ctr_contract.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. IsBig: nbo.IsBig,
  355. ProductLine: nbo.ProductLine,
  356. CustProvinceId: nbo.CustProvinceId,
  357. CustProvince: nbo.CustProvince,
  358. CustCityId: nbo.CustCityId,
  359. CustCity: nbo.CustCity,
  360. ApproStatus: "10",
  361. ContractType: req.ContractType,
  362. ContractAmount: contractAmount,
  363. InvoiceAmount: 0,
  364. CollectedAmount: 0,
  365. ContractStartTime: req.ContractStartTime,
  366. ContractEndTime: req.ContractEndTime,
  367. InchargeId: req.InchargeId,
  368. InchargeName: req.InchargeName,
  369. SignatoryId: req.SignatoryId,
  370. SignatoryName: req.SignatoryName,
  371. SignatoryType: req.SignatoryType,
  372. CustSignatoryId: req.CustSignatoryId,
  373. CustSignatoryName: req.CustSignatoryName,
  374. DistributorId: req.DistributorId,
  375. DistributorName: req.DistributorName,
  376. Remark: req.Remark,
  377. CreatedBy: int(s.userInfo.Id),
  378. CreatedName: s.userInfo.NickName,
  379. CreatedTime: gtime.Now(),
  380. UpdatedBy: int(s.userInfo.Id),
  381. UpdatedName: s.userInfo.NickName,
  382. UpdatedTime: gtime.Now(),
  383. }
  384. var id int
  385. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  386. ctrid, err := tx.InsertAndGetId("ctr_contract", ctr)
  387. if err != nil {
  388. return err
  389. }
  390. err = s.BindProduct(tx, int(ctrid), req.Product)
  391. if err != nil {
  392. return err
  393. }
  394. err = s.AddDynamicsByCurrentUser(tx, int(ctrid), "创建合同", map[string]interface{}{})
  395. if err != nil {
  396. return err
  397. }
  398. _, err = tx.Update("proj_business", map[string]interface{}{
  399. "nbo_type": projsrv.StatusDeal,
  400. }, "id = ?", nbo.Id)
  401. if err != nil {
  402. return err
  403. }
  404. id = int(ctrid)
  405. return nil
  406. })
  407. return id, txerr
  408. }
  409. var ContractApplyProcessCode = "PROC-7057E20A-2066-4644-9B35-9331E4DA912C" // 创建合同
  410. func (s CtrContractService) Commit(ctx context.Context, req *model.CtrContractCommitReq) (int64, error) {
  411. validErr := gvalid.CheckStruct(ctx, req, nil)
  412. if validErr != nil {
  413. return 0, myerrors.TipsError(validErr.Current().Error())
  414. }
  415. if !(req.ContractModel == "大数模板" || req.ContractModel == "客户模板") {
  416. return 0, myerrors.TipsError("合同模板不合法")
  417. }
  418. if !(req.Terms == "接纳全部条款" || req.Terms == "不接纳全部条款") {
  419. return 0, myerrors.TipsError("条款情况不合法")
  420. }
  421. if req.PayTerms == "" {
  422. return 0, myerrors.TipsError("付款条件不能为空")
  423. }
  424. if len(req.File) == 0 {
  425. return 0, myerrors.TipsError("附件不能为空")
  426. }
  427. ent, err := s.Dao.Where("id = ?", req.Id).One()
  428. if err != nil {
  429. return 0, err
  430. }
  431. if ent == nil {
  432. return 0, myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  433. }
  434. fileinfoByte, err := json.Marshal(req.File)
  435. if err != nil {
  436. return 0, err
  437. }
  438. workflowSrv, err := workflowService.NewFlowService(ctx)
  439. if err != nil {
  440. return 0, err
  441. }
  442. bizCode := strconv.Itoa(ent.Id)
  443. workflowId, err := workflowSrv.StartProcessInstance(bizCode, "30", "", &workflow.StartProcessInstanceRequest{
  444. ProcessCode: &ContractApplyProcessCode,
  445. FormComponentValues: []*workflow.StartProcessInstanceRequestFormComponentValues{
  446. {
  447. Id: utils.String("DDSelectField_ESX8H30W3VK0"),
  448. Name: utils.String("合同模板"),
  449. Value: utils.String(req.ContractModel),
  450. },
  451. {
  452. Id: utils.String("DDSelectField_13IQX96C2KAK0"),
  453. Name: utils.String("条款情况"),
  454. Value: utils.String(req.Terms),
  455. },
  456. {
  457. Id: utils.String("TextField_1A5SA7VOG5TS0"),
  458. Name: utils.String("合同编号"),
  459. Value: utils.String(ent.ContractCode),
  460. },
  461. {
  462. Id: utils.String("TextField_1EX61DPS3LA80"),
  463. Name: utils.String("客户名称"),
  464. Value: utils.String(ent.CustName),
  465. },
  466. {
  467. Id: utils.String("MoneyField_X1XV4KIR0GW0"),
  468. Name: utils.String("合同金额(元)"),
  469. Value: utils.String(strconv.FormatFloat(ent.ContractAmount, 'f', 2, 64)),
  470. },
  471. {
  472. Id: utils.String("TextareaField_1WZ5ILKBUVSW0"),
  473. Name: utils.String("付款条件"),
  474. Value: utils.String(req.PayTerms),
  475. },
  476. {
  477. Id: utils.String("DDAttachment_1051KJYC3MBK0"),
  478. Name: utils.String("附件"),
  479. // Details: productForm,
  480. Value: utils.String(string(fileinfoByte)),
  481. },
  482. },
  483. })
  484. if err != nil {
  485. return 0, err
  486. }
  487. _, err = s.Dao.Where("id = ?", ent.Id).Data(map[string]interface{}{
  488. "appro_status": 20,
  489. }).Update()
  490. return workflowId, err
  491. }
  492. // var spaceId = "21042518430"
  493. var spaceId = "21077726250"
  494. func (s CtrContractService) CommitWithFile(ctx context.Context, args *multipart.MultipartFile) error {
  495. if s.userInfo.DingtalkUid == "" {
  496. return fmt.Errorf("该用户钉钉 uid 为空")
  497. }
  498. if args.FileName == "" {
  499. return fmt.Errorf("文件名称不能为空")
  500. }
  501. if args.File == nil {
  502. return fmt.Errorf("文件不能为空")
  503. }
  504. if args.File.Name() == "" {
  505. return fmt.Errorf("文件路径不能为空")
  506. }
  507. contractId, err := strconv.Atoi(args.Meta["contractId"])
  508. if err != nil {
  509. return fmt.Errorf("合同 Id 不合法 %s", args.Meta["contractId"])
  510. }
  511. fmt.Println(args.File.Name(), args.FileName, args.FileSize, args.Meta)
  512. fmt.Println(spaceId, s.userInfo.DingtalkId, args.FileName, args.File.Name())
  513. // resp, err := s.UploadFile("21042518430", "8xljy04PZiS9iPxp5PhDnUzQiEiE", "引物导入模板-000000.xlsx", "/Users/chengjian/Downloads/引物导入模板.xlsx")
  514. resp, err := dingtalk.Client.GetStorage().UploadFile(spaceId, s.userInfo.DingtalkId, args.FileName, args.File.Name())
  515. if err != nil {
  516. return fmt.Errorf("钉钉上传文件异常 %s", err.Error())
  517. }
  518. _, err = s.Commit(ctx, &model.CtrContractCommitReq{
  519. Id: contractId,
  520. ContractModel: args.Meta["contractModel"],
  521. Terms: args.Meta["terms"],
  522. PayTerms: args.Meta["payTerms"],
  523. File: []model.DingFileInfo{
  524. {
  525. SpaceId: resp.Dentry.SpaceId,
  526. FileId: resp.Dentry.Id,
  527. FileName: resp.Dentry.Name,
  528. FileSize: resp.Dentry.Size,
  529. FileType: resp.Dentry.Extension,
  530. },
  531. },
  532. })
  533. if err != nil {
  534. return err
  535. }
  536. // workflow, err := s.WorkflowDao.Where("id = ?", workflowId).One()
  537. // if err != nil {
  538. // return err
  539. // }
  540. // instance, err := dingtalk.Client.GetWorkflow().QueryProcessInstanceDetail(workflow.ProcessInstId)
  541. // if err != nil {
  542. // return fmt.Errorf("查询审批实例详情错误: %s", err.Error())
  543. // }
  544. // fmt.Println(workflow.ProcessInstId, instance.Result.ApproverUserIds)
  545. // approverUserIds := g.Config().GetStrings("dingtalk.approver-user-ids")
  546. // fmt.Println(approverUserIds)
  547. // for _, uid := range approverUserIds {
  548. // resp, err := dingtalk.Client.GetStorage().AddPermission(
  549. // dingtalk.Client.Context.CorpId, spaceId, uid, "DOWNLOADER", "USER")
  550. // if err != nil {
  551. // return fmt.Errorf("添加审核附件权限异常: %s", err.Error())
  552. // }
  553. // fmt.Println(uid, resp)
  554. // }
  555. appendSrv, err := NewCtrContractAppendService(ctx)
  556. if err != nil {
  557. return err
  558. }
  559. _, err = appendSrv.Add(ctx, &model.CtrContractAppendAddReq{
  560. ContractId: contractId,
  561. FileName: resp.Dentry.Name,
  562. FileType: resp.Dentry.Extension,
  563. FileUrl: strings.Join([]string{"dingtalk", resp.Dentry.SpaceId, resp.Dentry.Id}, ":"),
  564. Remark: "",
  565. })
  566. if err != nil {
  567. return err
  568. }
  569. return nil
  570. }
  571. func (s CtrContractService) DownloadDingtalkFile(ctx context.Context, id int) (string, error) {
  572. ent, err := s.AppendDao.Where("id= ?", id).One()
  573. if err != nil {
  574. return "", err
  575. }
  576. if ent == nil {
  577. return "", myerrors.TipsError("附件不存在")
  578. }
  579. if !strings.HasPrefix(ent.FileUrl, "dingtalk") {
  580. return "", myerrors.TipsError("此附件不是钉钉附件")
  581. }
  582. fileInfo := strings.Split(ent.FileUrl, ":")
  583. if len(fileInfo) != 3 {
  584. return "", myerrors.TipsError("钉钉附件地址不合法")
  585. }
  586. spaceId := fileInfo[1]
  587. fileId := fileInfo[2]
  588. // res, err := dingtalk.Client.GetStorage().AddPermission(dingtalk.Client.Context.CorpId, spaceId, s.userInfo.DingtalkId, "EDITOR", "USER")
  589. // fmt.Println(res, err)
  590. // if err != nil {
  591. // return "", fmt.Errorf("设置权限异常 %s", err.Error())
  592. // }
  593. resp, err := dingtalk.Client.GetStorage().QueryFileDownloadInfo(spaceId, fileId, s.userInfo.DingtalkId)
  594. if err != nil {
  595. return "", myerrors.TipsError("获取文件下载信息异常")
  596. }
  597. fmt.Println(resp, err)
  598. req, err := http.NewRequest("GET", resp.HeaderSignatureInfo.ResourceUrls[0], nil)
  599. if err != nil {
  600. return "", fmt.Errorf("构建文件下载请求异常 %s", err.Error())
  601. }
  602. for k, v := range resp.HeaderSignatureInfo.Headers {
  603. req.Header.Add(k, v)
  604. }
  605. fileresp, err := http.DefaultClient.Do(req)
  606. if err != nil {
  607. return "", fmt.Errorf("文件下载异常 %s", err.Error())
  608. }
  609. data, err := io.ReadAll(fileresp.Body)
  610. if err != nil {
  611. return "", fmt.Errorf("读取下载内容异常 %s", err.Error())
  612. }
  613. return base64.StdEncoding.EncodeToString(data), nil
  614. }
  615. func ContractApplyApproval(ctx context.Context, flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  616. tenant, err := micro_srv.GetTenant(ctx)
  617. if err != nil {
  618. return fmt.Errorf("获取租户码异常:%s", err.Error())
  619. }
  620. contractDao := dao.NewCtrContractDao(tenant)
  621. contractId, err := strconv.Atoi(flow.BizCode)
  622. if err != nil {
  623. return fmt.Errorf("创建合同审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  624. }
  625. contract, err := contractDao.Where("id = ?", contractId).One()
  626. if err != nil {
  627. return err
  628. }
  629. if contract == nil {
  630. return fmt.Errorf("合同不存在:%s Id: %d", flow.BizCode, flow.Id)
  631. }
  632. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  633. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  634. }
  635. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  636. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  637. }
  638. if msg.ProcessType == "terminate" {
  639. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  640. "appro_status": "50",
  641. }).Update()
  642. return err
  643. }
  644. pass := msg.Result == "agree"
  645. if !pass {
  646. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  647. "appro_status": "40",
  648. }).Update()
  649. return err
  650. }
  651. _, err = contractDao.Where("id = ?", contractId).Data(map[string]interface{}{
  652. "appro_status": "30",
  653. }).Update()
  654. return err
  655. }
  656. func (s CtrContractService) Update(ctx context.Context, req *model.CtrContractUpdateReq) error {
  657. validErr := gvalid.CheckStruct(ctx, req, nil)
  658. if validErr != nil {
  659. return myerrors.TipsError(validErr.Current().Error())
  660. }
  661. ent, err := s.Dao.Where("id = ?", req.Id).One()
  662. if err != nil {
  663. return err
  664. }
  665. if ent == nil {
  666. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  667. }
  668. // if req.ContractCode != "" {
  669. // exist, err := s.Dao.Where("contract_code = ?", req.ContractCode).One()
  670. // if err != nil {
  671. // return err
  672. // }
  673. // if exist != nil && exist.Id != req.Id {
  674. // return myerrors.NewMsgError(nil, fmt.Sprintf("合同编号:%s 已存在", req.ContractCode))
  675. // }
  676. // }
  677. if req.ContractName != "" {
  678. exist, err := s.Dao.Where("contract_name = ?", req.ContractName).One()
  679. if err != nil {
  680. return err
  681. }
  682. if exist != nil && exist.Id != req.Id {
  683. return myerrors.TipsError(fmt.Sprintf("合同名称:%s 已存在", req.ContractName))
  684. }
  685. }
  686. var nbo *proj.ProjBusiness
  687. if req.NboId != 0 {
  688. nbo, err = s.ProjBusinessDao.Where("id = ?", req.NboId).One()
  689. if err != nil {
  690. return err
  691. }
  692. if nbo == nil {
  693. return myerrors.TipsError("项目不存在")
  694. }
  695. }
  696. toupdate := map[string]interface{}{}
  697. // if req.ContractCode != "" {
  698. // toupdate["contract_code"] = req.ContractCode
  699. // }
  700. if req.ContractName != "" {
  701. toupdate["contract_name"] = req.ContractName
  702. }
  703. if req.NboId != 0 {
  704. toupdate["cust_id"] = nbo.CustId
  705. toupdate["cust_name"] = nbo.CustName
  706. toupdate["nbo_id"] = nbo.Id
  707. toupdate["nbo_name"] = nbo.NboName
  708. toupdate["is_big"] = nbo.IsBig
  709. toupdate["product_line"] = nbo.ProductLine
  710. toupdate["cust_province_id"] = nbo.CustProvinceId
  711. toupdate["cust_province"] = nbo.CustProvince
  712. toupdate["cust_city_id"] = nbo.CustCityId
  713. toupdate["cust_city"] = nbo.CustCity
  714. }
  715. // if req.ApproStatus != "" {
  716. // toupdate["appro_status"] = req.ApproStatus
  717. // }
  718. if req.ContractType != "" {
  719. toupdate["contract_type"] = req.ContractType
  720. }
  721. // if req.ContractAmount != 0 {
  722. // toupdate["contract_amount"] = req.ContractAmount
  723. // }
  724. // if req.InvoiceAmount != 0 {
  725. // toupdate["invoice_amount"] = req.InvoiceAmount
  726. // }
  727. // if req.CollectedAmount != 0 {
  728. // toupdate["collected_amount"] = req.CollectedAmount
  729. // }
  730. if req.ContractStartTime != nil {
  731. toupdate["contract_start_time"] = req.ContractStartTime
  732. }
  733. if req.ContractEndTime != nil {
  734. toupdate["contract_end_time"] = req.ContractEndTime
  735. }
  736. //if req.InchargeId != 0 {
  737. // toupdate["incharge_id"] = req.InchargeId
  738. //}
  739. //if req.InchargeName != "" {
  740. // toupdate["incharge_name"] = req.InchargeName
  741. //}
  742. if req.SignatoryId != 0 {
  743. toupdate["signatory_id"] = req.SignatoryId
  744. }
  745. if req.SignatoryName != "" {
  746. toupdate["signatory_name"] = req.SignatoryName
  747. }
  748. if req.SignatoryType != "" {
  749. toupdate["signatory_type"] = req.SignatoryType
  750. }
  751. if req.CustSignatoryId != 0 {
  752. toupdate["cust_signatory_id"] = req.CustSignatoryId
  753. }
  754. if req.CustSignatoryName != "" {
  755. toupdate["cust_signatory_name"] = req.CustSignatoryName
  756. }
  757. if req.DistributorId != 0 {
  758. toupdate["distributor_id"] = req.DistributorId
  759. }
  760. if req.DistributorName != "" {
  761. toupdate["distributor_name"] = req.DistributorName
  762. }
  763. if req.Remark != nil {
  764. toupdate["remark"] = *req.Remark
  765. }
  766. if req.Product != nil {
  767. var contractAmount float64
  768. for _, p := range *req.Product {
  769. contractAmount += (p.TranPrice * float64(p.ProdNum))
  770. }
  771. toupdate["contract_amount"] = contractAmount
  772. }
  773. if len(toupdate) != 0 {
  774. toupdate["updated_by"] = int(s.userInfo.Id)
  775. toupdate["updated_name"] = s.userInfo.NickName
  776. toupdate["updated_time"] = gtime.Now()
  777. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  778. _, err = tx.Update("ctr_contract", toupdate, "id = ?", req.Id)
  779. if err != nil {
  780. return err
  781. }
  782. if req.Product != nil {
  783. err = s.BindProduct(tx, req.Id, *req.Product)
  784. if err != nil {
  785. return err
  786. }
  787. }
  788. return nil
  789. })
  790. if txerr != nil {
  791. return txerr
  792. }
  793. }
  794. return nil
  795. }
  796. func (s CtrContractService) Transfer(ctx context.Context, req *model.CtrContractTransferReq) error {
  797. if len(req.Id) == 0 {
  798. return nil
  799. }
  800. ents := map[int]*model.CtrContract{}
  801. for _, i := range req.Id {
  802. ent, err := s.Dao.Where("id = ?", i).One()
  803. if err != nil {
  804. return err
  805. }
  806. if ent == nil {
  807. return myerrors.TipsError(fmt.Sprintf("合同不存在: %d", req.Id))
  808. }
  809. ents[ent.Id] = ent
  810. }
  811. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  812. toupdate := map[string]interface{}{
  813. "incharge_id": req.InchargeId,
  814. "incharge_name": req.InchargeName,
  815. }
  816. _, err := tx.Update("ctr_contract", toupdate, "id in (?)", req.Id)
  817. if err != nil {
  818. return err
  819. }
  820. for _, ent := range ents {
  821. err = s.AddDynamicsByCurrentUser(tx, ent.Id, "转移合同", map[string]interface{}{
  822. "toInchargeId": req.InchargeId,
  823. "toInchargeName": req.InchargeName,
  824. "fromInchargeId": ent.InchargeId,
  825. "fromInchargeName": ent.InchargeName,
  826. "operatedId": s.userInfo.Id,
  827. "operatedName": s.userInfo.NickName,
  828. })
  829. if err != nil {
  830. return err
  831. }
  832. }
  833. return nil
  834. })
  835. if txerr != nil {
  836. return txerr
  837. }
  838. return nil
  839. }
  840. func (s CtrContractService) UpdateInvoiceAmount(tx *gdb.TX, id int) error {
  841. ctr := model.CtrContract{}
  842. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  843. if err == sql.ErrNoRows {
  844. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  845. }
  846. if err != nil {
  847. return err
  848. }
  849. 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)
  850. if err != nil {
  851. return err
  852. }
  853. amount := v.Float64()
  854. _, err = tx.Update("ctr_contract",
  855. map[string]interface{}{
  856. "invoice_amount": amount,
  857. }, "id = ?", id)
  858. if err != nil {
  859. return err
  860. }
  861. return nil
  862. }
  863. func (s CtrContractService) UpdateCollectedAmount(tx *gdb.TX, id int) error {
  864. ctr := model.CtrContract{}
  865. err := tx.GetStruct(&ctr, "select * from ctr_contract where id = ?", id)
  866. if err == sql.ErrNoRows {
  867. return myerrors.TipsError(fmt.Sprintf("合同不存在 %d", id))
  868. }
  869. if err != nil {
  870. return err
  871. }
  872. 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)
  873. if err != nil {
  874. return err
  875. }
  876. amount := v.Float64()
  877. _, err = tx.Update("ctr_contract",
  878. map[string]interface{}{
  879. "collected_amount": amount,
  880. }, "id = ?", id)
  881. if err != nil {
  882. return err
  883. }
  884. return nil
  885. }
  886. func (s CtrContractService) Delete(ctx context.Context, id []int) error {
  887. if len(id) == 0 {
  888. return nil
  889. }
  890. _, err := s.Dao.Where("Id IN (?)", id).Delete()
  891. return err
  892. }