123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691 |
- package order
- import (
- "app.yhyue.com/moapp/jybase/common"
- "context"
- "fmt"
- "github.com/gogf/gf/v2/frame/g"
- "github.com/gogf/gf/v2/util/gconv"
- "jyOrderManager/internal/jyutil"
- "jyOrderManager/internal/logic/user"
- "jyOrderManager/internal/model"
- "log"
- "strings"
- "time"
- )
- func init() {
- }
- func Detail(ctx context.Context, param model.OrderDetailParams) (map[string]interface{}, error) {
- result := make(map[string]interface{})
- //订单 暂无备注字段
- 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))
- if err != nil || orderData.IsEmpty() {
- return nil, err
- }
- var (
- userIdentity []int
- )
- for _, userid := range jyutil.SupAdmin { //超级管理员
- if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
- userIdentity = append(userIdentity, 1)
- }
- }
- for _, userid := range jyutil.PinTube { //销管
- if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
- userIdentity = append(userIdentity, 2)
- }
- }
- for _, userid := range jyutil.CSId { //销管
- if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
- userIdentity = append(userIdentity, 3)
- }
- }
- for _, userid := range jyutil.Administration { //销管
- if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
- userIdentity = append(userIdentity, 4)
- }
- }
- for _, userid := range jyutil.Finance { //销管
- if userid == jyutil.GetUserMsgFromCtx(ctx).EntUserId {
- userIdentity = append(userIdentity, 5)
- }
- }
- result["userIdentity"] = userIdentity
- orderMap := orderData.Map()
- orderMap["pay_money"] = gconv.Int64(orderMap["new_pay_money"])
- orderMap["commission"] = gconv.Int64(orderMap["new_commission"])
- payWay := gconv.String(orderData.Map()["pay_way"])
- switch {
- case strings.Contains(payWay, "wx"):
- orderMap["pay_way"] = "微信"
- case strings.Contains(payWay, "ali"):
- orderMap["pay_way"] = "支付宝"
- case strings.Contains(payWay, "trial"):
- orderMap["pay_way"] = "其他"
- case strings.Contains(payWay, "transferAccounts"):
- orderMap["pay_way"] = "对公转账"
- case strings.Contains(payWay, "测试使用"):
- orderMap["pay_way"] = "测试使用"
- }
- 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)
- //产品
- productData, err := g.DB().Query(ctx, fmt.Sprintf(`SELECT * FROM jy_order_detail WHERE order_code =%s and status =1`, param.OrderCode))
- var (
- productArr []map[string]interface{}
- autoAndAttribute bool
- isReturnStatus = gconv.Int(orderData.Map()["return_status"]) == 1
- )
- if err != nil || productData.IsEmpty() {
- return nil, err
- }
- var (
- //佣金 手续费 合同金额 企业
- isCommission, isProceduresMoney, isCash, isEnt, isAdmin bool
- newEntName string
- moneyCorrectionArr []map[string]interface{}
- productRed = make(map[int]int)
- )
- //红冲
- redPunch := make(map[string]interface{})
- subject := orderData.Map()["return_commpany"]
- moneyCorrectionData, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT * FROM moneyCorrection WHERE orderCode =%s order by createTime desc`, param.OrderCode))
- if !moneyCorrectionData.IsEmpty() {
- for _, m := range moneyCorrectionData.List() {
- if detailId := gconv.Int(m["detail_id"]); detailId > 0 {
- productRed[detailId] += gconv.Int(m["payMoney"])
- 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"])))
- if !orderDetail.IsEmpty() {
- m["name"] = orderDetail.Map()["product_type"]
- } else if gconv.String(m["activity_code"]) != "" {
- activityData, err := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT * FROM jy_product_activity WHERE code ='%s' `, gconv.String(m["activity_code"])))
- if err == nil && !activityData.IsEmpty() {
- m["name"] = gconv.String(activityData.Map()["name"])
- }
- }
- }
- if strings.Contains(common.InterfaceToStr(m["redType"]), "主体") {
- isEnt = true
- if common.InterfaceToStr(m["newSigningSubject"]) != "" {
- m["signingSubject"] = m["newSigningSubject"]
- }
- if newSigningSubject := common.InterfaceToStr(m["newSigningSubject"]); newSigningSubject != "" && newEntName == "" {
- newEntName = newSigningSubject
- }
- } else {
- if common.IntAll(m["payMoney"]) != 0 {
- isCash = true
- }
- if common.IntAll(m["commission"]) != 0 {
- isCommission = true
- }
- if common.IntAll(m["proceduresMoney"]) != 0 {
- isProceduresMoney = true
- }
- if common.InterfaceToStr(m["signingSubject"]) == "" {
- m["signingSubject"] = subject
- }
- }
- moneyCorrectionArr = append(moneyCorrectionArr, m)
- }
- if newEntName != "" {
- orderMap["return_commpany"] = newEntName
- }
- }
- redPunch["moneyCorrectionData"] = moneyCorrectionArr
- redPunch["isUpCash"] = isCash
- redPunch["isUpCommission"] = isCommission
- redPunch["isUpProceduresMoney"] = isProceduresMoney
- redPunch["isUpEnt"] = isEnt
- result["redPunchData"] = redPunch
- for _, m := range productData.List() {
- if activityCode := gconv.String(m["activity_code"]); activityCode != "" {
- activityData, err := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT * FROM jy_product_activity WHERE code ='%s' `, activityCode))
- if err == nil && !activityData.IsEmpty() {
- m["activityName"] = gconv.String(activityData.Map()["name"])
- }
- }
- if _, ok := productRed[gconv.Int(m["id"])]; ok {
- m["isRed"] = true
- } else {
- m["isRed"] = false
- }
- m["final_price"] = gconv.Int(m["final_price"]) + productRed[gconv.Int(m["id"])]
- productItem, _ := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT jpi.name,jpc.auto,jpc.code,jpc.attribute FROM jy_product_item jpi
- INNER JOIN jy_product_class jpc on jpi.product_class_id = jpc.id WHERE jpi.code = '%s'`, gconv.String(m["product_code"])))
- if !productItem.IsEmpty() {
- m["productName"] = productItem.Map()["name"]
- m["productItemCode"] = productItem.Map()["code"]
- m["auto"] = productItem.Map()["auto"]
- m["attribute"] = productItem.Map()["attribute"]
- if (gconv.Int(m["attribute"]) == 1 || gconv.Int(m["attribute"]) == 2) &&
- gconv.Int(m["auto"]) == 1 && gconv.Int(m["is_service_open"]) == 0 &&
- (gconv.Int(m["service_type"]) == 1 || gconv.Int(m["service_type"]) == 4) {
- autoAndAttribute = true
- }
- } else {
- m["productName"] = productItem.Map()["product_type"]
- }
- if gconv.String(m["product_type"]) == "大会员" && gconv.Int(gconv.Map(m["filter"])["comboId"]) == 0 {
- supMap := make(map[string]bool)
- for _, s := range gconv.Strings(gconv.Map(m["filter"])["supServiceIds"]) {
- supMap[s] = true
- }
- var ids []string
- serviceIds := gconv.Strings(gconv.Map(m["filter"])["serviceIds"])
- for _, id := range serviceIds {
- ids = append(serviceIds, gconv.String(id))
- }
- bigService, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT id,s_name FROM bigmember_service WHERE id in (%s) order by id`, strings.Join(ids, ",")))
- if !bigService.IsEmpty() {
- var (
- bigServiceNames []string
- supBigServiceNames []string
- )
- for _, m1 := range bigService.List() {
- switch gconv.Int(m1["id"]) {
- case 1:
- m1["s_name"] = "基础服务"
- case 30051, 30052, 30053: //0分报告过滤
- continue
- }
- if supMap[gconv.String(m1["id"])] {
- supBigServiceNames = append(supBigServiceNames, gconv.String(m1["s_name"]))
- } else {
- bigServiceNames = append(bigServiceNames, gconv.String(m1["s_name"]))
- }
- }
- if len(supBigServiceNames) > 0 {
- m["bigServiceNames"] = fmt.Sprintf("[补充权益]: %s ;[原已购权益]:%s", strings.Join(supBigServiceNames, "、"), strings.Join(bigServiceNames, "、"))
- } else {
- m["bigServiceNames"] = strings.Join(bigServiceNames, "、")
- }
- }
- }
- if linkedDetailId := gconv.Int(m["linked_detail_id"]); linkedDetailId > 0 {
- var orderArr []map[string]interface{}
- //关联订单
- if gconv.String(m["product_type"]) != "大会员" && gconv.String(m["product_type"]) != "VIP订阅" {
- var whereSql string
- if gconv.Int(orderData.Map()["buy_subject"]) == 1 {
- 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"]))
- } else {
- 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"]))
- }
- if linkedOrder := user.SpecialService(ctx, whereSql, gconv.String(m["product_type"]), gconv.Int(orderData.Map()["buy_subject"])); linkedOrder != nil {
- m["linkedOrder"] = linkedOrder
- }
- } else {
- switch gconv.Int(orderData.Map()["buy_subject"]) {
- case 1:
- userData, _ := jyutil.MG.DB().FindOne("user", map[string]interface{}{
- "$or": []map[string]interface{}{
- {"s_phone": orderData.Map()["user_phone"]},
- {"s_m_phone": orderData.Map()["user_phone"]},
- },
- })
- orderProduct, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT b.id,a.service_type,b.order_code,b.create_time FROM jy_order_detail a
- INNER JOIN dataexport_order b on a.order_code = b.order_code
- 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订阅%", "%大会员%")))
- if !orderData.IsEmpty() {
- for _, m2 := range orderProduct.List() {
- orderArr = append(orderArr, map[string]interface{}{
- "order_code": m2["order_code"],
- "create_time": m2["create_time"],
- "service_type": m2["service_type"],
- "order_detail_id": m2["id"],
- })
- }
- }
- if userData != nil && len(*userData) > 0 {
- var (
- areaCount, paySubNum int
- endTime string
- )
- switch gconv.String(m["product_type"]) {
- case "VIP订阅":
- vipInfo := common.ObjToMap((*userData)["o_vipjy"])
- buySet := common.ObjToMap((*vipInfo)["o_buyset"])
- areaCount = common.IntAll((*buySet)["areacount"])
- paySubNum = 1
- //判断是新版超级订阅还是老版超级订阅
- if common.IntAll((*buySet)["upgrade"]) == 1 {
- //newVip = true
- }
- endTime = time.Unix(common.Int64All((*userData)["l_vip_endtime"]), 0).Format("2006-01-02 15:04:05")
- case "大会员":
- bigStart := common.Int64All((*userData)["i_member_starttime"])
- bigEnd := common.Int64All((*userData)["i_member_endtime"])
- memberStatus := common.IntAll((*userData)["i_member_status"])
- if memberJyMap, ok1 := ((*userData)["o_member_jy"]).(map[string]interface{}); ok1 {
- areaCount = common.IntAll(memberJyMap["i_areacount"])
- }
- if bigStart >= time.Now().Unix() {
- endTime = time.Unix(bigEnd, 0).Format("2006-01-02 15:04:05")
- } else if (time.Now().Unix() < bigEnd && memberStatus > 0) || bigStart >= time.Now().Unix() {
- endTime = time.Unix(bigEnd, 0).Format("2006-01-02 15:04:05")
- }
- paySubNum = common.IntAll((*userData)["i_pay_sub_num"]) + common.IntAll((*userData)["i_free_sub_num"]) + 1
- }
- m["linkedOrder"] = map[string]interface{}{
- "name": gconv.String(m["product_type"]), //产品名称
- "serviceEndTime": endTime, //服务结束时间
- "empowerCount": paySubNum, //服务授权数
- "provinceCount": areaCount, //订阅省份
- "buySubject": 1, //个体
- "orderArr": orderArr, //关联订单
- }
- }
- case 2:
- 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
- INNER JOIN entniche_order b on a.id = b.wait_empower_id
- WHERE b.order_detail_id=%d`, linkedDetailId))
- if !entService.IsEmpty() {
- entOrderService, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT jod.*,do.create_time
- FROM jy_order_detail jod
- INNER JOIN entniche_order eo ON jod.id = eo.order_detail_id
- INNER JOIN dataexport_order do on jod.order_code= do.order_code
- 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"]))
- if !entOrderService.IsEmpty() {
- for _, m2 := range entOrderService.List() {
- orderArr = append(orderArr, map[string]interface{}{
- "order_code": m2["order_code"],
- "create_time": m2["create_time"],
- "service_type": m2["service_type"],
- "order_detail_id": m2["id"],
- })
- }
- m["linkedOrder"] = map[string]interface{}{
- "name": gconv.String(entService.Map()["product_type"]), //产品名称
- "serviceEndTime": gconv.String(entService.Map()["end_time"]), //服务结束时间
- "serviceStartTime": gconv.String(entService.Map()["start_time"]), //服务开始时间
- "empowerCount": gconv.String(entService.Map()["empower_count"]), //服务授权数
- "provinceCount": gconv.String(entService.Map()["province_count"]), //订阅省份
- "buySubject": 2, //个体
- "orderArr": orderArr, //关联订单
- }
- }
- }
- }
- }
- switch gconv.String(m["product_type"]) {
- case "大会员":
- BigFilterFmt(m)
- case "VIP订阅":
- VipFilterFmt(m)
- }
- }
- productArr = append(productArr, m)
- }
- //合同
- contractData, _ := g.DB().GetOne(ctx, fmt.Sprintf(`SELECT * FROM contract WHERE order_code =%s `, param.OrderCode))
- if !contractData.IsEmpty() {
- contractMap := contractData.Map()
- // 合同信息
- if contractMap["contract_file_url"] != nil && len(contractMap["contract_file_url"].(string)) > 0 {
- index_ := strings.LastIndex(contractMap["contract_file_url"].(string), "/")
- if index_ != -1 {
- contractMap["contract_file_name"] = contractMap["contract_file_url"].(string)[index_+1:]
- }
- }
- result["contractRes"] = contractMap
- }
- //全额回款 有会员权益 且没有开通
- //获取所有上级部门
- userCtx := jyutil.GetUserMsgFromCtx(ctx)
- departmentMap := make(map[int64]bool)
- for _, i2 := range jyutil.SupAdmin {
- if i2 == userCtx.EntUserId {
- isAdmin = true
- break
- }
- }
- for _, i3 := range jyutil.PinTube {
- if i3 == userCtx.EntUserId {
- isAdmin = true
- break
- }
- }
- salespersonEntUserId := gconv.Int64(orderData["salesperson_entUserId"])
- if !isAdmin {
- department, _ := g.DB().Query(ctx, `SELECT
- edu.dept_id,edu.user_id
- FROM
- entniche_department_user edu
- INNER JOIN entniche_user_role eur on eur.role_id =2 and edu.user_id = eur.user_id
- WHERE
- edu.user_id = ?
- 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)
- if !department.IsEmpty() {
- for _, m := range department.List() {
- departmentMap[gconv.Int64(m["user_id"])] = true
- }
- }
- }
- var isSupportOpen bool
- if autoAndAttribute {
- if isReturnStatus { //全额回款 是销售本人订单||部门管理员|| 销管&超级管理员
- if isAdmin || salespersonEntUserId == userCtx.EntUserId || departmentMap[userCtx.EntUserId] {
- isSupportOpen = true //是否可以权益开通
- }
- } else {
- //协议已归档&是销管或超级管理员
- isSupportOpen = !contractData.IsEmpty() && gconv.Int(contractData.Map()["contract_archive_status"]) == 1 && isAdmin
- }
- }
- orderMap["isSupportOpen"] = isSupportOpen
- result["productData"] = productArr
- //对公转账审核记录
- orderTransfer, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT * FROM jy_order_transfer WHERE order_code = '%s' order by create_time desc `, param.OrderCode))
- if !orderTransfer.IsEmpty() {
- result["orderTransfer"] = orderTransfer.List()
- }
- // 回款信息
- var (
- returnMoney, plantMoney int
- returnArr []map[string]interface{}
- )
- returnInfo, _ := g.DB().Query(ctx, fmt.Sprintf("SELECT * from return_money_record WHERE order_code=%s and state=1", param.OrderCode))
- // 回款交易详情列表
- if !returnInfo.IsEmpty() {
- for _, d := range returnInfo.List() {
- returnMoney += gconv.Int(d["return_money"])
- if d["return_voucher_url"] != nil && len(d["return_voucher_url"].(string)) > 0 {
- index_ := strings.LastIndex(d["return_voucher_url"].(string), "/")
- if index_ != -1 {
- d["return_voucher_name"] = d["return_voucher_url"].(string)[index_+1:]
- }
- }
- returnArr = append(returnArr, d)
- }
- }
- if gconv.Int(orderData.Map()["is_backstage_order"]) == 0 && gconv.Int(orderData.Map()["order_status"]) == 1 &&
- gconv.Int(orderData.Map()["pay_money"]) > 0 && gconv.Int(orderData.Map()["return_status"]) == 0 {
- returnMoney = gconv.Int(orderData.Map()["pay_money"])
- }
- result["returnRes"] = map[string]interface{}{
- "returnMoney": returnMoney,
- "remainingMoney": gconv.Int(orderData.Map()["pay_money"]) - returnMoney,
- "returnInfo": returnArr,
- }
- //回款计划
- returnMoneyPlant, err := g.DB().GetOne(ctx, "SELECT * from return_money_plant where order_code = ? order by create_time desc", param.OrderCode)
- if !returnMoneyPlant.IsEmpty() {
- for _, m2 := range gconv.Maps(returnMoneyPlant.Map()["plantList"]) {
- if gconv.String(m2["code"]) == "合计" {
- plantMoney = gconv.Int(m2["money"])
- }
- }
- }
- result["returnMoneyPlant"] = map[string]interface{}{
- "list": returnMoneyPlant.Map(),
- "returnMoney": returnMoney,
- "plantMoney": plantMoney,
- }
- //退款
- var (
- refundMoney int
- refundList []map[string]interface{}
- )
- refundData, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT rr.* FROM refund_record rr
- WHERE rr.order_code ='%s' order by rr.refund_time desc`, param.OrderCode))
- if !refundData.IsEmpty() {
- for _, datum := range refundData.List() {
- refundMoney += gconv.Int(datum["refund_money"])
- if gconv.Int(datum["refund_detail_id"]) > 0 {
- detailData, _ := g.DB().GetOne(ctx, `SELECT de.*,jc.class_name FROM jy_order_detail de
- LEFT JOIN jy_product_item ji on de.product_code = ji.code
- 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"]))
- if !detailData.IsEmpty() {
- if gconv.String(detailData.Map()["class_name"]) == "" {
- datum["name"] = detailData.Map()["product_type"]
- } else {
- datum["name"] = detailData.Map()["class_name"]
- }
- }
- }
- if gconv.String(datum["refund_active_code"]) != "" {
- activityData, _ := g.DB().GetOne(ctx, `SELECT * FROM jy_product_activity WHERE code =?`, gconv.Int(datum["refund_active_code"]))
- if !activityData.IsEmpty() {
- datum["name"] = activityData.Map()["name"]
- }
- }
- refundList = append(refundList, datum)
- }
- }
- if gconv.Int(orderData.Map()["is_backstage_order"]) == 0 && gconv.Int(orderData.Map()["order_status"]) == 1 &&
- gconv.Int(orderData.Map()["pay_money"]) > 0 {
- returnMoney = gconv.Int(orderData.Map()["pay_money"])
- }
- result["refundRes"] = map[string]interface{}{
- "refundMoney": refundMoney,
- "remainingMoney": returnMoney - refundMoney,
- "refundInfo": refundList,
- }
- //审核轨迹详情
- 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))
- if !recordsData.IsEmpty() {
- result["audit"] = recordsData.List()
- }
- //盖章记录
- 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
- LEFT JOIN entniche_user eu on os.applicant_id = eu.id
- LEFT JOIN entniche_user eus on os.salesman_id = eus.id
- WHERE order_code = '%s' and status = 0 order by create_time desc `, param.OrderCode))
- if !sealData.IsEmpty() {
- result["sealArr"] = sealData.List()
- }
- //配置盖章权益人
- result["stampedInterest"] = jyutil.StampedInterest
- var saleData = map[string]interface{}{
- "saleEdit": jyutil.SaleChangePower, //销售业绩变更展示
- }
- var saleRecordStatus int
- 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))
- if !saleRes.IsEmpty() {
- var (
- //最终业绩
- finalArr []map[string]interface{}
- finalShowTime string
- //记录
- record, recordTmp []map[string]interface{}
- repeatMapping = map[string]bool{}
- zeroChannel = map[string]bool{}
- //
- )
- for _, m := range saleRes.List() {
- var (
- status = gconv.Int64(m["state"])
- money = gconv.Int64(m["money"])
- salerId = gconv.Int64(m["ent_userId"])
- )
- if (status == 1 || status == 2) && money >= 0 { //最终合算
- if finalShowTime == "" {
- finalShowTime = gconv.String(m["statistics_time"])
- }
- finalArr = append(finalArr, map[string]interface{}{
- "id": salerId,
- "name": m["saler_name"],
- "saler_dept": m["saler_dept"],
- "distribution_channel": m["distribution_channel"],
- "order_channel_new": m["order_channel_new"],
- "money": money,
- })
- }
- switch status {
- case 1:
- saleRecordStatus = 1
- case 2:
- continue
- }
- if gconv.Int(m["change_value"]) == 0 || gconv.Int(m["money"]) == 0 {
- zeroChannelKey := fmt.Sprintf("%d_%s", salerId, gconv.String(m["distribution_channel"]))
- if zeroChannel[zeroChannelKey] {
- continue
- }
- zeroChannel[zeroChannelKey] = true
- }
- key := fmt.Sprintf("%d_%s", salerId, gconv.String(m["statistics_time"]))
- if repeatMapping[key] {
- continue
- }
- repeatMapping[key] = true
- recordTmp = append(recordTmp, map[string]interface{}{
- "saler_dept": m["saler_dept"],
- "name": m["saler_name"],
- "change_value": m["change_value"],
- "statistics_time": m["statistics_time"],
- "createtime": m["create_time"],
- "operator": m["operator"],
- "change_reason": m["change_reason"],
- "distribution_channel": m["distribution_channel"],
- "order_channel_new": m["order_channel_new"],
- "money": money,
- })
- }
- for i := len(recordTmp) - 1; i >= 0; i-- {
- record = append(record, recordTmp[i])
- }
- saleData["saleFinal"] = map[string]interface{}{
- "list": finalArr,
- "time": finalShowTime,
- }
- saleData["reason"] = jyutil.SaleChangeReason
- saleData["saleRecord"] = record
- result["saleDataRes"] = saleData
- }
- orderMap["saleRecordStatus"] = saleRecordStatus
- //发票信息
- var (
- invoiceMoney int
- invoiceList []map[string]interface{}
- )
- invoiceRes, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT *,(
- 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
- ) 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, "%纸质%"))
- if !invoiceRes.IsEmpty() {
- jyWebDomain := g.Cfg().MustGet(context.Background(), "jyWebDomain").String()
- for _, datum := range invoiceRes.List() {
- if common.ObjToString(datum["code_url"]) != "" {
- datum["code_url"] = jyWebDomain + common.ObjToString(datum["code_url"])
- }
- invoiceList = append(invoiceList, datum)
- invoiceMoney += gconv.Int(datum["invoice_money"])
- }
- }
- if invoiceMoney > 0 {
- orderMap["invoiced_status"] = common.If(gconv.Int(orderData.Map()["pay_money"])-invoiceMoney <= 0, 2, 3)
- } else {
- orderMap["invoiced_status"] = 0 //未开票
- }
- result["invoiceData"] = map[string]interface{}{
- "invoiceMoney": invoiceMoney,
- "remainingMoney": gconv.Int(orderData.Map()["pay_money"]) - invoiceMoney,
- "invoiceInfo": invoiceList,
- }
- result["orderData"] = orderMap
- return result, nil
- }
- func BigFilterFmt(m map[string]interface{}) {
- var bigFilter model.JyBigProductFilter
- err := gconv.Struct(m["filter"], bigFilter)
- if err != nil {
- log.Println("filter err", err)
- return
- }
- productType := "大会员"
- switch bigFilter.ComboId {
- case 1:
- productType += "专家版"
- case 2:
- productType += "智慧版"
- case 3:
- productType += "商机版"
- case 4:
- productType += "试用版"
- case 6:
- productType += "商机版2.0"
- case 7:
- productType += "专家版2.0"
- default:
- //自定义获取每个服务名称
- productType += "自定义"
- if len(bigFilter.SupServiceIds) == 0 {
- m["all_service_name"] = ServiceName(bigFilter.ServiceIds)
- }
- }
- m["product_type"] = productType
- if len(bigFilter.SupServiceIds) > 0 { //补充服务 区分升级前 升级后分类
- var preUpgradeService []string
- //基础服务过滤
- for _, id := range bigFilter.ServiceIds {
- var isSup bool
- for _, serviceId := range bigFilter.SupServiceIds {
- if id == serviceId {
- isSup = true
- break
- }
- }
- if !isSup {
- preUpgradeService = append(preUpgradeService, id)
- }
- }
- if bigFilter.ComboId == 0 { //自定义获取下老服务名称 套餐不展示
- m["old_service_name"] = ServiceName(preUpgradeService)
- }
- m["new_service_name"] = ServiceName(bigFilter.SupServiceIds)
- }
- }
- func ServiceName(id []string) (serviceName []string) {
- 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, ",")))
- if !bigService.IsEmpty() {
- for _, m2 := range bigService.List() {
- switch m2["i_class"] {
- case 1:
- serviceName = append(serviceName, "基础服务")
- case 2:
- serviceName = append(serviceName, fmt.Sprintf("%s%s", m2["s_new_name"],
- common.If(gconv.Int(m2["s_count_year"]) > 0, fmt.Sprintf("(%s)个", gconv.String(m2["s_count_year"])), "")))
- case 3:
- serviceName = append(serviceName, fmt.Sprintf("%s%s", m2["s_new_name"],
- common.If(gconv.Int(m2["s_count_year"]) > 0, fmt.Sprintf("(%s)份", gconv.String(m2["s_count_year"])), "")))
- case 4:
- serviceName = append(serviceName, fmt.Sprintf("%s%s", m2["s_new_name"],
- common.If(gconv.Int(m2["s_count_year"]) > 0, fmt.Sprintf(":%s/天", gconv.String(m2["s_count_year"])), "")))
- }
- }
- }
- return
- }
- func VipFilterFmt(m map[string]interface{}) {
- //升级订阅增购省份多少个
- var vipFilter model.VipCycleFilter
- gconv.Struct(m["filter"], vipFilter)
- productItem, _ := g.DB().GetOne(context.Background(), fmt.Sprintf(`SELECT * FROM jy_product_item WHERE code = '%s'`, gconv.String(m["product_code"])))
- if !productItem.IsEmpty() {
- if gconv.Int(productItem.Map()["unit_num"]) < vipFilter.FinalAreaCount {
- if vipFilter.FinalAreaCount == -1 || vipFilter.FinalAreaCount > 16 {
- m["upgradesNumber"] = 16 - gconv.Int(productItem.Map()["unit_num"])
- }
- }
- }
- }
|