瀏覽代碼

refactor(farm): 重构作物收获功能并优化事务处理

- 在 HarvestHandler 中添加事务处理,确保收获操作的原子性
- 修改 CropLogic 中的收获逻辑,使用 Res 对象表示结果
- 优化 TeamLogic 中的推荐关系添加逻辑,使用 Helper::check_tr() 检查事务
- 移除未使用的 FarmUserReferralRepository 类
- 调整 CropService 中的收获方法,返回 Res 对象
notfff 7 月之前
父節點
當前提交
841331f4f0

+ 8 - 17
app/Module/AppGame/Handler/Land/HarvestHandler.php

@@ -6,6 +6,7 @@ use App\Module\AppGame\Handler\BaseHandler;
 use App\Module\Farm\Services\CropService;
 use App\Module\Farm\Services\LandService;
 use Google\Protobuf\Internal\Message;
+use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use Uraus\Kku\Request\RequestLandHarvest;
 use Uraus\Kku\Response\ResponseLandHarvest;
@@ -54,24 +55,24 @@ class HarvestHandler extends BaseHandler
             if (!$landInfo) {
                 throw new LogicException("土地不存在或不属于当前用户");
             }
-
+            DB::beginTransaction();
             // 调用收获服务
-            $harvestResult = CropService::harvestCrop($userId, $landId);
-            if (!$harvestResult) {
+            $res = $harvestResult = CropService::harvestCrop($userId, $landId);
+            if ($res->error) {
                 throw new LogicException("收获失败,请检查土地状态或作物生长阶段");
             }
 
-            // 设置响应状态
-            $this->response->setCode(0);
-            $this->response->setMsg('收获成功');
+
 
             Log::info('用户收获成功', [
                 'user_id' => $userId,
                 'land_id' => $landId,
                 'harvest_result' => $harvestResult
             ]);
+            DB::commit();
 
-        } catch (LogicException $e) {
+        } catch (\Exception $e) {
+            DB::rollBack();
             // 设置错误响应
             $this->response->setCode(400);
             $this->response->setMsg($e->getMessage());
@@ -81,16 +82,6 @@ class HarvestHandler extends BaseHandler
                 'error' => $e->getMessage(),
                 'trace' => $e->getTraceAsString()
             ]);
-        } catch (\Exception $e) {
-            // 设置错误响应
-            $this->response->setCode(500);
-            $this->response->setMsg('系统错误,请稍后再试');
-
-            Log::error('收获操作异常', [
-                'user_id' => $this->user_id,
-                'error' => $e->getMessage(),
-                'trace' => $e->getTraceAsString()
-            ]);
         }
 
         return $response;

+ 1 - 0
app/Module/Farm/Commands/UpdateCropGrowthCommand.php

@@ -106,6 +106,7 @@ class UpdateCropGrowthCommand extends Command
     {
         $logic = new CropLogic();
         return $logic->calculateNextStage($crop);
+
     }
 
     /**

+ 22 - 11
app/Module/Farm/Logics/CropLogic.php

@@ -20,6 +20,7 @@ use App\Module\Farm\Models\FarmSowLog;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use UCore\Db\Helper;
+use UCore\DcatAdmin\Herlper;
 use UCore\Dto\Res;
 
 /**
@@ -181,11 +182,12 @@ class CropLogic
      * @param int $landId
      * @return HarvestResultDto|null
      */
-    public function harvestCrop(int $userId, int $landId): ?HarvestResultDto
+    public function harvestCrop(int $userId, int $landId): Res
     {
         try {
-            // 开启事务
-            DB::beginTransaction();
+//            事务检查
+
+            Helper::check_tr();
 
             // 获取土地信息
             $land = FarmLand::where('id', $landId)
@@ -209,7 +211,7 @@ class CropLogic
             }
 
             // 检查作物生长阶段
-            if ($crop->growth_stage !== GROWTH_STAGE::MATURE->value) {
+            if ($crop->growth_stage !== GROWTH_STAGE::MATURE) {
                 throw new \Exception('作物未成熟,不能收获');
             }
 
@@ -244,7 +246,7 @@ class CropLogic
             $land->save();
 
             // 提交事务
-            DB::commit();
+
 
             // 触发作物收获事件
             event(new CropHarvestedEvent($userId, $land, $crop, $harvestLog, $outputItemId, $outputAmount));
@@ -259,10 +261,11 @@ class CropLogic
                 'harvest_log_id' => $harvestLog->id
             ]);
 
-            return HarvestResultDto::fromModel($harvestLog, $outputItemId);
+
+            return Res::success();
         } catch (\Exception $e) {
             // 回滚事务
-            DB::rollBack();
+
 
             Log::error('作物收获失败', [
                 'user_id' => $userId,
@@ -271,7 +274,7 @@ class CropLogic
                 'trace' => $e->getTraceAsString()
             ]);
 
-            return null;
+            return Res::error('');
         }
     }
 
@@ -585,7 +588,7 @@ class CropLogic
             $crop->save();
 
             // 触发生长阶段变更事件
-            event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $oldStage->value, $newStage->value));
+            event(new CropGrowthStageChangedEvent($crop->user_id, $crop, $oldStage->value, $newStage));
 
             Log::info('作物生长阶段更新成功', [
                 'crop_id' => $cropId,
@@ -633,8 +636,16 @@ class CropLogic
             return GROWTH_STAGE::MATURE->value;
         }
 
-        // 正常阶段递增
-        return $currentStage + 1;
+        // 使用阶段映射确定下一个阶段
+        $stageMap = [
+            GROWTH_STAGE::SEED->value => GROWTH_STAGE::SPROUT->value,
+            GROWTH_STAGE::SPROUT->value => GROWTH_STAGE::GROWTH->value,
+            GROWTH_STAGE::GROWTH->value => GROWTH_STAGE::MATURE->value,
+            GROWTH_STAGE::MATURE->value => GROWTH_STAGE::WITHERED->value,
+            GROWTH_STAGE::WITHERED->value => GROWTH_STAGE::WITHERED->value, // 枯萎期保持不变
+        ];
+
+        return $stageMap[$currentStage->value] ?? GROWTH_STAGE::WITHERED->value;
     }
 
     /**

+ 5 - 38
app/Module/Farm/Logics/TeamLogic.php

@@ -9,6 +9,7 @@ use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use App\Module\Team\Services\TalentService;
 use App\Module\Team\Services\ReferralService;
+use UCore\Db\Helper;
 
 /**
  * 团队管理逻辑
@@ -25,6 +26,7 @@ class TeamLogic
     public function addReferral(int $userId, int $referrerId): bool
     {
         try {
+            Helper::check_tr();
             // 检查用户ID和推荐人ID是否相同
             if ($userId === $referrerId) {
                 throw new \Exception('用户不能推荐自己');
@@ -39,48 +41,13 @@ class TeamLogic
                 return true; // 已存在推荐关系,直接返回成功
             }
 
-            // 开启事务
-            DB::beginTransaction();
 
-            // 创建直接推荐关系
-            $directReferral = new FarmUserReferral();
-            $directReferral->user_id = $userId;
-            $directReferral->referrer_id = $referrerId;
-            $directReferral->level = 1; // 直推
-            $directReferral->save();
 
-            // 使用Team模块的服务更新推荐人的达人信息
-            ReferralService::addReferral($userId, $referrerId);
+
             TalentService::checkAndUpdateUserTalentLevel($referrerId);
 
-            // 获取推荐人的推荐人(用户的间接推荐人)
-            $indirectReferrer = FarmUserReferral::where('user_id', $referrerId)
-                ->where('level', 1)
-                ->first();
 
-            if ($indirectReferrer) {
-                $indirectReferrerId = $indirectReferrer->referrer_id;
-
-                // 检查是否已存在间接推荐关系
-                $existingIndirectReferral = FarmUserReferral::where('user_id', $userId)
-                    ->where('referrer_id', $indirectReferrerId)
-                    ->first();
-
-                if (!$existingIndirectReferral) {
-                    // 创建间接推荐关系
-                    $indirectReferral = new FarmUserReferral();
-                    $indirectReferral->user_id = $userId;
-                    $indirectReferral->referrer_id = $indirectReferrerId;
-                    $indirectReferral->level = 2; // 间推
-                    $indirectReferral->save();
-
-                    // 使用Team模块的服务更新间接推荐人的达人信息
-                    TalentService::checkAndUpdateUserTalentLevel($indirectReferrerId);
-                }
-            }
 
-            // 提交事务
-            DB::commit();
 
             Log::info('添加推荐关系成功', [
                 'user_id' => $userId,
@@ -90,8 +57,8 @@ class TeamLogic
 
             return true;
         } catch (\Exception $e) {
-            // 回滚事务
-            DB::rollBack();
+
+
 
             Log::error('添加推荐关系失败', [
                 'user_id' => $userId,

+ 0 - 102
app/Module/Farm/Repositories/FarmUserReferralRepository.php

@@ -1,102 +0,0 @@
-<?php
-
-namespace App\Module\Farm\Repositories;
-
-use App\Module\Farm\Models\FarmUserReferral;
-use Dcat\Admin\Repositories\EloquentRepository;
-use Illuminate\Database\Eloquent\Collection;
-
-/**
- * 用户推荐关系仓库
- *
- * 提供用户推荐关系数据的访问和操作功能。
- * 该类是用户推荐关系模块与后台管理系统的桥梁,用于处理用户推荐关系数据的CRUD操作。
- */
-class FarmUserReferralRepository extends EloquentRepository
-{
-    /**
-     * 模型类名
-     *
-     * @var string
-     */
-    protected $eloquentClass = FarmUserReferral::class;
-
-    /**
-     * 获取用户的推荐人
-     *
-     * @param int $userId
-     * @return Collection
-     */
-    public function findReferrersByUserId(int $userId): Collection
-    {
-        return FarmUserReferral::where('user_id', $userId)
-            ->orderBy('level')
-            ->get();
-    }
-
-    /**
-     * 获取用户的直接推荐人
-     *
-     * @param int $userId
-     * @return FarmUserReferral|null
-     */
-    public function findDirectReferrer(int $userId): ?FarmUserReferral
-    {
-        return FarmUserReferral::where('user_id', $userId)
-            ->where('level', 1)
-            ->first();
-    }
-
-    /**
-     * 获取用户推荐的人
-     *
-     * @param int $referrerId
-     * @return Collection
-     */
-    public function findReferredByReferrerId(int $referrerId): Collection
-    {
-        return FarmUserReferral::where('referrer_id', $referrerId)
-            ->orderBy('level')
-            ->get();
-    }
-
-    /**
-     * 获取用户直接推荐的人
-     *
-     * @param int $referrerId
-     * @return Collection
-     */
-    public function findDirectReferred(int $referrerId): Collection
-    {
-        return FarmUserReferral::where('referrer_id', $referrerId)
-            ->where('level', 1)
-            ->get();
-    }
-
-    /**
-     * 获取用户间接推荐的人
-     *
-     * @param int $referrerId
-     * @return Collection
-     */
-    public function findIndirectReferred(int $referrerId): Collection
-    {
-        return FarmUserReferral::where('referrer_id', $referrerId)
-            ->where('level', 2)
-            ->get();
-    }
-
-    /**
-     * 检查推荐关系是否存在
-     *
-     * @param int $userId
-     * @param int $referrerId
-     * @return bool
-     */
-    public function checkReferralExists(int $userId, int $referrerId): bool
-    {
-        return FarmUserReferral::where('user_id', $userId)
-            ->where('referrer_id', $referrerId)
-            ->exists();
-    }
-}

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

@@ -90,7 +90,7 @@ class CropService
      * @param int $landId
      * @return HarvestResultDto|null
      */
-    public static function harvestCrop(int $userId, int $landId): ?HarvestResultDto
+    public static function harvestCrop(int $userId, int $landId): Res
     {
         try {
             $cropLogic = new CropLogic();
@@ -103,7 +103,7 @@ class CropService
                 'trace' => $e->getTraceAsString()
             ]);
 
-            return null;
+            return Res::error();
         }
     }