123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684 |
- <?php
- namespace app\main\service;
- use app\admin\library\ShortUrl;
- use app\common\library\Redis;
- use app\main\constants\ActivityConstants;
- use app\main\constants\BookConstants;
- use app\main\constants\CacheConstants;
- use app\main\constants\ConsumeConstants;
- use app\main\constants\UrlConstants;
- use think\Cookie;
- use think\Exception;
- use think\Model;
- use think\Config;
- /**
- * 订阅活动
- * Class SubscripService
- * @package app\main\service
- */
- class SubscripService extends BaseService
- {
- private static $self=null;
- public static function instance()
- {
- if (self::$self == null) {
- self::$self = new self();
- }
- return self::$self;
- }
- //根据日期获取活动
- /**
- * @param $date
- * @return array
- */
- public function getActivity($date)
- {
- $redisKey = ActivityConstants::SUBSCRIP_ACTIVITY.$date;
- $active = Redis::instance()->hGetAll($redisKey);
- if (empty($active)){
- $active = model('SubscripActivity')
- ->where('begin_date',$date)
- ->where('state',1)
- ->find();
- if (empty($active)){
- $active['id'] = 0;
- }
- $active = is_object($active)?$active->toArray():$active;
- Redis::instance()->hMSet($redisKey,$active);
- Redis::instance()->expire($redisKey,3600*24);
- }
- if ( isset($active['id']) && !$active['id'] ){
- $active = [];
- }
- $active = self::formatActivity($active);
- return (array)$active;
- }
- /**
- * @param $Id
- * @return array
- */
- public function getActivityById($id)
- {
- $redisKey = ActivityConstants::SUBSCRIP_ACTIVITY.$id;
- $active = Redis::instance()->hGetAll($redisKey);
- if (empty($active)){
- $active = model('SubscripActivity')
- ->where('id',$id)
- ->find();
- if (empty($active)){
- $active['id'] = 0;
- }
- $active = is_object($active) ? $active->toArray() : $active;
- Redis::instance()->hmSet($redisKey,$active);
- Redis::instance()->expire($redisKey,3600*24);
- }
- if ( isset($active['id']) && !$active['id'] ){
- $active = [];
- }
- $active = self::formatActivity($active);
- return (array)$active;
- }
- /**
- * 处理活动状态 0 未开始 1 进行中 2 结束
- * @param $act
- * @return array
- */
- public static function formatActivity($act)
- {
- if (empty($act)){
- return [];
- }
- $act['status'] = $act['end_date'] >= date('Ymd',time()) ? 1 : 2;
- $act['md'] = substr($act['begin_date'],4);
- $act['md_bt'] = substr($act['begin_date'],4,2).'月'.substr($act['begin_date'],6).'日';
- $act['md_et'] = substr($act['end_date'],4,2).'月'.substr($act['end_date'],6).'日';
- return $act;
- }
- /**
- * 取出用户在进行中的活动
- * @param $userId
- * @return array
- */
- public function getActivityUser($userInfo)
- {
- $isWrite = model('ChannelSpecialManage')->isWhite('subscribe', $userInfo->channel_id);
- if (!$isWrite){
- return [];
- }
- $userId = $userInfo->id;
- $redisKey = ActivityConstants::SUBSCRIP_ACT_USER.$userId;
- $actUser = Redis::instance()->hGetAll($redisKey);
- LogService::info('订阅活动'.json_encode($actUser));
- if (empty($actUser)){
- $actUser = model('SubscripUser')
- ->where('user_id',$userId)
- ->where('act_end_date','>=',date('Ymd',time()))
- ->find();
- if (empty($actUser)){
- $actUser['id'] = 0;
- }
- $actUser = is_object($actUser) ? $actUser->toArray() : $actUser;
- Redis::instance()->hmSet($redisKey,$actUser);
- Redis::instance()->expire($redisKey,3600*24);
- }
- if ( !isset($actUser['id']) || $actUser['id'] == 0 ){
- $actUser = [];
- }
- return $actUser;
- }
- /**
- * 获取用户参加的所有活动
- * @param $userId
- * @return array
- */
- public function getUserActList($userId)
- {
- $redisKey = ActivityConstants::SUBSCRIP_ACT_USER_LIST.$userId;
- $ids = Redis::instance()->sMembers($redisKey);
- $actList = [];
- if (empty($ids)){
- $actL = model('SubscripUser')
- ->where('user_id',$userId)
- ->where('state','>',0)
- ->select();
- if ($actL){
- foreach($actL as &$act){
- $act = is_object($act) ? $act->toArray() : $act;
- $ids[] = $act['act_id'];
- Redis::instance()->sadd($redisKey,$act['act_id']);
- }
- }else{
- $ids[] = -1;
- Redis::instance()->sadd($redisKey,-1);
- }
- }
- $ids = array_unique($ids);
- if (!empty($ids)){
- foreach($ids as $id){
- $actemp = $this->getActivityById($id);
- if (!empty($actemp)){
- $actList[] = $actemp;
- }
- }
- }
- return (array)$actList;
- }
- public function checkUserState($userId,$actId)
- {
- $actL = model('SubscripUser')
- ->where('user_id',$userId)
- ->where('act_id',$actId)
- ->find();
- $state = !empty($actL) && $actL['state'] ? $actL['state'] : 3;
- return $state;
- }
- /**
- * 获取用户的打卡记录
- * @param $userInfo
- * @param $actId
- */
- public function getUserActLog($userInfo,$actId,$activity)
- {
- $redisKey = ActivityConstants::SUBSCRIP_USER_LOG.$userInfo->id.':'.$actId;
- $logList = Redis::instance()->sMembers($redisKey);
- LogService::info('SQL'.json_encode($logList));
- if (!$logList){
- $logList = model('SubscripLog')
- ->where('user_id',$userInfo->id)
- ->where('act_id',$actId)
- ->where('state','>',0)
- ->order('date','asc')
- ->select();
- if ($logList){
- $logList = array_column($logList,null,'date');
- foreach ($logList as $key =>$value){
- Redis::instance()->sadd($redisKey,json_encode($value));
- }
- }else{
- Redis::instance()->sadd($redisKey,json_encode(['date'=>0]));
- }
- Redis::instance()->expire($redisKey,86400);
- }else{
- $tempList = [];
- foreach ($logList as $key =>$value){
- $value = json_decode($value,true);
- $tempList[$value['date']] = $value;
- }
- $logList = $tempList;
- }
- $dateList = $this->getDateList($activity['begin_date'],$activity['days']);
- $log = [];
- //本次活动是否补卡
- $activity['re_sign'] = 0;
- foreach($dateList as $k =>$v){
- $temp = [
- 'id'=>$actId,
- 'user_id'=>$userInfo->id,
- 'date'=>isset($logList[$v]) ? $logList[$v]['date'] : $v,
- 'state'=>isset($logList[$v]) ? $logList[$v]['state'] : 0,
- 'sort'=>$k+1,
- 'days'=>$activity['days'],
- ];
- if ($temp['state'] == 2){
- $activity['re_sign'] = 1;
- }
- //如果是当天的就标记为-1 未完成状态(前端显示)
- $temp['state'] = ($temp['state'] == 0 && $temp['date'] == date('Ymd')) ? -1 : $temp['state'];
- $temp['d_text'] = substr($temp['date'],4,2).'月'.substr($temp['date'],6).'日';
- $log[] = $temp;
- }
- $activity['sort_day'] = count($dateList);
- $result['activity'] = $activity;
- $result['log'] = $log;
- $param = [
- 'sub_code'=>$userInfo->id.'_'.$actId,
- 'book_id'=>$activity['book_id'],
- 'sid'=>(int)$activity['chapter_id'],
- ];
- //获取分享内容
- $result['con'] = $this->getShareCon($userInfo->channel_id,$param,$activity);
- return $result;
- }
- /**
- * 生成日期列表
- * @param $beginDate
- * @param $days
- * @return array
- */
- public function getDateList($beginDate,$days)
- {
- $dateList = [];
- $beginTime = strtotime($beginDate);
- $today = date('Ymd',time());
- for ($i = 1;$i<=$days;$i++){
- $date = date('Ymd',$beginTime+3600*24*$i);
- if ($date > $today){
- break;
- }
- $dateList[] = $date;
- }
- return $dateList;
- }
- /**
- * 生成分析内容
- * @param $channelId
- * @param $params
- * @return string
- */
- public function getShareCon($channelId,$params)
- {
- $url = getCurrentDomain($channelId,'/index/book/chapter',$params);
- $shareUrl = '';
- $shortUrl = new ShortUrl();
- $shareUrl = $shortUrl->tencent($channelId, $url);
- $shareUrl = $shareUrl ? $shareUrl : $url;
- $con = "[微信红包]恭喜发财,大吉大利!
- 【 亲爱的,麻烦帮我一下吧,我正在参加阅读打卡返现活动,拜托帮帮我 】
- {$shareUrl}(链接地址)
- 帮我點上面链接,一起参加活动
- 从此告别书荒,热门小说应有尽有!~
- (悄悄告诉你,他们家书里有福利哟~你懂得)
- 爱你哟~!";
- return $con;
- }
- /**
- * 报名
- * @param $userInfo
- * @param $actId
- * @param $subCode
- * @return bool
- */
- public function insertActUser($userInfo,$actId,$orderInfo)
- {
- $actInfo = $this->getActivityById($actId);
- if (empty($actInfo)){
- LogService::info('订阅活动不存在'.$actId);
- return '';
- }
- //获取充值记录
- $recharge = FinancialService::instance()->getRechargeModel()->setConnect($orderInfo['user_id'])
- ->where('user_id', $orderInfo['user_id'])
- ->where('orders_id', $orderInfo['id'])
- ->find();
- //消费掉这条记录
- if (!empty($recharge)){
- $kandian = $recharge['remain_kandian'];
- $freeKandian = $recharge['remain_free_kandian'];
- FinancialService::instance()->getRechargeModel()->setConnect($orderInfo['user_id'])->update(['remain_kandian'=>0,'remain_free_kandian'=>0], ['id' => $recharge['id']]);
- $cache = CacheConstants::getFreeKandianUserRechargeListCacheKey($orderInfo['user_id']);
- $fcache = CacheConstants::getKandianUserRechargeListCacheKey($orderInfo['user_id']);
- Redis::instance()->del($cache);
- Redis::instance()->del($fcache);
- $consume = [
- 'user_id' => $orderInfo['user_id'],
- 'book_id' => 0,
- 'book_name' => '',
- 'type' => 0,
- 'chapter_id' => '',
- 'chapter_name' => '',
- 'kandian' => intval($kandian),
- 'free_kandian'=>(int)$freeKandian,
- 'dd_kandian' => $recharge['dd'] == 1 ? intval($kandian) : 0,
- 'createtime' => time(),
- 'updatetime' => time(),
- 'extend1' => '',
- 'extend2' => '',
- ];
- $info = [
- 'id' => $recharge['id'],
- 'kandian' => $kandian,
- 'free_kandian' => $freeKandian,
- 'dd_kandian' => $recharge['dd'] == 1 ? $recharge['kandian'] : 0,
- 'dd_free_kandian' => 0,
- 'remark'=>'读书订阅活动直接消费'
- ];
- $consume['consume_info'] = json_encode($info,JSON_UNESCAPED_UNICODE);
- FinancialService::instance()->getConsumeModel()->setConnect($orderInfo['user_id'])->insertGetId($consume);
- }
- //活动报名
- $insert = [
- 'user_id'=>$userInfo['id'],
- 'open_id'=>$userInfo['openid'],
- 'channel_id'=>$userInfo['channel_id'],
- 'act_id'=>$actId,
- 'act_date'=>$actInfo['begin_date'],
- 'act_end_date'=>$actInfo['end_date'],
- 'state'=>1,
- 'sub_code'=>$userInfo['id'].'_'.$actId,
- 'created_at'=>time(),
- 'updated_at' =>time()
- ];
- try {
- model('SubscripUser')->insert($insert);
- $this->delCache($userInfo['id']);
- LogService::info('订阅活动报名成功'.json_encode($userInfo));
- }catch (Exception $e){
- LogService::info('订阅活动重复报名'.$e->getMessage());
- }
- return true;
- }
- /**
- * 补卡
- * @param $toUserId
- * @param $actId
- * @return bool
- */
- public function insertOldLog($userInfo)
- {
- $channelIds = model('ChannelSpecialManage')->isWhite('subscribe', $userInfo['channel_id']);
- if (empty($channelIds)){
- return '';
- }
- //获取要补卡的用户
- $userId = $userInfo['id'];
- $fatherUser = model('SubscripUserRelation')
- ->where('user_id',$userId)
- ->where('state',1)
- ->where('lasttime','>',time())
- ->select();
- if (empty($fatherUser)){
- LogService::info('订阅活动-没有要补卡用户:'.$userId);
- return true;
- }
- foreach ($fatherUser as $k =>$v){
- $isFind = model('SubscripLog')->where('user_id',$v['father_user_id'])->where('act_id',$v['act_id'])->where('state',2)->find();
- if (!$isFind){
- $fatherUser = $v;
- break;
- }
- }
- if ($isFind){
- return false;
- }
- //查看所有打卡记录
- $logList = model('SubscripLog')
- ->field('date,id')
- ->where('user_id',$fatherUser['father_user_id'])
- ->where('act_id',$fatherUser['act_id'])
- ->select();
- $activity = $this->getActivityById($fatherUser['act_id']);
- $logList = array_column($logList,null,'date');
- $dateList = $this->getDateList($activity['begin_date'],$activity['days']);
- $count = count($dateList);
- //得到未补卡的时间
- $date = 0;
- for ($i=0;$i<$count;$i++){
- if (!isset($logList[$dateList[$i]])){
- $date = $dateList[$i];
- break;
- }
- }
- //写入打卡记录
- $insert = [
- 'user_id'=>$fatherUser['father_user_id'],
- 'act_id'=>$fatherUser['act_id'],
- 'date'=>$date,
- 'state'=>2,
- 'to_user_id'=>$userId,
- 'created_at'=>time(),
- 'updated_at'=>time(),
- ];
- //如果是活动的最后一天,标记用户的完成状态
- if ($activity['end_date'] == date('Ymd',time())){
- $count = model('SubscripLog')->where('user_id',$fatherUser['father_user_id'])->where('act_id',$fatherUser['act_id'])->group('date')->count();
- if($activity['days'] - $count <= 1){
- $this->updateUserState($fatherUser['father_user_id'],$fatherUser['act_id'],2);
- }
- }
- model('SubscripLog')->insert($insert);
- //更新所有关联用户为补卡状态
- model('SubscripUserRelation')->update(['state'=>2],['father_user_id'=>$fatherUser['father_user_id'],'act_id'=>$fatherUser['act_id']]);
- //删除打卡日志redis
- $this->delUserLogRedis($userId,$activity['id']);
- LogService::info('订阅活动补卡信息:'.json_encode($insert));
- return true;
- }
- /**
- * 分享的用户 写入关系表
- * @param $subCode
- * @param $userId
- * @return bool
- */
- public function insertUserRelation($subCode,$userId)
- {
- $subCode = explode('_',$subCode);
- if (!isset($subCode[0]) || !isset($subCode[1])){
- LogService::info('订阅活动补卡code错误:'.$subCode);
- return true;
- }
- $activity = $this->getActivityById($subCode[1]);
- if (empty($activity)){
- LogService::info('订阅活动无效:'.$subCode);
- return true;
- }
- //写入打卡记录
- $insert = [
- 'user_id'=>$userId,
- 'father_user_id'=>$subCode[0],
- 'act_id'=>$subCode[1],
- 'state'=>1,
- 'lasttime'=>strtotime($activity['end_date'])+3600*24,
- 'createtime'=>time()
- ];
- try {
- model('SubscripUserRelation')->save($insert);
- }catch (Exception $exception){
- LogService::info('订阅活动-插入关联表重复');
- }
- }
- /**
- * 打卡接口
- * @param $actUser
- * @return int|string
- */
- public function insertLog($actUser)
- {
- //查看用户今天有没打卡
- $today = date('Ymd',time());
- $redisKey = ActivityConstants::SUBSCRIP_USER_SIGN.$today.':'.$actUser['user_id'];
- if(Redis::instance()->exists($redisKey) || $today == $actUser['act_date']){//今天打过卡
- LogService::info('活动第一天,或者今日已经打卡:'.json_encode($actUser));
- return false;
- }
- $activity = $this->getActivityById($actUser['act_id']);
- //活动结束
- if (empty($activity) || $activity['end_date']<$today){
- $this->updateUserState($actUser['user_id'],$actUser['act_id'],3);
- LogService::info('本次活动完成:'.json_encode($activity));
- return false;
- }
- //如果是最后一天
- $state = 0;
- if ($activity['end_date'] == $today){
- $count = model('SubscripLog')->where('user_id',$actUser['user_id'])->where('act_id',$actUser['act_id'])->group('date')->count();
- if($activity['days'] - $count <= 1){
- $state = 2;
- }
- }
- $insert = [
- 'user_id'=>$actUser['user_id'],
- 'act_id'=>$actUser['act_id'],
- 'date'=>$today,
- 'state'=>1,
- 'created_at'=>time(),
- 'updated_at'=>time()
- ];
- $res = model('SubscripLog')->insert($insert);
- if ($res){
- Redis::instance()->set($redisKey,1,3600*24);
- //更新用户的最后打卡时间
- $this->updateUserState($actUser['user_id'],$actUser['act_id'],$state,date('Ymd',time()));
- //更新用户打卡日志缓存
- $this->delUserLogRedis($actUser['user_id'],$actUser['act_id']);
- }
- LogService::info('打卡完成:'.json_encode($actUser));
- return (int)$res;
- }
- /**
- * @param $userId
- * @param $actId
- * @param $state
- * @return false|int
- */
- public function updateUserState($userId,$actId,$state=0,$last_date='')
- {
- $actUser = model('SubscripUser')->where('user_id',$userId)
- ->where('act_id',$actId)
- ->find();
- if ($state){
- $actUser->state = $state;
- }
- if ($last_date){
- $actUser->last_date = $last_date;
- }
- $re = $actUser->save();
- $redisKey = ActivityConstants::SUBSCRIP_ACT_USER.$actUser['user_id'];
- Redis::instance()->del($redisKey);
- return $re;
- }
- /**
- * 清除用户打卡日志的缓存
- * @param $userId
- * @param $actId
- * @return bool
- */
- public function delUserLogRedis($userId,$actId)
- {
- $redisKey = ActivityConstants::SUBSCRIP_USER_LOG.$userId.':'.$actId;
- Redis::instance()->del($redisKey);
- return true;
- }
- /**
- * 获得弹窗信息
- * @param $userInfo
- * @param $actionUrl //当前用户访问的方法
- * @return array
- */
- public function getActPop($userInfo,$actionUrl)
- {
- $date = date('Ymd',time());
- $channelIds = model('ChannelSpecialManage')->isWhite('subscribe', $userInfo->channel_id);
- //活动是不是开启
- if (empty($channelIds)){
- return [];
- }
- //今天没活动
- $activity = $this->getActivity($date);
- if (empty($activity)){
- return [];
- }
- //查看用户是否有权限
- $redisKey = ActivityConstants::SUBSCRIP_USER_AUTH.$userInfo->id;
- $actAuth= Redis::instance()->SISMEMBER($redisKey,$activity['id']);
- if (empty($actAuth)){
- return [];
- }
- //当前位置能不能弹窗
- $location = [
- '/index/user/recent' => 2,
- '/index/user/index' => 1,
- '/index/index/index' => 3
- ];
- $actionIndex = $location[$actionUrl] ?? 0;
- // LogService::info($actionUrl.'--'.$activity['pop_space'].'订阅活动弹窗');
- // LogService::info(strstr((string)$activity['pop_space'],(string)$actionIndex).'订阅活动弹窗');
- if( strstr((string)$activity['pop_space'],(string)$actionIndex) === false ){
- return [];
- }
- $res['act_pop_img'] = $activity['pop_img'];
- $res['act_banner_img'] = $activity['banner_img'];
- $res['type'] = $actionIndex;
- //判断今天的弹窗次数
- $sub_pop_num = Cookie::get('sub_act_val');
- if ($sub_pop_num && $sub_pop_num >= 4) {
- $res['act_pop_img'] = '';
- }
- LogService::info(json_encode($res).'订阅活动弹窗');
- return $res;
- }
- /**
- * 检查是否需要banner
- */
- public function checkSubBanner($userInfo)
- {
- $date = date('Ymd',time());
- $channelIds = model('ChannelSpecialManage')->isWhite('subscribe', $userInfo->channel_id);
- //活动是不是开启
- if (empty($channelIds)){
- return '';
- }
- //今天没活动
- $activity = $this->getActivity($date);
- if (empty($activity)){
- return '';
- }
- //查看用户是否有权限
- $redisKey = ActivityConstants::SUBSCRIP_USER_AUTH.$userInfo->id;
- $actAuth= Redis::instance()->SISMEMBER($redisKey,$activity['id']);
- if (empty($actAuth)){
- return '';
- }
- $bannerImg = $activity['banner_img'];
- return $bannerImg;
- }
- /**
- * @param $userInfo
- * @return int
- * 检查用户是否报名过
- */
- public function checkUserSign($userInfo)
- {
- $channelIds = model('ChannelSpecialManage')->isWhite('subscribe', $userInfo->channel_id);
- LogService::info('订阅活动check'.$channelIds);
- //活动是不是开启
- if (empty($channelIds)){
- return 0;
- }
- $res = $this->getUserActList($userInfo->id);
- // LogService::info('订阅活动'.$res);
- return (int)$res;
- }
- public function delCache($userId)
- {
- $redisKey = ActivityConstants::SUBSCRIP_ACT_USER_LIST.$userId;
- Redis::instance()->del($redisKey);
- $redisKey = ActivityConstants::SUBSCRIP_ACT_USER.$userId;
- Redis::instance()->del($redisKey);
- return;
- }
- }
|