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.

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