ctr_contract_invoice.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. package service
  2. import (
  3. "context"
  4. "database/sql"
  5. "encoding/json"
  6. "fmt"
  7. "strconv"
  8. "strings"
  9. dao "dashoo.cn/micro/app/dao/contract"
  10. customerDao "dashoo.cn/micro/app/dao/cust"
  11. sysDao "dashoo.cn/micro/app/dao/sys"
  12. model "dashoo.cn/micro/app/model/contract"
  13. workflowModel "dashoo.cn/micro/app/model/workflow"
  14. workflowService "dashoo.cn/micro/app/service/workflow"
  15. "dashoo.cn/opms_libary/utils"
  16. "dashoo.cn/opms_libary/micro_srv"
  17. "dashoo.cn/opms_libary/myerrors"
  18. "dashoo.cn/opms_libary/plugin/dingtalk/message"
  19. "dashoo.cn/opms_libary/plugin/dingtalk/workflow"
  20. "dashoo.cn/opms_libary/request"
  21. "github.com/gogf/gf/database/gdb"
  22. "github.com/gogf/gf/os/gtime"
  23. "github.com/gogf/gf/util/gvalid"
  24. )
  25. type CtrContractInvoiceService struct {
  26. Dao *dao.CtrContractInvoiceDao
  27. ContractDao *dao.CtrContractDao
  28. CustomerDao *customerDao.CustCustomerDao
  29. UserDao *sysDao.SysUserDao
  30. ctrSrv *CtrContractService
  31. Tenant string
  32. userInfo request.UserInfo
  33. }
  34. func NewCtrContractInvoiceService(ctx context.Context) (*CtrContractInvoiceService, error) {
  35. tenant, err := micro_srv.GetTenant(ctx)
  36. if err != nil {
  37. return nil, myerrors.TipsError(fmt.Sprintf("获取租户码异常:%s", err.Error())) //fmt.Errorf("获取租户码异常:%s", err.Error())
  38. }
  39. // 获取用户信息
  40. userInfo, err := micro_srv.GetUserInfo(ctx)
  41. if err != nil {
  42. return nil, myerrors.TipsError(fmt.Sprintf("获取用户信息异常:%s", err.Error())) //fmt.Errorf("获取用户信息异常:%s", err.Error())
  43. }
  44. ctrSrv, err := NewCtrContractService(ctx)
  45. if err != nil {
  46. return nil, err
  47. }
  48. return &CtrContractInvoiceService{
  49. Dao: dao.NewCtrContractInvoiceDao(tenant),
  50. ContractDao: dao.NewCtrContractDao(tenant),
  51. CustomerDao: customerDao.NewCustCustomerDao(tenant),
  52. UserDao: sysDao.NewSysUserDao(tenant),
  53. ctrSrv: ctrSrv,
  54. Tenant: tenant,
  55. userInfo: userInfo,
  56. }, nil
  57. }
  58. func (s CtrContractInvoiceService) List(ctx context.Context, req *model.CtrContractInvoiceListReq) (int, []*model.CtrContractInvoice, error) {
  59. dao := &s.Dao.CtrContractInvoiceDao
  60. if req.SearchText != "" {
  61. likestr := fmt.Sprintf("%%%s%%", req.SearchText)
  62. dao = dao.Where("(cust_name LIKE ? || contract_code LIKE ?)", likestr, likestr)
  63. }
  64. if req.CustId != 0 {
  65. dao = dao.Where("cust_id = ?", req.CustId)
  66. }
  67. if req.CustName != "" {
  68. likestr := fmt.Sprintf("%%%s%%", req.CustName)
  69. dao = dao.Where("cust_name like ?", likestr)
  70. }
  71. if req.ContractId != 0 {
  72. dao = dao.Where("contract_id = ?", req.ContractId)
  73. }
  74. if req.ContractCode != "" {
  75. likestr := fmt.Sprintf("%%%s%%", req.ContractCode)
  76. dao = dao.Where("contract_code like ?", likestr)
  77. }
  78. if req.InvoiceType != "" {
  79. dao = dao.Where("invoice_type = ?", req.InvoiceType)
  80. }
  81. if req.ApproStatus != "" {
  82. dao = dao.Where("appro_status = ?", req.ApproStatus)
  83. }
  84. if req.InvoiceCode != "" {
  85. dao = dao.Where("invoice_code = ?", req.InvoiceCode)
  86. }
  87. if req.CourierCode != "" {
  88. dao = dao.Where("courier_code = ?", req.CourierCode)
  89. }
  90. if req.BeginTime != "" {
  91. dao = dao.Where("created_time > ?", req.BeginTime)
  92. }
  93. if req.EndTime != "" {
  94. dao = dao.Where("created_time < ?", req.EndTime)
  95. }
  96. total, err := dao.Count()
  97. if err != nil {
  98. return 0, nil, err
  99. }
  100. if req.PageNum != 0 {
  101. dao = dao.Page(req.GetPage())
  102. }
  103. orderby := "created_time desc"
  104. if req.OrderBy != "" {
  105. orderby = req.OrderBy
  106. }
  107. dao = dao.Order(orderby)
  108. ents := []*model.CtrContractInvoice{}
  109. err = dao.Structs(&ents)
  110. if err != nil && err != sql.ErrNoRows {
  111. return 0, nil, err
  112. }
  113. return total, ents, err
  114. }
  115. func (s CtrContractInvoiceService) Add(ctx context.Context, req *model.CtrContractInvoiceAddReq) (int, error) {
  116. validErr := gvalid.CheckStruct(ctx, req, nil)
  117. if validErr != nil {
  118. return 0, myerrors.TipsError(validErr.Current().Error())
  119. }
  120. c, err := s.ContractDao.Where("id = ?", req.ContractId).One()
  121. if err != nil {
  122. return 0, err
  123. }
  124. if c == nil {
  125. return 0, myerrors.TipsError(fmt.Sprintf("合同:%d 不存在", req.ContractId))
  126. }
  127. if req.InvoiceCode != "" {
  128. ent, err := s.Dao.Where("invoice_code = ?", req.InvoiceCode).One()
  129. if err != nil {
  130. return 0, err
  131. }
  132. if ent != nil {
  133. return 0, myerrors.TipsError(fmt.Sprintf("发票号码:%s 已存在", req.InvoiceCode))
  134. }
  135. }
  136. if req.CourierCode != "" {
  137. ent, err := s.Dao.Where("courier_code = ?", req.CourierCode).One()
  138. if err != nil {
  139. return 0, err
  140. }
  141. if ent != nil {
  142. return 0, myerrors.TipsError(fmt.Sprintf("快递单号:%s 已存在", req.CourierCode))
  143. }
  144. }
  145. ent := model.CtrContractInvoice{
  146. CustId: c.CustId,
  147. CustName: c.CustName,
  148. ContractId: req.ContractId,
  149. ContractCode: c.ContractCode,
  150. ContractAmount: c.ContractAmount,
  151. InvoiceAmount: req.InvoiceAmount,
  152. InvoiceDate: req.InvoiceDate,
  153. InvoiceType: req.InvoiceType,
  154. ApproStatus: "10",
  155. InvoiceCode: req.InvoiceCode,
  156. ActualInvoiceDate: req.ActualInvoiceDate,
  157. CourierCode: req.CourierCode,
  158. Remark: req.Remark,
  159. CreatedBy: int(s.userInfo.Id),
  160. CreatedName: s.userInfo.NickName,
  161. CreatedTime: gtime.Now(),
  162. UpdatedBy: int(s.userInfo.Id),
  163. UpdatedName: s.userInfo.NickName,
  164. UpdatedTime: gtime.Now(),
  165. }
  166. var id int
  167. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  168. invoiceId, err := tx.InsertAndGetId("ctr_contract_invoice", ent)
  169. if err != nil {
  170. return err
  171. }
  172. err = s.ctrSrv.AddDynamicsByCurrentUser(tx, req.ContractId, "创建发票", map[string]interface{}{
  173. "id": invoiceId,
  174. "invoiceAmount": req.InvoiceAmount,
  175. "invoiceDate": req.InvoiceDate,
  176. "invoiceType": req.InvoiceType,
  177. "invoiceCode": req.InvoiceCode,
  178. "actualInvoiceDate": req.ActualInvoiceDate,
  179. "courierCode": req.CourierCode,
  180. })
  181. if err != nil {
  182. return err
  183. }
  184. id = int(invoiceId)
  185. return nil
  186. })
  187. return id, txerr
  188. }
  189. func (s CtrContractInvoiceService) Update(ctx context.Context, req *model.CtrContractInvoiceUpdateReq) error {
  190. validErr := gvalid.CheckStruct(ctx, req, nil)
  191. if validErr != nil {
  192. return myerrors.TipsError(validErr.Current().Error())
  193. }
  194. ent, err := s.Dao.Where("id = ?", req.Id).One()
  195. if err != nil {
  196. return err
  197. }
  198. if ent == nil {
  199. return myerrors.TipsError(fmt.Sprintf("发票不存在: %d", req.Id))
  200. }
  201. if req.InvoiceCode != "" {
  202. exist, err := s.Dao.Where("invoice_code = ?", req.InvoiceCode).One()
  203. if err != nil {
  204. return err
  205. }
  206. if exist != nil && exist.Id != req.Id {
  207. return myerrors.TipsError(fmt.Sprintf("发票号码: %s 已存在", req.InvoiceCode))
  208. }
  209. }
  210. if req.CourierCode != "" {
  211. exist, err := s.Dao.Where("courier_code = ?", req.CourierCode).One()
  212. if err != nil {
  213. return err
  214. }
  215. if exist != nil && exist.Id != req.Id {
  216. return myerrors.TipsError(fmt.Sprintf("快递单号: %s 已存在", req.CourierCode))
  217. }
  218. }
  219. toupdate := map[string]interface{}{}
  220. // if req.CustId != 0 {
  221. // toupdate["cust_id"] = req.CustId
  222. // }
  223. // if req.CustName != 0 {
  224. // toupdate["cust_name"] = req.CustName
  225. // }
  226. // if req.ContractId != 0 {
  227. // toupdate["contract_id"] = req.ContractId
  228. // }
  229. // if req.ContractCode != 0 {
  230. // toupdate["contract_code"] = req.ContractCode
  231. // }
  232. // if req.ContractAmount != 0 {
  233. // toupdate["contract_amount"] = req.ContractAmount
  234. // }
  235. if req.InvoiceAmount != nil {
  236. toupdate["invoice_amount"] = *req.InvoiceAmount
  237. }
  238. if req.InvoiceDate != nil {
  239. toupdate["invoice_date"] = req.InvoiceDate
  240. }
  241. if req.InvoiceType != "" {
  242. toupdate["invoice_type"] = req.InvoiceType
  243. }
  244. if req.ApproStatus != "" {
  245. toupdate["appro_status"] = req.ApproStatus
  246. }
  247. if req.InvoiceCode != "" {
  248. toupdate["invoice_code"] = req.InvoiceCode
  249. }
  250. if req.ActualInvoiceDate != nil {
  251. toupdate["actual_invoice_date"] = req.ActualInvoiceDate
  252. }
  253. if req.CourierCode != "" {
  254. toupdate["courier_code"] = req.CourierCode
  255. }
  256. if req.Remark != nil {
  257. toupdate["remark"] = *req.Remark
  258. }
  259. if len(toupdate) != 0 {
  260. toupdate["updated_by"] = int(s.userInfo.Id)
  261. toupdate["updated_name"] = s.userInfo.NickName
  262. toupdate["updated_time"] = gtime.Now()
  263. txerr := s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  264. _, err = tx.Update("ctr_contract_invoice", toupdate, "id= ?", req.Id)
  265. if err != nil {
  266. return err
  267. }
  268. if req.InvoiceAmount != nil || req.ApproStatus != "" {
  269. err = s.ctrSrv.UpdateInvoiceAmount(tx, ent.ContractId)
  270. if err != nil {
  271. return err
  272. }
  273. }
  274. return nil
  275. })
  276. if txerr != nil {
  277. return txerr
  278. }
  279. }
  280. return nil
  281. }
  282. var InvoiceApplyProcessCode = "PROC-D2F97FDE-6277-404D-89B5-91123FEBF1B8" // 申请发票
  283. func (s CtrContractInvoiceService) InvoiceApply(ctx context.Context, req *model.CtrContractInvoiceInvoiceApplyReq) error {
  284. invoice, err := s.Dao.Where("id = ?", req.Id).One()
  285. if err != nil {
  286. return err
  287. }
  288. if invoice == nil {
  289. return myerrors.TipsError("发票不存在")
  290. }
  291. if invoice.ApproStatus != "10" {
  292. return myerrors.TipsError("发票当前状态不可提交审核")
  293. }
  294. contract, err := s.ContractDao.Where("id = ?", invoice.ContractId).One()
  295. if err != nil {
  296. return err
  297. }
  298. if contract == nil {
  299. return myerrors.TipsError("发票所属合同不存在")
  300. }
  301. cust, err := s.CustomerDao.Where("id = ?", invoice.CustId).One()
  302. if err != nil {
  303. return err
  304. }
  305. if cust == nil {
  306. return myerrors.TipsError("发票所属合同客户不存在")
  307. }
  308. allReceive := "未回全款"
  309. if req.AllReceive {
  310. allReceive = "已回全款"
  311. }
  312. product, err := s.ctrSrv.CtrProductDao.Where("contract_id = ?", contract.Id).All()
  313. if err != nil {
  314. return err
  315. }
  316. // productForm := []*workflow.StartProcessInstanceRequestFormComponentValuesDetails{}
  317. // for _, p := range product {
  318. // productForm = append(productForm, &workflow.StartProcessInstanceRequestFormComponentValuesDetails{
  319. // Details: []*workflow.StartProcessInstanceRequestFormComponentValuesDetailsDetails{
  320. // {
  321. // Id: utils.String("TextField_R967EJ9XVWW0"),
  322. // Name: utils.String("产品名称"),
  323. // Value: utils.String(p.ProdName),
  324. // },
  325. // {
  326. // Id: utils.String("TextField_18AAHJYNVUBG0"),
  327. // Name: utils.String("产品型号"),
  328. // Value: utils.String(p.ProdCode),
  329. // },
  330. // {
  331. // Id: utils.String("NumberField_1RFPF86Y699C0"),
  332. // Name: utils.String("产品数量"),
  333. // Value: utils.String(strconv.Itoa(p.ProdNum)),
  334. // },
  335. // },
  336. // })
  337. // }
  338. productForm := []interface{}{}
  339. for _, p := range product {
  340. productForm = append(productForm, []*workflow.StartProcessInstanceRequestFormComponentValuesDetailsDetails{
  341. {
  342. Id: utils.String("TextField_R967EJ9XVWW0"),
  343. Name: utils.String("产品名称"),
  344. Value: utils.String(p.ProdName),
  345. },
  346. {
  347. Id: utils.String("TextField_18AAHJYNVUBG0"),
  348. Name: utils.String("产品型号"),
  349. Value: utils.String(p.ProdCode),
  350. },
  351. {
  352. Id: utils.String("NumberField_1RFPF86Y699C0"),
  353. Name: utils.String("产品数量"),
  354. Value: utils.String(strconv.Itoa(p.ProdNum)),
  355. },
  356. })
  357. }
  358. productFormByte, err := json.Marshal(productForm)
  359. if err != nil {
  360. return err
  361. }
  362. workflowSrv, err := workflowService.NewFlowService(ctx)
  363. if err != nil {
  364. return err
  365. }
  366. bizCode := strings.Join([]string{
  367. strconv.Itoa(invoice.Id),
  368. strconv.Itoa(s.userInfo.Id),
  369. }, ":")
  370. _, err = workflowSrv.StartProcessInstance(bizCode, "31", &workflow.StartProcessInstanceRequest{
  371. ProcessCode: &InvoiceApplyProcessCode,
  372. FormComponentValues: []*workflow.StartProcessInstanceRequestFormComponentValues{
  373. {
  374. Id: utils.String("DDSelectField_FSWX8IG61HC0"),
  375. Name: utils.String("单选框"),
  376. Value: utils.String(allReceive),
  377. },
  378. {
  379. Id: utils.String("TextField_LUZ9EQ3IJB40"),
  380. Name: utils.String("合同编号"),
  381. Value: utils.String(contract.ContractCode),
  382. },
  383. {
  384. Id: utils.String("TextField_A0V5RQK1BC80"),
  385. Name: utils.String("客户编号"),
  386. Value: utils.String(cust.CustCode),
  387. },
  388. {
  389. Id: utils.String("TextField_1E2J1LS6H9HC0"),
  390. Name: utils.String("客户名称"),
  391. Value: utils.String(cust.CustName),
  392. },
  393. {
  394. Id: utils.String("TableField_1IGTG9NX08U80"),
  395. Name: utils.String("表格"),
  396. // Details: productForm,
  397. Value: utils.String(string(productFormByte)),
  398. },
  399. {
  400. Id: utils.String("MoneyField_1D8481FCI5FK0"),
  401. Name: utils.String("合同金额(元)"),
  402. Value: utils.String(strconv.FormatFloat(contract.ContractAmount, 'f', 2, 64)),
  403. },
  404. {
  405. Id: utils.String("MoneyField_BQ2E2JGXHGO0"),
  406. Name: utils.String("回款金额(元)"),
  407. Value: utils.String(strconv.FormatFloat(req.ReceiveAmount, 'f', 2, 64)),
  408. },
  409. {
  410. Id: utils.String("MoneyField_V47BSZICHIO0"),
  411. Name: utils.String("开票金额(元)"),
  412. Value: utils.String(strconv.FormatFloat(invoice.InvoiceAmount, 'f', 2, 64)),
  413. },
  414. },
  415. })
  416. if err != nil {
  417. return err
  418. }
  419. _, err = s.Dao.Where("id = ?", invoice.Id).Data(map[string]interface{}{
  420. "appro_status": 20,
  421. }).Update()
  422. return err
  423. }
  424. func InvoiceApplyApproval(ctx context.Context, flow *workflowModel.PlatWorkflow, msg *message.MixMessage) error {
  425. tenant, err := micro_srv.GetTenant(ctx)
  426. if err != nil {
  427. return fmt.Errorf("获取租户码异常:%s", err.Error())
  428. }
  429. invoiceDao := dao.NewCtrContractInvoiceDao(tenant)
  430. userDao := sysDao.NewSysUserDao(tenant)
  431. bizCode := strings.Split(flow.BizCode, ":")
  432. if len(bizCode) != 2 {
  433. return fmt.Errorf("申请发票审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  434. }
  435. invoiceId, err := strconv.Atoi(bizCode[0])
  436. if err != nil {
  437. return fmt.Errorf("申请发票审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  438. }
  439. userId, err := strconv.Atoi(bizCode[1])
  440. if err != nil {
  441. return fmt.Errorf("申请发票审批 bizCode 不合法:%s Id: %d", flow.BizCode, flow.Id)
  442. }
  443. user, err := userDao.Where("id = ?", userId).One()
  444. if err != nil {
  445. return err
  446. }
  447. if user == nil {
  448. return fmt.Errorf("用户不存在:%s Id: %d", flow.BizCode, flow.Id)
  449. }
  450. invoice, err := invoiceDao.Where("id = ?", invoiceId).One()
  451. if err != nil {
  452. return err
  453. }
  454. if invoice == nil {
  455. return fmt.Errorf("发票不存在:%s Id: %d", flow.BizCode, flow.Id)
  456. }
  457. if msg.ProcessType != "finish" && msg.ProcessType != "terminate" {
  458. return fmt.Errorf("无法识别的 ProcessType :%s", msg.ProcessType)
  459. }
  460. if msg.Result != "agree" && msg.Result != "refuse" && msg.Result != "" {
  461. return fmt.Errorf("无法识别的 Result :%s", msg.Result)
  462. }
  463. if msg.ProcessType == "terminate" {
  464. _, err = invoiceDao.Where("id = ?", invoiceId).Data(map[string]interface{}{
  465. "appro_status": "50",
  466. }).Update()
  467. return err
  468. }
  469. pass := msg.Result == "agree"
  470. if !pass {
  471. _, err = invoiceDao.Where("id = ?", invoiceId).Data(map[string]interface{}{
  472. "appro_status": "40",
  473. }).Update()
  474. return err
  475. }
  476. _, err = invoiceDao.Where("id = ?", invoiceId).Data(map[string]interface{}{
  477. "appro_status": "30",
  478. }).Update()
  479. return err
  480. }
  481. func (s CtrContractInvoiceService) Delete(ctx context.Context, id []int) error {
  482. if len(id) == 0 {
  483. return nil
  484. }
  485. return s.Dao.DB.Transaction(ctx, func(ctx context.Context, tx *gdb.TX) error {
  486. contractId := map[int]bool{}
  487. for _, i := range id {
  488. ent := model.CtrContractInvoice{}
  489. err := tx.GetStruct(&ent, "select * from ctr_contract_invoice where id = ?", i)
  490. if err == sql.ErrNoRows {
  491. continue
  492. }
  493. if err != nil {
  494. return err
  495. }
  496. if ent.ApproStatus == "30" {
  497. contractId[ent.ContractId] = true
  498. }
  499. }
  500. _, err := tx.Delete("ctr_contract_invoice", "id in (?)", id)
  501. if err != nil {
  502. return err
  503. }
  504. for cid := range contractId {
  505. err = s.ctrSrv.UpdateInvoiceAmount(tx, cid)
  506. if err != nil {
  507. return err
  508. }
  509. }
  510. return nil
  511. })
  512. }