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.

985 lines
35 KiB

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