automaticPayment.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. package timedTask
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gogf/gf/v2/database/gdb"
  7. "github.com/gogf/gf/v2/errors/gerror"
  8. "github.com/gogf/gf/v2/frame/g"
  9. "github.com/gogf/gf/v2/util/gconv"
  10. "jyOrderManager/internal/consts"
  11. "jyOrderManager/internal/jyutil"
  12. "jyOrderManager/internal/logic/order"
  13. "jyOrderManager/internal/logic/product"
  14. "log"
  15. "math"
  16. "net/rpc"
  17. "regexp"
  18. "strings"
  19. "time"
  20. )
  21. var (
  22. reg = regexp.MustCompile("[\\s()]+")
  23. )
  24. type FilterStr struct {
  25. PaybackNum int
  26. paybackListArr []map[string]interface{}
  27. }
  28. func AutomaticPaymentCollection() {
  29. autoReturnTaskTime := g.Cfg().MustGet(context.Background(), "autoReturnTaskTime", 3).Int()
  30. for {
  31. AutomaticPayment()
  32. time.Sleep(gconv.Duration(autoReturnTaskTime) * time.Minute)
  33. }
  34. }
  35. func AutomaticPayment() {
  36. var ctx = context.Background()
  37. log.Println("自动回款匹配。。。开始")
  38. query := fmt.Sprintf(`select * from transaction where ISRELATION = 0 and OTHNAM is not null and OTHNAM != "" and BNKTIM > '%s' order by id`, time.Now().AddDate(0, -g.Cfg().MustGet(ctx, "automaticPaymentTime", 3).Int(), 0).Format("2006-01-02 15:04:05"))
  39. data, _ := g.DB("cbs").Query(ctx, query)
  40. if !data.IsEmpty() {
  41. returnOrderMap := make(map[string]int)
  42. orderData, _ := g.DB().Query(ctx, `SELECT
  43. a.*,
  44. a.pay_money+(select IFNULL(sum(payMoney),0) as return_money from moneyCorrection where orderCode=a.order_code)as new_pay_money,
  45. (select IFNULL(sum(c.refund_money),0) as refund_money from refund_record c where c.order_code=a.order_code) as refund_money,
  46. (SELECT SUM(r.return_money) as returned_money FROM return_money_record r WHERE r.order_code=a.order_code AND state=1) as returned_money,
  47. a.commission+(select IFNULL(sum(commission),0) as return_commission from moneyCorrection where orderCode=a.order_code) as new_commission,
  48. b.paybackNum,
  49. b.paybackList ,
  50. c.money as deposit_money,
  51. FROM
  52. dataexport_order a
  53. LEFT JOIN (
  54. SELECT
  55. order_code,
  56. JSON_EXTRACT( plantList, "$.paybackNum" ) AS paybackNum,
  57. JSON_EXTRACT( plantList, "$.paybackList" ) AS paybackList
  58. FROM
  59. return_money_plant
  60. WHERE
  61. state != -1 and JSON_VALID( plantList )
  62. ) b ON a.order_code = b.order_code
  63. LEFT JOIN (
  64. SELECT
  65. de.order_code,
  66. de.money,
  67. odp.order_code as payment_order_code
  68. FROM
  69. order_deposit de
  70. LEFT JOIN order_deposit_payment odp ON odp.is_del=0 and de.order_code = odp.order_code
  71. WHERE odp.order_code IS NULL
  72. ) c ON a.order_code = c.order_code
  73. WHERE
  74. ( a.return_status = 0 OR a.return_status = 2 )
  75. AND a.audit_status = 3
  76. AND ( a.order_status = 1 OR a.order_status = 0 )`)
  77. returnOrderData, _ := g.DB().Query(ctx, `SELECT order_code, COUNT(*) as total_count FROM return_money_record WHERE state =1 GROUP BY order_code `)
  78. if !returnOrderData.IsEmpty() {
  79. for _, i2 := range returnOrderData.List() {
  80. returnOrderMap[gconv.String(i2["order_code"])] = gconv.Int(i2["total_count"])
  81. }
  82. }
  83. filterMap := make(map[string]FilterStr)
  84. if !orderData.IsEmpty() { //优化 获取filter字段中的数据
  85. for _, o := range orderData.List() {
  86. var paybackList string
  87. if pList := gconv.String(o["paybackList"]); pList != "" && pList != `""` && strings.Contains(pList, "合计") {
  88. paybackList = strings.ReplaceAll(pList[1:len(pList)-1], "\\", "")
  89. }
  90. var paybackListArr []map[string]interface{}
  91. if paybackList != "" {
  92. _ = json.Unmarshal([]byte(paybackList), &paybackListArr)
  93. }
  94. paybackNum := strings.ReplaceAll(gconv.String(o["paybackNum"]), `"`, "")
  95. filterMap[gconv.String(o["order_code"])] = FilterStr{
  96. gconv.Int(paybackNum),
  97. paybackListArr,
  98. }
  99. }
  100. }
  101. for _, v := range data.List() {
  102. returnMoney := int(math.Floor(float64(float64(gconv.Float64(v["TRSBAL"]))*100) + 0.5))
  103. companyName := gconv.String(v["OTHNAM"])
  104. remark := gconv.String(v["TXTDSM"])
  105. remarks := gconv.String(v["NUSAGE"])
  106. id := gconv.Int(v["id"])
  107. returnTime := gconv.String(v["BNKTIM"])
  108. BNKFLW := gconv.String(v["BNKFLW"])
  109. BNKNAM := gconv.String(v["BNKNAM"])
  110. if !orderData.IsEmpty() {
  111. for _, o := range orderData.List() {
  112. //filterMap := make(map[string]interface{})
  113. //_ = json.Unmarshal([]byte(gconv.String(o["filter"])), &filterMap)
  114. money := gconv.Int(o["new_pay_money"]) - gconv.Int(o["new_commission"]) - gconv.Int(o["procedures_money"])
  115. paymentUser := gconv.String(o["payment_user"])
  116. if paymentUser == "" {
  117. paymentUser = gconv.String(o["company_name"])
  118. }
  119. orderCode := gconv.String(o["order_code"])
  120. if status := PaymentPlanMatching(money, gconv.Int(o["deposit_money"]), returnMoney, paymentUser, companyName, remark, remarks, orderCode, filterMap[orderCode].PaybackNum, filterMap[orderCode].paybackListArr, returnOrderMap); status > 0 {
  121. if status == 1 || status == 2 { //定金 但定金不是合同金额
  122. // 插入定金表
  123. _, err := g.DB().Insert(ctx, "order_deposit_payment", map[string]interface{}{
  124. "order_code": orderCode,
  125. "pay_time": returnTime,
  126. "pay_way": 3,
  127. "operate_time": time.Now().Format("2006-01-02 15:04:05"),
  128. "flow_money": returnMoney,
  129. "pay_money": returnMoney,
  130. "remark": "自动关联保证金流水",
  131. "transaction_id": id,
  132. "bank_name": BNKNAM,
  133. "bank_flow": BNKFLW,
  134. "operate_type": 2,
  135. "pay_account_name": paymentUser,
  136. })
  137. if err != nil {
  138. log.Println("定金信息插入失败", id, orderCode, err)
  139. }
  140. g.DB("cbs").Update(ctx, "transaction", map[string]interface{}{"ISRELATION": 2}, map[string]interface{}{"id": id})
  141. if status == 1 {
  142. continue
  143. }
  144. }
  145. isExists, err := g.Redis("qmx_filter").Exists(ctx, "qmx_auto_return_"+fmt.Sprint(id))
  146. if isExists == 0 || err != nil {
  147. log.Println("自动回款匹配成功", id, orderCode)
  148. updateData := make(map[string]interface{})
  149. if status > 2 {
  150. updateData["order_status"] = 1
  151. returned_money := gconv.Int(o["returned_money"])
  152. if returned_money+returnMoney > money+gconv.Int(o["refund_money"]) {
  153. log.Printf("回款金额异常,订单:%s回款金额大于实际合同金额\n", orderCode)
  154. continue
  155. }
  156. updateData["return_status"] = 2
  157. //isFirstReturn := config.JysqlDB.Count("return_money_record", map[string]interface{}{"state": 1, "order_code": orderCode}) == 0
  158. returnReq, _ := g.DB().Insert(ctx, "return_money_record", map[string]interface{}{
  159. "order_code": orderCode,
  160. "return_time": returnTime,
  161. "return_money": returnMoney,
  162. "return_type": 3,
  163. "return_invoice_status": 0,
  164. "operate_time": time.Now().Format("2006-01-02 15:04:05"),
  165. "flow_money": returnMoney,
  166. "bank_name": BNKNAM,
  167. "bank_flow": BNKFLW,
  168. "operate_type": 2,
  169. "state": 1,
  170. "pay_account_name": paymentUser,
  171. })
  172. returnId, _ := returnReq.LastInsertId()
  173. if returnId <= 0 {
  174. log.Println("自动回款新增回款信息失败")
  175. continue
  176. }
  177. //计算已回款金额
  178. if returned_money == 0 {
  179. if err = order.CommonChange(ctx, orderCode, returnTime, order.ReturnMoney); err != nil {
  180. log.Printf("%s 回款销售业绩生效异常 %v", orderCode, err)
  181. }
  182. }
  183. if returned_money+returnMoney == money+gconv.Int(o["refund_money"]) {
  184. g.Redis("qmx_filter").SetEX(ctx, "qmx_auto_return_"+fmt.Sprint(id), 1, 3600)
  185. updateData["return_status"] = 1
  186. }
  187. g.DB().Update(ctx, "dataexport_order", updateData, map[string]interface{}{"order_code": orderCode})
  188. g.DB("cbs").Update(ctx, "transaction", map[string]interface{}{"ISRELATION": 1, "return_id": fmt.Sprint(returnId)}, map[string]interface{}{"id": id})
  189. log.Println("自动回款创建回款记录成功", id, orderCode)
  190. }
  191. log.Println("自动回款开通权益", orderCode, gconv.Int(o["return_status"]), updateData["return_status"], status, returnMoney, money)
  192. if (gconv.Int(o["return_status"]) != 1 && updateData["return_status"] == 1) || status == 2 {
  193. productDetail, err := g.DB().Ctx(ctx).Query(ctx, fmt.Sprintf(`SELECT * FROM jy_order_detail WHERE order_code ='%s' and returned_open =1 and is_service_open = 0 and status =1`, orderCode))
  194. if err != nil || productDetail.IsEmpty() {
  195. continue
  196. }
  197. //全额回款开通权益
  198. if !consts.PhoneRegex.MatchString(gconv.String(o["user_phone"])) {
  199. continue
  200. }
  201. uData, entId, userPositionId, err := jyutil.GetCreateUserData(gconv.String(o["user_phone"]), gconv.String(o["company_name"]), gconv.Int(o["buy_subject"]) == 2)
  202. if err != nil {
  203. continue
  204. }
  205. if err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
  206. // 产品服务开通
  207. for _, m := range productDetail.List() {
  208. if !jyutil.IsServiceOpen(m) {
  209. continue
  210. }
  211. //参数注入
  212. m["userMap"] = map[string]interface{}{
  213. "userData": uData, "entId": entId, "userPositionId": userPositionId,
  214. }
  215. m["phone"] = o["user_phone"]
  216. m["order_code"] = orderCode
  217. m["amount"] = m["final_price"]
  218. m["reqCompanyName"] = o["company_name"]
  219. m["reqSubject"] = o["buy_subject"]
  220. productCode := gconv.String(m["product_code"])
  221. m["linked_orderId"] = m["linked_detail_id"]
  222. m["linkedOrderId"] = m["linked_detail_id"]
  223. log.Println("自动开启服务参数", m)
  224. pFunc, err := product.JyProFunc.GetProductInitFuncByCode(productCode)
  225. if err != nil {
  226. continue
  227. }
  228. pObj, err := pFunc(m)
  229. if err != nil {
  230. gerror.Wrap(err, fmt.Sprintf("获取%s商品异常", productCode))
  231. continue
  232. }
  233. if err = pObj.OpenService(ctx, time.Now()); err != nil {
  234. continue
  235. }
  236. }
  237. if gconv.Int(o["buy_subject"]) == 2 {
  238. uData["userId"] = userPositionId
  239. }
  240. if orderUserId := gconv.String(o["user_id"]); orderUserId == "" || orderUserId != gconv.String(uData["userId"]) || (gconv.Int(o["buy_subject"]) == 2 && gconv.Int64(o["ent_id"]) != entId) {
  241. log.Printf("同步更新订单用户身份:orderUserId:%s,userId:%v,entId:%d\n", orderUserId, uData["userId"], entId)
  242. upData := g.Map{
  243. "user_id": uData["userId"],
  244. }
  245. if entId > 0 { //企业服务
  246. upData["ent_id"] = entId
  247. if personPhone := gconv.String(o["personPhone"]); personPhone != "" {
  248. jyutil.EndAddUser(ctx, entId, gconv.String(o["user_phone"]), personPhone, gconv.String(o["personName"]))
  249. }
  250. }
  251. //更新订单
  252. _, err = g.DB().Update(ctx, consts.OrderListTableName, upData, "order_code=?", orderCode)
  253. if err != nil {
  254. return err
  255. }
  256. }
  257. return nil
  258. }); err != nil {
  259. log.Println(err)
  260. continue
  261. }
  262. }
  263. } else {
  264. log.Println("自动回款重复匹配过滤", id, orderCode)
  265. }
  266. //回款关闭相应的支付码支付
  267. go CancelOnlinePay(ctx, orderCode)
  268. }
  269. }
  270. }
  271. }
  272. } else {
  273. log.Println("回款信息查询为空")
  274. }
  275. log.Println("自动回款匹配。。。结束")
  276. }
  277. // PaymentPlanMatching 回款计划匹配
  278. func PaymentPlanMatching(money, orderDeposit, returnMoney int, paymentUser, companyName, remark, remarks, orderCode string, paybackNum int, paybackListArr []map[string]interface{}, returnOrderMap map[string]int) int {
  279. pUser := reg.ReplaceAllString(paymentUser, "")
  280. //定金 已支付定金为0 todo 满足订单 定金不是合同金额
  281. if orderDeposit > 0 && returnMoney == orderDeposit && pUser == companyName {
  282. if money == orderDeposit { //定金是合同全款
  283. return 2
  284. }
  285. return 1
  286. }
  287. if money == returnMoney && (pUser == companyName || remark == orderCode || remarks == orderCode) {
  288. return 3
  289. }
  290. if paybackNum > 1 { //仅订单回款计划有多期时,才匹配回款计划,回款计划如只有1期,则无需匹配
  291. isFirstReturn := returnOrderMap[orderCode]
  292. if isFirstReturn < paybackNum && len(paybackListArr) > 0 && len(paybackListArr) >= isFirstReturn {
  293. //② 如该订单已有X笔回款,则匹配第“X+1”期的回款计划,其他期的回款计划不进行匹配,例如:该笔订单无回款,则匹配第1期的回款计划;该笔订单有1笔回款,则匹配第2期的回款计划。
  294. if gconv.String(paybackListArr[isFirstReturn]["code"]) != "合计" && returnMoney == gconv.Int(paybackListArr[isFirstReturn]["money"])*100 && (pUser == companyName) {
  295. return 4
  296. }
  297. }
  298. //}
  299. }
  300. return 0
  301. }
  302. func CancelOnlinePay(ctx context.Context, orderCode string) {
  303. if total, _ := g.DB().Ctx(ctx).Query(ctx, "SELECT count(*) from return_money_online WHERE status=0 and order_code=? and expire_time >?", orderCode, time.Now().Format("2006-01-02 15:04:05")); !total.IsEmpty() {
  304. r, err := rpc.DialHTTP("tcp", g.Cfg().MustGet(context.Background(), "jyPayRpc").String())
  305. defer r.Close()
  306. res := ""
  307. err = r.Call("JyPayRpc.CloseReturnOrder", orderCode, &res)
  308. if err != nil {
  309. log.Printf("%s关闭支付宝微信支付码失败 %s", orderCode, err)
  310. }
  311. }
  312. }