PC-7\Administrator 8 mesi fa
parent
commit
c16a3d4a3c

+ 421 - 70
app/admin/controller/userCenter/User.php

@@ -6,7 +6,7 @@ use think\facade\Db;
 
 class User extends Backend
 {
-    protected array $noNeedLogin = ['*'];
+//    protected array $noNeedLogin = ['*'];
     /**
      * 用户列表
      * @return void
@@ -14,61 +14,160 @@ class User extends Backend
      * @throws \think\db\exception\DbException
      * @throws \think\db\exception\ModelNotFoundException
      */
-    public function index():void
+    public function index(): void
     {
         $where = [];
 
-        // 姓名搜索
-        if (!empty($this->request->get('name'))) {
-            $name = $this->request->get('name');
-            $where[] = ['wac.name', 'like', '%' . $name . '%'];
+        // 用户名搜索
+        if (!empty($this->request->get('username'))) {
+            $username = $this->request->get('username');
+            $where[] = ['bu.username', 'like', '%' . $username . '%'];
+        }
+
+        // 昵称搜索
+        if (!empty($this->request->get('nickname'))) {
+            $nickname = $this->request->get('nickname');
+            $where[] = ['bu.nickname', 'like', '%' . $nickname . '%'];
         }
 
         // 邮箱搜索
         if (!empty($this->request->get('email'))) {
             $email = $this->request->get('email');
-            $where[] = ['wac.email', 'like', '%' . $email . '%'];
+            $where[] = ['bu.email', 'like', '%' . $email . '%'];
         }
 
-        // 企业搜索
-        if (!empty($this->request->get('company'))) {
-            $company = $this->request->get('company');
-            $where[] = ['wac.company', 'like', '%' . $company . '%'];
+        // 手机号搜索
+        if (!empty($this->request->get('mobile'))) {
+            $mobile = $this->request->get('mobile');
+            $where[] = ['bu.mobile', 'like', '%' . $mobile . '%'];
         }
 
         // 状态筛选
-        if (!empty($this->request->get('status'))) {
+        if ($this->request->has('status') && $this->request->get('status') !== '') {
             $status = $this->request->get('status');
-            $where['wac.status'] = $status;
+            $where[] = ['bu.status', '=', $status];
+        }
+
+        // 企业搜索(通过企业成员表关联)
+        if (!empty($this->request->get('company'))) {
+            $company = $this->request->get('company');
+            $companyIds = Db::name('ba_company')
+                ->where('name', 'like', '%' . $company . '%')
+                ->column('id');
+
+            if (!empty($companyIds)) {
+                $userIds = Db::name('ba_company_member')
+                    ->where('company_id', 'in', $companyIds)
+                    ->column('user_id');
+
+                if (!empty($userIds)) {
+                    $where[] = ['bu.id', 'in', $userIds];
+                } else {
+                    // 如果没有匹配的用户,返回空结果
+                    $where[] = ['bu.id', '=', 0];
+                }
+            } else {
+                // 如果没有匹配的企业,返回空结果
+                $where[] = ['bu.id', '=', 0];
+            }
         }
 
         // 排序
         $order = [];
         if (!empty($this->request->get('order'))) {
-            $order_a = $this->request->get('order');
-            $order_a = explode(',', $order_a);
-            $order[$order_a[0]] = $order_a[1];
+            $orderParam = $this->request->get('order');
+            $orderArray = explode(',', $orderParam);
+            if (count($orderArray) === 2) {
+                $order[$orderArray[0]] = $orderArray[1];
+            }
         } else {
-            $order['wac.id'] = 'desc';
+            $order['bu.id'] = 'desc';
         }
 
         // 分页
         $page = $this->request->get('page', 1);
         $limit = $this->request->get('limit', 20);
 
-        $userList = Db::name('user_on')
-            ->alias('wac')
-            ->leftJoin('company u', 'wac.company_id = u.id')
+        // 查询用户列表
+        $query = Db::table('ba_user')
+            ->alias('bu')
+            ->field([
+                'bu.id',
+                'bu.username',
+                'bu.nickname',
+                'bu.email',
+                'bu.mobile',
+                'bu.avatar',
+                'bu.gender',
+                'bu.status',
+                'bu.create_time',
+                'bu.last_login_time',
+                'bu.last_login_ip',
+                'bu.join_ip',
+                'bu.motto',
+                'bu.invitation_code',
+                'GROUP_CONCAT(DISTINCT bc.name SEPARATOR ", ") as company_names',
+                'GROUP_CONCAT(DISTINCT inviter.username SEPARATOR ", ") as inviter_names'
+            ])
+            ->leftJoin('ba_company_member bcm', 'bu.id = bcm.user_id')
+            ->leftJoin('ba_company bc', 'bcm.company_id = bc.id AND bc.status = 1')
+            ->leftJoin('ba_user_invitation bui', 'bu.id = bui.invitee_id')
+            ->leftJoin('ba_user inviter', 'bui.inviter_id = inviter.id')
             ->where($where)
-            ->field('wac.*, u.name as company_name')
-            ->order($order)
-            ->paginate([
-                'list_rows' => $limit,
-                'page' => $page
-            ]);
+            ->group('bu.id')
+            ->order($order);
+
+        $userList = $query->paginate([
+            'list_rows' => $limit,
+            'page' => $page
+        ]);
+
+        // 处理时间戳字段
+        $items = $userList->items();
+        foreach ($items as &$item) {
+            // 转换时间戳为日期时间格式
+            if (!empty($item['create_time'])) {
+                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
+            }
+
+            if (!empty($item['last_login_time'])) {
+                $item['last_login_time'] = date('Y-m-d H:i:s', $item['last_login_time']);
+            }
+
+            if (!empty($item['join_time'])) {
+                $item['join_time'] = date('Y-m-d H:i:s', $item['join_time']);
+            }
+
+            // 处理性别显示
+            $genderMap = [
+                0 => '未知',
+                1 => '男',
+                2 => '女'
+            ];
+            $item['gender_text'] = $genderMap[$item['gender']] ?? '未知';
+
+            // 处理状态显示
+            if ($item['status'] === 'enable') {
+                $item['status_text'] = '启用';
+            } elseif ($item['status'] === 'disable') {
+                $item['status_text'] = '禁用';
+            } else {
+                $item['status_text'] = $item['status'];
+            }
+
+            // 如果企业名为空,设置为空字符串
+            if (empty($item['company_names'])) {
+                $item['company_names'] = '';
+            }
+
+            // 如果邀请人为空,设置为空字符串
+            if (empty($item['inviter_names'])) {
+                $item['inviter_names'] = '';
+            }
+        }
 
         $this->success('查询成功', [
-            'list' => $userList->items(),
+            'list' => $items,
             'total' => $userList->total()
         ]);
     }
@@ -82,15 +181,16 @@ class User extends Backend
     public function edit():void
     {
         $id = $this->request->post('id');
-        $name = $this->request->post('name');
+        $username = $this->request->post('name');
         $email = $this->request->post('email');
         $password = $this->request->post('password');
         $company = $this->request->post('company');
         $company_id = $this->request->post('company_id');
         $status = $this->request->post('status', 1);
 
-        if (empty($name) || empty($email)) {
-            $this->error(__('姓名和邮箱不能为空'));
+
+        if (empty($username) || empty($email)) {
+            $this->error(__('用户名和邮箱不能为空'));
         }
 
         // 验证邮箱格式
@@ -98,8 +198,20 @@ class User extends Backend
             $this->error(__('邮箱格式不正确'));
         }
 
+        // 检查用户名是否已存在(编辑时排除自己)
+        $checkUsername = Db::name('user')
+            ->where('username', $username);
+
+        if (!empty($id)) {
+            $checkUsername->where('id', '<>', $id);
+        }
+
+        if ($checkUsername->find()) {
+            $this->error(__('用户名已存在'));
+        }
+
         // 检查邮箱是否已存在(编辑时排除自己)
-        $checkEmail = Db::name('user_on')
+        $checkEmail = Db::name('user')
             ->where('email', $email);
 
         if (!empty($id)) {
@@ -111,12 +223,11 @@ class User extends Backend
         }
 
         $data = [
-            'name' => $name,
+            'username' => $username,
+            'nickname' => $username,
             'email' => $email,
-            'company' => $company?: null,
-            'company_id' => $company_id?: null,
             'status' => $status,
-            'update_time' => date('Y-m-d H:i:s')
+            'update_time' => time()
         ];
 
         // 如果有密码,进行加密
@@ -128,19 +239,73 @@ class User extends Backend
         try {
             if (!empty($id)) {
                 // 编辑
-                $result = Db::name('user_on')
+                $result = Db::name('user')
                     ->where('id', $id)
                     ->update($data);
                 $message = '编辑成功';
             } else {
                 // 新增
-                $data['create_time'] = date('Y-m-d H:i:s');
-                $result = Db::name('user_on')
+                $data['join_time'] = time();
+                $data['create_time'] = time();
+
+                // 生成邀请码(可选)
+                if (empty($data['invitation_code'])) {
+                    $data['invitation_code'] = $this->generateInvitationCode();
+                }
+
+                $result = Db::name('user')
                     ->insert($data);
-                $id = Db::name('user_on')->getLastInsID();
+                $id = Db::name('user')->getLastInsID();
                 $message = '新增成功';
             }
 
+            // 处理企业成员关系
+            if ($company_id > 0) {
+                // 检查企业是否存在
+                $company = Db::name('company')
+                    ->where('id', $company_id)
+                    ->where('status', 1)
+                    ->find();
+
+                if ($company) {
+                    // 检查是否已经是该企业成员
+                    $member = Db::name('company_member')
+                        ->where('user_id', $id)
+                        ->find();
+
+                    if ($member) {
+                        // 更新企业成员关系
+                        Db::name('company_member')
+                            ->where('user_id', $id)
+                            ->update([
+                                'company_id' => $company_id,
+                                'email' => $email,
+                                'name' =>$username,
+                                'update_time' => date('Y-m-d H:i:s')
+                            ]);
+                    } else {
+                        // 新增企业成员关系
+                        Db::name('company_member')
+                            ->insert([
+                                'company_id' => $company_id,
+                                'user_id' => $id,
+                                'email' => $email,
+                                'name' =>$username,
+                                'role' => 2, // 普通成员
+                                'status' => 1,
+                                'join_time' => date('Y-m-d H:i:s'),
+                                'create_time' => date('Y-m-d H:i:s'),
+                                'update_time' => date('Y-m-d H:i:s')
+                            ]);
+                    }
+                }
+            } else {
+                // 如果企业ID为空,删除企业成员关系
+                Db::name('company_member')
+                    ->where('user_id', $id)
+                    ->delete();
+            }
+
             Db::commit();
 
         } catch (\Exception $e) {
@@ -155,6 +320,31 @@ class User extends Backend
         }
     }
 
+
+    /**
+     * 生成邀请码
+     * @return string
+     */
+    private function generateInvitationCode(): string
+    {
+        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
+        $code = '';
+        for ($i = 0; $i < 6; $i++) {
+            $code .= $characters[rand(0, strlen($characters) - 1)];
+        }
+
+        // 检查是否已存在
+        $exists = Db::name('user')
+            ->where('invitation_code', $code)
+            ->find();
+
+        if ($exists) {
+            return $this->generateInvitationCode();
+        }
+
+        return $code;
+    }
+
     /**
      * 用户详情
      * @return void
@@ -162,7 +352,7 @@ class User extends Backend
      * @throws \think\db\exception\DbException
      * @throws \think\db\exception\ModelNotFoundException
      */
-    public function detail():void
+    public function detail(): void
     {
         $id = $this->request->get('id');
 
@@ -171,7 +361,7 @@ class User extends Backend
         }
 
         // 获取用户基础信息
-        $userInfo = Db::name('user_on')
+        $userInfo = Db::name('user')
             ->where('id', $id)
             ->find();
 
@@ -179,6 +369,31 @@ class User extends Backend
             $this->error(__('用户不存在'));
         }
 
+        // 转换时间戳字段
+        if (!empty($userInfo['create_time'])) {
+            $userInfo['create_time_str'] = date('Y-m-d H:i:s', $userInfo['create_time']);
+        }
+        if (!empty($userInfo['last_login_time'])) {
+            $userInfo['last_login_time_str'] = date('Y-m-d H:i:s', $userInfo['last_login_time']);
+        }
+        if (!empty($userInfo['join_time'])) {
+            $userInfo['join_time_str'] = date('Y-m-d H:i:s', $userInfo['join_time']);
+        }
+        if (!empty($userInfo['update_time'])) {
+            $userInfo['update_time_str'] = date('Y-m-d H:i:s', $userInfo['update_time']);
+        }
+
+        // 获取用户所在企业信息
+        $companyInfo = Db::name('company_member')
+            ->alias('bcm')
+            ->leftJoin('ba_company bc', 'bcm.company_id = bc.id')
+            ->where('bcm.user_id', $id)
+            ->field('bc.id, bc.name')
+            ->find();
+
+        $userInfo['company_id'] = $companyInfo['id'] ?? 0;
+        $userInfo['company_name'] = $companyInfo['name'] ?? '';
+
         // 获取用户佣金信息
         $commissionInfo = Db::name('user_commission')
             ->where('user_id', $id)
@@ -187,40 +402,105 @@ class User extends Backend
         if (!$commissionInfo) {
             // 如果没有佣金记录,创建默认记录
             $commissionInfo = [
-                'total_commission' => 0,
-                'current_commission' => 0,
-                'promotion_link' => 'xxxx.com?from=' . $id
+                'total_commission' => '0.00',
+                'current_commission' => '0.00',
+                'frozen_commission' => '0.00',
+                'withdrawn_commission' => '0.00',
+                'promotion_link' =>  $this->generatePromotionLink($id),
+                'invitation_count' => 0
             ];
         }
 
-        // 获取用户购买的产品列表
-        $productList = Db::name('user_product')
+        // 获取用户购买的产品列表(包括套餐信息)
+        $productList = Db::name('user_product_usage')
             ->alias('up')
-            ->leftJoin('product p', 'up.product_id = p.id')
+            ->leftJoin('ba_product p', 'up.product_id = p.id')
+            ->leftJoin('ba_package_price pp', 'up.package_price_id = pp.id')
+            ->leftJoin('ba_package pk', 'pp.package_id = pk.id')
             ->where('up.user_id', $id)
-            ->field('up.*, p.name as product_name, p.type as product_type')
+            ->field('up.*, p.name as product_name, pp.spec_name as package_name, pp.card_type, pk.name as package_full_name')
             ->order('up.create_time', 'desc')
             ->select()
             ->toArray();
 
-        // 计算产品状态
+        // 处理产品状态和显示信息
         foreach ($productList as &$product) {
-            if (!empty($product['expire_time'])) {
-                $product['status'] = strtotime($product['expire_time']) < time() ? '已过期' : '正常';
+            // 确定产品名称
+            if (!empty($product['package_full_name'])) {
+                $product['display_name'] = $product['package_full_name'] . ' (' . $product['package_name'] . ')';
+            } else {
+                $product['display_name'] = $product['product_name'] ?? '未知产品';
+            }
+
+            // 处理卡类型显示
+            $cardTypeMap = [
+                1 => '次卡',
+                2 => '积分卡',
+                3 => '日卡',
+                4 => '周卡',
+                5 => '季卡',
+                6 => '月卡',
+                7 => '年卡'
+            ];
+            $product['card_type_text'] = $cardTypeMap[$product['card_type']] ?? '未知';
+
+            // 处理购买时间
+            if (!empty($product['create_time'])) {
+                $product['buy_time'] = date('Y-m-d H:i:s', strtotime($product['create_time']));
+            } else {
+                $product['buy_time'] = '';
+            }
+
+            // 处理到期时间
+            if (!empty($product['end_time'])) {
+                $product['expire_time'] = date('Y-m-d', strtotime($product['end_time']));
+            } else {
+                $product['expire_time'] = '';
+            }
+
+            // 判断状态
+            $currentTime = time();
+            $endTime = !empty($product['end_time']) ? strtotime($product['end_time']) : 0;
+
+            if ($product['status'] == 2) {
+                $product['status_text'] = '已过期';
+            } elseif ($product['status'] == 3) {
+                $product['status_text'] = '已用完';
+            } elseif ($endTime > 0 && $endTime < $currentTime) {
+                $product['status_text'] = '已过期';
+            } elseif ($product['remaining_times'] == 0 && $product['card_type'] == 1) {
+                $product['status_text'] = '已用完';
+            } elseif ($product['remaining_points'] == 0 && $product['card_type'] == 2) {
+                $product['status_text'] = '已用完';
             } else {
-                $product['status'] = '正常';
+                $product['status_text'] = '正常';
             }
         }
 
-        // 获取下级员工(关联其他用户)
-        $subordinateList = Db::name('user_relation')
-            ->alias('ur')
-            ->leftJoin('user_on u', 'ur.subordinate_id = u.id')
-            ->where('ur.user_id', $id)
-            ->field('u.name, ur.commission_amount, ur.status, ur.bind_time, ur.id as relation_id')
+        // 获取下级人员(通过邀请关系)
+        $subordinateList = Db::name('user_invitation')
+            ->alias('bui')
+            ->leftJoin('ba_user u', 'bui.invitee_id = u.id')
+            ->leftJoin('ba_user_commission uc', 'u.id = uc.user_id')
+            ->where('bui.inviter_id', $id)
+            ->field('u.id, u.username, u.nickname, u.email, uc.current_commission, bui.create_time')
+            ->order('bui.create_time', 'desc')
             ->select()
             ->toArray();
 
+        // 处理下级人员数据
+        foreach ($subordinateList as &$subordinate) {
+            if (!empty($subordinate['create_time'])) {
+                $subordinate['bind_time'] = date('Y-m-d H:i:s', strtotime($subordinate['create_time']));
+            } else {
+                $subordinate['bind_time'] = '';
+            }
+
+            $subordinate['name'] = $subordinate['nickname'] ?: $subordinate['username'];
+            $subordinate['commission_amount'] = $subordinate['current_commission'] ?? '0.00';
+            $subordinate['status_text'] = '正常';
+        }
+
         $result = [
             'user_info' => $userInfo,
             'commission_info' => $commissionInfo,
@@ -235,7 +515,7 @@ class User extends Backend
      * 删除用户
      * @return void
      */
-    public function delete():void
+    public function delete(): void
     {
         $id = $this->request->post('id');
 
@@ -243,9 +523,18 @@ class User extends Backend
             $this->error(__('参数错误'));
         }
 
-        // 检查是否有下级员工
-        $hasSubordinate = Db::name('user_relation')
-            ->where('user_id', $id)
+        // 检查是否存在
+        $user = Db::name('user')
+            ->where('id', $id)
+            ->find();
+
+        if (!$user) {
+            $this->error(__('用户不存在'));
+        }
+
+        // 检查是否有下级员工(通过邀请关系)
+        $hasSubordinate = Db::name('user_invitation')
+            ->where('inviter_id', $id)
             ->count();
 
         if ($hasSubordinate > 0) {
@@ -255,7 +544,7 @@ class User extends Backend
         Db::startTrans();
         try {
             // 删除用户
-            $result = Db::name('user_on')
+            $result = Db::name('user')
                 ->where('id', $id)
                 ->delete();
 
@@ -264,14 +553,47 @@ class User extends Backend
                 ->where('user_id', $id)
                 ->delete();
 
+            // 删除用户产品使用记录
+            Db::name('user_product_usage')
+                ->where('user_id', $id)
+                ->delete();
+
+            // 删除企业成员关系
+            Db::name('company_member')
+                ->where('user_id', $id)
+                ->delete();
+
+            // 删除邀请关系(如果该用户是别人的下级)
+            Db::name('user_invitation')
+                ->where('invitee_id', $id)
+                ->delete();
+
+            // 删除邀请码
+            Db::name('invitation_code')
+                ->where('user_id', $id)
+                ->delete();
+
             // 删除用户产品记录
             Db::name('user_product')
                 ->where('user_id', $id)
                 ->delete();
 
-            // 删除上级关系(如果该用户是别人的下级)
+            // 删除用户关系表记录
             Db::name('user_relation')
-                ->where('subordinate_id', $id)
+                ->where('user_id', $id)
+                ->whereOr('subordinate_id', $id)
+                ->delete();
+
+            // 删除佣金流水记录
+            Db::name('commission_flow')
+                ->where('user_id', $id)
+                ->whereOr('from_user_id', $id)
+                ->delete();
+
+            // 删除分销记录
+            Db::name('distribution_record')
+                ->where('buyer_id', $id)
+                ->whereOr('distributor_id', $id)
                 ->delete();
 
             Db::commit();
@@ -280,6 +602,7 @@ class User extends Backend
             Db::rollback();
             $this->error('删除失败: ' . $e->getMessage());
         }
+
         if ($result) {
             $this->success('删除成功');
         } else {
@@ -291,18 +614,20 @@ class User extends Backend
      * 解除下级关系
      * @return void
      */
-    public function removeSubordinate():void
+    public function removeSubordinate(): void
     {
-        $relationId = $this->request->post('relation_id');
+        $inviteeId = $this->request->post('invitee_id');
+        $inviterId = $this->request->post('inviter_id');
 
-        if (empty($relationId)) {
+        if (empty($inviteeId) || empty($inviterId)) {
             $this->error(__('参数错误'));
         }
 
         Db::startTrans();
         try {
-            $result = Db::name('user_relation')
-                ->where('id', $relationId)
+            $result = Db::name('ba_user_invitation')
+                ->where('inviter_id', $inviterId)
+                ->where('invitee_id', $inviteeId)
                 ->delete();
 
             Db::commit();
@@ -333,4 +658,30 @@ class User extends Backend
 
         $this->success('获取成功', $options);
     }
+
+
+    /**
+     * 生成推广链接
+     */
+    private function generatePromotionLink(int $userId): string
+    {
+        // 获取用户的邀请码
+        $user = Db::table('ba_user')
+            ->where('id', $userId)
+            ->field('invitation_code')
+            ->find();
+
+        $invitationCode = $user['invitation_code'] ?? '';
+
+        if (empty($invitationCode)) {
+            // 如果用户还没有邀请码,先生成一个
+            $invitationCode = $this->generateInvitationCode();
+            Db::table('ba_user')
+                ->where('id', $userId)
+                ->update(['invitation_code' => $invitationCode]);
+        }
+
+        $domain = request()->domain();
+        return $domain . '/#/user/register?invite=' . $invitationCode;
+    }
 }

+ 14 - 4
app/api/controller/User.php

@@ -15,7 +15,8 @@ use app\api\validate\User as UserValidate;
 
 class User extends Frontend
 {
-    protected array $noNeedLogin = ['*'];
+    protected array $noNeedLogin = ['checkIn','logout','subordinateList'];
+    protected array $noNeedPermission = ['dashboard'];
 
     protected $invitationService;
     protected $commissionService;
@@ -145,7 +146,7 @@ class User extends Frontend
     public function dashboard(): void
     {
         // 确保用户已登录
-        if (!$this->auth->isLogin()) {
+        if (!$this->auth->id) {
             $this->error('请先登录');
         }
 
@@ -206,8 +207,8 @@ class User extends Frontend
                 'promotion_info' => [
                     'invitation_code' => $invitationStats['invitation_code'],
                     'promotion_link' => $commissionDetail['commission']['promotion_link'],
-                    'invitation_count' => $invitationStats['invitation_count'],
-                    'total_invitation' => $invitationStats['commission']['total_invitation'] ?? 0,
+                    'today_invitation' => $invitationStats['today_invitation'] ?? 0, // 新增今日邀请人数
+                    'total_invitation' => $invitationStats['total_invitation'] ?? 0, // 修改字段名
                 ],
 
                 // 佣金信息
@@ -240,6 +241,10 @@ class User extends Frontend
      */
     public function invitationStats(): void
     {
+        // 确保用户已登录
+        if (!$this->auth->isLogin()) {
+            $this->error('请先登录');
+        }
         $userId = $this->auth->id;
 
         $stats = $this->invitationService->getUserInvitationStats($userId);
@@ -252,6 +257,10 @@ class User extends Frontend
      */
     public function subordinateList(): void
     {
+        // 确保用户已登录
+        if (!$this->auth->isLogin()) {
+            $this->error('请先登录');
+        }
         $userId = $this->auth->id;
         $page = $this->request->get('page', 1);
         $pageSize = $this->request->get('pageSize', 10);
@@ -311,4 +320,5 @@ class User extends Frontend
             $this->success();
         }
     }
+
 }

+ 5 - 5
app/api/controller/invitation/Allocation.php

@@ -112,7 +112,7 @@ class Allocation extends Frontend
             $this->error('参数错误');
         }
 
-        try {
+//        try {
             // 获取分配记录以确定卡类型
             $allocation = Db::table('ba_company_package_allocation')
                 ->alias('cpa')
@@ -120,7 +120,7 @@ class Allocation extends Frontend
                 ->where('cpa.id', $allocationId)
                 ->field('cpa.*, pp.card_type')
                 ->find();
-;
+
             if (!$allocation) {
                 $this->error('分配记录不存在');
             }
@@ -142,9 +142,9 @@ class Allocation extends Frontend
             }
 
 
-        } catch (\Throwable $e) {
-            $this->error($e->getMessage());
-        }
+//        } catch (\Throwable $e) {
+//            $this->error($e->getMessage());
+//        }
         if ($result) {
             $this->success('取消分配成功');
         } else {

+ 22 - 1
app/api/controller/invitation/Order.php

@@ -38,6 +38,9 @@ class Order extends Frontend
             $page = $this->request->get('page', 1);
             $pageSize = $this->request->get('pageSize', 10);
             $status = $this->request->get('status', 'all'); // all, paid, unpaid
+            $order_no = $this->request->get('order_no', '');//订单号
+            $star_time = $this->request->get('star_time', '');//创建订单开始时间
+            $end_time = $this->request->get('end_time', '');//创建订单结束时间
 
             // 构建查询条件
             $query = Db::table('ba_order')
@@ -50,9 +53,23 @@ class Order extends Frontend
                 $query->where('pay_status', 0); // 未支付
             }
 
+            // 查询订单号
+            if (!empty($order_no)) {
+                $query->where('order_no', $order_no); // 订单号
+            }
+
+            if (!empty($star_time) && !empty($end_time)) {
+                $where[] = ['order_time', 'between', [$star_time, $end_time]];
+                $query->where($where); // 塞选时间
+            } else {
+                $yesterday = date('Y-m-d 00:00:00', strtotime('-1 day'));
+                $yesterday_end = date('Y-m-d 23:59:00', strtotime('-1 day'));
+                $where[] = ['order_time', 'between', [$yesterday, $yesterday_end]];
+                $query->where($where); // 塞选时间
+            }
+
             // 获取订单总数
             $total = $query->count();
-
             // 获取订单列表(只取必要字段)
             $orders = $query->field('order_no, pay_amount, pay_method, pay_status, order_time, pay_time')
                 ->order('order_time', 'desc')
@@ -115,10 +132,14 @@ class Order extends Frontend
                 'total_orders' => $total,
                 'paid_orders' =>Db::table('ba_order')
                     ->where('user_id', $userId)
+                    ->where($where)
+                    ->where('order_no', 'IN', $orderNos)
                     ->where('pay_status', 1)
                     ->count(),
                 'unpaid_orders' =>Db::table('ba_order')
                     ->where('user_id', $userId)
+                    ->where($where)
+                    ->where('order_no', 'IN', $orderNos)
                     ->where('pay_status', 0)
                     ->count(),
             ];

+ 1 - 2
app/api/controller/invitation/Product.php

@@ -33,12 +33,11 @@ class Product extends Frontend
             $companyInfo = null;
             $companyService = new \app\common\service\CompanyPackageService();
             $companyData = $companyService->getUserCompany($userId);
-
             if ($companyData) {
                 $companyInfo = [
                     'company_id' => $companyData['id'],
                     'company_name' => $companyData['name'],
-                    'is_creator' => $companyData['creator_id'] == $userId
+                    'is_creator' => $companyData['creator_id']??$userId
                 ];
             }
         $this->success('', [

+ 5 - 5
app/api/controller/product/Payment.php

@@ -69,12 +69,12 @@ class Payment extends Frontend
         $orderItem = Db::table('ba_order_item')
             ->where('order_id', $orderId)
             ->find();
-
         $subject = $orderItem['item_name'] ?? '商品购买';
         $body = $orderItem['spec_name'] ?? '';
 
         // 创建支付服务实例
         $paymentService = PaymentFactory::create($payMethod);
+
         // 生成支付二维码
         $qrCodeResult = $paymentService->createQrCode(
             $order['order_no'],
@@ -510,10 +510,10 @@ class Payment extends Frontend
                     // 注意:这里不再重复创建用户产品记录!
                     // 因为 autoAllocateToBuyer 中已经会创建
                     // 只有次卡/积分卡需要在购买时也创建使用记录
-                    if ($package['card_type'] == 1 || $package['card_type'] == 2) {
-                        // 使用事务安全的方式创建
-                        $this->createUserProductRecordSafe($order['user_id'], $item, $package);
-                    }
+//                    if ($package['card_type'] == 1 || $package['card_type'] == 2) {
+//                        // 使用事务安全的方式创建
+//                        $this->createUserProductRecordSafe($order['user_id'], $item, $package);
+//                    }
                 }
 
                 // 10. 扣减库存

+ 11 - 4
app/api/controller/product/Purchase.php

@@ -27,7 +27,7 @@ class Purchase extends Frontend
             // 获取参数
             $packageId = $this->request->post('package_id', 0);
             $quantity = $this->request->post('quantity', 1);
-            $distributorId = $this->request->post('distributor_id', 0); // 分销人ID
+//            $distributorId = $this->request->post('distributor_id', 0); // 分销人ID
 
             if ($packageId <= 0) {
                 $this->error('请选择套餐');
@@ -36,7 +36,13 @@ class Purchase extends Frontend
             if ($quantity < 1) {
                 $this->error('购买数量错误');
             }
-
+        // 检查是否存在分销人ID
+        $distributorId=Db::table('ba_user_invitation')
+            ->where('invitee_id',$userId)
+            ->value('inviter_id');
+        if (!$distributorId){
+            $distributorId=0;
+        }
             // 查询套餐详情
             $package = Db::table('ba_package_price')
                 ->alias('pp')
@@ -47,7 +53,6 @@ class Purchase extends Frontend
                     p.name as package_name
                 ')
                 ->find();
-
             if (!$package) {
                 $this->error('套餐不存在');
             }
@@ -67,6 +72,8 @@ class Purchase extends Frontend
             }
 
             $companyId = $validationResult['company_id'];
+        }else{
+            $companyId =0;
         }
 
             // 查找关联的产品
@@ -104,7 +111,7 @@ class Purchase extends Frontend
                     'pay_method' => null, // 支付方式待选择
                     'pay_status' => 0, // 0=待支付
                     'order_status' => 0, // 0=待处理
-                    'is_commission' => $hasCommission ? 0 : 0, // 0=未处理佣金,1=已处理
+                    'is_commission' => $hasCommission ? 1 : 0, // 0=未处理佣金,1=已处理
                     'distributor_id' => $hasCommission ? $distributorId : null,
                     'commission_amount' => $commissionAmount,
                     'order_time' => date('Y-m-d H:i:s'),

+ 83 - 10
app/common/service/AlipayPaymentService.php

@@ -31,17 +31,52 @@ class AlipayPaymentService extends BasePaymentService
     }
 
     /**
-     * 获取私钥
+     * 获取私钥 - 修复版本
      */
     protected function getPrivateKey()
     {
         // 从文件路径读取或直接使用配置中的私钥
+        $privateKey = '';
+
         if (!empty($this->payConfig['private_key_path']) && file_exists($this->payConfig['private_key_path'])) {
-            return file_get_contents($this->payConfig['private_key_path']);
+            $privateKey = file_get_contents($this->payConfig['private_key_path']);
+        } elseif (!empty($this->payConfig['key'])) {
+            // 如果没有文件路径,可能私钥直接存储在配置中
+            $privateKey = $this->payConfig['key'];
+        }
+
+        if (empty($privateKey)) {
+            throw new \Exception('私钥内容为空');
         }
 
-        // 如果没有文件路径,可能私钥直接存储在配置中
-        return $this->payConfig['key'] ?? '';
+        // 清理私钥格式
+        $privateKey = $this->formatPrivateKey($privateKey);
+
+        return $privateKey;
+    }
+
+    /**
+     * 格式化私钥
+     */
+    protected function formatPrivateKey($privateKey)
+    {
+        // 移除可能的开头和结尾标记
+        $privateKey = str_replace([
+            '-----BEGIN PRIVATE KEY-----',
+            '-----END PRIVATE KEY-----',
+            '-----BEGIN RSA PRIVATE KEY-----',
+            '-----END RSA PRIVATE KEY-----',
+            "\r",
+            "\n"
+        ], '', $privateKey);
+
+        // 确保私钥是完整的行(每行64字符)
+        $privateKey = chunk_split($privateKey, 64, "\n");
+
+        // 添加 PKCS#1 格式的标记(支付宝推荐格式)
+        $privateKey = "-----BEGIN RSA PRIVATE KEY-----\n" . $privateKey . "-----END RSA PRIVATE KEY-----\n";
+
+        return $privateKey;
     }
 
     /**
@@ -70,7 +105,6 @@ class AlipayPaymentService extends BasePaymentService
                 'body' => $body ?: $subject,
                 'product_code' => 'FAST_INSTANT_TRADE_PAY',
             ];
-
             // 公共参数
             $params = [
                 'app_id' => $this->config['app_id'],
@@ -213,7 +247,7 @@ class AlipayPaymentService extends BasePaymentService
     /**
      * 验证签名
      */
-    protected function verifySign($data)
+    protected function verifySign($data, $sign = null)
     {
         $sign = $data['sign'];
         $signType = $data['sign_type'];
@@ -237,7 +271,7 @@ class AlipayPaymentService extends BasePaymentService
         $publicKey = $this->config['alipay_public_key'];
         $res = openssl_get_publickey($publicKey);
         $result = openssl_verify($signContent, base64_decode($sign), $res, OPENSSL_ALGO_SHA256);
-        openssl_free_key($res);
+//        openssl_free_key($res);
 
         return $result === 1;
     }
@@ -273,13 +307,13 @@ class AlipayPaymentService extends BasePaymentService
             openssl_sign($signContent, $sign, $res);
         }
 
-        openssl_free_key($res);
+//        openssl_free_key($res);
 
         return base64_encode($sign);
     }
 
     /**
-     * 执行请求
+     * 执行请求 - 简化修复版本
      */
     private function execute($params)
     {
@@ -304,9 +338,48 @@ class AlipayPaymentService extends BasePaymentService
 
         curl_close($ch);
 
+        // 清理响应数据
+        $response = trim($response);
+
+        // 移除可能的BOM头
+        if (substr($response, 0, 3) == "\xEF\xBB\xBF") {
+            $response = substr($response, 3);
+        }
+
+        // 转换编码确保是UTF-8
+        $encoding = mb_detect_encoding($response, ['UTF-8', 'GBK', 'GB2312', 'ASCII'], true);
+        if ($encoding && $encoding != 'UTF-8') {
+            $response = mb_convert_encoding($response, 'UTF-8', $encoding);
+        }
+
+        // 移除非法字符
+        $response = iconv('UTF-8', 'UTF-8//IGNORE', $response);
+
+        // 尝试解析
         $result = json_decode($response, true);
+
         if (json_last_error() !== JSON_ERROR_NONE) {
-            throw new \Exception('JSON解析失败: ' . json_last_error_msg());
+            // 记录详细的调试信息
+            $errorDetails = [
+                'error' => json_last_error_msg(),
+                'response_length' => strlen($response),
+                'response_preview' => substr($response, 0, 200),
+                'response_end' => substr($response, -200)
+            ];
+
+            $this->log('支付宝API响应JSON解析失败', $errorDetails, 'error');
+
+            // 尝试手动解析支付宝格式
+            if (preg_match('/\{.*\}/s', $response, $matches)) {
+                $jsonPart = $matches[0];
+                $result = json_decode($jsonPart, true);
+
+                if (json_last_error() === JSON_ERROR_NONE) {
+                    return $result;
+                }
+            }
+
+            throw new \Exception('JSON解析失败: ' . json_last_error_msg() . ',响应长度:' . strlen($response));
         }
 
         return $result;

+ 125 - 60
app/common/service/CompanyPackageService.php

@@ -1,6 +1,7 @@
 <?php
 namespace app\common\service;
 
+use think\db\Where;
 use think\facade\Db;
 use think\facade\Log;
 
@@ -57,7 +58,7 @@ class CompanyPackageService
      */
     public function getUserCompany($userId)
     {
-        // 检查用户是否是企业创建人或成员
+        // 检查用户是否是企业创建人
         $company = Db::table('ba_company')
             ->where('creator_id', $userId)
             ->where('status', 1)
@@ -76,7 +77,6 @@ class CompanyPackageService
             ->where('c.status', 1)
             ->field('c.id, c.name')
             ->find();
-
         return $member;
     }
 
@@ -124,9 +124,9 @@ class CompanyPackageService
                     'company_id' => $companyId,
                     'package_price_id' => $packagePriceId,
                     'product_id' => $this->getProductIdByPackage($packagePriceId),
-                    'total_seats' => $quantity,
+                    'total_seats' => $cardType < 3 ? 1000 : $quantity,
                     'assigned_seats' => 0,
-                    'available_seats' => $quantity,
+                    'available_seats' => $cardType < 3 ? 1000 : $quantity,
                     'is_shared' => $cardType < 3 ? 1 : 0, // 次卡/积分卡为共享资源
                     'card_type' => $cardType,
                     'total_times' => $cardType == 1 ? $unitValue * $quantity : 0,
@@ -223,7 +223,7 @@ class CompanyPackageService
                         'is_general' => 0,
                         'seat_index' => 0,
                         'parent_id' => $generalAllocationId, // 关联通用记录
-                        'allocation_status' => 1, // 已分配
+                        'allocation_status' => 0, // 未分配
                         'allocation_time' => date('Y-m-d H:i:s'),
                         'start_time' => date('Y-m-d H:i:s'),
                         'end_time' => null,
@@ -300,18 +300,19 @@ class CompanyPackageService
                     ->where('id', $companyId)
                     ->where('creator_id', $operatorId)
                     ->count() > 0;
-
             // 获取企业所有套餐席位
             $seats = Db::table('ba_company_package_seats')
                 ->alias('cs')
                 ->leftJoin('ba_package_price pp', 'pp.id = cs.package_price_id')
                 ->leftJoin('ba_product p', 'p.id = cs.product_id')
+                ->leftJoin('ba_company_package_allocation pcs', 'pcs.package_price_id = pp.id')
                 ->where('cs.company_id', $companyId)
-                ->where('cs.available_seats', '>', 0)
+                ->where('pcs.buyer_id', $operatorId)
+//                ->where('cs.available_seats', '>', 0)
                 ->where('cs.status', 1)
                 ->field('cs.*, pp.spec_name, pp.card_type, pp.type as package_type, p.name as product_name, p.type as product_type, p.link,pp.image')
+                ->group('pcs.package_price_id')
                 ->select();
-
             // 获取企业所有成员(包括创建者)
             $allMembers = $this->getAllCompanyMembers($companyId);
             // 处理数据
@@ -330,7 +331,6 @@ class CompanyPackageService
                         $unallocatedMembers[] = $member;
                     }
                 }
-
                 // 组织返回数据
                 $seatItem = [
                     'seats_id' => $seat['id'],
@@ -464,7 +464,6 @@ class CompanyPackageService
         }
 
         $cardType = $package['card_type'];
-
         if ($cardType >= 3) {
             // 日期卡:从分配记录中获取已分配成员
             return Db::table('ba_company_package_allocation')
@@ -481,6 +480,7 @@ class CompanyPackageService
                 COALESCE(cm.email, u.email) as email,
                 u.avatar,
                 u.mobile,
+                cpa.id as allocation_id,
                 cpa.allocation_time,
                 cpa.start_time,
                 cpa.end_time,
@@ -508,21 +508,28 @@ class CompanyPackageService
 
             // 获取授权用户的详细信息
 
+           $where[]=['cp.record_type','<>',0];
            $user=Db::table('ba_user')
             ->alias('u')
             // 使用字符串条件替代闭包
             ->leftJoin('ba_company_member cm', 'cm.user_id = u.id AND cm.company_id = ' . $companyId)
+            ->leftJoin('ba_company_package_allocation cp', 'u.id = cp.assigned_to_user_id')
             ->whereIn('u.id', $authorizedUserIds)
+            ->where('cp.allocation_status',1)
+            ->where($where)
+            ->where('cp.package_price_id',$packagePriceId)
             ->field('
                 u.id as user_id,
                 COALESCE(cm.name, u.nickname) as member_name,
                 COALESCE(cm.email, u.email) as email,
                 u.avatar,
+                cp.id as allocation_id,
                 u.mobile,
                 cm.role
             ')
             ->select()
             ->toArray();
+//           dump($user);die;
             return $user;
         }
     }
@@ -557,11 +564,12 @@ class CompanyPackageService
                 ->where('company_id', $seats['company_id'])
                 ->where('package_price_id', $seats['package_price_id'])
                 ->where('record_type', 2) // 购买记录
-                ->where('allocation_status', 0) // 未分配
+                ->whereIn('allocation_status', [0,2]) // 未分配
                 ->where('assigned_to_user_id', null) // 未指定用户
                 ->lock(true)
                 ->order('seat_index', 'asc') // 按席位索引排序
                 ->find();
+
             if (!$availableAllocation) {
                 throw new \Exception('没有可分配的套餐记录');
             }
@@ -782,7 +790,6 @@ class CompanyPackageService
                 ->where('id', $seatsId)
                 ->lock(true)
                 ->find();
-
             if (!$seats) {
                 throw new \Exception('企业套餐不存在');
             }
@@ -805,11 +812,9 @@ class CompanyPackageService
 
             // 5. 检查该成员是否已被授权
             $authorizedUsers = json_decode($seats['authorized_users'] ?? '[]', true);
-
             if (in_array($memberUserId, $authorizedUsers)) {
                 throw new \Exception('该成员已被授权使用此套餐');
             }
-
             // 6. 查找通用记录
             $generalRecord = Db::table('ba_company_package_allocation')
                 ->where('company_id', $seats['company_id'])
@@ -818,9 +823,11 @@ class CompanyPackageService
                 ->where('is_general', 1) // 是通用记录
                 ->order('id', 'asc')
                 ->find();
+
             if (!$generalRecord) {
                 throw new \Exception('未找到套餐购买记录');
             }
+
             // 7. 将成员添加到授权列表
             $authorizedUsers[] = $memberUserId;
 
@@ -829,38 +836,99 @@ class CompanyPackageService
                 ->update([
                     'authorized_users' => json_encode($authorizedUsers),
                     'assigned_member_count' => Db::raw('assigned_member_count + 1'),
+                    'assigned_seats' => Db::raw('assigned_seats + 1'),
+                    'available_seats' => Db::raw('available_seats - 1'),
                     'update_time' => date('Y-m-d H:i:s')
                 ]);
 
-            // 8. 创建新的分配记录
+            // 8. 检查是否存在已取消的分配记录
             $now = date('Y-m-d H:i:s');
-            $newAllocationData = [
-                'order_item_id' => $generalRecord['order_item_id'],
-                'order_id' => $generalRecord['order_id'],
-                'package_price_id' => $seats['package_price_id'],
-                'product_id' => $seats['product_id'],
-                'buyer_id' => $generalRecord['buyer_id'],
-                'company_id' => $seats['company_id'],
-                'assigned_to_user_id' => $memberUserId,
-                'assigned_by_user_id' => $allocatorId,
-                'record_type' => 1, // 用户分配记录
-                'is_general' => 0,
-                'seat_index' => 0,
-                'parent_id' => $generalRecord['id'], // 关联通用记录
-                'allocation_status' => 1, // 已分配
-                'allocation_time' => $now,
-                'start_time' => $now,
-                'end_time' => null,
-                'expire_time' => null,
-                'remaining_times' => $seats['remaining_times'],
-                'remaining_points' => $seats['remaining_points'],
-                'is_used' => 0,
-                'create_time' => $now,
-                'update_time' => $now
-            ];
+            $allocationId = 0;
+
+            // 查找该用户对于此套餐的已取消分配记录
+            $canceledAllocation = Db::table('ba_company_package_allocation')
+                ->where('company_id', $seats['company_id'])
+                ->where('package_price_id', $seats['package_price_id'])
+                ->where('assigned_to_user_id', $memberUserId)
+                ->where('record_type', 1) // 用户分配记录
+                ->where('allocation_status', 2) // 已取消状态
+                ->order('cancel_allocation_time', 'desc') // 取最新的取消记录
+                ->find();
+
+            if ($canceledAllocation) {
+                // 8.1 更新已取消的记录为已分配状态
+                Db::table('ba_company_package_allocation')
+                    ->where('id', $canceledAllocation['id'])
+                    ->update([
+                        'order_item_id' => $generalRecord['order_item_id'],
+                        'order_id' => $generalRecord['order_id'],
+                        'package_price_id' => $seats['package_price_id'],
+                        'product_id' => $seats['product_id'],
+                        'buyer_id' => $generalRecord['buyer_id'],
+                        'company_id' => $seats['company_id'],
+                        'assigned_to_user_id' => $memberUserId,
+                        'assigned_by_user_id' => $allocatorId,
+                        'record_type' => 1, // 用户分配记录
+                        'is_general' => 0,
+                        'parent_id' => $generalRecord['id'],
+                        'allocation_status' => 1, // 更新为已分配
+                        'allocation_time' => $now,
+                        'cancel_allocation_time' => null, // 清除取消时间
+                        'start_time' => $now,
+                        'end_time' => null,
+                        'expire_time' => null,
+                        'remaining_times' => $seats['remaining_times'],
+                        'remaining_points' => $seats['remaining_points'],
+                        'is_used' => 0,
+                        'usage_count' => $canceledAllocation['usage_count'] ?? 0, // 保留原有使用次数
+                        'update_time' => $now
+                    ]);
+
+                $allocationId = $canceledAllocation['id'];
+
+                Log::info('复用已取消的分配记录', [
+                    'allocation_id' => $allocationId,
+                    'member_user_id' => $memberUserId,
+                    'package_price_id' => $seats['package_price_id'],
+                    'company_id' => $seats['company_id']
+                ]);
+            } else {
+                // 8.2 创建新的分配记录
+                $newAllocationData = [
+                    'order_item_id' => $generalRecord['order_item_id'],
+                    'order_id' => $generalRecord['order_id'],
+                    'package_price_id' => $seats['package_price_id'],
+                    'product_id' => $seats['product_id'],
+                    'buyer_id' => $generalRecord['buyer_id'],
+                    'company_id' => $seats['company_id'],
+                    'assigned_to_user_id' => $memberUserId,
+                    'assigned_by_user_id' => $allocatorId,
+                    'record_type' => 1, // 用户分配记录
+                    'is_general' => 0,
+                    'seat_index' => 0,
+                    'parent_id' => $generalRecord['id'], // 关联通用记录
+                    'allocation_status' => 1, // 已分配
+                    'allocation_time' => $now,
+                    'start_time' => $now,
+                    'end_time' => null,
+                    'expire_time' => null,
+                    'remaining_times' => $seats['remaining_times'],
+                    'remaining_points' => $seats['remaining_points'],
+                    'is_used' => 0,
+                    'usage_count' => 0,
+                    'create_time' => $now,
+                    'update_time' => $now
+                ];
 
-            $allocationId = Db::table('ba_company_package_allocation')->insertGetId($newAllocationData);
+                $allocationId = Db::table('ba_company_package_allocation')->insertGetId($newAllocationData);
 
+                Log::info('创建新的分配记录', [
+                    'allocation_id' => $allocationId,
+                    'member_user_id' => $memberUserId,
+                    'package_price_id' => $seats['package_price_id'],
+                    'company_id' => $seats['company_id']
+                ]);
+            }
             // 9. 为用户创建产品使用记录
             $userProductService = new UserProductService();
             $orderItem = Db::table('ba_order_item')->where('id', $generalRecord['order_item_id'])->find();
@@ -868,7 +936,7 @@ class CompanyPackageService
             if ($orderItem) {
                 $package = Db::table('ba_package_price')->where('id', $seats['package_price_id'])->find();
                 if ($package) {
-                    $userProductService->createUserProductRecord($memberUserId, $orderItem, $package);
+                    $userProductService->createCompanyProductUsage($canceledAllocation, $memberUserId, $seats['card_type']);
                 }
             }
             // 10. 记录分配日志
@@ -906,7 +974,6 @@ class CompanyPackageService
                 ->where('id', $companyId)
                 ->where('creator_id', $userId)
                 ->count() > 0;
-
         if ($isCreator) {
             return true;
         }
@@ -914,10 +981,9 @@ class CompanyPackageService
         // 2. 检查是否是购买者(对于该套餐)
         if ($seatsId) {
             $isBuyer = Db::table('ba_company_package_allocation')
-                    ->where('seats_id', $seatsId)
+//                    ->where('seats_id', $seatsId)
                     ->where('buyer_id', $userId)
                     ->count() > 0;
-
             if ($isBuyer) {
                 return true;
             }
@@ -1101,20 +1167,20 @@ class CompanyPackageService
                 $userProductService = new UserProductService();
 
                 // 所有卡类型都需要创建使用记录
-                if ($package['card_type'] >= 3) { // 日期卡
+//                if ($package['card_type'] >= 3) { // 日期卡
                 // 日期卡分配时创建使用记录
                 $userProductService->createCompanyProductUsage($allocation, $buyerId, $package['card_type']);
-                } else { // 次卡(1)和积分卡(2)
-                    // 获取订单商品信息
-                    $orderItem = Db::table('ba_order_item')
-                        ->where('id', $allocation['order_item_id'])
-                        ->find();
-
-                    if ($orderItem) {
-                        // 创建用户产品记录(次卡/积分卡)
-                        $userProductService->createUserProductRecord($buyerId, $orderItem, $package);
-                    }
-                }
+//                } else { // 次卡(1)和积分卡(2)
+//                    // 获取订单商品信息
+//                    $orderItem = Db::table('ba_order_item')
+//                        ->where('id', $allocation['order_item_id'])
+//                        ->find();
+//
+//                    if ($orderItem) {
+//                        // 创建用户产品记录(次卡/积分卡)
+//                        $userProductService->createUserProductRecord($buyerId, $orderItem, $package);
+//                    }
+//                }
 
                 Db::commit();
 
@@ -1205,7 +1271,6 @@ class CompanyPackageService
                 ->where('allocation_status', 1) // 已分配
                 ->lock(true)
                 ->find();
-
             if (!$allocation) {
                 throw new \Exception('分配记录不存在或未分配');
             }
@@ -1233,13 +1298,14 @@ class CompanyPackageService
             if ($key !== false) {
                 unset($authorizedUsers[$key]);
                 $authorizedUsers = array_values($authorizedUsers); // 重新索引数组
-
                 // 更新席位表
                 Db::table('ba_company_package_seats')
                     ->where('id', $seats['id'])
                     ->update([
                         'authorized_users' => json_encode($authorizedUsers),
                         'assigned_member_count' => Db::raw('assigned_member_count - 1'),
+                        'assigned_seats' => Db::raw('assigned_seats - 1'),
+                        'available_seats' => Db::raw('available_seats + 1'),
                         'update_time' => date('Y-m-d H:i:s')
                     ]);
             }
@@ -1254,13 +1320,12 @@ class CompanyPackageService
                     'update_time' => $now
                 ]);
             // 6. 删除对应的用户产品使用记录
-            Db::table('ba_user_product_usage')
+            $del=Db::table('ba_user_product_usage')
                 ->where('user_id', $allocation['assigned_to_user_id'])
                 ->where('package_price_id', $allocation['package_price_id'])
                 ->where('company_id', $allocation['company_id'])
                 ->where('package_type', 2) // 企业套餐
                 ->delete();
-
             // 7. 记录取消分配日志
             Db::table('ba_allocation_log')->insert([
                 'allocation_id' => $allocationId,

+ 18 - 9
app/common/service/InvitationService.php

@@ -61,7 +61,6 @@ class InvitationService
         try {
             // 1. 为注册用户生成自己的邀请码
             $userInvitationCode = $this->generateInvitationCode();
-
             // 2. 将邀请码保存到用户表
             Db::table('ba_user')
                 ->where('id', $newUserId)
@@ -152,7 +151,7 @@ class InvitationService
                     ->where('user_id', $inviterId)
                     ->update([
                         'invitation_count' => $invitationCount,
-                        'total_invitation' => $invitationCount,
+//                        'total_invitation' => $invitationCount,
                         'update_time' => date('Y-m-d H:i:s')
                     ]);
             } else {
@@ -167,7 +166,7 @@ class InvitationService
                     'frozen_commission' => 0.00,
                     'promotion_link' => $promotionLink,
                     'invitation_count' => $invitationCount,
-                    'total_invitation' => $invitationCount,
+//                    'total_invitation' => $invitationCount,
                     'update_time' => date('Y-m-d H:i:s')
                 ]);
             }
@@ -188,7 +187,6 @@ class InvitationService
 
             if (!$exists) {
                 $promotionLink = $this->generatePromotionLink($userId);
-
                 Db::table('ba_user_commission')->insert([
                     'user_id' => $userId,
                     'total_commission' => 0.00,
@@ -197,7 +195,6 @@ class InvitationService
                     'frozen_commission' => 0.00,
                     'promotion_link' => $promotionLink,
                     'invitation_count' => 0,
-                    'total_invitation' => 0,
                     'update_time' => date('Y-m-d H:i:s')
                 ]);
             }
@@ -243,8 +240,8 @@ class InvitationService
                 ->field('invitation_code')
                 ->find();
 
-            // 获取邀请关系
-            $invitations = Db::table('ba_user_invitation')
+            // 获取总邀请人数
+            $totalInvitations = Db::table('ba_user_invitation')
                 ->alias('ui')
                 ->leftJoin('ba_user u', 'u.id = ui.invitee_id')
                 ->where('ui.inviter_id', $userId)
@@ -253,6 +250,17 @@ class InvitationService
                 ->select()
                 ->toArray();
 
+            // 获取今日邀请人数
+            $todayStart = date('Y-m-d 00:00:00');
+            $todayEnd = date('Y-m-d 23:59:59');
+            $todayInvitations = Db::table('ba_user_invitation')
+                ->alias('ui')
+                ->leftJoin('ba_user u', 'u.id = ui.invitee_id')
+                ->where('ui.inviter_id', $userId)
+                ->whereBetween('ui.create_time', [$todayStart, $todayEnd])
+                ->select()
+                ->toArray();
+
             // 获取佣金信息
             $commission = Db::table('ba_user_commission')
                 ->where('user_id', $userId)
@@ -268,8 +276,9 @@ class InvitationService
 
             return [
                 'invitation_code' => $user['invitation_code'] ?? '', // 用户的邀请码
-                'invitations' => $invitations,
-                'invitation_count' => count($invitations),
+                'invitations' => $totalInvitations, // 所有邀请记录
+                'today_invitation' => count($todayInvitations), // 今日邀请人数
+                'total_invitation' => count($totalInvitations), // 总邀请人数
                 'commission' => $commission ?: [
                     'total_commission' => 0,
                     'current_commission' => 0,

+ 1 - 0
app/common/service/PaymentFactory.php

@@ -9,6 +9,7 @@ class PaymentFactory
      */
     public static function create($payMethod, $payConfigId = 0)
     {
+
         switch ($payMethod) {
             case 'wechat':
                 return new WechatPaymentService($payMethod, $payConfigId);

+ 1 - 1
app/common/service/UserProductService.php

@@ -221,7 +221,7 @@ class UserProductService
                 ->where('upu.package_type', 2) // 企业套餐
                 ->where('upu.status', 1) // 有效
                 ->where('upu.is_allocated', 1) // 已分配
-                ->field('upu.*, 
+                ->field('upu.*,
                     p.name as product_name, p.type as product_type, p.link,
                     pp.spec_name, pp.type as package_type, pp.card_type,
                     cpa.assigned_by_user_id,pp.image')