OrderService.php 39 KB

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