OrderService.php 40 KB

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