ctr_contract.go 22 KB

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