| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793 |
- <?php
- namespace addons\Store\common\models;
- use addons\Coupon\common\enums\AddonsCouponEnum;
- use addons\Coupon\common\models\AddonsCoupon;
- use addons\Coupon\common\models\AddonsCouponUserRelate;
- use addons\Store\common\enums\CouponEnum;
- use addons\Store\common\enums\StoreEnum;
- use common\enums\AddonsEnum;
- use common\enums\StatusEnum;
- use common\models\base\BaseActiveRecord;
- use common\models\mall\MallAddons;
- use Yii;
- use yii\db\Exception;
- use yii\db\Expression;
- use yii\helpers\Json;
- /**
- * This is the model class for table "qimall_addons_store_coupon".
- *
- * @property int $id
- * @property int $mall_id
- * @property int $store_id 门店id
- * @property string $name 优惠券名称
- * @property int $type 优惠券类型,1:折扣,2:满减
- * @property float $discount 折扣率
- * @property float|null $discount_limit 折扣优惠金额上限
- * @property float $min_price 最低消费金额
- * @property float $sub_price 优惠金额
- * @property int $total_count 优惠券总数量
- * @property int $sort 排序按升序排列
- * @property int $expire_type 到期类型:1=领取后n天过期,2=指定有效期,3=领取后n天生效,生效后m天过期
- * @property int $expire_day 有效天数,expire_type=1和3时
- * @property int $effect_days 领取到生效之间间隔的天数(领取后n天生效)
- * @property int $begin_at 有效期开始时间
- * @property int $end_at 有效期结束时间
- * @property int $appoint_type 1 指定分类 2 指定商品 3全部
- * @property string|null $rule 使用说明
- * @property int $is_remind 是否开启提醒
- * @property int $remind_days 提前提醒天数(到期前多少天提醒),is_remind=1 时有效
- * @property int $is_receive_limit 是否限制领取
- * @property int $receive_count 每人可以领取的数量,is_receive_limit=1时有意义
- * @property int $is_member 是否指定会员等级
- * @property int $is_original_use 是否原价购买使用(如果是,则只有原价购买商品时可以使用该优惠券)
- * @property int $is_public_receive 是否公开领取,公开领取的优惠券会展示在商品详情页
- * @property int $is_giving 启用优惠券转送功能:0-否;1-是;
- * @property int $status 状态[-1:删除;0:禁用;1启用]
- * @property int $coupon_status 优惠券状态,1:未开始,2:领取中,3:已过期,4:已失效(后台操作失效)
- * @property int $is_giving_reward 是否开启转赠奖励,开启后转赠优惠券自己可以获得额外奖励;is_giving=1 时有效
- * @property int $is_consume_reward 是否开启使用奖励,开启后使用该优惠券可以获得额外奖励;is_giving=1 时有效
- * @property string $qrcode_url 优惠券分享二维码保存路径,二维码包含内容:页面路径+优惠券id
- * @property string $poster_url 优惠券分享海报图片保存路径
- * @property int $created_at 创建时间
- * @property int $updated_at
- * @property int $exchange_voucher_type 兑换券类型,0全部抵扣,1部分抵扣
- */
- class StoreCoupon extends BaseActiveRecord
- {
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%addons_store_coupon}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['mall_id'], 'required'],
- [['mall_id', 'store_id', 'type', 'total_count', 'sort', 'expire_type', 'expire_day', 'effect_days', 'begin_at', 'end_at', 'appoint_type', 'is_remind', 'remind_days', 'is_receive_limit', 'receive_count', 'is_member', 'is_original_use',
- 'is_public_receive', 'is_giving', 'status', 'coupon_status', 'is_giving_reward', 'is_open_screen','is_consume_reward', 'created_at', 'updated_at','watch_times', 'exchange_voucher_type'], 'integer'],
- [['discount', 'discount_limit', 'min_price', 'sub_price'], 'number'],
- [['rule'], 'string'],
- [['name'], 'string', 'max' => 150],
- [['qrcode_url', 'poster_url','video_url','first_frame'], 'string', 'max' => 255],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'mall_id' => 'Mall ID',
- 'store_id' => '门店id',
- 'name' => '优惠券名称',
- 'type' => '优惠券类型,1:折扣,2:满减,3:兑换',
- 'discount' => '折扣率',
- 'discount_limit' => '折扣优惠金额上限',
- 'min_price' => '最低消费金额',
- 'sub_price' => '优惠金额',
- 'total_count' => '优惠券总数量',
- 'sort' => '排序按升序排列',
- 'expire_type' => '到期类型:1=领取后n天过期,2=指定有效期,3=领取后n天生效,生效后m天过期',
- 'expire_day' => '有效天数,expire_type=1和3时',
- 'effect_days' => '领取到生效之间间隔的天数(领取后n天生效)',
- 'begin_at' => '有效期开始时间',
- 'end_at' => '有效期结束时间',
- 'appoint_type' => '1 指定分类 2 指定商品 3全部',
- 'rule' => '使用说明',
- 'is_remind' => '是否开启提醒',
- 'remind_days' => '提前提醒天数(到期前多少天提醒),is_remind=1 时有效',
- 'is_receive_limit' => '是否限制领取',
- 'receive_count' => '每人可以领取的数量,is_receive_limit=1时有意义',
- 'is_member' => '是否指定会员等级',
- 'is_original_use' => '是否原价购买使用(如果是,则只有原价购买商品时可以使用该优惠券)',
- 'is_public_receive' => '是否公开领取,公开领取的优惠券会展示在商品详情页',
- 'is_giving' => '启用优惠券转送功能:0-否;1-是;',
- 'status' => '状态[-1:删除;0:禁用;1启用]',
- 'coupon_status' => '优惠券状态,1:未开始,2:领取中,3:已过期,4:已失效(后台操作失效)',
- 'is_giving_reward' => '是否开启转赠奖励,开启后转赠优惠券自己可以获得额外奖励;is_giving=1 时有效',
- 'is_consume_reward' => '是否开启使用奖励,开启后使用该优惠券可以获得额外奖励;is_giving=1 时有效',
- 'qrcode_url' => '优惠券分享二维码保存路径,二维码包含内容:页面路径+优惠券id',
- 'poster_url' => '优惠券分享海报图片保存路径',
- 'exchange_voucher_type' => '抵扣券类型',
- 'created_at' => '创建时间',
- 'updated_at' => 'Updated At',
- ];
- }
- /**
- * 商品
- * @return \yii\db\ActiveQuery
- */
- public function getGoods()
- {
- return $this->hasMany(StoreGoods::class, ['id' => 'goods_id'])
- ->via('goodsRelate');
- }
- /**
- * 商品关系
- * @return \yii\db\ActiveQuery
- */
- public function getGoodsRelate()
- {
- return $this->hasMany(StoreCouponGoodsRelate::class, ['coupon_id' => 'id']);
- }
- /**
- * 分类关系
- * @return \yii\db\ActiveQuery
- */
- public function getCateRelate()
- {
- return $this->hasMany(StoreCouponCatRelate::class, ['coupon_id' => 'id']);
- }
- /**
- * 等级关系
- * @return \yii\db\ActiveQuery
- */
- public function getMemberRelate()
- {
- return $this->hasMany(StoreCouponMemberRelate::class, ['coupon_id' => 'id']);
- }
- /**
- * 会员关系
- * @return \yii\db\ActiveQuery
- */
- public function getUserRelate()
- {
- return $this->hasMany(StoreCouponUserRelate::class, ['coupon_id' => 'id']);
- }
- /**
- * 会员关系
- * @return \yii\db\ActiveQuery
- */
- public function getUserRelateOne()
- {
- return $this->hasOne(StoreCouponUserRelate::class, ['coupon_id' => 'id']);
- }
- /**
- * 保存数据
- * @param array $params
- * @return StoreCoupon|bool
- * @throws \yii\db\Exception
- */
- public static function setData(array $params, string $scenarios = 'create')
- {
- $transaction = \Yii::$app->db->beginTransaction();
- try {
- if (empty($params['coupon_info'])) throw new \Exception('优惠券数据为空');
- if (isset($params['coupon_info']['type']) && $params['coupon_info']['type'] == 3) { // 兑换券是指定产品
- $params['coupon_info']['appoint_type'] = 2;
- }
- $coupon_info = $params['coupon_info'];
- unset($coupon_info['effect_expire_days']);
- $member_level_limits = $params['member_level_limits'] ?? [];
- $goods_id_list = $params['goods_id_list'] ?? [];
- $giving_rewards = $params['giving_reward'] ?? [];
- $consume_rewards = $params['consume_reward'] ?? [];
- $category_ids = $params['category_ids'] ?? [];
- $time = time();
- // 检查优惠券使用场景
- self::checkUseScene($params);
- if (!empty($coupon_info['id'])) {
- // 更新
- $model = self::findOne(['id' => $coupon_info['id'], 'status' => [StatusEnum::ENABLED, StatusEnum::DISABLED], 'mall_id' => $coupon_info['mall_id'], 'store_id' => $coupon_info['store_id']]);
- if (empty($model)) throw new Exception('优惠券不存在或已删除');
- // if ($model->total_count > $coupon_info['total_count']) throw new \Exception('优惠券发放数量不能减少');
- if ($coupon_info['total_count'] < 1) {
- //禅道优惠1458 调整优惠券编辑发放数量
- throw new \Exception('优惠券发放数量不能小于1');
- }
- } else {
- // 添加
- $model = new self();
- $model->loadDefaultValues();
- // 计算优惠券 有效期起止时间
- if (in_array($coupon_info['expire_type'], [StoreEnum::EXPIRE_TYPE1, StoreEnum::EXPIRE_TYPE3])) {
- // 领取后立即生效,n天过期
- // 领取后n天生效,m天过期
- $begin_at = $time;
- $end_at = 0;
- $coupon_status = 2;
- } else {
- $begin_at = $coupon_info['begin_at'];
- $end_at = $coupon_info['end_at'];
- $coupon_status = $begin_at <= $time ? 2 : 1;
- }
- $coupon_info['begin_at'] = $begin_at;
- $coupon_info['end_at'] = $end_at;
- $coupon_info['coupon_status'] = $coupon_status;
- }
- if (!$model->load($coupon_info, '') || !$model->save()) throw new \PHPUnit\Util\Exception($model->getErrorMessage());
- if (!empty($category_ids)) {
- $res = StoreCouponCatRelate::setData($model->id, $category_ids);
- if (!$res) throw new Exception(StoreCouponCatRelate::getStaticError());
- }
- if (!empty($goods_id_list)) {
- $res = StoreCouponGoodsRelate::setData($model->id, $goods_id_list);
- if (!$res) throw new Exception(StoreCouponGoodsRelate::getStaticError());
- }
- if (1 == $coupon_info['is_member'] && !empty($member_level_limits)) {
- $res = StoreCouponMemberRelate::setData($model->mall_id, $model->id, $model->store_id, $member_level_limits);
- if (!$res) throw new Exception(StoreCouponMemberRelate::getStaticError());
- }
- if (
- 1 == $coupon_info['is_giving'] &&
- 1 == $coupon_info['is_giving_reward'] &&
- !empty($giving_rewards)
- ) {
- $res = StoreCouponReward::setData($model->mall_id, $model->id, $model->store_id, StoreEnum::REWARD_TYPE_GIVING, $giving_rewards);
- if (!$res) throw new Exception(StoreCouponReward::getStaticError());
- }
- if (1 == $coupon_info['is_consume_reward'] && !empty($consume_rewards)) {
- $res = StoreCouponReward::setData($model->mall_id, $model->id, $model->store_id, StoreEnum::REWARD_TYPE_CONSUME, $consume_rewards);
- if (!$res) throw new Exception(StoreCouponReward::getStaticError());
- }
- $transaction->commit();
- return $model;
- } catch (Exception $e) {
- $transaction->rollBack();
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- /**
- * @name:
- * @msg: 检查优惠券的使用场景(指定适用类型、是否可以转赠、转赠和使用奖励、适用会员)
- * @param {array} $post
- * @return {*}
- */
- private static function checkUseScene(array $coupon_data)
- {
- $coupon_info = $coupon_data['coupon_info'] ?? [];
- $giving_rewards = $coupon_data['giving_reward'] ?? [];
- $consume_rewards = $coupon_data['consume_reward'] ?? [];
- $goods_id_list = $coupon_data['goods_id_list'] ?? [];
- $member_level_limits = $coupon_data['member_level_limits'] ?? [];
- $category_ids = $coupon_data['category_ids'] ?? [];
- if (1 == $coupon_info['appoint_type']) {
- // 指定分类可用
- if (empty($category_ids)) {
- throw new \Exception('指定分类可用的优惠券,请指定可用分类');
- }
- } elseif (2 == $coupon_info['appoint_type']) {
- // 指定商品可用
- if (empty($goods_id_list)) {
- throw new \Exception('指定商品可用的优惠券,请指定可用商品');
- }
- }
- if (1 == $coupon_info['is_giving']) {
- // 开启转赠
- if (1 == $coupon_info['is_giving_reward'] && empty($giving_rewards)) {
- throw new \Exception('请填写转赠奖励');
- }
- if (1 == $coupon_info['is_consume_reward'] && empty($consume_rewards)) {
- throw new \Exception('请填写使用奖励');
- }
- }
- if (1 == $coupon_info['is_member']) {
- // 指定会员等级
- if (empty($member_level_limits)) {
- throw new \Exception('请指定可以领取优惠券的会员等级');
- }
- }
- }
- /**
- * @name:
- * @msg: 解析优惠券信息
- * @param {array} $coupon_data 优惠券原始数据
- * @param {bool} $is_user_coupon 是否会员已经领取的优惠券的数据,默认 false
- * @return array
- */
- public static function parseCouponInfo(array $coupon_data, bool $is_user_coupon = false): array
- {
- $coupon_data['min_price'] = floatval($coupon_data['min_price']);
- $coupon_data['sub_price'] = floatval($coupon_data['sub_price']);
- $coupon_data['discount'] = floatval($coupon_data['discount']);
- $coupon_data['discount_limit'] = floatval($coupon_data['discount_limit']);
- $sub_price = 0;
- if (1 == $coupon_data['type']) {
- $content = '消费满' . $coupon_data['min_price'] . '元打' . $coupon_data['discount'] . '折';
- if ($coupon_data['discount_limit'] > 0) {
- $content .= ',最高优惠' . $coupon_data['discount_limit'] . '元';
- $sub_price = $coupon_data['discount_limit'];
- }
- } elseif (2 == $coupon_data['type']) {
- $content = '消费满' . $coupon_data['min_price'] . '元减' . $coupon_data['sub_price'] . '元';
- $sub_price = $coupon_data['sub_price'];
- } else if (3 == $coupon_data['type']) {
- if ($coupon_data['exchange_voucher_type'] == 0) {
- $content = '全额抵扣';
- } else {
- $content = '消费满0元减' . $coupon_data['sub_price'] . '元';
- $sub_price = $coupon_data['sub_price'];
- }
- } else {
- $content = '';
- }
- $superposition = '';
- if (1 == $coupon_data['is_original_use']) $superposition = '仅原价购买时可用';
- if ($is_user_coupon) {
- $begin_at = date('Y-m-d H:i', $coupon_data['start_time']);
- $end_at = date('Y-m-d H:i', $coupon_data['end_time']);
- $use_time = $begin_at . ' 至 ' . $end_at;
- } else {
- switch ($coupon_data['expire_type']) {
- case StoreEnum::APPOINT_TYPE1:
- $use_time = str_replace('N', $coupon_data['expire_day'], StoreEnum::getExpireTypeMap()[StoreEnum::APPOINT_TYPE1]);
- break;
- case StoreEnum::APPOINT_TYPE2:
- $begin_at = date('Y-m-d H:i', $coupon_data['begin_at']);
- $end_at = date('Y-m-d H:i', $coupon_data['end_at']);
- $use_time = $begin_at . ' 至 ' . $end_at;
- break;
- case StoreEnum::APPOINT_TYPE3:
- $use_time = str_replace('N', $coupon_data['expire_day'], StoreEnum::getExpireTypeMap()[StoreEnum::APPOINT_TYPE3]);
- $use_time = str_replace('M', $coupon_data['effect_days'], StoreEnum::getExpireTypeMap()[StoreEnum::APPOINT_TYPE3]);
- break;
- default:
- $use_time = '';
- break;
- }
- $begin_at = date('Y-m-d H:i', $coupon_data['begin_at']);
- $end_at = $coupon_data['end_at'] ? date('Y-m-d H:i', $coupon_data['end_at']) : '';
- }
- $coupon_info = [
- 'name' => $coupon_data['name'],
- 'appoint_type' => $coupon_data['appoint_type'],
- 'status_text' => StoreEnum::getCouponStatusMap($coupon_data['coupon_status'], true),
- 'use_time' => $use_time,
- 'content' => $content,
- 'begin_at' => $begin_at,
- 'end_at' => $end_at,
- 'sub_price' => floatval($sub_price),
- 'min_price' => floatval($coupon_data['min_price']),
- 'rule' => $coupon_data['rule'],
- 'superposition_use' => $superposition,
- ];
- return $coupon_info;
- }
- public static function formatData($store_coupon)
- {
- $item['name'] = $store_coupon['name'];
- $item['discount_method'] = $store_coupon['type'] == 1 ? $store_coupon['discount'] . '折' : '优惠' . $store_coupon['sub_price'] . '元';
- return $item;
- }
- public static function getCanUseCouponList($form, $isNewRecord)
- {
- if (!empty($isNewRecord)) return $form;
- $data = is_array($form->data) ? $form->data : Json::decode($form->data, true);
- $user_coupon_ids = $data['user_coupon_ids']??[];
- $mall_id = $form['mall_id'];
- $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
- $store_arr = [];
- $store_ids = '';
- foreach ($form['group_order_goods'] as $item) {
- $store_ids = $item['mch_order_info']['store_id'];
- }
- $store_extra = StoreExtra::lists(['where'=>[['store_id'=>$store_ids]]]);
- $is_open_coupon_deduct = true;
- foreach ($store_extra as $k=>$v){
- $deduct_setting = json_decode($v['deduct_setting'],true);
- if(empty($deduct_setting['is_open_coupon_deduct'])){
- $is_open_coupon_deduct = false;
- break;
- }
- $store_ids= $v['store_id'];
- }
- if($is_open_coupon_deduct==false) return $form;
- $params = [];
- $time = time();
- $where[] = ['status' => StatusEnum::ENABLED];
- $where[] = ['coupon_status' => AddonsCouponEnum::STATUS_RECEIVING];
- $where[] = ['is_use' => AddonsCouponEnum::IS_USE0];
- $where[] = ['or', ['is_giving' => AddonsCouponEnum::GIVING_N], ['is_giving' => AddonsCouponEnum::GIVING, 'giving_status' => AddonsCouponEnum::GIVING_STATUS1]];
- $where[] = ['giving_status' => [AddonsCouponEnum::GIVING_STATUS0, AddonsCouponEnum::GIVING_STATUS1]];
- $where[] = ['user_id' => $form['user_id']];
- $where[] = ['<=', 'start_time', $time];
- $where[] = ['>=', 'end_time', $time];
- $where[] = new Expression("FIND_IN_SET({$store_ids},store_id)");
- $params['where'] = $where;
- $list = StoreCouponUserRelate::lists($params);
- $platform_coupon_ids = [];
- $store_coupon_ids = [];
- foreach ($list as $value) {
- $value['from_type'] == 1 ? $platform_coupon_ids[] = $value['coupon_id'] : $store_coupon_ids[] = $value['coupon_id'];
- }
- // 优惠券ID去重
- $platform_coupon_ids = array_unique($platform_coupon_ids);
- $store_coupon_ids = array_unique($store_coupon_ids);
- if ($is_install) $platform_coupon_list = AddonsCoupon::lists(['where' => [['id' => $platform_coupon_ids]], 'index' => 'id','with'=>['goodsRelate','cateRelate', 'storeGoods']]);
- $store_coupon_list = StoreCoupon::lists(['where' => [['id' => $store_coupon_ids]], 'index' => 'id','with'=>['goodsRelate','cateRelate']]);
- $goods_id_arr = $goods_arr = [];
- $total_coupon_discount_money = 0;
- $is_original_goods_price = 1;
- foreach ($form['group_order_goods'] as $item) {
- if(empty($user_coupon_ids)) {
- if (
- // 精确对比2个数字
- bccomp($item['mch_order_info']['goods_price'], $item['mch_order_info']['original_goods_price'], 2) != 0
- ) {
- $is_original_goods_price = 0;
- }
- }
- $store_arr[$item['mch_order_info']['store_id']] = $item['mch_order_info']['goods_price'];
- if (!empty($item['goods'])) {
- foreach ($item['goods'] as $v) {
- $coupon_discount_money = 0;
- foreach ($v['goods_details'] as $val) {
- $coupon_discount_money += $val['marketing']['coupon_discount_money'] ?? 0;
- }
- $total_coupon_discount_money+=$coupon_discount_money;
- $goods_id_arr[] = $v['goods_id'];
- $goods_arr[$v['goods_id']] = ['num' => $v['num'], 'goods_price' => $v['goods_price'], 'coupon_discount_money' => $coupon_discount_money, 'store_id' => $v['goods_details'][0]['store_id']];
- }
- }
- }
- self::getCateArr($goods_id_arr,$goods_arr, $cate_id_arr, $cate_arr);
- $can_use_list = $can_use_list1 = $can_use_list2 = $can_use_list3 = $can_use_list4 = $can_use_list6 = [];
- // 优惠券今日剩余可使用次数
- $exchangeTypeCouponMaxUseNum = [];
- foreach ($list as &$v) {
- switch ($v['from_type']) {
- case 1:
- if (!empty($platform_coupon_list[$v['coupon_id']])) {
- $coupon = $platform_coupon_list[$v['coupon_id']];
- $coupon['from_type'] = $v['from_type'];
- //因为平台优惠券,指定门店支持多门店,且下单时,不同门店不能一起下单,所以可在此把优惠券的store_id 替换成下单商品的门店id
- $coupon['store_id'] = $store_ids;
- }
- break;
- case 2:
- if (!empty($store_coupon_list[$v['coupon_id']])) {
- $coupon = $store_coupon_list[$v['coupon_id']];
- $coupon['from_type'] = $v['from_type'];
- }
- break;
- }
- if (empty($coupon)) continue;
- $coupon_user_relate_arr[$v['from_type']][$coupon['id']] = $v;
- $coupon['user_coupon_id'] = $v['id'];
- // 判断是否原价使用优惠券
- if (!empty($coupon['is_original_use'])) {
- if ($is_original_goods_price == 0) {
- continue;
- }
- }
- if ($v['from_type'] == 1) {
- // 是否是转赠后才能使用
- if (!AddonsCoupon::checkCouponSourceIsFromSharing(array_merge($v, ['coupon' => $coupon]), 2)) {
- continue;
- }
- // 指定门店,相当于指定门店的全场通用
- unset($coupon['goodsRelate']);
- unset($coupon['cateRelate']);
- if (!empty($coupon['store_id'])) {
- if ($coupon['appoint_type'] == AddonsCouponEnum::APPOINT_TYPE6) {
- if($coupon['type'] == AddonsCouponEnum::EXCHANGE) {
- // 多件商品下单不能使用该券
- if (count($form['order_goods']) > 1) {
- continue;
- }
- $num = AddonsCoupon::getTodayLimit($form['mall_id'], $form['user_id'], $coupon, 0, 2);
- // 验证该券每日使用次数
- if (!$num) {
- continue;
- }
- $exchangeTypeCouponMaxUseNum[$coupon['id']] = $num;
- }
- $gs_id_arr = array_column($coupon['storeGoodsRelate'], 'goods_id');
- unset($coupon['storeGoodsRelate']);
- self::packagingArr($coupon, $goods_id_arr, $goods_arr, $can_use_list6, $gs_id_arr, $coupon_user_relate_arr, $v['from_type'], $coupon['appoint_type'],0,$user_coupon_ids);
- continue;
- }
- // 该券属于平台指的门店优惠券
- if (!empty($store_arr[$coupon['store_id']])) {
- unset($coupon['storeGoodsRelate']);
- $store_total_goods_price = $store_arr[$coupon['store_id']];
- self::packagingArr($coupon, [], [], $can_use_list4, [], $coupon_user_relate_arr, $v['from_type'], 3, $store_total_goods_price,$user_coupon_ids);
- }
- }
- continue;
- } else {
- //1 指定分类 2 指定商品 3全部
- if ($coupon['appoint_type'] == AddonsCouponEnum::APPOINT_TYPE1) {
- $ct_id_arr = array_column($coupon['cateRelate'], 'cate_id');
- unset($coupon['cateRelate']);
- unset($coupon['goodsRelate']);
- self::packagingArr($coupon, $ct_id_arr, $cate_arr, $can_use_list1, $ct_id_arr, $coupon_user_relate_arr, $v['from_type'], $coupon['appoint_type'],0,$user_coupon_ids,$total_coupon_discount_money);
- continue;
- }
- if ($coupon['appoint_type'] == AddonsCouponEnum::APPOINT_TYPE2) {
- $gs_id_arr = array_column($coupon['goodsRelate'], 'goods_id');
- unset($coupon['goodsRelate']);
- unset($coupon['cateRelate']);
- self::packagingArr($coupon, $goods_id_arr, $goods_arr, $can_use_list2, $gs_id_arr, $coupon_user_relate_arr, $v['from_type'], $coupon['appoint_type'],0,$user_coupon_ids);
- continue;
- }
- if ($coupon['appoint_type'] == AddonsCouponEnum::APPOINT_TYPE3) {
- unset($coupon['goodsRelate']);
- unset($coupon['cateRelate']);
- if (!empty($coupon['store_id'])) {
- //该券属于某个门店的全场通用券
- $store_total_goods_price = $store_arr[$coupon['store_id']];
- if(empty($store_total_goods_price)) continue;
- self::packagingArr($coupon, [], [], $can_use_list3, [], $coupon_user_relate_arr, $v['from_type'], $coupon['appoint_type'], $store_total_goods_price, $user_coupon_ids, $total_coupon_discount_money);
- }
- continue;
- }
- }
- }
-
- if (!empty($can_use_list1)) self::formatArr($can_use_list1, $can_use_list, 2);
- if (!empty($can_use_list2)) self::formatArr($can_use_list2, $can_use_list, 2);
- if (!empty($can_use_list3)) self::formatArr($can_use_list3, $can_use_list, 2);
- if (!empty($can_use_list4)) self::formatArr($can_use_list4, $can_use_list, 2);
- if (!empty($can_use_list6)) self::formatArr($can_use_list6, $can_use_list, 2);
- $discount_money = $form['marketing']['deduct']['coupon']['money'] ?? 0;
- $form->marketing['deduct']['coupon'] = [
- 'list' => $can_use_list,
- 'type_map' => CouponEnum::getTypeMap(),
- 'expire_type_map' => StoreEnum::getExpireTypeMap(),
- 'appoint_type_map' => StoreEnum::getAppointTypeMap(),
- 'discount_money' => $discount_money,
- 'exchange_type_coupon_max_use_num' => $exchangeTypeCouponMaxUseNum ?: null,
- ];
- return $form;
- }
- public static function packagingArr($coupon, $id_arr, $arr, &$can_use_list, $have_id_arr, $coupon_user_relate_arr, $from_type, $appoint_type = 1, $total_price = 0,$user_coupon_ids =[],$total_coupon_discount_money = 0)
- {
- $coupon['coupon_discount_money'] = 0;
- // 获取用户优惠券有效期结束时间 替换结束时间
- $end_at = $coupon_user_relate_arr[$from_type][$coupon['id']]['end_time'];
- $coupon['end_at'] = $end_at;
- if ($appoint_type == StoreEnum::APPOINT_TYPE1) {
- // foreach ($id_arr as $id) {
- // if (in_array($id, $have_id_arr)) {
- // $price = $arr[$id]['goods_price'];
- // if (($coupon['min_price'] && ($total_coupon_discount_money + $price) >= $coupon['min_price'])||(in_array($coupon['user_coupon_id'],$user_coupon_ids))) {
- // if ($coupon['type'] == StoreEnum::DISCOUNT) $coupon['sub_price'] = bcmul($coupon['discount'] / 10, $price, 2);
- // /* if (!empty( $can_use_list[$from_type][$coupon['store_id']][$coupon['id']])) {
- // //优惠额度更大的优先
- // if ( $can_use_list[$from_type][$coupon['store_id']][$coupon['id']]['sub_price'] < $coupon['sub_price']) {
- // $can_use_list[$from_type][$coupon['store_id']][$coupon['id']] = $coupon;
- // continue;
- // }
- // //有效期更短的优先
- // $end_at = $coupon_user_relate_arr[$from_type][$coupon['id']]['end_at'];
- // if ( $can_use_list[$from_type][$coupon['store_id']][$coupon['id']]['sub_price'] == $coupon['sub_price'] && $end_at > time()) {
- // $can_use_list[$from_type][$coupon['store_id']][$coupon['id']] = $coupon;
- // }
- // } else {
- // $can_use_list[$from_type][$coupon['store_id']][$coupon['id']] = $coupon;
- // } */
- // $can_use_list[$from_type][$coupon['store_id']][] = $coupon;
- // }
- // }
- // }
- // 优惠券支持的分类
- // $id_arr;
- // 当前全部商品
- // $arr;
- if (count(array_diff($id_arr, array_keys($arr))) == 0) {
- $can_use_list[$from_type][$coupon['store_id']][] = $coupon;
- }
- }
- if ($appoint_type == StoreEnum::APPOINT_TYPE2 || ($from_type == 1 && $appoint_type == AddonsCouponEnum::APPOINT_TYPE6)) {
- foreach ($id_arr as $id) {
- if (in_array($id, $have_id_arr)) {
- if ($coupon['type'] == AddonsCouponEnum::EXCHANGE) {
- $can_use_list[$from_type][$coupon['store_id']][] = $coupon;
- break;
- }
- $price = $arr[$id]['goods_price'];
- if (empty($coupon['min_price'])) { // 考虑到抵扣券全部抵扣并没有 最低消费金额
- if (($coupon['type'] == 3 && empty($coupon['exchange_voucher_type'])) || (in_array($coupon['user_coupon_id'],$user_coupon_ids))) {
- if ($coupon['type'] == StoreEnum::DISCOUNT) $coupon['sub_price'] = bcmul($coupon['discount'] / 10, $price, 2);
- $can_use_list[$from_type][$coupon['store_id']][] = $coupon;
- break;
- }
- } else {
- if ((($arr[$id]['coupon_discount_money'] + $price) >= $coupon['min_price']) || (in_array($coupon['user_coupon_id'],$user_coupon_ids))) {
- if ($coupon['type'] == StoreEnum::DISCOUNT) $coupon['sub_price'] = bcmul($coupon['discount'] / 10, $price, 2);
- $can_use_list[$from_type][$coupon['store_id']][] = $coupon;
- break;
- }
- }
- }
- }
- // 当前购买的ID
- // $have_id_arr;
- // 支持的ID
- // $id_arr;
- /*if (count(array_diff($id_arr, array_keys($arr))) == 0) {
- $can_use_list[$from_type][$coupon['store_id']][] = $coupon;
- }*/
- }
- if ($appoint_type == AddonsCouponEnum::APPOINT_TYPE3) {
- // 计算优惠前金额
- // $total_price = bcadd($total_price, $total_coupon_discount_money, 2);
- if (empty($coupon['min_price'])) {
- if (($coupon['type'] == 3 && empty($coupon['exchange_voucher_type'])) || (in_array($coupon['user_coupon_id'],$user_coupon_ids))) {
- if ($coupon['type'] == AddonsCouponEnum::DISCOUNT) $coupon['sub_price'] = bcmul($coupon['discount'] / 10, $total_price, 2);
- $can_use_list[$from_type][$coupon['store_id']][] = $coupon;
- }
- } else {
- if (($total_price >= $coupon['min_price']) || (in_array($coupon['user_coupon_id'], $user_coupon_ids))) {
- if ($coupon['type'] == AddonsCouponEnum::DISCOUNT) $coupon['sub_price'] = bcmul($coupon['discount'] / 10, $total_price, 2);
- $can_use_list[$from_type][$coupon['store_id']][] = $coupon;
- }
- }
- }
- }
- /**
- * 获取分类数据
- * @Author: hua
- * @DateTime: 2021/10/15 10:56
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $goods_id_arr
- * @param $goods_arr
- * @param $cate_id_arr
- * @param $cate_arr
- * @return string
- */
- public static function getCateArr($goods_id_arr, $goods_arr,&$cate_id_arr, &$cate_arr)
- {
- $goods_cate_relate_list = StoreGoodsCateRelate::findAll(['goods_id' => $goods_id_arr]);
- foreach ($goods_cate_relate_list as $v) {
- $cate_id_arr[] = $v['cate_id'];
- $cate_arr[$v['cate_id']]['store_id'] = $goods_arr[$v['goods_id']]['store_id'] ?? 0;
- if (isset($cate_arr[$v['cate_id']])) {
- if (!isset($cate_arr[$v['cate_id']]['goods_price'])) $cate_arr[$v['cate_id']]['goods_price'] = 0;
- $cate_arr[$v['cate_id']]['goods_price'] += $goods_arr[$v['goods_id']]['goods_price'] ?? 0;
- } else {
- $cate_arr[$v['cate_id']]['goods_price'] = $goods_arr[$v['goods_id']]['goods_price'] ?? 0;
- }
- }
- return '';
- }
- /**
- * 格式化
- * @Author: hua
- * @DateTime: 2021/10/15 10:04
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $input_arr
- * @param $output_arr
- * @param int $deep
- */
- public static function formatArr($input_arr, &$output_arr, $deep = 1)
- {
- if ($deep == 1) {
- foreach ($input_arr as $from_type=>$val){
- foreach ($val as $store_id=>$coupon){
- $output_arr[] = $coupon;
- }
- }
- }
- if ($deep == 2) {
- foreach ($input_arr as $from_type=>$val){
- foreach ($val as $store_id=>$rows){
- foreach ($rows as $coupon_id=>$coupon){
- $output_arr[] = $coupon;
- }
- }
- }
- }
- }
- public static function deleteCoupon(int $coupon_id, int $mall_id)
- {
- $transaction = \Yii::$app->db->beginTransaction();
- try {
- $model = StoreCoupon::findOne(['mall_id' => $mall_id, 'id' => $coupon_id, 'status' => StatusEnum::ENABLED]);
- if (empty($model)) {
- throw new \Exception('优惠券不存在或已删除');
- }
- $model->status = StatusEnum::DISABLED;
- $model->coupon_status = AddonsCouponEnum::STATUS_FAILURE;
- $model->updated_at = time();
- $res_coupon = $model->save();
- $res_user_coupon = StoreCouponUserRelate::updateAll(['status' => StatusEnum::DISABLED, 'coupon_status' => AddonsCouponEnum::STATUS_FAILURE], ['mall_id' => $mall_id,'from_type'=>2, 'id' => $coupon_id, 'status' => StatusEnum::ENABLED]);
- if ($res_coupon === false || $res_user_coupon === false) {
- throw new \Exception('删除失败: res_coupon => ' . $model->getErrorMessage() . ', res_user_coupon => ' . StoreCouponUserRelate::getStaticError());
- }
- $transaction->commit();
- return true;
- } catch (\Exception $e) {
- $transaction->rollBack();
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- public static function getCouponListByDiy($params)
- {
- $list = self::listPage([
- 'where' => $params,
- 'select' => 'id,name,type,min_price,discount,exchange_voucher_type,sub_price',
- 'limit' => 10
- ]);
- $type_map = CouponEnum::getTypeMap();
- if ($list['list']) {
- foreach ($list['list'] as &$item) {
- $item['type_text'] = $type_map[$item['type']] . '券';
- if (1 == $item['type']) {
- $content = '消费满' . $item['min_price'] . '元打' . $item['discount'] . '折';
- if ($item['discount_limit'] > 0) {
- $content .= ',最高优惠' . $item['discount_limit'] . '元';
- }
- } elseif (2 == $item['type']) {
- $content = '消费满' . $item['min_price'] . '元减' . $item['sub_price'] . '元';
- } else if (3 == $item['type']) {
- if ($item['exchange_voucher_type'] == 0) {
- $content = '全额抵扣';
- } else {
- $content = '消费满0元减' . $item['sub_price'] . '元';
- }
- } else {
- $content = '';
- }
- $item['content'] = $content;
- }
- }
- return $list;
- }
- }
|