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.

986 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
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. $insertRes = CouponUserUse::query()->insert($couponUse);
  296. if ($insertRes) {
  297. $numberRemain = $coupon['number_remain'] - 1;
  298. if ($numberRemain == 0) {
  299. $status = 2;
  300. } elseif ($numberRemain > 0 && $numberRemain < $coupon['number']) {
  301. $status = 1;
  302. } elseif ($numberRemain == $coupon['number']) {
  303. $status = 0;
  304. }
  305. $upRes = CouponRec::query()->where(['id' => $coupon['id']])->update(['number_remain' => $numberRemain, 'status' => $status]);
  306. if (!$upRes) {
  307. Db::rollBack();
  308. return '优惠券使用失败';
  309. }
  310. // 缓存使用记录
  311. $usedRes = $this->couponService->cacheTodayCouponUsed($coupon['user_id'], $coupon['system_coupon_user_id'], $coupon['id']);
  312. if (!$usedRes) {
  313. Db::rollBack();
  314. return '优惠券使用失败';
  315. }
  316. } else {
  317. Db::rollBack();
  318. return '优惠券使用失败';
  319. }
  320. }
  321. }
  322. Db::commit();
  323. return $orderMainId;
  324. } catch (Exception $e) {
  325. $this->log->event(
  326. LogLabel::ORDER_LOG,
  327. ['message' => $e->getMessage()]
  328. );
  329. Db::rollBack();
  330. return $e->getMessage();
  331. }
  332. }
  333. /**
  334. * @inheritDoc
  335. */
  336. public function addOfflineOrder($data)
  337. {
  338. Db::beginTransaction();
  339. try {
  340. // 主订单数据
  341. $dataMain = [];
  342. // 获取分布式全局ID
  343. $generator = ApplicationContext::getContainer()->get(IdGeneratorInterface::class);
  344. $globalRrderId = $generator->generate();
  345. // 主订单插入数据
  346. $currentTime = time();
  347. $dataMain = [
  348. 'delivery_no' => '',
  349. 'dada_fee' => 0,
  350. 'market_id' => 0,
  351. 'box_money' => 0,
  352. 'ps_money' => 0,
  353. 'mj_money' => 0,
  354. 'xyh_money' => 0,
  355. 'yhq_money' => 0,
  356. 'yhq_money2' => 0,
  357. 'zk_money' => 0,
  358. 'tel' => '',
  359. 'name' => '',
  360. 'address' => '',
  361. 'area' => '',
  362. 'lat' => '',
  363. 'lng' => '',
  364. 'note' => '',
  365. 'form_id' => '',
  366. 'form_id2' => '',
  367. 'delivery_time' => '',
  368. 'order_type' => 0,
  369. 'coupon_id' => 0,
  370. 'coupon_id2' => 0,
  371. 'store_list' => '',
  372. 'receive_coupon_ids' => '',
  373. 'type' => OrderMain::ORDER_TYPE_OFFLINE,
  374. 'time' => date('Y-m-d H:i:s', $currentTime),
  375. 'time_add' => $currentTime,
  376. 'pay_time' => '',
  377. 'pay_type' => OrderMain::ORDER_PAY_WX,
  378. 'state' => OrderMain::ORDER_STATE_UNPAY,
  379. 'dm_state' => OrderMain::ORDER_STATE_UNPAY,
  380. 'code' => $globalRrderId,
  381. 'jj_note' => '',
  382. 'uniacid' => 2,
  383. 'order_num' => 'dm'.date('YmdHis') . mt_rand(1000, 9999),
  384. 'money' => $data['money'],
  385. 'user_id' => $data['user_id'],
  386. 'store_ids' => $data['store_id'],
  387. 'global_order_id' => $globalRrderId,
  388. ];
  389. // 主订单模型保存
  390. $orderMain = OrderMain::create($dataMain);
  391. $orderMainId = $orderMain->id;
  392. // 子订单模型保存
  393. $dataChild = [
  394. 'uniacid' => 1,
  395. 'order_num' => 's'.date('YmdHis') . mt_rand(1000, 9999),
  396. 'user_id' => $orderMain->user_id,
  397. 'store_id' => $data['store_id'],
  398. 'order_main_id' => $orderMainId,
  399. 'state' => OrderMain::ORDER_STATE_UNPAY,
  400. 'dm_state' => OrderMain::ORDER_STATE_UNPAY,
  401. 'tel' => $orderMain->tel,
  402. 'name' => $orderMain->name,
  403. 'address' => $orderMain->address,
  404. 'area' => $orderMain->area,
  405. 'time' => date("Y-m-d H:i:s"),
  406. 'note' => '',
  407. 'delivery_time' => $orderMain->delivery_time,
  408. 'type' => $orderMain->type,
  409. 'lat' => $orderMain->lat,
  410. 'lng' => $orderMain->lng,
  411. 'pay_type' => $orderMain->pay_type,
  412. 'order_type' => $orderMain->order_type,
  413. 'money' => $data['money'],
  414. 'box_money' => 0,
  415. 'mj_money' => 0,
  416. 'yhq_money' => 0,
  417. 'yhq_money2' => 0,
  418. 'zk_money' => 0,
  419. 'coupon_id' => 0,
  420. 'coupon_id2' => 0,
  421. 'xyh_money' => 0,
  422. 'time_add' => date("Y-m-d H:i:s"),
  423. 'jj_note' => '',
  424. 'form_id' => '',
  425. 'form_id2' => '',
  426. 'code' => '',
  427. ];
  428. $orderChildId = Order::query()->insertGetId($dataChild);
  429. Db::commit();
  430. return $orderMainId;
  431. } catch (Exception $e) {
  432. $this->log->event(
  433. LogLabel::ORDER_LOG,
  434. ['message' => $e->getMessage()]
  435. );
  436. Db::rollBack();
  437. return '购买失败';
  438. }
  439. }
  440. /**
  441. * 计算和校验当前订单可用红包及金额
  442. * @param $couponIds
  443. * @param $orderAmount
  444. * @param $userId
  445. * @param $marketId
  446. * @return int|string
  447. * @throws Exception
  448. */
  449. protected function getCouponAmount($couponIds, $orderAmount, $userId, $marketId)
  450. {
  451. // 用户当前订单可用优惠券
  452. $couponsCanUse = $this->couponService->getOrderCanUseCoupons(
  453. $orderAmount,
  454. $marketId,
  455. $userId,
  456. [
  457. 'receive.id',
  458. 'receive.user_id',
  459. 'receive.number',
  460. 'receive.number_remain',
  461. 'receive.system_coupon_user_id',
  462. 'coupon.discounts',
  463. 'coupon.discount_type',
  464. ]
  465. );
  466. $couponCanUseIds = array_column($couponsCanUse, 'id');
  467. $couponCanUseIds = array_intersect($couponCanUseIds, $couponIds);
  468. $couponCannotUseIds = array_diff($couponIds, $couponCanUseIds);
  469. if (empty($couponCanUseIds)||!empty($couponCannotUseIds)) {
  470. throw new Exception('您的订单中有优惠券已经失效');
  471. }
  472. // 计算红包折扣金额
  473. $couponMoney = 0;
  474. foreach ($couponsCanUse as $key => $coupon) {
  475. if (!in_array($coupon->id, $couponIds)) {
  476. continue;
  477. }
  478. if ($coupon->discount_type == Coupon::DISCOUNT_TYPE_CASH) {
  479. $couponMoney = bcadd($couponMoney, $coupon->discounts, 2);
  480. } elseif ($coupon->discount_type == Coupon::DISCOUNT_TYPE_RATE) {
  481. $discountRate = bcdiv($coupon->discounts,10);
  482. $discountRate = bcsub(1,$discountRate);
  483. $discountMoney = bcmul($orderAmount, $discountRate);
  484. $couponMoney = bcadd($couponMoney, $discountMoney, 2);
  485. }
  486. }
  487. return $couponMoney;
  488. }
  489. /**
  490. * @inheritDoc
  491. */
  492. public function existsByGlobalOrderId($global_order_id)
  493. {
  494. return OrderMain::query()->where(['order_num' => $global_order_id])->value('id');
  495. }
  496. /**
  497. * @inheritDoc
  498. */
  499. public function onlineCompleted($global_order_id)
  500. {
  501. Db::beginTransaction();
  502. try {
  503. // 主订单状态更新
  504. $orderMain = OrderMain::query()
  505. ->where(['global_order_id' => $global_order_id, 'state' => OrderMain::ORDER_STATE_DELIVERY])
  506. ->first();
  507. if (empty($orderMain)) {
  508. Db::rollBack();
  509. return false;
  510. }
  511. $orderMain->state = OrderMain::ORDER_STATE_COMPLETE;
  512. $orderMain->save();
  513. // 子订单状态更新
  514. $upChild = Order::query()
  515. ->where(['order_main_id' => $orderMain->id])
  516. ->update(['state' => OrderMain::ORDER_STATE_COMPLETE]);
  517. Db::commit();
  518. return true;
  519. } catch (Exception $e) {
  520. $this->log->event(LogLabel::ONLINE_COMPLETE_LOG, ['exception' => $e->getMessage()]);
  521. Db::rollBack();
  522. return false;
  523. }
  524. }
  525. /**
  526. * @inheritDoc
  527. */
  528. public function onlinePaid($global_order_id)
  529. {
  530. Db::beginTransaction();
  531. try {
  532. // 查询订单
  533. $orderMain = OrderMain::query()
  534. ->where([
  535. 'global_order_id' => $global_order_id,
  536. 'type' => OrderMain::ORDER_TYPE_ONLINE
  537. ])
  538. ->first();
  539. // 修改订单、子订单状态
  540. $currentTime = time();
  541. $orderMain->state = OrderMain::ORDER_STATE_UNTAKE;
  542. $orderMain->time_pay = $currentTime;
  543. $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime);
  544. $orderMain->save();
  545. $upOrder = Order::query()
  546. ->where(['order_main_id' => $orderMain->id])
  547. ->update(['state' => OrderMain::ORDER_STATE_UNTAKE, 'pay_time' => $orderMain->pay_time]);
  548. // 更新商户销量
  549. $upStoreScore = Store::query()
  550. ->whereIn('id', explode(',', $orderMain->store_ids))
  551. ->update(['score' => Db::raw('score+1')]);
  552. // 更新商品库存和销量
  553. $orders = Order::query()->select(['id', 'money', 'user_id', 'store_id', 'pay_time'])
  554. ->where(['order_main_id' => $orderMain->id])
  555. ->get()
  556. ->toArray();
  557. $orderGoods = OrderGoods::query()->select(['good_id AS id', 'number', 'combination_id'])
  558. ->whereIn('order_id', array_values(array_column($orders, 'id')))
  559. ->get()
  560. ->toArray();
  561. foreach ($orderGoods as $key => &$goodsItem) {
  562. $goods = Goods::find($goodsItem['id']);
  563. // 库存处理,有规格
  564. if ($goodsItem['combination_id']) {
  565. $combination = SpecCombination::find($goodsItem['combination_id']);
  566. $combination->number = $combination->number - $goodsItem['number'];
  567. $combination->save();
  568. } else {
  569. $goods->inventory = $goods->inventory - $goodsItem['number'];
  570. }
  571. $goods->sales = $goods->sales + $goodsItem['number'];
  572. $goods->save();
  573. }
  574. // 月销流水
  575. $statistics = [];
  576. foreach ($orders as $key => &$order) {
  577. $statistics[] = [
  578. 'money' => $order['money'],
  579. 'user_id' => $order['user_id'],
  580. 'store_id' => $order['store_id'],
  581. 'market_id' => $orderMain->market_id,
  582. 'order_id' => $order['id'],
  583. 'createtime' => strtotime($order['pay_time']),
  584. ];
  585. }
  586. if (is_array($statistics) && !empty($statistics)) {
  587. $inSalesStatistics = OrderSalesStatistic::query()->insert($statistics);
  588. }
  589. Db::commit();
  590. return true;
  591. } catch (Exception $e) {
  592. $this->log->event(LogLabel::ONLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  593. Db::rollBack();
  594. return false;
  595. }
  596. }
  597. /**
  598. * @inheritDoc
  599. */
  600. public function offlinePaid($global_order_id)
  601. {
  602. Db::beginTransaction();
  603. try {
  604. // 主订单状态更新
  605. $orderMain = OrderMain::query()
  606. ->where(['global_order_id' => $global_order_id, 'type' => OrderMain::ORDER_TYPE_OFFLINE])
  607. ->first();
  608. if (empty($orderMain)) {
  609. $this->log->event(
  610. LogLabel::PAY_NOTIFY_WXMINI,
  611. ['order_not_found' => $global_order_id]
  612. );
  613. Db::rollBack();
  614. return false;
  615. }
  616. $currentTime = time();
  617. $orderMain->state = OrderMain::ORDER_STATE_UNTAKE;
  618. $orderMain->dm_state = OrderMain::ORDER_STATE_UNTAKE;
  619. $orderMain->time_pay = $currentTime;
  620. $orderMain->pay_time = date('Y-m-d H:i:s', $currentTime);
  621. $orderMain->save();
  622. // 子订单状态更新
  623. $upOrder = Order::query()
  624. ->where(['order_main_id' => $orderMain->id])
  625. ->update([
  626. 'state' => OrderMain::ORDER_STATE_UNTAKE,
  627. 'dm_state' => OrderMain::ORDER_STATE_UNTAKE,
  628. 'pay_time' => date('Y-m-d H:i:s', $currentTime)
  629. ]);
  630. Db::commit();
  631. return true;
  632. } catch (Exception $e) {
  633. $this->log->event(LogLabel::OFFLINE_PAID_LOG, ['exception' => $e->getMessage()]);
  634. Db::rollBack();
  635. return false;
  636. }
  637. }
  638. /**
  639. * @inheritDoc
  640. */
  641. public function onlineCancel($global_order_id){
  642. $sqlRes = OrderMain::where('global_order_id',$global_order_id)
  643. ->update(['state' => OrderMain::ORDER_STATE_CANCEL]);
  644. if(!$sqlRes){
  645. return false;
  646. }
  647. //撤销redis 用券记录
  648. $redisRes = $this->couponService->orderRefundCoupons($global_order_id);
  649. //撤销特价商品购买记录
  650. $ssdbRes = $this->purchaseLimitService->delSsdbPurchaseRecord($global_order_id);
  651. return $redisRes && $ssdbRes;
  652. }
  653. /**
  654. * @inheritDoc
  655. */
  656. public function onlineRefund($global_order_id)
  657. {
  658. Db::beginTransaction();
  659. try {
  660. // 主订单状态更新
  661. $orderMain = OrderMain::query()
  662. ->select('id','global_order_id','state','pay_type','user_id','money')
  663. ->where(['global_order_id' => $global_order_id, 'state' => OrderMain::ORDER_STATE_REFUNDING])
  664. ->first();
  665. if (empty($orderMain)) {
  666. Db::rollBack();
  667. return [
  668. 'code' => 1,
  669. 'msg' =>'查询不到订单'
  670. ];
  671. }
  672. $orderMain->state = OrderMain::ORDER_STATE_REFUNDED;
  673. if(!$orderMain->save()){
  674. Db::rollBack();
  675. return [
  676. 'code' => 2,
  677. 'msg' =>'更新主订单失败'
  678. ];
  679. };
  680. // 子订单状态更新
  681. $upChild = Order::query()
  682. ->where('order_main_id' , $orderMain->id)
  683. ->where('state',OrderMain::ORDER_STATE_REFUNDING)
  684. ->update(['state' => OrderMain::ORDER_STATE_REFUNDED]);
  685. if(empty($upChild)){
  686. Db::rollBack();
  687. return [
  688. 'code' => 3,
  689. 'msg' =>'更新子订单失败'
  690. ];
  691. }
  692. if($orderMain->pay_type == OrderMain::ORDER_PAY_WX){
  693. // 微信支付 微信退款
  694. $refundRes = $this->wxRefundService->wxPayRefund($orderMain->global_order_id);
  695. if(
  696. empty($refundRes)
  697. || !$refundRes
  698. || !isset($refundRes['result_code'])
  699. || $refundRes['result_code'] != 'SUCCESS'
  700. ){
  701. Db::rollBack();
  702. return $refundRes;
  703. };
  704. }else if($orderMain->pay_type == OrderMain::ORDER_PAY_BALANCE){
  705. // 余额支付 退款到用户余额
  706. if($this->userService->userWallet($orderMain->user_id,$orderMain->money,Users::WALLET_TYPE_INC)){
  707. Db::rollBack();
  708. return [
  709. 'code' => 4,
  710. 'msg' =>'退款到用户余额失败'
  711. ];
  712. };
  713. }
  714. /* --- 退款成功 --- */
  715. $orderMain = $orderMain->fresh();
  716. if(empty($orderMain->refund_time)){
  717. // 添加退款时间
  718. $orderMain->refund_time = time();
  719. $orderMain->save();
  720. // 退款返还优惠券
  721. $this->couponService->orderRefundCoupons($orderMain->global_order_id);
  722. // 删除特价商品缓存
  723. $this->purchaseLimitService->delSsdbPurchaseRecord($orderMain->global_order_id);
  724. // 添加用户的流水
  725. $this->financialService->userByOLOrderRefund($orderMain->user_id, $orderMain->global_order_id, $orderMain->money);
  726. }
  727. Db::commit();
  728. return [
  729. 'code' => 0,
  730. 'msg' =>'退款成功'
  731. ];
  732. } catch (\Exception $e) {
  733. $this->log->event(LogLabel::ORDER_LOG, ['msg'=> '订单退款','exception' => $e->getMessage()]);
  734. Db::rollBack();
  735. return [
  736. 'code' => 5,
  737. 'msg' => $e->getMessage()
  738. ];
  739. }
  740. }
  741. /**
  742. * 订单退款失败
  743. * 回退订单状态
  744. */
  745. public function onlineRefundFail($global_order_id)
  746. {
  747. Db::beginTransaction();
  748. try {
  749. $time = time();
  750. // 主订单状态更新
  751. $orderMain = OrderMain::query()
  752. ->select('id','global_order_id','state','pay_type')
  753. ->where(['global_order_id' => $global_order_id, 'state' => OrderMain::ORDER_STATE_REFUNDED])
  754. ->first();
  755. if (empty($orderMain)) {
  756. Db::rollBack();
  757. return false;
  758. }
  759. $orderMain->state = OrderMain::ORDER_STATE_REFUNDING;
  760. $upOrderMain = $orderMain->save();
  761. // 子订单状态更新
  762. $upChild = Order::query()
  763. ->where('order_main_id' , $orderMain->id)
  764. ->where('state',OrderMain::ORDER_STATE_REFUNDED)
  765. ->update(['state' => OrderMain::ORDER_STATE_REFUNDING]);
  766. if(empty($upChild)){
  767. Db::rollBack();
  768. return false;
  769. }
  770. Db::commit();
  771. return true;
  772. } catch (Exception $e) {
  773. $this->log->event(LogLabel::ORDER_LOG, ['msg'=> '订单退款失败时处理状态9->8 ','exception' => $e->getMessage()]);
  774. Db::rollBack();
  775. return false;
  776. }
  777. }
  778. /**
  779. * 删除特价商品缓存
  780. */
  781. public function clearTodayGoodPurchase($userId, $goodId)
  782. {
  783. $ssdb = ApplicationContext::getContainer()->get(SSDBTask::class);
  784. return $ssdb->exec('del', SsdbKeysPrefix::PURCHASE_RECORD. date('Ymd') .'_'.$userId, $goodId);
  785. }
  786. /**
  787. * @inheritDoc
  788. */
  789. public function onlineAutoCancelByUserId($user_id)
  790. {
  791. Db::beginTransaction();
  792. try {
  793. $orders = OrderMain::query()
  794. ->select(['id', 'global_order_id'])
  795. ->where([
  796. 'user_id' => $user_id,
  797. 'state' => OrderMain::ORDER_STATE_UNPAY
  798. ])
  799. ->where('time_add', '<', (time()-900))
  800. ->get()->toArray();
  801. foreach ($orders as $key => &$item) {
  802. $order = OrderMain::query()->find($item['id']);
  803. $order->state = OrderMain::ORDER_STATE_CANCEL;
  804. $order->save();
  805. //撤销redis 用券记录
  806. $this->couponService->orderRefundCoupons($item['global_order_id']);
  807. //撤销特价商品购买记录
  808. $this->purchaseLimitService->delSsdbPurchaseRecord($item['global_order_id']);
  809. }
  810. Db::commit();
  811. return true;
  812. } catch (Exception $e) {
  813. $this->log->event(LogLabel::AUTO_CANCEL_USER_ORDER, ['exception' => $e->getMessage()]);
  814. Db::rollBack();
  815. return false;
  816. }
  817. }
  818. /**
  819. * @inheritDoc
  820. */
  821. public function userOnlineOrders($user_id, $state, $page=1, $pagesize=10)
  822. {
  823. $builder = OrderMain::query()
  824. ->where(['user_id' => $user_id, 'del' => OrderMain::ORDER_DEL_NO, 'type' => OrderMain::ORDER_TYPE_ONLINE]);
  825. if ($state != 0) {
  826. $state = explode(',', $state);
  827. $builder = $builder->whereIn('state', $state);
  828. }
  829. $orders = $builder->orderBy('id', 'desc')
  830. ->orderBy('state', 'asc')
  831. ->get()->forPage($page, $pagesize)->toArray();
  832. foreach ($orders as $key => &$order) {
  833. // 市场名称
  834. $order['market_name'] = Market::query()->where(['id' => $order['market_id']])->value('name');
  835. // 商品数量和第一个商品名、图
  836. $orderChildIds = Order::query()->select(['id'])->where(['order_main_id' => $order['id']])->get()->toArray();
  837. $orderChildIds = array_values(array_column($orderChildIds, 'id'));
  838. $order['g_num'] = OrderGoods::query()->whereIn('order_id', $orderChildIds)->count();
  839. $goods = OrderGoods::query()->whereIn('order_id', $orderChildIds)->select(['name', 'img'])->first();
  840. $order['good_name'] = $goods->name;
  841. // TODO 临时写死oss压缩类型
  842. $order['img'] = $this->attachmentService->switchImgToAliOss($goods->img);
  843. }
  844. return $orders;
  845. }
  846. }