| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409 |
- <?php
- namespace addons\SignIn\common\login;
- use addons\Coupon\common\enums\AddonsCouponEnum;
- use addons\Coupon\common\models\AddonsCouponUserRelate;
- use addons\Redpack\common\enums\RedpackEnum;
- use addons\Redpack\common\models\RedpackWallet;
- use addons\SignIn\common\logic\RepeatedRewardsLogic;
- use addons\SignIn\common\models\SignInUserPropertyAward;
- use addons\SignIn\common\models\UserSignInRecord;
- use addons\SignIn\common\models\UserSignInAward;
- use addons\SignIn\common\models\UserSignInAwardRecord;
- use addons\Coupon\common\models\AddonsCoupon;
- use common\enums\AddonsEnum;
- use common\enums\RabbitMqEnum;
- use common\enums\StatusEnum;
- use common\enums\UserWalletEnum;
- use common\models\mall\MallAddons;
- use services\common\UserWalletService;
- use Yii;
- use addons\Coupon\common\models\AddonsCouponMemberRelate;
- use common\models\user\User;
- class SignInReward
- {
- public static function sexecuteReward($user_id, $mall_id, $sign_id) {
- $data = ['user_id' => $user_id, 'mall_id' => $mall_id, 'sign_id' => $sign_id];
- Yii::$app->services->rabbitMq->push(RabbitMqEnum::EXCHANGE_TASK, RabbitMqEnum::TASK_QUEUE, $data, self::class, 'sendReward');
- }
- /**
- * 签到赠送优惠券积分
- */
- public function sendReward($data) {
- $user_id = $data['user_id'];
- $mall_id = $data['mall_id'];
- $sign_id = $data['sign_id'];
- $signRecord = UserSignInRecord::getOne([['user_id' => $user_id]], true, [], 'created_at desc');
- if (empty($signRecord)) return true;
- try {
- Yii::$app->db->close();
- $t = Yii::$app->db->beginTransaction();
- $signTime = $signRecord['created_at'];
- $time = strtotime(date("Y-m-d H:i:s",strtotime('1 days')));
- $date = date("Y-m-d",$time-24*60*60);
- $start_time = strtotime($date.' 00:00:00');
- $end_time = strtotime($date.' 23:59:59');
- $userAward = UserSignInAward::findOne(['mall_id' => $mall_id, 'user_id' => $user_id]);
- if (empty($userAward)) {
- $userAward = new UserSignInAward();
- $userAward->mall_id = $mall_id;
- $userAward->user_id = $user_id;
- $userAward->created_at = $time;
- }
- $signRecord = UserSignInRecord::getOne([
- ['user_id' => $user_id],
- ['>=','created_at',$start_time],
- ['<=','created_at',$end_time],
- ], true, [], 'created_at desc');
- if(empty($signRecord)){
- //非连续,把total_sign_in=1
- $userAward->total_sign_in = 1;
- }else{
- $userAward->total_sign_in = $userAward->total_sign_in ? $userAward->total_sign_in + 1 : 1;
- }
- $userAward->sign_at = $signTime;
- $userAward->updated_at = $time;
- $totalSignIn = $userAward->total_sign_in;//连续签到天数
- $reward = Yii::$app->services->setting->addons->get($mall_id, 'SignIn', 'reward');
- $reward_score = isset($reward['reward_score']) ? json_decode($reward['reward_score'], true) : [];
- $reward_coupon = isset($reward['reward_coupon']) ? json_decode($reward['reward_coupon'], true) : [];
- $today_coupon = isset($reward['today_coupon']) ? json_decode($reward['today_coupon'], true) : [];
- $today_score = isset($reward['today_score']) ? json_decode($reward['today_score'], true) : [];
- $is_coupon_sign_repeat = !empty($reward['is_coupon_sign_repeat'])?$reward['is_coupon_sign_repeat']:0;
- $is_score_sign_repeat = !empty($reward['is_score_sign_repeat'])?$reward['is_score_sign_repeat']:0;
- $couponIds = empty($reward_coupon) ? [] : array_column($reward_coupon, 'coupon_id');
- if (!empty($today_coupon['coupon_id'])) array_push($couponIds, $today_coupon['coupon_id']);
- // 优化1480,赠送优惠券时需要判断该用户有无权限
- $receiveUserInfo = User::findOne(['id' => $user_id]);
- $recordsList = AddonsCouponMemberRelate::find()->where(['coupon_id' => $couponIds])->andWhere(['member_level' => $receiveUserInfo['level']])->asArray()->all();
- $couponIds = [];
- foreach ($recordsList as $k => $v) {
- array_push($couponIds, $v['coupon_id']);
- }
- $couponIds && $couponList = AddonsCoupon::find()
- ->where(['id' => $couponIds, 'mall_id' => $mall_id])
- ->andWhere(['=', 'status', StatusEnum::ENABLED])
- ->andWhere(['=', 'coupon_status', AddonsCouponEnum::STATUS_RECEIVING])
- ->andWhere(['or', ['=', 'total_count', '-1'], ['>', 'total_count', 0]])
- ->andFilterWhere(['or', ['and', ['>', 'end_at', time()], ['=', 'expire_type', 2]],['=', 'expire_type', 1]])
- ->indexBy('id')
- ->asArray()->all();
- $scoreData = [];//签到积分
- $scoreNum = 0;
- $couponData = [];//签到优惠券
- $couponNum = 0;
- $subCoupon = []; //扣除优惠券数量
- $insertWallet = [];//赠送积分到用户钱包
- $insertCoupon = [];//赠送优惠券
- //赠送积分
- if (!empty($reward_score)) {
- foreach ($reward_score as $score_val) {
- if ($score_val['day'] == $totalSignIn) {
- $give_type = !empty($score_val['give_type'])?$score_val['give_type']:'score';
- $res = $this->giveReward($mall_id,$user_id,$give_type,$score_val['num'],$sign_id,$signTime,$time,2,$userAward->total_sign_in);
- if(!empty($res['insertWallet'])){
- $insertWallet[] = $res['insertWallet'];
- }
- if(!empty($res['scoreData'])){
- $scoreData[] = $res['scoreData'];
- }
- $userPropertyAward = SignInUserPropertyAward::findOne(['mall_id' => $mall_id,'give_type'=>$give_type, 'user_id' => $user_id,'status'=>[StatusEnum::ENABLED,StatusEnum::DISABLED]]);
- if (empty($userPropertyAward)) {
- $userPropertyAward = $this->getUserPropertyAward($mall_id,$user_id,$give_type);
- }
- $userPropertyAward->total_num += $score_val['num'];
- $userPropertyAward->save();
- $scoreNum += 1;
- }
- }
- // 判断是否开启重复积分赠送
- if (!empty($is_score_sign_repeat)) {
- $rewardScoreData = [
- 'mall_id' => $mall_id,
- 'user_id' => $user_id,
- 'sign_id' => $sign_id,
- 'total_sign_in' => $totalSignIn,
- 'reward_score' => $reward_score,
- 'sign_time' => $signTime,
- ];
- $res=RepeatedRewardsLogic::reward($rewardScoreData);
- if (!empty($res)) {
- if(!empty($res['insertWallet'])){
- $insertWallet[] = $res['insertWallet'];
- }
- if(!empty($res['scoreData'])){
- $scoreData[] = $res['scoreData'];
- }
- $scoreNum += 1;
- }
- }
- }
- //每日签到送积分
- if (!empty($today_score) && $today_score['num'] > 0) {
- $give_type = !empty($today_score['give_type'])?$today_score['give_type']:'score';
- $res = $this->giveReward($mall_id,$user_id,$give_type,$today_score['num'],$sign_id,$signTime,$time,1,0);
- if(!empty($res['insertWallet'])){
- $insertWallet[] = $res['insertWallet'];
- }
- if(!empty($res['scoreData'])){
- $scoreData[] = $res['scoreData'];
- }
- $scoreNum += 1;
- $userPropertyAward = SignInUserPropertyAward::findOne(['mall_id' => $mall_id,'give_type'=>$give_type, 'user_id' => $user_id,'status'=>[StatusEnum::ENABLED,StatusEnum::DISABLED]]);
- if (empty($userPropertyAward)) {
- $userPropertyAward = $this->getUserPropertyAward($mall_id,$user_id,$give_type);
- }
- $userPropertyAward->total_num += $today_score['num'];
- $userPropertyAward->save();
- }
- //赠送优惠券
- if (!empty($reward_coupon) || !empty($couponList)) {
- $describe = '连续签到'. $userAward->total_sign_in . '天赠送优惠券';
- foreach ($reward_coupon as $coupon_val) {
- if (!isset($couponList[$coupon_val['coupon_id']])) continue; // 排除过期,数量为0,禁用
- if ($coupon_val['num'] > $couponList[$coupon_val['coupon_id']]['total_count'] && $couponList[$coupon_val['coupon_id']]['total_count'] != -1) continue; // 单个配置数量不足不赠送 例如,配置赠送3个,剩余2个
- if ($coupon_val['day'] == $totalSignIn) {
- $couponNum += $coupon_val['num'];
- $couponData[] = [
- 'mall_id' => $mall_id,
- 'user_id' => $user_id,
- 'sign_id' => $sign_id,
- 'num' => $coupon_val['num'],
- 'coupon_id' => $coupon_val['coupon_id'],
- 'type' => 2,
- 'describe' => $describe . '[' . $couponList[$coupon_val['coupon_id']]['name'] . ']',
- 'sign_at' => $signTime,
- 'created_at' => $time,
- 'updated_at' => $time
- ];
- $insertCoupon[$coupon_val['coupon_id']] = $coupon_val['num'];
- if ($couponList[$coupon_val['coupon_id']]['total_count'] != -1) $subCoupon[$coupon_val['coupon_id']] = $coupon_val['num'];
- }
- }
- if (!empty($is_coupon_sign_repeat)) {
- $rewardCouponData = [
- 'mall_id' => $mall_id,
- 'user_id' => $user_id,
- 'sign_id' => $sign_id,
- 'total_sign_in' => $totalSignIn,
- 'reward_coupon' => $reward_coupon,
- 'coupon_list' => $couponList,
- 'sign_time' => $signTime,
- 'describe' => $describe,
- ];
- $res=RepeatedRewardsLogic::reward($rewardCouponData, 'coupon');
- if (!empty($res)) {
- if (!empty($res['couponNum'])) {
- $couponNum += $res['couponNum'];
- }
- if (!empty($res['couponData'])) {
- $couponData[] = $res['couponData'][0];
- }
- if (!empty($res['insertCoupon'])) {
- $insertCoupon = $res['insertCoupon'];
- }
- if (!empty($res['subCoupon'])) {
- $subCoupon = $res['subCoupon'];
- }
- }
- }
- }
- //每日签到送优惠券
- if (!empty($today_coupon) && $today_coupon['num'] > 0) {
- if (isset($couponList[$today_coupon['coupon_id']])) {
- if ($today_coupon['num'] < $couponList[$today_coupon['coupon_id']] ||
- $couponList[$today_coupon['coupon_id']]['total_count'] == -1) {
- $couponNum += 1;
- $couponData[] = [
- 'mall_id' => $mall_id,
- 'user_id' => $user_id,
- 'sign_id' => $sign_id,
- 'num' => $today_coupon['num'],
- 'coupon_id' => $today_coupon['coupon_id'],
- 'type' => 2,
- 'describe' => '每日签到赠送优惠券[' . $couponList[$today_coupon['coupon_id']]['name'] . ']',
- 'sign_at' => $signTime,
- 'created_at' => $time,
- 'updated_at' => $time
- ];
- if (isset($insertCoupon[$today_coupon['coupon_id']])) {
- $insertCoupon[$today_coupon['coupon_id']] += $today_coupon['num'];
- } else {
- $insertCoupon[$today_coupon['coupon_id']] = $today_coupon['num'];
- }
- }
- }
- }
- //赠送优惠券
- if (!empty($insertCoupon)) AddonsCouponUserRelate::giveCoupon($mall_id, $user_id, $insertCoupon, AddonsCouponEnum::SEND_FROM5);
- //操作用户钱包
- if (!empty($insertWallet)) {
- $res = UserWalletService::batchHandleByQueue($insertWallet);
- if ($res === false) {
- $t->rollBack();
- echo '签到赠送积分,操作用户钱包失败' . UserWalletService::getStaticError();
- return true;
- }
- }
- //签到奖励汇总
- $userAward->score_num = $userAward->score_num ? $userAward->score_num + $scoreNum : $scoreNum;
- $userAward->coupon_num = $userAward->coupon_num ? $userAward->coupon_num + $couponNum : $couponNum;
- if (!$userAward->save()) {
- $t->rollBack();
- echo '签到赠送积分优惠券,添加签到汇总数据失败' . $userAward->getErrorMessage();
- return true;
- }
- $installData = array_merge($scoreData, $couponData);
- //签到奖励记录
- if (!empty($installData)) {
- $field = ['mall_id', 'user_id', 'sign_id', 'num', 'coupon_id', 'type', 'describe', 'sign_at', 'created_at', 'updated_at'];
- $addSignInAward = Yii::$app->db->createCommand()->batchInsert(UserSignInAwardRecord::tableName(), $field, $installData)->execute();
- if (!$addSignInAward) {
- $t->rollBack();
- echo '签到赠送积分优惠券,添加签到记录失败' . UserSignInAwardRecord::$static_error;
- return true;
- }
- }
- $t->commit();
- return true;
- } catch (\Exception $e) {
- $t->rollBack();
- echo '签到赠送积分优惠券失败,' . $e->getMessage() . $e->getFile() .',行数:' . $e->getLine();
- }
- }
- /**
- * 清除连续签到
- */
- public function cleanTotalSignIn() {
- $day = date('Y-m-d', strtotime("-1 day"));
- $time = strtotime($day . ' 00:00:00');
- try {
- $model = UserSignInAward::find()->select('id')->where(['>', 'total_sign_in', 0])->andWhere(['<', 'sign_at', $time]);
- foreach ($model->asArray()->batch(300) as $userAward) {
- $ids = array_column($userAward, 'id');
- UserSignInAward::updateAll(['total_sign_in' => 0], ['id' => $ids]);
- }
- return true;
- } catch (\Exception $e) {
- return '清除连续签到错误,' . $e->getMessage() . '行数:' . $e->getLine();
- }
- }
- /**
- * 赠送奖励
- * @param $mall_id
- * @param $user_id
- * @param $give_type //赠送类型:积分、余额、红包
- * @param $num //数量
- * @param $sign_id //签到id
- * @param $signTime //签到时间
- * @param $time //时间
- * @param $type //类型 :1:每日签到;2:连续签到
- * @param $total_sign_in //连续签到天数
- * @return array
- * @throws \Exception
- */
- public function giveReward($mall_id,$user_id,$give_type,$num,$sign_id,$signTime,$time,$type,$total_sign_in){
- $insertWallet = [];
- $desc = '';
- if(in_array($give_type,['Redpack','RedpackFrozen'])){
- if(MallAddons::isInstall($mall_id,'Redpack')){
- // 插入红包金额表
- $config = Yii::$app->services->setting->addons->get($mall_id, AddonsEnum::ADDONS_NAME_REDPACK, 'basic');
- $title=!empty($config['redpack_name'])?$config['redpack_name']:'红包';
- $is_frozen = false;
- if($give_type=='RedpackFrozen'){
- $is_frozen = true;
- $title = '冻结'.$title;
- }else{
- $title = '激活'.$title;
- }
- switch ($type){
- case 1:
- $desc = "每日签到赠送{$title}" . $num;
- $from_type = RedpackEnum::FROM_SIGN_IN_EVERY_DAY;
- break;
- case 2:
- $from_type = RedpackEnum::FROM_SIGN_IN_CONTINUOUS;
- $desc ='连续签到'.$total_sign_in. "天赠送{$title} {$num}";
- break;
- }
- $wallet = RedpackWallet::setData([
- 'mall_id' => $mall_id,
- 'user_id' => $user_id,
- 'is_frozen' => $is_frozen,
- 'money' => $num,
- 'source_table' => UserSignInRecord::tableName(),
- 'source_table_id' => $sign_id,
- 'from_type' => $from_type,
- 'desc' => $desc,
- ]);
- if ($wallet == false) throw new \Exception(RedpackWallet::getStaticError());
- }
- }else{
- $title = Yii::$app->services->setting->mall->get($mall_id, 'score.score_name') ?? '积分';
- $wallet_type = UserWalletService::WALLET_TYPE_SCORE;
- switch ($give_type){
- case 'balance':
- $title= Yii::$app->services->setting->mall->get($mall_id, 'balance.balance_name') ?? '余额';
- $wallet_type = UserWalletService::WALLET_TYPE_BALANCE;
- break;
- }
- switch ($type){
- case 1:
- $desc = "每日签到赠送{$title}" . $num;
- break;
- case 2:
- $desc ='连续签到'.$total_sign_in. "天赠送{$title}" . $num;
- break;
- }
- $insertWallet = $this->getInsertWallet($mall_id,$user_id, $num,$wallet_type,$sign_id,$desc);
- }
- $scoreData = [
- 'mall_id' => $mall_id,
- 'user_id' => $user_id,
- 'sign_id' => $sign_id,
- 'num' => $num,
- 'coupon_id' => 0,
- 'type' => 1,
- 'describe' => $desc,
- 'sign_at' => $signTime,
- 'created_at' => $time,
- 'updated_at' => $time
- ];
- return ['insertWallet'=>$insertWallet,'scoreData'=>$scoreData];
- }
- public function getInsertWallet($mall_id,$user_id,$num,$wallet_type,$sign_id,$desc){
- return ['mall_id' => $mall_id, 'user_id' => $user_id,
- 'is_frozen' => false,
- 'wallet_type' =>$wallet_type,
- 'money' => $num,
- 'desc' => $desc,
- 'source_table' => 'sign_record',
- 'source_table_id' => $sign_id,
- 'from_type' => UserWalletEnum::REWARD,
- 'capital_type' => UserWalletEnum::SIGNIN,
- ];
- }
- public function getUserPropertyAward($mall_id,$user_id,$give_type){
- $userPropertyAward = new SignInUserPropertyAward();
- $userPropertyAward->mall_id = $mall_id;
- $userPropertyAward->user_id = $user_id;
- $userPropertyAward->give_type = $give_type;
- $userPropertyAward->total_num = 0;
- return $userPropertyAward;
- }
- }
|