ctr_contract.go 28 KB

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