Browse Source

fix:邀请记录

super-yimizi 18 hours ago
parent
commit
9e05685260

+ 42 - 5
application/api/controller/Share.php

@@ -29,8 +29,8 @@ class Share extends Base
         }
 
         // 使用服务类添加分享记录
-        $shareInfo = ShareService::addShareLog($user, $params);
-
+        $shareInfo = ShareService::addShareLog($user->id, $params);
+      
         if ($shareInfo) {
             $this->success('添加分享记录成功', $shareInfo);
         } else {
@@ -44,10 +44,47 @@ class Share extends Base
     public function index()
     {
         $user = auth_user();
-        $logs = ShareModel::with(['user' => function ($query) {
-            return $query->field(['id', 'nickname', 'avatar']);
-        }])->where('share_id', $user->id)->paginate($this->request->param('list_rows', 8));
+        $pageSize = $this->request->param('page_size', 10);
+        $type = $this->request->param('type', 'received'); // received=我收到的分享, shared=我分享的
+        
+        // 使用服务类获取分享记录
+        $logs = ShareService::getUserShareLogs($user->id, $pageSize, $type);
 
         $this->success('获取成功', $logs);
     }
+
+    /**
+     * 获取分享统计数据
+     */
+    public function stats()
+    {
+        $user = auth_user();
+        
+        // 使用服务类获取分享统计
+        $stats = ShareService::getUserShareStats($user->id);
+        
+        $this->success('获取成功', $stats);
+    }
+
+    /**
+     * 查看分享记录详情
+     */
+    public function detail()
+    {
+        $user = auth_user();
+        $shareLogId = $this->request->param('id/d');
+        
+        if (!$shareLogId) {
+            $this->error('参数错误');
+        }
+        
+        // 使用服务类获取分享详情
+        $shareLog = ShareService::getShareLogDetail($shareLogId, $user->id);
+        
+        if (!$shareLog) {
+            $this->error('记录不存在或无权限访问');
+        }
+        
+        $this->success('获取成功', $shareLog);
+    }
 }

+ 21 - 2
application/api/controller/User.php

@@ -35,10 +35,11 @@ class User extends Base
     public function index()
     {
         $logincode = $this->request->param('logincode');
+        $user = $this->auth->getUser();
         $info = $this->auth->getUserInfo();
         $info['avatar'] = !empty($info['avatar']) ? cdnurl($info['avatar'], true) :'';
-        $info['gender_text'] = UserEnum::getGenderText($this->auth->getUser()->gender ?? 0);
-        $info['age'] = $this->auth->getUser()->age ?? 0;
+        $info['gender_text'] = UserEnum::getGenderText($user->gender ?? 0);
+        $info['age'] = $user->age ?? 0;
 
         // 判断是否需要编辑个人信息 个人信息是否 都填了  昵称、性别、年龄
         $isNeedEditProfile = 0;
@@ -47,6 +48,23 @@ class User extends Base
         }
         $info['is_need_editprofile'] = $isNeedEditProfile;
 
+        // 获取上级用户信息
+        $parentUserInfo = null;
+        if (!empty($user->parent_user_id)) {
+            $parentUser = \app\common\model\User::where('id', $user->parent_user_id)
+                ->field('id,username,nickname,avatar,mobile')
+                ->find();
+            if ($parentUser) {
+                $parentUserInfo = [
+                    'id' => $parentUser->id,
+                    'username' => $parentUser->username,
+                    'nickname' => $parentUser->nickname,
+                    'avatar' => !empty($parentUser->avatar) ? cdnurl($parentUser->avatar, true) : '',
+                    'mobile' => $parentUser->mobile ? substr_replace($parentUser->mobile, '****', 3, 4) : ''
+                ];
+            }
+        }
+
         $openid = '';
         //如果有传登录code,则获取openid
         if ($logincode) {
@@ -56,6 +74,7 @@ class User extends Base
 
         $this->success('', [
             'userInfo' => $info,
+            'parentUserInfo' => $parentUserInfo,
             'openid'            => $openid,
         ]);
     }

+ 3 - 3
application/api/controller/commission/Agent.php

@@ -321,9 +321,9 @@ class Agent extends Commission
                 $fromPlatformId  // 来源平台ID
             );
             
-            // 固定跳转到分销海报页面,携带smp参数
-            $page = 'pages/me/edit'; // 分销海报页面路径
-            $scene = 'spm=' . $spmParams;
+        // 固定跳转到分销海报页面,携带smp参数和邀请码
+        $page = 'pages/me/edit'; // 分销海报页面路径
+        $scene = 'spm=' . $spmParams . '&invite_code=' . $agent->invite_code;
             
             // 生成小程序码
             $content = $mp->app_code->getUnlimit($scene, [

+ 1 - 2
application/api/validate/Share.php

@@ -55,8 +55,7 @@ class Share extends Validate
      */
     public function checkSharePlatform($value, $rule, $data)
     {
-        $validChannels = ChannelEnum::getChannelMap();
-        if (!in_array($value, $validChannels)) {
+        if (!ChannelEnum::isValidChannel($value)) {
             return '分享渠道参数错误';
         }
         return true;

+ 3 - 5
application/common/Service/Commission/Agent.php

@@ -238,11 +238,9 @@ class Agent
     {
         $bindCheck = false;   // 默认不绑定
 
-        // 该用户已经有上级
-        if ($this->user->parent_user_id !== NULL) {
+        if ($this->user->parent_user_id !== 0) {
             return false;
         }
-
         // 不满足绑定下级事件
         if ($this->config->getInviteLockEvent() !== $event) {
             return false;
@@ -299,9 +297,9 @@ class Agent
         if ($user_id === 0) {
             $user_id = $this->user->id;
         }
-        \think\Queue::push('\addons\shopro\job\Commission@agentUpgrade', [
+        \think\Queue::push('\app\job\Commission@agentUpgrade', [
             'user_id' => $user_id
-        ], 'shopro');
+        ], 'shop');
     }
 
     /**

+ 95 - 18
application/common/Service/Share/ShareService.php

@@ -13,32 +13,24 @@ class ShareService
 {
     /**
      * 添加分享记录
-     * @param object $user 当前用户对象
+     * @param int $userId 当前用户ID
      * @param array $params 分享参数
      * @return mixed
      */
-    public static function addShareLog($user, $params)
+    public static function addShareLog($userId = 0, $params)
     {
         // 错误的分享参数
         if (empty($params['spm'])) {
             return false;
         }
-
-        // 解析spm参数: shareId.page.query.platform.from
-        $spmParts = explode('.', $params['spm']);
-        if (count($spmParts) < 5) {
-            return false;
-        }
-
-        list($shareId, $pageType, $query, $platform, $from) = $spmParts;
-
+        $shareId = $params['shareId'];
         // 分享用户为空
         if ($shareId <= 0) {
             return false;
         }
 
         // 不能分享给本人
-        if ($shareId == $user->id) {
+        if ($shareId == $userId) {
             return false;
         }
 
@@ -55,7 +47,7 @@ class ShareService
 
         // 5分钟内相同的分享信息不保存,防止冗余数据
         $lastShareLog = ShareModel::where([
-            'user_id' => $user->id
+            'user_id' => $userId
         ])->where('createtime', '>', time() - 300)->order('id desc')->find();
 
         if ($lastShareLog && $lastShareLog->spm === $params['spm']) {
@@ -63,7 +55,7 @@ class ShareService
         }
 
         // 根据页面类型构造页面路径和描述
-        $pageInfo = self::getPageInfo($pageType, $query);
+        $pageInfo = self::getPageInfo($params['page'], $params['query'], $shareUser);
         
         $memoText = '通过' . ShareEnum::getFromText($params['from']) . '访问了' . $pageInfo['description'];
 
@@ -73,17 +65,18 @@ class ShareService
         ];
 
         $shareInfo = ShareModel::create([
-            'user_id' => $user->id,
+            'user_id' => $userId,
             'share_id' => $shareId,
             'spm' => $params['spm'],
             'page' => $pageInfo['path'],
-            'query' => $query,
+            'query' => $params['query'],
             'platform' => $params['platform'],
             'from' => $params['from'],
             'ext' => $ext
         ]);
 
         $data = ['shareInfo' => $shareInfo];
+       
         \think\Hook::listen('user_share_after', $data);
 
         return $shareInfo;
@@ -93,9 +86,10 @@ class ShareService
      * 根据页面类型获取页面信息
      * @param int $pageType 页面类型
      * @param string $query 查询参数
+     * @param object $shareUser 分享者用户对象(可选)
      * @return array
      */
-    private static function getPageInfo($pageType, $query)
+    private static function getPageInfo($pageType, $query, $shareUser = null)
     {
         $pageInfo = [
             'path' => '',
@@ -134,7 +128,11 @@ class ShareService
                 
             case PageTypeEnum::AGENT_POSTER:
                 $pageInfo['path'] = '/pages/agent/poster';
-                $pageInfo['description'] = '分销海报页';
+                if ($shareUser) {
+                    $pageInfo['description'] = $shareUser->nickname . '的分销海报页';
+                } else {
+                    $pageInfo['description'] = '分销海报页';
+                }
                 break;
                 
             default:
@@ -191,4 +189,83 @@ class ShareService
             'from' => intval($from)
         ];
     }
+
+    /**
+     * 获取用户的分享记录列表
+     * @param int $userId 用户ID
+     * @param int $pageSize 每页数量
+     * @param string $type 记录类型:shared(我分享的) | received(我收到的分享)
+     * @return mixed
+     */
+    public static function getUserShareLogs($userId, $pageSize = 8, $type = 'received')
+    {
+        $query = ShareModel::with(['user' => function ($query) {
+            return $query->field(['id', 'nickname', 'avatar']);
+        }]);
+
+        // 根据类型设置查询条件
+        if ($type === 'shared') {
+            // 查看我分享的记录(我作为分享者)
+            $query->where('share_id', $userId);
+        } else {
+            // 查看我收到的分享记录(我作为被分享者)
+            $query->where('user_id', $userId);
+        }
+
+        $logs = $query->order('createtime desc')
+                     ->paginate($pageSize);
+
+        return $logs;
+    }
+
+    /**
+     * 获取用户分享统计数据
+     * @param int $userId 用户ID
+     * @return array
+     */
+    public static function getUserShareStats($userId)
+    {
+        return [
+            'shared_count' => ShareModel::where('share_id', $userId)->count(), // 我分享的次数
+            'received_count' => ShareModel::where('user_id', $userId)->count(), // 收到的分享次数
+            'today_shared' => ShareModel::where('share_id', $userId)
+                                       ->whereTime('createtime', 'today')
+                                       ->count(), // 今日分享次数
+            'today_received' => ShareModel::where('user_id', $userId)
+                                         ->whereTime('createtime', 'today')
+                                         ->count(), // 今日收到分享次数
+        ];
+    }
+
+    /**
+     * 获取分享记录详情
+     * @param int $shareLogId 分享记录ID
+     * @param int $userId 当前用户ID(用于权限验证)
+     * @return mixed
+     */
+    public static function getShareLogDetail($shareLogId, $userId = 0)
+    {
+        $query = ShareModel::with(['user']);
+        
+        // 如果指定了用户ID,则验证权限(只能查看自己相关的记录)
+        if ($userId > 0) {
+            $query->where(function($query) use ($userId) {
+                $query->whereOr('user_id', $userId)
+                      ->whereOr('share_id', $userId);
+            });
+        }
+
+        $shareLog = $query->where('id', $shareLogId)->find();
+
+        if ($shareLog) {
+            // 解析SPM参数
+            $spmInfo = self::parseSpm($shareLog->spm);
+            if ($spmInfo) {
+                $shareLog->spm_info = $spmInfo;
+                $shareLog->page_type_text = PageTypeEnum::getPageTypeText($spmInfo['pageType']);
+            }
+        }
+
+        return $shareLog;
+    }
 }

+ 4 - 3
application/extra/queue.php

@@ -1,11 +1,12 @@
 <?php
+use think\Env;
 return [
     'connector'  => 'Redis',          // Redis 驱动
     'expire'     => 0,             // 任务的过期时间,默认为60秒; 若要禁用,则设置为 null
     'default'    => 'default',    // 默认的队列名称
-    'host'       => '127.0.0.1',       // redis 主机ip
-    'port'       => 6379,        // redis 端口
-    'password'   => '',             // redis 密码
+    'host'       => Env::get('redis.REDIS_HOST','127.0.0.1'),       // redis 主机ip
+    'port'       => Env::get('redis.REDIS_PORT','6379'),        // redis 端口
+    'password'   => Env::get('redis.REDIS_PASSWORD',''),             // redis 密码
     'select'     => 0,          // 使用哪一个 db,默认为 db0
     'timeout'    => 0,          // redis连接的超时时间
     'persistent' => false,

+ 25 - 0
application/job/BaseJob.php

@@ -0,0 +1,25 @@
+<?php
+
+namespace app\job;
+
+use think\Log;
+
+/**
+ * BaseJob 基类
+ */
+class BaseJob
+{
+
+
+    public function failed($data)
+    {
+        // 失败队列,这里不用添加了, 后续程序会自动添加,这里可以发送邮件或者通知
+
+        // 记录日志
+        // \think\Db::name('shopro_failed_job')->insert([
+        //     'data' => json_encode($data),
+        //     'createtime' => time(),
+        //     'updatetime' => time()
+        // ]);
+    }
+}

+ 38 - 0
application/job/Commission.php

@@ -0,0 +1,38 @@
+<?php
+namespace app\job;
+
+use think\queue\Job;
+use think\Db;
+use think\exception\HttpResponseException;
+use app\common\Service\Commission\Agent as AgentService;
+
+/**
+ * 分销任务
+ */
+class Commission extends BaseJob
+{
+
+    /**
+     * 分销商升级
+     */
+    public function agentUpgrade(Job $job, $payload)
+    {
+        try {
+            $userId = $payload['user_id'];
+            $agent = new AgentService($userId);
+
+            if ($agent->user) {
+                Db::transaction(function () use ($agent) {
+                    $agent->runAgentUpgradePlan();
+                });
+            }
+            $job->delete();
+        } catch (HttpResponseException $e) {
+            $data = $e->getResponse()->getData();
+            $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
+            format_log_error($e, 'AgentUpgrade.HttpResponseException', $message);
+        } catch (\Exception $e) {
+            format_log_error($e, 'AgentUpgrade');
+        }
+    }
+}

+ 0 - 2
application/listeners/Commission.php

@@ -33,7 +33,6 @@ class Commission
     public function userShareAfter($payload)
     {
         $shareInfo = $payload['shareInfo'];
-
         if ($shareInfo) {
 
             $user_id = intval($shareInfo->user_id); // 受邀用户
@@ -41,7 +40,6 @@ class Commission
             $share_id = intval($shareInfo->share_id); // 邀请人
 
             $agent = new AgentService($user_id);
-
             $bindCheck = $agent->bindUserRelation('share', $share_id);
 
             // 统计单链业绩