CharController.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\Models\Char\CharBase;
  5. use App\Models\Char\CharCashItem_OutputBox;
  6. use App\Models\Char\CharItem;
  7. use App\Models\Char\CharFellow;
  8. use App\Models\Char\CharQuest;
  9. use Illuminate\Support\Facades\Log;
  10. use App\Models\Char\CharQuest_History;
  11. class CharController extends Controller
  12. {
  13. /**
  14. * Получение всех персонажей из базы данных с пагинацией
  15. * (по умолчанию - только активные персонажи, если в запросе with_deleted=true - в том числе удаленные).
  16. *
  17. * @return \Illuminate\Http\JsonResponse
  18. */
  19. public function GetAllCharacters(Request $request)
  20. {
  21. // 1. Валидация и параметры запроса
  22. $validated = $request->validate([
  23. 'per_page' => 'sometimes|integer|min:1|max:100',
  24. 'search' => 'sometimes|string|nullable|max:50',
  25. 'with_deleted' => 'sometimes'
  26. ]);
  27. // Флаг: включать ли удаленных персонажей
  28. // Используем $request->boolean(), который корректно приводит строки ('true', '1', 'on', 'yes') к true
  29. $withDeleted = $request->boolean('with_deleted');
  30. $perPage = $validated['per_page'] ?? 15;
  31. $search = trim($validated['search'] ?? '');
  32. $sortField = $request->input('sort_field', 'DBKey');
  33. $sortOrder = strtolower($request->input('sort_order', 'asc')) === 'desc' ? 'desc' : 'asc';
  34. // whitelist для полей сортировки и выборки
  35. $allowedSortFields = ['DBKey', 'Name', 'Level', 'AccountName', 'Deleted'];
  36. if (!in_array($sortField, $allowedSortFields, true)) {
  37. $sortField = 'DBKey';
  38. }
  39. // 2. Запрос с выборкой только нужных полей
  40. $query = CharBase::query()->select($allowedSortFields);
  41. // Если не запрошено with_deleted=true — возвращаем только активных персонажей (Deleted = 0)
  42. if (!$withDeleted) {
  43. $query->where('Deleted', 0);
  44. }
  45. if ($search !== '') {
  46. $query->where(function ($q) use ($search) {
  47. $q->where('Name', 'like', "%{$search}%")
  48. ->orWhere('AccountName', 'like', "%{$search}%");
  49. if (ctype_digit($search)) {
  50. $q->orWhere('DBKey', (int) $search);
  51. }
  52. });
  53. }
  54. // 3. Сортировка и пагинация
  55. $charactersPaginator = $query->orderBy($sortField, $sortOrder)->paginate($perPage);
  56. // 4. Ответ
  57. // Если по запросу не найдено ни одного персонажа, возвращаем специальный ответ
  58. // для сохранения обратной совместимости API.
  59. if ($charactersPaginator->total() === 0) {
  60. return response()->json([
  61. 'characters' => (object) [],
  62. 'code' => -2,
  63. 'msg' => 'Characters not found.'
  64. ], 200);
  65. }
  66. // Laravel автоматически преобразует пагинатор в корректный JSON,
  67. // включая только выбранные через select() поля.
  68. return response()->json([
  69. 'code' => 0,
  70. 'msg' => 'Characters successfully received.',
  71. 'characters' => $charactersPaginator,
  72. ], 200);
  73. }
  74. /**
  75. * Получение всех персонажей пользователя по имени пользователя. *
  76. * (по умолчанию - только активные персонажи, если в запросе with_deleted=true - в том числе удаленные персонажи)
  77. *
  78. * @param string $username
  79. * @return \Illuminate\Http\JsonResponse
  80. */
  81. public function GetUserCharacters($username)
  82. {
  83. // Флаг: включать ли удаленных персонажей (with_deleted=true/1/on/yes)
  84. $withDeleted = request()->boolean('with_deleted');
  85. // Получаем всех персонажей по $username
  86. $characters = CharBase::where('AccountName', $username)
  87. ->when(!$withDeleted, function ($q) {
  88. // Если не запрошены удаленные персонажи — фильтруем только активных
  89. $q->where('Deleted', 0);
  90. })
  91. ->get();
  92. // Проверяем, найдены ли персонажи
  93. if ($characters->isEmpty()) {
  94. return response()->json(['characters' => [], 'code' => -2, 'msg' => 'Characters not found for this user.'], 200);
  95. }
  96. // Подсчитываем общее время в игре для всех персонажей пользователя
  97. $totalPlayTime = $characters->sum('TotalPlayTime');
  98. // Возвращаем только DBKey, Name, Level, GuildDBKey, TotalPlayTime, Deleted для всех персонажей
  99. $characters = $characters->map(function ($character) {
  100. return [
  101. 'DBKey' => $character->DBKey,
  102. 'Name' => $character->Name,
  103. 'Level' => $character->Level,
  104. 'GuildDBKey' => $character->GuildDBKey,
  105. 'CharPlayTime' => $character->TotalPlayTime,
  106. 'Deleted' => $character->Deleted,
  107. ];
  108. });
  109. return response()->json([
  110. 'code' => 0,
  111. 'msg' => 'Characters successfully received.',
  112. 'characters' => $characters,
  113. 'totalPlayTime' => $totalPlayTime
  114. ], 200);
  115. }
  116. /**
  117. * Отправка предмета на персонажа.
  118. *
  119. * @param \Illuminate\Http\Request $request
  120. * @return \Illuminate\Http\JsonResponse
  121. */
  122. public function SendItemToCharacter(Request $request)
  123. {
  124. $character = CharBase::where('DBKey', $request->Owner)->first();
  125. if (!$character) {
  126. return response()->json(['code' => -1, 'msg' => 'Character not found.'], 404);
  127. }
  128. $validator = \Validator::make($request->all(), [
  129. 'Owner' => 'required',
  130. 'Kind' => 'required',
  131. 'RecId' => 'required',
  132. 'Amount' => 'required|numeric',
  133. 'Period' => 'required|numeric',
  134. 'evPType' => 'required',
  135. 'Comment' => 'required'
  136. ], [], [
  137. 'Owner' => '',
  138. 'Kind' => '',
  139. 'RecId' => '',
  140. 'Amount' => '',
  141. 'Period' => '',
  142. 'evPType' => '',
  143. 'Comment' => ''
  144. ]);
  145. if (!$validator->passes())
  146. return response()->json(['code' => -1, 'msg' => $validator->errors()], 400);
  147. CharCashItem_OutputBox::SENDITEMOUTPUTBOX($request);
  148. return response()->json([
  149. 'code' => 0,
  150. 'msg' => 'Items successfully sent.'
  151. ], 200);
  152. }
  153. /**
  154. * Получение всех данных персонажа из указанной таблицы.
  155. *
  156. * @param int $char_id
  157. * @param string $table_name
  158. * @return \Illuminate\Http\JsonResponse
  159. */
  160. public function GetCharacterData($char_id, $table_name)
  161. {
  162. // Получаем конфигурацию таблицы через приватный метод
  163. $config = $this->resolveTable($table_name);
  164. if (!$config) {
  165. return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
  166. }
  167. $modelClass = $config['model'];
  168. $key = $config['key'];
  169. // Проверяем существование персонажа
  170. if (!CharBase::find($char_id)) {
  171. return response()->json(['code' => -2, 'msg' => 'Character not found.'], 404);
  172. }
  173. // Получаем данные
  174. $data = $modelClass::where($key, $char_id)->get();
  175. if ($data->isEmpty()) {
  176. return response()->json(['code' => -3, 'msg' => 'No data found for this character in the specified table.'], 200);
  177. }
  178. return response()->json([
  179. 'code' => 0,
  180. 'msg' => 'Data successfully received.',
  181. 'data' => $data
  182. ], 200);
  183. }
  184. /**
  185. * Обновление данных персонажа в указанной таблице.
  186. *
  187. * @param Request $request
  188. * @param int $char_id
  189. * @param string $table_name
  190. * @return \Illuminate\Http\JsonResponse
  191. */
  192. public function UpdateCharacterData(Request $request, $char_id, $table_name)
  193. {
  194. // 1. Получаем конфигурацию таблицы через приватный метод
  195. $config = $this->resolveTable($table_name);
  196. if (!$config) {
  197. return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
  198. }
  199. $modelClass = $config['model'];
  200. $ownerKey = $config['key']; // Ключ, по которому связывается с CharBase - id персонажа
  201. $primaryKey = $config['pk']; // Для CharBase - DBKey
  202. // 2. Определяем, какую запись обновляем
  203. if ($table_name === 'CharBase') {
  204. $model = $modelClass::find($char_id);
  205. } else {
  206. $recordId = $request->input($primaryKey);
  207. if (!$recordId) {
  208. return response()->json(['code' => -4, 'msg' => "Primary key '$primaryKey' is required for this table."], 400);
  209. }
  210. $model = $modelClass::find($recordId);
  211. }
  212. if (!$model) {
  213. return response()->json(['code' => -2, 'msg' => 'Record not found.'], 404);
  214. }
  215. // Проверяем принадлежность записи персонажу
  216. if ($model->{$ownerKey} != $char_id) {
  217. return response()->json(['code' => -5, 'msg' => 'Record does not belong to the character.'], 403);
  218. }
  219. // 3. Подготавливаем данные к обновлению – защищаем PK и владение
  220. $data = $request->except([$primaryKey, $ownerKey, 'DBKey', 'Owner', 'Account']);
  221. // 4. Обновляем модель и возвращаем ответ
  222. return $this->_updateAndRespond($model, $data);
  223. }
  224. /**
  225. * Получает конкретный предмет по $char_item_id из указанной таблицы $table предметов.
  226. *
  227. * @param string $table
  228. * @param int $char_item_id
  229. * @return \Illuminate\Http\JsonResponse
  230. */
  231. public function GetCharItem(string $table, int $char_item_id)
  232. {
  233. // Получаем конфигурацию таблицы (модель и первичный ключ)
  234. $config = $this->resolveTable($table);
  235. if (!$config) {
  236. return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
  237. }
  238. $modelClass = $config['model'];
  239. $pk = $config['pk'];
  240. // Ищем предмет по первичному ключу из конфигурации
  241. $item = $modelClass::where($pk, $char_item_id)->first();
  242. if (!$item) {
  243. return response()->json([
  244. 'code' => -2,
  245. 'msg' => 'Item not found.',
  246. ], 404);
  247. }
  248. return response()->json([
  249. 'code' => 0,
  250. 'msg' => 'Item successfully received.',
  251. 'data' => $item,
  252. ], 200);
  253. }
  254. /**
  255. * Обновляет конкретный предмет по $char_item_id в указанной таблице $table предметов.
  256. *
  257. * @param \Illuminate\Http\Request $request
  258. * @param string $table
  259. * @param int $char_item_id
  260. * @return \Illuminate\Http\JsonResponse
  261. */
  262. public function UpdateCharItem(Request $request, string $table, int $char_item_id)
  263. {
  264. // Получаем конфигурацию таблицы (модель и первичный ключ)
  265. $config = $this->resolveTable($table);
  266. if (!$config) {
  267. return response()->json(['code' => -1, 'msg' => 'Table not allowed or does not exist.'], 400);
  268. }
  269. $modelClass = $config['model'];
  270. $pk = $config['pk'];
  271. // Ищем предмет по первичному ключу из конфигурации
  272. $item = $modelClass::where($pk, $char_item_id)->first();
  273. if (!$item) {
  274. return response()->json([
  275. 'code' => -2,
  276. 'msg' => 'Item not found.',
  277. ], 404);
  278. }
  279. // Определяем защищённые поля динамически, чтобы не дать изменить PK и владельца
  280. $protected = [$pk, 'Owner', 'Account'];
  281. $data = $request->except($protected);
  282. return $this->_updateAndRespond($item, $data, 'Item successfully updated.');
  283. }
  284. /**
  285. * Получение квеста персонажа по char_id и RecId.
  286. * Поддерживается выбор таблицы (CharQuest или CharQuest_History) через опциональный параметр $table.
  287. *
  288. * @param string $char_id
  289. * @param string $rec_id
  290. * @param string|null $table
  291. * @return \Illuminate\Http\JsonResponse
  292. */
  293. public function GetCharQuest(string $char_id, string $rec_id, ?string $table = null)
  294. {
  295. // По умолчанию используем CharQuest
  296. $table = $table ?? 'CharQuest';
  297. // Проверяем допустимость таблицы для данной операции
  298. $allowedQuestTables = ['CharQuest', 'CharQuest_History'];
  299. if (!in_array($table, $allowedQuestTables, true)) {
  300. return response()->json(['code' => -1, 'msg' => 'Table not allowed for this operation.'], 400);
  301. }
  302. // Проверяем существование персонажа
  303. if (!CharBase::find($char_id)) {
  304. return response()->json(['code' => -2, 'msg' => 'Character not found.'], 404);
  305. }
  306. // Получаем конфиг модели по таблице и делаем выборку по Owner и RecId
  307. $config = $this->resolveTable($table);
  308. $modelClass = $config['model'];
  309. $quest = $modelClass::where('Owner', $char_id)
  310. ->where('RecId', $rec_id)
  311. ->first();
  312. if (!$quest) {
  313. return response()->json([
  314. 'code' => -3,
  315. 'msg' => 'Quest not found for this character.',
  316. ], 404);
  317. }
  318. return response()->json([
  319. 'code' => 0,
  320. 'msg' => 'Quest successfully received.',
  321. 'data' => $quest,
  322. ], 200);
  323. }
  324. /**
  325. * Обновление квеста персонажа по char_id и RecId.
  326. * Поддерживается выбор таблицы (CharQuest или CharQuest_History) через опциональный параметр $table.
  327. *
  328. * @param \Illuminate\Http\Request $request
  329. * @param string $char_id
  330. * @param string $rec_id
  331. * @param string|null $table
  332. * @return \Illuminate\Http\JsonResponse
  333. */
  334. public function UpdateCharQuest(Request $request, string $char_id, string $rec_id, ?string $table = null)
  335. {
  336. // По умолчанию используем CharQuest
  337. $table = $table ?? 'CharQuest';
  338. // Проверяем допустимость таблицы для данной операции
  339. $allowedQuestTables = ['CharQuest', 'CharQuest_History'];
  340. if (!in_array($table, $allowedQuestTables, true)) {
  341. return response()->json(['code' => -1, 'msg' => 'Table not allowed for this operation.'], 400);
  342. }
  343. // Проверяем существование персонажа
  344. if (!CharBase::find($char_id)) {
  345. return response()->json(['code' => -2, 'msg' => 'Character not found.'], 404);
  346. }
  347. // Получаем конфиг модели по таблице и делаем выборку по Owner и RecId
  348. $config = $this->resolveTable($table);
  349. $modelClass = $config['model'];
  350. $quest = $modelClass::where('Owner', $char_id)
  351. ->where('RecId', $rec_id)
  352. ->first();
  353. if (!$quest) {
  354. return response()->json([
  355. 'code' => -3,
  356. 'msg' => 'Quest not found for this character.',
  357. ], 404);
  358. }
  359. // Защищаем поля Owner и RecId от изменения
  360. $protected = ['Owner', 'RecId'];
  361. $data = $request->except($protected);
  362. return $this->_updateAndRespond($quest, $data, 'Quest successfully updated.');
  363. }
  364. //------------------------------ ПРИВАТНЫЕ МЕТОДЫ -----------------------------------------
  365. /**
  366. * Возвращает конфигурацию таблицы или null, если таблица не разрешена.
  367. *
  368. * @param string $table
  369. * @return array|null
  370. */
  371. private function resolveTable(string $table): ?array
  372. {
  373. return self::TABLES[$table] ?? null;
  374. }
  375. /**
  376. * Белый список доступных для обновления таблиц.
  377. * Используется в resolveTable(), GetCharacterData(), UpdateCharacterData().
  378. */
  379. private const TABLES = [
  380. 'CharBase' => ['key' => 'DBKey', 'model' => CharBase::class, 'pk' => 'DBKey'],
  381. 'CharItem' => ['key' => 'Owner', 'model' => CharItem::class, 'pk' => 'CharItemID'],
  382. 'CharFellow' => ['key' => 'Owner', 'model' => CharFellow::class, 'pk' => 'FellowID'],
  383. 'CharCashItem_OutputBox' => ['key' => 'Owner', 'model' => CharCashItem_OutputBox::class, 'pk' => 'ItemDBIndex'],
  384. 'CharQuest' => ['key' => 'Owner', 'model' => CharQuest::class, 'pk' => 'RecId'],
  385. 'CharQuest_History' => ['key' => 'Owner', 'model' => CharQuest_History::class, 'pk' => 'RecId'],
  386. ];
  387. /**
  388. * Общий метод для обновления модели и формирования ответа.
  389. *
  390. * @param \Illuminate\Database\Eloquent\Model $model
  391. * @param array $data
  392. * @param string $successMsg
  393. * @return \Illuminate\Http\JsonResponse
  394. */
  395. private function _updateAndRespond(\Illuminate\Database\Eloquent\Model $model, array $data, string $successMsg = 'Data successfully updated.')
  396. {
  397. // 1. Фильтруем поля для массового присвоения
  398. $fillable = $model->getFillable();
  399. $guarded = $model->getGuarded();
  400. if (!empty($fillable)) {
  401. // Если есть fillable - используем только их
  402. $filteredData = array_intersect_key($data, array_flip($fillable));
  403. } elseif ($guarded === ['*']) {
  404. // Если guarded = ['*'] - запрещено массовое присвоение
  405. return response()->json(['code' => -6, 'msg' => 'Mass assignment is not allowed for this model.'], 400);
  406. } else {
  407. // Если есть guarded (но не ['*']) - исключаем только guarded поля
  408. $filteredData = array_diff_key($data, array_flip($guarded));
  409. }
  410. // 2. Конвертируем null-поля в '', чтобы вместо NULL в БД сохранялась пустая строка
  411. $filteredData = array_map(static fn($v) => $v === null ? '' : $v, $filteredData);
  412. if (empty($filteredData)) {
  413. return response()->json(['code' => -6, 'msg' => 'No valid fields to update.'], 400);
  414. }
  415. // 3. Пытаемся обновить запись
  416. try {
  417. $ok = $model->update($filteredData);
  418. } catch (\Throwable $e) {
  419. Log::error('Database error while updating record:', ['error' => $e->getMessage()]);
  420. return response()->json([
  421. 'code' => -7,
  422. 'msg' => 'Database error while updating record.',
  423. 'error' => $e->getMessage(),
  424. ], 500);
  425. }
  426. if (!$ok) {
  427. return response()->json([
  428. 'code' => -8,
  429. 'msg' => 'Update failed, record not modified.',
  430. ], 500);
  431. }
  432. // 4. Возвращаем успешный ответ
  433. return response()->json([
  434. 'code' => 0,
  435. 'msg' => $successMsg,
  436. 'data' => $model->fresh()
  437. ], 200);
  438. }
  439. }