OrderService.php 40 KB

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