detail.go 27 KB

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