OnboardController.php 23 KB

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