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.

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