ctr_contract_invoice.go 15 KB

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