where('order_addtimes', '<', $timeUnix) ->get(); foreach ($orders as $order) { // 订单主表 Order::where('order_id', $order->order_id)->update([ 'order_is_complete' => 'Y', 'order_status_system' => 'CONFIRM', 'order_status_storage' => 'DONE' ]); // 订单详情表 OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'DONE']); // 会员升级 Event::dispatch('order_pay.member_level.up', $order->join_order_member_id); // 7天后自动完成 order_is_complete=Y // $redis = Redis::connection(); // $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd', strtotime("+7 days")); // $redis->sadd($key, $order->order_id); } Db::commit(); } catch (\Exception $e) { Db::rollBack(); } } /** * @Desc 自动完成订单 * @Author Gorden * @Date 2024/7/16 9:37 * * @return void */ public static function AutomaticComplete() { Db::beginTransaction(); try { $redis = Redis::connection(); $key = Order::AUTOMATIC_COMPLETE_PREFIX . date('Ymd'); $orderIds = $redis->smembers($key); foreach ($orderIds as $orderId) { $order = Order::where('order_id', $orderId) ->select('order_is_complete', 'order_category', 'order_status_system', 'join_order_member_id') ->first(); if ($order && $order->order_is_complete != 'Y' && $order->order_category != 'RETURN' && in_array($order->order_status_system, ['RECVING', 'SIGNED', 'CONFIRM'])) { // 更新主表 Order::where('order_id', $orderId)->update(['order_is_complete' => 'Y', 'order_status_system' => 'CONFIRM', 'order_status_storage' => 'DONE']); // sheet表 OrderSheet::where('join_sheet_order_id', $orderId)->update(['order_sheet_status' => 'DONE']); // 会员升级 Event::dispatch('order_pay.member_level.up', $order->join_order_member_id); } } $redis->del($key); Db::commit(); } catch (\Exception $e) { dump($e->getMessage()); Db::rollBack(); } } public static function checkPayingOrder() { try { Db::beginTransaction(); $timeUnix = strtotime("-30 minutes"); $orders = Order::where('order_status_system', 'PAYING') ->where('order_category', '<>', 'DISHES') // 点餐不自动取消 ->where('order_category', '<>', 'VIP') // 康养城订单不自动取消,有分次付款 // ->where('order_platform','<>','SYSTEM') // 后台产生的订单不自动取消 ->where(function ($query) { $query->where('order_platform', '<>', 'SYSTEM')->orWhereNull('order_platform'); }) ->where('order_addtimes', '<', $timeUnix) ->get(); foreach ($orders as $order) { // 订单主表 Order::where('order_id', $order->order_id)->update([ 'order_is_complete' => 'Y', 'order_status_system' => 'CANCEL', 'order_status_payment' => 'CANCEL' ]); $sheets = OrderSheet::where('join_sheet_order_id', $order->order_id)->get(); foreach ($sheets as $sheet) { // 还原库存 $goodsSku = GoodsSku::where('goods_sku_id', $sheet->join_sheet_goods_sku_id)->first(); if (!empty($goodsSku) && !empty($goodsSku->goods_sku_storage_json)) { $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true); if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) { $skuStorageJson['storage'] = $skuStorageJson['storage'] + $sheet->order_sheet_num; $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson); $goodsSku->save(); } } $goodsRunning = GoodsRunning::where('join_running_goods_id', $sheet->join_sheet_goods_id)->first(); if (!empty($goodsRunning)) { $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage + $sheet->order_sheet_num; $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale - $sheet->order_sheet_num; $goodsRunning->save(); } } // 订单详情表 OrderSheet::where('join_sheet_order_id', $order->order_id)->update(['order_sheet_status' => 'CANCEL']); // 支付表 $payDetail = PayDetail::where('join_pay_order_id', $order->order_groupby)->first(); if (!empty($payDetail)) { $payExtendJson = []; if (!empty($payDetail->pay_extend_json)) { $payExtendJson = json_decode($payDetail->pay_extend_json, true); } $payExtendJson['cancel_times'] = date('Y-m-d H:i:s'); PayDetail::where('join_pay_order_id', $order->order_groupby)->update([ 'pay_status' => 'CANCEL', 'pay_extend_json' => json_encode($payExtendJson) ]); } } Db::commit(); } catch (\Exception $e) { Db::rollBack(); } } /** * @Desc 生成核销数据 * @Author Gorden * @Date 2024/9/9 17:07 * * @param $params * @return array */ public static function generateWriteOffData($params) { return [ 'charge' => [ 'charge_amount' => 1, 'charge_content' => $params['order_remark'] ?? '', 'charge_user_id' => $params['write_off_member_id'], 'charge_premises' => $params['dept_premises_id'], ], 'member_id' => $params['join_order_member_id'] ]; } /** * @Desc 生成核销数据-入order_process * @Author Gorden * @Date 2024/9/9 17:07 * * @param $params * @return array */ public static function generateWriteOffDataByOrderProcess($params) { return [ 'charge' => [ 'charge_amount' => $params['charge_amount'], 'charge_content' => $params['order_remark'] ?? '', 'charge_user_id' => $params['write_off_member_id'], 'charge_premises' => $params['dept_premises_id'], 'charge_premises_info' => $params['dept'] ?? '' ], 'member_id' => $params['join_order_member_id'], 'goods_id' => $params['goods_id'] ?? '', 'goods_sku_id' => $params['goods_sku_id'] ?? '', 'order_id' => $params['order_id'], 'platform' => 'SYSTEM', 'order_code' => random_string(10, 'number'), 'appointment' => $params['appointment_ids'] ?? '', ]; } public static function generateAppointmentApplyData($params) { $member = Member::with('cert', 'info') ->where('member_id', $params['join_order_member_id']) ->first(); $name = ''; if (!empty($member) && !empty($member->cert) && !empty($member->cert->member_cert_name)) { $name = $member->cert->member_cert_name; } else if (!empty($member) && !empty($member->info) && !empty($member->info->member_info_nickname)) { $name = $member->info->member_info_nickname; } return [ 'name' => $name, 'times' => '', 'mobile' => !empty($member) ? $member->member_mobile : '', 'person' => $params['order_sheet_num'] ?? '', 'premises' => $params['dept_premises_id'] ?? '' ]; } /** * 微信支付宝扫码支付 */ public static function qrcodePay($params) { $log = SupportLog::channel('pay'); $log->info("PAY_PARAMS", json_decode(json_encode($params), true)); $params['order_amount_pay'] = floatval($params['order_amount_pay']); $qrcodeNbr = $params['qrcode_nbr']; $prefix = substr($qrcodeNbr, 0, 2); // 模拟数据 // $result = [ // 'return_code'=>'SUCCESS', // 'result_code' => 'SUCCESS' // ]; // $result=[ // 'code'=> '10000', // 'msg' => 'Success' // ]; // return $result; // 微信支付 if (in_array($prefix, [10, 11, 12, 13, 14, 15])) { $payData = [ 'out_trade_no' => $params['orderGroupId'], 'body' => '万悦康养订单', 'total_fee' => $params['order_amount_pay'] * 100, 'auth_code' => $params['qrcode_nbr'], ]; try { $config = config('payment.wxpay'); $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN') . '/notify/orderPay/wxpay'; Pay::wechat($config)->pos($payData); $result = self::findWxpay($params['orderGroupId'], 0); } catch (GatewayException $g) { $result = self::findWxpay($params['orderGroupId'], 0); } catch (\Exception $e) { $log->error("WXPAY", ['msg' => $e->getMessage()]); $result = self::findWxpay($params['orderGroupId'], 0); // throw new BusinessException("支付失败"); } try { $log->info("WXPAY_RETURN", json_decode(json_encode($result), true)); } catch (\Exception $e) { } } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) { $payData = [ 'out_trade_no' => $params['orderGroupId'], 'total_amount' => $params['order_amount_pay'], 'subject' => '万悦康养订单', 'auth_code' => $params['qrcode_nbr'], ]; try { $config = config('payment.alipay'); $config['notify_url'] = getenv('NOTIFY_DOMAIN_ADMIN') . '/notify/orderPay/alipay'; Pay::alipay($config)->pos($payData); $result = self::findAlipay($params['orderGroupId'], 0); } catch (GatewayException $g) { $result = self::findAlipay($params['orderGroupId'], 0); } catch (\Exception $e) { $log->error("ALIPAY", ['msg' => $e->getMessage()]); throw new BusinessException("支付失败"); } try { $log->info("ALIPAY_RETURN", json_decode(json_encode($result), true)); } catch (\Exception $e) { } } else { throw new BusinessException("付款码无效"); } return $result; } /** * @Desc 查询微信支付 * @Author Gorden * @Date 2024/8/16 14:55 * * @param $orderId * @param $nbr 循环次数 * @return mixed|void * @throws BusinessException */ public static function findWxpay($orderId, $nbr = 0) { try { $result = Pay::wechat(config('payment.wxpay'))->find($orderId, 'pos'); $result = json_decode(json_encode($result), true); } catch (\Exception $e) { SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => $e->getMessage()]); } 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') { SupportLog::channel('pay')->info("FIND_WXPAY_SUCCESS", ['nbr' => $nbr, 'order_id' => $orderId]); return $result; } else { if ($nbr > 1) { SupportLog::channel('pay')->error("FIND_WXPAY", ['msg' => '订单查询失败', 'order_id' => $orderId]); return ['msg' => '订单查询失败']; } sleep(3); SupportLog::channel('pay')->error("FIND_WXPAY", ['nbr' => $nbr, 'order_id' => $orderId]); return self::findWxpay($orderId, $nbr + 1); } } /** * @Desc 查询支付宝订单 * @Author Gorden * @Date 2024/8/16 15:16 * * @param $orderId * @param $nbr 循环次数 * @return mixed|void * @throws BusinessException */ public static function findAlipay($orderId, $nbr = 0) { try { $result = Pay::alipay(config('payment.alipay'))->find($orderId); $result = json_decode(json_encode($result), true); } catch (\Exception $e) { SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => $e->getMessage()]); } if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') { SupportLog::channel('pay')->info("FIND_ALIPAY_SUCCESS", ['nbr' => $nbr, 'order_id' => $orderId]); return $result; } else { if ($nbr > 1) { SupportLog::channel('pay')->error("FIND_ALIPAY", ['msg' => '订单查询失败', 'order_id' => $orderId]); return ['msg' => '订单查询失败']; } sleep(3); SupportLog::channel('pay')->error("FIND_ALIPAY", ['nbr' => $nbr, 'order_id' => $orderId]); return self::findAlipay($orderId, $nbr + 1); } } /** * 验证产品库存 */ public static function checkGoodsStorage($params) { foreach ($params['goodsContentList'] as $goods) { // 减库存,规格和总库存 if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) { $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first(); $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true); if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) { $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr']; } if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) { throw new BusinessException('库存不足'); } } $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first(); $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr']; if ($goodsRunning->goods_running_storage < 0) { throw new BusinessException('库存不足'); } } } /** * 下单时结算的组合支付payDetail */ public static function createPayDetail($params) { $insertPayDetailData = [ 'join_pay_member_id' => $params['join_order_member_id'], 'join_pay_order_id' => $params['orderGroupId'], 'pay_status' => $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING', 'pay_category' => !empty($params['submit_goods_classify']) ? $params['submit_goods_classify'] : $params['goods_classify'], 'pay_amount' => $params['order_amount_pay'], 'pay_paytimes' => date('Y-m-d H:i:s'), 'pay_prepayid' => $params['pay_category'], 'pay_json_request' => json_encode($params), 'pay_json_response' => $params['pay_json_response'] ?? '[]', 'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]', 'pay_addtimes' => time() ]; PayDetail::insert($insertPayDetailData); } /** * 组合支付,PayDetail */ public static function createPayConstituteDetail($params, $payDetail) { $qrcodePrepayId = ''; if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) { $qrcodePrepayId = $params['join_order_member_id'] . '-QRCODE'; } if (!$payDetail || ($payDetail->pay_prepayid != $params['pay_category'] && $payDetail->pay_prepayid != $qrcodePrepayId)) { $payDetail = new PayDetail(); $payDetail->join_pay_member_id = $params['join_order_member_id']; $payDetail->join_pay_order_id = $params['orderGroupId']; $payDetail->pay_category = $params['goods_classify'] ?? ''; $payDetail->pay_prepayid = $params['pay_category']; $payDetail->pay_json_request = json_encode($params); $payDetail->pay_addtimes = time(); } if ($payDetail->pay_prepayid == $qrcodePrepayId) { $payDetail->pay_prepayid = $params['pay_category']; } $payDetail->pay_json_response = $params['pay_json_response'] ?? json_encode([ 'pay-result' => '支付成功', 'result-datetime' => date('Y-m-d H:i:s') ]); $payDetail->pay_amount = $params['order_amount_pay']; $payDetail->pay_paytimes = date('Y-m-d H:i:s'); $payDetail->pay_status = 'SUCCESS'; $payDetail->join_pay_object_json = !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]'; $payDetail->save(); } public static function getPayWayByPrepayId($prepayId) { $payWay = ''; $categoryArray = explode('-', $prepayId); if (isset($categoryArray[1])) { $payWay = $categoryArray[1]; } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) { $payWay = $categoryArray[0]; } return $payWay; } /** * @Desc 支付使用优惠券 * @Author Gorden * @Date 2024/8/28 14:59 * * @param $memberId * @param $goods * @param $coupon * @param $payAmount * @return array|mixed */ public static function payUseCoupon($type, $settlementNow, $memberId, $goods, $coupon, $payAmount) { try { foreach ($coupon as $item) { if (!in_array(substr($item, 0, 2), ['CU', 'CO'])) { return []; } } $amountBalance = [ 'pay_amount' => $payAmount, 'welfare_balance' => 0, 'cut_balance' => 0, ]; foreach ($goods as $good) { $result = OrderService::useCoupon($type, $settlementNow, $memberId, $goods, $good, $coupon, $amountBalance); $amountBalance = [ 'pay_amount' => $result['pay_amount'], 'welfare_balance' => $result['welfare_balance'], 'cut_balance' => $result['cut_balance'], ]; } $couponDetailsIds = Redis::sMembers("ORDER:USE:COUPON:" . $memberId); Redis::del("ORDER:USE:COUPON:" . $memberId); $useCouponJson = Redis::get("ORDER:USE:COUPON:DISCOUNT:" . $memberId); Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId); return [ 'pay_amount' => $amountBalance['pay_amount'], 'detail_ids' => $couponDetailsIds, 'use_coupon_json' => $useCouponJson ?? [] ]; } catch (\Exception $e) { dump($e->getTrace()); } } public static function useCoupon($type, $settlementNow, $memberId, $goods, $good, $coupon, $amountBalance) { try { $cacheKey = "ORDER:USE:COUPON:" . $memberId; $cacheDiscountKey = "ORDER:USE:COUPON:DISCOUNT:" . $memberId; $payAmount = $amountBalance['pay_amount']; $welfareBalance = $amountBalance['welfare_balance']; $cutBalance = $amountBalance['cut_balance']; $goodsId = $good['goods_id']; $money = $good['goods_sales_price'] * $good['nbr']; $discountData = Redis::get($cacheDiscountKey); if (empty($discountData)) { $discountData = []; } else { $discountData = json_decode($discountData, true); } foreach ($coupon as $couponId) { $couponDetail = CouponDetail::leftJoin('coupon_goods', 'coupon_goods.join_goods_coupon_id', '=', 'coupon_detail.join_detail_coupon_id') ->leftJoin('coupon', 'coupon.coupon_id', '=', 'coupon_detail.join_detail_coupon_id') ->select('coupon_detail.coupon_detail_id', 'coupon_goods.coupon_goods_id', 'coupon_id', 'coupon_classify', 'coupon_value', 'coupon_minimum_limit', 'coupon_category') ->where('coupon_goods.join_coupon_goods_id', $goodsId) ->where('coupon_goods.join_coupon_goods_sku_id', $good['sku_id']) ->where('join_goods_coupon_id', $couponId) ->where('coupon_detail.join_coupon_detail_member_id', $memberId); if ($settlementNow == 'Y' && $type == 'pay') { $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED', 'WAITING']); } else { $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED'); } $couponDetail = $couponDetail->orderBy('coupon_detail_id', 'DESC') ->first(); if (!$couponDetail) { continue; } if ($settlementNow == 'Y') { $updateData = [ 'coupon_detail_status' => 'USED', 'coupon_detail_used_datetime' => date('Y-m-d H:i:s') ]; } else { $updateData = [ 'coupon_detail_status' => 'WAITING', ]; } // 计算优惠券包含的优惠商品的件数和总价 $countAndAmount = self::countAndAmount($goods, $couponId); // 如果是计件 if ($couponDetail->coupon_category == 'PIECE' && $countAndAmount['count'] < $couponDetail->coupon_minimum_limit) { continue; } if (in_array($couponDetail->coupon_classify, ['立减券', '满减券'])) { if (Redis::sIsMember($cacheKey, $couponId)) { continue; } Redis::sAdd($cacheKey, $couponId); if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) { $payAmount = $payAmount - $couponDetail->coupon_value; // json记录 $discountData[$couponId] = [ 'coupon_id' => $couponId, 'coupon_value' => $couponDetail->coupon_value, 'coupon_classify' => $couponDetail->coupon_classify, 'coupon_detail_id' => [$couponDetail->coupon_detail_id] ]; Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE)); CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData); } } elseif ($couponDetail->coupon_classify == '折扣券') { if (Redis::sIsMember($cacheKey, $couponId)) { continue; } Redis::sAdd($cacheKey, $couponId); if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) { $zhekouAmount = round($countAndAmount['amount'] * (100 - $couponDetail->coupon_value) / 100, 2); $payAmount = $payAmount - $zhekouAmount; // json记录 $discountData[$couponId] = [ 'coupon_id' => $couponId, 'coupon_value' => $zhekouAmount, 'coupon_classify' => $couponDetail->coupon_classify, 'coupon_detail_id' => [$couponDetail->coupon_detail_id] ]; Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE)); CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData); } } elseif (in_array($couponDetail->coupon_classify, ['抵用券', '赠品券'])) { if (Redis::sIsMember($cacheKey, $couponId)) { continue; } Redis::sAdd($cacheKey, $couponId); CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData); if ($good['nbr'] > 1) { $diyongAmount = $good['goods_sales_price']; $payAmount = $payAmount - $diyongAmount; } elseif (ceil($good['nbr']) == 1) { $diyongAmount = round($good['goods_sales_price'] * $good['nbr'], 2); $payAmount = $payAmount - $diyongAmount; } // json记录 $discountData[$couponId] = [ 'coupon_id' => $couponId, 'coupon_value' => $diyongAmount, 'coupon_classify' => $couponDetail->coupon_classify, 'coupon_detail_id' => [$couponDetail->coupon_detail_id] ]; Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE)); } elseif ($couponDetail->coupon_classify == '福利券') { if (Redis::sIsMember($cacheKey, $couponId)) { continue; } Redis::sAdd($cacheKey, $couponId); CouponDetail::where('coupon_detail_id', $couponDetail->coupon_detail_id)->update($updateData); $fuliAmount = 0; if (!empty($couponDetail->coupon_value)) { $fuliAmount = $couponDetail->coupon_value; } if ($fuliAmount >= $countAndAmount['amount']) { $preferentialAmount = $countAndAmount['amount']; } else { $preferentialAmount = $fuliAmount; } $payAmount = $payAmount - $preferentialAmount; // json记录 $discountData[$couponId] = [ 'coupon_id' => $couponId, 'coupon_value' => $preferentialAmount, 'coupon_classify' => $couponDetail->coupon_classify, 'coupon_detail_id' => [$couponDetail->coupon_detail_id] ]; Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE)); } elseif (in_array($couponDetail->coupon_classify, ['年卡', '季卡', '月卡'])) { if (Redis::sIsMember($cacheKey, $couponId) || Redis::sIsMember($cacheKey, $goodsId)) { continue; } Redis::sAdd($cacheKey, $couponId); Redis::sAdd($cacheKey, $goodsId); $kaAmount = 0; if (!empty($discountData[$couponId]['coupon_value'])) { $kaAmount = $discountData[$couponId]['coupon_value']; } if ($good['nbr'] > 1) { $payAmount = $payAmount - $good['goods_sales_price']; $kaAmount = $good['goods_sales_price']; } else { $payAmount = $payAmount - $good['goods_sales_price'] * $good['nbr']; $kaAmount = $good['goods_sales_price'] * $good['nbr']; } // json记录 $discountData[$couponId] = [ 'coupon_id' => $couponId, 'coupon_value' => $kaAmount, 'coupon_classify' => $couponDetail->coupon_classify, 'coupon_detail_id' => [$couponDetail->coupon_detail_id] ]; Redis::set($cacheDiscountKey, json_encode($discountData, JSON_UNESCAPED_UNICODE)); } } if ($payAmount < 0) { $payAmount = 0; } $amountBalance = [ 'pay_amount' => round($payAmount, 2), 'welfare_balance' => 0, 'cut_balance' => 0 ]; return $amountBalance; } catch (\Exception $e) { Redis::del("ORDER:USE:COUPON:" . $memberId); Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId); dump($e->getTrace()); } } /** * @Desc 选择优惠券,计算 * @Author Gorden * @Date 2024/8/28 14:18 * * @param $memberId * @param $goods * @param $good * @param $coupon * @param $amountBalance * @return array|void */ public static function chooseCoupon($settlementNow, $memberId, $goods, $good, $coupon, $amountBalance) { try { $cacheKey = "ORDER:USE:COUPON:" . $memberId; $payAmount = $amountBalance['pay_amount']; $welfareBalance = $amountBalance['welfare_balance']; $cutBalance = $amountBalance['cut_balance']; $goodsId = $good['goods_id']; $money = $good['goods_sales_price'] * $good['nbr']; foreach ($coupon as $couponId) { $couponDetail = CouponDetail::leftJoin('coupon_goods', 'coupon_goods.join_goods_coupon_id', '=', 'coupon_detail.join_detail_coupon_id') ->leftJoin('coupon', 'coupon.coupon_id', '=', 'coupon_detail.join_detail_coupon_id') ->select('coupon_detail.coupon_detail_id', 'coupon_goods.coupon_goods_id', 'coupon_id', 'coupon_classify', 'coupon_value', 'coupon_minimum_limit', 'coupon_category') ->where('coupon_goods.join_coupon_goods_id', $goodsId) ->where('coupon_goods.join_coupon_goods_sku_id', $good['sku_id']) ->where('join_goods_coupon_id', $couponId) ->where('coupon_detail.join_coupon_detail_member_id', $memberId); if ($settlementNow == 'Y') { $couponDetail = $couponDetail->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED', 'WAITING']); } else { $couponDetail = $couponDetail->where('coupon_detail.coupon_detail_status', 'ACTIVED'); } $couponDetail = $couponDetail->orderBy('coupon_detail_id', 'DESC') ->first(); if (!$couponDetail) { continue; } // 计算优惠券包含的优惠商品的件数和总价 $countAndAmount = self::countAndAmount($goods, $couponId); // 如果是计件 if ($couponDetail->coupon_category == 'PIECE' && $countAndAmount['count'] < $couponDetail->coupon_minimum_limit) { continue; } if (in_array($couponDetail->coupon_classify, ['立减券', '满减券'])) { if (Redis::sIsMember($cacheKey, $couponId)) { continue; } Redis::sAdd($cacheKey, $couponId); if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) { $payAmount = $payAmount - $couponDetail->coupon_value; } } elseif ($couponDetail->coupon_classify == '折扣券') { if (Redis::sIsMember($cacheKey, $couponId)) { continue; } Redis::sAdd($cacheKey, $couponId); if ($couponDetail->coupon_category == 'PIECE' || ($couponDetail->coupon_category == 'NORMAL' && $countAndAmount['amount'] >= $couponDetail->coupon_minimum_limit)) { $zhekouAmount = round($countAndAmount['amount'] * (100 - $couponDetail->coupon_value) / 100, 2); $payAmount = $payAmount - $zhekouAmount; } } elseif (in_array($couponDetail->coupon_classify, ['抵用券', '赠品券'])) { if (Redis::sIsMember($cacheKey, $couponId)) { continue; } Redis::sAdd($cacheKey, $couponId); if ($good['nbr'] > 1) { $diyongAmount = $good['goods_sales_price']; $payAmount = $payAmount - $diyongAmount; } elseif (ceil($good['nbr']) == 1) { $diyongAmount = round($good['goods_sales_price'] * $good['nbr'], 2); $payAmount = $payAmount - $diyongAmount; } } elseif ($couponDetail->coupon_classify == '福利券') { if (Redis::sIsMember($cacheKey, $couponId)) { continue; } Redis::sAdd($cacheKey, $couponId); $fuliAmount = 0; if (!empty($couponDetail->coupon_value)) { $fuliAmount = $couponDetail->coupon_value; } if ($fuliAmount >= $countAndAmount['amount']) { $preferentialAmount = $countAndAmount['amount']; } else { $preferentialAmount = $fuliAmount; } $payAmount = $payAmount - $preferentialAmount; } elseif (in_array($couponDetail->coupon_classify, ['年卡', '季卡', '月卡'])) { if (Redis::sIsMember($cacheKey, $couponId) || Redis::sIsMember($cacheKey, $goodsId)) { continue; } Redis::sAdd($cacheKey, $couponId); Redis::sAdd($cacheKey, $goodsId); if ($good['nbr'] > 1) { $payAmount = $payAmount - $good['goods_sales_price']; } else { $payAmount = $payAmount - $good['goods_sales_price'] * $good['nbr']; } } } if ($payAmount < 0) { $payAmount = 0; } $amountBalance = [ 'pay_amount' => round($payAmount, 2), 'welfare_balance' => $welfareBalance, 'cut_balance' => $cutBalance ]; return $amountBalance; } catch (\Exception $e) { Redis::del("ORDER:USE:COUPON:" . $memberId); Redis::del("ORDER:USE:COUPON:DISCOUNT:" . $memberId); dump($e->getTrace()); } } public static function countAndAmount($goods, $couponId) { try { $goodsIds = array_column($goods, 'goods_id'); $couponGoods = CouponGoods::whereIn('join_coupon_goods_id', $goodsIds) ->where('join_goods_coupon_id', $couponId) ->select('join_coupon_goods_id', 'join_coupon_goods_sku_id') ->get() ->toArray(); $count = 0; $amount = 0; foreach ($couponGoods as $couponGood) { foreach ($goods as $good) { if ($good['goods_id'] == $couponGood['join_coupon_goods_id'] && $good['sku_id'] == $couponGood['join_coupon_goods_sku_id']) { $count += $good['nbr']; $amount += $good['goods_sales_price'] * $good['nbr']; } } } return compact('count', 'amount'); } catch (\Exception $e) { dump($e->getTrace()); } } public static $couponClassify = [ 'wipe' => '抹零', 'custom' => '自定义优惠金额' ]; public static $payWay = [ 'WXPAY' => '微信支付', 'ALIPAY' => '支付宝', 'CASH' => '账户余额', 'CARD' => '储值卡', 'WELFARE' => '福利账户', 'MONEY' => '现金', 'OFFLINE' => '线下支付', 'OFFLINE_WXPAY' => '线下支付-微信', 'OFFLINE_ALIPAY' => '线下支付-支付宝', 'QRCODE' => '付款码', 'NONE' => '付零', 'VIP' => 'VIP账户' ]; }