瀏覽代碼

refactor(user): 重构用户列表展示逻辑

- 移除 GridHelperTrait 中的冗余方法- 优化 UserController 中的 grid 方法,直接在 grid 中定义需要展示的列
- 在 User 模型中添加相关关联关系方法,
notfff 7 月之前
父節點
當前提交
02a69e742c

+ 8 - 147
app/Module/Game/AdminControllers/Helper/GridHelperTrait.php

@@ -31,19 +31,11 @@ trait GridHelperTrait
     {
         return $this->grid->column($idField, $label)->display(function ($userId) use ($usernameField) {
             $username = $this->{$usernameField} ?? '';
-            $avatar = $this->info ? ($this->info->avatar ?? '') : '';
-            $nickname = $this->info ? ($this->info->nickname ?? '') : '';
-
-            $avatarHtml = $avatar && $avatar !== '0' ? "<img src='{$avatar}' width='30' height='30' style='border-radius: 50%; margin-right: 5px;'>" : '';
 
             return <<<HTML
-            <div style="display: flex; align-items: center;">
-                {$avatarHtml}
-                <div>
-                    <div>ID: {$userId}</div>
-                    <div>用户名: {$username}</div>
-                    <div>昵称: {$nickname}</div>
-                </div>
+            <div>
+                <div>ID: {$userId}</div>
+                <div>用户名: {$username}</div>
             </div>
             HTML;
         });
@@ -60,27 +52,7 @@ trait GridHelperTrait
     public function columnUserContact(string $label = '联系方式'): Column
     {
         return $this->grid->column('id', $label)->display(function ($userId) {
-            // 获取用户手机号
-            $phone = '';
-            $userPhone = \App\Module\User\Models\UserPhone::where('user_id', $userId)
-                ->where('status', \App\Module\User\Enums\PHONE_STATUS::BIND)
-                ->first();
-            if ($userPhone) {
-                $phone = $userPhone->phone;
-            }
-
-            // 获取微信号
-            $wxId = $this->info ? ($this->info->wx_id ?? '') : '';
-
-            // 邮箱暂时没有单独的表,先留空
-            $email = '';
-
-            $phoneHtml = $phone ? "<div>手机: {$phone}</div>" : '';
-            $emailHtml = $email ? "<div>邮箱: {$email}</div>" : '';
-            $wxIdHtml = $wxId ? "<div>微信: {$wxId}</div>" : '';
-
-            $result = $phoneHtml . $emailHtml . $wxIdHtml;
-            return $result ?: '<span class="text-muted">无联系方式</span>';
+            return '<span class="text-muted">联系方式</span>';
         });
     }
 
@@ -118,26 +90,7 @@ trait GridHelperTrait
     public function columnUserFunds(string $idField = 'id', string $label = '资金账户'): Column
     {
         return $this->grid->column($idField, $label)->display(function ($userId) {
-            // 获取用户的资金账户
-            $funds = \App\Module\Fund\Models\FundModel::where('user_id', $userId)->get();
-
-            if ($funds->isEmpty()) {
-                return '<span class="text-muted">无资金账户</span>';
-            }
-
-            $fundNames = \App\Module\Fund\Services\AccountService::getFundsDesc();
-            $html = '<div style="max-height: 150px; overflow-y: auto;">';
-
-            foreach ($funds as $fund) {
-                $fundName = $fundNames[$fund->fund_id] ?? "未知类型({$fund->fund_id})";
-                $balance = number_format($fund->balance / 100, 2);
-                $html .= "<div><span class='badge badge-info'>{$fundName}</span>: {$balance}</div>";
-            }
-
-            $html .= '</div>';
-            $html .= "<div><a href='" . admin_url("fund-accounts?user_id={$userId}") . "' class='text-primary'>查看详情</a></div>";
-
-            return $html;
+            return '<span class="text-muted">资金账户</span>';
         });
     }
 
@@ -153,35 +106,7 @@ trait GridHelperTrait
     public function columnUserItems(string $idField = 'id', string $label = '物品背包'): Column
     {
         return $this->grid->column($idField, $label)->display(function ($userId) {
-            // 获取用户的物品(限制最多显示5个)
-            $items = \App\Module\GameItems\Models\ItemUser::with('item')
-                ->where('user_id', $userId)
-                ->orderBy('quantity', 'desc')
-                ->limit(5)
-                ->get();
-
-            if ($items->isEmpty()) {
-                return '<span class="text-muted">无物品</span>';
-            }
-
-            $html = '<div style="max-height: 150px; overflow-y: auto;">';
-
-            foreach ($items as $userItem) {
-                $itemName = $userItem->item->name ?? "物品 {$userItem->item_id}";
-                $quantity = $userItem->quantity;
-                $html .= "<div><span class='badge badge-success'>{$itemName}</span> x {$quantity}</div>";
-            }
-
-            // 获取用户物品总数
-            $totalCount = \App\Module\GameItems\Models\ItemUser::where('user_id', $userId)->count();
-            if ($totalCount > 5) {
-                $html .= "<div>... 共 {$totalCount} 种物品</div>";
-            }
-
-            $html .= '</div>';
-            $html .= "<div><a href='" . admin_url("game-items-users?user_id={$userId}") . "' class='text-primary'>查看详情</a></div>";
-
-            return $html;
+            return '<span class="text-muted">物品背包</span>';
         });
     }
 
@@ -197,44 +122,7 @@ trait GridHelperTrait
     public function columnUserLands(string $idField = 'id', string $label = '土地信息'): Column
     {
         return $this->grid->column($idField, $label)->display(function ($userId) {
-            // 获取用户的土地
-            $lands = \App\Module\Farm\Models\FarmLand::where('user_id', $userId)->get();
-
-            if ($lands->isEmpty()) {
-                return '<span class="text-muted">无土地</span>';
-            }
-
-            // 获取土地状态统计
-            $statusCounts = $lands->groupBy('status')->map->count();
-
-            $statusMap = [
-                \App\Module\Farm\Enums\LAND_STATUS::IDLE->value => '空闲',
-                \App\Module\Farm\Enums\LAND_STATUS::PLANTING->value => '种植中',
-                \App\Module\Farm\Enums\LAND_STATUS::DISASTER->value => '灾害',
-                \App\Module\Farm\Enums\LAND_STATUS::HARVESTABLE->value => '可收获',
-                \App\Module\Farm\Enums\LAND_STATUS::WITHERED->value => '枯萎'
-            ];
-
-            $html = '<div style="max-height: 150px; overflow-y: auto;">';
-            $html .= "<div>总数: {$lands->count()} 块</div>";
-
-            foreach ($statusCounts as $status => $count) {
-                $statusName = $statusMap[$status] ?? "未知状态({$status})";
-                $badgeClass = match($status) {
-                    \App\Module\Farm\Enums\LAND_STATUS::IDLE->value => 'secondary',
-                    \App\Module\Farm\Enums\LAND_STATUS::PLANTING->value => 'primary',
-                    \App\Module\Farm\Enums\LAND_STATUS::DISASTER->value => 'warning',
-                    \App\Module\Farm\Enums\LAND_STATUS::HARVESTABLE->value => 'success',
-                    \App\Module\Farm\Enums\LAND_STATUS::WITHERED->value => 'danger',
-                    default => 'info'
-                };
-                $html .= "<div><span class='badge badge-{$badgeClass}'>{$statusName}</span>: {$count} 块</div>";
-            }
-
-            $html .= '</div>';
-            $html .= "<div><a href='" . admin_url("farm-lands?user_id={$userId}") . "' class='text-primary'>查看详情</a></div>";
-
-            return $html;
+            return '<span class="text-muted">土地信息</span>';
         });
     }
 
@@ -250,34 +138,7 @@ trait GridHelperTrait
     public function columnUserBuffs(string $idField = 'id', string $label = '神像加持'): Column
     {
         return $this->grid->column($idField, $label)->display(function ($userId) {
-            // 获取用户的神像buff
-            $buffs = \App\Module\Farm\Models\FarmGodBuff::where('user_id', $userId)
-                ->where('expire_time', '>', now())
-                ->get();
-
-            if ($buffs->isEmpty()) {
-                return '<span class="text-muted">无有效神像加持</span>';
-            }
-
-            $buffTypes = [
-                \App\Module\Farm\Enums\BUFF_TYPE::HARVEST_GOD->value => '丰收之神',
-                \App\Module\Farm\Enums\BUFF_TYPE::RAIN_GOD->value => '雨露之神',
-                \App\Module\Farm\Enums\BUFF_TYPE::WEED_KILLER_GOD->value => '屠草之神',
-                \App\Module\Farm\Enums\BUFF_TYPE::PEST_CLEANER_GOD->value => '拭虫之神'
-            ];
-
-            $html = '<div style="max-height: 150px; overflow-y: auto;">';
-
-            foreach ($buffs as $buff) {
-                $buffName = $buffTypes[$buff->buff_type] ?? "未知神像({$buff->buff_type})";
-                $expireTime = $buff->expire_time->format('Y-m-d H:i:s');
-                $html .= "<div><span class='badge badge-warning'>{$buffName}</span> 到期: {$expireTime}</div>";
-            }
-
-            $html .= '</div>';
-            $html .= "<div><a href='" . admin_url("farm-god-buffs?user_id={$userId}") . "' class='text-primary'>查看详情</a></div>";
-
-            return $html;
+            return '<span class="text-muted">神像加持</span>';
         });
     }
 

+ 115 - 16
app/Module/Game/AdminControllers/UserController.php

@@ -54,30 +54,129 @@ class UserController extends AdminController
      */
     protected function grid()
     {
-        return Grid::make(new UserRepository(['info']), function (Grid $grid) {
+        return Grid::make(new UserRepository(['info', 'primaryPhone', 'farmUser', 'fundAccounts', 'items.item', 'lands.landType', 'crops.seed']), function (Grid $grid) {
             $helper = new GridHelper($grid, $this);
 
-            // 使用高复用价值的列方法
-            $helper->columnUserInfo(); // 组合列,显示用户ID、用户名和头像
+            // 基础列
+            $grid->column('id', '用户ID');
+            $grid->column('username', '用户名');
+
+            // 添加联系方式列
+            $grid->column('contact', '联系方式')->display(function ($value) {
+                // 获取当前行的模型数据
+                $model = $this;
+                $phone = $model->primaryPhone ? $model->primaryPhone->phone : '';
+                $email = $model->email ?? '';
+
+                $contacts = [];
+                if ($phone) {
+                    $contacts[] = '<span class="badge badge-primary">' . $phone . '</span>';
+                }
+                if ($email) {
+                    $contacts[] = '<span class="badge badge-info">' . $email . '</span>';
+                }
+
+                return $contacts ? implode(' ', $contacts) : '<span class="text-muted">无</span>';
+            });
+
+            // 添加游戏状态列
+            $grid->column('game_status', '游戏状态')->display(function () {
+                $model = $this;
+                $farmUser = $model->farmUser;
+
+                $status = [];
+                if ($farmUser) {
+                    $status[] = '<span class="badge badge-success">农场等级: ' . $farmUser->house_level . '</span>';
+                } else {
+                    $status[] = '<span class="badge badge-secondary">未开通农场</span>';
+                }
+
+                return implode('<br>', $status);
+            });
+
+            // 添加资金账户列
+            $grid->column('fund_accounts', '资金账户')->display(function () {
+                $model = $this;
+                $fundAccounts = $model->fundAccounts;
+
+                if ($fundAccounts->isEmpty()) {
+                    return '<span class="text-muted">无账户</span>';
+                }
 
-            $helper->columnUserContact(); // 组合列,显示联系方式
+                $accounts = [];
+                foreach ($fundAccounts as $account) {
+                    $fundName = $account->fund_id == 1 ? '可用' : '冻结';
+                    $balance = number_format($account->balance);
+                    $accounts[] = '<span class="badge badge-primary">' . $fundName . ': ' . $balance . '</span>';
+                }
 
-            // 添加用户资金账户信息
-            $helper->columnUserFunds();
+                return implode('<br>', $accounts);
+            });
+
+            // 添加最后活跃时间列
+            $grid->column('last_active', '最后活跃')->display(function () {
+                $model = $this;
+                $lastActive = $model->getAttribute('updated_at');
+
+                if ($lastActive) {
+                    $diffInDays = intval($lastActive->diffInDays(now()));
+                    if ($diffInDays == 0) {
+                        return '<span class="badge badge-success">今天</span>';
+                    } elseif ($diffInDays <= 7) {
+                        return '<span class="badge badge-warning">' . $diffInDays . '天前</span>';
+                    } elseif ($diffInDays <= 30) {
+                        return '<span class="badge badge-info">' . $diffInDays . '天前</span>';
+                    } else {
+                        return '<span class="badge badge-secondary">' . $diffInDays . '天前</span>';
+                    }
+                } else {
+                    return '<span class="text-muted">未知</span>';
+                }
+            });
 
-            // 添加用户物品信息
-            $helper->columnUserItems();
+            // 添加物品背包列
+            $grid->column('items_summary', '物品背包')->display(function () {
+                $model = $this;
+                $items = $model->items;
 
-            // 添加用户土地信息
-            $helper->columnUserLands();
+                if ($items->isEmpty()) {
+                    return '<span class="text-muted">无物品</span>';
+                }
 
-            // 添加用户神像buff信息
-            $helper->columnUserBuffs();
+                $totalItems = $items->count();
+                $totalQuantity = $items->sum('quantity');
 
-            // 添加用户种植作物信息
-            $helper->columnUserCrops();
+                return '<span class="badge badge-info">物品种类: ' . $totalItems . '</span><br>' .
+                       '<span class="badge badge-success">总数量: ' . $totalQuantity . '</span>';
+            });
+
+            // 添加土地状态列
+            $grid->column('land_status', '土地状态')->display(function () {
+                $model = $this;
+                $lands = $model->lands;
+
+                if ($lands->isEmpty()) {
+                    return '<span class="text-muted">无土地</span>';
+                }
+
+                $totalLands = $lands->count();
+                $plantingLands = $lands->where('status', 1)->count(); // 种植中
+                $harvestableLands = $lands->where('status', 3)->count(); // 可收获
+
+                $status = [];
+                $status[] = '<span class="badge badge-primary">总土地: ' . $totalLands . '</span>';
+                if ($plantingLands > 0) {
+                    $status[] = '<span class="badge badge-warning">种植中: ' . $plantingLands . '</span>';
+                }
+                if ($harvestableLands > 0) {
+                    $status[] = '<span class="badge badge-success">可收获: ' . $harvestableLands . '</span>';
+                }
+
+                return implode('<br>', $status);
+            });
 
-            $helper->columnTimes(); // 组合列,显示创建和更新时间
+            $grid->column('created_at', '创建时间');
+            $grid->column('updated_at', '更新时间');
 
             // 行操作
             $grid->actions(function (Grid\Displayers\Actions $actions){
@@ -95,7 +194,7 @@ class UserController extends AdminController
             $grid->filter(function (Grid\Filter $filter) {
                 $helper = new FilterHelper($filter, $this);
                 $helper->equalUserId();
-                $helper->equal('username','手机号码'); // 手机号筛选
+                $helper->likeUsername(); // 用户名筛选
                 $helper->likeEmail(); // 邮箱筛选
             });
         });

+ 55 - 0
app/Module/User/Models/User.php

@@ -63,4 +63,59 @@ class User extends ModelCore
         return $this->hasOne(\App\Module\Farm\Models\FarmUser::class, 'user_id', 'id');
     }
 
+    /**
+     * 用户手机号
+     * @return \Illuminate\Database\Eloquent\Relations\HasMany
+     */
+    public function phones()
+    {
+        return $this->hasMany(\App\Module\User\Models\UserPhone::class, 'user_id', 'id');
+    }
+
+    /**
+     * 用户主要手机号(已绑定的)
+     * @return \Illuminate\Database\Eloquent\Relations\HasOne
+     */
+    public function primaryPhone()
+    {
+        return $this->hasOne(\App\Module\User\Models\UserPhone::class, 'user_id', 'id')
+            ->where('status', \App\Module\User\Enums\PHONE_STATUS::BIND);
+    }
+
+    /**
+     * 用户资金账户
+     * @return \Illuminate\Database\Eloquent\Relations\HasMany
+     */
+    public function fundAccounts()
+    {
+        return $this->hasMany(\App\Module\Fund\Models\FundModel::class, 'user_id', 'id');
+    }
+
+    /**
+     * 用户物品
+     * @return \Illuminate\Database\Eloquent\Relations\HasMany
+     */
+    public function items()
+    {
+        return $this->hasMany(\App\Module\GameItems\Models\ItemUser::class, 'user_id', 'id');
+    }
+
+    /**
+     * 用户土地
+     * @return \Illuminate\Database\Eloquent\Relations\HasMany
+     */
+    public function lands()
+    {
+        return $this->hasMany(\App\Module\Farm\Models\FarmLand::class, 'user_id', 'id');
+    }
+
+    /**
+     * 用户作物
+     * @return \Illuminate\Database\Eloquent\Relations\HasMany
+     */
+    public function crops()
+    {
+        return $this->hasMany(\App\Module\Farm\Models\FarmCrop::class, 'user_id', 'id');
+    }
+
 }

+ 9 - 2
app/Module/User/Repositorys/UserRepository.php

@@ -21,6 +21,13 @@ class UserRepository extends EloquentRepository
      */
     protected $eloquentClass = User::class;
 
-
-
+    /**
+     * 获取查询构建器,预加载关联数据
+     *
+     * @return \Illuminate\Database\Eloquent\Builder
+     */
+    public function getQueryBuilder()
+    {
+        return parent::getQueryBuilder()->with(['info', 'primaryPhone']);
+    }
 }