ctr_contract.go 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  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. var sequence int
  356. if req.ContractType == "XS" { // 销售合同
  357. sequence, err = service.SequenceYearRest(s.Dao.DB, "contract_code_xs")
  358. if err != nil {
  359. return 0, err
  360. }
  361. } else if req.ContractType == "JS" { // 技术合同
  362. sequence, err = service.SequenceYearRest(s.Dao.DB, "contract_code_js")
  363. if err != nil {
  364. return 0, err
  365. }
  366. } else {
  367. return 0, myerrors.TipsError("不支持的合同类型")
  368. }
  369. if req.ContractCode == "" {
  370. req.ContractCode = fmt.Sprintf("DH%s%s-%03d", req.ContractType, time.Now().Format("0601"), sequence)
  371. }
  372. c, err = s.Dao.Where("contract_code = ?", req.ContractCode).One()
  373. if err != nil {
  374. return 0, err
  375. }
  376. if c != nil {
  377. return 0, myerrors.TipsError(fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  378. }
  379. var contractAmount float64
  380. for _, p := range req.Product {
  381. contractAmount += (p.TranPrice * float64(p.ProdNum))
  382. }
  383. ctr := model.CtrContract{
  384. ContractCode: req.ContractCode,
  385. ContractName: req.ContractName,
  386. CustId: nbo.CustId,
  387. CustName: nbo.CustName,
  388. NboId: nbo.Id,
  389. NboName: nbo.NboName,
  390. IsBig: nbo.IsBig,
  391. ProductLine: nbo.ProductLine,
  392. CustProvinceId: nbo.CustProvinceId,
  393. CustProvince: nbo.CustProvince,
  394. CustCityId: nbo.CustCityId,
  395. CustCity: nbo.CustCity,
  396. ApproStatus: "10",
  397. ContractType: req.ContractType,
  398. ContractAmount: contractAmount,
  399. InvoiceAmount: 0,
  400. CollectedAmount: 0,
  401. ContractStartTime: req.ContractStartTime,
  402. ContractEndTime: req.ContractEndTime,
  403. ContractSignTime: req.ContractSignTime,
  404. InchargeId: req.InchargeId,
  405. InchargeName: req.InchargeName,
  406. SignatoryId: req.SignatoryId,
  407. SignatoryName: req.SignatoryName,
  408. SignatoryType: req.SignatoryType,
  409. SignatoryUnit: req.SignatoryUnit,
  410. EarnestMoney: req.EarnestMoney,
  411. CustSignatoryId: req.CustSignatoryId,
  412. CustSignatoryName: req.CustSignatoryName,
  413. DistributorId: req.DistributorId,
  414. DistributorName: req.DistributorName,
  415. Remark: req.Remark,
  416. ServiceFeeAgreement: req.ServiceFeeAgreement,
  417. CreatedBy: int(s.userInfo.Id),
  418. CreatedName: s.userInfo.NickName,
  419. CreatedTime: gtime.Now(),
  420. UpdatedBy: int(s.userInfo.Id),
  421. UpdatedName: s.userInfo.NickName,
  422. UpdatedTime: gtime.Now(),
  423. }
  424. var id int
  425. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  426. ctrid, err := tx.InsertAndGetId("ctr_contract", ctr)
  427. if err != nil {
  428. return err
  429. }
  430. err = s.BindProduct(tx, int(ctrid), ctr.ContractCode, req.Product)
  431. if err != nil {
  432. return err
  433. }
  434. err = s.AddDynamicsByCurrentUser(tx, int(ctrid), "创建合同", map[string]interface{}{})
  435. if err != nil {
  436. return err
  437. }
  438. _, err = tx.Update("proj_business", map[string]interface{}{
  439. "nbo_type": projsrv.StatusDeal,
  440. }, "id = ?", nbo.Id)
  441. if err != nil {
  442. return err
  443. }
  444. id = int(ctrid)
  445. return nil
  446. })
  447. return id, txerr
  448. }
  449. var ContractApplyProcessCode = "PROC-7057E20A-2066-4644-9B35-9331E4DA912C" // 创建合同
  450. func (s CtrContractService) Commit(ctx context.Context, req *model.CtrContractCommitReq) (int64, error) {
  451. validErr := gvalid.CheckStruct(ctx, req, nil)
  452. if validErr != nil {
  453. return 0, myerrors.TipsError(validErr.Current().Error())
  454. }
  455. if !(req.ContractModel == "大数模板" || req.ContractModel == "客户模板") {
  456. return 0, myerrors.TipsError("合同模板不合法")
  457. }
  458. if !(req.Terms == "接纳全部条款" || req.Terms == "不接纳全部条款") {
  459. return 0, myerrors.TipsError("条款情况不合法")
  460. }
  461. if req.PayTerms == "" {
  462. return 0, myerrors.TipsError("付款条件不能为空")
  463. }
  464. if len(req.File) == 0 {
  465. return 0, myerrors.TipsError("附件不能为空")
  466. }
  467. ent, err := s.Dao.Where("id = ?", req.Id).One()
  468. if err != nil {
  469. return 0, err
  470. }
  471. if ent == nil {
  472. return 0, myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  473. }
  474. fileinfoByte, err := json.Marshal(req.File)
  475. if err != nil {
  476. return 0, err
  477. }
  478. workflowSrv, err := workflowService.NewFlowService(ctx)
  479. if err != nil {
  480. return 0, err
  481. }
  482. bizCode := strconv.Itoa(ent.Id)
  483. workflowId, err := workflowSrv.StartProcessInstance(bizCode, "30", "", &workflow.StartProcessInstanceRequest{
  484. ProcessCode: &ContractApplyProcessCode,
  485. FormComponentValues: []*workflow.StartProcessInstanceRequestFormComponentValues{
  486. {
  487. Id: utils.String("DDSelectField_ESX8H30W3VK0"),
  488. Name: utils.String("合同模板"),
  489. Value: utils.String(req.ContractModel),
  490. },
  491. {
  492. Id: utils.String("DDSelectField_13IQX96C2KAK0"),
  493. Name: utils.String("条款情况"),
  494. Value: utils.String(req.Terms),
  495. },
  496. {
  497. Id: utils.String("TextField_1A5SA7VOG5TS0"),
  498. Name: utils.String("合同编号"),
  499. Value: utils.String(ent.ContractCode),
  500. },
  501. {
  502. Id: utils.String("TextField_1EX61DPS3LA80"),
  503. Name: utils.String("客户名称"),
  504. Value: utils.String(ent.CustName),
  505. },
  506. {
  507. Id: utils.String("MoneyField_X1XV4KIR0GW0"),
  508. Name: utils.String("合同金额(元)"),
  509. Value: utils.String(strconv.FormatFloat(ent.ContractAmount, 'f', 2, 64)),
  510. },
  511. {
  512. Id: utils.String("TextareaField_1WZ5ILKBUVSW0"),
  513. Name: utils.String("付款条件"),
  514. Value: utils.String(req.PayTerms),
  515. },
  516. {
  517. Id: utils.String("DDAttachment_1051KJYC3MBK0"),
  518. Name: utils.String("附件"),
  519. // Details: productForm,
  520. Value: utils.String(string(fileinfoByte)),
  521. },
  522. },
  523. })
  524. if err != nil {
  525. return 0, err
  526. }
  527. _, err = s.Dao.Where("id = ?", ent.Id).Data(map[string]interface{}{
  528. "appro_status": 20,
  529. }).Update()
  530. return workflowId, err
  531. }
  532. // var spaceId = "21042518430"
  533. var spaceId = "21077726250"
  534. func (s CtrContractService) CommitWithFile(ctx context.Context, formData *multipart.Form) error {
  535. if s.userInfo.DingtalkUid == "" {
  536. return fmt.Errorf("该用户钉钉 uid 为空")
  537. }
  538. if len(formData.File) == 0 {
  539. return myerrors.TipsError("文件不能为空")
  540. }
  541. if _, ok := formData.File["file"]; !ok {
  542. return myerrors.TipsError("文件不能为空")
  543. }
  544. if formData.File["file"].FileName == "" {
  545. return fmt.Errorf("文件名称不能为空")
  546. }
  547. if formData.File["file"].File == nil {
  548. return fmt.Errorf("文件不能为空")
  549. }
  550. if formData.File["file"].File.Name() == "" {
  551. return fmt.Errorf("文件路径不能为空")
  552. }
  553. contractId, err := strconv.Atoi(formData.Value["contractId"])
  554. if err != nil {
  555. return fmt.Errorf("合同 Id 不合法 %s", formData.Value["contractId"])
  556. }
  557. //fmt.Println(args.File.Name(), args.FileName, args.FileSize, args.Meta)
  558. //fmt.Println(spaceId, s.userInfo.DingtalkId, args.FileName, args.File.Name())
  559. // resp, err := s.UploadFile("21042518430", "8xljy04PZiS9iPxp5PhDnUzQiEiE", "引物导入模板-000000.xlsx", "/Users/chengjian/Downloads/引物导入模板.xlsx")
  560. resp, err := dingtalk.Client.GetStorage().UploadFile(spaceId, s.userInfo.DingtalkId, formData.File["file"].FileName, formData.File["file"].File.Name())
  561. if err != nil {
  562. return fmt.Errorf("钉钉上传文件异常 %s", err.Error())
  563. }
  564. _, err = s.Commit(ctx, &model.CtrContractCommitReq{
  565. Id: contractId,
  566. ContractModel: formData.Value["contractModel"],
  567. Terms: formData.Value["terms"],
  568. PayTerms: formData.Value["payTerms"],
  569. File: []model.DingFileInfo{
  570. {
  571. SpaceId: resp.Dentry.SpaceId,
  572. FileId: resp.Dentry.Id,
  573. FileName: resp.Dentry.Name,
  574. FileSize: resp.Dentry.Size,
  575. FileType: resp.Dentry.Extension,
  576. },
  577. },
  578. })
  579. if err != nil {
  580. return err
  581. }
  582. // workflow, err := s.WorkflowDao.Where("id = ?", workflowId).One()
  583. // if err != nil {
  584. // return err
  585. // }
  586. // instance, err := dingtalk.Client.GetWorkflow().QueryProcessInstanceDetail(workflow.ProcessInstId)
  587. // if err != nil {
  588. // return fmt.Errorf("查询审批实例详情错误: %s", err.Error())
  589. // }
  590. // fmt.Println(workflow.ProcessInstId, instance.Result.ApproverUserIds)
  591. // approverUserIds := g.Config().GetStrings("dingtalk.approver-user-ids")
  592. // fmt.Println(approverUserIds)
  593. // for _, uid := range approverUserIds {
  594. // resp, err := dingtalk.Client.GetStorage().AddPermission(
  595. // dingtalk.Client.Context.CorpId, spaceId, uid, "DOWNLOADER", "USER")
  596. // if err != nil {
  597. // return fmt.Errorf("添加审核附件权限异常: %s", err.Error())
  598. // }
  599. // fmt.Println(uid, resp)
  600. // }
  601. appendSrv, err := NewCtrContractAppendService(ctx)
  602. if err != nil {
  603. return err
  604. }
  605. _, err = appendSrv.Add(ctx, &model.CtrContractAppendAddReq{
  606. ContractId: contractId,
  607. FileName: resp.Dentry.Name,
  608. FileType: resp.Dentry.Extension,
  609. FileUrl: strings.Join([]string{"dingtalk", resp.Dentry.SpaceId, resp.Dentry.Id}, ":"),
  610. Remark: "",
  611. })
  612. if err != nil {
  613. return err
  614. }
  615. return nil
  616. }
  617. func (s CtrContractService) DownloadDingtalkFile(ctx context.Context, id int) (string, error) {
  618. ent, err := s.AppendDao.Where("id= ?", id).One()
  619. if err != nil {
  620. return "", err
  621. }
  622. if ent == nil {
  623. return "", myerrors.TipsError("附件不存在")
  624. }
  625. if !strings.HasPrefix(ent.FileUrl, "dingtalk") {
  626. return "", myerrors.TipsError("此附件不是钉钉附件")
  627. }
  628. fileInfo := strings.Split(ent.FileUrl, ":")
  629. if len(fileInfo) != 3 {
  630. return "", myerrors.TipsError("钉钉附件地址不合法")
  631. }
  632. spaceId := fileInfo[1]
  633. fileId := fileInfo[2]
  634. // res, err := dingtalk.Client.GetStorage().AddPermission(dingtalk.Client.Context.CorpId, spaceId, s.userInfo.DingtalkId, "EDITOR", "USER")
  635. // fmt.Println(res, err)
  636. // if err != nil {
  637. // return "", fmt.Errorf("设置权限异常 %s", err.Error())
  638. // }
  639. resp, err := dingtalk.Client.GetStorage().QueryFileDownloadInfo(spaceId, fileId, s.userInfo.DingtalkId)
  640. if err != nil {
  641. return "", myerrors.TipsError("获取文件下载信息异常")
  642. }
  643. fmt.Println(resp, err)
  644. req, err := http.NewRequest("GET", resp.HeaderSignatureInfo.ResourceUrls[0], nil)
  645. if err != nil {
  646. return "", fmt.Errorf("构建文件下载请求异常 %s", err.Error())
  647. }
  648. for k, v := range resp.HeaderSignatureInfo.Headers {
  649. req.Header.Add(k, v)
  650. }
  651. fileresp, err := http.DefaultClient.Do(req)
  652. if err != nil {
  653. return "", fmt.Errorf("文件下载异常 %s", err.Error())
  654. }
  655. data, err := io.ReadAll(fileresp.Body)
  656. if err != nil {
  657. return "", fmt.Errorf("读取下载内容异常 %s", err.Error())
  658. }
  659. return base64.StdEncoding.EncodeToString(data), nil
  660. }
  661. func ContractApplyApproval(ctx context.Context, flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  662. tenant, err := micro_srv.GetTenant(ctx)
  663. if err != nil {
  664. return fmt.Errorf("获取租户码异常:%s", err.Error())
  665. }
  666. contractDao := dao.NewCtrContractDao(tenant)
  667. contractId, err := strconv.Atoi(flow.BizCode)
  668. if err != nil {
  669. return fmt.Errorf("创建合同审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  670. }
  671. contract, err := contractDao.Where("id = ?", contractId).One()
  672. if err != nil {
  673. return err
  674. }
  675. if contract == nil {
  676. return fmt.Errorf("合同不存在:%s Id: %d", flow.BizCode, flow.Id)
  677. }
  678. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  679. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  680. }
  681. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  682. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  683. }
  684. var status string
  685. if msg.ProcessType == "terminate" {
  686. status = "50"
  687. } else {
  688. pass := msg.Result == "agree"
  689. if !pass {
  690. status = "40"
  691. } else {
  692. status = "30"
  693. }
  694. }
  695. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  696. "appro_status": status,
  697. }).Update()
  698. if err != nil {
  699. return err
  700. }
  701. if status != "30" {
  702. return nil
  703. }
  704. return contractDao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  705. _, err = worksrv.DeliverOrderAdd(tx, contractId, request.UserInfo{})
  706. return err
  707. })
  708. }
  709. func (s CtrContractService) Update(ctx context.Context, req *model.CtrContractUpdateReq) error {
  710. validErr := gvalid.CheckStruct(ctx, req, nil)
  711. if validErr != nil {
  712. return myerrors.TipsError(validErr.Current().Error())
  713. }
  714. ent, err := s.Dao.Where("id = ?", req.Id).One()
  715. if err != nil {
  716. return err
  717. }
  718. if ent == nil {
  719. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  720. }
  721. // if req.ContractCode != "" {
  722. // exist, err := s.Dao.Where("contract_code = ?", req.ContractCode).One()
  723. // if err != nil {
  724. // return err
  725. // }
  726. // if exist != nil && exist.Id != req.Id {
  727. // return myerrors.NewMsgError(nil, fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  728. // }
  729. // }
  730. if req.ContractName != "" {
  731. exist, err := s.Dao.Where("contract_name = ?", req.ContractName).One()
  732. if err != nil {
  733. return err
  734. }
  735. if exist != nil && exist.Id != req.Id {
  736. return myerrors.TipsError(fmt.Sprintf("合同名称:%s 已存在", req.ContractName))
  737. }
  738. }
  739. var nbo *proj.ProjBusiness
  740. if req.NboId != 0 {
  741. nbo, err = s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  742. if err != nil {
  743. return err
  744. }
  745. if nbo == nil {
  746. return myerrors.TipsError("项目不存在")
  747. }
  748. }
  749. toupdate := map[string]interface{}{}
  750. // if req.ContractCode != "" {
  751. // toupdate["contract_code"] = req.ContractCode
  752. // }
  753. if req.ContractName != "" {
  754. toupdate["contract_name"] = req.ContractName
  755. }
  756. if req.NboId != 0 {
  757. toupdate["cust_id"] = nbo.CustId
  758. toupdate["cust_name"] = nbo.CustName
  759. toupdate["nbo_id"] = nbo.Id
  760. toupdate["nbo_name"] = nbo.NboName
  761. toupdate["is_big"] = nbo.IsBig
  762. toupdate["product_line"] = nbo.ProductLine
  763. toupdate["cust_province_id"] = nbo.CustProvinceId
  764. toupdate["cust_province"] = nbo.CustProvince
  765. toupdate["cust_city_id"] = nbo.CustCityId
  766. toupdate["cust_city"] = nbo.CustCity
  767. }
  768. // if req.ApproStatus != "" {
  769. // toupdate["appro_status"] = req.ApproStatus
  770. // }
  771. if req.ContractType != "" {
  772. toupdate["contract_type"] = req.ContractType
  773. }
  774. // if req.ContractAmount != 0 {
  775. // toupdate["contract_amount"] = req.ContractAmount
  776. // }
  777. // if req.InvoiceAmount != 0 {
  778. // toupdate["invoice_amount"] = req.InvoiceAmount
  779. // }
  780. // if req.CollectedAmount != 0 {
  781. // toupdate["collected_amount"] = req.CollectedAmount
  782. // }
  783. if req.ContractStartTime != nil {
  784. toupdate["contract_start_time"] = req.ContractStartTime
  785. }
  786. if req.ContractEndTime != nil {
  787. toupdate["contract_end_time"] = req.ContractEndTime
  788. }
  789. if req.ContractSignTime != nil {
  790. toupdate["contract_sign_time"] = req.ContractSignTime
  791. }
  792. //if req.InchargeId != 0 {
  793. // toupdate["incharge_id"] = req.InchargeId
  794. //}
  795. //if req.InchargeName != "" {
  796. // toupdate["incharge_name"] = req.InchargeName
  797. //}
  798. if req.SignatoryId != 0 {
  799. toupdate["signatory_id"] = req.SignatoryId
  800. }
  801. if req.SignatoryName != "" {
  802. toupdate["signatory_name"] = req.SignatoryName
  803. }
  804. if req.SignatoryType != "" {
  805. toupdate["signatory_type"] = req.SignatoryType
  806. }
  807. if req.SignatoryUnit != "" {
  808. toupdate["signatory_unit"] = req.SignatoryUnit
  809. }
  810. if req.EarnestMoney != nil {
  811. toupdate["earnest_money"] = req.EarnestMoney
  812. }
  813. if req.CustSignatoryId != 0 {
  814. toupdate["cust_signatory_id"] = req.CustSignatoryId
  815. }
  816. if req.CustSignatoryName != "" {
  817. toupdate["cust_signatory_name"] = req.CustSignatoryName
  818. }
  819. if req.DistributorId != 0 {
  820. toupdate["distributor_id"] = req.DistributorId
  821. }
  822. if req.DistributorName != "" {
  823. toupdate["distributor_name"] = req.DistributorName
  824. }
  825. if req.Remark != nil {
  826. toupdate["remark"] = *req.Remark
  827. }
  828. if req.Product != nil {
  829. var contractAmount float64
  830. for _, p := range *req.Product {
  831. contractAmount += (p.TranPrice * float64(p.ProdNum))
  832. }
  833. toupdate["contract_amount"] = contractAmount
  834. }
  835. if len(toupdate) != 0 {
  836. toupdate["updated_by"] = int(s.userInfo.Id)
  837. toupdate["updated_name"] = s.userInfo.NickName
  838. toupdate["updated_time"] = gtime.Now()
  839. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  840. _, err = tx.Update("ctr_contract", toupdate, "id = ?", req.Id)
  841. if err != nil {
  842. return err
  843. }
  844. if req.Product != nil {
  845. err = s.BindProduct(tx, req.Id, ent.ContractCode, *req.Product)
  846. if err != nil {
  847. return err
  848. }
  849. }
  850. return nil
  851. })
  852. if txerr != nil {
  853. return txerr
  854. }
  855. }
  856. return nil
  857. }
  858. func (s CtrContractService) UpdateProduct(ctx context.Context, req *model.CtrContractUpdateProductReq) error {
  859. validErr := gvalid.CheckStruct(ctx, req, nil)
  860. if validErr != nil {
  861. return myerrors.TipsError(validErr.Current().Error())
  862. }
  863. ent, err := s.CtrProductDao.Where("id = ?", req.Id).One()
  864. if err != nil {
  865. return err
  866. }
  867. if ent == nil {
  868. return myerrors.TipsError(fmt.Sprintf("合同产品记录不存在: %d", req.Id))
  869. }
  870. toupdate := map[string]interface{}{}
  871. if req.MaintainPeriod != nil {
  872. toupdate["maintain_period"] = req.MaintainPeriod
  873. }
  874. if req.WarrantPeriod != nil {
  875. toupdate["warrant_period"] = req.WarrantPeriod
  876. }
  877. if req.MaintainStartTime != nil {
  878. toupdate["maintain_start_time"] = req.MaintainStartTime
  879. }
  880. if req.MaintainRemark != nil {
  881. toupdate["maintain_remark"] = req.MaintainRemark
  882. }
  883. if req.AcceptTime != nil {
  884. toupdate["accept_time"] = req.AcceptTime
  885. }
  886. if req.PurchaseCost != nil {
  887. toupdate["purchase_cost"] = req.PurchaseCost
  888. }
  889. if req.DevCost != nil {
  890. toupdate["dev_cost"] = req.DevCost
  891. }
  892. if req.MaintainCost != nil {
  893. toupdate["maintain_cost"] = req.MaintainCost
  894. }
  895. if req.DirectCost != nil {
  896. toupdate["direct_cost"] = req.DirectCost
  897. }
  898. if len(toupdate) != 0 {
  899. toupdate["updated_by"] = int(s.userInfo.Id)
  900. toupdate["updated_name"] = s.userInfo.NickName
  901. toupdate["updated_time"] = gtime.Now()
  902. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  903. _, err = tx.Update("ctr_contract_product", toupdate, "id = ?", req.Id)
  904. if err != nil {
  905. return err
  906. }
  907. err = s.AddDynamicsByCurrentUser(tx, ent.ContractId, "更新合同产品信息", toupdate)
  908. if err != nil {
  909. return err
  910. }
  911. return nil
  912. })
  913. if txerr != nil {
  914. return txerr
  915. }
  916. }
  917. return nil
  918. }
  919. func (s CtrContractService) Transfer(ctx context.Context, req *model.CtrContractTransferReq) error {
  920. if len(req.Id) == 0 {
  921. return nil
  922. }
  923. ents := map[int]*model.CtrContract{}
  924. for _, i := range req.Id {
  925. ent, err := s.Dao.Where("id = ?", i).One()
  926. if err != nil {
  927. return err
  928. }
  929. if ent == nil {
  930. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  931. }
  932. ents[ent.Id] = ent
  933. }
  934. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  935. toupdate := map[string]interface{}{
  936. "incharge_id": req.InchargeId,
  937. "incharge_name": req.InchargeName,
  938. }
  939. _, err := tx.Update("ctr_contract", toupdate, "id in (?)", req.Id)
  940. if err != nil {
  941. return err
  942. }
  943. for _, ent := range ents {
  944. err = s.AddDynamicsByCurrentUser(tx, ent.Id, "转移合同", map[string]interface{}{
  945. "toInchargeId": req.InchargeId,
  946. "toInchargeName": req.InchargeName,
  947. "fromInchargeId": ent.InchargeId,
  948. "fromInchargeName": ent.InchargeName,
  949. "operatedId": s.userInfo.Id,
  950. "operatedName": s.userInfo.NickName,
  951. })
  952. if err != nil {
  953. return err
  954. }
  955. }
  956. return nil
  957. })
  958. if txerr != nil {
  959. return txerr
  960. }
  961. return nil
  962. }
  963. func (s CtrContractService) UpdateInvoiceAmount(tx *gdb.TX, id int) error {
  964. ctr := model.CtrContract{}
  965. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  966. if err == sql.ErrNoRows {
  967. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  968. }
  969. if err != nil {
  970. return err
  971. }
  972. 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)
  973. if err != nil {
  974. return err
  975. }
  976. amount := v.Float64()
  977. _, err = tx.Update("ctr_contract",
  978. map[string]interface{}{
  979. "invoice_amount": amount,
  980. }, "id = ?", id)
  981. if err != nil {
  982. return err
  983. }
  984. return nil
  985. }
  986. func (s CtrContractService) UpdateCollectedAmount(tx *gdb.TX, id int) error {
  987. ctr := model.CtrContract{}
  988. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  989. if err == sql.ErrNoRows {
  990. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  991. }
  992. if err != nil {
  993. return err
  994. }
  995. 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)
  996. if err != nil {
  997. return err
  998. }
  999. amount := v.Float64()
  1000. _, err = tx.Update("ctr_contract",
  1001. map[string]interface{}{
  1002. "collected_amount": amount,
  1003. }, "id = ?", id)
  1004. if err != nil {
  1005. return err
  1006. }
  1007. return nil
  1008. }
  1009. func (s CtrContractService) Delete(ctx context.Context, id []int) error {
  1010. if len(id) == 0 {
  1011. return nil
  1012. }
  1013. _, err := s.Dao.Where("Id IN (?)", id).Delete()
  1014. return err
  1015. }
  1016. func init() {
  1017. tenant := g.Config().GetString("micro_srv.tenant")
  1018. if tenant == "" {
  1019. panic("定时任务租户码未设置,请前往配置")
  1020. }
  1021. contractDao := dao.NewCtrContractDao(tenant)
  1022. produceDao := dao.NewCtrContractProductDao(tenant)
  1023. job := func() {
  1024. alert := map[int]*[]model.CtrContractProduct{
  1025. 180: {},
  1026. 90: {},
  1027. 30: {},
  1028. 10: {},
  1029. // 7: {},
  1030. }
  1031. where := `DATE_FORMAT(DATE_ADD(maintain_start_time, INTERVAL ? day), "%Y-%m-%d") = DATE_FORMAT(NOW(), "%Y-%m-%d")`
  1032. for day, p := range alert {
  1033. err := produceDao.Where(where, day).Structs(p)
  1034. if err != nil {
  1035. glog.Error(err)
  1036. }
  1037. glog.Infof("运维期到期 %d 天提醒,产品个数 %d", day, len(*p))
  1038. }
  1039. for day, p := range alert {
  1040. for _, i := range *p {
  1041. ctr, err := contractDao.Where("id = ?", i.ContractId).One()
  1042. if err != nil {
  1043. glog.Error(err)
  1044. }
  1045. text := fmt.Sprintf("合同:%s-%s 中的产品:%s 距离运维到期还有 %d 天",
  1046. ctr.ContractCode, ctr.ContractName, i.ProdName, day)
  1047. msg := g.MapStrStr{
  1048. "msgTitle": "运维期到期提醒",
  1049. "msgContent": text,
  1050. "msgType": "20",
  1051. "recvUserIds": strconv.Itoa(ctr.InchargeId),
  1052. "msgStatus": "10",
  1053. "sendType": "10",
  1054. }
  1055. if err := service.CreateSystemMessage(msg); err != nil {
  1056. glog.Error("消息提醒异常:", err)
  1057. }
  1058. glog.Infof("%s", text)
  1059. }
  1060. }
  1061. }
  1062. // 每天凌晨2点执行
  1063. gcron.AddSingleton("0 0 2 * * *", job)
  1064. // job()
  1065. }