ctr_contract.go 23 KB

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