ctr_contract.go 28 KB

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