detail.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. package order
  2. import (
  3. "app.yhyue.com/moapp/jybase/common"
  4. "app.yhyue.com/moapp/jybase/encrypt"
  5. "context"
  6. "fmt"
  7. "github.com/gogf/gf/v2/frame/g"
  8. "github.com/gogf/gf/v2/util/gconv"
  9. "jyOrderManager/internal/jyutil"
  10. "jyOrderManager/internal/logic/user"
  11. "jyOrderManager/internal/model"
  12. "log"
  13. "strings"
  14. )
  15. func init() {
  16. }
  17. func Detail(ctx context.Context, param model.OrderDetailParams) (map[string]interface{}, error) {
  18. result := make(map[string]interface{})
  19. //订单 暂无备注字段
  20. orderData, err := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT d.*,d.pay_money+(select IFNULL(sum(payMoney),0) as return_money from moneyCorrection where orderCode='%s') as new_pay_money,d.commission+(select IFNULL(sum(commission),0) as return_commission from moneyCorrection where orderCode='%s') as new_commission,(select a.item_name AS order_parent_name from dict_item a where a.item_code=d.order_channel ) AS order_channel_new FROM dataexport_order d WHERE order_code ='%s' `, param.OrderCode, param.OrderCode, param.OrderCode))
  21. if err != nil || orderData.IsEmpty() {
  22. return nil, err
  23. }
  24. var (
  25. userIdentity []int
  26. )
  27. for _, userid := range jyutil.SupAdmin { //超级管理员
  28. if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
  29. userIdentity = append(userIdentity, 1)
  30. }
  31. }
  32. for _, userid := range jyutil.PinTube { //销管
  33. if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
  34. userIdentity = append(userIdentity, 2)
  35. }
  36. }
  37. for _, userid := range jyutil.CSId { //销管
  38. if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
  39. userIdentity = append(userIdentity, 3)
  40. }
  41. }
  42. for _, userid := range jyutil.Administration { //销管
  43. if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
  44. userIdentity = append(userIdentity, 4)
  45. }
  46. }
  47. for _, userid := range jyutil.Finance { //销管
  48. if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
  49. userIdentity = append(userIdentity, 5)
  50. }
  51. }
  52. result["userIdentity"] = userIdentity
  53. orderMap := orderData.Map()
  54. orderMap["pay_money"] = gconv.Int64(orderMap["new_pay_money"])
  55. orderMap["commission"] = gconv.Int64(orderMap["new_commission"])
  56. payWay := gconv.String(orderData.Map()["pay_way"])
  57. var table string
  58. switch {
  59. case strings.Contains(payWay, "wx"):
  60. orderMap["pay_way"] = "微信"
  61. table = "weixin_pay"
  62. case strings.Contains(payWay, "ali"):
  63. orderMap["pay_way"] = "支付宝"
  64. table = "ali_pay"
  65. case strings.Contains(payWay, "trial"):
  66. orderMap["pay_way"] = "其他"
  67. case strings.Contains(payWay, "transferAccounts"):
  68. orderMap["pay_way"] = "对公转账"
  69. case strings.Contains(payWay, "测试使用"):
  70. orderMap["pay_way"] = "测试使用"
  71. case strings.Contains(payWay, "third_party"):
  72. orderMap["pay_way"] = "第三方平台"
  73. }
  74. if outTradeNo := gconv.String(orderMap["out_trade_no"]); outTradeNo != "" && table != "" {
  75. payId, _ := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT * FROM %s WHERE out_trade_no = '%s' ORDER BY create_time desc`, table, outTradeNo))
  76. if !payId.IsEmpty() {
  77. orderMap["transaction_id"] = gconv.String(payId.Map()["transaction_id"])
  78. }
  79. }
  80. //
  81. orderMap["pure_amount"] = common.If(gconv.Int(orderMap["pay_money"])-gconv.Int(orderMap["commission"]) > 0, gconv.Int(orderMap["pay_money"])-gconv.Int(orderMap["commission"]), 0)
  82. //产品
  83. productData, err := g.DB().Query(ctx, fmt.Sprintf(`SELECT * FROM jy_order_detail WHERE order_code =%s and status =1`, param.OrderCode))
  84. var (
  85. productArr []map[string]interface{}
  86. autoAndAttribute bool
  87. isReturnStatus = gconv.Int(orderData.Map()["return_status"]) == 1
  88. )
  89. if err != nil || productData.IsEmpty() {
  90. return nil, err
  91. }
  92. var (
  93. //佣金 手续费 合同金额 企业
  94. isCommission, isProceduresMoney, isCash, isEnt, isAdmin bool
  95. newEntName string
  96. moneyCorrectionArr []map[string]interface{}
  97. productRed = make(map[int]int)
  98. )
  99. //红冲
  100. redPunch := make(map[string]interface{})
  101. subject := orderData.Map()["return_commpany"]
  102. moneyCorrectionData, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT * FROM moneyCorrection WHERE orderCode =%s order by createTime desc`, param.OrderCode))
  103. if !moneyCorrectionData.IsEmpty() {
  104. for _, m := range moneyCorrectionData.List() {
  105. if detailId := gconv.Int(m["detail_id"]); detailId > 0 {
  106. productRed[detailId] += gconv.Int(m["payMoney"])
  107. orderDetail, _ := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT product_type FROM jy_order_detail WHERE id =%d and status =1`, gconv.Int(m["detail_id"])))
  108. if !orderDetail.IsEmpty() {
  109. m["name"] = orderDetail.Map()["product_type"]
  110. } else if gconv.String(m["activity_code"]) != "" {
  111. activityData, err := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT * FROM jy_product_activity WHERE code ='%s' `, gconv.String(m["activity_code"])))
  112. if err == nil && !activityData.IsEmpty() {
  113. m["name"] = gconv.String(activityData.Map()["name"])
  114. }
  115. }
  116. }
  117. if strings.Contains(common.InterfaceToStr(m["redType"]), "主体") {
  118. isEnt = true
  119. if common.InterfaceToStr(m["newSigningSubject"]) != "" {
  120. m["signingSubject"] = m["newSigningSubject"]
  121. }
  122. if newSigningSubject := common.InterfaceToStr(m["newSigningSubject"]); newSigningSubject != "" && newEntName == "" {
  123. newEntName = newSigningSubject
  124. }
  125. } else {
  126. if common.IntAll(m["payMoney"]) != 0 {
  127. isCash = true
  128. }
  129. if common.IntAll(m["commission"]) != 0 {
  130. isCommission = true
  131. }
  132. if common.IntAll(m["proceduresMoney"]) != 0 {
  133. isProceduresMoney = true
  134. }
  135. if common.InterfaceToStr(m["signingSubject"]) == "" {
  136. m["signingSubject"] = subject
  137. }
  138. }
  139. moneyCorrectionArr = append(moneyCorrectionArr, m)
  140. }
  141. if newEntName != "" {
  142. orderMap["return_commpany"] = newEntName
  143. }
  144. }
  145. redPunch["moneyCorrectionData"] = moneyCorrectionArr
  146. redPunch["isUpCash"] = isCash
  147. redPunch["isUpCommission"] = isCommission
  148. redPunch["isUpProceduresMoney"] = isProceduresMoney
  149. redPunch["isUpEnt"] = isEnt
  150. result["redPunchData"] = redPunch
  151. for _, m := range productData.List() {
  152. filter := gconv.Map(m["filter"])
  153. if activityCode := gconv.String(m["activity_code"]); activityCode != "" {
  154. activityData, err := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT * FROM jy_product_activity WHERE code ='%s' `, activityCode))
  155. if err == nil && !activityData.IsEmpty() {
  156. m["activityName"] = gconv.String(activityData.Map()["name"])
  157. }
  158. }
  159. if _, ok := productRed[gconv.Int(m["id"])]; ok {
  160. m["isRed"] = true
  161. } else {
  162. m["isRed"] = false
  163. }
  164. m["final_price"] = gconv.Int(m["final_price"]) + productRed[gconv.Int(m["id"])]
  165. if productName := gconv.String(filter["productName"]); productName == "" { //历史订单中的类型不做匹配处理
  166. productItem, _ := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT jpi.name,jpc.auto,jpc.code,jpc.attribute FROM jy_product_item jpi
  167. INNER JOIN jy_product_class jpc on jpi.product_class_id = jpc.id WHERE jpi.code = '%s'`, gconv.String(m["product_code"])))
  168. if !productItem.IsEmpty() {
  169. m["productName"] = productItem.Map()["name"]
  170. m["productItemCode"] = productItem.Map()["code"]
  171. m["attribute"] = productItem.Map()["attribute"]
  172. m["auto"] = common.If(gconv.Int(orderMap["is_backstage_order"]) != 1, 2, productItem.Map()["auto"])
  173. if (gconv.Int(m["attribute"]) == 1 || gconv.Int(m["attribute"]) == 2) &&
  174. gconv.Int(m["auto"]) == 1 && gconv.Int(m["is_service_open"]) == 0 &&
  175. (gconv.Int(m["service_type"]) == 1 || gconv.Int(m["service_type"]) == 4) {
  176. autoAndAttribute = true
  177. }
  178. } else {
  179. if gconv.Int(orderMap["is_backstage_order"]) == 0 {
  180. m["productName"] = "标准版"
  181. } else {
  182. m["productName"] = productItem.Map()["product_type"]
  183. }
  184. }
  185. } else {
  186. m["productName"] = productName
  187. }
  188. if dataPackNum := gconv.Int(filter["dataPackNum"]); dataPackNum > 0 {
  189. m["bigServiceNames"] = fmt.Sprintf("赠送数据流量包 (高级字段包) %d条", dataPackNum)
  190. }
  191. /*if gconv.String(m["product_type"]) == "大会员" && gconv.Int(gconv.Map(m["filter"])["comboId"]) == 0 {
  192. supMap := make(map[string]bool)
  193. for _, s := range gconv.Strings(gconv.Map(m["filter"])["supServiceIds"]) {
  194. supMap[s] = true
  195. }
  196. var ids []string
  197. serviceIds := gconv.Strings(gconv.Map(m["filter"])["serviceIds"])
  198. for _, id := range serviceIds {
  199. ids = append(serviceIds, gconv.String(id))
  200. }
  201. bigService, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT id,s_name FROM bigmember_service WHERE id in (%s) order by id`, strings.Join(ids, ",")))
  202. if !bigService.IsEmpty() {
  203. var (
  204. bigServiceNames []string
  205. supBigServiceNames []string
  206. )
  207. for _, m1 := range bigService.List() {
  208. switch gconv.Int(m1["id"]) {
  209. case 1:
  210. m1["s_name"] = "基础服务"
  211. case 30051, 30052, 30053: //0分报告过滤
  212. continue
  213. }
  214. if supMap[gconv.String(m1["id"])] {
  215. supBigServiceNames = append(supBigServiceNames, gconv.String(m1["s_name"]))
  216. } else {
  217. bigServiceNames = append(bigServiceNames, gconv.String(m1["s_name"]))
  218. }
  219. }
  220. if len(supBigServiceNames) > 0 {
  221. m["bigServiceNames"] = fmt.Sprintf("[补充权益]: %s ;[原已购权益]:%s", strings.Join(supBigServiceNames, "、"), strings.Join(bigServiceNames, "、"))
  222. } else {
  223. m["bigServiceNames"] = strings.Join(bigServiceNames, "、")
  224. }
  225. }
  226. }*/
  227. if linkedDetailId := gconv.Int(m["linked_detail_id"]); linkedDetailId > 0 {
  228. var orderArr []map[string]interface{}
  229. //关联订单
  230. if gconv.String(m["product_type"]) != "大会员" && gconv.String(m["product_type"]) != "VIP订阅" {
  231. var whereSql string
  232. if gconv.Int(orderData.Map()["buy_subject"]) == 1 {
  233. whereSql = fmt.Sprintf("dor.user_phone = '%s' and dor.buy_subject =1 and dor.create_time< '%s' ", gconv.String(orderData.Map()["user_phone"]), gconv.String(orderData.Map()["create_time"]))
  234. } else {
  235. whereSql = fmt.Sprintf("dor.user_phone = '%s' and dor.buy_subject =2 and dor.company_name ='%s' and dor.create_time< '%s' ", gconv.String(orderData.Map()["user_phone"]), gconv.String(orderData.Map()["company_name"]), gconv.String(orderData.Map()["create_time"]))
  236. }
  237. if linkedOrder := user.SpecialService(ctx, whereSql, gconv.String(m["product_type"]), gconv.Int(orderData.Map()["buy_subject"])); linkedOrder != nil {
  238. m["linkedOrder"] = linkedOrder
  239. }
  240. } else {
  241. var (
  242. areaCount, paySubNum, buySubject int
  243. endTime, startTime string
  244. )
  245. linkedDetail, _ := g.DB().GetOne(ctx, `SELECT * FROM jy_order_detail where id = ?`, linkedDetailId)
  246. if linkedDetail.IsEmpty() {
  247. log.Println("产品关联订单获取异常", param.OrderCode, linkedDetailId)
  248. continue
  249. }
  250. switch gconv.String(m["product_type"]) {
  251. case "VIP订阅":
  252. var ttt model.VipCycleFilter
  253. if err = gconv.Struct(linkedDetail.Map()["filter"], &ttt); err != nil {
  254. continue
  255. }
  256. areaCount = ttt.FinalAreaCount
  257. paySubNum = gconv.Int(common.If(gconv.Int(orderData.Map()["buy_subject"]) == 1, 1, ttt.FinalAccountCount))
  258. case "大会员":
  259. var ttt model.JyBigProductFilter
  260. if err = gconv.Struct(linkedDetail.Map()["filter"], &ttt); err != nil {
  261. continue
  262. }
  263. areaCount = ttt.FinalAreaCount
  264. paySubNum = ttt.FinalAccountCount
  265. }
  266. switch gconv.Int(orderData.Map()["buy_subject"]) {
  267. case 1:
  268. buySubject = 1
  269. orderProduct, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT b.id,a.service_type,b.order_code,b.create_time,a.service_starttime,a.service_endtime FROM jy_order_detail a
  270. INNER JOIN dataexport_order b on a.order_code = b.order_code
  271. WHERE a.status = 1 and a.is_service_open = 1 and b.user_id = '%s' and b.create_time< '%s' and a.product_type like '%s' ORDER BY b.create_time desc `, gconv.String(orderMap["user_id"]), orderMap["create_time"], common.If(gconv.String(m["product_type"]) == "VIP订阅", "%VIP订阅%", "%大会员%")))
  272. if !orderData.IsEmpty() {
  273. for _, m2 := range orderProduct.List() {
  274. if endTime == "" && gconv.String(m2["service_endtime"]) != "" {
  275. endTime = gconv.String(m2["service_endtime"])
  276. }
  277. if startTime == "" && gconv.String(m2["service_starttime"]) != "" {
  278. startTime = gconv.String(m2["service_starttime"])
  279. }
  280. orderArr = append(orderArr, map[string]interface{}{
  281. "order_code": m2["order_code"],
  282. "create_time": m2["create_time"],
  283. "service_type": m2["service_type"],
  284. "order_detail_id": m2["id"],
  285. })
  286. }
  287. }
  288. case 2:
  289. buySubject = 2
  290. entService, _ := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT a.id,a.product_type,a.end_time,a.start_time,a.empower_count,a.province_count FROM entniche_wait_empower a
  291. INNER JOIN entniche_order b on a.id = b.wait_empower_id
  292. WHERE b.order_detail_id=%d`, linkedDetailId))
  293. if !entService.IsEmpty() {
  294. entOrderService, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT jod.*,do.create_time
  295. FROM jy_order_detail jod
  296. INNER JOIN entniche_order eo ON jod.id = eo.order_detail_id
  297. INNER JOIN dataexport_order do on jod.order_code= do.order_code
  298. WHERE eo.wait_empower_id = %s and jod.is_service_open =1 and jod.status =1 and do.create_time< '%s' ORDER BY do.create_time desc`, gconv.String(entService.Map()["id"]), orderMap["create_time"]))
  299. if !entOrderService.IsEmpty() {
  300. for _, m2 := range entOrderService.List() {
  301. if endTime == "" && gconv.String(m2["service_endtime"]) != "" {
  302. endTime = gconv.String(m2["service_endtime"])
  303. }
  304. if startTime == "" && gconv.String(m2["service_starttime"]) != "" {
  305. startTime = gconv.String(m2["service_starttime"])
  306. }
  307. orderArr = append(orderArr, map[string]interface{}{
  308. "order_code": m2["order_code"],
  309. "create_time": m2["create_time"],
  310. "service_type": m2["service_type"],
  311. "order_detail_id": m2["id"],
  312. })
  313. }
  314. }
  315. }
  316. }
  317. m["linkedOrder"] = map[string]interface{}{
  318. "name": gconv.String(m["product_type"]), //产品名称
  319. "serviceEndTime": endTime, //服务结束时间
  320. "serviceStartTime": startTime, //服务开始时间
  321. "product_code": gconv.String(linkedDetail.Map()["product_code"]),
  322. "empowerCount": paySubNum, //服务授权数
  323. "provinceCount": areaCount, //订阅省份
  324. "buySubject": buySubject, //个体
  325. "orderArr": orderArr, //关联订单
  326. }
  327. }
  328. switch gconv.String(m["product_type"]) {
  329. case "大会员":
  330. BigFilterFmt(m)
  331. case "VIP订阅":
  332. VipFilterFmt(m)
  333. }
  334. }
  335. productArr = append(productArr, m)
  336. }
  337. //合同
  338. contractData, _ := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT * FROM contract WHERE order_code =%s `, param.OrderCode))
  339. if !contractData.IsEmpty() {
  340. contractMap := contractData.Map()
  341. // 合同信息
  342. if contractMap["contract_file_url"] != nil && len(contractMap["contract_file_url"].(string)) > 0 {
  343. index_ := strings.LastIndex(contractMap["contract_file_url"].(string), "/")
  344. if index_ != -1 {
  345. contractMap["contract_file_name"] = contractMap["contract_file_url"].(string)[index_+1:]
  346. }
  347. }
  348. result["contractRes"] = contractMap
  349. }
  350. //全额回款 有会员权益 且没有开通
  351. //获取所有上级部门
  352. userCtx := jyutil.GetUserMsgFromCtx(ctx)
  353. departmentMap := make(map[int64]bool)
  354. for _, i2 := range jyutil.SupAdmin {
  355. if i2 == userCtx.EntUserId {
  356. isAdmin = true
  357. break
  358. }
  359. }
  360. for _, i3 := range jyutil.PinTube {
  361. if i3 == userCtx.EntUserId {
  362. isAdmin = true
  363. break
  364. }
  365. }
  366. salespersonEntUserId := gconv.Int64(orderData["salesperson_entUserId"])
  367. if !isAdmin {
  368. department, _ := g.DB().Query(ctx, `SELECT
  369. edu.dept_id,edu.user_id
  370. FROM
  371. entniche_department_user edu
  372. INNER JOIN entniche_user_role eur on eur.role_id =2 and edu.user_id = eur.user_id
  373. WHERE
  374. edu.user_id = ?
  375. OR edu.dept_id IN ( SELECT edp.pid FROM entniche_department_parent edp INNER JOIN entniche_department_user edu1 ON edu1.user_id = ? AND edp.id = edu1.dept_id )`, salespersonEntUserId, salespersonEntUserId)
  376. if !department.IsEmpty() {
  377. for _, m := range department.List() {
  378. departmentMap[gconv.Int64(m["user_id"])] = true
  379. }
  380. }
  381. }
  382. var isSupportOpen bool
  383. if autoAndAttribute {
  384. if isReturnStatus { //全额回款 是销售本人订单||部门管理员|| 销管&超级管理员
  385. if isAdmin || salespersonEntUserId == userCtx.EntUserId || departmentMap[userCtx.EntUserId] {
  386. isSupportOpen = true //是否可以权益开通
  387. }
  388. } else {
  389. //协议已归档&是销管或超级管理员
  390. isSupportOpen = !contractData.IsEmpty() && gconv.Int(contractData.Map()["contract_archive_status"]) == 1 && isAdmin
  391. }
  392. }
  393. orderMap["isSupportOpen"] = isSupportOpen
  394. result["productData"] = productArr
  395. var transferList []map[string]interface{}
  396. //对公转账审核记录
  397. orderTransfer, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT * FROM jy_order_transfer WHERE order_code = '%s' order by create_time desc `, param.OrderCode))
  398. if !orderTransfer.IsEmpty() {
  399. for _, m := range orderTransfer.List() {
  400. if gconv.String(m["update_time"]) == gconv.String(m["create_time"]) {
  401. m["update_time"] = ""
  402. }
  403. transferList = append(transferList, m)
  404. }
  405. result["orderTransfer"] = transferList
  406. }
  407. // 回款信息
  408. var (
  409. returnMoney, plantMoney int
  410. returnArr []map[string]interface{}
  411. )
  412. returnInfo, _ := g.DB().Query(ctx, fmt.Sprintf("SELECT * from return_money_record WHERE order_code=%s and state=1", param.OrderCode))
  413. // 回款交易详情列表
  414. if !returnInfo.IsEmpty() {
  415. for _, d := range returnInfo.List() {
  416. returnMoney += gconv.Int(d["return_money"])
  417. if d["return_voucher_url"] != nil && len(d["return_voucher_url"].(string)) > 0 {
  418. index_ := strings.LastIndex(d["return_voucher_url"].(string), "/")
  419. if index_ != -1 {
  420. d["return_voucher_name"] = d["return_voucher_url"].(string)[index_+1:]
  421. }
  422. }
  423. returnArr = append(returnArr, d)
  424. }
  425. }
  426. if gconv.Int(orderData.Map()["is_backstage_order"]) == 0 && gconv.Int(orderData.Map()["order_status"]) == 1 &&
  427. gconv.Int(orderData.Map()["pay_money"]) > 0 && gconv.Int(orderData.Map()["return_status"]) == 0 {
  428. returnMoney = gconv.Int(orderData.Map()["pay_money"])
  429. }
  430. if gconv.Int(orderMap["return_status"]) == 1 {
  431. returnMoney = gconv.Int(orderMap["pay_money"])
  432. }
  433. result["returnRes"] = map[string]interface{}{
  434. "returnMoney": returnMoney,
  435. "remainingMoney": gconv.Int(orderMap["pay_money"]) - returnMoney,
  436. "returnInfo": returnArr,
  437. }
  438. //回款计划
  439. returnMoneyPlant, err := g.DB().GetOne(ctx, "SELECT * from return_money_plant where order_code = ? order by create_time desc", param.OrderCode)
  440. if !returnMoneyPlant.IsEmpty() {
  441. for _, m2 := range gconv.Maps(returnMoneyPlant.Map()["plantList"]) {
  442. if gconv.String(m2["code"]) == "合计" {
  443. plantMoney = gconv.Int(m2["money"])
  444. }
  445. }
  446. }
  447. result["returnMoneyPlant"] = map[string]interface{}{
  448. "list": returnMoneyPlant.Map(),
  449. "returnMoney": returnMoney,
  450. "plantMoney": plantMoney,
  451. }
  452. //退款
  453. var (
  454. refundMoney int
  455. refundList []map[string]interface{}
  456. )
  457. refundData, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT rr.* FROM refund_record rr
  458. WHERE rr.order_code ='%s' order by rr.refund_time desc`, param.OrderCode))
  459. if !refundData.IsEmpty() {
  460. for _, datum := range refundData.List() {
  461. refundMoney += gconv.Int(datum["refund_money"])
  462. if gconv.Int(datum["refund_detail_id"]) > 0 {
  463. detailData, _ := g.DB().GetOne(ctx, `SELECT de.*,jc.class_name FROM jy_order_detail de
  464. LEFT JOIN jy_product_item ji on de.product_code = ji.code
  465. LEFT JOIN jy_product_class jc on ji.product_class_id = jc.id WHERE de.id =? and de.status =1`, gconv.Int(datum["refund_detail_id"]))
  466. if !detailData.IsEmpty() {
  467. if gconv.String(detailData.Map()["class_name"]) == "" {
  468. datum["name"] = detailData.Map()["product_type"]
  469. } else {
  470. datum["name"] = detailData.Map()["class_name"]
  471. }
  472. }
  473. }
  474. if gconv.String(datum["refund_active_code"]) != "" {
  475. activityData, _ := g.DB().GetOne(ctx, `SELECT * FROM jy_product_activity WHERE code =?`, gconv.Int(datum["refund_active_code"]))
  476. if !activityData.IsEmpty() {
  477. datum["name"] = activityData.Map()["name"]
  478. }
  479. }
  480. refundList = append(refundList, datum)
  481. }
  482. }
  483. if gconv.Int(orderData.Map()["is_backstage_order"]) == 0 && gconv.Int(orderData.Map()["order_status"]) == 1 &&
  484. gconv.Int(orderData.Map()["pay_money"]) > 0 {
  485. returnMoney = gconv.Int(orderData.Map()["pay_money"])
  486. }
  487. result["refundRes"] = map[string]interface{}{
  488. "refundMoney": refundMoney,
  489. "remainingMoney": returnMoney - refundMoney,
  490. "refundInfo": refundList,
  491. }
  492. //审核轨迹详情
  493. recordsData, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT * FROM audit_records WHERE order_code =%s and audit_type = 2 order by create_time desc `, param.OrderCode))
  494. if !recordsData.IsEmpty() {
  495. result["audit"] = recordsData.List()
  496. }
  497. //盖章记录
  498. sealData, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT os.id,os.stamp_time,os.create_time,eus.name as salesman_name,eu.name as applicant_name FROM order_seal os
  499. LEFT JOIN entniche_user eu on os.applicant_id = eu.id
  500. LEFT JOIN entniche_user eus on os.salesman_id = eus.id
  501. WHERE order_code = '%s' and status = 0 order by create_time desc `, param.OrderCode))
  502. if !sealData.IsEmpty() {
  503. result["sealArr"] = sealData.List()
  504. }
  505. //配置盖章权益人
  506. result["stampedInterest"] = jyutil.StampedInterest
  507. var saleData = map[string]interface{}{
  508. "saleEdit": jyutil.SaleChangePower, //销售业绩变更展示
  509. }
  510. var saleRecordStatus int
  511. saleRes, _ := g.DB().Query(ctx, fmt.Sprintf("SELECT d.*,(select CONCAT_WS('/', a.parent_name, a.item_name) AS order_parent_name from dict_item a where a.item_code=d.distribution_channel ) AS order_channel_new FROM order_sale_record d WHERE d.ordercode='%s' and d.state in (1,-1,2) order by d.create_time asc", param.OrderCode))
  512. if !saleRes.IsEmpty() {
  513. var (
  514. //最终业绩
  515. finalArr []map[string]interface{}
  516. finalShowTime string
  517. //记录
  518. record, recordTmp []map[string]interface{}
  519. repeatMapping = map[string]bool{}
  520. zeroChannel = map[string]bool{}
  521. //
  522. )
  523. for _, m := range saleRes.List() {
  524. var (
  525. status = gconv.Int64(m["state"])
  526. money = gconv.Int64(m["money"])
  527. salerId = gconv.Int64(m["ent_userId"])
  528. )
  529. if (status == 1 || status == 2) && money >= 0 { //最终合算
  530. if finalShowTime == "" {
  531. finalShowTime = gconv.String(m["statistics_time"])
  532. }
  533. finalArr = append(finalArr, map[string]interface{}{
  534. "id": salerId,
  535. "name": m["saler_name"],
  536. "saler_dept": m["saler_dept"],
  537. "distribution_channel": m["distribution_channel"],
  538. "order_channel_new": m["order_channel_new"],
  539. "money": money,
  540. })
  541. }
  542. switch status {
  543. case 1:
  544. saleRecordStatus = 1
  545. case 2:
  546. continue
  547. }
  548. if gconv.Int(m["change_value"]) == 0 || gconv.Int(m["money"]) == 0 {
  549. zeroChannelKey := fmt.Sprintf("%d_%s", salerId, gconv.String(m["distribution_channel"]))
  550. if zeroChannel[zeroChannelKey] {
  551. continue
  552. }
  553. zeroChannel[zeroChannelKey] = true
  554. }
  555. key := fmt.Sprintf("%d_%s", salerId, gconv.String(m["statistics_time"]))
  556. if repeatMapping[key] {
  557. continue
  558. }
  559. repeatMapping[key] = true
  560. recordTmp = append(recordTmp, map[string]interface{}{
  561. "saler_dept": m["saler_dept"],
  562. "name": m["saler_name"],
  563. "change_value": m["change_value"],
  564. "statistics_time": m["statistics_time"],
  565. "createtime": m["create_time"],
  566. "operator": m["operator"],
  567. "change_reason": m["change_reason"],
  568. "distribution_channel": m["distribution_channel"],
  569. "order_channel_new": m["order_channel_new"],
  570. "money": money,
  571. })
  572. }
  573. for i := len(recordTmp) - 1; i >= 0; i-- {
  574. record = append(record, recordTmp[i])
  575. }
  576. saleData["saleFinal"] = map[string]interface{}{
  577. "list": finalArr,
  578. "time": finalShowTime,
  579. }
  580. saleData["reason"] = jyutil.SaleChangeReason
  581. saleData["saleRecord"] = record
  582. result["saleDataRes"] = saleData
  583. }
  584. orderMap["saleRecordStatus"] = saleRecordStatus
  585. //发票信息
  586. var (
  587. invoiceMoney int
  588. invoiceList []map[string]interface{}
  589. )
  590. invoiceRes, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT *,(
  591. SELECT count(1) as count FROM invoice b WHERE b.order_code = a.order_code and b.only_Identifying is not null and b.only_Identifying = a.only_Identifying
  592. ) as isChanged FROM invoice a WHERE a.order_code = '%s' and a.invoice_status != -2 and a.invoice_variety is not null ORDER BY a.create_time DESC`, param.OrderCode))
  593. if !invoiceRes.IsEmpty() {
  594. jyWebDomain := g.Cfg().MustGet(context.Background(), "jyWebDomain").String()
  595. for _, datum := range invoiceRes.List() {
  596. if common.ObjToString(datum["code_url"]) != "" {
  597. datum["code_url"] = jyWebDomain + common.ObjToString(datum["code_url"])
  598. }
  599. datum["invoiceId"] = encrypt.SE.Encode2Hex(gconv.String(datum["id"]))
  600. invoiceList = append(invoiceList, datum)
  601. invoiceMoney += gconv.Int(datum["invoice_order_money"])
  602. }
  603. }
  604. if invoiceMoney > 0 {
  605. orderMap["invoiced_status"] = common.If(gconv.Int(orderData.Map()["pay_money"])-invoiceMoney <= 0, 2, 3)
  606. } else {
  607. orderMap["invoiced_status"] = 0 //未开票
  608. }
  609. result["invoiceData"] = map[string]interface{}{
  610. "invoiceMoney": invoiceMoney,
  611. "remainingMoney": gconv.Int(orderData.Map()["pay_money"]) - invoiceMoney,
  612. "invoiceInfo": invoiceList,
  613. }
  614. result["orderData"] = orderMap
  615. return result, nil
  616. }
  617. func BigFilterFmt(m map[string]interface{}) {
  618. var bigFilter model.JyBigProductFilter
  619. err := gconv.Struct(m["filter"], bigFilter)
  620. if err != nil {
  621. log.Println("filter err", err)
  622. return
  623. }
  624. productType := "大会员"
  625. switch bigFilter.ComboId {
  626. case 1:
  627. productType += "专家版"
  628. case 2:
  629. productType += "智慧版"
  630. case 3:
  631. productType += "商机版"
  632. case 4:
  633. productType += "试用版"
  634. case 6:
  635. productType += "商机版2.0"
  636. case 7:
  637. productType += "专家版2.0"
  638. default:
  639. //自定义获取每个服务名称
  640. productType += "自定义"
  641. if len(bigFilter.SupServiceIds) == 0 {
  642. m["all_service_name"] = ServiceName(bigFilter.ServiceIds)
  643. }
  644. }
  645. m["product_type"] = productType
  646. if len(bigFilter.SupServiceIds) > 0 { //补充服务 区分升级前 升级后分类
  647. var preUpgradeService []string
  648. //基础服务过滤
  649. for _, id := range bigFilter.ServiceIds {
  650. var isSup bool
  651. for _, serviceId := range bigFilter.SupServiceIds {
  652. if id == serviceId {
  653. isSup = true
  654. break
  655. }
  656. }
  657. if !isSup {
  658. preUpgradeService = append(preUpgradeService, id)
  659. }
  660. }
  661. if bigFilter.ComboId == 0 { //自定义获取下老服务名称 套餐不展示
  662. m["old_service_name"] = ServiceName(preUpgradeService)
  663. }
  664. m["new_service_name"] = ServiceName(bigFilter.SupServiceIds)
  665. }
  666. }
  667. func ServiceName(id []string) (serviceName []string) {
  668. bigService, _ := g.DB().Query(context.Background(), fmt.Sprintf(`SELECT id,s_new_name,i_class,s_count_year FROM bigmember_service WHERE id in (%s) ORDER BY i_class ASC,i_sort ASC`, strings.Join(id, ",")))
  669. if !bigService.IsEmpty() {
  670. for _, m2 := range bigService.List() {
  671. switch m2["i_class"] {
  672. case 1:
  673. serviceName = append(serviceName, "基础服务")
  674. case 2:
  675. serviceName = append(serviceName, fmt.Sprintf("%s%s", m2["s_new_name"],
  676. common.If(gconv.Int(m2["s_count_year"]) > 0, fmt.Sprintf("(%s)个", gconv.String(m2["s_count_year"])), "")))
  677. case 3:
  678. serviceName = append(serviceName, fmt.Sprintf("%s%s", m2["s_new_name"],
  679. common.If(gconv.Int(m2["s_count_year"]) > 0, fmt.Sprintf("(%s)份", gconv.String(m2["s_count_year"])), "")))
  680. case 4:
  681. serviceName = append(serviceName, fmt.Sprintf("%s%s", m2["s_new_name"],
  682. common.If(gconv.Int(m2["s_count_year"]) > 0, fmt.Sprintf(":%s/天", gconv.String(m2["s_count_year"])), "")))
  683. }
  684. }
  685. }
  686. return
  687. }
  688. func VipFilterFmt(m map[string]interface{}) {
  689. //升级订阅增购省份多少个
  690. var vipFilter model.VipCycleFilter
  691. gconv.Struct(m["filter"], vipFilter)
  692. productItem, _ := g.DB().GetOne(context.Background(), fmt.Sprintf(`SELECT * FROM jy_product_item WHERE code = '%s'`, gconv.String(m["product_code"])))
  693. if !productItem.IsEmpty() {
  694. if gconv.Int(productItem.Map()["unit_num"]) < vipFilter.FinalAreaCount {
  695. if vipFilter.FinalAreaCount == -1 || vipFilter.FinalAreaCount > 16 {
  696. m["upgradesNumber"] = 16 - gconv.Int(productItem.Map()["unit_num"])
  697. }
  698. }
  699. }
  700. }