detail.vue 41 KB

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