附近小店
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

712 regels
20 KiB

  1. package svc
  2. import (
  3. "applet/app/db"
  4. "applet/app/db/model"
  5. "applet/app/e"
  6. "applet/app/enum"
  7. "applet/app/md"
  8. "applet/app/utils"
  9. "applet/app/utils/cache"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "github.com/gin-gonic/gin"
  14. "github.com/shopspring/decimal"
  15. "time"
  16. "xorm.io/xorm"
  17. )
  18. func OrderCate(c *gin.Context) {
  19. var cate = []map[string]string{
  20. {"name": "全部", "value": ""},
  21. {"name": "待付款", "value": "0"},
  22. {"name": "待提货", "value": "1"},
  23. {"name": "已完成", "value": "2"},
  24. {"name": "已取消", "value": "3"},
  25. }
  26. e.OutSuc(c, cate, nil)
  27. return
  28. }
  29. func OrderList(c *gin.Context) {
  30. var arg map[string]string
  31. if err := c.ShouldBindJSON(&arg); err != nil {
  32. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  33. return
  34. }
  35. user := GetUser(c)
  36. arg["uid"] = utils.IntToStr(user.Info.Uid)
  37. data := db.GetOrderList(MasterDb(c), arg)
  38. var state = []string{"待付款", "待提货", "已完成", "已取消"}
  39. list := make([]map[string]interface{}, 0)
  40. if data != nil {
  41. now := time.Now().Unix()
  42. for _, v := range *data {
  43. store := db.GetStoreIdEg(MasterDb(c), utils.IntToStr(v.StoreUid))
  44. info := db.GetOrderInfoAllEg(MasterDb(c), utils.Int64ToStr(v.Oid))
  45. goodsInfo := make([]map[string]string, 0)
  46. if info != nil {
  47. for _, v1 := range *info {
  48. tmp := map[string]string{
  49. "img": v1.Img,
  50. "title": v1.Title,
  51. "sku_str": "",
  52. }
  53. skuData := make([]md.Sku, 0)
  54. json.Unmarshal([]byte(v1.SkuInfo), &skuData)
  55. skuStr := ""
  56. for _, v2 := range skuData {
  57. if skuStr != "" {
  58. skuStr += ";"
  59. }
  60. skuStr += v2.Value
  61. }
  62. tmp["sku_str"] = skuStr
  63. goodsInfo = append(goodsInfo, tmp)
  64. }
  65. }
  66. downTime := "0"
  67. if v.State == 0 {
  68. downTime = utils.IntToStr(int(v.CreateAt.Unix() + 15*60 - now))
  69. if now > v.CreateAt.Unix()+15*60 {
  70. v.State = 3
  71. }
  72. if utils.StrToInt(downTime) < 0 {
  73. downTime = "0"
  74. }
  75. }
  76. storeName := ""
  77. if store != nil {
  78. storeName = store.Name
  79. }
  80. tmp := map[string]interface{}{
  81. "oid": utils.Int64ToStr(v.Oid),
  82. "label": "自提",
  83. "state": utils.IntToStr(v.State),
  84. "state_str": state[v.State],
  85. "store_name": storeName,
  86. "goods_info": goodsInfo,
  87. "amount": v.Amount,
  88. "num": utils.IntToStr(v.Num),
  89. "timer": "",
  90. "code": v.Code,
  91. "down_time": downTime,
  92. }
  93. if v.Type == 1 {
  94. tmp["label"] = "外卖"
  95. }
  96. if v.IsNow == 1 {
  97. tmp["timer"] = "立即提货"
  98. } else if v.Timer != "" {
  99. tmp["timer"] = "提货时间:" + v.Timer
  100. }
  101. list = append(list, tmp)
  102. }
  103. }
  104. e.OutSuc(c, list, nil)
  105. return
  106. }
  107. func OrderDetail(c *gin.Context) {
  108. var arg map[string]string
  109. if err := c.ShouldBindJSON(&arg); err != nil {
  110. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  111. return
  112. }
  113. data := db.GetOrderEg(MasterDb(c), arg["oid"])
  114. var state = []string{"待付款", "待提货", "已完成", "已取消"}
  115. now := time.Now().Unix()
  116. store := db.GetStoreIdEg(MasterDb(c), utils.IntToStr(data.StoreUid))
  117. downTime := "0"
  118. if data.State == 0 {
  119. downTime = utils.IntToStr(int(data.CreateAt.Unix() + 15*60 - now))
  120. if now > data.CreateAt.Unix()+15*60 {
  121. data.State = 3
  122. }
  123. if utils.StrToInt(downTime) < 0 {
  124. downTime = "0"
  125. }
  126. }
  127. storeName := ""
  128. storeAddress := ""
  129. lat := ""
  130. lng := ""
  131. km := ""
  132. if store != nil {
  133. storeName = store.Name
  134. storeAddress = store.Address
  135. lat = store.Lat
  136. lng = store.Lng
  137. km = ""
  138. if arg["lat"] != "" && arg["lng"] != "" {
  139. km1 := utils.CalculateDistance(utils.StrToFloat64(lat), utils.StrToFloat64(lng), utils.StrToFloat64(arg["lat"]), utils.StrToFloat64(arg["lng"]))
  140. if km1 < 1 {
  141. km = utils.Float64ToStr(km1*1000) + "m"
  142. } else {
  143. km = utils.Float64ToStr(km1) + "km"
  144. }
  145. }
  146. }
  147. confirmAt := ""
  148. if data.ConfirmAt.IsZero() == false {
  149. confirmAt = data.ConfirmAt.Format("2006-01-02 15:04:05")
  150. }
  151. payMethod := "-"
  152. if data.PayMethod > 0 {
  153. payMethod = md.PayMethodIdToName[data.PayMethod]
  154. }
  155. orderInfo := []map[string]string{
  156. {"title": "订单编号", "content": utils.Int64ToStr(data.Oid)},
  157. {"title": "下单时间", "content": data.CreateAt.Format("2006-01-02 15:04:05")},
  158. {"title": "提货时间", "content": confirmAt},
  159. {"title": "预留电话", "content": data.Phone},
  160. {"title": "支付方式", "content": payMethod},
  161. {"title": "备注信息", "content": data.Memo},
  162. }
  163. goodsInfo := make([]map[string]string, 0)
  164. info := db.GetOrderInfoAllEg(MasterDb(c), utils.Int64ToStr(data.Oid))
  165. if info != nil {
  166. for _, v := range *info {
  167. tmp := map[string]string{
  168. "img": v.Img,
  169. "title": v.Title,
  170. "price": v.Price,
  171. "num": utils.IntToStr(v.Num),
  172. "sku_str": "",
  173. }
  174. skuData := make([]md.Sku, 0)
  175. json.Unmarshal([]byte(v.SkuInfo), &skuData)
  176. skuStr := ""
  177. for _, v1 := range skuData {
  178. if skuStr != "" {
  179. skuStr += ";"
  180. }
  181. skuStr += v1.Value
  182. }
  183. tmp["sku_str"] = skuStr
  184. goodsInfo = append(goodsInfo, tmp)
  185. }
  186. }
  187. tmp := map[string]interface{}{
  188. "oid": utils.Int64ToStr(data.Oid),
  189. "label": "自提",
  190. "state": utils.IntToStr(data.State),
  191. "state_str": state[data.State],
  192. "store_name": storeName,
  193. "store_address": storeAddress,
  194. "lat": lat,
  195. "lng": lng,
  196. "km": km,
  197. "amount": data.Amount,
  198. "num": utils.IntToStr(data.Num),
  199. "timer": "",
  200. "code": data.Code,
  201. "down_time": downTime,
  202. "order_info": orderInfo,
  203. "goods_info": goodsInfo,
  204. "goods_count": utils.IntToStr(len(goodsInfo)),
  205. }
  206. if data.Type == 1 {
  207. tmp["label"] = "外卖"
  208. }
  209. if data.IsNow == 1 {
  210. tmp["timer"] = "立即提货"
  211. } else if data.Timer != "" {
  212. tmp["timer"] = data.Timer
  213. }
  214. e.OutSuc(c, tmp, nil)
  215. return
  216. }
  217. func OrderCoupon(c *gin.Context) {
  218. var arg md.OrderTotal
  219. if err := c.ShouldBindJSON(&arg); err != nil {
  220. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  221. return
  222. }
  223. totalPrice := commGoods(c, arg)
  224. returnData := CommCoupon(c, totalPrice)
  225. e.OutSuc(c, returnData, nil)
  226. return
  227. }
  228. func CommCoupon(c *gin.Context, totalPrice string) map[string]interface{} {
  229. var err error
  230. engine := MasterDb(c)
  231. user := GetUser(c)
  232. now := time.Now().Format("2006-01-02 15:04:05")
  233. var ActCouponUserList []*model.CommunityTeamCouponUser
  234. sess := engine.Table("act_coupon_user").
  235. Where("store_type=? and uid = ? AND is_use = ? AND (valid_time_start < ? AND valid_time_end > ?)", 0,
  236. user.Info.Uid, 0, now, now)
  237. err = sess.Find(&ActCouponUserList)
  238. if err != nil {
  239. return map[string]interface{}{}
  240. }
  241. var ids = make([]int, 0)
  242. for _, v := range ActCouponUserList {
  243. ids = append(ids, v.MerchantSchemeId)
  244. }
  245. var merchantScheme []model.CommunityTeamCoupon
  246. engine.In("id", ids).Find(&merchantScheme)
  247. var merchantSchemeMap = make(map[int]model.CommunityTeamCoupon)
  248. for _, v := range merchantScheme {
  249. merchantSchemeMap[v.Id] = v
  250. }
  251. var couponList []md.CouponList // 可使用的
  252. couponList = make([]md.CouponList, 0)
  253. count := 0
  254. for _, item := range ActCouponUserList {
  255. var coupon = md.CouponList{
  256. Id: utils.Int64ToStr(item.Id),
  257. Title: item.Name,
  258. Timer: item.ValidTimeStart.Format("2006.01.02") + "-" + item.ValidTimeEnd.Format("2006.01.02"),
  259. Label: "全部商品可用",
  260. Img: item.Img,
  261. Content: item.ActivityStatement,
  262. IsCanUse: "0",
  263. NotUseStr: "",
  264. }
  265. var cal struct {
  266. Reach string `json:"reach"`
  267. Reduce string `json:"reduce"`
  268. }
  269. err = json.Unmarshal([]byte(item.Cal), &cal)
  270. if err != nil {
  271. return map[string]interface{}{}
  272. }
  273. switch item.Kind {
  274. case int(enum.ActCouponTypeImmediate):
  275. if utils.AnyToFloat64(totalPrice) >= utils.AnyToFloat64(cal.Reduce) {
  276. coupon.IsCanUse = "1"
  277. }
  278. case int(enum.ActCouponTypeReachReduce):
  279. if utils.AnyToFloat64(totalPrice) >= utils.AnyToFloat64(cal.Reduce) {
  280. coupon.IsCanUse = "1"
  281. }
  282. case int(enum.ActCouponTypeReachDiscount):
  283. if utils.AnyToFloat64(totalPrice) >= utils.AnyToFloat64(cal.Reduce) && utils.AnyToFloat64(cal.Reduce) > 0 {
  284. coupon.IsCanUse = "1"
  285. }
  286. if utils.AnyToFloat64(cal.Reduce) == 0 {
  287. coupon.IsCanUse = "1"
  288. }
  289. }
  290. if coupon.IsCanUse != "1" {
  291. coupon.NotUseStr = "订单金额未满" + cal.Reduce + "元"
  292. }
  293. if coupon.IsCanUse == "1" {
  294. count++
  295. }
  296. couponList = append(couponList, coupon)
  297. }
  298. returnData := map[string]interface{}{
  299. "total": utils.IntToStr(count),
  300. "coupon_list": couponList,
  301. }
  302. return returnData
  303. }
  304. func OrderCancel(c *gin.Context) {
  305. var arg map[string]string
  306. if err := c.ShouldBindJSON(&arg); err != nil {
  307. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  308. return
  309. }
  310. // 加锁 防止并发提取
  311. mutexKey := fmt.Sprintf("%s:team.OrderCancel:%s", c.GetString("mid"), arg["oid"])
  312. withdrawAvailable, err := cache.Do("SET", mutexKey, 1, "EX", 5, "NX")
  313. if err != nil {
  314. e.OutErr(c, e.ERR, err)
  315. return
  316. }
  317. if withdrawAvailable != "OK" {
  318. e.OutErr(c, e.ERR, e.NewErr(400000, "请求过于频繁,请稍后再试"))
  319. return
  320. }
  321. sess := MasterDb(c).NewSession()
  322. defer sess.Close()
  323. sess.Begin()
  324. order := db.GetOrder(sess, arg["oid"])
  325. if order == nil {
  326. sess.Rollback()
  327. e.OutErr(c, 400, e.NewErr(400, "订单不存在"))
  328. return
  329. }
  330. if order.State > 0 {
  331. sess.Rollback()
  332. e.OutErr(c, 400, e.NewErr(400, "订单不能取消"))
  333. return
  334. }
  335. orderInfo := db.GetOrderInfo(sess, arg["oid"])
  336. if orderInfo != nil {
  337. goodsMap := make(map[int]int)
  338. skuMap := make(map[int]int)
  339. for _, v := range *orderInfo {
  340. goodsMap[v.GoodsId] += v.Num
  341. skuMap[v.SkuId] += v.Num
  342. }
  343. for k, v := range goodsMap {
  344. sql := `update community_team_goods set stock=stock+%d where id=%d`
  345. sql = fmt.Sprintf(sql, v, k)
  346. _, err := db.QueryNativeStringWithSess(sess, sql)
  347. if err != nil {
  348. sess.Rollback()
  349. e.OutErr(c, 400, e.NewErr(400, "订单取消失败"))
  350. return
  351. }
  352. }
  353. for k, v := range skuMap {
  354. sql := `update community_team_sku set stock=stock+%d where sku_id=%d`
  355. sql = fmt.Sprintf(sql, v, k)
  356. _, err := db.QueryNativeStringWithSess(sess, sql)
  357. if err != nil {
  358. sess.Rollback()
  359. e.OutErr(c, 400, e.NewErr(400, "订单取消失败"))
  360. return
  361. }
  362. }
  363. }
  364. order.State = 3
  365. order.UpdateAt = time.Now()
  366. update, err := sess.Where("id=?", order.Id).Cols("state,update_at").Update(order)
  367. if update == 0 || err != nil {
  368. sess.Rollback()
  369. e.OutErr(c, 400, e.NewErr(400, "订单取消失败"))
  370. return
  371. }
  372. if order.CouponId > 0 {
  373. update, err = sess.Where("id=?", order.CouponId).Cols("is_use").Update(&model.CommunityTeamCouponUser{IsUse: 0})
  374. if update == 0 || err != nil {
  375. sess.Rollback()
  376. e.OutErr(c, 400, e.NewErr(400, "订单取消失败"))
  377. return
  378. }
  379. }
  380. sess.Commit()
  381. e.OutSuc(c, "success", nil)
  382. return
  383. }
  384. func OrderConfirm(c *gin.Context) {
  385. var arg map[string]string
  386. if err := c.ShouldBindJSON(&arg); err != nil {
  387. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  388. return
  389. }
  390. // 加锁 防止并发提取
  391. mutexKey := fmt.Sprintf("%s:team.OrderConfirm:%s", c.GetString("mid"), arg["oid"])
  392. withdrawAvailable, err := cache.Do("SET", mutexKey, 1, "EX", 5, "NX")
  393. if err != nil {
  394. e.OutErr(c, e.ERR, err)
  395. return
  396. }
  397. if withdrawAvailable != "OK" {
  398. e.OutErr(c, e.ERR, e.NewErr(400000, "请求过于频繁,请稍后再试"))
  399. return
  400. }
  401. sess := MasterDb(c).NewSession()
  402. defer sess.Close()
  403. sess.Begin()
  404. order := db.GetOrder(sess, arg["oid"])
  405. if order == nil {
  406. sess.Rollback()
  407. e.OutErr(c, 400, e.NewErr(400, "订单不存在"))
  408. return
  409. }
  410. if order.State != 1 {
  411. sess.Rollback()
  412. e.OutErr(c, 400, e.NewErr(400, "订单不能确认收货"))
  413. return
  414. }
  415. order.State = 2
  416. order.UpdateAt = time.Now()
  417. update, err := sess.Where("id=?", order.Id).Cols("state,update_at").Update(order)
  418. if update == 0 || err != nil {
  419. sess.Rollback()
  420. e.OutErr(c, 400, e.NewErr(400, "订单取消失败"))
  421. return
  422. }
  423. sess.Commit()
  424. e.OutSuc(c, "success", nil)
  425. return
  426. }
  427. func OrderCreate(c *gin.Context) {
  428. var arg md.OrderTotal
  429. if err := c.ShouldBindJSON(&arg); err != nil {
  430. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  431. return
  432. }
  433. user := GetUser(c)
  434. // 加锁 防止并发提取
  435. mutexKey := fmt.Sprintf("%s:team.OrderCreate:%s", c.GetString("mid"), utils.IntToStr(user.Info.Uid))
  436. withdrawAvailable, err := cache.Do("SET", mutexKey, 1, "EX", 5, "NX")
  437. if err != nil {
  438. e.OutErr(c, e.ERR, err)
  439. return
  440. }
  441. if withdrawAvailable != "OK" {
  442. e.OutErr(c, e.ERR, e.NewErr(400000, "请求过于频繁,请稍后再试"))
  443. return
  444. }
  445. sess := MasterDb(c).NewSession()
  446. defer sess.Close()
  447. err = sess.Begin()
  448. if err != nil {
  449. e.OutErr(c, 400, err.Error())
  450. return
  451. }
  452. totalPrice := commGoods(c, arg)
  453. coupon := "0"
  454. totalPrice, coupon, err = CouponProcess(c, sess, totalPrice, arg)
  455. if err != nil {
  456. sess.Rollback()
  457. e.OutErr(c, 400, err.Error())
  458. return
  459. }
  460. ordId := utils.OrderUUID(user.Info.Uid)
  461. // 获取店铺信息
  462. store := db.GetStoreId(sess, arg.StoreId)
  463. num := 0
  464. for _, item := range arg.GoodsInfo {
  465. num += utils.StrToInt(item.Num)
  466. }
  467. var order = &model.CommunityTeamOrder{
  468. Uid: user.Info.Uid,
  469. StoreUid: utils.StrToInt(arg.StoreId),
  470. Commission: utils.Float64ToStr(utils.FloatFormat(utils.AnyToFloat64(totalPrice)*(utils.AnyToFloat64(store.Commission)/100), 2)),
  471. CreateAt: time.Now(),
  472. UpdateAt: time.Now(),
  473. BuyPhone: arg.BuyPhone,
  474. Coupon: coupon,
  475. Num: num,
  476. IsNow: utils.StrToInt(arg.IsNow),
  477. Timer: arg.Timer,
  478. Memo: arg.Memo,
  479. Oid: utils.StrToInt64(ordId),
  480. Amount: totalPrice,
  481. MealNum: utils.StrToInt(arg.MealNum),
  482. }
  483. if utils.StrToFloat64(coupon) > 0 {
  484. order.CouponId = utils.StrToInt(arg.CouponId)
  485. }
  486. insert, err := sess.Insert(order)
  487. if insert == 0 || err != nil {
  488. sess.Rollback()
  489. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  490. return
  491. }
  492. for _, item := range arg.GoodsInfo {
  493. // 获取详细信息
  494. goodsInterface, has, err := db.GetComm(MasterDb(c), &model.CommunityTeamGoods{Id: utils.StrToInt(item.GoodsId)})
  495. if err != nil || !has {
  496. sess.Rollback()
  497. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  498. return
  499. }
  500. goodsModel := goodsInterface.(*model.CommunityTeamGoods)
  501. var skuInterface interface{}
  502. if item.SkuId != "-1" {
  503. skuInterface, _, _ = db.GetComm(MasterDb(c), &model.CommunityTeamSku{GoodsId: utils.StrToInt(item.GoodsId), SkuId: utils.StrToInt64(item.SkuId)})
  504. } else {
  505. skuInterface, _, _ = db.GetComm(MasterDb(c), &model.CommunityTeamSku{GoodsId: utils.StrToInt(item.GoodsId)})
  506. }
  507. if err != nil || !has {
  508. sess.Rollback()
  509. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  510. return
  511. }
  512. skuModel := skuInterface.(*model.CommunityTeamSku)
  513. var goodsSaleCount int
  514. // 走普通逻辑
  515. stock := skuModel.Stock - utils.StrToInt(item.Num)
  516. saleCount := skuModel.SaleCount + utils.StrToInt(item.Num)
  517. goodsSaleCount = goodsModel.SaleCount + utils.StrToInt(item.Num)
  518. if stock < 0 {
  519. sess.Rollback()
  520. e.OutErr(c, 400, e.NewErr(400, "库存不足"))
  521. return
  522. }
  523. update, err := sess.Where("sku_id=?", skuModel.SkuId).Cols("stock", "sale_count").Update(&model.CommunityTeamSku{Stock: stock, SaleCount: saleCount})
  524. if err != nil {
  525. sess.Rollback()
  526. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  527. return
  528. }
  529. if update != 1 {
  530. sess.Rollback()
  531. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  532. return
  533. }
  534. // 更新销量
  535. goodsModel.SaleCount = goodsSaleCount
  536. goodsModel.Stock = goodsModel.Stock - utils.StrToInt(item.Num)
  537. _, err = sess.Where("id = ?", goodsModel.Id).Cols("sale_count,stock").Update(goodsModel)
  538. if err != nil {
  539. sess.Rollback()
  540. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  541. return
  542. }
  543. // 插入订单
  544. insert, err := sess.Insert(&model.CommunityTeamOrderInfo{
  545. Oid: utils.StrToInt64(ordId),
  546. Title: goodsModel.Title,
  547. Img: goodsModel.Img,
  548. Price: skuModel.Price,
  549. Num: utils.StrToInt(item.Num),
  550. SkuInfo: skuModel.Sku,
  551. GoodsId: skuModel.GoodsId,
  552. SkuId: int(skuModel.SkuId),
  553. })
  554. if err != nil {
  555. sess.Rollback()
  556. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  557. return
  558. }
  559. if insert != 1 {
  560. sess.Rollback()
  561. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  562. return
  563. }
  564. }
  565. // 更新优惠券使用状态
  566. if utils.StrToInt(arg.CouponId) > 0 {
  567. affect, err := sess.Where("id = ?", arg.CouponId).
  568. Update(&model.CommunityTeamCouponUser{IsUse: 1})
  569. if err != nil {
  570. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  571. return
  572. }
  573. if affect != 1 {
  574. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  575. return
  576. }
  577. }
  578. err = sess.Commit()
  579. if err != nil {
  580. sess.Rollback()
  581. e.OutErr(c, 400, err.Error())
  582. return
  583. }
  584. sess.Commit()
  585. e.OutSuc(c, map[string]string{"oid": ordId}, nil)
  586. return
  587. }
  588. func OrderTotal(c *gin.Context) {
  589. var arg md.OrderTotal
  590. if err := c.ShouldBindJSON(&arg); err != nil {
  591. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  592. return
  593. }
  594. sess := MasterDb(c).NewSession()
  595. defer sess.Close()
  596. err := sess.Begin()
  597. if err != nil {
  598. e.OutErr(c, 400, err.Error())
  599. return
  600. }
  601. totalPrice := commGoods(c, arg)
  602. oldTotalPrice := totalPrice
  603. coupon := "0"
  604. totalPrice, coupon, err = CouponProcess(c, sess, totalPrice, arg)
  605. if err != nil {
  606. sess.Rollback()
  607. e.OutErr(c, 400, err.Error())
  608. return
  609. }
  610. user := GetUser(c)
  611. result := map[string]interface{}{
  612. "balance_money": GetCommissionPrec(c, user.Profile.FinValid, SysCfgGet(c, "commission_prec"), SysCfgGet(c, "is_show_point")),
  613. "small_amount": GetCommissionPrec(c, oldTotalPrice, SysCfgGet(c, "commission_prec"), SysCfgGet(c, "is_show_point")),
  614. "all_amount": GetCommissionPrec(c, totalPrice, SysCfgGet(c, "commission_prec"), SysCfgGet(c, "is_show_point")),
  615. "coupon": GetCommissionPrec(c, coupon, SysCfgGet(c, "commission_prec"), SysCfgGet(c, "is_show_point")),
  616. }
  617. sess.Commit()
  618. e.OutSuc(c, result, nil)
  619. return
  620. }
  621. func CouponProcess(c *gin.Context, sess *xorm.Session, total string, args md.OrderTotal) (string, string, error) {
  622. if utils.StrToInt(args.CouponId) == 0 {
  623. return total, "0", nil
  624. }
  625. now := time.Now().Format("2006-01-02 15:04:05")
  626. user := GetUser(c)
  627. var goodsIds []int
  628. var skuIds []string
  629. for _, item := range args.GoodsInfo {
  630. goodsIds = append(goodsIds, utils.StrToInt(item.GoodsId))
  631. skuIds = append(skuIds, utils.AnyToString(item.SkuId))
  632. }
  633. // 获取优惠券信息
  634. var mallUserCoupon model.CommunityTeamCouponUser
  635. isExist, err := sess.
  636. Where("id = ? AND uid = ? AND is_use = ? AND (valid_time_start < ? AND valid_time_end > ?)", args.CouponId, user.Info.Uid, 0, now, now).
  637. Get(&mallUserCoupon)
  638. if err != nil {
  639. return "", "", err
  640. }
  641. if !isExist {
  642. return "", "", errors.New("无相关优惠券信息")
  643. }
  644. var cal struct {
  645. Reach string `json:"reach"`
  646. Reduce string `json:"reduce"`
  647. }
  648. _ = json.Unmarshal([]byte(mallUserCoupon.Cal), &cal)
  649. reach, err := decimal.NewFromString(cal.Reach)
  650. reduce, err := decimal.NewFromString(cal.Reduce)
  651. if err != nil {
  652. return "", "", err
  653. }
  654. var specialTotal = total
  655. // 是否满足优惠条件
  656. if !reach.IsZero() { // 满减及有门槛折扣
  657. if utils.StrToFloat64(specialTotal) < utils.StrToFloat64(reach.String()) {
  658. return "", "", errors.New("不满足优惠条件")
  659. }
  660. } else {
  661. if mallUserCoupon.Kind == 1 { //立减
  662. if utils.StrToFloat64(specialTotal) < utils.StrToFloat64(reduce.String()) {
  663. return "", "", errors.New("付款金额有误")
  664. }
  665. }
  666. }
  667. // 计算优惠后支付金额
  668. couponTotal := "0"
  669. if mallUserCoupon.Kind == int(enum.ActCouponTypeImmediate) ||
  670. mallUserCoupon.Kind == int(enum.ActCouponTypeReachReduce) { // 立减 || 满减
  671. couponTotal = reduce.String()
  672. total = utils.Float64ToStr(utils.StrToFloat64(total) - utils.StrToFloat64(reduce.String()))
  673. } else { // 折扣
  674. couponTotal = utils.Float64ToStr(utils.StrToFloat64(total) - utils.StrToFloat64(total)*utils.StrToFloat64(reduce.String())/10)
  675. total = utils.Float64ToStr(utils.StrToFloat64(total) * utils.StrToFloat64(reduce.String()) / 10)
  676. }
  677. return total, couponTotal, nil
  678. }
  679. func commGoods(c *gin.Context, arg md.OrderTotal) (totalPrice string) {
  680. engine := MasterDb(c)
  681. var totalPriceAmt float64 = 0
  682. for _, item := range arg.GoodsInfo {
  683. goodsInterface, _, _ := db.GetComm(engine, &model.CommunityTeamGoods{Id: utils.StrToInt(item.GoodsId)})
  684. goodsModel := goodsInterface.(*model.CommunityTeamGoods)
  685. var skuInterface interface{}
  686. if item.SkuId != "-1" {
  687. skuInterface, _, _ = db.GetComm(engine, &model.CommunityTeamSku{GoodsId: utils.StrToInt(item.GoodsId), SkuId: utils.StrToInt64(item.SkuId)})
  688. } else {
  689. skuInterface, _, _ = db.GetComm(engine, &model.CommunityTeamSku{GoodsId: utils.StrToInt(item.GoodsId)})
  690. }
  691. skuModel := skuInterface.(*model.CommunityTeamSku)
  692. priceOne := goodsModel.Price
  693. if item.SkuId != "-1" {
  694. priceOne = skuModel.Price
  695. }
  696. totalPriceAmt += utils.StrToFloat64(priceOne) * utils.StrToFloat64(item.Num)
  697. }
  698. return utils.Float64ToStr(totalPriceAmt)
  699. }