| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203 |
- <template>
- <div>
- <div class="inner--headers">
- <h2>{{ pageId }}</h2>
- <div class="bread--crumbs--wrap">
- <span>홈</span>
- <span>{{ pageId }}</span>
- </div>
- </div>
- <div class="data--list--wrap">
- <div class="btn--actions--wrap">
- <div class="left--sections">
- <v-btn class="custom-btn btn-pink bdrs--10"><i class="ico"></i>개별 배송</v-btn>
- <v-btn class="custom-btn bdrs--10 btn-white" @click="deliLocated()"
- ><i class="ico"></i>공동구매 배송</v-btn
- >
- </div>
- <div class="right--sections"></div>
- </div>
- <div class="item--section">
- <div v-if="imgTemp" class="item--thumb">
- <img :src="imgTemp" alt="" />
- </div>
- <div v-else class="item--thumb min--240">NO IMAGE</div>
- <div class="item--info">
- <h2>{{ form.formValue1 }}</h2>
- <p>공급가: {{ Number(form.formValue2).toLocaleString() }}원</p>
- <p>판매가: {{ Number(form.formValue3).toLocaleString() }}원</p>
- </div>
- </div>
- <div class="btn--actions--wrap">
- <div class="left--sections"></div>
- <div class="right--sections">
- <div class="caption--wrap">
- <i class="ico">!</i>
- <div class="caption--box">
- - 주문일은 YYYY.MM.DD 혹은 YYYY-MM-DD 형태로 입력해 주세요.<br />
- - 구매자 정보 입력 후 저장 버튼을 꼭 클릭해 주세요.<br />
- - 엑셀 파일은 최대 10MB까지 업로드 가능합니다.<br />
- - 엑셀 파일의 헤더는 다음과 같아야 합니다: 구매자명, 주소, 연락처, 이메일,
- 구매수량, 총구매금액, 배송업체, 송장번호, 주문일
- </div>
- </div>
- <v-btn class="custom-btn btn-white mini" @click="addEmptyRow"
- ><i class="ico"></i>항목 추가</v-btn
- >
- <v-btn class="custom-btn btn-white mini" @click="deleteSelectedRows"
- ><i class="ico"></i>항목 삭제</v-btn
- >
- <input
- ref="excelFileInput"
- type="file"
- accept=".xlsx,.xls"
- @change="handleExcelUpload"
- style="display: none"
- />
- <v-btn class="custom-btn btn-excel" @click="$refs.excelFileInput.click()"
- ><i class="ico"></i>엑셀 업로드</v-btn
- >
- <v-btn class="custom-btn btn-excel" @click="downloadExcel"
- ><i class="ico"></i>엑셀 다운로드</v-btn
- >
- </div>
- </div>
- <div class="tbl-wrapper">
- <div class="tbl-wrap">
- <!-- ag grid -->
- <ag-grid-vue
- style="width: 100%; height: calc(10 * 2.94rem)"
- class="ag-theme-quartz"
- :gridOptions="gridOptions"
- rowSelection="multiple"
- :rowData="tblItems"
- :paginationPageSize="pageObj.pageSize"
- :suppressPaginationPanel="true"
- @grid-ready="onGridReady"
- @cell-value-changed="onCellValueChanged"
- >
- </ag-grid-vue>
- <!-- 페이징 -->
- <div class="ag-grid-custom-pagenations">
- <pagination @chg_page="chgPage" :pageObj="pageObj"></pagination>
- </div>
- </div>
- </div>
- <div class="view-btm-btn">
- <div class="btn-l">
- <v-btn class="custom-btn btn-list" @click="listLocated"
- ><i class="ico"></i>목록</v-btn
- >
- </div>
- <div class="btn-r">
- <v-btn class="custom-btn btn-blue2" @click="fnRegEvt"
- ><i class="ico"></i>저장</v-btn
- >
- </div>
- </div>
- </div>
- <!-- 로딩 오버레이 -->
- <LoadingOverlay :is-loading="isLoading" :loading-message="loadingMessage" />
- </div>
- </template>
- <script setup>
- import "@vuepic/vue-datepicker/dist/main.css";
- import { AgGridVue } from "ag-grid-vue3";
- import * as XLSX from "xlsx";
- import pagination from "../components/common/pagination.vue";
- /************************************************************************
- | 레이아웃
- ************************************************************************/
- definePageMeta({
- layout: "default",
- });
- /************************************************************************
- | PROPS
- ************************************************************************/
- const props = defineProps({
- propsData: {
- type: Object,
- default: () => {},
- },
- });
- /************************************************************************
- | 스토어
- ************************************************************************/
- const useDtStore = useDetailStore();
- const useAtStore = useAuthStore();
- /************************************************************************
- | 전역
- ************************************************************************/
- const memberType = useAtStore.auth.memberType;
- const memberSeq = useAtStore.auth.seq;
- const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
- const router = useRouter();
- const pageId = ref("배송 관리");
- const { isLoading, loadingMessage, withLoading } = useLoading();
- let pageObj = ref({
- page: 1, // 현재 페이지
- pageMaxNumSize: 10, // 페이지 숫자 최대 표현 개수
- pageSize: 10, // 테이블 조회 데이터 개수
- totalCnt: 0, // 전체 페이지
- });
- const imgTemp = ref("");
- const tblItems = ref([]); // stat 데이터
- const isExcelProcessed = ref(false); // 엑셀 업로드로 데이터가 처리되었는지 여부
- const form = ref({
- formValue1: "",
- formValue2: "",
- formValue3: "",
- formValue4: "",
- formValue5: null,
- formValue6: "",
- formValue7: "",
- formValue8: "0",
- formValue8Arr: [
- { title: "판매중", value: "0" },
- { title: "품절", value: "1" },
- ],
- formValue9: "Y",
- formValue9Arr: [
- { title: "노출", value: "Y" },
- { title: "비노출", value: "N" },
- ],
- formValue10: "",
- });
- /* eslint-disable */
- /* prettier-ignore */
- pageObj.value.totalCnt = tblItems.value.length;
- const remToPx = () => parseFloat(getComputedStyle(document.documentElement).fontSize);
- const rowHeightRem = 2.65; // 원하는 rem 값
- const rowHeightPx = rowHeightRem * remToPx();
- const gridApi = shallowRef();
- // gridOption
- const gridOptions = {
- columnDefs: [
- { checkboxSelection: true, headerCheckboxSelection: true, width: 50 },
- {
- headerName: "No",
- valueGetter: (params) => params.api.getDisplayedRowCount() - params.node.rowIndex,
- sortable: false,
- width: 70,
- },
- {
- headerName: "인플루언서",
- field: "NICK_NAME",
- width: 150,
- hide: memberType == "INFLUENCER",
- },
- {
- headerName: "구매자명",
- field: "BUYER_NAME",
- width: 120,
- editable: true,
- },
- {
- headerName: "주소",
- field: "ADDRESS",
- editable: true,
- },
- {
- headerName: "연락처",
- field: "PHONE",
- width: 140,
- editable: true,
- },
- {
- headerName: "이메일",
- field: "EMAIL",
- editable: true,
- },
- {
- headerName: "구매수량",
- field: "QTY",
- width: 120,
- editable: true,
- cellRenderer: (params) => {
- return Number(params.value).toLocaleString();
- },
- },
- {
- headerName: "총구매금액",
- field: "TOTAL",
- editable: true,
- width: 120,
- cellRenderer: (params) => {
- return Number(params.value).toLocaleString();
- },
- },
- {
- headerName: "배송업체",
- field: "DELI_COMP",
- width: 100,
- editable: true,
- },
- {
- headerName: "송장번호",
- field: "DELI_NUMB",
- editable: true,
- },
- {
- headerName: "주문일",
- field: "ORDER_DATE",
- editable: true,
- },
- ],
- rowData: tblItems.value, // 테이블 데이터
- autoSizeStrategy: {
- type: "fitGridWidth", // width맞춤
- },
- suppressMovableColumns: true,
- headerHeight: rowHeightPx,
- rowHeight: rowHeightPx,
- pagination: true,
- suppressPaginationPanel: true, // 하단 default 페이징 컨트롤 숨김
- rowMultiSelectWithClick: true,
- rowSelection: {
- checkboxes: true,
- headerCheckbox: true,
- 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})`);
- }
- },
- };
- /************************************************************************
- | 함수(METHODS)
- ************************************************************************/
- const listLocated = () => {
- router.push({
- path: "/view/common/deli/",
- });
- };
- const onGridReady = (__PARAMS) => {
- 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);
- };
- const fnRegEvt = () => {
- let param = {
- id: pageId,
- title: pageId,
- content: "등록하시겠습니까?",
- yes: {
- text: "등록",
- isProc: true,
- event: "FN_INSERT",
- param: "",
- },
- no: {
- text: "취소",
- isProc: false,
- },
- };
- $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
- };
- // 엑셀 컬럼명 매핑 테이블
- const excelColumnMapping = {
- 구매자명: "BUYER_NAME",
- 주소: "ADDRESS",
- 연락처: "PHONE",
- 이메일: "EMAIL",
- 구매수량: "QTY",
- 총구매금액: "TOTAL",
- 배송업체: "DELI_COMP",
- 송장번호: "DELI_NUMB",
- 주문일: "ORDER_DATE",
- };
- // Excel 날짜를 문자열로 변환하는 함수 (시간 포함)
- const convertExcelDate = (value) => {
- // Date 객체인 경우 (XLSX 라이브러리가 cellDates: true로 자동 변환한 경우)
- if (value instanceof Date) {
- try {
- const year = value.getFullYear();
- const month = String(value.getMonth() + 1).padStart(2, '0');
- const day = String(value.getDate()).padStart(2, '0');
- const hours = String(value.getHours()).padStart(2, '0');
- const minutes = String(value.getMinutes()).padStart(2, '0');
- const seconds = String(value.getSeconds()).padStart(2, '0');
- return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
- } catch (error) {
- console.warn('Date 객체 변환 실패:', value, error);
- return value;
- }
- }
-
- // 숫자 타입이고 날짜 범위에 있는지 확인 (Excel 시리얼 날짜)
- if (typeof value === 'number' && value > 1 && value < 100000) {
- try {
- // Excel의 시리얼 번호를 Date 객체로 변환
- const excelStartDate = new Date(1900, 0, 1); // 1900년 1월 1일
- const convertedDate = new Date(excelStartDate.getTime() + (value - 2) * 24 * 60 * 60 * 1000);
-
- const year = convertedDate.getFullYear();
- const month = String(convertedDate.getMonth() + 1).padStart(2, '0');
- const day = String(convertedDate.getDate()).padStart(2, '0');
-
- return `${year}-${month}-${day} 00:00:00`;
- } catch (error) {
- console.warn('Excel 시리얼 날짜 변환 실패:', value, error);
- return value;
- }
- }
-
- // 이미 문자열 형태의 날짜인 경우
- if (typeof value === 'string') {
- // YYYY.MM.DD 또는 YYYY-MM-DD 형태를 YYYY-MM-DD 00:00:00로 변환
- let dateStr = value.replace(/\./g, '-').trim();
-
- // 시간 부분이 없으면 00:00:00 추가
- if (!dateStr.includes(' ') && dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
- dateStr += ' 00:00:00';
- }
-
- return dateStr;
- }
-
- console.log('날짜 변환 대상이 아님:', typeof value, value);
- return value;
- };
- const addEmptyRow = () => {
- const newRow = {
- BUYER_NAME: "",
- ADDRESS: "",
- PHONE: "",
- EMAIL: "",
- QTY: "",
- TOTAL: "",
- DELI_COMP: "",
- DELI_NUMB: "",
- ORDER_DATE: "",
- };
- // 맨 앞에 추가 (unshift 사용)
- tblItems.value.unshift(newRow);
- pageObj.value.totalCnt = tblItems.value.length;
- isExcelProcessed.value = false; // 수동 추가이므로 엑셀 처리 아님
- // ag-grid 데이터 갱신
- if (gridApi.value) {
- gridApi.value.setGridOption("rowData", tblItems.value);
- }
- $toast.success("새 항목이 추가되었습니다.");
- };
- const deleteSelectedRows = () => {
- if (!gridApi.value) return;
- const selectedRows = gridApi.value.getSelectedRows();
- if (selectedRows.length === 0) {
- $toast.warning("삭제할 항목을 선택해주세요.");
- return;
- }
- let param = {
- id: pageId,
- title: pageId,
- content: `선택된 ${selectedRows.length}개 항목을 삭제하시겠습니까?`,
- yes: {
- text: "삭제",
- isProc: true,
- event: "FN_DELETE_SELECTED",
- param: selectedRows,
- },
- no: {
- text: "취소",
- isProc: false,
- },
- };
- $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
- };
- const fnDeleteSelected = (selectedRows) => {
- // 선택된 행들을 tblItems에서 제거
- selectedRows.forEach((selectedRow) => {
- const index = tblItems.value.findIndex(
- (item) =>
- item.BUYER_NAME === selectedRow.BUYER_NAME &&
- item.ADDRESS === selectedRow.ADDRESS &&
- item.PHONE === selectedRow.PHONE &&
- item.EMAIL === selectedRow.EMAIL
- );
- if (index > -1) {
- tblItems.value.splice(index, 1);
- }
- });
- pageObj.value.totalCnt = tblItems.value.length;
- // ag-grid 데이터 갱신
- if (gridApi.value) {
- gridApi.value.setGridOption("rowData", tblItems.value);
- }
- $toast.success(`${selectedRows.length}개 항목이 삭제되었습니다.`);
- };
- const handleExcelUpload = async (event) => {
- const file = event.target.files[0];
- if (!file) return;
-
- // 사용자 타입에 따라 다른 업로드 로직 호출
- if (memberType === 'VENDOR') {
- await handleVendorExcelUpload(file);
- } else {
- await handleInfluencerExcelUpload(file);
- }
-
- // 파일 입력 초기화
- event.target.value = "";
- };
- const handleInfluencerExcelUpload = async (file) => {
- const errorHandler = useErrorHandler();
- // 파일 크기 검증 (10MB)
- const maxSize = 10 * 1024 * 1024;
- if (file.size > maxSize) {
- const sizeError = new Error("파일 크기 초과");
- sizeError.name = "FileSizeError";
- errorHandler.handleFileError(sizeError, file.name);
- event.target.value = "";
- return;
- }
- // 파일 형식 검증
- const allowedTypes = [
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- "application/vnd.ms-excel",
- ];
- if (!allowedTypes.includes(file.type)) {
- const typeError = new Error("지원하지 않는 파일 형식");
- typeError.name = "FileTypeError";
- errorHandler.handleFileError(typeError, file.name);
- event.target.value = "";
- return;
- }
- const reader = new FileReader();
- reader.onload = async (e) => {
- try {
- const data = new Uint8Array(e.target.result);
- const workbook = XLSX.read(data, { type: "array", cellDates: true });
- const sheetName = workbook.SheetNames[0];
- const worksheet = workbook.Sheets[sheetName];
- const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, raw: false, dateNF: 'yyyy-mm-dd' });
- if (jsonData.length < 2) {
- $toast.error(
- "엑셀 파일에 데이터가 없습니다. 헤더와 최소 1개 이상의 데이터 행이 필요합니다."
- );
- return;
- }
- const headers = jsonData[0];
- const rows = jsonData.slice(1);
- // 필수 헤더 검증
- const requiredHeaders = ["구매자명", "주소", "연락처"];
- const missingHeaders = requiredHeaders.filter(
- (header) => !headers.includes(header)
- );
- if (missingHeaders.length > 0) {
- $toast.error(`필수 헤더가 누락되었습니다: ${missingHeaders.join(", ")}`);
- return;
- }
- // 컬럼명 매핑 및 데이터 변환
- const mappedData = rows
- .map((row, rowIndex) => {
- const mappedRow = {};
- let hasValidData = false;
- headers.forEach((header, index) => {
- const fieldName = excelColumnMapping[header];
- if (fieldName && row[index] !== undefined && row[index] !== "") {
- // 주문일 필드인 경우 날짜 변환 처리
- if (fieldName === 'ORDER_DATE') {
- mappedRow[fieldName] = convertExcelDate(row[index]);
- } else {
- mappedRow[fieldName] = row[index];
- }
- hasValidData = true;
- }
- });
- // 필수 필드 검증
- if (hasValidData) {
- const missingRequiredFields = [];
- if (!mappedRow.BUYER_NAME) missingRequiredFields.push("구매자명");
- if (!mappedRow.ADDRESS) missingRequiredFields.push("주소");
- if (!mappedRow.PHONE) missingRequiredFields.push("연락처");
- if (missingRequiredFields.length > 0) {
- console.warn(
- `${rowIndex + 2}행: 필수 필드 누락 - ${missingRequiredFields.join(
- ", "
- )}`
- );
- }
- }
- return hasValidData ? mappedRow : null;
- })
- .filter((row) => row !== null);
- if (mappedData.length === 0) {
- $toast.error(
- "매핑 가능한 데이터가 없습니다. 엑셀 헤더명과 데이터를 확인해주세요."
- );
- return;
- }
- // 기존 데이터와 엑셀 데이터를 주문일 기준으로 분리 처리
- const processResult = await processInfluencerExcelData(mappedData);
- const { updatedData, newData, errors } = processResult;
- // 업데이트된 기존 데이터 + 신규 데이터를 합쳐서 그리드에 설정
- tblItems.value = [...updatedData, ...newData];
- pageObj.value.totalCnt = tblItems.value.length;
- isExcelProcessed.value = true; // 엑셀 처리 완료 표시
- // ag-grid 데이터 갱신
- if (gridApi.value) {
- gridApi.value.setGridOption("rowData", tblItems.value);
- }
- // 결과에 따른 사용자 피드백
- const totalProcessed = updatedData.length + newData.length;
- if (totalProcessed > 0) {
- if (updatedData.length > 0 && newData.length > 0) {
- $toast.success(
- `총 ${totalProcessed}건 처리완료 (업데이트: ${updatedData.length}건, 신규: ${newData.length}건)`
- );
- } else if (updatedData.length > 0) {
- $toast.success(
- `${updatedData.length}건의 기존 주문이 업데이트되었습니다.`
- );
- } else {
- $toast.success(
- `${newData.length}건의 신규 주문이 추가되었습니다.`
- );
- }
- } else {
- $toast.error(
- "처리된 데이터가 없습니다. 엑셀 데이터를 확인해주세요."
- );
- }
- if (errors.length > 0) {
- console.warn("처리 중 발생한 오류들:", errors);
- }
- } catch (error) {
- console.error("엑셀 파일 처리 중 오류:", error);
- $toast.error(
- "엑셀 파일을 읽는 중 오류가 발생했습니다. 파일 형식을 확인해주세요."
- );
- }
- };
- reader.onerror = () => {
- $toast.error("파일을 읽는 중 오류가 발생했습니다.");
- };
- reader.readAsArrayBuffer(file);
- };
- const handleVendorExcelUpload = async (file) => {
- const errorHandler = useErrorHandler();
- // 파일 크기 검증 (10MB)
- const maxSize = 10 * 1024 * 1024;
- if (file.size > maxSize) {
- const sizeError = new Error("파일 크기 초과");
- sizeError.name = "FileSizeError";
- errorHandler.handleFileError(sizeError, file.name);
- return;
- }
- // 파일 형식 검증
- const allowedTypes = [
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
- "application/vnd.ms-excel",
- ];
- if (!allowedTypes.includes(file.type)) {
- const typeError = new Error("지원하지 않는 파일 형식");
- typeError.name = "FileTypeError";
- errorHandler.handleFileError(typeError, file.name);
- return;
- }
- const reader = new FileReader();
- reader.onload = async (e) => {
- try {
- const data = new Uint8Array(e.target.result);
- const workbook = XLSX.read(data, { type: "array", cellDates: true });
- const sheetName = workbook.SheetNames[0];
- const worksheet = workbook.Sheets[sheetName];
- const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, raw: false, dateNF: 'yyyy-mm-dd' });
- if (jsonData.length < 2) {
- $toast.error("엑셀 파일에 데이터가 없습니다. 헤더와 최소 1개 이상의 데이터 행이 필요합니다.");
- return;
- }
- const headers = jsonData[0];
- const rows = jsonData.slice(1);
- // 벤더사용 필수 헤더 검증
- const requiredHeaders = ["구매자명", "연락처", "배송업체", "송장번호"];
- const missingHeaders = requiredHeaders.filter(
- (header) => !headers.includes(header)
- );
- if (missingHeaders.length > 0) {
- $toast.error(`필수 헤더가 누락되었습니다: ${missingHeaders.join(", ")}`);
- return;
- }
- // 벤더사용 컬럼 매핑
- const vendorColumnMapping = {
- "구매자명": "BUYER_NAME",
- "연락처": "PHONE",
- "배송업체": "DELI_COMP",
- "송장번호": "DELI_NUMB"
- };
- // 업로드 데이터 변환
- const uploadData = rows
- .map((row, rowIndex) => {
- const mappedRow = {};
- let hasValidData = false;
- headers.forEach((header, index) => {
- const fieldName = vendorColumnMapping[header];
- if (fieldName && row[index] !== undefined && row[index] !== "") {
- mappedRow[fieldName] = String(row[index]).trim();
- hasValidData = true;
- }
- });
- // 필수 필드 검증
- if (hasValidData) {
- const missingRequiredFields = [];
- if (!mappedRow.BUYER_NAME) missingRequiredFields.push("구매자명");
- if (!mappedRow.PHONE) missingRequiredFields.push("연락처");
- if (!mappedRow.DELI_COMP) missingRequiredFields.push("배송업체");
- if (!mappedRow.DELI_NUMB) missingRequiredFields.push("송장번호");
- if (missingRequiredFields.length > 0) {
- console.warn(`${rowIndex + 2}행: 필수 필드 누락 - ${missingRequiredFields.join(", ")}`);
- return null;
- }
- }
- return hasValidData ? mappedRow : null;
- })
- .filter((row) => row !== null);
- if (uploadData.length === 0) {
- $toast.error("유효한 데이터가 없습니다. 엑셀 헤더명과 데이터를 확인해주세요.");
- return;
- }
- // 기존 데이터와 매칭하여 업데이트
- await updateDeliveryInfo(uploadData);
- } catch (error) {
- console.error("엑셀 파일 처리 중 오류:", error);
- errorHandler.handleApiError(error, "엑셀 파일 처리");
- }
- };
- reader.onerror = () => {
- $toast.error("파일을 읽는 중 오류가 발생했습니다.");
- };
- reader.readAsArrayBuffer(file);
- };
- const updateDeliveryInfo = async (uploadData) => {
- let matchedCount = 0;
- let unmatchedCount = 0;
- const unmatchedItems = [];
- // 기존 데이터와 매칭
- const updatedItems = tblItems.value.map(existingItem => {
- // 구매자명과 연락처로 매칭 (공백 제거 후 비교)
- const matchedUpload = uploadData.find(upload =>
- upload.BUYER_NAME.replace(/\s/g, '') === existingItem.BUYER_NAME.replace(/\s/g, '') &&
- upload.PHONE.replace(/\s/g, '').replace(/-/g, '') === existingItem.PHONE.replace(/\s/g, '').replace(/-/g, '')
- );
- if (matchedUpload) {
- matchedCount++;
- // 배송업체와 송장번호만 업데이트
- return {
- ...existingItem,
- DELI_COMP: matchedUpload.DELI_COMP,
- DELI_NUMB: matchedUpload.DELI_NUMB
- };
- }
- return existingItem;
- });
- // 매칭되지 않은 업로드 데이터 확인
- uploadData.forEach(upload => {
- const matched = tblItems.value.find(existing =>
- existing.BUYER_NAME.replace(/\s/g, '') === upload.BUYER_NAME.replace(/\s/g, '') &&
- existing.PHONE.replace(/\s/g, '').replace(/-/g, '') === upload.PHONE.replace(/\s/g, '').replace(/-/g, '')
- );
-
- if (!matched) {
- unmatchedCount++;
- unmatchedItems.push({
- buyerName: upload.BUYER_NAME,
- phone: upload.PHONE
- });
- }
- });
- // 업데이트된 데이터로 테이블 갱신
- tblItems.value = updatedItems;
-
- // ag-grid 데이터 갱신
- if (gridApi.value) {
- gridApi.value.setGridOption("rowData", tblItems.value);
- }
- // 결과 메시지 표시
- if (matchedCount > 0 && unmatchedCount === 0) {
- $toast.success(`${matchedCount}건의 배송정보가 성공적으로 업데이트되었습니다.`);
- } else if (matchedCount > 0 && unmatchedCount > 0) {
- $toast.warning(
- `${matchedCount}건 업데이트 완료, ${unmatchedCount}건 매칭 실패\n매칭 실패 항목: ${unmatchedItems.map(item => `${item.buyerName}(${item.phone})`).join(", ")}`
- );
- } else {
- $toast.error("매칭되는 주문 정보가 없습니다. 구매자명과 연락처를 확인해주세요.");
- }
- };
- const processInfluencerExcelData = async (uploadData) => {
- const updatedData = [];
- const newData = [];
- const errors = [];
- // 기존 데이터를 맵으로 변환 (구매자명 + 연락처 키로 매핑)
- const existingDataMap = new Map();
- tblItems.value.forEach(item => {
- const key = `${item.BUYER_NAME?.trim()}_${item.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
- existingDataMap.set(key, item);
- });
- uploadData.forEach((excelItem, index) => {
- try {
- // 엑셀 데이터의 키 생성
- const key = `${excelItem.BUYER_NAME?.trim()}_${excelItem.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
- const existingItem = existingDataMap.get(key);
- if (existingItem) {
- // 기존 데이터가 있는 경우 주문일 비교
- const existingOrderDate = formatDateForComparison(existingItem.ORDER_DATE);
- const excelOrderDate = formatDateForComparison(excelItem.ORDER_DATE);
- if (existingOrderDate === excelOrderDate) {
- // 주문일이 같으면 업데이트 (배송정보 등 다른 필드 업데이트)
- updatedData.push({
- ...existingItem,
- ADDRESS: excelItem.ADDRESS || existingItem.ADDRESS,
- EMAIL: excelItem.EMAIL || existingItem.EMAIL,
- QTY: excelItem.QTY || existingItem.QTY,
- TOTAL: excelItem.TOTAL || existingItem.TOTAL,
- DELI_COMP: excelItem.DELI_COMP || existingItem.DELI_COMP,
- DELI_NUMB: excelItem.DELI_NUMB || existingItem.DELI_NUMB
- });
- } else {
- // 주문일이 다르면 신규 데이터로 추가
- newData.push({
- ...excelItem,
- // 인플루언서 정보는 기존 데이터에서 가져오기
- NICK_NAME: existingItem.NICK_NAME || "알 수 없음"
- });
- }
- } else {
- // 기존 데이터가 없으면 신규 데이터로 추가
- newData.push({
- ...excelItem,
- NICK_NAME: "알 수 없음" // 기본값
- });
- }
- } catch (error) {
- errors.push(`${index + 1}행 처리 중 오류: ${error.message}`);
- }
- });
- // 업데이트되지 않은 기존 데이터도 유지
- tblItems.value.forEach(existingItem => {
- const key = `${existingItem.BUYER_NAME?.trim()}_${existingItem.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
- const hasUpdate = uploadData.some(excelItem => {
- const excelKey = `${excelItem.BUYER_NAME?.trim()}_${excelItem.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
- return excelKey === key;
- });
- // 업데이트되지 않은 기존 데이터는 updatedData에 그대로 추가
- if (!hasUpdate) {
- updatedData.push(existingItem);
- }
- });
- return { updatedData, newData, errors };
- };
- const formatDateForComparison = (dateStr) => {
- if (!dateStr) return '';
-
- // 문자열로 변환하고 공백 제거
- let formattedDate = dateStr.toString().trim();
-
- // YYYY.MM.DD 형태를 YYYY-MM-DD로 변환
- formattedDate = formattedDate.replace(/\./g, '-');
-
- // 시간 부분이 있으면 제거하고 날짜 부분만 추출
- if (formattedDate.includes(' ')) {
- formattedDate = formattedDate.split(' ')[0];
- }
-
- return formattedDate;
- };
- const validateAndMatchOrders = async (uploadData) => {
- try {
- const response = await useAxios().post("/deli/validateOrders", {
- item_seq: useDtStore.boardInfo.seq,
- uploadData: uploadData,
- });
- return {
- matchedData: response.data.matched || [],
- unmatchedData: response.data.unmatched || [],
- errors: response.data.errors || [],
- };
- } catch (error) {
- console.error("주문 매칭 검증 중 오류:", error);
- // API 오류 시 클라이언트에서 기본 매칭 수행
- return performClientSideMatching(uploadData);
- }
- };
- const performClientSideMatching = (uploadData) => {
- // 클라이언트 사이드 매칭 로직 (백업용)
- const matchedData = [];
- const unmatchedData = [];
- const errors = [];
- uploadData.forEach((item, index) => {
- // 기본 검증: 구매자명과 연락처가 있는지 확인
- if (!item.BUYER_NAME || !item.PHONE) {
- unmatchedData.push(item);
- errors.push(`${index + 1}행: 구매자명 또는 연락처 누락`);
- } else {
- matchedData.push(item);
- }
- });
- return { matchedData, unmatchedData, errors };
- };
- const showUnmatchedDataModal = (unmatchedData, errors) => {
- const errorDetails =
- errors.length > 0 ? errors.join("\n") : "매칭 실패 데이터가 있습니다.";
- let param = {
- id: "unmatchedData",
- title: "업로드 실패 항목",
- content: `다음 ${unmatchedData.length}건의 데이터를 처리할 수 없습니다:\n\n${errorDetails}\n\n데이터를 수정 후 다시 업로드해주세요.`,
- yes: {
- text: "확인",
- isProc: false,
- },
- };
- $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
- };
- const downloadExcel = () => {
- if (!tblItems.value || tblItems.value.length === 0) {
- $toast.warning("다운로드할 데이터가 없습니다.");
- return;
- }
- // 한글 헤더명 배열
- const headers = [
- "구매자명",
- "주소",
- "연락처",
- "이메일",
- "구매수량",
- "총구매금액",
- "배송업체",
- "송장번호",
- "주문일",
- ];
- // 데이터를 엑셀 형식으로 변환
- const excelData = tblItems.value.map((item) => [
- item.BUYER_NAME || "",
- item.ADDRESS || "",
- item.PHONE || "",
- item.EMAIL || "",
- item.QTY || "",
- item.TOTAL || "",
- item.DELI_COMP || "",
- item.DELI_NUMB || "",
- item.ORDER_DATE || "",
- ]);
- // 헤더를 첫 번째 행에 추가
- const worksheetData = [headers, ...excelData];
- // 워크시트 생성
- const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
- // 워크북 생성
- const workbook = XLSX.utils.book_new();
- XLSX.utils.book_append_sheet(workbook, worksheet, "배송관리");
- // 파일명 생성 (현재 날짜 포함)
- const today = new Date();
- const dateString =
- today.getFullYear() +
- String(today.getMonth() + 1).padStart(2, "0") +
- String(today.getDate()).padStart(2, "0");
- const fileName = `배송관리_${dateString}.xlsx`;
- // 엑셀 파일 다운로드
- XLSX.writeFile(workbook, fileName);
- $toast.success("엑셀 파일이 다운로드되었습니다.");
- };
- const fnDetail = () => {
- let req = {
- seq: useDtStore.boardInfo.seq,
- };
- let req2 = {
- item_seq: useDtStore.boardInfo.seq,
- };
-
- // 인플루언서일 경우 본인의 inf_seq값 추가
- if (memberType === 'INFLUENCER') {
- req2.inf_seq = memberSeq;
- }
- useAxios()
- .get(`/item/detail/${req.seq}`)
- .then((res) => {
- form.value.formValue1 = res.data.NAME;
- form.value.formValue2 = res.data.PRICE1;
- form.value.formValue3 = res.data.PRICE2;
- form.value.formValue4 = res.data.DELI_FEE;
- form.value.formValue5 = res.data.THUMB_FILE;
- form.value.formValue6 = res.data.SUB_TITLE;
- form.value.formValue8 = res.data.STATUS;
- form.value.formValue9 = res.data.SHOW_YN;
- form.value.formValue10 = res.data.ADD_INFO;
- //썸네일 파일이 있으면 넣어줌
- if (form.value.formValue5) {
- imgTemp.value = `https://shopdeli.mycafe24.com/writable/uploads/item/thumb/${form.value.formValue5}`;
- }
- })
- .catch((error) => {
- $toast.error("제품 정보를 불러오는 중 오류가 발생했습니다.");
- })
- .finally(() => {});
- // 기 저장된 구매자명 리스트
- // 제품 seq, 인플루언서 seq가 일치하는 리스트만
- useAxios()
- .post(`/deli/list`, req2)
- .then((res) => {
- console.log(res.data);
- tblItems.value = res.data;
- pageObj.value.totalCnt = tblItems.value.length;
- isExcelProcessed.value = false; // 초기 로드이므로 엑셀 처리 아님
- })
- .catch((error) => {
- $toast.error("제품 정보를 불러오는 중 오류가 발생했습니다.");
- })
- .finally(() => {});
- };
- const fnInsert = async () => {
- // 벤더사인 경우 배송정보 업데이트 API 사용
- if (memberType === 'VENDOR') {
- await fnVendorUpdate();
- return;
- }
- // 인플루언서인 경우 기존 로직 사용
- const deliveryData = {
- item_seq: useDtStore.boardInfo.seq,
- inf_seq: memberSeq,
- useOrderDateMatching: isExcelProcessed.value, // 엑셀 업로드로 처리된 경우 true
- deliveryList: tblItems.value.map((item) => ({
- buyerName: item.BUYER_NAME,
- address: item.ADDRESS,
- phone: item.PHONE,
- email: item.EMAIL,
- qty: item.QTY,
- total: item.TOTAL,
- deliComp: item.DELI_COMP || '',
- deliNumb: item.DELI_NUMB ? String(item.DELI_NUMB) : '',
- orderDate: item.ORDER_DATE.replaceAll(".", "-"),
- })),
- };
- await withLoading(async () => {
- return useAxios().post("/deli/reg", deliveryData);
- }, "배송 데이터를 저장하는 중...")
- .then((res) => {
- $toast.success("배송 데이터가 성공적으로 저장되었습니다.");
- // 저장 완료 후 배송 관리 리스트로 이동하며 업로드 성공 상태 전달
- router.push({
- path: "/view/common/deli",
- query: {
- uploadStatus: "success",
- itemId: useDtStore.boardInfo.seq,
- recordCount: tblItems.value.length,
- statusUpdated: "false",
- },
- });
- })
- .catch((error) => {
- const errorHandler = useErrorHandler();
- errorHandler.handleApiError(error, "배송 데이터 저장");
- })
- .finally(() => {});
- };
- const fnVendorUpdate = async () => {
- // 배송정보가 있는 항목만 추출 (구매자명과 연락처는 필수)
- const deliveryUpdates = tblItems.value
- .filter(item => item.BUYER_NAME && item.PHONE)
- .map(item => ({
- buyerName: item.BUYER_NAME,
- phone: item.PHONE,
- deliComp: item.DELI_COMP || '',
- deliNumb: item.DELI_NUMB ? String(item.DELI_NUMB) : ''
- }));
- if (deliveryUpdates.length === 0) {
- $toast.error("업데이트할 배송정보가 없습니다.");
- return;
- }
- console.log('벤더 배송정보 업데이트 데이터:', {
- item_seq: useDtStore.boardInfo.seq,
- deliveryUpdates: deliveryUpdates
- });
- const updateData = {
- item_seq: useDtStore.boardInfo.seq,
- deliveryUpdates: deliveryUpdates
- };
- await withLoading(async () => {
- return useAxios().post("/deli/updateDeliveryInfo", updateData);
- }, "배송정보를 업데이트하는 중...")
- .then((res) => {
- $toast.success(`${res.data.updated_count}건의 배송정보가 업데이트되었습니다.`);
- // 배송 관리 목록으로 이동
- router.push({
- path: "/view/common/deli",
- query: {
- uploadStatus: "success",
- itemId: useDtStore.boardInfo.seq,
- recordCount: res.data.updated_count,
- statusUpdated: "false",
- },
- });
- })
- .catch((error) => {
- const errorHandler = useErrorHandler();
- errorHandler.handleApiError(error, "배송정보 업데이트");
- });
- };
- /************************************************************************
- | 팝업 이벤트버스 정의
- ************************************************************************/
- $eventBus.off("FN_INSERT");
- $eventBus.on("FN_INSERT", () => {
- fnInsert();
- });
- $eventBus.off("FN_DELETE_SELECTED");
- $eventBus.on("FN_DELETE_SELECTED", (selectedRows) => {
- fnDeleteSelected(selectedRows);
- });
- /************************************************************************
- | WATCH
- ************************************************************************/
- watch(
- () => props,
- () => {
- searchObj.value = props.propsData;
- fnGetStat();
- },
- { deep: true }
- );
- onMounted(() => {
- fnDetail();
- });
- </script>
|