ctr_contract_invoice.go 15 KB

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