OrderService.php 38 KB

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