feat(sn): CS 기준 UI 통일 및 지도 팝업 표준화

This commit is contained in:
2026-08-20 14:57:20 +09:00
parent c9e3ff0d91
commit 0cbbc3b934
167 changed files with 21191 additions and 14161 deletions
@@ -8,8 +8,8 @@
* - 고정 위치 및 z-index를 통한 최상위 레이어 배치
* - 조건부 렌더링을 통한 성능 최적화
*/
import React from 'react';
import { LoadingWithAnimation } from '@common/components/ui/loading';
import React from "react";
import { LoadingWithAnimation } from "@common/components/ui/loading";
interface LoadingOverlayProps {
isLoading: boolean;
@@ -19,12 +19,13 @@ const LoadingOverlay: React.FC<LoadingOverlayProps> = ({ isLoading }) => {
if (!isLoading) return null;
return (
<div className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50">
<div className="relative w-16 h-16">
// 화면을 차단하는 로딩 오버레이는 배경 콘텐츠를 가리는 의미색이므로 반투명 검정을 유지한다.
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
<div className="relative h-16 w-16">
<LoadingWithAnimation color="primary" />
</div>
</div>
);
};
export default LoadingOverlay;
export default LoadingOverlay;
@@ -10,7 +10,7 @@
* - 콜백 함수를 통한 선택 값 전달
*/
import React from "react";
import { SelectBox } from '@common/business_components/ui'
import { SelectBox } from "@common/business_components/ui";
interface YearRangeSelectBoxProps {
start: string;
@@ -37,11 +37,11 @@ export function getStartYearArray({
endYear?: string;
} = {}) {
const years = Array.from({ length: maxYear - minYear + 1 }, (_, i) =>
(maxYear - i).toString()
).filter(y => !endYear || parseInt(y) <= parseInt(endYear));
(maxYear - i).toString(),
).filter((y) => !endYear || parseInt(y) <= parseInt(endYear));
return [
{ val: "0", text: placeholder },
...years.map(y => ({ val: y, text: y })),
...years.map((y) => ({ val: y, text: y })),
];
}
@@ -58,11 +58,11 @@ export function getEndYearArray({
startYear?: string;
} = {}) {
const years = Array.from({ length: maxYear - minYear + 1 }, (_, i) =>
(maxYear - i).toString()
).filter(y => !startYear || parseInt(y) >= parseInt(startYear));
(maxYear - i).toString(),
).filter((y) => !startYear || parseInt(y) >= parseInt(startYear));
return [
{ val: "9999", text: placeholder },
...years.map(y => ({ val: y, text: y })),
...years.map((y) => ({ val: y, text: y })),
];
}
@@ -75,50 +75,50 @@ export function YearRangeSelectBox({
minYear = 1900,
maxYear = new Date().getFullYear(),
className = "",
selectClass = "rounded-lg bg-white flex-shrink-0 w-[70px]"
selectClass = "rounded-lg bg-background flex-shrink-0 w-[70px]",
}: YearRangeSelectBoxProps) {
// 시작년도 배열
const getStartYearArray = () => {
const years = Array.from({ length: maxYear - minYear + 1 }, (_, i) =>
(maxYear - i).toString()
).filter(y => !end || parseInt(y) <= parseInt(end));
(maxYear - i).toString(),
).filter((y) => !end || parseInt(y) <= parseInt(end));
return [
{ val: "0", text: "전체" },
...years.map(y => ({ val: y, text: y })),
...years.map((y) => ({ val: y, text: y })),
];
};
// 종료년도 배열
const getEndYearArray = () => {
const years = Array.from({ length: maxYear - minYear + 1 }, (_, i) =>
(maxYear - i).toString()
).filter(y => !start || parseInt(y) >= parseInt(start));
(maxYear - i).toString(),
).filter((y) => !start || parseInt(y) >= parseInt(start));
return [
{ val: "9999", text: "전체" },
...years.map(y => ({ val: y, text: y })),
...years.map((y) => ({ val: y, text: y })),
];
};
return (
<div className={`flex items-center mr-8 ${className}`}>
<div className={`mr-8 flex items-center ${className}`}>
<SelectBox
className="flex-1"
className="flex-1"
selectClass={selectClass}
label={startLabel}
selectArray={getStartYearArray()}
onSelectValue={val => onChange({ start: String(val), end })}
onSelectValue={(val) => onChange({ start: String(val), end })}
value={start}
selectContentClass="z-[101]"
/>
<span className="font-semibold text-xl mx-2">~</span>
<span className="mx-2 text-xl font-semibold">~</span>
<SelectBox
className="flex-1"
selectClass={selectClass}
label={endLabel}
selectArray={getEndYearArray()}
onSelectValue={val => onChange({ start, end: String(val) })}
onSelectValue={(val) => onChange({ start, end: String(val) })}
value={end}
selectContentClass="z-[101]"
/>
</div>
);
}
}
@@ -8,16 +8,15 @@
* - 로딩 상태 관리 및 에러 핸들링
* - Zustand를 통한 시도/시군구 데이터 관리
* - CQL 필터를 통한 시설물 검색 조건 설정
*
*
* 🔗 사용 API
* - 관망도 시설물 목록 조회: GET /api/v1/fclts (sewerage-service)
*/
import React, { useState, useEffect } from "react";
import { SelectBox } from '@common/business_components/ui'
import { Label } from '@common/components';
import useStore from '../../store/useStore';
import { getData } from '@/components/lib/api/index';
import { SelectBox } from "@common/business_components/ui";
import { Label } from "@common/components";
import useStore from "../../store/useStore";
import { getData } from "@/components/lib/api/index";
interface ApiSelectOption {
text: string;
@@ -43,9 +42,9 @@ interface CtpvSggPrcsFcltSelectBoxProps {
selectValueClassName?: string;
}
const defaultOption: ApiSelectOption = { val: '0', text: '전체' };
const defaultOption: ApiSelectOption = { val: "0", text: "전체" };
const buildFacilityDefaultOption = (facilityName: string): ApiSelectOption => ({
val: '0',
val: "0",
text: facilityName || defaultOption.text,
});
@@ -66,15 +65,16 @@ export function CtpvSggPrcsFcltSelectBox({
compact = false,
selectValueClassName = "",
}: CtpvSggPrcsFcltSelectBoxProps) {
const [prcsFcltOptions, setPrcsFcltOptions] = useState<ApiSelectOption[]>([]);
const { ctpv, sgg } = useStore();
const sidoStr = String(sido ?? '');
const sidoStr = String(sido ?? "");
const sidoPrefix = sidoStr.slice(0, 2);
const normalizedDefaultFacilityName = String(defaultSwtrmtFcltNm ?? '').trim();
const normalizedDefaultFacilityName = String(
defaultSwtrmtFcltNm ?? "",
).trim();
useEffect(() => {
onSwagePrcsFcltChange?.('0');
onSwagePrcsFcltChange?.("0");
const fetchData = async () => {
if (!sggName) {
@@ -85,25 +85,32 @@ export function CtpvSggPrcsFcltSelectBox({
if (setIsLoading) setIsLoading(true);
try {
const queryParamsFacility = new URLSearchParams({
lyrTypeNm: 'tb_il_swage_prcs_fclt',
page: '0',
size: '100000', // 요청하신 URL에 맞게 50으로 변경 가능
sort: 'string',
lyrTypeNm: "tb_il_swage_prcs_fclt",
page: "0",
size: "100000", // 요청하신 URL에 맞게 50으로 변경 가능
sort: "string",
});
const cqlFiltersFacility: string[] = [];
if (sggName) cqlFiltersFacility.push(`sgg_nm ILIKE '%${sggName}%'`);
if (cqlFiltersFacility.length > 0) queryParamsFacility.append('cqlFiter', cqlFiltersFacility.join(' and '));
if (cqlFiltersFacility.length > 0)
queryParamsFacility.append(
"cqlFiter",
cqlFiltersFacility.join(" and "),
);
const facilityRes = await getData(`v1/fclts?${queryParamsFacility.toString()}`);
const facilityRes = await getData(
`v1/fclts?${queryParamsFacility.toString()}`,
);
const facilities = (facilityRes.data || [])
.map((item: any) => ({
text: item.swtrmtFcltNm,
val: item.fid
val: item.fid,
}))
.sort((a: ApiSelectOption, b: ApiSelectOption) => a.text.localeCompare(b.text, 'ko'));
.sort((a: ApiSelectOption, b: ApiSelectOption) =>
a.text.localeCompare(b.text, "ko"),
);
setPrcsFcltOptions(facilities);
} catch (error) {
console.error("BaseLayout: 지역/시설 데이터 조회 중 오류 발생:", error);
@@ -121,8 +128,9 @@ export function CtpvSggPrcsFcltSelectBox({
if (!selectedSwagePrcsFclt || selectedSwagePrcsFclt !== "0") return;
if (prcsFcltOptions.length === 0) return;
const matchedDefaultFacility = prcsFcltOptions.find((option) =>
String(option.text ?? "").trim() === normalizedDefaultFacilityName,
const matchedDefaultFacility = prcsFcltOptions.find(
(option) =>
String(option.text ?? "").trim() === normalizedDefaultFacilityName,
);
if (!matchedDefaultFacility) return;
@@ -137,47 +145,77 @@ export function CtpvSggPrcsFcltSelectBox({
]);
return (
<div className={`flex items-center justify-center ${className} ${compact ? "mr-0" : "mr-8"}`}>
<Label className={`${compact ? "mr-1.5 text-base" : "mr-2 text-xl"} whitespace-nowrap font-medium text-gray-600`}>시도</Label>
<div
className={`flex items-center justify-center ${className} ${compact ? "mr-0" : "mr-8"}`}
>
<Label
className={`${compact ? "mr-1.5" : "mr-2"} whitespace-nowrap text-[1.3rem] font-medium text-label`}
>
시도
</Label>
<SelectBox
className={compact ? "mr-4 w-[180px]" : "mr-8 w-48"}
selectClass={`${compact ? "w-[180px]" : ""} rounded-lg bg-white ${selectValueClassName}`}
selectClass={`${compact ? "w-[180px]" : ""} rounded-lg bg-background ${selectValueClassName}`}
label=""
selectArray={[defaultOption, ...ctpv]}
value={sido}
onSelectValue={val => {
onSelectValue={(val) => {
onSidoChange(String(val));
if (setCtpvName) setCtpvName(ctpv.find(opt => String(opt.val) === String(val))?.text || "");
if (setCtpvName)
setCtpvName(
ctpv.find((opt) => String(opt.val) === String(val))?.text || "",
);
if (setSwtrmtFcltNm) setSwtrmtFcltNm("");
}}
selectContentClass="z-[101]"
/>
<Label className={`${compact ? "mr-1.5 text-base" : "mr-2 text-xl"} whitespace-nowrap font-medium text-gray-600`}>시군구</Label>
<Label
className={`${compact ? "mr-1.5" : "mr-2"} whitespace-nowrap text-[1.3rem] font-medium text-label`}
>
시군구
</Label>
<SelectBox
className={compact ? "w-36" : "w-48"}
selectClass={`${compact ? "w-36" : "w-48"} truncate rounded-lg bg-white ${selectValueClassName}`}
selectClass={`${compact ? "w-36" : "w-48"} truncate rounded-lg bg-background ${selectValueClassName}`}
label=""
selectArray={[defaultOption, ...sgg.filter(opt => opt.val.startsWith(sidoPrefix))]}
selectArray={[
defaultOption,
...sgg.filter((opt) => opt.val.startsWith(sidoPrefix)),
]}
value={sigungu}
onSelectValue={val => {
onSigunguChange(String(val))
if (setSggName) setSggName(sgg.find(opt => String(opt.val) === String(val))?.text || "");
if (setSwtrmtFcltNm) setSwtrmtFcltNm("")
onSelectValue={(val) => {
onSigunguChange(String(val));
if (setSggName)
setSggName(
sgg.find((opt) => String(opt.val) === String(val))?.text || "",
);
if (setSwtrmtFcltNm) setSwtrmtFcltNm("");
}}
selectContentClass="z-[101]"
/>
{selectedSwagePrcsFclt && onSwagePrcsFcltChange && (
<>
<Label className="text-xl text-gray-600 font-medium whitespace-nowrap ml-8 mr-4">하수처리시설명</Label>
<Label
className={`${compact ? "ml-4 mr-1.5" : "ml-8 mr-4"} whitespace-nowrap text-[1.3rem] font-medium text-label`}
>
하수처리시설명
</Label>
<SelectBox
className="w-[160px]"
selectClass="rounded-lg bg-white truncate"
selectClass={`truncate rounded-lg bg-background ${selectValueClassName}`}
label=""
selectArray={[buildFacilityDefaultOption(normalizedDefaultFacilityName), ...prcsFcltOptions]}
selectArray={[
buildFacilityDefaultOption(normalizedDefaultFacilityName),
...prcsFcltOptions,
]}
value={selectedSwagePrcsFclt}
onSelectValue={(val) => {
onSwagePrcsFcltChange?.(String(val))
if (setSwtrmtFcltNm) setSwtrmtFcltNm(prcsFcltOptions.find(opt => String(opt.val) === String(val))?.text || "")
onSwagePrcsFcltChange?.(String(val));
if (setSwtrmtFcltNm)
setSwtrmtFcltNm(
prcsFcltOptions.find((opt) => String(opt.val) === String(val))
?.text || "",
);
}}
selectContentClass="z-[101]"
/>
+78 -41
View File
@@ -9,16 +9,27 @@
* - 파일 형식 검증 및 미리보기 지원
* - TUS 프로토콜을 통한 대용량 파일 업로드
*/
"use client"
"use client";
import { FileUploader } from "@common/components";
import { Button } from '@common/components/ui';
import { Button } from "@common/components/ui";
import { handleUpload } from "@/components/lib/utils";
import { useId, useState } from 'react';
import { useId, useState } from "react";
import type { HttpResponse, Upload } from "tus-js-client";
import { useAlertStore } from "@/shared/lib";
interface FileUploadFormProps {
onSubmit?: (files: string, year: string, quarter: string, code: string, id: string) => void;
onFileSelect?: (file: File | null, atflCd: string | null, atflId: string | null) => void; // 파일 선택 시 호출될 콜백 추가
onSubmit?: (
files: string,
year: string,
quarter: string,
code: string,
id: string,
) => void;
onFileSelect?: (
file: File | null,
atflCd: string | null,
atflId: string | null,
) => void; // 파일 선택 시 호출될 콜백 추가
showButton?: boolean; // 버튼 표시 여부 (기본값 true)
showPreview?: boolean; // 파일명 프리뷰 표시 여부
accept?: string; // 파일 형식 지정
@@ -31,38 +42,48 @@ const FileUploadForm = ({
showButton = true,
showPreview = false,
accept = ".jpeg, .jpg, .png",
fileIdx // props에서 fileIdx 받기
fileIdx, // props에서 fileIdx 받기
}: FileUploadFormProps) => {
const alert = useAlertStore((state) => state.setMessage);
const [internalAtflCd, setInternalAtflCd] = useState<string | null>(null);
const [internalAtflId, setInternalAtflId] = useState<string | null>(null);
const [currentFile, setCurrentFile] = useState<File | null>(null); // 현재 선택된 파일을 저장할 상태
const [fileName, setFileName] = useState<string>('');
const [fileName, setFileName] = useState<string>("");
const [files, setFiles] = useState<FileList | null>(null);
const [upload, setUpload] = useState<Upload | null>(null);
const uniqueId = useId(); // 각 FileUploadForm 인스턴스에 대한 고유 ID 생성
// FileUploader 컴포넌트를 강제로 재마운트하기 위한 key 상태 추가
const [uploaderKey, setUploaderKey] = useState(0);
const quater = [{ text: '1분기', val: '1' }, { text: '2분기', val: '2' }, { text: '3분기', val: '3' }, { text: '4분기', val: '4' }];
const quater = [
{ text: "1분기", val: "1" },
{ text: "2분기", val: "2" },
{ text: "3분기", val: "3" },
{ text: "4분기", val: "4" },
];
// 현재 년도부터 10년 전까지의 년도 옵션 생성
const yearOptions = Array.from({ length: 10 }, (_, i) => {
const year = new Date().getFullYear() - i;
return { text: `${year}년`, val: year.toString() };
});
const [selectedYear, setSelectedYear] = useState<string>(yearOptions[0]?.val || '');
const [selectedQuarter, setSelectedQuarter] = useState<string>(quater[0]?.val || '');
const [selectedYear, setSelectedYear] = useState<string>(
yearOptions[0]?.val || "",
);
const [selectedQuarter, setSelectedQuarter] = useState<string>(
quater[0]?.val || "",
);
function registFile() {
if (!currentFile) {
alert('파일을 선택해주세요.');
alert("파일을 선택해주세요.");
return;
}
if (!selectedYear) {
alert('등록년도를 선택해주세요.');
alert("등록년도를 선택해주세요.");
return;
}
if (!selectedQuarter) {
alert('분기를 선택해주세요.');
alert("분기를 선택해주세요.");
return;
}
@@ -72,27 +93,36 @@ const FileUploadForm = ({
handleUploadWithResponse(files, currentFile)
.then(({ atflCd, atflId }) => {
// 업로드 완료 후 onSubmit 실행
console.log('fileNm', fileNm);
console.log('selectedYear', selectedYear);
console.log('selectedQuarter', selectedQuarter);
console.log('atflCd', atflCd);
console.log('atflId', atflId);
onSubmit(fileNm, selectedYear, selectedQuarter, atflCd || '', atflId || '');
console.log("fileNm", fileNm);
console.log("selectedYear", selectedYear);
console.log("selectedQuarter", selectedQuarter);
console.log("atflCd", atflCd);
console.log("atflId", atflId);
onSubmit(
fileNm,
selectedYear,
selectedQuarter,
atflCd || "",
atflId || "",
);
// UI 초기화
setFiles(null);
setFileName('');
setUploaderKey(prev => prev + 1);
setFileName("");
setUploaderKey((prev) => prev + 1);
})
.catch((error) => {
console.error('파일 업로드 실패:', error);
alert('파일 업로드 중 오류가 발생했습니다.');
console.error("파일 업로드 실패:", error);
alert("파일 업로드 중 오류가 발생했습니다.");
});
}
}
// handleUpload를 Promise로 감싸는 헬퍼 함수
function handleUploadWithResponse(files: FileList, file: File): Promise<{ atflCd: string | null, atflId: string | null }> {
function handleUploadWithResponse(
files: FileList,
file: File,
): Promise<{ atflCd: string | null; atflId: string | null }> {
return new Promise((resolve, reject) => {
const uploadResponseHandler = async (res: HttpResponse) => {
try {
@@ -102,7 +132,8 @@ const FileUploadForm = ({
return;
}
const { atflCd: newAtflCd, atflId: newAtflId } = JSON.parse(fileInfo) ?? {};
const { atflCd: newAtflCd, atflId: newAtflId } =
JSON.parse(fileInfo) ?? {};
// 내부 상태도 업데이트 (다른 용도로 사용할 수 있음)
setInternalAtflCd(newAtflCd);
@@ -121,11 +152,11 @@ const FileUploadForm = ({
};
const uploadErrorHandler = (error: Error) => {
console.error('Upload failed:', error);
console.error("Upload failed:", error);
reject(error);
};
console.log('Starting upload for files:', files);
console.log("Starting upload for files:", files);
// 기존 handleUpload 유틸리티 사용 (수정하지 않음)
handleUpload(files, {
@@ -136,16 +167,23 @@ const FileUploadForm = ({
});
}
return (
<div> {/* 컴포넌트 루트 div */}
<div className="card p-6"> {/* 카드 스타일링 */}
<div className='flex items-center gap-2'> {/* FileUploader와 Button을 정렬하는 메인 flex 컨테이너 */}
<div className="w-[300px] mr-4"> {/* FileUploader의 너비와 오른쪽 여백을 제어하는 컨테이너 */}
<div>
{" "}
{/* 컴포넌트 루트 div */}
<div className="card p-6">
{" "}
{/* 카드 스타일링 */}
<div className="flex items-center gap-2">
{" "}
{/* FileUploader와 Button을 정렬하는 메인 flex 컨테이너 */}
<div className="mr-4 w-[300px]">
{" "}
{/* FileUploader의 너비와 오른쪽 여백을 제어하는 컨테이너 */}
<FileUploader
key={uploaderKey} // key 추가: 변경 시 컴포넌트 재마운트됨
id={uniqueId}
className="!h-auto !max-w-none flex-row items-center gap-2"
className="!h-auto !max-w-none flex-row items-center gap-2 [&_.file-uploader-label]:h-[3.2rem]"
accept={accept}
onUpload={(e) => {
const selectedFiles = e.target.files;
@@ -167,9 +205,9 @@ const FileUploadForm = ({
setFileName(firstFile.name);
setCurrentFile(firstFile);
console.log('selectedFiles', selectedFiles);
console.log('firstFile', firstFile);
console.log('firstFile name', firstFile.name);
console.log("selectedFiles", selectedFiles);
console.log("firstFile", firstFile);
console.log("firstFile name", firstFile.name);
if (onFileSelect) {
onFileSelect(firstFile, internalAtflCd, internalAtflId);
@@ -188,8 +226,7 @@ const FileUploadForm = ({
</div>
{showButton ? ( // showButton이 true일 때만 버튼 렌더링
<Button
className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700"
size="sm"
className="hover:bg-primary/90 rounded-sm bg-primary px-4 py-2 text-sm font-medium text-primary-foreground"
onClick={() => registFile()}
>
등록
@@ -198,7 +235,7 @@ const FileUploadForm = ({
</div>
</div>
</div>
)
}
);
};
export default FileUploadForm
export default FileUploadForm;
@@ -9,23 +9,41 @@
* - 콜백 함수를 통한 업로드 결과 전달
* - TUS 프로토콜을 통한 대용량 파일 업로드
*/
"use client"
import { SelectBox } from '@common/business_components/ui';
import React, { useState, useEffect } from 'react'
import FileUploadForm from './fileUploadForm';
import { yearOptions, getQuarterOptions } from '@/components/lib/utils';
"use client";
import { SelectBox } from "@common/business_components/ui";
import React, { useState, useEffect } from "react";
import FileUploadForm from "./fileUploadForm";
import { yearOptions, getQuarterOptions } from "@/components/lib/utils";
const operFileUploadForm = ({ title, onSubmit }: { title: string, onSubmit: (files: string, year: string, quarter: string, code: string, id: string) => void }) => {
const [selectedYear, setSelectedYear] = useState<string>(yearOptions[0]?.val || '');
const [quaterOptions, setQuaterOptions] = useState(() => getQuarterOptions(selectedYear));
const [selectedQuarter, setSelectedQuarter] = useState<string>(quaterOptions[0]?.val || '');
const operFileUploadForm = ({
title,
onSubmit,
}: {
title: string;
onSubmit: (
files: string,
year: string,
quarter: string,
code: string,
id: string,
) => void;
}) => {
const [selectedYear, setSelectedYear] = useState<string>(
yearOptions[0]?.val || "",
);
const [quaterOptions, setQuaterOptions] = useState(() =>
getQuarterOptions(selectedYear),
);
const [selectedQuarter, setSelectedQuarter] = useState<string>(
quaterOptions[0]?.val || "",
);
// 년도가 변경될 때 분기 옵션 업데이트
useEffect(() => {
const updatedQuarterOptions = getQuarterOptions(selectedYear);
setQuaterOptions(updatedQuarterOptions);
// 분기 옵션이 변경되면 첫 번째 옵션으로 자동 선택
setSelectedQuarter(updatedQuarterOptions[0]?.val || '');
setSelectedQuarter(updatedQuarterOptions[0]?.val || "");
}, [selectedYear]);
// 년도 변경 핸들러
@@ -36,15 +54,15 @@ const operFileUploadForm = ({ title, onSubmit }: { title: string, onSubmit: (fil
return (
<div>
<div className='card-header'>
<div className="card-header">
<h3 className="text-2xl font-medium">{title}</h3>
</div>
<div className="card p-6">
<div className="grid grid-col-2 items-center space-x-4">
<div className='flex'>
<div className="grid-col-2 grid items-center space-x-4">
<div className="flex">
<SelectBox
className="w-50 mr-3 ml-4"
selectClass="rounded-lg bg-white"
className="w-50 ml-4 mr-3"
selectClass="rounded-lg bg-background"
label="년도"
selectArray={yearOptions}
onSelectValue={handleYearChange}
@@ -52,24 +70,33 @@ const operFileUploadForm = ({ title, onSubmit }: { title: string, onSubmit: (fil
/>
<SelectBox
className="w-50"
selectClass="rounded-lg bg-white"
selectClass="rounded-lg bg-background"
label="분기"
selectArray={quaterOptions}
onSelectValue={(value: string | number) => setSelectedQuarter(String(value))}
onSelectValue={(value: string | number) =>
setSelectedQuarter(String(value))
}
value={selectedQuarter}
/>
<FileUploadForm
onSubmit={(files, year, quarter, code, id) => {
onSubmit(files, (selectedYear ?? year) || '', (selectedQuarter ?? quarter) || '', code, id);
onSubmit(
files,
(selectedYear ?? year) || "",
(selectedQuarter ?? quarter) || "",
code,
id,
);
}}
showButton={true}
showPreview={true}
accept={""} />
accept={""}
/>
</div>
</div>
</div>
</div>
)
}
);
};
export default operFileUploadForm
export default operFileUploadForm;
+12 -9
View File
@@ -12,11 +12,15 @@
import { Button } from "@common/components/ui";
import toast from "react-hot-toast";
export const confirmToast = (content: string, saveFunc: () => void, contentClass?:string) => {
export const confirmToast = (
content: string,
saveFunc: () => void,
contentClass?: string,
) => {
toast(
(t) => (
<span className="flex flex-col items-center">
<div className={`mb-6 ${contentClass}`} >{content}</div>
<div className={`mb-6 ${contentClass}`}>{content}</div>
<div className="flex flex-row space-x-2">
<Button
size={"sm"}
@@ -36,7 +40,7 @@ export const confirmToast = (content: string, saveFunc: () => void, contentClass
{
id: "global-confirm-toast", // 중복 토스트 방지
duration: Infinity, // 자동 사라짐 방지
}
},
);
};
@@ -44,16 +48,15 @@ export const showConfirmToast = (message: string) => {
toast.custom(
(t) => (
<div
className={`w-[500px] min-h-[140px] bg-white shadow-lg rounded-xl p-6 border border-gray-200
${t.visible ? "animate-enter" : "animate-leave"}`}
className={`min-h-[140px] w-[500px] rounded-xl border border-border bg-background p-6 shadow-lg ${t.visible ? "animate-enter" : "animate-leave"}`}
>
<div className="text-3xl font-extrabold text-red-600 bg-yellow-100 px-4 py-2 rounded-md shadow-md">
<div className="rounded-md bg-yellow-100 px-4 py-2 text-3xl font-extrabold text-red-600 shadow-md">
{message}
</div>{" "}
<div className="flex justify-end gap-2">
<Button
size={"sm"}
className="px-4 py-1.5 rounded bg-gray-200 text-sm hover:bg-gray-300"
className="rounded bg-secondary px-4 py-1.5 text-sm text-secondary-foreground hover:bg-accent"
onClick={() => toast.dismiss(t.id)}
>
확인완료
@@ -61,6 +64,6 @@ export const showConfirmToast = (message: string) => {
</div>
</div>
),
{ duration: Infinity }
{ duration: Infinity },
); // 수동 닫기
};
};
+126 -52
View File
@@ -10,10 +10,14 @@
* - 폼 데이터 변경 콜백 및 저장 기능
*/
import UiPageNations from "@common/business_components/ui/table/uiPageNations";
import { Table, TableBody, TableCell, TableRow, Button } from "@common/components";
import {
Button,
Table,
TableBody,
TableCell,
TableRow,
} from "@common/components";
import { useEffect, useState } from "react";
import { confirmToast, showConfirmToast } from '@/components/ui/toast'
import { toast, Toaster } from "react-hot-toast";
type UiTableProps = {
headName: React.ReactNode | undefined;
@@ -34,7 +38,9 @@ type UiTableProps = {
pageSize2?: number;
total2?: number;
children2?: Record<string, React.ReactNode> | undefined;
cellClick2?: ((index: number | undefined, headId: string) => void) | undefined;
cellClick2?:
| ((index: number | undefined, headId: string) => void)
| undefined;
onPageChange2?: (page: number) => void;
className2?: string;
resetPageNo2?: boolean;
@@ -42,7 +48,9 @@ type UiTableProps = {
showSecondTable?: boolean;
showSaveButton?: boolean;
onSaveClick?: () => void;
onFormDataChange?: (formData: { [key: string]: string | number | boolean }) => void; // 추가
onFormDataChange?: (formData: {
[key: string]: string | number | boolean;
}) => void; // 추가
};
type UiSelectOption =
@@ -68,10 +76,14 @@ type UiHeadProps = {
};
const getSelectOptionValue = (option: UiSelectOption) =>
typeof option === "string" ? option : String(option.value ?? option.val ?? "");
typeof option === "string"
? option
: String(option.value ?? option.val ?? "");
const getSelectOptionLabel = (option: UiSelectOption) =>
typeof option === "string" ? option : String(option.label ?? option.text ?? getSelectOptionValue(option));
typeof option === "string"
? option
: String(option.label ?? option.text ?? getSelectOptionValue(option));
const isSelectOptionHidden = (option: UiSelectOption) =>
typeof option === "string" ? false : Boolean(option.hidden);
@@ -97,7 +109,9 @@ export function VerticalTable({
onFormDataChange,
}: UiTableProps) {
const [cur, setCur] = useState<number>(1);
const [formData, setFormData] = useState<{ [key: string]: string | number | boolean }>({});
const [formData, setFormData] = useState<{
[key: string]: string | number | boolean;
}>({});
const [errors, setErrors] = useState<{ [key: string]: string }>({});
useEffect(() => {
@@ -123,7 +137,7 @@ export function VerticalTable({
setFormData(newFormData);
if (errors[id]) {
setErrors(prev => {
setErrors((prev) => {
const newErrors = { ...prev };
delete newErrors[id];
return newErrors;
@@ -141,9 +155,9 @@ export function VerticalTable({
};
const showError = (fieldId: string, message: string) => {
setErrors(prev => ({
setErrors((prev) => ({
...prev,
[fieldId]: message
[fieldId]: message,
}));
};
@@ -151,39 +165,46 @@ export function VerticalTable({
<>
{headName ? (
<div className="card-header flex items-center justify-between">
<h3 className="text-2xl mx-3 font-medium text-label">{headName}</h3>
<h3 className="mx-3 text-2xl font-medium text-label">{headName}</h3>
{showSaveButton && onSaveClick && (
<Button
onClick={onSaveClick}
className="px-4 mr-3 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700"
>
<Button type="button" color="primary" onClick={onSaveClick}>
저장
</Button>
)}
</div>
) : null}
<div className={`card !m-[1.2rem] !p-0r ${className}`}>
<div className={`card !m-[1.2rem] !p-0 ${className}`}>
{tableName1 && ( // tableName prop이 있으면 표시
<div className="text-xl font-semibold my-2 mx-3">{tableName1}</div>
<div className="mx-3 my-2 text-xl font-semibold">{tableName1}</div>
)}
<Table variant="secondary">
<TableBody className="text-center">
{headlist?.map((head) => (
<TableRow key={head.id}>
{/* 컬럼 제목 */}
<TableCell className={`font-bold bg-blue-100 text-xs w-[120px] whitespace-nowrap`}>
<TableCell className="w-[120px] whitespace-nowrap bg-secondary text-xs font-bold text-label">
{head.title}
{head.required ? <span className="ml-1 text-red-600">*</span> : null}
{head.required ? (
<span className="ml-1 text-red-600">*</span>
) : null}
</TableCell>
{/* 데이터 값 또는 입력 필드 */}
<TableCell className="text-xs">
{children && children[head.id] ? children[head.id] : isEditable ? (
{children && children[head.id] ? (
children[head.id]
) : isEditable ? (
head.type === "select" ? (
<select
id={head.id}
value={formData[head.id] !== undefined ? String(formData[head.id]) : ""}
onChange={(e) => handleInputChange(head.id, e.target.value)}
className="w-full border border-gray-300 rounded-sm px-2 py-1 text-xl border-radius-0"
value={
formData[head.id] !== undefined
? String(formData[head.id])
: ""
}
onChange={(e) =>
handleInputChange(head.id, e.target.value)
}
className="border-radius-0 w-full rounded-sm border border-border px-2 py-1 text-xl"
>
{head.options?.map((option, optionIndex) => {
const optionValue = getSelectOptionValue(option);
@@ -215,35 +236,51 @@ export function VerticalTable({
const isValidNumber = /^[0-9]+$/.test(newValue);
if (!isValidNumber) {
showError(head.id, `${head.title}는 숫자만 입력 가능합니다.`);
showError(
head.id,
`${head.title}는 숫자만 입력 가능합니다.`,
);
return;
}
if (head.length && newValue.length > head.length) {
showError(head.id, `${head.title}는 최대 ${head.length}자까지 입력 가능합니다.`);
if (
head.length &&
newValue.length > head.length
) {
showError(
head.id,
`${head.title}는 최대 ${head.length}자까지 입력 가능합니다.`,
);
return;
}
const numericValue = parseInt(newValue);
if (isNaN(numericValue) || numericValue < 0) return;
if (isNaN(numericValue) || numericValue < 0)
return;
handleInputChange(head.id, numericValue);
} else {
const newValue = e.target.value;
if (head.length && newValue.length > head.length) {
showError(head.id, `${head.title}는 최대 ${head.length}자까지 입력 가능합니다.`);
if (
head.length &&
newValue.length > head.length
) {
showError(
head.id,
`${head.title}는 최대 ${head.length}자까지 입력 가능합니다.`,
);
return;
}
handleInputChange(head.id, e.target.value);
}
}}
className="w-full text-xl border-radius-0 border border-gray-300 rounded-sm px-2 py-1"
className="border-radius-0 w-full rounded-sm border border-border px-2 py-1 text-xl"
placeholder={head.placeholder}
/>
{errors[head.id] && (
<div className="text-red-500 font-bold text-xl mt-1 text-left">
<div className="mt-1 text-left text-xl font-bold text-red-500">
{errors[head.id]}
</div>
)}
@@ -260,7 +297,9 @@ export function VerticalTable({
</TableBody>
</Table>
{tableName2 && ( // tableName prop이 있으면 표시
<div className="text-xl font-semibold mt-8 my-2 mx-3">{tableName2}</div>
<div className="mx-3 my-2 mt-8 text-xl font-semibold">
{tableName2}
</div>
)}
{showSecondTable && (
<Table variant="secondary">
@@ -268,19 +307,29 @@ export function VerticalTable({
{headlist2?.map((head) => (
<TableRow key={head.id}>
{/* 컬럼 제목 */}
<TableCell className={`font-bold bg-blue-100 text-xs w-[120px] whitespace-nowrap`}>
{head.title}
{head.required ? <span className="ml-1 text-red-600">*</span> : null}
</TableCell>
<TableCell className="w-[120px] whitespace-nowrap bg-secondary text-xs font-bold text-label">
{head.title}
{head.required ? (
<span className="ml-1 text-red-600">*</span>
) : null}
</TableCell>
{/* 데이터 값 또는 입력 필드 */}
<TableCell className="text-xs">
{children && children[head.id] ? children[head.id] : isEditable2 ? (
{children && children[head.id] ? (
children[head.id]
) : isEditable2 ? (
head.type === "select" ? (
<select
id={head.id}
value={formData[head.id] !== undefined ? String(formData[head.id]) : ""}
onChange={(e) => handleInputChange(head.id, e.target.value)}
className="w-full border border-gray-300 rounded-sm px-2 py-1 text-xl border-radius-0"
value={
formData[head.id] !== undefined
? String(formData[head.id])
: ""
}
onChange={(e) =>
handleInputChange(head.id, e.target.value)
}
className="border-radius-0 w-full rounded-sm border border-border px-2 py-1 text-xl"
>
{head.options?.map((option, optionIndex) => {
const optionValue = getSelectOptionValue(option);
@@ -299,8 +348,18 @@ export function VerticalTable({
<div className="w-full">
<input
id={head.id}
type={head.type === "date" ? "date" : head.isNumber ? "number" : "text"}
value={formData[head.id] !== undefined ? String(formData[head.id]) : ""}
type={
head.type === "date"
? "date"
: head.isNumber
? "number"
: "text"
}
value={
formData[head.id] !== undefined
? String(formData[head.id])
: ""
}
onChange={(e) => {
if (head.isNumber) {
const newValue = e.target.value;
@@ -312,35 +371,51 @@ export function VerticalTable({
const isValidNumber = /^[0-9]+$/.test(newValue);
if (!isValidNumber) {
showError(head.id, `${head.title}는 숫자만 입력 가능합니다.`);
showError(
head.id,
`${head.title}는 숫자만 입력 가능합니다.`,
);
return;
}
if (head.length && newValue.length > head.length) {
showError(head.id, `${head.title}는 최대 ${head.length}자까지 입력 가능합니다.`);
if (
head.length &&
newValue.length > head.length
) {
showError(
head.id,
`${head.title}는 최대 ${head.length}자까지 입력 가능합니다.`,
);
return;
}
const numericValue = parseInt(newValue);
if (isNaN(numericValue) || numericValue < 0) return;
if (isNaN(numericValue) || numericValue < 0)
return;
handleInputChange(head.id, numericValue);
} else {
const newValue = e.target.value;
if (head.length && newValue.length > head.length) {
showError(head.id, `${head.title}는 최대 ${head.length}자까지 입력 가능합니다.`);
if (
head.length &&
newValue.length > head.length
) {
showError(
head.id,
`${head.title}는 최대 ${head.length}자까지 입력 가능합니다.`,
);
return;
}
handleInputChange(head.id, e.target.value);
}
}}
className="w-full text-xl border-radius-0 border border-gray-300 rounded-sm px-2 py-1"
className="border-radius-0 w-full rounded-sm border border-border px-2 py-1 text-xl"
placeholder={head.placeholder}
/>
{errors[head.id] && (
<div className="text-red-500 font-bold text-xl mt-1 text-left">
<div className="mt-1 text-left text-xl font-bold text-red-500">
{errors[head.id]}
</div>
)}
@@ -366,7 +441,6 @@ export function VerticalTable({
/>
)}
</div>
<Toaster position="top-center"></Toaster>
</>
);
}