ctr_contract.go 32 KB

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