detail.vue 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234
  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 ? res.data.ORDER_START_DATE.slice(0, 10) : '';
  944. form.value.order_end_date = res.data.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. console.error('제품 상세 정보 로드 오류:', error);
  952. $toast.error("제품 정보를 불러오는 중 오류가 발생했습니다.");
  953. })
  954. .finally(() => {});
  955. // 기 저장된 구매자명 리스트
  956. // 제품 seq, 인플루언서 seq가 일치하는 리스트만
  957. useAxios()
  958. .post(`/deli/list`, req2)
  959. .then((res) => {
  960. console.log(res.data);
  961. tblItems.value = res.data;
  962. pageObj.value.totalCnt = tblItems.value.length;
  963. isExcelProcessed.value = false; // 초기 로드이므로 엑셀 처리 아님
  964. })
  965. .catch((error) => {
  966. $toast.error("제품 정보를 불러오는 중 오류가 발생했습니다.");
  967. })
  968. .finally(() => {});
  969. };
  970. const fnInsert = async () => {
  971. // 벤더사인 경우 배송정보 업데이트 API 사용
  972. if (memberType === 'VENDOR') {
  973. await fnVendorUpdate();
  974. return;
  975. }
  976. // 인플루언서인 경우 기존 로직 사용
  977. const deliveryData = {
  978. item_seq: useDtStore.boardInfo.seq,
  979. inf_seq: memberSeq,
  980. useOrderDateMatching: isExcelProcessed.value, // 엑셀 업로드로 처리된 경우 true
  981. deliveryList: tblItems.value.map((item) => ({
  982. buyerName: item.BUYER_NAME,
  983. address: item.ADDRESS,
  984. phone: item.PHONE,
  985. email: item.EMAIL,
  986. qty: item.QTY,
  987. total: item.TOTAL,
  988. deliComp: item.DELI_COMP || '',
  989. deliNumb: item.DELI_NUMB ? String(item.DELI_NUMB) : '',
  990. orderDate: item.ORDER_DATE.replaceAll(".", "-"),
  991. })),
  992. };
  993. await withLoading(async () => {
  994. return useAxios().post("/deli/reg", deliveryData);
  995. }, "배송 데이터를 저장하는 중...")
  996. .then((res) => {
  997. $toast.success("배송 데이터가 성공적으로 저장되었습니다.");
  998. // 저장 완료 후 배송 관리 리스트로 이동하며 업로드 성공 상태 전달
  999. router.push({
  1000. path: "/view/common/deli",
  1001. query: {
  1002. uploadStatus: "success",
  1003. itemId: useDtStore.boardInfo.seq,
  1004. recordCount: tblItems.value.length,
  1005. statusUpdated: "false",
  1006. },
  1007. });
  1008. })
  1009. .catch((error) => {
  1010. const errorHandler = useErrorHandler();
  1011. errorHandler.handleApiError(error, "배송 데이터 저장");
  1012. })
  1013. .finally(() => {});
  1014. };
  1015. const fnVendorUpdate = async () => {
  1016. // 배송업체나 송장번호가 실제로 입력된 항목만 추출
  1017. const deliveryUpdates = tblItems.value
  1018. .filter(item => {
  1019. // 구매자명과 연락처는 필수, 그리고 배송업체나 송장번호 중 하나라도 값이 있어야 함
  1020. return item.BUYER_NAME && item.PHONE &&
  1021. (item.DELI_COMP || item.DELI_NUMB);
  1022. })
  1023. .map(item => ({
  1024. buyerName: item.BUYER_NAME,
  1025. phone: item.PHONE,
  1026. deliComp: item.DELI_COMP || '',
  1027. deliNumb: item.DELI_NUMB ? String(item.DELI_NUMB) : ''
  1028. }));
  1029. if (deliveryUpdates.length === 0) {
  1030. $toast.error("배송업체나 송장번호가 입력된 항목이 없습니다.");
  1031. return;
  1032. }
  1033. console.log('벤더 배송정보 업데이트 데이터 (편집된 항목만):', {
  1034. item_seq: useDtStore.boardInfo.seq,
  1035. deliveryUpdates: deliveryUpdates,
  1036. 총_항목수: tblItems.value.length,
  1037. 업데이트_항목수: deliveryUpdates.length
  1038. });
  1039. const updateData = {
  1040. item_seq: useDtStore.boardInfo.seq,
  1041. deliveryUpdates: deliveryUpdates
  1042. };
  1043. await withLoading(async () => {
  1044. return useAxios().post("/deli/updateDeliveryInfo", updateData);
  1045. }, "배송정보를 업데이트하는 중...")
  1046. .then((res) => {
  1047. console.log('배송정보 업데이트 응답:', res.data);
  1048. if (res.data.debug_logs) {
  1049. console.log('=== 디버그 로그 ===');
  1050. res.data.debug_logs.forEach((log, index) => {
  1051. console.log(`${index + 1}. ${log}`);
  1052. });
  1053. console.log('================');
  1054. }
  1055. $toast.success(`${res.data.updated_count}건의 배송정보가 업데이트되었습니다.`);
  1056. // 배송 관리 목록으로 이동
  1057. router.push({
  1058. path: "/view/common/deli",
  1059. query: {
  1060. uploadStatus: "success",
  1061. itemId: useDtStore.boardInfo.seq,
  1062. recordCount: res.data.updated_count,
  1063. statusUpdated: "false",
  1064. },
  1065. });
  1066. })
  1067. .catch((error) => {
  1068. console.log('배송정보 업데이트 에러:', error);
  1069. if (error.response?.data?.debug_logs) {
  1070. console.log('=== 에러 디버그 로그 ===');
  1071. error.response.data.debug_logs.forEach((log, index) => {
  1072. console.log(`${index + 1}. ${log}`);
  1073. });
  1074. console.log('====================');
  1075. }
  1076. const errorHandler = useErrorHandler();
  1077. errorHandler.handleApiError(error, "배송정보 업데이트");
  1078. });
  1079. };
  1080. /************************************************************************
  1081. | 팝업 이벤트버스 정의
  1082. ************************************************************************/
  1083. $eventBus.off("FN_INSERT");
  1084. $eventBus.on("FN_INSERT", () => {
  1085. fnInsert();
  1086. });
  1087. $eventBus.off("FN_DELETE_SELECTED");
  1088. $eventBus.on("FN_DELETE_SELECTED", (selectedRows) => {
  1089. fnDeleteSelected(selectedRows);
  1090. });
  1091. /************************************************************************
  1092. | WATCH
  1093. ************************************************************************/
  1094. watch(
  1095. () => props,
  1096. () => {
  1097. searchObj.value = props.propsData;
  1098. fnGetStat();
  1099. },
  1100. { deep: true }
  1101. );
  1102. onMounted(() => {
  1103. fnDetail();
  1104. });
  1105. </script>