OrderService.php 39 KB

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