Compare commits

...
19 Commits
Author SHA1 Message Date
yschoi d975e8fed0 로그인 처리
iipbs_sn / build (push) Waiting to run
2025-05-26 10:32:26 +09:00
swcho 6156cf6419 Merge remote-tracking branch 'origin/iipbs/sn/dev' into iipbs/sn/ii
iipbs_sn / build (push) Has been cancelled
2025-05-23 16:43:34 +09:00
JIeunhuh 66837f5a8a 페이징 관련 코드 수정
iipbs_sn / build (push) Waiting to run
2025-05-23 15:49:28 +09:00
JIeunhuh ef03ab961c 파일 삭제 및 테이블 페이징 처리 구현 (테스트 필요)
iipbs_sn / build (push) Waiting to run
2025-05-23 15:35:00 +09:00
swcho 01e3f112b3 Merge remote-tracking branch 'origin/iipbs/sn/dev' into iipbs/sn/ii 2025-05-23 15:29:34 +09:00
swcho 0183b91c39 feat: I/I 분석 화면 엑셀 파일 업로드 시 Json 변환 기능 구현 및 title 수정 2025-05-23 15:28:28 +09:00
JIeunhuh d26c499c2a url 오타 수정
iipbs_sn / build (push) Waiting to run
2025-05-23 14:26:45 +09:00
JIeunhuh 36e5e7761f Merge commit '26c28c53dbc7c3558bc6963519e67748b1f56050' into iipbs/sn/oi 2025-05-23 14:25:56 +09:00
JIeunhuh 96f89fafcc 테이블 초기값 설정 2025-05-23 14:10:56 +09:00
JIeunhuh aa87e4950e 도시침수 및 노후하수 관로 api작업 완료(테스트필요) 2025-05-23 14:08:48 +09:00
yschoi 26c28c53db 파일업로드 수정
iipbs_sn / build (push) Waiting to run
2025-05-23 13:43:07 +09:00
swcho 525fd5bdb1 Merge commit '7f7a780b7a1d9aa12a598460ea01ad0f0abdf62c' into iipbs/sn/ii 2025-05-22 17:00:24 +09:00
swcho 7f7a780b7a feat: filePicked 컴포넌트에 dateType 파라미터 추가 2025-05-22 16:59:14 +09:00
YangJinSoo94 07bd859563 엑셀 다중 시트 및 스타일 적용용 2025-05-22 16:52:31 +09:00
JIeunhuh 2a6b4652d2 Merge commit 'ab00dc1e869715a6e03c52f0c0312ae94de7f462' into iipbs/sn/oi 2025-05-22 11:44:21 +09:00
JIeunhuh 1f5bf6b5c4 Merge remote-tracking branch 'origin/iipbs/sn/dev' into iipbs/sn/oi 2025-05-22 11:19:04 +09:00
JIeunhuh 36540bcb69 파일 위치 변경 2025-05-22 11:18:52 +09:00
YangJinSoo94 56dd0734a0 테이블 number타입 세자리마다 , 포맷 버그 수정 2025-05-21 16:54:48 +09:00
YangJinSoo94 9a854339ab lineBarChcart 상단 영역이 생기는 문제해결 2025-05-21 13:22:00 +09:00
30 changed files with 1007 additions and 498 deletions
+100
View File
@@ -0,0 +1,100 @@
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
const REFRESH_TOKEN = process.env.NEXT_PUBLIC_REFRESH_TOKEN || "refresh-token";
const SERVER_API_URL = process.env.NEXT_PUBLIC_SERVER_API_URL || "";
const SITE_ID = process.env.NEXT_PUBLIC_SITE_ID || "SN";
async function handler(
request: Request,
params: { url: string[] },
method: "GET" | "POST" | "PUT" | "DELETE",
) {
const cookieStore = await cookies();
const headers: Record<string, string> = {
"Content-Type": "application/json",
"X-Site-Id": SITE_ID,
};
let body = {};
const isRefreshHandler = params.url.includes("refresh");
// silent refresh
if (isRefreshHandler) {
const refreshToken = cookieStore.get(REFRESH_TOKEN);
headers[CLAIM_NAME] = refreshToken?.value ?? "";
if (!headers[CLAIM_NAME]) {
return NextResponse.json({ message: "Can't refresh" }, { status: 401 });
}
}
try {
if (!isRefreshHandler) {
body = await request.json();
}
const result = await fetch(`${SERVER_API_URL}/${params.url.join("/")}`, {
method,
headers,
body: JSON.stringify(body),
});
if (!result.ok) {
console.log("Invalid Credentials ");
return NextResponse.json(
{ message: "Invalid Credentials" },
{ status: 401 },
);
}
const accessToken = result.headers.get(ACCESS_TOKEN);
const refreshToken = result.headers.get(REFRESH_TOKEN);
const userId = result.headers.get(AUTH_USER_ID);
if (accessToken && userId) {
const response = NextResponse.json({
[ACCESS_TOKEN]: accessToken,
[AUTH_USER_ID]: userId,
});
if (refreshToken) {
cookieStore.set(REFRESH_TOKEN, refreshToken, {
httpOnly: true,
sameSite: "lax",
path: "/",
});
}
return response;
}
return NextResponse.json(
{ message: "Invalid Credentials" },
{ status: 401 },
);
} catch (error) {
return NextResponse.json(
{ message: "Server Error", error },
{ status: 500 },
);
}
}
export async function POST(
request: Request,
props: { params: Promise<{ url: string[] }> },
) {
const params = await props.params;
return handler(request, params, "POST");
}
export async function PUT(
request: Request,
props: { params: Promise<{ url: string[] }> },
) {
const params = await props.params;
return handler(request, params, "PUT");
}
@@ -0,0 +1,105 @@
import { AxiosError } from "axios";
import { tokenManager } from "../lib/token-manager";
const ENDPOINT = {
USER_SERVICE: {
LOGIN: "/user-service/login",
USERS: "/user-service/api/v1/users",
SILENT_REFRESH: "/user-service/api/v1/users/token/refresh",
AUTHORIZATIONS: "/user-service/api/v1/authorizations",
ROLE_AUTHORIZATIONS: "/user-service/api/v1/role-authorizations",
},
};
const JWT_EXPIRATION_TIME = 1800000;
const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
const ACCESS_TOKEN = process.env.NEXT_PUBLIC_ACCESS_TOKEN || "access-token";
export interface ILogin {
userId: string;
password: string;
}
export interface LoginService {
login(payload: ILogin): Promise<void>;
silentRefresh(): Promise<void>;
}
export class LoginApiService implements LoginService {
private static instance: LoginApiService;
private constructor() {}
public static getInstance(): LoginApiService {
if (!LoginApiService.instance) {
LoginApiService.instance = new LoginApiService();
}
return LoginApiService.instance;
}
public async login(payload: ILogin): Promise<void> {
try {
const response = await fetch(`/api/proxy${ENDPOINT.USER_SERVICE.LOGIN}`, {
method: "POST",
body: JSON.stringify({
userId: payload.userId,
password: payload.password,
}),
});
const data = await response.json();
const accessToken = data[ACCESS_TOKEN];
const tokenId = data[AUTH_USER_ID];
if (!accessToken || !tokenId) {
throw new Error("Missing required authentication tokens");
}
tokenManager.setToken(CLAIM_NAME, accessToken);
tokenManager.setToken(AUTH_USER_ID, tokenId);
tokenManager.setupRefreshTimer(
() => this.silentRefresh(),
JWT_EXPIRATION_TIME,
);
} catch (error) {
if (error instanceof AxiosError) {
throw new Error(`Login failed: ${error.response?.data?.message}`);
}
throw new Error(`Login failed: ${error}`);
}
}
public async silentRefresh(): Promise<void> {
try {
const response = await fetch(
`/api/proxy${ENDPOINT.USER_SERVICE.SILENT_REFRESH}`,
{
method: "PUT",
},
);
const data = await response.json();
const accessToken = response.headers.get("access-token");
const tokenId = response.headers.get("token-id");
if (!accessToken || !tokenId) {
throw new Error("Missing required authentication tokens");
}
tokenManager.setToken(CLAIM_NAME, accessToken);
tokenManager.setToken(AUTH_USER_ID, tokenId);
} catch (error) {
tokenManager.clearAuthToken();
if (error instanceof AxiosError) {
throw new Error(
`Silent refresh failed: ${error.response?.data?.message}`,
);
}
throw new Error(`Silent refresh failed: ${error}`);
}
}
}
export const LoginApi = LoginApiService.getInstance();
@@ -0,0 +1,2 @@
export { LoginApi } from "./api/login-service";
export { AuthWrapper } from "./lib/auth-wrapper";
@@ -0,0 +1,87 @@
"use client";
import { useEffect } from "react";
import { useRouter, usePathname } from "next/navigation";
import axios from "axios";
import Cookies from "js-cookie";
import { useUserStore, type IUserInfo } from "@store";
import { getCookie } from "@utils";
import { LoginApi } from "../api/login-service";
import { tokenManager } from "../lib/token-manager";
const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
const ENDPOINT = {
USER_SERVICE: {
LOGIN: "/user-service/login",
USERS: "/user-service/api/v1/users",
SILENT_REFRESH: "/user-service/api/v1/users/token/refresh",
AUTHORIZATIONS: "/user-service/api/v1/authorizations",
ROLE_AUTHORIZATIONS: "/user-service/api/v1/role-authorizations",
},
};
const AuthWrapper = ({ children }: { children: React.ReactNode }) => {
const router = useRouter();
const pathname = usePathname(); // 현재 경로
const { userInfo, setUserInfo } = useUserStore((state) => state);
async function authCheck() {
const checkToken = getCookie(AUTH_USER_ID);
if (!checkToken) {
//TODO 나중에 수정해야....
const userId = "admin1gmail";
const password = "test1234!";
await LoginApi.login({ userId, password });
// window.location.href = "http://dev.onasys.co.kr/auth/login";
// throw new Error("Missing required authentication tokens");
}
const accessToken = tokenManager.getToken(CLAIM_NAME);
const tokenId = tokenManager.getToken(AUTH_USER_ID);
const response = await axios.get<IUserInfo>(
`${ENDPOINT.USER_SERVICE.USERS}/info/me`,
{
withCredentials: true,
headers: {
[CLAIM_NAME]: accessToken,
[AUTH_USER_ID]: tokenId ?? "",
},
},
);
if (!userInfo) setUserInfo(response.data);
}
useEffect(() => {
(async () => {
try {
await authCheck();
} catch (error) {
console.error("Auth check failed:", error);
try {
await LoginApi.silentRefresh();
await authCheck();
} catch (refreshError) {
console.error("Token refresh failed:", refreshError);
setUserInfo(null);
// TODO 운영에 반영 할때 수정해야.....
// 현재 경로가 로그인 페이지가 아닐 때만 redirect
// if (!pathname.startsWith("/auth/login")) {
// window.location.href = "http://dev.onasys.co.kr/auth/login";
// }
}
}
})();
}, [pathname]); // pathname도 의존성에 포함
return <>{children}</>;
};
export { AuthWrapper };
@@ -0,0 +1,61 @@
import { getCookie, setCookie, removeCookie } from "@utils";
const AUTH_USER_ID = process.env.NEXT_PUBLIC_AUTH_USER_ID || "token-id";
const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization";
export class TokenManager {
private static instance: TokenManager;
private refreshTimer: NodeJS.Timeout | null = null;
private constructor() {}
public static getInstance(): TokenManager {
if (!TokenManager.instance) {
TokenManager.instance = new TokenManager();
}
return TokenManager.instance;
}
public getToken(key: string): string | undefined {
return getCookie(key);
}
public setToken(key: string, value: string): void {
setCookie(key, value, {
secure: window.location.protocol === "https:",
sameSite: "lax",
});
}
public removeToken(key: string): void {
removeCookie(key);
}
public setupRefreshTimer(
callback: () => Promise<void>,
expirationTime: number,
): void {
if (this.refreshTimer) {
clearTimeout(this.refreshTimer);
}
this.refreshTimer = setTimeout(() => {
callback().catch((error) => {
console.error("Silent refresh failed:", error);
this.clearAuthToken();
});
}, expirationTime - 60000);
}
public clearAuthToken(): void {
if (this.refreshTimer) {
clearTimeout(this.refreshTimer);
this.refreshTimer = null;
}
this.removeToken(CLAIM_NAME);
this.removeToken(AUTH_USER_ID);
}
}
export const tokenManager = TokenManager.getInstance();
@@ -0,0 +1,9 @@
export interface ILogin {
userId: string;
password: string;
}
export interface LoginService {
login(payload: ILogin): Promise<void>;
silentRefresh(): Promise<void>;
}
@@ -10,9 +10,5 @@ export const searchData = async<T extends Record<string, any>>(url: string, para
}, {} as Record<string, string>)
);
const data = await getData(`${url}?${params.toString()}`);
if (data) {
console.log(data.content)
// TODO: data 들어오면 data 보여주게 작업필요 ~ !
data.content && console.log(data)
}
return data && data.content
}
@@ -0,0 +1,63 @@
export const TEST_UUID= '2d4b151d-1828-41e0-91d9-4cd28ea1cc7e'
import { z } from "zod";
// 수용가-맨홀 매칭결과 (아직 안함)
export const MatchingResultZod = z.object({
anls_sn: z.number(),
mhl_mng_no: z.string(), // 일련번호 0 포함인지? number? string?
rcptr_no: z.string(),
});
export type MatchingResultZodType = z.infer<typeof MatchingResultZod>;
export const excelToMatchingResultData = (excelData: any) => {
const MatchingResultData: MatchingResultZodType[] = excelData.map((item: any) => {
return {
anls_sn: Number(item["NO"]),
mhl_mng_no: String(item["FTR_IDN"]), // 임시값이라 추후 수정 필요
rcptr_no: String(item["수용가"]),
};
}).filter((el: any) => el !== undefined);
return MatchingResultData;
};
// 시간패턴
export const timePatternZod = z.object({
hr_id: z.number(),
rt: z.number().nullish(),
});
export type timePatternZodType = z.infer<typeof timePatternZod>;
export const excelToTimePatternData = (excelData: any) => {
const timePatternData: timePatternZodType[] = excelData.map((item: any) => {
return {
hr_id: Number(item["시간"]),
rt: Number(item["비율"]),
};
}).filter((el: any) => el !== undefined);
return timePatternData;
};
// 유량자료
export const flowRateZod = z.object({
ppl_mng_no: z.string(),
mtrng_dt: z.number(), // type 뭘로 해야할지 Date? timeStamp임
oilq: z.number().nullish(),
});
export type flowRateZodType = z.infer<typeof flowRateZod>;
export const excelToflowRateData = (excelData: any) => {
const flowRateData: flowRateZodType[] = excelData.map((item: any) => {
return {
ppl_mng_no: String(item["관로번호"]),
mtrng_dt: new Date(item["시간"]).toISOString(), // type 뭘로 해야할지 Date? timeStamp임
oilq: Number(item["유량(㎥/h)"]),
};
}).filter((el: any) => el !== undefined);
return flowRateData;
};
@@ -1,3 +1,4 @@
export { getCookie, setCookie, removeCookie } from "./cookie";
export { handleUpload } from "./fileUploadUtil";
export * from "./fileDownload";
export * from './date'
+50 -48
View File
@@ -1,32 +1,34 @@
"use client"
import { FileUpload, SelectBox } from '@common/business_components/ui';
import { Button, Input } from '@common/components/ui';
import { SelectBox } from '@common/business_components/ui';
import { Button } from '@common/components/ui';
import React, { useState } from 'react'
import type { HttpResponse, Upload } from "tus-js-client";
import { FileUploader } from "@common/components";
import { handleUpload } from "@utils";
import { set } from 'react-hook-form';
const FileUploadForm = ({ title, onSubmit }: { title: string, onSubmit:(files:FileList, year:string, quarter:string) => void }) => {
const FileUploadForm = ({ title, onSubmit }: { title: string, onSubmit: (files: string, year: string, quarter: string, code:string, id:string) => void }) => {
const [atflCd, setAtflCd] = useState<string | null>(null);
const [atflId, setAtflId] = useState<string | null>(null);
const handleUploadResponse = (file: File) => async (res: HttpResponse) => {
const fileInfo = res.getHeader("X-File-Info");
if (!fileInfo) return;
const { atflCd, atflId } = JSON.parse(fileInfo) ?? {};
const orgnlFileNm = file.name;
console.log(atflCd, atflId, orgnlFileNm);
};
console.log('orgnlFileNm', orgnlFileNm, atflCd, atflId);
setAtflCd(atflCd);
setAtflId(atflId);
};
// 현재 년도부터 10년 전까지의 년도 옵션 생성
const yearOptions = Array.from({ length: 10 }, (_, i) => {
const year = new Date().getFullYear() - i;
return { text: `${year}년`, val: year.toString() };
});
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' }]
const [files, setFiles] = useState<FileList | null>(null);
const [selectedYear, setSelectedYear] = useState<string>(yearOptions[0]?.val || '');
const [selectedQuarter, setSelectedQuarter] = useState<string>(quater[0]?.val || '');
const [selectedQuarter, setSelectedQuarter] = useState<string>(quater[0]?.val || '');
const [upload, setUpload] = useState<Upload | null>(null);
return (
@@ -37,50 +39,48 @@ const FileUploadForm = ({ title, onSubmit }: { title: string, onSubmit:(files:Fi
<div className="card p-6">
<div className="grid grid-col-2 items-center space-x-4">
<div className='flex'>
<SelectBox
className="w-50 mr-3 ml-4"
selectClass="rounded-lg bg-white"
label="년도"
selectArray={yearOptions}
onSelectValue={(value: string | number) => setSelectedYear(String(value))}
/><SelectBox
className="w-50"
selectClass="rounded-lg bg-white"
label="분기"
selectArray={quater}
onSelectValue={(value: string | number) => setSelectedQuarter(String(value))}
/>
<div className='flex ml-5 items-center'>
<SelectBox
className="w-50 mr-3 ml-4"
selectClass="rounded-lg bg-white"
label="년도"
selectArray={yearOptions}
onSelectValue={(value: string | number) => setSelectedYear(String(value))}
/><SelectBox
className="w-50"
selectClass="rounded-lg bg-white"
label="분기"
selectArray={quater}
onSelectValue={(value: string | number) => setSelectedQuarter(String(value))}
/>
<div className='flex ml-5 items-center'>
<div className="w-[80px] mr-4">
<FileUploader
id="atflCd"
className="!h-auto !max-w-none flex-col !items-start"
accept=".jpeg,.jpg,.png"
onUpload={(e) => {
const selectedFiles = e.target.files;
if (!selectedFiles) return;
<FileUploader
id="atflCd"
className="!h-auto !max-w-none flex-col !items-start"
accept=".jpeg,.jpg,.png"
onUpload={(e) => {
const selectedFiles = e.target.files;
if (!selectedFiles) return;
const fileArray = Array.from(selectedFiles);
if(!fileArray){
setFiles(fileArray);
}
if (fileArray[0]) {
handleUpload(selectedFiles, {
handleUploadStart: setUpload,
handleSuccess: setUpload,
handleResponse: handleUploadResponse(fileArray[0]),
});
}
setFiles(selectedFiles);
if (selectedFiles[0]) {
handleUpload(selectedFiles, {
handleUploadStart: setUpload,
handleSuccess: setUpload,
handleResponse: handleUploadResponse(selectedFiles[0]),
});
}
}}
customPreview={<></>}
/>
}}
customPreview={<></>}
/>
</div>
<Button
className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700"
size="sm"
onClick={() => {
if (!files?.[0]) {
console.log(files?.[0]?.name)
if (!files) {
alert('파일을 선택해주세요.');
return;
}
@@ -89,9 +89,11 @@ const FileUploadForm = ({ title, onSubmit }: { title: string, onSubmit:(files:Fi
return;
}
if (!selectedQuarter) {
alert('분기기를 선택해주세요.');
alert('분기를 선택해주세요.');
return;
}
const fileNm = files?.[0]?.name || '';
onSubmit(fileNm, selectedYear, selectedQuarter, atflCd || '', atflId || '');
}}
>
등록
+41 -21
View File
@@ -4,6 +4,8 @@ import { SearchDiv, SearchFormLeft, SelectBox, SearchFormRight, Form, UiTable }
import ListDiv from '@common/business_components/ui/list_div'
import { Button } from '@common/components/ui'
import React, { type ReactNode } from 'react'
import { SelectBox2 } from '@common/business_components/ui/select/index-2'
type TitleName = {
mainTitle: string
firstCardTitle: string
@@ -12,6 +14,7 @@ type TitleName = {
type SelectBox = {
labelNm?: Label
searchChk?: boolean
title?: string // SearchDiv의 제목 (선택 사항)
}
type Label = {
first: string
@@ -41,15 +44,30 @@ type BaseLayout = {
const BaseLayout = ({ children, titleName, form, onSubmitEvent, graphBtn = false, searchBox }: BaseLayout) => {
return (
<ContentLayout title={titleName.mainTitle}>
<SearchDiv>
<SearchFormLeft>
<SelectBox className="col-span-2" label={searchBox?.labelNm?.first ?? ''} selectArray={[{ text: '한강 유역청', val: '1' }]} onSelectValue={(val) => { }} selectClass={undefined} />
<SelectBox label={searchBox?.labelNm?.second ?? ''} selectArray={[{ text: '경기도', val: '1' }]} className="col-span-2" onSelectValue={() => { }} selectClass='' />
<SelectBox label={searchBox?.labelNm?.third ?? ''} selectArray={[{ text: '양평군', val: '1' }]} className="col-span-3" onSelectValue={() => { }} selectClass='' />
<SelectBox label={searchBox?.labelNm?.fourth ?? ''} selectArray={[{ text: '양평하수처리장', val: '1' }]} className="col-span-3" onSelectValue={() => { }} selectClass='' />
</SearchFormLeft>
{searchBox?.searchChk ? <SearchFormRight><Button>조회</Button></SearchFormRight> : null}
</SearchDiv>
<ListDiv>
{/* searchBox.title이 있으면 h3 태그로 제목을 표시합니다. */}
{searchBox?.title && (
<div className="card-header">
<h3 className="text-2xl font-medium">{searchBox.title}</h3>
<div>
{graphBtn ? <Button className="!mr-[1.2rem]">다운로드</Button> : null}
{/* 그래프 있을 시 */}
{graphBtn ? <Button className="!mr-[1.2rem]">삭제</Button> : null}
</div>
</div>
)}
<div className="flex items-center w-full">
<div className="flex-1">
<SearchFormLeft>
<SelectBox2 label={searchBox?.labelNm?.first ?? ''} selectArray={[{ text: '한강 유역청', val: '1' }]} className="col-span-2" onSelectValue={(val) => { }} selectClass={undefined} />
<SelectBox2 label={searchBox?.labelNm?.second ?? ''} selectArray={[{ text: '경기도', val: '1' }]} className="col-span-2" onSelectValue={() => { }} selectClass='' />
<SelectBox2 label={searchBox?.labelNm?.third ?? ''} selectArray={[{ text: '양평군', val: '1' }]} className="col-span-3" onSelectValue={() => { }} selectClass='' />
<SelectBox2 label={searchBox?.labelNm?.fourth ?? ''} selectArray={[{ text: '양평하수처리장', val: '1' }]} className="col-span-3" onSelectValue={() => { }} selectClass='' />
</SearchFormLeft>
</div>
{searchBox?.searchChk ? <SearchFormRight><Button>조회</Button></SearchFormRight> : null}
</div>
</ListDiv>
<ListDiv>
<div className="card-header">
<h3 className="text-2xl font-medium">{titleName.firstCardTitle}</h3>
@@ -68,18 +86,20 @@ const BaseLayout = ({ children, titleName, form, onSubmitEvent, graphBtn = false
</form>
</Form>
</ListDiv>
{children?.[1] != null ? <ListDiv>
<div className="card-header flex items-center justify-between">
<h3 className="text-2xl font-medium">{titleName?.secondCardTitle}</h3>
<div>
{graphBtn ? <Button className="!mr-[1.2rem]">다운로드</Button> : null}
{/* 그래프 있을 시 */}
{graphBtn ? <Button className="!mr-[1.2rem]">삭제</Button> : null}
</div>
</div>
<div className="card !m-[1.2rem]">{children?.[1]}</div>
</ListDiv> : null}
</ContentLayout>
{
children?.[1] != null ? <ListDiv>
<div className="card-header flex items-center justify-between">
<h3 className="text-2xl font-medium">{titleName?.secondCardTitle}</h3>
<div>
{graphBtn ? <Button className="!mr-[1.2rem]">다운로드</Button> : null}
{/* 그래프 있을 시 */}
{graphBtn ? <Button className="!mr-[1.2rem]">삭제</Button> : null}
</div>
</div>
<div className="card !m-[1.2rem]">{children?.[1]}</div>
</ListDiv> : null
}
</ContentLayout >
)
}
+103 -29
View File
@@ -1,12 +1,15 @@
'use client'
import React, { useState } from 'react'
import { FormField, SelectBox } from '@common/business_components/ui'
import React, { useRef, useState } from 'react'
import { Button, DatePicker, Input } from '@common/components/ui'
import { z } from 'zod'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import FormSection from '@/components/ui/formSection'
import BaseLayout from '../BaseLayout'
import { filePicked, FileUpload } from '@common/business_components/ui'
import { excelToflowRateData, excelToMatchingResultData, excelToTimePatternData } from '../../components/lib/utils/excelToJson'
import { postData } from '@/components/lib/api'
const formSchema = z.object({
managenm: z.string(),
region: z.string(),
@@ -14,7 +17,7 @@ const formSchema = z.object({
inputdate: z.coerce.date(),
rtkSource: z.string(),
suyeongaPlace: z.string(),
pattern : z.string()
pattern: z.string()
})
const region: { text: string, val: number }[] = [{ text: '양평', val: 1 }, { text: '강남', val: 2 }, { text: 'test', val: 3 }]
const IrSetting = () => {
@@ -30,35 +33,106 @@ const IrSetting = () => {
pattern: ""
}
})
const [file1, setFile1] = useState<File | null>(null);
const [file2, setFile2] = useState<File | null>(null);
const [file3, setFile3] = useState<File | null>(null);
const [file4, setFile4] = useState<File | null>(null);
const [selectedDate, setSelectedDate] = useState(new Date())
const fileInputRef1 = useRef<HTMLInputElement>(null)
const fileInputRef2 = useRef<HTMLInputElement>(null)
const fileInputRef3 = useRef<HTMLInputElement>(null)
const fileInputRef4 = useRef<HTMLInputElement>(null)
// 버튼 클릭 핸들러
const handleAnalysisClick = async () => {
const file1 = fileInputRef1.current?.files?.[0]
const file2 = fileInputRef2.current?.files?.[0]
const file3 = fileInputRef3.current?.files?.[0]
if (!file1 || !file2 || !file3) {
alert('모든 파일을 선택해주세요.')
return
}
let json2: any = null;
let json3: any = null;
await filePicked(file2, 0).then((res) => {
if (res !== undefined) json2 = excelToMatchingResultData(res);
});
await filePicked(file3, 0).then((res) => {
if (res !== undefined) json3 = excelToTimePatternData(res);
});
console.log(file1)
console.log(json2)
console.log(json3)
}
// 버튼 클릭 핸들러
const handleUploadClick = async () => {
const file4 = fileInputRef4.current?.files?.[0];
if (!file4) {
alert('파일을 선택해주세요.')
return
}
let json4: any = null;
await filePicked(file4, 0).then((res) => {
console.log(res);
if (res !== undefined) json4 = excelToflowRateData(res);
});
console.log(json4);
// json4가 존재하면 postData로 백엔드에 전송
if (json4) {
try {
const response = await postData('your-backend-endpoint', json4); // 'your-backend-endpoint'를 실제 API 경로로 변경
console.log('업로드 결과:', response);
alert('업로드가 완료되었습니다.');
} catch (error) {
console.error('업로드 실패:', error);
alert('업로드에 실패했습니다.');
}
}
}
return (
<BaseLayout titleName={{ mainTitle: '침입수 산정', firstCardTitle: '실측자료 등록', secondCardTitle: '침입수 분석자료 입력' }} form={form} onSubmitEvent={() => { }} graphBtn={false}>
<div className="grid gap-4">
<FormSection name='suyeongaPlace' form={form} titleNm='○ 오수관망도'><div className="w-[150px]">
<Input id="fileNm" type="file" />
</div></FormSection>
<FormSection name='suyeonga' form={form} titleNm='○ 수용가-맨홀 매칭결과'><div className="w-[150px]">
<Input id="fileNm" type="file" />
</div></FormSection>
<FormSection name='pattern' form={form} titleNm='○ 오수량 시간패턴'><div className="w-[150px]">
<Input id="fileNm" type="file" />
</div></FormSection>
<FormSection name='inputdate' form={form} titleNm='○ 상수사용량 적용기간'>
<DatePicker selected={selectedDate} onSelect={(date: Date | undefined) => { if (date) setSelectedDate(date) }} mode={"single"} />
</FormSection>
<FormSection name='rtkSource' form={form} titleNm='○ 오수전환율'><Input className="h-[3.2rem] text-center text-xl w-[150px]" /></FormSection>
<div className="flex justify-end mt-1">
<Button type="submit">침입수분석 실행</Button>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<FormSection name='region' form={form} titleNm='○ 파일위치'>
<div className="w-[150px]">
<Input id="fileNm" type="file" />
<>
<BaseLayout titleName={{ mainTitle: '침입수 분석', firstCardTitle: '침입수 분석 자료 입력', secondCardTitle: '실측자료 등록' }} form={form} onSubmitEvent={() => { }} graphBtn={false} searchBox={{ title: '분석 대장지역 선택' }} >
<div className="grid gap-4">
<FormSection name='suyeongaPlace' form={form} titleNm='▷ 오수관망도'><div className="">
<Input id="fileNm" ref={fileInputRef1} type="file" />
</div></FormSection>
<FormSection name='suyeonga' form={form} titleNm='▷ 수용가-맨홀 매칭결과'><div className="w-[150px]">
<Input id="fileNm" ref={fileInputRef2} type="file" accept=".xls, .xlsx, .xlsm, .xltx" />
</div></FormSection>
<FormSection name='pattern' form={form} titleNm='▷ 오수량 시간패턴'><div className="w-[150px]">
<Input id="fileNm" ref={fileInputRef3} type="file" accept=".xls, .xlsx, .xlsm, .xltx" />
</div></FormSection>
<FormSection name='inputdate' form={form} titleNm='▷ 상수사용량 적용기간'>
<DatePicker selected={selectedDate} onSelect={(date: Date | undefined) => { if (date) setSelectedDate(date) }} mode={"single"} />
</FormSection>
<FormSection name='rtkSource' form={form} titleNm='▷ 오수전환율'><Input className="h-[3.2rem] text-center text-xl w-[150px]" /></FormSection>
<FormSection name='analysis information' form={form} titleNm='▷ 분석 정보'><Input className="h-[3.2rem] text-center text-xl w-[150px]" /></FormSection>
<div className="flex justify-center mt-1">
<Button type="submit" onClick={handleAnalysisClick}>침입수분석 실행</Button>
</div>
</FormSection>
</div>
</BaseLayout>
</div>
<div className="flex items-center gap-24">
<FormSection name='region' form={form} titleNm='▷ 유량자료 등록'>
<div className="w-[150px]">
<Input id="fileNm" ref={fileInputRef4} type="file" accept=".xls, .xlsx, .xlsm, .xltx" />
</div>
</FormSection>
<div className='mt-1'>
<Button type="submit" onClick={handleUploadClick}>자료 업로드</Button>
</div>
</div>
</BaseLayout>
</>
)
}
+26 -25
View File
@@ -88,17 +88,17 @@ export default function RTKForm() {
}
const [selectedDate, setSelectedDate] = useState(new Date())
return (
<BaseLayout titleName={{ mainTitle: 'RDII 분석', firstCardTitle: 'RDII 분석자료 입력' }} form={form} onSubmitEvent={() => { }} graphBtn={false}>
<BaseLayout searchBox={{ title: '분석 대장지역 선택' }} titleName={{ mainTitle: 'RDII 분석', firstCardTitle: 'RDII 분석자료 입력', secondCardTitle: '실측자료 등록' }} form={form} onSubmitEvent={() => { }} graphBtn={false} >
{[<div className="space-y-[1.2rem]" key="form-section">
<div className="grid grid-cols-2 gap-4">
<FormSection name="rtkSource" form={form} titleNm="○ RTK계수 출처"><Input
className="h-10 text-center text-xl w-[150px]"
placeholder=""
/></FormSection>
<FormSection name="rdiiArea" form={form} titleNm="○ RDII 기여면적(ha)"><Input
className="h-10 text-center text-xl w-[150px]"
placeholder=""
/></FormSection></div>
<FormSection name="rtkSource" form={form} titleNm="○ RTK계수 출처"><Input
className="h-10 text-center text-xl w-[150px]"
placeholder=""
/></FormSection>
<FormSection name="rdiiArea" form={form} titleNm="○ RDII 기여면적(ha)"><Input
className="h-10 text-center text-xl w-[150px]"
placeholder=""
/></FormSection></div>
<div className="grid grid-cols-2">
<div>
<div className="mb-[1.2rem] text-xl font-medium">○ 단위도 계수</div>
@@ -132,23 +132,24 @@ export default function RTKForm() {
</div>
</div>
<div className="grid grid-cols-2 gap-4">
<FormSection name="suyeonga" form={form} titleNm="○ 오수관망도"><div className="w-[150px]">
<Input id="fileNm" type="file" />
</div></FormSection>
<FormSection name="regopm" form={form} titleNm="○ 수용가-맨홀 매칭결과"><div className="w-[150px]">
<Input id="fileNm2" type="file" />
</div></FormSection>
<FormSection name='date' form={form} titleNm='○ 상수사용량 적용기간'>
<DatePicker selected={selectedDate} onSelect={(date: Date | undefined) => { if (date) setSelectedDate(date) }} mode={"single"} />
</FormSection>
<FormSection name='rate' form={form} titleNm='○ 오수전환율'><Input className="h-[3.2rem] text-center text-xl w-[150px]" /></FormSection>
<FormSection name="rain" form={form} titleNm="○ 강우자료"><div className="w-[150px]">
<Input id="fileNm3" type="file" />
</div></FormSection>
<FormSection name="suyeonga" form={form} titleNm="○ 오수관망도"><div className="w-[150px]">
<Input id="fileNm" type="file" />
</div></FormSection>
<FormSection name="regopm" form={form} titleNm="○ 수용가-맨홀 매칭결과"><div className="w-[150px]">
<Input id="fileNm2" type="file" />
</div></FormSection>
<FormSection name='date' form={form} titleNm='○ 상수사용량 적용기간'>
<DatePicker selected={selectedDate} onSelect={(date: Date | undefined) => { if (date) setSelectedDate(date) }} mode={"single"} />
</FormSection>
<FormSection name='rate' form={form} titleNm='○ 오수전환율'><Input className="h-[3.2rem] text-center text-xl w-[150px]" /></FormSection>
<FormSection name="rain" form={form} titleNm="○ 강우자료"><div className="w-[150px]">
<Input id="fileNm3" type="file" />
</div></FormSection>
<FormSection name='rate' form={form} titleNm='○ 분석 정보'><Input className="h-[3.2rem] text-center text-xl w-[150px]" /></FormSection>
</div>
<div className="flex justify-end mt-1">
<Button type="submit">RDII분석 실행</Button>
</div>
<div className="flex justify-end mt-1">
<Button type="submit">RDII분석 실행</Button>
</div>
</div>
]}
</BaseLayout >
+1 -1
View File
@@ -57,7 +57,7 @@ const Result = () => {
}
})
return (
<BaseLayout searchBox={{labelNm: {first: "분석기간",second: "침입수",third: "처리장",fourth: "처리구역",},searchChk: true,}} titleName={{ mainTitle: '분석결과', firstCardTitle: '분석이력', secondCardTitle:'RDII 산정결과 현황'}} form={form} onSubmitEvent={() => { }} graphBtn={true}>
<BaseLayout searchBox={{labelNm: {first: "분석기간",second: "분석구분",third: "하수처리장",fourth: "하수처리구역",},searchChk: true,}} titleName={{ mainTitle: '분석결과', firstCardTitle: '분석이력', secondCardTitle:'RDII 산정결과 현황'}} form={form} onSubmitEvent={() => { }} graphBtn={true}>
{[<div key='table1'>
<div className="mb-[1.2rem] text-xl font-medium">○ 침입수 산정결과 현황</div>
<UiTable
+10 -10
View File
@@ -1,9 +1,10 @@
import './styles/base.css'
import './styles/components.css'
import "./styles/base.css";
import "./styles/components.css";
import type { Metadata } from "next";
import { cookies } from "next/headers";
import { StoreProvider } from './store'
import { ClientLayout } from './clientLayout'
import { StoreProvider } from "./store/store-provider";
import { AuthWrapper } from "./components/lib/auth";
import { ClientLayout } from "./clientLayout";
export const metadata: Metadata = {
title: "디지털 하수관로",
@@ -20,18 +21,17 @@ export default async function RootLayout({
}: Readonly<{
children: React.ReactNode;
}>) {
const theme = (await cookies()).get("site-theme-key");
return (
<html lang="en" data-theme={theme?.value}>
<body>
<StoreProvider>
<ClientLayout>
{children}
</ClientLayout>
<StoreProvider>
<AuthWrapper>
<ClientLayout>{children}</ClientLayout>
</AuthWrapper>
</StoreProvider>
</body>
</html>
)
);
}
+116 -73
View File
@@ -1,16 +1,15 @@
'use client'
import { SearchDiv, SearchFormLeft, SearchFormRight, UiTable } from '@common/business_components/ui'
import { Button, DatePicker, Input, Label } from '@common/components/ui'
import React, { useState } from 'react'
import React, { useEffect, useState } from 'react'
import FileUploadForm from '../../components/ui/fileUploadForm'
import ListDiv from '@common/business_components/ui/list_div'
import ContentLayout from '@/components/ui/contentLayout'
import { tableData } from '../oldPp/page'
import { searchData } from '@/components/lib/common/apiHelpers'
import { tableHeadlist } from '..'
import { handleDownload } from '@/components/lib/utils/fileDownload'
import { handleUpload } from '@/components/lib/utils/fileUploadUtil'
import { formatDate } from '@/components/lib/common/date'
import { formatDate } from '@/components/lib/utils/date'
import { deleteData, getData, postData } from '@/components/lib/api'
const Page = () => {
const [fromDate, setFromDate] = useState(new Date())
@@ -20,83 +19,127 @@ const Page = () => {
const [usr, setUsr] = useState('')
const [pjNm, setpjNm] = useState('')
const [fileNm, setFileNm] = useState('')
// TODO: 초기값 세팅필요
const [atflId, setAtflId] = useState('')
const [atflCd, setAtflCd] = useState('')
const [sbmrgPrevntBizSn, setSbmrgPrevntBizSn] = useState('')
const [tableData, setTableData] = useState<any>([{}])
const [curPage, setCurPage] = useState(1)
const fetchData = async () => {
const data = await searchData('v1/sbmrgPrevnt', {
fromRegDt: formatDate(fromDate),
fromMngYr: manageYear,
toMngYr: mngQu,
toRegDt: formatDate(toDate),
atflNm: pjNm,
rgtrNm: usr,
page: curPage - 1,
size: '10'
})
setTableData(data)
}
useEffect(() => {
setCurPage(1)
fetchData()
}, [])
const isChckFile = () => {
if (fileNm === '' || fileNm === undefined) {
alert('파일을 선택해주세요')
return false
}
// TODO: 추후 파일코드 동적으로 세팅
handleDownload('/attach-service/api/v1/download/6066b08c-2a55-438c-b8ff-2aed9739a0c6', fileNm)
handleDownload(`/attach-service/api/v1/download/${atflId}`, fileNm)
}
//TODO: 파일 업로드 처리
return (
<ContentLayout title='도시침수 예방사업'>
<SearchDiv>
<SearchFormLeft>
<div className='flex items-center gap-4'>
<div className='flex items-center gap-2'>
<Label className="w-20 text-xl text-gray-600">등록기간</Label>
<DatePicker mode={'single'}
selected={fromDate}
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }} />
<span>~</span>
<DatePicker mode={'single'}
selected={toDate}
onSelect={(date: Date | undefined) => { if (date) setToDate(date) }} />
const isDeleteFile = async () => {
if (fileNm === '' || fileNm === undefined) {
alert('삭제할 파일을 선택해주세요')
return false
}
const data = await getData(`/attach-service/api/v1/atfl/attachments/${atflId}`)
if (data) {
const delData = await deleteData(`v1/sbmrgPrevnt/${sbmrgPrevntBizSn}`)
if (delData) {
alert('삭제되었습니다.')
fetchData()
} else {
alert('삭제에 실패했습니다.')
}
}
}
const registFile = async (fileNm: string, year: string, quater: string, cd: string, id: string) => {
const data = await postData('v1/sbmrgPrevnt', {
atflNm: fileNm,
mngYr: year,
mngQu: quater,
atflCd: cd,
atflId: id
})
if (data.ok) { setAtflId(data.atflId); setAtflCd(data.atflCd) }
}
return (
<ContentLayout title='도시침수 예방사업'>
<SearchDiv>
<SearchFormLeft>
<div className='flex items-center gap-4'>
<div className='flex items-center gap-2'>
<Label className="w-20 text-xl text-gray-600">등록기간</Label>
<DatePicker mode={'single'}
selected={fromDate}
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }} />
<span>~</span>
<DatePicker mode={'single'}
selected={toDate}
onSelect={(date: Date | undefined) => { if (date) setToDate(date) }} />
</div>
<div className='flex items-center'>
<Label className="w-20 text-xl text-gray-600">관리년도</Label>
<Input
className='w-[100px]'
value={manageYear}
onChange={(e) => setManageYear(e.target.value)}
/>
<span>~</span>
<Input
className='w-[100px]'
value={mngQu}
onChange={(e) => setMngQu(e.target.value)}
/>
</div>
<div className='flex items-center'>
<Label className="w-20 text-xl text-gray-600">등록자</Label>
<Input
className='w-[100px]'
value={usr}
onChange={(e) => setUsr(e.target.value)}
/>
</div>
<div className='flex items-center'>
<Label className="w-20 text-xl text-gray-600">파일명</Label>
<Input
className='w-[100px]'
value={pjNm}
onChange={(e) => setpjNm(e.target.value)}
/>
</div>
</div>
<div className='flex items-center'>
<Label className="w-20 text-xl text-gray-600">관리년도</Label>
<Input
className='w-[100px]'
value={manageYear}
onChange={(e) => setManageYear(e.target.value)}
/>
<span>~</span>
<Input
className='w-[100px]'
value={mngQu}
onChange={(e) => setMngQu(e.target.value)}
/>
</div>
<div className='flex items-center'>
<Label className="w-20 text-xl text-gray-600">등록자</Label>
<Input
className='w-[100px]'
value={usr}
onChange={(e) => setUsr(e.target.value)}
/>
</div>
<div className='flex items-center'>
<Label className="w-20 text-xl text-gray-600">파일명</Label>
<Input
className='w-[100px]'
value={pjNm}
onChange={(e) => setpjNm(e.target.value)}
/>
</SearchFormLeft>
<SearchFormRight>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={async () => await fetchData() } >조회</Button>
</SearchFormRight>
</SearchDiv>
<ListDiv className="mt-4">
<div className="card-header flex items-center justify-between">
<h3 className="text-2xl font-medium">사업정보 등록현황</h3>
<div>
<Button className="px-4 py-2 !mr-[1.2rem] bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={isChckFile} >파일 다운로드</Button>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={isDeleteFile} >삭제</Button>
</div>
</div>
</SearchFormLeft>
<SearchFormRight>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={() => { searchData('v1/sbmrgPrevnt', { fromRegDt: formatDate(fromDate), fromMngYr: manageYear, toMngYr: mngQu, toRegDt: formatDate(toDate), atflNm: pjNm, rgtrNm: usr, page: '0', size: '10' }) }} >조회</Button>
</SearchFormRight>
</SearchDiv>
<ListDiv className="mt-4">
<div className="card-header flex items-center justify-between">
<h3 className="text-2xl font-medium">사업정보 등록현황</h3>
<div>
<Button className="px-4 py-2 !mr-[1.2rem] bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={isChckFile} >파일 다운로드</Button>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={() => { }} >삭제</Button>
</div>
</div>
<UiTable headName='' tableData={tableData} headlist={tableHeadlist} pageSize={10} total={10} cellClick={(index) => { if (index != null) { const fileName = tableData[index]?.fileNm ?? ""; setFileNm(fileName) } }} onPageChange={function (page: number): void {
throw new Error('Function not implemented.')
}}></UiTable>
</ListDiv>
<ListDiv className="mt-4">
<FileUploadForm title='도시침수 예방사업 사업추진현황 등록' onSubmit={()=>{}}/>
</ListDiv>
</ContentLayout>
)
<UiTable headName='' tableData={tableData} headlist={tableHeadlist} pageSize={10} total={10} cellClick={(index) => { if (index != null) { const fileName = tableData[index]?.fileNm ?? ""; setFileNm(fileName); setSbmrgPrevntBizSn(tableData[index]?.sbmrgPrevntBizSn) } }} onPageChange={async (page:number)=>{setCurPage(page); await fetchData()}}></UiTable>
</ListDiv>
<ListDiv className="mt-4">
<FileUploadForm title='도시침수 예방사업 사업추진현황 등록' onSubmit={async (file, year, quater, cd, id) => { await registFile(file, year, quater, cd, id) }} />
</ListDiv>
</ContentLayout>
)
}
export default Page
+1 -1
View File
@@ -1,5 +1,5 @@
export const tableHeadlist = [
{ id: 'no', title: 'NO' },
{ id: 'sbmrgPrevntBizSn', title: '일련번호' },
{ id: 'fileNm', title: '파일명' },
{ id: 'mngYr', title: '년도' },
{ id: 'mngQu', title: '분기' },
+67 -20
View File
@@ -1,17 +1,15 @@
'use client'
import { SearchDiv, SearchFormLeft, SearchFormRight, UiTable } from '@common/business_components/ui'
import { Button, DatePicker, Input, Label } from '@common/components/ui'
import React, { useState } from 'react'
import React, { useEffect, useState } from 'react'
import FileUploadForm from '../../components/ui/fileUploadForm'
import ListDiv from '@common/business_components/ui/list_div'
import ContentLayout from '@/components/ui/contentLayout'
import { tableHeadlist } from '..'
import { handleDownload } from '@/components/lib/utils/fileDownload'
import { searchData } from '@/components/lib/common/apiHelpers'
import { formatDate } from '@/components/lib/common/date'
// TODO: 임시 id
export const tableData = [{ 'no': '1', 'fileNm': '2023년 노후하수관로 정비사업', 'mngYr': '2023', 'mngQu': '1', 'registDt': '2023-10-01', 'registUsr': '홍길동' },]
import { formatDate } from '@/components/lib/utils/date'
import { deleteData, getData, postData } from '@/components/lib/api'
const Page = () => {
const [fromDate, setFromDate] = useState<Date>(new Date());
const [toDate, setToDate] = useState<Date>(new Date());
@@ -20,15 +18,66 @@ const Page = () => {
const [usr, setUsr] = useState('')
const [pjNm, setpjNm] = useState('')
const [fileNm, setFileNm] = useState('')
const isChckFile = () => {
if (fileNm === '' || fileNm === undefined) {
alert('파일을 선택해주세요')
return false
}
// TODO: 추후 파일코드 동적으로 세팅
handleDownload('/sn/attach-service/api/v1/download/6066b08c-2a55-438c-b8ff-2aed9739a0c6', fileNm)
return true
}
const [atflId, setAtflId] = useState('')
const [atflCd, setAtflCd] = useState('')
const [sbmrgPrevntBizSn, setSbmrgPrevntBizSn] = useState('')
const [tableData, setTableData] = useState<any>([{}])
const [curPage, setCurPage] = useState(1)
// 데이터 조회
const fetchData = async () => {
const data = await searchData('v1/dcrpPpl', {
fromRegDt: formatDate(fromDate),
fromMngYr: manageYear,
toMngYr: mngQu,
toRegDt: formatDate(toDate),
atflNm: pjNm,
rgtrNm: usr,
page: curPage - 1,
size: '10'
})
setTableData(data)
}
useEffect(() => {
setCurPage(1)
fetchData()
}, [])
// 파일 다운로드
const isChckFile = () => {
if (fileNm === '' || fileNm === undefined) {
alert('파일을 선택해주세요')
return false
}
handleDownload(`/attach-service/api/v1/download/${atflId}}`, fileNm)
return true
}
// 파일 삭제
const isDeleteFile = async () => {
if (fileNm === '' || fileNm === undefined) {
alert('삭제할 파일을 선택해주세요')
return false
}
const data = await getData(`/attach-service/api/v1/atfl/attachments/${atflId}`)
if (data) {
const delData = await deleteData(`v1/sbmrgPrevnt/${sbmrgPrevntBizSn}`)
if (delData) {
alert('삭제되었습니다.')
fetchData()
} else {
alert('삭제에 실패했습니다.')
}
}
}
// 파일 등록
const registFile = async (fileNm: string, year: string, quater: string, cd: string, id: string) => {
const data = await postData('v1/dcrpPpl', {
atflNm: fileNm,
mngYr: year,
mngQu: quater,
atflCd: cd,
atflId: id
})
if (data.ok) { setAtflId(data.atflId); setAtflCd(data.atflCd) }
}
return (
<ContentLayout title='노후 하수관로 정비사업'>
<SearchDiv>
@@ -77,7 +126,7 @@ const Page = () => {
</div>
</SearchFormLeft>
<SearchFormRight>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 mr-2" size="sm" onClick={() => { searchData('v1/dcrpPpl', { fromRegDt: formatDate(fromDate), fromMngYr: manageYear, toMngYr: mngQu, toRegDt: formatDate(toDate), atflNm: pjNm, rgtrNm: usr, page: '0', size: '10' }) }}>조회</Button>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 mr-2" size="sm" onClick={async () => {await fetchData()}}>조회</Button>
</SearchFormRight>
</SearchDiv>
<ListDiv className="mt-4">
@@ -85,15 +134,13 @@ const Page = () => {
<h3 className="text-2xl font-medium">사업정보 등록현황</h3>
<div>
<Button className="px-4 py-2 !mr-[1.2rem] bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={isChckFile}>파일 다운로드</Button>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" >삭제</Button>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700 !mr-[1.2rem]" size="sm" onClick={isDeleteFile}>삭제</Button>
</div>
</div>
<UiTable headName='' tableData={tableData} headlist={tableHeadlist} pageSize={10} total={20} children={undefined} cellClick={(index) => { if (index != null) { const fileName = tableData[index]?.fileNm ?? ""; setFileNm(fileName) } }} onPageChange={function (page: number): void {
throw new Error('Function not implemented.')
}}></UiTable>
<UiTable headName='' tableData={tableData} headlist={tableHeadlist} pageSize={10} total={20} children={undefined} cellClick={(index) => { if (index != null) { const fileName = tableData[index]?.fileNm ?? ""; setFileNm(fileName); setSbmrgPrevntBizSn(tableData[index]?.sbmrgPrevntBizSn) } }} onPageChange={async (page:number)=>{setCurPage(page); await fetchData()}}></UiTable>
</ListDiv>
<ListDiv className="mt-4">
<FileUploadForm title='노후 하수관로 정비사업 주진현황 등록' onSubmit={() => { }} />
<FileUploadForm title='노후 하수관로 정비사업 주진현황 등록' onSubmit={async (file, year, quater, cd, id) => { await registFile(file, year, quater, cd, id) }} />
</ListDiv>
</ContentLayout>
)
+1 -45
View File
@@ -1,45 +1 @@
'use client'
import { type ReactNode, createContext, useContext, useRef } from 'react'
import { useStore } from 'zustand'
import { type SnStore, StoreZus } from './store'
export type StoreApi = ReturnType<typeof StoreZus>
export const StoreContext = createContext<StoreApi | undefined>(
undefined,
)
export interface StoreProviderProps {
children: ReactNode
}
export const StoreProvider = ({
children,
}: StoreProviderProps) => {
const storeRef = useRef<StoreApi | null>(null)
if (!storeRef.current) {
storeRef.current = StoreZus()
}
return (
<StoreContext.Provider value={storeRef.current}>
{children}
</StoreContext.Provider>
)
}
export const useSnStore = <T,>(
//selector: (store: ReturnType<typeof StoreZus>) => T,
selector: (store: SnStore) => T,
): T => {
const storeContext = useContext(StoreContext)
if (!storeContext) {
throw new Error(`useStore must be used within StoreProvider`)
}
return useStore(storeContext, selector)
}
export { useUserStore, type IUserInfo } from "./user-store";
-76
View File
@@ -1,76 +0,0 @@
export type TableUpperProps = {
id: string;
title: string;
upName?: string;
upSequnce?: number;
}
type PublicReuseFacility = {
sido: string,
sigungo: string,
facilityName: string,
location: string,
locationgubun: string,
facilityCapacity: string,
yn?: string,
authoDay?: string,
area?: string,
reuse?: string
}
const upHeadList:TableUpperProps[] = [
{ id: "sido", title: "자산ID"},
{ id: "sigungo", title: "설비시설"},
{ id: "facilityName", title: "주소"},
{ id: "location", title: "자산코드"},
{ id: "locationgubun", title: "자산명"},
{ id: "facilityCapacity", title: "용도"},
{ id: "yn", title: '신설/교체'},
{ id: "authoDay", title: '처리구역'},
{ id: "area", title: '내용연수' },
{ id: "reuse", title: '취득금액' },
];
const publicReuseFacilityUper:PublicReuseFacility[] = [
{
sido: "1048967",
sigungo: "관로",
facilityName: "양평군 양평읍 백안리 25-5전",
location: "S-T-S-2018000675",
locationgubun: "2018000675",
facilityCapacity: "오수관",
yn: "신설",
authoDay: "양평하수처리구역",
area: "30",
reuse: "28,313,220"
}
]
export type tableState = {
isInit: boolean;
upHeadList: TableUpperProps[];
publicReuseFacilityUper: PublicReuseFacility[];
}
type tableActions = {
decrementList: () => void
}
export type tableType = tableState & tableActions;
export const tableStateExport:tableState= {
isInit:false,
upHeadList: upHeadList,
publicReuseFacilityUper: publicReuseFacilityUper,
}
export const tableActionsExport:(set:any)=>tableActions=(set: any) => {
return {
decrementList:()=>set(
(state:tableState) => {
return (
{
upHeadList: state.upHeadList,
publicReuseFacilityUper: state.publicReuseFacilityUper.slice(0, state.publicReuseFacilityUper.length - 1)
})}
)
}
}
+27
View File
@@ -0,0 +1,27 @@
"use client";
import { createContext, useRef } from "react";
import { createUserStore } from "../store/user-store";
type StoreContextType = {
userStore: ReturnType<typeof createUserStore>;
};
export const StoreContext = createContext<StoreContextType | undefined>(
undefined,
);
export const StoreProvider = ({ children }: { children: React.ReactNode }) => {
const storeRef = useRef<StoreContextType | null>(null);
if (storeRef.current === null) {
storeRef.current = {
userStore: createUserStore(),
};
}
return (
<StoreContext.Provider value={storeRef.current}>
{children}
</StoreContext.Provider>
);
};
-14
View File
@@ -1,14 +0,0 @@
import { createStore } from 'zustand/vanilla';
import { tableActionsExport, tableStateExport, type tableState, type tableType } from './table';
export type SnStore = tableType;
//export type SnStore = ReturnType<typeof StoreZus>["getState"];
export const StoreZus = (initState: tableState = tableStateExport) => {
return createStore<SnStore>()((set) => {
return {
...initState,
...tableActionsExport(set)
}
})
}
//store 등록하는 부분
-116
View File
@@ -1,116 +0,0 @@
export type TableUpperProps = {
id: string,
title: string,
upSequnce?: number,
upName?: string
}
type PublicReuseFacility = {
sido: string,
sigungo: string,
facilityName: string,
location: string,
locationgubun: string,
facilityCapacity: string,
yn?: string,
authoDay?: string,
area?: string,
reuse?: string
}
const upHeadList:TableUpperProps[] = [
{ id: "sido", title: "자산ID"},
{ id: "sigungo", title: "설비시설"},
{ id: "facilityName", title: "주소"},
{ id: "location", title: "자산코드"},
{ id: "locationgubun", title: "자산명"},
{ id: "facilityCapacity", title: "용도"},
{ id: "yn", title: '신설/교체'},
{ id: "authoDay", title: '처리구역'},
{ id: "area", title: '내용연수' },
{ id: "reuse", title: '취득금액' },
];
const publicReuseFacilityUper:PublicReuseFacility[] = [
{
sido: "1048967",
sigungo: "관로",
facilityName: "양평군 양평읍 백안리 25-5전",
location: "S-T-S-2018000675",
locationgubun: "2018000675",
facilityCapacity: "오수관",
yn: "신설",
authoDay: "양평하수처리구역",
area: "30",
reuse: "28,313,220"
}
]
export type tableState = {
isInit: boolean;
upHeadList: TableUpperProps[];
publicReuseFacilityUper: PublicReuseFacility[];
}
type tableActions = {
setHeadList: (newHeadList: TableUpperProps[]) => void
setTableData: (newTableDataList: PublicReuseFacility[]) => void
decrementList: () => void
addRow: (newTableData: PublicReuseFacility) => void
}
export type tableType = tableState & tableActions;
export const tableStateExport:tableState= {
isInit:false,
upHeadList: [
{ id: "sido", title: "자산ID"},
{ id: "sigungo", title: "설비시설"},
{ id: "facilityName", title: "주소"},
{ id: "location", title: "자산코드"},
{ id: "locationgubun", title: "자산명"},
{ id: "facilityCapacity", title: "용도"},
{ id: "yn", title: '신설/교체'},
{ id: "authoDay", title: '처리구역'},
{ id: "area", title: '내용연수' },
{ id: "reuse", title: '취득금액' },
],
publicReuseFacilityUper: publicReuseFacilityUper,
}
export const tableActionsExport:(set:any)=>tableActions=(set: any) => {
return {
// 마지막 데이터 삭제
decrementList: ()=>set(
(state: tableState) => {
return (
{
...state,
upHeadList: state.upHeadList,
publicReuseFacilityUper: state.publicReuseFacilityUper.slice(0, state.publicReuseFacilityUper.length - 1)
})}
),
// 데이터 추가
addRow: (newTableData: PublicReuseFacility)=>set(
(state: tableState) => {
console.log('asdfasdfadsf')
return (
{
...state,
upHeadList: state.upHeadList,
publicReuseFacilityUper: [...state.publicReuseFacilityUper, newTableData]
})}
),
// 테이블 헤더 변경
setHeadList: (newHeadList: TableUpperProps[]) => set(
(state: tableState) => ({
...state,
upHeadList: newHeadList
})
),
// 시설 목록 데이터 변경
setTableData: (newTableData: PublicReuseFacility[]) => set(
(state: tableState) => ({
...state,
publicReuseFacilityUper: newTableData
})
),
}
}
+74
View File
@@ -0,0 +1,74 @@
"use client";
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { createStore } from "zustand/vanilla";
export interface IUserInfo {
regDt: string;
mdfcnDt: string;
rgtr: string;
mdfr: string;
adminRoleYn: string;
userUnqId: string;
userId: string;
userName: string;
email: string;
encryptedPassword: string;
refreshToken: string;
userStateCode: string;
lastLoginDate: string;
loginFailCount: number;
pswdHnt: string;
pswdAns: string;
mphn: string;
telno: string;
zip: string;
addr: string;
daddr: string;
laeSeCd: string;
ogdpSeCd: string;
aprvYn: string;
autzrId: string;
expryYmd: string;
lastPswdChgDt: string;
googleId: string;
kakaoId: string;
naverId: string;
isSocialUser: boolean;
hasPassword: boolean;
}
export type UserState = {
userInfo: IUserInfo | null;
};
type UserStore = {
userInfo: IUserInfo | null;
setUserInfo: (userInfo: IUserInfo | null) => void;
};
// ✅ zustand 기본 create + persist 적용
export const useUserStore = create<UserStore>()(
persist(
(set) => ({
userInfo: null,
setUserInfo: (userInfo) => set({ userInfo }),
}),
{
name: "user-store", // localStorage 키
partialize: (state) => ({ userInfo: state.userInfo }), // 선택적 저장
},
),
);
export const defaultInitState: UserState = {
userInfo: null,
};
export const createUserStore = (initState: UserState = defaultInitState) => {
return createStore<UserStore>()((set) => ({
...initState,
setUserInfo: (userInfo: IUserInfo | null) => set(() => ({ userInfo })),
}));
};
+18 -1
View File
@@ -46,9 +46,26 @@ export function middleware(req: NextRequest) {
});
}
if (pathname.startsWith("/user-service")) {
const requestHeaders = new Headers(req.headers);
const newUrl = `${serverApiUrl}${pathname}`;
console.log(
`[Middleware] Rewriting from '/user-service' path to: ${newUrl}`,
);
return NextResponse.rewrite(new URL(newUrl), {
headers: requestHeaders,
});
}
return NextResponse.next();
}
export const config = {
matcher: ["/server/:path*","/geoserver/:path*", "/attach-service/:path*"],
matcher: [
"/server/:path*",
"/geoserver/:path*",
"/attach-service/:path*",
"/user-service/:path*",
],
};
@@ -130,7 +130,7 @@ export default function LineBarchart({
className="text-[12px] font-bold"
tickCount={6}
orientation="left"
domain={[0, Math.ceil(lineMaxValue * 1.1)]}
domain={[0, Math.ceil(lineMaxValue * 1)]}
label={{ value: yFieldText, angle: -90, position: 'insideLeft' }}
/>}
{/* 오른쪽 Y축: barVal */}
@@ -139,7 +139,7 @@ export default function LineBarchart({
className="text-[12px] font-bold"
tickCount={6}
orientation="right"
domain={[0, Math.ceil(barMaxValue * 1.1)]}
domain={[0, Math.ceil(barMaxValue * 1)]}
label={{ value: yFieldText2, angle: -90, position: 'insideRight' }}
reversed={true}
/>}
@@ -47,7 +47,17 @@ export const excelArrayStyle = async (data: ArrayBuffer, range: [typeof sheetPar
rangeCells?.style((styleQ)=>{
makeCellStyle(styleQ)
});
} )
// 모든 데이터 셀에 세로 가운데 정렬 적용
if (item.data && item.data.length > 0) {
const numCols = item.data[0]?.length || 0;
const numRows = item.data.length;
const dataRange = workbook.activeSheet(index)?.sheet(index)?.range(`A1:${String.fromCharCode(65 + numCols - 1)}${numRows}`);
dataRange?.style((styleQ) => {
styleQ.verticalAlignment("center");
});
}
});
}
makeExcelFile(workbook, fileNm)
@@ -15,9 +15,30 @@ export const downloadExcel = ({ data, fileName = new Date().getTime().toString()
excelStyle(XLSX.write(workbook, { bookType: "xlsx", type: "buffer" }), headerRange, fileName);
};
export const sheetParameter ={
data:[[]], headerNum:0, headerRange:'A1:V3', sheetName:'Sheet1', startCol:0
}
export const downloadMultipleExcel = (fileName = new Date().getTime().toString() + '.xlsx', sheetArray: Array<typeof sheetParameter>): Promise<JSON | undefined> => {
const workbook = XLSX.utils.book_new();
for (let i = 0; i < sheetArray.length; i++) {
// Create a new worksheet for each sheet
const worksheet = XLSX.utils.aoa_to_sheet(sheetArray[i]?.data || [[]]);
// Add data to the worksheet starting from the specified header number
if (sheetArray&&sheetArray[i]?.headerNum) {
XLSX.utils.sheet_add_aoa(worksheet, sheetArray[i]?.data || [[]], { origin: `A${sheetArray[i]?.headerNum}` });
}
// Append the worksheet to the workbook with the specified sheet name
XLSX.utils.book_append_sheet(workbook, worksheet, sheetArray[i]?.sheetName);
}
if (sheetArray.length > 0) {
excelArrayStyle(XLSX.write(workbook, { bookType: "xlsx", type: "buffer" }), sheetArray, fileName);
}
return Promise.resolve(undefined);
};
export const filePicked=(oFile: File, headerNum:number=0):Promise<JSON | undefined> =>{
export const filePicked=(oFile: File, headerNum:number=0, dateType="yyyymmdd"):Promise<JSON | undefined> =>{
// Create A File Reader HTML5
const reader = new FileReader();
return new Promise<JSON | undefined>((resolve, reject) => {
@@ -30,7 +51,7 @@ export const filePicked=(oFile: File, headerNum:number=0):Promise<JSON | undefin
return;
}
//셀데이터에서 데이트 형식으로 입력하면 yyyymmdd 형식으로 변환
const wb = XLSX.read(data, { type: 'binary', cellDates: true, dateNF: "yyyymmdd" });
const wb = XLSX.read(data, { type: 'binary', cellDates: true, dateNF: dateType });
let jsonXls: JSON | undefined;
// Loop Over Each Sheet
wb.SheetNames.forEach(function (sheetName,index ) {
@@ -104,7 +125,7 @@ export const filePickedArray=(oFile: File, headerNum:number=0):Promise<JSON[] |
export const filePickedBlob=(oFile: ArrayBuffer, data:[][],fileNm:string, headerNum:number=0, headerRange='A1:V3'):Promise<JSON | undefined> =>{ // Create A File Reader HTML5
export const filePickedBlob=(oFile: ArrayBuffer, data:[][],fileNm:string, headerNum:number=0, headerRange='A1:V3', startCol?:number):Promise<JSON | undefined> =>{ // Create A File Reader HTML5
return new Promise<JSON | undefined>(() => {
// Ready The Event For When A File Gets Selected
const wb = XLSX.read(oFile, { type: 'binary' });
@@ -116,7 +137,8 @@ export const filePickedBlob=(oFile: ArrayBuffer, data:[][],fileNm:string, header
if (sheet) {
//오리진 확인 test 필요
// const sheet = XLSX.utils.json_to_sheet(data);
XLSX.utils.sheet_add_aoa(sheet, data, { origin: 'A'+headerNum });
const excelStartCol = startCol?startCol.toString():'A';
XLSX.utils.sheet_add_aoa(sheet, data, { origin: excelStartCol+headerNum });
// XLSX.utils.book_append_sheet(wb, sheet, 'test');
await excelStyle(XLSX.write(wb, { bookType: "xlsx", type: "buffer" }), headerRange, fileNm)
} else {
@@ -127,9 +149,6 @@ export const filePickedBlob=(oFile: ArrayBuffer, data:[][],fileNm:string, header
});
}
export const sheetParameter ={
data:[[]], headerNum:0, headerRange:'A1:V3'
}
export const filePickedBlobArray= (oFile: ArrayBuffer,fileNm:string, sheetArray: [typeof sheetParameter]):Promise<JSON | undefined> =>{ // Create A File Reader HTML5
return new Promise<JSON | undefined> (async () => {
// Ready The Event For When A File Gets Selected
@@ -142,7 +161,8 @@ export const sheetParameter ={
if (sheet) {
//오리진 확인 test 필요
// const sheet = XLSX.utils.json_to_sheet(data);
XLSX.utils.sheet_add_aoa(sheet, sheetArray[index].data, { origin: 'A'+sheetArray[index].headerNum });
const startCol = sheetArray[index].startCol?sheetArray[index].startCol.toString():'A';
XLSX.utils.sheet_add_aoa(sheet, sheetArray[index].data, { origin: startCol+sheetArray[index].headerNum });
// XLSX.utils.book_append_sheet(wb, sheet, 'test');
} else {
console.error(`Sheet "${sheetName}" is undefined.`);
@@ -72,7 +72,7 @@ export function UiTable({ tableData, headlist, pageSize, total, headName, childr
onClick={() => handleCellClick(index, head.id)}
key={`cell-${head.id}-${index}`}
>
{String(el[head.id]).includes('.')
{typeof el[head.id] !== 'number'?String(el[head.id] ?? ''): String(el[head.id]).includes('.')
? String(el[head.id]).split('.').map((part, index) =>
index === 0 ? part.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : part
).join('.')
@@ -86,7 +86,7 @@ export function UiTable({ tableData, headlist, pageSize, total, headName, childr
onClick={() => handleCellClick(index, head.id)}
key={`cell-${head.id}-${index}`}
>
{String(el[head.id]).includes('.')
{typeof el[head.id] !== 'number'?String(el[head.id] ?? ''): String(el[head.id]).includes('.')
? String(el[head.id]).split('.').map((part, index) =>
index === 0 ? part.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : part
).join('.')