Răsfoiți Sursa

refactor(game): 重构宝箱开启逻辑

- 优化了宝箱开启的事务处理流程
- 改进了错误处理和日志记录
- 调整了数据结构和命名规范
-移除了不必要的注释和冗余代码
notfff 7 luni în urmă
părinte
comite
78a89eafe6

+ 28 - 4
UCore/Helper/Logger.php

@@ -45,14 +45,14 @@ class Logger
     static public function exception($msg, \Throwable $exception, $data = [])
     {
         // 格式化堆栈跟踪,使其换行显示
-        $traceString = $exception->getTraceAsString();
+        $traceString    = $exception->getTraceAsString();
         $formattedTrace = str_replace('#', "\n    #", $traceString);
 
         // 构建格式化的日志信息
         $logMessage = $msg . "\n" .
-                     "异常信息: " . $exception->getMessage() . "\n" .
-                     "文件位置: " . $exception->getFile() . ":" . $exception->getLine() . "\n" .
-                     "堆栈跟踪:\n    " . $formattedTrace;
+                      "异常信息: " . $exception->getMessage() . "\n" .
+                      "文件位置: " . $exception->getFile() . ":" . $exception->getLine() . "\n" .
+                      "堆栈跟踪:\n    " . $formattedTrace;
 
         // 如果有额外数据,添加到日志中
         if (!empty($data)) {
@@ -69,4 +69,28 @@ class Logger
     }
 
 
+    public static function clear_log()
+    {
+        // 获取当前日志文件路径
+        $logPath     = storage_path('logs');
+        $currentDate = date('Y-m-d');
+
+        // Laravel 默认日志文件名格式
+        $logFiles = [
+            $logPath . '/laravel.log',
+            $logPath . "/laravel-{$currentDate}.log",
+        ];
+
+        $clearedCount = 0;
+        foreach ($logFiles as $logFile) {
+            if (file_exists($logFile)) {
+                // 清空文件内容但保留文件
+                file_put_contents($logFile, '');
+                $clearedCount++;
+            }
+        }
+
+        return $clearedCount;
+    }
+
 }

+ 35 - 56
app/Console/Commands/ReproduceErrorCommand.php

@@ -22,6 +22,7 @@ use UCore\Helper\Logger;
  */
 class ReproduceErrorCommand extends Command
 {
+
     /**
      * 命令签名
      *
@@ -55,16 +56,16 @@ class ReproduceErrorCommand extends Command
      */
     public function handle()
     {
-        $identifier = $this->argument('identifier');
-        $type = $this->option('type');
-        $timeout = (int) $this->option('timeout');
+        $identifier  = $this->argument('identifier');
+        $type        = $this->option('type');
+        $timeout     = (int)$this->option('timeout');
         $noclearLogs = $this->option('no-clear-logs');
 
         // 如果开启了清空日志选项,则清空日志文件
         if ($noclearLogs) {
 
-        }else{
-             $this->clearLogFiles();
+        } else {
+            $this->clearLogFiles();
         }
 
         $this->info("开始查找请求记录...");
@@ -76,6 +77,7 @@ class ReproduceErrorCommand extends Command
 
         if (!$requestLog) {
             $this->error("未找到匹配的请求记录");
+
             return 1;
         }
 
@@ -92,10 +94,11 @@ class ReproduceErrorCommand extends Command
         // 检查必要的数据
         if (empty($requestLog->protobuf_json)) {
             $this->error("请求记录中缺少 protobuf_json 数据");
+
             return 1;
         }
         $this->info("请求数据");
-        dump(json_decode($requestLog->protobuf_json,true));
+        dump(json_decode($requestLog->protobuf_json, true));
 
         // 解析 headers 获取 token
         $token = $this->extractToken($requestLog->headers);
@@ -105,8 +108,8 @@ class ReproduceErrorCommand extends Command
             $this->info("提取到 token: " . substr($token, 0, 10) . "...");
         }
         //  user_id
-        if($requestLog->user_id){
-            SessionHelper::sessionLogin($token,$requestLog->user_id);
+        if ($requestLog->user_id) {
+            SessionHelper::sessionLogin($token, $requestLog->user_id);
             $this->info("token 设置用户: {$requestLog->user_id} ");
         }
 
@@ -131,7 +134,8 @@ class ReproduceErrorCommand extends Command
 //        }
         $this->line("响应内容:");
 
-        dump(json_decode($response['body'],true));
+        dump(json_decode($response['body'], true));
+
         return 0;
     }
 
@@ -181,6 +185,7 @@ class ReproduceErrorCommand extends Command
                 return $query->where('run_unid', $identifier)->first();
             default:
                 $this->error("不支持的类型: {$type}");
+
                 return null;
         }
     }
@@ -204,7 +209,7 @@ class ReproduceErrorCommand extends Command
             }
 
             // 查找 token 字段(可能在不同的键名下)
-            $tokenKeys = ['token', 'Token', 'authorization', 'Authorization'];
+            $tokenKeys = [ 'token', 'Token', 'authorization', 'Authorization' ];
 
             foreach ($tokenKeys as $key) {
                 if (isset($headers[$key])) {
@@ -213,6 +218,7 @@ class ReproduceErrorCommand extends Command
                     if (is_array($tokenValue)) {
                         return $tokenValue[0] ?? null;
                     }
+
                     return $tokenValue;
                 }
             }
@@ -220,6 +226,7 @@ class ReproduceErrorCommand extends Command
             return null;
         } catch (\Exception $e) {
             $this->warn("解析 headers 失败: " . $e->getMessage());
+
             return null;
         }
     }
@@ -235,11 +242,11 @@ class ReproduceErrorCommand extends Command
         $this->info("目标地址: {$this->baseUrl}");
 
         $this->client = new Client([
-            'base_uri' => $this->baseUrl,
-            'timeout' => $timeout,
-            'http_errors' => false,
-            'verify' => false, // 禁用 SSL 验证
-        ]);
+                                       'base_uri'    => $this->baseUrl,
+                                       'timeout'     => $timeout,
+                                       'http_errors' => false,
+                                       'verify'      => false, // 禁用 SSL 验证
+                                   ]);
     }
 
     /**
@@ -254,7 +261,7 @@ class ReproduceErrorCommand extends Command
         try {
             $headers = [
                 'Content-Type' => 'application/json',
-                'Accept' => 'application/json'
+                'Accept'       => 'application/json'
             ];
 
             if ($token) {
@@ -262,29 +269,29 @@ class ReproduceErrorCommand extends Command
             }
 
             Log::info('复现请求开始', [
-                'url' => $this->baseUrl . '/gameapi',
-                'headers' => $headers,
+                'url'         => $this->baseUrl . '/gameapi',
+                'headers'     => $headers,
                 'body_length' => strlen($protobufJson)
             ]);
 
             $response = $this->client->post('/gameapi', [
-                'body' => $protobufJson,
+                'body'    => $protobufJson,
                 'headers' => $headers
             ]);
 
-            $statusCode = $response->getStatusCode();
+            $statusCode      = $response->getStatusCode();
             $responseHeaders = $response->getHeaders();
-            $responseBody = $response->getBody()->getContents();
+            $responseBody    = $response->getBody()->getContents();
 
             Log::info('复现请求完成', [
-                'status_code' => $statusCode,
+                'status_code'     => $statusCode,
                 'response_length' => strlen($responseBody)
             ]);
 
             return [
                 'status_code' => $statusCode,
-                'headers' => $responseHeaders,
-                'body' => $responseBody
+                'headers'     => $responseHeaders,
+                'body'        => $responseBody
             ];
 
         } catch (\Exception $e) {
@@ -293,6 +300,7 @@ class ReproduceErrorCommand extends Command
                 'error' => $e->getMessage(),
                 'trace' => $e->getTraceAsString()
             ]);
+
             return null;
         }
     }
@@ -302,39 +310,10 @@ class ReproduceErrorCommand extends Command
      */
     protected function clearLogFiles(): void
     {
-        $this->info("正在清空日志文件...");
 
-        try {
-            // 获取当前日志文件路径
-            $logPath = storage_path('logs');
-            $currentDate = date('Y-m-d');
-
-            // Laravel 默认日志文件名格式
-            $logFiles = [
-                $logPath . '/laravel.log',
-                $logPath . "/laravel-{$currentDate}.log",
-            ];
-
-            $clearedCount = 0;
-
-            foreach ($logFiles as $logFile) {
-                if (file_exists($logFile)) {
-                    // 清空文件内容但保留文件
-                    file_put_contents($logFile, '');
-                    $clearedCount++;
-                    $this->line("已清空: " . basename($logFile));
-                }
-            }
+        Logger::clear_log();
+        Logger::debug('旧的日志已经清理');
 
-            if ($clearedCount > 0) {
-                $this->info("成功清空 {$clearedCount} 个日志文件");
-            } else {
-                $this->warn("未找到需要清空的日志文件");
-            }
-
-            Logger::debug('旧的日志已经清理');
-        } catch (\Exception $e) {
-            $this->error("清空日志文件失败: " . $e->getMessage());
-        }
     }
+
 }

+ 39 - 60
app/Module/AppGame/Handler/Item/OpenboxHandler.php

@@ -7,6 +7,7 @@ use App\Module\GameItems\Services\ChestService;
 use App\Module\GameItems\Validations\ChestOpenValidation;
 use Google\Protobuf\Internal\Message;
 
+use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use Uraus\Kku\Request\RequestItemOpenBox;
 use Uraus\Kku\Response\ResponseItemOpenBox;
@@ -17,8 +18,10 @@ use UCore\Exception\LogicException;
  */
 class OpenboxHandler extends BaseHandler
 {
+
     /**
      * 是否需要登录
+     *
      * @var bool
      */
     protected bool $need_login = true;
@@ -31,90 +34,66 @@ class OpenboxHandler extends BaseHandler
      */
     public function handle(Message $data): Message
     {
-        // 创建响应对象
-        $response = new ResponseItemOpenbox();
 
+        // 获取请求参数
+        $itemId     = $data->getItemId();
+        $instanceId = $data->getItemInstanceId();
+        $selectIds  = iterator_to_array($data->getSelectIds()->getIterator());
+        $userId     = $this->user_id;
+
+        // 先进行验证,避免不必要的事务开销
+        $validation = ChestOpenValidation::make([
+                                                    'user_id'     => $userId,
+                                                    'item_id'     => $itemId,
+                                                    'instance_id' => $instanceId,
+                                                    'quantity'    => 1
+                                                ]);
+
+        // 验证数据
+        $validation->validated();
         try {
-            // 获取请求参数
-            $itemId = $data->getItemId();
-            $instanceId = $data->getItemInstanceId();
-            $selectIds = iterator_to_array($data->getSelectIds()->getIterator());
-            $userId = $this->user_id;
-
-            // 先进行验证,避免不必要的事务开销
-            $validation = new ChestOpenValidation([
-                'user_id' => $userId,
-                'item_id' => $itemId,
-                'instance_id' => $instanceId,
-                'quantity' => 1
-            ]);
-
-            // 验证数据
-            $validation->validated();
 
+            // 开始事务
+            DB::beginTransaction();
             // 使用新宝箱服务开启宝箱
             $result = ChestService::openChest($userId, $itemId, 1, [
-                'select_ids' => $selectIds,
+                'select_ids'  => $selectIds,
                 'source_type' => 'app_open_box',
                 'device_info' => request()->userAgent(),
-                'ip_address' => request()->ip(),
+                'ip_address'  => request()->ip(),
             ]);
 
             if (!$result || !$result['success']) {
                 throw new LogicException("开启宝箱失败,请检查宝箱是否存在或是否可开启");
             }
 
-            // 设置响应状态
-            $this->response->setCode(0);
-            $this->response->setMsg('开启宝箱成功');
 
             Log::info('用户开启宝箱成功', [
-                'user_id' => $userId,
-                'item_id' => $itemId,
+                'user_id'     => $userId,
+                'item_id'     => $itemId,
                 'instance_id' => $instanceId,
-                'select_ids' => $selectIds,
-                'result' => $result,
-                'version' => 'new'
-            ]);
-
-        } catch (\UCore\Exception\ValidateException $e) {
-            // 验证失败
-            $this->response->setCode(400);
-            $this->response->setMsg($e->getMessage());
-
-            Log::warning('宝箱开启验证失败', [
-                'user_id' => $userId ?? null,
-                'item_id' => $itemId ?? null,
-                'instance_id' => $instanceId ?? null,
-                'error' => $e->getMessage()
-            ]);
-
-        } catch (LogicException $e) {
-            // 业务逻辑异常
-            $this->response->setCode(400);
-            $this->response->setMsg($e->getMessage());
-
-            Log::warning('用户开启宝箱失败', [
-                'user_id' => $userId ?? null,
-                'item_id' => $itemId ?? null,
-                'instance_id' => $instanceId ?? null,
-                'error' => $e->getMessage()
+                'select_ids'  => $selectIds,
+                'result'      => $result,
+                'version'     => 'new'
             ]);
+            DB::commit();
 
         } catch (\Exception $e) {
-            // 系统异常
-            $this->response->setCode(500);
-            $this->response->setMsg('系统错误,请稍后再试');
+            DB::rollBack();
+
 
             Log::error('开启宝箱操作异常', [
-                'user_id' => $userId ?? null,
-                'item_id' => $itemId ?? null,
+                'user_id'     => $userId ?? null,
+                'item_id'     => $itemId ?? null,
                 'instance_id' => $instanceId ?? null,
-                'error' => $e->getMessage(),
-                'trace' => $e->getTraceAsString()
+                'error'       => $e->getMessage(),
+                'trace'       => $e->getTraceAsString()
             ]);
+            throw $e;
         }
-
+        // 创建响应对象
+        $response = new ResponseItemOpenbox();
         return $response;
     }
+
 }

+ 1 - 1
app/Module/Game/Services/ConsumeService.php

@@ -256,7 +256,7 @@ class ConsumeService
 
         // 检查数量是否足够
         if ($totalQuantity < $quantity) {
-            return Res::error("物品数量不足,需要 {$quantity},实际 {$totalQuantity}", [
+            return Res::error("物品 $itemId 数量不足,需要 {$quantity},实际 {$totalQuantity}", [
                 'item_id'  => $itemId,
                 'required' => $quantity,
                 'actual'   => $totalQuantity

+ 109 - 122
app/Module/GameItems/Services/ChestService.php

@@ -11,6 +11,7 @@ use App\Module\GameItems\Models\ItemChestConfig;
 use Exception;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
+use UCore\Dto\Res;
 
 /**
  * 宝箱服务类 - 使用消耗组/奖励组系统
@@ -20,6 +21,7 @@ use Illuminate\Support\Facades\Log;
  */
 class ChestService
 {
+
     /**
      * 开启宝箱
      *
@@ -30,7 +32,7 @@ class ChestService
      * @return array 开启结果
      * @throws Exception
      */
-    public static function openChest(int $userId, int $chestId, int $quantity = 1, array $options = []): array
+    public static function openChest(int $userId, int $chestId, int $quantity = 1, array $options = []): Res
     {
         // 获取宝箱信息
         $chest = Item::findOrFail($chestId);
@@ -41,7 +43,7 @@ class ChestService
         }
 
         // 获取宝箱配置
-        $chestConfig = ItemChestConfig::with(['consumeGroup', 'rewardGroup', 'conditionGroup'])
+        $chestConfig = ItemChestConfig::with([ 'consumeGroup', 'rewardGroup', 'conditionGroup' ])
             ->where('item_id', $chestId)
             ->where('is_active', true)
             ->first();
@@ -54,103 +56,84 @@ class ChestService
             throw new Exception("宝箱 {$chestId} 没有配置奖励组");
         }
 
-        // 开始事务
-        DB::beginTransaction();
-        try {
-            $allResults = [];
-            $totalCosts = [];
-
-            // 循环开启每个宝箱
-            for ($i = 0; $i < $quantity; $i++) {
-                // 验证并扣除消耗(如果有消耗组配置)
-                if ($chestConfig->consume_group_id) {
-                    $consumeResult = ConsumeService::executeConsume(
-                        $userId,
-                        $chestConfig->consume_group_id,
-                        "开启宝箱",
-                        $chestId
-                    );
-
-                    if (!$consumeResult->success) {
-                        throw new Exception("消耗验证失败: " . $consumeResult->message);
-                    }
-
-                    // 记录消耗详情
-                    $totalCosts = array_merge($totalCosts, $consumeResult->data ?? []);
-                }
-
-                // 消耗宝箱本身
-                $consumeResult = ItemService::consumeItem(
-                    $userId,
-                    $chestId,
-                    null,
-                    1,
-                    [
-                        'source_type' => 'chest_open',
-                        'source_id' => $chestId,
-                        'details' => ['quantity' => 1],
-                        'ip_address' => $options['ip_address'] ?? null,
-                        'device_info' => $options['device_info'] ?? null,
-                    ]
-                );
 
-                if (!$consumeResult['success']) {
-                    throw new Exception("消耗宝箱失败: " . $consumeResult['message']);
-                }
+        $allResults = [];
+        $totalCosts = [];
 
-                // 发放奖励(支持保底机制)
-                $rewardResult = RewardService::grantRewardWithPity(
+        // 循环开启每个宝箱
+        for ($i = 0; $i < $quantity; $i++) {
+            // 验证并扣除消耗(如果有消耗组配置)
+            if ($chestConfig->consume_group_id) {
+                $consumeResult = ConsumeService::executeConsume(
                     $userId,
-                    $chestConfig->reward_group_id,
-                    'chest_open',
-                    $chestId,
-                    true // 启用保底机制
+                    $chestConfig->consume_group_id,
+                    "开启宝箱",
+                    $chestId
                 );
 
-                if (!$rewardResult->success) {
-                    throw new Exception("发放奖励失败: " . ($rewardResult->errorMessage ?? '未知错误'));
+                if (!$consumeResult->success) {
+                    throw new Exception("消耗验证失败: " . $consumeResult->message);
                 }
 
-                // 记录本次开启结果
-                $allResults[] = $rewardResult->items;
+                // 记录消耗详情
+                $totalCosts = array_merge($totalCosts, $consumeResult->data ?? []);
             }
 
-            // 记录宝箱开启日志
-            $openLog = ItemChestOpenLog::create([
-                'user_id' => $userId,
-                'chest_id' => $chestId,
-                'open_quantity' => $quantity,
-                'result_items' => $allResults,
-                'pity_triggered' => false, // V2版本暂不支持保底机制
-                'pity_content_id' => null,
-                'open_time' => now(),
-                'ip_address' => $options['ip_address'] ?? null,
-                'device_info' => $options['device_info'] ?? null,
-            ]);
-
-            DB::commit();
+            // 消耗宝箱本身
+            $consumeResult = ItemService::consumeItem(
+                $userId,
+                $chestId,
+                null,
+                1,
+                [
+                    'source_type' => 'chest_open',
+                    'source_id'   => $chestId,
+                    'details'     => [ 'quantity' => 1 ],
+                    'ip_address'  => $options['ip_address'] ?? null,
+                    'device_info' => $options['device_info'] ?? null,
+                ]
+            );
+
+            if (!$consumeResult['success']) {
+                throw new Exception("消耗宝箱失败: " . $consumeResult['message']);
+            }
 
-            return [
-                'success' => true,
-                'chest_id' => $chestId,
-                'quantity' => $quantity,
-                'results' => $allResults,
-                'costs' => $totalCosts,
-                'log_id' => $openLog->id,
-                'version' => 'new',
-            ];
+            // 发放奖励(支持保底机制)
+            $rewardResult = RewardService::grantRewardWithPity(
+                $userId,
+                $chestConfig->reward_group_id,
+                'chest_open',
+                $chestId,
+                true // 启用保底机制
+            );
+
+            if (!$rewardResult->success) {
+                throw new Exception("发放奖励失败: " . ($rewardResult->errorMessage ?? '未知错误'));
+            }
 
-        } catch (Exception $e) {
-            DB::rollBack();
-            Log::error('宝箱开启失败', [
-                'user_id' => $userId,
-                'chest_id' => $chestId,
-                'quantity' => $quantity,
-                'error' => $e->getMessage(),
-                'trace' => $e->getTraceAsString()
-            ]);
-            throw $e;
+            // 记录本次开启结果
+            $allResults[] = $rewardResult->items;
         }
+
+        // 记录宝箱开启日志
+        $openLog = ItemChestOpenLog::create([
+                                                'user_id'         => $userId,
+                                                'chest_id'        => $chestId,
+                                                'open_quantity'   => $quantity,
+                                                'result_items'    => $allResults,
+                                                'pity_triggered'  => false, // V2版本暂不支持保底机制
+                                                'pity_content_id' => null,
+                                                'open_time'       => now(),
+                                                'ip_address'      => $options['ip_address'] ?? null,
+                                                'device_info'     => $options['device_info'] ?? null,
+                                            ]);
+
+
+        return Res::success('成功', [
+            'openLog' => $openLog->id
+        ]);
+
+
     }
 
     /**
@@ -170,19 +153,22 @@ class ChestService
         }
 
         // 获取宝箱配置
-        $chestConfig = ItemChestConfig::with(['consumeGroup.consumeItems', 'rewardGroup.rewardItems', 'conditionGroup'])
+        $chestConfig = ItemChestConfig::with([
+                                                 'consumeGroup.consumeItems', 'rewardGroup.rewardItems',
+                                                 'conditionGroup'
+                                             ])
             ->where('item_id', $chestId)
             ->where('is_active', true)
             ->first();
 
         $preview = [
-            'chest_id' => $chestId,
-            'chest_name' => $chest->name,
-            'version' => 'new',
-            'consume_group' => null,
-            'reward_group' => null,
+            'chest_id'        => $chestId,
+            'chest_name'      => $chest->name,
+            'version'         => 'new',
+            'consume_group'   => null,
+            'reward_group'    => null,
             'condition_group' => null,
-            'config_status' => $chestConfig ? 'active' : 'not_configured',
+            'config_status'   => $chestConfig ? 'active' : 'not_configured',
         ];
 
         if (!$chestConfig) {
@@ -192,15 +178,15 @@ class ChestService
         // 获取消耗组信息
         if ($chestConfig->consumeGroup) {
             $preview['consume_group'] = [
-                'id' => $chestConfig->consumeGroup->id,
-                'name' => $chestConfig->consumeGroup->name,
-                'code' => $chestConfig->consumeGroup->code,
+                'id'          => $chestConfig->consumeGroup->id,
+                'name'        => $chestConfig->consumeGroup->name,
+                'code'        => $chestConfig->consumeGroup->code,
                 'description' => $chestConfig->consumeGroup->description,
-                'items' => $chestConfig->consumeGroup->consumeItems->map(function ($item) {
+                'items'       => $chestConfig->consumeGroup->consumeItems->map(function ($item) {
                     return [
                         'consume_type' => $item->consume_type,
-                        'target_id' => $item->target_id,
-                        'quantity' => $item->quantity,
+                        'target_id'    => $item->target_id,
+                        'quantity'     => $item->quantity,
                     ];
                 })->toArray(),
             ];
@@ -209,19 +195,19 @@ class ChestService
         // 获取奖励组信息
         if ($chestConfig->rewardGroup) {
             $preview['reward_group'] = [
-                'id' => $chestConfig->rewardGroup->id,
-                'name' => $chestConfig->rewardGroup->name,
-                'code' => $chestConfig->rewardGroup->code,
-                'description' => $chestConfig->rewardGroup->description,
-                'is_random' => $chestConfig->rewardGroup->is_random,
+                'id'           => $chestConfig->rewardGroup->id,
+                'name'         => $chestConfig->rewardGroup->name,
+                'code'         => $chestConfig->rewardGroup->code,
+                'description'  => $chestConfig->rewardGroup->description,
+                'is_random'    => $chestConfig->rewardGroup->is_random,
                 'random_count' => $chestConfig->rewardGroup->random_count,
-                'reward_mode' => $chestConfig->rewardGroup->reward_mode,
-                'items' => $chestConfig->rewardGroup->rewardItems->map(function ($item) {
+                'reward_mode'  => $chestConfig->rewardGroup->reward_mode,
+                'items'        => $chestConfig->rewardGroup->rewardItems->map(function ($item) {
                     return [
-                        'reward_type' => $item->reward_type,
-                        'target_id' => $item->target_id,
-                        'quantity' => $item->quantity,
-                        'weight' => $item->weight,
+                        'reward_type'   => $item->reward_type,
+                        'target_id'     => $item->target_id,
+                        'quantity'      => $item->quantity,
+                        'weight'        => $item->weight,
                         'is_guaranteed' => $item->is_guaranteed,
                     ];
                 })->toArray(),
@@ -231,9 +217,9 @@ class ChestService
         // 获取条件组信息
         if ($chestConfig->conditionGroup) {
             $preview['condition_group'] = [
-                'id' => $chestConfig->conditionGroup->id,
-                'name' => $chestConfig->conditionGroup->name,
-                'code' => $chestConfig->conditionGroup->code,
+                'id'          => $chestConfig->conditionGroup->id,
+                'name'        => $chestConfig->conditionGroup->name,
+                'code'        => $chestConfig->conditionGroup->code,
                 'description' => $chestConfig->conditionGroup->description,
             ];
         }
@@ -259,12 +245,12 @@ class ChestService
             if ($chest->type != ITEM_TYPE::CHEST) {
                 return [
                     'can_open' => false,
-                    'message' => "物品 {$chestId} 不是宝箱类型",
+                    'message'  => "物品 {$chestId} 不是宝箱类型",
                 ];
             }
 
             // 获取宝箱配置
-            $chestConfig = ItemChestConfig::with(['consumeGroup'])
+            $chestConfig = ItemChestConfig::with([ 'consumeGroup' ])
                 ->where('item_id', $chestId)
                 ->where('is_active', true)
                 ->first();
@@ -272,7 +258,7 @@ class ChestService
             if (!$chestConfig) {
                 return [
                     'can_open' => false,
-                    'message' => "宝箱 {$chestId} 没有配置新系统或配置未激活",
+                    'message'  => "宝箱 {$chestId} 没有配置新系统或配置未激活",
                 ];
             }
 
@@ -280,7 +266,7 @@ class ChestService
             if (!$chestConfig->reward_group_id) {
                 return [
                     'can_open' => false,
-                    'message' => "宝箱 {$chestId} 没有配置奖励组",
+                    'message'  => "宝箱 {$chestId} 没有配置奖励组",
                 ];
             }
 
@@ -289,7 +275,7 @@ class ChestService
             if (!$checkResult->success) {
                 return [
                     'can_open' => false,
-                    'message' => $checkResult->message,
+                    'message'  => $checkResult->message,
                 ];
             }
 
@@ -299,21 +285,22 @@ class ChestService
                 if (!$canConsume->success) {
                     return [
                         'can_open' => false,
-                        'message' => "消耗验证失败: " . $canConsume->message,
+                        'message'  => "消耗验证失败: " . $canConsume->message,
                     ];
                 }
             }
 
             return [
                 'can_open' => true,
-                'message' => '可以开启',
+                'message'  => '可以开启',
             ];
 
         } catch (Exception $e) {
             return [
                 'can_open' => false,
-                'message' => "检查失败: " . $e->getMessage(),
+                'message'  => "检查失败: " . $e->getMessage(),
             ];
         }
     }
+
 }

+ 3 - 3
app/Module/GameItems/Validators/ChestItemValidator.php

@@ -9,7 +9,7 @@ use UCore\Validator;
 
 /**
  * 宝箱物品验证器
- * 
+ *
  * 验证物品是否为宝箱类型且配置正确
  */
 class ChestItemValidator extends Validator
@@ -28,14 +28,14 @@ class ChestItemValidator extends Validator
         try {
             // 获取物品信息
             $item = Item::find($itemId);
-            
+
             if (!$item) {
                 $this->addError("物品不存在");
                 return false;
             }
 
             // 检查是否为宝箱类型
-            if ($item->type !== ITEM_TYPE::CHEST->value) {
+            if ($item->type !== ITEM_TYPE::CHEST) {
                 $this->addError("该物品不是宝箱类型");
                 return false;
             }

+ 18 - 21
app/Module/GameItems/Validators/ChestOwnershipValidator.php

@@ -7,11 +7,12 @@ use UCore\Validator;
 
 /**
  * 宝箱归属验证器
- * 
+ *
  * 验证用户是否拥有指定的宝箱
  */
 class ChestOwnershipValidator extends Validator
 {
+
     /**
      * 验证宝箱归属
      *
@@ -22,37 +23,33 @@ class ChestOwnershipValidator extends Validator
     public function validate(mixed $value, array $data): bool
     {
         $itemId = (int)$value;
-        
+
         // 从 args 获取参数键名
-        $userIdKey = $this->args[0] ?? 'user_id';
+        $userIdKey     = $this->args[0] ?? 'user_id';
         $instanceIdKey = $this->args[1] ?? 'instance_id';
 
-        $userId = $data[$userIdKey] ?? null;
+        $userId     = $data[$userIdKey] ?? null;
         $instanceId = $data[$instanceIdKey] ?? null;
 
         if (!$userId) {
             $this->addError('用户ID不能为空');
+
             return false;
         }
 
-        try {
-            // 检查用户是否拥有该宝箱
-            $userItem = ItemService::getUserItem($userId, $itemId, $instanceId);
-            
-            if (!$userItem) {
-                $this->addError('您没有该宝箱或宝箱不存在');
-                return false;
-            }
-
-            if ($userItem->quantity <= 0) {
-                $this->addError('宝箱数量不足');
-                return false;
-            }
-
-            return true;
-        } catch (\Exception $e) {
-            $this->addError('验证宝箱归属时发生错误: ' . $e->getMessage());
+        // 检查用户是否拥有该宝箱
+        $userItem = ItemService::checkItemQuantity($userId, $itemId, 1, $instanceId);
+
+        if (!$userItem) {
+            $this->addError('您没有该宝箱或宝箱不存在');
+
             return false;
         }
+
+
+        return true;
+
+
     }
+
 }

+ 4 - 0
app/Providers/AppServiceProvider.php

@@ -4,6 +4,7 @@ namespace App\Providers;
 
 use Carbon\Carbon;
 use Illuminate\Support\ServiceProvider;
+use UCore\Helper\Logger;
 
 class AppServiceProvider extends ServiceProvider
 {
@@ -25,6 +26,9 @@ class AppServiceProvider extends ServiceProvider
             $logger = new \UCore\Logging\SizeRotatingDailyLogger();
             return $logger($config);
         });
+        if(env('REQUEST_CLEAR_LOG',0)){
+            Logger::clear_log();
+        }
 
 //        Carbon::setTi('Asia/Shanghai');
     }

+ 0 - 62
app/Services/Blockchain/MinerService.php

@@ -1,62 +0,0 @@
-<?php
-
-namespace App\Services\Blockchain;
-
-class MinerService
-{
-    /**
-     * 计算预估矿工费
-     * @param string $atype 交易类型
-     * @param string $toAddress 目标地址
-     * @param string $amount 交易金额
-     * @return array 返回矿工费信息
-     */
-    public function calculateMinerFee(string $atype, string $toAddress, string $amount): array
-    {
-        // 基础费率
-        $baseFee = 0.003;
-
-        // 根据交易类型调整费率
-        $typeFee = match($atype) {
-            'transfer' => 0.001,
-            'swap' => 0.002,
-            'stake' => 0.0015,
-            default => 0.001
-        };
-
-        // 根据金额计算动态费率(金额越大,费率越高)
-        $amountFee = $amount * 0.0001;
-
-        // 计算总费用(基础费率 + 类型费率 + 动态费率)
-        $totalFee = $baseFee + $typeFee + $amountFee;
-
-        // 确保最小费用不低于0.001
-        $totalFee = max(0.001, $totalFee);
-
-        // 确保最大费用不超过0.01
-        $totalFee = min(0.01, $totalFee);
-
-        return [
-            'minerAmount' => number_format($totalFee, 6, '.', ''),
-            'desc' => $this->generateDescription($atype, $totalFee)
-        ];
-    }
-
-    /**
-     * 生成费用说明
-     * @param string $atype 交易类型
-     * @param float $fee 费用
-     * @return string
-     */
-    private function generateDescription(string $atype, float $fee): string
-    {
-        $typeDesc = match($atype) {
-            'transfer' => '转账',
-            'swap' => '兑换',
-            'stake' => '质押',
-            default => '交易'
-        };
-
-        return sprintf('%s交易预估矿工费用(实际费用可能会有波动)', $typeDesc);
-    }
-}