Deli.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. <?php
  2. namespace App\Controllers;
  3. use CodeIgniter\RESTful\ResourceController;
  4. class Deli extends ResourceController
  5. {
  6. // New: 공동구매 주문 내역 리스트
  7. public function orderList()
  8. {
  9. $db = \Config\Database::connect();
  10. $request = $this->request->getJSON(true);
  11. $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
  12. $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
  13. $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
  14. $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
  15. // ITEM_ORDER_LIST와 ITEM_LIST를 JOIN해서 주문 목록 조회
  16. $builder = $db->table('ITEM_ORDER_LIST IOL')
  17. ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2, IL.TYPE as ITEM_TYPE, IL.THUMB_FILE')
  18. ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
  19. ->where('IL.DEL_YN', 'N'); // 삭제되지 않은 아이템만
  20. // 아이템 타입 필터링
  21. if (!empty($itemType)) {
  22. $builder->where('IL.TYPE', $itemType);
  23. }
  24. // 사용자 타입에 따른 필터링
  25. if ($memberType === 'VENDOR' && !empty($companyNumber)) {
  26. // 벤더사: 자사 아이템의 주문만
  27. $builder->where('IL.COMPANY_NUMBER', $companyNumber);
  28. } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
  29. // 인플루언서: 자신이 담당하는 주문만
  30. $builder->where('IOL.INF_SEQ', $infSeq);
  31. } elseif ($memberType === 'BRAND' && !empty($infSeq)) {
  32. // 브랜드사: 자사가 담당하는 아이템의 주문만
  33. $builder->where('IL.CONTACT_BRD', $infSeq);
  34. }
  35. // 주문일 기준으로 최신순 정렬
  36. $builder->orderBy('IOL.ORDER_DATE', 'DESC');
  37. $lists = $builder->get()->getResultArray();
  38. return $this->respond($lists, 200);
  39. }
  40. // New: 공동구매 주문 내역 등록/업데이트
  41. public function orderRegister()
  42. {
  43. // 한국 시간으로 설정
  44. date_default_timezone_set('Asia/Seoul');
  45. $db = \Config\Database::connect();
  46. $request = $this->request->getJSON(true);
  47. $itemSeq = isset($request['item_seq']) ? $request['item_seq'] : null;
  48. $infSeq = isset($request['inf_seq']) ? $request['inf_seq'] : null;
  49. $orderList = $request['orderList'] ?? [];
  50. if (!$itemSeq) {
  51. return $this->fail('필수 파라미터가 누락되었습니다.', 400);
  52. }
  53. // orderList가 비어있으면 해당 item_seq의 모든 데이터 삭제만 수행
  54. if (empty($orderList)) {
  55. $db->transBegin();
  56. try {
  57. // 기존 데이터 모두 삭제
  58. $deletedCount = $db->table('ITEM_ORDER_LIST')
  59. ->where('ITEM_SEQ', $itemSeq)
  60. ->delete();
  61. $db->transCommit();
  62. return $this->respond([
  63. 'message' => '주문 내역이 성공적으로 처리되었습니다.',
  64. 'updated_count' => 0,
  65. 'new_count' => 0,
  66. 'deleted_count' => $deletedCount,
  67. 'errors' => []
  68. ], 200);
  69. } catch (\Exception $e) {
  70. $db->transRollback();
  71. return $this->fail('주문 내역 처리 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
  72. }
  73. }
  74. // 빈 데이터나 변경사항 없는 경우 먼저 체크
  75. $hasValidData = false;
  76. foreach ($orderList as $order) {
  77. if (!empty($order['ORDER_NUMB']) && !empty($order['BUYER_NAME'])) {
  78. $hasValidData = true;
  79. break;
  80. }
  81. }
  82. // 유효한 데이터가 없으면 기존 데이터와 비교해서 변경사항 확인
  83. if (!$hasValidData) {
  84. $existingCount = $db->table('ITEM_ORDER_LIST')
  85. ->where('ITEM_SEQ', $itemSeq)
  86. ->countAllResults();
  87. // 기존 데이터도 없고 새로운 유효 데이터도 없으면 변경사항 없음
  88. if ($existingCount == 0) {
  89. return $this->respond([
  90. 'message' => '저장할 데이터가 없습니다.',
  91. 'updated_count' => 0,
  92. 'new_count' => 0,
  93. 'deleted_count' => 0,
  94. 'errors' => []
  95. ], 200);
  96. }
  97. }
  98. // 유효성 검사 (유효한 데이터가 있을 때만)
  99. foreach ($orderList as $index => $order) {
  100. // 빈 행은 건너뛰기
  101. if (empty($order['ORDER_NUMB']) && empty($order['BUYER_NAME'])) {
  102. continue;
  103. }
  104. $requiredFields = ['ORDER_NUMB', 'BUYER_NAME'];
  105. foreach ($requiredFields as $field) {
  106. if (!isset($order[$field]) || $order[$field] === '') {
  107. return $this->fail("orderList[$index] 항목의 '{$field}' 값이 누락되었습니다.", 400);
  108. }
  109. }
  110. }
  111. $db->transBegin();
  112. $updatedCount = 0;
  113. $newCount = 0;
  114. $deletedCount = 0;
  115. $errors = [];
  116. try {
  117. // 1. 먼저 해당 item_seq의 기존 데이터를 모두 조회
  118. $existingOrders = $db->table('ITEM_ORDER_LIST')
  119. ->where('ITEM_SEQ', $itemSeq)
  120. ->get()->getResultArray();
  121. // 2. 현재 전송된 데이터 목록에서 ORDER_NUMB + BUYER_NAME 조합 추출
  122. $currentOrderKeys = [];
  123. foreach ($orderList as $order) {
  124. if (!empty($order['ORDER_NUMB']) && !empty($order['BUYER_NAME'])) {
  125. $currentOrderKeys[] = $order['ORDER_NUMB'] . '_' . $order['BUYER_NAME'];
  126. }
  127. }
  128. // 3. 기존 데이터 중 현재 목록에 없는 항목들 삭제
  129. foreach ($existingOrders as $existingOrder) {
  130. $existingKey = $existingOrder['ORDER_NUMB'] . '_' . $existingOrder['BUYER_NAME'];
  131. if (!in_array($existingKey, $currentOrderKeys)) {
  132. $deleteResult = $db->table('ITEM_ORDER_LIST')
  133. ->where('SEQ', $existingOrder['SEQ'])
  134. ->delete();
  135. if ($deleteResult) {
  136. $deletedCount++;
  137. }
  138. }
  139. }
  140. // 4. 업데이트 또는 신규 추가 처리
  141. foreach ($orderList as $order) {
  142. $metadata = $order['_metadata'] ?? [];
  143. $isUpdated = $metadata['isUpdated'] ?? false;
  144. $isNew = $metadata['isNew'] ?? false;
  145. // 메타데이터가 없는 경우 DB에서 기존 데이터 확인
  146. if (!$isUpdated && !$isNew) {
  147. $existingRecord = $db->table('ITEM_ORDER_LIST')
  148. ->where('ITEM_SEQ', $itemSeq)
  149. ->where('ORDER_NUMB', $order['ORDER_NUMB'])
  150. ->where('BUYER_NAME', $order['BUYER_NAME'])
  151. ->get()->getRowArray();
  152. if ($existingRecord) {
  153. $isUpdated = true;
  154. } else {
  155. // 주문번호+구매자명이 정확히 일치하지 않으면 신규 추가
  156. $isNew = true;
  157. }
  158. }
  159. if ($isUpdated) {
  160. // 기존 데이터 조회하여 변경사항 확인
  161. $existingRecord = $db->table('ITEM_ORDER_LIST')
  162. ->where('ITEM_SEQ', $itemSeq)
  163. ->where('ORDER_NUMB', $order['ORDER_NUMB'])
  164. ->where('BUYER_NAME', $order['BUYER_NAME'])
  165. ->get()->getRowArray();
  166. if ($existingRecord) {
  167. $updateData = [];
  168. $hasChanges = false;
  169. // 각 필드별로 변경사항 확인
  170. if (($existingRecord['PHONE'] ?? '') !== ($order['PHONE'] ?? '')) {
  171. $updateData['PHONE'] = $order['PHONE'] ?? '';
  172. $hasChanges = true;
  173. }
  174. if (($existingRecord['QTY'] ?? 0) != ($order['QTY'] ?? 0)) {
  175. $updateData['QTY'] = $order['QTY'] ?? 0;
  176. $hasChanges = true;
  177. }
  178. if (($existingRecord['DELI_COMP'] ?? '') !== ($order['DELI_COMP'] ?? '')) {
  179. $updateData['DELI_COMP'] = $order['DELI_COMP'] ?? '';
  180. $hasChanges = true;
  181. }
  182. if (($existingRecord['DELI_NUMB'] ?? '') !== ($order['DELI_NUMB'] ?? '')) {
  183. $updateData['DELI_NUMB'] = $order['DELI_NUMB'] ?? '';
  184. $hasChanges = true;
  185. }
  186. // 실제 변경사항이 있을 때만 UPDATE_DATE 갱신
  187. if ($hasChanges) {
  188. $updateData['UPDATE_DATE'] = date('Y-m-d H:i:s');
  189. $result = $db->table('ITEM_ORDER_LIST')
  190. ->where('ITEM_SEQ', $itemSeq)
  191. ->where('ORDER_NUMB', $order['ORDER_NUMB'])
  192. ->where('BUYER_NAME', $order['BUYER_NAME'])
  193. ->update($updateData);
  194. if ($result) {
  195. $updatedCount++;
  196. } else {
  197. $errors[] = "업데이트 실패: {$order['ORDER_NUMB']} - {$order['BUYER_NAME']}";
  198. }
  199. }
  200. // 변경사항이 없으면 업데이트하지 않음
  201. } else {
  202. // 기존 데이터를 찾을 수 없으면 신규로 처리
  203. $isNew = true;
  204. }
  205. }
  206. if ($isNew) {
  207. // 신규 데이터 추가
  208. $insertData = [
  209. 'ITEM_SEQ' => $itemSeq,
  210. 'ORDER_NUMB' => $order['ORDER_NUMB'],
  211. 'BUYER_NAME' => $order['BUYER_NAME'],
  212. 'PHONE' => $order['PHONE'] ?? '',
  213. 'QTY' => $order['QTY'] ?? 0,
  214. 'INF_SEQ' => $infSeq,
  215. 'DELI_COMP' => $order['DELI_COMP'] ?? '',
  216. 'DELI_NUMB' => $order['DELI_NUMB'] ?? '',
  217. 'REG_DATE' => $metadata['originalCreatedAt'] ?? date('Y-m-d H:i:s'),
  218. 'UPDATE_DATE' => $metadata['lastModifiedAt'] ?? date('Y-m-d H:i:s'),
  219. ];
  220. $result = $db->table('ITEM_ORDER_LIST')->insert($insertData);
  221. if ($result) {
  222. $newCount++;
  223. } else {
  224. $errors[] = "삽입 실패: {$order['ORDER_NUMB']} - {$order['BUYER_NAME']}";
  225. }
  226. }
  227. }
  228. // 에러가 있으면 실패로 처리
  229. if (count($errors) > 0) {
  230. $db->transRollback();
  231. return $this->fail(implode(' | ', $errors), 400);
  232. }
  233. if ($updatedCount > 0 || $newCount > 0 || $deletedCount > 0) {
  234. $db->transCommit();
  235. return $this->respond([
  236. 'message' => '주문 내역이 성공적으로 처리되었습니다.',
  237. 'updated_count' => $updatedCount,
  238. 'new_count' => $newCount,
  239. 'deleted_count' => $deletedCount,
  240. 'errors' => $errors
  241. ], 200);
  242. } else {
  243. $db->transRollback();
  244. return $this->fail('처리할 수 있는 데이터가 없습니다.', 400);
  245. }
  246. } catch (\Exception $e) {
  247. $db->transRollback();
  248. return $this->fail('주문 내역 처리 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
  249. }
  250. }
  251. //아이템 리스트
  252. public function itemlist()
  253. {
  254. $db = \Config\Database::connect();
  255. // POST JSON 파라미터 받기
  256. $request = $this->request->getJSON(true);
  257. $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
  258. $showYn = isset($request['SHOW_YN']) ? $request['SHOW_YN'] : null;
  259. $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
  260. $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
  261. $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
  262. // 서브쿼리: 사용자 타입에 따른 주문 집계
  263. $subQuery = $db->table('ITEM_ORDER_LIST')
  264. ->select('ITEM_SEQ, SUM(QTY) AS sum_qty, SUM(TOTAL) AS sum_total, MAX(REG_DATE) AS latest_reg_date');
  265. // 인플루언서: 본인이 받은 주문만
  266. if ($memberType === 'INFLUENCER') {
  267. if (is_null($infSeq)) {
  268. // INF_SEQ가 없으면 빈 결과 반환
  269. return $this->respond([], 200);
  270. }
  271. $subQuery->where('INF_SEQ', $infSeq);
  272. }
  273. // 배송정보가 등록되지 않은 주문만 (배송관리 페이지용)
  274. // 배송업체와 송장번호가 모두 비어있는 경우만 포함 (AND 조건)
  275. $subQuery->where('(DELI_COMP IS NULL OR DELI_COMP = "")')
  276. ->where('(DELI_NUMB IS NULL OR DELI_NUMB = "")');
  277. $subQuery->groupBy('ITEM_SEQ');
  278. // 메인 쿼리: ITEM_LIST와 위 서브쿼리 조인 (실제 주문이 있는 제품만)
  279. $builder = $db->table('ITEM_LIST I')
  280. ->select('I.*, O.sum_qty, O.sum_total, O.latest_reg_date')
  281. ->join("(" . $subQuery->getCompiledSelect() . ") O", 'I.SEQ = O.ITEM_SEQ', 'inner')
  282. ->where('I.DEL_YN', 'N');
  283. // 벤더: 자사 제품만 필터링
  284. if ($memberType === 'VENDOR') {
  285. if (empty($companyNumber)) {
  286. // COMPANY_NUMBER가 없으면 빈 결과 반환
  287. return $this->respond([], 200);
  288. }
  289. $builder->where('I.COMPANY_NUMBER', $companyNumber);
  290. }
  291. if (!is_null($showYn) && $showYn !== '') {
  292. $builder->where('I.SHOW_YN', $showYn);
  293. }
  294. $builder->where('I.TYPE', $itemType);
  295. $builder->orderBy('I.UDPDATE', 'DESC');
  296. $lists = $builder->get()->getResultArray();
  297. return $this->respond($lists, 200);
  298. }
  299. //아이템 검색
  300. public function deliSearch()
  301. {
  302. $db = \Config\Database::connect();
  303. // 요청 바디에서 filter와 keyword 추출
  304. $request = $this->request->getJSON(true);
  305. $filter = isset($request['filter']) ? $request['filter'] : null;
  306. $keyword = isset($request['keyword']) ? $request['keyword'] : null;
  307. $startDate = $request['startDate'] ?? null;
  308. $endDate = $request['endDate'] ?? null;
  309. $showYN = $request['showYN'] ?? null;
  310. $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
  311. $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
  312. $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
  313. $memberSeq = isset($request['MEMBER_SEQ']) ? $request['MEMBER_SEQ'] : null;
  314. $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
  315. $filterMap = [
  316. 'name' => 'I.NAME',
  317. ];
  318. // 서브쿼리: 사용자 타입에 따른 주문 집계
  319. $subQuery = $db->table('ITEM_ORDER_LIST')
  320. ->select('ITEM_SEQ, SUM(QTY) AS sum_qty, SUM(TOTAL) AS sum_total, MAX(REG_DATE) AS latest_reg_date');
  321. // 인플루언서: 본인이 받은 주문만
  322. if ($memberType === 'INFLUENCER') {
  323. if (is_null($infSeq)) {
  324. // INF_SEQ가 없으면 빈 결과 반환
  325. return $this->respond([], 200);
  326. }
  327. $subQuery->where('INF_SEQ', $infSeq);
  328. }
  329. // 배송정보가 등록되지 않은 주문만 (배송관리 페이지용)
  330. $subQuery->where('(DELI_COMP IS NULL OR DELI_COMP = "")')
  331. ->where('(DELI_NUMB IS NULL OR DELI_NUMB = "")');
  332. $subQuery->groupBy('ITEM_SEQ');
  333. // 메인 쿼리: ITEM_LIST와 위 서브쿼리 조인 (실제 주문이 있는 제품만)
  334. $builder = $db->table('ITEM_LIST I')
  335. ->select('I.*, O.sum_qty, O.sum_total, O.latest_reg_date')
  336. ->join("(" . $subQuery->getCompiledSelect() . ") O", 'I.SEQ = O.ITEM_SEQ', 'inner')
  337. ->where('I.DEL_YN', 'N');
  338. // 사용자 타입별 필터링
  339. if ($memberType === 'VENDOR' && !empty($companyNumber)) {
  340. // 벤더사의 경우: 자사 제품만 검색
  341. $builder->where('I.COMPANY_NUMBER', $companyNumber);
  342. } elseif ($memberType === 'INFLUENCER' && !empty($memberSeq)) {
  343. // 인플루언서의 경우: 파트너십이 체결된 벤더사의 제품만 검색
  344. $builder->select('I.*, O.sum_qty, O.sum_total, O.latest_reg_date, VIP.STATUS as PARTNERSHIP_STATUS');
  345. $builder->join('VENDOR_LIST VL', 'I.COMPANY_NUMBER = VL.COMPANY_NUMBER', 'inner');
  346. $builder->join('VENDOR_INFLUENCER_PARTNERSHIP VIP', 'VL.SEQ = VIP.VENDOR_SEQ', 'inner');
  347. $builder->where('VIP.INFLUENCER_SEQ', $memberSeq);
  348. $builder->where('VIP.STATUS', 'APPROVED');
  349. $builder->where('VIP.IS_ACTIVE', 'Y');
  350. }
  351. // 키워드 검색
  352. if (!empty($keyword)) {
  353. if (empty($filter)) {
  354. // 필터를 선택 안했으면 전체 검색
  355. $first = true;
  356. foreach ($filterMap as $column) {
  357. if ($first) {
  358. $builder->like($column, $keyword);
  359. $first = false;
  360. } else {
  361. $builder->orLike($column, $keyword);
  362. }
  363. }
  364. } elseif (isset($filterMap[$filter])) {
  365. // 특정 필터 검색
  366. $builder->like($filterMap[$filter], $keyword);
  367. }
  368. }
  369. // 노출중, 비노출 여부 확인
  370. if (!empty($showYN)) {
  371. $builder->where('I.SHOW_YN', $showYN);
  372. }
  373. if (!empty($itemType)) {
  374. $builder->where('I.TYPE', $itemType);
  375. }
  376. // INF_SEQ 조건 추가 (값이 있을 때만)
  377. if (!empty($infSeq)) {
  378. $builder->where('I.CONTACT_INF', $infSeq);
  379. }
  380. // 날짜 범위 검색 (latest_reg_date 기준)
  381. if (!empty($startDate)) {
  382. $builder->where('O.latest_reg_date >=', $startDate . ' 00:00:00');
  383. }
  384. if (!empty($endDate)) {
  385. $builder->where('O.latest_reg_date <=', $endDate . ' 23:59:59');
  386. }
  387. $builder->orderBy('I.UDPDATE', 'DESC');
  388. // 조회
  389. $lists = $builder->get()->getResultArray();
  390. return $this->respond($lists, 200);
  391. }
  392. //배송중 검색
  393. public function shippingSearch()
  394. {
  395. $db = \Config\Database::connect();
  396. $request = $this->request->getJSON(true);
  397. $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
  398. $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
  399. $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
  400. $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
  401. $filter = isset($request['filter']) ? $request['filter'] : null;
  402. $keyword = isset($request['keyword']) ? $request['keyword'] : null;
  403. $startDate = isset($request['startDate']) ? $request['startDate'] : null;
  404. $endDate = isset($request['endDate']) ? $request['endDate'] : null;
  405. $builder = $db->table('ITEM_ORDER_LIST IOL')
  406. ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2')
  407. ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
  408. ->where('IOL.DELI_COMP !=', '')
  409. ->where('IOL.DELI_NUMB !=', '')
  410. ->where('IOL.DELI_COMP IS NOT NULL')
  411. ->where('IOL.DELI_NUMB IS NOT NULL');
  412. // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 조건 추가
  413. $columns = $db->getFieldNames('ITEM_ORDER_LIST');
  414. if (in_array('DELIVERY_STATUS', $columns)) {
  415. $builder->where('IOL.DELIVERY_STATUS', 'SHIPPING');
  416. } else {
  417. // DELIVERY_STATUS 컬럼이 없으면 배송업체와 송장번호가 있는 것을 배송중으로 간주
  418. // 단, 배송완료된 것은 제외 (DELIVERED_DATE가 없는 것만)
  419. if (in_array('DELIVERED_DATE', $columns)) {
  420. $builder->where('IOL.DELIVERED_DATE IS NULL');
  421. }
  422. }
  423. // 아이템 타입 필터링
  424. if (!empty($itemType)) {
  425. $builder->where('IL.TYPE', $itemType);
  426. }
  427. // 검색 조건 추가
  428. if (!empty($keyword)) {
  429. if ($filter === 'name') {
  430. $builder->like('IL.NAME', $keyword);
  431. } elseif ($filter === 'buyer') {
  432. $builder->like('IOL.BUYER_NAME', $keyword);
  433. } else {
  434. // 전체 검색
  435. $builder->groupStart()
  436. ->like('IL.NAME', $keyword)
  437. ->orLike('IOL.BUYER_NAME', $keyword)
  438. ->groupEnd();
  439. }
  440. }
  441. // 날짜 범위 검색
  442. if (!empty($startDate)) {
  443. $builder->where('DATE(IOL.SHIPPING_DATE) >=', $startDate);
  444. }
  445. if (!empty($endDate)) {
  446. $builder->where('DATE(IOL.SHIPPING_DATE) <=', $endDate);
  447. }
  448. // 사용자 타입에 따른 필터링
  449. if ($memberType === 'VENDOR' && !empty($companyNumber)) {
  450. $builder->where('IL.COMPANY_NUMBER', $companyNumber);
  451. } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
  452. $builder->where('IOL.INF_SEQ', $infSeq);
  453. }
  454. $builder->orderBy('IOL.REG_DATE', 'DESC');
  455. $lists = $builder->get()->getResultArray();
  456. return $this->respond($lists, 200);
  457. }
  458. //구매자 리스트
  459. public function delilist()
  460. {
  461. $db = \Config\Database::connect();
  462. $request = $this->request->getJSON(true);
  463. $itemSeq = isset($request['item_seq']) ? $request['item_seq'] : null;
  464. $infSeq = isset($request['inf_seq']) ? $request['inf_seq'] : null;
  465. // 쿼리 빌더
  466. $builder = $db->table('ITEM_ORDER_LIST I');
  467. $builder->select('I.*, U.NICK_NAME');
  468. $builder->join('USER_LIST U', 'I.INF_SEQ = U.SEQ', 'left');
  469. $builder->where('I.ITEM_SEQ', $itemSeq);
  470. if ($infSeq) {
  471. $builder->where('I.INF_SEQ', $infSeq);
  472. }
  473. // 배송정보가 등록되지 않은 주문만 표시 (송장번호 등록용)
  474. // 배송업체와 송장번호가 모두 비어있는 경우만 포함
  475. $builder->where('(I.DELI_COMP IS NULL OR I.DELI_COMP = "")')
  476. ->where('(I.DELI_NUMB IS NULL OR I.DELI_NUMB = "")');
  477. // 주문일 기준으로 정렬
  478. $builder->orderBy('I.ORDER_DATE', 'DESC');
  479. $lists = $builder->get()->getResultArray();
  480. return $this->respond($lists, 200);
  481. }
  482. //구매자 등록
  483. public function deliRegister()
  484. {
  485. $db = \Config\Database::connect();
  486. $request = $this->request->getJSON(true);
  487. $itemSeq = isset($request['item_seq']) ? $request['item_seq'] : null;
  488. $infSeq = isset($request['inf_seq']) ? $request['inf_seq'] : null;
  489. $deliveryList = $request['deliveryList'] ?? [];
  490. // 🔍 먼저 전체 유효성 검사
  491. foreach ($deliveryList as $index => $delivery) {
  492. $requiredFields = ['buyerName', 'address', 'phone', 'qty', 'total', 'orderDate'];
  493. foreach ($requiredFields as $field) {
  494. if (!isset($delivery[$field]) || $delivery[$field] === '') {
  495. return $this->fail("deliveryList[$index] 항목의 '{$field}' 값이 누락되었습니다.", 400);
  496. }
  497. }
  498. }
  499. // ✅ 유효성 통과 후 삭제 + 삽입
  500. $db->table('ITEM_ORDER_LIST')
  501. ->where('ITEM_SEQ', $itemSeq)
  502. ->where('INF_SEQ', $infSeq)
  503. ->delete();
  504. foreach ($deliveryList as $delivery) {
  505. $data = [
  506. 'ITEM_SEQ' => $itemSeq,
  507. 'INF_SEQ' => $infSeq,
  508. 'BUYER_NAME' => $delivery['buyerName'],
  509. 'ADDRESS' => $delivery['address'],
  510. 'PHONE' => $delivery['phone'],
  511. 'EMAIL' => $delivery['email'],
  512. 'QTY' => $delivery['qty'],
  513. 'TOTAL' => $delivery['total'],
  514. 'DELI_COMP' => $delivery['deliComp'] ?? '',
  515. 'DELI_NUMB' => $delivery['deliNumb'] ?? '',
  516. 'ORDER_DATE' => date('Y-m-d H:i:s', strtotime($delivery['orderDate'])),
  517. 'REG_DATE' => date('Y-m-d'),
  518. ];
  519. $db->table('ITEM_ORDER_LIST')->insert($data);
  520. }
  521. return $this->respond(['message' => '배송 데이터가 성공적으로 저장되었습니다.'], 200);
  522. }
  523. //벤더사용 배송정보 업데이트
  524. public function updateDeliveryInfo()
  525. {
  526. $db = \Config\Database::connect();
  527. $request = $this->request->getJSON(true);
  528. $itemSeq = isset($request['item_seq']) ? $request['item_seq'] : null;
  529. $deliveryUpdates = $request['deliveryUpdates'] ?? [];
  530. if (!$itemSeq || empty($deliveryUpdates)) {
  531. return $this->fail('필수 파라미터가 누락되었습니다.', 400);
  532. }
  533. $db->transBegin();
  534. $updatedCount = 0;
  535. $errors = [];
  536. try {
  537. foreach ($deliveryUpdates as $update) {
  538. $buyerName = $update['buyerName'] ?? '';
  539. $phone = $update['phone'] ?? '';
  540. $deliComp = $update['deliComp'] ?? '';
  541. $deliNumb = $update['deliNumb'] ?? '';
  542. if (!$buyerName || !$phone) {
  543. $errors[] = "구매자명과 연락처는 필수입니다.";
  544. continue;
  545. }
  546. // 업데이트할 데이터 준비
  547. $updateData = [
  548. 'DELI_COMP' => $deliComp,
  549. 'DELI_NUMB' => $deliNumb
  550. ];
  551. // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 추가
  552. $columns = $db->getFieldNames('ITEM_ORDER_LIST');
  553. if (in_array('DELIVERY_STATUS', $columns)) {
  554. $updateData['DELIVERY_STATUS'] = 'SHIPPING';
  555. }
  556. if (in_array('SHIPPING_DATE', $columns)) {
  557. $updateData['SHIPPING_DATE'] = date('Y-m-d H:i:s');
  558. }
  559. // 구매자명과 연락처로 해당 주문 찾기
  560. $result = $db->table('ITEM_ORDER_LIST')
  561. ->where('ITEM_SEQ', $itemSeq)
  562. ->where('BUYER_NAME', $buyerName)
  563. ->where('PHONE', $phone)
  564. ->update($updateData);
  565. if ($result) {
  566. $updatedCount++;
  567. } else {
  568. $errors[] = "매칭되는 주문을 찾을 수 없습니다: {$buyerName}({$phone})";
  569. }
  570. }
  571. if ($updatedCount > 0) {
  572. $db->transCommit();
  573. return $this->respond([
  574. 'message' => "배송정보가 성공적으로 업데이트되었습니다.",
  575. 'updated_count' => $updatedCount,
  576. 'errors' => $errors
  577. ], 200);
  578. } else {
  579. $db->transRollback();
  580. return $this->fail('업데이트할 수 있는 데이터가 없습니다.', 400);
  581. }
  582. } catch (\Exception $e) {
  583. $db->transRollback();
  584. return $this->fail('배송정보 업데이트 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
  585. }
  586. }
  587. //아이템 상세
  588. public function itemDetail($seq)
  589. {
  590. // DB 객체 얻기
  591. $db = \Config\Database::connect();
  592. $builder = $db->table('ITEM_LIST');
  593. $item = $builder->where('seq', $seq)->get()->getRowArray();
  594. if($item){
  595. return $this->respond($item, 200);
  596. } else {
  597. return $this->respond([
  598. 'status' => 'fail',
  599. 'message' => '유효하지 않은 seq입니다.'
  600. ], 404);
  601. }
  602. }
  603. //아이템 삭제
  604. public function itemDelete($seq)
  605. {
  606. $db = \Config\Database::connect();
  607. $db->transBegin();
  608. //아이템 삭제
  609. $deleted = $db->table('ITEM_LIST')
  610. ->where('SEQ', $seq)
  611. ->update(['DEL_YN' => 'Y']);
  612. if ($db->transStatus() === false || !$deleted) {
  613. $db->transRollback();
  614. return $this->respond(['status' => 'fail', 'message' => '이벤트 삭제 중 오류가 발생했습니다.']);
  615. }
  616. $db->transCommit();
  617. return $this->respond(['status' => 'success', 'message' => '이벤트가 삭제되었습니다.'], 200);
  618. }
  619. // 배송중 리스트 조회
  620. public function getShippingList()
  621. {
  622. $db = \Config\Database::connect();
  623. $request = $this->request->getJSON(true);
  624. $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
  625. $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
  626. $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
  627. $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
  628. $builder = $db->table('ITEM_ORDER_LIST IOL')
  629. ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2')
  630. ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
  631. ->where('IOL.DELI_COMP !=', '')
  632. ->where('IOL.DELI_NUMB !=', '')
  633. ->where('IOL.DELI_COMP IS NOT NULL')
  634. ->where('IOL.DELI_NUMB IS NOT NULL');
  635. // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 조건 추가
  636. $columns = $db->getFieldNames('ITEM_ORDER_LIST');
  637. if (in_array('DELIVERY_STATUS', $columns)) {
  638. $builder->where('IOL.DELIVERY_STATUS', 'SHIPPING');
  639. } else {
  640. // DELIVERY_STATUS 컬럼이 없으면 배송업체와 송장번호가 있는 것을 배송중으로 간주
  641. // 단, 배송완료된 것은 제외 (DELIVERED_DATE가 없는 것만)
  642. if (in_array('DELIVERED_DATE', $columns)) {
  643. $builder->where('IOL.DELIVERED_DATE IS NULL');
  644. }
  645. }
  646. // 아이템 타입 필터링
  647. if (!empty($itemType)) {
  648. $builder->where('IL.TYPE', $itemType);
  649. }
  650. // 사용자 타입에 따른 필터링
  651. if ($memberType === 'VENDOR' && !empty($companyNumber)) {
  652. $builder->where('IL.COMPANY_NUMBER', $companyNumber);
  653. } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
  654. $builder->where('IOL.INF_SEQ', $infSeq);
  655. }
  656. $builder->orderBy('IOL.REG_DATE', 'DESC');
  657. $lists = $builder->get()->getResultArray();
  658. return $this->respond($lists, 200);
  659. }
  660. // 배송완료 리스트 조회
  661. public function getDeliveredList()
  662. {
  663. $db = \Config\Database::connect();
  664. $request = $this->request->getJSON(true);
  665. $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
  666. $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
  667. $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
  668. $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
  669. $builder = $db->table('ITEM_ORDER_LIST IOL')
  670. ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2')
  671. ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner');
  672. // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 조건 추가
  673. $columns = $db->getFieldNames('ITEM_ORDER_LIST');
  674. if (in_array('DELIVERY_STATUS', $columns)) {
  675. $builder->where('IOL.DELIVERY_STATUS', 'DELIVERED');
  676. } else {
  677. // DELIVERY_STATUS 컬럼이 없으면 배송업체와 송장번호가 있는 것을 배송완료로 간주
  678. $builder->where('IOL.DELI_COMP !=', '')
  679. ->where('IOL.DELI_NUMB !=', '')
  680. ->where('IOL.DELI_COMP IS NOT NULL')
  681. ->where('IOL.DELI_NUMB IS NOT NULL');
  682. }
  683. // 아이템 타입 필터링
  684. if (!empty($itemType)) {
  685. $builder->where('IL.TYPE', $itemType);
  686. }
  687. // 정산완료되지 않은 주문만 표시 (배송완료 페이지용)
  688. if (in_array('SETTLEMENT_STATUS', $columns)) {
  689. $builder->where('(IOL.SETTLEMENT_STATUS IS NULL OR IOL.SETTLEMENT_STATUS != "COMPLETED")');
  690. }
  691. // 사용자 타입에 따른 필터링
  692. if ($memberType === 'VENDOR' && !empty($companyNumber)) {
  693. $builder->where('IL.COMPANY_NUMBER', $companyNumber);
  694. } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
  695. $builder->where('IOL.INF_SEQ', $infSeq);
  696. }
  697. // 정렬을 안전하게 처리
  698. if (in_array('DELIVERED_DATE', $columns)) {
  699. $builder->orderBy('IOL.DELIVERED_DATE', 'DESC');
  700. } else {
  701. $builder->orderBy('IOL.REG_DATE', 'DESC');
  702. }
  703. $lists = $builder->get()->getResultArray();
  704. return $this->respond($lists, 200);
  705. }
  706. // 배송완료 처리
  707. public function markAsDelivered()
  708. {
  709. $db = \Config\Database::connect();
  710. $request = $this->request->getJSON(true);
  711. $orderIds = isset($request['order_ids']) ? $request['order_ids'] : [];
  712. if (empty($orderIds)) {
  713. return $this->fail('처리할 주문이 선택되지 않았습니다.', 400);
  714. }
  715. $db->transBegin();
  716. try {
  717. foreach ($orderIds as $orderId) {
  718. $db->table('ITEM_ORDER_LIST')
  719. ->where('SEQ', $orderId)
  720. ->update([
  721. 'DELIVERY_STATUS' => 'DELIVERED',
  722. 'DELIVERED_DATE' => date('Y-m-d H:i:s')
  723. ]);
  724. }
  725. $db->transCommit();
  726. return $this->respond(['message' => '배송완료 처리되었습니다.'], 200);
  727. } catch (\Exception $e) {
  728. $db->transRollback();
  729. return $this->fail('배송완료 처리 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
  730. }
  731. }
  732. // 정산완료 처리
  733. public function markAsSettled()
  734. {
  735. $db = \Config\Database::connect();
  736. $request = $this->request->getJSON(true);
  737. $orderIds = isset($request['order_ids']) ? $request['order_ids'] : [];
  738. if (empty($orderIds)) {
  739. return $this->fail('처리할 주문이 선택되지 않았습니다.', 400);
  740. }
  741. $db->transBegin();
  742. try {
  743. foreach ($orderIds as $orderId) {
  744. $db->table('ITEM_ORDER_LIST')
  745. ->where('SEQ', $orderId)
  746. ->update([
  747. 'SETTLEMENT_STATUS' => 'COMPLETED',
  748. 'SETTLED_DATE' => date('Y-m-d H:i:s')
  749. ]);
  750. }
  751. $db->transCommit();
  752. return $this->respond(['message' => '정산완료 처리되었습니다.'], 200);
  753. } catch (\Exception $e) {
  754. $db->transRollback();
  755. return $this->fail('정산완료 처리 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
  756. }
  757. }
  758. // 정산관리 리스트 조회
  759. public function getSettlementList()
  760. {
  761. $db = \Config\Database::connect();
  762. $request = $this->request->getJSON(true);
  763. $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
  764. $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
  765. $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
  766. $settlementStatus = isset($request['SETTLEMENT_STATUS']) ? $request['SETTLEMENT_STATUS'] : null;
  767. $builder = $db->table('ITEM_ORDER_LIST IOL')
  768. ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2, IL.TYPE as ITEM_TYPE, UL.NICK_NAME as INF_NICK_NAME')
  769. ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
  770. ->join('USER_LIST UL', 'IOL.INF_SEQ = UL.SEQ', 'left');
  771. // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 조건 추가
  772. $columns = $db->getFieldNames('ITEM_ORDER_LIST');
  773. if (in_array('DELIVERY_STATUS', $columns)) {
  774. $builder->where('IOL.DELIVERY_STATUS', 'DELIVERED');
  775. } else {
  776. // DELIVERY_STATUS 컬럼이 없으면 배송업체와 송장번호가 있는 것을 대상으로 함
  777. $builder->where('IOL.DELI_COMP !=', '')
  778. ->where('IOL.DELI_NUMB !=', '')
  779. ->where('IOL.DELI_COMP IS NOT NULL')
  780. ->where('IOL.DELI_NUMB IS NOT NULL');
  781. }
  782. // 정산 상태 필터링 (SETTLEMENT_STATUS 컬럼이 존재하는 경우만)
  783. if ($settlementStatus && in_array('SETTLEMENT_STATUS', $columns)) {
  784. $builder->where('IOL.SETTLEMENT_STATUS', $settlementStatus);
  785. }
  786. // 사용자 타입에 따른 필터링
  787. if ($memberType === 'VENDOR' && !empty($companyNumber)) {
  788. $builder->where('IL.COMPANY_NUMBER', $companyNumber);
  789. } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
  790. $builder->where('IOL.INF_SEQ', $infSeq);
  791. }
  792. $builder->orderBy('IOL.DELIVERED_DATE', 'DESC');
  793. $lists = $builder->get()->getResultArray();
  794. return $this->respond($lists, 200);
  795. }
  796. }