附近小店
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.
 
 
 

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