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

758 lines
22 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. couponList := make([]md.CouponList, 0)
  232. storeId := c.GetHeader("store_id")
  233. if utils.StrToInt(storeId) > 0 {
  234. returnData := map[string]interface{}{
  235. "total": "0",
  236. "coupon_list": couponList,
  237. }
  238. return returnData
  239. }
  240. var err error
  241. engine := MasterDb(c)
  242. user := GetUser(c)
  243. now := time.Now().Format("2006-01-02 15:04:05")
  244. var ActCouponUserList []*model.CommunityTeamCouponUser
  245. sess := engine.
  246. Where("store_type=? and uid = ? AND is_use = ? AND (valid_time_start < ? AND valid_time_end > ?)", 0,
  247. user.Info.Uid, 1, now, now)
  248. err = sess.Limit(100).OrderBy("valid_time_end asc,id asc").Find(&ActCouponUserList)
  249. if err != nil {
  250. return map[string]interface{}{}
  251. }
  252. var ids = make([]int, 0)
  253. for _, v := range ActCouponUserList {
  254. ids = append(ids, v.MerchantSchemeId)
  255. }
  256. var merchantScheme []model.CommunityTeamCoupon
  257. engine.In("id", ids).Find(&merchantScheme)
  258. var merchantSchemeMap = make(map[int]model.CommunityTeamCoupon)
  259. for _, v := range merchantScheme {
  260. merchantSchemeMap[v.Id] = v
  261. }
  262. notCouponList := make([]md.CouponList, 0)
  263. count := 0
  264. for _, item := range ActCouponUserList {
  265. var coupon = md.CouponList{
  266. Id: utils.Int64ToStr(item.Id),
  267. Title: item.Name,
  268. Timer: item.ValidTimeStart.Format("2006.01.02") + "-" + item.ValidTimeEnd.Format("2006.01.02"),
  269. Label: "全部商品可用",
  270. Img: item.Img,
  271. Content: item.Info,
  272. Info: item.Info,
  273. IsCanUse: "0",
  274. NotUseStr: "",
  275. }
  276. var cal struct {
  277. Reach string `json:"reach"`
  278. Reduce string `json:"reduce"`
  279. }
  280. err = json.Unmarshal([]byte(item.Cal), &cal)
  281. if err != nil {
  282. return map[string]interface{}{}
  283. }
  284. switch item.Kind {
  285. case int(enum.ActCouponTypeImmediate):
  286. if utils.AnyToFloat64(totalPrice) >= utils.AnyToFloat64(cal.Reduce) {
  287. coupon.IsCanUse = "1"
  288. }
  289. case int(enum.ActCouponTypeReachReduce):
  290. if utils.AnyToFloat64(totalPrice) >= utils.AnyToFloat64(cal.Reduce) {
  291. coupon.IsCanUse = "1"
  292. }
  293. case int(enum.ActCouponTypeReachDiscount):
  294. if utils.AnyToFloat64(totalPrice) >= utils.AnyToFloat64(cal.Reduce) && utils.AnyToFloat64(cal.Reduce) > 0 {
  295. coupon.IsCanUse = "1"
  296. }
  297. if utils.AnyToFloat64(cal.Reduce) == 0 {
  298. coupon.IsCanUse = "1"
  299. }
  300. }
  301. if coupon.IsCanUse != "1" {
  302. coupon.NotUseStr = "订单金额未满" + cal.Reduce + "元"
  303. }
  304. if coupon.IsCanUse == "1" {
  305. count++
  306. couponList = append(couponList, coupon)
  307. } else {
  308. notCouponList = append(notCouponList, coupon)
  309. }
  310. }
  311. for _, v := range notCouponList {
  312. couponList = append(couponList, v)
  313. }
  314. returnData := map[string]interface{}{
  315. "total": utils.IntToStr(count),
  316. "coupon_list": couponList,
  317. }
  318. return returnData
  319. }
  320. func OrderCancel(c *gin.Context) {
  321. var arg map[string]string
  322. if err := c.ShouldBindJSON(&arg); err != nil {
  323. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  324. return
  325. }
  326. // 加锁 防止并发提取
  327. mutexKey := fmt.Sprintf("%s:team.OrderCancel:%s", c.GetString("mid"), arg["oid"])
  328. withdrawAvailable, err := cache.Do("SET", mutexKey, 1, "EX", 5, "NX")
  329. if err != nil {
  330. e.OutErr(c, e.ERR, err)
  331. return
  332. }
  333. if withdrawAvailable != "OK" {
  334. e.OutErr(c, e.ERR, e.NewErr(400000, "请求过于频繁,请稍后再试"))
  335. return
  336. }
  337. sess := MasterDb(c).NewSession()
  338. defer sess.Close()
  339. sess.Begin()
  340. order := db.GetOrder(sess, arg["oid"])
  341. if order == nil {
  342. sess.Rollback()
  343. e.OutErr(c, 400, e.NewErr(400, "订单不存在"))
  344. return
  345. }
  346. if order.State == 0 {
  347. now := time.Now().Unix()
  348. if now > order.CreateAt.Unix()+15*60 {
  349. order.State = 3
  350. }
  351. }
  352. if order.State > 0 {
  353. sess.Rollback()
  354. e.OutErr(c, 400, e.NewErr(400, "订单不能取消"))
  355. return
  356. }
  357. orderInfo := db.GetOrderInfo(sess, arg["oid"])
  358. if orderInfo != nil {
  359. goodsMap := make(map[int]int)
  360. skuMap := make(map[int]int)
  361. for _, v := range *orderInfo {
  362. goodsMap[v.GoodsId] += v.Num
  363. skuMap[v.SkuId] += v.Num
  364. }
  365. for k, v := range goodsMap {
  366. sql := `update community_team_goods set stock=stock+%d where id=%d`
  367. sql = fmt.Sprintf(sql, v, k)
  368. _, err := db.QueryNativeStringWithSess(sess, sql)
  369. if err != nil {
  370. sess.Rollback()
  371. e.OutErr(c, 400, e.NewErr(400, "订单取消失败"))
  372. return
  373. }
  374. }
  375. for k, v := range skuMap {
  376. sql := `update community_team_sku set stock=stock+%d where sku_id=%d`
  377. sql = fmt.Sprintf(sql, v, k)
  378. _, err := db.QueryNativeStringWithSess(sess, sql)
  379. if err != nil {
  380. sess.Rollback()
  381. e.OutErr(c, 400, e.NewErr(400, "订单取消失败"))
  382. return
  383. }
  384. }
  385. }
  386. order.State = 3
  387. order.UpdateAt = time.Now()
  388. order.CancelAt = time.Now()
  389. update, err := sess.Where("id=?", order.Id).Cols("state,update_at,cancel_at").Update(order)
  390. if update == 0 || err != nil {
  391. sess.Rollback()
  392. e.OutErr(c, 400, e.NewErr(400, "订单取消失败"))
  393. return
  394. }
  395. if order.CouponId > 0 {
  396. update, err = sess.Where("id=?", order.CouponId).Cols("is_use").Update(&model.CommunityTeamCouponUser{IsUse: 0})
  397. if update == 0 || err != nil {
  398. sess.Rollback()
  399. e.OutErr(c, 400, e.NewErr(400, "订单取消失败"))
  400. return
  401. }
  402. }
  403. sess.Commit()
  404. e.OutSuc(c, "success", nil)
  405. return
  406. }
  407. func OrderConfirm(c *gin.Context) {
  408. var arg map[string]string
  409. if err := c.ShouldBindJSON(&arg); err != nil {
  410. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  411. return
  412. }
  413. // 加锁 防止并发提取
  414. mutexKey := fmt.Sprintf("%s:team.OrderConfirm:%s", c.GetString("mid"), arg["oid"])
  415. withdrawAvailable, err := cache.Do("SET", mutexKey, 1, "EX", 5, "NX")
  416. if err != nil {
  417. e.OutErr(c, e.ERR, err)
  418. return
  419. }
  420. if withdrawAvailable != "OK" {
  421. e.OutErr(c, e.ERR, e.NewErr(400000, "请求过于频繁,请稍后再试"))
  422. return
  423. }
  424. sess := MasterDb(c).NewSession()
  425. defer sess.Close()
  426. sess.Begin()
  427. order := db.GetOrder(sess, arg["oid"])
  428. if order == nil {
  429. sess.Rollback()
  430. e.OutErr(c, 400, e.NewErr(400, "订单不存在"))
  431. return
  432. }
  433. if order.State != 1 {
  434. sess.Rollback()
  435. e.OutErr(c, 400, e.NewErr(400, "订单不能确认收货"))
  436. return
  437. }
  438. order.State = 2
  439. order.UpdateAt = time.Now()
  440. order.ConfirmAt = time.Now()
  441. update, err := sess.Where("id=?", order.Id).Cols("state,confirm_at,update_at").Update(order)
  442. if update == 0 || err != nil {
  443. sess.Rollback()
  444. e.OutErr(c, 400, e.NewErr(400, "订单确认失败"))
  445. return
  446. }
  447. //给商家余额
  448. store := db.GetStoreId(sess, utils.IntToStr(order.StoreUid))
  449. if store == nil {
  450. sess.Rollback()
  451. e.OutErr(c, 400, e.NewErr(400, "订单确认失败"))
  452. return
  453. }
  454. if store.ParentUid > 0 {
  455. money := utils.StrToFloat64(order.Amount) - utils.StrToFloat64(order.AgentCommission)
  456. bools := MoneyCheck(c, sess, order.StoreUid, 0, 1, money, "订单核销", order.Oid)
  457. if bools == false {
  458. sess.Rollback()
  459. e.OutErr(c, 400, e.NewErr(400, "订单确认失败"))
  460. return
  461. }
  462. }
  463. sess.Commit()
  464. e.OutSuc(c, "success", nil)
  465. return
  466. }
  467. func OrderCreate(c *gin.Context) {
  468. var arg md.OrderTotal
  469. if err := c.ShouldBindJSON(&arg); err != nil {
  470. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  471. return
  472. }
  473. user := GetUser(c)
  474. // 加锁 防止并发提取
  475. mutexKey := fmt.Sprintf("%s:team.OrderCreate:%s", c.GetString("mid"), utils.IntToStr(user.Info.Uid))
  476. withdrawAvailable, err := cache.Do("SET", mutexKey, 1, "EX", 5, "NX")
  477. if err != nil {
  478. e.OutErr(c, e.ERR, err)
  479. return
  480. }
  481. if withdrawAvailable != "OK" {
  482. e.OutErr(c, e.ERR, e.NewErr(400000, "请求过于频繁,请稍后再试"))
  483. return
  484. }
  485. sess := MasterDb(c).NewSession()
  486. defer sess.Close()
  487. err = sess.Begin()
  488. if err != nil {
  489. e.OutErr(c, 400, err.Error())
  490. return
  491. }
  492. totalPrice := commGoods(c, arg)
  493. coupon := "0"
  494. totalPrice, coupon, err = CouponProcess(c, sess, totalPrice, arg)
  495. if err != nil {
  496. sess.Rollback()
  497. e.OutErr(c, 400, err.Error())
  498. return
  499. }
  500. ordId := utils.OrderUUID(user.Info.Uid)
  501. // 获取店铺信息
  502. store := db.GetStoreId(sess, arg.StoreId)
  503. num := 0
  504. for _, item := range arg.GoodsInfo {
  505. num += utils.StrToInt(item.Num)
  506. }
  507. var order = &model.CommunityTeamOrder{
  508. Uid: user.Info.Uid,
  509. StoreUid: utils.StrToInt(arg.StoreId),
  510. Commission: utils.Float64ToStr(utils.FloatFormat(utils.AnyToFloat64(totalPrice)*(utils.AnyToFloat64(store.Commission)/100), 2)),
  511. CreateAt: time.Now(),
  512. UpdateAt: time.Now(),
  513. BuyPhone: arg.BuyPhone,
  514. Coupon: coupon,
  515. Num: num,
  516. IsNow: utils.StrToInt(arg.IsNow),
  517. Timer: arg.Timer,
  518. Memo: arg.Memo,
  519. Oid: utils.StrToInt64(ordId),
  520. Amount: totalPrice,
  521. MealNum: utils.StrToInt(arg.MealNum),
  522. }
  523. if store.ParentUid > 0 { //代理下门店
  524. order.StoreType = 2
  525. order.ParentUid = store.ParentUid
  526. order.AgentCommission = utils.Float64ToStr(utils.FloatFormat(utils.AnyToFloat64(totalPrice)*(utils.AnyToFloat64(store.AgentCommission)/100), 2))
  527. }
  528. if utils.StrToFloat64(coupon) > 0 {
  529. order.CouponId = utils.StrToInt(arg.CouponId)
  530. }
  531. insert, err := sess.Insert(order)
  532. if insert == 0 || err != nil {
  533. sess.Rollback()
  534. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  535. return
  536. }
  537. for _, item := range arg.GoodsInfo {
  538. // 获取详细信息
  539. goodsInterface, has, err := db.GetComm(MasterDb(c), &model.CommunityTeamGoods{Id: utils.StrToInt(item.GoodsId)})
  540. if err != nil || !has {
  541. sess.Rollback()
  542. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  543. return
  544. }
  545. goodsModel := goodsInterface.(*model.CommunityTeamGoods)
  546. var skuInterface interface{}
  547. if item.SkuId != "-1" {
  548. skuInterface, _, _ = db.GetComm(MasterDb(c), &model.CommunityTeamSku{GoodsId: utils.StrToInt(item.GoodsId), SkuId: utils.StrToInt64(item.SkuId)})
  549. } else {
  550. skuInterface, _, _ = db.GetComm(MasterDb(c), &model.CommunityTeamSku{GoodsId: utils.StrToInt(item.GoodsId)})
  551. }
  552. if err != nil || !has {
  553. sess.Rollback()
  554. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  555. return
  556. }
  557. skuModel := skuInterface.(*model.CommunityTeamSku)
  558. var goodsSaleCount int
  559. // 走普通逻辑
  560. stock := skuModel.Stock - utils.StrToInt(item.Num)
  561. saleCount := skuModel.SaleCount + utils.StrToInt(item.Num)
  562. goodsSaleCount = goodsModel.SaleCount + utils.StrToInt(item.Num)
  563. if stock < 0 {
  564. sess.Rollback()
  565. e.OutErr(c, 400, e.NewErr(400, "库存不足"))
  566. return
  567. }
  568. update, err := sess.Where("sku_id=?", skuModel.SkuId).Cols("stock", "sale_count").Update(&model.CommunityTeamSku{Stock: stock, SaleCount: saleCount})
  569. if err != nil {
  570. sess.Rollback()
  571. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  572. return
  573. }
  574. if update != 1 {
  575. sess.Rollback()
  576. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  577. return
  578. }
  579. // 更新销量
  580. goodsModel.SaleCount = goodsSaleCount
  581. goodsModel.Stock = goodsModel.Stock - utils.StrToInt(item.Num)
  582. _, err = sess.Where("id = ?", goodsModel.Id).Cols("sale_count,stock").Update(goodsModel)
  583. if err != nil {
  584. sess.Rollback()
  585. e.OutErr(c, 400, e.NewErr(400, "商品不存在"))
  586. return
  587. }
  588. // 插入订单
  589. insert, err := sess.Insert(&model.CommunityTeamOrderInfo{
  590. Oid: utils.StrToInt64(ordId),
  591. Title: goodsModel.Title,
  592. Img: goodsModel.Img,
  593. Price: skuModel.Price,
  594. Num: utils.StrToInt(item.Num),
  595. SkuInfo: skuModel.Sku,
  596. GoodsId: skuModel.GoodsId,
  597. SkuId: int(skuModel.SkuId),
  598. })
  599. if err != nil {
  600. sess.Rollback()
  601. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  602. return
  603. }
  604. if insert != 1 {
  605. sess.Rollback()
  606. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  607. return
  608. }
  609. }
  610. // 更新优惠券使用状态
  611. if utils.StrToInt(arg.CouponId) > 0 {
  612. affect, err := sess.Where("id = ?", arg.CouponId).
  613. Update(&model.CommunityTeamCouponUser{IsUse: 1})
  614. if err != nil {
  615. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  616. return
  617. }
  618. if affect != 1 {
  619. e.OutErr(c, 400, e.NewErr(400, "下单失败"))
  620. return
  621. }
  622. }
  623. err = sess.Commit()
  624. if err != nil {
  625. sess.Rollback()
  626. e.OutErr(c, 400, err.Error())
  627. return
  628. }
  629. sess.Commit()
  630. e.OutSuc(c, map[string]string{"oid": ordId}, nil)
  631. return
  632. }
  633. func OrderTotal(c *gin.Context) {
  634. var arg md.OrderTotal
  635. if err := c.ShouldBindJSON(&arg); err != nil {
  636. e.OutErr(c, e.ERR_INVALID_ARGS, err)
  637. return
  638. }
  639. sess := MasterDb(c).NewSession()
  640. defer sess.Close()
  641. err := sess.Begin()
  642. if err != nil {
  643. e.OutErr(c, 400, err.Error())
  644. return
  645. }
  646. totalPrice := commGoods(c, arg)
  647. oldTotalPrice := totalPrice
  648. coupon := "0"
  649. totalPrice, coupon, err = CouponProcess(c, sess, totalPrice, arg)
  650. if err != nil {
  651. sess.Rollback()
  652. e.OutErr(c, 400, err.Error())
  653. return
  654. }
  655. user := GetUser(c)
  656. result := map[string]interface{}{
  657. "balance_money": GetCommissionPrec(c, user.Profile.FinValid, SysCfgGet(c, "commission_prec"), SysCfgGet(c, "is_show_point")),
  658. "small_amount": GetCommissionPrec(c, oldTotalPrice, SysCfgGet(c, "commission_prec"), SysCfgGet(c, "is_show_point")),
  659. "all_amount": GetCommissionPrec(c, totalPrice, SysCfgGet(c, "commission_prec"), SysCfgGet(c, "is_show_point")),
  660. "coupon": GetCommissionPrec(c, coupon, SysCfgGet(c, "commission_prec"), SysCfgGet(c, "is_show_point")),
  661. }
  662. sess.Commit()
  663. e.OutSuc(c, result, nil)
  664. return
  665. }
  666. func CouponProcess(c *gin.Context, sess *xorm.Session, total string, args md.OrderTotal) (string, string, error) {
  667. if utils.StrToInt(args.CouponId) == 0 {
  668. return total, "0", nil
  669. }
  670. now := time.Now().Format("2006-01-02 15:04:05")
  671. user := GetUser(c)
  672. var goodsIds []int
  673. var skuIds []string
  674. for _, item := range args.GoodsInfo {
  675. goodsIds = append(goodsIds, utils.StrToInt(item.GoodsId))
  676. skuIds = append(skuIds, utils.AnyToString(item.SkuId))
  677. }
  678. // 获取优惠券信息
  679. var mallUserCoupon model.CommunityTeamCouponUser
  680. isExist, err := sess.
  681. Where("id = ? AND uid = ? AND is_use = ? AND (valid_time_start < ? AND valid_time_end > ?)", args.CouponId, user.Info.Uid, 1, now, now).
  682. Get(&mallUserCoupon)
  683. if err != nil {
  684. return "", "", err
  685. }
  686. if !isExist {
  687. return "", "", errors.New("无相关优惠券信息")
  688. }
  689. var cal struct {
  690. Reach string `json:"reach"`
  691. Reduce string `json:"reduce"`
  692. }
  693. _ = json.Unmarshal([]byte(mallUserCoupon.Cal), &cal)
  694. reach, err := decimal.NewFromString(cal.Reach)
  695. reduce, err := decimal.NewFromString(cal.Reduce)
  696. if err != nil {
  697. return "", "", err
  698. }
  699. var specialTotal = total
  700. // 是否满足优惠条件
  701. if !reach.IsZero() { // 满减及有门槛折扣
  702. if utils.StrToFloat64(specialTotal) < utils.StrToFloat64(reach.String()) {
  703. return "", "", errors.New("不满足优惠条件")
  704. }
  705. } else {
  706. if mallUserCoupon.Kind == 1 { //立减
  707. if utils.StrToFloat64(specialTotal) < utils.StrToFloat64(reduce.String()) {
  708. return "", "", errors.New("不满足优惠条件")
  709. }
  710. }
  711. }
  712. // 计算优惠后支付金额
  713. couponTotal := "0"
  714. if mallUserCoupon.Kind == int(enum.ActCouponTypeImmediate) ||
  715. mallUserCoupon.Kind == int(enum.ActCouponTypeReachReduce) { // 立减 || 满减
  716. couponTotal = reduce.String()
  717. total = utils.Float64ToStr(utils.StrToFloat64(total) - utils.StrToFloat64(reduce.String()))
  718. } else { // 折扣
  719. couponTotal = utils.Float64ToStr(utils.StrToFloat64(total) - utils.StrToFloat64(total)*utils.StrToFloat64(reduce.String())/10)
  720. total = utils.Float64ToStr(utils.StrToFloat64(total) * utils.StrToFloat64(reduce.String()) / 10)
  721. }
  722. return total, couponTotal, nil
  723. }
  724. func commGoods(c *gin.Context, arg md.OrderTotal) (totalPrice string) {
  725. engine := MasterDb(c)
  726. var totalPriceAmt float64 = 0
  727. for _, item := range arg.GoodsInfo {
  728. goodsInterface, _, _ := db.GetComm(engine, &model.CommunityTeamGoods{Id: utils.StrToInt(item.GoodsId)})
  729. goodsModel := goodsInterface.(*model.CommunityTeamGoods)
  730. var skuInterface interface{}
  731. if item.SkuId != "-1" {
  732. skuInterface, _, _ = db.GetComm(engine, &model.CommunityTeamSku{GoodsId: utils.StrToInt(item.GoodsId), SkuId: utils.StrToInt64(item.SkuId)})
  733. } else {
  734. skuInterface, _, _ = db.GetComm(engine, &model.CommunityTeamSku{GoodsId: utils.StrToInt(item.GoodsId)})
  735. }
  736. skuModel := skuInterface.(*model.CommunityTeamSku)
  737. priceOne := goodsModel.Price
  738. if item.SkuId != "-1" {
  739. priceOne = skuModel.Price
  740. }
  741. totalPriceAmt += utils.StrToFloat64(priceOne) * utils.StrToFloat64(item.Num)
  742. }
  743. return utils.Float64ToStr(totalPriceAmt)
  744. }