OnboardController.php 22 KB

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