FishingController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. <?php
  2. namespace App\Controllers\Api;
  3. use CodeIgniter\HTTP\ResponseInterface;
  4. class FishingController extends BaseApiController
  5. {
  6. protected $format = 'json';
  7. protected $table = 'fishing';
  8. /**
  9. * 낚시터 목록
  10. * GET /api/fishing/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. $searchField = trim((string) $this->request->getGet('search_field')); // '', field, area, name, fish_species
  25. $search = trim((string) $this->request->getGet('search'));
  26. $partnership = trim((string) $this->request->getGet('partnership'));
  27. $status = trim((string) $this->request->getGet('status'));
  28. $startDate = trim((string) $this->request->getGet('start_date'));
  29. $endDate = trim((string) $this->request->getGet('end_date'));
  30. $db = $this->getDB();
  31. $builder = $db->table($this->table . ' fs');
  32. $builder->join('fishing_field f', 'f.id = fs.field_id', 'left');
  33. $builder->join('fishing_area a', 'a.id = fs.area_id', 'left');
  34. $builder->where('fs.deleted_YN', 'N');
  35. if ($search !== '') {
  36. if ($searchField === 'field') {
  37. $builder->like('f.name', $search);
  38. } elseif ($searchField === 'area') {
  39. $builder->like('a.name', $search);
  40. } elseif ($searchField === 'name') {
  41. $builder->like('fs.name', $search);
  42. } elseif ($searchField === 'fish_species') {
  43. $builder->like('fs.fish_species', $search);
  44. } else {
  45. // 전체: 분야 / 지역명 / 낚시터명 / 어종
  46. $builder->groupStart()
  47. ->like('f.name', $search)
  48. ->orLike('a.name', $search)
  49. ->orLike('fs.name', $search)
  50. ->orLike('fs.fish_species', $search)
  51. ->groupEnd();
  52. }
  53. }
  54. if ($partnership === 'Y' || $partnership === 'N') {
  55. $builder->where('fs.partnership_YN', $partnership);
  56. }
  57. if ($status === 'Y' || $status === 'N') {
  58. $builder->where('fs.status_YN', $status);
  59. }
  60. if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $startDate)) {
  61. $builder->where('fs.created_at >=', $startDate . ' 00:00:00');
  62. }
  63. if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $endDate)) {
  64. $builder->where('fs.created_at <=', $endDate . ' 23:59:59');
  65. }
  66. $total = $builder->countAllResults(false);
  67. // 계좌번호는 목록에서 제외 (민감정보)
  68. $items = $builder
  69. ->select('fs.id, fs.name, fs.field_id, fs.area_id, fs.operating_hours, fs.fish_species, fs.address, fs.partnership_YN, fs.status_YN, fs.created_at, f.name as field_name, a.name as area_name')
  70. ->orderBy('fs.id', 'DESC')
  71. ->limit($perPage, $offset)
  72. ->get()
  73. ->getResult();
  74. return $this->respondSuccess([
  75. 'items' => $items,
  76. 'total' => $total,
  77. 'page' => $page,
  78. 'per_page' => $perPage,
  79. 'total_pages' => (int) ceil($total / $perPage),
  80. ]);
  81. } catch (\Exception $e) {
  82. log_message('error', 'FishingController index error: ' . $e->getMessage());
  83. return $this->respondError('목록 조회 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  84. }
  85. }
  86. /**
  87. * 낚시터 등록
  88. * POST /api/fishing
  89. */
  90. public function create()
  91. {
  92. $auth = $this->requireAuth();
  93. if ($auth instanceof ResponseInterface) {
  94. return $auth;
  95. }
  96. try {
  97. $payload = $this->request->getJSON(true);
  98. if (!is_array($payload) || empty($payload)) {
  99. $payload = $this->request->getPost() ?? [];
  100. }
  101. $fieldId = (int) ($payload['field_id'] ?? 0);
  102. $areaId = (int) ($payload['area_id'] ?? 0);
  103. $name = trim((string) ($payload['name'] ?? ''));
  104. // 필수값 검증
  105. if ($fieldId <= 0) {
  106. return $this->respondError('분야를 선택하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  107. }
  108. if ($areaId <= 0) {
  109. return $this->respondError('지역을 선택하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  110. }
  111. if ($name === '') {
  112. return $this->respondError('낚시터명을 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  113. }
  114. if (mb_strlen($name) > 100) {
  115. return $this->respondError('낚시터명은 100자 이내로 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  116. }
  117. $db = $this->getDB();
  118. // 분야 / 지역 존재 확인
  119. $fieldExists = $db->table('fishing_field')
  120. ->where('id', $fieldId)->where('deleted_YN', 'N')->countAllResults();
  121. if ($fieldExists === 0) {
  122. return $this->respondError('존재하지 않는 분야입니다.', ResponseInterface::HTTP_BAD_REQUEST);
  123. }
  124. $areaExists = $db->table('fishing_area')
  125. ->where('id', $areaId)->where('deleted_YN', 'N')->countAllResults();
  126. if ($areaExists === 0) {
  127. return $this->respondError('존재하지 않는 지역입니다.', ResponseInterface::HTTP_BAD_REQUEST);
  128. }
  129. $partnership = (($payload['partnership_YN'] ?? 'N') === 'Y') ? 'Y' : 'N';
  130. $status = (($payload['status_YN'] ?? 'Y') === 'N') ? 'N' : 'Y';
  131. $insertData = [
  132. 'field_id' => $fieldId,
  133. 'area_id' => $areaId,
  134. 'name' => $name,
  135. 'operating_hours' => trim((string) ($payload['operating_hours'] ?? '')),
  136. 'fish_species' => trim((string) ($payload['fish_species'] ?? '')),
  137. 'zip_code' => trim((string) ($payload['zip_code'] ?? '')),
  138. 'address' => trim((string) ($payload['address'] ?? '')),
  139. 'address_detail' => trim((string) ($payload['address_detail'] ?? '')),
  140. 'address_refer' => trim((string) ($payload['address_refer'] ?? '')),
  141. 'lat' => trim((string) ($payload['lat'] ?? '')),
  142. 'lng' => trim((string) ($payload['lng'] ?? '')),
  143. 'partnership_YN' => $partnership,
  144. 'status_YN' => $status,
  145. 'created_at' => date('Y-m-d H:i:s'),
  146. ];
  147. // 제휴인 경우에만 계좌 정보 저장 (계좌번호 양방향 암호화)
  148. if ($partnership === 'Y') {
  149. $insertData['bank_code'] = trim((string) ($payload['bank_code'] ?? ''));
  150. $insertData['account_number'] = $this->encryptValue(trim((string) ($payload['account_number'] ?? '')));
  151. $insertData['account_holder'] = trim((string) ($payload['account_holder'] ?? ''));
  152. } else {
  153. $insertData['bank_code'] = '';
  154. $insertData['account_number'] = '';
  155. $insertData['account_holder'] = '';
  156. }
  157. if (!$db->table($this->table)->insert($insertData)) {
  158. return $this->respondError('등록에 실패했습니다.', ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  159. }
  160. $newId = $db->insertID();
  161. $row = $db->table($this->table)->where('id', $newId)->get()->getRow();
  162. if ($row) {
  163. $row->account_number = $this->decryptValue($row->account_number);
  164. }
  165. return $this->respondSuccess($row, '낚시터가 등록되었습니다.', ResponseInterface::HTTP_CREATED);
  166. } catch (\Exception $e) {
  167. log_message('error', 'FishingController create error: ' . $e->getMessage());
  168. return $this->respondError('등록 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  169. }
  170. }
  171. /**
  172. * 낚시터 상세 조회
  173. * GET /api/fishing/:id
  174. */
  175. public function show($id = null)
  176. {
  177. $auth = $this->requireAuth();
  178. if ($auth instanceof ResponseInterface) {
  179. return $auth;
  180. }
  181. if (empty($id)) {
  182. return $this->respondError('ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  183. }
  184. try {
  185. $row = $this->getDB()->table($this->table . ' fs')
  186. ->select('fs.*, f.name as field_name, a.name as area_name')
  187. ->join('fishing_field f', 'f.id = fs.field_id', 'left')
  188. ->join('fishing_area a', 'a.id = fs.area_id', 'left')
  189. ->where('fs.id', (int) $id)
  190. ->where('fs.deleted_YN', 'N')
  191. ->get()
  192. ->getRow();
  193. if (!$row) {
  194. return $this->respondError('해당 낚시터를 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  195. }
  196. $row->account_number = $this->decryptValue($row->account_number);
  197. $row->photos = $this->getDB()->table('fishing_photos')
  198. ->where('fishing_id', (int) $id)
  199. ->orderBy('sort_order', 'ASC')
  200. ->orderBy('id', 'ASC')
  201. ->get()
  202. ->getResult();
  203. return $this->respondSuccess($row);
  204. } catch (\Exception $e) {
  205. log_message('error', 'FishingController show error: ' . $e->getMessage());
  206. return $this->respondError('조회 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  207. }
  208. }
  209. /**
  210. * 낚시터 수정
  211. * PUT /api/fishing/:id
  212. */
  213. public function update($id = null)
  214. {
  215. $auth = $this->requireAuth();
  216. if ($auth instanceof ResponseInterface) {
  217. return $auth;
  218. }
  219. if (empty($id)) {
  220. return $this->respondError('ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  221. }
  222. try {
  223. $payload = $this->request->getJSON(true);
  224. if (!is_array($payload) || empty($payload)) {
  225. $payload = $this->request->getRawInput() ?? [];
  226. }
  227. $fieldId = (int) ($payload['field_id'] ?? 0);
  228. $areaId = (int) ($payload['area_id'] ?? 0);
  229. $name = trim((string) ($payload['name'] ?? ''));
  230. if ($fieldId <= 0) return $this->respondError('분야를 선택하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  231. if ($areaId <= 0) return $this->respondError('지역을 선택하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  232. if ($name === '') return $this->respondError('낚시터명을 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  233. if (mb_strlen($name) > 100) return $this->respondError('낚시터명은 100자 이내로 입력하세요.', ResponseInterface::HTTP_BAD_REQUEST);
  234. $db = $this->getDB();
  235. $exists = $db->table($this->table)
  236. ->where('id', (int) $id)->where('deleted_YN', 'N')->countAllResults();
  237. if ($exists === 0) {
  238. return $this->respondError('해당 낚시터를 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  239. }
  240. $fieldExists = $db->table('fishing_field')
  241. ->where('id', $fieldId)->where('deleted_YN', 'N')->countAllResults();
  242. if ($fieldExists === 0) return $this->respondError('존재하지 않는 분야입니다.', ResponseInterface::HTTP_BAD_REQUEST);
  243. $areaExists = $db->table('fishing_area')
  244. ->where('id', $areaId)->where('deleted_YN', 'N')->countAllResults();
  245. if ($areaExists === 0) return $this->respondError('존재하지 않는 지역입니다.', ResponseInterface::HTTP_BAD_REQUEST);
  246. $partnership = (($payload['partnership_YN'] ?? 'N') === 'Y') ? 'Y' : 'N';
  247. $status = (($payload['status_YN'] ?? 'Y') === 'N') ? 'N' : 'Y';
  248. $updateData = [
  249. 'field_id' => $fieldId,
  250. 'area_id' => $areaId,
  251. 'name' => $name,
  252. 'operating_hours' => trim((string) ($payload['operating_hours'] ?? '')),
  253. 'fish_species' => trim((string) ($payload['fish_species'] ?? '')),
  254. 'zip_code' => trim((string) ($payload['zip_code'] ?? '')),
  255. 'address' => trim((string) ($payload['address'] ?? '')),
  256. 'address_detail' => trim((string) ($payload['address_detail'] ?? '')),
  257. 'address_refer' => trim((string) ($payload['address_refer'] ?? '')),
  258. 'lat' => trim((string) ($payload['lat'] ?? '')),
  259. 'lng' => trim((string) ($payload['lng'] ?? '')),
  260. 'partnership_YN' => $partnership,
  261. 'status_YN' => $status,
  262. 'updated_at' => date('Y-m-d H:i:s'),
  263. ];
  264. if ($partnership === 'Y') {
  265. $updateData['bank_code'] = trim((string) ($payload['bank_code'] ?? ''));
  266. $updateData['account_number'] = $this->encryptValue(trim((string) ($payload['account_number'] ?? '')));
  267. $updateData['account_holder'] = trim((string) ($payload['account_holder'] ?? ''));
  268. } else {
  269. $updateData['bank_code'] = '';
  270. $updateData['account_number'] = '';
  271. $updateData['account_holder'] = '';
  272. }
  273. $db->table($this->table)->where('id', (int) $id)->update($updateData);
  274. $row = $db->table($this->table)->where('id', (int) $id)->get()->getRow();
  275. if ($row) $row->account_number = $this->decryptValue($row->account_number);
  276. return $this->respondSuccess($row, '낚시터가 수정되었습니다.');
  277. } catch (\Exception $e) {
  278. log_message('error', 'FishingController update error: ' . $e->getMessage());
  279. return $this->respondError('수정 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  280. }
  281. }
  282. /**
  283. * 낚시터 삭제 (soft delete)
  284. * DELETE /api/fishing/:id
  285. */
  286. public function delete($id = null)
  287. {
  288. $auth = $this->requireAuth();
  289. if ($auth instanceof ResponseInterface) {
  290. return $auth;
  291. }
  292. if (empty($id)) {
  293. return $this->respondError('ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  294. }
  295. try {
  296. $db = $this->getDB();
  297. $exists = $db->table($this->table)
  298. ->where('id', (int) $id)->where('deleted_YN', 'N')->countAllResults();
  299. if ($exists === 0) {
  300. return $this->respondError('해당 낚시터를 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  301. }
  302. $db->table($this->table)
  303. ->where('id', (int) $id)
  304. ->update([
  305. 'deleted_YN' => 'Y',
  306. 'updated_at' => date('Y-m-d H:i:s'),
  307. ]);
  308. return $this->respondSuccess(null, '낚시터가 삭제되었습니다.');
  309. } catch (\Exception $e) {
  310. log_message('error', 'FishingController delete error: ' . $e->getMessage());
  311. return $this->respondError('삭제 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  312. }
  313. }
  314. /**
  315. * 낚시터 사진 삭제 (파일 + DB hard delete)
  316. * DELETE /api/fishing/photo/:photoId
  317. */
  318. public function deletePhoto($photoId = null)
  319. {
  320. $auth = $this->requireAuth();
  321. if ($auth instanceof ResponseInterface) {
  322. return $auth;
  323. }
  324. if (empty($photoId)) {
  325. return $this->respondError('사진 ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  326. }
  327. try {
  328. $db = $this->getDB();
  329. $photo = $db->table('fishing_photos')->where('id', (int) $photoId)->get()->getRow();
  330. if (!$photo) {
  331. return $this->respondError('해당 사진을 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  332. }
  333. $fullPath = FCPATH . ltrim($photo->file_path, '/');
  334. if (is_file($fullPath)) {
  335. @unlink($fullPath);
  336. }
  337. $db->table('fishing_photos')->where('id', (int) $photoId)->delete();
  338. return $this->respondSuccess(null, '사진이 삭제되었습니다.');
  339. } catch (\Exception $e) {
  340. log_message('error', 'FishingController deletePhoto error: ' . $e->getMessage());
  341. return $this->respondError('사진 삭제 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  342. }
  343. }
  344. /**
  345. * 낚시터 사진 업로드 (다중)
  346. * POST /api/fishing/:id/photos (multipart, photos[])
  347. */
  348. public function uploadPhotos($id = null)
  349. {
  350. $auth = $this->requireAuth();
  351. if ($auth instanceof ResponseInterface) {
  352. return $auth;
  353. }
  354. if (empty($id)) {
  355. return $this->respondError('낚시터 ID가 필요합니다.', ResponseInterface::HTTP_BAD_REQUEST);
  356. }
  357. try {
  358. $db = $this->getDB();
  359. $exists = $db->table($this->table)
  360. ->where('id', (int) $id)->where('deleted_YN', 'N')->countAllResults();
  361. if ($exists === 0) {
  362. return $this->respondError('해당 낚시터를 찾을 수 없습니다.', ResponseInterface::HTTP_NOT_FOUND);
  363. }
  364. $files = $this->request->getFileMultiple('photos');
  365. if (empty($files)) {
  366. return $this->respondError('업로드할 사진이 없습니다.', ResponseInterface::HTTP_BAD_REQUEST);
  367. }
  368. $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  369. $uploadPath = FCPATH . 'uploads/fishing/';
  370. if (!is_dir($uploadPath)) {
  371. mkdir($uploadPath, 0755, true);
  372. }
  373. $maxRow = $db->table('fishing_photos')
  374. ->selectMax('sort_order')
  375. ->where('fishing_id', (int) $id)
  376. ->get()->getRow();
  377. $order = $maxRow && $maxRow->sort_order !== null ? (int) $maxRow->sort_order + 1 : 0;
  378. $saved = [];
  379. foreach ($files as $file) {
  380. if (!$file->isValid()) continue;
  381. $mime = $file->getMimeType();
  382. if (!in_array($mime, $allowed, true)) continue;
  383. $originalName = $file->getClientName();
  384. $size = $file->getSize();
  385. $newName = $file->getRandomName();
  386. $file->move($uploadPath, $newName);
  387. $fullPath = $uploadPath . $newName;
  388. $width = null;
  389. $height = null;
  390. $info = @getimagesize($fullPath);
  391. if ($info) {
  392. $width = $info[0];
  393. $height = $info[1];
  394. }
  395. $photoData = [
  396. 'fishing_id' => (int) $id,
  397. 'original_name' => $originalName,
  398. 'stored_name' => $newName,
  399. 'file_path' => '/uploads/fishing/' . $newName,
  400. 'file_size' => $size,
  401. 'mime_type' => $mime,
  402. 'width' => $width,
  403. 'height' => $height,
  404. 'sort_order' => $order,
  405. 'created_at' => date('Y-m-d H:i:s'),
  406. ];
  407. $db->table('fishing_photos')->insert($photoData);
  408. $photoData['id'] = $db->insertID();
  409. $saved[] = $photoData;
  410. $order++;
  411. }
  412. if (empty($saved)) {
  413. return $this->respondError('유효한 이미지 파일이 없습니다. (JPG/PNG/GIF/WebP만 허용)', ResponseInterface::HTTP_BAD_REQUEST);
  414. }
  415. return $this->respondSuccess($saved, count($saved) . '장의 사진이 업로드되었습니다.', ResponseInterface::HTTP_CREATED);
  416. } catch (\Exception $e) {
  417. log_message('error', 'FishingController uploadPhotos error: ' . $e->getMessage());
  418. return $this->respondError('사진 업로드 중 오류가 발생했습니다: ' . $e->getMessage(), ResponseInterface::HTTP_INTERNAL_SERVER_ERROR);
  419. }
  420. }
  421. /** 값 암호화 (빈 값은 그대로 빈 문자열) */
  422. private function encryptValue(string $plain): string
  423. {
  424. if ($plain === '') return '';
  425. $encrypter = \Config\Services::encrypter();
  426. return base64_encode($encrypter->encrypt($plain));
  427. }
  428. /** 값 복호화 (실패/빈 값이면 빈 문자열) */
  429. private function decryptValue(?string $cipher): string
  430. {
  431. if (empty($cipher)) return '';
  432. try {
  433. $encrypter = \Config\Services::encrypter();
  434. return $encrypter->decrypt(base64_decode($cipher));
  435. } catch (\Exception $e) {
  436. log_message('error', 'Account decrypt error: ' . $e->getMessage());
  437. return '';
  438. }
  439. }
  440. }