智慧食堂
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.

668 line
23 KiB

  1. package svc
  2. import (
  3. "applet/app/customer/enum"
  4. "applet/app/customer/md"
  5. "applet/app/db"
  6. "applet/app/db/model"
  7. enum2 "applet/app/enum"
  8. svc3 "applet/app/svc"
  9. "applet/app/utils"
  10. "applet/app/utils/logx"
  11. "encoding/json"
  12. "errors"
  13. "fmt"
  14. "github.com/gin-gonic/gin"
  15. "github.com/wechatpay-apiv3/wechatpay-go/core"
  16. "github.com/wechatpay-apiv3/wechatpay-go/services/partnerpayments/jsapi"
  17. jsapi2 "github.com/wechatpay-apiv3/wechatpay-go/services/payments/jsapi"
  18. utils2 "github.com/wechatpay-apiv3/wechatpay-go/utils"
  19. "io/ioutil"
  20. "math"
  21. "net/url"
  22. "strconv"
  23. "time"
  24. )
  25. func CheckIsOpenLimitOrderFood(enterpriseId int) (err error) {
  26. //查询`central_kitchen_for_school_set`
  27. centralKitchenForSchoolSetDb := db.CentralKitchenForSchoolSetDb{}
  28. centralKitchenForSchoolSetDb.Set(enterpriseId)
  29. set, err := centralKitchenForSchoolSetDb.GetCentralKitchenForSchoolSet()
  30. if err != nil {
  31. return
  32. }
  33. if set != nil && set.IsOpenLimitOrderFood == 1 {
  34. //TODO::判断每月25日至最后一日不可以订餐
  35. day := time.Now().Day()
  36. if day >= set.OrderFoodStartDate && day <= set.OrderFoodEndDate {
  37. return errors.New(fmt.Sprintf("每月%d日至%d日可以订餐!", set.OrderFoodStartDate, set.OrderFoodEndDate))
  38. }
  39. }
  40. return
  41. }
  42. func BuyPackageForAli(c *gin.Context, req md.BuyPackageReq) (outTradeNo, tradeNo, total string, err error) {
  43. user := GetUser(c)
  44. session := db.Db.NewSession()
  45. defer session.Close()
  46. session.Begin()
  47. if err != nil {
  48. _ = session.Rollback()
  49. return
  50. }
  51. //1、判断是否为教师
  52. isTeacher := false
  53. userIdentityDb := db.UserIdentityDb{}
  54. userIdentityDb.Set(0)
  55. userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId)
  56. if err != nil {
  57. return
  58. }
  59. if userIdentity == nil {
  60. err = errors.New("未查询到对应身份记录")
  61. return
  62. }
  63. if userIdentity.Identity == enum2.UserIdentityForCentralKitchenForTeacher {
  64. isTeacher = true
  65. }
  66. //2、计算数据(1:按学期购买 2:按月购买 3:按天购买 4:补餐)
  67. var totalPrice float64
  68. var data []*model.CentralKitchenForSchoolUserWithDay
  69. if req.Kind == 1 {
  70. totalPrice, data, err = CalcBySchoolTerm(user.Id, isTeacher, req)
  71. if err != nil {
  72. return
  73. }
  74. }
  75. if req.Kind == 2 {
  76. totalPrice, data, err = CalcByMonth(user.Id, isTeacher, req)
  77. if err != nil {
  78. return
  79. }
  80. }
  81. if req.Kind == 3 {
  82. totalPrice, data, err = CalcByDay(user.Id, isTeacher, req)
  83. if err != nil {
  84. return
  85. }
  86. }
  87. if req.Kind == 4 {
  88. totalPrice, data, err = CalcSupplementaryByDay(user.Id, isTeacher, req)
  89. if err != nil {
  90. return
  91. }
  92. }
  93. total = utils.Float64ToStr(totalPrice)
  94. //3、生成订单号
  95. outTradeNo = utils.OrderUUID(user.Id)
  96. //4、请求 alipay.trade.create(统一收单交易创建接口)
  97. sysCfgDb := db.SysCfgDb{}
  98. sysCfgDb.Set()
  99. sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.OpenAppletAppid, enum2.OpenAlipayAppid, enum2.OpenAlipayAppPrivateKey, enum2.OpenAlipayPublicKey, enum2.JsapiPayAppAutToken, enum2.JsapiPayNotifyUrl)
  100. err, resp := CurlAlipayTradeCreate(md.CurlAlipayTradeCreateReq{
  101. Config: struct {
  102. PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"`
  103. PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"`
  104. PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"`
  105. }{
  106. PayAliAppId: sysCfg[enum2.OpenAlipayAppid],
  107. PayAliPrivateKey: sysCfg[enum2.OpenAlipayAppPrivateKey],
  108. PayAliPublicKey: sysCfg[enum2.OpenAlipayPublicKey],
  109. },
  110. OpAppId: sysCfg[enum2.OpenAppletAppid],
  111. BuyerId: user.UserId,
  112. TotalAmount: total,
  113. OutTradeNo: outTradeNo,
  114. Subject: "购买食堂套餐",
  115. AppAuthToken: sysCfg[enum2.JsapiPayAppAutToken],
  116. NotifyUrl: sysCfg[enum2.JsapiPayNotifyUrl],
  117. })
  118. if err != nil {
  119. return
  120. }
  121. //5、插入订单记录
  122. now := time.Now()
  123. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  124. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  125. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdInsertBySession(session, &model.CentralKitchenForSchoolPackageOrd{
  126. EnterpriseId: req.EnterpriseId,
  127. Uid: user.Id,
  128. UserIdentityId: req.UserIdentityId,
  129. UserIdentityName: userIdentity.Name,
  130. TotalPrice: total,
  131. Kind: req.Kind,
  132. OutTradeNo: outTradeNo,
  133. TradeNo: resp.TradeNo,
  134. State: enum2.CentralKitchenForSchoolPackageOrdStateForWait,
  135. OrdState: enum2.CentralKitchenForSchoolPackageOrdOrdStateForWait,
  136. ReqContent: string(utils.Serialize(req)),
  137. WithDayData: string(utils.Serialize(data)),
  138. PayWay: enum.PayWayForAli,
  139. CreateAt: now.Format("2006-01-02 15:04:05"),
  140. UpdateAt: now.Format("2006-01-02 15:04:05"),
  141. PayAt: "2006-01-02 15:04:05",
  142. })
  143. if err != nil {
  144. _ = session.Rollback()
  145. return
  146. }
  147. session.Commit()
  148. tradeNo = resp.TradeNo
  149. return
  150. }
  151. func BuyPackageForWx(c *gin.Context, req md.BuyPackageReq) (outTradeNo, total string, resp *jsapi2.PrepayWithRequestPaymentResponse, err error) {
  152. user := GetUser(c)
  153. session := db.Db.NewSession()
  154. defer session.Close()
  155. session.Begin()
  156. if err != nil {
  157. _ = session.Rollback()
  158. return
  159. }
  160. //1、判断是否为教师
  161. isTeacher := false
  162. userIdentityDb := db.UserIdentityDb{}
  163. userIdentityDb.Set(0)
  164. userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId)
  165. if err != nil {
  166. return
  167. }
  168. if userIdentity == nil {
  169. err = errors.New("未查询到对应身份记录")
  170. return
  171. }
  172. if userIdentity.Identity == enum2.UserIdentityForCentralKitchenForTeacher {
  173. isTeacher = true
  174. }
  175. //2、计算数据(1:按学期购买 2:按月购买 3:按天购买 4:补餐)
  176. var totalPrice float64
  177. var data []*model.CentralKitchenForSchoolUserWithDay
  178. if req.Kind == 1 {
  179. totalPrice, data, err = CalcBySchoolTerm(user.Id, isTeacher, req)
  180. if err != nil {
  181. return
  182. }
  183. }
  184. if req.Kind == 2 {
  185. totalPrice, data, err = CalcByMonth(user.Id, isTeacher, req)
  186. if err != nil {
  187. return
  188. }
  189. }
  190. if req.Kind == 3 {
  191. totalPrice, data, err = CalcByDay(user.Id, isTeacher, req)
  192. if err != nil {
  193. return
  194. }
  195. }
  196. if req.Kind == 4 {
  197. totalPrice, data, err = CalcSupplementaryByDay(user.Id, isTeacher, req)
  198. if err != nil {
  199. return
  200. }
  201. }
  202. total = utils.Float64ToStr(totalPrice)
  203. //3、生成订单号
  204. outTradeNo = utils.OrderUUID(user.Id)
  205. //4、请求 /v3/pay/partner/transactions/jsapi (生成预支付交易单)
  206. sysCfgDb := db.SysCfgDb{}
  207. sysCfgDb.Set()
  208. client, err := svc3.NewWxPayClient(c)
  209. if err != nil {
  210. return
  211. }
  212. wxSvc := jsapi.JsapiApiService{Client: client}
  213. companyWithWxpayInfoDb := db.CompanyWithWxpayInfoDb{}
  214. companyWithWxpayInfoDb.Set()
  215. wxMchId, err := companyWithWxpayInfoDb.GetCompanyWithWxpayInfoByEnterprise(req.EnterpriseId)
  216. if err != nil {
  217. return "", "", nil, err
  218. }
  219. sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.WxAppletAppId, enum2.WxSpAppId, enum2.WxSpMchId, enum2.WxAppletAppId, enum2.WxJsapiPayNotifyUrl)
  220. fmt.Println(int64(math.Round(totalPrice * 100)))
  221. openId := c.GetHeader("openid") //TODO::实时获取用户的openId
  222. if openId == "" {
  223. openId = user.OpenId
  224. }
  225. result, _, err := wxSvc.Prepay(c,
  226. jsapi.PrepayRequest{
  227. SpAppid: core.String(sysCfg[enum2.WxSpAppId]),
  228. SpMchid: core.String(sysCfg[enum2.WxSpMchId]),
  229. SubAppid: core.String(sysCfg[enum2.WxAppletAppId]),
  230. SubMchid: core.String(wxMchId),
  231. Description: core.String("购买食堂套餐"),
  232. OutTradeNo: core.String(outTradeNo),
  233. TimeExpire: core.Time(time.Now().Add(20 * time.Minute)),
  234. //Attach: core.String("自定义数据说明"),
  235. NotifyUrl: core.String(sysCfg[enum2.WxJsapiPayNotifyUrl]),
  236. Amount: &jsapi.Amount{
  237. Currency: core.String("CNY"),
  238. Total: core.Int64(int64(math.Round(totalPrice * 100))),
  239. },
  240. Payer: &jsapi.Payer{
  241. //SpOpenid: core.String("oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"),
  242. SubOpenid: core.String(openId),
  243. },
  244. },
  245. )
  246. fmt.Println(">>>>>>>>>>>", core.Int64(utils.StrToInt64(total)*100))
  247. if err != nil {
  248. _ = session.Rollback()
  249. return
  250. }
  251. //5、插入订单记录
  252. now := time.Now()
  253. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  254. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  255. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdInsertBySession(session, &model.CentralKitchenForSchoolPackageOrd{
  256. EnterpriseId: req.EnterpriseId,
  257. Uid: user.Id,
  258. UserIdentityId: req.UserIdentityId,
  259. UserIdentityName: userIdentity.Name,
  260. TotalPrice: total,
  261. Kind: req.Kind,
  262. OutTradeNo: outTradeNo,
  263. TradeNo: "",
  264. State: enum2.CentralKitchenForSchoolPackageOrdStateForWait,
  265. OrdState: enum2.CentralKitchenForSchoolPackageOrdOrdStateForWait,
  266. ReqContent: string(utils.Serialize(req)),
  267. WithDayData: string(utils.Serialize(data)),
  268. PayWay: enum.PayWayForWx,
  269. PrepayId: *result.PrepayId,
  270. CreateAt: now.Format("2006-01-02 15:04:05"),
  271. UpdateAt: now.Format("2006-01-02 15:04:05"),
  272. PayAt: "2006-01-02 15:04:05",
  273. })
  274. if err != nil {
  275. _ = session.Rollback()
  276. return
  277. }
  278. session.Commit()
  279. //prepayId = *resp.PrepayId
  280. resp = new(jsapi2.PrepayWithRequestPaymentResponse)
  281. resp.PrepayId = result.PrepayId
  282. resp.SignType = core.String("RSA")
  283. appid := sysCfg[enum2.WxAppletAppId]
  284. resp.Appid = &appid
  285. resp.TimeStamp = core.String(strconv.FormatInt(time.Now().Unix(), 10))
  286. nonce, err := utils2.GenerateNonce()
  287. if err != nil {
  288. _ = session.Rollback()
  289. return
  290. }
  291. resp.NonceStr = core.String(nonce)
  292. resp.Package = core.String("prepay_id=" + *result.PrepayId)
  293. message := fmt.Sprintf("%s\n%s\n%s\n%s\n", *resp.Appid, *resp.TimeStamp, *resp.NonceStr, *resp.Package)
  294. signatureResult, err := wxSvc.Client.Sign(c, message)
  295. if err != nil {
  296. _ = session.Rollback()
  297. return
  298. }
  299. resp.PaySign = core.String(signatureResult.Signature)
  300. return
  301. }
  302. func NursingHomeBuyPackageReq(c *gin.Context, req md.NursingHomeBuyPackageReq) (outTradeNo, tradeNo, total string, err error) {
  303. user := GetUser(c)
  304. session := db.Db.NewSession()
  305. defer session.Close()
  306. session.Begin()
  307. if err != nil {
  308. _ = session.Rollback()
  309. return
  310. }
  311. userIdentityDb := db.UserIdentityDb{}
  312. userIdentityDb.Set(0)
  313. userIdentity, err := userIdentityDb.GetUserIdentity(req.UserIdentityId)
  314. if err != nil {
  315. return
  316. }
  317. if userIdentity == nil {
  318. err = errors.New("未查询到对应身份记录")
  319. return
  320. }
  321. //1、计算数据(1:按年购买 2:按月购买 3:按天购买 4:补餐)
  322. var totalPrice float64
  323. var data []*model.NursingHomeUserWithDay
  324. if req.Kind == 1 {
  325. totalPrice, data, err = CalcByYearForNursingHome(user.Id, req)
  326. if err != nil {
  327. return
  328. }
  329. }
  330. if req.Kind == 2 {
  331. totalPrice, data, err = CalcByMonthForNursingHome(user.Id, req)
  332. if err != nil {
  333. return
  334. }
  335. }
  336. if req.Kind == 3 {
  337. totalPrice, data, err = CalcByDayForNursingHome(user.Id, req)
  338. if err != nil {
  339. return
  340. }
  341. }
  342. if req.Kind == 4 {
  343. totalPrice, data, err = CalcByDayForNursingHome(user.Id, req)
  344. if err != nil {
  345. return
  346. }
  347. }
  348. total = utils.Float64ToStr(totalPrice)
  349. //3、生成订单号
  350. outTradeNo = utils.OrderUUID(user.Id)
  351. //4、请求 alipay.trade.create(统一收单交易创建接口)
  352. sysCfgDb := db.SysCfgDb{}
  353. sysCfgDb.Set()
  354. sysCfg := sysCfgDb.SysCfgFindWithDb(enum2.OpenAppletAppid, enum2.OpenAlipayAppid, enum2.OpenAlipayAppPrivateKey, enum2.OpenAlipayPublicKey, enum2.JsapiPayAppAutToken)
  355. err, resp := CurlAlipayTradeCreate(md.CurlAlipayTradeCreateReq{
  356. Config: struct {
  357. PayAliAppId string `json:"pay_ali_app_id" label:"支付宝开放平台-第三方应用-appid"`
  358. PayAliPrivateKey string `json:"pay_ali_private_key" label:"支付宝开放平台-第三方应用-接口加签-应用私钥"`
  359. PayAliPublicKey string `json:"pay_ali_public_key" label:"支付宝开放平台-第三方应用-接口加签-支付宝公钥"`
  360. }{
  361. PayAliAppId: sysCfg[enum2.OpenAlipayAppid],
  362. PayAliPrivateKey: sysCfg[enum2.OpenAlipayAppPrivateKey],
  363. PayAliPublicKey: sysCfg[enum2.OpenAlipayPublicKey],
  364. },
  365. OpAppId: sysCfg[enum2.OpenAppletAppid],
  366. BuyerId: user.UserId,
  367. TotalAmount: total,
  368. OutTradeNo: outTradeNo,
  369. Subject: "购买食堂套餐",
  370. AppAuthToken: sysCfg[enum2.JsapiPayAppAutToken],
  371. })
  372. if err != nil {
  373. return
  374. }
  375. //5、插入订单记录
  376. now := time.Now()
  377. NursingHomePackageOrd := db.NursingHomePackageOrd{}
  378. NursingHomePackageOrd.Set(outTradeNo)
  379. _, err = NursingHomePackageOrd.NursingHomePackageOrdInsertBySession(session, &model.NursingHomePackageOrd{
  380. EnterpriseId: req.EnterpriseId,
  381. Uid: user.Id,
  382. UserIdentityId: req.UserIdentityId,
  383. UserIdentityName: userIdentity.Name,
  384. TotalPrice: total,
  385. Kind: req.Kind,
  386. OutTradeNo: outTradeNo,
  387. TradeNo: resp.TradeNo,
  388. State: enum2.NursingHomePackageOrdStateForWait,
  389. OrdState: enum2.NursingHomePackageOrdOrdStateForWait,
  390. ReqContent: string(utils.Serialize(req)),
  391. WithDayData: string(utils.Serialize(data)),
  392. CreateAt: now.Format("2006-01-02 15:04:05"),
  393. UpdateAt: now.Format("2006-01-02 15:04:05"),
  394. })
  395. if err != nil {
  396. _ = session.Rollback()
  397. return
  398. }
  399. session.Commit()
  400. tradeNo = resp.TradeNo
  401. return
  402. }
  403. func DealCentralKitchenForSchoolOrderCallBack(outTradeNo, tradeStatus, successTime string) (state int, err error) {
  404. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  405. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  406. ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd()
  407. if err != nil {
  408. return
  409. }
  410. if ord == nil {
  411. err = errors.New("未查询到对应订单记录")
  412. return
  413. }
  414. if ord.State == enum2.CentralKitchenForSchoolPackageOrdStateForWait {
  415. if tradeStatus == "TRADE_CLOSED" {
  416. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForFail
  417. }
  418. if tradeStatus == "TRADE_SUCCESS" {
  419. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForSuccess
  420. ord.OrdState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForSuccess
  421. ord.PayAt = successTime
  422. //TODO::将预留数据插入到 `central_kitchen_for_school_user_with_day`
  423. var data []*model.CentralKitchenForSchoolUserWithDay
  424. err = json.Unmarshal([]byte(ord.WithDayData), &data)
  425. if err != nil {
  426. return
  427. }
  428. var hasMonths = map[string]map[string]interface{}{}
  429. var hasKinds = map[string]map[string]string{}
  430. var hasTotalPrice = map[string]map[string]float64{}
  431. for _, v := range data {
  432. date, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local)
  433. if hasMonths[utils.TimeParseStd(v.Date).Month().String()] == nil {
  434. hasMonths[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]interface{})
  435. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  436. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  437. } else {
  438. startTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"]), time.Local)
  439. if startTime.After(date) {
  440. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  441. }
  442. endTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"]), time.Local)
  443. if endTime.Before(date) {
  444. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  445. }
  446. }
  447. if hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] == nil {
  448. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]float64)
  449. }
  450. if hasKinds[utils.TimeParseStd(v.Date).Month().String()] == nil {
  451. hasKinds[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]string)
  452. }
  453. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["month"] = int(utils.TimeParseStd(v.Date).Month())
  454. hasKinds[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] = utils.IntToStr(v.Kind)
  455. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] += utils.StrToFloat64(v.Amount)
  456. v.OrdNo = outTradeNo
  457. }
  458. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  459. centralKitchenForSchoolUserWithDayDb.Set(0)
  460. _, err = centralKitchenForSchoolUserWithDayDb.BatchAddCentralKitchenForSchoolUserWithDays(data)
  461. if err != nil {
  462. return
  463. }
  464. //TODO::插入数据至 `central_kitchen_for_school_package_ord_for_reserve`
  465. centralKitchenForSchoolPackageOrdForReserve := db.CentralKitchenForSchoolPackageOrdForReserve{}
  466. centralKitchenForSchoolPackageOrdForReserve.Set(outTradeNo)
  467. for k, v := range hasMonths {
  468. for _, v1 := range hasKinds[k] {
  469. _, err = centralKitchenForSchoolPackageOrdForReserve.CentralKitchenForSchoolPackageOrdForReserveInsert(&model.CentralKitchenForSchoolPackageOrdForReserve{
  470. EnterpriseId: ord.EnterpriseId,
  471. Uid: ord.Uid,
  472. UserIdentityName: ord.UserIdentityName,
  473. UserIdentityId: ord.UserIdentityId,
  474. Kind: utils.StrToInt(v1),
  475. OutTradeNo: ord.OutTradeNo,
  476. ReserveMonth: utils.AnyToString(v["month"]),
  477. MealTimeStart: utils.AnyToString(v["meal_time_start"]),
  478. MealTimeEnd: utils.AnyToString(v["meal_time_end"]),
  479. TotalPrice: utils.Float64ToStr(hasTotalPrice[k][v1]),
  480. CreateAt: time.Now().Format("2006-01-02 15:04:05"),
  481. UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
  482. })
  483. if err != nil {
  484. return
  485. }
  486. }
  487. }
  488. }
  489. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(ord, "state", "ord_state", "pay_at")
  490. if err != nil {
  491. return
  492. }
  493. }
  494. state = ord.State
  495. return
  496. }
  497. func DealCentralKitchenForSchoolOrderCallBackForWx(outTradeNo, transactionId, tradeStatus, successTime string) (state int, err error) {
  498. centralKitchenForSchoolPackageOrd := db.CentralKitchenForSchoolPackageOrd{}
  499. centralKitchenForSchoolPackageOrd.Set(outTradeNo)
  500. ord, err := centralKitchenForSchoolPackageOrd.GetCentralKitchenForSchoolPackageOrd()
  501. if err != nil {
  502. return
  503. }
  504. if ord == nil {
  505. err = errors.New("未查询到对应订单记录")
  506. return
  507. }
  508. if ord.State == enum2.CentralKitchenForSchoolPackageOrdStateForWait {
  509. if tradeStatus == "CLOSED" || tradeStatus == "PAYERROR" {
  510. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForFail
  511. }
  512. if tradeStatus == "SUCCESS" {
  513. ord.State = enum2.CentralKitchenForSchoolPackageOrdStateForSuccess
  514. ord.OrdState = enum2.CentralKitchenForSchoolPackageOrdOrdStateForSuccess
  515. ord.TradeNo = transactionId
  516. ord.PayAt = successTime
  517. //TODO::将预留数据插入到 `central_kitchen_for_school_user_with_day`
  518. var data []*model.CentralKitchenForSchoolUserWithDay
  519. err = json.Unmarshal([]byte(ord.WithDayData), &data)
  520. if err != nil {
  521. return
  522. }
  523. var hasMonths = map[string]map[string]interface{}{}
  524. var hasKinds = map[string]map[string]string{}
  525. var hasTotalPrice = map[string]map[string]float64{}
  526. for _, v := range data {
  527. date, _ := time.ParseInLocation("2006-01-02", v.Date, time.Local)
  528. if hasMonths[utils.TimeParseStd(v.Date).Month().String()] == nil {
  529. hasMonths[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]interface{})
  530. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  531. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  532. } else {
  533. startTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"]), time.Local)
  534. if startTime.After(date) {
  535. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_start"] = date.Format("2006-01-02")
  536. }
  537. endTime, _ := time.ParseInLocation("2006-01-02", utils.AnyToString(hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"]), time.Local)
  538. if endTime.Before(date) {
  539. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["meal_time_end"] = date.Format("2006-01-02")
  540. }
  541. }
  542. if hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] == nil {
  543. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]float64)
  544. }
  545. if hasKinds[utils.TimeParseStd(v.Date).Month().String()] == nil {
  546. hasKinds[utils.TimeParseStd(v.Date).Month().String()] = make(map[string]string)
  547. }
  548. hasMonths[utils.TimeParseStd(v.Date).Month().String()]["month"] = int(utils.TimeParseStd(v.Date).Month())
  549. hasKinds[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] = utils.IntToStr(v.Kind)
  550. hasTotalPrice[utils.TimeParseStd(v.Date).Month().String()][utils.IntToStr(v.Kind)] += utils.StrToFloat64(v.Amount)
  551. v.OrdNo = outTradeNo
  552. }
  553. centralKitchenForSchoolUserWithDayDb := db.CentralKitchenForSchoolUserWithDayDb{}
  554. centralKitchenForSchoolUserWithDayDb.Set(0)
  555. _, err = centralKitchenForSchoolUserWithDayDb.BatchAddCentralKitchenForSchoolUserWithDays(data)
  556. if err != nil {
  557. return
  558. }
  559. //TODO::插入数据至 `central_kitchen_for_school_package_ord_for_reserve`
  560. centralKitchenForSchoolPackageOrdForReserve := db.CentralKitchenForSchoolPackageOrdForReserve{}
  561. centralKitchenForSchoolPackageOrdForReserve.Set(outTradeNo)
  562. for k, v := range hasMonths {
  563. for _, v1 := range hasKinds[k] {
  564. _, err = centralKitchenForSchoolPackageOrdForReserve.CentralKitchenForSchoolPackageOrdForReserveInsert(&model.CentralKitchenForSchoolPackageOrdForReserve{
  565. EnterpriseId: ord.EnterpriseId,
  566. Uid: ord.Uid,
  567. UserIdentityName: ord.UserIdentityName,
  568. UserIdentityId: ord.UserIdentityId,
  569. Kind: utils.StrToInt(v1),
  570. OutTradeNo: ord.OutTradeNo,
  571. ReserveMonth: utils.AnyToString(v["month"]),
  572. MealTimeStart: utils.AnyToString(v["meal_time_start"]),
  573. MealTimeEnd: utils.AnyToString(v["meal_time_end"]),
  574. TotalPrice: utils.Float64ToStr(hasTotalPrice[k][v1]),
  575. CreateAt: time.Now().Format("2006-01-02 15:04:05"),
  576. UpdateAt: time.Now().Format("2006-01-02 15:04:05"),
  577. })
  578. if err != nil {
  579. return
  580. }
  581. }
  582. }
  583. }
  584. _, err = centralKitchenForSchoolPackageOrd.CentralKitchenForSchoolPackageOrdUpdate(ord, "state", "ord_state", "trade_no", "pay_at")
  585. if err != nil {
  586. return
  587. }
  588. }
  589. state = ord.State
  590. return
  591. }
  592. func CheckAllCallbackParams(c *gin.Context) interface{} {
  593. body, _ := ioutil.ReadAll(c.Request.Body)
  594. utils.FilePutContents("CheckAllCallbackParams", utils.SerializeStr(string(body)))
  595. dataAlipay, _ := GetAlipayCallbackParams(body)
  596. if dataAlipay != nil {
  597. return dataAlipay
  598. }
  599. return nil
  600. }
  601. // GetAlipayCallbackParams 支付宝参数解析
  602. func GetAlipayCallbackParams(body []byte) (*md.AliPayCallback, error) {
  603. decodeArgs, err := url.QueryUnescape(string(body))
  604. if err != nil {
  605. _ = logx.Warn(err)
  606. return nil, logx.Warn("回调参数解码错误")
  607. }
  608. data, err := url.ParseQuery(decodeArgs)
  609. if err != nil {
  610. return nil, err
  611. }
  612. dataMap := make(map[string]interface{})
  613. for k := range data {
  614. dataMap[k] = data.Get(k)
  615. }
  616. callbackStr := utils.Serialize(dataMap)
  617. fmt.Println("支付宝回调数据", string(callbackStr))
  618. var args md.AliPayCallback
  619. if err := json.Unmarshal(callbackStr, &args); err != nil {
  620. return nil, logx.Warn(err)
  621. }
  622. return &args, nil
  623. }