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.

892 lines
32 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. <?php
  2. namespace App\Service;
  3. use App\Commons\Log;
  4. use App\Constants\LogLabel;
  5. use App\Model\Coupon;
  6. use App\Model\CouponRec;
  7. use App\Model\CouponUserUse;
  8. use App\Model\Goods;
  9. use App\Model\Order;
  10. use App\Model\OrderGoods;
  11. use App\Model\OrderMain;
  12. use App\Model\OrderSalesStatistic;
  13. use App\Model\SpecCombination;
  14. use App\Model\Store;
  15. use Exception;
  16. use Hyperf\DbConnection\Db;
  17. use Hyperf\Snowflake\IdGeneratorInterface;
  18. use Hyperf\Utils\ApplicationContext;
  19. use Hyperf\Di\Annotation\Inject;
  20. use App\Service\WxRefundServiceInterface;
  21. use App\Service\UserServiceInterface;
  22. use App\Model\Users;
  23. use App\Constants\SsdbKeysPrefix;
  24. use App\Service\PurchaseLimitServiceInterface;
  25. class OrderService implements OrderServiceInterface
  26. {
  27. /**
  28. * @Inject
  29. * @var Log
  30. */
  31. protected $log;
  32. /**
  33. * @Inject
  34. * @var CouponServiceInterface
  35. */
  36. protected $couponService;
  37. /**
  38. * @Inject
  39. * @var WxRefundServiceInterface
  40. */
  41. protected $wxRefundService;
  42. /**
  43. * @Inject
  44. * @var UserServiceInterface
  45. */
  46. protected $userService;
  47. /**
  48. * @Inject
  49. * @var PurchaseLimitServiceInterface
  50. */
  51. protected $purchaseLimitService;
  52. /**
  53. * @Inject
  54. * @var FinancialRecordServiceInterface
  55. */
  56. protected $financialService;
  57. /**
  58. * @inheritDoc
  59. */
  60. public function addOnlineOrder($data)
  61. {
  62. bcscale(6);
  63. $dataMain = $data;
  64. Db::beginTransaction();
  65. try {
  66. // TODO 这个字段后续可能不用了,之前由达达订单号从前端传上来
  67. $dataMain['order_num'] = 'o'.date('YmdHis').mt_rand(1000,9999);
  68. // 计算当前订单可用红包优惠金额
  69. $couponMoney = 0;
  70. $receiveCouponIds = [];
  71. if (isset($data['receive_coupon_ids'])&&$data['receive_coupon_ids']) {
  72. $receiveCouponIds = explode(',', str_replace(',',',',$data['receive_coupon_ids']));
  73. $couponMoney = $this->getCouponAmount($receiveCouponIds, $data['money'], $data['user_id'], $data['market_id']);
  74. }
  75. $dataMain['yhq_money2'] = $couponMoney;
  76. // 获取分布式全局ID
  77. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  78. $dataMain['global_order_id'] = $generator->generate();
  79. // 店铺IDs
  80. $dataMain['store_ids'] = '';
  81. $storeList = json_decode(html_entity_decode($data['store_list']), true);
  82. if (!is_array($storeList)||empty($storeList)) {
  83. Db::rollBack();
  84. return '订单中商品不存在或已失效';
  85. }
  86. // 获取商户IDs
  87. foreach ($storeList as &$item) {
  88. $dataMain['store_ids'] .= empty($dataMain['store_ids']) ? $item['store_id'] : ','.$item['store_id'];
  89. }
  90. // 主订单插入数据
  91. $currentTime = time();
  92. $dataMain['time'] = date('Y-m-d H:i:s', $currentTime);
  93. $dataMain['time_add'] = $currentTime;
  94. $dataMain['pay_time'] = '';
  95. $dataMain['state'] = OrderMain::ORDER_STATE_UNPAY;
  96. $dataMain['code'] = $dataMain['global_order_id'];
  97. $dataMain['jj_note'] = '';
  98. // 主订单模型保存
  99. $orderMain = OrderMain::create($dataMain);
  100. $orderMainId = $orderMain->id;
  101. // 统计订单中所有店铺当日订单数,做店铺订单序号
  102. $countsArr = Order::query()
  103. ->selectRaw('store_id, COUNT(*) AS count')
  104. ->whereIn('store_id', explode(',', $dataMain['store_ids']))
  105. ->where(['type' => OrderMain::ORDER_TYPE_ONLINE])
  106. ->whereBetween('time', [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')])
  107. ->groupBy('store_id')
  108. ->get()
  109. ->toArray();
  110. $storeOrderCounts = [];
  111. foreach ($countsArr as $key => &$row) {
  112. $storeOrderCounts[$row['store_id']] = $row['count'];
  113. }
  114. // 循环处理订单总额、子订单总额、商品、商户订单等信息
  115. $orderAmountTotal = 0; # 总订单金额
  116. $orderGoods = [];
  117. foreach ($storeList as $key => &$item) {
  118. // 子订单数据处理
  119. $dataChild = [
  120. 'uniacid' => $data['uniacid'],
  121. 'order_num' => 's'.date('YmdHis', time()) . rand(1111, 9999),
  122. 'user_id' => $orderMain->user_id,
  123. 'store_id' => $item['store_id'],
  124. 'order_main_id' => $orderMainId,
  125. 'state' => OrderMain::ORDER_STATE_UNPAY,
  126. 'tel' => $orderMain->tel,
  127. 'name' => $orderMain->name,
  128. 'address' => $orderMain->address,
  129. 'area' => $orderMain->area,
  130. 'time' => date("Y-m-d H:i:s"),
  131. 'note' => $item['note'] ?? '',
  132. 'delivery_time' => $orderMain->delivery_time,
  133. 'type' => $orderMain->type,
  134. 'lat' => $orderMain->lat,
  135. 'lng' => $orderMain->lng,
  136. 'pay_type' => $orderMain->pay_type,
  137. 'order_type' => $orderMain->order_type,
  138. 'money' => floatval($item['subtotal']),
  139. 'box_money' => floatval($item['box_money']),
  140. 'mj_money' => floatval($item['mj_money']),
  141. 'yhq_money' => floatval($item['yhq_money']),
  142. 'yhq_money2' => floatval($item['yhq_money2']),
  143. 'zk_money' => floatval($item['zk_money']),
  144. 'coupon_id' => $item['coupon_id'],
  145. 'coupon_id2' => $item['coupon_id2'],
  146. 'xyh_money' => floatval($item['xyh_money']),
  147. 'oid' => (isset($storeOrderCounts[$item['store_id']]) ? $item['store_id'] : 0) + 1,
  148. 'time_add' => date("Y-m-d H:i:s"),
  149. 'jj_note' => '',
  150. 'form_id' => '',
  151. 'form_id2' => '',
  152. 'code' => '',
  153. ];
  154. $orderChildId = Order::query()->insertGetId($dataChild);
  155. // 子订单内商品处理
  156. $goodsAmountTotal = 0;
  157. if (!is_array($item['good_list'])||empty($item['good_list'])) {
  158. Db::rollBack();
  159. return '订单商品异常';
  160. }
  161. foreach ($item['good_list'] as &$goods) {
  162. $goodsAmount = bcadd(floatval($goods['money']), floatval($goods['box_money']));
  163. $goodsAmount = bcmul($goodsAmount, $goods['num']);
  164. $goodsAmountTotal = bcadd($goodsAmountTotal, $goodsAmount);
  165. $orderGoods[$goods['id']] = $goods;
  166. $orderGoods[$goods['id']]['uniacid'] = $data['uniacid'];
  167. $orderGoods[$goods['id']]['order_id'] = $orderChildId;
  168. $orderGoods[$goods['id']]['user_id'] = $dataMain['user_id'];
  169. $orderGoods[$goods['id']]['store_id'] = $item['store_id'];
  170. }
  171. // 子订单优惠总额
  172. $discountAmountTotal = bcadd($dataChild['mj_money'], $dataChild['yhq_money']);
  173. $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['yhq_money2']);
  174. $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['zk_money']);
  175. $discountAmountTotal = bcadd($discountAmountTotal, $dataChild['xyh_money']);
  176. $goodsAmountTotal = bcsub($goodsAmountTotal, $discountAmountTotal, 2);
  177. $orderAmountTotal = bcadd($orderAmountTotal, $goodsAmountTotal, 2);
  178. // 校验子订单金额
  179. if ($goodsAmountTotal != $dataChild['money']) {
  180. Db::rollBack();
  181. return '店铺订单总金额错误';
  182. }
  183. }
  184. // 校验库存
  185. foreach ($orderGoods as $Key => &$goodsItem) {
  186. $goodsItem['combination_id'] = intval($goodsItem['combination_id']);
  187. // 存在规格,则去规格处查库存
  188. $goods = [];
  189. if ($goodsItem['combination_id'] > 0) {
  190. $combination = SpecCombination::query()
  191. ->select(['good_id AS id', 'number AS inventory'])
  192. ->where(['id' => $goodsItem['combination_id']])
  193. ->first()
  194. ->toArray();
  195. $goods = Goods::query()
  196. ->select(['id', 'name', 'is_max'])
  197. ->where(['id' => $combination['id']])
  198. ->first()
  199. ->toArray();
  200. $goods['inventory'] = $combination['inventory'];
  201. } else {
  202. $goods = Goods::query()
  203. ->select(['id', 'name', 'is_max', 'inventory'])
  204. ->where(['id' => $goodsItem['good_id']])
  205. ->first()
  206. ->toArray();
  207. }
  208. if (!$goods) {
  209. Db::rollBack();
  210. return '缺少商品';
  211. }
  212. if($goodsItem['num'] > $goods['inventory'] && $goods['is_max'] != Goods::INVENTORY_NOLIMIT){
  213. Db::rollBack();
  214. return '商品 '.$goods->name.' 库存不足!';
  215. }
  216. }
  217. // 校验总订单金额
  218. $deliveryAmount = 0; # 配送费用
  219. if($dataMain['order_type'] == OrderMain::ORDER_TYPE_ONLINE){
  220. $deliveryAmount = $dataMain['dada_fee'];
  221. }
  222. $orderAmountTotal = bcadd($orderAmountTotal, $deliveryAmount);
  223. # 总订单优惠总额
  224. $discountAmountTotal = bcadd($dataMain['mj_money'], $dataMain['yhq_money']);
  225. $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['yhq_money2']);
  226. $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['zk_money']);
  227. $discountAmountTotal = bcadd($discountAmountTotal, $dataMain['xyh_money']);
  228. $orderAmountTotal = bcsub($orderAmountTotal, $discountAmountTotal, 2);
  229. if ($orderAmountTotal != bcsub(bcadd($dataMain['money'], $deliveryAmount), $discountAmountTotal, 2)) {
  230. Db::rollBack();
  231. return '订单总金额错误';
  232. }
  233. // 添加订单商品
  234. $tempGoods = $orderGoods;
  235. $orderGoods = [];
  236. foreach ($tempGoods as $key => &$value) {
  237. $goodsTemp['good_id'] = $value['good_id'];
  238. $goodsTemp['img'] = $value['logo'];
  239. $goodsTemp['number'] = $value['num'];
  240. $goodsTemp['order_id'] = $value['order_id'];
  241. $goodsTemp['name'] = $value['name'];
  242. $goodsTemp['money'] = $value['money'];
  243. $goodsTemp['dishes_id'] = $value['dishes_id'];
  244. $goodsTemp['spec'] = $value['spec'];
  245. $goodsTemp['is_qg'] = $value['is_qg'];
  246. $goodsTemp['good_unit'] = $value['good_unit'];
  247. $goodsTemp['uniacid'] = $value['uniacid'];
  248. $goodsTemp['combination_id'] = $value['combination_id'];
  249. $orderGoods[] = $goodsTemp;
  250. }
  251. $addOrderGoods = OrderGoods::query()->insert($orderGoods);
  252. if (!$addOrderGoods) {
  253. Db::rollBack();
  254. return '订单商品异常';
  255. }
  256. //判断是否有购买特价商品
  257. $this->purchaseLimitService->ssdbPurchaseRecord($orderGoods,$data['user_id'],$dataMain['global_order_id']);
  258. // 修改总订单金额,金额是计算来的
  259. // TODO 这部分其实可以结合处理优化一下,循环前后关联处理太多
  260. $updateOrderMain = OrderMain::query()->where(['id' => $orderMainId])->update(['money' => $orderAmountTotal, 'total_money' => $dataMain['money']]);
  261. if (!$updateOrderMain) {
  262. Db::rollBack();
  263. return '订单总金额记录失败';
  264. }
  265. // 处理红包的使用
  266. $canUseCoupons = CouponRec::select(['id', 'user_id', 'number', 'number_remain', 'system_coupon_user_id'])
  267. ->whereIn('id', $receiveCouponIds)
  268. ->get()->toArray();
  269. if (is_array($canUseCoupons)&&!empty($canUseCoupons)) {
  270. # 使用记录、更新当前优惠券
  271. foreach ($canUseCoupons as $key => &$coupon) {
  272. $couponUse = [
  273. 'user_id' => $coupon['user_id'],
  274. 'user_receive_id' => $coupon['id'],
  275. 'system_coupon_id' => $coupon['system_coupon_user_id'],
  276. 'order_main_id' => $orderMainId,
  277. 'use_time' => $currentTime,
  278. 'return_time' => 0,
  279. 'number' => 1,
  280. 'status' => 1,
  281. 'update_time' => 0,
  282. ];
  283. var_dump('$couponUse',$couponUse);
  284. $insertRes = CouponUserUse::query()->insert($couponUse);
  285. if ($insertRes) {
  286. $numberRemain = $coupon['number_remain'] - 1;
  287. if ($numberRemain == 0) {
  288. $status = 2;
  289. } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) {
  290. $status = 1;
  291. } elseif ($numberRemain == $coupon['number']) {
  292. $status = 0;
  293. }
  294. $upRes = CouponRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]);
  295. if (!$upRes) {
  296. Db::rollBack();
  297. return '优惠券使用失败';
  298. }
  299. // 缓存使用记录
  300. $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']);
  301. if (!$usedRes) {
  302. Db::rollBack();
  303. return '优惠券使用失败';
  304. }
  305. } else {
  306. Db::rollBack();
  307. return '优惠券使用失败';
  308. }
  309. }
  310. }
  311. Db::commit();
  312. return $orderMainId;
  313. } catch (Exception $e) {
  314. $this->log->event(
  315. LogLabel::ORDER_LOG,
  316. ['message' => $e->getMessage()]
  317. );
  318. Db::rollBack();
  319. return $e->getMessage();
  320. }
  321. }
  322. /**
  323. * @inheritDoc
  324. */
  325. public function addOfflineOrder($data)
  326. {
  327. Db::beginTransaction();
  328. try {
  329. // 主订单数据
  330. $dataMain = [];
  331. // 获取分布式全局ID
  332. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  333. $globalRrderId = $generator->generate();
  334. // 主订单插入数据
  335. $currentTime = time();
  336. $dataMain = [
  337. 'delivery_no' => '',
  338. 'dada_fee' => 0,
  339. 'market_id' => 0,
  340. 'box_money' => 0,
  341. 'ps_money' => 0,
  342. 'mj_money' => 0,
  343. 'xyh_money' => 0,
  344. 'yhq_money' => 0,
  345. 'yhq_money2' => 0,
  346. 'zk_money' => 0,
  347. 'tel' => '',
  348. 'name' => '',
  349. 'address' => '',
  350. 'area' => '',
  351. 'lat' => '',
  352. 'lng' => '',
  353. 'note' => '',
  354. 'form_id' => '',
  355. 'form_id2' => '',
  356. 'delivery_time' => '',
  357. 'order_type' => 0,
  358. 'coupon_id' => 0,
  359. 'coupon_id2' => 0,
  360. 'store_list' => '',
  361. 'receive_coupon_ids' => '',
  362. 'type' => OrderMain::ORDER_TYPE_OFFLINE,
  363. 'time' => date('Y-m-d H:i:s', $currentTime),
  364. 'time_add' => $currentTime,
  365. 'pay_time' => '',
  366. 'pay_type' => OrderMain::ORDER_PAY_WX,
  367. 'state' => OrderMain::ORDER_STATE_UNPAY,
  368. 'dm_state' => OrderMain::ORDER_STATE_UNPAY,
  369. 'code' => $globalRrderId,
  370. 'jj_note' => '',
  371. 'uniacid' => 2,
  372. 'order_num' => 'dm'.date('YmdHis') . mt_rand(1000, 9999),
  373. 'money' => $data['money'],
  374. 'user_id' => $data['user_id'],
  375. 'store_ids' => $data['store_id'],
  376. 'global_order_id' => $globalRrderId,
  377. ];
  378. // 主订单模型保存
  379. $orderMain = OrderMain::create($dataMain);
  380. $orderMainId = $orderMain->id;
  381. // 子订单模型保存
  382. $dataChild = [
  383. 'uniacid' => 1,
  384. 'order_num' => 's'.date('YmdHis') . mt_rand(1000, 9999),
  385. 'user_id' => $orderMain->user_id,
  386. 'store_id' => $data['store_id'],
  387. 'order_main_id' => $orderMainId,
  388. 'state' => OrderMain::ORDER_STATE_UNPAY,
  389. 'dm_state' => OrderMain::ORDER_STATE_UNPAY,
  390. 'tel' => $orderMain->tel,
  391. 'name' => $orderMain->name,
  392. 'address' => $orderMain->address,
  393. 'area' => $orderMain->area,
  394. 'time' => date("Y-m-d H:i:s"),
  395. 'note' => '',
  396. 'delivery_time' => $orderMain->delivery_time,
  397. 'type' => $orderMain->type,
  398. 'lat' => $orderMain->lat,
  399. 'lng' => $orderMain->lng,
  400. 'pay_type' => $orderMain->pay_type,
  401. 'order_type' => $orderMain->order_type,
  402. 'money' => $data['money'],
  403. 'box_money' => 0,
  404. 'mj_money' => 0,
  405. 'yhq_money' => 0,
  406. 'yhq_money2' => 0,
  407. 'zk_money' => 0,
  408. 'coupon_id' => 0,
  409. 'coupon_id2' => 0,
  410. 'xyh_money' => 0,
  411. 'time_add' => date("Y-m-d H:i:s"),
  412. 'jj_note' => '',
  413. 'form_id' => '',
  414. 'form_id2' => '',
  415. 'code' => '',
  416. ];
  417. $orderChildId = Order::query()->insertGetId($dataChild);
  418. Db::commit();
  419. return $orderMainId;
  420. } catch (Exception $e) {
  421. $this->log->event(
  422. LogLabel::ORDER_LOG,
  423. ['message' => $e->getMessage()]
  424. );
  425. Db::rollBack();
  426. return '购买失败';
  427. }
  428. }
  429. /**
  430. * 计算和校验当前订单可用红包及金额
  431. * @param $couponIds
  432. * @param $orderAmount
  433. * @param $userId
  434. * @param $marketId
  435. * @return int|string
  436. * @throws Exception
  437. */
  438. protected function getCouponAmount($couponIds, $orderAmount, $userId, $marketId)
  439. {
  440. // 用户当前订单可用优惠券
  441. $couponsCanUse = $this->couponService->getOrderCanUseCoupons(
  442. $orderAmount,
  443. $marketId,
  444. $userId,
  445. [
  446. 'receive.id',
  447. 'receive.user_id',
  448. 'receive.number',
  449. 'receive.number_remain',
  450. 'receive.system_coupon_user_id',
  451. 'coupon.discounts',
  452. 'coupon.discount_type',
  453. ]
  454. );
  455. $couponCanUseIds = array_column($couponsCanUse, 'id');
  456. $couponCanUseIds = array_intersect($couponCanUseIds, $couponIds);
  457. $couponCannotUseIds = array_diff($couponIds, $couponCanUseIds);
  458. if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) {
  459. throw new Exception('您的订单中有优惠券已经失效');
  460. }
  461. // 计算红包折扣金额
  462. $couponMoney = 0;
  463. foreach ($couponsCanUse as $key => $coupon) {
  464. if (!in_array($coupon->id, $couponIds)) {
  465. continue;
  466. }
  467. if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
  468. $couponMoney = bcadd($couponMoney, $coupon->discounts, 2);
  469. } elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
  470. $discountRate = bcdiv($coupon->discounts,10);
  471. $discountRate = bcsub(1,$discountRate);
  472. $discountMoney = bcmul($orderAmount, $discountRate);
  473. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  474. }
  475. }
  476. return $couponMoney;
  477. }
  478. /**
  479. * @inheritDoc
  480. */
  481. public function existsByGlobalOrderId($global_order_id)
  482. {
  483. return OrderMain::query()->where(['order_num' => $global_order_id])->value('id');
  484. }
  485. /**
  486. * @inheritDoc
  487. */
  488. public function onlineCompleted($global_order_id)
  489. {
  490. Db::beginTransaction();
  491. try {
  492. // 主订单状态更新
  493. $orderMain = OrderMain::query()
  494. ->where(['global_order_id' => $global_order_id, 'state' => OrderMain::ORDER_STATE_DELIVERY])
  495. ->first();
  496. if (empty($orderMain)) {
  497. Db::rollBack();
  498. return false;
  499. }
  500. $orderMain->state = OrderMain::ORDER_STATE_COMPLETE;
  501. $orderMain->save();
  502. // 子订单状态更新
  503. $upChild = Order::query()
  504. ->where(['order_main_id' => $orderMain->id])
  505. ->update(['state' => OrderMain::ORDER_STATE_COMPLETE]);
  506. Db::commit();
  507. return true;
  508. } catch (Exception $e) {
  509. $this->log->event(LogLabel::ONLINE_COMPLETE_LOG, ['exception' => $e->getMessage()]);
  510. Db::rollBack();
  511. return false;
  512. }
  513. }
  514. /**
  515. * @inheritDoc
  516. */
  517. public function onlinePaid($global_order_id)
  518. {
  519. Db::beginTransaction();
  520. try {
  521. // 查询订单
  522. $orderMain = OrderMain::query()
  523. ->where([
  524. 'global_order_id' => $global_order_id,
  525. 'type' => OrderMain::ORDER_TYPE_ONLINE
  526. ])
  527. ->first();
  528. // 修改订单、子订单状态
  529. $currentTime = time();
  530. $orderMain->state = OrderMain::ORDER_STATE_UNTAKE;
  531. $orderMain->time_pay = $currentTime;
  532. $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime);
  533. $orderMain->save();
  534. $upOrder = Order::query()
  535. ->where(['order_main_id' => $orderMain->id])
  536. ->update(['state' => OrderMain::ORDER_STATE_UNTAKE, 'pay_time' => $orderMain->pay_time]);
  537. // 更新商户销量
  538. $upStoreScore = Store::query()
  539. ->whereIn('id', explode(',', $orderMain->store_ids))
  540. ->update(['score' => Db::raw('score+1')]);
  541. // 更新商品库存和销量
  542. $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time'])
  543. ->where(['order_main_id' => $orderMain->id])
  544. ->get()
  545. ->toArray();
  546. $orderGoods = OrderGoods::query()->select(['good_id AS id', 'number', 'combination_id'])
  547. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  548. ->get()
  549. ->toArray();
  550. foreach ($orderGoods as $key => &$goodsItem) {
  551. $goods = Goods::find($goodsItem['id']);
  552. // 库存处理,有规格
  553. if ($goodsItem['combination_id']) {
  554. $combination = SpecCombination::find($goodsItem['combination_id']);
  555. $combination->number = $combination->number - $goodsItem['number'];
  556. $combination->save();
  557. } else {
  558. $goods->inventory = $goods->inventory - $goodsItem['number'];
  559. }
  560. $goods->sales = $goods->sales - $goodsItem['number'];
  561. $goods->save();
  562. }
  563. // 月销流水
  564. $statistics = [];
  565. foreach ($orders as $key => &$order) {
  566. $statistics[] = [
  567. 'money' => $order['money'],
  568. 'user_id' => $order['user_id'],
  569. 'store_id' => $order['store_id'],
  570. 'market_id' => $orderMain->market_id,
  571. 'order_id' => $order['id'],
  572. 'createtime' => strtotime($order['pay_time']),
  573. ];
  574. }
  575. if (is_array($statistics) && !empty($statistics)) {
  576. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  577. }
  578. Db::commit();
  579. return true;
  580. } catch (Exception $e) {
  581. $this->log->event(LogLabel::ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  582. Db::rollBack();
  583. return false;
  584. }
  585. }
  586. /**
  587. * @inheritDoc
  588. */
  589. public function offlinePaid($global_order_id)
  590. {
  591. Db::beginTransaction();
  592. try {
  593. // 主订单状态更新
  594. $orderMain = OrderMain::query()
  595. ->where(['global_order_id' => $global_order_id, 'type' => OrderMain::ORDER_TYPE_OFFLINE])
  596. ->first();
  597. if (empty($orderMain)) {
  598. $this->log->event(
  599. LogLabel::PAY_NOTIFY_WXMINI,
  600. ['order_not_found' => $global_order_id]
  601. );
  602. Db::rollBack();
  603. return false;
  604. }
  605. $currentTime = time();
  606. $orderMain->state = OrderMain::ORDER_STATE_UNTAKE;
  607. $orderMain->dm_state = OrderMain::ORDER_STATE_UNTAKE;
  608. $orderMain->time_pay = $currentTime;
  609. $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime);
  610. $orderMain->save();
  611. // 子订单状态更新
  612. $upOrder = Order::query()
  613. ->where(['order_main_id' => $orderMain->id])
  614. ->update([
  615. 'state' => OrderMain::ORDER_STATE_UNTAKE,
  616. 'dm_state' => OrderMain::ORDER_STATE_UNTAKE,
  617. 'pay_time' => date('Y-m-d H:i:s', $currentTime)
  618. ]);
  619. Db::commit();
  620. return true;
  621. } catch (Exception $e) {
  622. $this->log->event(LogLabel::OFFLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  623. Db::rollBack();
  624. return false;
  625. }
  626. }
  627. /**
  628. * @inheritDoc
  629. */
  630. public function onlineCancel($global_order_id){
  631. OrderMain::where('global_order_id',$global_order_id)
  632. ->update(['state' => OrderMain::ORDER_STATE_CANCEL]);
  633. //撤销redis 用券记录
  634. $redisRes = $this->couponService->orderRefundCoupons($global_order_id);
  635. //撤销特价商品购买记录
  636. $ssdbRes = $this->purchaseLimitService->delSsdbPurchaseRecord($global_order_id);
  637. return $redisRes && $ssdbRes;
  638. }
  639. /**
  640. * @inheritDoc
  641. */
  642. public function onlineRefund($global_order_id)
  643. {
  644. Db::beginTransaction();
  645. try {
  646. // 主订单状态更新
  647. $orderMain = OrderMain::query()
  648. ->select('id','global_order_id','state','pay_type','user_id','money')
  649. ->where(['global_order_id' => $global_order_id, 'state' => OrderMain::ORDER_STATE_REFUNDING])
  650. ->first();
  651. if (empty($orderMain)) {
  652. Db::rollBack();
  653. return '查询不到订单';
  654. }
  655. $orderMain->state = OrderMain::ORDER_STATE_REFUNDED;
  656. if(!$orderMain->save()){
  657. Db::rollBack();
  658. return '更新主订单失败';
  659. };
  660. // 子订单状态更新
  661. $upChild = Order::query()
  662. ->where('order_main_id' , $orderMain->id)
  663. ->where('state',OrderMain::ORDER_STATE_REFUNDING)
  664. ->update(['state' => OrderMain::ORDER_STATE_REFUNDED]);
  665. if(empty($upChild)){
  666. Db::rollBack();
  667. return '更新子订单失败';
  668. }
  669. if($orderMain->pay_type == OrderMain::ORDER_PAY_WX){
  670. $data = [
  671. 'global_order_id' => $global_order_id,
  672. 'money' => $orderMain->money
  673. ];
  674. // 微信支付 微信退款
  675. $refundRes = $this->wxRefundService->wxPayRefund($data);
  676. var_dump($refundRes);
  677. if(
  678. empty($refundRes)
  679. || !isset($refundRes['result_code'])
  680. || $refundRes['result_code'] != 'SUCCESS'
  681. ){
  682. Db::rollBack();
  683. return $refundRes;
  684. };
  685. /* --- 退款成功 --- */
  686. $orderMain = $orderMain->fresh();
  687. if(empty($orderMain->refund_time)){
  688. // 添加退款时间
  689. $orderMain->refund_time = time();
  690. $orderMain->save();
  691. // 退款返还优惠券
  692. $this->couponService->orderRefundCoupons($orderMain->global_order_id);
  693. // 删除特价商品缓存
  694. $this->purchaseLimitService->delSsdbPurchaseRecord($orderMain->id);
  695. // 添加用户的流水
  696. $this->financialService->userByOLOrderRefund($orderMain->user_id, $orderMain->global_order_id, $orderMain->money);
  697. }
  698. }else if($orderMain->pay_type == OrderMain::ORDER_PAY_BALANCE){
  699. // 余额支付 退款到用户余额
  700. // if($this->userService->userWallet($orderMain->user_id,$orderMain->money,Users::WALLET_TYPE_INC)){
  701. // Db::rollBack();
  702. // return false;
  703. // };
  704. // 返还优惠券
  705. // $this->couponService->orderRefundCoupon($global_order_id);
  706. // 删除特价商品缓存
  707. // $this->orderService->clearTodayGoodPurchase($orderMain->user_id,1);
  708. // 添加用户流水
  709. // $this->financialService->userByOLOrderRefund($orderMain->user_id, $orderMain->global_order_id, $orderMain->money);
  710. }
  711. Db::commit();
  712. return true;
  713. } catch (\Exception $e) {
  714. $this->log->event(LogLabel::ORDER_LOG, ['msg'=> '订单退款','exception' => $e->getMessage()]);
  715. Db::rollBack();
  716. return false;
  717. }
  718. }
  719. /**
  720. * 订单退款失败
  721. * 回退订单状态
  722. */
  723. public function onlineRefundFail($global_order_id)
  724. {
  725. Db::beginTransaction();
  726. try {
  727. $time = time();
  728. // 主订单状态更新
  729. $orderMain = OrderMain::query()
  730. ->select('id','global_order_id','state','pay_type')
  731. ->where(['global_order_id' => $global_order_id, 'state' => OrderMain::ORDER_STATE_REFUNDED])
  732. ->first();
  733. if (empty($orderMain)) {
  734. Db::rollBack();
  735. return false;
  736. }
  737. $orderMain->state = OrderMain::ORDER_STATE_REFUNDING;
  738. $upOrderMain = $orderMain->save();
  739. // 子订单状态更新
  740. $upChild = Order::query()
  741. ->where('order_main_id' , $orderMain->id)
  742. ->where('state',OrderMain::ORDER_STATE_REFUNDED)
  743. ->update(['state' => OrderMain::ORDER_STATE_REFUNDING]);
  744. if(empty($upChild)){
  745. Db::rollBack();
  746. return false;
  747. }
  748. Db::commit();
  749. return true;
  750. } catch (Exception $e) {
  751. $this->log->event(LogLabel::ORDER_LOG, ['msg'=> '订单退款失败时处理状态9->8 ','exception' => $e->getMessage()]);
  752. Db::rollBack();
  753. return false;
  754. }
  755. }
  756. /**
  757. * 删除特价商品缓存
  758. */
  759. public function clearTodayGoodPurchase($userId, $goodId)
  760. {
  761. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  762. return $ssdb->exec('del', SsdbKeysPrefix::PURCHASE_RECORD. date('Ymd') .'_'.$userId, $goodId);
  763. }
  764. }