| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756 |
- <?php
- namespace addons\Coupon\common\models;
- use addons\Coupon\common\enums\AddonsCouponEnum;
- use addons\Store\common\enums\StoreEnum;
- use addons\Store\common\models\StoreCouponUserRelate;
- use common\enums\AddonsEnum;
- use common\enums\OrderStatusEnum;
- use common\enums\RedisKeyEnum;
- use common\enums\StatusEnum;
- use common\helpers\LockHelper;
- use common\models\mall\MallAddons;
- use common\models\user\User;
- use Exception;
- use Yii;
- /**
- * This is the model class for table "{{%addons_coupon_user_relate}}".
- *
- * @property int $id
- * @property int $mall_id
- * @property int $user_id 用户
- * @property int $coupon_id 优惠卷
- * @property int $coupon_status 优惠券状态,2:领取中,3:已过期,4:已失效(后台操作失效、转赠被领取后、使用之后)
- * @property int $status 状态[-1:删除;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 $created_at 创建时间
- * @property int $updated_at
- * @property int $give_time 转赠次数
- * @property int $start_time 优惠券开始生效时间
- * @property int $end_time 优惠券过期时间
- * @property int $is_use 是否已使用:0=未使用,1=已使用
- * @property string $mch_id
- */
- class AddonsCouponUserRelate extends \common\models\base\BaseActiveRecord
- {
- /**
- * {@inheritdoc}
- */
- public static function tableName()
- {
- return '{{%addons_coupon_user_relate}}';
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['mall_id', 'user_id', 'coupon_id'], 'required'],
- [['mall_id', 'user_id', 'coupon_id', 'coupon_status', 'status', 'is_giving', 'giving_status', 'is_force_failure', 'is_send_reward', 'created_at', 'updated_at', 'start_time', 'end_time', 'is_use','give_time'], 'integer'],
- [['receive_type'], 'string', 'max' => 255],
- [['receive_platform'], 'string', 'max' => 25],
- [['mch_id'], 'string'],
- [['store_id'], 'safe'],
- ];
- }
- /**
- * {@inheritdoc}
- */
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'mall_id' => '商城ID',
- 'user_id' => '会员ID',
- 'coupon_id' => '优惠券ID',
- 'coupon_status' => '优惠券状态',
- 'status' => 'Status',
- 'is_giving' => '优惠券是否已转赠',
- 'giving_status' => '转赠状态',
- 'receive_type' => '领取场景',
- 'receive_platform' => '领取平台',
- 'is_force_failure' => '是否已被强制失效',
- 'is_send_reward' => '是否已发放奖励',
- 'give_time'=>'转赠次数',
- 'created_at' => 'Created At',
- 'updated_at' => 'Updated At',
- 'start_time' => '有效期开始时间',
- 'end_time' => '有效期结束时间',
- 'is_use' => '是否已使用',
- 'mch_id' => '商户id',
- ];
- }
- /**
- * @return ActiveQueryInterface the relational query object.
- */
- public function getUser()
- {
- return $this->hasOne(User::class, ['id' => 'user_id']);
- }
- /**
- * 商品
- * @return \yii\db\ActiveQuery
- */
- public function getCoupon()
- {
- return $this->hasOne(AddonsCoupon::class, ['id' => 'coupon_id']);
- // ->where(['status' => StatusEnum::ENABLED]);
- }
- /**
- * 保存数据
- * @Author: zhengjianhua
- * @DateTime: 2021/12/18 0018 11:13
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $params
- * @return AddonsCoupon|bool
- * @throws \yii\db\Exception
- */
- public static function setData($params)
- {
- $lock_key = RedisKeyEnum::suffix(RedisKeyEnum::LOCK_COUPON , $params['coupon_id']);
- $identification = uniqid();
- $t = Yii::$app->db->beginTransaction();
- try {
- if (!LockHelper::lock($lock_key, $identification, 30, 60)) throw new Exception('当前访问人数过多');
- $where[] = ['id' => $params['coupon_id'], 'mall_id' => $params['mall_id'], 'status' => StatusEnum::ENABLED];
- $coupon_model = AddonsCoupon::getOne($where);
- 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) {
- $message = '该优惠券已失效';
- // 判断用户是否领取过优惠券
- $counts = self::find()->where(['mall_id' => $params['mall_id'],'user_id' => $params['user_id'],'coupon_id' => $params['coupon_id']])->count();
- if ($counts) {
- $message = '您已领取过优惠券';
- }
- throw new Exception($message);
- }
- 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'],'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']){
- $member_relate_list = AddonsCouponMemberRelate::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('该优惠券指定会员等级');
- }
- $time = time();
- 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('有效期时间设置不对');
- }
- $coupon_user_relate = null;
- if (!empty($params['coupon_id'])) {
- $insert = [];
- $remind_datas = [];
- $now = time();
- for ($i = 0; $i < $params['num']; $i++) {
- $insert[] = [ $params['mall_id'], $params['user_id'], $params['coupon_id'], $coupon_model['coupon_status'], 1, $params['start_time'], $params['end_time'], 0, 0, 0, AddonsCouponEnum::getSendFromMap($params['receive_type'], $params['mall_id']), $params['receive_platform'], 0, 0, $now, $now,$coupon_model['mch_id'] ];
- $remind_datas[] = [$params['mall_id'], $params['user_id'], $params['coupon_id'], $params['end_time'], 1, 1, $now, $now];
- }
- $field = ['mall_id','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','mch_id'];
- // 批量插入数据
- $res = Yii::$app->db->createCommand()->batchInsert(self::tableName(), $field, $insert)->execute();
- if($res==false) throw new Exception('领取失败');
- $coupon_user_relate = AddonsCouponUserRelate::getOne([
- [ 'user_id'=>$params['user_id']],
- ['mall_id'=>$params['mall_id']],
- ['coupon_id'=>$params['coupon_id']]
- ],true,[],'id desc');
- $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_datas)) {
- $remind_fields = ['mall_id', 'user_id', 'coupon_id', 'expire_time', 'status', 'send_status', 'created_at', 'updated_at'];
- $remind_table_name = (new AddonsCouponRemind())->tableSchema->name;
- Yii::$app->db->createCommand()->batchInsert($remind_table_name, $remind_fields, $remind_datas)->execute();
- }
- }
- LockHelper::ulock($lock_key,$identification);
- $t->commit();
- return $coupon_user_relate;
- } catch (Exception $e) {
- LockHelper::ulock($lock_key,$identification);
- $t->rollBack();
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- /**
- * @desc:领取别人赠与
- * @Author: hua
- * @Date: 2021/12/24
- * @Time: 17:38
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $params
- * @return AddonsCoupon|false|null
- */
- public static function receiveByGive($params)
- {
- $t = Yii::$app->db->beginTransaction();
- try {
- $share_log_model = AddonsCouponShareLog::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 = AddonsCouponUserRelate::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"]==AddonsCouponEnum::STATUS_EXPIRED) throw new Exception('该优惠券已过期');
- if($coupon_user_relate_model["coupon_status"]==AddonsCouponEnum::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"]==AddonsCouponEnum::GIVING_STATUS2) throw new Exception('该优惠券已被领取');
- $coupon_model = AddonsCoupon::findOne(['id'=>$coupon_user_relate_model['coupon_id']]);
- if($coupon_model['is_member']){
- $member_relate_list = AddonsCouponMemberRelate::lists(['where'=>[['mall_id'=>$params['mall_id']],['coupon_id'=>$coupon_model['id']]], 'select' => 'member_level']);
- $level_arr = array_column($member_relate_list,'member_level');
- $receiveUserInfo = User::findOne(['id' => $params['user_id']]);
- if(!in_array($receiveUserInfo['level'],$level_arr))throw new Exception('该优惠券指定会员等级');
- }
- if (1 == $coupon_model['is_receive_limit']) {
- $received_counts = AddonsCouponUserRelate::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' => [AddonsCouponEnum::GIVING_STATUS0,AddonsCouponEnum::GIVING_STATUS1]]])
- ->count();
- if(!empty($params['direct_gift'])){
- if ($coupon_model['receive_count'] > 0 && $received_counts >= $coupon_model['receive_count']) throw new Exception('对方已经领取过了');
- }else{
- if ($coupon_model['receive_count'] > 0 && $received_counts >= $coupon_model['receive_count']) throw new Exception('你已经领取过了');
- }
- }
- $now = time();
- if(!empty($coupon_model->store_id)){
- $coupon_user_model = new StoreCouponUserRelate();
- $coupon_user_model->from_type = 1;
- }else{
- $coupon_user_model = new self();
- $coupon_user_model->mch_id = $coupon_model->mch_id;
- }
- $coupon_user_model->mall_id = $params['mall_id'];
- $coupon_user_model->user_id = $params['user_id'];
- $coupon_user_model->coupon_id = $coupon_user_relate_model['coupon_id'];
- $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 = AddonsCouponEnum::getSendFromMap(AddonsCouponEnum::SEND_FROM6, $params['mall_id']).',赠送者ID:'.$share_log_model->giving_user_id;
- $coupon_user_model->receive_platform = $params['receive_platform'];
- $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;
- $coupon_user_model->store_id = !empty($coupon_model->store_id) ? $coupon_model->store_id : 0;
- $res = $coupon_user_model->save();
- if($res==false) throw new Exception($coupon_user_model->getErrorMessage());
- $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 = AddonsCouponShareLog::setData($share_data);
- if($res==false) throw new Exception($share_log_model->getErrorMessage());
- $coupon_user_relate_model->giving_status = AddonsCouponEnum::GIVING_STATUS2;
- $coupon_user_relate_model->coupon_status = AddonsCouponEnum::STATUS_FAILURE;
- $res = $coupon_user_relate_model->save();
- if($res==false) throw new Exception('更新赠送者优惠券状态失败');
- if (1 == $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 AddonsCouponRemind())->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;
- }
- }
- /**
- * 更新
- * @param $params
- * @return bool
- */
- public static function updateData($params)
- {
- try {
- $count = self::updateAll($params['fields'], ['coupon_id' => $params['coupon_id'], 'user_id' => $params['user_id']]);
- if (!$count) return false;
- return true;
- } catch (Exception $e) {
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- /**
- * 转送
- * @param $params
- * @return bool
- * @throws \yii\db\Exception
- */
- /*
- public static function transfer($params)
- {
- $t = \Yii::$app->db->beginTransaction();
- try {
- $model = self::findOne($params['user_coupon_id']);
- if (empty($model)) throw new Exception('查无数据');
- $model->status = StatusEnum::DELETE;
- $model->save();
- $data = [
- 'coupon_id' => $model->coupon_id,
- 'user_id' => $params['user_id'],
- 'is_use' => 0,
- 'from' => ReceiveTypeEnum::TRANSFER,
- 'extra' => '来源user_coupon_id是:' . $params['user_coupon_id'],
- 'end_time' => $params['end_time'],
- ];
- $model = new self();
- if (!$model->load($data, '') || !$model->save()) throw new Exception($model->getErrorMessage());
- $model->save();
- $t->commit();
- return true;
- } catch (Exception $e) {
- $t->rollBack();
- self::$static_error = $e->getMessage();
- return false;
- }
- }
- */
- /**
- * @desc:购买商品赠送优惠券
- * @Author: hua
- * @Date: 2021/12/3
- * @Time: 15:42
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $mall_id
- * @param $goods_ids
- * @param $user_id
- * @param string $order_id
- * @param int $order_status
- * @return false
- */
- public static function BuyGoodsGiveCoupon($mall_id, $goods_ids, $user_id,$order_id='', $order_status = OrderStatusEnum::ACCOMPLISH)
- {
- try {
- $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
- if (!$is_install) return false;
- $params = [
- 'where'=>[['mall_id' => $mall_id],['item_id' => $goods_ids],[ 'is_enable' => 1],['status' => StatusEnum::ENABLED], ['item_type' => 'goods']],
- 'with'=>['detail'=>function($query){
- $query->where(['status'=>StatusEnum::ENABLED]);
- }],
- ];
- $give_item_setting_list = CouponGiveItemSetting::lists($params);
- if (empty($give_item_setting_list)) return false;
- $give_coupon_arr = [];
- foreach ($give_item_setting_list as $give_item_setting) {
- // 如果当前订单状态为完成,但是仅限于支付完成赠送或者当前订单状态为支付,但是仅限于订单完成赠送,那么就不执行赠送
- if ($order_status == OrderStatusEnum::ACCOMPLISH && $give_item_setting['send_type'] == StatusEnum::ENABLED ||
- $order_status == OrderStatusEnum::PAY && $give_item_setting['send_type'] == StatusEnum::DISABLED) continue;
- foreach ($give_item_setting['detail'] as $item) {
- if (isset($give_coupon_arr[$item['coupon_id']])) {
- $give_coupon_arr[$item['coupon_id']] += $item['num'];
- } else {
- $give_coupon_arr[$item['coupon_id']] = $item['num'];
- }
- }
- }
- if (count($give_coupon_arr) > 0) {
- $res = self::giveCoupon($mall_id,$user_id,$give_coupon_arr,AddonsCouponEnum::SEND_FROM2,'platform');
- if($res==false) throw new \Exception('购买商品-订单完成order_id'.$order_id.'-赠送优惠券失败');
- }
- } catch (\Exception $e) {
- self::setStaticError($e->getMessage());
- return false;
- }
- }
- //订单满额赠送
- public static function FullAmountGiveCoupon($mall_id, $user_id, $config = '', $order_id = '' )
- {
- try {
- $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
- if (!$is_install) return false;
- if (empty($config)) return false;
- $config = json_decode($config, true);
- if (empty($config['multiple_selection'])) return false;
- $params = [
- 'where'=>[['mall_id' => $mall_id],['item_id' => $order_id],[ 'is_enable' => 0],['status' => StatusEnum::ENABLED], ['item_type' => 'order']],
- ];
- $give_item_setting_list = CouponGiveItemSetting::lists($params);
- if (!empty($give_item_setting_list)) return false;
- $give_coupon_arr = [];
- foreach ($config['multiple_selection'] as $key => $value) {
- $give_coupon_arr[$value['relevant_id']] = $value['num'];
- }
- if (!empty($give_coupon_arr)) {
- $res = self::giveCoupon($mall_id,$user_id,$give_coupon_arr,AddonsCouponEnum::SEND_FROM18,'platform');
- if($res===false) throw new \Exception('订单满额赠送order_id'.$order_id.'-赠送优惠券失败');
- }
- $result = Yii::$app->db->createCommand()->insert(CouponGiveItemSetting::tableName(),[
- 'mall_id' => $mall_id,
- 'item_id' => $order_id,
- 'is_enable' => 0,
- 'status' => StatusEnum::ENABLED,
- 'item_type' => 'order',
- 'send_type' => 0,
- 'created_at' => time(),
- 'updated_at' => time()])->execute();
- } catch (\Exception $e) {
- self::setStaticError($e->getMessage());
- print_r($e->getMessage());
- return false;
- }
- }
- /**
- * @desc:赠送优惠券
- * @Author: hua
- * @Date: 2021/12/6
- * @Time: 11:33
- * @Copyright: copyright (c) 2021 广东七件事集团
- * @param $mall_id
- * @param $user_id
- * @param $give_coupon_arr //$give_coupon_arr=['coupon_id'=>'num'];
- * @param $receive_type
- * @param $receive_platform
- * @return array|bool
- */
- public static function giveCouponOld($mall_id, $user_id,$give_coupon_arr,$receive_type =2,$receive_platform='platform')
- {
- $trans = Yii::$app->db->beginTransaction();
- $locks = [];
- try {
- $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
- if (!$is_install) throw new Exception('优惠券并未安装');
- $coupon_id_arr = array_keys($give_coupon_arr);
- $coupon_list = AddonsCoupon::findAll(['mall_id' => $mall_id, 'id' => $coupon_id_arr, 'status' => StatusEnum::ENABLED, 'coupon_status' => AddonsCouponEnum::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 , $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 AddonsCouponEnum::EXPIRE_TYPE2:
- $start_time = $time;
- $end_time = $coupon['end_at'];
- break;
- case AddonsCouponEnum::EXPIRE_TYPE1:
- $start_time = $time;
- $end_time = $coupon['expire_day'] * 86400 + $time;
- break;
- case AddonsCouponEnum::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'],
- ];
- }
- $field = ['mall_id','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'];
- $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, $user_id, $coupon_id, $item['coupon_status'], StatusEnum::ENABLED, $item['start_time'], $item['end_time'], 0, 0, 0, AddonsCouponEnum::getSendFromMap($receive_type, $mall_id), $receive_platform, 0, 0, $time, $time, ];
- }
- $coupon_model = AddonsCoupon::findOne(['id'=>$coupon_id]);
- $coupon_model->total_count -= $num;
- $res = $coupon_model->save();
- if($res==false) throw new \Exception('赠送优惠券失败');
- }
- if (!empty($insert)) {
- $res = Yii::$app->db->createCommand()->batchInsert(AddonsCouponUserRelate::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;
- }
- }
- public static function giveCoupon($mall_id, $user_id,$give_coupon_arr,$receive_type =2,$receive_platform='platform')
- {
- $trans = Yii::$app->db->beginTransaction();
- $locks = [];
- try {
- $is_install = MallAddons::isInstall($mall_id, AddonsEnum::ADDONS_NAME_COUPON);
- if (!$is_install) throw new Exception('优惠券并未安装');
- $coupon_id_arr = array_keys($give_coupon_arr);
- $coupon_list = AddonsCoupon::findAll(['mall_id' => $mall_id, 'id' => $coupon_id_arr, 'status' => StatusEnum::ENABLED, 'coupon_status' => AddonsCouponEnum::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 , $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 AddonsCouponEnum::EXPIRE_TYPE2:
- $start_time = $time;
- $end_time = $coupon['end_at'];
- break;
- case AddonsCouponEnum::EXPIRE_TYPE1:
- $start_time = $time;
- $end_time = $coupon['expire_day'] * 86400 + $time;
- break;
- case AddonsCouponEnum::EXPIRE_TYPE3:
- $start_time = $coupon['effect_days'] * 86400 + $time;
- $end_time = $coupon['expire_day'] * 86400 + $start_time;
- break;
- default:
- throw new Exception('有效期时间设置不对');
- }
- if(!empty($coupon['store_id'])){
- $give_destination = StoreCouponUserRelate::tableName();
- // $give_destination_model = StoreCouponUserRelate::find();
- }else{
- $give_destination = AddonsCouponUserRelate::tableName();
- // $give_destination_model = AddonsCouponUserRelate::find();
-
- // //获取用户已领取的数量
- // $user_have_num = $give_destination_model->where(['status' => StatusEnum::ENABLED, 'coupon_id' => $coupon['id'], 'mall_id' => $mall_id, 'user_id' => $user_id])->count();
- // //如果优惠券限制可领取数量,用户已领取的优惠券超过限制数量则跳过领取
- // if ($coupon['is_receive_limit'] == 1 && $user_have_num >= $coupon['receive_count']) continue;
- }
-
- $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'],
- 'store_id' => $coupon['store_id'],
- 'coupon_status' => $coupon['coupon_status'],
- 'give_destination' => $give_destination,
- ];
- }
- $field = ['mall_id','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'];
- $insert = [];
- $insert_store = [];
- foreach ($can_give_coupon_arr as $coupon_id => $item) {
- switch ($item['give_destination']){
- case AddonsCouponUserRelate::tableName():
- $num = $item['num'];
- if($item['total_count']<$item['num']) $num = $item['total_count'];
- for ($i = 0; $i < $num; $i++) {
- $insert[] = [ $mall_id, $user_id, $coupon_id, $item['coupon_status'], StatusEnum::ENABLED, $item['start_time'], $item['end_time'], 0, 0, 0, AddonsCouponEnum::getSendFromMap($receive_type, $mall_id), $receive_platform, 0, 0, $time, $time, ];
- }
- break;
- case StoreCouponUserRelate::tableName():
- $num = $item['num'];
- if($item['total_count']<$item['num']) $num = $item['total_count'];
- for ($i = 0; $i < $num; $i++) {
- $insert_store[] = [$mall_id, $item['store_id'],1,$user_id, $coupon_id, $item['coupon_status'], StatusEnum::ENABLED, $item['start_time'], $item['end_time'], 0, 0, 0, AddonsCouponEnum::getSendFromMap($receive_type, $mall_id), $receive_platform, 0, 0, $time, $time, ];
- }
- break;
- }
- $coupon_model = AddonsCoupon::findOne(['id'=>$coupon_id]);
- $coupon_model->total_count -= $num;
- $res = $coupon_model->save();
- if($res==false) throw new \Exception('赠送优惠券失败');
- }
- if (!empty($insert)) {
- $res = Yii::$app->db->createCommand()->batchInsert(AddonsCouponUserRelate::tableName(), $field, $insert)->execute();
- if ($res==false) {
- throw new \Exception('赠送优惠券失败');
- }
- }
- if (!empty($insert_store)) {
- $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(StoreCouponUserRelate::tableName(), $field, $insert_store)->execute();
- }
- $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 {
- $model = self::findOne(['mall_id' => $params['mall_id'], 'id' => $params['id'], 'status' => StatusEnum::ENABLED]);
- 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();
- self::setData($e->getMessage());
- return false;
- }
- }
- //直接赠送
- public static function giveCouponBy2($params){
- $t = Yii::$app->db->beginTransaction();
- try {
- $mall_id = $params['mall_id'];
- $coupon_id = $params['coupon_id'];
- $user_id = $params['user_id'];
- $user_coupon_id = $params['user_coupon_id'];
- $receive_user_id = $params['receive_user_id'];
- $receive_platform = $params['receive_platform'];
- $num = $params['num'];
- $config = \Yii::$app->services->setting->addons->get($mall_id, AddonsEnum::ADDONS_NAME_COUPON, 'basic');
- if(!empty($config['give_type'])&&$config['give_type']==2){
- // $coupon = AddonsCoupon::findOne(['mall_id' => $mall_id, 'id' => $coupon_id, 'coupon_status' => 2, 'status' => StatusEnum::ENABLED]);
- $coupon = AddonsCoupon::findOne(['mall_id' => $mall_id, 'id' => $coupon_id]);
- if (empty($coupon)) {
- throw new Exception('优惠券不存在或者已经失效');
- }
- if (1 != $coupon->is_giving) {
- throw new Exception('优惠券不可转赠');
- }
- $params = [
- 'mall_id' => $mall_id,
- 'coupon_id' => $coupon_id,
- 'user_coupon_id' => $user_coupon_id,
- 'giving_user_id' => $user_id,
- ];
- $res = AddonsCouponShareLog::setData($params);
- if($res==false) throw new Exception(AddonsCouponShareLog::getStaticError());
- $params = [
- 'mall_id'=>$mall_id,
- 'coupon_share_log_id'=>$res['id'],
- 'coupon_id' => $coupon_id,
- 'user_id'=>$receive_user_id,
- 'num'=>$num,
- 'receive_platform'=>$receive_platform,
- 'direct_gift'=>1,
- ];
- $res = AddonsCouponUserRelate::receiveByGive($params);
- if($res==false) throw new Exception(AddonsCouponUserRelate::getStaticError());
- }else{
- throw new Exception('不支持该赠送方式');
- }
- $t->commit();
- return $res;
- }catch (Exception $e){
- $t->rollBack();
- throw new Exception($e->getMessage());
- }
- }
- public static function fixMchId(){
- $list = AddonsCouponUserRelate::lists([
- 'where' => [
- ['>', 'mall_id', 0]
- ],
- 'select' => 'coupon_id',
- 'group' => 'coupon_id'
- ]);
- $coupon_ids = array_column($list, 'coupon_id');
- $coupon_list = AddonsCoupon::lists(['where' => [['id' => $coupon_ids], ['<>', 'mch_id', '']], 'select' => 'id,mch_id']);
- foreach ($coupon_list as $item) {
- $res = AddonsCouponUserRelate::updateAll(['mch_id' => $item['mch_id']], ['coupon_id' => $item['id']]);
- var_dump($res);
- }
- }
- }
|