OrderService.php 41 KB

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