Procházet zdrojové kódy

feat(farm): 添加房屋配置 JSON 生成和检查功能

- 新增 RefreshCheckTool 和 SyncFarmHouseJsonTool 工具类
- 在 FarmHouseConfigController 中集成 JSON 生成功能
- 添加 FarmHouseJsonConfig 类用于缓存房屋配置 JSON 数据
- 更新数据库结构,为房屋配置、种子产出和种子配置表添加 AUTO_INCREMENT 属性- 在 JSON_CONFIG_NAME 枚举中添加 FARM_HOUSE 配置项
- 修改 ItemController,移除冗余的 generateJson 方法
- 更新 .gitignore,排除 public/json 目录下的 JSON 文件
Your Name před 8 měsíci
rodič
revize
1bd7d082a1

+ 1 - 0
.gitignore

@@ -26,3 +26,4 @@ yarn-error.log
 *.ignore.md
 *.s.md
 
+!/public/json/*.json

+ 50 - 0
app/Module/Farm/AdminControllers/FarmHouseConfigController.php

@@ -6,12 +6,16 @@ use App\Module\Farm\AdminControllers\Helper\FilterHelper;
 use App\Module\Farm\AdminControllers\Helper\FormHelper;
 use App\Module\Farm\AdminControllers\Helper\GridHelper;
 use App\Module\Farm\AdminControllers\Helper\ShowHelper;
+use App\Module\Farm\AdminControllers\Tools\RefreshCheckTool;
+use App\Module\Farm\AdminControllers\Tools\SyncFarmHouseJsonTool;
+use App\Module\Farm\DCache\FarmHouseJsonConfig;
 use App\Module\Farm\Repositories\FarmHouseConfigRepository;
 use Dcat\Admin\Form;
 use Dcat\Admin\Grid;
 use Dcat\Admin\Show;
 use UCore\DcatAdmin\AdminController;
 use Spatie\RouteAttributes\Attributes\Resource;
+use Spatie\RouteAttributes\Attributes\Get;
 
 /**
  * 房屋等级配置管理控制器
@@ -19,6 +23,37 @@ use Spatie\RouteAttributes\Attributes\Resource;
 #[Resource('farm-house-configs', names: 'dcat.admin.farm-house-configs')]
 class FarmHouseConfigController extends AdminController
 {
+    /**
+     * 生成房屋配置JSON数据
+     */
+    #[Get('farm-house-configs/generate-json')]
+    public function generateJson()
+    {
+        try {
+            // 直接调用命令生成JSON
+            $process = new \Symfony\Component\Process\Process(['php', 'artisan', 'farm:generate-house-json']);
+            $process->setWorkingDirectory(base_path());
+            $process->run();
+
+            if (!$process->isSuccessful()) {
+                return response()->json([
+                    'status'  => 'error',
+                    'message' => 'JSON生成失败: ' . $process->getErrorOutput()
+                ]);
+            }
+
+            return response()->json([
+                'status'  => 'success',
+                'message' => 'JSON生成成功'
+            ]);
+        } catch (\Exception $e) {
+            return response()->json([
+                'status'  => 'error',
+                'message' => 'JSON生成失败: ' . $e->getMessage()
+            ]);
+        }
+    }
+
     /**
      * 页面标题
      *
@@ -41,6 +76,21 @@ class FarmHouseConfigController extends AdminController
     protected function grid()
     {
         return Grid::make(new FarmHouseConfigRepository(), function (Grid $grid) {
+            // 检查配置表状态
+            $status = RefreshCheckTool::checkSyncStatus();
+
+            if ($status['is_synced']) {
+                admin_success('JSON配置表状态', $status['message']);
+            } else {
+                admin_warning('JSON配置表状态', $status['message']);
+            }
+
+            // 添加工具按钮
+            $grid->tools([
+                new RefreshCheckTool($status['should_display']),
+                new SyncFarmHouseJsonTool($status['should_display'])
+            ]);
+
             $helper = new GridHelper($grid, $this);
 
             $helper->columnId();

+ 72 - 0
app/Module/Farm/AdminControllers/Tools/RefreshCheckTool.php

@@ -0,0 +1,72 @@
+<?php
+
+namespace App\Module\Farm\AdminControllers\Tools;
+
+use Dcat\Admin\Grid\Tools\AbstractTool;
+use Illuminate\Support\Facades\Log;
+
+class RefreshCheckTool extends AbstractTool
+{
+    protected $shouldDisplay;
+    protected $style = 'btn btn-default waves-effect';
+
+    public function __construct(bool $shouldDisplay = true)
+    {
+        $this->shouldDisplay = $shouldDisplay;
+    }
+
+    public function title()
+    {
+        return '检查状态';
+    }
+
+    public function render()
+    {
+        if (!$this->shouldDisplay) {
+            return '';
+        }
+
+        return parent::render();
+    }
+
+    public static function checkSyncStatus(): array
+    {
+        $jsonPath = public_path('json/farm_house.json');
+
+        if (!file_exists($jsonPath)) {
+            return [
+                'is_synced' => false,
+                'message' => '配置文件不存在,请立即生成',
+                'should_display' => true
+            ];
+        }
+
+        try {
+            $json = json_decode(file_get_contents($jsonPath), true);
+            $generatedAt = \Carbon\Carbon::parse($json['generated_at']);
+            $lastUpdated = \Carbon\Carbon::parse(\App\Module\Farm\Models\FarmHouseConfig::max('updated_at'));
+
+            if ($generatedAt->lt($lastUpdated)) {
+                return [
+                    'is_synced' => false,
+                    'message' => "配置文件需要更新(生成于 {$generatedAt->format('Y-m-d H:i:s')},最后修改于 {$lastUpdated->format('Y-m-d H:i:s')})",
+                    'should_display' => true
+                ];
+            } else {
+                return [
+                    'is_synced' => true,
+                    'message' => "配置文件已是最新(生成于 {$generatedAt->format('Y-m-d H:i:s')})",
+                    'should_display' => false
+                ];
+            }
+        } catch (\Exception $e) {
+            Log::error('Check farm house config sync status failed: '.$e->getMessage());
+
+            return [
+                'is_synced' => false,
+                'message' => '检查配置文件状态失败:'.$e->getMessage(),
+                'should_display' => true
+            ];
+        }
+    }
+}

+ 72 - 0
app/Module/Farm/AdminControllers/Tools/SyncFarmHouseJsonTool.php

@@ -0,0 +1,72 @@
+<?php
+
+namespace App\Module\Farm\AdminControllers\Tools;
+
+use App\Module\Farm\DCache\FarmHouseJsonConfig;
+use Dcat\Admin\Grid\Tools\AbstractTool;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Log;
+
+class SyncFarmHouseJsonTool extends AbstractTool
+{
+    protected $shouldDisplay;
+    protected $style = 'btn btn-primary waves-effect';
+
+    public function __construct(bool $shouldDisplay = true)
+    {
+        $this->shouldDisplay = $shouldDisplay;
+    }
+
+    public function title()
+    {
+        return '生成JSON';
+    }
+
+    public function confirm()
+    {
+        return '确定要生成房屋配置JSON数据吗?';
+    }
+
+    public function handle(Request $request)
+    {
+        try {
+            // 直接调用命令生成JSON
+            $process = new \Symfony\Component\Process\Process(['php', 'artisan', 'farm:generate-house-json']);
+            $process->setWorkingDirectory(base_path());
+            $process->run();
+
+            if (!$process->isSuccessful()) {
+                Log::error('Generate farm_house.json failed: ' . $process->getErrorOutput());
+                return $this->response()->error('生成失败:' . $process->getErrorOutput());
+            }
+
+            return $this->response()->success('生成成功')->refresh();
+        } catch (\Exception $e) {
+            Log::error('Generate farm_house.json exception: '.$e->getMessage());
+            return $this->response()->error('生成失败:'.$e->getMessage());
+        }
+    }
+
+    public function render()
+    {
+        if (!$this->shouldDisplay) {
+            return '';
+        }
+
+        return parent::render();
+    }
+
+    public static function shouldDisplay(): bool
+    {
+        $jsonPath = public_path('json/farm_house.json');
+        if (!file_exists($jsonPath)) {
+            return true;
+        }
+
+        $json = json_decode(file_get_contents($jsonPath), true);
+        $generatedAt = \Carbon\Carbon::parse($json['generated_at']);
+        $lastUpdated = \Carbon\Carbon::parse(\App\Module\Farm\Models\FarmHouseConfig::max('updated_at'));
+
+        return $generatedAt->lt($lastUpdated);
+    }
+}

+ 61 - 0
app/Module/Farm/DCache/FarmHouseJsonConfig.php

@@ -0,0 +1,61 @@
+<?php
+
+namespace App\Module\Farm\DCache;
+
+use App\Module\Farm\Commands\GenerateFarmHouseConfigJson;
+use App\Module\LCache\DQueueJob;
+
+/**
+ * 农场房屋配置表缓存
+ */
+class FarmHouseJsonConfig extends DQueueJob
+{
+    /**
+     * 获取新数据
+     *
+     * @param array $parameter 参数
+     * @return mixed
+     */
+    static public function getNewData(array $parameter = [])
+    {
+        try {
+            return GenerateFarmHouseConfigJson::generateJson();
+        } catch (\Exception $e) {
+            // 如果生成失败,返回空数组
+            return [
+                'generated_at' => now()->toDateTimeString(),
+                'house_configs' => []
+            ];
+        }
+    }
+
+    /**
+     * 获取缓存时间(秒)
+     *
+     * @return int
+     */
+    static public function getTtl(): int
+    {
+        return 3600; // 1小时
+    }
+
+    /**
+     * 获取防重复执行时间(秒)
+     *
+     * @return int
+     */
+    static public function getPreventDuplication(): int
+    {
+        return 600; // 10分钟
+    }
+
+    /**
+     * 获取必需参数索引
+     *
+     * @return array
+     */
+    static public function getRequiredArgIndex(): array
+    {
+        return [];
+    }
+}

+ 1 - 1
app/Module/Farm/Databases/GenerateSql/farm_house_configs.sql

@@ -15,4 +15,4 @@ CREATE TABLE `kku_farm_house_configs` (
   `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
   PRIMARY KEY (`id`),
   UNIQUE KEY `idx_level` (`level`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房屋等级配置表';
+) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房屋等级配置表';

+ 2 - 2
app/Module/Farm/Databases/GenerateSql/farm_seed_outputs.sql

@@ -10,7 +10,7 @@ CREATE TABLE `kku_farm_seed_outputs` (
   `item_id` bigint unsigned NOT NULL COMMENT '产出物品ID',
   `min_amount` int unsigned NOT NULL COMMENT '最小产出数量',
   `max_amount` int unsigned NOT NULL COMMENT '最大产出数量',
-  `probability` decimal(5,4) NOT NULL COMMENT '产出概率(0-1)',
+  `probability` decimal(7,4) NOT NULL COMMENT '产出概率(0-1)',
   `is_default` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否为默认产出',
   `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
   `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
@@ -18,4 +18,4 @@ CREATE TABLE `kku_farm_seed_outputs` (
   KEY `idx_seed_id` (`seed_id`),
   KEY `idx_item_id` (`item_id`),
   KEY `idx_probability` (`probability`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='种子产出配置表';
+) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='种子产出配置表';

+ 1 - 1
app/Module/Farm/Databases/GenerateSql/farm_seeds.sql

@@ -21,4 +21,4 @@ CREATE TABLE `kku_farm_seeds` (
   PRIMARY KEY (`id`),
   KEY `idx_type` (`type`),
   KEY `idx_item_id` (`item_id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='种子配置表';
+) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='种子配置表';

+ 1 - 0
app/Module/Game/Enums/JSON_CONFIG_NAME.php

@@ -9,5 +9,6 @@ enum JSON_CONFIG_NAME: string
     case PET = 'pets';
     case PET_LEVEL = 'pet_levels';
     case PET_SKILL = 'pet_skills';
+    case FARM_HOUSE = 'farm_house';
 
 }

+ 0 - 12
app/Module/GameItems/AdminControllers/ItemController.php

@@ -32,19 +32,7 @@ use App\Module\GameItems\AdminControllers\Actions\DuplicateRowAction;
 class ItemController extends AdminController
 {
 
-    /**
-     * 生成物品JSON数据
-     */
-    #[Get('game-items/generate-json')]
-    public function generateJson()
-    {
-        $success = ItemJsonConfig::getData([], true);
 
-        return response()->json([
-                                    'status'  => $success ? 'success' : 'error',
-                                    'message' => $success ? 'JSON生成成功' : 'JSON生成失败'
-                                ]);
-    }
 
 
     /**