Przeglądaj źródła

+ deli 업데이트

송용우 4 miesięcy temu
rodzic
commit
f36c91198b

+ 2 - 0
backend/app/Config/Routes2.php

@@ -125,6 +125,8 @@ $routes->post('deli/markSettled', 'Deli::markAsSettled');
 $routes->post('deli/settlement', 'Deli::getSettlementList');
 $routes->post('deli/pendingOrdersForVendor', 'Deli::getPendingOrdersForVendor');
 $routes->post('deli/updateStatus', 'Deli::updateStatus');
+$routes->post('deli/debugOrderData', 'Deli::debugOrderData');
+$routes->post('deli/shippingDebug', 'Deli::getShippingListDebug');
 
 // =============================================================================
 // 파트너십 전용 웹 라우팅 (향후 확장)

+ 211 - 8
backend/app/Controllers/Deli.php

@@ -157,6 +157,20 @@ class Deli extends ResourceController
                         'REG_DATE' => date('Y-m-d'),
                     ];
 
+                    // DELIVERY_STATUS 컬럼이 있으면 상태 설정
+                    $columns = $db->getFieldNames('ITEM_ORDER_LIST');
+                    if (in_array('DELIVERY_STATUS', $columns)) {
+                        // 배송업체와 송장번호가 모두 있으면 SHIPPING, 없으면 PENDING
+                        if (!empty($delivery['deliComp']) && !empty($delivery['deliNumb'])) {
+                            $data['DELIVERY_STATUS'] = 'SHIPPING';
+                            if (in_array('SHIPPING_DATE', $columns)) {
+                                $data['SHIPPING_DATE'] = date('Y-m-d H:i:s');
+                            }
+                        } else {
+                            $data['DELIVERY_STATUS'] = 'PENDING';
+                        }
+                    }
+
                     if ($existingOrder) {
                         // 기존 주문 업데이트
                         $db->table('ITEM_ORDER_LIST')
@@ -192,6 +206,20 @@ class Deli extends ResourceController
                         'REG_DATE' => date('Y-m-d'),
                     ];
 
+                    // DELIVERY_STATUS 컬럼이 있으면 상태 설정
+                    $columns = $db->getFieldNames('ITEM_ORDER_LIST');
+                    if (in_array('DELIVERY_STATUS', $columns)) {
+                        // 배송업체와 송장번호가 모두 있으면 SHIPPING, 없으면 PENDING
+                        if (!empty($delivery['deliComp']) && !empty($delivery['deliNumb'])) {
+                            $data['DELIVERY_STATUS'] = 'SHIPPING';
+                            if (in_array('SHIPPING_DATE', $columns)) {
+                                $data['SHIPPING_DATE'] = date('Y-m-d H:i:s');
+                            }
+                        } else {
+                            $data['DELIVERY_STATUS'] = 'PENDING';
+                        }
+                    }
+
                     $db->table('ITEM_ORDER_LIST')->insert($data);
                     $insertCount++;
                 }
@@ -233,12 +261,16 @@ class Deli extends ResourceController
         $errors = [];
 
         try {
+            log_message('info', '벤더 배송정보 업데이트 요청: ' . json_encode($request));
+            
             foreach ($deliveryUpdates as $update) {
                 $buyerName = $update['buyerName'] ?? '';
                 $phone = $update['phone'] ?? '';
                 $deliComp = $update['deliComp'] ?? '';
                 $deliNumb = $update['deliNumb'] ?? '';
 
+                log_message('info', "배송정보 업데이트 시도: {$buyerName}({$phone}) - 배송업체: {$deliComp}, 송장번호: {$deliNumb}");
+
                 if (!$buyerName || !$phone) {
                     $errors[] = "구매자명과 연락처는 필수입니다.";
                     continue;
@@ -263,13 +295,29 @@ class Deli extends ResourceController
                     }
                 }
 
-                // 구매자명과 연락처로 해당 주문 찾기
+                // 먼저 해당 조건의 데이터가 존재하는지 확인
+                $existingOrder = $db->table('ITEM_ORDER_LIST')
+                    ->where('ITEM_SEQ', $itemSeq)
+                    ->where('BUYER_NAME', $buyerName)
+                    ->where('PHONE', $phone)
+                    ->get()
+                    ->getRowArray();
+                
+                log_message('info', '업데이트 조건: ITEM_SEQ=' . $itemSeq . ', BUYER_NAME=' . $buyerName . ', PHONE=' . $phone);
+                log_message('info', '기존 주문 존재 여부: ' . ($existingOrder ? 'YES' : 'NO'));
+                if ($existingOrder) {
+                    log_message('info', '기존 주문 데이터: ' . json_encode($existingOrder));
+                }
+                log_message('info', '업데이트 데이터: ' . json_encode($updateData));
+                
                 $result = $db->table('ITEM_ORDER_LIST')
                     ->where('ITEM_SEQ', $itemSeq)
                     ->where('BUYER_NAME', $buyerName)
                     ->where('PHONE', $phone)
                     ->update($updateData);
 
+                log_message('info', '업데이트 결과: ' . ($result ? 'SUCCESS' : 'FAILED') . ' (affected rows: ' . $result . ')');
+
                 if ($result) {
                     $updatedCount++;
                 } else {
@@ -343,37 +391,77 @@ class Deli extends ResourceController
         $companyNumber = isset($request['COMPANY_NUMBER']) ? $request['COMPANY_NUMBER'] : null;
         $infSeq = isset($request['INF_SEQ']) ? $request['INF_SEQ'] : null;
 
+        // 디버깅 로그
+        log_message('info', '배송중 리스트 조회 파라미터: ' . json_encode($request));
+
         $builder = $db->table('ITEM_ORDER_LIST IOL')
             ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2, U.NICK_NAME')
             ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
-            ->join('USER_LIST U', 'IOL.INF_SEQ = U.SEQ', 'left')
-            ->where('IOL.DELI_COMP !=', '')
-            ->where('IOL.DELI_NUMB !=', '')
-            ->where('IOL.DELI_COMP IS NOT NULL')
-            ->where('IOL.DELI_NUMB IS NOT NULL');
+            ->join('USER_LIST U', 'IOL.INF_SEQ = U.SEQ', 'left');
 
         // DELIVERY_STATUS 컬럼이 존재하는지 확인하고 조건 추가
         $columns = $db->getFieldNames('ITEM_ORDER_LIST');
+        log_message('info', 'ITEM_ORDER_LIST 컬럼: ' . json_encode($columns));
+        
         if (in_array('DELIVERY_STATUS', $columns)) {
-            $builder->where('IOL.DELIVERY_STATUS', 'SHIPPING');
+            // DELIVERY_STATUS 컬럼이 있는 경우 - 배송업체와 송장번호가 있으면서 SHIPPING 상태인 것
+            $builder->where('IOL.DELI_COMP !=', '')
+                    ->where('IOL.DELI_NUMB !=', '')
+                    ->where('IOL.DELI_COMP IS NOT NULL')
+                    ->where('IOL.DELI_NUMB IS NOT NULL')
+                    ->where('IOL.DELIVERY_STATUS', 'SHIPPING');
+            log_message('info', '배송중 조건: 배송정보 있고 DELIVERY_STATUS = SHIPPING');
         } else {
             // DELIVERY_STATUS 컬럼이 없으면 배송업체와 송장번호가 있는 것을 배송중으로 간주
-            // 단, 배송완료된 것은 제외 (DELIVERED_DATE가 없는 것만)
+            $builder->where('IOL.DELI_COMP !=', '')
+                    ->where('IOL.DELI_NUMB !=', '')
+                    ->where('IOL.DELI_COMP IS NOT NULL')
+                    ->where('IOL.DELI_NUMB IS NOT NULL');
+            
+            // 배송완료된 것은 제외 (DELIVERED_DATE가 없는 것만)
             if (in_array('DELIVERED_DATE', $columns)) {
                 $builder->where('IOL.DELIVERED_DATE IS NULL');
             }
+            log_message('info', '배송중 조건: 배송업체+송장번호 있고 배송완료일 없음');
         }
 
         // 사용자 타입에 따른 필터링
         if ($memberType === 'VENDOR' && !empty($companyNumber)) {
             $builder->where('IL.COMPANY_NUMBER', $companyNumber);
+            log_message('info', '벤더 필터링: COMPANY_NUMBER = ' . $companyNumber);
         } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
             $builder->where('IOL.INF_SEQ', $infSeq);
+            log_message('info', '인플루언서 필터링: INF_SEQ = ' . $infSeq);
         }
 
         $builder->orderBy('IOL.REG_DATE', 'DESC');
+        
+        // 실행된 쿼리 로그
+        $query = $builder->getCompiledSelect(false);
+        log_message('info', '배송중 리스트 쿼리: ' . $query);
+        
         $lists = $builder->get()->getResultArray();
+        log_message('info', '배송중 리스트 결과 개수: ' . count($lists));
+        
+        // 첫 번째 결과 로그
+        if (!empty($lists)) {
+            log_message('info', '첫 번째 배송중 데이터: ' . json_encode($lists[0]));
+        }
 
+        // 디버깅을 위해 조건 없이 전체 데이터도 확인
+        $allDataBuilder = $db->table('ITEM_ORDER_LIST IOL')
+            ->select('IOL.*, IL.NAME as ITEM_NAME')
+            ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner');
+            
+        if ($memberType === 'VENDOR' && !empty($companyNumber)) {
+            $allDataBuilder->where('IL.COMPANY_NUMBER', $companyNumber);
+        } elseif ($memberType === 'INFLUENCER' && !empty($infSeq)) {
+            $allDataBuilder->where('IOL.INF_SEQ', $infSeq);
+        }
+        
+        $allDataBuilder->orderBy('IOL.REG_DATE', 'DESC')->limit(5);
+        $allData = $allDataBuilder->get()->getResultArray();
+        log_message('info', '전체 주문 데이터 (최근 5건): ' . json_encode($allData));
 
         return $this->respond($lists, 200);
     }
@@ -639,4 +727,119 @@ class Deli extends ResourceController
         }
     }
 
+    // 디버깅용 주문 데이터 조회
+    public function debugOrderData()
+    {
+        $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;
+
+        // 전체 주문 데이터 조회
+        $builder = $db->table('ITEM_ORDER_LIST IOL')
+            ->select('IOL.*, IL.NAME as ITEM_NAME, IL.COMPANY_NUMBER as ITEM_COMPANY')
+            ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner');
+
+        // 사용자 타입에 따른 필터링
+        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')
+                ->limit(10); // 최근 10건만
+
+        $orders = $builder->get()->getResultArray();
+
+        // 컬럼 정보도 함께 반환
+        $columns = $db->getFieldNames('ITEM_ORDER_LIST');
+
+        return $this->respond([
+            'columns' => $columns,
+            'orders' => $orders,
+            'count' => count($orders),
+            'filter' => [
+                'memberType' => $memberType,
+                'companyNumber' => $companyNumber,
+                'infSeq' => $infSeq
+            ]
+        ], 200);
+    }
+
+    // 배송중 데이터 강제 조회 (디버깅용)
+    public function getShippingListDebug()
+    {
+        $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;
+
+        $builder = $db->table('ITEM_ORDER_LIST IOL')
+            ->select('IOL.*, IL.NAME as ITEM_NAME, IL.PRICE1, IL.PRICE2, U.NICK_NAME')
+            ->join('ITEM_LIST IL', 'IOL.ITEM_SEQ = IL.SEQ', 'inner')
+            ->join('USER_LIST U', 'IOL.INF_SEQ = U.SEQ', 'left');
+
+        // 사용자 타입에 따른 필터링만 적용 (배송 조건 제외)
+        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');
+        $allData = $builder->get()->getResultArray();
+
+        // 각 조건별로 분류
+        $withDeliveryInfo = [];
+        $withShippingStatus = [];
+        $withBoth = [];
+        
+        $columns = $db->getFieldNames('ITEM_ORDER_LIST');
+        
+        foreach ($allData as $item) {
+            $hasDeliveryInfo = !empty($item['DELI_COMP']) && !empty($item['DELI_NUMB']);
+            $hasShippingStatus = isset($item['DELIVERY_STATUS']) && $item['DELIVERY_STATUS'] === 'SHIPPING';
+            
+            if ($hasDeliveryInfo) {
+                $withDeliveryInfo[] = $item;
+            }
+            
+            if ($hasShippingStatus) {
+                $withShippingStatus[] = $item;
+            }
+            
+            if ($hasDeliveryInfo && $hasShippingStatus) {
+                $withBoth[] = $item;
+            }
+        }
+
+        return $this->respond([
+            'columns' => $columns,
+            'total_count' => count($allData),
+            'with_delivery_info' => [
+                'count' => count($withDeliveryInfo),
+                'data' => array_slice($withDeliveryInfo, 0, 3)
+            ],
+            'with_shipping_status' => [
+                'count' => count($withShippingStatus),
+                'data' => array_slice($withShippingStatus, 0, 3)
+            ],
+            'with_both_conditions' => [
+                'count' => count($withBoth),
+                'data' => array_slice($withBoth, 0, 3)
+            ],
+            'sample_all_data' => array_slice($allData, 0, 3),
+            'filter' => [
+                'memberType' => $memberType,
+                'companyNumber' => $companyNumber,
+                'infSeq' => $infSeq
+            ]
+        ], 200);
+    }
+
 }

+ 45 - 65
pages/view/common/deli/detail.vue

@@ -74,6 +74,7 @@
             :paginationPageSize="pageObj.pageSize"
             :suppressPaginationPanel="true"
             @grid-ready="onGridReady"
+            @cell-value-changed="onCellValueChanged"
           >
           </ag-grid-vue>
 
@@ -265,6 +266,18 @@
       enableClickSelection: false,
       mode: "multiRow",
     },
+    // 셀 편집 완료 시 데이터 업데이트
+    onCellValueChanged: (event) => {
+      const rowIndex = event.rowIndex;
+      const field = event.colDef.field;
+      const newValue = event.newValue;
+      
+      // tblItems 배열의 해당 행 데이터 업데이트
+      if (rowIndex >= 0 && rowIndex < tblItems.value.length) {
+        tblItems.value[rowIndex][field] = newValue;
+        console.log(`셀 편집 완료: ${field} = ${newValue} (행 ${rowIndex})`);
+      }
+    },
   };
 
   /************************************************************************
@@ -279,6 +292,29 @@
     gridApi.value = __PARAMS.api;
   };
 
+  const onCellValueChanged = (event) => {
+    const rowIndex = event.rowIndex;
+    const field = event.colDef.field;
+    const newValue = event.newValue;
+    
+    // tblItems 배열의 해당 행 데이터 업데이트
+    if (rowIndex >= 0 && rowIndex < tblItems.value.length) {
+      tblItems.value[rowIndex][field] = newValue;
+      console.log(`셀 편집 완료: ${field} = ${newValue} (행 ${rowIndex})`);
+      
+      // 배송업체나 송장번호가 변경된 경우 추가 로직
+      if (field === 'DELI_COMP' || field === 'DELI_NUMB') {
+        console.log('배송정보 변경됨:', {
+          row: rowIndex,
+          field: field,
+          value: newValue,
+          DELI_COMP: tblItems.value[rowIndex].DELI_COMP,
+          DELI_NUMB: tblItems.value[rowIndex].DELI_NUMB
+        });
+      }
+    }
+  };
+
   const chgPage = (__PAGE) => {
     pageObj.value.page = __PAGE;
     gridApi.value.paginationGoToPage(__PAGE - 1);
@@ -1067,43 +1103,7 @@
       return useAxios().post("/deli/reg", deliveryData);
     }, "배송 데이터를 저장하는 중...")
       .then((res) => {
-        // 송장번호가 등록된 경우 상태를 COMPLETE로 업데이트
-        const hasTrackingNumbers = deliveryData.deliveryList.some(
-          (item) => item.deliNumb && typeof item.deliNumb === 'string' && item.deliNumb.trim() !== ""
-        );
-
-        if (hasTrackingNumbers) {
-          // 상태 업데이트 API 호출
-          const statusUpdateData = {
-            item_seq: useDtStore.boardInfo.seq,
-            status: "COMPLETE",
-          };
-
-          useAxios()
-            .post("/deli/updateStatus", statusUpdateData)
-            .then(() => {
-              $toast.success(
-                "배송 데이터가 성공적으로 저장되었습니다. 상태가 완료로 변경되었습니다."
-              );
-
-              // WebSocket을 통해 상태 변경 이벤트 발행
-              const { $socket } = useNuxtApp();
-              if ($socket) {
-                $socket.emit("deliveryStatusUpdate", {
-                  itemId: useDtStore.boardInfo.seq,
-                  itemName: form.value.formValue1,
-                  status: "COMPLETE",
-                  updatedBy: memberSeq,
-                  updatedAt: new Date().toISOString(),
-                });
-              }
-            })
-            .catch(() => {
-              $toast.success("배송 데이터가 저장되었으나 상태 업데이트에 실패했습니다.");
-            });
-        } else {
-          $toast.success("배송 데이터가 성공적으로 저장되었습니다.");
-        }
+        $toast.success("배송 데이터가 성공적으로 저장되었습니다.");
 
         // 저장 완료 후 배송 관리 리스트로 이동하며 업로드 성공 상태 전달
         router.push({
@@ -1112,7 +1112,7 @@
             uploadStatus: "success",
             itemId: useDtStore.boardInfo.seq,
             recordCount: tblItems.value.length,
-            statusUpdated: hasTrackingNumbers ? "true" : "false",
+            statusUpdated: "false",
           },
         });
       })
@@ -1139,6 +1139,11 @@
       return;
     }
 
+    console.log('벤더 배송정보 업데이트 데이터:', {
+      item_seq: useDtStore.boardInfo.seq,
+      deliveryUpdates: deliveryUpdates
+    });
+
     const updateData = {
       item_seq: useDtStore.boardInfo.seq,
       deliveryUpdates: deliveryUpdates
@@ -1148,32 +1153,7 @@
       return useAxios().post("/deli/updateDeliveryInfo", updateData);
     }, "배송정보를 업데이트하는 중...")
       .then((res) => {
-        // 송장번호가 등록된 경우 상태를 COMPLETE로 업데이트
-        const hasTrackingNumbers = deliveryUpdates.some(
-          (item) => item.deliNumb && typeof item.deliNumb === 'string' && item.deliNumb.trim() !== ""
-        );
-
-        if (hasTrackingNumbers) {
-          // 상태 업데이트 API 호출
-          const statusUpdateData = {
-            item_seq: useDtStore.boardInfo.seq,
-            status: "COMPLETE",
-          };
-
-          useAxios()
-            .post("/deli/updateStatus", statusUpdateData)
-            .then(() => {
-              $toast.success(
-                "배송정보가 업데이트되고 상태가 완료로 변경되었습니다."
-              );
-            })
-            .catch((error) => {
-              console.error("상태 업데이트 실패:", error);
-              $toast.warning("배송정보는 업데이트되었으나 상태 변경에 실패했습니다.");
-            });
-        } else {
-          $toast.success(`${res.data.updated_count}건의 배송정보가 업데이트되었습니다.`);
-        }
+        $toast.success(`${res.data.updated_count}건의 배송정보가 업데이트되었습니다.`);
 
         // 배송 관리 목록으로 이동
         router.push({
@@ -1182,7 +1162,7 @@
             uploadStatus: "success",
             itemId: useDtStore.boardInfo.seq,
             recordCount: res.data.updated_count,
-            statusUpdated: hasTrackingNumbers ? "true" : "false",
+            statusUpdated: "false",
           },
         });
       })