ItemController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. <?php
  2. namespace App\Controllers\Api;
  3. use CodeIgniter\HTTP\ResponseInterface;
  4. class ItemController extends BaseApiController
  5. {
  6. protected $format = 'json';
  7. protected $table = 'item';
  8. /**
  9. * 아이템 목록
  10. * GET /api/item/list
  11. */
  12. public function index()
  13. {
  14. $auth = $this->requireAuth();
  15. if ($auth instanceof ResponseInterface) {
  16. return $auth;
  17. }
  18. try {
  19. $page = (int) ($this->request->getGet('page') ?? 1);
  20. $perPage = (int) ($this->request->getGet('per_page') ?? 10);
  21. if ($page < 1) $page = 1;
  22. if ($perPage < 1) $perPage = 10;
  23. $offset = ($page - 1) * $perPage;
  24. $search = trim((string) $this->request->getGet('search'));
  25. $type = trim((string) $this->request->getGet('type'));
  26. $status = trim((string) $this->request->getGet('status'));
  27. $db = $this->getDB();
  28. $builder = $db->table($this->table);
  29. $builder->where('deleted_YN', 'N');
  30. if ($search !== '') {
  31. $builder->like('name', $search);
  32. }
  33. if (in_array($type, ['T', 'P', 'B'], true)) {
  34. $builder->where('type', $type);
  35. }
  36. if ($status === 'Y' || $status === 'N') {
  37. $builder->where('status_YN', $status);
  38. }
  39. $total = $builder->countAllResults(false);
  40. $items = $builder
  41. ->select('id, name, type, point, file_name, file_path, status_YN, created_at, updated_at')
  42. ->orderBy('id', 'DESC')
  43. ->limit($perPage, $offset)
  44. ->get()
  45. ->getResult();
  46. return $this->respondSuccess([
  47. 'items' => $items,
  48. 'total' => $total,
  49. 'page' => $page,
  50. 'per_page' => $perPage,
  51. 'total_pages' => (int) ceil($total / $perPage),
  52. ]);
  53. } catch (\Exception $e) {
  54. log_message('error', 'ItemController index error: ' . $e->getMessage());
  55. return $this->respondError('목록 조회 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  56. }
  57. }
  58. /**
  59. * 아이템 상세 조회
  60. * GET /api/item/:id
  61. */
  62. public function show($id = null)
  63. {
  64. $auth = $this->requireAuth();
  65. if ($auth instanceof ResponseInterface) {
  66. return $auth;
  67. }
  68. if (empty($id)) {
  69. return $this->respondError('ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  70. }
  71. try {
  72. $row = $this->getDB()->table($this->table)
  73. ->where('id', (int) $id)
  74. ->where('deleted_YN', 'N')
  75. ->get()
  76. ->getRow();
  77. if (!$row) {
  78. return $this->respondError('해당 아이템을 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  79. }
  80. return $this->respondSuccess($row);
  81. } catch (\Exception $e) {
  82. log_message('error', 'ItemController show error: ' . $e->getMessage());
  83. return $this->respondError('조회 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  84. }
  85. }
  86. /**
  87. * 아이템 수정 (텍스트 필드)
  88. * PUT /api/item/:id (JSON)
  89. */
  90. public function update($id = null)
  91. {
  92. $auth = $this->requireAuth();
  93. if ($auth instanceof ResponseInterface) {
  94. return $auth;
  95. }
  96. if (empty($id)) {
  97. return $this->respondError('ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  98. }
  99. try {
  100. $payload = $this->request->getJSON(true);
  101. if (!is_array($payload) || empty($payload)) {
  102. $payload = $this->request->getRawInput() ?? [];
  103. }
  104. $name = trim((string) ($payload['name'] ?? ''));
  105. $type = trim((string) ($payload['type'] ?? ''));
  106. $point = $payload['point'] ?? null;
  107. $status = trim((string) ($payload['status_YN'] ?? 'Y'));
  108. if ($name === '') {
  109. return $this->respondError('아이템명을 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  110. }
  111. if (mb_strlen($name) > 50) {
  112. return $this->respondError('아이템명은 50자 이내로 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  113. }
  114. if (!in_array($type, ['T', 'P', 'B'], true)) {
  115. return $this->respondError('구분을 선택하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  116. }
  117. $pointValue = null;
  118. if ($type === 'P') {
  119. if ($point === null || $point === '' || !is_numeric($point) || (int) $point < 0) {
  120. return $this->respondError('포인트를 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  121. }
  122. $pointValue = (int) $point;
  123. } elseif ($type === 'B') {
  124. if ($point !== null && $point !== '') {
  125. if (!is_numeric($point) || (int) $point < 0) {
  126. return $this->respondError('포인트는 0 이상의 숫자여야 합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  127. }
  128. $pointValue = (int) $point;
  129. }
  130. }
  131. $status = ($status === 'N') ? 'N' : 'Y';
  132. $db = $this->getDB();
  133. $exists = $db->table($this->table)
  134. ->where('id', (int) $id)->where('deleted_YN', 'N')->countAllResults();
  135. if ($exists === 0) {
  136. return $this->respondError('해당 아이템을 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  137. }
  138. $db->table($this->table)->where('id', (int) $id)->update([
  139. 'name' => $name,
  140. 'type' => $type,
  141. 'point' => $pointValue,
  142. 'status_YN' => $status,
  143. 'updated_at' => date('Y-m-d H:i:s'),
  144. ]);
  145. $row = $db->table($this->table)->where('id', (int) $id)->get()->getRow();
  146. return $this->respondSuccess($row, '아이템이 수정되었습니다.');
  147. } catch (\Exception $e) {
  148. log_message('error', 'ItemController update error: ' . $e->getMessage());
  149. return $this->respondError('수정 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  150. }
  151. }
  152. /**
  153. * 아이템 이미지 교체
  154. * POST /api/item/:id/image (multipart: image)
  155. */
  156. public function uploadImage($id = null)
  157. {
  158. $auth = $this->requireAuth();
  159. if ($auth instanceof ResponseInterface) {
  160. return $auth;
  161. }
  162. if (empty($id)) {
  163. return $this->respondError('ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  164. }
  165. try {
  166. $db = $this->getDB();
  167. $row = $db->table($this->table)
  168. ->where('id', (int) $id)->where('deleted_YN', 'N')->get()->getRow();
  169. if (!$row) {
  170. return $this->respondError('해당 아이템을 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  171. }
  172. $file = $this->request->getFile('image');
  173. if (!$file || !$file->isValid()) {
  174. return $this->respondError('이미지가 전송되지 않았습니다.', ResponseInterface::HTTP_BAD_REQUEST);
  175. }
  176. $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  177. $mime = $file->getMimeType();
  178. if (!in_array($mime, $allowed, true)) {
  179. return $this->respondError('이미지 형식이 올바르지 않습니다.', ResponseInterface::HTTP_BAD_REQUEST);
  180. }
  181. $uploadPath = FCPATH . 'uploads/item/';
  182. if (!is_dir($uploadPath)) {
  183. mkdir($uploadPath, 0755, true);
  184. }
  185. $fileName = $file->getClientName();
  186. $stored = $file->getRandomName();
  187. $file->move($uploadPath, $stored);
  188. // 기존 이미지 삭제
  189. if (!empty($row->file_path)) {
  190. $oldFull = FCPATH . ltrim($row->file_path, '/');
  191. if (is_file($oldFull)) @unlink($oldFull);
  192. }
  193. $db->table($this->table)->where('id', (int) $id)->update([
  194. 'file_name' => $fileName,
  195. 'file_path' => '/uploads/item/' . $stored,
  196. 'updated_at' => date('Y-m-d H:i:s'),
  197. ]);
  198. $updated = $db->table($this->table)->where('id', (int) $id)->get()->getRow();
  199. return $this->respondSuccess($updated, '이미지가 교체되었습니다.');
  200. } catch (\Exception $e) {
  201. log_message('error', 'ItemController uploadImage error: ' . $e->getMessage());
  202. return $this->respondError('이미지 업로드 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  203. }
  204. }
  205. /**
  206. * 아이템 이미지 제거
  207. * DELETE /api/item/:id/image
  208. */
  209. public function deleteImage($id = null)
  210. {
  211. $auth = $this->requireAuth();
  212. if ($auth instanceof ResponseInterface) {
  213. return $auth;
  214. }
  215. if (empty($id)) {
  216. return $this->respondError('ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  217. }
  218. try {
  219. $db = $this->getDB();
  220. $row = $db->table($this->table)
  221. ->where('id', (int) $id)->where('deleted_YN', 'N')->get()->getRow();
  222. if (!$row) {
  223. return $this->respondError('해당 아이템을 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  224. }
  225. if (!empty($row->file_path)) {
  226. $full = FCPATH . ltrim($row->file_path, '/');
  227. if (is_file($full)) @unlink($full);
  228. }
  229. $db->table($this->table)->where('id', (int) $id)->update([
  230. 'file_name' => null,
  231. 'file_path' => null,
  232. 'updated_at' => date('Y-m-d H:i:s'),
  233. ]);
  234. return $this->respondSuccess(null, '이미지가 제거되었습니다.');
  235. } catch (\Exception $e) {
  236. log_message('error', 'ItemController deleteImage error: ' . $e->getMessage());
  237. return $this->respondError('이미지 제거 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  238. }
  239. }
  240. /**
  241. * 아이템 삭제 (soft delete)
  242. * DELETE /api/item/:id
  243. */
  244. public function delete($id = null)
  245. {
  246. $auth = $this->requireAuth();
  247. if ($auth instanceof ResponseInterface) {
  248. return $auth;
  249. }
  250. if (empty($id)) {
  251. return $this->respondError('ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  252. }
  253. try {
  254. $db = $this->getDB();
  255. $exists = $db->table($this->table)
  256. ->where('id', (int) $id)->where('deleted_YN', 'N')->countAllResults();
  257. if ($exists === 0) {
  258. return $this->respondError('해당 아이템을 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  259. }
  260. $db->table($this->table)->where('id', (int) $id)->update([
  261. 'deleted_YN' => 'Y',
  262. 'updated_at' => date('Y-m-d H:i:s'),
  263. ]);
  264. return $this->respondSuccess(null, '아이템이 삭제되었습니다.');
  265. } catch (\Exception $e) {
  266. log_message('error', 'ItemController delete error: ' . $e->getMessage());
  267. return $this->respondError('삭제 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  268. }
  269. }
  270. /**
  271. * 아이템 등록
  272. * POST /api/item (multipart: name, type, point, status_YN, image)
  273. */
  274. public function create()
  275. {
  276. $auth = $this->requireAuth();
  277. if ($auth instanceof ResponseInterface) {
  278. return $auth;
  279. }
  280. try {
  281. $name = trim((string) $this->request->getPost('name'));
  282. $type = trim((string) $this->request->getPost('type')); // T(진출권) / P(포인트) / B(뱃지)
  283. $point = $this->request->getPost('point');
  284. $status = trim((string) $this->request->getPost('status_YN'));
  285. $file = $this->request->getFile('image');
  286. // 필수 검증
  287. if ($name === '') {
  288. return $this->respondError('아이템명을 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  289. }
  290. if (mb_strlen($name) > 50) {
  291. return $this->respondError('아이템명은 50자 이내로 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  292. }
  293. if (!in_array($type, ['T', 'P', 'B'], true)) {
  294. return $this->respondError('구분을 선택하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  295. }
  296. // type 별 포인트 처리
  297. // T(진출권): 포인트 무시 (null), P(포인트): 필수 + 양수, B(뱃지): 선택
  298. $pointValue = null;
  299. if ($type === 'P') {
  300. if ($point === null || $point === '' || !is_numeric($point) || (int) $point < 0) {
  301. return $this->respondError('포인트를 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  302. }
  303. $pointValue = (int) $point;
  304. } elseif ($type === 'B') {
  305. if ($point !== null && $point !== '') {
  306. if (!is_numeric($point) || (int) $point < 0) {
  307. return $this->respondError('포인트는 0 이상의 숫자여야 합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  308. }
  309. $pointValue = (int) $point;
  310. }
  311. }
  312. $status = ($status === 'N') ? 'N' : 'Y';
  313. // 이미지 업로드 (선택)
  314. $fileName = null;
  315. $filePath = null;
  316. if ($file && $file->isValid()) {
  317. $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  318. $mime = $file->getMimeType();
  319. if (!in_array($mime, $allowed, true)) {
  320. return $this->respondError('이미지 형식이 올바르지 않습니다. (JPG/PNG/GIF/WebP)', ResponseInterface::HTTP_BAD_REQUEST);
  321. }
  322. $uploadPath = FCPATH . 'uploads/item/';
  323. if (!is_dir($uploadPath)) {
  324. mkdir($uploadPath, 0755, true);
  325. }
  326. $fileName = $file->getClientName();
  327. $stored = $file->getRandomName();
  328. $file->move($uploadPath, $stored);
  329. $filePath = '/uploads/item/' . $stored;
  330. }
  331. $insertData = [
  332. 'name' => $name,
  333. 'type' => $type,
  334. 'point' => $pointValue,
  335. 'file_name' => $fileName,
  336. 'file_path' => $filePath,
  337. 'status_YN' => $status,
  338. 'created_at' => date('Y-m-d H:i:s'),
  339. ];
  340. $db = $this->getDB();
  341. if (!$db->table($this->table)->insert($insertData)) {
  342. return $this->respondError('등록에 실패했습니다.', ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  343. }
  344. $newId = $db->insertID();
  345. $row = $db->table($this->table)->where('id', $newId)->get()->getRow();
  346. return $this->respondSuccess($row, '아이템이 등록되었습니다.', ResponseInterface::HTTP_CREATED);
  347. } catch (\Exception $e) {
  348. log_message('error', 'ItemController create error: ' . $e->getMessage());
  349. return $this->respondError('등록 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  350. }
  351. }
  352. }