| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432 |
- <?php
- namespace addons\Store\common\models;
- use addons\Coupon\common\enums\AddonsCouponEnum;
- use addons\Coupon\common\models\AddonsCoupon;
- use addons\Coupon\common\models\AddonsCouponMemberRelate;
- use addons\Coupon\common\models\AddonsCouponRemind;
- use addons\Coupon\common\models\AddonsCouponStatistics;
- use addons\Store\common\enums\StoreEnum;
- use common\enums\AddonsEnum;
- use common\enums\RedisKeyEnum;
- use common\enums\StatusEnum;
- use common\helpers\LockHelper;
- use common\models\base\BaseActiveRecord;
- use common\models\mall\MallAddons;
- use common\models\user\User;
- use Yii;
- use yii\db\Exception;
- /**
- * This is the model class for table "qimall_addons_store_coupon_user_relate".
- *
- * @property int $id
- * @property int $mall_id
- * @property string $store_id 门店id
- * @property int $from_type 类型:1:平台优惠券;2:门店优惠券
- * @property int $user_id 用户
- * @property int $coupon_id 优惠卷
- * @property int $coupon_status 优惠券状态,2:领取中,3:已过期,4:已失效(后台操作失效、转赠被领取后、使用之后)
- * @property int $start_time 优惠券开始生效时间
- * @property int $end_time 优惠券过期时间
- * @property int $is_use 是否已使用:0=未使用,1=已使用
- * @property int $is_giving 是否已赠送:0-否;1-是;
- * @property int $giving_status 转赠状态,0:未转赠,1:转赠中,2:已被领取(转赠完成)
- * @property string $receive_type 获取方式,如"商品详情页领取"
- * @property string $receive_platform 领取来源,从哪个平台领取的,wechat:微信,mp-wx:微信小程序,h5,app,work-wx:企业微信
- * @property int $is_force_failure 是否强制失效,后台操作用户已领取的优惠券失效
- * @property int $is_send_reward 是否已经发放优惠券奖励,1:是,0:否
- * @property int $status 状态[-1:删除;0:禁用;1启用]
- * @property int $created_at 创建时间
- * @property int $updated_at
- */
- class StoreCouponUserRelate extends BaseActiveRecord
- {
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%addons_store_coupon_user_relate}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['mall_id', 'from_type', 'user_id', 'coupon_id'], 'required'],
- [['mall_id', 'user_id', 'coupon_id', 'coupon_status', 'start_time', 'end_time', 'is_use', 'is_giving', 'giving_status', 'is_force_failure', 'is_send_reward', 'status', 'created_at', 'updated_at'], 'integer'],
- [['receive_type'], 'string', 'max' => 255],
- [['receive_platform'], 'string', 'max' => 25],
- [['store_id'], 'string'],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'mall_id' => 'Mall ID',
- 'store_id' => '门店id',
- 'from_type' => '类型:1:平台优惠券;2:门店优惠券',
- 'user_id' => '用户',
- 'coupon_id' => '优惠卷',
- 'coupon_status' => '优惠券状态,2:领取中,3:已过期,4:已失效(后台操作失效、转赠被领取后、使用之后)',
- 'start_time' => '优惠券开始生效时间',
- 'end_time' => '优惠券过期时间',
- 'is_use' => '是否已使用:0=未使用,1=已使用',
- 'is_giving' => '是否已赠送:0-否;1-是;',
- 'giving_status' => '转赠状态,0:未转赠,1:转赠中,2:已被领取(转赠完成)',
- 'receive_type' => '获取方式,如\"商品详情页领取\"',
- 'receive_platform' => '领取来源,从哪个平台领取的,wechat:微信,mp-wx:微信小程序,h5,app,work-wx:企业微信',
- 'is_force_failure' => '是否强制失效,后台操作用户已领取的优惠券失效',
- 'is_send_reward' => '是否已经发放优惠券奖励,1:是,0:否',
- 'status' => '状态[-1:删除;0:禁用;1启用]',
- 'created_at' => '创建时间',
- 'updated_at' => 'Updated At',
- ];
- }
- public static function setData($params)
- {
- $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_COUPON . ':' . $params['from_type'] . ':', $params['coupon_id']);
- $identification = uniqid();
- $t = Yii::$app->db->beginTransaction();
- try {
- $time = time();
- if (!LockHelper::lock($lock_key, $identification, 30, 60)) throw new Exception('当前访问人数过多');
- switch ($params['from_type']) {
- case 1:
- $where[] = ['id' => $params['coupon_id'], 'mall_id' => $params['mall_id'], 'status' => [StatusEnum::ENABLED,StatusEnum::DISABLED]];
- $coupon_model = AddonsCoupon::getOne($where);
- if (empty($coupon_model['store_id'])) throw new Exception('该优惠券不是平台指的给门店领取');
- $relate_id = self::receive($coupon_model, $params, $time, $t);
- AddonsCouponStatistics::setData(['mall_id'=>$params['mall_id'], 'coupon_id'=>$params['coupon_id'],'received_number'=>1,]);
- break;
- case 2:
- $where[] = ['id' => $params['coupon_id'], 'mall_id' => $params['mall_id'], 'status' => [StatusEnum::ENABLED,StatusEnum::DISABLED]];
- $coupon_model = StoreCoupon::getOne($where);
- $relate_id = self::receive($coupon_model, $params, $time, $t);
- StoreCouponStatistics::setData(['mall_id'=>$params['mall_id'], 'coupon_id'=>$params['coupon_id'],
- 'store_id'=>$coupon_model['store_id'], 'received_number'=>1,]);
- break;
- default:
- throw new Exception('领取类型有误');
- break;
- }
- LockHelper::ulock($lock_key, $identification);
- $t->commit();
- return $relate_id;
- } catch (Exception $e) {
- LockHelper::ulock($lock_key, $identification);
- $t->rollBack();
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- //领取优惠券
- public static function receive($coupon_model, $params, $time, $t)
- {
- if (empty($coupon_model)) throw new Exception('该优惠券不存在');
- if ($coupon_model["coupon_status"] == AddonsCouponEnum::STATUS_NOT_BEGIN) throw new Exception('该优惠券不能领取');
- if ($coupon_model["coupon_status"] == AddonsCouponEnum::STATUS_EXPIRED) throw new Exception('该优惠券已过期');
- if ($coupon_model["coupon_status"] == AddonsCouponEnum::STATUS_FAILURE) throw new Exception('该优惠券已失效');
- if ($coupon_model["total_count"] <= 0) {
- $coupon_model->status = StatusEnum::DISABLED;
- $coupon_model->save();
- $t->commit();
- throw new Exception('该优惠券被领完啦');
- }
- if ($params['num'] > $coupon_model['total_count']) throw new Exception('该优惠券数量不足');
- if ($coupon_model['is_receive_limit']) {
- $counts = self::find()->where(['mall_id' => $params['mall_id'], 'from_type' => $params['from_type'], 'user_id' => $params['user_id'], 'coupon_id' => $params['coupon_id']])->count();
- if (($counts + $params['num']) > $coupon_model['receive_count']) throw new Exception('每人只可以领取' . $coupon_model['receive_count'] . '张');
- }
- if ($coupon_model['is_member']) {
- if($coupon_model instanceof AddonsCoupon){
- $member_relate_list = AddonsCouponMemberRelate::lists(['where' => [['mall_id' => $params['mall_id']], ['coupon_id' => $coupon_model['id']]], 'select' => 'member_level']);
- }else{
- $member_relate_list = StoreCouponMemberRelate::lists(['where' => [['mall_id' => $params['mall_id']], ['coupon_id' => $coupon_model['id']]], 'select' => 'member_level']);
- }
- $level_arr = array_column($member_relate_list, 'member_level');
- if (!in_array($params['user']['level'], $level_arr)) throw new Exception('该优惠券指定会员等级');
- }
- switch ($coupon_model['expire_type']) {
- case AddonsCouponEnum::EXPIRE_TYPE2:
- $params['start_time'] = $coupon_model['begin_at'];
- $params['end_time'] = $coupon_model['end_at'];
- break;
- case AddonsCouponEnum::EXPIRE_TYPE1:
- $params['start_time'] = $time;
- $params['end_time'] = $coupon_model['expire_day'] * 86400 + $time;
- break;
- case AddonsCouponEnum::EXPIRE_TYPE3:
- $params['start_time'] = $coupon_model['effect_days'] * 86400 + $time;
- $params['end_time'] = $coupon_model['expire_day'] * 86400 + $params['start_time'];
- break;
- default:
- throw new Exception('有效期时间设置不对');
- }
- $insert = [];
- $remind = [];
- for ($i = 0; $i < $params['num']; $i++) {
- $insert[] = [$params['mall_id'], $coupon_model['store_id'], $params['from_type'], $params['user_id'], $params['coupon_id'], $coupon_model['coupon_status'], 1, $params['start_time'], $params['end_time'], 0, 0, 0, StoreEnum::getSendFromMap($params['receive_type'], $params['mall_id']), $params['receive_platform'], 0, 0, $time, $time];
- $remind[] = [$params['mall_id'], $params['user_id'], $params['coupon_id'], $params['end_time'], 1, 1, $time, $time];
- }
- $field = ['mall_id', 'store_id', 'from_type', 'user_id', 'coupon_id', 'coupon_status', 'status', 'start_time', 'end_time', 'is_use', 'is_giving', 'giving_status', 'receive_type', 'receive_platform', 'is_force_failure', 'is_send_reward', 'created_at', 'updated_at'];
- // 批量插入数据
- $res = Yii::$app->db->createCommand()->batchInsert(self::tableName(), $field, $insert)->execute();
- $newId = Yii::$app->db->getLastInsertID();
- if ($res == false) throw new Exception('领取失败');
- $total_count = $coupon_model->total_count - $params['num'];
- $coupon_model->total_count = $total_count >= 0 ? $total_count : 0;
- $res = $coupon_model->save();
- if ($res == false) throw new Exception('领取失败 ' . $coupon_model->getErrotMessage());
- if (1 == $coupon_model->is_remind && !empty($remind)) {
- $remind_fields = ['mall_id', 'user_id', 'coupon_id', 'expire_time', 'status', 'send_status', 'created_at', 'updated_at'];
- $remind_table_name = (new StoreCouponRemind())->tableSchema->name;
- Yii::$app->db->createCommand()->batchInsert($remind_table_name, $remind_fields, $remind)->execute();
- }
- return $newId;
- }
- /**
- * @desc:领取别人赠与
- * @Author: hua
- * @Date: 2022/7/16
- * @Time: 10:22
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $params
- * @return StoreCouponUserRelate|false
- */
- public static function receiveByGive($params)
- {
- $t = Yii::$app->db->beginTransaction();
- try {
- $share_log_model = StoreCouponShareLog::findOne(['id' => $params['coupon_share_log_id']]);
- if (empty($share_log_model)) throw new Exception('未找到转赠记录');
- $params['user_coupon_id'] = $share_log_model->user_coupon_id;
- $where[] = ['id' => $params['user_coupon_id'], 'mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED];
- $coupon_user_relate_model = StoreCouponUserRelate::getOne($where);
- if (empty($coupon_user_relate_model)) throw new Exception('该优惠券不存在');
- if ($coupon_user_relate_model['user_id'] == $params['user_id']) throw new Exception('不能领取自己分享的优惠券');
- if ($coupon_user_relate_model["coupon_status"] == StoreEnum::STATUS_EXPIRED) throw new Exception('该优惠券已过期');
- if ($coupon_user_relate_model["coupon_status"] == StoreEnum::STATUS_FAILURE) throw new Exception('该优惠券已失效');
- if ($coupon_user_relate_model["is_use"] == 1) throw new Exception('该优惠券已被赠送者使用');
- if ($coupon_user_relate_model["is_giving"] == 0) throw new Exception('该优惠券没有被赠送者送出');
- if ($coupon_user_relate_model["giving_status"] == StoreEnum::GIVING_STATUS2) throw new Exception('该优惠券已被领取');
- if($coupon_user_relate_model['from_type']==1){
- $coupon_class = AddonsCoupon::class;
- $coupon_member_relate_class = AddonsCouponMemberRelate::class;
- }else{
- $coupon_class = StoreCoupon::class;
- $coupon_member_relate_class = StoreCouponMemberRelate::class;
- }
- $coupon_model = $coupon_class::findOne(['id' => $coupon_user_relate_model['coupon_id']]);
- if ($coupon_model['is_member']) {
- $member_relate_list = $coupon_member_relate_class::lists(['where' => [['mall_id' => $params['mall_id']], ['coupon_id' => $coupon_model['id']]], 'select' => 'member_level']);
- $level_arr = array_column($member_relate_list, 'member_level');
- if (!in_array($params['user']['level'], $level_arr)) throw new Exception('该优惠券指定会员等级');
- }
- if ($coupon_model['is_receive_limit'] ) {
- $received_counts = StoreCouponUserRelate::find()
- ->where(['mall_id' => $params['mall_id'], 'user_id' => $params['user_id'], 'status' => StatusEnum::ENABLED, 'coupon_id' => $coupon_model['id']])
- ->andWhere(['or', ['is_giving' => 0], ['is_giving' => 1, 'giving_status' => [StoreEnum::GIVING_STATUS0, StoreEnum::GIVING_STATUS1]]])
- ->count();
- if ($received_counts >= $coupon_model['receive_count']) throw new Exception('你已经领取过了');
- }
- $now = time();
- $coupon_user_model = new self();
- $coupon_user_model->mall_id = $params['mall_id'];
- $coupon_user_model->user_id = $params['user_id'];
- $coupon_user_model->store_id = $coupon_user_relate_model['store_id'];
- $coupon_user_model->coupon_id = $coupon_user_relate_model['coupon_id'];
- $coupon_user_model->from_type = $coupon_user_relate_model['from_type'];
- $coupon_user_model->coupon_status = $coupon_user_relate_model['coupon_status'];
- $coupon_user_model->status = 1;
- $coupon_user_model->start_time = $coupon_user_relate_model['start_time'];
- $coupon_user_model->end_time = $coupon_user_relate_model['end_time'];
- $coupon_user_model->is_use = 0;
- $coupon_user_model->is_giving = 0;
- $coupon_user_model->giving_status = 0;
- $coupon_user_model->receive_type = StoreEnum::getSendFromMap(StoreEnum::SEND_FROM6);
- $coupon_user_model->receive_platform = $params['receive_platform']??'o2o';
- $coupon_user_model->is_force_failure = 0;
- $coupon_user_model->is_send_reward = 0;
- $coupon_user_model->created_at = $now;
- $coupon_user_model->updated_at = $now;
- $res = $coupon_user_model->save();
- if ($res == false) throw new Exception('领取失败');
- $share_data = [
- 'mall_id' => $params['mall_id'],
- 'coupon_share_log_id' => $params['coupon_share_log_id'],
- 'get_user_coupon_id' => $coupon_user_model->id,
- 'receive_user_id' => $params['user_id'],
- ];
- $res = StoreCouponShareLog::setData($share_data);
- if ($res == false) throw new Exception(StoreCouponShareLog::getStaticError());
- $coupon_user_relate_model->giving_status = StoreEnum::GIVING_STATUS2;
- $coupon_user_relate_model->coupon_status = StoreEnum::STATUS_FAILURE;
- $res = $coupon_user_relate_model->save();
- if ($res == false) throw new Exception('更新赠送者优惠券状态失败');
- if ($coupon_model['is_remind']) {
- $remind_datas[] = [$params['mall_id'], $params['coupon_id'], $params['user_id'], $coupon_user_relate_model['end_time'], 1, 1, $now, $now];
- $remind_fields = ['mall_id', 'coupon_id', 'user_id', 'expire_time', 'status', 'send_status', 'created_at', 'updated_at'];
- $remind_table_name = (new StoreCouponRemind())->tableSchema->name;
- Yii::$app->db->createCommand()->batchInsert($remind_table_name, $remind_fields, $remind_datas)->execute();
- }
- $t->commit();
- return $coupon_user_model;
- } catch (Exception $e) {
- $t->rollBack();
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- /**
- * @desc:o2o订单完成后赠送优惠券
- * @Author: hua
- * @Date: 2022/7/15
- * @Time: 17:50
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $mall_id
- * @param $store_id
- * @param $from_type
- * @param $user_id
- * @param $give_coupon_arr //$give_coupon_arr=['coupon_id'=>'num'];
- * @param int $receive_type
- * @param string $receive_platform
- * @return array|false
- */
- public static function giveCouponByOrder($mall_id, $store_id, $user_id, $give_coupon_arr, $from_type, $receive_type = 2, $receive_platform = 'platform')
- {
- $trans = Yii::$app->db->beginTransaction();
- $locks = [];
- try {
- if ($from_type == 1) {
- $class = AddonsCoupon::class;
- $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
- if (!$is_install) return true;
- } else {
- $class = StoreCoupon::class;
- }
- $coupon_id_arr = array_keys($give_coupon_arr);
- $coupon_list = $class::findAll(['mall_id' => $mall_id, 'id' => $coupon_id_arr, 'status' => StatusEnum::ENABLED, 'coupon_status' => StoreEnum::STATUS_RECEIVING]);
- if (empty($coupon_list)) throw new Exception('暂无可用优惠券');
- $user = User::findOne(['id' => $user_id]);
- $can_give_coupon_arr = [];
- $time = time();
- foreach ($coupon_list as $coupon) {
- $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_COUPON, ':o2o:' . $coupon['id']);
- $identification = uniqid();
- if (!LockHelper::lock($lock_key, $identification, 30, 60)) throw new Exception('当前访问人数过多');
- $locks[$lock_key] = $identification;
- if ($coupon['expire_type'] == 2 && $coupon['end_at'] <= $time) continue;
- if ($coupon['total_count'] <= 0) continue;
- $member_level_arr = array_column($coupon['memberRelate'], 'level');
- if (!empty($member_level_arr) && !in_array($user['level'], $member_level_arr)) continue;
- $time = time();
- switch ($coupon['expire_type']) {
- case StoreEnum::EXPIRE_TYPE2:
- $start_time = $time;
- $end_time = $coupon['end_at'];
- break;
- case StoreEnum::EXPIRE_TYPE1:
- $start_time = $time;
- $end_time = $coupon['expire_day'] * 86400 + $time;
- break;
- case StoreEnum::EXPIRE_TYPE3:
- $start_time = $coupon['effect_days'] * 86400 + $time;
- $end_time = $coupon['expire_day'] * 86400 + $start_time;
- break;
- default:
- throw new Exception('有效期时间设置不对');
- }
- $can_give_coupon_arr[$coupon['id']] = [
- 'num' => $give_coupon_arr[$coupon['id']],
- 'start_time' => $start_time,
- 'end_time' => $end_time,
- 'total_count' => $coupon['total_count'],
- 'name' => $coupon['name'],
- 'coupon_status' => $coupon['coupon_status'],
- 'store_id'=>$coupon['store_id'],
- ];
- }
- $field = ['mall_id', 'store_id', 'from_type', 'user_id', 'coupon_id', 'coupon_status', 'start_time', 'end_time', 'is_use', 'is_giving', 'giving_status', 'receive_type', 'receive_platform', 'is_force_failure', 'is_send_reward', 'status', 'created_at', 'updated_at'];
- $insert = [];
- foreach ($can_give_coupon_arr as $coupon_id => $item) {
- $num = $item['num'];
- if ($item['total_count'] < $item['num']) $num = $item['total_count'];
- for ($i = 0; $i < $num; $i++) {
- $insert[] = [$mall_id, $store_id, $from_type, $user_id, $coupon_id, $item['coupon_status'], $item['start_time'], $item['end_time'], 0, 0, 0, StoreEnum::getSendFromMap($receive_type), $receive_platform, 0, 0, StatusEnum::ENABLED, $time, $time,];
- }
- $class = $from_type == 1 ? AddonsCoupon::class : StoreCoupon::class;
- $coupon_model = $class::findOne(['id' => $coupon_id]);
- $coupon_model->total_count -= $num;
- $res = $coupon_model->save();
- if ($res == false) throw new \Exception('赠送优惠券失败');
- if ($from_type == 1) {
- AddonsCouponStatistics::setData(['mall_id' => $mall_id, 'coupon_id' => $coupon_id, 'received_number' => $num,]);
- }else{
- StoreCouponStatistics::setData(['mall_id'=>$mall_id, 'coupon_id'=>$coupon_id, 'store_id'=>$item['store_id'], 'received_number'=>$num,]);
- }
- }
- if (!empty($insert)) {
- $res = Yii::$app->db->createCommand()->batchInsert(StoreCouponUserRelate::tableName(), $field, $insert)->execute();
- if ($res == false) {
- throw new \Exception('赠送优惠券失败');
- }
- }
- $trans->commit();
- LockHelper::batchUlock($locks);
- return $can_give_coupon_arr;
- } catch (\Exception $e) {
- $trans->rollBack();
- LockHelper::batchUlock($locks);
- self::setStaticError($e->getMessage());
- return false;
- }
- }
- /**
- * @notes:优惠券状态处理
- * @param $params
- * @return bool
- * @throws \yii\db\Exception
- * @author: lun
- * @Time: 2022/10/27 9:45
- */
- public static function handle($params)
- {
- $trans = Yii::$app->db->beginTransaction();
- try {
- $where = [['mall_id' => $params['mall_id']], ['id' => $params['id']], ['status' => StatusEnum::ENABLED]];
- $where[] = ['or like', 'store_id', [$params['store_id'].'%', '%'.$params['store_id'].'%', '%'.$params['store_id']], false];
- $model = self::getOne($where);
- if (empty($model)) throw new Exception('查无此数据');
- if ($params['status'] == StatusEnum::DELETE) {
- $model->status = $params['status'];
- $model->is_force_failure = StatusEnum::ENABLED;
- }
- if (!$model->save()) throw new \yii\db\Exception($model->getErrorMessage());
- $trans->commit();
- return true;
- } catch (Exception $e) {
- $trans->rollBack();
- return false;
- }
- }
- }
|