list.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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/model"
  10. "log"
  11. "strings"
  12. )
  13. func List(ctx context.Context, param model.OrderListParams) (map[string]interface{}, error) {
  14. var (
  15. orderSql, productArr []string
  16. productSql, channelSql string
  17. adminId = jyutil.GetUserMsgFromCtx(ctx).EntUserId
  18. )
  19. if param.Page <= 0 {
  20. param.Page = 1
  21. }
  22. if param.Size <= 0 || param.Size > 100 {
  23. param.Size = 50
  24. }
  25. switch param.ListSource { //默认全部订单
  26. case 1: //我的订单
  27. orderSql = append(orderSql, fmt.Sprintf(`(a.salesperson_entUserId ='%d' or a.order_code in (SELECT ordercode FROM order_sale_record WHERE ent_userId = %d and state in (1,2) GROUP BY ordercode))`, adminId, adminId))
  28. case 2: //代用户下单
  29. // 我的订单、高翔、沈炳义查看所有得帮助用户下单的订单
  30. productSql = ` INNER JOIN (SELECT DISTINCT(order_code) FROM jy_order_detail WHERE product_type = 'VIP订阅' and status =1) ptc on ptc.order_code = a.order_code `
  31. orderSql = append(orderSql, " a.del_status = 0 and a.order_channel = 'xdqd04' ")
  32. var isHelpList bool
  33. for _, s := range g.Cfg().MustGet(ctx, "request_auth").Int64s() {
  34. if s == adminId {
  35. isHelpList = false
  36. break
  37. }
  38. }
  39. if !isHelpList { //查看个人
  40. orderSql = append(orderSql, fmt.Sprintf(`(a.salesperson_entUserId ='%d' or a.order_code in (SELECT ordercode FROM order_sale_record WHERE ent_userId = %d and state in (1,2) GROUP BY ordercode))`, adminId, adminId))
  41. //orderSql = append(orderSql, fmt.Sprintf(" f.ent_userId= '%d' ", adminId))
  42. }
  43. default: //默认全部订单
  44. // SalesChannelClass1 string `json:"sales_channel_class1"` //一级销售渠道
  45. // SalesChannelClass2 string `json:"sales_channel_class2"` //二级销售渠道
  46. // PayMoneyMin int `json:"payMoneyMin"` //实付金额最小
  47. // PayMoneyMax int `json:"payMoneyMax"` //实付金额最大
  48. // PayType int `json:"payType"` //付费类型
  49. // PayWay string `json:"payWay"` //付款方式
  50. // AuditStatus int `json:"auditStatus"` // 审核状态
  51. // ContractStatus int `json:"contractStatus"` //合同状态
  52. if param.SalesChannelClass1 != "" { //一级销售渠道
  53. if param.SalesChannelClass2 == "" { //二级销售渠道
  54. //根据销售渠道一级分类代码查询二级分类
  55. class, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT item_code FROM dict_item WHERE parent_code = '%s'`, param.SalesChannelClass1))
  56. if !class.IsEmpty() {
  57. var distributionChannel []string
  58. for _, val := range class.List() {
  59. distributionChannel = append(distributionChannel, fmt.Sprintf("'%s'", gconv.String(val["item_code"])))
  60. }
  61. channelSql = fmt.Sprintf(` INNER JOIN (
  62. SELECT ordercode FROM order_sale_record WHERE distribution_channel in (%s) and state in (1,2) GROUP BY ordercode
  63. ) f ON a.order_code = f.ordercode `, strings.Join(distributionChannel, " or "))
  64. }
  65. } else {
  66. channelSql = fmt.Sprintf(` INNER JOIN (
  67. SELECT ordercode FROM order_sale_record WHERE distribution_channel = '%s' and state in (1,2) GROUP BY ordercode
  68. ) f ON a.order_code = f.ordercode `, param.SalesChannelClass2)
  69. }
  70. }
  71. if param.PayMoneyMin >= 0 { //实付金额最小
  72. orderSql = append(orderSql, fmt.Sprintf(" a.pay_money>=%d ", param.PayMoneyMin))
  73. }
  74. if param.PayMoneyMax >= 0 { //实付金额最大
  75. orderSql = append(orderSql, fmt.Sprintf(" a.pay_money<= %d", param.PayMoneyMax))
  76. }
  77. // 0 支付宝 1 微信 2 线下支付 3 对公转账 4其他 全部传空
  78. switch param.PayWay {
  79. case "0":
  80. orderSql = append(orderSql, " locate('ali', a.pay_way) > 0 ")
  81. case "1":
  82. orderSql = append(orderSql, " locate('wx', a.pay_way) > 0 ")
  83. case "2":
  84. orderSql = append(orderSql, " a.pay_way = '线下支付' ")
  85. case "3":
  86. orderSql = append(orderSql, " a.pay_way = 'transferAccounts' ")
  87. case "4":
  88. orderSql = append(orderSql, " locate('ali', a.pay_way) = 0 and locate('wx', a.pay_way) = 0 and a.pay_way != '线下支付' and a.pay_way != 'transferAccounts' and a.pay_way != '测试使用' ")
  89. case "5":
  90. orderSql = append(orderSql, " a.pay_way = '测试使用' ")
  91. }
  92. if param.AuditStatus > 0 { // 1 微信 2 线下支付 3 对公转账
  93. orderSql = append(orderSql, fmt.Sprintf(` a.course_status = %d `, param.AuditStatus))
  94. }
  95. if param.PayType != "" {
  96. productArr = append(productArr, fmt.Sprintf(` service_type = %s `, param.PayType))
  97. }
  98. switch param.ContractStatus { //协议上传
  99. case 1: //未归档
  100. orderSql = append(orderSql, `e.contract_status is null or e.contract_status = 0`)
  101. case 2: //已归档
  102. orderSql = append(orderSql, `e.contract_status = 1`)
  103. }
  104. }
  105. if len(param.ProductType) > 0 {
  106. productArr = append(productArr, fmt.Sprintf(" product_type in ('%s') ", strings.Join(param.ProductType, "','")))
  107. }
  108. if len(productArr) > 0 {
  109. productSql = fmt.Sprintf(` INNER JOIN (SELECT DISTINCT(order_code) FROM jy_order_detail WHERE %s and status =1) ptc on ptc.order_code = a.order_code `, strings.Join(productArr, " and "))
  110. }
  111. if param.SearchContent != "" {
  112. orderSql = append(orderSql, fmt.Sprintf(` (a.order_code = '%s' or a.company_name LIKE '%s' or a.user_phone LIKE '%s')`,
  113. param.SearchContent, `%`+param.SearchContent+`%`, `%`+param.SearchContent+`%`))
  114. }
  115. if len(param.CourseStatus) > 0 {
  116. var statusArr []string
  117. for _, status := range param.CourseStatus {
  118. switch status {
  119. case 4: //已退回
  120. statusArr = append(statusArr, "-2,-3,-4")
  121. case 5: //审核通过
  122. statusArr = append(statusArr, "4")
  123. default:
  124. statusArr = append(statusArr, gconv.String(status))
  125. }
  126. }
  127. orderSql = append(orderSql, fmt.Sprintf(" a.audit_status in (%s)", strings.Join(statusArr, ",")))
  128. }
  129. if len(param.OrderStatus) > 0 && len(param.OrderStatus) != 3 {
  130. orderSql = append(orderSql, fmt.Sprintf(" a.order_status in (%s)", strings.Join(param.OrderStatus, ",")))
  131. }
  132. if len(param.ReturnStatus) > 0 && len(param.ReturnStatus) != 3 {
  133. var isAllReturn bool
  134. for _, status := range param.ReturnStatus {
  135. if status == "1" {
  136. isAllReturn = true
  137. break
  138. }
  139. }
  140. if isAllReturn { //兼容线上已支付订单
  141. orderSql = append(orderSql, fmt.Sprintf("( a.return_status in (%s) or (a.order_status =1 and a.is_backstage_order =0) )", strings.Join(param.ReturnStatus, ",")))
  142. } else {
  143. orderSql = append(orderSql, fmt.Sprintf(" a.return_status in (%s)", strings.Join(param.ReturnStatus, ",")))
  144. }
  145. }
  146. if len(param.RefundStatus) > 0 && len(param.RefundStatus) != 3 {
  147. orderSql = append(orderSql, fmt.Sprintf(" a.refund_status in (%s)", strings.Join(param.RefundStatus, ",")))
  148. }
  149. /*switch len(param.InvoiceType) { //存在单选或2个选项是进行判断 全选或不选不进行where
  150. case 1: //单选发票方式
  151. for _, s := range param.InvoiceType {
  152. switch s {
  153. case 1: //未开票
  154. orderSql = append(orderSql, `b.order_code is null`)
  155. case 2: //部分开票
  156. orderSql = append(orderSql, `(b.order_code is not null and IFNULL(b.invoiced_amount, 0) < a.pay_money - a.commission)`)
  157. case 3:
  158. orderSql = append(orderSql, `(b.order_code is not null and IFNULL(b.invoiced_amount, 0) = a.pay_money - a.commission)`)
  159. }
  160. }
  161. case 2: //多选发票方式
  162. var isOne bool
  163. for _, s := range param.InvoiceType {
  164. if s == 1 {
  165. isOne = true
  166. }
  167. }
  168. if isOne { //存在未开发票选项
  169. for _, s := range param.InvoiceType {
  170. switch s {
  171. case 2: //部分开票
  172. orderSql = append(orderSql, `IFNULL(b.invoiced_amount, 0) < a.pay_money - a.commission - IFNULL(g.orderMoney, 0)`)
  173. case 3:
  174. orderSql = append(orderSql, `(b.order_code is null or IFNULL(b.invoiced_amount, 0) = a.pay_money - a.commission - IFNULL(g.orderMoney, 0))`)
  175. }
  176. }
  177. } else { //不存在未开发票选项
  178. orderSql = append(orderSql, `(b.order_code is not null and IFNULL(b.invoiced_amount, 0) <= a.pay_money - a.commission - IFNULL(g.orderMoney, 0))`)
  179. }
  180. }*/
  181. //发票状态;0 未申请 1 已申请 -2 已冲红(退款后发票冲红) 3 部分开票
  182. if len(param.InvoiceType) > 0 {
  183. var invoiceSql []string
  184. for _, iType := range param.InvoiceType {
  185. switch iType {
  186. case -2:
  187. invoiceSql = append(invoiceSql, " (a.refund_status = 1 and a.applybill_status = 1) ")
  188. default:
  189. invoiceSql = append(invoiceSql, fmt.Sprintf(" a.applybill_status =%d ", iType))
  190. }
  191. }
  192. orderSql = append(orderSql, fmt.Sprintf(` (%s) `, strings.Join(invoiceSql, " or ")))
  193. }
  194. if len(param.ContractType) == 1 {
  195. var statusArr []string
  196. for _, s := range param.ContractType {
  197. switch s {
  198. case 1: //未归档
  199. statusArr = append(statusArr, `e.contract_archive_status is null or e.contract_archive_status = 0`)
  200. case 2: //已归档
  201. statusArr = append(statusArr, `e.contract_archive_status = 1`)
  202. }
  203. }
  204. orderSql = append(orderSql, fmt.Sprintf("(%s)", strings.Join(statusArr, " or ")))
  205. }
  206. if param.OrderTimeStart != "" {
  207. orderSql = append(orderSql, fmt.Sprintf("a.create_time>='%s'", param.OrderTimeStart))
  208. }
  209. if param.OrderTimeEnd != "" {
  210. orderSql = append(orderSql, fmt.Sprintf("a.create_time<='%s'", param.OrderTimeEnd))
  211. }
  212. sqlWhere := `SELECT
  213. %s
  214. FROM
  215. dataexport_order a
  216. %s
  217. %s
  218. LEFT JOIN (
  219. SELECT
  220. order_code,
  221. SUM(invoice_money) AS invoiced_amount
  222. FROM
  223. invoice
  224. WHERE
  225. invoice_status = 1 and invoice_changed = 0
  226. GROUP BY
  227. order_code
  228. ) b ON a.order_code = b.order_code
  229. LEFT JOIN (
  230. SELECT
  231. order_code,
  232. SUM(return_money) AS return_money
  233. FROM
  234. return_money_record
  235. WHERE
  236. state = 1
  237. GROUP BY
  238. order_code
  239. ) c ON a.order_code = c.order_code
  240. LEFT JOIN (
  241. SELECT
  242. order_code,
  243. SUM(refund_money) AS refund_money
  244. FROM
  245. refund_record
  246. GROUP BY
  247. order_code
  248. ) d ON a.order_code = d.order_code
  249. LEFT JOIN contract e ON a.order_code = e.order_code
  250. LEFT JOIN (
  251. SELECT
  252. orderCode,
  253. SUM(orderMoney) AS orderMoney
  254. FROM
  255. moneyCorrection
  256. GROUP BY
  257. orderCode
  258. ) g ON a.order_code = g.orderCode
  259. LEFT JOIN entniche_user h on a.salesperson_entUserId = h.id
  260. %s`
  261. var whereSql string
  262. if len(orderSql) > 0 {
  263. whereSql = fmt.Sprintf(" where %s", strings.Join(orderSql, " and "))
  264. }
  265. //列表
  266. sql := fmt.Sprintf(sqlWhere, " a.id,\n a.order_code,\n a.personPhone,\n a.personName,\n a.create_time,\n a.order_money,\n a.company_name,\n a.user_phone,\n a.user_nickname,\n a.buy_subject,\n a.audit_status,\n a.order_status,\n a.pay_money - IFNULL(g.orderMoney, 0) as pay_money,\n a.commission,\n a.return_status,\n IFNULL(c.return_money, 0) as return_money,\n IFNULL(b.invoiced_amount, 0) as invoiced_amount,\n a.refund_status,\n IFNULL(d.refund_money, 0) as refund_money,\n e.contract_status,\n e.contract_time,\n e.contract_archive_status,\n e.contract_archive_time,\n h.name as ent_user_name", productSql, channelSql, whereSql)
  267. //数量
  268. sqlCount := fmt.Sprintf(sqlWhere, " count(1) ", productSql, channelSql, whereSql)
  269. //合同总金额
  270. sqlSum := fmt.Sprintf(sqlWhere, " sum(pay_money) as pay_money_sum ", productSql, channelSql, whereSql)
  271. log.Println("list count sql :", sqlCount)
  272. log.Println("list sql :", sql)
  273. count, err := g.DB().GetCount(ctx, sqlCount)
  274. if err != nil {
  275. log.Println("count err:=", err.Error())
  276. return nil, err
  277. }
  278. var sortClassify string
  279. switch param.SortClassify {
  280. case 1:
  281. sortClassify = " a.pay_money "
  282. case 2:
  283. sortClassify = " return_money "
  284. case 3:
  285. sortClassify = " invoiced_amount "
  286. case 4:
  287. sortClassify = " refund_money "
  288. case 5:
  289. sortClassify = " e.contract_time "
  290. case 6:
  291. sortClassify = " e.contract_archive_time "
  292. default:
  293. sortClassify = " a.create_time "
  294. }
  295. list, err := g.DB().Query(ctx, fmt.Sprintf(`%s order by %s %v LIMIT %d,%d`, sql, sortClassify, common.If(param.SortType == 1, " asc ", " desc "), (param.Page-1)*param.Size, param.Size))
  296. if err != nil {
  297. log.Println("list err:=", err.Error())
  298. return nil, err
  299. }
  300. var (
  301. listArr []map[string]interface{}
  302. payMoneySum int
  303. )
  304. for _, m := range list.List() {
  305. //代用户下单为线上单子 付款金额order_money
  306. if param.ListSource == 2 && m["pay_money"] == nil {
  307. m["pay_money"] = m["order_money"]
  308. }
  309. //未退款金额
  310. remainingAmount := gconv.Int(m["return_money"])
  311. returnAmount := gconv.Int(m["return_money"])
  312. if gconv.Int(m["is_backstage_order"]) == 0 && gconv.Int(m["order_status"]) == 1 &&
  313. gconv.Int(m["pay_money"]) > 0 && gconv.Int(m["return_status"]) == 0 {
  314. remainingAmount = gconv.Int(m["pay_money"])
  315. returnAmount = gconv.Int(m["pay_money"])
  316. m["return_money"] = returnAmount
  317. }
  318. //未回款金额
  319. m["no_return_money"] = gconv.Int(m["pay_money"]) - returnAmount
  320. m["no_refund_money"] = remainingAmount - gconv.Int(m["refund_money"])
  321. //开票
  322. noInvoicedAmount := gconv.Int(m["pay_money"]) - gconv.Int(m["invoiced_amount"])
  323. m["no_invoiced_amount"] = common.If(noInvoicedAmount < 0, 0, noInvoicedAmount) //未开票金额
  324. if gconv.Int(m["invoiced_amount"]) != 0 {
  325. m["invoiced_status"] = common.If(noInvoicedAmount <= 0, 2, 3)
  326. } else {
  327. m["invoiced_status"] = 0 //未开票
  328. }
  329. jyOrderDetail, _ := g.DB().Query(ctx, fmt.Sprintf(`SELECT jod.*,jpi.name FROM jy_order_detail jod
  330. LEFT JOIN jy_product_item jpi on jod.product_code = jpi.code
  331. WHERE jod.order_code = '%s' and jod.status =1 order by jod.final_price desc, jod.id desc`, gconv.String(m["order_code"])))
  332. if !jyOrderDetail.IsEmpty() {
  333. switch param.ListSource {
  334. case 1: //我的订单获取所有关联订单名称
  335. var productType []string
  336. for _, m2 := range jyOrderDetail.List() {
  337. if gconv.String(m2["productType"]) == "大会员" {
  338. productType = append(productType, gconv.String(m2["name"]))
  339. } else {
  340. productType = append(productType, gconv.String(m2["product_type"]))
  341. }
  342. }
  343. m["product_type"] = strings.Join(productType, ",")
  344. default:
  345. m["service_type"] = jyOrderDetail.List()[0]["service_type"]
  346. if gconv.String(jyOrderDetail.List()[0]["productType"]) == "大会员" {
  347. m["product_type"] = gconv.String(jyOrderDetail.List()[0]["name"])
  348. } else {
  349. m["product_type"] = gconv.String(jyOrderDetail.List()[0]["product_type"])
  350. }
  351. }
  352. }
  353. listArr = append(listArr, m)
  354. }
  355. sumData, _ := g.DB().GetOne(ctx, sqlSum)
  356. if !sumData.IsEmpty() {
  357. payMoneySum = gconv.Int(sumData.Map()["pay_money_sum"])
  358. }
  359. return map[string]interface{}{
  360. "count": count,
  361. "list": listArr,
  362. "payMoneySum": payMoneySum,
  363. }, nil
  364. }