diff --git a/apps/st/app/(with-base-layout)/statistics/page.tsx b/apps/st/app/(with-base-layout)/statistics/page.tsx index 3c51a4307..f32417f76 100644 --- a/apps/st/app/(with-base-layout)/statistics/page.tsx +++ b/apps/st/app/(with-base-layout)/statistics/page.tsx @@ -1,3 +1,3 @@ -import { statisticsPage } from "@/pages/statistics"; +import { StatisticsPage } from "@/pages/statistics"; -export default statisticsPage; \ No newline at end of file +export default StatisticsPage; diff --git a/apps/st/src/components/css/DataGrid.css b/apps/st/src/components/css/DataGrid.css index 8b1378917..f602400c7 100644 --- a/apps/st/src/components/css/DataGrid.css +++ b/apps/st/src/components/css/DataGrid.css @@ -1 +1,53 @@ +@tailwind components; +@layer components { + .rg-grid .rg-header .rg-table .rg-header-group-cell { + @apply !bg-[#466995] !text-[#fff]; + } + .rg-grid .rg-header .rg-table .rg-header-cell { + @apply !bg-[#5987bf] !text-[#fff]; + } + .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell { + @apply !bg-white; + } + /* 셀 클래스가 있으면 위 기본색보다 우선 (같은 specificity + 나중 규칙) */ + .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-readonly { + @apply !bg-[#f0f0f0] !text-[#666]; + } + .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-verify-error { + @apply !bg-[#ffe6e6] !text-[#c00]; + } + .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-total { + @apply !bg-[#e3eaf2]; + } + + [data-theme="black"] { + .rg-grid .rg-header .rg-table .rg-header-group-cell { + @apply !bg-[#3C4043] !text-[#fff]; + } + .rg-grid .rg-header .rg-table .rg-header-cell { + @apply !bg-[#62686d] !text-[#fff]; + } + .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell { + @apply !bg-[#545556] !text-[#fff]; + } + } + + [data-theme="red"] { + .rg-grid .rg-header .rg-table .rg-header-group-cell { + @apply !bg-[#646469] !text-[#fff]; + } + .rg-grid .rg-header .rg-table .rg-header-cell { + @apply !bg-[#8d8d94] !text-[#fff]; + } + } + + [data-theme="green"] { + .rg-grid .rg-header .rg-table .rg-header-group-cell { + @apply !bg-[#518585] !text-[#fff]; + } + .rg-grid .rg-header .rg-table .rg-header-cell { + @apply !bg-[#6bafae] !text-[#fff]; + } + } +} diff --git a/apps/st/src/components/module/DataGrid.tsx b/apps/st/src/components/module/DataGrid.tsx index 0d0d7ca02..8df22b216 100644 --- a/apps/st/src/components/module/DataGrid.tsx +++ b/apps/st/src/components/module/DataGrid.tsx @@ -3,7 +3,14 @@ import { ValueType } from "realgrid"; import RealGrid, { GridFitStyle, type DisplayOptions } from "realgrid"; import { RealGridReact, RGDataColumn } from "realgrid-react"; -import type { DataGridProps, RealGridColumnInfo, GridViewWithSetColumns, FooterItemWithCallback, ColumnLayoutItem, CellStyleCallback } from "../type/DataGrid.type"; +import type { + DataGridProps, + RealGridColumnInfo, + GridViewWithSetColumns, + FooterItemWithCallback, + ColumnLayoutItem, + CellStyleCallback, +} from "../type/DataGrid.type"; import { getComputedValueCallback } from "@/components/util/grid/computedFieldCallbacks"; import JSZip from "jszip"; import * as XLSX from "xlsx"; @@ -18,7 +25,7 @@ declare module "realgrid" { interface GridView { setOptions(options: { footer?: { visible?: boolean }; - summaryMode?: 'aggregate' | 'statistical' | 'none'; + summaryMode?: "aggregate" | "statistical" | "none"; checkBar?: { visible?: boolean }; }): void; } @@ -36,16 +43,25 @@ if (typeof window !== "undefined") { window.JSZip = JSZip; } -RealGrid.setLicenseKey(process.env.NEXT_PUBLIC_ST_REALGRID_KEY || ''); +RealGrid.setLicenseKey(process.env.NEXT_PUBLIC_ST_REALGRID_KEY || ""); /** setDataComparer(field, comparer) - setFields 없이 숫자 정렬용. comparer(field, row1, row2) => -1|0|1 */ interface RealGridDataProviderComparer { - setDataComparer?(field: string | number, comparer: (field: string | number, row1: number, row2: number) => number): void; + setDataComparer?( + field: string | number, + comparer: ( + field: string | number, + row1: number, + row2: number, + ) => number, + ): void; getValue?(row: number, field: string | number): unknown; } /** setDataComparer용 숫자 비교기. setFields 없이 숫자 정렬. */ -function createNumberComparer(dp: RealGridDataProviderComparer): (field: string | number, row1: number, row2: number) => number { +function createNumberComparer( + dp: RealGridDataProviderComparer, +): (field: string | number, row1: number, row2: number) => number { return (field, row1, row2) => { const get = dp.getValue?.bind(dp); if (!get) return 0; @@ -73,23 +89,33 @@ function toNum(v: unknown): number { /** 헤더에 정렬 화살표 표시 (CSS 방식) */ function updateHeaderSortIndicator( gridView: { - columnByIndex?: (i: number) => { fieldName?: string; name?: string } | undefined; - columnByName?: (name: string) => { fieldName?: string; name?: string } | undefined; - getColumn?: (i: number) => { fieldName?: string; name?: string } | undefined; + columnByIndex?: ( + i: number, + ) => { fieldName?: string; name?: string } | undefined; + columnByName?: ( + name: string, + ) => { fieldName?: string; name?: string } | undefined; + getColumn?: ( + i: number, + ) => { fieldName?: string; name?: string } | undefined; }, columns: { fieldName?: string; name: string }[], - sortDir: Record + sortDir: Record, ) { try { columns.forEach((col) => { if (!col.fieldName && !col.name) return; - + // 컬럼 찾기 let gridCol: { fieldName?: string; name?: string } | undefined; for (let i = 0; i < 100; i++) { - const c = gridView.columnByIndex?.(i) ?? gridView.getColumn?.(i); + const c = + gridView.columnByIndex?.(i) ?? gridView.getColumn?.(i); if (!c) break; - if (c.fieldName === (col.fieldName || col.name) || c.name === (col.fieldName || col.name)) { + if ( + c.fieldName === (col.fieldName || col.name) || + c.name === (col.fieldName || col.name) + ) { gridCol = c; break; } @@ -97,42 +123,55 @@ function updateHeaderSortIndicator( if (!gridCol) { gridCol = gridView.columnByName?.(col.name); } - + if (!gridCol) return; - - const fieldName = gridCol.fieldName || gridCol.name || col.fieldName || col.name; + + const fieldName = + gridCol.fieldName || gridCol.name || col.fieldName || col.name; const direction = sortDir[fieldName] || sortDir[col.name] || "none"; - + // DOM에서 헤더 요소 찾기 - const gridEl1 = document.querySelector('[data-grid-id]') as HTMLElement | null; - const gridEl2 = document.querySelector('.rg-grid') as HTMLElement | null; + const gridEl1 = document.querySelector( + "[data-grid-id]", + ) as HTMLElement | null; + const gridEl2 = document.querySelector( + ".rg-grid", + ) as HTMLElement | null; const gridEl = gridEl1 || gridEl2; if (!gridEl) return; - + // 헤더 셀 찾기 (fieldName 또는 name으로) - const headerCells = gridEl.querySelectorAll('.rg-header-cell, [class*="header"]'); + const headerCells = gridEl.querySelectorAll( + '.rg-header-cell, [class*="header"]', + ); let targetCell: HTMLElement | null = null; - + headerCells.forEach((cell) => { const el = cell as HTMLElement; const text = el.textContent?.trim(); const colName = col.name; const colFieldName = col.fieldName; - if (text && (text.includes(colName) || (colFieldName && text.includes(colFieldName)))) { + if ( + text && + (text.includes(colName) || + (colFieldName && text.includes(colFieldName))) + ) { targetCell = el; } }); - + if (!targetCell) return; - + const headerCell = targetCell as HTMLElement; - + // 기존 화살표 제거 - const existingIndicator = headerCell.querySelector(".rg-sort-indicator") as HTMLElement | null; + const existingIndicator = headerCell.querySelector( + ".rg-sort-indicator", + ) as HTMLElement | null; if (existingIndicator) { existingIndicator.remove(); } - + // 화살표 추가 if (direction === "asc" || direction === "desc") { const indicator = document.createElement("span"); @@ -153,48 +192,84 @@ function updateHeaderSortIndicator( /** onSorting: mergeCells: true인 컬럼이 있으면 그룹 내 순서 유지 정렬, 없으면 RealGrid 기본 정렬 */ function createOnSortingHandler( - columns: { fieldName?: string; name: string; mergeCells?: boolean; sortdisable?: boolean; valueType?: ValueType }[], - setRowData: React.Dispatch[]>>, + columns: { + fieldName?: string; + name: string; + mergeCells?: boolean; + sortdisable?: boolean; + valueType?: ValueType; + }[], + setRowData: React.Dispatch< + React.SetStateAction[]> + >, sortDirRef: { current: Record }, - originalRowsRef: { current: Record[]> } + originalRowsRef: { + current: Record[]>; + }, ) { - const fieldNames = [...new Set(columns.map((c) => c.fieldName).filter((x): x is string => typeof x === "string"))]; + const fieldNames = [ + ...new Set( + columns + .map((c) => c.fieldName) + .filter((x): x is string => typeof x === "string"), + ), + ]; // mergeCells: true인 컬럼 찾기 (시군구 등) - 그룹 필드로 사용 // 시군구를 우선으로 찾고, 없으면 첫 번째 mergeCells 컬럼 사용 - const mergeCellCols = columns.filter((c) => c.mergeCells === true && c.fieldName); - const mergeCellCol = mergeCellCols.find((c) => c.fieldName === 'gugun') || mergeCellCols[0]; + const mergeCellCols = columns.filter( + (c) => c.mergeCells === true && c.fieldName, + ); + const mergeCellCol = + mergeCellCols.find((c) => c.fieldName === "gugun") || mergeCellCols[0]; const groupField = mergeCellCol?.fieldName || null; - const orderByField = 'displayYear'; // 고정값 또는 설정 가능하게 할 수 있음 + const orderByField = "displayYear"; // 고정값 또는 설정 가능하게 할 수 있음 const hasMergeCells = mergeCellCols.length > 0; - - return function onSorting(g: unknown, fields: unknown[], _directions: unknown[]) { - const grid = g as { getColumn?: (i: number) => { fieldName?: string; name?: string } | undefined; getDataSource?: () => { getRowCount(): number; getValue(r: number, f: string): unknown } }; + + return function onSorting( + g: unknown, + fields: unknown[], + _directions: unknown[], + ) { + const grid = g as { + getColumn?: ( + i: number, + ) => { fieldName?: string; name?: string } | undefined; + getDataSource?: () => { + getRowCount(): number; + getValue(r: number, f: string): unknown; + }; + }; const idx = fields?.[0]; if (idx === undefined) return true; let sortField: string | null = null; if (typeof idx === "string") sortField = idx; else { const colObj = grid?.getColumn?.(typeof idx === "number" ? idx : 0); - sortField = (colObj?.fieldName ?? colObj?.name) ?? null; + sortField = colObj?.fieldName ?? colObj?.name ?? null; } if (!sortField) return true; - const col = columns.find((c) => (c.fieldName === sortField || c.name === sortField)); + const col = columns.find( + (c) => c.fieldName === sortField || c.name === sortField, + ); if (!col || col.sortdisable) return true; - + // mergeCells: true인 컬럼이 없으면 RealGrid 기본 정렬 사용 if (!hasMergeCells || !groupField) return true; - + const ds = grid.getDataSource?.(); if (!ds) return true; const cnt = ds.getRowCount(); const rows: Record[] = []; for (let i = 0; i < cnt; i++) { const r: Record = {}; - for (const f of fieldNames) r[f] = ds.getValue(i, f) as string | number; + for (const f of fieldNames) + r[f] = ds.getValue(i, f) as string | number; rows.push(r); } const prev = sortDirRef.current[sortField] ?? "none"; - const setRows = (ds as { setRows?: (r: unknown[]) => void }).setRows?.bind(ds); + const setRows = ( + ds as { setRows?: (r: unknown[]) => void } + ).setRows?.bind(ds); if (prev === "desc") { const orig = originalRowsRef.current[sortField]; @@ -210,7 +285,13 @@ function createOnSortingHandler( } const sortAsc = prev !== "asc"; sortDirRef.current[sortField] = sortAsc ? "asc" : "desc"; - const sorted = sortRowsGroupPreserving(rows, sortField, sortAsc, { groupField, orderByField }, col.valueType); + const sorted = sortRowsGroupPreserving( + rows, + sortField, + sortAsc, + { groupField, orderByField }, + col.valueType, + ); setRows?.(sorted); setRowData(sorted); return false; @@ -223,7 +304,7 @@ function sortRowsGroupPreserving( sortField: string, sortAsc: boolean, opt: { groupField: string; orderByField?: string }, - valueType?: ValueType + valueType?: ValueType, ): Record[] { const groups = new Map[]>(); for (const r of rows) { @@ -231,7 +312,7 @@ function sortRowsGroupPreserving( if (!groups.has(k)) groups.set(k, []); groups.get(k)!.push(r); } - + // valueType에 따라 비교 함수 선택 const compareValue = (val: unknown): number | string => { if (valueType === ValueType.NUMBER) { @@ -240,22 +321,28 @@ function sortRowsGroupPreserving( // 텍스트나 기타 타입은 문자열로 비교 return String(val ?? ""); }; - + const rep = (arr: Record[]): number | string => { const values = arr.map((r) => compareValue(r[sortField])); if (valueType === ValueType.NUMBER) { - const nums = values.filter((v): v is number => typeof v === "number" && !isNaN(v)); + const nums = values.filter( + (v): v is number => typeof v === "number" && !isNaN(v), + ); if (nums.length === 0) return sortAsc ? Infinity : -Infinity; return sortAsc ? Math.min(...nums) : Math.max(...nums); } else { // 문자열 정렬 - const strs = values.filter((v): v is string => typeof v === "string"); + const strs = values.filter( + (v): v is string => typeof v === "string", + ); if (strs.length === 0) return sortAsc ? "\uffff" : ""; strs.sort(); - return sortAsc ? (strs[0] as string) : (strs[strs.length - 1] as string); + return sortAsc + ? (strs[0] as string) + : (strs[strs.length - 1] as string); } }; - + const entries = [...groups.entries()].sort((a, b) => { const valA = rep(a[1]); const valB = rep(b[1]); @@ -267,22 +354,50 @@ function sortRowsGroupPreserving( const strB = String(valB); return (sortAsc ? 1 : -1) * strA.localeCompare(strB); }); - + return entries.flatMap(([, arr]) => arr); } /** columnInfo → RealGrid DataField 배열 (computed → valueCallback 포함, setFields용) */ -function buildFieldsFromColumns(columns: { fieldName: string; valueType?: ValueType; computed?: import("../type/DataGrid.type").ComputedFieldConfig }[]) { +function buildFieldsFromColumns( + columns: { + fieldName: string; + valueType?: ValueType; + computed?: import("../type/DataGrid.type").ComputedFieldConfig; + }[], +) { return columns.map((col) => { - const field: { fieldName: string; dataType: string; valueCallback?: (prod: unknown, dataRow: number, fieldName: string, fieldNames: string[], values: unknown[]) => number } = { + const field: { + fieldName: string; + dataType: string; + valueCallback?: ( + prod: unknown, + dataRow: number, + fieldName: string, + fieldNames: string[], + values: unknown[], + ) => number; + } = { fieldName: col.fieldName, dataType: col.valueType === ValueType.NUMBER ? "number" : "text", }; if (col.computed) { - const hasFields = "fields" in col.computed && col.computed.fields.length > 0; - const hasNumeratorDenominator = "numeratorFields" in col.computed && col.computed.numeratorFields.length > 0 && col.computed.denominatorFields.length > 0; + const hasFields = + "fields" in col.computed && col.computed.fields.length > 0; + const hasNumeratorDenominator = + "numeratorFields" in col.computed && + col.computed.numeratorFields.length > 0 && + col.computed.denominatorFields.length > 0; if (hasFields || hasNumeratorDenominator) { - field.valueCallback = getComputedValueCallback(col.computed) as (prod: unknown, dataRow: number, fieldName: string, fieldNames: string[], values: unknown[]) => number; + field.valueCallback = getComputedValueCallback( + col.computed, + ) as ( + prod: unknown, + dataRow: number, + fieldName: string, + fieldNames: string[], + values: unknown[], + ) => number; } } return field; @@ -300,6 +415,7 @@ const DataGrid = ({ setRowData, getGridDataRef, cellStyleCallback, + onRowClick, }: DataGridProps) => { const { columns, columnLayout } = columnInfo; const gridRef = useRef(null); @@ -322,7 +438,7 @@ const DataGrid = ({ const exportExcel = () => { if (rowData.length === 0) { - alert('데이터가 없습니다.'); + alert("데이터가 없습니다."); return; } @@ -330,11 +446,12 @@ const DataGrid = ({ const gridView = gridRef.current.gridView; - const menuName = menuList - ?.flatMap((m) => m.children || []) - .flatMap((subM) => subM || []) - .find((s) => s.menuEngNm === activeTabId) - ?.menuKornNm || 'export'; + const menuName = + menuList + ?.flatMap((m) => m.children || []) + .flatMap((subM) => subM || []) + .find((s) => s.menuEngNm === activeTabId)?.menuKornNm || + "export"; // 엑셀 import 시 매칭을 위해 헤더에 fieldName 포함 (예: "합계 (swgeProcZoneInnerSm)") const originalHeaders: Map = new Map(); @@ -342,7 +459,7 @@ const DataGrid = ({ if (col.fieldName && gridView.columnByName) { const gridCol = gridView.columnByName(col.name); if (gridCol && gridCol.header) { - const originalText = gridCol.header.text || ''; + const originalText = gridCol.header.text || ""; originalHeaders.set(col.name, originalText); const headerWithFieldName = `${originalText} (${col.fieldName})`; gridCol.header.text = headerWithFieldName; @@ -351,26 +468,34 @@ const DataGrid = ({ }); // exportGrid 호출 전에 columnLayout 정규화 (col 속성 추가) - const normalizeLayoutForExport = (layout: ColumnLayoutItem[]): ColumnLayoutItem[] => { - return layout.map(item => { - if (typeof item === 'string') { + const normalizeLayoutForExport = ( + layout: ColumnLayoutItem[], + ): ColumnLayoutItem[] => { + return layout.map((item) => { + if (typeof item === "string") { return item; } - if (item && typeof item === 'object') { + if (item && typeof item === "object") { // { column: string, footerUserSpans?: ... } 형태인 경우 - if ('column' in item && typeof item.column === 'string') { - const colItem = item as { column: string; footerUserSpans?: unknown[] }; + if ("column" in item && typeof item.column === "string") { + const colItem = item as { + column: string; + footerUserSpans?: unknown[]; + }; // col 속성 추가 (RealGrid가 exportGrid에서 필요로 함) return { ...colItem, - col: gridView.columnByName?.(colItem.column) || null, + col: + gridView.columnByName?.(colItem.column) || null, } as ColumnLayoutItem; } // { name: string, items: ... } 형태인 경우 - if ('items' in item && Array.isArray(item.items)) { + if ("items" in item && Array.isArray(item.items)) { return { ...item, - items: normalizeLayoutForExport(item.items as ColumnLayoutItem[]), + items: normalizeLayoutForExport( + item.items as ColumnLayoutItem[], + ), }; } } @@ -384,11 +509,23 @@ const DataGrid = ({ // footerUserSpans가 있는 경우에만 정규화 const checkFooterUserSpans = (layout: ColumnLayoutItem[]): boolean => { - return layout.some(item => { - if (typeof item === 'string') return false; - if (item && typeof item === 'object' && 'footerUserSpans' in item) return true; - if (item && typeof item === 'object' && 'items' in item && Array.isArray(item.items)) { - return checkFooterUserSpans(item.items as ColumnLayoutItem[]); + return layout.some((item) => { + if (typeof item === "string") return false; + if ( + item && + typeof item === "object" && + "footerUserSpans" in item + ) + return true; + if ( + item && + typeof item === "object" && + "items" in item && + Array.isArray(item.items) + ) { + return checkFooterUserSpans( + item.items as ColumnLayoutItem[], + ); } return false; }); @@ -401,17 +538,22 @@ const DataGrid = ({ } gridView.exportGrid({ - type: 'excel', - target: 'local', + type: "excel", + target: "local", fileName: `${menuName}.xlsx`, - footer: 'hidden', + footer: "hidden", done: () => { // 헤더 원복 columns.forEach((col) => { if (col.fieldName && gridView.columnByName) { const gridCol = gridView.columnByName(col.name); - if (gridCol && gridCol.header && originalHeaders.has(col.name)) { - gridCol.header.text = originalHeaders.get(col.name) || ''; + if ( + gridCol && + gridCol.header && + originalHeaders.has(col.name) + ) { + gridCol.header.text = + originalHeaders.get(col.name) || ""; } } }); @@ -420,11 +562,13 @@ const DataGrid = ({ layoutRestored = true; setTimeout(() => { if (gridRef.current?.gridView && originalLayout) { - gridRef.current.gridView.setColumnLayout?.(originalLayout); + gridRef.current.gridView.setColumnLayout?.( + originalLayout, + ); } }, 100); } - alert('내보내기가 완료되었습니다.'); + alert("내보내기가 완료되었습니다."); }, }); }; @@ -443,21 +587,24 @@ const DataGrid = ({ try { const data = event.target?.result; if (!data) { - alert('파일을 읽을 수 없습니다.'); + alert("파일을 읽을 수 없습니다."); return; } // SheetJS로 엑셀 파일을 JSON으로 변환 - const workbook = XLSX.read(data, { type: 'array', cellDates: true }); + const workbook = XLSX.read(data, { + type: "array", + cellDates: true, + }); const firstSheetName = workbook.SheetNames[0]; - const worksheet = workbook.Sheets[firstSheetName || '']; + const worksheet = workbook.Sheets[firstSheetName || ""]; - if (!worksheet || !worksheet['!ref']) { - alert('워크시트를 읽을 수 없습니다.'); + if (!worksheet || !worksheet["!ref"]) { + alert("워크시트를 읽을 수 없습니다."); return; } - const range = XLSX.utils.decode_range(worksheet['!ref']); + const range = XLSX.utils.decode_range(worksheet["!ref"]); const headerRowCount = rowStartNum || 1; // 기본값 1 const headerStartRow = Math.max(0, headerRowCount - 1); // 0-based index @@ -466,13 +613,28 @@ const DataGrid = ({ const headerRowIndexes: number[] = []; for (let col = range.s.c; col <= range.e.c; col++) { - let headerValue = ''; + let headerValue = ""; let headerRowIndex = headerStartRow; // rowStartNum 행부터 시작해서 위로 올라가면서 헤더 찾기 - for (let rowIndex = headerStartRow; rowIndex >= 0; rowIndex--) { - const cell = worksheet[XLSX.utils.encode_cell({ r: rowIndex, c: col })]; - if (cell && cell.v !== undefined && cell.v !== null && cell.v !== '') { + for ( + let rowIndex = headerStartRow; + rowIndex >= 0; + rowIndex-- + ) { + const cell = + worksheet[ + XLSX.utils.encode_cell({ + r: rowIndex, + c: col, + }) + ]; + if ( + cell && + cell.v !== undefined && + cell.v !== null && + cell.v !== "" + ) { headerValue = String(cell.v); headerRowIndex = rowIndex; break; @@ -490,29 +652,40 @@ const DataGrid = ({ } // 실제 데이터가 시작하는 행 찾기 (헤더가 있는 최대 행 번호 + 1) - const maxHeaderRowIndex = headerRowIndexes.length > 0 ? Math.max(...headerRowIndexes) : headerStartRow; + const maxHeaderRowIndex = + headerRowIndexes.length > 0 + ? Math.max(...headerRowIndexes) + : headerStartRow; const dataStartRow = maxHeaderRowIndex + 1; // 엑셀 컬럼 인덱스 → 그리드 fieldName 매핑 const headerToFieldNameMap = new Map(); headers.forEach((headerText, colIndex) => { let fieldName: string | null = null; - + // 헤더에 fieldName이 포함된 경우 (예: "합계 (swgeProcZoneInnerSm)") - const fieldNameMatch = headerText.match(/\(([a-zA-Z_][a-zA-Z0-9_]*)\)$/); + const fieldNameMatch = headerText.match( + /\(([a-zA-Z_][a-zA-Z0-9_]*)\)$/, + ); if (fieldNameMatch && fieldNameMatch[1]) { const extractedFieldName = fieldNameMatch[1]; - if (columns.find(c => c.fieldName === extractedFieldName)) { + if ( + columns.find( + (c) => c.fieldName === extractedFieldName, + ) + ) { fieldName = extractedFieldName; } } - + // 매칭 실패 시 원본 헤더 텍스트 사용 if (!fieldName) { - console.warn(`엑셀 컬럼 ${colIndex + 1} (헤더: "${headerText}") 매칭 실패 → 헤더 텍스트를 fieldName으로 사용`); + console.warn( + `엑셀 컬럼 ${colIndex + 1} (헤더: "${headerText}") 매칭 실패 → 헤더 텍스트를 fieldName으로 사용`, + ); fieldName = headerText; } - + headerToFieldNameMap.set(headerText, fieldName); }); @@ -522,23 +695,46 @@ const DataGrid = ({ const rowData: Record = {}; let hasData = false; - for (let colIndex = 0; colIndex < headers.length; colIndex++) { + for ( + let colIndex = 0; + colIndex < headers.length; + colIndex++ + ) { const col = range.s.c + colIndex; - const cell = worksheet[XLSX.utils.encode_cell({ r: row, c: col })]; - const headerName = headers[colIndex] || `Column${colIndex + 1}`; + const cell = + worksheet[ + XLSX.utils.encode_cell({ r: row, c: col }) + ]; + const headerName = + headers[colIndex] || `Column${colIndex + 1}`; // 헤더 텍스트를 fieldName으로 변환 - const fieldName = headerToFieldNameMap.get(headerName) || headerName; + const fieldName = + headerToFieldNameMap.get(headerName) || + headerName; - let cellValue: string | number = ''; - if (cell && cell.v !== undefined && cell.v !== null) { + let cellValue: string | number = ""; + if ( + cell && + cell.v !== undefined && + cell.v !== null + ) { // 엑셀 셀 타입이 숫자이거나 값이 숫자인 경우 숫자로 변환 - if (cell.t === 'n' || (typeof cell.v === 'number' && !isNaN(cell.v))) { + if ( + cell.t === "n" || + (typeof cell.v === "number" && + !isNaN(cell.v)) + ) { cellValue = cell.v as number; } else { const stringValue = String(cell.v); // 문자열이지만 숫자로 변환 가능한 경우 숫자로 변환 - const numericValue = Number(stringValue.replace(/,/g, '')); - if (!isNaN(numericValue) && stringValue.trim() !== '') { + const numericValue = Number( + stringValue.replace(/,/g, ""), + ); + if ( + !isNaN(numericValue) && + stringValue.trim() !== "" + ) { cellValue = numericValue; } else { cellValue = stringValue; @@ -546,7 +742,11 @@ const DataGrid = ({ } } - if (cellValue !== '' && cellValue !== null && cellValue !== undefined) { + if ( + cellValue !== "" && + cellValue !== null && + cellValue !== undefined + ) { hasData = true; } @@ -560,49 +760,57 @@ const DataGrid = ({ } setRowData(dataRows); } catch (error) { - console.error('엑셀 파일 파싱 오류:', error); - alert('엑셀 파일 파싱 중 오류가 발생했습니다.'); + console.error("엑셀 파일 파싱 오류:", error); + alert("엑셀 파일 파싱 중 오류가 발생했습니다."); } finally { if (fileInputRef.current) { - fileInputRef.current.value = ''; + fileInputRef.current.value = ""; } } }; reader.onerror = () => { - alert('파일 읽기 중 오류가 발생했습니다.'); + alert("파일 읽기 중 오류가 발생했습니다."); if (fileInputRef.current) { - fileInputRef.current.value = ''; + fileInputRef.current.value = ""; } }; reader.readAsArrayBuffer(file); } catch (error) { - console.error('엑셀 파일 가져오기 오류:', error); - alert('엑셀 파일 가져오기 중 오류가 발생했습니다.'); + console.error("엑셀 파일 가져오기 오류:", error); + alert("엑셀 파일 가져오기 중 오류가 발생했습니다."); if (fileInputRef.current) { - fileInputRef.current.value = ''; + fileInputRef.current.value = ""; } } }; useEffect(() => { - if (!gridRef.current?.gridView || !gridRef.current?.dataProvider) return; + if (!gridRef.current?.gridView || !gridRef.current?.dataProvider) + return; const gridView = gridRef.current.gridView; const dataProvider = gridRef.current.dataProvider; // mergeCells: true인 컬럼이 있으면 onSorting에서 클라이언트 정렬로 처리 const hasMergeCells = columns.some((col) => col.mergeCells === true); - + // setDataComparer로 숫자 정렬 (mergeCells가 있으면 onSorting에서 클라이언트 정렬로 처리) const dp = dataProvider as RealGridDataProviderComparer; - if (typeof dp.setDataComparer === "function" && typeof dp.getValue === "function") { + if ( + typeof dp.setDataComparer === "function" && + typeof dp.getValue === "function" + ) { const numberComparer = createNumberComparer(dp); const seen = new Set(); columns.forEach((col) => { if (hasMergeCells) return; // mergeCells가 있으면 모든 컬럼을 클라이언트 정렬로 처리 - if (col.valueType === ValueType.NUMBER && col.fieldName && !seen.has(col.fieldName)) { + if ( + col.valueType === ValueType.NUMBER && + col.fieldName && + !seen.has(col.fieldName) + ) { seen.add(col.fieldName); try { dp.setDataComparer!(col.fieldName, numberComparer); @@ -614,9 +822,20 @@ const DataGrid = ({ } // mergeCells: true인 컬럼이 있으면 onSorting에서 그룹 내 순서 유지 정렬 적용 - (gridView as { onSorting?: (g: unknown, f: unknown[], d: unknown[]) => boolean }).onSorting = createOnSortingHandler(columns, setRowData, sortDirRef, originalRowsRef); + ( + gridView as { + onSorting?: (g: unknown, f: unknown[], d: unknown[]) => boolean; + } + ).onSorting = createOnSortingHandler( + columns, + setRowData, + sortDirRef, + originalRowsRef, + ); - (gridView.displayOptions as DisplayOptions).fitStyle = GridFitStyle.EVEN; + (gridView.displayOptions as DisplayOptions).fitStyle = + GridFitStyle.EVEN; + gridView.displayOptions.rowHeight = 30; gridView.header.height = 60; // 헤더 체크박스 표시 여부 설정 @@ -626,23 +845,34 @@ const DataGrid = ({ }); // footer가 있는 컬럼이 있으면 footer 높이 설정 - const hasFooter = columns.some(col => col.footer); + const hasFooter = columns.some((col) => col.footer); if (hasFooter) { // footer가 배열이거나 multiRow가 true인 footer가 있으면 멀티푸터 설정 (여러 행) - const hasArrayFooter = columns.some(col => col.footer && Array.isArray(col.footer)); - const hasMultiRowFooter = columns.some(col => { + const hasArrayFooter = columns.some( + (col) => col.footer && Array.isArray(col.footer), + ); + const hasMultiRowFooter = columns.some((col) => { const footer = col.footer; - return footer && !Array.isArray(footer) && 'multiRow' in footer && footer.multiRow === true; + return ( + footer && + !Array.isArray(footer) && + "multiRow" in footer && + footer.multiRow === true + ); }); if (hasArrayFooter || hasMultiRowFooter) { // footer 배열의 길이를 확인하여 행 수 결정 const arrayFooterLengths = columns - .filter(col => col.footer && Array.isArray(col.footer)) - .map(col => (col.footer as unknown[]).length); - const maxFooterLength = arrayFooterLengths.length > 0 - ? Math.max(...arrayFooterLengths) - : 2; // 기본값 2 - const footerHeights = Array.from({ length: maxFooterLength }, () => ({ height: 40 })); + .filter((col) => col.footer && Array.isArray(col.footer)) + .map((col) => (col.footer as unknown[]).length); + const maxFooterLength = + arrayFooterLengths.length > 0 + ? Math.max(...arrayFooterLengths) + : 2; // 기본값 2 + const footerHeights = Array.from( + { length: maxFooterLength }, + () => ({ height: 40 }), + ); gridView.setFooters?.(footerHeights); } else { gridView.footer.height = 40; @@ -657,21 +887,31 @@ const DataGrid = ({ } gridView.setOptions({ - summaryMode: "aggregate" + summaryMode: "aggregate", }); // footerUserSpans가 있는 경우 setColumnLayout으로 설정 const checkFooterUserSpans = (layout: unknown[]): boolean => { - return layout.some(item => { - if (typeof item === 'string') return false; - if (item && typeof item === 'object' && 'footerUserSpans' in item) return true; - if (item && typeof item === 'object' && 'items' in item && Array.isArray(item.items)) { + return layout.some((item) => { + if (typeof item === "string") return false; + if ( + item && + typeof item === "object" && + "footerUserSpans" in item + ) + return true; + if ( + item && + typeof item === "object" && + "items" in item && + Array.isArray(item.items) + ) { return checkFooterUserSpans(item.items); } return false; }); }; - + if (checkFooterUserSpans(columnLayout)) { // setColumnLayout은 그리드가 완전히 렌더링된 후 호출해야 함 setTimeout(() => { @@ -686,93 +926,136 @@ const DataGrid = ({ setTimeout(() => { const currentGridView = gridRef.current?.gridView; if (!currentGridView || !currentGridView.columnByName) { - console.warn('GridView not available for footer setup'); + console.warn("GridView not available for footer setup"); return; } - + // footer가 배열인 컬럼이 있으면 setColumns를 다시 호출하여 footer 설정 - const hasArrayFooter = columns.some(col => col.footer && Array.isArray(col.footer)); + const hasArrayFooter = columns.some( + (col) => col.footer && Array.isArray(col.footer), + ); if (hasArrayFooter) { // 모든 컬럼 정보를 다시 가져와서 footer 배열을 포함하여 setColumns 호출 - const columnsWithFooter: RealGridColumnInfo[] = columns.map(col => { - const colInfo: RealGridColumnInfo = { - name: col.name, - fieldName: col.fieldName, - header: col.header, - editable: col.editable, - valueType: col.valueType, - dataFormat: col.dataFormat, - ...(col.styleName != null && { styleName: col.styleName }), - ...(col.mergeCells && { mergeRule: { criteria: 'value' as const } }), - }; - - if (col.footer) { - if (Array.isArray(col.footer)) { - colInfo.footer = col.footer; - } else { - colInfo.footer = { - text: col.footer.text, - expression: col.footer.expression, - numberFormat: col.footer.numberFormat, - }; + const columnsWithFooter: RealGridColumnInfo[] = columns.map( + (col) => { + const colInfo: RealGridColumnInfo = { + name: col.name, + fieldName: col.fieldName, + header: col.header, + editable: col.editable, + valueType: col.valueType, + dataFormat: col.dataFormat, + ...(col.styleName != null && { + styleName: col.styleName, + }), + ...(col.mergeCells && { + mergeRule: { criteria: "value" as const }, + }), + }; + + if (col.footer) { + if (Array.isArray(col.footer)) { + colInfo.footer = col.footer; + } else { + colInfo.footer = { + text: col.footer.text, + expression: col.footer.expression, + numberFormat: col.footer.numberFormat, + }; + } } - } - - return colInfo; - }); - + + return colInfo; + }, + ); + try { - (currentGridView as GridViewWithSetColumns).setColumns?.(columnsWithFooter); - + (currentGridView as GridViewWithSetColumns).setColumns?.( + columnsWithFooter, + ); + // setColumns 호출 후 footer 배열의 valueCallback을 다시 설정 setTimeout(() => { - columns.forEach(col => { - if (!col.footer || !Array.isArray(col.footer)) return; - + columns.forEach((col) => { + if (!col.footer || !Array.isArray(col.footer)) + return; + try { - const column = currentGridView.columnByName(col.name); + const column = currentGridView.columnByName( + col.name, + ); if (!column) return; - + // footer 배열의 각 요소에 valueCallback 설정 col.footer.forEach((footerItem, index) => { - if (footerItem.valueCallback && column.footer) { + if ( + footerItem.valueCallback && + column.footer + ) { // footer가 배열인 경우 - if (Array.isArray(column.footer) && column.footer[index]) { - (column.footer[index] as FooterItemWithCallback).valueCallback = footerItem.valueCallback; + if ( + Array.isArray(column.footer) && + column.footer[index] + ) { + ( + column.footer[ + index + ] as FooterItemWithCallback + ).valueCallback = + footerItem.valueCallback; } } }); } catch (e) { - console.warn(`Error setting footer array valueCallback for column ${col.name}:`, e); + console.warn( + `Error setting footer array valueCallback for column ${col.name}:`, + e, + ); } }); }, 50); } catch (e) { - console.warn('Failed to set columns with footer array:', e); + console.warn("Failed to set columns with footer array:", e); } } - + // footer가 단일 객체이고 valueCallback이 있는 경우 - columns.forEach(col => { + columns.forEach((col) => { if (!col.footer || Array.isArray(col.footer)) return; - + try { const column = currentGridView.columnByName(col.name); if (!column || !column.footer) return; - + if (col.footer.valueCallback) { - (column.footer as { valueCallback?: typeof col.footer.valueCallback }).valueCallback = col.footer.valueCallback; + ( + column.footer as { + valueCallback?: typeof col.footer.valueCallback; + } + ).valueCallback = col.footer.valueCallback; } } catch (e) { - console.warn(`Error setting footer valueCallback for column ${col.name}:`, e); + console.warn( + `Error setting footer valueCallback for column ${col.name}:`, + e, + ); } }); }, 200); if (getGridDataRef) { - const fieldNames = columns.map((c) => c.fieldName).filter(Boolean) as string[]; + const fieldNames = columns + .map((c) => c.fieldName) + .filter(Boolean) as string[]; getGridDataRef.current = () => { - const gv = gridRef.current?.gridView as { getDataSource?: () => { getRowCount(): number; getValue(r: number, f: string): unknown } } | undefined; + const gv = gridRef.current?.gridView as + | { + getDataSource?: () => { + getRowCount(): number; + getValue(r: number, f: string): unknown; + }; + } + | undefined; if (!gv?.getDataSource) return []; const ds = gv.getDataSource(); if (!ds) return []; @@ -780,7 +1063,8 @@ const DataGrid = ({ const rows: Record[] = []; for (let i = 0; i < cnt; i++) { const r: Record = {}; - for (const f of fieldNames) r[f] = ds.getValue(i, f) as string | number; + for (const f of fieldNames) + r[f] = ds.getValue(i, f) as string | number; rows.push(r); } return rows; @@ -790,30 +1074,78 @@ const DataGrid = ({ return () => { if (getGridDataRef) getGridDataRef.current = null; }; - }, [columns, columnLayout, fixedColumns, rowData, showHeaderCheckbox, getGridDataRef]); + }, [ + columns, + columnLayout, + fixedColumns, + rowData, + showHeaderCheckbox, + getGridDataRef, + ]); + + // 행 클릭 이벤트 설정 + useEffect(() => { + if (!gridRef.current?.gridView || !onRowClick) return; + + const gridView = gridRef.current.gridView; + + // onCellClicked 이벤트 핸들러 설정 + gridView.onCellClicked = (grid, clickData) => { + // 데이터 셀만 처리 (헤더, 푸터 등 제외) + if ( + clickData.cellType === "data" && + clickData.itemIndex !== undefined + ) { + try { + // 행 전체 데이터 가져오기 + const row = rowData[clickData.itemIndex]; + + // 부모 컴포넌트로 데이터 전달 + onRowClick(row ?? {}); + } catch (error) { + console.error("행 데이터 가져오기 오류:", error); + } + } + }; + + // cleanup: 컴포넌트 언마운트 시 이벤트 핸들러 제거 + return () => { + if (gridView.onCellClicked) { + gridView.onCellClicked = undefined; + } + }; + }, [onRowClick]); return ( -
+
-
- {isExcelImport && - - } - {isExcelExport && - - } + )}
{ @@ -894,4 +1225,4 @@ const DataGrid = ({ ); }; -export default DataGrid; \ No newline at end of file +export default DataGrid; diff --git a/apps/st/src/components/statistics/verification/ManagementVerificationRule.tsx b/apps/st/src/components/statistics/verification/HbStatisticsVerification.tsx similarity index 99% rename from apps/st/src/components/statistics/verification/ManagementVerificationRule.tsx rename to apps/st/src/components/statistics/verification/HbStatisticsVerification.tsx index 708e2c02e..81fa83b2a 100644 --- a/apps/st/src/components/statistics/verification/ManagementVerificationRule.tsx +++ b/apps/st/src/components/statistics/verification/HbStatisticsVerification.tsx @@ -40,7 +40,7 @@ interface VerificationFormValues { }; } -const ManagementVerificationRule = () => { +const HbStatisticsVerification = () => { const [verificationHistoryRowData, setVerificationHistoryRowData] = useState[]>( verificationHistoryMockData, @@ -103,7 +103,7 @@ const ManagementVerificationRule = () => {
{/* 통계 검증 섹션 */}
-

+

통계 검증

@@ -462,8 +462,8 @@ const ManagementVerificationRule = () => {
{/* 검증 이력 섹션 */} -
-

+
+

검증 이력

{ ); }; -export default ManagementVerificationRule; +export default HbStatisticsVerification; diff --git a/apps/st/src/components/statistics/verification/VerificationArticleManagement.tsx b/apps/st/src/components/statistics/verification/VerificationArticleManagement.tsx new file mode 100644 index 000000000..321d2dca2 --- /dev/null +++ b/apps/st/src/components/statistics/verification/VerificationArticleManagement.tsx @@ -0,0 +1,261 @@ +"use client"; + +import DataGrid from "@/components/module/DataGrid"; +import { + hbArticleColumnInfo, + imrArticleColumnInfo, + validationArticleColumnInfo, +} from "@/entities/statistics/model/verification-article-column"; +import { + Button, + Input, + Label, + Tabs, + TabsContent, + TabsList, + TabsTrigger, +} from "@common/components"; +import { CodeSelect } from "@/entities/code/ui/code-select"; +import { verificationTargetManagementApi } from "@/entities/statistics/api/verification-target-management-service"; +import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; +import { useState } from "react"; +import { ENDPOINT } from "@/shared/config"; +import type { + VerificationTargetManagementSearchParams, + VerificationTargetManagementResponse, +} from "@/entities/statistics/model/verification-target-management-interface"; +import { VerificationTargetDialog } from "./VerificationTargetDialog"; +import { useConfirm } from "@frontend-opensource/use-react-hooks"; + +const TAB_CONFIG = { + HB: { value: "HB", label: "H-B", columnInfo: hbArticleColumnInfo }, + IMR: { value: "IMR", label: "I-MR", columnInfo: imrArticleColumnInfo }, + VV: { + value: "VV", + label: "Validation", + columnInfo: validationArticleColumnInfo, + }, +} as const; + +type TabValue = keyof typeof TAB_CONFIG; + +function VerificationArticleManagement() { + const queryClient = useQueryClient(); + const { confirm } = useConfirm(); + const [activeTab, setActiveTab] = useState("HB"); + const [statsCd, setStatsCd] = useState(""); + const [vrfcTrgtNm, setVrfcTrgtNm] = useState(""); + const [searchParams, setSearchParams] = + useState({ + vrfcMthdCd: activeTab, + statsCd, + vrfcTrgtNm, + }); + const [dialogOpen, setDialogOpen] = useState(false); + const [selectedData, setSelectedData] = + useState(null); + + const { data: verificationData } = useQuery({ + queryKey: [ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG, searchParams], + queryFn: async () => { + const response = + await verificationTargetManagementApi.getVerificationTargetManagementList( + { + vrfcMthdCd: searchParams.vrfcMthdCd, + statsCd: searchParams.statsCd || undefined, + vrfcTrgtNm: searchParams.vrfcTrgtNm || undefined, + }, + ); + return response; + }, + }); + + const rowData = (verificationData?.content || []) as unknown as Record< + string, + string | number + >[]; + const columnInfo = TAB_CONFIG[activeTab].columnInfo; + + function handleSearch() { + setSearchParams({ + vrfcMthdCd: activeTab, + statsCd, + vrfcTrgtNm, + }); + } + + function handleInitialize() { + setStatsCd(""); + setVrfcTrgtNm(""); + setSearchParams({ + vrfcMthdCd: activeTab, + statsCd: "", + vrfcTrgtNm: "", + }); + } + + function handleTabChange(value: string) { + const newTab = value as TabValue; + setActiveTab(newTab); + setSearchParams({ + vrfcMthdCd: newTab, + statsCd, + vrfcTrgtNm, + }); + } + + const updateMutation = useMutation({ + mutationFn: (data: VerificationTargetManagementResponse) => + verificationTargetManagementApi.updateVerificationTargetManagement( + data.vrfcTrgtSn, + { + vrfcMthdCd: data.vrfcMthdCd, + statsCd: data.statsCd, + schmNm: data.schmNm, + tblNm: data.tblNm, + colNm: data.colNm, + pkColNm: data.pkColNm, + ipcrCntVl: data.ipcrCntVl, + pctlCrtrVl: data.pctlCrtrVl, + scopCntCntVl: data.scopCntCntVl, + thrsCntVl: data.thrsCntVl, + useYn: data.useYn, + vrfcTrgtNm: data.vrfcTrgtNm, + }, + ), + onSuccess: () => { + queryClient.invalidateQueries({ + queryKey: [ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG], + }); + setDialogOpen(false); + }, + }); + + const deleteMutation = useMutation({ + mutationFn: (vrfcTrgtSn: number) => + verificationTargetManagementApi.deleteVerificationTargetManagement( + vrfcTrgtSn, + ), + onSuccess: () => { + queryClient.invalidateQueries({ + queryKey: [ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG], + }); + setDialogOpen(false); + }, + }); + + function handleRowClick(rowData: Record) { + setSelectedData( + rowData as unknown as VerificationTargetManagementResponse, + ); + setDialogOpen(true); + } + + function handleSubmit(e: React.FormEvent) { + e.preventDefault(); + handleSearch(); + } + + async function handleSave(data: VerificationTargetManagementResponse) { + if (await confirm("저장하시겠습니까?")) { + updateMutation.mutate(data); + } + } + + async function handleDelete(vrfcTrgtSn: number) { + if (await confirm("정말 삭제하시겠습니까?")) { + deleteMutation.mutate(vrfcTrgtSn); + } + } + + return ( + + + {Object.entries(TAB_CONFIG).map(([key, config]) => ( + + {config.label} + + ))} + + +
+
+
+
+ + +
+ +
+ + setVrfcTrgtNm(e.target.value)} + placeholder="검증명" + className="w-[20rem]" + /> +
+ +
+ + +
+
+
+
+ + {Object.entries(TAB_CONFIG).map(([key, config]) => ( + + {}} + onRowClick={handleRowClick} + isExcelImport={false} + /> + + ))} + + +
+ ); +} + +export default VerificationArticleManagement; diff --git a/apps/st/src/components/statistics/verification/VerificationTargetDialog.tsx b/apps/st/src/components/statistics/verification/VerificationTargetDialog.tsx new file mode 100644 index 000000000..29e1607d3 --- /dev/null +++ b/apps/st/src/components/statistics/verification/VerificationTargetDialog.tsx @@ -0,0 +1,380 @@ +"use client"; + +import { + Button, + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, + Input, + Table, + TableBody, + TableCell, + TableHead, + TableRow, +} from "@common/components"; +import { CodeSelect } from "@/entities/code/ui/code-select"; +import type { VerificationTargetManagementResponse } from "@/entities/statistics/model/verification-target-management-interface"; +import { + verificationTargetManagementSchema, + type VerificationTargetManagementFormData, +} from "@/entities/statistics/model/verification-target-management-schema"; +import { useEffect } from "react"; +import { useForm, Controller } from "react-hook-form"; +import { zodResolver } from "@hookform/resolvers/zod"; + +interface VerificationTargetDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + data: VerificationTargetManagementResponse | null; + onSave: (data: VerificationTargetManagementResponse) => void; + onDelete: (vrfcTrgtSn: number) => void; +} + +export function VerificationTargetDialog({ + open, + onOpenChange, + data, + onSave, + onDelete, +}: VerificationTargetDialogProps) { + const { + control, + handleSubmit, + reset, + formState: { errors }, + } = useForm({ + resolver: zodResolver(verificationTargetManagementSchema), + defaultValues: data || undefined, + }); + + useEffect(() => { + if (data && open) reset(data); + }, [data, open]); + + function onSubmit(formData: VerificationTargetManagementFormData) { + if (!data) return; + onSave({ + ...data, + ...formData, + } as VerificationTargetManagementResponse); + } + + function handleDelete() { + if (data?.vrfcTrgtSn) { + onDelete(data.vrfcTrgtSn); + } + } + + if (!data) return null; + + return ( + + + + 검증 항목 상세 + + +
+ + + + + 통계항목 + + + ( +
+ + {errors.statsCd && ( +

+ {errors.statsCd.message} +

+ )} +
+ )} + /> +
+ + 검증명 + + + ( + + )} + /> + +
+ + + + 스키마명 + + + ( +
+ + {errors.schmNm && ( +

+ {errors.schmNm.message} +

+ )} +
+ )} + /> +
+ + 테이블명 + + + ( +
+ + {errors.tblNm && ( +

+ {errors.tblNm.message} +

+ )} +
+ )} + /> +
+
+ + + + 컬럼명 + + + ( +
+ + {errors.colNm && ( +

+ {errors.colNm.message} +

+ )} +
+ )} + /> +
+ + PK 키 + + + ( +
+ + {errors.pkColNm && ( +

+ {errors.pkColNm.message} +

+ )} +
+ )} + /> +
+
+ + + + 중요도 계수(μ) + + + ( +
+ + field.onChange( + e.target.value + ? Number( + e.target + .value, + ) + : null, + ) + } + placeholder="(0 ~ 1)" + /> +
+ )} + /> +
+ + 백분위수 기준값(pct) + + + ( +
+ + field.onChange( + e.target.value + ? Number( + e.target + .value, + ) + : null, + ) + } + placeholder="(0 ~ 0.5)" + /> +
+ )} + /> +
+
+ + + + 스케일 조정 계수(A) + + + ( + + field.onChange( + e.target.value + ? Number( + e.target + .value, + ) + : null, + ) + } + /> + )} + /> + + + 임계 계수(c) + + + ( + + field.onChange( + e.target.value + ? Number( + e.target + .value, + ) + : null, + ) + } + /> + )} + /> + + +
+
+ + + + + + +
+
+
+ ); +} diff --git a/apps/st/src/components/type/DataGrid.type.ts b/apps/st/src/components/type/DataGrid.type.ts index 634512d58..59948afb8 100644 --- a/apps/st/src/components/type/DataGrid.type.ts +++ b/apps/st/src/components/type/DataGrid.type.ts @@ -11,28 +11,55 @@ export type RealGridColumnInfo = { valueType?: import("realgrid").ValueType; dataFormat?: string; styleName?: string; - mergeRule?: { criteria: 'value' }; - footer?: { + mergeRule?: { criteria: "value" }; + footer?: + | { text?: string; - expression?: 'sum' | 'avg' | 'count' | 'max' | 'min'; + expression?: "sum" | "avg" | "count" | "max" | "min"; numberFormat?: string; - valueCallback?: (grid: GridView, column: DataColumn, footerIndex: number, columnFooter: ColumnFooter, value: number | string | undefined) => number | string; - } | Array<{ + valueCallback?: ( + grid: GridView, + column: DataColumn, + footerIndex: number, + columnFooter: ColumnFooter, + value: number | string | undefined, + ) => number | string; + } + | Array<{ text?: string; - expression?: 'sum' | 'avg' | 'count' | 'max' | 'min'; + expression?: "sum" | "avg" | "count" | "max" | "min"; numberFormat?: string; - valueCallback?: (grid: GridView, column: DataColumn, footerIndex: number, columnFooter: ColumnFooter, value: number | string | undefined) => number | string; + valueCallback?: ( + grid: GridView, + column: DataColumn, + footerIndex: number, + columnFooter: ColumnFooter, + value: number | string | undefined, + ) => number | string; }>; }; /** setColumns 메서드가 있는 GridView */ -export type GridViewWithSetColumns = GridView & { setColumns?: (columns: RealGridColumnInfo[]) => void }; +export type GridViewWithSetColumns = GridView & { + setColumns?: (columns: RealGridColumnInfo[]) => void; +}; /** footer 배열 요소에 valueCallback 할당용 */ -export type FooterItemWithCallback = { valueCallback?: (grid: GridView, column: DataColumn, footerIndex: number, columnFooter: ColumnFooter, value: number | string | undefined) => number | string }; +export type FooterItemWithCallback = { + valueCallback?: ( + grid: GridView, + column: DataColumn, + footerIndex: number, + columnFooter: ColumnFooter, + value: number | string | undefined, + ) => number | string; +}; export type GridView = { - getSummary(field: string, summary: 'sum' | 'avg' | 'count' | 'max' | 'min'): number | undefined; + getSummary( + field: string, + summary: "sum" | "avg" | "count" | "max" | "min", + ): number | undefined; getDataSource(): { getRowCount(): number; getValue(rowIndex: number, field: string): number | string; @@ -41,7 +68,12 @@ export type GridView = { getDataRow(itemIndex: number): number; }; -export type MergeCallback = (grid: GridView, column: DataColumn, itemIndex: number, value: number | string | null | undefined) => number | null; +export type MergeCallback = ( + grid: GridView, + column: DataColumn, + itemIndex: number, + value: number | string | null | undefined, +) => number | null; export type DataColumn = { name: string; @@ -66,15 +98,28 @@ export type DataFieldValueCallback = ( dataRow: number, fieldName: string, fieldNames: string[], - values: unknown[] + values: unknown[], ) => number | string | undefined; /** 계산 필드 설정 (computedFieldCallbacks.ts 참고) */ export type ComputedFieldConfig = | { fields: string[]; type: "sum" | "avg" } - | { numeratorFields: string[]; denominatorFields: string[]; type: "pblswrgPopltnSuprtRate" } - | { numeratorFields: string[]; denominatorFields: string[]; type: "adtrtPopltnSuprtRate" } - | { numeratorFields: string[]; denominatorFields: string[]; thirdFields: string[], type: "swrgInstlrtRate" }; + | { + numeratorFields: string[]; + denominatorFields: string[]; + type: "pblswrgPopltnSuprtRate"; + } + | { + numeratorFields: string[]; + denominatorFields: string[]; + type: "adtrtPopltnSuprtRate"; + } + | { + numeratorFields: string[]; + denominatorFields: string[]; + thirdFields: string[]; + type: "swrgInstlrtRate"; + }; export type ColumnConfig = { name: string; @@ -92,18 +137,32 @@ export type ColumnConfig = { sortPreserveGroupOrder?: SortPreserveGroupOrder; valueType?: ValueType; dataFormat?: string; - footer?: { + footer?: + | { text?: string; - expression?: 'sum' | 'avg' | 'count' | 'max' | 'min'; + expression?: "sum" | "avg" | "count" | "max" | "min"; numberFormat?: string; - valueCallback?: (grid: GridView, column: DataColumn, footerIndex: number, columnFooter: ColumnFooter, value: number | string | undefined) => number | string; + valueCallback?: ( + grid: GridView, + column: DataColumn, + footerIndex: number, + columnFooter: ColumnFooter, + value: number | string | undefined, + ) => number | string; multiRow?: boolean; // 여러 행 footer 사용 여부 - } | Array<{ + } + | Array<{ text?: string; - expression?: 'sum' | 'avg' | 'count' | 'max' | 'min'; + expression?: "sum" | "avg" | "count" | "max" | "min"; numberFormat?: string; - valueCallback?: (grid: GridView, column: DataColumn, footerIndex: number, columnFooter: ColumnFooter, value: number | string | undefined) => number | string; - }>, // RealGrid에서 footer를 배열로 설정할 수 있음 + valueCallback?: ( + grid: GridView, + column: DataColumn, + footerIndex: number, + columnFooter: ColumnFooter, + value: number | string | undefined, + ) => number | string; + }>; // RealGrid에서 footer를 배열로 설정할 수 있음 }; export type FooterUserSpan = { @@ -112,16 +171,19 @@ export type FooterUserSpan = { text?: string; // 표시할 텍스트 }; -export type ColumnLayoutItem = string | { - name: string; - hideChildHeaders?: boolean; - header: { text: string }; - items: (string | ColumnLayoutItem)[]; - footerUserSpans?: FooterUserSpan[]; // footer 병합 설정 -} | { - column: string; // 컬럼 이름 (footerUserSpans 사용 시) - footerUserSpans?: FooterUserSpan[]; // footer 병합 설정 -}; +export type ColumnLayoutItem = + | string + | { + name: string; + hideChildHeaders?: boolean; + header: { text: string }; + items: (string | ColumnLayoutItem)[]; + footerUserSpans?: FooterUserSpan[]; // footer 병합 설정 + } + | { + column: string; // 컬럼 이름 (footerUserSpans 사용 시) + footerUserSpans?: FooterUserSpan[]; // footer 병합 설정 + }; export type ColumnInfo = { columns: ColumnConfig[]; @@ -138,7 +200,7 @@ export type ColumnInfoList = { isSplitGrid?: boolean; // 5:5 분리형 그리드 유무 left?: ColumnInfoList; // SplitDataGrid용 왼쪽 그리드 정보 right?: ColumnInfoList; // SplitDataGrid용 오른쪽 그리드 정보 -} +}; // 개별 셀 스타일을 동적으로 결정하기 위한 콜백 (예: 검증 오류 셀 강조) export type CellStyleCallbackParams = { @@ -158,11 +220,16 @@ export type DataGridProps = { fixedColumns?: number; // 고정할 컬럼 개수 (좌측부터) showHeaderCheckbox?: boolean; // 헤더 체크박스 표시 여부 (기본값: true) rowData: Record[]; - setRowData: React.Dispatch[]>>; - /** 저장 등 시점에 그리드 현재 데이터를 가져올 수 있도록 할당 (편집 반영된 값) */ - getGridDataRef?: { current: (() => Record[]) | null }; + setRowData: React.Dispatch< + React.SetStateAction[]> + >; /** 셀 단위로 styleName을 동적으로 결정 (예: 검증 오류 셀) */ cellStyleCallback?: CellStyleCallback; + /** 저장 등 시점에 그리드 현재 데이터를 가져올 수 있도록 할당 (편집 반영된 값) */ + getGridDataRef?: { + current: (() => Record[]) | null; + }; + onRowClick?: (rowData: Record) => void; // 행 클릭 이벤트 }; export type TabDataGridProps = { @@ -173,7 +240,9 @@ export type TabDataGridProps = { onRowsChange?: (rows: Record[]) => void; showHeaderCheckbox?: boolean; // 헤더 체크박스 표시 여부 (기본값: true) rowDataMap: Map[]>; - setRowDataMap: React.Dispatch[]>>>; + setRowDataMap: React.Dispatch< + React.SetStateAction[]>> + >; isSplitGrid?: boolean; // 5:5 분리형 그리드 유무 /** 활성 탭 키 (제어 모드). 부모에서 넘기면 해당 탭이 선택됨 */ activeTab?: string; @@ -189,6 +258,10 @@ export type SplitDataGridProps = { showHeaderCheckbox?: boolean; leftRowData: Record[]; rightRowData: Record[]; - setLeftRowData: React.Dispatch[]>>; - setRightRowData: React.Dispatch[]>>; -}; \ No newline at end of file + setLeftRowData: React.Dispatch< + React.SetStateAction[]> + >; + setRightRowData: React.Dispatch< + React.SetStateAction[]> + >; +}; diff --git a/apps/st/src/entities/statistics/api/verification-target-management-service.ts b/apps/st/src/entities/statistics/api/verification-target-management-service.ts new file mode 100644 index 000000000..5bbcd714c --- /dev/null +++ b/apps/st/src/entities/statistics/api/verification-target-management-service.ts @@ -0,0 +1,95 @@ +import { client } from "@/shared/api"; +import { ENDPOINT } from "@/shared/config"; + +import type { + VerificationTargetManagementService, + VerificationTargetManagementSearchParams, + VerificationTargetManagementListApiResponse, + VerificationTargetManagementDetailApiResponse, + VerificationTargetManagementSaveRequest, + VerificationTargetManagementSaveApiResponse, + VerificationTargetManagementUpdateRequest, + VerificationTargetManagementUpdateApiResponse, + VerificationTargetManagementDeleteApiResponse, +} from "../model/verification-target-management-interface"; + +export class VerificationTargetManagementApiService implements VerificationTargetManagementService { + /** + * 검증 대상 목록 조회 + * @param params 검색 조건 (vrfcMthdCd, statsCd, tblNm, colNm, vrfcTrgtNm, useYn, page, size, sort) + */ + public async getVerificationTargetManagementList( + params: VerificationTargetManagementSearchParams, + ): Promise { + const response = + await client.get( + `${ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG}`, + { params }, + ); + return response.data; + } + + /** + * 검증 대상 상세 조회 + * @param vrfcTrgtSn 검증 대상 일련번호 + */ + public async getVerificationTargetManagementById( + vrfcTrgtSn: number, + ): Promise { + const response = + await client.get( + `${ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG}/${vrfcTrgtSn}`, + ); + return response.data; + } + + /** + * 검증 대상 등록 + * @param request 등록 요청 데이터 + */ + public async saveVerificationTargetManagement( + request: VerificationTargetManagementSaveRequest, + ): Promise { + const response = + await client.post( + `${ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG}`, + request, + ); + return response.data; + } + + /** + * 검증 대상 수정 + * @param vrfcTrgtSn 검증 대상 일련번호 + * @param request 수정 요청 데이터 + */ + public async updateVerificationTargetManagement( + vrfcTrgtSn: number, + request: VerificationTargetManagementUpdateRequest, + ): Promise { + const response = + await client.put( + `${ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG}/${vrfcTrgtSn}`, + request, + ); + return response.data; + } + + /** + * 검증 대상 삭제 + * @param vrfcTrgtSn 검증 대상 일련번호 + */ + public async deleteVerificationTargetManagement( + vrfcTrgtSn: number, + ): Promise { + const response = + await client.delete( + `${ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG}/${vrfcTrgtSn}`, + ); + return response.data; + } +} + +// 통합 인스턴스 수출 +export const verificationTargetManagementApi = + new VerificationTargetManagementApiService(); diff --git a/apps/st/src/entities/statistics/model/verification-article-column.ts b/apps/st/src/entities/statistics/model/verification-article-column.ts new file mode 100644 index 000000000..b1ba02d4a --- /dev/null +++ b/apps/st/src/entities/statistics/model/verification-article-column.ts @@ -0,0 +1,200 @@ +import { ValueType } from "realgrid"; +import type { ColumnInfo } from "@rsone/components"; + +export const hbArticleColumnInfo: ColumnInfo = { + columns: [ + { + name: "statsNm", + fieldName: "statsNm", + header: { text: "통계항목" }, + editable: false, + sortdisable: false, + }, + { + name: "vrfcTrgtNm", + fieldName: "vrfcTrgtNm", + header: { text: "검증명" }, + editable: false, + sortdisable: false, + }, + { + name: "tblNm", + fieldName: "tblNm", + header: { text: "테이블명" }, + editable: false, + sortdisable: false, + }, + { + name: "colNm", + fieldName: "colNm", + header: { text: "컬럼명" }, + editable: false, + sortdisable: false, + }, + { + name: "pctlCrtrVl", + fieldName: "pctlCrtrVl", + header: { text: "Percentile" }, + editable: false, + sortdisable: false, + valueType: ValueType.NUMBER, + dataFormat: "#,##0.##", + }, + { + name: "scopCntCntVl", + fieldName: "scopCntCntVl", + header: { text: "A" }, + editable: false, + sortdisable: false, + valueType: ValueType.NUMBER, + dataFormat: "#,##0.###", + }, + { + name: "thrsCntVl", + fieldName: "thrsCntVl", + header: { text: "C" }, + editable: false, + sortdisable: false, + valueType: ValueType.NUMBER, + dataFormat: "#,##0.###", + }, + { + name: "rgtrNm", + fieldName: "rgtrNm", + header: { text: "등록자" }, + editable: false, + sortdisable: false, + }, + { + name: "regDt", + fieldName: "regDt", + header: { text: "등록일시" }, + editable: false, + sortdisable: false, + }, + ], + columnLayout: [ + "statsNm", + "vrfcTrgtNm", + "tblNm", + "colNm", + "pctlCrtrVl", + "scopCntCntVl", + "thrsCntVl", + "rgtrNm", + "regDt", + ], +}; + +export const imrArticleColumnInfo: ColumnInfo = { + columns: [ + { + name: "statsNm", + fieldName: "statsNm", + header: { text: "통계항목" }, + editable: false, + sortdisable: false, + }, + { + name: "vrfcTrgtNm", + fieldName: "vrfcTrgtNm", + header: { text: "검증명" }, + editable: false, + sortdisable: false, + }, + { + name: "tblNm", + fieldName: "tblNm", + header: { text: "테이블명" }, + editable: false, + sortdisable: false, + }, + { + name: "colNm", + fieldName: "colNm", + header: { text: "컬럼명" }, + editable: false, + sortdisable: false, + }, + { + name: "ipcrCntVl", + fieldName: "ipcrCntVl", + header: { text: "μ" }, + editable: false, + sortdisable: false, + valueType: ValueType.NUMBER, + dataFormat: "#,##0.###", + }, + { + name: "rgtrNm", + fieldName: "rgtrNm", + header: { text: "등록자" }, + editable: false, + sortdisable: false, + }, + { + name: "regDt", + fieldName: "regDt", + header: { text: "등록일시" }, + editable: false, + sortdisable: false, + }, + ], + columnLayout: [ + "statsNm", + "vrfcTrgtNm", + "tblNm", + "colNm", + "ipcrCntVl", + "rgtrNm", + "regDt", + ], +}; + +export const validationArticleColumnInfo: ColumnInfo = { + columns: [ + { + name: "statsNm", + fieldName: "statsNm", + header: { text: "통계항목" }, + editable: false, + sortdisable: false, + }, + { + name: "vrfcTrgtNm", + fieldName: "vrfcTrgtNm", + header: { text: "검증명" }, + editable: false, + sortdisable: false, + }, + { + name: "tblNm", + fieldName: "tblNm", + header: { text: "테이블명" }, + editable: false, + sortdisable: false, + }, + { + name: "colNm", + fieldName: "colNm", + header: { text: "컬럼명" }, + editable: false, + sortdisable: false, + }, + { + name: "rgtrNm", + fieldName: "rgtrNm", + header: { text: "등록자" }, + editable: false, + sortdisable: false, + }, + { + name: "regDt", + fieldName: "regDt", + header: { text: "등록일시" }, + editable: false, + sortdisable: false, + }, + ], + columnLayout: ["statsNm", "vrfcTrgtNm", "tblNm", "colNm", "rgtrNm", "regDt"], +}; diff --git a/apps/st/src/entities/statistics/model/verification-article-interface.ts b/apps/st/src/entities/statistics/model/verification-article-interface.ts new file mode 100644 index 000000000..98b2d5274 --- /dev/null +++ b/apps/st/src/entities/statistics/model/verification-article-interface.ts @@ -0,0 +1,57 @@ +/** H-B 탭 검증 항목 */ +export interface HBArticleItem { + /** 통계 항목명 */ + statsItmNm: string; + /** 검증 항목명 */ + vrfcItmNm: string; + /** 테이블명 */ + tblNm: string; + /** 컬럼명 */ + colNm: string; + /** Percentile 값 */ + percentileVal: number; + /** A 값 */ + aVal: number; + /** C 값 */ + cVal: number; + /** 등록자명 */ + regNm: string; + /** 등록 일시 */ + regDt: string; +} + +/** I-MR 탭 검증 항목 */ +export interface IMRArticleItem { + /** 통계 항목명 */ + statsItmNm: string; + /** 검증명 */ + vrfcNm: string; + /** 테이블명 */ + tblNm: string; + /** 컬럼명 */ + colNm: string; + /** 등록자명 */ + regNm: string; + /** 등록 일시 */ + regDt: string; +} + +/** Validation 탭 검증 항목 */ +export interface ValidationArticleItem { + /** 순번 */ + no: string; + /** 통계항목명 */ + statsItmNm: string; + /** 검증명 */ + vrfcNm: string; + /** 테이블명 */ + tblNm: string; + /** 컬럼명 */ + colNm: string; + /** 비교 테이블명 */ + cmpTblNm: string; + /** 비교 컬럼명 */ + cmpColNm: string; + /** 기본규칙 */ + bscRul: string; +} diff --git a/apps/st/src/entities/statistics/model/verification-article-mock.ts b/apps/st/src/entities/statistics/model/verification-article-mock.ts new file mode 100644 index 000000000..272efeb16 --- /dev/null +++ b/apps/st/src/entities/statistics/model/verification-article-mock.ts @@ -0,0 +1,150 @@ +import { fakerKO as faker } from "@faker-js/faker"; +import type { + HBArticleItem, + IMRArticleItem, + ValidationArticleItem, +} from "./verification-article-interface"; + +const HB_STATS_ITEMS = [ + "하수도 보급률", + "하수관로", + "하수처리시설 및 방류량보고", + "펌프장", + "공공하수처리시설", + "분뇨처리시설", + "개인하수처리시설", + "하수도재정", + "물 재이용", +]; + +const HB_VERIFICATION_ITEMS = [ + "행정구역 보급률", + "유역환경청별 보급률", + "관로연장", + "처리용량", + "방류량", + "펌프용량", +]; + +const IMR_STATS_ITEMS = [ + "하수도 보급률", + "하수관로", + "하수처리시설 및 방류량보고", + "펌프장", + "공공하수처리시설", + "분뇨처리시설", + "개인하수처리시설", + "하수도재정", + "물 재이용", +]; + +const VALIDATION_STATS_ITEMS = [ + "하수관로 유지관리", + "하수저류시설 및 빗물펌프장", + "공공하수처리시설", + "분뇨처리시설", + "개인하수처리시설", + "하수도재정", +]; + +const VERIFICATION_NAMES = [ + "제정별 사업비", + "관로길이", + "공란검증", + "범위검증", + "논리검증", + "유지보수", +]; + +const TABLE_NAMES = [ + "tb_stats_drng_sys", + "tb_stats_ppline", + "tb_stats_fclt", + "tb_stats_pump_stt", + "tb_stats_sewg_trtm", +]; + +const COLUMN_NAMES = [ + "drng_sys_rate", + "ppline_len", + "fclt_cpct", + "pump_cpct", + "trtm_qty", + "popl_cnt", +]; + +const BASIC_RULES = [ + "값 > 0", + "값 >= 0", + "값 != NULL", + "범위: 0-100", + "A > B", +]; + +function formatDateTime(date: Date): string { + const y = date.getFullYear(); + const m = String(date.getMonth() + 1).padStart(2, "0"); + const d = String(date.getDate()).padStart(2, "0"); + const h = String(date.getHours()).padStart(2, "0"); + const min = String(date.getMinutes()).padStart(2, "0"); + return `${y}-${m}-${d} ${h}:${min}`; +} + +/** H-B 탭 목데이터 생성 */ +export function createHBArticleMock(count = 10): HBArticleItem[] { + faker.seed(100); + return Array.from({ length: count }, (_, index) => ({ + statsItmNm: faker.helpers.arrayElement(HB_STATS_ITEMS), + vrfcItmNm: faker.helpers.arrayElement(HB_VERIFICATION_ITEMS), + tblNm: faker.helpers.arrayElement(TABLE_NAMES), + colNm: faker.helpers.arrayElement(COLUMN_NAMES), + percentileVal: faker.number.float({ + min: 0, + max: 100, + fractionDigits: 2, + }), + aVal: faker.number.float({ min: 0, max: 10, fractionDigits: 3 }), + cVal: faker.number.float({ min: 0, max: 10, fractionDigits: 3 }), + regNm: faker.person.fullName(), + regDt: formatDateTime(faker.date.recent({ days: 90 })), + })); +} + +/** I-MR 탭 목데이터 생성 */ +export function createIMRArticleMock(count = 10): IMRArticleItem[] { + faker.seed(200); + return Array.from({ length: count }, (_, index) => ({ + statsItmNm: faker.helpers.arrayElement(IMR_STATS_ITEMS), + vrfcNm: faker.helpers.arrayElement(VERIFICATION_NAMES), + tblNm: faker.helpers.arrayElement(TABLE_NAMES), + colNm: faker.helpers.arrayElement(COLUMN_NAMES), + regNm: faker.person.fullName(), + regDt: formatDateTime(faker.date.recent({ days: 90 })), + })); +} + +/** Validation 탭 목데이터 생성 */ +export function createValidationArticleMock( + count = 6, +): ValidationArticleItem[] { + faker.seed(300); + return Array.from({ length: count }, (_, index) => ({ + no: `${index + 1}`, + statsItmNm: faker.helpers.arrayElement(VALIDATION_STATS_ITEMS), + vrfcNm: faker.helpers.arrayElement(VERIFICATION_NAMES), + tblNm: faker.helpers.arrayElement(TABLE_NAMES), + colNm: faker.helpers.arrayElement(COLUMN_NAMES), + cmpTblNm: faker.helpers.arrayElement(TABLE_NAMES), + cmpColNm: faker.helpers.arrayElement(COLUMN_NAMES), + bscRul: faker.helpers.arrayElement(BASIC_RULES), + })); +} + +/** H-B 탭 기본 목데이터 */ +export const hbArticleMockData = createHBArticleMock(10); + +/** I-MR 탭 기본 목데이터 */ +export const imrArticleMockData = createIMRArticleMock(10); + +/** Validation 탭 기본 목데이터 */ +export const validationArticleMockData = createValidationArticleMock(6); diff --git a/apps/st/src/entities/statistics/model/verification-target-management-interface.ts b/apps/st/src/entities/statistics/model/verification-target-management-interface.ts new file mode 100644 index 000000000..08d771256 --- /dev/null +++ b/apps/st/src/entities/statistics/model/verification-target-management-interface.ts @@ -0,0 +1,105 @@ +import type { PageableList } from "@/shared/model"; +import type { ApiResponse } from "./statistics-interface"; + +// 검증 대상 관리 응답 DTO +export interface VerificationTargetManagementResponse { + vrfcTrgtSn: number; // 검증 대상 일련번호 + vrfcMthdCd: string; // 검증 방법 코드 + vrfcMthdNm: string; // 검증 방법 명 + statsCd: string; // 통계 코드 + statsNm: string; // 통계 항목 명 + schmNm: string; // 스키마 명 + tblNm: string; // 테이블 명 + colNm: string; // 컬럼 명 + pkColNm: string; // pk 컬럼 명 + ipcrCntVl: number | null; // 중요도 계수 값 (mu) + pctlCrtrVl: number | null; // 백분위 기준 값 (percentile) + scopCntCntVl: number | null; // 범위 조정 계수 값 (A) + thrsCntVl: number | null; // 임계 계수 값 (C) + useYn: string; // 사용 여부 + vrfcTrgtNm: string; // 검증대상명 + rgtr: string | null; // 등록자 ID + regDt: string | null; // 등록 일시 + mdfr: string | null; // 수정자 ID + rgtrNm: string | null; // 등록자명 + mdfrNm: string | null; // 수정자명 + mdfcn: string | null; // 수정 일시 +} + +// 검증 대상 관리 검색 DTO +export interface VerificationTargetManagementSearchParams { + vrfcMthdCd?: string; // 검증 방법 코드 + statsCd?: string; // 통계 코드 + tblNm?: string; // 테이블 명 + colNm?: string; // 컬럼 명 + vrfcTrgtNm?: string; // 검증대상명 + useYn?: string; // 사용 여부 + page?: number; // 페이지 번호 (0부터 시작) + size?: number; // 페이지 크기 + sort?: string; // 정렬 조건 (예: "vrfcTrgtSn,desc") +} + +// 검증 대상 관리 저장 요청 DTO +export interface VerificationTargetManagementSaveRequest { + vrfcMthdCd: string; // 검증 방법 코드 (필수, 최대 10자) + statsCd: string; // 통계 코드 (필수, 최대 10자) + schmNm: string; // 스키마 명 (필수, 최대 150자) + tblNm: string; // 테이블 명 (필수, 최대 150자) + colNm: string; // 컬럼 명 (필수, 최대 150자) + pkColNm: string; // pk 컬럼 명 (필수, 최대 150자) + ipcrCntVl?: number | null; // 중요도 계수 값 (mu) + pctlCrtrVl?: number | null; // 백분위 기준 값 (percentile) + scopCntCntVl?: number | null; // 범위 조정 계수 값 (A) + thrsCntVl?: number | null; // 임계 계수 값 (C) + useYn?: string; // 사용 여부 (Y/N, 최대 1자) + vrfcTrgtNm?: string; // 검증대상명 (최대 150자) +} + +// 검증 대상 관리 수정 요청 DTO +export interface VerificationTargetManagementUpdateRequest { + vrfcMthdCd: string; // 검증 방법 코드 (필수, 최대 10자) + statsCd: string; // 통계 코드 (필수, 최대 10자) + schmNm: string; // 스키마 명 (필수, 최대 150자) + tblNm: string; // 테이블 명 (필수, 최대 150자) + colNm: string; // 컬럼 명 (필수, 최대 150자) + pkColNm: string; // pk 컬럼 명 (필수, 최대 150자) + ipcrCntVl?: number | null; // 중요도 계수 값 (mu) + pctlCrtrVl?: number | null; // 백분위 기준 값 (percentile) + scopCntCntVl?: number | null; // 범위 조정 계수 값 (A) + thrsCntVl?: number | null; // 임계 계수 값 (C) + useYn?: string; // 사용 여부 (Y/N, 최대 1자) + vrfcTrgtNm?: string; // 검증대상명 (최대 150자) +} + +// API 응답 타입 +export type VerificationTargetManagementListApiResponse = + PageableList; +export type VerificationTargetManagementDetailApiResponse = + ApiResponse; +export type VerificationTargetManagementSaveApiResponse = ApiResponse; +export type VerificationTargetManagementUpdateApiResponse = ApiResponse; +export type VerificationTargetManagementDeleteApiResponse = ApiResponse; + +// 서비스 인터페이스 +export interface VerificationTargetManagementService { + getVerificationTargetManagementList( + params: VerificationTargetManagementSearchParams, + ): Promise; + + getVerificationTargetManagementById( + vrfcTrgtSn: number, + ): Promise; + + saveVerificationTargetManagement( + request: VerificationTargetManagementSaveRequest, + ): Promise; + + updateVerificationTargetManagement( + vrfcTrgtSn: number, + request: VerificationTargetManagementUpdateRequest, + ): Promise; + + deleteVerificationTargetManagement( + vrfcTrgtSn: number, + ): Promise; +} diff --git a/apps/st/src/entities/statistics/model/verification-target-management-schema.ts b/apps/st/src/entities/statistics/model/verification-target-management-schema.ts new file mode 100644 index 000000000..821e860f8 --- /dev/null +++ b/apps/st/src/entities/statistics/model/verification-target-management-schema.ts @@ -0,0 +1,29 @@ +import { z } from "zod"; + +export const verificationTargetManagementSchema = z.object({ + vrfcTrgtSn: z.number().optional(), + vrfcMthdCd: z.string().optional(), + vrfcMthdNm: z.string().optional().nullable(), + statsCd: z.string().min(1, "통계항목을 선택해주세요"), + statsNm: z.string().optional().nullable(), + schmNm: z.string().min(1, "스키마명을 입력해주세요"), + tblNm: z.string().min(1, "테이블명을 입력해주세요"), + colNm: z.string().min(1, "컬럼명을 입력해주세요"), + pkColNm: z.string().min(1, "PK 키를 입력해주세요"), + ipcrCntVl: z.number().optional().nullable(), + pctlCrtrVl: z.number().optional().nullable(), + scopCntCntVl: z.number().optional().nullable(), + thrsCntVl: z.number().optional().nullable(), + useYn: z.string().optional(), + vrfcTrgtNm: z.string().optional().nullable(), + rgtr: z.string().optional().nullable(), + regDt: z.string().optional().nullable(), + mdfr: z.string().optional().nullable(), + rgtrNm: z.string().optional().nullable(), + mdfrNm: z.string().optional().nullable(), + mdfcn: z.string().optional().nullable(), +}); + +export type VerificationTargetManagementFormData = z.infer< + typeof verificationTargetManagementSchema +>; diff --git a/apps/st/src/pages/statistics/index.ts b/apps/st/src/pages/statistics/index.ts index 7a969422f..c419d5df7 100644 --- a/apps/st/src/pages/statistics/index.ts +++ b/apps/st/src/pages/statistics/index.ts @@ -1 +1 @@ -export { default as statisticsPage } from "./ui/statistics-page"; \ No newline at end of file +export { default as StatisticsPage } from "./ui/statistics-page"; diff --git a/apps/st/src/shared/config/api.ts b/apps/st/src/shared/config/api.ts index c8ff0983e..1b9cf74ec 100644 --- a/apps/st/src/shared/config/api.ts +++ b/apps/st/src/shared/config/api.ts @@ -3,73 +3,76 @@ import { PROXY_HOST } from "./env"; export const BASE_URL = `${PROXY_HOST}/server`; export const ENDPOINT = { - ATTACH_SERVICE: { - TUS_UPLOAD: "/attach-service/api/v1/tus/upload", - EDITOR_UPLOAD: "/attach-service/api/v1/upload/editor", - IMAGES: "/attach-service/api/v1/images", - MOVIE_THUMBNAIL: "/attach-service/api/v1/movie/thumbnail", - ATTACHMENTS: "/attach-service/api/v1/atfl/attachments", - DOWNLOAD: "/attach-service/api/v1/atflcd/download", - STREAM_VIDEO: "/attach-service/api/v1/stream/video", - }, - USER_SERVICE: { - LOGIN: "/user-service/login", - USERS: "/user-service/api/v1/users", - SILENT_REFRESH: "/user-service/api/v1/users/token/refresh", - AUTHORIZATIONS: "/user-service/api/v1/authorizations", - ROLE_AUTHORIZATIONS: "/user-service/api/v1/role-authorizations", - ROLES: "/user-service/api/v1/roles", - LOGINLOG: "/user-service/api/v1/login-logs", - PRIVACYLOG: "/user-service//api/v1/prvc-inq-logs", - }, - CMS_SERVICE: { - DASHBOARD: "/cms-service/api/v1/dashboard", - SITES: "/cms-service/api/v1/sites", - IPS: "/cms-service/api/v1/site-ips", - DOMAINS: "/cms-service/api/v1/site-dmns", - POSTINGS: "/cms-service/api/v1/site-pstgs", - CODE: "/cms-service/api/v1/code/cache", - MENUS: "/cms-service/api/v1/menus", - MENU_ROLES: "/cms-service/api/v1/menu-roles", - MENU_AUTHRTS: "/cms-service/api/v1/menu-authrts", - MENU_TEMPORARY_STORAGE: "/cms-service/api/v1/menu-tmpr-strg", - MENU_HISTORY: "/cms-service/api/v1/menu-hstry", - CONTENTS: "/cms-service/api/v1/contents", - CONTENTS_DETAILS: "/cms-service/api/v1/contents-details", - ORGANIZATIONS: "/cms-service/api/v1/ognzs", - USER_ORGANIZATION: "/cms-service/api/v1/user-ognz", - IMAGES: "/cms-service/api/v1/images", - BANNERS: "/cms-service/api/v1/bnrs", - TEMPLATE: "/cms-service/api/v1/tmplt", - TERMS: "/cms-service/api/v1/trms", - LWPO_CODE: "/cms-service/api/v1/lwpo-cds", - UP_CODE: "/cms-service/api/v1/up-codes", - POPUPS: "/cms-service/api/v1/popups", - SCHEDULES: "/cms-service/api/v1/schdls", - SURVEY: "/cms-service/api/v1/srvy", - SURVEY_QUESTION: "/cms-service/api/v1/srvy-qitem", - SURVEY_ARTICLE: "/cms-service/api/v1/srvy-artcl", - ZIPS: "/cms-service/api/v1/zips", - GROUPS: "/cms-service/api/v1/groups", - GROUP_USERS: "/cms-service/api/v1/group-users", - MANAGER_IP: "/cms-service/api/v1/mgrip", - APILOG: "/cms-service/api/v1/api-logs", - SITE_AUTHORITY: "/cms-service/api/v1/site-authrt", - CONNECTION_LOG: "/cms-service/api/v1/cntnlog", - }, - BOARD_SERVICE: { - BBS: "/board-service/api/v1/bbs", - BBS_TEMPLATES: "/board-service/api/v1/bbsTmplt", - POSTS: "/board-service/api/v1/posts", - POSTS_COMMENTS: "/board-service/api/v1/posts-cmnts", - POST_EVALUATION: "/board-service/api/v1/pstEvl", - }, - ST_SERVICE: { - COMMON: "/st-management-service/api/v1/common", - INPUT: "/st-input-service/api/v1/input", - REVIEW: "/st-management-service/api/v1/review", - INPUTCOMMON: "/st-input-service/api/v1/common", - } + ATTACH_SERVICE: { + TUS_UPLOAD: "/attach-service/api/v1/tus/upload", + EDITOR_UPLOAD: "/attach-service/api/v1/upload/editor", + IMAGES: "/attach-service/api/v1/images", + MOVIE_THUMBNAIL: "/attach-service/api/v1/movie/thumbnail", + ATTACHMENTS: "/attach-service/api/v1/atfl/attachments", + DOWNLOAD: "/attach-service/api/v1/atflcd/download", + STREAM_VIDEO: "/attach-service/api/v1/stream/video", + }, + USER_SERVICE: { + LOGIN: "/user-service/login", + USERS: "/user-service/api/v1/users", + SILENT_REFRESH: "/user-service/api/v1/users/token/refresh", + AUTHORIZATIONS: "/user-service/api/v1/authorizations", + ROLE_AUTHORIZATIONS: "/user-service/api/v1/role-authorizations", + ROLES: "/user-service/api/v1/roles", + LOGINLOG: "/user-service/api/v1/login-logs", + PRIVACYLOG: "/user-service//api/v1/prvc-inq-logs", + }, + CMS_SERVICE: { + DASHBOARD: "/cms-service/api/v1/dashboard", + SITES: "/cms-service/api/v1/sites", + IPS: "/cms-service/api/v1/site-ips", + DOMAINS: "/cms-service/api/v1/site-dmns", + POSTINGS: "/cms-service/api/v1/site-pstgs", + CODE: "/cms-service/api/v1/code/cache", + MENUS: "/cms-service/api/v1/menus", + MENU_ROLES: "/cms-service/api/v1/menu-roles", + MENU_AUTHRTS: "/cms-service/api/v1/menu-authrts", + MENU_TEMPORARY_STORAGE: "/cms-service/api/v1/menu-tmpr-strg", + MENU_HISTORY: "/cms-service/api/v1/menu-hstry", + CONTENTS: "/cms-service/api/v1/contents", + CONTENTS_DETAILS: "/cms-service/api/v1/contents-details", + ORGANIZATIONS: "/cms-service/api/v1/ognzs", + USER_ORGANIZATION: "/cms-service/api/v1/user-ognz", + IMAGES: "/cms-service/api/v1/images", + BANNERS: "/cms-service/api/v1/bnrs", + TEMPLATE: "/cms-service/api/v1/tmplt", + TERMS: "/cms-service/api/v1/trms", + LWPO_CODE: "/cms-service/api/v1/lwpo-cds", + UP_CODE: "/cms-service/api/v1/up-codes", + POPUPS: "/cms-service/api/v1/popups", + SCHEDULES: "/cms-service/api/v1/schdls", + SURVEY: "/cms-service/api/v1/srvy", + SURVEY_QUESTION: "/cms-service/api/v1/srvy-qitem", + SURVEY_ARTICLE: "/cms-service/api/v1/srvy-artcl", + ZIPS: "/cms-service/api/v1/zips", + GROUPS: "/cms-service/api/v1/groups", + GROUP_USERS: "/cms-service/api/v1/group-users", + MANAGER_IP: "/cms-service/api/v1/mgrip", + APILOG: "/cms-service/api/v1/api-logs", + SITE_AUTHORITY: "/cms-service/api/v1/site-authrt", + CONNECTION_LOG: "/cms-service/api/v1/cntnlog", + }, + BOARD_SERVICE: { + BBS: "/board-service/api/v1/bbs", + BBS_TEMPLATES: "/board-service/api/v1/bbsTmplt", + POSTS: "/board-service/api/v1/posts", + POSTS_COMMENTS: "/board-service/api/v1/posts-cmnts", + POST_EVALUATION: "/board-service/api/v1/pstEvl", + }, + ST_SERVICE: { + COMMON: "/st-management-service/api/v1/common", + INPUT: "/st-input-service/api/v1/input", + REVIEW: "/st-management-service/api/v1/review", + INPUTCOMMON: "/st-input-service/api/v1/common", + }, + STATVERIFY_SERVICE: { + VRFCTGT_MNG: "/statverify-service/api/v1/vrfc-trgt-mng", + }, }; export const JWT_EXPIRATION_TIME = 1800000; diff --git a/apps/st/src/shared/ui/statistics-page-layout.tsx b/apps/st/src/shared/ui/statistics-page-layout.tsx index 1597a7af0..b34ebb5eb 100644 --- a/apps/st/src/shared/ui/statistics-page-layout.tsx +++ b/apps/st/src/shared/ui/statistics-page-layout.tsx @@ -7,12 +7,10 @@ function StatisticsPageLayout({ children }: { children: React.ReactNode }) { const pageTitle = tabs.find((t) => t.menuItem.menuEngNm === activeTabId); - const menuPaths = pageTitle?.path - ?.split(">") - .map((path) => path.trim()); + const menuPaths = pageTitle?.path?.split(">").map((path) => path.trim()); return ( -
+
{ return null; } - const handleCloseTab = (e: React.MouseEvent | React.KeyboardEvent, tabId: string) => { + const handleCloseTab = ( + e: React.MouseEvent | React.KeyboardEvent, + tabId: string, + ) => { e.stopPropagation(); removeTab(tabId); }; @@ -22,22 +25,22 @@ const TabBar = () => { className="w-full" variant="outline" > - + {tabs.map((tab) => ( - + {tab.label} handleCloseTab(e, tab.id)} aria-label={`${tab.label} 탭 닫기`} - className="flex items-center justify-center flex-shrink-0 leading-none hover:text-[#2094fa]" + className="flex flex-shrink-0 items-center justify-center leading-none hover:text-[#2094fa]" > @@ -46,7 +49,6 @@ const TabBar = () => { ); -} +}; export { TabBar }; - diff --git a/packages/common/components/src/ui/footer/index.tsx b/packages/common/components/src/ui/footer/index.tsx index 029b25910..2430820ff 100644 --- a/packages/common/components/src/ui/footer/index.tsx +++ b/packages/common/components/src/ui/footer/index.tsx @@ -20,7 +20,7 @@ type BannerImageProps = { lnkgUrlAddr: string; }; -const BannerImage = ({ atflCd, bnrSn, lnkgUrlAddr }: BannerImageProps) => { +const BannerImage = ({ atflCd, lnkgUrlAddr }: BannerImageProps) => { const { data: imageUrl, isLoading } = useQuery({ queryKey: [ENDPOINT.ATTACH_SERVICE.IMAGES, atflCd], queryFn: () => getImageUrlByAtflCd(atflCd), @@ -29,13 +29,13 @@ const BannerImage = ({ atflCd, bnrSn, lnkgUrlAddr }: BannerImageProps) => { const handleClick = () => { if (lnkgUrlAddr) { - window.open(lnkgUrlAddr, '_blank'); + window.open(lnkgUrlAddr, "_blank"); } }; if (isLoading) { return ( -
+
로딩 중...
); @@ -43,18 +43,22 @@ const BannerImage = ({ atflCd, bnrSn, lnkgUrlAddr }: BannerImageProps) => { if (!imageUrl) { return ( -
+
이미지 없음
); } return ( -
- 배너 이미지 + 배너 이미지
); }; @@ -70,25 +74,33 @@ export function Footer() { queryFn: () => getBannerList(siteId), }); -// MAIN 타입 배너만 필터링 - const mainBanners = bannerList?.filter((banner) => banner.bnrTypeCd === "BNRFTER") ?? []; - + // MAIN 타입 배너만 필터링 + const mainBanners = + bannerList?.filter((banner) => banner.bnrTypeCd === "BNRFTER") ?? []; const plugin = useRef(Autoplay({ delay: 2000, stopOnInteraction: true })); return ( -