detail.vue 40 KB

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