| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918 | <?phpnamespace app\admin\service\order;use app\model\CouponDetail;use app\model\CouponGoods;use app\model\GoodsRunning;use app\model\GoodsSku;use app\model\Member;use app\model\MemberBenefit;use app\model\Order;use app\model\OrderSheet;use app\model\PayDetail;use app\model\SysDept;use support\Db;use support\exception\BusinessException;use support\Log as SupportLog;use support\Redis;use Webman\Event\Event;use Yansongda\Pay\Exceptions\GatewayException;use Yansongda\Pay\Log;use Yansongda\Pay\Pay;class OrderService{    /**     * @Desc 自动确认收货     * @Author Gorden     * @Date 2024/4/11 16:09     *     * @return void     */    public static function AutomaticReceipt()    {        try {            Db::beginTransaction();            $timeUnix = strtotime("-7 days");            $orders = Order::where('order_status_system', 'SIGNED')                ->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(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();                    }                }                // 释放优惠券                if (!empty($order->order_discount_json)) {                    $orderDiscountJson = json_decode($order->order_discount_json, true);                    foreach ($orderDiscountJson as $discount) {                        if (!empty($discount['coupon_id']) && !empty($discount['coupon_detail_id'])) {                            foreach ($discount['coupon_detail_id'] as $detailId) {                                if (substr($detailId, 0, 4) == 'CUDT') {                                    // 恢复优惠券                                    CouponDetail::where('coupon_detail_id', $detailId)->update(['coupon_detail_status' => 'ACTIVED']);                                }                            }                        }                    }                }                // 订单详情表                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'],                'charge_waiter' => $params['charge_waiter'] ?? ''            ],            '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_waiter' => $params['charge_waiter'] ?? '',                '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';                $wxReturn = Pay::wechat($config)->pos($payData);                $log->info("WXPAY_RETURN", json_decode(json_encode($wxReturn), true));                $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';                $alipayReturn = Pay::alipay($config)->pos($payData);                $log->info("WXPAY_RETURN", json_decode(json_encode($alipayReturn), true));                $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']);                } 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']);                } 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());        }    }    /**     * @Desc     * @Author Gorden     * @Date 2024/9/11 11:11     *     * @param MemberBenefit $benefit     * @return false[]|true[]     */    public static function checkPackageBenefit(MemberBenefit $benefit)    {        $result = ['sheet' => true, 'order' => true];        // 除此权益外,套包的其他权益是否用完了  where('join_benefit_package_id', $benefit->join_benefit_package_id)        $benefits = MemberBenefit::where('join_benefit_order_id', $benefit->join_benefit_order_id)            ->where('member_benefit_id', '<>', $benefit->member_benefit_id)            ->get()            ->toArray();        foreach ($benefits as $benefitItem) {            if ($benefitItem['join_benefit_package_id'] == $benefit->join_benefit_package_id) {                if ($benefitItem['member_benefit_limit_count'] > $benefitItem['member_benefit_used_count']) {                    return ['sheet' => false, 'order' => false];                }            }        }        foreach ($benefits as $benefitItem) {            if ($benefitItem['member_benefit_limit_count'] > $benefitItem['member_benefit_used_count']) {                $result['order'] = false;                return $result;            }        }        return $result;    }    public static $couponClassify = [        'wipe' => '抹零',        'custom' => '自定义优惠金额'    ];    public static $payWay = [        'WXPAY' => '微信支付',        'ALIPAY' => '支付宝',        'CASH' => '账户余额',        'CARD' => '储值卡',        'WELFARE' => '福利账户',        'MONEY' => '现金',        'OFFLINE' => '线下支付',        'OFFLINE_WXPAY' => '线下支付-微信',        'OFFLINE_ALIPAY' => '线下支付-支付宝',        'QRCODE' => '付款码',        'NONE' => '付零',        'VIP' => 'VIP账户'    ];}
 |