Browse Source

refactor(farm): 重构农场模块代码

- 优化数据库事务处理逻辑
- 添加日志记录功能
- 使用枚举类型替换土地状态
- 移除冗余的查询方法
- 优化用户相关页面的 HTML 生成逻辑
notfff 7 months ago
parent
commit
205bffe192

+ 4 - 1
UCore/Db/Helper.php

@@ -3,6 +3,7 @@
 namespace UCore\Db;
 
 use Illuminate\Support\Facades\DB;
+use UCore\Helper\Logger;
 
 /**
  * 数据库助手类
@@ -19,11 +20,13 @@ class Helper
     {
         $level = DB::transactionLevel();
         if($level === 0){
+            Logger::error("check_tr - transaction level is 0 没有开启事务");
             // 没有开启事务
             throw new \LogicException("transaction level is 0");
         }
         if($level > 1){
-            // 没有开启事务
+            // 事务嵌套
+            Logger::error("check_tr - transaction level >1 事务嵌套 ");
             throw new \LogicException("transaction level > 1");
         }
 

+ 28 - 20
app/Module/AppGame/Handler/Land/FertilizerHandler.php

@@ -8,6 +8,7 @@ use App\Module\Farm\Services\LandService;
 use App\Module\GameItems\Logics\Item;
 use App\Module\GameItems\Services\ItemService;
 use Google\Protobuf\Internal\Message;
+use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use Uraus\Kku\Request\RequestLandFertilizer;
 use Uraus\Kku\Response\ResponseLandFertilizer;
@@ -61,28 +62,35 @@ class FertilizerHandler extends BaseHandler
         if ($crop_growth_time <= 0) {
             throw new LogicException("该肥料物品无效");
         }
-        // 调用施肥服务
-        $result = CropService::useFertilizer($userId, $landId,$crop_growth_time);
-        if (!$result) {
-            throw new LogicException("施肥失败,请检查土地状态或作物生长阶段");
+        DB::beginTransaction();
+        try {
+
+            // 调用施肥服务
+            $result = CropService::useFertilizer($userId, $landId,$crop_growth_time);
+            if (!$result) {
+                throw new LogicException("施肥失败,请检查土地状态或作物生长阶段");
+            }
+
+            // 消耗物品
+            ItemService::consumeItem($userId, $itemId, null, 1, [
+                'source_type' => 'land_fertilizer',
+                'source_id'   => $landId,
+                'details'     => [ 'land_id' => $landId ]
+            ]);
+
+
+
+            Log::info('用户施肥成功', [
+                'user_id' => $userId,
+                'land_id' => $landId,
+                'item_id' => $itemId
+            ]);
+            DB::commit();
+        } catch (\Exception $e) {
+            DB::rollBack();
+            throw $e;
         }
 
-        // 消耗物品
-        ItemService::consumeItem($userId, $itemId, null, 1, [
-            'source_type' => 'land_fertilizer',
-            'source_id'   => $landId,
-            'details'     => [ 'land_id' => $landId ]
-        ]);
-
-
-
-        Log::info('用户施肥成功', [
-            'user_id' => $userId,
-            'land_id' => $landId,
-            'item_id' => $itemId
-        ]);
-
-
         return $response;
     }
 

+ 1 - 0
app/Module/AppGame/HttpControllers/ProtobufController.php

@@ -167,6 +167,7 @@ class ProtobufController extends Controller
             $response->setMsg($errorMsg);
         } catch (\Exception $e) {
             if(App::is_local()){
+                dump("本地环境,直接输出异常信息");
                 throw $e;
             }
             $errorMsg = $e->getMessage();

+ 1 - 1
app/Module/Farm/AdminControllers/FarmLandController.php

@@ -152,7 +152,7 @@ class FarmLandController extends AdminController
             $helper->selectTableUserID('user_id', '用户ID');
             $form->number('position', '位置')->min(1)->max(20)->required();
             $helper->selectLandType('land_type', '土地类型');
-            $helper->selectLandStatus('status', '状态');
+            $helper->selectOptionCast('status', '状态');
 
             $form->display('created_at', '创建时间');
             $form->display('updated_at', '更新时间');

+ 2 - 17
app/Module/Farm/AdminControllers/Helper/FormHelperTrait.php

@@ -59,23 +59,8 @@ trait FormHelperTrait
         ])->required();
     }
 
-    /**
-     * 添加土地状态选择
-     *
-     * @param string $field 字段名
-     * @param string $label 标签名
-     * @return Field\Select
-     */
-    public function selectLandStatus(string $field = 'status', string $label = '土地状态'): Field\Select
-    {
-        return $this->form->select($field, $label)->options([
-            LAND_STATUS::IDLE->value => LAND_STATUS::getName(LAND_STATUS::IDLE->value),
-            LAND_STATUS::PLANTING->value => LAND_STATUS::getName(LAND_STATUS::PLANTING->value),
-            LAND_STATUS::DISASTER->value => LAND_STATUS::getName(LAND_STATUS::DISASTER->value),
-            LAND_STATUS::HARVESTABLE->value => LAND_STATUS::getName(LAND_STATUS::HARVESTABLE->value),
-            LAND_STATUS::WITHERED->value => LAND_STATUS::getName(LAND_STATUS::WITHERED->value),
-        ])->required();
-    }
+
+
 
     /**
      * 添加土地类型选择

+ 5 - 1
app/Module/Farm/Models/FarmLand.php

@@ -2,13 +2,14 @@
 
 namespace App\Module\Farm\Models;
 
+use App\Module\Farm\Enums\LAND_STATUS;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
 use Illuminate\Database\Eloquent\Relations\HasOne;
 
 /**
  * 土地信息模型
- * field start 
+ * field start
  * @property  int  $id  主键ID
  * @property  int  $user_id  用户ID
  * @property  int  $position  土地位置(1-20)
@@ -38,6 +39,9 @@ class FarmLand extends Model
         'land_type',
         'status',
     ];
+    protected $casts = [
+        'status' => LAND_STATUS::class
+    ];
 
     /**
      * 获取关联的用户农场

+ 0 - 64
app/Module/Farm/Repositories/FarmLandRepository.php

@@ -21,69 +21,5 @@ class FarmLandRepository extends EloquentRepository
      */
     protected $eloquentClass = FarmLand::class;
 
-    /**
-     * 获取用户的所有土地
-     *
-     * @param int $userId
-     * @return Collection
-     */
-    public function findByUserId(int $userId): Collection
-    {
-        return FarmLand::where('user_id', $userId)->get();
-    }
-
-    /**
-     * 获取用户指定位置的土地
-     *
-     * @param int $userId
-     * @param int $position
-     * @return FarmLand|null
-     */
-    public function findByUserIdAndPosition(int $userId, int $position): ?FarmLand
-    {
-        return FarmLand::where('user_id', $userId)
-            ->where('position', $position)
-            ->first();
-    }
-
-    /**
-     * 获取用户指定状态的土地
-     *
-     * @param int $userId
-     * @param int $status
-     * @return Collection
-     */
-    public function findByUserIdAndStatus(int $userId, int $status): Collection
-    {
-        return FarmLand::where('user_id', $userId)
-            ->where('status', $status)
-            ->get();
-    }
 
-    /**
-     * 获取用户指定类型的土地
-     *
-     * @param int $userId
-     * @param int $landType
-     * @return Collection
-     */
-    public function findByUserIdAndType(int $userId, int $landType): Collection
-    {
-        return FarmLand::where('user_id', $userId)
-            ->where('land_type', $landType)
-            ->get();
-    }
-
-    /**
-     * 获取用户的特殊土地数量
-     *
-     * @param int $userId
-     * @return int
-     */
-    public function countSpecialLands(int $userId): int
-    {
-        return FarmLand::where('user_id', $userId)
-            ->whereIn('land_type', [4, 5, 6]) // 金、蓝、紫特殊土地
-            ->count();
-    }
 }

+ 4 - 4
app/Module/User/AdminControllers/Actions/UserRelatedPagesAction.php

@@ -95,12 +95,12 @@ class UserRelatedPagesAction extends RowAction
             ],
         ];
 
-        // 生成HTML
-        $html = '<div class="btn-group" style="margin-right: 5px;">';
+        // 生成HTML - 使用flex布局并添加flex-wrap实现按钮自动换行
+        $html = '<div class="btn-toolbar" style="display: flex; flex-wrap: wrap; margin-right: 5px;">';
 
         foreach ($links as $link) {
-            $html .= '<a href="' . $link['url'] . '" target="_blank" class="btn btn-sm btn-primary" style="margin-right: 3px;" title="' . $link['title'] . '">';
-            $html .= '<i class="fa ' . $link['icon'] . '"></i>'.$link['title'];
+            $html .= '<a href="' . $link['url'] . '" target="_blank" class="btn btn-sm btn-primary" style="margin-right: 5px; margin-bottom: 5px;" title="' . $link['title'] . '">';
+            $html .= '<i class="fa ' . $link['icon'] . '"></i> '.$link['title'];
             $html .= '</a>';
         }