ctr_contract.go 22 KB

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