OrderService.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. <?php
  2. namespace app\admin\service\order;
  3. use app\model\CouponDetail;
  4. use app\model\CouponGoods;
  5. use app\model\GoodsRunning;
  6. use app\model\GoodsSku;
  7. use app\model\Member;
  8. use app\model\MemberBenefit;
  9. use app\model\Order;
  10. use app\model\OrderSheet;
  11. use app\model\PayDetail;
  12. use app\model\SysDept;
  13. use support\Db;
  14. use support\exception\BusinessException;
  15. use support\Log as SupportLog;
  16. use support\Redis;
  17. use Webman\Event\Event;
  18. use Yansongda\Pay\Exceptions\GatewayException;
  19. use Yansongda\Pay\Log;
  20. use Yansongda\Pay\Pay;
  21. class OrderService
  22. {
  23. /**
  24. * @Desc 自动确认收货
  25. * @Author Gorden
  26. * @Date 2024/4/11 16:09
  27. *
  28. * @return void
  29. */
  30. public static function AutomaticReceipt()
  31. {
  32. try {
  33. Db::beginTransaction();
  34. $timeUnix = strtotime("-7 days");
  35. $orders = Order::where('order_status_system', 'SIGNED')
  36. ->where('order_addtimes', '<', $timeUnix)
  37. ->get();
  38. foreach ($orders as $order) {
  39. // 订单主表
  40. Order::where('order_id', $order->order_id)->update([
  41. 'order_is_complete' => 'Y',
  42. 'order_status_system' => 'CONFIRM',
  43. 'order_status_storage' => 'DONE'
  44. ]);
  45. // 订单详情表
  46. OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'DONE']);
  47. // 会员升级
  48. Event::dispatch('order_pay.member_level.up', $order->join_order_member_id);
  49. // 7天后自动完成 order_is_complete=Y
  50. // $redis = Redis::connection();
  51. // $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days"));
  52. // $redis->sadd($key, $order->order_id);
  53. }
  54. Db::commit();
  55. } catch (\Exception $e) {
  56. Db::rollBack();
  57. }
  58. }
  59. /**
  60. * @Desc 自动完成订单
  61. * @Author Gorden
  62. * @Date 2024/7/16 9:37
  63. *
  64. * @return void
  65. */
  66. public static function AutomaticComplete()
  67. {
  68. Db::beginTransaction();
  69. try {
  70. $redis = Redis::connection();
  71. $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd');
  72. $orderIds = $redis->smembers($key);
  73. foreach ($orderIds as $orderId) {
  74. $order = Order::where('order_id', $orderId)
  75. ->select('order_is_complete', 'order_category', 'order_status_system', 'join_order_member_id')
  76. ->first();
  77. if ($order && $order->order_is_complete != 'Y' && $order->order_category != 'RETURN' && in_array($order->order_status_system, ['RECVING', 'SIGNED', 'CONFIRM'])) {
  78. // 更新主表
  79. Order::where('order_id', $orderId)->update(['order_is_complete' => 'Y', 'order_status_system' => 'CONFIRM', 'order_status_storage' => 'DONE']);
  80. // sheet表
  81. OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']);
  82. // 会员升级
  83. Event::dispatch('order_pay.member_level.up', $order->join_order_member_id);
  84. }
  85. }
  86. $redis->del($key);
  87. Db::commit();
  88. } catch (\Exception $e) {
  89. dump($e->getMessage());
  90. Db::rollBack();
  91. }
  92. }
  93. public static function checkPayingOrder()
  94. {
  95. try {
  96. Db::beginTransaction();
  97. $timeUnix = strtotime("-30 minutes");
  98. $orders = Order::where('order_status_system', 'PAYING')
  99. ->where('order_category', '<>', 'DISHES') // 点餐不自动取消
  100. ->where('order_category', '<>', 'VIP') // 康养城订单不自动取消,有分次付款
  101. ->where('order_category', '<>', 'COMBINE') // 新客专享
  102. ->where('order_category', '<>', 'PARTNER') // 会员合伙人
  103. ->where('order_category', '<>', 'REFERRER') // 推荐官
  104. ->where(function ($query) {
  105. $query->where('order_platform', '<>', 'SYSTEM')->orWhereNull('order_platform');
  106. })
  107. ->where('order_addtimes', '<', $timeUnix)
  108. ->get();
  109. foreach ($orders as $order) {
  110. // 订单主表
  111. Order::where('order_id', $order->order_id)->update([
  112. 'order_is_complete' => 'Y',
  113. 'order_status_system' => 'CANCEL',
  114. 'order_status_payment' => 'CANCEL'
  115. ]);
  116. $sheets = OrderSheet::where('join_sheet_order_id', $order->order_id)->get();
  117. foreach ($sheets as $sheet) {
  118. // 还原库存
  119. $goodsSku = GoodsSku::where('goods_sku_id', $sheet->join_sheet_goods_sku_id)->first();
  120. if (!empty($goodsSku) && !empty($goodsSku->goods_sku_storage_json)) {
  121. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  122. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  123. $skuStorageJson['storage'] = $skuStorageJson['storage'] + $sheet->order_sheet_num;
  124. $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
  125. $goodsSku->save();
  126. }
  127. }
  128. $goodsRunning = GoodsRunning::where('join_running_goods_id', $sheet->join_sheet_goods_id)->first();
  129. if (!empty($goodsRunning)) {
  130. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage + $sheet->order_sheet_num;
  131. $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale - $sheet->order_sheet_num;
  132. $goodsRunning->save();
  133. }
  134. }
  135. // 释放优惠券
  136. if (!empty($order->order_discount_json)) {
  137. $orderDiscountJson = json_decode($order->order_discount_json, true);
  138. foreach ($orderDiscountJson as $discount) {
  139. if (!empty($discount['coupon_id']) && !empty($discount['coupon_detail_id'])) {
  140. foreach ($discount['coupon_detail_id'] as $detailId) {
  141. if (substr($detailId, 0, 4) == 'CUDT') {
  142. // 恢复优惠券
  143. CouponDetail::where('coupon_detail_id', $detailId)->update(['coupon_detail_status' => 'ACTIVED']);
  144. }
  145. }
  146. }
  147. }
  148. }
  149. // 订单详情表
  150. OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'CANCEL']);
  151. // 支付表
  152. $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first();
  153. if (!empty($payDetail)) {
  154. $payExtendJson = [];
  155. if (!empty($payDetail->pay_extend_json)) {
  156. $payExtendJson = json_decode($payDetail->pay_extend_json, true);
  157. }
  158. $payExtendJson['cancel_times'] = date('Y-m-d H:i:s');
  159. PayDetail::where('join_pay_order_id', $order->order_groupby)->update([
  160. 'pay_status' => 'CANCEL',
  161. 'pay_extend_json' => json_encode($payExtendJson)
  162. ]);
  163. }
  164. }
  165. Db::commit();
  166. } catch (\Exception $e) {
  167. Db::rollBack();
  168. }
  169. }
  170. /**
  171. * @Desc 生成核销数据
  172. * @Author Gorden
  173. * @Date 2024/9/9 17:07
  174. *
  175. * @param $params
  176. * @return array
  177. */
  178. public static function generateWriteOffData($params)
  179. {
  180. return [
  181. 'charge' => [
  182. 'charge_amount' => 1,
  183. 'charge_content' => $params['order_remark'] ?? '',
  184. 'charge_user_id' => $params['write_off_member_id'],
  185. 'charge_premises' => $params['dept_premises_id'],
  186. 'charge_waiter' => $params['charge_waiter'] ?? ''
  187. ],
  188. 'member_id' => $params['join_order_member_id']
  189. ];
  190. }
  191. /**
  192. * @Desc 生成核销数据-入order_process
  193. * @Author Gorden
  194. * @Date 2024/9/9 17:07
  195. *
  196. * @param $params
  197. * @return array
  198. */
  199. public static function generateWriteOffDataByOrderProcess($params)
  200. {
  201. return [
  202. 'charge' => [
  203. 'charge_amount' => $params['charge_amount'],
  204. 'charge_content' => $params['order_remark'] ?? '',
  205. 'charge_waiter' => $params['charge_waiter'] ?? '',
  206. 'charge_user_id' => $params['write_off_member_id'],
  207. 'charge_premises' => $params['dept_premises_id'],
  208. 'charge_premises_info' => $params['dept'] ?? ''
  209. ],
  210. 'member_id' => $params['join_order_member_id'],
  211. 'goods_id' => $params['goods_id'] ?? '',
  212. 'goods_sku_id' => $params['goods_sku_id'] ?? '',
  213. 'order_id' => $params['order_id'],
  214. 'platform' => 'SYSTEM',
  215. 'order_code' => random_string(10, 'number'),
  216. 'appointment' => $params['appointment_ids'] ?? '',
  217. ];
  218. }
  219. public static function generateAppointmentApplyData($params)
  220. {
  221. $member = Member::with('cert', 'info')
  222. ->where('member_id', $params['join_order_member_id'])
  223. ->first();
  224. $name = '';
  225. if (!empty($member) && !empty($member->cert) && !empty($member->cert->member_cert_name)) {
  226. $name = $member->cert->member_cert_name;
  227. } else if (!empty($member) && !empty($member->info) && !empty($member->info->member_info_nickname)) {
  228. $name = $member->info->member_info_nickname;
  229. }
  230. return [
  231. 'name' => $name,
  232. 'times' => '',
  233. 'mobile' => !empty($member) ? $member->member_mobile : '',
  234. 'person' => $params['order_sheet_num'] ?? '',
  235. 'premises' => $params['dept_premises_id'] ?? ''
  236. ];
  237. }
  238. /**
  239. * 微信支付宝扫码支付
  240. */
  241. public static function qrcodePay($params)
  242. {
  243. $log = SupportLog::channel('pay');
  244. $log->info("PAY_PARAMS", json_decode(json_encode($params), true));
  245. $params['order_amount_pay'] = floatval($params['order_amount_pay']);
  246. $qrcodeNbr = $params['qrcode_nbr'];
  247. $prefix = substr($qrcodeNbr, 0, 2);
  248. // 模拟数据
  249. // $result = [
  250. // 'return_code'=>'SUCCESS',
  251. // 'result_code' => 'SUCCESS'
  252. // ];
  253. // $result=[
  254. // 'code'=> '10000',
  255. // 'msg' => 'Success'
  256. // ];
  257. // return $result;
  258. // 微信支付
  259. if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
  260. $payData = [
  261. 'out_trade_no' => $params['orderGroupId'],
  262. 'body' => '万悦康养订单',
  263. 'total_fee' => $params['order_amount_pay'] * 100,
  264. 'auth_code' => $params['qrcode_nbr'],
  265. ];
  266. try {
  267. $config = config('payment.wxpay');
  268. $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN') . '/notify/orderPay/wxpay';
  269. $wxReturn = Pay::wechat($config)->pos($payData);
  270. $log->info("WXPAY_RETURN", json_decode(json_encode($wxReturn), true));
  271. $result = self::findWxpay($params['orderGroupId'], 0);
  272. } catch (GatewayException $g) {
  273. $result = self::findWxpay($params['orderGroupId'], 0);
  274. } catch (\Exception $e) {
  275. $log->error("WXPAY", ['msg' => $e->getMessage()]);
  276. $result = self::findWxpay($params['orderGroupId'], 0);
  277. // throw new BusinessException("支付失败");
  278. }
  279. try {
  280. $log->info("WXPAY_RETURN", json_decode(json_encode($result), true));
  281. } catch (\Exception $e) {
  282. }
  283. } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
  284. $payData = [
  285. 'out_trade_no' => $params['orderGroupId'],
  286. 'total_amount' => $params['order_amount_pay'],
  287. 'subject' => '万悦康养订单',
  288. 'auth_code' => $params['qrcode_nbr'],
  289. ];
  290. try {
  291. $config = config('payment.alipay');
  292. $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN') . '/notify/orderPay/alipay';
  293. $alipayReturn = Pay::alipay($config)->pos($payData);
  294. $log->info("WXPAY_RETURN", json_decode(json_encode($alipayReturn), true));
  295. $result = self::findAlipay($params['orderGroupId'], 0);
  296. } catch (GatewayException $g) {
  297. $result = self::findAlipay($params['orderGroupId'], 0);
  298. } catch (\Exception $e) {
  299. $log->error("ALIPAY", ['msg' => $e->getMessage()]);
  300. throw new BusinessException("支付失败:" . $e->getMessage());
  301. // $result['key'] = 'value';
  302. }
  303. try {
  304. $log->info("ALIPAY_RETURN", json_decode(json_encode($result), true));
  305. } catch (\Exception $e) {
  306. }
  307. } else {
  308. throw new BusinessException("付款码无效");
  309. }
  310. return $result;
  311. }
  312. /**
  313. * @Desc 查询微信支付
  314. * @Author Gorden
  315. * @Date 2024/8/16 14:55
  316. *
  317. * @param $orderId
  318. * @param $nbr 循环次数
  319. * @return mixed|void
  320. * @throws BusinessException
  321. */
  322. public static function findWxpay($orderId, $nbr = 0)
  323. {
  324. try {
  325. $result = Pay::wechat(config('payment.wxpay'))->find($orderId, 'pos');
  326. $result = json_decode(json_encode($result), true);
  327. } catch (\Exception $e) {
  328. SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => $e->getMessage()]);
  329. }
  330. if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
  331. SupportLog::channel('pay')->info("FIND_WXPAY_SUCCESS", ['nbr' => $nbr, 'order_id' => $orderId]);
  332. return $result;
  333. } else {
  334. if ($nbr > 1) {
  335. SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => '订单查询失败', 'order_id' => $orderId]);
  336. return ['msg' => '订单查询失败'];
  337. }
  338. sleep(3);
  339. SupportLog::channel('pay')->error("FIND_WXPAY", ['nbr' => $nbr, 'order_id' => $orderId]);
  340. return self::findWxpay($orderId, $nbr + 1);
  341. }
  342. }
  343. /**
  344. * @Desc 查询支付宝订单
  345. * @Author Gorden
  346. * @Date 2024/8/16 15:16
  347. *
  348. * @param $orderId
  349. * @param $nbr 循环次数
  350. * @return mixed|void
  351. * @throws BusinessException
  352. */
  353. public static function findAlipay($orderId, $nbr = 0)
  354. {
  355. try {
  356. $result = Pay::alipay(config('payment.alipay'))->find($orderId);
  357. $result = json_decode(json_encode($result), true);
  358. } catch (\Exception $e) {
  359. SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => $e->getMessage()]);
  360. }
  361. if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
  362. SupportLog::channel('pay')->info("FIND_ALIPAY_SUCCESS", ['nbr' => $nbr, 'order_id' => $orderId]);
  363. return $result;
  364. } else {
  365. if ($nbr > 1) {
  366. SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => '订单查询失败', 'order_id' => $orderId]);
  367. return ['msg' => '订单查询失败'];
  368. }
  369. sleep(3);
  370. SupportLog::channel('pay')->error("FIND_ALIPAY", ['nbr' => $nbr, 'order_id' => $orderId]);
  371. return self::findAlipay($orderId, $nbr + 1);
  372. }
  373. }
  374. /**
  375. * 验证产品库存
  376. */
  377. public static function checkGoodsStorage($params)
  378. {
  379. foreach ($params['goodsContentList'] as $goods) {
  380. // 减库存,规格和总库存
  381. if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE', 'COMBINE'])) {
  382. $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
  383. $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
  384. if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
  385. $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
  386. }
  387. if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
  388. throw new BusinessException('库存不足');
  389. }
  390. }
  391. $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
  392. $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
  393. if ($goodsRunning->goods_running_storage < 0) {
  394. throw new BusinessException('库存不足');
  395. }
  396. }
  397. }
  398. /**
  399. * 下单时结算的组合支付payDetail
  400. */
  401. public static function createPayDetail($params)
  402. {
  403. $insertPayDetailData = [
  404. 'join_pay_member_id' => $params['join_order_member_id'],
  405. 'join_pay_order_id' => $params['orderGroupId'],
  406. 'pay_status' => $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
  407. 'pay_category' => !empty($params['submit_goods_classify']) ? $params['submit_goods_classify'] : $params['goods_classify'],
  408. 'pay_amount' => $params['order_amount_pay'],
  409. 'pay_paytimes' => date('Y-m-d H:i:s'),
  410. 'pay_prepayid' => $params['pay_category'],
  411. 'pay_json_request' => json_encode($params),
  412. 'pay_json_response' => $params['pay_json_response'] ?? '[]',
  413. 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
  414. 'pay_addtimes' => time()
  415. ];
  416. PayDetail::insert($insertPayDetailData);
  417. }
  418. /**
  419. * 组合支付,PayDetail
  420. */
  421. public static function createPayConstituteDetail($params, $payDetail)
  422. {
  423. $qrcodePrepayId = '';
  424. if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
  425. $qrcodePrepayId = $params['join_order_member_id'] . '-QRCODE';
  426. }
  427. if (!$payDetail || ($payDetail->pay_prepayid != $params['pay_category'] && $payDetail->pay_prepayid != $qrcodePrepayId)) {
  428. $payDetail = new PayDetail();
  429. $payDetail->join_pay_member_id = $params['join_order_member_id'];
  430. $payDetail->join_pay_order_id = $params['orderGroupId'];
  431. $payDetail->pay_category = $params['goods_classify'] ?? '';
  432. $payDetail->pay_prepayid = $params['pay_category'];
  433. $payDetail->pay_json_request = json_encode($params);
  434. $payDetail->pay_addtimes = time();
  435. }
  436. if ($payDetail->pay_prepayid == $qrcodePrepayId) {
  437. $payDetail->pay_prepayid = $params['pay_category'];
  438. }
  439. $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
  440. 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
  441. ]);
  442. $payDetail->pay_amount = $params['order_amount_pay'];
  443. $payDetail->pay_paytimes = date('Y-m-d H:i:s');
  444. $payDetail->pay_status = 'SUCCESS';
  445. $payDetail->join_pay_object_json = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  446. $payDetail->save();
  447. }
  448. /**
  449. * 组合支付,PayDetail
  450. */
  451. public static function createProductPayConstituteDetail($params)
  452. {
  453. dump($params);
  454. $payDetail = new PayDetail();
  455. $payDetail->join_pay_member_id = $params['join_order_member_id'];
  456. $payDetail->join_pay_order_id = $params['orderGroupId'];
  457. $payDetail->pay_category = $params['goods_classify'] ?? '';
  458. $payDetail->pay_json_request = json_encode($params);
  459. $payDetail->pay_addtimes = time();
  460. $payDetail->pay_prepayid = $params['pay_category'];
  461. $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
  462. 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
  463. ]);
  464. $payDetail->pay_amount = $params['order_amount_pay'];
  465. $payDetail->pay_paytimes = date('Y-m-d H:i:s');
  466. $payDetail->pay_status = $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING';
  467. $payDetail->join_pay_object_json = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  468. $payDetail->save();
  469. }
  470. public static function getPayWayByPrepayId($prepayId)
  471. {
  472. $payWay = '';
  473. $categoryArray = explode('-', $prepayId);
  474. if (isset($categoryArray[1])) {
  475. $payWay = $categoryArray[1];
  476. } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
  477. $payWay = $categoryArray[0];
  478. }
  479. return $payWay;
  480. }
  481. /**
  482. * @Desc 支付使用优惠券
  483. * @Author Gorden
  484. * @Date 2024/8/28 14:59
  485. *
  486. * @param $memberId
  487. * @param $goods
  488. * @param $coupon
  489. * @param $payAmount
  490. * @return array|mixed
  491. */
  492. public static function payUseCoupon($type, $settlementNow, $memberId, $goods, $coupon, $payAmount)
  493. {
  494. try {
  495. foreach ($coupon as $item) {
  496. if (!in_array(substr($item, 0, 2), ['CU', 'CO'])) {
  497. return [];
  498. }
  499. }
  500. $amountBalance = [
  501. 'pay_amount' => $payAmount,
  502. 'welfare_balance' => 0,
  503. 'cut_balance' => 0,
  504. ];
  505. foreach ($goods as $good) {
  506. $result = OrderService::useCoupon($type, $settlementNow, $memberId, $goods, $good, $coupon, $amountBalance);
  507. $amountBalance = [
  508. 'pay_amount' => $result['pay_amount'],
  509. 'welfare_balance' => $result['welfare_balance'],
  510. 'cut_balance' => $result['cut_balance'],
  511. ];
  512. }
  513. $couponDetailsIds = Redis::sMembers("ORDER:USE:COUPON:" . $memberId);
  514. Redis::del("ORDER:USE:COUPON:" . $memberId);
  515. $useCouponJson = Redis::get("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
  516. Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
  517. return [
  518. 'pay_amount' => $amountBalance['pay_amount'],
  519. 'detail_ids' => $couponDetailsIds,
  520. 'use_coupon_json' => $useCouponJson ?? []
  521. ];
  522. } catch (\Exception $e) {
  523. dump($e->getTrace());
  524. }
  525. }
  526. public static function useCoupon($type, $settlementNow, $memberId, $goods, $good, $coupon, $amountBalance)
  527. {
  528. try {
  529. $cacheKey = "ORDER:USE:COUPON:" . $memberId;
  530. $cacheDiscountKey = "ORDER:USE:COUPON:DISCOUNT:" . $memberId;
  531. $payAmount = $amountBalance['pay_amount'];
  532. $welfareBalance = $amountBalance['welfare_balance'];
  533. $cutBalance = $amountBalance['cut_balance'];
  534. $goodsId = $good['goods_id'];
  535. $money = $good['goods_sales_price'] * $good['nbr'];
  536. $discountData = Redis::get($cacheDiscountKey);
  537. if (empty($discountData)) {
  538. $discountData = [];
  539. } else {
  540. $discountData = json_decode($discountData, true);
  541. }
  542. foreach ($coupon as $couponId) {
  543. $couponDetail = CouponDetail::leftJoin('coupon_goods', 'coupon_goods.join_goods_coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
  544. ->leftJoin('coupon', 'coupon.coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
  545. ->select('coupon_detail.coupon_detail_id', 'coupon_goods.coupon_goods_id', 'coupon_id', 'coupon_classify', 'coupon_value', 'coupon_minimum_limit', 'coupon_category')
  546. ->where('coupon_goods.join_coupon_goods_id', $goodsId)
  547. ->where('coupon_goods.join_coupon_goods_sku_id', $good['sku_id'])
  548. ->where('join_goods_coupon_id', $couponId)
  549. ->where('coupon_detail.join_coupon_detail_member_id', $memberId);
  550. if ($settlementNow == 'Y' && $type == 'pay') {
  551. $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED']);
  552. } else {
  553. $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED');
  554. }
  555. $couponDetail = $couponDetail->orderBy('coupon_detail_id', 'DESC')
  556. ->first();
  557. if (!$couponDetail) {
  558. continue;
  559. }
  560. if ($settlementNow == 'Y') {
  561. $updateData = [
  562. 'coupon_detail_status' => 'USED',
  563. 'coupon_detail_used_datetime' => date('Y-m-d H:i:s')
  564. ];
  565. } else {
  566. $updateData = [
  567. 'coupon_detail_status' => 'WAITING',
  568. ];
  569. }
  570. // 计算优惠券包含的优惠商品的件数和总价
  571. $countAndAmount = self::countAndAmount($goods, $couponId);
  572. // 如果是计件
  573. if ($couponDetail->coupon_category == 'PIECE' && $countAndAmount['count'] < $couponDetail->coupon_minimum_limit) {
  574. continue;
  575. }
  576. if (in_array($couponDetail->coupon_classify, ['立减券', '满减券'])) {
  577. if (Redis::sIsMember($cacheKey, $couponId)) {
  578. continue;
  579. }
  580. Redis::sAdd($cacheKey, $couponId);
  581. if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
  582. $payAmount = $payAmount - $couponDetail->coupon_value;
  583. // json记录
  584. $discountData[$couponId] = [
  585. 'coupon_id' => $couponId,
  586. 'coupon_value' => $couponDetail->coupon_value,
  587. 'coupon_classify' => $couponDetail->coupon_classify,
  588. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  589. ];
  590. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  591. CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
  592. }
  593. } elseif ($couponDetail->coupon_classify == '折扣券') {
  594. if (Redis::sIsMember($cacheKey, $couponId)) {
  595. continue;
  596. }
  597. Redis::sAdd($cacheKey, $couponId);
  598. if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
  599. $zhekouAmount = round($countAndAmount['amount'] * (100 - $couponDetail->coupon_value) / 100, 2);
  600. $payAmount = $payAmount - $zhekouAmount;
  601. // json记录
  602. $discountData[$couponId] = [
  603. 'coupon_id' => $couponId,
  604. 'coupon_value' => $zhekouAmount,
  605. 'coupon_classify' => $couponDetail->coupon_classify,
  606. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  607. ];
  608. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  609. CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
  610. }
  611. } elseif (in_array($couponDetail->coupon_classify, ['抵用券', '赠品券'])) {
  612. if (Redis::sIsMember($cacheKey, $couponId)) {
  613. continue;
  614. }
  615. Redis::sAdd($cacheKey, $couponId);
  616. CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
  617. if ($good['nbr'] > 1) {
  618. $diyongAmount = $good['goods_sales_price'];
  619. $payAmount = $payAmount - $diyongAmount;
  620. } elseif (ceil($good['nbr']) == 1) {
  621. $diyongAmount = round($good['goods_sales_price'] * $good['nbr'], 2);
  622. $payAmount = $payAmount - $diyongAmount;
  623. }
  624. // json记录
  625. $discountData[$couponId] = [
  626. 'coupon_id' => $couponId,
  627. 'coupon_value' => $diyongAmount,
  628. 'coupon_classify' => $couponDetail->coupon_classify,
  629. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  630. ];
  631. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  632. } elseif ($couponDetail->coupon_classify == '福利券') {
  633. if (Redis::sIsMember($cacheKey, $couponId)) {
  634. continue;
  635. }
  636. Redis::sAdd($cacheKey, $couponId);
  637. CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
  638. $fuliAmount = 0;
  639. if (!empty($couponDetail->coupon_value)) {
  640. $fuliAmount = $couponDetail->coupon_value;
  641. }
  642. if ($fuliAmount >= $countAndAmount['amount']) {
  643. $preferentialAmount = $countAndAmount['amount'];
  644. } else {
  645. $preferentialAmount = $fuliAmount;
  646. }
  647. $payAmount = $payAmount - $preferentialAmount;
  648. // json记录
  649. $discountData[$couponId] = [
  650. 'coupon_id' => $couponId,
  651. 'coupon_value' => $preferentialAmount,
  652. 'coupon_classify' => $couponDetail->coupon_classify,
  653. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  654. ];
  655. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  656. } elseif (in_array($couponDetail->coupon_classify, ['年卡', '季卡', '月卡'])) {
  657. if (Redis::sIsMember($cacheKey, $couponId) || Redis::sIsMember($cacheKey, $goodsId)) {
  658. continue;
  659. }
  660. Redis::sAdd($cacheKey, $couponId);
  661. Redis::sAdd($cacheKey, $goodsId);
  662. $kaAmount = 0;
  663. if (!empty($discountData[$couponId]['coupon_value'])) {
  664. $kaAmount = $discountData[$couponId]['coupon_value'];
  665. }
  666. if ($good['nbr'] > 1) {
  667. $payAmount = $payAmount - $good['goods_sales_price'];
  668. $kaAmount = $good['goods_sales_price'];
  669. } else {
  670. $payAmount = $payAmount - $good['goods_sales_price'] * $good['nbr'];
  671. $kaAmount = $good['goods_sales_price'] * $good['nbr'];
  672. }
  673. // json记录
  674. $discountData[$couponId] = [
  675. 'coupon_id' => $couponId,
  676. 'coupon_value' => $kaAmount,
  677. 'coupon_classify' => $couponDetail->coupon_classify,
  678. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  679. ];
  680. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  681. }
  682. }
  683. if ($payAmount < 0) {
  684. $payAmount = 0;
  685. }
  686. $amountBalance = [
  687. 'pay_amount' => round($payAmount, 2),
  688. 'welfare_balance' => 0,
  689. 'cut_balance' => 0
  690. ];
  691. return $amountBalance;
  692. } catch (\Exception $e) {
  693. Redis::del("ORDER:USE:COUPON:" . $memberId);
  694. Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
  695. dump($e->getTrace());
  696. }
  697. }
  698. /**
  699. * @Desc 选择优惠券,计算
  700. * @Author Gorden
  701. * @Date 2024/8/28 14:18
  702. *
  703. * @param $memberId
  704. * @param $goods
  705. * @param $good
  706. * @param $coupon
  707. * @param $amountBalance
  708. * @return array|void
  709. */
  710. public static function chooseCoupon($settlementNow, $memberId, $goods, $good, $coupon, $amountBalance)
  711. {
  712. try {
  713. $cacheKey = "ORDER:USE:COUPON:" . $memberId;
  714. $payAmount = $amountBalance['pay_amount'];
  715. $welfareBalance = $amountBalance['welfare_balance'];
  716. $cutBalance = $amountBalance['cut_balance'];
  717. $goodsId = $good['goods_id'];
  718. $money = $good['goods_sales_price'] * $good['nbr'];
  719. foreach ($coupon as $couponId) {
  720. $couponDetail = CouponDetail::leftJoin('coupon_goods', 'coupon_goods.join_goods_coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
  721. ->leftJoin('coupon', 'coupon.coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
  722. ->select('coupon_detail.coupon_detail_id', 'coupon_goods.coupon_goods_id', 'coupon_id', 'coupon_classify', 'coupon_value', 'coupon_minimum_limit', 'coupon_category')
  723. ->where('coupon_goods.join_coupon_goods_id', $goodsId)
  724. ->where('coupon_goods.join_coupon_goods_sku_id', $good['sku_id'])
  725. ->where('join_goods_coupon_id', $couponId)
  726. ->where('coupon_detail.join_coupon_detail_member_id', $memberId);
  727. if ($settlementNow == 'Y') {
  728. $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED']);
  729. } else {
  730. $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED');
  731. }
  732. $couponDetail = $couponDetail->orderBy('coupon_detail_id', 'DESC')
  733. ->first();
  734. if (!$couponDetail) {
  735. continue;
  736. }
  737. // 计算优惠券包含的优惠商品的件数和总价
  738. $countAndAmount = self::countAndAmount($goods, $couponId);
  739. // 如果是计件
  740. if ($couponDetail->coupon_category == 'PIECE' && $countAndAmount['count'] < $couponDetail->coupon_minimum_limit) {
  741. continue;
  742. }
  743. if (in_array($couponDetail->coupon_classify, ['立减券', '满减券'])) {
  744. if (Redis::sIsMember($cacheKey, $couponId)) {
  745. continue;
  746. }
  747. Redis::sAdd($cacheKey, $couponId);
  748. if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
  749. $payAmount = $payAmount - $couponDetail->coupon_value;
  750. }
  751. } elseif ($couponDetail->coupon_classify == '折扣券') {
  752. if (Redis::sIsMember($cacheKey, $couponId)) {
  753. continue;
  754. }
  755. Redis::sAdd($cacheKey, $couponId);
  756. if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
  757. $zhekouAmount = round($countAndAmount['amount'] * (100 - $couponDetail->coupon_value) / 100, 2);
  758. $payAmount = $payAmount - $zhekouAmount;
  759. }
  760. } elseif (in_array($couponDetail->coupon_classify, ['抵用券', '赠品券'])) {
  761. if (Redis::sIsMember($cacheKey, $couponId)) {
  762. continue;
  763. }
  764. Redis::sAdd($cacheKey, $couponId);
  765. if ($good['nbr'] > 1) {
  766. $diyongAmount = $good['goods_sales_price'];
  767. $payAmount = $payAmount - $diyongAmount;
  768. } elseif (ceil($good['nbr']) == 1) {
  769. $diyongAmount = round($good['goods_sales_price'] * $good['nbr'], 2);
  770. $payAmount = $payAmount - $diyongAmount;
  771. }
  772. } elseif ($couponDetail->coupon_classify == '福利券') {
  773. if (Redis::sIsMember($cacheKey, $couponId)) {
  774. continue;
  775. }
  776. Redis::sAdd($cacheKey, $couponId);
  777. $fuliAmount = 0;
  778. if (!empty($couponDetail->coupon_value)) {
  779. $fuliAmount = $couponDetail->coupon_value;
  780. }
  781. if ($fuliAmount >= $countAndAmount['amount']) {
  782. $preferentialAmount = $countAndAmount['amount'];
  783. } else {
  784. $preferentialAmount = $fuliAmount;
  785. }
  786. $payAmount = $payAmount - $preferentialAmount;
  787. } elseif (in_array($couponDetail->coupon_classify, ['年卡', '季卡', '月卡'])) {
  788. if (Redis::sIsMember($cacheKey, $couponId) || Redis::sIsMember($cacheKey, $goodsId)) {
  789. continue;
  790. }
  791. Redis::sAdd($cacheKey, $couponId);
  792. Redis::sAdd($cacheKey, $goodsId);
  793. if ($good['nbr'] > 1) {
  794. $payAmount = $payAmount - $good['goods_sales_price'];
  795. } else {
  796. $payAmount = $payAmount - $good['goods_sales_price'] * $good['nbr'];
  797. }
  798. }
  799. }
  800. if ($payAmount < 0) {
  801. $payAmount = 0;
  802. }
  803. $amountBalance = [
  804. 'pay_amount' => round($payAmount, 2),
  805. 'welfare_balance' => $welfareBalance,
  806. 'cut_balance' => $cutBalance
  807. ];
  808. return $amountBalance;
  809. } catch (\Exception $e) {
  810. Redis::del("ORDER:USE:COUPON:" . $memberId);
  811. Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
  812. dump($e->getTrace());
  813. }
  814. }
  815. public static function countAndAmount($goods, $couponId)
  816. {
  817. try {
  818. $goodsIds = array_column($goods, 'goods_id');
  819. $couponGoods = CouponGoods::whereIn('join_coupon_goods_id', $goodsIds)
  820. ->where('join_goods_coupon_id', $couponId)
  821. ->select('join_coupon_goods_id', 'join_coupon_goods_sku_id')
  822. ->get()
  823. ->toArray();
  824. $count = 0;
  825. $amount = 0;
  826. foreach ($couponGoods as $couponGood) {
  827. foreach ($goods as $good) {
  828. if ($good['goods_id'] == $couponGood['join_coupon_goods_id'] && $good['sku_id'] == $couponGood['join_coupon_goods_sku_id']) {
  829. $count += $good['nbr'];
  830. $amount += $good['goods_sales_price'] * $good['nbr'];
  831. }
  832. }
  833. }
  834. return compact('count', 'amount');
  835. } catch (\Exception $e) {
  836. dump($e->getTrace());
  837. }
  838. }
  839. /**
  840. * @Desc
  841. * @Author Gorden
  842. * @Date 2024/9/11 11:11
  843. *
  844. * @param MemberBenefit $benefit
  845. * @return false[]|true[]
  846. */
  847. public static function checkPackageBenefit(MemberBenefit $benefit)
  848. {
  849. $result = ['sheet' => true, 'order' => true];
  850. // 除此权益外,套包的其他权益是否用完了 where('join_benefit_package_id', $benefit->join_benefit_package_id)
  851. $benefits = MemberBenefit::where('join_benefit_order_id', $benefit->join_benefit_order_id)
  852. ->where('member_benefit_id', '<>', $benefit->member_benefit_id)
  853. ->get()
  854. ->toArray();
  855. foreach ($benefits as $benefitItem) {
  856. if ($benefitItem['join_benefit_package_id'] == $benefit->join_benefit_package_id) {
  857. if ($benefitItem['member_benefit_limit_count'] > $benefitItem['member_benefit_used_count']) {
  858. return ['sheet' => false, 'order' => false];
  859. }
  860. }
  861. }
  862. foreach ($benefits as $benefitItem) {
  863. if ($benefitItem['member_benefit_limit_count'] > $benefitItem['member_benefit_used_count']) {
  864. $result['order'] = false;
  865. return $result;
  866. }
  867. }
  868. return $result;
  869. }
  870. /**
  871. * @Desc 拆单提成
  872. * @Author Gorden
  873. * @Date 2024/9/29 16:27
  874. *
  875. * @return void
  876. */
  877. public static function splitOrderCommission($params)
  878. {
  879. $orders = Order::where('order_groupby', $params['orderGroupId'])->get()->toArray();
  880. if (!empty($orders)) {
  881. foreach ($orders as $orderItem) {
  882. $params['orderId'] = $orderItem['order_id'];
  883. Event::dispatch('commission.order', $params);
  884. }
  885. }
  886. }
  887. public static $couponClassify = [
  888. 'wipe' => '抹零',
  889. 'custom' => '自定义优惠金额'
  890. ];
  891. public static $payWay = [
  892. 'WXPAY' => '微信支付',
  893. 'ALIPAY' => '支付宝',
  894. 'CASH' => '账户余额',
  895. 'CARD' => '储值卡',
  896. 'WELFARE' => '福利账户',
  897. 'MONEY' => '现金',
  898. 'OFFLINE' => '线下支付',
  899. 'OFFLINE_WXPAY' => '线下支付-微信',
  900. 'OFFLINE_ALIPAY' => '线下支付-支付宝',
  901. 'QRCODE' => '付款码',
  902. 'NONE' => '付零',
  903. 'VIP' => 'VIP账户'
  904. ];
  905. }