OrderService.php 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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. /**
  445. * 组合支付,PayDetail
  446. */
  447. public static function createProductPayConstituteDetail($params)
  448. {
  449. dump($params);
  450. $payDetail = new PayDetail();
  451. $payDetail->join_pay_member_id = $params['join_order_member_id'];
  452. $payDetail->join_pay_order_id = $params['orderGroupId'];
  453. $payDetail->pay_category = $params['goods_classify'] ?? '';
  454. $payDetail->pay_json_request = json_encode($params);
  455. $payDetail->pay_addtimes = time();
  456. $payDetail->pay_prepayid = $params['pay_category'];
  457. $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([
  458. 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s')
  459. ]);
  460. $payDetail->pay_amount = $params['order_amount_pay'];
  461. $payDetail->pay_paytimes = date('Y-m-d H:i:s');
  462. $payDetail->pay_status = $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING';
  463. $payDetail->join_pay_object_json = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]';
  464. $payDetail->save();
  465. }
  466. public static function getPayWayByPrepayId($prepayId)
  467. {
  468. $payWay = '';
  469. $categoryArray = explode('-', $prepayId);
  470. if (isset($categoryArray[1])) {
  471. $payWay = $categoryArray[1];
  472. } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
  473. $payWay = $categoryArray[0];
  474. }
  475. return $payWay;
  476. }
  477. /**
  478. * @Desc 支付使用优惠券
  479. * @Author Gorden
  480. * @Date 2024/8/28 14:59
  481. *
  482. * @param $memberId
  483. * @param $goods
  484. * @param $coupon
  485. * @param $payAmount
  486. * @return array|mixed
  487. */
  488. public static function payUseCoupon($type, $settlementNow, $memberId, $goods, $coupon, $payAmount)
  489. {
  490. try {
  491. foreach ($coupon as $item) {
  492. if (!in_array(substr($item, 0, 2), ['CU', 'CO'])) {
  493. return [];
  494. }
  495. }
  496. $amountBalance = [
  497. 'pay_amount' => $payAmount,
  498. 'welfare_balance' => 0,
  499. 'cut_balance' => 0,
  500. ];
  501. foreach ($goods as $good) {
  502. $result = OrderService::useCoupon($type, $settlementNow, $memberId, $goods, $good, $coupon, $amountBalance);
  503. $amountBalance = [
  504. 'pay_amount' => $result['pay_amount'],
  505. 'welfare_balance' => $result['welfare_balance'],
  506. 'cut_balance' => $result['cut_balance'],
  507. ];
  508. }
  509. $couponDetailsIds = Redis::sMembers("ORDER:USE:COUPON:" . $memberId);
  510. Redis::del("ORDER:USE:COUPON:" . $memberId);
  511. $useCouponJson = Redis::get("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
  512. Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
  513. return [
  514. 'pay_amount' => $amountBalance['pay_amount'],
  515. 'detail_ids' => $couponDetailsIds,
  516. 'use_coupon_json' => $useCouponJson ?? []
  517. ];
  518. } catch (\Exception $e) {
  519. dump($e->getTrace());
  520. }
  521. }
  522. public static function useCoupon($type, $settlementNow, $memberId, $goods, $good, $coupon, $amountBalance)
  523. {
  524. try {
  525. $cacheKey = "ORDER:USE:COUPON:" . $memberId;
  526. $cacheDiscountKey = "ORDER:USE:COUPON:DISCOUNT:" . $memberId;
  527. $payAmount = $amountBalance['pay_amount'];
  528. $welfareBalance = $amountBalance['welfare_balance'];
  529. $cutBalance = $amountBalance['cut_balance'];
  530. $goodsId = $good['goods_id'];
  531. $money = $good['goods_sales_price'] * $good['nbr'];
  532. $discountData = Redis::get($cacheDiscountKey);
  533. if (empty($discountData)) {
  534. $discountData = [];
  535. } else {
  536. $discountData = json_decode($discountData, true);
  537. }
  538. foreach ($coupon as $couponId) {
  539. $couponDetail = CouponDetail::leftJoin('coupon_goods', 'coupon_goods.join_goods_coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
  540. ->leftJoin('coupon', 'coupon.coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
  541. ->select('coupon_detail.coupon_detail_id', 'coupon_goods.coupon_goods_id', 'coupon_id', 'coupon_classify', 'coupon_value', 'coupon_minimum_limit', 'coupon_category')
  542. ->where('coupon_goods.join_coupon_goods_id', $goodsId)
  543. ->where('coupon_goods.join_coupon_goods_sku_id', $good['sku_id'])
  544. ->where('join_goods_coupon_id', $couponId)
  545. ->where('coupon_detail.join_coupon_detail_member_id', $memberId);
  546. if ($settlementNow == 'Y' && $type == 'pay') {
  547. $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED']);
  548. } else {
  549. $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED');
  550. }
  551. $couponDetail = $couponDetail->orderBy('coupon_detail_id', 'DESC')
  552. ->first();
  553. if (!$couponDetail) {
  554. continue;
  555. }
  556. if ($settlementNow == 'Y') {
  557. $updateData = [
  558. 'coupon_detail_status' => 'USED',
  559. 'coupon_detail_used_datetime' => date('Y-m-d H:i:s')
  560. ];
  561. } else {
  562. $updateData = [
  563. 'coupon_detail_status' => 'WAITING',
  564. ];
  565. }
  566. // 计算优惠券包含的优惠商品的件数和总价
  567. $countAndAmount = self::countAndAmount($goods, $couponId);
  568. // 如果是计件
  569. if ($couponDetail->coupon_category == 'PIECE' && $countAndAmount['count'] < $couponDetail->coupon_minimum_limit) {
  570. continue;
  571. }
  572. if (in_array($couponDetail->coupon_classify, ['立减券', '满减券'])) {
  573. if (Redis::sIsMember($cacheKey, $couponId)) {
  574. continue;
  575. }
  576. Redis::sAdd($cacheKey, $couponId);
  577. if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
  578. $payAmount = $payAmount - $couponDetail->coupon_value;
  579. // json记录
  580. $discountData[$couponId] = [
  581. 'coupon_id' => $couponId,
  582. 'coupon_value' => $couponDetail->coupon_value,
  583. 'coupon_classify' => $couponDetail->coupon_classify,
  584. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  585. ];
  586. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  587. CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
  588. }
  589. } elseif ($couponDetail->coupon_classify == '折扣券') {
  590. if (Redis::sIsMember($cacheKey, $couponId)) {
  591. continue;
  592. }
  593. Redis::sAdd($cacheKey, $couponId);
  594. if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
  595. $zhekouAmount = round($countAndAmount['amount'] * (100 - $couponDetail->coupon_value) / 100, 2);
  596. $payAmount = $payAmount - $zhekouAmount;
  597. // json记录
  598. $discountData[$couponId] = [
  599. 'coupon_id' => $couponId,
  600. 'coupon_value' => $zhekouAmount,
  601. 'coupon_classify' => $couponDetail->coupon_classify,
  602. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  603. ];
  604. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  605. CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
  606. }
  607. } elseif (in_array($couponDetail->coupon_classify, ['抵用券', '赠品券'])) {
  608. if (Redis::sIsMember($cacheKey, $couponId)) {
  609. continue;
  610. }
  611. Redis::sAdd($cacheKey, $couponId);
  612. CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
  613. if ($good['nbr'] > 1) {
  614. $diyongAmount = $good['goods_sales_price'];
  615. $payAmount = $payAmount - $diyongAmount;
  616. } elseif (ceil($good['nbr']) == 1) {
  617. $diyongAmount = round($good['goods_sales_price'] * $good['nbr'], 2);
  618. $payAmount = $payAmount - $diyongAmount;
  619. }
  620. // json记录
  621. $discountData[$couponId] = [
  622. 'coupon_id' => $couponId,
  623. 'coupon_value' => $diyongAmount,
  624. 'coupon_classify' => $couponDetail->coupon_classify,
  625. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  626. ];
  627. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  628. } elseif ($couponDetail->coupon_classify == '福利券') {
  629. if (Redis::sIsMember($cacheKey, $couponId)) {
  630. continue;
  631. }
  632. Redis::sAdd($cacheKey, $couponId);
  633. CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData);
  634. $fuliAmount = 0;
  635. if (!empty($couponDetail->coupon_value)) {
  636. $fuliAmount = $couponDetail->coupon_value;
  637. }
  638. if ($fuliAmount >= $countAndAmount['amount']) {
  639. $preferentialAmount = $countAndAmount['amount'];
  640. } else {
  641. $preferentialAmount = $fuliAmount;
  642. }
  643. $payAmount = $payAmount - $preferentialAmount;
  644. // json记录
  645. $discountData[$couponId] = [
  646. 'coupon_id' => $couponId,
  647. 'coupon_value' => $preferentialAmount,
  648. 'coupon_classify' => $couponDetail->coupon_classify,
  649. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  650. ];
  651. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  652. } elseif (in_array($couponDetail->coupon_classify, ['年卡', '季卡', '月卡'])) {
  653. if (Redis::sIsMember($cacheKey, $couponId) || Redis::sIsMember($cacheKey, $goodsId)) {
  654. continue;
  655. }
  656. Redis::sAdd($cacheKey, $couponId);
  657. Redis::sAdd($cacheKey, $goodsId);
  658. $kaAmount = 0;
  659. if (!empty($discountData[$couponId]['coupon_value'])) {
  660. $kaAmount = $discountData[$couponId]['coupon_value'];
  661. }
  662. if ($good['nbr'] > 1) {
  663. $payAmount = $payAmount - $good['goods_sales_price'];
  664. $kaAmount = $good['goods_sales_price'];
  665. } else {
  666. $payAmount = $payAmount - $good['goods_sales_price'] * $good['nbr'];
  667. $kaAmount = $good['goods_sales_price'] * $good['nbr'];
  668. }
  669. // json记录
  670. $discountData[$couponId] = [
  671. 'coupon_id' => $couponId,
  672. 'coupon_value' => $kaAmount,
  673. 'coupon_classify' => $couponDetail->coupon_classify,
  674. 'coupon_detail_id' => [$couponDetail->coupon_detail_id]
  675. ];
  676. Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE));
  677. }
  678. }
  679. if ($payAmount < 0) {
  680. $payAmount = 0;
  681. }
  682. $amountBalance = [
  683. 'pay_amount' => round($payAmount, 2),
  684. 'welfare_balance' => 0,
  685. 'cut_balance' => 0
  686. ];
  687. return $amountBalance;
  688. } catch (\Exception $e) {
  689. Redis::del("ORDER:USE:COUPON:" . $memberId);
  690. Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
  691. dump($e->getTrace());
  692. }
  693. }
  694. /**
  695. * @Desc 选择优惠券,计算
  696. * @Author Gorden
  697. * @Date 2024/8/28 14:18
  698. *
  699. * @param $memberId
  700. * @param $goods
  701. * @param $good
  702. * @param $coupon
  703. * @param $amountBalance
  704. * @return array|void
  705. */
  706. public static function chooseCoupon($settlementNow, $memberId, $goods, $good, $coupon, $amountBalance)
  707. {
  708. try {
  709. $cacheKey = "ORDER:USE:COUPON:" . $memberId;
  710. $payAmount = $amountBalance['pay_amount'];
  711. $welfareBalance = $amountBalance['welfare_balance'];
  712. $cutBalance = $amountBalance['cut_balance'];
  713. $goodsId = $good['goods_id'];
  714. $money = $good['goods_sales_price'] * $good['nbr'];
  715. foreach ($coupon as $couponId) {
  716. $couponDetail = CouponDetail::leftJoin('coupon_goods', 'coupon_goods.join_goods_coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
  717. ->leftJoin('coupon', 'coupon.coupon_id', '=', 'coupon_detail.join_detail_coupon_id')
  718. ->select('coupon_detail.coupon_detail_id', 'coupon_goods.coupon_goods_id', 'coupon_id', 'coupon_classify', 'coupon_value', 'coupon_minimum_limit', 'coupon_category')
  719. ->where('coupon_goods.join_coupon_goods_id', $goodsId)
  720. ->where('coupon_goods.join_coupon_goods_sku_id', $good['sku_id'])
  721. ->where('join_goods_coupon_id', $couponId)
  722. ->where('coupon_detail.join_coupon_detail_member_id', $memberId);
  723. if ($settlementNow == 'Y') {
  724. $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED']);
  725. } else {
  726. $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED');
  727. }
  728. $couponDetail = $couponDetail->orderBy('coupon_detail_id', 'DESC')
  729. ->first();
  730. if (!$couponDetail) {
  731. continue;
  732. }
  733. // 计算优惠券包含的优惠商品的件数和总价
  734. $countAndAmount = self::countAndAmount($goods, $couponId);
  735. // 如果是计件
  736. if ($couponDetail->coupon_category == 'PIECE' && $countAndAmount['count'] < $couponDetail->coupon_minimum_limit) {
  737. continue;
  738. }
  739. if (in_array($couponDetail->coupon_classify, ['立减券', '满减券'])) {
  740. if (Redis::sIsMember($cacheKey, $couponId)) {
  741. continue;
  742. }
  743. Redis::sAdd($cacheKey, $couponId);
  744. if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
  745. $payAmount = $payAmount - $couponDetail->coupon_value;
  746. }
  747. } elseif ($couponDetail->coupon_classify == '折扣券') {
  748. if (Redis::sIsMember($cacheKey, $couponId)) {
  749. continue;
  750. }
  751. Redis::sAdd($cacheKey, $couponId);
  752. if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) {
  753. $zhekouAmount = round($countAndAmount['amount'] * (100 - $couponDetail->coupon_value) / 100, 2);
  754. $payAmount = $payAmount - $zhekouAmount;
  755. }
  756. } elseif (in_array($couponDetail->coupon_classify, ['抵用券', '赠品券'])) {
  757. if (Redis::sIsMember($cacheKey, $couponId)) {
  758. continue;
  759. }
  760. Redis::sAdd($cacheKey, $couponId);
  761. if ($good['nbr'] > 1) {
  762. $diyongAmount = $good['goods_sales_price'];
  763. $payAmount = $payAmount - $diyongAmount;
  764. } elseif (ceil($good['nbr']) == 1) {
  765. $diyongAmount = round($good['goods_sales_price'] * $good['nbr'], 2);
  766. $payAmount = $payAmount - $diyongAmount;
  767. }
  768. } elseif ($couponDetail->coupon_classify == '福利券') {
  769. if (Redis::sIsMember($cacheKey, $couponId)) {
  770. continue;
  771. }
  772. Redis::sAdd($cacheKey, $couponId);
  773. $fuliAmount = 0;
  774. if (!empty($couponDetail->coupon_value)) {
  775. $fuliAmount = $couponDetail->coupon_value;
  776. }
  777. if ($fuliAmount >= $countAndAmount['amount']) {
  778. $preferentialAmount = $countAndAmount['amount'];
  779. } else {
  780. $preferentialAmount = $fuliAmount;
  781. }
  782. $payAmount = $payAmount - $preferentialAmount;
  783. } elseif (in_array($couponDetail->coupon_classify, ['年卡', '季卡', '月卡'])) {
  784. if (Redis::sIsMember($cacheKey, $couponId) || Redis::sIsMember($cacheKey, $goodsId)) {
  785. continue;
  786. }
  787. Redis::sAdd($cacheKey, $couponId);
  788. Redis::sAdd($cacheKey, $goodsId);
  789. if ($good['nbr'] > 1) {
  790. $payAmount = $payAmount - $good['goods_sales_price'];
  791. } else {
  792. $payAmount = $payAmount - $good['goods_sales_price'] * $good['nbr'];
  793. }
  794. }
  795. }
  796. if ($payAmount < 0) {
  797. $payAmount = 0;
  798. }
  799. $amountBalance = [
  800. 'pay_amount' => round($payAmount, 2),
  801. 'welfare_balance' => $welfareBalance,
  802. 'cut_balance' => $cutBalance
  803. ];
  804. return $amountBalance;
  805. } catch (\Exception $e) {
  806. Redis::del("ORDER:USE:COUPON:" . $memberId);
  807. Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId);
  808. dump($e->getTrace());
  809. }
  810. }
  811. public static function countAndAmount($goods, $couponId)
  812. {
  813. try {
  814. $goodsIds = array_column($goods, 'goods_id');
  815. $couponGoods = CouponGoods::whereIn('join_coupon_goods_id', $goodsIds)
  816. ->where('join_goods_coupon_id', $couponId)
  817. ->select('join_coupon_goods_id', 'join_coupon_goods_sku_id')
  818. ->get()
  819. ->toArray();
  820. $count = 0;
  821. $amount = 0;
  822. foreach ($couponGoods as $couponGood) {
  823. foreach ($goods as $good) {
  824. if ($good['goods_id'] == $couponGood['join_coupon_goods_id'] && $good['sku_id'] == $couponGood['join_coupon_goods_sku_id']) {
  825. $count += $good['nbr'];
  826. $amount += $good['goods_sales_price'] * $good['nbr'];
  827. }
  828. }
  829. }
  830. return compact('count', 'amount');
  831. } catch (\Exception $e) {
  832. dump($e->getTrace());
  833. }
  834. }
  835. /**
  836. * @Desc
  837. * @Author Gorden
  838. * @Date 2024/9/11 11:11
  839. *
  840. * @param MemberBenefit $benefit
  841. * @return false[]|true[]
  842. */
  843. public static function checkPackageBenefit(MemberBenefit $benefit)
  844. {
  845. $result = ['sheet' => true, 'order' => true];
  846. // 除此权益外,套包的其他权益是否用完了 where('join_benefit_package_id', $benefit->join_benefit_package_id)
  847. $benefits = MemberBenefit::where('join_benefit_order_id', $benefit->join_benefit_order_id)
  848. ->where('member_benefit_id', '<>', $benefit->member_benefit_id)
  849. ->get()
  850. ->toArray();
  851. foreach ($benefits as $benefitItem) {
  852. if ($benefitItem['join_benefit_package_id'] == $benefit->join_benefit_package_id) {
  853. if ($benefitItem['member_benefit_limit_count'] > $benefitItem['member_benefit_used_count']) {
  854. return ['sheet' => false, 'order' => false];
  855. }
  856. }
  857. }
  858. foreach ($benefits as $benefitItem) {
  859. if ($benefitItem['member_benefit_limit_count'] > $benefitItem['member_benefit_used_count']) {
  860. $result['order'] = false;
  861. return $result;
  862. }
  863. }
  864. return $result;
  865. }
  866. public static $couponClassify = [
  867. 'wipe' => '抹零',
  868. 'custom' => '自定义优惠金额'
  869. ];
  870. public static $payWay = [
  871. 'WXPAY' => '微信支付',
  872. 'ALIPAY' => '支付宝',
  873. 'CASH' => '账户余额',
  874. 'CARD' => '储值卡',
  875. 'WELFARE' => '福利账户',
  876. 'MONEY' => '现金',
  877. 'OFFLINE' => '线下支付',
  878. 'OFFLINE_WXPAY' => '线下支付-微信',
  879. 'OFFLINE_ALIPAY' => '线下支付-支付宝',
  880. 'QRCODE' => '付款码',
  881. 'NONE' => '付零',
  882. 'VIP' => 'VIP账户'
  883. ];
  884. }