| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961 |
- <?php
- namespace App\Controllers;
- use CodeIgniter\RESTful\ResourceController;
- class Deli extends ResourceController
- {
- // New: 공동구매 주문 내역 리스트
- public function orderList()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
- $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
- $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
- $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
- // ITEM_ORDER_LIST와 ITEM_LIST를 JOIN해서 주문 목록 조회
- $builder = $db->table('ITEM_ORDER_LIST IOL')
- ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2, IL.TYPE as ITEM_TYPE, IL.THUMB_FILE')
- ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
- ->where('IL.DEL_YN', 'N'); // 삭제되지 않은 아이템만
- // 아이템 타입 필터링
- if (!empty($itemType)) {
- $builder->where('IL.TYPE', $itemType);
- }
- // 사용자 타입에 따른 필터링
- if ($memberType === 'VENDOR' && !empty($companyNumber)) {
- // 벤더사: 자사 아이템의 주문만
- $builder->where('IL.COMPANY_NUMBER', $companyNumber);
- } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
- // 인플루언서: 자신이 담당하는 주문만
- $builder->where('IOL.INF_SEQ', $infSeq);
- } elseif ($memberType === 'BRAND' && !empty($infSeq)) {
- // 브랜드사: 자사가 담당하는 아이템의 주문만
- $builder->where('IL.CONTACT_BRD', $infSeq);
- }
- // 주문일 기준으로 최신순 정렬
- $builder->orderBy('IOL.ORDER_DATE', 'DESC');
- $lists = $builder->get()->getResultArray();
- return $this->respond($lists, 200);
- }
- // New: 공동구매 주문 내역 등록/업데이트
- public function orderRegister()
- {
- // 한국 시간으로 설정
- date_default_timezone_set('Asia/Seoul');
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $itemSeq = isset($request['item_seq']) ? $request['item_seq'] : null;
- $infSeq = isset($request['inf_seq']) ? $request['inf_seq'] : null;
- $orderList = $request['orderList'] ?? [];
- if (!$itemSeq) {
- return $this->fail('필수 파라미터가 누락되었습니다.', 400);
- }
- // orderList가 비어있으면 해당 item_seq의 모든 데이터 삭제만 수행
- if (empty($orderList)) {
- $db->transBegin();
- try {
- // 기존 데이터 모두 삭제
- $deletedCount = $db->table('ITEM_ORDER_LIST')
- ->where('ITEM_SEQ', $itemSeq)
- ->delete();
- $db->transCommit();
- return $this->respond([
- 'message' => '주문 내역이 성공적으로 처리되었습니다.',
- 'updated_count' => 0,
- 'new_count' => 0,
- 'deleted_count' => $deletedCount,
- 'errors' => []
- ], 200);
- } catch (\Exception $e) {
- $db->transRollback();
- return $this->fail('주문 내역 처리 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
- }
- }
- // 빈 데이터나 변경사항 없는 경우 먼저 체크
- $hasValidData = false;
- foreach ($orderList as $order) {
- if (!empty($order['ORDER_NUMB']) && !empty($order['BUYER_NAME'])) {
- $hasValidData = true;
- break;
- }
- }
- // 유효한 데이터가 없으면 기존 데이터와 비교해서 변경사항 확인
- if (!$hasValidData) {
- $existingCount = $db->table('ITEM_ORDER_LIST')
- ->where('ITEM_SEQ', $itemSeq)
- ->countAllResults();
- // 기존 데이터도 없고 새로운 유효 데이터도 없으면 변경사항 없음
- if ($existingCount == 0) {
- return $this->respond([
- 'message' => '저장할 데이터가 없습니다.',
- 'updated_count' => 0,
- 'new_count' => 0,
- 'deleted_count' => 0,
- 'errors' => []
- ], 200);
- }
- }
- // 유효성 검사 (유효한 데이터가 있을 때만)
- foreach ($orderList as $index => $order) {
- // 빈 행은 건너뛰기
- if (empty($order['ORDER_NUMB']) && empty($order['BUYER_NAME'])) {
- continue;
- }
- $requiredFields = ['ORDER_NUMB', 'BUYER_NAME'];
- foreach ($requiredFields as $field) {
- if (!isset($order[$field]) || $order[$field] === '') {
- return $this->fail("orderList[$index] 항목의 '{$field}' 값이 누락되었습니다.", 400);
- }
- }
- }
- $db->transBegin();
- $updatedCount = 0;
- $newCount = 0;
- $deletedCount = 0;
- $errors = [];
- try {
- // 1. 먼저 해당 item_seq의 기존 데이터를 모두 조회
- $existingOrders = $db->table('ITEM_ORDER_LIST')
- ->where('ITEM_SEQ', $itemSeq)
- ->get()->getResultArray();
- // 2. 현재 전송된 데이터 목록에서 ORDER_NUMB + BUYER_NAME 조합 추출
- $currentOrderKeys = [];
- foreach ($orderList as $order) {
- if (!empty($order['ORDER_NUMB']) && !empty($order['BUYER_NAME'])) {
- $currentOrderKeys[] = $order['ORDER_NUMB'] . '_' . $order['BUYER_NAME'];
- }
- }
- // 3. 기존 데이터 중 현재 목록에 없는 항목들 삭제
- foreach ($existingOrders as $existingOrder) {
- $existingKey = $existingOrder['ORDER_NUMB'] . '_' . $existingOrder['BUYER_NAME'];
- if (!in_array($existingKey, $currentOrderKeys)) {
- $deleteResult = $db->table('ITEM_ORDER_LIST')
- ->where('SEQ', $existingOrder['SEQ'])
- ->delete();
- if ($deleteResult) {
- $deletedCount++;
- }
- }
- }
- // 4. 업데이트 또는 신규 추가 처리
- foreach ($orderList as $order) {
- $metadata = $order['_metadata'] ?? [];
- $isUpdated = $metadata['isUpdated'] ?? false;
- $isNew = $metadata['isNew'] ?? false;
- // 메타데이터가 없는 경우 DB에서 기존 데이터 확인
- if (!$isUpdated && !$isNew) {
- $existingRecord = $db->table('ITEM_ORDER_LIST')
- ->where('ITEM_SEQ', $itemSeq)
- ->where('ORDER_NUMB', $order['ORDER_NUMB'])
- ->where('BUYER_NAME', $order['BUYER_NAME'])
- ->get()->getRowArray();
- if ($existingRecord) {
- $isUpdated = true;
- } else {
- // 주문번호+구매자명이 정확히 일치하지 않으면 신규 추가
- $isNew = true;
- }
- }
- if ($isUpdated) {
- // 기존 데이터 조회하여 변경사항 확인
- $existingRecord = $db->table('ITEM_ORDER_LIST')
- ->where('ITEM_SEQ', $itemSeq)
- ->where('ORDER_NUMB', $order['ORDER_NUMB'])
- ->where('BUYER_NAME', $order['BUYER_NAME'])
- ->get()->getRowArray();
- if ($existingRecord) {
- $updateData = [];
- $hasChanges = false;
- // 각 필드별로 변경사항 확인
- if (($existingRecord['PHONE'] ?? '') !== ($order['PHONE'] ?? '')) {
- $updateData['PHONE'] = $order['PHONE'] ?? '';
- $hasChanges = true;
- }
- if (($existingRecord['QTY'] ?? 0) != ($order['QTY'] ?? 0)) {
- $updateData['QTY'] = $order['QTY'] ?? 0;
- $hasChanges = true;
- }
- if (($existingRecord['ADDRESS'] ?? '') != ($order['ADDRESS'] ?? 0)) {
- $updateData['ADDRESS'] = $order['ADDRESS'] ?? 0;
- $hasChanges = true;
- }
- if (($existingRecord['DELI_COMP'] ?? '') !== ($order['DELI_COMP'] ?? '')) {
- $updateData['DELI_COMP'] = $order['DELI_COMP'] ?? '';
- $hasChanges = true;
- }
- if (($existingRecord['DELI_NUMB'] ?? '') !== ($order['DELI_NUMB'] ?? '')) {
- $updateData['DELI_NUMB'] = $order['DELI_NUMB'] ?? '';
- $hasChanges = true;
- }
- // 실제 변경사항이 있을 때만 UPDATE_DATE 갱신
- if ($hasChanges) {
- $updateData['UPDATE_DATE'] = date('Y-m-d H:i:s');
- $result = $db->table('ITEM_ORDER_LIST')
- ->where('ITEM_SEQ', $itemSeq)
- ->where('ORDER_NUMB', $order['ORDER_NUMB'])
- ->where('BUYER_NAME', $order['BUYER_NAME'])
- ->update($updateData);
- if ($result) {
- $updatedCount++;
- } else {
- $errors[] = "업데이트 실패: {$order['ORDER_NUMB']} - {$order['BUYER_NAME']}";
- }
- }
- // 변경사항이 없으면 업데이트하지 않음
- } else {
- // 기존 데이터를 찾을 수 없으면 신규로 처리
- $isNew = true;
- }
- }
- if ($isNew) {
- // 신규 데이터 추가
- $insertData = [
- 'ITEM_SEQ' => $itemSeq,
- 'ORDER_NUMB' => $order['ORDER_NUMB'],
- 'BUYER_NAME' => $order['BUYER_NAME'],
- 'PHONE' => $order['PHONE'] ?? '',
- 'QTY' => $order['QTY'] ?? 0,
- 'ADDRESS' => $order['ADDRESS'] ?? '',
- 'INF_SEQ' => $infSeq,
- 'DELI_COMP' => $order['DELI_COMP'] ?? '',
- 'DELI_NUMB' => $order['DELI_NUMB'] ?? '',
- 'REG_DATE' => $metadata['originalCreatedAt'] ?? date('Y-m-d H:i:s'),
- 'UPDATE_DATE' => $metadata['lastModifiedAt'] ?? date('Y-m-d H:i:s'),
- ];
- $result = $db->table('ITEM_ORDER_LIST')->insert($insertData);
- if ($result) {
- $newCount++;
- } else {
- $errors[] = "삽입 실패: {$order['ORDER_NUMB']} - {$order['BUYER_NAME']}";
- }
- }
- }
- // 에러가 있으면 실패로 처리
- if (count($errors) > 0) {
- $db->transRollback();
- return $this->fail(implode(' | ', $errors), 400);
- }
- if ($updatedCount > 0 || $newCount > 0 || $deletedCount > 0) {
- $db->transCommit();
- return $this->respond([
- 'message' => '주문 내역이 성공적으로 처리되었습니다.',
- 'updated_count' => $updatedCount,
- 'new_count' => $newCount,
- 'deleted_count' => $deletedCount,
- 'errors' => $errors
- ], 200);
- } else {
- $db->transRollback();
- return $this->fail('처리할 수 있는 데이터가 없습니다.', 400);
- }
- } catch (\Exception $e) {
- $db->transRollback();
- return $this->fail('주문 내역 처리 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
- }
- }
- //아이템 리스트
- public function itemlist()
- {
- $db = \Config\Database::connect();
- // POST JSON 파라미터 받기
- $request = $this->request->getJSON(true);
- $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
- $showYn = isset($request['SHOW_YN']) ? $request['SHOW_YN'] : null;
- $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
- $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
- $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
- // 서브쿼리: 사용자 타입에 따른 주문 집계
- $subQuery = $db->table('ITEM_ORDER_LIST')
- ->select('ITEM_SEQ, SUM(QTY) AS sum_qty, SUM(TOTAL) AS sum_total, MAX(REG_DATE) AS latest_reg_date');
- // 인플루언서: 본인이 받은 주문만
- if ($memberType === 'INFLUENCER') {
- if (is_null($infSeq)) {
- // INF_SEQ가 없으면 빈 결과 반환
- return $this->respond([], 200);
- }
- $subQuery->where('INF_SEQ', $infSeq);
- }
- // 배송정보가 등록되지 않은 주문만 (배송관리 페이지용)
- // 배송업체와 송장번호가 모두 비어있는 경우만 포함 (AND 조건)
- $subQuery->where('(DELI_COMP IS NULL OR DELI_COMP = "")')
- ->where('(DELI_NUMB IS NULL OR DELI_NUMB = "")');
- $subQuery->groupBy('ITEM_SEQ');
- // 메인 쿼리: ITEM_LIST와 위 서브쿼리 조인 (실제 주문이 있는 제품만)
- $builder = $db->table('ITEM_LIST I')
- ->select('I.*, O.sum_qty, O.sum_total, O.latest_reg_date')
- ->join("(" . $subQuery->getCompiledSelect() . ") O", 'I.SEQ = O.ITEM_SEQ', 'inner')
- ->where('I.DEL_YN', 'N');
- // 벤더: 자사 제품만 필터링
- if ($memberType === 'VENDOR') {
- if (empty($companyNumber)) {
- // COMPANY_NUMBER가 없으면 빈 결과 반환
- return $this->respond([], 200);
- }
- $builder->where('I.COMPANY_NUMBER', $companyNumber);
- }
- if (!is_null($showYn) && $showYn !== '') {
- $builder->where('I.SHOW_YN', $showYn);
- }
- $builder->where('I.TYPE', $itemType);
- $builder->orderBy('I.UDPDATE', 'DESC');
- $lists = $builder->get()->getResultArray();
- return $this->respond($lists, 200);
- }
- //아이템 검색
- public function deliSearch()
- {
- $db = \Config\Database::connect();
- // 요청 바디에서 filter와 keyword 추출
- $request = $this->request->getJSON(true);
- $filter = isset($request['filter']) ? $request['filter'] : null;
- $keyword = isset($request['keyword']) ? $request['keyword'] : null;
- $startDate = $request['startDate'] ?? null;
- $endDate = $request['endDate'] ?? null;
- $showYN = $request['showYN'] ?? null;
- $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
- $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
- $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
- $memberSeq = isset($request['MEMBER_SEQ']) ? $request['MEMBER_SEQ'] : null;
- $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
- $filterMap = [
- 'name' => 'I.NAME',
- ];
- // 서브쿼리: 사용자 타입에 따른 주문 집계
- $subQuery = $db->table('ITEM_ORDER_LIST')
- ->select('ITEM_SEQ, SUM(QTY) AS sum_qty, SUM(TOTAL) AS sum_total, MAX(REG_DATE) AS latest_reg_date');
- // 인플루언서: 본인이 받은 주문만
- if ($memberType === 'INFLUENCER') {
- if (is_null($infSeq)) {
- // INF_SEQ가 없으면 빈 결과 반환
- return $this->respond([], 200);
- }
- $subQuery->where('INF_SEQ', $infSeq);
- }
- // 배송정보가 등록되지 않은 주문만 (배송관리 페이지용)
- $subQuery->where('(DELI_COMP IS NULL OR DELI_COMP = "")')
- ->where('(DELI_NUMB IS NULL OR DELI_NUMB = "")');
- $subQuery->groupBy('ITEM_SEQ');
- // 메인 쿼리: ITEM_LIST와 위 서브쿼리 조인 (실제 주문이 있는 제품만)
- $builder = $db->table('ITEM_LIST I')
- ->select('I.*, O.sum_qty, O.sum_total, O.latest_reg_date')
- ->join("(" . $subQuery->getCompiledSelect() . ") O", 'I.SEQ = O.ITEM_SEQ', 'inner')
- ->where('I.DEL_YN', 'N');
- // 사용자 타입별 필터링
- if ($memberType === 'VENDOR' && !empty($companyNumber)) {
- // 벤더사의 경우: 자사 제품만 검색
- $builder->where('I.COMPANY_NUMBER', $companyNumber);
- } elseif ($memberType === 'INFLUENCER' && !empty($memberSeq)) {
- // 인플루언서의 경우: 파트너십이 체결된 벤더사의 제품만 검색
- $builder->select('I.*, O.sum_qty, O.sum_total, O.latest_reg_date, VIP.STATUS as PARTNERSHIP_STATUS');
- $builder->join('VENDOR_LIST VL', 'I.COMPANY_NUMBER = VL.COMPANY_NUMBER', 'inner');
- $builder->join('VENDOR_INFLUENCER_PARTNERSHIP VIP', 'VL.SEQ = VIP.VENDOR_SEQ', 'inner');
- $builder->where('VIP.INFLUENCER_SEQ', $memberSeq);
- $builder->where('VIP.STATUS', 'APPROVED');
- $builder->where('VIP.IS_ACTIVE', 'Y');
- }
- // 키워드 검색
- if (!empty($keyword)) {
- if (empty($filter)) {
- // 필터를 선택 안했으면 전체 검색
- $first = true;
- foreach ($filterMap as $column) {
- if ($first) {
- $builder->like($column, $keyword);
- $first = false;
- } else {
- $builder->orLike($column, $keyword);
- }
- }
- } elseif (isset($filterMap[$filter])) {
- // 특정 필터 검색
- $builder->like($filterMap[$filter], $keyword);
- }
- }
- // 노출중, 비노출 여부 확인
- if (!empty($showYN)) {
- $builder->where('I.SHOW_YN', $showYN);
- }
- if (!empty($itemType)) {
- $builder->where('I.TYPE', $itemType);
- }
- // INF_SEQ 조건 추가 (값이 있을 때만)
- if (!empty($infSeq)) {
- $builder->where('I.CONTACT_INF', $infSeq);
- }
- // 날짜 범위 검색 (latest_reg_date 기준)
- if (!empty($startDate)) {
- $builder->where('O.latest_reg_date >=', $startDate . ' 00:00:00');
- }
- if (!empty($endDate)) {
- $builder->where('O.latest_reg_date <=', $endDate . ' 23:59:59');
- }
- $builder->orderBy('I.UDPDATE', 'DESC');
- // 조회
- $lists = $builder->get()->getResultArray();
- return $this->respond($lists, 200);
- }
- //배송중 검색
- public function shippingSearch()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
- $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
- $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
- $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
- $filter = isset($request['filter']) ? $request['filter'] : null;
- $keyword = isset($request['keyword']) ? $request['keyword'] : null;
- $startDate = isset($request['startDate']) ? $request['startDate'] : null;
- $endDate = isset($request['endDate']) ? $request['endDate'] : null;
- $builder = $db->table('ITEM_ORDER_LIST IOL')
- ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2')
- ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
- ->where('IOL.DELI_COMP !=', '')
- ->where('IOL.DELI_NUMB !=', '')
- ->where('IOL.DELI_COMP IS NOT NULL')
- ->where('IOL.DELI_NUMB IS NOT NULL');
- // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 조건 추가
- $columns = $db->getFieldNames('ITEM_ORDER_LIST');
- if (in_array('DELIVERY_STATUS', $columns)) {
- $builder->where('IOL.DELIVERY_STATUS', 'SHIPPING');
- } else {
- // DELIVERY_STATUS 컬럼이 없으면 배송업체와 송장번호가 있는 것을 배송중으로 간주
- // 단, 배송완료된 것은 제외 (DELIVERED_DATE가 없는 것만)
- if (in_array('DELIVERED_DATE', $columns)) {
- $builder->where('IOL.DELIVERED_DATE IS NULL');
- }
- }
- // 아이템 타입 필터링
- if (!empty($itemType)) {
- $builder->where('IL.TYPE', $itemType);
- }
- // 검색 조건 추가
- if (!empty($keyword)) {
- if ($filter === 'name') {
- $builder->like('IL.NAME', $keyword);
- } elseif ($filter === 'buyer') {
- $builder->like('IOL.BUYER_NAME', $keyword);
- } else {
- // 전체 검색
- $builder->groupStart()
- ->like('IL.NAME', $keyword)
- ->orLike('IOL.BUYER_NAME', $keyword)
- ->groupEnd();
- }
- }
- // 날짜 범위 검색
- if (!empty($startDate)) {
- $builder->where('DATE(IOL.SHIPPING_DATE) >=', $startDate);
- }
- if (!empty($endDate)) {
- $builder->where('DATE(IOL.SHIPPING_DATE) <=', $endDate);
- }
- // 사용자 타입에 따른 필터링
- if ($memberType === 'VENDOR' && !empty($companyNumber)) {
- $builder->where('IL.COMPANY_NUMBER', $companyNumber);
- } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
- $builder->where('IOL.INF_SEQ', $infSeq);
- }
- $builder->orderBy('IOL.REG_DATE', 'DESC');
- $lists = $builder->get()->getResultArray();
- return $this->respond($lists, 200);
- }
- //구매자 리스트
- public function delilist()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $itemSeq = isset($request['item_seq']) ? $request['item_seq'] : null;
- $infSeq = isset($request['inf_seq']) ? $request['inf_seq'] : null;
- // 쿼리 빌더
- $builder = $db->table('ITEM_ORDER_LIST I');
- $builder->select('I.*, U.NICK_NAME');
- $builder->join('USER_LIST U', 'I.INF_SEQ = U.SEQ', 'left');
- $builder->where('I.ITEM_SEQ', $itemSeq);
- if ($infSeq) {
- $builder->where('I.INF_SEQ', $infSeq);
- }
- // 배송정보가 등록되지 않은 주문만 표시 (송장번호 등록용)
- // 배송업체와 송장번호가 모두 비어있는 경우만 포함
- $builder->where('(I.DELI_COMP IS NULL OR I.DELI_COMP = "")')
- ->where('(I.DELI_NUMB IS NULL OR I.DELI_NUMB = "")');
- // 주문일 기준으로 정렬
- $builder->orderBy('I.ORDER_DATE', 'DESC');
- $lists = $builder->get()->getResultArray();
- return $this->respond($lists, 200);
- }
- //구매자 등록
- public function deliRegister()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $itemSeq = isset($request['item_seq']) ? $request['item_seq'] : null;
- $infSeq = isset($request['inf_seq']) ? $request['inf_seq'] : null;
- $deliveryList = $request['deliveryList'] ?? [];
- // 🔍 먼저 전체 유효성 검사
- foreach ($deliveryList as $index => $delivery) {
- $requiredFields = ['buyerName', 'address', 'phone', 'qty', 'total', 'orderDate'];
- foreach ($requiredFields as $field) {
- if (!isset($delivery[$field]) || $delivery[$field] === '') {
- return $this->fail("deliveryList[$index] 항목의 '{$field}' 값이 누락되었습니다.", 400);
- }
- }
- }
- // ✅ 유효성 통과 후 삭제 + 삽입
- $db->table('ITEM_ORDER_LIST')
- ->where('ITEM_SEQ', $itemSeq)
- ->where('INF_SEQ', $infSeq)
- ->delete();
- foreach ($deliveryList as $delivery) {
- $data = [
- 'ITEM_SEQ' => $itemSeq,
- 'INF_SEQ' => $infSeq,
- 'BUYER_NAME' => $delivery['buyerName'],
- 'ADDRESS' => $delivery['address'],
- 'PHONE' => $delivery['phone'],
- 'EMAIL' => $delivery['email'],
- 'QTY' => $delivery['qty'],
- 'TOTAL' => $delivery['total'],
- 'DELI_COMP' => $delivery['deliComp'] ?? '',
- 'DELI_NUMB' => $delivery['deliNumb'] ?? '',
- 'ORDER_DATE' => date('Y-m-d H:i:s', strtotime($delivery['orderDate'])),
- 'REG_DATE' => date('Y-m-d'),
- ];
- $db->table('ITEM_ORDER_LIST')->insert($data);
- }
- return $this->respond(['message' => '배송 데이터가 성공적으로 저장되었습니다.'], 200);
- }
- //벤더사용 배송정보 업데이트
- public function updateDeliveryInfo()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $itemSeq = isset($request['item_seq']) ? $request['item_seq'] : null;
- $deliveryUpdates = $request['deliveryUpdates'] ?? [];
- if (!$itemSeq || empty($deliveryUpdates)) {
- return $this->fail('필수 파라미터가 누락되었습니다.', 400);
- }
- $db->transBegin();
- $updatedCount = 0;
- $errors = [];
- try {
- foreach ($deliveryUpdates as $update) {
- $buyerName = $update['buyerName'] ?? '';
- $phone = $update['phone'] ?? '';
- $deliComp = $update['deliComp'] ?? '';
- $deliNumb = $update['deliNumb'] ?? '';
- if (!$buyerName || !$phone) {
- $errors[] = "구매자명과 연락처는 필수입니다.";
- continue;
- }
- // 업데이트할 데이터 준비
- $updateData = [
- 'DELI_COMP' => $deliComp,
- 'DELI_NUMB' => $deliNumb
- ];
- // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 추가
- $columns = $db->getFieldNames('ITEM_ORDER_LIST');
- if (in_array('DELIVERY_STATUS', $columns)) {
- $updateData['DELIVERY_STATUS'] = 'SHIPPING';
- }
- if (in_array('SHIPPING_DATE', $columns)) {
- $updateData['SHIPPING_DATE'] = date('Y-m-d H:i:s');
- }
- // 구매자명과 연락처로 해당 주문 찾기
- $result = $db->table('ITEM_ORDER_LIST')
- ->where('ITEM_SEQ', $itemSeq)
- ->where('BUYER_NAME', $buyerName)
- ->where('PHONE', $phone)
- ->update($updateData);
- if ($result) {
- $updatedCount++;
- } else {
- $errors[] = "매칭되는 주문을 찾을 수 없습니다: {$buyerName}({$phone})";
- }
- }
- if ($updatedCount > 0) {
- $db->transCommit();
- return $this->respond([
- 'message' => "배송정보가 성공적으로 업데이트되었습니다.",
- 'updated_count' => $updatedCount,
- 'errors' => $errors
- ], 200);
- } else {
- $db->transRollback();
- return $this->fail('업데이트할 수 있는 데이터가 없습니다.', 400);
- }
- } catch (\Exception $e) {
- $db->transRollback();
- return $this->fail('배송정보 업데이트 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
- }
- }
- //아이템 상세
- public function itemDetail($seq)
- {
- // DB 객체 얻기
- $db = \Config\Database::connect();
- $builder = $db->table('ITEM_LIST');
- $item = $builder->where('seq', $seq)->get()->getRowArray();
- if($item){
- return $this->respond($item, 200);
- } else {
- return $this->respond([
- 'status' => 'fail',
- 'message' => '유효하지 않은 seq입니다.'
- ], 404);
- }
- }
- //아이템 삭제
- public function itemDelete($seq)
- {
- $db = \Config\Database::connect();
- $db->transBegin();
- //아이템 삭제
- $deleted = $db->table('ITEM_LIST')
- ->where('SEQ', $seq)
- ->update(['DEL_YN' => 'Y']);
- if ($db->transStatus() === false || !$deleted) {
- $db->transRollback();
- return $this->respond(['status' => 'fail', 'message' => '이벤트 삭제 중 오류가 발생했습니다.']);
- }
- $db->transCommit();
- return $this->respond(['status' => 'success', 'message' => '이벤트가 삭제되었습니다.'], 200);
- }
- // 배송중 리스트 조회
- public function getShippingList()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
- $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
- $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
- $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
- $builder = $db->table('ITEM_ORDER_LIST IOL')
- ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2')
- ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
- ->where('IOL.DELI_COMP !=', '')
- ->where('IOL.DELI_NUMB !=', '')
- ->where('IOL.DELI_COMP IS NOT NULL')
- ->where('IOL.DELI_NUMB IS NOT NULL');
- // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 조건 추가
- $columns = $db->getFieldNames('ITEM_ORDER_LIST');
- if (in_array('DELIVERY_STATUS', $columns)) {
- $builder->where('IOL.DELIVERY_STATUS', 'SHIPPING');
- } else {
- // DELIVERY_STATUS 컬럼이 없으면 배송업체와 송장번호가 있는 것을 배송중으로 간주
- // 단, 배송완료된 것은 제외 (DELIVERED_DATE가 없는 것만)
- if (in_array('DELIVERED_DATE', $columns)) {
- $builder->where('IOL.DELIVERED_DATE IS NULL');
- }
- }
- // 아이템 타입 필터링
- if (!empty($itemType)) {
- $builder->where('IL.TYPE', $itemType);
- }
- // 사용자 타입에 따른 필터링
- if ($memberType === 'VENDOR' && !empty($companyNumber)) {
- $builder->where('IL.COMPANY_NUMBER', $companyNumber);
- } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
- $builder->where('IOL.INF_SEQ', $infSeq);
- }
- $builder->orderBy('IOL.REG_DATE', 'DESC');
- $lists = $builder->get()->getResultArray();
- return $this->respond($lists, 200);
- }
- // 배송완료 리스트 조회
- public function getDeliveredList()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
- $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
- $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
- $itemType = isset($request['TYPE']) ? $request['TYPE'] : null;
- $builder = $db->table('ITEM_ORDER_LIST IOL')
- ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2')
- ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner');
- // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 조건 추가
- $columns = $db->getFieldNames('ITEM_ORDER_LIST');
- if (in_array('DELIVERY_STATUS', $columns)) {
- $builder->where('IOL.DELIVERY_STATUS', 'DELIVERED');
- } else {
- // DELIVERY_STATUS 컬럼이 없으면 배송업체와 송장번호가 있는 것을 배송완료로 간주
- $builder->where('IOL.DELI_COMP !=', '')
- ->where('IOL.DELI_NUMB !=', '')
- ->where('IOL.DELI_COMP IS NOT NULL')
- ->where('IOL.DELI_NUMB IS NOT NULL');
- }
- // 아이템 타입 필터링
- if (!empty($itemType)) {
- $builder->where('IL.TYPE', $itemType);
- }
- // 정산완료되지 않은 주문만 표시 (배송완료 페이지용)
- if (in_array('SETTLEMENT_STATUS', $columns)) {
- $builder->where('(IOL.SETTLEMENT_STATUS IS NULL OR IOL.SETTLEMENT_STATUS != "COMPLETED")');
- }
- // 사용자 타입에 따른 필터링
- if ($memberType === 'VENDOR' && !empty($companyNumber)) {
- $builder->where('IL.COMPANY_NUMBER', $companyNumber);
- } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
- $builder->where('IOL.INF_SEQ', $infSeq);
- }
- // 정렬을 안전하게 처리
- if (in_array('DELIVERED_DATE', $columns)) {
- $builder->orderBy('IOL.DELIVERED_DATE', 'DESC');
- } else {
- $builder->orderBy('IOL.REG_DATE', 'DESC');
- }
- $lists = $builder->get()->getResultArray();
- return $this->respond($lists, 200);
- }
- // 배송완료 처리
- public function markAsDelivered()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $orderIds = isset($request['order_ids']) ? $request['order_ids'] : [];
- if (empty($orderIds)) {
- return $this->fail('처리할 주문이 선택되지 않았습니다.', 400);
- }
- $db->transBegin();
- try {
- foreach ($orderIds as $orderId) {
- $db->table('ITEM_ORDER_LIST')
- ->where('SEQ', $orderId)
- ->update([
- 'DELIVERY_STATUS' => 'DELIVERED',
- 'DELIVERED_DATE' => date('Y-m-d H:i:s')
- ]);
- }
- $db->transCommit();
- return $this->respond(['message' => '배송완료 처리되었습니다.'], 200);
- } catch (\Exception $e) {
- $db->transRollback();
- return $this->fail('배송완료 처리 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
- }
- }
- // 정산완료 처리
- public function markAsSettled()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $orderIds = isset($request['order_ids']) ? $request['order_ids'] : [];
- if (empty($orderIds)) {
- return $this->fail('처리할 주문이 선택되지 않았습니다.', 400);
- }
- $db->transBegin();
- try {
- foreach ($orderIds as $orderId) {
- $db->table('ITEM_ORDER_LIST')
- ->where('SEQ', $orderId)
- ->update([
- 'SETTLEMENT_STATUS' => 'COMPLETED',
- 'SETTLED_DATE' => date('Y-m-d H:i:s')
- ]);
- }
- $db->transCommit();
- return $this->respond(['message' => '정산완료 처리되었습니다.'], 200);
- } catch (\Exception $e) {
- $db->transRollback();
- return $this->fail('정산완료 처리 중 오류가 발생했습니다: ' . $e->getMessage(), 500);
- }
- }
- // 정산관리 리스트 조회
- public function getSettlementList()
- {
- $db = \Config\Database::connect();
- $request = $this->request->getJSON(true);
- $memberType = isset($request['MEMBER_TYPE']) ? $request['MEMBER_TYPE'] : null;
- $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
- $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
- $settlementStatus = isset($request['SETTLEMENT_STATUS']) ? $request['SETTLEMENT_STATUS'] : null;
- $builder = $db->table('ITEM_ORDER_LIST IOL')
- ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2, IL.TYPE as ITEM_TYPE, UL.NICK_NAME as INF_NICK_NAME')
- ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
- ->join('USER_LIST UL', 'IOL.INF_SEQ = UL.SEQ', 'left');
- // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 조건 추가
- $columns = $db->getFieldNames('ITEM_ORDER_LIST');
- if (in_array('DELIVERY_STATUS', $columns)) {
- $builder->where('IOL.DELIVERY_STATUS', 'DELIVERED');
- } else {
- // DELIVERY_STATUS 컬럼이 없으면 배송업체와 송장번호가 있는 것을 대상으로 함
- $builder->where('IOL.DELI_COMP !=', '')
- ->where('IOL.DELI_NUMB !=', '')
- ->where('IOL.DELI_COMP IS NOT NULL')
- ->where('IOL.DELI_NUMB IS NOT NULL');
- }
- // 정산 상태 필터링 (SETTLEMENT_STATUS 컬럼이 존재하는 경우만)
- if ($settlementStatus && in_array('SETTLEMENT_STATUS', $columns)) {
- $builder->where('IOL.SETTLEMENT_STATUS', $settlementStatus);
- }
- // 사용자 타입에 따른 필터링
- if ($memberType === 'VENDOR' && !empty($companyNumber)) {
- $builder->where('IL.COMPANY_NUMBER', $companyNumber);
- } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
- $builder->where('IOL.INF_SEQ', $infSeq);
- }
- $builder->orderBy('IOL.DELIVERED_DATE', 'DESC');
- $lists = $builder->get()->getResultArray();
- return $this->respond($lists, 200);
- }
- }
|