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.

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