dm_new menu

This commit is contained in:
dongsilove
2026-02-18 22:11:12 +09:00
parent f621f4dfa1
commit 7a91fcbd80
74 changed files with 9010 additions and 13 deletions
+99
View File
@@ -0,0 +1,99 @@
//8880
import { AUTH_USER_ID, CLAIM_NAME } from "@/src/shared/config";
import { getCookie } from "@common/components/lib/cookie";
const tokenId = getCookie(AUTH_USER_ID);
const Authorization = getCookie(CLAIM_NAME);
export const fetchType = {
COMMON: "common",
WR: "wr",
FO: "fo",
SN: "sn"
};
const API_VERSION = "/api/v1"
const servers = {
common: "",
local: "",
fo: "/operation-service" + API_VERSION,
wr: "/reuse-service" + API_VERSION,
sn: "/sewerage-service" + API_VERSION,
}
interface RequestParams {
[key: string]: unknown;
}
export const getFetch = async (type: string, url: string) => {
const baseUrl = servers[type];
const response = await fetch(baseUrl + url, {
method: "GET",
headers: {
accept: "application/json",
[AUTH_USER_ID]: tokenId ?? "",
[CLAIM_NAME]: Authorization ?? "",
},
});
if (!response.ok) {
throw new Error(`오류 발생: ${response.status}`);
}
const res = await response.json();
return res;
};
export const postFetch = async (url: string, params: RequestParams) => {
const baseUrl = servers[fetchType.WR];
const response = await fetch(baseUrl + url, {
method: "POST",
headers: {
"Content-Type": "application/json",
[AUTH_USER_ID]: tokenId ?? "",
[CLAIM_NAME]: Authorization ?? "",
},
body: JSON.stringify(params),
});
if (!response.ok) {
throw new Error(`오류 발생: ${response.status}`);
}
return response;
};
export const putFetch = async (url: string, params: RequestParams) => {
const baseUrl = servers[fetchType.WR];
const response = await fetch(baseUrl + url, {
method: "PUT",
headers: {
"Content-Type": "application/json",
[AUTH_USER_ID]: tokenId ?? "",
[CLAIM_NAME]: Authorization ?? "",
},
body: JSON.stringify(params),
});
if (!response.ok) {
throw new Error(`오류 발생: ${response.status}`);
}
return response;
};
export const deleteFetch = async (url: string, params: RequestParams) => {
const baseUrl = servers[fetchType.WR];
const response = await fetch(baseUrl + url, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
[AUTH_USER_ID]: tokenId ?? "",
[CLAIM_NAME]: Authorization ?? "",
},
body: JSON.stringify(params),
});
if (!response.ok) {
throw new Error(`오류 발생: ${response.status}`);
}
return response;
};
@@ -0,0 +1,103 @@
import { useDmStore } from '@/app/store';
import type { DemandCompType } from '@common/business_components/ui/sdmInsertForm/form';
import React, { useCallback, useEffect, useRef, useState } from 'react';
type thisProps = {
label: string | undefined;
initValue: string | undefined;
setValue : (dmdCoNm?: string) => void;
setRtnData : (rtnData: DemandCompType[]) => void;
}
export default function SearchInputText({label=undefined, initValue=undefined, setValue=()=>{}, setRtnData=()=>{}} :thisProps) {
const { getDemandCompList, Sdm } = useDmStore((state) => state);
const {
demandCompList
} = Sdm;
const [isOpen, setIsOpen] = useState(false);
const [textValue, setTextValue] = useState(initValue || '');
const wrapperRef = useRef<HTMLDivElement>(null);
const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setTextValue(value);
setValue(value);
if (value) {
setIsOpen(true);
getDemandCompList(value, 20);
} else {
setIsOpen(false);
}
}, [getDemandCompList, setValue]);
const handleSuggestionClick = useCallback((dmdCoNm: string) => {
setTextValue(dmdCoNm);
setValue(dmdCoNm);
setIsOpen(false);
setRtnData(demandCompList);
}, [demandCompList, setRtnData, setValue]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
return (
<div ref={wrapperRef}>
<input
type="text"
value={textValue}
onChange={handleInputChange}
/* onFocus={() => setIsOpen(true)} */
className="w-full h-[3.2rem] !text-xl pl-3 text-gray-600 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder={`${label}을(를) 입력하세요`}
/>
{isOpen && (
<div className=" z-1 w-full mt-2 bg-white border border-gray-300 rounded-md shadow-lg h-90 overflow-auto">
<div className="max-h-72">
{demandCompList && demandCompList.length > 0 ? demandCompList.map((item : DemandCompType, index : number) => (
<div
key={index}
className="!text-xl w-full text-left px-5 py-3 hover:bg-gray-100 cursor-pointer overflow-auto"
onClick={() => handleSuggestionClick(item.dmdCoNm)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
handleSuggestionClick(item.dmdCoNm);
}
}}
>
{item.dmdInfoId.substring(10,14) !== '0000' ? (
<>
<span className="text-gray-500">사업자번호 : </span> {item.dmdInfoId.substring(0,10)}&nbsp;
<span className="text-gray-500">종사업자번호 : </span> {item.dmdInfoId.substring(10,14)}&nbsp;
</>
) : (
<>
<span className="text-gray-500">사업자번호 : </span> {item.dmdInfoId.substring(0,10)}&nbsp;
</>
)}
<span className="float-right">{item.dmdCoNm}</span>
</div>
)) : (
<div className="!text-xl w-full px-5 py-3 hover:bg-gray-100 cursor-pointer overflow-auto">
검색 결과가 없습니다.
</div>
)}
</div>
</div>
)}
</div>
)
}
@@ -0,0 +1,54 @@
export const sanitizeInput = (val: string, allowDecimal = false) => {
if (val === "") return ""; // 빈 값 허용
// 소숫점 허용
if (allowDecimal) {
// 숫자와 점만 허용
let cleaned = val.replace(/[^0-9.]/g, "");
// 소숫점 여러 개일 경우 첫 번째만 유지
const parts = cleaned.split(".");
if (parts.length > 2) {
cleaned = parts[0] + "." + parts.slice(1).join("");
}
return cleaned;
}
// 정수만 허용
return val.replace(/[^0-9]/g, "");
};
// utils: format Date <-> "YYYY-MM-DD" without moment
export const formatDateToYMD=(value: Date): string => {
if (!value) return "";
// value can be Date | string ("YYYY-MM-DD")
if (typeof value === "string") {
// assume already in yyyy-mm-dd
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
const d = new Date(value);
if (isNaN(d.getTime())) return "";
return toYMD(d);
}
if (value instanceof Date) {
if (isNaN(value.getTime())) return "";
return toYMD(value);
}
return "";
}
const toYMD=(date: Date): string => {
// avoid timezone shift by normalizing to local date parts
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
return `${y}-${m}-${day}`;
}
// const parseYMDToDate=(ymd: string): Date | null => {
// if (!/^\d{4}-\d{2}-\d{2}$/.test(ymd)) return null;
// const [y, m, d] = ymd.split("-").map(Number);
// const date = new Date(y, (m - 1), d);
// // validate round-trip
// return (date.getFullYear() === y && date.getMonth() === m - 1 && date.getDate() === d) ? date : null;
// }
@@ -0,0 +1,6 @@
import { PROXY_HOST } from "@/src/shared/config/env";
export const LOCAL_URL = PROXY_HOST;
export const DEV_URL_FO = "/operation-service";
export const DEV_URL_WR = "/reuse-service";
export const DEV_URL_SN = "/sewerage-service";
@@ -0,0 +1,139 @@
import React, { useCallback, useEffect, useRef, useState } from "react";
type SearchType = {
bscFctNm: string;
bscFctCd: string;
};
type thisProps = {
label: string | undefined;
initValue: string | undefined;
setValue: (searchNm?: string) => void;
setRtnData: (rtnData: any) => void;
searchList?: SearchType[];
};
export default function SearchInputText({
label = undefined,
initValue = undefined,
setValue = () => {},
setRtnData = () => {},
searchList = [],
}: thisProps) {
const [isOpen, setIsOpen] = useState(false);
const [textValue, setTextValue] = useState(initValue || "");
const [highlightIndex, setHighlightIndex] = useState<number>(-1);
const wrapperRef = useRef<HTMLDivElement>(null);
const handleInputChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
setTextValue(value);
setValue(value);
setHighlightIndex(-1);
setIsOpen(value !== "");
},
[setValue]
);
const handleSuggestionClick = useCallback(
(searchNm: string) => {
setValue(searchNm);
setTextValue(searchNm);
setIsOpen(false);
setRtnData(searchList?.find((item) => item.bscFctNm === searchNm) || {});
},
[searchList, setRtnData, setValue]
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLInputElement>) => {
if (!isOpen || searchList.length === 0) return;
if (e.key === "ArrowDown") {
e.preventDefault();
setHighlightIndex((prev) => (prev + 1) % searchList.length);
} else if (e.key === "ArrowUp") {
e.preventDefault();
setHighlightIndex((prev) =>
prev <= 0 ? searchList.length - 1 : prev - 1
);
} else if (e.key === "Enter") {
e.preventDefault();
if (searchList.length === 1 && searchList[0]) {
handleSuggestionClick(searchList[0].bscFctNm);
} else if (highlightIndex >= 0 && highlightIndex < searchList.length && searchList[highlightIndex]) {
handleSuggestionClick(searchList[highlightIndex].bscFctNm);
}
}
},
[highlightIndex, isOpen, searchList, handleSuggestionClick]
);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
wrapperRef.current &&
!wrapperRef.current.contains(event.target as Node)
) {
setIsOpen(false);
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
return (
<div ref={wrapperRef} className="relative">
<input
type="text"
value={textValue || ""}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
className="w-full h-[3.2rem] !text-xl pl-3 text-gray-600 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
placeholder={`${label}을(를) 입력하세요`}
onClick={() => {
setTextValue("");
setValue("");
setIsOpen(false);
}}
/>
{isOpen && (
<div className="absolute top-full left-0 z-50 mb-2 max-h-72 w-full overflow-auto rounded-md border border-gray-300 bg-white shadow-lg">
<div className="max-h-72">
{searchList.length > 0 ? (
searchList.map((item, index) => (
<div
key={index}
className={`w-full cursor-pointer overflow-auto px-5 py-3 text-left !text-xl ${
highlightIndex === index
? "bg-blue-100"
: "hover:bg-gray-100"
}`}
onClick={() => handleSuggestionClick(item.bscFctNm)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
handleSuggestionClick(item.bscFctNm);
}
}}
>
<span className="float-left">{item.bscFctNm}</span>
</div>
))
) : (
<div className="!text-xl w-full px-5 py-3 hover:bg-gray-100 cursor-pointer overflow-auto">
검색 결과가 없습니다.
</div>
)}
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,118 @@
"use client";
import { useDmStore } from "@/app/store";
import {
SelectBox,
type SelectDataType,
} from "@common/business_components/ui";
import { Button, Label } from "@common/components/ui";
import { useCallback, useEffect, useState } from "react";
import SearchInputText from "../SearchInputText/SearchInputText";
export function SearchBar({
setHasuPk,
onApply,
}: {
setHasuPk: (hasuPk: any) => void;
onApply: () => void;
}) {
const { map, Common, initializeCommonData, findRuseFclt } = useDmStore(
(state) => state
);
const [sidoValue, setSidoValue] = useState<string>("");
const [sigunValue, setSigunValue] = useState<string>("");
const [filteredSigunData, setFilteredSigunData] = useState<SelectDataType[]>([
{ text: "전체", val: "0" },
]);
useEffect(() => {
initializeCommonData();
}, [initializeCommonData]);
const initializeSigunData = useCallback(
(sidoCd: string) => {
if (sidoCd === "0") {
setSigunValue("0");
setFilteredSigunData([{ text: "전체", val: "0" }]);
} else {
const newFilteredData = [
{ text: "전체", val: "0" },
...Common.selectSigunData.filter(
(item: SelectDataType) => item.val.substring(0, 2) === sidoCd
),
];
setSigunValue("0");
setFilteredSigunData(newFilteredData);
}
},
[Common.selectSigunData]
);
const onSelectValue = useCallback(
(val: string, type: string) => {
switch (type) {
case "ctpvCd":
initializeSigunData(val);
setSidoValue(val);
break;
case "sggCd":
setSigunValue(val);
}
},
[initializeSigunData]
);
return (
<div className="flex justify-center w-full px-4 py-3">
<div className="flex items-center w-full max-w-screen-lg rounded-xl bg-white shadow-md px-6 py-4 space-x-3">
<SelectBox
labelClass="w-[40px]"
className="w-[200px]"
label="시도"
selectClass="rounded-lg bg-white"
selectArray={Common.selectSidoData || []}
onSelectValue={(val) => onSelectValue(val.toString(), "ctpvCd")}
value={sidoValue || Common.selectSidoData[0]?.val || ""}
/>
<SelectBox
labelClass="w-[65px]"
className="w-[200px]"
label="시군구"
selectClass="rounded-lg bg-white"
selectArray={filteredSigunData || []}
onSelectValue={(val) => onSelectValue(val.toString(), "sggCd")}
value={sigunValue}
/>
<Label className="text-gray-600">하수재이용시설</Label>
<SearchInputText
label="시설명"
initValue={undefined}
setValue={(searchNm?: string) => {
let sggOrCity = "";
if (searchNm) {
if (sigunValue === "0" || sigunValue === "") {
sggOrCity = sidoValue;
} else {
sggOrCity = sigunValue;
}
findRuseFclt(sggOrCity, searchNm);
}
}}
setRtnData={(rtnData: any) => {
setHasuPk(rtnData);
}}
searchList={map.ruseFcltList || []}
/>
<Button
color="sky"
className="ml-2 text-white"
size="sm"
onClick={() => {
onApply();
}}
>
적용
</Button>
</div>
</div>
);
}
@@ -0,0 +1,35 @@
import { FormUi } from "@common/business_components/ui";
import type { ControllerRenderProps, FieldError, FieldValues, Path } from "react-hook-form";
import { cloneElement, isValidElement } from "react";
interface AccessibleFormFieldProps<T extends FieldValues> {
field: ControllerRenderProps<T, Path<T>>;
label: string;
required?: boolean;
error?: FieldError;
isDisabled?: boolean;
inputComponent: React.ReactElement<{ disabled?: boolean }>;
}
export function AccessibleFormField<T extends FieldValues>({
label,
required = false,
inputComponent,
isDisabled = false,
}: AccessibleFormFieldProps<T>) {
const labelText = required ? `${label} *` : label;
return (
<FormUi label={labelText} isDisabled={isDisabled}>
<div>
{isValidElement(inputComponent)
? cloneElement(inputComponent, { disabled: isDisabled } as Partial<typeof inputComponent.props>)
: inputComponent}
{/* {error?.message && Array.from(new Set(error.message.split('\n'))).map((msg, idx) => (
<p key={idx} className="text-red-500 text-sm mt-1" role="alert">
{msg}
</p>
))} */}
</div>
</FormUi>
);
}
@@ -0,0 +1,962 @@
import ModalSimilarPage from "@/app/(base-layout)/pages/sdmMng/sdmInfoInsert/modalSimilar/page";
import { useDmStore } from "@/app/store";
import {
CANDIDATE,
// DatePicker,
FormField,
FormLabel,
FormUi,
SelectBox,
UiModal,
} from "@common/business_components";
import { Input } from "@common/components";
import { Button, Label } from "@common/components/ui";
import { useSearchParams } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import { AccessibleFormField } from "./AccessibleFormField";
import {
type ControllerRenderProps,
type UseFormReturn,
type FieldError,
useWatch,
} from "react-hook-form";
import SearchInputText from "../common/searhDemandInput/component";
import React from "react";
import { formatDateToYMD, sanitizeInput } from "../common/utils/utils";
import type { DemandCompType } from "@common/business_components/ui/sdmInsertForm/form";
import type { SdmInfoFormData } from "@/app/store/sdmMng";
export interface SdmInfoRegFormProps {
form: UseFormReturn<SdmInfoFormData>;
onCheckboxChange?: (checked: boolean) => void;
facilityName?: string;
}
type FieldComponent = (
field: ControllerRenderProps<SdmInfoFormData, keyof SdmInfoFormData>
) => React.ReactElement<{ disabled?: boolean }>;
export function SdmInfoRegForm({
form,
onCheckboxChange,
facilityName,
}: SdmInfoRegFormProps) {
const { initializeCommonData, Sdm } = useDmStore((state) => state);
const { useTypesData, defaultRules, disableRules } = Sdm;
const searchParams = useSearchParams();
const [sdmNmValue, setSdmNmValue] = useState<string>(
searchParams.get("dmdCoNm") || ""
);
const [frontPHdata, setFrontPHdata] = useState("0");
const [backPHdata, setBackPHdata] = useState("0");
const [isBznmTotNoDisabled, setIsBznmTotNoDisabled] = useState(false);
const [isSimilarCase, setIsSimilarCase] = useState(false);
const [key, setKey] = useState(0);
// 후보지 팝업 오픈 상태
//모달 조회에 필요한 데이터
const [sply, setSply] = useState<number>(0);
const [usageCd, setUsageCd] = useState<string>("청소");
const [money, setMoney] = useState<number>(0);
useEffect(() => {
initializeCommonData();
}, [initializeCommonData]);
useEffect(() => {
console.log("candidateTitle ", form.getValues("candidateTitle"));
}, [form.getValues]);
useEffect(() => {
if (useTypesData && useTypesData.length > 0) {
setTimeout(() => {
form.setValue("usePurpose", useTypesData[0]?.val?.toString() || "");
}, 500);
}
}, [useTypesData, form.setValue, form]);
useEffect(() => {
if (facilityName) {
setSdmNmValue(facilityName);
form.setValue("sdmNm", facilityName);
setKey((prev) => prev + 1);
}
}, [facilityName, form.setValue, form]);
useEffect(() => {
if (searchParams.get("dmdCoNm")) {
form.setValue("sdmNm", searchParams.get("dmdCoNm") || "");
setSdmNmValue(searchParams.get("dmdCoNm") || "");
setKey((prev) => prev + 1);
}
}, [searchParams, form.setValue, form]);
const searchCandidate = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
const dmdInfoId = JSON.parse(
sessionStorage.getItem("user") || "{}"
)?.dmdInfoId?.toString();
const url = `/map/popup?dmdInfoId=${encodeURIComponent(dmdInfoId)}`;
const width = window.screen.availWidth;
const height = window.screen.availHeight;
const left = 0;
const top = 0;
const popupOptions = `width=${width},height=${height},left=${left},top=${top},resizable=yes,scrollbars=yes`;
window.open(url, "candidatePopup", popupOptions);
};
const searchSimilarCase = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
setIsSimilarCase(true);
};
const handleCheckboxChange = (checked: boolean) => {
setIsBznmTotNoDisabled(checked);
onCheckboxChange?.(checked);
};
useEffect(() => {
const watchPH = form.getValues(`ph`);
if (watchPH && watchPH !== undefined) {
const [frontPH, backPH] = watchPH.split("~");
if (frontPH) {
setFrontPHdata(frontPH);
}
if (backPH) {
setBackPHdata(backPH);
}
} else {
setFrontPHdata("0");
setBackPHdata("0");
}
}, [form.getValues(`ph`)]);
const isSetPh = useCallback(
(typePHdata: string, index: number) => {
const PHdata = form.getValues("ph");
const isPH = PHdata?.split("~")[index] || "";
if (index == 0) {
form.setValue("ph", `${isPH}~${typePHdata}`);
setBackPHdata(typePHdata);
} else if (index == 1) {
form.setValue("ph", `${typePHdata}~${isPH}`);
setFrontPHdata(typePHdata);
}
},
[form]
);
const usePurpose = useWatch({ control: form.control, name: "usePurpose" });
useEffect(() => {
if (!usePurpose) return;
// Apply default values
const defaults = defaultRules[usePurpose];
if (defaults) {
Object.entries(defaults).forEach(([field, value]) => {
form.setValue(field as keyof SdmInfoFormData, value, {
shouldDirty: true,
});
});
}
}, [form.getValues("usePurpose")]);
// 시설 선택시 이벤트
const selectComp = useCallback(
(rtnData: DemandCompType[]) => {
const rtnCompData = rtnData?.[0];
form.setValue("sdmNm", rtnCompData?.dmdCoNm || "");
},
[form]
);
const formFields: Array<{
name: keyof SdmInfoFormData;
label: string;
component: FieldComponent | undefined;
formIndex: number;
required?: boolean;
}> = [
{
name: "sdmNm",
label: "수요처선택",
formIndex: 0,
required: true,
component: (field) => (
<div key={key}>
<SearchInputText
label="수요처명"
setValue={(val) => {
setSdmNmValue(val || "");
field.onChange(val || "");
}}
setRtnData={selectComp}
initValue={facilityName || sdmNmValue}
{...field}
/>
</div>
),
},
{
name: "demandYmd",
label: "요구시기",
formIndex: 0,
required: true,
component: (field) => (
<div className="relative w-64">
{/* <DatePicker
mode="single"
selected={field.value as Date}
onSelect={(date) => {
field.onChange(date as Date);
}}
className=""
//defaultMonth={field.value as Date}
field={{
value: field.value as Date,
onChange: (date: Date | undefined) => {
field.onChange(date as Date);
},
}}
showOutsideDays={true}
selectClass={undefined}
/> */}
{/* 네이티브 input */}
<Input
className="w-full !text-xl text-right"
type="date"
onChange= {(e) => {
const selectedDate = e.target.value ? new Date(e.target.value) : null;
field.onChange(selectedDate);
}}
value={ formatDateToYMD(field.value as Date) }
/>
</div>
),
},
{
name: "demandQnty",
label: "요구수량(㎥/d)",
formIndex: 0,
required: true,
component: (field) => (
<Input
type="text"
className="!text-xl text-gray-600"
value={field.value as string}
onChange={(e) => {
field.onChange(e);
setSply(Number(e.target.value));
}}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
),
},
{
name: "usePurpose",
label: "사용용도",
formIndex: 0,
required: true,
component: (field) => (
<SelectBox
selectClass={undefined}
label=""
selectArray={useTypesData}
onSelectValue={(val) => {
field.onChange(val.toString());
setUsageCd(val.toString());
}}
className=""
value={field.value as string}
/>
),
},
{
name: "money",
label: "희망단가(원)",
formIndex: 0,
required: true,
component: (field) => (
<FormUi
onCheckboxChange={handleCheckboxChange}
isDisabled={isBznmTotNoDisabled}
>
<Input
type="text"
className="!text-xl text-gray-600"
value={field.value as string}
onChange={(e) => {
field.onChange(e);
setMoney(Number(e.target.value));
}}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
</FormUi>
),
},
{
name: "reqWaterQlty",
label: "요구수질",
formIndex: 0,
required: true,
component: undefined,
},
{
name: "candidateTitle",
label: CANDIDATE || "공급처 후보지 선택(필수아님)",
formIndex: 2,
component: () => (
<div>
<div className="-mt-14 float-right flex gap-10">
<Button
className="rounded-md"
color="sky"
size={"sm"}
onClick={searchCandidate}
>
후보지 조회
</Button>
<Button
className="rounded-md"
color="sky"
size={"sm"}
onClick={searchSimilarCase}
>
유사사례
</Button>
</div>
<div className="flex justify-center gap-10 mt-5">
{(form.getValues("candidateTitle") || []).map(
(candidate: any, index: number) => (
<Input
key={index}
placeholder={`후보지${index + 1}`}
type="text"
className="!text-xl w-[130px] text-gray-600"
value={candidate.ruseUtztnFcltNm}
readOnly
/>
)
)}
</div>
</div>
),
},
];
const normalFields = formFields.filter(
(f) => f.formIndex === 0 && f.component
);
const candidateFields = formFields.filter(
(f) => f.formIndex === 2 && f.component
);
return (
<>
{normalFields.map(({ name, label, component, required }) =>
component ? (
<FormField
key={name}
control={form.control}
name={name}
render={({ field }) =>
name === "money" ? (
<div>
<Label className="text-black">희망단가(원)*</Label>
{component(field)}
</div>
) : (
// <FormUi label={label + "*"}>{component(field)}</FormUi>
<AccessibleFormField
field={field}
label={label}
required={required}
error={
typeof form.formState.errors[name]?.message === "string"
? (form.formState.errors[name] as FieldError)
: undefined
}
inputComponent={component(field)}
/>
)
}
/>
) : null
)}
<div className="mt-10">
<FormLabel className="text-xl">요구수질</FormLabel>
<div className="grid grid-cols-2 gap-x-10 gap-y-6 mt-3 mb-3">
<FormField
control={form.control}
name={`grssClfg`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi
label={
!isDisabled ? `총대장균군수(개/mg)*` : "총대장균군수(개/mg)"
}
>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 text-right rounded-md"
placeholder=""
onChange={(e) => {
const inputValue = e.target.value.replace(
/[^0-9]/g,
""
); // 정수만
field.onChange(
inputValue === "" ? null : Number(inputValue)
);
}}
value={
field.value !== undefined && field.value !== null
? `${field.value}`
: "불검출"
}
maxLength={6}
disabled={isDisabled}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
{/* TODO: 총대장균군수 확인 필요*/}
{field.value !== null ? (
<span className="text-xl absolute inset-y-0 right-3 flex items-center text-gray-500 pointer-events-none">
이하
</span>
) : (
<></>
)}
</div>
</div>
</FormUi>
);
}}
/>
<FormField
control={form.control}
name={`tn`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi
label={
!isDisabled ? `총질소(T-N)(mg/L)*` : "총질소(T-N)(mg/L)"
}
>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 text-right rounded-md"
placeholder=""
onChange={(e) => {
const inputValue = e.target.value.replace(
/[^0-9]/g,
""
); // 정수만
field.onChange(
inputValue === "" ? null : Number(inputValue)
);
}}
value={
field.value !== undefined && field.value !== null
? `${field.value}`
: ""
}
maxLength={6}
disabled={isDisabled}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
<span className="text-xl absolute inset-y-0 right-3 flex items-center text-gray-500 pointer-events-none">
이하
</span>
</div>
</div>
</FormUi>
);
}}
/>
<FormField
control={form.control}
name={`combResdch`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi
label={
!isDisabled ? `결합잔류염소(mg/L)*` : "결합잔류염소(mg/L)"
}
>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 text-right rounded-md"
placeholder=""
onChange={(e) => {
const cleanValue = sanitizeInput(
e.target.value,
true
);
field.onChange(
cleanValue === "" ? null : Number(cleanValue)
);
}}
value={field.value ?? ""}
maxLength={6}
disabled={isDisabled}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
<span className="text-xl absolute inset-y-0 right-3 flex items-center text-gray-500 pointer-events-none">
이상
</span>
</div>
</div>
</FormUi>
);
}}
/>
<FormField
control={form.control}
name={`tph`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi
label={!isDisabled ? `총인(T-P)(mg/L)*` : "총인(T-P)(mg/L)"}
>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 text-right rounded-md"
placeholder=""
onChange={(e) => {
const cleanValue = sanitizeInput(
e.target.value,
true
);
field.onChange(
cleanValue === "" ? null : Number(cleanValue)
);
}}
value={field.value ?? ""}
maxLength={6}
disabled={isDisabled}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
<span className="text-xl absolute inset-y-0 right-3 flex items-center text-gray-500 pointer-events-none">
이하
</span>
</div>
</div>
</FormUi>
);
}}
/>
<FormField
control={form.control}
name={`trbt`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi label={!isDisabled ? `탁도(NTU)*` : "탁도(NTU)"}>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 text-right rounded-md"
placeholder=""
onChange={(e) => {
const inputValue = e.target.value.replace(
/[^0-9]/g,
""
); // 정수만
field.onChange(
inputValue === "" ? null : Number(inputValue)
);
}}
value={
field.value !== undefined && field.value !== null
? `${field.value}`
: ""
}
maxLength={6}
disabled={isDisabled}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
<span className="text-xl absolute inset-y-0 right-3 flex items-center text-gray-500 pointer-events-none">
이하
</span>
</div>
</div>
</FormUi>
);
}}
/>
<div className="col-span-1">
<Label className="text-xl">수소이온농도(pH)</Label>
<div className="flex flex-row items-center gap-2">
<Input
className="!text-xl w-36"
placeholder=""
type="text"
onChange={(e) => {
const cleanValue = sanitizeInput(e.target.value, true);
isSetPh(cleanValue, 1);
}}
value={frontPHdata ?? ""}
maxLength={5}
/>
<span className="text-xl mx-2">~</span>
<Input
className="!text-xl w-36 "
placeholder=""
type="text"
onChange={(e) => {
const cleanValue = sanitizeInput(e.target.value, true);
isSetPh(cleanValue, 0);
}}
value={backPHdata ?? ""}
maxLength={5}
/>
</div>
</div>
<FormField
control={form.control}
name={`bod`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi
label={
!isDisabled
? `생물학적 산소요구량(BOD)(mg/L)*`
: "생물학적 산소요구량(BOD)(mg/L)"
}
>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 text-right rounded-md"
placeholder=""
onChange={(e) => {
const inputValue = e.target.value.replace(
/[^0-9]/g,
""
); // 정수만
field.onChange(
inputValue === "" ? null : Number(inputValue)
);
}}
value={
field.value !== undefined && field.value !== null
? `${field.value}`
: ""
}
maxLength={6}
disabled={isDisabled}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
<span className="text-xl absolute inset-y-0 right-3 flex items-center text-gray-500 pointer-events-none">
이하
</span>
</div>
</div>
</FormUi>
);
}}
/>
<FormField
control={form.control}
name={`clIonQnt`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi
label={!isDisabled ? `염화물(mgCL/L)*` : "염화물(mgCL/L)"}
>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 text-right rounded-md"
placeholder=""
onChange={(e) => {
const inputValue = e.target.value.replace(
/[^0-9]/g,
""
); // 정수만
field.onChange(
inputValue === "" ? null : Number(inputValue)
);
}}
value={
field.value !== undefined && field.value !== null
? `${field.value}`
: ""
}
maxLength={6}
disabled={isDisabled}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
<span className="text-xl absolute inset-y-0 right-3 flex items-center text-gray-500 pointer-events-none">
이하
</span>
</div>
</div>
</FormUi>
);
}}
/>
<FormField
control={form.control}
name={`smll`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi label={!isDisabled ? `냄새*` : "냄새"}>
<SelectBox
className="!text-2xl rounded-md"
label={""}
selectClass={undefined}
selectArray={[
{ text: "불쾌하지않을것", val: "불쾌하지않을것" },
{ text: "해당사항없음", val: "해당사항없음" },
]}
onSelectValue={(val: string | number) => {
field.onChange(val.toString());
}}
value={field.value}
readOnly={isDisabled}
onBlur={field.onBlur}
ref={field.ref}
/>
</FormUi>
);
}}
/>
<FormField
control={form.control}
name={`cdtnv`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi
label={
!isDisabled ? `전기전도도(㎲/cm)*` : "전기전도도(㎲/cm)"
}
>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 text-right rounded-md"
placeholder=""
onChange={(e) => {
const inputValue = e.target.value.replace(
/[^0-9]/g,
""
); // 정수만
field.onChange(
inputValue === "" ? null : Number(inputValue)
);
}}
value={
field.value !== undefined && field.value !== null
? `${field.value}`
: ""
}
maxLength={6}
disabled={isDisabled}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
<span className="text-xl absolute inset-y-0 right-3 flex items-center text-gray-500 pointer-events-none">
이하
</span>
</div>
</div>
</FormUi>
);
}}
/>
<FormField
control={form.control}
name={`crmty`}
render={({ field }) => {
const disabledFields = usePurpose ? disableRules[usePurpose] : [];
const isDisabled = disabledFields
? disabledFields.includes(field.name)
: true;
return (
<FormUi label={!isDisabled ? `색도(도)*` : "색도(도)"}>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 text-right rounded-md"
placeholder=""
onChange={(e) => {
const inputValue = e.target.value.replace(
/[^0-9]/g,
""
); // 정수만
field.onChange(
inputValue === "" ? null : Number(inputValue)
);
}}
value={
field.value !== undefined && field.value !== null
? `${field.value}`
: ""
}
maxLength={6}
disabled={isDisabled}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
<span className="text-xl absolute inset-y-0 right-3 flex items-center text-gray-500 pointer-events-none">
이하
</span>
</div>
</div>
</FormUi>
);
}}
/>
<FormField
control={form.control}
name={`rmrk`}
render={({ field }) => {
return (
<FormUi label={"비고"}>
<div className="flex items-center gap-2">
<div className="relative flex-1 min-w-0">
<Input
type="text"
className="w-full pr-16 border py-2 rounded-md"
placeholder=""
onChange={(e) => {
field.onChange(e.target.value);
}}
value={
field.value !== undefined && field.value !== ""
? `${field.value}`
: ""
}
onBlur={field.onBlur}
name={field.name}
ref={field.ref}
/>
</div>
</div>
</FormUi>
);
}}
/>
</div>
</div>
{candidateFields.map(({ name, label, component, required }, index) =>
component ? (
<FormField
key={name + index}
control={form.control}
name={name}
render={({ field }) => (
// <FormUi label={label}>
// {component(field)}
// </FormUi>
<AccessibleFormField
field={field}
label={label}
required={required}
error={
typeof form.formState.errors[name]?.message === "string"
? (form.formState.errors[name] as FieldError)
: undefined
}
inputComponent={component?.(field)}
/>
)}
/>
) : null
)}
{isSimilarCase && (
<UiModal
body={
<ModalSimilarPage sply={sply} usageCd={usageCd} money={money} />
}
bodyClass="sm:max-w-[100vw] w-[1400px] h-[100dvh] max-h-[900px] overflow-y-auto overflow-x-hidden"
open={isSimilarCase}
onOpenChange={(open) => !open && setIsSimilarCase(false)}
noHeaderYn="Y"
noFooterYn="Y"
/>
)}
</>
);
}
@@ -0,0 +1,197 @@
import { useDmStore } from "@/app/store";
import { BZNM_TOT_NO, FormField, FormUi } from "@common/business_components";
import type { DemandCompType } from "@common/business_components/ui/sdmInsertForm/form";
import { Button, Input } from "@common/components";
import { zodResolver } from "@hookform/resolvers/zod";
import { sha512 } from 'js-sha512';
import React, { useEffect, useMemo, useState } from "react";
import { FormProvider, useForm, type ControllerRenderProps } from "react-hook-form";
import toast from "react-hot-toast";
import * as z from "zod";
export function SdmLoginForm() {
const { actionLogin, initializeCommonData } = useDmStore((state) => state);
const [isBznmTotNoDisabled, setIsBznmTotNoDisabled] = useState(true);
const formatBusinessNumber = (value: string) => {
// 숫자만 추출
const digitsOnly = value.replace(/\D/g, "");
// 10자리까지만 처리
const limitedDigits = digitsOnly.slice(0, 10);
// 3-2-5 형식으로 포맷팅
if (limitedDigits.length <= 3) {
return limitedDigits;
} else if (limitedDigits.length <= 5) {
return `${limitedDigits.slice(0, 3)}-${limitedDigits.slice(3)}`;
} else {
return `${limitedDigits.slice(0, 3)}-${limitedDigits.slice(3, 5)}-${limitedDigits.slice(5)}`;
}
};
// 스키마를 useMemo로 최적화
const sdmLoginFormSchema = useMemo(() => z.object({
dmdInfoId: z.string()
.min(1, "사업자등록번호를 입력해주세요")
.regex(/^\d{10}$/, "사업자등록번호는 10자리 숫자만 입력 가능합니다"),
bznmTotNo: isBznmTotNoDisabled
? z.string().optional()
: z.string().length(4, "종사업자등록번호는 4자리 숫자만 입력 가능합니다"),
password: z.string()
.min(1, "비밀번호를 입력해주세요")
.min(8, "비밀번호는 8자 이상 입력해주세요")
.max(16, "비밀번호는 16자 이내로 입력해주세요"),
rgtr: z.string().optional(),
dmdAplyPswd: z.string().optional(),
}), [isBznmTotNoDisabled]);
type SdmLoginForm = z.infer<typeof sdmLoginFormSchema>;
type FieldComponent = (field: ControllerRenderProps<SdmLoginForm, keyof SdmLoginForm>) => React.ReactElement;
const formSchema = sdmLoginFormSchema;
useEffect(() => {
initializeCommonData();
}, [initializeCommonData]);
const defaultValues: SdmLoginForm = {
dmdInfoId: '',
bznmTotNo: '',
password: '',
rgtr: '',
dmdAplyPswd: '',
};
const form = useForm<SdmLoginForm>({
resolver: zodResolver(formSchema),
defaultValues,
mode: "onChange",
});
const handleCheckboxChange = (checked: boolean) => {
setIsBznmTotNoDisabled(checked);
};
const initPassword = () => {
toast(
(t) => (
<div className="flex flex-col items-center">
<div className="text-2xl mb-2">
관리자(031-0000-0000)에게 비밀번호 초기화 요청을 유선으로 하시기 바랍니다.
</div>
<Button size={"sm"} onClick={() => toast.dismiss(t.id)}>
확인
</Button>
</div>
),
{
id: "pwd-reset",
duration: Infinity,
position: "top-center",
}
);
}
const handleLogin = () => {
const data = form.getValues();
const passwordStr = sha512.hex(data.password)
data.dmdAplyPswd = passwordStr;
const param = {
dmdInfoId: data.dmdInfoId + (isBznmTotNoDisabled ? '0000' : data.bznmTotNo),
dmdAplyPswd: data.dmdAplyPswd,
}
actionLogin(param as unknown as DemandCompType);
};
const formFields: Array<{
name: keyof SdmLoginForm;
label: string;
component: FieldComponent | undefined;
}> = [
{
name: "dmdInfoId",
label: "사업자등록번호",
component: (field) => (
<Input
placeholder="사업자등록번호를 입력하세요"
type="text"
className="!mt-5 !mb-5 !text-xl text-gray-600"
{...field}
value={formatBusinessNumber(field.value as string)}
onChange={(e) => {
const dmdId = e.target.value.replace(/\D/g, "").slice(0, 10);
field.onChange(dmdId);
}}
/>
)
},
{
name: "bznmTotNo",
label: BZNM_TOT_NO || "종사업자등록번호",
component: (field) => (
<FormUi
label="종사업자등록번호"
onCheckboxChange={handleCheckboxChange}
isDisabled={isBznmTotNoDisabled}
>
<Input
placeholder="여러사업장이 있을 경우 입력해주세요"
type="text"
className="!mt-5 !text-xl text-gray-600"
disabled={isBznmTotNoDisabled}
{...field}
/>
</FormUi>
)
},
{
name: "password",
label: "비밀번호",
component: (field) => (
<Input
placeholder="비밀번호를 입력하세요"
type="password"
className="!mt-5 !mb-5 !text-xl text-gray-600"
{...field}
/>
)
}
];
return (
<>
<div>
<FormProvider {...form}>
{formFields.map(({ name, label, component }) => (
<FormField
key={name}
control={form.control}
name={name}
render={({ field }) => (
label === '종사업자등록번호' ?
<>
{component && component(field)}
</>
: <FormUi label={label}>
{component && component(field)}
</FormUi>
)}
/>
))}
</FormProvider>
<div className="flex justify-center pt-4">
<div className="flex flex-col items-center">
<Button
onClick={handleLogin}
className="w-32 bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2 px-4 rounded-md transition-colors duration-200"
>
로그인
</Button>
<div className="text-xl mt-2 text-gray-400 cursor-pointer" onClick={initPassword}>비밀번호 초기화 요청</div>
</div>
</div>
</div>
</>
);
}