768 lines
37 KiB
TypeScript
768 lines
37 KiB
TypeScript
import { useEffect, useRef, useState } from "react";
|
||
|
||
import {
|
||
Button,
|
||
Dialog,
|
||
DialogContent,
|
||
DialogFooter,
|
||
DialogHeader,
|
||
DialogTitle,
|
||
DialogClose,
|
||
Textarea,
|
||
Skeleton,
|
||
Input,
|
||
Checkbox,
|
||
} from "@common/components";
|
||
import { CodeSelect } from "@/entities/code";
|
||
|
||
import { generalverificationApiService } from "@/entities/statistics/api/general-verification-service";
|
||
import type { VerifyDetailResponseDto, VerifyColumnListResponseData, SelectedVerifyColumnListResponseData } from "@/entities/statistics/model/general-verification-interface";
|
||
|
||
import { useAlertStore } from "@/shared/lib";
|
||
|
||
export interface FomulaDialogConfirmPayload {
|
||
kornArtopnEqtnCn: string;
|
||
engArtopnEqtnCn: string;
|
||
/** 참조 통계코드 (선택 안 했으면 null) */
|
||
refStatsCd: string | null;
|
||
}
|
||
|
||
interface FomulaDialogProps {
|
||
open: boolean;
|
||
onOpenChange?: (open: boolean) => void;
|
||
data?: VerifyDetailResponseDto | null;
|
||
trgtStatsCd?: string;
|
||
trgtStatsNm?: string;
|
||
/** 바로 앞 수식 연산자가 like / !like 일 때 '사용자 직접 입력' 체크박스 표시 */
|
||
allowLikeDirectInput?: boolean;
|
||
/** 확인 클릭 시 검사 통과 후 호출. 해당 행에 반영 후 다이얼로그 닫기는 부모에서 처리 */
|
||
onConfirm?: (payload: FomulaDialogConfirmPayload) => void;
|
||
}
|
||
|
||
const FomulaDialog = ({ open, onOpenChange, data, trgtStatsCd, trgtStatsNm, allowLikeDirectInput = false, onConfirm }: FomulaDialogProps) => {
|
||
const [columnInfo, setColumnInfo] = useState<VerifyColumnListResponseData | null>(null);
|
||
const [selectedColumnInfo, setSelectedColumnInfo] = useState<SelectedVerifyColumnListResponseData | null>(null);
|
||
const [showCommonColumns, setShowCommonColumns] = useState<boolean>(true);
|
||
const [showTargetColumns, setShowTargetColumns] = useState<boolean>(true);
|
||
const [showRefColumns, setShowRefColumns] = useState<boolean>(true);
|
||
const [commonColumnSearchValue, setCommonColumnSearchValue] = useState<string>('');
|
||
const [targetColumnSearchValue, setTargetColumnSearchValue] = useState<string>('');
|
||
const [refColumnSearchValue, setRefColumnSearchValue] = useState<string>('');
|
||
/** 참조 통계 - 다이얼로그 내부에서만 사용. 열 때마다 해당 행(data)의 저장값으로 초기화, 저장 시에만 부모에 반영 예정 */
|
||
const [refStatsCdLocal, setRefStatsCdLocal] = useState<string>('');
|
||
/** 수식 = 토큰 배열. 한글명 중복 시 출처(공통/대상/참조)별 engColNm 보존 */
|
||
const [formulaDisplaySegments, setFormulaDisplaySegments] = useState<string[]>([]);
|
||
const [formulaValueSegments, setFormulaValueSegments] = useState<string[]>([]);
|
||
/** like / !like 수식에서 '사용자 직접 입력' 체크 여부 */
|
||
const [userDirectInput, setUserDirectInput] = useState(false);
|
||
/** 확인 클릭 시 검사 실패 메시지 (Textarea 아래 빨간 글씨) */
|
||
const [formulaSaveError, setFormulaSaveError] = useState<string | null>(null);
|
||
/** 참조 통계 변경 시 안내 메시지 */
|
||
const [refStatsChangeNotice, setRefStatsChangeNotice] = useState<string | null>(null);
|
||
|
||
const formulaTextareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||
|
||
const isUserDirectInputMode = allowLikeDirectInput && userDirectInput;
|
||
|
||
const { setMessage: alert } = useAlertStore((state) => state);
|
||
|
||
/** 다이얼로그에서 쓰는 기호 → 제출용 value. 백엔드 규격에 맞게 수정 가능 */
|
||
const OPERATOR_SYMBOL_TO_VALUE: Record<string, string> = {
|
||
'+': '+',
|
||
'-': '-',
|
||
'×': '*',
|
||
'%': '/',
|
||
'(': '(',
|
||
')': ')',
|
||
};
|
||
|
||
/** 공통 → 대상 → 참조 순, 첫 등장 kornColNm만 사용 (로드/직접입력 시 파싱용) */
|
||
const getKornToEngMapForParse = (): Map<string, string> => {
|
||
const map = new Map<string, string>();
|
||
const refCols = selectedColumnInfo?.targetColumnInfo?.colList ?? columnInfo?.refColumnInfo?.colList ?? [];
|
||
[...(columnInfo?.commonColumnInfo ?? []), ...(columnInfo?.targetColumnInfo?.colList ?? []), ...refCols].forEach(
|
||
(item) => {
|
||
if (!map.has(item.kornColNm)) map.set(item.kornColNm, item.engColNm);
|
||
}
|
||
);
|
||
return map;
|
||
};
|
||
|
||
/** 한글 수식 문자열을 토큰(표시/값) 배열로 파싱. 컬럼명은 longest match */
|
||
const parseDisplayToSegments = (displayStr: string): { display: string[]; value: string[] } => {
|
||
if (displayStr.length === 0) return { display: [], value: [] };
|
||
const kornToEng = getKornToEngMapForParse();
|
||
const kornList = [...kornToEng.keys()].filter(Boolean).sort((a, b) => b.length - a.length);
|
||
const display: string[] = [];
|
||
const value: string[] = [];
|
||
let i = 0;
|
||
while (i < displayStr.length) {
|
||
let matched = false;
|
||
for (const korn of kornList) {
|
||
if (displayStr.slice(i, i + korn.length) === korn) {
|
||
display.push(korn);
|
||
value.push(kornToEng.get(korn) ?? korn);
|
||
i += korn.length;
|
||
matched = true;
|
||
break;
|
||
}
|
||
}
|
||
if (!matched) {
|
||
const ch = displayStr[i];
|
||
if (ch != null) {
|
||
display.push(ch);
|
||
value.push(ch);
|
||
}
|
||
i += 1;
|
||
}
|
||
}
|
||
return { display, value };
|
||
};
|
||
|
||
/** 직접 입력 저장값의 양쪽 백틱 제거 (편집용) */
|
||
const stripBacktickWrap = (value: string) => {
|
||
if (value.length >= 2 && value.startsWith("`") && value.endsWith("`")) {
|
||
return value.slice(1, -1);
|
||
}
|
||
return value;
|
||
};
|
||
|
||
/** 직접 입력 저장 시 백틱으로 감싸기 (이미 감싸진 경우 유지) */
|
||
const wrapWithBacktick = (value: string) => {
|
||
if (!value) return value;
|
||
if (value.startsWith("`") && value.endsWith("`")) return value;
|
||
return `\`${value}\``;
|
||
};
|
||
|
||
const handleUserDirectInputChange = (checked: boolean) => {
|
||
setFormulaSaveError(null);
|
||
setUserDirectInput(checked);
|
||
const current = formulaDisplaySegments.join("");
|
||
if (checked) {
|
||
const editable = stripBacktickWrap(current);
|
||
setFormulaDisplaySegments(editable ? [editable] : []);
|
||
setFormulaValueSegments(editable ? [editable] : []);
|
||
return;
|
||
}
|
||
const { display, value } = parseDisplayToSegments(current);
|
||
setFormulaDisplaySegments(display);
|
||
setFormulaValueSegments(value);
|
||
};
|
||
|
||
const handleFormulaKey = (val: string) => {
|
||
setFormulaSaveError(null);
|
||
if (val === 'backspace') {
|
||
setFormulaDisplaySegments((prev) => prev.slice(0, -1));
|
||
setFormulaValueSegments((prev) => prev.slice(0, -1));
|
||
} else if (val === 'ac') {
|
||
setFormulaDisplaySegments([]);
|
||
setFormulaValueSegments([]);
|
||
} else {
|
||
setFormulaDisplaySegments((prev) => [...prev, val]);
|
||
setFormulaValueSegments((prev) => [...prev, val]);
|
||
}
|
||
};
|
||
|
||
/** 컬럼 버튼: 한글 표시 + 해당 출처의 영문명 저장 (한글 중복 시에도 구분) */
|
||
const handleFormulaColumn = (kornColNm: string, engColNm: string) => {
|
||
setFormulaSaveError(null);
|
||
setFormulaDisplaySegments((prev) => [...prev, kornColNm]);
|
||
setFormulaValueSegments((prev) => [...prev, engColNm]);
|
||
};
|
||
|
||
/** 제출/저장 시 사용할 영문 수식 (컬럼 engColNm + 연산자 기호 → value 치환) */
|
||
const getFormulaValueForSubmit = (): string =>
|
||
formulaValueSegments.map((seg) => OPERATOR_SYMBOL_TO_VALUE[seg] ?? seg).join('');
|
||
|
||
const OPERATORS = ['+', '-', '×', '/', '%'] as const;
|
||
const isOperator = (s: string) => s.length === 1 && (OPERATORS as readonly string[]).includes(s);
|
||
const isParen = (s: string) => s === '(' || s === ')';
|
||
const isValueToken = (s: string) =>
|
||
s.length > 1 || (s.length === 1 && !isOperator(s) && !isParen(s));
|
||
const isDigit = (s: string) => s.length === 1 && /[0-9]/.test(s);
|
||
|
||
/** 저장 시 수식 규칙 검사. 오류 시 메시지 반환, 통과 시 null */
|
||
const validateFormulaForSave = (segments: string[]): string | null => {
|
||
if (segments.length === 0) return null;
|
||
|
||
for (let i = 0; i < segments.length - 1; i++) {
|
||
const a = segments[i];
|
||
const b = segments[i + 1];
|
||
if (a != null && b != null && isValueToken(a) && isValueToken(b) && !(isDigit(a) && isDigit(b))) {
|
||
return '컬럼(또는 숫자) 사이에 더하기, 빼기, 나누기, 곱하기 기호가 있어야 합니다.';
|
||
}
|
||
}
|
||
|
||
// "(값)"도 하나의 값으로 취급: 값/닫는괄호 뒤에는 '(' 또는 값이 올 수 없고, 사이에 연산자가 있어야 함.
|
||
// 예: 컬럼(100), 값)(100) 같은 형태는 연산자 누락으로 간주
|
||
for (let i = 0; i < segments.length - 1; i++) {
|
||
const a = segments[i];
|
||
const b = segments[i + 1];
|
||
if (a == null || b == null) continue;
|
||
// 연속 숫자(예: 50)는 예외 허용
|
||
if (isDigit(a) && isDigit(b)) continue;
|
||
|
||
const aIsValueBoundary = isValueToken(a) || a === ')';
|
||
const bIsValueBoundary = b === '(' || isValueToken(b);
|
||
if (aIsValueBoundary && bIsValueBoundary) {
|
||
return '컬럼(또는 숫자) 사이에 더하기, 빼기, 나누기, 곱하기 기호가 있어야 합니다.';
|
||
}
|
||
}
|
||
|
||
const last = segments[segments.length - 1];
|
||
if (last && isOperator(last)) {
|
||
return '수식은 기호로 끝날 수 없습니다. (닫는 괄호 제외)';
|
||
}
|
||
|
||
const stack: boolean[] = [];
|
||
for (let i = 0; i < segments.length; i++) {
|
||
const s = segments[i];
|
||
if (s == null) continue;
|
||
if (s === '(') {
|
||
stack.push(false);
|
||
} else if (s === ')') {
|
||
if (stack.length === 0) return '닫는 괄호가 여는 괄호 없이 사용되었습니다.';
|
||
const hadValue = stack.pop();
|
||
if (!hadValue) return '괄호 안에 값이 있어야 합니다.';
|
||
if (stack.length > 0) stack[stack.length - 1] = true;
|
||
} else if (stack.length > 0 && isValueToken(s)) {
|
||
stack[stack.length - 1] = true;
|
||
}
|
||
}
|
||
if (stack.length > 0) return '여는 괄호에 대응하는 닫는 괄호가 없습니다.';
|
||
|
||
return null;
|
||
};
|
||
|
||
const getVerifyColumnList = async () => {
|
||
try {
|
||
if (!trgtStatsCd) return;
|
||
let response;
|
||
|
||
if (data?.vrfcDtlSn == null || data.vrfcDtlSn <= 0) {
|
||
response = await generalverificationApiService.getSelectedVerifyColumnList(trgtStatsCd)
|
||
} else {
|
||
response = await generalverificationApiService.getVerifyColumnList({
|
||
trgtStatsCd,
|
||
vrfcDtlSn: data.vrfcDtlSn,
|
||
refStatsCd: data.refStatsCd,
|
||
});
|
||
}
|
||
|
||
|
||
if (response?.status === 'success') {
|
||
setColumnInfo(response.data);
|
||
} else {
|
||
alert(response?.message || '데이터 조회 중 오류가 발생했습니다.');
|
||
}
|
||
} catch {
|
||
alert('데이터 조회 중 오류가 발생했습니다.');
|
||
}
|
||
};
|
||
|
||
const getSelectedVerifyColumnList = async (statsCd: string) => {
|
||
try {
|
||
const response = await generalverificationApiService.getSelectedVerifyColumnList(statsCd);
|
||
if (response?.status === 'success' && response.data) {
|
||
setSelectedColumnInfo({
|
||
targetColumnInfo: response.data.targetColumnInfo ?? { statsCd: statsCd, colList: [] },
|
||
commonColumnInfo: response.data.commonColumnInfo ?? [],
|
||
});
|
||
} else {
|
||
setSelectedColumnInfo(null);
|
||
}
|
||
} catch {
|
||
setSelectedColumnInfo(null);
|
||
}
|
||
};
|
||
|
||
useEffect(() => {
|
||
if (open) {
|
||
setColumnInfo(null);
|
||
setSelectedColumnInfo(null);
|
||
}
|
||
if (open) void getVerifyColumnList();
|
||
}, [open, trgtStatsCd, data?.vrfcDtlSn]);
|
||
|
||
useEffect(() => {
|
||
if (open) setRefStatsCdLocal(data?.refStatsCd ?? '');
|
||
}, [open, data?.refStatsCd, data?.vrfcDtlSn]);
|
||
|
||
useEffect(() => {
|
||
if (!open) {
|
||
setSelectedColumnInfo(null);
|
||
setRefStatsCdLocal('');
|
||
setFormulaDisplaySegments([]);
|
||
setFormulaValueSegments([]);
|
||
setUserDirectInput(false);
|
||
setFormulaSaveError(null);
|
||
setRefStatsChangeNotice(null);
|
||
}
|
||
}, [open]);
|
||
|
||
useEffect(() => {
|
||
if (open) {
|
||
const raw = data?.kornArtopnEqtnCn ?? '';
|
||
const wasBacktickWrapped =
|
||
raw.length >= 2 && raw.startsWith("`") && raw.endsWith("`");
|
||
const str = stripBacktickWrap(raw);
|
||
if (wasBacktickWrapped && allowLikeDirectInput) {
|
||
setFormulaDisplaySegments(str ? [str] : []);
|
||
setFormulaValueSegments(str ? [str] : []);
|
||
setUserDirectInput(true);
|
||
} else {
|
||
const { display, value } = parseDisplayToSegments(str);
|
||
setFormulaDisplaySegments(display);
|
||
setFormulaValueSegments(value);
|
||
setUserDirectInput(false);
|
||
}
|
||
}
|
||
}, [open, data?.kornArtopnEqtnCn, data?.vrfcDtlSn, allowLikeDirectInput]);
|
||
|
||
/**
|
||
* 재오픈 직후에는 columnInfo가 아직 없어서 parseDisplayToSegments가 컬럼명을 매칭 못하고
|
||
* 한글을 1글자씩 토큰화하는 경우가 있음.
|
||
* 컬럼 목록 로딩 후(= map이 채워진 후) "표시 문자열이 원본과 동일 + 값 토큰이 표시 토큰과 동일"한 케이스만 재파싱해서
|
||
* engColNm 치환이 반영되도록 보정한다.
|
||
*/
|
||
useEffect(() => {
|
||
if (!open || isUserDirectInputMode) return;
|
||
const src = stripBacktickWrap(data?.kornArtopnEqtnCn ?? '');
|
||
if (!src) return;
|
||
|
||
const displayJoined = formulaDisplaySegments.join('');
|
||
const valueJoined = formulaValueSegments.join('');
|
||
// 아직 컬럼 치환이 안 된 상태(= value가 display와 동일)에서만 재파싱
|
||
if (displayJoined !== src) return;
|
||
if (valueJoined !== displayJoined) return;
|
||
|
||
// 컬럼 목록이 준비된 이후에만 의미가 있음
|
||
const hasColumns =
|
||
(columnInfo?.commonColumnInfo?.length ?? 0) > 0 ||
|
||
(columnInfo?.targetColumnInfo?.colList?.length ?? 0) > 0 ||
|
||
(columnInfo?.refColumnInfo?.colList?.length ?? 0) > 0 ||
|
||
(selectedColumnInfo?.targetColumnInfo?.colList?.length ?? 0) > 0;
|
||
if (!hasColumns) return;
|
||
|
||
const { display, value } = parseDisplayToSegments(src);
|
||
const nextDisplayJoined = display.join('');
|
||
const nextValueJoined = value.join('');
|
||
// 파싱 결과가 현재와 완전히 같으면 setState 반복으로 무한 렌더가 날 수 있으니 중단
|
||
if (nextDisplayJoined === displayJoined && nextValueJoined === valueJoined) return;
|
||
// 컬럼 치환이 전혀 안 됐다면(= value가 display와 동일) 보정의 의미가 없으니 중단
|
||
if (nextValueJoined === nextDisplayJoined) return;
|
||
|
||
setFormulaDisplaySegments(display);
|
||
setFormulaValueSegments(value);
|
||
}, [
|
||
open,
|
||
data?.kornArtopnEqtnCn,
|
||
columnInfo?.commonColumnInfo,
|
||
columnInfo?.targetColumnInfo?.colList,
|
||
columnInfo?.refColumnInfo?.colList,
|
||
selectedColumnInfo?.targetColumnInfo?.colList,
|
||
formulaDisplaySegments,
|
||
formulaValueSegments,
|
||
]);
|
||
|
||
useEffect(() => {
|
||
if (!open || isUserDirectInputMode || columnInfo?.kornArtopnEqtnCn == null) return;
|
||
const strippedColumn = stripBacktickWrap(columnInfo.kornArtopnEqtnCn);
|
||
const strippedData = stripBacktickWrap(data?.kornArtopnEqtnCn ?? "");
|
||
if (strippedData !== strippedColumn) return;
|
||
const { display, value } = parseDisplayToSegments(strippedColumn);
|
||
setFormulaDisplaySegments(display);
|
||
setFormulaValueSegments(value);
|
||
}, [open, data?.kornArtopnEqtnCn, columnInfo?.kornArtopnEqtnCn, isUserDirectInputMode]);
|
||
|
||
const handleChangeRefStatsCd = (next: string) => {
|
||
if (!open) return;
|
||
|
||
// 현재 refStatsCdLocal에 해당하는 참조 컬럼이 수식에 포함돼 있으면 변경을 막고 안내만 표시
|
||
const currentRefCols = refColList ?? [];
|
||
const currentRefEngSet = new Set(currentRefCols.map((c) => c.engColNm).filter(Boolean));
|
||
const hasCurrentRefToken =
|
||
currentRefEngSet.size > 0 && formulaValueSegments.some((seg) => currentRefEngSet.has(seg));
|
||
|
||
if (hasCurrentRefToken) {
|
||
setRefStatsChangeNotice('수식에 기존 참조 컬럼이 포함되어 있어 참조 통계를 변경할 수 없습니다. 먼저 해당 참조 컬럼을 제거해주세요.');
|
||
return;
|
||
}
|
||
|
||
setRefStatsChangeNotice(null);
|
||
setRefStatsCdLocal(next);
|
||
};
|
||
|
||
/** 참조 통계 선택 시 해당 통계의 컬럼 목록으로 교체 */
|
||
useEffect(() => {
|
||
if (!open) return;
|
||
if (refStatsCdLocal) {
|
||
void getSelectedVerifyColumnList(refStatsCdLocal);
|
||
} else {
|
||
setSelectedColumnInfo(null);
|
||
}
|
||
}, [open, refStatsCdLocal]);
|
||
|
||
/** 참조 컬럼: 선택한 참조 통계로 조회한 목록이 있으면 사용, 없으면 getVerifyColumnList 결과 사용 */
|
||
const refColList = selectedColumnInfo?.targetColumnInfo?.colList ?? columnInfo?.refColumnInfo?.colList ?? [];
|
||
|
||
const handleOpenChange = (nextOpen: boolean) => {
|
||
if (!nextOpen) {
|
||
setFormulaDisplaySegments([]);
|
||
setFormulaValueSegments([]);
|
||
setUserDirectInput(false);
|
||
setFormulaSaveError(null);
|
||
setSelectedColumnInfo(null);
|
||
setRefStatsCdLocal('');
|
||
setCommonColumnSearchValue('');
|
||
setTargetColumnSearchValue('');
|
||
setRefColumnSearchValue('');
|
||
}
|
||
onOpenChange?.(nextOpen);
|
||
};
|
||
|
||
const handleSearchColumn = (value: string, type: string) => {
|
||
if (type === 'common') {
|
||
setCommonColumnSearchValue(value);
|
||
} else if (type === 'target') {
|
||
setTargetColumnSearchValue(value);
|
||
} else {
|
||
setRefColumnSearchValue(value);
|
||
}
|
||
};
|
||
|
||
const normalizeSearch = (v: string) => v.replace(/\s+/g, "").toLowerCase();
|
||
|
||
const commonSearch = normalizeSearch(commonColumnSearchValue);
|
||
const commonColumns = columnInfo?.commonColumnInfo ?? [];
|
||
const filteredCommonColumns =
|
||
commonSearch.length > 0
|
||
? commonColumns.filter((c) => {
|
||
const korn = normalizeSearch(c.kornColNm ?? '');
|
||
const eng = normalizeSearch(c.engColNm ?? '');
|
||
return korn.includes(commonSearch) || eng.includes(commonSearch);
|
||
})
|
||
: commonColumns;
|
||
|
||
const targetSearch = normalizeSearch(targetColumnSearchValue);
|
||
const targetColumns = columnInfo?.targetColumnInfo?.colList ?? [];
|
||
const filteredTargetColumns =
|
||
targetSearch.length > 0
|
||
? targetColumns.filter((t) => {
|
||
const korn = normalizeSearch(t.kornColNm ?? '');
|
||
const eng = normalizeSearch(t.engColNm ?? '');
|
||
return korn.includes(targetSearch) || eng.includes(targetSearch);
|
||
})
|
||
: targetColumns;
|
||
|
||
const refSearch = normalizeSearch(refColumnSearchValue);
|
||
const filterdRefColumns =
|
||
refSearch.length > 0
|
||
? refColList.filter((r) => {
|
||
const korn = normalizeSearch(r.kornColNm ?? '');
|
||
const eng = normalizeSearch(r.engColNm ?? '');
|
||
return korn.includes(refSearch) || eng.includes(refSearch);
|
||
})
|
||
: refColList;
|
||
|
||
return (
|
||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||
<DialogContent aria-describedby={undefined} className="max-w-[100rem] w-full max-h-[90%] overflow-auto">
|
||
<DialogHeader>
|
||
<DialogTitle>
|
||
수식 상세 정보
|
||
</DialogTitle>
|
||
</DialogHeader>
|
||
<div className="flex flex-col gap-4">
|
||
<div className="flex justify-start gap-20 p-4 border rounded-xl">
|
||
<div className="flex flex-col gap-2">
|
||
<h3 className="font-bold text-title text-[14px]">기호 및 숫자</h3>
|
||
<div className="grid grid-cols-3 gap-2 w-max">
|
||
<Button type="button" value="+" color="gray" className="w-[65px]" onClick={() => handleFormulaKey('+')}>
|
||
<span className="text-[18px]">+</span>
|
||
</Button>
|
||
<Button type="button" value="-" color="gray" className="w-[65px]" onClick={() => handleFormulaKey('-')}>
|
||
<span className="text-[18px]">-</span>
|
||
</Button>
|
||
<Button type="button" value="*" color="gray" className="w-[65px]" onClick={() => handleFormulaKey('×')}>
|
||
<span className="text-[18px]">×</span>
|
||
</Button>
|
||
<Button type="button" value="/" color="gray" className="w-[65px]" onClick={() => handleFormulaKey('%')}>
|
||
<span className="text-[18px]">%</span>
|
||
</Button>
|
||
<Button type="button" value="(" color="gray" className="w-[65px]" onClick={() => handleFormulaKey('(')}>
|
||
<span className="text-[18px]">(</span>
|
||
</Button>
|
||
<Button type="button" value=")" color="gray" className="w-[65px]" onClick={() => handleFormulaKey(')')}>
|
||
<span className="text-[18px]">)</span>
|
||
</Button>
|
||
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '⌫', 'AC'].map((n) => {
|
||
const keyVal = n !== 'AC' && n !== '⌫' ? String(n) : n === '⌫' ? 'backspace' : 'ac';
|
||
return (
|
||
<Button
|
||
key={n}
|
||
type="button"
|
||
value={keyVal}
|
||
color={n !== 'AC' && n !== '⌫' ? 'white' : 'primary'}
|
||
className="w-[65px]"
|
||
onClick={() => handleFormulaKey(keyVal)}
|
||
>
|
||
<span className="text-[18px]">{n}</span>
|
||
</Button>
|
||
);
|
||
})}
|
||
</div>
|
||
</div>
|
||
<div className="w-full flex flex-col gap-2">
|
||
<div className="flex items-center gap-3">
|
||
<h3 className="font-bold text-title text-[14px]">수식 미리보기</h3>
|
||
{allowLikeDirectInput && (
|
||
<label className="flex items-center gap-2 text-[13px] text-gray-700 cursor-pointer select-none">
|
||
<Checkbox
|
||
id="userDirectInput"
|
||
checked={userDirectInput}
|
||
onCheckedChange={(checked) =>
|
||
handleUserDirectInputChange(checked === true)
|
||
}
|
||
/>
|
||
사용자 직접 입력
|
||
</label>
|
||
)}
|
||
</div>
|
||
<Textarea
|
||
className={`w-full flex-1 resize-none !text-3xl p-4 !leading-loose font-bold ${
|
||
isUserDirectInputMode
|
||
? "bg-white text-gray-900"
|
||
: "bg-gray-100 text-gray-600"
|
||
}`}
|
||
id="formulaDisplayInput"
|
||
ref={formulaTextareaRef}
|
||
value={formulaDisplaySegments.join('')}
|
||
onChange={(e) => {
|
||
setFormulaSaveError(null);
|
||
if (isUserDirectInputMode) {
|
||
const raw = e.target.value;
|
||
setFormulaDisplaySegments(raw ? [raw] : []);
|
||
setFormulaValueSegments(raw ? [raw] : []);
|
||
return;
|
||
}
|
||
const { display, value } = parseDisplayToSegments(e.target.value);
|
||
setFormulaDisplaySegments(display);
|
||
setFormulaValueSegments(value);
|
||
}}
|
||
rows={4}
|
||
readOnly={!isUserDirectInputMode}
|
||
/>
|
||
{formulaSaveError && (
|
||
<p className="text-sm text-red-600 mt-1" role="alert">
|
||
{formulaSaveError}
|
||
</p>
|
||
)}
|
||
</div>
|
||
</div>
|
||
<div className="flex flex-col gap-2 p-4 border rounded-xl">
|
||
<div className="flex items-center justify-between">
|
||
<h3 className="font-bold text-title text-[14px]">공통 컬럼</h3>
|
||
<Button
|
||
type="button"
|
||
size="sm"
|
||
color="white"
|
||
onClick={() => setShowCommonColumns((prev) => !prev)}
|
||
>
|
||
{showCommonColumns ? "접기" : "펼치기"}
|
||
</Button>
|
||
</div>
|
||
{showCommonColumns &&
|
||
<div className="mb-2">
|
||
<Input
|
||
className="w-[20rem] rounded-sm !text-[1.3rem] focus-visible:ring-0 focus-visible:ring-offset-0"
|
||
value={commonColumnSearchValue}
|
||
onChange={(e) => handleSearchColumn(e.target.value, 'common')}
|
||
placeholder="검색어를 입력하세요."
|
||
/>
|
||
</div>}
|
||
{showCommonColumns ? (
|
||
<div className="flex flex-wrap gap-2">
|
||
{columnInfo?.commonColumnInfo?.length && columnInfo.commonColumnInfo.length > 0 ?
|
||
filteredCommonColumns.map((c) => (
|
||
<Button
|
||
key={c.engColNm}
|
||
type="button"
|
||
value={c.engColNm}
|
||
size="sm"
|
||
color="lightGray"
|
||
disabled={isUserDirectInputMode}
|
||
onClick={() => handleFormulaColumn(c.kornColNm, c.engColNm)}
|
||
>
|
||
{c.kornColNm}
|
||
</Button>
|
||
))
|
||
:
|
||
<Skeleton className="h-[12rem] w-full rounded-xl" />
|
||
}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
<div className="flex flex-col gap-2 p-4 border rounded-xl">
|
||
<div className="flex items-center justify-between">
|
||
<h3 className="font-bold text-title text-[14px]">{trgtStatsNm} 컬럼</h3>
|
||
<Button
|
||
type="button"
|
||
size="sm"
|
||
color="white"
|
||
onClick={() => setShowTargetColumns((prev) => !prev)}
|
||
>
|
||
{showTargetColumns ? "접기" : "펼치기"}
|
||
</Button>
|
||
</div>
|
||
{showTargetColumns &&
|
||
<div className="mb-2">
|
||
<Input
|
||
className="w-[20rem] rounded-sm !text-[1.3rem] focus-visible:ring-0 focus-visible:ring-offset-0"
|
||
value={targetColumnSearchValue}
|
||
onChange={(e) => handleSearchColumn(e.target.value, 'target')}
|
||
placeholder="검색어를 입력하세요."
|
||
/>
|
||
</div>
|
||
}
|
||
{showTargetColumns ? (
|
||
<div className="flex flex-wrap gap-2">
|
||
{columnInfo?.targetColumnInfo?.colList.length && columnInfo.targetColumnInfo.colList.length > 0 ?
|
||
filteredTargetColumns.map((t) => (
|
||
<Button
|
||
key={t.engColNm}
|
||
type="button"
|
||
value={t.engColNm}
|
||
size="sm"
|
||
disabled={isUserDirectInputMode}
|
||
onClick={() => handleFormulaColumn(t.kornColNm, t.engColNm)}
|
||
>
|
||
{t.kornColNm}
|
||
</Button>
|
||
))
|
||
:
|
||
<Skeleton className="h-[12rem] w-full rounded-xl" />
|
||
}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
<div className="flex flex-col gap-2 p-4 border rounded-xl">
|
||
<div className="flex items-center justify-between">
|
||
<div className="flex gap-2 justify-center items-center">
|
||
<h3 className="font-bold text-title text-[14px]">참조 컬럼</h3>
|
||
<CodeSelect
|
||
upCd="STITEM"
|
||
value={refStatsCdLocal}
|
||
onValueChange={handleChangeRefStatsCd}
|
||
placeholder="선택"
|
||
className="w-[16rem]"
|
||
/>
|
||
</div>
|
||
{(refColList?.length ?? 0) > 0 ?
|
||
<Button
|
||
type="button"
|
||
size="sm"
|
||
color="white"
|
||
onClick={() => setShowRefColumns((prev) => !prev)}
|
||
>
|
||
{showRefColumns ? "접기" : "펼치기"}
|
||
</Button>
|
||
:
|
||
null
|
||
}
|
||
</div>
|
||
{refStatsChangeNotice && (
|
||
<p className="text-[12px] text-red-600" role="alert">
|
||
{refStatsChangeNotice}
|
||
</p>
|
||
)}
|
||
{(refStatsCdLocal && showRefColumns) &&
|
||
<div className="mb-2">
|
||
<Input
|
||
className="w-[20rem] rounded-sm !text-[1.3rem] focus-visible:ring-0 focus-visible:ring-offset-0"
|
||
value={refColumnSearchValue}
|
||
onChange={(e) => handleSearchColumn(e.target.value, 'ref')}
|
||
placeholder="검색어를 입력하세요."
|
||
/>
|
||
</div>
|
||
}
|
||
{showRefColumns ? (
|
||
<div className="flex flex-wrap gap-2">
|
||
{(filterdRefColumns?.length ?? 0) > 0 ?
|
||
filterdRefColumns.map((r) => (
|
||
<Button
|
||
key={r.engColNm}
|
||
type="button"
|
||
value={r.engColNm}
|
||
size="sm"
|
||
color="sky"
|
||
disabled={isUserDirectInputMode}
|
||
onClick={() => handleFormulaColumn(r.kornColNm, r.engColNm)}
|
||
>
|
||
{r.kornColNm}
|
||
</Button>
|
||
))
|
||
:
|
||
null
|
||
}
|
||
</div>
|
||
) : null}
|
||
</div>
|
||
</div>
|
||
<DialogFooter>
|
||
<Button
|
||
size="lg"
|
||
type="button"
|
||
onClick={() => {
|
||
if (isUserDirectInputMode) {
|
||
setFormulaSaveError(null);
|
||
const raw = formulaDisplaySegments.join("");
|
||
const wrapped = wrapWithBacktick(raw);
|
||
const isEmptyFormula = raw.trim().length === 0;
|
||
onConfirm?.({
|
||
kornArtopnEqtnCn: isEmptyFormula ? raw : wrapped,
|
||
engArtopnEqtnCn: isEmptyFormula ? raw : wrapped,
|
||
refStatsCd: isEmptyFormula
|
||
? null
|
||
: refStatsCdLocal
|
||
? refStatsCdLocal
|
||
: null,
|
||
});
|
||
onOpenChange?.(false);
|
||
return;
|
||
}
|
||
const err = validateFormulaForSave(formulaValueSegments);
|
||
if (err) {
|
||
setFormulaSaveError(err);
|
||
requestAnimationFrame(() => {
|
||
formulaTextareaRef.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||
formulaTextareaRef.current?.focus?.();
|
||
});
|
||
return;
|
||
}
|
||
setFormulaSaveError(null);
|
||
const kornArtopnEqtnCn = formulaDisplaySegments.join('');
|
||
const engArtopnEqtnCn = getFormulaValueForSubmit();
|
||
const isEmptyFormula = kornArtopnEqtnCn.trim().length === 0;
|
||
onConfirm?.({
|
||
kornArtopnEqtnCn,
|
||
engArtopnEqtnCn,
|
||
refStatsCd: isEmptyFormula ? null : (refStatsCdLocal ? refStatsCdLocal : null),
|
||
});
|
||
onOpenChange?.(false);
|
||
}}
|
||
>
|
||
확인
|
||
</Button>
|
||
<DialogClose asChild>
|
||
<Button size="lg" color="white">
|
||
취소
|
||
</Button>
|
||
</DialogClose>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
);
|
||
};
|
||
|
||
export default FomulaDialog; |