detail.vue 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154
  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. const addEmptyRow = () => {
  308. const newRow = {
  309. BUYER_NAME: "",
  310. ADDRESS: "",
  311. PHONE: "",
  312. EMAIL: "",
  313. QTY: "",
  314. TOTAL: "",
  315. DELI_COMP: "",
  316. DELI_NUMB: "",
  317. ORDER_DATE: "",
  318. };
  319. // 맨 앞에 추가 (unshift 사용)
  320. tblItems.value.unshift(newRow);
  321. pageObj.value.totalCnt = tblItems.value.length;
  322. isExcelProcessed.value = false; // 수동 추가이므로 엑셀 처리 아님
  323. // ag-grid 데이터 갱신
  324. if (gridApi.value) {
  325. gridApi.value.setGridOption("rowData", tblItems.value);
  326. }
  327. $toast.success("새 항목이 추가되었습니다.");
  328. };
  329. const deleteSelectedRows = () => {
  330. if (!gridApi.value) return;
  331. const selectedRows = gridApi.value.getSelectedRows();
  332. if (selectedRows.length === 0) {
  333. $toast.warning("삭제할 항목을 선택해주세요.");
  334. return;
  335. }
  336. let param = {
  337. id: pageId,
  338. title: pageId,
  339. content: `선택된 ${selectedRows.length}개 항목을 삭제하시겠습니까?`,
  340. yes: {
  341. text: "삭제",
  342. isProc: true,
  343. event: "FN_DELETE_SELECTED",
  344. param: selectedRows,
  345. },
  346. no: {
  347. text: "취소",
  348. isProc: false,
  349. },
  350. };
  351. $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  352. };
  353. const fnDeleteSelected = (selectedRows) => {
  354. // 선택된 행들을 tblItems에서 제거
  355. selectedRows.forEach((selectedRow) => {
  356. const index = tblItems.value.findIndex(
  357. (item) =>
  358. item.BUYER_NAME === selectedRow.BUYER_NAME &&
  359. item.ADDRESS === selectedRow.ADDRESS &&
  360. item.PHONE === selectedRow.PHONE &&
  361. item.EMAIL === selectedRow.EMAIL
  362. );
  363. if (index > -1) {
  364. tblItems.value.splice(index, 1);
  365. }
  366. });
  367. pageObj.value.totalCnt = tblItems.value.length;
  368. // ag-grid 데이터 갱신
  369. if (gridApi.value) {
  370. gridApi.value.setGridOption("rowData", tblItems.value);
  371. }
  372. $toast.success(`${selectedRows.length}개 항목이 삭제되었습니다.`);
  373. };
  374. const handleExcelUpload = async (event) => {
  375. const file = event.target.files[0];
  376. if (!file) return;
  377. // 사용자 타입에 따라 다른 업로드 로직 호출
  378. if (memberType === 'VENDOR') {
  379. await handleVendorExcelUpload(file);
  380. } else {
  381. await handleInfluencerExcelUpload(file);
  382. }
  383. // 파일 입력 초기화
  384. event.target.value = "";
  385. };
  386. const handleInfluencerExcelUpload = async (file) => {
  387. const errorHandler = useErrorHandler();
  388. // 파일 크기 검증 (10MB)
  389. const maxSize = 10 * 1024 * 1024;
  390. if (file.size > maxSize) {
  391. const sizeError = new Error("파일 크기 초과");
  392. sizeError.name = "FileSizeError";
  393. errorHandler.handleFileError(sizeError, file.name);
  394. event.target.value = "";
  395. return;
  396. }
  397. // 파일 형식 검증
  398. const allowedTypes = [
  399. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  400. "application/vnd.ms-excel",
  401. ];
  402. if (!allowedTypes.includes(file.type)) {
  403. const typeError = new Error("지원하지 않는 파일 형식");
  404. typeError.name = "FileTypeError";
  405. errorHandler.handleFileError(typeError, file.name);
  406. event.target.value = "";
  407. return;
  408. }
  409. const reader = new FileReader();
  410. reader.onload = async (e) => {
  411. try {
  412. const data = new Uint8Array(e.target.result);
  413. const workbook = XLSX.read(data, { type: "array" });
  414. const sheetName = workbook.SheetNames[0];
  415. const worksheet = workbook.Sheets[sheetName];
  416. const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
  417. if (jsonData.length < 2) {
  418. $toast.error(
  419. "엑셀 파일에 데이터가 없습니다. 헤더와 최소 1개 이상의 데이터 행이 필요합니다."
  420. );
  421. return;
  422. }
  423. const headers = jsonData[0];
  424. const rows = jsonData.slice(1);
  425. // 필수 헤더 검증
  426. const requiredHeaders = ["구매자명", "주소", "연락처"];
  427. const missingHeaders = requiredHeaders.filter(
  428. (header) => !headers.includes(header)
  429. );
  430. if (missingHeaders.length > 0) {
  431. $toast.error(`필수 헤더가 누락되었습니다: ${missingHeaders.join(", ")}`);
  432. return;
  433. }
  434. // 컬럼명 매핑 및 데이터 변환
  435. const mappedData = rows
  436. .map((row, rowIndex) => {
  437. const mappedRow = {};
  438. let hasValidData = false;
  439. headers.forEach((header, index) => {
  440. const fieldName = excelColumnMapping[header];
  441. if (fieldName && row[index] !== undefined && row[index] !== "") {
  442. mappedRow[fieldName] = row[index];
  443. hasValidData = true;
  444. }
  445. });
  446. // 필수 필드 검증
  447. if (hasValidData) {
  448. const missingRequiredFields = [];
  449. if (!mappedRow.BUYER_NAME) missingRequiredFields.push("구매자명");
  450. if (!mappedRow.ADDRESS) missingRequiredFields.push("주소");
  451. if (!mappedRow.PHONE) missingRequiredFields.push("연락처");
  452. if (missingRequiredFields.length > 0) {
  453. console.warn(
  454. `${rowIndex + 2}행: 필수 필드 누락 - ${missingRequiredFields.join(
  455. ", "
  456. )}`
  457. );
  458. }
  459. }
  460. return hasValidData ? mappedRow : null;
  461. })
  462. .filter((row) => row !== null);
  463. if (mappedData.length === 0) {
  464. $toast.error(
  465. "매핑 가능한 데이터가 없습니다. 엑셀 헤더명과 데이터를 확인해주세요."
  466. );
  467. return;
  468. }
  469. // 기존 데이터와 엑셀 데이터를 주문일 기준으로 분리 처리
  470. const processResult = await processInfluencerExcelData(mappedData);
  471. const { updatedData, newData, errors } = processResult;
  472. // 업데이트된 기존 데이터 + 신규 데이터를 합쳐서 그리드에 설정
  473. tblItems.value = [...updatedData, ...newData];
  474. pageObj.value.totalCnt = tblItems.value.length;
  475. isExcelProcessed.value = true; // 엑셀 처리 완료 표시
  476. // ag-grid 데이터 갱신
  477. if (gridApi.value) {
  478. gridApi.value.setGridOption("rowData", tblItems.value);
  479. }
  480. // 결과에 따른 사용자 피드백
  481. const totalProcessed = updatedData.length + newData.length;
  482. if (totalProcessed > 0) {
  483. if (updatedData.length > 0 && newData.length > 0) {
  484. $toast.success(
  485. `총 ${totalProcessed}건 처리완료 (업데이트: ${updatedData.length}건, 신규: ${newData.length}건)`
  486. );
  487. } else if (updatedData.length > 0) {
  488. $toast.success(
  489. `${updatedData.length}건의 기존 주문이 업데이트되었습니다.`
  490. );
  491. } else {
  492. $toast.success(
  493. `${newData.length}건의 신규 주문이 추가되었습니다.`
  494. );
  495. }
  496. } else {
  497. $toast.error(
  498. "처리된 데이터가 없습니다. 엑셀 데이터를 확인해주세요."
  499. );
  500. }
  501. if (errors.length > 0) {
  502. console.warn("처리 중 발생한 오류들:", errors);
  503. }
  504. } catch (error) {
  505. console.error("엑셀 파일 처리 중 오류:", error);
  506. $toast.error(
  507. "엑셀 파일을 읽는 중 오류가 발생했습니다. 파일 형식을 확인해주세요."
  508. );
  509. }
  510. };
  511. reader.onerror = () => {
  512. $toast.error("파일을 읽는 중 오류가 발생했습니다.");
  513. };
  514. reader.readAsArrayBuffer(file);
  515. };
  516. const handleVendorExcelUpload = async (file) => {
  517. const errorHandler = useErrorHandler();
  518. // 파일 크기 검증 (10MB)
  519. const maxSize = 10 * 1024 * 1024;
  520. if (file.size > maxSize) {
  521. const sizeError = new Error("파일 크기 초과");
  522. sizeError.name = "FileSizeError";
  523. errorHandler.handleFileError(sizeError, file.name);
  524. return;
  525. }
  526. // 파일 형식 검증
  527. const allowedTypes = [
  528. "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  529. "application/vnd.ms-excel",
  530. ];
  531. if (!allowedTypes.includes(file.type)) {
  532. const typeError = new Error("지원하지 않는 파일 형식");
  533. typeError.name = "FileTypeError";
  534. errorHandler.handleFileError(typeError, file.name);
  535. return;
  536. }
  537. const reader = new FileReader();
  538. reader.onload = async (e) => {
  539. try {
  540. const data = new Uint8Array(e.target.result);
  541. const workbook = XLSX.read(data, { type: "array" });
  542. const sheetName = workbook.SheetNames[0];
  543. const worksheet = workbook.Sheets[sheetName];
  544. const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
  545. if (jsonData.length < 2) {
  546. $toast.error("엑셀 파일에 데이터가 없습니다. 헤더와 최소 1개 이상의 데이터 행이 필요합니다.");
  547. return;
  548. }
  549. const headers = jsonData[0];
  550. const rows = jsonData.slice(1);
  551. // 벤더사용 필수 헤더 검증
  552. const requiredHeaders = ["구매자명", "연락처", "배송업체", "송장번호"];
  553. const missingHeaders = requiredHeaders.filter(
  554. (header) => !headers.includes(header)
  555. );
  556. if (missingHeaders.length > 0) {
  557. $toast.error(`필수 헤더가 누락되었습니다: ${missingHeaders.join(", ")}`);
  558. return;
  559. }
  560. // 벤더사용 컬럼 매핑
  561. const vendorColumnMapping = {
  562. "구매자명": "BUYER_NAME",
  563. "연락처": "PHONE",
  564. "배송업체": "DELI_COMP",
  565. "송장번호": "DELI_NUMB"
  566. };
  567. // 업로드 데이터 변환
  568. const uploadData = rows
  569. .map((row, rowIndex) => {
  570. const mappedRow = {};
  571. let hasValidData = false;
  572. headers.forEach((header, index) => {
  573. const fieldName = vendorColumnMapping[header];
  574. if (fieldName && row[index] !== undefined && row[index] !== "") {
  575. mappedRow[fieldName] = String(row[index]).trim();
  576. hasValidData = true;
  577. }
  578. });
  579. // 필수 필드 검증
  580. if (hasValidData) {
  581. const missingRequiredFields = [];
  582. if (!mappedRow.BUYER_NAME) missingRequiredFields.push("구매자명");
  583. if (!mappedRow.PHONE) missingRequiredFields.push("연락처");
  584. if (!mappedRow.DELI_COMP) missingRequiredFields.push("배송업체");
  585. if (!mappedRow.DELI_NUMB) missingRequiredFields.push("송장번호");
  586. if (missingRequiredFields.length > 0) {
  587. console.warn(`${rowIndex + 2}행: 필수 필드 누락 - ${missingRequiredFields.join(", ")}`);
  588. return null;
  589. }
  590. }
  591. return hasValidData ? mappedRow : null;
  592. })
  593. .filter((row) => row !== null);
  594. if (uploadData.length === 0) {
  595. $toast.error("유효한 데이터가 없습니다. 엑셀 헤더명과 데이터를 확인해주세요.");
  596. return;
  597. }
  598. // 기존 데이터와 매칭하여 업데이트
  599. await updateDeliveryInfo(uploadData);
  600. } catch (error) {
  601. console.error("엑셀 파일 처리 중 오류:", error);
  602. errorHandler.handleApiError(error, "엑셀 파일 처리");
  603. }
  604. };
  605. reader.onerror = () => {
  606. $toast.error("파일을 읽는 중 오류가 발생했습니다.");
  607. };
  608. reader.readAsArrayBuffer(file);
  609. };
  610. const updateDeliveryInfo = async (uploadData) => {
  611. let matchedCount = 0;
  612. let unmatchedCount = 0;
  613. const unmatchedItems = [];
  614. // 기존 데이터와 매칭
  615. const updatedItems = tblItems.value.map(existingItem => {
  616. // 구매자명과 연락처로 매칭 (공백 제거 후 비교)
  617. const matchedUpload = uploadData.find(upload =>
  618. upload.BUYER_NAME.replace(/\s/g, '') === existingItem.BUYER_NAME.replace(/\s/g, '') &&
  619. upload.PHONE.replace(/\s/g, '').replace(/-/g, '') === existingItem.PHONE.replace(/\s/g, '').replace(/-/g, '')
  620. );
  621. if (matchedUpload) {
  622. matchedCount++;
  623. // 배송업체와 송장번호만 업데이트
  624. return {
  625. ...existingItem,
  626. DELI_COMP: matchedUpload.DELI_COMP,
  627. DELI_NUMB: matchedUpload.DELI_NUMB
  628. };
  629. }
  630. return existingItem;
  631. });
  632. // 매칭되지 않은 업로드 데이터 확인
  633. uploadData.forEach(upload => {
  634. const matched = tblItems.value.find(existing =>
  635. existing.BUYER_NAME.replace(/\s/g, '') === upload.BUYER_NAME.replace(/\s/g, '') &&
  636. existing.PHONE.replace(/\s/g, '').replace(/-/g, '') === upload.PHONE.replace(/\s/g, '').replace(/-/g, '')
  637. );
  638. if (!matched) {
  639. unmatchedCount++;
  640. unmatchedItems.push({
  641. buyerName: upload.BUYER_NAME,
  642. phone: upload.PHONE
  643. });
  644. }
  645. });
  646. // 업데이트된 데이터로 테이블 갱신
  647. tblItems.value = updatedItems;
  648. // ag-grid 데이터 갱신
  649. if (gridApi.value) {
  650. gridApi.value.setGridOption("rowData", tblItems.value);
  651. }
  652. // 결과 메시지 표시
  653. if (matchedCount > 0 && unmatchedCount === 0) {
  654. $toast.success(`${matchedCount}건의 배송정보가 성공적으로 업데이트되었습니다.`);
  655. } else if (matchedCount > 0 && unmatchedCount > 0) {
  656. $toast.warning(
  657. `${matchedCount}건 업데이트 완료, ${unmatchedCount}건 매칭 실패\n매칭 실패 항목: ${unmatchedItems.map(item => `${item.buyerName}(${item.phone})`).join(", ")}`
  658. );
  659. } else {
  660. $toast.error("매칭되는 주문 정보가 없습니다. 구매자명과 연락처를 확인해주세요.");
  661. }
  662. };
  663. const processInfluencerExcelData = async (uploadData) => {
  664. const updatedData = [];
  665. const newData = [];
  666. const errors = [];
  667. // 기존 데이터를 맵으로 변환 (구매자명 + 연락처 키로 매핑)
  668. const existingDataMap = new Map();
  669. tblItems.value.forEach(item => {
  670. const key = `${item.BUYER_NAME?.trim()}_${item.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
  671. existingDataMap.set(key, item);
  672. });
  673. uploadData.forEach((excelItem, index) => {
  674. try {
  675. // 엑셀 데이터의 키 생성
  676. const key = `${excelItem.BUYER_NAME?.trim()}_${excelItem.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
  677. const existingItem = existingDataMap.get(key);
  678. if (existingItem) {
  679. // 기존 데이터가 있는 경우 주문일 비교
  680. const existingOrderDate = formatDateForComparison(existingItem.ORDER_DATE);
  681. const excelOrderDate = formatDateForComparison(excelItem.ORDER_DATE);
  682. if (existingOrderDate === excelOrderDate) {
  683. // 주문일이 같으면 업데이트 (배송정보 등 다른 필드 업데이트)
  684. updatedData.push({
  685. ...existingItem,
  686. ADDRESS: excelItem.ADDRESS || existingItem.ADDRESS,
  687. EMAIL: excelItem.EMAIL || existingItem.EMAIL,
  688. QTY: excelItem.QTY || existingItem.QTY,
  689. TOTAL: excelItem.TOTAL || existingItem.TOTAL,
  690. DELI_COMP: excelItem.DELI_COMP || existingItem.DELI_COMP,
  691. DELI_NUMB: excelItem.DELI_NUMB || existingItem.DELI_NUMB
  692. });
  693. } else {
  694. // 주문일이 다르면 신규 데이터로 추가
  695. newData.push({
  696. ...excelItem,
  697. // 인플루언서 정보는 기존 데이터에서 가져오기
  698. NICK_NAME: existingItem.NICK_NAME || "알 수 없음"
  699. });
  700. }
  701. } else {
  702. // 기존 데이터가 없으면 신규 데이터로 추가
  703. newData.push({
  704. ...excelItem,
  705. NICK_NAME: "알 수 없음" // 기본값
  706. });
  707. }
  708. } catch (error) {
  709. errors.push(`${index + 1}행 처리 중 오류: ${error.message}`);
  710. }
  711. });
  712. // 업데이트되지 않은 기존 데이터도 유지
  713. tblItems.value.forEach(existingItem => {
  714. const key = `${existingItem.BUYER_NAME?.trim()}_${existingItem.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
  715. const hasUpdate = uploadData.some(excelItem => {
  716. const excelKey = `${excelItem.BUYER_NAME?.trim()}_${excelItem.PHONE?.replace(/\s/g, '').replace(/-/g, '')}`;
  717. return excelKey === key;
  718. });
  719. // 업데이트되지 않은 기존 데이터는 updatedData에 그대로 추가
  720. if (!hasUpdate) {
  721. updatedData.push(existingItem);
  722. }
  723. });
  724. return { updatedData, newData, errors };
  725. };
  726. const formatDateForComparison = (dateStr) => {
  727. if (!dateStr) return '';
  728. // YYYY.MM.DD 또는 YYYY-MM-DD 형태를 YYYY-MM-DD로 통일
  729. return dateStr.toString().replace(/\./g, '-').trim();
  730. };
  731. const validateAndMatchOrders = async (uploadData) => {
  732. try {
  733. const response = await useAxios().post("/deli/validateOrders", {
  734. item_seq: useDtStore.boardInfo.seq,
  735. uploadData: uploadData,
  736. });
  737. return {
  738. matchedData: response.data.matched || [],
  739. unmatchedData: response.data.unmatched || [],
  740. errors: response.data.errors || [],
  741. };
  742. } catch (error) {
  743. console.error("주문 매칭 검증 중 오류:", error);
  744. // API 오류 시 클라이언트에서 기본 매칭 수행
  745. return performClientSideMatching(uploadData);
  746. }
  747. };
  748. const performClientSideMatching = (uploadData) => {
  749. // 클라이언트 사이드 매칭 로직 (백업용)
  750. const matchedData = [];
  751. const unmatchedData = [];
  752. const errors = [];
  753. uploadData.forEach((item, index) => {
  754. // 기본 검증: 구매자명과 연락처가 있는지 확인
  755. if (!item.BUYER_NAME || !item.PHONE) {
  756. unmatchedData.push(item);
  757. errors.push(`${index + 1}행: 구매자명 또는 연락처 누락`);
  758. } else {
  759. matchedData.push(item);
  760. }
  761. });
  762. return { matchedData, unmatchedData, errors };
  763. };
  764. const showUnmatchedDataModal = (unmatchedData, errors) => {
  765. const errorDetails =
  766. errors.length > 0 ? errors.join("\n") : "매칭 실패 데이터가 있습니다.";
  767. let param = {
  768. id: "unmatchedData",
  769. title: "업로드 실패 항목",
  770. content: `다음 ${unmatchedData.length}건의 데이터를 처리할 수 없습니다:\n\n${errorDetails}\n\n데이터를 수정 후 다시 업로드해주세요.`,
  771. yes: {
  772. text: "확인",
  773. isProc: false,
  774. },
  775. };
  776. $eventBus.emit("OPEN_CONFIRM_POP_UP", param);
  777. };
  778. const downloadExcel = () => {
  779. if (!tblItems.value || tblItems.value.length === 0) {
  780. $toast.warning("다운로드할 데이터가 없습니다.");
  781. return;
  782. }
  783. // 한글 헤더명 배열
  784. const headers = [
  785. "구매자명",
  786. "주소",
  787. "연락처",
  788. "이메일",
  789. "구매수량",
  790. "총구매금액",
  791. "배송업체",
  792. "송장번호",
  793. "주문일",
  794. ];
  795. // 데이터를 엑셀 형식으로 변환
  796. const excelData = tblItems.value.map((item) => [
  797. item.BUYER_NAME || "",
  798. item.ADDRESS || "",
  799. item.PHONE || "",
  800. item.EMAIL || "",
  801. item.QTY || "",
  802. item.TOTAL || "",
  803. item.DELI_COMP || "",
  804. item.DELI_NUMB || "",
  805. item.ORDER_DATE || "",
  806. ]);
  807. // 헤더를 첫 번째 행에 추가
  808. const worksheetData = [headers, ...excelData];
  809. // 워크시트 생성
  810. const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
  811. // 워크북 생성
  812. const workbook = XLSX.utils.book_new();
  813. XLSX.utils.book_append_sheet(workbook, worksheet, "배송관리");
  814. // 파일명 생성 (현재 날짜 포함)
  815. const today = new Date();
  816. const dateString =
  817. today.getFullYear() +
  818. String(today.getMonth() + 1).padStart(2, "0") +
  819. String(today.getDate()).padStart(2, "0");
  820. const fileName = `배송관리_${dateString}.xlsx`;
  821. // 엑셀 파일 다운로드
  822. XLSX.writeFile(workbook, fileName);
  823. $toast.success("엑셀 파일이 다운로드되었습니다.");
  824. };
  825. const fnDetail = () => {
  826. let req = {
  827. seq: useDtStore.boardInfo.seq,
  828. };
  829. let req2 = {
  830. item_seq: useDtStore.boardInfo.seq,
  831. };
  832. // 인플루언서일 경우 본인의 inf_seq값 추가
  833. if (memberType === 'INFLUENCER') {
  834. req2.inf_seq = memberSeq;
  835. }
  836. useAxios()
  837. .get(`/item/detail/${req.seq}`)
  838. .then((res) => {
  839. form.value.formValue1 = res.data.NAME;
  840. form.value.formValue2 = res.data.PRICE1;
  841. form.value.formValue3 = res.data.PRICE2;
  842. form.value.formValue4 = res.data.DELI_FEE;
  843. form.value.formValue5 = res.data.THUMB_FILE;
  844. form.value.formValue6 = res.data.SUB_TITLE;
  845. form.value.formValue8 = res.data.STATUS;
  846. form.value.formValue9 = res.data.SHOW_YN;
  847. form.value.formValue10 = res.data.ADD_INFO;
  848. //썸네일 파일이 있으면 넣어줌
  849. if (form.value.formValue5) {
  850. imgTemp.value = `https://shopdeli.mycafe24.com/writable/uploads/item/thumb/${form.value.formValue5}`;
  851. }
  852. })
  853. .catch((error) => {
  854. $toast.error("제품 정보를 불러오는 중 오류가 발생했습니다.");
  855. })
  856. .finally(() => {});
  857. // 기 저장된 구매자명 리스트
  858. // 제품 seq, 인플루언서 seq가 일치하는 리스트만
  859. useAxios()
  860. .post(`/deli/list`, req2)
  861. .then((res) => {
  862. console.log(res.data);
  863. tblItems.value = res.data;
  864. pageObj.value.totalCnt = tblItems.value.length;
  865. isExcelProcessed.value = false; // 초기 로드이므로 엑셀 처리 아님
  866. })
  867. .catch((error) => {
  868. $toast.error("제품 정보를 불러오는 중 오류가 발생했습니다.");
  869. })
  870. .finally(() => {});
  871. };
  872. const fnInsert = async () => {
  873. // 벤더사인 경우 배송정보 업데이트 API 사용
  874. if (memberType === 'VENDOR') {
  875. await fnVendorUpdate();
  876. return;
  877. }
  878. // 인플루언서인 경우 기존 로직 사용
  879. const deliveryData = {
  880. item_seq: useDtStore.boardInfo.seq,
  881. inf_seq: memberSeq,
  882. useOrderDateMatching: isExcelProcessed.value, // 엑셀 업로드로 처리된 경우 true
  883. deliveryList: tblItems.value.map((item) => ({
  884. buyerName: item.BUYER_NAME,
  885. address: item.ADDRESS,
  886. phone: item.PHONE,
  887. email: item.EMAIL,
  888. qty: item.QTY,
  889. total: item.TOTAL,
  890. deliComp: item.DELI_COMP || '',
  891. deliNumb: item.DELI_NUMB ? String(item.DELI_NUMB) : '',
  892. orderDate: item.ORDER_DATE.replaceAll(".", "-"),
  893. })),
  894. };
  895. await withLoading(async () => {
  896. return useAxios().post("/deli/reg", deliveryData);
  897. }, "배송 데이터를 저장하는 중...")
  898. .then((res) => {
  899. // 송장번호가 등록된 경우 상태를 COMPLETE로 업데이트
  900. const hasTrackingNumbers = deliveryData.deliveryList.some(
  901. (item) => item.deliNumb && typeof item.deliNumb === 'string' && item.deliNumb.trim() !== ""
  902. );
  903. if (hasTrackingNumbers) {
  904. // 상태 업데이트 API 호출
  905. const statusUpdateData = {
  906. item_seq: useDtStore.boardInfo.seq,
  907. status: "COMPLETE",
  908. };
  909. useAxios()
  910. .post("/deli/updateStatus", statusUpdateData)
  911. .then(() => {
  912. $toast.success(
  913. "배송 데이터가 성공적으로 저장되었습니다. 상태가 완료로 변경되었습니다."
  914. );
  915. // WebSocket을 통해 상태 변경 이벤트 발행
  916. const { $socket } = useNuxtApp();
  917. if ($socket) {
  918. $socket.emit("deliveryStatusUpdate", {
  919. itemId: useDtStore.boardInfo.seq,
  920. itemName: form.value.formValue1,
  921. status: "COMPLETE",
  922. updatedBy: memberSeq,
  923. updatedAt: new Date().toISOString(),
  924. });
  925. }
  926. })
  927. .catch(() => {
  928. $toast.success("배송 데이터가 저장되었으나 상태 업데이트에 실패했습니다.");
  929. });
  930. } else {
  931. $toast.success("배송 데이터가 성공적으로 저장되었습니다.");
  932. }
  933. // 저장 완료 후 배송 관리 리스트로 이동하며 업로드 성공 상태 전달
  934. router.push({
  935. path: "/view/common/deli",
  936. query: {
  937. uploadStatus: "success",
  938. itemId: useDtStore.boardInfo.seq,
  939. recordCount: tblItems.value.length,
  940. statusUpdated: hasTrackingNumbers ? "true" : "false",
  941. },
  942. });
  943. })
  944. .catch((error) => {
  945. const errorHandler = useErrorHandler();
  946. errorHandler.handleApiError(error, "배송 데이터 저장");
  947. })
  948. .finally(() => {});
  949. };
  950. const fnVendorUpdate = async () => {
  951. // 배송정보가 있는 항목만 추출 (구매자명과 연락처는 필수)
  952. const deliveryUpdates = tblItems.value
  953. .filter(item => item.BUYER_NAME && item.PHONE)
  954. .map(item => ({
  955. buyerName: item.BUYER_NAME,
  956. phone: item.PHONE,
  957. deliComp: item.DELI_COMP || '',
  958. deliNumb: item.DELI_NUMB ? String(item.DELI_NUMB) : ''
  959. }));
  960. if (deliveryUpdates.length === 0) {
  961. $toast.error("업데이트할 배송정보가 없습니다.");
  962. return;
  963. }
  964. const updateData = {
  965. item_seq: useDtStore.boardInfo.seq,
  966. deliveryUpdates: deliveryUpdates
  967. };
  968. await withLoading(async () => {
  969. return useAxios().post("/deli/updateDeliveryInfo", updateData);
  970. }, "배송정보를 업데이트하는 중...")
  971. .then((res) => {
  972. // 송장번호가 등록된 경우 상태를 COMPLETE로 업데이트
  973. const hasTrackingNumbers = deliveryUpdates.some(
  974. (item) => item.deliNumb && typeof item.deliNumb === 'string' && item.deliNumb.trim() !== ""
  975. );
  976. if (hasTrackingNumbers) {
  977. // 상태 업데이트 API 호출
  978. const statusUpdateData = {
  979. item_seq: useDtStore.boardInfo.seq,
  980. status: "COMPLETE",
  981. };
  982. useAxios()
  983. .post("/deli/updateStatus", statusUpdateData)
  984. .then(() => {
  985. $toast.success(
  986. "배송정보가 업데이트되고 상태가 완료로 변경되었습니다."
  987. );
  988. })
  989. .catch((error) => {
  990. console.error("상태 업데이트 실패:", error);
  991. $toast.warning("배송정보는 업데이트되었으나 상태 변경에 실패했습니다.");
  992. });
  993. } else {
  994. $toast.success(`${res.data.updated_count}건의 배송정보가 업데이트되었습니다.`);
  995. }
  996. // 배송 관리 목록으로 이동
  997. router.push({
  998. path: "/view/common/deli",
  999. query: {
  1000. uploadStatus: "success",
  1001. itemId: useDtStore.boardInfo.seq,
  1002. recordCount: res.data.updated_count,
  1003. statusUpdated: hasTrackingNumbers ? "true" : "false",
  1004. },
  1005. });
  1006. })
  1007. .catch((error) => {
  1008. const errorHandler = useErrorHandler();
  1009. errorHandler.handleApiError(error, "배송정보 업데이트");
  1010. });
  1011. };
  1012. /************************************************************************
  1013. | 팝업 이벤트버스 정의
  1014. ************************************************************************/
  1015. $eventBus.off("FN_INSERT");
  1016. $eventBus.on("FN_INSERT", () => {
  1017. fnInsert();
  1018. });
  1019. $eventBus.off("FN_DELETE_SELECTED");
  1020. $eventBus.on("FN_DELETE_SELECTED", (selectedRows) => {
  1021. fnDeleteSelected(selectedRows);
  1022. });
  1023. /************************************************************************
  1024. | WATCH
  1025. ************************************************************************/
  1026. watch(
  1027. () => props,
  1028. () => {
  1029. searchObj.value = props.propsData;
  1030. fnGetStat();
  1031. },
  1032. { deep: true }
  1033. );
  1034. onMounted(() => {
  1035. fnDetail();
  1036. });
  1037. </script>