OnboardController.php 23 KB

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