ctr_contract.go 27 KB

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