ctr_contract.go 27 KB

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