detail.vue 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203
  1. <template>
  2. <div>
  3. <div class="inner--headers">
  4. <h2>{{ pageId }}</h2>
  5. <div class="bread--crumbs--wrap">
  6. <span>홈</span>
  7. <span>{{ pageId }}</span>
  8. </div>
  9. </div>
  10. <div class="data--list--wrap">
  11. <div class="btn--actions--wrap">
  12. <div class="left--sections">
  13. <v-btn class="custom-btn btn-pink bdrs--10"><i class="ico"></i>개별 배송</v-btn>
  14. <v-btn class="custom-btn bdrs--10 btn-white" @click="deliLocated()"
  15. ><i class="ico"></i>공동구매 배송</v-btn
  16. >
  17. </div>
  18. <div class="right--sections"></div>
  19. </div>
  20. <div class="item--section">
  21. <div v-if="imgTemp" class="item--thumb">
  22. <img :src="imgTemp" alt="" />
  23. </div>
  24. <div v-else class="item--thumb min--240">NO IMAGE</div>
  25. <div class="item--info">
  26. <h2>{{ form.formValue1 }}</h2>
  27. <p>공급가: {{ Number(form.formValue2).toLocaleString() }}원</p>
  28. <p>판매가: {{ Number(form.formValue3).toLocaleString() }}원</p>
  29. </div>
  30. </div>
  31. <div class="btn--actions--wrap">
  32. <div class="left--sections"></div>
  33. <div class="right--sections">
  34. <div class="caption--wrap">
  35. <i class="ico">!</i>
  36. <div class="caption--box">
  37. - 주문일은 YYYY.MM.DD 혹은 YYYY-MM-DD 형태로 입력해 주세요.<br />
  38. - 구매자 정보 입력 후 저장 버튼을 꼭 클릭해 주세요.<br />
  39. - 엑셀 파일은 최대 10MB까지 업로드 가능합니다.<br />
  40. - 엑셀 파일의 헤더는 다음과 같아야 합니다: 구매자명, 주소, 연락처, 이메일,
  41. 구매수량, 총구매금액, 배송업체, 송장번호, 주문일
  42. </div>
  43. </div>
  44. <v-btn class="custom-btn btn-white mini" @click="addEmptyRow"
  45. ><i class="ico"></i>항목 추가</v-btn
  46. >
  47. <v-btn class="custom-btn btn-white mini" @click="deleteSelectedRows"
  48. ><i class="ico"></i>항목 삭제</v-btn
  49. >
  50. <input
  51. ref="excelFileInput"
  52. type="file"
  53. accept=".xlsx,.xls"
  54. @change="handleExcelUpload"
  55. style="display: none"
  56. />
  57. <v-btn class="custom-btn btn-excel" @click="$refs.excelFileInput.click()"
  58. ><i class="ico"></i>엑셀 업로드</v-btn
  59. >
  60. <v-btn class="custom-btn btn-excel" @click="downloadExcel"
  61. ><i class="ico"></i>엑셀 다운로드</v-btn
  62. >
  63. </div>
  64. </div>
  65. <div class="tbl-wrapper">
  66. <div class="tbl-wrap">
  67. <!-- ag grid -->
  68. <ag-grid-vue
  69. style="width: 100%; height: calc(10 * 2.94rem)"
  70. class="ag-theme-quartz"
  71. :gridOptions="gridOptions"
  72. rowSelection="multiple"
  73. :rowData="tblItems"
  74. :paginationPageSize="pageObj.pageSize"
  75. :suppressPaginationPanel="true"
  76. @grid-ready="onGridReady"
  77. @cell-value-changed="onCellValueChanged"
  78. >
  79. </ag-grid-vue>
  80. <!-- 페이징 -->
  81. <div class="ag-grid-custom-pagenations">
  82. <pagination @chg_page="chgPage" :pageObj="pageObj"></pagination>
  83. </div>
  84. </div>
  85. </div>
  86. <div class="view-btm-btn">
  87. <div class="btn-l">
  88. <v-btn class="custom-btn btn-list" @click="listLocated"
  89. ><i class="ico"></i>목록</v-btn
  90. >
  91. </div>
  92. <div class="btn-r">
  93. <v-btn class="custom-btn btn-blue2" @click="fnRegEvt"
  94. ><i class="ico"></i>저장</v-btn
  95. >
  96. </div>
  97. </div>
  98. </div>
  99. <!-- 로딩 오버레이 -->
  100. <LoadingOverlay :is-loading="isLoading" :loading-message="loadingMessage" />
  101. </div>
  102. </template>
  103. <script setup>
  104. import "@vuepic/vue-datepicker/dist/main.css";
  105. import { AgGridVue } from "ag-grid-vue3";
  106. import * as XLSX from "xlsx";
  107. import pagination from "../components/common/pagination.vue";
  108. /************************************************************************
  109. | 레이아웃
  110. ************************************************************************/
  111. definePageMeta({
  112. layout: "default",
  113. });
  114. /************************************************************************
  115. | PROPS
  116. ************************************************************************/
  117. const props = defineProps({
  118. propsData: {
  119. type: Object,
  120. default: () => {},
  121. },
  122. });
  123. /************************************************************************
  124. | 스토어
  125. ************************************************************************/
  126. const useDtStore = useDetailStore();
  127. const useAtStore = useAuthStore();
  128. /************************************************************************
  129. | 전역
  130. ************************************************************************/
  131. const memberType = useAtStore.auth.memberType;
  132. const memberSeq = useAtStore.auth.seq;
  133. const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();
  134. const router = useRouter();
  135. const pageId = ref("배송 관리");
  136. const { isLoading, loadingMessage, withLoading } = useLoading();
  137. let pageObj = ref({
  138. page: 1, // 현재 페이지
  139. pageMaxNumSize: 10, // 페이지 숫자 최대 표현 개수
  140. pageSize: 10, // 테이블 조회 데이터 개수
  141. totalCnt: 0, // 전체 페이지
  142. });
  143. const imgTemp = ref("");
  144. const tblItems = ref([]); // stat 데이터
  145. const isExcelProcessed = ref(false); // 엑셀 업로드로 데이터가 처리되었는지 여부
  146. const form = ref({
  147. formValue1: "",
  148. formValue2: "",
  149. formValue3: "",
  150. formValue4: "",
  151. formValue5: null,
  152. formValue6: "",
  153. formValue7: "",
  154. formValue8: "0",
  155. formValue8Arr: [
  156. { title: "판매중", value: "0" },
  157. { title: "품절", value: "1" },
  158. ],
  159. formValue9: "Y",
  160. formValue9Arr: [
  161. { title: "노출", value: "Y" },
  162. { title: "비노출", value: "N" },
  163. ],
  164. formValue10: "",
  165. });
  166. /* eslint-disable */
  167. /* prettier-ignore */
  168. pageObj.value.totalCnt = tblItems.value.length;
  169. const remToPx = () => parseFloat(getComputedStyle(document.documentElement).fontSize);
  170. const rowHeightRem = 2.65; // 원하는 rem 값
  171. const rowHeightPx = rowHeightRem * remToPx();
  172. const gridApi = shallowRef();
  173. // gridOption
  174. const gridOptions = {
  175. columnDefs: [
  176. { checkboxSelection: true, headerCheckboxSelection: true, width: 50 },
  177. {
  178. headerName: "No",
  179. valueGetter: (params) => params.api.getDisplayedRowCount() - params.node.rowIndex,
  180. sortable: false,
  181. width: 70,
  182. },
  183. {
  184. headerName: "인플루언서",
  185. field: "NICK_NAME",
  186. width: 150,
  187. hide: memberType == "INFLUENCER",
  188. },
  189. {
  190. headerName: "구매자명",
  191. field: "BUYER_NAME",
  192. width: 120,
  193. editable: true,
  194. },
  195. {
  196. headerName: "주소",
  197. field: "ADDRESS",
  198. editable: true,
  199. },
  200. {
  201. headerName: "연락처",
  202. field: "PHONE",
  203. width: 140,
  204. editable: true,
  205. },
  206. {
  207. headerName: "이메일",
  208. field: "EMAIL",
  209. editable: true,
  210. },
  211. {
  212. headerName: "구매수량",
  213. field: "QTY",
  214. width: 120,
  215. editable: true,
  216. cellRenderer: (params) => {
  217. return Number(params.value).toLocaleString();
  218. },
  219. },
  220. {
  221. headerName: "총구매금액",
  222. field: "TOTAL",
  223. editable: true,
  224. width: 120,
  225. cellRenderer: (params) => {
  226. return Number(params.value).toLocaleString();
  227. },
  228. },
  229. {
  230. headerName: "배송업체",
  231. field: "DELI_COMP",
  232. width: 100,
  233. editable: true,
  234. },
  235. {
  236. headerName: "송장번호",
  237. field: "DELI_NUMB",
  238. editable: true,
  239. },
  240. {
  241. headerName: "주문일",
  242. field: "ORDER_DATE",
  243. editable: true,
  244. },
  245. ],
  246. rowData: tblItems.value, // 테이블 데이터
  247. autoSizeStrategy: {
  248. type: "fitGridWidth", // width맞춤
  249. },
  250. suppressMovableColumns: true,
  251. headerHeight: rowHeightPx,
  252. rowHeight: rowHeightPx,
  253. pagination: true,
  254. suppressPaginationPanel: true, // 하단 default 페이징 컨트롤 숨김
  255. rowMultiSelectWithClick: true,
  256. rowSelection: {
  257. checkboxes: true,
  258. headerCheckbox: true,
  259. enableClickSelection: false,
  260. mode: "multiRow",
  261. },
  262. // 셀 편집 완료 시 데이터 업데이트
  263. onCellValueChanged: (event) => {
  264. const rowIndex = event.rowIndex;
  265. const field = event.colDef.field;
  266. const newValue = event.newValue;
  267. // tblItems 배열의 해당 행 데이터 업데이트
  268. if (rowIndex >= 0 && rowIndex < tblItems.value.length) {
  269. tblItems.value[rowIndex][field] = newValue;
  270. console.log(`셀 편집 완료: ${field} = ${newValue} (행 ${rowIndex})`);
  271. }
  272. },
  273. };
  274. /************************************************************************
  275. | 함수(METHODS)
  276. ************************************************************************/
  277. const listLocated = () => {
  278. router.push({
  279. path: "/view/common/deli/",
  280. });
  281. };
  282. const onGridReady = (__PARAMS) => {
  283. gridApi.value = __PARAMS.api;
  284. };
  285. const onCellValueChanged = (event) => {
  286. const rowIndex = event.rowIndex;
  287. const field = event.colDef.field;
  288. const newValue = event.newValue;
  289. // tblItems 배열의 해당 행 데이터 업데이트
  290. if (rowIndex >= 0 && rowIndex < tblItems.value.length) {
  291. tblItems.value[rowIndex][field] = newValue;
  292. console.log(`셀 편집 완료: ${field} = ${newValue} (행 ${rowIndex})`);
  293. // 배송업체나 송장번호가 변경된 경우 추가 로직
  294. if (field === 'DELI_COMP' || field === 'DELI_NUMB') {
  295. console.log('배송정보 변경됨:', {
  296. row: rowIndex,
  297. field: field,
  298. value: newValue,
  299. DELI_COMP: tblItems.value[rowIndex].DELI_COMP,
  300. DELI_NUMB: tblItems.value[rowIndex].DELI_NUMB
  301. });
  302. }
  303. }
  304. };
  305. const chgPage = (__PAGE) => {
  306. pageObj.value.page = __PAGE;
  307. gridApi.value.paginationGoToPage(__PAGE - 1);
  308. };
  309. const fnRegEvt = () => {
  310. let param = {
  311. id: pageId,
  312. title: pageId,
  313. content: "등록하시겠습니까?",
  314. yes: {
  315. text: "등록",
  316. isProc: true,
  317. event: "FN_INSERT",
  318. param: "",
  319. },
  320. no: {
  321. text: "취소",
  322. isProc: false,
  323. },
  324. };
  325. $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  326. };
  327. // 엑셀 컬럼명 매핑 테이블
  328. const excelColumnMapping = {
  329. 구매자명: "BUYER_NAME",
  330. 주소: "ADDRESS",
  331. 연락처: "PHONE",
  332. 이메일: "EMAIL",
  333. 구매수량: "QTY",
  334. 총구매금액: "TOTAL",
  335. 배송업체: "DELI_COMP",
  336. 송장번호: "DELI_NUMB",
  337. 주문일: "ORDER_DATE",
  338. };
  339. // Excel 날짜를 문자열로 변환하는 함수 (시간 포함)
  340. const convertExcelDate = (value) => {
  341. // Date 객체인 경우 (XLSX 라이브러리가 cellDates: true로 자동 변환한 경우)
  342. if (value instanceof Date) {
  343. try {
  344. const year = value.getFullYear();
  345. const month = String(value.getMonth() + 1).padStart(2, '0');
  346. const day = String(value.getDate()).padStart(2, '0');
  347. const hours = String(value.getHours()).padStart(2, '0');
  348. const minutes = String(value.getMinutes()).padStart(2, '0');
  349. const seconds = String(value.getSeconds()).padStart(2, '0');
  350. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  351. } catch (error) {
  352. console.warn('Date 객체 변환 실패:', value, error);
  353. return value;
  354. }
  355. }
  356. // 숫자 타입이고 날짜 범위에 있는지 확인 (Excel 시리얼 날짜)
  357. if (typeof value === 'number' && value > 1 && value < 100000) {
  358. try {
  359. // Excel의 시리얼 번호를 Date 객체로 변환
  360. const excelStartDate = new Date(1900, 0, 1); // 1900년 1월 1일
  361. const convertedDate = new Date(excelStartDate.getTime() + (value - 2) * 24 * 60 * 60 * 1000);
  362. const year = convertedDate.getFullYear();
  363. const month = String(convertedDate.getMonth() + 1).padStart(2, '0');
  364. const day = String(convertedDate.getDate()).padStart(2, '0');
  365. return `${year}-${month}-${day} 00:00:00`;
  366. } catch (error) {
  367. console.warn('Excel 시리얼 날짜 변환 실패:', value, error);
  368. return value;
  369. }
  370. }
  371. // 이미 문자열 형태의 날짜인 경우
  372. if (typeof value === 'string') {
  373. // YYYY.MM.DD 또는 YYYY-MM-DD 형태를 YYYY-MM-DD 00:00:00로 변환
  374. let dateStr = value.replace(/\./g, '-').trim();
  375. // 시간 부분이 없으면 00:00:00 추가
  376. if (!dateStr.includes(' ') && dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
  377. dateStr += ' 00:00:00';
  378. }
  379. return dateStr;
  380. }
  381. console.log('날짜 변환 대상이 아님:', typeof value, value);
  382. return value;
  383. };
  384. const addEmptyRow = () => {
  385. const newRow = {
  386. BUYER_NAME: "",
  387. ADDRESS: "",
  388. PHONE: "",
  389. EMAIL: "",
  390. QTY: "",
  391. TOTAL: "",
  392. DELI_COMP: "",
  393. DELI_NUMB: "",
  394. ORDER_DATE: "",
  395. };
  396. // 맨 앞에 추가 (unshift 사용)
  397. tblItems.value.unshift(newRow);
  398. pageObj.value.totalCnt = tblItems.value.length;
  399. isExcelProcessed.value = false; // 수동 추가이므로 엑셀 처리 아님
  400. // ag-grid 데이터 갱신
  401. if (gridApi.value) {
  402. gridApi.value.setGridOption("rowData", tblItems.value);
  403. }
  404. $toast.success("새 항목이 추가되었습니다.");
  405. };
  406. const deleteSelectedRows = () => {
  407. if (!gridApi.value) return;
  408. const selectedRows = gridApi.value.getSelectedRows();
  409. if (selectedRows.length === 0) {
  410. $toast.warning("삭제할 항목을 선택해주세요.");
  411. return;
  412. }
  413. let param = {
  414. id: pageId,
  415. title: pageId,
  416. content: `선택된 ${selectedRows.length}개 항목을 삭제하시겠습니까?`,
  417. yes: {
  418. text: "삭제",
  419. isProc: true,
  420. event: "FN_DELETE_SELECTED",
  421. param: selectedRows,
  422. },
  423. no: {
  424. text: "취소",
  425. isProc: false,
  426. },
  427. };
  428. $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  429. };
  430. const fnDeleteSelected = (selectedRows) => {
  431. // 선택된 행들을 tblItems에서 제거
  432. selectedRows.forEach((selectedRow) => {
  433. const index = tblItems.value.findIndex(
  434. (item) =>
  435. item.BUYER_NAME === selectedRow.BUYER_NAME &&
  436. item.ADDRESS === selectedRow.ADDRESS &&
  437. item.PHONE === selectedRow.PHONE &&
  438. item.EMAIL === selectedRow.EMAIL
  439. );
  440. if (index > -1) {
  441. tblItems.value.splice(index, 1);
  442. }
  443. });
  444. pageObj.value.totalCnt = tblItems.value.length;
  445. // ag-grid 데이터 갱신
  446. if (gridApi.value) {
  447. gridApi.value.setGridOption("rowData", tblItems.value);
  448. }
  449. $toast.success(`${selectedRows.length}개 항목이 삭제되었습니다.`);
  450. };
  451. const handleExcelUpload = async (event) => {
  452. const file = event.target.files[0];
  453. if (!file) return;
  454. // 사용자 타입에 따라 다른 업로드 로직 호출
  455. if (memberType === 'VENDOR') {
  456. await handleVendorExcelUpload(file);
  457. } else {
  458. await handleInfluencerExcelUpload(file);
  459. }
  460. // 파일 입력 초기화
  461. event.target.value = "";
  462. };
  463. const handleInfluencerExcelUpload = async (file) => {
  464. const errorHandler = useErrorHandler();
  465. // 파일 크기 검증 (10MB)
  466. const maxSize = 10 * 1024 * 1024;
  467. if (file.size > maxSize) {
  468. const sizeError = new Error("파일 크기 초과");
  469. sizeError.name = "FileSizeError";
  470. errorHandler.handleFileError(sizeError, file.name);
  471. event.target.value = "";
  472. return;
  473. }
  474. // 파일 형식 검증
  475. const allowedTypes = [
  476. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  477. "application/vnd.ms-excel",
  478. ];
  479. if (!allowedTypes.includes(file.type)) {
  480. const typeError = new Error("지원하지 않는 파일 형식");
  481. typeError.name = "FileTypeError";
  482. errorHandler.handleFileError(typeError, file.name);
  483. event.target.value = "";
  484. return;
  485. }
  486. const reader = new FileReader();
  487. reader.onload = async (e) => {
  488. try {
  489. const data = new Uint8Array(e.target.result);
  490. const workbook = XLSX.read(data, { type: "array", cellDates: true });
  491. const sheetName = workbook.SheetNames[0];
  492. const worksheet = workbook.Sheets[sheetName];
  493. const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, raw: false, dateNF: 'yyyy-mm-dd' });
  494. if (jsonData.length < 2) {
  495. $toast.error(
  496. "엑셀 파일에 데이터가 없습니다. 헤더와 최소 1개 이상의 데이터 행이 필요합니다."
  497. );
  498. return;
  499. }
  500. const headers = jsonData[0];
  501. const rows = jsonData.slice(1);
  502. // 필수 헤더 검증
  503. const requiredHeaders = ["구매자명", "주소", "연락처"];
  504. const missingHeaders = requiredHeaders.filter(
  505. (header) => !headers.includes(header)
  506. );
  507. if (missingHeaders.length > 0) {
  508. $toast.error(`필수 헤더가 누락되었습니다: ${missingHeaders.join(", ")}`);
  509. return;
  510. }
  511. // 컬럼명 매핑 및 데이터 변환
  512. const mappedData = rows
  513. .map((row, rowIndex) => {
  514. const mappedRow = {};
  515. let hasValidData = false;
  516. headers.forEach((header, index) => {
  517. const fieldName = excelColumnMapping[header];
  518. if (fieldName && row[index] !== undefined && row[index] !== "") {
  519. // 주문일 필드인 경우 날짜 변환 처리
  520. if (fieldName === 'ORDER_DATE') {
  521. mappedRow[fieldName] = convertExcelDate(row[index]);
  522. } else {
  523. mappedRow[fieldName] = row[index];
  524. }
  525. hasValidData = true;
  526. }
  527. });
  528. // 필수 필드 검증
  529. if (hasValidData) {
  530. const missingRequiredFields = [];
  531. if (!mappedRow.BUYER_NAME) missingRequiredFields.push("구매자명");
  532. if (!mappedRow.ADDRESS) missingRequiredFields.push("주소");
  533. if (!mappedRow.PHONE) missingRequiredFields.push("연락처");
  534. if (missingRequiredFields.length > 0) {
  535. console.warn(
  536. `${rowIndex + 2}행: 필수 필드 누락 - ${missingRequiredFields.join(
  537. ", "
  538. )}`
  539. );
  540. }
  541. }
  542. return hasValidData ? mappedRow : null;
  543. })
  544. .filter((row) => row !== null);
  545. if (mappedData.length === 0) {
  546. $toast.error(
  547. "매핑 가능한 데이터가 없습니다. 엑셀 헤더명과 데이터를 확인해주세요."
  548. );
  549. return;
  550. }
  551. // 기존 데이터와 엑셀 데이터를 주문일 기준으로 분리 처리
  552. const processResult = await processInfluencerExcelData(mappedData);
  553. const { updatedData, newData, errors } = processResult;
  554. // 업데이트된 기존 데이터 + 신규 데이터를 합쳐서 그리드에 설정
  555. tblItems.value = [...updatedData, ...newData];
  556. pageObj.value.totalCnt = tblItems.value.length;
  557. isExcelProcessed.value = true; // 엑셀 처리 완료 표시
  558. // ag-grid 데이터 갱신
  559. if (gridApi.value) {
  560. gridApi.value.setGridOption("rowData", tblItems.value);
  561. }
  562. // 결과에 따른 사용자 피드백
  563. const totalProcessed = updatedData.length + newData.length;
  564. if (totalProcessed > 0) {
  565. if (updatedData.length > 0 && newData.length > 0) {
  566. $toast.success(
  567. `총 ${totalProcessed}건 처리완료 (업데이트: ${updatedData.length}건, 신규: ${newData.length}건)`
  568. );
  569. } else if (updatedData.length > 0) {
  570. $toast.success(
  571. `${updatedData.length}건의 기존 주문이 업데이트되었습니다.`
  572. );
  573. } else {
  574. $toast.success(
  575. `${newData.length}건의 신규 주문이 추가되었습니다.`
  576. );
  577. }
  578. } else {
  579. $toast.error(
  580. "처리된 데이터가 없습니다. 엑셀 데이터를 확인해주세요."
  581. );
  582. }
  583. if (errors.length > 0) {
  584. console.warn("처리 중 발생한 오류들:", errors);
  585. }
  586. } catch (error) {
  587. console.error("엑셀 파일 처리 중 오류:", error);
  588. $toast.error(
  589. "엑셀 파일을 읽는 중 오류가 발생했습니다. 파일 형식을 확인해주세요."
  590. );
  591. }
  592. };
  593. reader.onerror = () => {
  594. $toast.error("파일을 읽는 중 오류가 발생했습니다.");
  595. };
  596. reader.readAsArrayBuffer(file);
  597. };
  598. const handleVendorExcelUpload = async (file) => {
  599. const errorHandler = useErrorHandler();
  600. // 파일 크기 검증 (10MB)
  601. const maxSize = 10 * 1024 * 1024;
  602. if (file.size > maxSize) {
  603. const sizeError = new Error("파일 크기 초과");
  604. sizeError.name = "FileSizeError";
  605. errorHandler.handleFileError(sizeError, file.name);
  606. return;
  607. }
  608. // 파일 형식 검증
  609. const allowedTypes = [
  610. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  611. "application/vnd.ms-excel",
  612. ];
  613. if (!allowedTypes.includes(file.type)) {
  614. const typeError = new Error("지원하지 않는 파일 형식");
  615. typeError.name = "FileTypeError";
  616. errorHandler.handleFileError(typeError, file.name);
  617. return;
  618. }
  619. const reader = new FileReader();
  620. reader.onload = async (e) => {
  621. try {
  622. const data = new Uint8Array(e.target.result);
  623. const workbook = XLSX.read(data, { type: "array", cellDates: true });
  624. const sheetName = workbook.SheetNames[0];
  625. const worksheet = workbook.Sheets[sheetName];
  626. const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1, raw: false, dateNF: 'yyyy-mm-dd' });
  627. if (jsonData.length < 2) {
  628. $toast.error("엑셀 파일에 데이터가 없습니다. 헤더와 최소 1개 이상의 데이터 행이 필요합니다.");
  629. return;
  630. }
  631. const headers = jsonData[0];
  632. const rows = jsonData.slice(1);
  633. // 벤더사용 필수 헤더 검증
  634. const requiredHeaders = ["구매자명", "연락처", "배송업체", "송장번호"];
  635. const missingHeaders = requiredHeaders.filter(
  636. (header) => !headers.includes(header)
  637. );
  638. if (missingHeaders.length > 0) {
  639. $toast.error(`필수 헤더가 누락되었습니다: ${missingHeaders.join(", ")}`);
  640. return;
  641. }
  642. // 벤더사용 컬럼 매핑
  643. const vendorColumnMapping = {
  644. "구매자명": "BUYER_NAME",
  645. "연락처": "PHONE",
  646. "배송업체": "DELI_COMP",
  647. "송장번호": "DELI_NUMB"
  648. };
  649. // 업로드 데이터 변환
  650. const uploadData = rows
  651. .map((row, rowIndex) => {
  652. const mappedRow = {};
  653. let hasValidData = false;
  654. headers.forEach((header, index) => {
  655. const fieldName = vendorColumnMapping[header];
  656. if (fieldName && row[index] !== undefined && row[index] !== "") {
  657. mappedRow[fieldName] = String(row[index]).trim();
  658. hasValidData = true;
  659. }
  660. });
  661. // 필수 필드 검증
  662. if (hasValidData) {
  663. const missingRequiredFields = [];
  664. if (!mappedRow.BUYER_NAME) missingRequiredFields.push("구매자명");
  665. if (!mappedRow.PHONE) missingRequiredFields.push("연락처");
  666. if (!mappedRow.DELI_COMP) missingRequiredFields.push("배송업체");
  667. if (!mappedRow.DELI_NUMB) missingRequiredFields.push("송장번호");
  668. if (missingRequiredFields.length > 0) {
  669. console.warn(`${rowIndex + 2}행: 필수 필드 누락 - ${missingRequiredFields.join(", ")}`);
  670. return null;
  671. }
  672. }
  673. return hasValidData ? mappedRow : null;
  674. })
  675. .filter((row) => row !== null);
  676. if (uploadData.length === 0) {
  677. $toast.error("유효한 데이터가 없습니다. 엑셀 헤더명과 데이터를 확인해주세요.");
  678. return;
  679. }
  680. // 기존 데이터와 매칭하여 업데이트
  681. await updateDeliveryInfo(uploadData);
  682. } catch (error) {
  683. console.error("엑셀 파일 처리 중 오류:", error);
  684. errorHandler.handleApiError(error, "엑셀 파일 처리");
  685. }
  686. };
  687. reader.onerror = () => {
  688. $toast.error("파일을 읽는 중 오류가 발생했습니다.");
  689. };
  690. reader.readAsArrayBuffer(file);
  691. };
  692. const updateDeliveryInfo = async (uploadData) => {
  693. let matchedCount = 0;
  694. let unmatchedCount = 0;
  695. const unmatchedItems = [];
  696. // 기존 데이터와 매칭
  697. const updatedItems = tblItems.value.map(existingItem => {
  698. // 구매자명과 연락처로 매칭 (공백 제거 후 비교)
  699. const matchedUpload = uploadData.find(upload =>
  700. upload.BUYER_NAME.replace(/\s/g, '') === existingItem.BUYER_NAME.replace(/\s/g, '') &&
  701. upload.PHONE.replace(/\s/g, '').replace(/-/g, '') === existingItem.PHONE.replace(/\s/g, '').replace(/-/g, '')
  702. );
  703. if (matchedUpload) {
  704. matchedCount++;
  705. // 배송업체와 송장번호만 업데이트
  706. return {
  707. ...existingItem,
  708. DELI_COMP: matchedUpload.DELI_COMP,
  709. DELI_NUMB: matchedUpload.DELI_NUMB
  710. };
  711. }
  712. return existingItem;
  713. });
  714. // 매칭되지 않은 업로드 데이터 확인
  715. uploadData.forEach(upload => {
  716. const matched = tblItems.value.find(existing =>
  717. existing.BUYER_NAME.replace(/\s/g, '') === upload.BUYER_NAME.replace(/\s/g, '') &&
  718. existing.PHONE.replace(/\s/g, '').replace(/-/g, '') === upload.PHONE.replace(/\s/g, '').replace(/-/g, '')
  719. );
  720. if (!matched) {
  721. unmatchedCount++;
  722. unmatchedItems.push({
  723. buyerName: upload.BUYER_NAME,
  724. phone: upload.PHONE
  725. });
  726. }
  727. });
  728. // 업데이트된 데이터로 테이블 갱신
  729. tblItems.value = updatedItems;
  730. // ag-grid 데이터 갱신
  731. if (gridApi.value) {
  732. gridApi.value.setGridOption("rowData", tblItems.value);
  733. }
  734. // 결과 메시지 표시
  735. if (matchedCount > 0 && unmatchedCount === 0) {
  736. $toast.success(`${matchedCount}건의 배송정보가 성공적으로 업데이트되었습니다.`);
  737. } else if (matchedCount > 0 && unmatchedCount > 0) {
  738. $toast.warning(
  739. `${matchedCount}건 업데이트 완료, ${unmatchedCount}건 매칭 실패\n매칭 실패 항목: ${unmatchedItems.map(item => `${item.buyerName}(${item.phone})`).join(", ")}`
  740. );
  741. } else {
  742. $toast.error("매칭되는 주문 정보가 없습니다. 구매자명과 연락처를 확인해주세요.");
  743. }
  744. };
  745. const processInfluencerExcelData = async (uploadData) => {
  746. const updatedData = [];
  747. const newData = [];
  748. const errors = [];
  749. // 기존 데이터를 맵으로 변환 (구매자명 + 연락처 키로 매핑)
  750. const existingDataMap = new Map();
  751. tblItems.value.forEach(item => {
  752. const key = `${item.BUYER_NAME?.trim()}_${item.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
  753. existingDataMap.set(key, item);
  754. });
  755. uploadData.forEach((excelItem, index) => {
  756. try {
  757. // 엑셀 데이터의 키 생성
  758. const key = `${excelItem.BUYER_NAME?.trim()}_${excelItem.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
  759. const existingItem = existingDataMap.get(key);
  760. if (existingItem) {
  761. // 기존 데이터가 있는 경우 주문일 비교
  762. const existingOrderDate = formatDateForComparison(existingItem.ORDER_DATE);
  763. const excelOrderDate = formatDateForComparison(excelItem.ORDER_DATE);
  764. if (existingOrderDate === excelOrderDate) {
  765. // 주문일이 같으면 업데이트 (배송정보 등 다른 필드 업데이트)
  766. updatedData.push({
  767. ...existingItem,
  768. ADDRESS: excelItem.ADDRESS || existingItem.ADDRESS,
  769. EMAIL: excelItem.EMAIL || existingItem.EMAIL,
  770. QTY: excelItem.QTY || existingItem.QTY,
  771. TOTAL: excelItem.TOTAL || existingItem.TOTAL,
  772. DELI_COMP: excelItem.DELI_COMP || existingItem.DELI_COMP,
  773. DELI_NUMB: excelItem.DELI_NUMB || existingItem.DELI_NUMB
  774. });
  775. } else {
  776. // 주문일이 다르면 신규 데이터로 추가
  777. newData.push({
  778. ...excelItem,
  779. // 인플루언서 정보는 기존 데이터에서 가져오기
  780. NICK_NAME: existingItem.NICK_NAME || "알 수 없음"
  781. });
  782. }
  783. } else {
  784. // 기존 데이터가 없으면 신규 데이터로 추가
  785. newData.push({
  786. ...excelItem,
  787. NICK_NAME: "알 수 없음" // 기본값
  788. });
  789. }
  790. } catch (error) {
  791. errors.push(`${index + 1}행 처리 중 오류: ${error.message}`);
  792. }
  793. });
  794. // 업데이트되지 않은 기존 데이터도 유지
  795. tblItems.value.forEach(existingItem => {
  796. const key = `${existingItem.BUYER_NAME?.trim()}_${existingItem.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
  797. const hasUpdate = uploadData.some(excelItem => {
  798. const excelKey = `${excelItem.BUYER_NAME?.trim()}_${excelItem.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
  799. return excelKey === key;
  800. });
  801. // 업데이트되지 않은 기존 데이터는 updatedData에 그대로 추가
  802. if (!hasUpdate) {
  803. updatedData.push(existingItem);
  804. }
  805. });
  806. return { updatedData, newData, errors };
  807. };
  808. const formatDateForComparison = (dateStr) => {
  809. if (!dateStr) return '';
  810. // 문자열로 변환하고 공백 제거
  811. let formattedDate = dateStr.toString().trim();
  812. // YYYY.MM.DD 형태를 YYYY-MM-DD로 변환
  813. formattedDate = formattedDate.replace(/\./g, '-');
  814. // 시간 부분이 있으면 제거하고 날짜 부분만 추출
  815. if (formattedDate.includes(' ')) {
  816. formattedDate = formattedDate.split(' ')[0];
  817. }
  818. return formattedDate;
  819. };
  820. const validateAndMatchOrders = async (uploadData) => {
  821. try {
  822. const response = await useAxios().post("/deli/validateOrders", {
  823. item_seq: useDtStore.boardInfo.seq,
  824. uploadData: uploadData,
  825. });
  826. return {
  827. matchedData: response.data.matched || [],
  828. unmatchedData: response.data.unmatched || [],
  829. errors: response.data.errors || [],
  830. };
  831. } catch (error) {
  832. console.error("주문 매칭 검증 중 오류:", error);
  833. // API 오류 시 클라이언트에서 기본 매칭 수행
  834. return performClientSideMatching(uploadData);
  835. }
  836. };
  837. const performClientSideMatching = (uploadData) => {
  838. // 클라이언트 사이드 매칭 로직 (백업용)
  839. const matchedData = [];
  840. const unmatchedData = [];
  841. const errors = [];
  842. uploadData.forEach((item, index) => {
  843. // 기본 검증: 구매자명과 연락처가 있는지 확인
  844. if (!item.BUYER_NAME || !item.PHONE) {
  845. unmatchedData.push(item);
  846. errors.push(`${index + 1}행: 구매자명 또는 연락처 누락`);
  847. } else {
  848. matchedData.push(item);
  849. }
  850. });
  851. return { matchedData, unmatchedData, errors };
  852. };
  853. const showUnmatchedDataModal = (unmatchedData, errors) => {
  854. const errorDetails =
  855. errors.length > 0 ? errors.join("\n") : "매칭 실패 데이터가 있습니다.";
  856. let param = {
  857. id: "unmatchedData",
  858. title: "업로드 실패 항목",
  859. content: `다음 ${unmatchedData.length}건의 데이터를 처리할 수 없습니다:\n\n${errorDetails}\n\n데이터를 수정 후 다시 업로드해주세요.`,
  860. yes: {
  861. text: "확인",
  862. isProc: false,
  863. },
  864. };
  865. $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  866. };
  867. const downloadExcel = () => {
  868. if (!tblItems.value || tblItems.value.length === 0) {
  869. $toast.warning("다운로드할 데이터가 없습니다.");
  870. return;
  871. }
  872. // 한글 헤더명 배열
  873. const headers = [
  874. "구매자명",
  875. "주소",
  876. "연락처",
  877. "이메일",
  878. "구매수량",
  879. "총구매금액",
  880. "배송업체",
  881. "송장번호",
  882. "주문일",
  883. ];
  884. // 데이터를 엑셀 형식으로 변환
  885. const excelData = tblItems.value.map((item) => [
  886. item.BUYER_NAME || "",
  887. item.ADDRESS || "",
  888. item.PHONE || "",
  889. item.EMAIL || "",
  890. item.QTY || "",
  891. item.TOTAL || "",
  892. item.DELI_COMP || "",
  893. item.DELI_NUMB || "",
  894. item.ORDER_DATE || "",
  895. ]);
  896. // 헤더를 첫 번째 행에 추가
  897. const worksheetData = [headers, ...excelData];
  898. // 워크시트 생성
  899. const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
  900. // 워크북 생성
  901. const workbook = XLSX.utils.book_new();
  902. XLSX.utils.book_append_sheet(workbook, worksheet, "배송관리");
  903. // 파일명 생성 (현재 날짜 포함)
  904. const today = new Date();
  905. const dateString =
  906. today.getFullYear() +
  907. String(today.getMonth() + 1).padStart(2, "0") +
  908. String(today.getDate()).padStart(2, "0");
  909. const fileName = `배송관리_${dateString}.xlsx`;
  910. // 엑셀 파일 다운로드
  911. XLSX.writeFile(workbook, fileName);
  912. $toast.success("엑셀 파일이 다운로드되었습니다.");
  913. };
  914. const fnDetail = () => {
  915. let req = {
  916. seq: useDtStore.boardInfo.seq,
  917. };
  918. let req2 = {
  919. item_seq: useDtStore.boardInfo.seq,
  920. };
  921. // 인플루언서일 경우 본인의 inf_seq값 추가
  922. if (memberType === 'INFLUENCER') {
  923. req2.inf_seq = memberSeq;
  924. }
  925. useAxios()
  926. .get(`/item/detail/${req.seq}`)
  927. .then((res) => {
  928. form.value.formValue1 = res.data.NAME;
  929. form.value.formValue2 = res.data.PRICE1;
  930. form.value.formValue3 = res.data.PRICE2;
  931. form.value.formValue4 = res.data.DELI_FEE;
  932. form.value.formValue5 = res.data.THUMB_FILE;
  933. form.value.formValue6 = res.data.SUB_TITLE;
  934. form.value.formValue8 = res.data.STATUS;
  935. form.value.formValue9 = res.data.SHOW_YN;
  936. form.value.formValue10 = res.data.ADD_INFO;
  937. //썸네일 파일이 있으면 넣어줌
  938. if (form.value.formValue5) {
  939. imgTemp.value = `https://shopdeli.mycafe24.com/writable/uploads/item/thumb/${form.value.formValue5}`;
  940. }
  941. })
  942. .catch((error) => {
  943. $toast.error("제품 정보를 불러오는 중 오류가 발생했습니다.");
  944. })
  945. .finally(() => {});
  946. // 기 저장된 구매자명 리스트
  947. // 제품 seq, 인플루언서 seq가 일치하는 리스트만
  948. useAxios()
  949. .post(`/deli/list`, req2)
  950. .then((res) => {
  951. console.log(res.data);
  952. tblItems.value = res.data;
  953. pageObj.value.totalCnt = tblItems.value.length;
  954. isExcelProcessed.value = false; // 초기 로드이므로 엑셀 처리 아님
  955. })
  956. .catch((error) => {
  957. $toast.error("제품 정보를 불러오는 중 오류가 발생했습니다.");
  958. })
  959. .finally(() => {});
  960. };
  961. const fnInsert = async () => {
  962. // 벤더사인 경우 배송정보 업데이트 API 사용
  963. if (memberType === 'VENDOR') {
  964. await fnVendorUpdate();
  965. return;
  966. }
  967. // 인플루언서인 경우 기존 로직 사용
  968. const deliveryData = {
  969. item_seq: useDtStore.boardInfo.seq,
  970. inf_seq: memberSeq,
  971. useOrderDateMatching: isExcelProcessed.value, // 엑셀 업로드로 처리된 경우 true
  972. deliveryList: tblItems.value.map((item) => ({
  973. buyerName: item.BUYER_NAME,
  974. address: item.ADDRESS,
  975. phone: item.PHONE,
  976. email: item.EMAIL,
  977. qty: item.QTY,
  978. total: item.TOTAL,
  979. deliComp: item.DELI_COMP || '',
  980. deliNumb: item.DELI_NUMB ? String(item.DELI_NUMB) : '',
  981. orderDate: item.ORDER_DATE.replaceAll(".", "-"),
  982. })),
  983. };
  984. await withLoading(async () => {
  985. return useAxios().post("/deli/reg", deliveryData);
  986. }, "배송 데이터를 저장하는 중...")
  987. .then((res) => {
  988. $toast.success("배송 데이터가 성공적으로 저장되었습니다.");
  989. // 저장 완료 후 배송 관리 리스트로 이동하며 업로드 성공 상태 전달
  990. router.push({
  991. path: "/view/common/deli",
  992. query: {
  993. uploadStatus: "success",
  994. itemId: useDtStore.boardInfo.seq,
  995. recordCount: tblItems.value.length,
  996. statusUpdated: "false",
  997. },
  998. });
  999. })
  1000. .catch((error) => {
  1001. const errorHandler = useErrorHandler();
  1002. errorHandler.handleApiError(error, "배송 데이터 저장");
  1003. })
  1004. .finally(() => {});
  1005. };
  1006. const fnVendorUpdate = async () => {
  1007. // 배송정보가 있는 항목만 추출 (구매자명과 연락처는 필수)
  1008. const deliveryUpdates = tblItems.value
  1009. .filter(item => item.BUYER_NAME && item.PHONE)
  1010. .map(item => ({
  1011. buyerName: item.BUYER_NAME,
  1012. phone: item.PHONE,
  1013. deliComp: item.DELI_COMP || '',
  1014. deliNumb: item.DELI_NUMB ? String(item.DELI_NUMB) : ''
  1015. }));
  1016. if (deliveryUpdates.length === 0) {
  1017. $toast.error("업데이트할 배송정보가 없습니다.");
  1018. return;
  1019. }
  1020. console.log('벤더 배송정보 업데이트 데이터:', {
  1021. item_seq: useDtStore.boardInfo.seq,
  1022. deliveryUpdates: deliveryUpdates
  1023. });
  1024. const updateData = {
  1025. item_seq: useDtStore.boardInfo.seq,
  1026. deliveryUpdates: deliveryUpdates
  1027. };
  1028. await withLoading(async () => {
  1029. return useAxios().post("/deli/updateDeliveryInfo", updateData);
  1030. }, "배송정보를 업데이트하는 중...")
  1031. .then((res) => {
  1032. $toast.success(`${res.data.updated_count}건의 배송정보가 업데이트되었습니다.`);
  1033. // 배송 관리 목록으로 이동
  1034. router.push({
  1035. path: "/view/common/deli",
  1036. query: {
  1037. uploadStatus: "success",
  1038. itemId: useDtStore.boardInfo.seq,
  1039. recordCount: res.data.updated_count,
  1040. statusUpdated: "false",
  1041. },
  1042. });
  1043. })
  1044. .catch((error) => {
  1045. const errorHandler = useErrorHandler();
  1046. errorHandler.handleApiError(error, "배송정보 업데이트");
  1047. });
  1048. };
  1049. /************************************************************************
  1050. | 팝업 이벤트버스 정의
  1051. ************************************************************************/
  1052. $eventBus.off("FN_INSERT");
  1053. $eventBus.on("FN_INSERT", () => {
  1054. fnInsert();
  1055. });
  1056. $eventBus.off("FN_DELETE_SELECTED");
  1057. $eventBus.on("FN_DELETE_SELECTED", (selectedRows) => {
  1058. fnDeleteSelected(selectedRows);
  1059. });
  1060. /************************************************************************
  1061. | WATCH
  1062. ************************************************************************/
  1063. watch(
  1064. () => props,
  1065. () => {
  1066. searchObj.value = props.propsData;
  1067. fnGetStat();
  1068. },
  1069. { deep: true }
  1070. );
  1071. onMounted(() => {
  1072. fnDetail();
  1073. });
  1074. </script>