Pārlūkot izejas kodu

рефакторинг методов для работы с разными таблицами предметов

ilg2005 4 mēneši atpakaļ
vecāks
revīzija
5edf095613

+ 52 - 29
app/Http/Controllers/CharController.php

@@ -72,7 +72,7 @@ class CharController extends Controller
         ], 200);
     }
 
-    
+
     /**
      * Получение всех персонажей пользователя по имени пользователя.
      *
@@ -153,7 +153,7 @@ class CharController extends Controller
             'msg' => 'Items successfully sent.'
         ], 200);
     }
-    
+
 
     /**
      * Получение всех данных персонажа из указанной таблицы.
@@ -171,7 +171,7 @@ class CharController extends Controller
         }
 
         $modelClass = $config['model'];
-        $key        = $config['key'];
+        $key = $config['key'];
 
         // Проверяем существование персонажа
         if (!CharBase::find($char_id)) {
@@ -187,7 +187,7 @@ class CharController extends Controller
 
         return response()->json([
             'code' => 0,
-            'msg'  => 'Data successfully received.',
+            'msg' => 'Data successfully received.',
             'data' => $data
         ], 200);
     }
@@ -209,9 +209,9 @@ class CharController extends Controller
             return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
         }
 
-        $modelClass  = $config['model'];
-        $ownerKey    = $config['key']; // Ключ, по которому связывается с CharBase - id персонажа
-        $primaryKey  = $config['pk']; // Для CharBase - DBKey
+        $modelClass = $config['model'];
+        $ownerKey = $config['key']; // Ключ, по которому связывается с CharBase - id персонажа
+        $primaryKey = $config['pk']; // Для CharBase - DBKey
 
         // 2. Определяем, какую запись обновляем
         if ($table_name === 'CharBase') {
@@ -241,52 +241,74 @@ class CharController extends Controller
     }
 
     /**
-     * Получает конкретный предмет по CharItemID.
+     * Получает конкретный предмет по $char_item_id из указанной таблицы $table предметов.
      *
+     * @param string $table
      * @param int $char_item_id
      * @return \Illuminate\Http\JsonResponse
      */
-    public function GetCharItem(int $char_item_id)
+    public function GetCharItem(string $table, int $char_item_id)
     {
-        $item = CharItem::find($char_item_id);
+        // Получаем конфигурацию таблицы (модель и первичный ключ)
+        $config = $this->resolveTable($table);
+        if (!$config) {
+            return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
+        }
+
+        $modelClass = $config['model'];
+        $pk = $config['pk'];
+
+        // Ищем предмет по первичному ключу из конфигурации
+        $item = $modelClass::where($pk, $char_item_id)->first();
 
         if (!$item) {
             return response()->json([
                 'code' => -2,
-                'msg'  => 'CharItem not found.'
+                'msg' => 'Item not found.',
             ], 404);
         }
 
         return response()->json([
             'code' => 0,
-            'msg'  => 'CharItem successfully received.',
+            'msg' => 'Item successfully received.',
             'data' => $item,
         ], 200);
     }
 
     /**
-     * Обновляет конкретный предмет по CharItemID.
+     * Обновляет конкретный предмет по $char_item_id в указанной таблице $table предметов.
      *
      * @param \Illuminate\Http\Request $request
+     * @param string $table
      * @param int $char_item_id
      * @return \Illuminate\Http\JsonResponse
      */
-    public function UpdateCharItem(Request $request, int $char_item_id)
+    public function UpdateCharItem(Request $request, string $table, int $char_item_id)
     {
-        $item = CharItem::find($char_item_id);
+        // Получаем конфигурацию таблицы (модель и первичный ключ)
+        $config = $this->resolveTable($table);
+        if (!$config) {
+            return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
+        }
+
+        $modelClass = $config['model'];
+        $pk = $config['pk'];
+
+        // Ищем предмет по первичному ключу из конфигурации
+        $item = $modelClass::where($pk, $char_item_id)->first();
 
         if (!$item) {
             return response()->json([
                 'code' => -2,
-                'msg'  => 'CharItem not found.'
+                'msg' => 'Item not found.',
             ], 404);
         }
 
-        // Определяем защищённые поля, которые нельзя обновлять
-        $protected = ['CharItemID', 'Owner', 'Account'];
+        // Определяем защищённые поля динамически, чтобы не дать изменить PK и владельца
+        $protected = [$pk, 'Owner', 'Account'];
         $data = $request->except($protected);
 
-        return $this->_updateAndRespond($item, $data, 'CharItem successfully updated.');
+        return $this->_updateAndRespond($item, $data, 'Item successfully updated.');
     }
 
     //------------------------------ ПРИВАТНЫЕ МЕТОДЫ -----------------------------------------
@@ -307,11 +329,12 @@ class CharController extends Controller
      * Используется в resolveTable(), GetCharacterData(), UpdateCharacterData().
      */
     private const TABLES = [
-        'CharBase'   => ['key' => 'DBKey',  'model' => CharBase::class,   'pk' => 'DBKey'],
-        'CharItem'   => ['key' => 'Owner',  'model' => CharItem::class,   'pk' => 'CharItemID'],
-        'CharFellow' => ['key' => 'Owner',  'model' => CharFellow::class, 'pk' => 'FellowID'],
+        'CharBase' => ['key' => 'DBKey', 'model' => CharBase::class, 'pk' => 'DBKey'],
+        'CharItem' => ['key' => 'Owner', 'model' => CharItem::class, 'pk' => 'CharItemID'],
+        'CharFellow' => ['key' => 'Owner', 'model' => CharFellow::class, 'pk' => 'FellowID'],
+        'CharCashItem_OutputBox' => ['key' => 'Owner', 'model' => CharCashItem_OutputBox::class, 'pk' => 'ItemDBIndex'],
     ];
-   
+
 
     /**
      * Общий метод для обновления модели и формирования ответа.
@@ -326,7 +349,7 @@ class CharController extends Controller
         // 1. Фильтруем поля для массового присвоения
         $fillable = $model->getFillable();
         $guarded = $model->getGuarded();
-        
+
         if (!empty($fillable)) {
             // Если есть fillable - используем только их
             $filteredData = array_intersect_key($data, array_flip($fillable));
@@ -339,7 +362,7 @@ class CharController extends Controller
         }
 
         // 2. Конвертируем null-поля в '', чтобы вместо NULL в БД сохранялась пустая строка
-        $filteredData = array_map(static fn ($v) => $v === null ? '' : $v, $filteredData);
+        $filteredData = array_map(static fn($v) => $v === null ? '' : $v, $filteredData);
 
         if (empty($filteredData)) {
             return response()->json(['code' => -6, 'msg' => 'No valid fields to update.'], 400);
@@ -350,8 +373,8 @@ class CharController extends Controller
             $ok = $model->update($filteredData);
         } catch (\Throwable $e) {
             return response()->json([
-                'code'  => -7,
-                'msg'   => 'Database error while updating record.',
+                'code' => -7,
+                'msg' => 'Database error while updating record.',
                 'error' => $e->getMessage(),
             ], 500);
         }
@@ -359,14 +382,14 @@ class CharController extends Controller
         if (!$ok) {
             return response()->json([
                 'code' => -8,
-                'msg'  => 'Update failed, record not modified.',
+                'msg' => 'Update failed, record not modified.',
             ], 500);
         }
 
         // 4. Возвращаем успешный ответ
         return response()->json([
             'code' => 0,
-            'msg'  => $successMsg,
+            'msg' => $successMsg,
             'data' => $model->fresh()
         ], 200);
     }

+ 20 - 7
app/Models/Char/CharCashItem_OutputBox.php

@@ -13,21 +13,34 @@ class CharCashItem_OutputBox extends Model
     protected $primaryKey = "ItemDBIndex";
     protected $dates = ["CreateDate", "DeleteDate"];
     protected $fillable =
-            [
-              "ItemDBIndex", "Owner", "Kind", "RecId", "Amount", "strChargeNo", "Deleted", "CreateDate", "DeleteDate",
-              "GaveCharName", "Confirm", "Period", "Price", "evPType", "Comment"
-            ];
+        [
+            "ItemDBIndex",
+            "Owner",
+            "Kind",
+            "RecId",
+            "Amount",
+            "strChargeNo",
+            "Deleted",
+            "CreateDate",
+            "DeleteDate",
+            "GaveCharName",
+            "Confirm",
+            "Period",
+            "Price",
+            "evPType",
+            "Comment"
+        ];
 
     public $timestamps = false;
 
     public static function SENDITEMOUTPUTBOX($request)
     {
 
-        if($request['Owner'] == ""){
+        if ($request['Owner'] == "") {
 
             $chars = CharBase::get();
             foreach ($chars as $char) {
-                if($char->Online == 1){
+                if ($char->Online == 1) {
                     $send = new CharCashItem_OutputBox();
                     $send->Owner = $char->DBKey;
                     $send->Kind = $request['Kind'];
@@ -47,7 +60,7 @@ class CharCashItem_OutputBox extends Model
                 }
             }
 
-        }else{
+        } else {
             $send = new CharCashItem_OutputBox();
             $send->Owner = $request['Owner'];
             $send->Kind = $request['Kind'];

+ 3 - 2
routes/api.php

@@ -35,8 +35,9 @@ Route::group(['prefix' => 'api'], function () {
     Route::post('UpdateCharacterData/{char_id}/{table_name}', 'CharController@UpdateCharacterData');
     Route::post('SendItemToCharacter', 'CharController@SendItemToCharacter');
 
-    Route::get('GetCharItem/{char_item_id}', 'CharController@GetCharItem');
-    Route::post('UpdateCharItem/{char_item_id}', 'CharController@UpdateCharItem');
+    // Получение и обновление предмета по char_item_id в нужной таблице
+    Route::get('GetCharItem/{table}/{char_item_id}', 'CharController@GetCharItem');
+    Route::post('UpdateCharItem/{table}/{char_item_id}', 'CharController@UpdateCharItem');
 
     Route::group(['prefix' => 'funcs_adm'], function () {
         Route::get('UpdateCharItemAccount/{CharID?}', 'ADMIN\AdminController@UpdateCharItemAccount');