Parcourir la source

feat(farm): 添加种植记录功能并优化种植流程

- 新增种植记录表和模型 FarmSowLog
- 在种植作物时创建种植日志
- 修改种植接口返回值,增加日志 ID- 优化种植流程,增加土地状态检查
notfff il y a 7 mois
Parent
commit
274ad39862

+ 18 - 12
app/Module/AppGame/Handler/Land/SowHandler.php

@@ -59,6 +59,11 @@ class SowHandler extends BaseHandler
                 throw new LogicException("土地不存在或不属于当前用户");
             }
 
+            // 在事务开始前检查土地状态
+            if ($landInfo->status !== \App\Module\Farm\Enums\LAND_STATUS::IDLE->value) {
+                throw new LogicException("土地状态不允许种植");
+            }
+
             // 验证用户是否拥有该种子物品
             $hasItem = ItemService::getUserItems($userId, ['item_id' => $itemId]);
             if ($hasItem->isEmpty()) {
@@ -68,27 +73,27 @@ class SowHandler extends BaseHandler
             // 开启数据库事务
             DB::beginTransaction();
 
-           
-
             // 调用Farm模块的CropService种植作物
             $plantResult = CropService::plantCrop($userId, $landId, $itemId);
             if (!$plantResult) {
                 throw new LogicException("种植失败,请检查土地状态");
             }
-            
-             // 消耗种子物品
+
+            // 获取种植日志ID
+            $sowLogId = $plantResult['log_id'] ?? 0;
+
+            // 消耗种子物品
             ItemService::consumeItem($userId, $itemId, $itemInstanceId, 1, [
                 'source_type' => 'land_sow',
                 'source_id' => $landId,
                 'details' => [
                     'land_id' => $landId,
-                    'sow_id'=>$sow_log_id
-                    ]
+                    'sow_id' => $sowLogId
+                ]
             ]);
 
-            // 设置响应状态
-            $this->response->setCode(0);
-            $this->response->setMsg('种植成功');
+
+
 
             // 提交事务
             DB::commit();
@@ -98,14 +103,15 @@ class SowHandler extends BaseHandler
                 'land_id' => $landId,
                 'seed_id' => $itemId,
                 'item_instance_id' => $itemInstanceId,
-                'crop_id' => $plantResult->id ?? 0
+                'crop_id' => $plantResult['crop']->id ?? 0,
+                'sow_log_id' => $sowLogId
             ]);
 
         } catch (LogicException $e) {
             // 回滚事务
 
             DB::rollBack();
-            
+
 
             // 设置错误响应
             $this->response->setCode(400);
@@ -116,7 +122,7 @@ class SowHandler extends BaseHandler
                 'error' => $e->getMessage(),
                 'trace' => $e->getTraceAsString()
             ]);
-   
+
         }
 
         return $response;

+ 19 - 0
app/Module/Farm/Databases/GenerateSql/farm_sow_logs.sql

@@ -0,0 +1,19 @@
+-- 种植记录表
+-- 记录用户种植作物的历史记录
+-- 创建时间:2023-07-15
+
+DROP TABLE IF EXISTS `kku_farm_sow_logs`;
+
+CREATE TABLE `kku_farm_sow_logs` (
+  `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID',
+  `user_id` bigint NOT NULL COMMENT '用户ID',
+  `land_id` bigint unsigned NOT NULL COMMENT '土地ID',
+  `crop_id` bigint unsigned NOT NULL COMMENT '作物ID',
+  `seed_id` bigint unsigned NOT NULL COMMENT '种子ID',
+  `sow_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '种植时间',
+  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+  PRIMARY KEY (`id`) USING BTREE,
+  KEY `idx_user_id` (`user_id`) USING BTREE,
+  KEY `idx_sow_time` (`sow_time`) USING BTREE,
+  KEY `idx_seed_id` (`seed_id`) USING BTREE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='种植记录表';

+ 21 - 9
app/Module/Farm/Logics/CropLogic.php

@@ -15,6 +15,7 @@ use App\Module\Farm\Models\FarmHarvestLog;
 use App\Module\Farm\Models\FarmLand;
 use App\Module\Farm\Models\FarmSeed;
 use App\Module\Farm\Models\FarmSeedOutput;
+use App\Module\Farm\Models\FarmSowLog;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use UCore\Db\Helper;
@@ -84,13 +85,14 @@ class CropLogic
      * @param int $userId
      * @param int $landId
      * @param int $seedId
-     * @return CropInfoDto|null
+     * @return array|null 返回包含CropInfoDto和日志ID的数组,格式为['crop' => CropInfoDto, 'log_id' => int]
+     * @throws \Exception
      */
-    public function plantCrop(int $userId, int $landId, int $seedId): ?CropInfoDto
+    public function plantCrop(int $userId, int $landId, int $seedId): ?array
     {
         try {
-            // 开启事务
-            DB::beginTransaction();
+            // 检查是否已开启事务
+            \UCore\Db\Helper::check_tr();
 
             // 获取土地信息
             $land = FarmLand::where('id', $landId)
@@ -126,13 +128,19 @@ class CropLogic
             $crop->fertilized = false;
             $crop->save();
 
+            // 创建种植日志
+            $sowLog = new FarmSowLog();
+            $sowLog->user_id = $userId;
+            $sowLog->land_id = $landId;
+            $sowLog->crop_id = $crop->id;
+            $sowLog->seed_id = $seedId;
+            $sowLog->sow_time = now();
+            $sowLog->save();
+
             // 更新土地状态
             $land->status = LAND_STATUS::PLANTING->value;
             $land->save();
 
-            // 提交事务
-            DB::commit();
-
             // 触发作物种植事件
             event(new CropPlantedEvent($userId, $land, $crop));
 
@@ -140,10 +148,14 @@ class CropLogic
                 'user_id' => $userId,
                 'land_id' => $landId,
                 'seed_id' => $seedId,
-                'crop_id' => $crop->id
+                'crop_id' => $crop->id,
+                'sow_log_id' => $sowLog->id
             ]);
 
-            return CropInfoDto::fromModel($crop);
+            return [
+                'crop' => CropInfoDto::fromModel($crop),
+                'log_id' => $sowLog->id
+            ];
         } catch (\Exception $e) {
             // 回滚事务
             DB::rollBack();

+ 88 - 0
app/Module/Farm/Models/FarmSowLog.php

@@ -0,0 +1,88 @@
+<?php
+
+namespace App\Module\Farm\Models;
+
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
+
+/**
+ * 种植记录模型
+ * field start 
+ * @property  int  $id  主键ID
+ * @property  int  $user_id  用户ID
+ * @property  int  $land_id  土地ID
+ * @property  int  $crop_id  作物ID
+ * @property  int  $seed_id  种子ID
+ * @property  string  $sow_time  种植时间
+ * @property  \Carbon\Carbon  $created_at  创建时间
+ * field end
+ */
+class FarmSowLog extends Model
+{
+    /**
+     * 与模型关联的表名
+     *
+     * @var string
+     */
+    protected $table = 'farm_sow_logs';
+
+    /**
+     * 可批量赋值的属性
+     *
+     * @var array
+     */
+    protected $fillable = [
+        'user_id',
+        'land_id',
+        'crop_id',
+        'seed_id',
+        'sow_time',
+    ];
+
+    /**
+     * 应该被转换为日期的属性
+     *
+     * @var array
+     */
+    protected $dates = [
+        'sow_time',
+        'created_at',
+    ];
+
+    /**
+     * 表明模型是否应该被打上时间戳
+     *
+     * @var bool
+     */
+    public $timestamps = false;
+
+    /**
+     * 获取关联的作物
+     *
+     * @return BelongsTo
+     */
+    public function crop(): BelongsTo
+    {
+        return $this->belongsTo(FarmCrop::class, 'crop_id', 'id');
+    }
+
+    /**
+     * 获取关联的种子
+     *
+     * @return BelongsTo
+     */
+    public function seed(): BelongsTo
+    {
+        return $this->belongsTo(FarmSeed::class, 'seed_id', 'id');
+    }
+
+    /**
+     * 获取关联的土地
+     *
+     * @return BelongsTo
+     */
+    public function land(): BelongsTo
+    {
+        return $this->belongsTo(FarmLand::class, 'land_id', 'id');
+    }
+}

+ 2 - 2
app/Module/Farm/Services/CropService.php

@@ -62,9 +62,9 @@ class CropService
      * @param int $userId
      * @param int $landId
      * @param int $seedId
-     * @return CropInfoDto|null
+     * @return array|null 返回包含CropInfoDto和日志ID的数组,格式为['crop' => CropInfoDto, 'log_id' => int]
      */
-    public static function plantCrop(int $userId, int $landId, int $seedId): ?CropInfoDto
+    public static function plantCrop(int $userId, int $landId, int $seedId): ?array
     {
         try {
             $cropLogic = new CropLogic();