OrderService.php 43 KB

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