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.

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