ctr_contract.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. package service
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "time"
  13. basedao "dashoo.cn/micro/app/dao/base"
  14. dao "dashoo.cn/micro/app/dao/contract"
  15. custdao "dashoo.cn/micro/app/dao/cust"
  16. projdao "dashoo.cn/micro/app/dao/proj"
  17. workflowdao "dashoo.cn/micro/app/dao/workflow"
  18. model "dashoo.cn/micro/app/model/contract"
  19. proj "dashoo.cn/micro/app/model/proj"
  20. workflowModel "dashoo.cn/micro/app/model/workflow"
  21. "dashoo.cn/micro/app/service"
  22. projsrv "dashoo.cn/micro/app/service/proj"
  23. workflowService "dashoo.cn/micro/app/service/workflow"
  24. "dashoo.cn/opms_libary/micro_srv"
  25. "dashoo.cn/opms_libary/multipart"
  26. "dashoo.cn/opms_libary/myerrors"
  27. "dashoo.cn/opms_libary/plugin/dingtalk"
  28. "dashoo.cn/opms_libary/plugin/dingtalk/message"
  29. "dashoo.cn/opms_libary/plugin/dingtalk/workflow"
  30. "dashoo.cn/opms_libary/request"
  31. "dashoo.cn/opms_libary/utils"
  32. "github.com/gogf/gf/database/gdb"
  33. "github.com/gogf/gf/frame/g"
  34. "github.com/gogf/gf/os/gcron"
  35. "github.com/gogf/gf/os/glog"
  36. "github.com/gogf/gf/os/gtime"
  37. "github.com/gogf/gf/util/gvalid"
  38. )
  39. type CtrContractService struct {
  40. Dao *dao.CtrContractDao
  41. ProjBusinessDao *projdao.ProjBusinessDao
  42. CustomerDao *custdao.CustCustomerDao
  43. CtrProductDao *dao.CtrContractProductDao
  44. ProductDao *basedao.BaseProductDao
  45. DynamicsDao *dao.CtrContractDynamicsDao
  46. WorkflowDao *workflowdao.PlatWorkflowDao
  47. AppendDao *dao.CtrContractAppendDao
  48. GoalDao *dao.CtrContractGoalDao
  49. Tenant string
  50. userInfo request.UserInfo
  51. DataScope g.Map `json:"dataScope"`
  52. }
  53. func NewCtrContractService(ctx context.Context) (*CtrContractService, error) {
  54. tenant, err := micro_srv.GetTenant(ctx)
  55. if err != nil {
  56. err = myerrors.TipsError(fmt.Sprintf("获取租户码异常:%s", err.Error()))
  57. return nil, err //fmt.Errorf("获取租户码异常:%s", err.Error())
  58. }
  59. // 获取用户信息
  60. userInfo, err := micro_srv.GetUserInfo(ctx)
  61. if err != nil {
  62. return nil, fmt.Errorf("获取用户信息异常:%s", err.Error())
  63. }
  64. return &CtrContractService{
  65. Dao: dao.NewCtrContractDao(tenant),
  66. ProjBusinessDao: projdao.NewProjBusinessDao(tenant),
  67. CustomerDao: custdao.NewCustCustomerDao(tenant),
  68. CtrProductDao: dao.NewCtrContractProductDao(tenant),
  69. ProductDao: basedao.NewBaseProductDao(tenant),
  70. DynamicsDao: dao.NewCtrContractDynamicsDao(tenant),
  71. WorkflowDao: workflowdao.NewPlatWorkflowDao(tenant),
  72. AppendDao: dao.NewCtrContractAppendDao(tenant),
  73. GoalDao: dao.NewCtrContractGoalDao(tenant),
  74. Tenant: tenant,
  75. userInfo: userInfo,
  76. DataScope: userInfo.DataScope,
  77. }, nil
  78. }
  79. func (s CtrContractService) Get(ctx context.Context, id int) (*model.CtrContractGetRsp, error) {
  80. ent, err := s.Dao.Where("Id = ?", id).One()
  81. if err != nil {
  82. return nil, err
  83. }
  84. if ent == nil {
  85. return nil, myerrors.TipsError("合同不存在")
  86. }
  87. product, err := s.CtrProductDao.Where("contract_id = ?", id).All()
  88. if err != nil {
  89. return nil, err
  90. }
  91. if product == nil {
  92. product = []*model.CtrContractProduct{}
  93. }
  94. return &model.CtrContractGetRsp{
  95. CtrContract: *ent,
  96. Product: product,
  97. }, nil
  98. }
  99. func (s CtrContractService) DynamicsList(ctx context.Context, req *model.CtrContractDynamicsListReq) (int, interface{}, error) {
  100. dao := &s.DynamicsDao.CtrContractDynamicsDao
  101. if req.SearchText != "" {
  102. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  103. dao = dao.Where("(opn_people LIKE ? || opn_content LIKE ?)", likestr, likestr)
  104. }
  105. if req.ContractId != 0 {
  106. dao = dao.Where("contract_id = ?", req.ContractId)
  107. }
  108. if req.OpnPeopleId != 0 {
  109. dao = dao.Where("opn_people_id = ?", req.OpnPeopleId)
  110. }
  111. if req.OpnPeople != "" {
  112. likestr := fmt.Sprintf("%%%s%%", req.OpnPeople)
  113. dao = dao.Where("opn_people like ?", likestr)
  114. }
  115. if req.OpnType != "" {
  116. dao = dao.Where("opn_type = ?", req.OpnType)
  117. }
  118. // if req.OpnContent != "" {
  119. // likestr := fmt.Sprintf("%%%s%%", req.OpnContent)
  120. // dao = dao.Where("opn_content like ?", likestr)
  121. // }
  122. if req.BeginTime != "" {
  123. dao = dao.Where("created_time > ?", req.BeginTime)
  124. }
  125. if req.EndTime != "" {
  126. dao = dao.Where("created_time < ?", req.EndTime)
  127. }
  128. total, err := dao.Count()
  129. if err != nil {
  130. return 0, nil, err
  131. }
  132. if req.PageNum != 0 {
  133. dao = dao.Page(req.GetPage())
  134. }
  135. orderby := "created_time desc"
  136. if req.OrderBy != "" {
  137. orderby = req.OrderBy
  138. }
  139. dao = dao.Order(orderby)
  140. ents := []*model.CtrContractDynamics{}
  141. err = dao.Structs(&ents)
  142. if err != nil && err != sql.ErrNoRows {
  143. return 0, nil, err
  144. }
  145. ret := map[string][]*model.CtrContractDynamics{}
  146. for _, ent := range ents {
  147. date := ent.OpnDate.Format("Y-m-d")
  148. ret[date] = append(ret[date], ent)
  149. }
  150. return total, ret, err
  151. }
  152. func (s CtrContractService) List(ctx context.Context, req *model.CtrContractListReq) (int, []*model.CtrContractListRsp, error) {
  153. ctx = context.WithValue(ctx, "contextService", s)
  154. dao := s.Dao.DataScope(ctx, "incharge_id").As("a")
  155. if req.SearchText != "" {
  156. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  157. dao = dao.Where("(a.contract_code LIKE ? || a.contract_name LIKE ? || a.cust_name LIKE ? || a.nbo_name LIKE ?)", likestr, likestr, likestr, likestr)
  158. }
  159. if req.ContractCode != "" {
  160. likestr := fmt.Sprintf("%%%s%%", req.ContractCode)
  161. dao = dao.Where("a.contract_code like ?", likestr)
  162. }
  163. if req.ContractName != "" {
  164. likestr := fmt.Sprintf("%%%s%%", req.ContractName)
  165. dao = dao.Where("a.contract_name like ?", likestr)
  166. }
  167. if req.CustId != 0 {
  168. dao = dao.Where("a.cust_id = ?", req.CustId)
  169. }
  170. if req.CustName != "" {
  171. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  172. dao = dao.Where("a.cust_name like ?", likestr)
  173. }
  174. if req.NboId != 0 {
  175. dao = dao.Where("a.nbo_id = ?", req.NboId)
  176. }
  177. if req.NboName != "" {
  178. likestr := fmt.Sprintf("%%%s%%", req.NboName)
  179. dao = dao.Where("a.nbo_name like ?", likestr)
  180. }
  181. if req.ApproStatus != "" {
  182. dao = dao.Where("a.appro_status = ?", req.ApproStatus)
  183. }
  184. if req.ContractType != "" {
  185. dao = dao.Where("a.contract_type = ?", req.ContractType)
  186. }
  187. // if req.ContractStartTime != nil {
  188. // dao = dao.Where("a.contract_start_time > ?", req.ContractStartTime)
  189. // }
  190. // if req.ContractEndTime != nil {
  191. // dao = dao.Where("a.contract_end_time < ?", req.ContractEndTime)
  192. // }
  193. if req.InchargeId != 0 {
  194. dao = dao.Where("a.incharge_id = ?", req.InchargeId)
  195. }
  196. if req.InchargeName != "" {
  197. likestr := fmt.Sprintf("%%%s%%", req.InchargeName)
  198. dao = dao.Where("a.incharge_name like ?", likestr)
  199. }
  200. if req.SignatoryId != 0 {
  201. dao = dao.Where("a.signatory_id = ?", req.SignatoryId)
  202. }
  203. if req.SignatoryName != "" {
  204. likestr := fmt.Sprintf("%%%s%%", req.SignatoryName)
  205. dao = dao.Where("a.signatory_name like ?", likestr)
  206. }
  207. if req.DistributorId != 0 {
  208. dao = dao.Where("a.distributor_id = ?", req.DistributorId)
  209. }
  210. if req.DistributorName != "" {
  211. likestr := fmt.Sprintf("%%%s%%", req.DistributorName)
  212. dao = dao.Where("a.distributor_name like ?", likestr)
  213. }
  214. if req.BeginTime != "" {
  215. dao = dao.Where("a.created_time > ?", req.BeginTime)
  216. }
  217. if req.EndTime != "" {
  218. dao = dao.Where("a.created_time < ?", req.EndTime)
  219. }
  220. total, err := dao.Count()
  221. if err != nil {
  222. return 0, nil, err
  223. }
  224. if req.PageNum != 0 {
  225. dao = dao.Page(req.GetPage())
  226. }
  227. orderby := "a.created_time desc"
  228. if req.OrderBy != "" {
  229. orderby = req.OrderBy
  230. }
  231. dao = dao.Order(orderby)
  232. ents := []*model.CtrContractListRsp{}
  233. err = dao.Structs(&ents)
  234. if err != nil && err != sql.ErrNoRows {
  235. return 0, nil, err
  236. }
  237. return total, ents, err
  238. }
  239. func (s CtrContractService) BindProduct(tx *gdb.TX, id int, code string, product []model.CtrAddProduct) error {
  240. var amount float64
  241. for _, p := range product {
  242. amount += (p.TranPrice * float64(p.ProdNum))
  243. }
  244. _, err := tx.Delete("ctr_contract_product", "contract_id = ?", id)
  245. if err != nil {
  246. return err
  247. }
  248. tocreate := []model.CtrContractProduct{}
  249. for _, p := range product {
  250. product, err := s.ProductDao.Where("id = ?", p.ProdId).One()
  251. if err != nil {
  252. return err
  253. }
  254. if product == nil {
  255. return myerrors.TipsError(fmt.Sprintf("产品: %d 不存在", p.ProdId))
  256. }
  257. tocreate = append(tocreate, model.CtrContractProduct{
  258. ContractId: id,
  259. ContractCode: code,
  260. ProdId: p.ProdId,
  261. ProdCode: product.ProdCode,
  262. ProdName: product.ProdName,
  263. ProdClass: product.ProdClass,
  264. ProdNum: p.ProdNum,
  265. MaintTerm: p.MaintTerm,
  266. SugSalesPrice: p.SugSalesPrice,
  267. TranPrice: p.TranPrice,
  268. ContractPrive: amount,
  269. Remark: p.Remark,
  270. CreatedBy: int(s.userInfo.Id),
  271. CreatedName: s.userInfo.NickName,
  272. CreatedTime: gtime.Now(),
  273. UpdatedBy: int(s.userInfo.Id),
  274. UpdatedName: s.userInfo.NickName,
  275. UpdatedTime: gtime.Now(),
  276. })
  277. }
  278. if len(tocreate) != 0 {
  279. _, err = tx.Insert("ctr_contract_product", tocreate)
  280. if err != nil {
  281. return err
  282. }
  283. }
  284. return nil
  285. }
  286. func (s CtrContractService) AddDynamicsByCurrentUser(tx *gdb.TX, contractId int, opnType string, content map[string]interface{}) error {
  287. contentByte, err := json.Marshal(content)
  288. if err != nil {
  289. return err
  290. }
  291. _, err = tx.InsertAndGetId("ctr_contract_dynamics", model.CtrContractDynamics{
  292. ContractId: contractId,
  293. OpnPeopleId: s.userInfo.Id,
  294. OpnPeople: s.userInfo.NickName,
  295. OpnDate: gtime.Now(),
  296. OpnType: opnType,
  297. OpnContent: string(contentByte),
  298. Remark: "",
  299. CreatedBy: s.userInfo.Id,
  300. CreatedName: s.userInfo.NickName,
  301. CreatedTime: gtime.Now(),
  302. UpdatedBy: s.userInfo.Id,
  303. UpdatedName: s.userInfo.NickName,
  304. UpdatedTime: gtime.Now(),
  305. })
  306. return err
  307. }
  308. func (s CtrContractService) Add(ctx context.Context, req *model.CtrContractAddReq) (int, error) {
  309. validErr := gvalid.CheckStruct(ctx, req, nil)
  310. if validErr != nil {
  311. return 0, myerrors.TipsError(validErr.Current().Error())
  312. }
  313. if len(req.Product) == 0 {
  314. return 0, myerrors.TipsError("产品不能为空")
  315. }
  316. for _, p := range req.Product {
  317. if p.ProdNum < 1 {
  318. return 0, myerrors.TipsError("产品数量必须大于 0")
  319. }
  320. }
  321. c, err := s.Dao.Where("contract_name = ?", req.ContractName).One()
  322. if err != nil {
  323. return 0, err
  324. }
  325. if c != nil {
  326. return 0, myerrors.TipsError(fmt.Sprintf("合同名称:%s 已存在", req.ContractName))
  327. }
  328. nbo, err := s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  329. if err != nil {
  330. return 0, err
  331. }
  332. if nbo == nil {
  333. return 0, myerrors.TipsError("项目不存在")
  334. }
  335. // c, err = s.Dao.Where("nbo_id = ?", req.NboId).One()
  336. // if err != nil {
  337. // return 0, err
  338. // }
  339. // if c != nil {
  340. // return 0, myerrors.TipsError("所选项目已添加合同")
  341. // }
  342. sequence, err := service.Sequence(s.Dao.DB, "contract_code")
  343. if err != nil {
  344. return 0, err
  345. }
  346. if req.ContractCode == "" {
  347. req.ContractCode = fmt.Sprintf("DS%s%s%s", req.ContractType, time.Now().Format("0601"), sequence)
  348. }
  349. c, err = s.Dao.Where("contract_code = ?", req.ContractCode).One()
  350. if err != nil {
  351. return 0, err
  352. }
  353. if c != nil {
  354. return 0, myerrors.TipsError(fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  355. }
  356. var contractAmount float64
  357. for _, p := range req.Product {
  358. contractAmount += (p.TranPrice * float64(p.ProdNum))
  359. }
  360. ctr := model.CtrContract{
  361. ContractCode: req.ContractCode,
  362. ContractName: req.ContractName,
  363. CustId: nbo.CustId,
  364. CustName: nbo.CustName,
  365. NboId: nbo.Id,
  366. NboName: nbo.NboName,
  367. IsBig: nbo.IsBig,
  368. ProductLine: nbo.ProductLine,
  369. CustProvinceId: nbo.CustProvinceId,
  370. CustProvince: nbo.CustProvince,
  371. CustCityId: nbo.CustCityId,
  372. CustCity: nbo.CustCity,
  373. ApproStatus: "10",
  374. ContractType: req.ContractType,
  375. ContractAmount: contractAmount,
  376. InvoiceAmount: 0,
  377. CollectedAmount: 0,
  378. ContractStartTime: req.ContractStartTime,
  379. ContractEndTime: req.ContractEndTime,
  380. ContractSignTime: req.ContractSignTime,
  381. InchargeId: req.InchargeId,
  382. InchargeName: req.InchargeName,
  383. SignatoryId: req.SignatoryId,
  384. SignatoryName: req.SignatoryName,
  385. SignatoryType: req.SignatoryType,
  386. SignatoryUnit: req.SignatoryUnit,
  387. EarnestMoney: req.EarnestMoney,
  388. CustSignatoryId: req.CustSignatoryId,
  389. CustSignatoryName: req.CustSignatoryName,
  390. DistributorId: req.DistributorId,
  391. DistributorName: req.DistributorName,
  392. Remark: req.Remark,
  393. ServiceFeeAgreement: req.ServiceFeeAgreement,
  394. CreatedBy: int(s.userInfo.Id),
  395. CreatedName: s.userInfo.NickName,
  396. CreatedTime: gtime.Now(),
  397. UpdatedBy: int(s.userInfo.Id),
  398. UpdatedName: s.userInfo.NickName,
  399. UpdatedTime: gtime.Now(),
  400. }
  401. var id int
  402. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  403. ctrid, err := tx.InsertAndGetId("ctr_contract", ctr)
  404. if err != nil {
  405. return err
  406. }
  407. err = s.BindProduct(tx, int(ctrid), ctr.ContractCode, req.Product)
  408. if err != nil {
  409. return err
  410. }
  411. err = s.AddDynamicsByCurrentUser(tx, int(ctrid), "创建合同", map[string]interface{}{})
  412. if err != nil {
  413. return err
  414. }
  415. _, err = tx.Update("proj_business", map[string]interface{}{
  416. "nbo_type": projsrv.StatusDeal,
  417. }, "id = ?", nbo.Id)
  418. if err != nil {
  419. return err
  420. }
  421. id = int(ctrid)
  422. return nil
  423. })
  424. return id, txerr
  425. }
  426. var ContractApplyProcessCode = "PROC-7057E20A-2066-4644-9B35-9331E4DA912C" // 创建合同
  427. func (s CtrContractService) Commit(ctx context.Context, req *model.CtrContractCommitReq) (int64, error) {
  428. validErr := gvalid.CheckStruct(ctx, req, nil)
  429. if validErr != nil {
  430. return 0, myerrors.TipsError(validErr.Current().Error())
  431. }
  432. if !(req.ContractModel == "大数模板" || req.ContractModel == "客户模板") {
  433. return 0, myerrors.TipsError("合同模板不合法")
  434. }
  435. if !(req.Terms == "接纳全部条款" || req.Terms == "不接纳全部条款") {
  436. return 0, myerrors.TipsError("条款情况不合法")
  437. }
  438. if req.PayTerms == "" {
  439. return 0, myerrors.TipsError("付款条件不能为空")
  440. }
  441. if len(req.File) == 0 {
  442. return 0, myerrors.TipsError("附件不能为空")
  443. }
  444. ent, err := s.Dao.Where("id = ?", req.Id).One()
  445. if err != nil {
  446. return 0, err
  447. }
  448. if ent == nil {
  449. return 0, myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  450. }
  451. fileinfoByte, err := json.Marshal(req.File)
  452. if err != nil {
  453. return 0, err
  454. }
  455. workflowSrv, err := workflowService.NewFlowService(ctx)
  456. if err != nil {
  457. return 0, err
  458. }
  459. bizCode := strconv.Itoa(ent.Id)
  460. workflowId, err := workflowSrv.StartProcessInstance(bizCode, "30", "", &workflow.StartProcessInstanceRequest{
  461. ProcessCode: &ContractApplyProcessCode,
  462. FormComponentValues: []*workflow.StartProcessInstanceRequestFormComponentValues{
  463. {
  464. Id: utils.String("DDSelectField_ESX8H30W3VK0"),
  465. Name: utils.String("合同模板"),
  466. Value: utils.String(req.ContractModel),
  467. },
  468. {
  469. Id: utils.String("DDSelectField_13IQX96C2KAK0"),
  470. Name: utils.String("条款情况"),
  471. Value: utils.String(req.Terms),
  472. },
  473. {
  474. Id: utils.String("TextField_1A5SA7VOG5TS0"),
  475. Name: utils.String("合同编号"),
  476. Value: utils.String(ent.ContractCode),
  477. },
  478. {
  479. Id: utils.String("TextField_1EX61DPS3LA80"),
  480. Name: utils.String("客户名称"),
  481. Value: utils.String(ent.CustName),
  482. },
  483. {
  484. Id: utils.String("MoneyField_X1XV4KIR0GW0"),
  485. Name: utils.String("合同金额(元)"),
  486. Value: utils.String(strconv.FormatFloat(ent.ContractAmount, 'f', 2, 64)),
  487. },
  488. {
  489. Id: utils.String("TextareaField_1WZ5ILKBUVSW0"),
  490. Name: utils.String("付款条件"),
  491. Value: utils.String(req.PayTerms),
  492. },
  493. {
  494. Id: utils.String("DDAttachment_1051KJYC3MBK0"),
  495. Name: utils.String("附件"),
  496. // Details: productForm,
  497. Value: utils.String(string(fileinfoByte)),
  498. },
  499. },
  500. })
  501. if err != nil {
  502. return 0, err
  503. }
  504. _, err = s.Dao.Where("id = ?", ent.Id).Data(map[string]interface{}{
  505. "appro_status": 20,
  506. }).Update()
  507. return workflowId, err
  508. }
  509. // var spaceId = "21042518430"
  510. var spaceId = "21077726250"
  511. func (s CtrContractService) CommitWithFile(ctx context.Context, args *multipart.MultipartFile) error {
  512. if s.userInfo.DingtalkUid == "" {
  513. return fmt.Errorf("该用户钉钉 uid 为空")
  514. }
  515. if args.FileName == "" {
  516. return fmt.Errorf("文件名称不能为空")
  517. }
  518. if args.File == nil {
  519. return fmt.Errorf("文件不能为空")
  520. }
  521. if args.File.Name() == "" {
  522. return fmt.Errorf("文件路径不能为空")
  523. }
  524. contractId, err := strconv.Atoi(args.Meta["contractId"])
  525. if err != nil {
  526. return fmt.Errorf("合同 Id 不合法 %s", args.Meta["contractId"])
  527. }
  528. fmt.Println(args.File.Name(), args.FileName, args.FileSize, args.Meta)
  529. fmt.Println(spaceId, s.userInfo.DingtalkId, args.FileName, args.File.Name())
  530. // resp, err := s.UploadFile("21042518430", "8xljy04PZiS9iPxp5PhDnUzQiEiE", "引物导入模板-000000.xlsx", "/Users/chengjian/Downloads/引物导入模板.xlsx")
  531. resp, err := dingtalk.Client.GetStorage().UploadFile(spaceId, s.userInfo.DingtalkId, args.FileName, args.File.Name())
  532. if err != nil {
  533. return fmt.Errorf("钉钉上传文件异常 %s", err.Error())
  534. }
  535. _, err = s.Commit(ctx, &model.CtrContractCommitReq{
  536. Id: contractId,
  537. ContractModel: args.Meta["contractModel"],
  538. Terms: args.Meta["terms"],
  539. PayTerms: args.Meta["payTerms"],
  540. File: []model.DingFileInfo{
  541. {
  542. SpaceId: resp.Dentry.SpaceId,
  543. FileId: resp.Dentry.Id,
  544. FileName: resp.Dentry.Name,
  545. FileSize: resp.Dentry.Size,
  546. FileType: resp.Dentry.Extension,
  547. },
  548. },
  549. })
  550. if err != nil {
  551. return err
  552. }
  553. // workflow, err := s.WorkflowDao.Where("id = ?", workflowId).One()
  554. // if err != nil {
  555. // return err
  556. // }
  557. // instance, err := dingtalk.Client.GetWorkflow().QueryProcessInstanceDetail(workflow.ProcessInstId)
  558. // if err != nil {
  559. // return fmt.Errorf("查询审批实例详情错误: %s", err.Error())
  560. // }
  561. // fmt.Println(workflow.ProcessInstId, instance.Result.ApproverUserIds)
  562. // approverUserIds := g.Config().GetStrings("dingtalk.approver-user-ids")
  563. // fmt.Println(approverUserIds)
  564. // for _, uid := range approverUserIds {
  565. // resp, err := dingtalk.Client.GetStorage().AddPermission(
  566. // dingtalk.Client.Context.CorpId, spaceId, uid, "DOWNLOADER", "USER")
  567. // if err != nil {
  568. // return fmt.Errorf("添加审核附件权限异常: %s", err.Error())
  569. // }
  570. // fmt.Println(uid, resp)
  571. // }
  572. appendSrv, err := NewCtrContractAppendService(ctx)
  573. if err != nil {
  574. return err
  575. }
  576. _, err = appendSrv.Add(ctx, &model.CtrContractAppendAddReq{
  577. ContractId: contractId,
  578. FileName: resp.Dentry.Name,
  579. FileType: resp.Dentry.Extension,
  580. FileUrl: strings.Join([]string{"dingtalk", resp.Dentry.SpaceId, resp.Dentry.Id}, ":"),
  581. Remark: "",
  582. })
  583. if err != nil {
  584. return err
  585. }
  586. return nil
  587. }
  588. func (s CtrContractService) DownloadDingtalkFile(ctx context.Context, id int) (string, error) {
  589. ent, err := s.AppendDao.Where("id= ?", id).One()
  590. if err != nil {
  591. return "", err
  592. }
  593. if ent == nil {
  594. return "", myerrors.TipsError("附件不存在")
  595. }
  596. if !strings.HasPrefix(ent.FileUrl, "dingtalk") {
  597. return "", myerrors.TipsError("此附件不是钉钉附件")
  598. }
  599. fileInfo := strings.Split(ent.FileUrl, ":")
  600. if len(fileInfo) != 3 {
  601. return "", myerrors.TipsError("钉钉附件地址不合法")
  602. }
  603. spaceId := fileInfo[1]
  604. fileId := fileInfo[2]
  605. // res, err := dingtalk.Client.GetStorage().AddPermission(dingtalk.Client.Context.CorpId, spaceId, s.userInfo.DingtalkId, "EDITOR", "USER")
  606. // fmt.Println(res, err)
  607. // if err != nil {
  608. // return "", fmt.Errorf("设置权限异常 %s", err.Error())
  609. // }
  610. resp, err := dingtalk.Client.GetStorage().QueryFileDownloadInfo(spaceId, fileId, s.userInfo.DingtalkId)
  611. if err != nil {
  612. return "", myerrors.TipsError("获取文件下载信息异常")
  613. }
  614. fmt.Println(resp, err)
  615. req, err := http.NewRequest("GET", resp.HeaderSignatureInfo.ResourceUrls[0], nil)
  616. if err != nil {
  617. return "", fmt.Errorf("构建文件下载请求异常 %s", err.Error())
  618. }
  619. for k, v := range resp.HeaderSignatureInfo.Headers {
  620. req.Header.Add(k, v)
  621. }
  622. fileresp, err := http.DefaultClient.Do(req)
  623. if err != nil {
  624. return "", fmt.Errorf("文件下载异常 %s", err.Error())
  625. }
  626. data, err := io.ReadAll(fileresp.Body)
  627. if err != nil {
  628. return "", fmt.Errorf("读取下载内容异常 %s", err.Error())
  629. }
  630. return base64.StdEncoding.EncodeToString(data), nil
  631. }
  632. func ContractApplyApproval(ctx context.Context, flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  633. tenant, err := micro_srv.GetTenant(ctx)
  634. if err != nil {
  635. return fmt.Errorf("获取租户码异常:%s", err.Error())
  636. }
  637. contractDao := dao.NewCtrContractDao(tenant)
  638. contractId, err := strconv.Atoi(flow.BizCode)
  639. if err != nil {
  640. return fmt.Errorf("创建合同审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  641. }
  642. contract, err := contractDao.Where("id = ?", contractId).One()
  643. if err != nil {
  644. return err
  645. }
  646. if contract == nil {
  647. return fmt.Errorf("合同不存在:%s Id: %d", flow.BizCode, flow.Id)
  648. }
  649. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  650. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  651. }
  652. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  653. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  654. }
  655. if msg.ProcessType == "terminate" {
  656. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  657. "appro_status": "50",
  658. }).Update()
  659. return err
  660. }
  661. pass := msg.Result == "agree"
  662. if !pass {
  663. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  664. "appro_status": "40",
  665. }).Update()
  666. return err
  667. }
  668. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  669. "appro_status": "30",
  670. }).Update()
  671. return err
  672. }
  673. func (s CtrContractService) Update(ctx context.Context, req *model.CtrContractUpdateReq) error {
  674. validErr := gvalid.CheckStruct(ctx, req, nil)
  675. if validErr != nil {
  676. return myerrors.TipsError(validErr.Current().Error())
  677. }
  678. ent, err := s.Dao.Where("id = ?", req.Id).One()
  679. if err != nil {
  680. return err
  681. }
  682. if ent == nil {
  683. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  684. }
  685. // if req.ContractCode != "" {
  686. // exist, err := s.Dao.Where("contract_code = ?", req.ContractCode).One()
  687. // if err != nil {
  688. // return err
  689. // }
  690. // if exist != nil && exist.Id != req.Id {
  691. // return myerrors.NewMsgError(nil, fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  692. // }
  693. // }
  694. if req.ContractName != "" {
  695. exist, err := s.Dao.Where("contract_name = ?", req.ContractName).One()
  696. if err != nil {
  697. return err
  698. }
  699. if exist != nil && exist.Id != req.Id {
  700. return myerrors.TipsError(fmt.Sprintf("合同名称:%s 已存在", req.ContractName))
  701. }
  702. }
  703. var nbo *proj.ProjBusiness
  704. if req.NboId != 0 {
  705. nbo, err = s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  706. if err != nil {
  707. return err
  708. }
  709. if nbo == nil {
  710. return myerrors.TipsError("项目不存在")
  711. }
  712. }
  713. toupdate := map[string]interface{}{}
  714. // if req.ContractCode != "" {
  715. // toupdate["contract_code"] = req.ContractCode
  716. // }
  717. if req.ContractName != "" {
  718. toupdate["contract_name"] = req.ContractName
  719. }
  720. if req.NboId != 0 {
  721. toupdate["cust_id"] = nbo.CustId
  722. toupdate["cust_name"] = nbo.CustName
  723. toupdate["nbo_id"] = nbo.Id
  724. toupdate["nbo_name"] = nbo.NboName
  725. toupdate["is_big"] = nbo.IsBig
  726. toupdate["product_line"] = nbo.ProductLine
  727. toupdate["cust_province_id"] = nbo.CustProvinceId
  728. toupdate["cust_province"] = nbo.CustProvince
  729. toupdate["cust_city_id"] = nbo.CustCityId
  730. toupdate["cust_city"] = nbo.CustCity
  731. }
  732. // if req.ApproStatus != "" {
  733. // toupdate["appro_status"] = req.ApproStatus
  734. // }
  735. if req.ContractType != "" {
  736. toupdate["contract_type"] = req.ContractType
  737. }
  738. // if req.ContractAmount != 0 {
  739. // toupdate["contract_amount"] = req.ContractAmount
  740. // }
  741. // if req.InvoiceAmount != 0 {
  742. // toupdate["invoice_amount"] = req.InvoiceAmount
  743. // }
  744. // if req.CollectedAmount != 0 {
  745. // toupdate["collected_amount"] = req.CollectedAmount
  746. // }
  747. if req.ContractStartTime != nil {
  748. toupdate["contract_start_time"] = req.ContractStartTime
  749. }
  750. if req.ContractEndTime != nil {
  751. toupdate["contract_end_time"] = req.ContractEndTime
  752. }
  753. if req.ContractSignTime != nil {
  754. toupdate["contract_sign_time"] = req.ContractSignTime
  755. }
  756. //if req.InchargeId != 0 {
  757. // toupdate["incharge_id"] = req.InchargeId
  758. //}
  759. //if req.InchargeName != "" {
  760. // toupdate["incharge_name"] = req.InchargeName
  761. //}
  762. if req.SignatoryId != 0 {
  763. toupdate["signatory_id"] = req.SignatoryId
  764. }
  765. if req.SignatoryName != "" {
  766. toupdate["signatory_name"] = req.SignatoryName
  767. }
  768. if req.SignatoryType != "" {
  769. toupdate["signatory_type"] = req.SignatoryType
  770. }
  771. if req.SignatoryUnit != "" {
  772. toupdate["signatory_unit"] = req.SignatoryUnit
  773. }
  774. if req.EarnestMoney != nil {
  775. toupdate["earnest_money"] = req.EarnestMoney
  776. }
  777. if req.CustSignatoryId != 0 {
  778. toupdate["cust_signatory_id"] = req.CustSignatoryId
  779. }
  780. if req.CustSignatoryName != "" {
  781. toupdate["cust_signatory_name"] = req.CustSignatoryName
  782. }
  783. if req.DistributorId != 0 {
  784. toupdate["distributor_id"] = req.DistributorId
  785. }
  786. if req.DistributorName != "" {
  787. toupdate["distributor_name"] = req.DistributorName
  788. }
  789. if req.Remark != nil {
  790. toupdate["remark"] = *req.Remark
  791. }
  792. if req.Product != nil {
  793. var contractAmount float64
  794. for _, p := range *req.Product {
  795. contractAmount += (p.TranPrice * float64(p.ProdNum))
  796. }
  797. toupdate["contract_amount"] = contractAmount
  798. }
  799. if len(toupdate) != 0 {
  800. toupdate["updated_by"] = int(s.userInfo.Id)
  801. toupdate["updated_name"] = s.userInfo.NickName
  802. toupdate["updated_time"] = gtime.Now()
  803. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  804. _, err = tx.Update("ctr_contract", toupdate, "id = ?", req.Id)
  805. if err != nil {
  806. return err
  807. }
  808. if req.Product != nil {
  809. err = s.BindProduct(tx, req.Id, ent.ContractCode, *req.Product)
  810. if err != nil {
  811. return err
  812. }
  813. }
  814. return nil
  815. })
  816. if txerr != nil {
  817. return txerr
  818. }
  819. }
  820. return nil
  821. }
  822. func (s CtrContractService) UpdateProduct(ctx context.Context, req *model.CtrContractUpdateProductReq) error {
  823. validErr := gvalid.CheckStruct(ctx, req, nil)
  824. if validErr != nil {
  825. return myerrors.TipsError(validErr.Current().Error())
  826. }
  827. ent, err := s.CtrProductDao.Where("id = ?", req.Id).One()
  828. if err != nil {
  829. return err
  830. }
  831. if ent == nil {
  832. return myerrors.TipsError(fmt.Sprintf("合同产品记录不存在: %d", req.Id))
  833. }
  834. toupdate := map[string]interface{}{}
  835. if req.MaintainPeriod != nil {
  836. toupdate["maintain_period"] = req.MaintainPeriod
  837. }
  838. if req.WarrantPeriod != nil {
  839. toupdate["warrant_period"] = req.WarrantPeriod
  840. }
  841. if req.MaintainStartTime != nil {
  842. toupdate["maintain_start_time"] = req.MaintainStartTime
  843. }
  844. if req.MaintainRemark != nil {
  845. toupdate["maintain_remark"] = req.MaintainRemark
  846. }
  847. if req.AcceptTime != nil {
  848. toupdate["accept_time"] = req.AcceptTime
  849. }
  850. if req.PurchaseCost != nil {
  851. toupdate["purchase_cost"] = req.PurchaseCost
  852. }
  853. if req.DevCost != nil {
  854. toupdate["dev_cost"] = req.DevCost
  855. }
  856. if req.MaintainCost != nil {
  857. toupdate["maintain_cost"] = req.MaintainCost
  858. }
  859. if req.DirectCost != nil {
  860. toupdate["direct_cost"] = req.DirectCost
  861. }
  862. if len(toupdate) != 0 {
  863. toupdate["updated_by"] = int(s.userInfo.Id)
  864. toupdate["updated_name"] = s.userInfo.NickName
  865. toupdate["updated_time"] = gtime.Now()
  866. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  867. _, err = tx.Update("ctr_contract_product", toupdate, "id = ?", req.Id)
  868. if err != nil {
  869. return err
  870. }
  871. err = s.AddDynamicsByCurrentUser(tx, ent.ContractId, "更新合同产品信息", toupdate)
  872. if err != nil {
  873. return err
  874. }
  875. return nil
  876. })
  877. if txerr != nil {
  878. return txerr
  879. }
  880. }
  881. return nil
  882. }
  883. func (s CtrContractService) Transfer(ctx context.Context, req *model.CtrContractTransferReq) error {
  884. if len(req.Id) == 0 {
  885. return nil
  886. }
  887. ents := map[int]*model.CtrContract{}
  888. for _, i := range req.Id {
  889. ent, err := s.Dao.Where("id = ?", i).One()
  890. if err != nil {
  891. return err
  892. }
  893. if ent == nil {
  894. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  895. }
  896. ents[ent.Id] = ent
  897. }
  898. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  899. toupdate := map[string]interface{}{
  900. "incharge_id": req.InchargeId,
  901. "incharge_name": req.InchargeName,
  902. }
  903. _, err := tx.Update("ctr_contract", toupdate, "id in (?)", req.Id)
  904. if err != nil {
  905. return err
  906. }
  907. for _, ent := range ents {
  908. err = s.AddDynamicsByCurrentUser(tx, ent.Id, "转移合同", map[string]interface{}{
  909. "toInchargeId": req.InchargeId,
  910. "toInchargeName": req.InchargeName,
  911. "fromInchargeId": ent.InchargeId,
  912. "fromInchargeName": ent.InchargeName,
  913. "operatedId": s.userInfo.Id,
  914. "operatedName": s.userInfo.NickName,
  915. })
  916. if err != nil {
  917. return err
  918. }
  919. }
  920. return nil
  921. })
  922. if txerr != nil {
  923. return txerr
  924. }
  925. return nil
  926. }
  927. func (s CtrContractService) UpdateInvoiceAmount(tx *gdb.TX, id int) error {
  928. ctr := model.CtrContract{}
  929. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  930. if err == sql.ErrNoRows {
  931. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  932. }
  933. if err != nil {
  934. return err
  935. }
  936. v, err := tx.GetValue("select sum(invoice_amount) from ctr_contract_invoice where contract_id=? and appro_status='30' and deleted_time is null", id)
  937. if err != nil {
  938. return err
  939. }
  940. amount := v.Float64()
  941. _, err = tx.Update("ctr_contract",
  942. map[string]interface{}{
  943. "invoice_amount": amount,
  944. }, "id = ?", id)
  945. if err != nil {
  946. return err
  947. }
  948. return nil
  949. }
  950. func (s CtrContractService) UpdateCollectedAmount(tx *gdb.TX, id int) error {
  951. ctr := model.CtrContract{}
  952. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  953. if err == sql.ErrNoRows {
  954. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  955. }
  956. if err != nil {
  957. return err
  958. }
  959. v, err := tx.GetValue("select sum(collection_amount) from ctr_contract_collection where contract_id=? and appro_status='20' and deleted_time is null", id)
  960. if err != nil {
  961. return err
  962. }
  963. amount := v.Float64()
  964. _, err = tx.Update("ctr_contract",
  965. map[string]interface{}{
  966. "collected_amount": amount,
  967. }, "id = ?", id)
  968. if err != nil {
  969. return err
  970. }
  971. return nil
  972. }
  973. func (s CtrContractService) Delete(ctx context.Context, id []int) error {
  974. if len(id) == 0 {
  975. return nil
  976. }
  977. _, err := s.Dao.Where("Id IN (?)", id).Delete()
  978. return err
  979. }
  980. func init() {
  981. tenant := g.Config().GetString("micro_srv.tenant")
  982. if tenant == "" {
  983. panic("定时任务租户码未设置,请前往配置")
  984. }
  985. contractDao := dao.NewCtrContractDao(tenant)
  986. produceDao := dao.NewCtrContractProductDao(tenant)
  987. job := func() {
  988. alert := map[int]*[]model.CtrContractProduct{
  989. 180: {},
  990. 90: {},
  991. 30: {},
  992. 10: {},
  993. // 7: {},
  994. }
  995. where := `DATE_FORMAT(DATE_ADD(maintain_start_time, INTERVAL ? day), "%Y-%m-%d") = DATE_FORMAT(NOW(), "%Y-%m-%d")`
  996. for day, p := range alert {
  997. err := produceDao.Where(where, day).Structs(p)
  998. if err != nil {
  999. glog.Error(err)
  1000. }
  1001. glog.Infof("运维期到期 %d 天提醒,产品个数 %d", day, len(*p))
  1002. }
  1003. for day, p := range alert {
  1004. for _, i := range *p {
  1005. ctr, err := contractDao.Where("id = ?", i.ContractId).One()
  1006. if err != nil {
  1007. glog.Error(err)
  1008. }
  1009. text := fmt.Sprintf("合同:%s-%s 中的产品:%s 距离运维到期还有 %d 天",
  1010. ctr.ContractCode, ctr.ContractName, i.ProdName, day)
  1011. msg := g.MapStrStr{
  1012. "msgTitle": "运维期到期提醒",
  1013. "msgContent": text,
  1014. "msgType": "20",
  1015. "recvUserIds": strconv.Itoa(ctr.InchargeId),
  1016. "msgStatus": "10",
  1017. "sendType": "10",
  1018. }
  1019. if err := service.CreateSystemMessage(msg); err != nil {
  1020. glog.Error("消息提醒异常:", err)
  1021. }
  1022. glog.Infof("%s", text)
  1023. }
  1024. }
  1025. }
  1026. // 每天凌晨2点执行
  1027. gcron.AddSingleton("0 0 2 * * *", job)
  1028. // job()
  1029. }