detail.go 30 KB

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