Compare commits

..
Author SHA1 Message Date
yschoi 719052d777 Merge remote-tracking branch 'origin/main' into iipbs/sn/dev 2025-07-26 15:34:39 +09:00
mind-one002 22d71c30f9 Merge branch 'iipbs/wr/dev' 2025-07-26 15:15:01 +09:00
mind-one005 562a562d15 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend 2025-07-26 15:14:03 +09:00
mind-one005 f94cb832a0 Merge branch 'iipbs/common/main' into iipbs/sn/dev 2025-07-26 15:04:05 +09:00
mind-one005 8fbecc41a5 LineBarChart2 비율대로 보이도록 2025-07-26 15:03:09 +09:00
leedj312 87be84f620 실적등록 수정 2025-07-26 13:23:11 +09:00
leedj312 7661823c8b 스토어 아이디 env 프로덕션 수정 2025-07-26 10:30:00 +09:00
rsone001 2aba7bb16e ESlint 문법 에러 수정 2025-07-25 22:49:06 +09:00
mind-one005 735304cee0 Merge branch 'iipbs/sn/dev' 2025-07-25 20:43:15 +09:00
mind-one005 1ca2900a63 조회click시 paging초기화 2025-07-25 20:41:38 +09:00
100JM 53c966fc11 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend 2025-07-25 20:09:05 +09:00
chanii8 03efe1dfb5 Merge branch 'iipbs_cs' of https://www.onasys.co.kr:3000/ONAANDALL/frontend 2025-07-25 19:52:17 +09:00
chanii8 4ee840fa82 chore: pnpm-lock 업데이트 2025-07-25 18:56:54 +09:00
swcho 64a8ebbdbb Merge branch 'iipbs/sn/ii' into iipbs/sn/dev 2025-07-25 18:50:37 +09:00
swcho e8da4ac531 fix: 하수관망도, I/I 분석, 운영정보 페이지 페이지네이션 에러 수정 2025-07-25 18:50:12 +09:00
leedj312 bf77775cd6 Merge commit '711adc2e170ddc84dc81638ff6b85e8aa416df43' into iipbs/wr/dev 2025-07-25 18:47:15 +09:00
leedj312 711adc2e17 폼 오류 수정 2025-07-25 18:45:31 +09:00
chanii8 9a62ef6276 [apps/cs] chore: 숫자에 toLocaleString() 메서드 적용 2025-07-25 18:44:30 +09:00
JIeunhuh 552ae18feb Merge commit '4920b4c1a26d81c9078e22c49bff1adda3eb834f' into iipbs/wr/dev 2025-07-25 18:39:31 +09:00
chanii8 bd999eb0f3 [apps/cs] chore: 수정 요청 사항 반영 2025-07-25 18:38:56 +09:00
JIeunhuh bd0c22c129 Merge commit 'd389390b0c25db4a9b229a2d76e99ff922d951c6' into iipbs/wr/dev 2025-07-25 18:37:36 +09:00
JIeunhuh 4920b4c1a2 수요처 추가 2025-07-25 18:35:57 +09:00
swcho ed4279d321 fix: SearchModal 페이지네이션 초기화 2025-07-25 18:31:09 +09:00
JIeunhuh d389390b0c 수요처 상세, 리스트 현황 구현 완료 2025-07-25 18:30:14 +09:00
JIeunhuh 60ae8c9e72 수요처 작업중 2025-07-25 18:08:28 +09:00
swcho e3de7ec112 Merge branch 'iipbs/sn/ii' into iipbs/sn/dev 2025-07-25 18:02:18 +09:00
swcho 61ed66d4f0 feat: SearchModal 데이터 포매팅 2025-07-25 18:00:05 +09:00
100JM 393e174a6d 연계 모듈 관리 2025-07-25 17:39:13 +09:00
leedj312 c4f2af0bfe rgtr nullish 작업 2025-07-25 16:58:52 +09:00
mind-one005 294da35347 오류 표시 수정 2025-07-25 16:32:13 +09:00
chanii8 78eb2d8fcd [apps/cs] chore: 이미지 등록 폼 수정 2025-07-25 15:11:41 +09:00
swcho 89ca295b69 fix:
- 침입수, RDII 분석결과 페이지 페이징 처리, 삭제 후 조회 로직 에러 수정
2025-07-25 15:08:39 +09:00
mind-one005 9a3378d07b 반올림 & , 적용 2025-07-25 15:02:04 +09:00
Your Name 190adb6bc1 테이블 헤더 위치 좀더 위로 수정 2025-07-25 14:30:59 +09:00
chanii8 d7233992fe [apps/cs] feat: 접속자 통계 페이지 레이아웃 작업 2025-07-25 14:30:33 +09:00
swcho b980321557 fix:
- 운영정보 검색 한 페이지에 4개씩으로 변경 (화면 비율 고려)
- 상세페이지 X 버튼 위치 고정
2025-07-25 14:24:24 +09:00
Your Name 59bccfe1d6 테이블 및 굵은영역 뒷쪽에 글자보이는 문제해결 2025-07-25 14:03:52 +09:00
swcho 590adb5b4e fix: 오수펌프장, 우수펌프장 명칭 바뀐 것 수정 2025-07-25 11:42:51 +09:00
mind-one005 c204d90d14 rdii 그래프 수정 2025-07-25 11:27:57 +09:00
mind-one005 e0bc5869d6 Merge branch 'iipbs/common/main' into iipbs/sn/dev 2025-07-25 10:54:00 +09:00
mind-one005 84ff24c5b5 LineBarChart2 추가 2025-07-25 10:52:47 +09:00
mind-one005 b8da4d7d42 Merge branch 'iipbs/common/main' into iipbs/sn/dev 2025-07-25 10:45:01 +09:00
mind-one005 e1b48ab7c8 Merge branch 'iipbs/common/main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs/common/main 2025-07-25 10:44:19 +09:00
mind-one005 4c3be448f0 LineBarChar2 추가 2025-07-25 10:42:36 +09:00
jyha00 8ede32f4c4 수요처폼 글씨 크기 변경 2025-07-25 10:41:41 +09:00
swcho be47ac0edb fix:
- 하수처리시설 정보에서 디지털 자료관 연계 정보 기능 주석 처리
- 운영정보 검색 시 페이지 리셋 추가
- 하수관로 연계정보에서 사업명 줄바꿈 처리
2025-07-25 10:06:19 +09:00
swcho 0795299b48 feat: 상류관로 보기 기능에 로딩바 추가 2025-07-25 00:58:55 +09:00
swcho 3380addd78 Merge branch 'iipbs/common/main' into iipbs/sn/ii 2025-07-25 00:50:40 +09:00
swcho 2862fdc9fd fix: Gis.js fetch 로직 에러 수정 2025-07-25 00:50:03 +09:00
swcho c9e413a3d3 Merge branch 'iipbs/sn/dev' into iipbs/sn/ii 2025-07-25 00:28:27 +09:00
swcho 6413bc6b18 feat: featureClickEventPopup 하수맨홀 선택 시 상류관로 보기 기능 구현 2025-07-25 00:28:01 +09:00
swcho fbb47c2593 Merge branch 'iipbs/common/main' into iipbs/sn/ii 2025-07-25 00:25:24 +09:00
swcho a446739432 feat:
- gis.select.js 피처 다중 셀렉트 기능 추가
- Gis.js 상류관로 조회 메서드 추가
- GisLonLat 주석 처리(위경도 표시X)
2025-07-25 00:23:02 +09:00
mind-one005 b513fddbd5 LineBarchart 1차 2025-07-24 22:13:37 +09:00
mind-one005 c0c7bdfa5b Merge branch 'iipbs/sn/dev' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs/sn/dev 2025-07-24 22:06:34 +09:00
mind-one005 55b8e91298 Merge branch 'iipbs/common/main' into iipbs/sn/dev 2025-07-24 22:04:25 +09:00
mind-one005 ea125605d1 Merge branch 'iipbs/common/main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs/common/main 2025-07-24 22:01:01 +09:00
mind-one005 8353800dac feat: LineBarChar.tsx Null 체크 추가 2025-07-24 22:00:58 +09:00
83 changed files with 6103 additions and 452 deletions
@@ -0,0 +1,2 @@
import { LinkPage } from "@/pages/link";
export default LinkPage;
@@ -0,0 +1,10 @@
import { ModifyLinkPage as VModifyLinkPage } from "@/pages/link";
export default async function ModifyLinkPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
return <VModifyLinkPage linkSn={id} />;
};
@@ -0,0 +1,2 @@
import { RegistLinkPage } from "@/pages/link";
export default RegistLinkPage;
@@ -0,0 +1,2 @@
import { LinkLogPage } from "@/pages/linkLog";
export default LinkLogPage;
@@ -0,0 +1,2 @@
import { LinkParamsPage } from "@/pages/linkParams";
export default LinkParamsPage;
@@ -0,0 +1,2 @@
import { LinkStatsPage } from "@/pages/linkStats";
export default LinkStatsPage;
@@ -0,0 +1,2 @@
import { LinkTablePage } from "@/pages/linkTable";
export default LinkTablePage;
@@ -0,0 +1,2 @@
import { UserStatisticsPage } from "@/pages/user-statistics";
export default UserStatisticsPage;
@@ -0,0 +1,191 @@
import axios from "axios";
import {
type LinkService,
type LinkSearchParam,
type LinkList,
type LinkFormData,
type LinkInfo,
type LinkLogList,
type LinkStatsList,
type LinkVrblList,
type LinkVrblFormData,
type LinkVrbl,
type LinkTable,
type LinkTableColumnsList,
type LinkTableColumns,
type LinkTableColData,
type LinkTableFormData,
} from "../model/link-interface";
export class LinkApiService implements LinkService {
public async getLinkList(params: LinkSearchParam): Promise<LinkList> {
const response = await axios.get<LinkList>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkList`,
{ params }
);
return response.data;
}
public async getLinkInfo(linkSn: string): Promise<LinkInfo> {
const response = await axios.get<LinkInfo>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkInfo/${linkSn}`,
);
return response.data;
}
public async linkQuickStart(linkSn: string): Promise<string> {
const response = await axios.patch<string>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/linkQuickStart/${linkSn}`,
);
return response.data;
}
public async updateLinkInfo(data: LinkFormData): Promise<void> {
await axios.put<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/updateLinkInfo`,
data,
);
}
public async insertLinkInfo(data: LinkFormData): Promise<void> {
await axios.post<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/insertLinkInfo`,
data,
);
}
public async deleteLink(linkSn: string): Promise<void> {
await axios.delete<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/deleteLink/${linkSn}`,
);
}
public async getLinkLogList(params: LinkSearchParam): Promise<LinkLogList> {
const response = await axios.get<LinkLogList>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/selectLinkLoglist`,
{ params }
);
return response.data;
}
public async getLinkStatsList(params: LinkSearchParam): Promise<LinkStatsList> {
const response = await axios.get<LinkStatsList>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/selectLinkStats`,
{ params }
);
return response.data;
}
public async getLinkVrblList(linkSn: string): Promise<LinkVrblList> {
const response = await axios.get<LinkVrblList>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkVrblList/${linkSn}`,
);
return response.data;
}
public async insertLinkVrbl(data: LinkVrblFormData): Promise<number> {
const response = await axios.post<number>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/insertLinkVrbl`,
data,
);
return response.data;
}
public async deleteLinkVrbl(data: string[]): Promise<void> {
await axios.delete<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/deleteLinkVrbl`,
{
data
}
);
}
public async getLinkVrblInfo(linkVrblSn: string): Promise<LinkVrbl> {
const response = await axios.get<LinkVrbl>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkVrblInfo/${linkVrblSn}`,
);
return response.data;
}
public async updateLinkVrblInfo(data: LinkVrblFormData): Promise<void> {
await axios.put<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/updateLinkVrblInfo`,
data,
);
}
public async getLinkTableInfo(linkSn: string): Promise<LinkTable> {
const response = await axios.get<LinkTable>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableInfo/${linkSn}`,
);
return response.data;
}
public async getLinkTableColList(linkSn: string): Promise<LinkTableColumnsList> {
const response = await axios.get<LinkTableColumnsList>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableColList/${linkSn}`,
);
return response.data;
}
public async getLinkTableColInfo(params: { colSn: string; tblSn:string; }): Promise<LinkTableColumns> {
const response = await axios.get<LinkTableColumns>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableColInfo`,
{ params }
);
return response.data;
}
public async insertLinkTableCol(data: LinkTableColData): Promise<void> {
await axios.post<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/insertLinkTableCol`,
data
);
}
public async deleteLinkTableCol(data: string[]): Promise<void> {
await axios.delete<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/deleteLinkTableCol`,
{
data
},
);
}
public async updateLinkTableCol(data: LinkTableColData): Promise<void> {
axios.put<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/updateLinkTableCol`,
data,
);
}
public async insertLinkTableInfo(data: LinkTableFormData): Promise<void> {
await axios.post<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/insertLinkTableInfo`,
data
);
}
public async updateLinkTableInfo(data: LinkTableFormData): Promise<void> {
await axios.put<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/updateLinkTableInfo`,
data
);
}
public async countLinkTblNm(tblNm: string): Promise<{count: number, tbl_sn: string}> {
const response = await axios.get<{count: number, tbl_sn: string}>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/countLinkTblNm/${tblNm}`,
);
return response.data;
}
public async updateLinkResultCode(linkSn: string): Promise<void> {
await axios.patch<void>(
`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/updateLinkResultCode/${linkSn}`,
);
}
}
export const LinkApi = new LinkApiService();
+18
View File
@@ -0,0 +1,18 @@
export { LinkApi } from "./api/link-service";
export {
type LinkSearchParam,
type Link,
type LinkFormData,
type LinkLog,
type LinkStats,
type LinkVrbl,
type LinkVrblFormData,
type LinkTable,
type LinkTableColumns,
type LinkTableColData,
type LinkTableFormData,
linkFormSchema,
linkVrblFormSchema,
LinkTableColumnsSchema,
LinkTableSchema,
} from "./model/link-interface"
@@ -0,0 +1,235 @@
import { z } from "zod";
import type { PageableParams, PageableList } from "@/shared/model";
export interface Link {
link_sn: string;
link_nm: string;
link_clsf_cd: string;
link_url: string;
link_srvr_ip: string;
link_db_cd: string;
link_key: string;
link_id: string;
link_pswd: string;
link_cycle_stng: string;
srvc_usg: string;
last_link_rslt_cd: string;
last_link_excn_dt: string;
next_link_excn_dt: string;
last_link_err_cd: string;
mdfcn_dt: string;
mdfr: string;
link_batch_time: string;
}
export interface LinkLog {
rownum: number;
link_sn: string;
link_nm: string;
link_rslt_cd: string;
err_cn: string;
link_err_cd: string;
log_crt_dt: string;
}
export interface LinkInfo extends LinkFormData {
link_sn: string;
link_nm: string;
link_clsf_cd: string;
link_url: string;
link_srvr_ip: string;
link_db_cd: string;
link_key: string;
link_id: string;
link_pswd: string;
srvc_usg: string;
last_link_rslt_cd: string;
last_link_excn_dt: string;
next_link_excn_dt: string;
last_link_err_cd: string;
mdfcn_dt: string;
mdfr: string;
link_batch_time: number;
}
export interface LinkStats {
link_sn: string;
link_nm: string;
count: number;
}
export interface LinkVrbl {
link_vrbl_sn: string;
link_vrbl_nm: string;
link_vrbl_vl: string;
link_vrbl_cd: string;
link_vrbl_expln: string;
mdfcn_dt: string;
mdfr: string;
}
export interface LinkTable {
link_nm: string;
link_sn: string;
tbl_sn: string;
sou_tbl_nm: string;
sou_tbl_korn_nm: string;
sou_tbl_expln: string;
trsf_tbl_nm: string;
trsf_tbl_korn_nm: string;
trsf_tbl_expln: string;
}
export interface LinkTableColumns {
tbl_sn: string;
col_sn: string;
sou_col_nm: string;
sou_col_korn_nm: string;
sou_col_data_frm: string;
sou_col_sz: number;
trsf_col_nm: string;
trsf_col_korn_nm: string;
trsf_col_data_frm: string;
trsf_col_sz: number
pk_yn: string;
col_seq: number;
mdfcn_dt: string;
mdfr: string;
}
export const linkFormSchema = z.object({
link_clsf_cd: z.string().max(8).nullable().refine((val) => {
// 빈 값이나 "none" 값이면 false 반환
return val && val !== "none";
}, {
message: "연계 분류를 선택해주세요"
}),
link_sn: z.string().max(50).nullable().optional(),
link_nm: z.string().max(40, { message: '연계명은 40자 이하로 입력해 주세요.' }).nonempty({ message: '연계명은 필수입니다.' }),
link_url: z.string().max(1000, { message: '연계 URL은 1000자 이하로 입력해 주세요.' }).nonempty({ message: '연계 URL은 필수입니다.' }),
link_srvr_ip: z.string().max(20).nullable().optional(),
link_db_cd: z.string().max(10).nullable().optional(),
link_key: z.string().max(100, { message: '연계 KEY는 100자 이하로 입력해 주세요.' }).nonempty({ message: '연계 KEY는 필수입니다.' }),
link_id: z.string().max(20).nullable().optional(),
link_pswd: z.string().max(128).nullable().optional(),
srvc_usg: z.string().max(40).nullable().optional(),
last_link_rslt_cd: z.string().max(4).nullable().optional(),
last_link_excn_dt: z.string().max(40).nullable().optional(),
next_link_excn_dt: z.string().max(40).nullable().optional(),
last_link_err_cd: z.string().max(10).nullable().optional(),
mdfcn_dt: z.string().nullable().optional(),
mdfr: z.string().nullable().optional(),
link_batch_time: z.coerce.number().nullable().optional().refine((val) => {
if (val == null) return true;
return val >= 5;
}, {
message: "연계 주기는 5분 이상이어야 합니다."
}),
});
export const linkVrblFormSchema = z.object({
link_sn: z.string().max(50).nullable().optional(),
link_vrbl_sn: z.string().max(50).nullable().optional(),
link_vrbl_nm: z.string().max(40, { message: '변수명은 40자 이하로 입력해 주세요.' }).nonempty({ message: '변수명은 필수입니다.' }),
link_vrbl_expln: z.string().max(4000, { message: '설명은 400자 이하로 입력해 주세요.' }).nullable().optional(),
link_vrbl_cd: z.string().max(10, { message: '변수코드는 10자 이하로 입력해 주세요.' }).nullable().optional(),
link_vrbl_vl: z.string().max(1000, { message: '변수값은 1000자 이하로 입력해 주세요.' }).nonempty({ message: '변수값은 필수입니다.' }),
mdfcn_dt: z.string().nullable().optional(),
mdfr: z.string().nullable().optional(),
});
export const LinkTableColumnsSchema = z.object({
link_sn: z.string().max(50).nullable().optional(),
tbl_sn: z.string().max(50).nullable().optional(),
col_sn: z.string().max(50).nullable().optional(),
sou_col_nm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nullable().optional(),
sou_col_korn_nm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nullable().optional(),
sou_col_data_frm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nullable().optional(),
sou_col_sz: z.coerce.number().nullable().optional().refine((val) => {
if (val == null) return true;
return val.toString().replace('.', '').length <= 14;
}, {
message: '최대 14자리까지 입력 가능합니다.',
}),
pk_yn: z.string().max(1).nonempty(),
trsf_col_nm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nonempty({ message: '변환컬럼명은 필수입니다.' }),
trsf_col_korn_nm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nonempty({ message: '변환컬럼 한글명은 필수입니다.' }),
trsf_col_data_frm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nonempty({ message: '변환컬럼 데이터 형식은 필수입니다.' }),
trsf_col_sz: z.coerce.number().nullable().optional().refine((val) => {
if (val == null) return true;
return val.toString().replace('.', '').length <= 14;
}, {
message: '최대 14자리까지 입력 가능합니다.',
}),
col_seq: z.coerce.number().nullable().optional().refine((val) => {
if (val == null) return true;
return val > 0;
}, {
message: "컬럼 매칭 순서는 0 이상이어야 합니다."
}),
mdfcn_dt: z.string().nullable().optional(),
mdfr: z.string().nullable().optional(),
});
export const LinkTableSchema = z.object({
link_sn: z.string().max(50).nullable().optional(),
tbl_sn: z.string().max(50).nullable().optional(),
link_nm: z.string().max(50).nullable().optional(),
sou_tbl_nm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nullable().optional(),
sou_tbl_korn_nm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nullable().optional(),
sou_tbl_expln: z.string().max(2000, { message: '설명은 2000자 이하로 입력해 주세요.' }).nullable().optional(),
trsf_tbl_nm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nonempty({ message: '변환테이블명은 필수입니다.' }),
trsf_tbl_korn_nm: z.string().max(40, { message: '40자 이하로 입력해 주세요.' }).nonempty({ message: '변환테이블 한글명은 필수입니다.' }),
trsf_tbl_expln: z.string().max(2000, { message: '설명은 2000자 이하로 입력해 주세요.' }).nullable().optional(),
mdfcn_dt: z.string().nullable().optional(),
mdfr: z.string().nullable().optional(),
});
interface LinkStatsListObject {
linkSuccStats: LinkStats[] | null;
linkFailStats: LinkStats[] | null;
}
export interface LinkSearchParam extends PageableParams {
linkSn?: string;
linkNm?: string;
startDate?: string;
endDate?: string;
isSucc?: string;
}
export type LinkFormData = z.infer<typeof linkFormSchema>;
export type LinkVrblFormData = z.infer<typeof linkVrblFormSchema>;
export type LinkTableColData = z.infer<typeof LinkTableColumnsSchema>;
export type LinkTableFormData = z.infer<typeof LinkTableSchema>;
export type LinkList = PageableList<Link>;
export type LinkLogList = PageableList<LinkLog>;
export type LinkStatsList = LinkStatsListObject;
export type LinkVrblList = PageableList<LinkVrbl>;
export type LinkTableColumnsList = PageableList<LinkTableColumns>;
export interface LinkService {
getLinkList(params: LinkSearchParam): Promise<LinkList>;
getLinkInfo(params: string): Promise<LinkInfo>;
linkQuickStart(params: string): Promise<string>;
updateLinkInfo(data: LinkFormData): Promise<void>;
deleteLink(params: string): Promise<void>;
getLinkLogList(params: LinkSearchParam): Promise<LinkLogList>;
getLinkStatsList(params: LinkSearchParam): Promise<LinkStatsList>;
getLinkVrblList(params: string): Promise<LinkVrblList>;
insertLinkVrbl(data: LinkVrblFormData): Promise<number>;
deleteLinkVrbl(data: string[]): Promise<void>;
getLinkVrblInfo(params: string): Promise<LinkVrbl>;
updateLinkVrblInfo(data: LinkVrblFormData): Promise<void>;
getLinkTableInfo(params: string): Promise<LinkTable>;
getLinkTableColList(params: string): Promise<LinkTableColumnsList>;
getLinkTableColInfo(params: { colSn: string; tblSn: string; }): Promise<LinkTableColumns>;
insertLinkTableCol(data: LinkTableColData): Promise<void>;
deleteLinkTableCol(data: string[]): Promise<void>;
updateLinkTableCol(data: LinkTableColData): Promise<void>;
insertLinkTableInfo(data: LinkTableFormData): Promise<void>;
updateLinkTableInfo(data: LinkTableFormData): Promise<void>;
insertLinkInfo(data: LinkFormData): Promise<void>;
countLinkTblNm(tblNm: string): Promise<{ count: number, tbl_sn: string }>;
updateLinkResultCode(linkSn: string): Promise<void>;
}
@@ -47,7 +47,7 @@ function AddAdminDialog() {
const [open, setOpen] = useState(false);
const [userSearchQuery, setUserSearchQuery] = useState<UserSearchParams>({
keywordType: "",
keywordType: "userName",
keyword: "",
});
const [selectedGroupId, setSelectedGroupId] = useState("");
@@ -193,6 +193,7 @@ function AddAdminDialog() {
<form onSubmit={handleSearch} className="flex items-center gap-2">
<Select
value={userSearchQuery.keywordType}
onValueChange={(value) =>
setUserSearchQuery({ ...userSearchQuery, keywordType: value })
}
@@ -201,8 +202,8 @@ function AddAdminDialog() {
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
<SelectItem value="userId">아이디</SelectItem>
<SelectItem value="userName">이름</SelectItem>
<SelectItem value="userId">아이디</SelectItem>
</SelectContent>
</Select>
<Input
+10 -16
View File
@@ -7,7 +7,6 @@ import { getCoreRowModel, type PaginationState } from "@tanstack/react-table";
import {
Button,
Input,
InputDatePicker,
Label,
Select,
SelectContent,
@@ -15,10 +14,11 @@ import {
SelectTrigger,
SelectValue,
} from "@common/components";
import { columns } from "@/pages/apilog/model/table-columns";
import { ApiLogApi, type ApiLogParams } from "@/entities/apilog";
import { useDataTable } from "@/shared/lib";
import { ENDPOINT } from "@/shared/config";
import { columns } from "@/pages/apilog/model/table-columns";
import { InputDateRangePicker } from "@/shared/ui/input-date-range-picker";
type DateRange = {
from?: Date | undefined;
@@ -133,6 +133,11 @@ function ApiLogPage() {
setDateRange(presetDateRange || defaultDateRange);
};
const handleDateRangeChange = (dateRange: DateRange) => {
setDateRange(dateRange);
setPresetDateRange("");
};
return (
<div className="flex-1">
<div className="card card-border">
@@ -148,20 +153,9 @@ function ApiLogPage() {
<SelectItem value="3M">3개월</SelectItem>
</SelectContent>
</Select>
<InputDatePicker
value={dateRange.from}
onChange={(date) => {
setDateRange({ ...dateRange, from: date });
setPresetDateRange("");
}}
/>
~
<InputDatePicker
value={dateRange.to}
onChange={(date) => {
setDateRange({ ...dateRange, to: date });
setPresetDateRange("");
}}
<InputDateRangePicker
dateRange={dateRange}
setDateRange={handleDateRangeChange}
/>
<Label className="ml-4 mr-2 text-label">사용자ID</Label>
<Input
@@ -110,10 +110,16 @@ function DashboardPage() {
<div className="absolute left-0 top-0 p-6 tracking-tighter text-white">
<h3 className="text-2xl font-medium">총 회원수</h3>
<div className="mt-2 text-6xl font-bold">
{data?.memberTotCnt ?? "-"}
{data?.memberTotCnt
? data.memberTotCnt.toLocaleString()
: "-"}
</div>
<p className="mt-1 text-2xl opacity-80">
금일 신규 가입자 {data?.memberTodayCnt ?? "-"}명
금일 신규 가입자
{data?.memberTodayCnt
? data.memberTodayCnt.toLocaleString()
: "-"}
명
</p>
</div>
{/* 차트 영역 */}
@@ -131,10 +137,12 @@ function DashboardPage() {
<div className="absolute left-0 top-0 p-6 tracking-tighter">
<h3 className="text-2xl font-medium">전체 게시물</h3>
<div className="mt-2 text-6xl font-bold">
{data?.pstTotCnt ?? "-"}
{data?.pstTotCnt ? data.pstTotCnt.toLocaleString() : "-"}
</div>
<p className="mt-1 text-2xl opacity-80">
금일 +{data?.pstTodayCnt ?? "-"} 등록
금일 +
{data?.pstTodayCnt ? data.pstTodayCnt.toLocaleString() : "-"}{" "}
등록
</p>
</div>
{/* 차트 영역 */}
@@ -152,10 +160,16 @@ function DashboardPage() {
<div className="absolute left-0 top-0 p-6 tracking-tighter">
<h3 className="text-2xl font-medium">오늘 접속자 수</h3>
<div className="mt-2 text-6xl font-bold">
{data?.accessTodayCnt ?? "-"}
{data?.accessTodayCnt
? data.accessTodayCnt.toLocaleString()
: "-"}
</div>
<p className="mt-1 text-2xl opacity-80">
전일 대비 +{data?.accessBefDayPer ?? "-"}%
전일 대비 +
{data?.accessBefDayPer
? data.accessBefDayPer.toLocaleString()
: "-"}
%
</p>
</div>
{/* 차트 영역 */}
@@ -173,7 +187,7 @@ function DashboardPage() {
<div className="absolute left-0 top-0 p-6 tracking-tighter">
<h3 className="text-2xl font-medium">API 호출 건수</h3>
<div className="mt-2 text-6xl font-bold">
{data?.apiTodayCnt ?? "-"}
{data?.apiTodayCnt ? data.apiTodayCnt.toLocaleString() : "-"}
</div>
<p className="mt-1 text-2xl opacity-80">금일 누적</p>
</div>
@@ -221,7 +235,10 @@ function DashboardPage() {
</div>
<div className="mt-5">
<div className="text-5xl font-bold">
{data?.waitMemberCnt}건
{data?.waitMemberCnt
? data.waitMemberCnt.toLocaleString()
: "0"}
건
</div>
<div className="mt-2 text-2xl text-gray-500">
신규 가입 승인 대기
@@ -253,7 +270,9 @@ function DashboardPage() {
<span className="text-2xl font-medium">메뉴 승인</span>
</div>
<div className="mt-5">
<div className="text-5xl font-bold">3건</div>
<div className="text-5xl font-bold">
{(3).toLocaleString()}건
</div>
<div className="mt-2 text-2xl text-gray-500">
매뉴 수정 승인 대기
</div>
@@ -283,7 +302,10 @@ function DashboardPage() {
</div>
<div className="mt-5">
<div className="text-5xl font-bold">
{data?.waitCntnCnt}건
{data?.waitCntnCnt
? data.waitCntnCnt.toLocaleString()
: "0"}
건
</div>
<div className="mt-2 text-2xl text-gray-500">
컨텐츠 수정 승인 대기
@@ -303,19 +325,19 @@ function DashboardPage() {
<div className="space-y-4">
<div className="flex items-center justify-between border-b border-border pb-4">
<span className="font-medium">신규 사용자 가입</span>
<span>1분 전</span>
<span>{(1).toLocaleString()}분 전</span>
</div>
<div className="flex items-center justify-between border-b border-border pb-4">
<span className="font-medium">메뉴 수정 요청</span>
<span>5분 전</span>
<span>{(5).toLocaleString()}분 전</span>
</div>
<div className="flex items-center justify-between border-b border-border pb-4">
<span className="font-medium">게시물 신고</span>
<span>10분 전</span>
<span>{(10).toLocaleString()}분 전</span>
</div>
<div className="flex items-center justify-between">
<span className="font-medium">컨텐츠 승인 요청</span>
<span>15분 전</span>
<span>{(15).toLocaleString()}분 전</span>
</div>
</div>
</div>
@@ -328,20 +350,22 @@ function DashboardPage() {
<div className="p-4">
<div className="space-y-4">
<div className="flex items-center justify-between border-b border-border pb-4">
<span className="font-medium">3월 정기 시스템 점검</span>
<span className="font-medium">
{(3).toLocaleString()}월 정기 시스템 점검
</span>
<span>내일</span>
</div>
<div className="flex items-center justify-between border-b border-border pb-4">
<span className="font-medium">서버 업데이트 예정</span>
<span>3일 후</span>
<span>{(3).toLocaleString()}일 후</span>
</div>
<div className="flex items-center justify-between border-b border-border pb-4">
<span className="font-medium">백업 스케줄</span>
<span>5일 후</span>
<span>{(5).toLocaleString()}일 후</span>
</div>
<div className="flex items-center justify-between">
<span className="font-medium">정기 보안 점검</span>
<span>7일 후</span>
<span>{(7).toLocaleString()}일 후</span>
</div>
</div>
</div>
+2 -2
View File
@@ -161,11 +161,11 @@ function GroupForm({ form }: GroupFormProps) {
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="Y" id="mngrY" />
<Label htmlFor="mngrY">Y</Label>
<Label htmlFor="mngrY">예</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="N" id="mngrN" />
<Label htmlFor="mngrN">N</Label>
<Label htmlFor="mngrN">아니오</Label>
</div>
</RadioGroup>
</FormControl>
@@ -1,6 +1,6 @@
"use client";
import { memo, useState } from "react";
import { memo, useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
@@ -43,7 +43,7 @@ const GroupsDialog = memo(
const { data: group } = useQuery({
queryKey: [ENDPOINT.CMS_SERVICE.GROUPS, groupId],
queryFn: () => GroupApi.findGroupById(groupId!),
enabled: !!groupId && open, // open 시점 groupId가 있을 때만 상세 조회 API 호출
enabled: !!groupId && open, // open 시점 groupId가 있을 때만 상세 조회 API 호출
});
const { mutateAsync: createGroup } = useMutationWrapper({
@@ -77,7 +77,7 @@ const GroupsDialog = memo(
delYn: group?.delYn ?? "",
authrtId: group?.authrtId ?? "",
siteId: group?.siteId ?? "",
mngrYn: group?.mngrYn ?? "",
mngrYn: group?.mngrYn ?? "Y",
},
});
@@ -91,6 +91,10 @@ const GroupsDialog = memo(
if (await confirm(confirmMessage)) callback(data);
};
useEffect(() => {
if (open) form.reset();
}, [open]);
return (
<Dialog open={open} onOpenChange={setOpen} {...props}>
<DialogTrigger asChild>{children}</DialogTrigger>
@@ -23,6 +23,7 @@ function CreatePage() {
resolver: zodResolver(imageFormSchema),
defaultValues: {
atflYn: "Y",
useYn: "Y",
},
});
@@ -124,6 +124,7 @@ function ImageForm({ form, imgSn, ...props }: ImageFormProps) {
{...field}
type="number"
min={0}
max={9999}
value={field.value ?? ""}
onChange={(e) =>
field.onChange(parseInt(e.target.value))
+3
View File
@@ -0,0 +1,3 @@
export { ModifyLinkPage } from "./ui/modify-page";
export { RegistLinkPage } from "./ui/regist-page";
export { LinkPage } from "./ui/link-page";
@@ -0,0 +1,88 @@
import dayjs from "dayjs";
import { createColumnHelper } from "@tanstack/react-table";
import { type Link } from "@/entities/link";
import QuickStartButton from "../ui/QuickStartButton";
const columnHelper = createColumnHelper<Link>();
const convertMinutesToPeriod = (minutes: number): string => {
if (!minutes) return '';
const year = Math.floor(minutes / (525600)); // 365일 * 24시간 * 60분
minutes = minutes % 525600;
const month = Math.floor(minutes / (43200)); // 30일 * 24시간 * 60분
minutes = minutes % 43200;
const day = Math.floor(minutes / 1440); // 24시간 * 60분
minutes = minutes % 1440;
const hour = Math.floor(minutes / 60);
const minute = minutes % 60;
const parts = [];
if (year > 0) parts.push(`${year}년`);
if (month > 0) parts.push(`${month}개월`);
if (day > 0) parts.push(`${day}일`);
if (hour > 0) parts.push(`${hour}시간`);
if (minute > 0) parts.push(`${minute}분`);
return parts.join(' ');
};
const columns = [
columnHelper.accessor((_, index) => index + 1, {
id: 'no',
header: 'NO',
}),
columnHelper.accessor('link_sn', {
id: 'link_sn',
header: '연계일련번호',
}),
columnHelper.accessor('link_nm', {
id: 'link_nm',
header: '연계 명',
}),
columnHelper.accessor('link_url', {
id: 'link_url',
header: '연계 URL',
cell: (info) => (info.getValue() ? info.getValue() : '-'),
}),
columnHelper.accessor('link_srvr_ip', {
id: 'link_srvr_ip',
header: '연계서버 IP',
cell: (info) => (info.getValue() ? info.getValue() : '-'),
}),
columnHelper.accessor('link_batch_time', {
id: 'link_batch_time',
header: '연계 주기',
cell: (info) => convertMinutesToPeriod(Number(info.getValue())),
}),
columnHelper.accessor('srvc_usg', {
id: 'srvc_usg',
header: '서비스용도',
cell: (info) => (info.getValue() ? info.getValue() : '-'),
}),
columnHelper.display({
id: 'last_link_rslt_cd',
header: '연계상태',
cell: (info) => {
const resultCd = info.row.original.last_link_rslt_cd;
return <span className={`${(resultCd === 'SUCC') ? 'text-[rgb(53,162,235)]' : (resultCd === 'FAIL' ? 'text-[rgb(255,99,132)]' : 'text-[rgba(31,208,120,1)]')}`}>{resultCd === 'SUCC' ? '성공' : (resultCd === 'FAIL' ? '실패' : '대기')}</span>
},
}),
columnHelper.accessor('last_link_excn_dt', {
id: 'last_link_excn_dt',
header: '최종연계일',
cell: (info) => (info.getValue() ? dayjs(info.getValue()).format('YYYY-MM-DD HH:mm') : '-'),
}),
columnHelper.display({
id: 'quick_start_btn',
header: '즉시 실행',
cell: (info) => {
return <QuickStartButton linkSn={info.row.original.link_sn} />
}
})
];
export { columns };
@@ -0,0 +1,36 @@
import { useMutation } from "@tanstack/react-query";
import { LinkApi } from "@/entities/link";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { Button } from "@common/components";
const QuickStartButton: React.FC<{ linkSn: string }> = ({ linkSn }) => {
const { setMessage: alert } = useAlertStore((state) => state);
const { mutateAsync: updateQuickStart } = useMutation({
mutationFn: (linkSn: string) => LinkApi.linkQuickStart(linkSn),
onSuccess: (result) => {
if (result === 'succ') {
alert('즉시 실행 요청이 완료되었습니다.');
} else {
alert('기존 요청이 실행 대기중입니다.');
}
},
onError: () => {
alert('즉시 실행 요청을 실패했습니다.');
},
});
return (
<Button
color="sky"
onClick={(e) => {
e.stopPropagation();
updateQuickStart(linkSn);
}}
>
즉시 실행
</Button>
);
};
export default QuickStartButton;
+590
View File
@@ -0,0 +1,590 @@
import {
Button,
Input,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Select,
SelectTrigger,
SelectContent,
SelectItem,
SelectValue,
} from "@common/components";
import { FormItem, FormControl, FormField, Form } from "@/shared/ui/form";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import type { UseFormReturn } from "react-hook-form";
import { type LinkFormData } from "@/entities/link";
import dayjs from "dayjs";
import { useRouter } from "next/navigation";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { useState } from "react";
type LinkFormProps = {
form: UseFormReturn<LinkFormData>;
linkSn?: string;
updateLinkInfo?: (data: LinkFormData) => void;
handleInsertLink?: (data: LinkFormData) => void;
deleteLink?: () => void;
updateLinkResultCode?: () => void;
}
const LinkForm = ({ form, linkSn, updateLinkInfo, handleInsertLink, deleteLink, updateLinkResultCode }: LinkFormProps) => {
const isModifyMode = !!linkSn;
const router = useRouter();
const { confirm } = useConfirm();
const [onConfirm, setOnConfirm] = useState(false);
const handleConfirm = async (callback: () => Promise<void>) => {
setOnConfirm(true);
await callback();
setOnConfirm(false);
};
const handleSubmit = async (data: LinkFormData) => {
const confirmMsg = !!linkSn ? '수정 하시겠습니까?' : '저장 하시겠습니까?';
await handleConfirm(async () => {
if (await confirm(confirmMsg)) {
if (linkSn) {
updateLinkInfo?.(data);
} else {
handleInsertLink?.(data);
}
}
});
};
const handleDelete = async () => {
await handleConfirm(async () => {
if (await confirm('삭제하시겠습니까?')) {
deleteLink?.();
}
})
};
const convertMinutesToPeriod = (minutes: number) => {
if (!minutes) return {
year: 0,
month: 0,
day: 0,
hour: 0,
minute: 0
};
const year = Math.floor(minutes / (525600)); // 365일 * 24시간 * 60분
minutes = minutes % 525600;
const month = Math.floor(minutes / (43200)); // 30일 * 24시간 * 60분
minutes = minutes % 43200;
const day = Math.floor(minutes / 1440); // 24시간 * 60분
minutes = minutes % 1440;
const hour = Math.floor(minutes / 60);
const minute = minutes % 60;
const timeParts = {
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
};
return timeParts;
};
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)}>
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
{isModifyMode &&
<TableRow>
<TableHead>연계 일련번호</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_sn"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="w-[12rem] !text-[1.3rem]"
disabled={true}
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
}
<TableRow>
<TableHead>* 연계 명</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.link_nm && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.link_nm.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 연계 분류</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_clsf_cd"
render={({ field }) => (
<FormItem>
<FormControl>
<Select value={field.value ?? "none"} onValueChange={(value) => field.onChange(value)}>
<SelectTrigger id="link_clsf_cd" className="w-[20rem]">
<SelectValue placeholder="전체"></SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="none">선택</SelectItem>
<SelectItem value="link0001">TIBERO 데이터베이스</SelectItem>
<SelectItem value="link0002">ORACLE 데이터베이스</SelectItem>
<SelectItem value="link0003">공공데이터 포털 API</SelectItem>
<SelectItem value="link0004">한강홍수통제소 API</SelectItem>
<SelectItem value="link0005">기상청 API</SelectItem>
<SelectItem value="link0006">국가지하수정보센터 API</SelectItem>
<SelectItem value="link0007">행정정보공동이용센터 연계</SelectItem>
</SelectContent>
</Select>
</FormControl>
{form.formState.errors.link_clsf_cd && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.link_clsf_cd.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 연계 URL</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_url"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.link_url && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.link_url.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>연계서버 IP</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_srvr_ip"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 연계 KEY</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_key"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.link_key && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.link_key.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>연계 ID</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_id"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>연계 비밀번호</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_pswd"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
type="password"
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>서비스 용도</TableHead>
<TableCell>
<FormField
control={form.control}
name="srvc_usg"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>연계 주기</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_batch_time"
render={({ field }) => {
const timeParts = convertMinutesToPeriod(Number(field.value));
return (
<FormItem>
<FormControl>
<div className="flex items-center gap-6">
<div className="flex items-center">
<Input
value={timeParts.year}
className="w-20 !text-[1.3rem]"
type="number"
min={0}
onChange={(e) => {
const total = (Number(e.target.value) * 525600) +
(timeParts.month * 43200) +
(timeParts.day * 1440) +
(timeParts.hour * 60) +
timeParts.minute;
field.onChange(total);
}}
/>
<span className="ml-2">년</span>
</div>
<div className="flex items-center">
<Input
value={timeParts.month}
className="w-20 !text-[1.3rem]"
type="number"
min={0}
max={11}
onChange={(e) => {
const total = (timeParts.year * 525600) +
(Number(e.target.value) * 43200) +
(timeParts.day * 1440) +
(timeParts.hour * 60) +
timeParts.minute;
field.onChange(total);
}}
/>
<span className="ml-2">월</span>
</div>
<div className="flex items-center">
<Input
value={timeParts.day}
className="w-20 !text-[1.3rem]"
type="number"
min={0}
max={30}
onChange={(e) => {
const total = (timeParts.year * 525600) +
(timeParts.month * 43200) +
(Number(e.target.value) * 1440) +
(timeParts.hour * 60) +
timeParts.minute;
field.onChange(total);
}}
/>
<span className="ml-2">일</span>
</div>
<div className="flex items-center">
<Input
value={timeParts.hour}
className="w-20 !text-[1.3rem]"
type="number"
min={0}
max={23}
onChange={(e) => {
const total = (timeParts.year * 525600) +
(timeParts.month * 43200) +
(timeParts.day * 1440) +
(Number(e.target.value) * 60) +
timeParts.minute;
field.onChange(total);
}}
/>
<span className="ml-2">시간</span>
</div>
<div className="flex items-center">
<Input
value={timeParts.minute}
className="w-20 !text-[1.3rem]"
type="number"
min={0}
max={59}
onChange={(e) => {
const total = (timeParts.year * 525600) +
(timeParts.month * 43200) +
(timeParts.day * 1440) +
(timeParts.hour * 60) +
Number(e.target.value);
field.onChange(total);
}}
/>
<span className="ml-2">분</span>
</div>
</div>
</FormControl>
{form.formState.errors.link_batch_time && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.link_batch_time.message}
</p>
)}
</FormItem>
);
}}
/>
</TableCell>
</TableRow>
{isModifyMode &&
<>
<TableRow>
<TableHead>연계 상태</TableHead>
<TableCell>
<FormField
control={form.control}
name="last_link_rslt_cd"
render={({ field }) => {
return (
<FormItem>
<FormControl>
<div className="flex items-center gap-6">
<Input
{...field}
value={field.value ? (field.value === 'SUCC' ? '성공' : (field.value === 'FAIL' ? '실패' : '대기')) : ''}
className="!text-[1.3rem] w-[15rem]"
disabled
/>
<Button color="green" type="button" onClick={() => updateLinkResultCode?.()}>대기로 전환</Button>
</div>
</FormControl>
</FormItem>
);
}}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>최종 연계 실행일</TableHead>
<TableCell>
<FormField
control={form.control}
name="last_link_excn_dt"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ? dayjs(field.value).format('YYYY-MM-DD HH:mm:ss') : ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>다음 연계 실행일</TableHead>
<TableCell>
<FormField
control={form.control}
name="next_link_excn_dt"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ? dayjs(field.value).format('YYYY-MM-DD HH:mm:ss') : ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>수정자</TableHead>
<TableCell>
<FormField
control={form.control}
name="mdfr"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>수정일시</TableHead>
<TableCell>
<FormField
control={form.control}
name="mdfcn_dt"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ? dayjs(field.value).format('YYYY-MM-DD') : ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
</>
}
</TableBody>
</Table>
</div>
<div className="flex justify-center gap-4 pb-12 pt-10">
<Button
size="lg"
color="white"
type="button"
onClick={() => router.back()}
>
목록
</Button>
<Button size="lg" type="submit">
저장
</Button>
{isModifyMode && (
<Button size="lg" color="red" type="button" onClick={handleDelete}>
삭제
</Button>
)}
</div>
</form>
</Form>
<ConfirmDialog isOpen={onConfirm} />
</>
)
};
export default LinkForm;
+134
View File
@@ -0,0 +1,134 @@
"use client";
import "@common/assets/styles/grid.css";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Button, Input, Label, LoadingWithAnimation } from "@common/components";
import { getCoreRowModel } from "@tanstack/react-table";
import { LinkApi, type Link, type LinkSearchParam } from "@/entities/link";
import { useQuery } from "@tanstack/react-query";
import { columns } from "../model/table-columns";
import { useQueryClient } from "@tanstack/react-query";
import { useDataTable } from "@/shared/lib";
function LinkPage() {
const router = useRouter();
const queryClient = useQueryClient();
const [linkSn, setLinkSn] = useState<string>('');
const [linkNm, setLinkNm] = useState<string>('');
const [linkSearchParam, setLinkSearchParam] = useState<LinkSearchParam>({
linkSn: '',
linkNm: ''
});
const query = useQuery({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkList`, linkSearchParam],
queryFn: () => LinkApi.getLinkList(linkSearchParam),
});
const handleResetSearchParam = () => {
setLinkSn('');
setLinkNm('');
setLinkSearchParam({
...linkSearchParam,
linkSn: '',
linkNm: '',
});
};
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setLinkSearchParam({
...linkSearchParam,
linkSn,
linkNm
});
};
const handleRowClick = (link: Link) => {
queryClient.removeQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkList`],
});
queryClient.removeQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkInfo`],
});
router.push(`link/register/${link.link_sn}`);
};
const handleClickRegist = () => {
router.push('link/register');
};
const { tableComponent } = useDataTable({
query,
tableOptions: {
columns,
manualPagination: true,
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
},
dataTableOptions: {
onRowClick: handleRowClick,
viewPagination: true,
},
});
return (
<div className="card card-border !mt-6">
<div className="card card-border">
<form className="flex items-center gap-2 p-2" onSubmit={handleSubmit}>
<Label htmlFor="liSnSearchInput" className="mr-2 text-label">
일련번호
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem] mr-4"
id="liSnSearchInput"
value={linkSn}
onChange={(e) => setLinkSn(e.target.value)}
autoComplete="off"
/>
<Label htmlFor="liNmSearchInput" className="mr-2 text-label">
연계 명
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem] mr-2"
id="liNmSearchInput"
value={linkNm}
onChange={(e) => setLinkNm(e.target.value)}
autoComplete="off"
/>
<Button color="green" className="h-[3.2rem]" type="button" onClick={handleResetSearchParam}>
초기화
</Button>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
</form>
</div>
<div className="card card-border flex flex-col h-[calc(100vh-28rem)]">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">연계 목록</h3>
<div>
<Button onClick={handleClickRegist}>등록</Button>
</div>
</div>
<div className="card !m-[1.2rem] overflow-auto h-full !p-0">
{!query.isLoading ?
<div>{tableComponent}</div>
:
<div className="[data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center h-full">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
}
</div>
</div>
</div>
);
}
export { LinkPage };
+111
View File
@@ -0,0 +1,111 @@
"use client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { LinkApi, linkFormSchema, type LinkFormData } from "@/entities/link";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import LinkForm from "./link-form";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { useEffect } from "react";
import { getUserInfo } from "../../../../../../packages/common/components/src/api";
import { AUTH_USER_ID } from "@/shared/config";
import { getCookie } from "@common/components";
function ModifyLinkPage({ linkSn }: { linkSn: string }) {
const router = useRouter();
const queryClient = useQueryClient();
const { setMessage: alert } = useAlertStore((state) => state);
const userUniqId = getCookie(AUTH_USER_ID) ?? "";
// 컴포넌트 마운트 시 캐시 초기화
useEffect(() => {
queryClient.removeQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkInfo`],
});
}, [queryClient]);
const { data: linkInfo, refetch } = useQuery({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkInfo`],
queryFn: () => LinkApi.getLinkInfo(linkSn),
enabled: !!linkSn,
});
const { mutateAsync: updateLinkInfo } = useMutation({
mutationFn: (data: LinkFormData) => LinkApi.updateLinkInfo({
...data,
link_clsf_cd: data.link_clsf_cd !== 'none' ? data.link_clsf_cd : null,
mdfr: userUniqId
}),
onSuccess: () => {
alert('수정되었습니다.');
router.push('/link');
}
});
const { mutateAsync: deleteLink } = useMutation({
mutationFn: () => LinkApi.deleteLink(linkSn),
onSuccess: () => {
alert('삭제되었습니다.', router.back);
}
});
const { mutateAsync: updateLinkResultCode } = useMutation({
mutationFn: () => LinkApi.updateLinkResultCode(linkSn),
onSuccess: () => {
alert('대기로 전환되었습니다.');
refetch();
}
});
const fetchUserInfo = async () => {
const userData = await getUserInfo();
return userData.userName;
};
const form = useForm<LinkFormData>({
resolver: zodResolver(linkFormSchema),
defaultValues: {},
});
useEffect(() => {
const applyFormData = async () => {
if (linkInfo) {
let newData = { ...linkInfo };
if (linkInfo.mdfr) {
const userName = await fetchUserInfo();
newData = {
...linkInfo,
mdfr: userName,
};
}
form.reset(newData);
}
};
applyFormData();
}, [linkInfo]);
return (
<>
<div className="card card-border !mb-0 !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">연계정보 수정</h3>
</div>
<LinkForm
form={form}
linkSn={linkSn}
updateLinkInfo={updateLinkInfo}
deleteLink={deleteLink}
updateLinkResultCode={updateLinkResultCode}
/>
</div>
</>
);
};
export { ModifyLinkPage };
+64
View File
@@ -0,0 +1,64 @@
"use client";
import { LinkApi, type LinkFormData, linkFormSchema } from "@/entities/link";
import LinkForm from "./link-form";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import dayjs from "dayjs";
import { useMutation } from "@tanstack/react-query";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { useRouter } from "next/navigation";
import { AUTH_USER_ID } from "@/shared/config";
import { getCookie } from "@common/components";
function RegistLinkPage() {
const { setMessage: alert } = useAlertStore((state) => state);
const router = useRouter();
const userUniqId = getCookie(AUTH_USER_ID) ?? "";
const form = useForm<LinkFormData>({
resolver: zodResolver(linkFormSchema),
defaultValues: {
link_nm: '',
link_url: '',
link_srvr_ip: '',
link_db_cd: '',
link_key: '',
link_id: '',
link_pswd: '',
srvc_usg: '',
link_batch_time: 5,
link_clsf_cd: 'none',
},
});
const { mutate: insertLinkInfo } = useMutation({
mutationFn: (data: LinkFormData) => LinkApi.insertLinkInfo(data),
onSuccess: () => {
alert('저장되었습니다.');
router.push('/link');
}
});
const handleInsertLink = (data: LinkFormData) => {
const insertData = {
...data,
link_clsf_cd: data.link_clsf_cd !== 'none' ? data.link_clsf_cd : null,
next_link_excn_dt: dayjs().add(Number(data.link_batch_time), 'minute').format('YYYY-MM-DD HH:mm:ss'),
mdfr: userUniqId,
};
insertLinkInfo(insertData);
};
return (
<div className="card card-border !mb-0 !mt-6">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">연계 등록</h3>
</div>
<LinkForm form={form} handleInsertLink={handleInsertLink} />
</div>
);
};
export { RegistLinkPage };
+1
View File
@@ -0,0 +1 @@
export { LinkLogPage } from './ui/link-log-page';
@@ -0,0 +1,55 @@
import dayjs from "dayjs";
import { createColumnHelper } from "@tanstack/react-table";
import { type LinkLog } from "@/entities/link";
const columnHelper = createColumnHelper<LinkLog>();
const columns = [
columnHelper.accessor('rownum', {
id: 'rownum',
header: 'NO',
}),
columnHelper.accessor('link_sn', {
id: 'link_sn',
header: '연계일련번호',
}),
columnHelper.accessor('link_nm', {
id: 'link_nm',
header: '연계 명',
}),
columnHelper.display({
id: 'link_rslt_cd',
header: '연계실행결과',
cell: (info) => {
const isSucc = info.row.original.link_rslt_cd.trim() === 'SUCC';
return <span className={`${isSucc ? 'text-[rgb(53,162,235)]' : 'text-[rgb(255,99,132)]'}`}>{isSucc ? '성공' : '실패'}</span>
},
}),
columnHelper.accessor('link_err_cd', {
id: 'link_err_cd',
header: '연계오류코드',
cell: (info) => (info.getValue() ? info.getValue() : '-'),
}),
columnHelper.accessor('err_cn', {
id: 'err_cn',
header: '연계오류메세지',
cell: (info) => (
<div
className="max-w-[500px] truncate"
title={info.getValue() ?? ''}
>
{info.getValue() || '-'}
</div>
),
}),
columnHelper.accessor('log_crt_dt', {
id: 'log_crt_dt',
header: '연계실행일자',
cell: (info) => {
const date = dayjs(info.getValue());
return date.format('YYYY-MM-DD HH:mm');
}
}),
];
export { columns };
@@ -0,0 +1,189 @@
"use client";
import "@common/assets/styles/grid.css";
import { useState } from "react";
import { Button, Input, Label, DatePicker, Select, SelectTrigger, SelectContent, SelectItem, SelectValue, LoadingWithAnimation } from "@common/components";
import { useQuery } from "@tanstack/react-query";
import { getCoreRowModel, type PaginationState, type RowSelectionState, } from "@tanstack/react-table";
import { LinkApi, type LinkSearchParam } from "@/entities/link";
import { columns } from "../model/table-columns";
import dayjs from "dayjs";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { useDataTable } from "@/shared/lib";
function LinkLogPage() {
const { setMessage: alert } = useAlertStore((state) => state);
const [linkSn, setLinkSn] = useState<string>('');
const [linkNm, setLinkNm] = useState<string>('');
const [isSucc, setIsSucc] = useState<string>('ALL');
const [startDate, setStartDate] = useState<string>(dayjs().subtract(7, "day").format('YYYY-MM-DD'));
const [endDate, setEndDate] = useState<string>(dayjs().format('YYYY-MM-DD'));
const [linkSearchParam, setLinkSearchParam] = useState<LinkSearchParam>({
linkSn: '',
linkNm: '',
isSucc: '',
startDate: '',
endDate: '',
});
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 100,
});
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const query = useQuery({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkList`, linkSearchParam, pagination],
queryFn: () =>
LinkApi.getLinkLogList({
...linkSearchParam,
page: pagination.pageIndex,
size: pagination.pageSize,
isSucc,
startDate,
endDate,
}),
});
const { tableComponent } = useDataTable({
query,
tableOptions: {
columns,
state: {
pagination,
rowSelection,
},
manualPagination: true,
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
onPaginationChange: setPagination,
onRowSelectionChange: setRowSelection,
},
dataTableOptions: {
viewPagination: true,
},
});
const handleResetSearchParam = () => {
setIsSucc('ALL');
setLinkNm('');
setLinkSn('');
setStartDate(dayjs().subtract(7, "day").format('YYYY-MM-DD'));
setEndDate(dayjs().format('YYYY-MM-DD'));
setLinkSearchParam({
...linkSearchParam,
linkSn: '',
linkNm: '',
isSucc: 'ALL',
startDate: dayjs().subtract(7, "day").format('YYYY-MM-DD'),
endDate: dayjs().format('YYYY-MM-DD'),
});
};
const handleSubmit = async (e?: React.FormEvent<HTMLFormElement>) => {
e?.preventDefault();
if (startDate && endDate) {
if (startDate > endDate) {
alert('종료일이 시작일보다 이전일 수 없습니다.');
return;
} else {
setPagination({
...pagination,
pageIndex: 0,
});
setLinkSearchParam({
...linkSearchParam,
linkSn,
linkNm,
isSucc,
startDate,
endDate,
});
}
} else {
alert('조회 날짜를 선택해주세요.');
return;
}
};
return (
<div className="card card-border !mt-6">
<div className="card card-border">
<form className="flex items-center gap-2 p-2" onSubmit={handleSubmit}>
<Label htmlFor="liSnSearchInput" className="mr-2 text-label">
일련번호
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem] mr-4"
id="liSnSearchInput"
value={linkSn}
onChange={(e) => setLinkSn(e.target.value)}
autoComplete="off"
/>
<Label htmlFor="liNmSearchInput" className="mr-2 text-label">
연계 명
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem] mr-4"
id="liNmSearchInput"
value={linkNm}
onChange={(e) => setLinkNm(e.target.value)}
autoComplete="off"
/>
<Label htmlFor="liResultCode" className="mr-2 text-label">
실행결과
</Label>
<Select onValueChange={(e) => setIsSucc(e)} value={isSucc}>
<SelectTrigger id="liResultCode" className="w-[10rem] mr-4">
<SelectValue placeholder="전체"></SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="ALL">전체</SelectItem>
<SelectItem value="SUCC">성공</SelectItem>
<SelectItem value="FAIL">실패</SelectItem>
</SelectContent>
</Select>
<Label htmlFor="sDateSearchInput" className="mx-2 text-label">
시작일
</Label>
<DatePicker id="sDateSearchInput" mode={"single"} selected={dayjs(startDate).toDate()} onSelect={(e) => setStartDate(dayjs(e).format('YYYY-MM-DD'))} />
<Label htmlFor="eDateSearchInput" className="mx-2 text-label">
종료일
</Label>
<DatePicker id="eDateSearchInput" mode={"single"} className="mr-2" selected={dayjs(endDate).toDate()} onSelect={(e) => setEndDate(dayjs(e).format('YYYY-MM-DD'))} />
<Button color="green" className="h-[3.2rem]" type="button" onClick={handleResetSearchParam}>
초기화
</Button>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
</form>
</div>
<div className="card card-border flex flex-col h-[calc(100vh-28rem)]">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">로그 목록 (검색 조건에 따른 건수 : {query.data?.totalElements.toLocaleString('ko-KR') ?? 0} )</h3>
</div>
<div className="card !m-[1.2rem] overflow-auto h-full !p-0">
{query.isLoading ?
<div className="[data-theme='black']:bg-transparent rounded-lg p-10 h-full flex justify-center items-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
:
<div>{tableComponent}</div>
}
</div>
</div>
</div>
)
};
export { LinkLogPage };
+1
View File
@@ -0,0 +1 @@
export { LinkParamsPage } from './ui/link-params-page';
@@ -0,0 +1,26 @@
import { createColumnHelper } from "@tanstack/react-table";
import { type Link } from "@/entities/link";
const columnHelper = createColumnHelper<Link>();
const columns = [
columnHelper.accessor((_, index) => index + 1, {
id: 'no',
header: 'NO',
}),
columnHelper.accessor('link_sn', {
id: 'link_sn',
header: '연계 일련번호',
}),
columnHelper.accessor('link_nm', {
id: 'link_nm',
header: '연계 명',
}),
columnHelper.accessor('srvc_usg', {
id: 'srvc_usg',
header: '서비스용도',
cell: (info) => (info.getValue() ? info.getValue() : '-'),
}),
];
export { columns };
@@ -0,0 +1,98 @@
import { createColumnHelper } from "@tanstack/react-table";
import { type LinkVrbl } from "@/entities/link";
import { Checkbox } from "@common/components";
const columnHelper = createColumnHelper<LinkVrbl>();
function vrblColumns({
selectedVrblIds,
setSelectedVrblIds,
}: {
selectedVrblIds: string[];
setSelectedVrblIds: React.Dispatch<React.SetStateAction<string[]>>;
}) {
return [
columnHelper.display({
id: "select",
header: ({ table }) => {
const allRows = table.getRowModel().rows;
const allSelected =
allRows.length > 0 &&
allRows.every((row) =>
selectedVrblIds.includes(row.original.link_vrbl_sn)
);
return (
<div className="flex justify-center items-center">
<Checkbox
className="bg-white"
checked={
allSelected
? true
: false
}
onCheckedChange={(checked) => {
if (checked) {
setSelectedVrblIds(allRows.map((row) => row.original.link_vrbl_sn));
} else {
setSelectedVrblIds([]);
}
}}
/>
</div>
);
},
cell: ({ row }) => {
const id = row.original.link_vrbl_sn;
const checked = selectedVrblIds.includes(id);
return (
<div className="flex justify-center items-center">
<Checkbox
checked={checked}
onClick={(e) => e.stopPropagation()}
onCheckedChange={(checked) => {
setSelectedVrblIds((prev) =>
checked ? [...prev, id] : prev.filter((x) => x !== id)
);
}}
/>
</div>
);
},
}),
columnHelper.accessor("link_vrbl_sn", {
id: "link_vrbl_sn",
header: "연계 변수 일련번호",
}),
columnHelper.accessor("link_vrbl_nm", {
id: "link_vrbl_nm",
header: "변수 명",
}),
columnHelper.accessor("link_vrbl_cd", {
id: "link_vrbl_cd",
header: "변수코드",
cell: (info) => (info.getValue() ? info.getValue() : '-'),
}),
columnHelper.accessor("link_vrbl_vl", {
id: "link_vrbl_vl",
header: "변수 값",
cell: (info) => (info.getValue() === 'now' ? '요청일자' : info.getValue() === 'nowMonth' ? '요청월' : info.getValue()),
}),
columnHelper.accessor("link_vrbl_expln", {
id: "link_vrbl_expln",
header: "설명",
cell: (info) => (
<div
className="max-w-72 truncate"
title={info.getValue() ?? ''}
>
{info.getValue() || '-'}
</div>
),
}),
];
}
export { vrblColumns };
@@ -0,0 +1,351 @@
'use client';
import {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
DialogClose,
Button,
Input,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Checkbox,
RadioGroup,
RadioGroupItem,
Label
} from "@common/components";
import { FormItem, FormControl, FormField, Form } from "@/shared/ui/form";
import { type LinkVrblFormData } from "@/entities/link";
import dayjs from "dayjs";
import type { UseFormReturn } from "react-hook-form";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { useState, useEffect } from "react";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
type LinkParamsDialogProps = {
selectedLink: {
linkSn: string;
linkNm: string;
};
form: UseFormReturn<LinkVrblFormData>;
insertLinkVrbl: (data: LinkVrblFormData) => void;
dialogOpen: boolean;
onOpenChange: (val: boolean) => void;
updateLinkVrbl: (data: LinkVrblFormData) => void;
}
function LinkParamsDialog({ selectedLink, form, insertLinkVrbl, dialogOpen, onOpenChange, updateLinkVrbl }: LinkParamsDialogProps) {
const isModifyMode = !!form.getValues('link_vrbl_sn');
const { confirm } = useConfirm();
const [onConfirm, setOnConfirm] = useState<boolean>(false);
const [isToday, setIsToday] = useState<boolean>(false);
const [checkNowMonth, setCheckNowMonth] = useState<string>('now');
const handleConfirm = async (callback: () => Promise<void>) => {
setOnConfirm(true);
await callback();
setOnConfirm(false);
};
function replaceEmptyWithNull<T extends Record<string, unknown>>(data: T): T {
const result = {} as T;
for (const [key, value] of Object.entries(data)) {
(result as Record<string, unknown>)[key] = value === '' ? null : value;
}
return result as T;
};
const handleSubmit = async (data: LinkVrblFormData) => {
const confirmMsg = isModifyMode ? '수정 하시겠습니까?' : '저장 하시겠습니까?';
await handleConfirm(async () => {
const cleanData = replaceEmptyWithNull(data);
if (await confirm(confirmMsg)) {
if (isModifyMode) {
updateLinkVrbl(isToday ? { ...cleanData, link_vrbl_vl: checkNowMonth } : cleanData);
} else {
insertLinkVrbl(isToday ? { ...cleanData, link_vrbl_vl: checkNowMonth } : cleanData);
}
}
});
};
const handleCheckTodayValue = (check: boolean | string) => {
if (check) {
setIsToday(true);
form.setValue('link_vrbl_vl', (checkNowMonth === 'now' ? '요청일자' : '요청월'));
} else {
setIsToday(false);
form.setValue('link_vrbl_vl', '');
}
};
useEffect(() => {
if (!dialogOpen) {
setIsToday(false);
setCheckNowMonth('now');
form.reset({
link_vrbl_nm: '',
link_vrbl_expln: '',
link_vrbl_cd: '',
link_vrbl_vl: '',
});
}
if (isModifyMode && (form.getValues('link_vrbl_vl') === 'now' || form.getValues('link_vrbl_vl') === 'nowMonth')) {
setIsToday(true);
setCheckNowMonth(form.getValues('link_vrbl_vl'));
}
}, [dialogOpen]);
return (
<Dialog
open={dialogOpen}
onOpenChange={(open) => {
onOpenChange(open);
}}
>
<DialogTrigger asChild>
<Button color="green" className="h-[3.2rem]" onClick={() => onOpenChange(true)}>행 추가</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[55rem]">
<DialogHeader>
<DialogTitle>
{selectedLink.linkNm} ({selectedLink.linkSn})
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)}>
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<TableBody>
{isModifyMode &&
<TableRow>
<TableHead>변수 일련번호</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_vrbl_sn"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
}
<TableRow>
<TableHead>* 변수 명</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_vrbl_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.link_vrbl_nm && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.link_vrbl_nm.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>변수 설명</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_vrbl_expln"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.link_vrbl_expln && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.link_vrbl_expln.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>변수 코드</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_vrbl_cd"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.link_vrbl_cd && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.link_vrbl_cd.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 변수 값</TableHead>
<TableCell>
<FormField
control={form.control}
name="link_vrbl_vl"
render={({ field }) => (
<FormItem>
<div className="flex items-center gap-x-2 mb-4">
<Checkbox id="isToday" className="!border-gray-600" checked={isToday} onCheckedChange={(check) => handleCheckTodayValue(check)} />
<label htmlFor="isToday" className="text-gray-600">변수 값이 오늘 날짜 일시 체크해 주세요.</label>
</div>
{isToday &&
<div className="flex items-center gap-x-2 mb-4">
<RadioGroup
name="checkNowMonth"
onValueChange={(value) => {
setCheckNowMonth(value);
form.setValue('link_vrbl_vl', (value === 'now' ? '요청일자' : '요청월'));
}}
>
<div className="flex items-center space-x-2">
<RadioGroupItem value="now" id="now" checked={checkNowMonth === 'now'} />
<Label htmlFor="now">요청일자(YYYY-MM-DD)</Label>
</div>
<div className="flex items-center space-x-2">
<RadioGroupItem value="nowMonth" id="nowMonth" checked={checkNowMonth === 'nowMonth'} />
<Label htmlFor="nowMonth">요청월(YYYY-MM)</Label>
</div>
</RadioGroup>
</div>
}
<FormControl>
<Input
{...field}
value={field.value ? (field.value === 'now' ? '요청일자' : field.value === 'nowMonth' ? '요청월' : field.value) : ''}
className={`!text-[1.3rem] ${isToday ? 'bg-gray-100' : ''}`}
autoComplete="off"
disabled={isToday}
/>
</FormControl>
{form.formState.errors.link_vrbl_vl && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.link_vrbl_vl.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
{isModifyMode &&
<>
<TableRow>
<TableHead>수정자</TableHead>
<TableCell>
<FormField
control={form.control}
name="mdfr"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>수정일시</TableHead>
<TableCell>
<FormField
control={form.control}
name="mdfcn_dt"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ? dayjs(field.value).format('YYYY-MM-DD') : ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
</>
}
</TableBody>
</Table>
</div>
<DialogFooter>
<Button type="submit">저장</Button>
<DialogClose asChild>
<Button color="white">취소</Button>
</DialogClose>
</DialogFooter>
</form>
</Form>
<ConfirmDialog isOpen={onConfirm} />
</DialogContent>
</Dialog>
)
};
export { LinkParamsDialog };
@@ -0,0 +1,405 @@
'use client';
import { useState, useMemo } from "react";
import {
Button,
DataTable,
Input,
Label,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
LoadingWithAnimation,
} from "@common/components";
import { getCoreRowModel, useReactTable, type PaginationState, type RowSelectionState, } from "@tanstack/react-table";
import { LinkApi, type Link, type LinkSearchParam, type LinkVrblFormData, linkVrblFormSchema } from "@/entities/link";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { columns } from "../model/table-columns";
import { vrblColumns } from "../model/vrbl-table-columns";
import { type LinkVrbl } from "@/entities/link";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { LinkParamsDialog } from "./link-params-dialog";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { getUserInfo } from "../../../../../../packages/common/components/src/api";
import { AUTH_USER_ID } from "@/shared/config";
import { getCookie } from "@common/components";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { useDataTable } from "@/shared/lib";
function LinkParamsPage() {
const queryClient = useQueryClient();
const [linkSn, setLinkSn] = useState<string>('');
const [linkNm, setLinkNm] = useState<string>('');
const [linkSearchParam, setLinkSearchParam] = useState<LinkSearchParam>({
linkSn: '',
linkNm: ''
});
const [selectedLink, setSelectedLink] = useState<{
linkSn: string;
linkNm: string;
}>({
linkSn: '',
linkNm: ''
});
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 100,
});
const { confirm } = useConfirm();
const [selectedVrblIds, setSelectedVrblIds] = useState<string[]>([]);
const [isDBdata, setIsDBData] = useState<boolean>(false);
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
const [onConfirm, setOnConfirm] = useState<boolean>(false);
const userUniqId = getCookie(AUTH_USER_ID) ?? "";
const { setMessage: alert } = useAlertStore((state) => state);
const dbIdList = ['link0001', 'link0002'];
// Link 목록 쿼리
const query = useQuery({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkList`, linkSearchParam],
queryFn: () => LinkApi.getLinkList({
...linkSearchParam,
page: pagination.pageIndex,
size: pagination.pageSize,
}),
});
// LinkVrbl 목록 쿼리 - 별도 관리
const linkVrblQuery = useQuery({
queryKey: ['linkVrblList', selectedLink.linkSn],
queryFn: () => LinkApi.getLinkVrblList(selectedLink.linkSn),
enabled: !!selectedLink.linkSn && !dbIdList.includes(selectedLink.linkSn),
staleTime: 0, // 항상 최신 데이터를 가져오도록 설정
});
const handleResetSearchParam = () => {
setSelectedLink({
linkSn: '',
linkNm: ''
});
setLinkSn('');
setLinkNm('');
setLinkSearchParam({
...linkSearchParam,
linkSn: '',
linkNm: ''
});
};
const handleConfirm = async (callback: () => Promise<void>) => {
setOnConfirm(true);
await callback();
setOnConfirm(false);
};
const { mutateAsync: insertLinkVrbl } = useMutation({
mutationFn: async (data: LinkVrblFormData) =>
await LinkApi.insertLinkVrbl({
...data,
link_sn: selectedLink.linkSn,
mdfr: userUniqId,
}),
onSuccess: async () => {
// 쿼리 무효화를 통한 최신 데이터 가져오기
await queryClient.invalidateQueries({
queryKey: ['linkVrblList', selectedLink.linkSn]
});
setDialogOpen(false);
alert('저장되었습니다.');
}
});
const { mutateAsync: updateLinkVrbl } = useMutation({
mutationFn: async (data: LinkVrblFormData) => await LinkApi.updateLinkVrblInfo({
...data,
link_sn: selectedLink.linkSn,
mdfr: userUniqId,
}),
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ['linkVrblList', selectedLink.linkSn]
});
setDialogOpen(false);
alert('저장되었습니다.');
}
});
const { mutateAsync: deleteLinkVrbl } = useMutation({
mutationFn: async (data: string[]) => await LinkApi.deleteLinkVrbl(data),
onSuccess: async () => {
await queryClient.invalidateQueries({
queryKey: ['linkVrblList', selectedLink.linkSn]
});
setSelectedVrblIds([]);
alert('삭제되었습니다.');
}
});
// linkVrblQuery의 데이터를 사용
const tableData = useMemo(() => {
return linkVrblQuery.data?.content ?? [];
}, [linkVrblQuery.data]);
const vrblCols = useMemo(
() =>
vrblColumns({
selectedVrblIds,
setSelectedVrblIds,
}),
[selectedVrblIds]
);
const vrblTable = useReactTable({
data: tableData,
columns: vrblCols,
getCoreRowModel: getCoreRowModel(),
});
const form = useForm<LinkVrblFormData>({
resolver: zodResolver(linkVrblFormSchema),
defaultValues: {},
});
const handleRowClick = async (link: Link) => {
setSelectedLink({
linkSn: link.link_sn,
linkNm: link.link_nm,
});
setSelectedVrblIds([]);
if (dbIdList.includes(link.link_clsf_cd)) {
setIsDBData(true);
} else {
setIsDBData(false);
}
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setSelectedLink({
linkSn: '',
linkNm: ''
});
setLinkSearchParam({
...linkSearchParam,
linkSn,
linkNm
});
};
const fetchUserInfo = async () => {
const userData = await getUserInfo();
return userData.userName;
};
const handleDeleteParam = async () => {
if (selectedVrblIds.length === 0) {
alert('삭제할 파라미터를 선택해 주세요.');
} else {
await handleConfirm(async () => {
if (await confirm('선택한 파라미터 정보를 삭제하시겠습니까?')) {
deleteLinkVrbl(selectedVrblIds);
}
});
}
};
const handleVrblRowClick = async (data: LinkVrbl) => {
const linkVrblInfo = await LinkApi.getLinkVrblInfo(data.link_vrbl_sn);
if (linkVrblInfo) {
let newData = { ...linkVrblInfo };
if (linkVrblInfo.mdfr) {
const userName = await fetchUserInfo();
newData = {
...linkVrblInfo,
mdfr: userName,
};
}
form.reset(newData);
}
setDialogOpen(true);
};
const { tableComponent } = useDataTable({
query,
tableOptions: {
columns,
state: {
pagination,
rowSelection,
},
manualPagination: true,
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
onPaginationChange: setPagination,
onRowSelectionChange: setRowSelection,
},
dataTableOptions: {
onRowClick: handleRowClick,
viewPagination: true,
},
});
// LinkVrbl 데이터 표시 로직
const renderLinkVrblContent = () => {
if (isDBdata) {
return (
<div className="flex items-center justify-center mt-14 text-gray-500 text-3xl flex-1">
변수를 지원하지 않는 연계 데이터입니다.
</div>
);
}
if (!selectedLink.linkSn) {
return (
<div className="flex items-center justify-center mt-14 text-gray-500 text-3xl flex-1">
연계 데이터를 선택해주세요.
</div>
);
}
if (linkVrblQuery.isLoading) {
return (
<div className="[data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center h-full">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
);
}
return (
<>
<div className="mb-2 mt-14 flex justify-end items-center flex-none">
{tableData.length > 0 && (
<Button color="red" className="h-[3.2rem] mr-2" type="button" onClick={handleDeleteParam}>
행 삭제
</Button>
)}
<LinkParamsDialog
selectedLink={selectedLink}
form={form}
insertLinkVrbl={insertLinkVrbl}
dialogOpen={dialogOpen}
onOpenChange={setDialogOpen}
updateLinkVrbl={updateLinkVrbl}
/>
</div>
{tableData.length > 0 ? (
<div className="overflow-auto flex-1 min-h-[300px]">
<DataTable table={vrblTable} onRowClick={handleVrblRowClick} />
</div>
) : (
<div className="flex items-center justify-center h-20 text-gray-500 text-3xl">
등록된 연계 변수가 없습니다.
</div>
)}
</>
);
};
return (
<div className="card card-border !mt-6">
<div className="card card-border">
<form className="flex items-center gap-2 p-2" onSubmit={handleSubmit}>
<Label htmlFor="liSnSearchInput" className="mr-2 text-label">
일련번호
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem] mr-4"
id="liSnSearchInput"
value={linkSn}
onChange={(e) => setLinkSn(e.target.value)}
autoComplete="off"
/>
<Label htmlFor="liNmSearchInput" className="mr-2 text-label">
연계 명
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem] mr-2"
id="liNmSearchInput"
value={linkNm}
onChange={(e) => setLinkNm(e.target.value)}
autoComplete="off"
/>
<Button color="green" className="h-[3.2rem]" type="button" onClick={handleResetSearchParam}>
초기화
</Button>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
</form>
</div>
<div className="card !mb-0 flex h-[calc(100vh-28rem)] gap-5 !p-0">
<div className="card card-border w-1/2 !mx-0 flex flex-col">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">연계 목록</h3>
</div>
<div className="card !m-[1.2rem] overflow-auto !p-0 h-full">
{!query.isLoading ? (
<div>{tableComponent}</div>
) : (
<div className="[data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center h-full">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
</div>
</div>
<div className="card card-border w-1/2 !mx-0 flex flex-col">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">연계 변수 정보</h3>
</div>
<div className="card !m-[1.2rem] !p-0 overflow-auto h-full flex flex-col">
<Table variant="secondary" className="flex-none">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>연계 일련번호</TableHead>
<TableCell>
{selectedLink.linkSn ? selectedLink.linkSn : '-'}
</TableCell>
</TableRow>
<TableRow>
<TableHead>연계 명</TableHead>
<TableCell>
{selectedLink.linkNm ? selectedLink.linkNm : '-'}
</TableCell>
</TableRow>
</TableBody>
</Table>
{renderLinkVrblContent()}
</div>
</div>
</div>
<ConfirmDialog isOpen={onConfirm} />
</div>
);
}
export { LinkParamsPage };
+1
View File
@@ -0,0 +1 @@
export { LinkStatsPage } from './ui/link-stats-page';
@@ -0,0 +1,378 @@
"use client";
import { useState, useEffect, useRef } from "react";
import dayjs from "dayjs";
import { LinkApi, type LinkStats, type LinkSearchParam } from "@/entities/link";
import { Button, Label, DatePicker, LoadingWithAnimation } from "@common/components";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Tooltip,
Legend,
type ChartOptions,
type Chart,
} from "chart.js";
import { Line } from "react-chartjs-2";
import { getCoreRowModel, type PaginationState, type RowSelectionState, } from "@tanstack/react-table";
import { columns } from "@/pages/linkLog/model/table-columns";
import { useDataTable } from "@/shared/lib";
import { useQuery } from "@tanstack/react-query";
interface LinkStatsListObject {
linkSuccStats: LinkStats[] | null;
linkFailStats: LinkStats[] | null;
}
function LinkStatsPage() {
const succChartRef = useRef<Chart<"line"> | null>(null);
const failChartRef = useRef<Chart<"line"> | null>(null);
const [startDate, setStartDate] = useState<string>(dayjs().subtract(7, "day").format('YYYY-MM-DD'));
const [endDate, setEndDate] = useState<string>(dayjs().format('YYYY-MM-DD'));
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 100,
});
const [linkStatsList, setLinkStatsList] = useState<LinkStatsListObject | null>(null);
const [logQueryParam, setLogQueryParam] = useState<{
isSucc: 'SUCC' | 'FAIL';
linkSn?: string;
linkNm?: string;
} | null>(null);
const query = useQuery({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkList`, logQueryParam, pagination],
queryFn: () =>
LinkApi.getLinkLogList({
...logQueryParam,
page: pagination.pageIndex,
size: pagination.pageSize,
startDate,
endDate,
}),
enabled: !!logQueryParam,
});
const { tableComponent } = useDataTable({
query,
tableOptions: {
columns,
state: {
pagination,
rowSelection,
},
manualPagination: true,
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
onPaginationChange: setPagination,
onRowSelectionChange: setRowSelection,
},
dataTableOptions: {
viewPagination: true,
},
});
const [linkSearchParam, setLinkSearchParam] = useState<LinkSearchParam>({
linkSn: '',
linkNm: '',
startDate: '',
endDate: '',
});
ChartJS.register(
LineElement,
CategoryScale,
LinearScale,
PointElement,
Tooltip,
Legend
);
const succData = {
labels: linkStatsList?.linkSuccStats?.map((e) => e.link_nm),
datasets: [
{
label: '연계 성공',
data: linkStatsList?.linkSuccStats?.map((e) => e.count),
fill: false,
borderColor: 'rgb(53, 162, 235)',
backgroundColor: 'rgb(53, 162, 235)',
tension: 0.1,
pointRadius: 6,
pointHoverRadius: 8,
},
],
};
const succOptions: ChartOptions<'line'> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
},
},
scales: {
y: {
min: 0,
},
},
};
const failData = {
labels: linkStatsList?.linkFailStats?.map((e) => e.link_nm),
datasets: [
{
label: '연계 실패',
data: linkStatsList?.linkFailStats?.map((e) => e.count),
fill: false,
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgb(255, 99, 132)',
tension: 0.1,
pointRadius: 6,
pointHoverRadius: 8,
},
],
};
const failOptions: ChartOptions<'line'> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
},
},
scales: {
y: {
min: 0,
},
},
};
const handleResetSearchParam = async () => {
setLinkSearchParam({
linkSn: '',
linkNm: '',
startDate: dayjs().subtract(7, "day").format('YYYY-MM-DD'),
endDate: dayjs().format('YYYY-MM-DD'),
});
setLogQueryParam({
isSucc: 'SUCC',
linkNm: '',
linkSn: '',
});
setStartDate(dayjs().subtract(7, "day").format('YYYY-MM-DD'));
setEndDate(dayjs().format('YYYY-MM-DD'));
const data = await LinkApi.getLinkStatsList({
...linkSearchParam,
linkSn: '',
linkNm: '',
startDate: dayjs().subtract(7, "day").format('YYYY-MM-DD'),
endDate: dayjs().format('YYYY-MM-DD'),
});
setLinkStatsList(data);
};
const handleSubmit = async (e?: React.FormEvent<HTMLFormElement>) => {
e?.preventDefault();
if (startDate && endDate) {
if (startDate > endDate) {
alert('종료일이 시작일보다 이전일 수 없습니다.');
return;
} else {
const data = await LinkApi.getLinkStatsList({
...linkSearchParam,
startDate,
endDate
});
setLinkStatsList(data);
setLogQueryParam({
isSucc: 'SUCC',
linkNm: '',
linkSn: '',
});
setLinkSearchParam({
...linkSearchParam,
startDate,
endDate
});
}
} else {
alert('조회 날짜를 선택해주세요.');
return;
}
};
const handleSuccChartClick = async (event: React.MouseEvent<HTMLCanvasElement>) => {
if (!succChartRef.current) return;
const chart = succChartRef.current;
const points = chart.getElementsAtEventForMode(
event.nativeEvent,
"nearest",
{ intersect: true },
false
);
if (points[0] && linkStatsList?.linkSuccStats) {
const index = points[0].index;
setPagination({
...pagination,
pageIndex: 0,
pageSize: 100,
});
setLogQueryParam({
isSucc: 'SUCC',
linkNm: linkStatsList.linkSuccStats[index]?.link_nm,
linkSn: linkStatsList.linkSuccStats[index]?.link_sn,
});
}
};
const handleFailChartClick = async (event: React.MouseEvent<HTMLCanvasElement>) => {
if (!failChartRef.current) return;
const chart = failChartRef.current;
const points = chart.getElementsAtEventForMode(
event.nativeEvent,
"nearest",
{ intersect: true },
false
);
if (points[0] && linkStatsList?.linkFailStats) {
const index = points[0].index;
setPagination({
...pagination,
pageIndex: 0,
pageSize: 100,
});
setLogQueryParam({
isSucc: 'FAIL',
linkNm: linkStatsList.linkFailStats[index]?.link_nm,
linkSn: linkStatsList.linkFailStats[index]?.link_sn,
});
}
};
const handleSubmitToday = async () => {
const data = await LinkApi.getLinkStatsList({
...linkSearchParam,
startDate: dayjs().format('YYYY-MM-DD'),
endDate: dayjs().format('YYYY-MM-DD'),
});
setEndDate(dayjs().format('YYYY-MM-DD'));
setStartDate(dayjs().format('YYYY-MM-DD'));
setLinkStatsList(data);
setLinkSearchParam({
...linkSearchParam,
startDate: dayjs().format('YYYY-MM-DD'),
endDate: dayjs().format('YYYY-MM-DD'),
});
setLogQueryParam({
isSucc: 'SUCC',
linkNm: '',
linkSn: '',
});
};
useEffect(() => {
const fetchData = async () => {
const data = await LinkApi.getLinkStatsList({
...linkSearchParam,
startDate,
endDate
});
setLinkStatsList(data);
};
setLinkSearchParam({
...linkSearchParam,
startDate,
endDate
});
fetchData();
}, []);
return (
<div className="card !mb-0 !min-h-[calc(100vh-16.8rem)]">
<div className="card card-border">
<form className="flex items-center gap-2 p-2" onSubmit={handleSubmit}>
<Label htmlFor="sDateSearchInput" className="mx-2 text-label">
시작일
</Label>
<DatePicker id="sDateSearchInput" mode={"single"} selected={dayjs(startDate).toDate()} onSelect={(e) => setStartDate(dayjs(e).format('YYYY-MM-DD'))} />
<Label htmlFor="eDateSearchInput" className="mx-2 text-label">
종료일
</Label>
<DatePicker id="eDateSearchInput" mode={"single"} className="mr-2" selected={dayjs(endDate).toDate()} onSelect={(e) => setEndDate(dayjs(e).format('YYYY-MM-DD'))} />
<Button color="green" className="h-[3.2rem]" type="button" onClick={handleResetSearchParam}>
초기화
</Button>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
<Button className="h-[3.2rem]" type="button" onClick={handleSubmitToday}>
오늘 날짜로 조회
</Button>
</form>
</div>
<div className="card card-border">
<div className="card !m-[1.2rem] !p-0 flex flex-col gap-y-8">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">조회 일자 : {`${linkSearchParam.startDate} ~ ${linkSearchParam.endDate}`}</h3>
</div>
<div className="h-[32rem] w-full">
<Line ref={succChartRef} data={succData} options={succOptions} onClick={handleSuccChartClick} />
</div>
<div className="h-[32rem]">
<Line ref={failChartRef} data={failData} options={failOptions} onClick={handleFailChartClick} />
</div>
</div>
<div className="card !m-[1.2rem] !p-0">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">
{logQueryParam?.linkNm ? `${logQueryParam.linkNm} 연계 ${logQueryParam.isSucc === 'FAIL' ? '실패' : '성공'} 로그 목록 (${linkSearchParam.startDate} ~ ${linkSearchParam.endDate}) - ${query.data?.totalElements.toLocaleString('ko-KR') ?? 0}건` : '로그 목록'}
</h3>
</div>
<div className="card !m-[1.2rem] h-[40rem] overflow-auto !p-0">
{logQueryParam?.linkNm ?
query.isLoading ?
<div className="[data-theme='black']:bg-transparent rounded-lg p-10 h-full flex justify-center items-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
:
<div>{tableComponent}</div>
:
<div className="flex items-center justify-center h-full text-gray-500 text-3xl">
차트 데이터를 선택해주세요.
</div>
}
</div>
</div>
</div>
</div>
)
};
export { LinkStatsPage };
+1
View File
@@ -0,0 +1 @@
export { LinkTablePage} from "./ui/link-table-page";
@@ -0,0 +1,103 @@
import { createColumnHelper } from "@tanstack/react-table";
import { type LinkTableColumns } from "@/entities/link";
import { Checkbox } from "@common/components";
const columnHelper = createColumnHelper<LinkTableColumns>();
function tableColumns({ selectedColIds, setSelectedColIds }: {
selectedColIds: string[];
setSelectedColIds: React.Dispatch<React.SetStateAction<string[]>>;
}) {
return [
columnHelper.display({
id: "select",
header: ({ table }) => {
const allRows = table.getRowModel().rows;
const allSelected =
allRows.length > 0 &&
allRows.every((row) =>
selectedColIds.includes(row.original.col_sn)
);
return (
<div className="flex justify-center items-center">
<Checkbox
className="bg-white"
checked={
allSelected
? true
: false
}
onCheckedChange={(checked) => {
if (checked) {
setSelectedColIds(allRows.map((row) => row.original.col_sn));
} else {
setSelectedColIds([]);
}
}}
/>
</div>
);
},
cell: ({ row }) => {
const id = row.original.col_sn;
const checked = selectedColIds.includes(id);
return (
<div className="flex justify-center items-center">
<Checkbox
checked={checked}
onClick={(e) => e.stopPropagation()}
onCheckedChange={(checked) => {
setSelectedColIds((prev) =>
checked ? [...prev, id] : prev.filter((x) => x !== id)
);
}}
/>
</div>
);
},
}),
columnHelper.accessor('col_sn', {
id: 'col_sn',
header: '컬럼 일련번호'
}),
columnHelper.accessor('sou_col_nm', {
id: 'sou_col_nm',
header: '원천컬럼명',
cell: (info) => info.getValue() ? info.getValue() : '-',
}),
columnHelper.accessor('sou_col_korn_nm', {
id: 'sou_col_korn_nm',
header: '원천컬럼 한글명',
cell: (info) => info.getValue() ? info.getValue() : '-',
}),
columnHelper.accessor('sou_col_sz', {
id: 'sou_col_sz',
header: '원천컬럼 크기',
cell: (info) => info.getValue() ? info.getValue() : '-',
}),
columnHelper.accessor('trsf_col_nm', {
id: 'trsf_col_nm',
header: '변환컬럼명',
cell: (info) => info.getValue() ? info.getValue() : '-',
}),
columnHelper.accessor('trsf_col_korn_nm', {
id: 'trsf_col_korn_nm',
header: '변환컬럼 한글명',
cell: (info) => info.getValue() ? info.getValue() : '-',
}),
columnHelper.accessor('trsf_col_sz', {
id: 'trsf_col_sz',
header: '변환컬럼 크기',
cell: (info) => info.getValue() ? info.getValue() : '-',
}),
columnHelper.accessor('pk_yn', {
id: 'pk_yn',
header: 'PK 여부',
cell: (info) => info.getValue() === 'Y' ? '예' : '아니오',
}),
]
}
export { tableColumns };
@@ -0,0 +1,503 @@
'use client';
import {
Dialog,
DialogTrigger,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
DialogClose,
Button,
Input,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
Select,
SelectTrigger,
SelectContent,
SelectItem,
SelectValue,
Checkbox
} from "@common/components";
import { FormItem, FormControl, FormField, Form } from "@/shared/ui/form";
import { type LinkTableColData, type LinkTable } from "@/entities/link";
import dayjs from "dayjs";
import type { UseFormReturn } from "react-hook-form";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { useState, useEffect } from "react";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
interface LinkTableDialogProps {
dialogOpen: boolean;
onOpenChange: (val: boolean) => void;
form: UseFormReturn<LinkTableColData>;
tableInfo: LinkTable;
insertLinkTableCol: (data: LinkTableColData) => void;
updateLinkTableCol: (data: LinkTableColData) => void;
}
function LinkTableDialog({ dialogOpen, onOpenChange, form, tableInfo, insertLinkTableCol, updateLinkTableCol }: LinkTableDialogProps) {
const isModifyMode = !!form.getValues('col_sn');
const { confirm } = useConfirm();
const [onConfirm, setOnConfirm] = useState<boolean>(false);
const [useColSeq, setUseColSeq] = useState<boolean>(false);
const handleConfirm = async (callback: () => Promise<void>) => {
setOnConfirm(true);
await callback();
setOnConfirm(false);
};
const handleSubmit = async (data: LinkTableColData) => {
const confirmMsg = isModifyMode ? '수정 하시겠습니까?' : '저장 하시겠습니까?';
await handleConfirm(async () => {
if (await confirm(confirmMsg)) {
if (!isModifyMode) {
insertLinkTableCol({
...data,
link_sn: tableInfo.link_sn,
tbl_sn: tableInfo.tbl_sn,
});
} else {
updateLinkTableCol({
...data,
link_sn: tableInfo.link_sn,
tbl_sn: tableInfo.tbl_sn,
});
}
}
});
};
const handleCheckColSeqValue = (check: boolean | string) => {
if (check) {
setUseColSeq(false);
form.setValue('col_seq', null);
} else {
setUseColSeq(true);
}
};
useEffect(() => {
if (!dialogOpen) {
setUseColSeq(false);
form.reset({
tbl_sn: '',
col_sn: '',
sou_col_nm: '',
sou_col_korn_nm: '',
sou_col_data_frm: '',
sou_col_sz: null,
trsf_col_nm: '',
trsf_col_korn_nm: '',
trsf_col_data_frm: '',
trsf_col_sz: null,
col_seq: null,
pk_yn: 'N',
mdfcn_dt: '',
mdfr: '',
});
}
if (isModifyMode && form.getValues('col_seq')) {
setUseColSeq(true);
}
}, [dialogOpen]);
return (
<Dialog
open={dialogOpen}
onOpenChange={(open) => {
onOpenChange(open);
}}
>
<DialogTrigger asChild>
<Button color="green" className="h-[3.2rem]" onClick={() => onOpenChange(true)}>행 추가</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-[55rem]">
<DialogHeader>
<DialogTitle>
{tableInfo.trsf_tbl_korn_nm} ({tableInfo.tbl_sn})
</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(handleSubmit)}>
<div className="card">
<Table variant="secondary">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<TableBody>
{isModifyMode &&
<TableRow>
<TableHead>컬럼 일련번호</TableHead>
<TableCell>
<FormField
control={form.control}
name="col_sn"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
}
<TableRow>
<TableHead>* 원천컬럼명</TableHead>
<TableCell>
<FormField
control={form.control}
name="sou_col_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.sou_col_nm && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.sou_col_nm.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 원천컬럼 한글명</TableHead>
<TableCell>
<FormField
control={form.control}
name="sou_col_korn_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.sou_col_korn_nm && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.sou_col_korn_nm.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 원천컬럼 데이터 형식</TableHead>
<TableCell>
<FormField
control={form.control}
name="sou_col_data_frm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.sou_col_data_frm && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.sou_col_data_frm.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>원천컬럼 크기</TableHead>
<TableCell>
<FormField
control={form.control}
name="sou_col_sz"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
type="number"
min={0}
max={99999999999999}
onChange={(e) => {
const onlyDigits = e.target.value.replace(/\D/g, "").slice(0, 14);
field.onChange(onlyDigits); // react-hook-form에 반영
}}
/>
</FormControl>
<p className="text-gray-500 text-base pt-2">
※ 14자리까지 입력 가능합니다.
</p>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>PK 여부</TableHead>
<TableCell>
<FormField
control={form.control}
name="pk_yn"
render={({ field }) => (
<FormItem>
<FormControl>
<Select value={field.value ?? "N"} onValueChange={field.onChange}>
<SelectTrigger id="liResultCode" className="w-[10rem] mr-4">
<SelectValue placeholder="아니오"></SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="Y">예</SelectItem>
<SelectItem value="N">아니오</SelectItem>
</SelectContent>
</Select>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 변환컬럼명</TableHead>
<TableCell>
<FormField
control={form.control}
name="trsf_col_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.trsf_col_nm && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.trsf_col_nm.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 변환컬럼 한글명</TableHead>
<TableCell>
<FormField
control={form.control}
name="trsf_col_korn_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.trsf_col_korn_nm && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.trsf_col_korn_nm.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 변환컬럼 데이터 형식</TableHead>
<TableCell>
<FormField
control={form.control}
name="trsf_col_data_frm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
/>
</FormControl>
{form.formState.errors.trsf_col_data_frm && (
<p className="text-red-500 text-base pt-2">
{form.formState.errors.trsf_col_data_frm.message}
</p>
)}
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>변환컬럼 크기</TableHead>
<TableCell>
<FormField
control={form.control}
name="trsf_col_sz"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
type="number"
min={0}
max={99999999999999}
onChange={(e) => {
const onlyDigits = e.target.value.replace(/\D/g, "").slice(0, 14);
field.onChange(onlyDigits); // react-hook-form에 반영
}}
/>
</FormControl>
<p className="text-gray-500 text-base pt-2">
※ 14자리까지 입력 가능합니다.
</p>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>컬럼 매칭 순서</TableHead>
<TableCell>
<FormField
control={form.control}
name="col_seq"
render={({ field }) => (
<FormItem>
<div className="flex items-center gap-x-2 mb-4">
<Checkbox id="useColSeq" className="!border-gray-600" checked={!useColSeq} onCheckedChange={(check) => handleCheckColSeqValue(check)} />
<label htmlFor="useColSeq" className="text-gray-600">사용안함</label>
</div>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
autoComplete="off"
type="number"
min={0}
disabled={!useColSeq}
max={999}
onChange={(e) => {
const onlyDigits = e.target.value.replace(/\D/g, "").slice(0, 3);
field.onChange(onlyDigits); // react-hook-form에 반영
}}
/>
</FormControl>
<p className="text-gray-500 text-base pt-2">
※ 3자리까지 입력 가능합니다.
</p>
</FormItem>
)}
/>
</TableCell>
</TableRow>
{isModifyMode &&
<>
<TableRow>
<TableHead>수정자</TableHead>
<TableCell>
<FormField
control={form.control}
name="mdfr"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableHead>수정일시</TableHead>
<TableCell>
<FormField
control={form.control}
name="mdfcn_dt"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ? dayjs(field.value).format('YYYY-MM-DD') : ""}
className="!text-[1.3rem]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
</TableCell>
</TableRow>
</>
}
</TableBody>
</Table>
</div>
<DialogFooter>
<Button type="submit">저장</Button>
<DialogClose asChild>
<Button color="white">취소</Button>
</DialogClose>
</DialogFooter>
</form>
</Form>
<ConfirmDialog isOpen={onConfirm} />
</DialogContent>
</Dialog>
)
}
export { LinkTableDialog };
@@ -0,0 +1,710 @@
'use client';
import { useState, useMemo } from "react";
import {
Button,
DataTable,
Input,
Label,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
LoadingWithAnimation,
} from "@common/components";
import { getCoreRowModel, type PaginationState, type RowSelectionState, useReactTable } from "@tanstack/react-table";
import { LinkApi, type Link, type LinkSearchParam, type LinkTable, type LinkTableColumns, type LinkTableColData, type LinkTableFormData, LinkTableColumnsSchema, LinkTableSchema } from "@/entities/link";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { columns } from "../../linkParams/model/table-columns";
import { tableColumns } from "../model/table-columns";
import { LinkTableDialog } from "./link-table-dialog";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { getUserInfo } from "../../../../../../packages/common/components/src/api";
import { AUTH_USER_ID } from "@/shared/config";
import { getCookie } from "@common/components";
import { useAlertStore } from "@/shared/lib/use-alert-store";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { FormItem, FormControl, FormField, Form } from "@/shared/ui/form";
import { useDataTable } from "@/shared/lib";
function LinkTablePage() {
const queryClient = useQueryClient();
const userUniqId = getCookie(AUTH_USER_ID) ?? "";
const [linkSn, setLinkSn] = useState<string>('');
const [linkNm, setLinkNm] = useState<string>('');
const [linkSearchParam, setLinkSearchParam] = useState<LinkSearchParam>({
linkSn: '',
linkNm: ''
});
const [selectedTableInfo, setSelectedTableInfo] = useState<LinkTable | null>(null);
const [tableColList, setTableColList] = useState<LinkTableColumns[]>([]);
const [dialogOpen, setDialogOpen] = useState<boolean>(false);
const [selectedColIds, setSelectedColIds] = useState<string[]>([]);
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 100,
});
const { setMessage: alert } = useAlertStore((state) => state);
const { confirm } = useConfirm();
const [onConfirm, setOnConfirm] = useState<boolean>(false);
const handleConfirm = async (callback: () => Promise<void>) => {
setOnConfirm(true);
await callback();
setOnConfirm(false);
};
const query = useQuery({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkList`, linkSearchParam],
queryFn: () => LinkApi.getLinkList({
...linkSearchParam,
page: pagination.pageIndex,
size: pagination.pageSize,
}),
});
const { mutateAsync: insertLinkTableCol } = useMutation({
mutationFn: async (data: LinkTableColData) => await LinkApi.insertLinkTableCol({
...data,
mdfr: userUniqId,
}),
onSuccess: async () => {
if (selectedTableInfo) {
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableInfo`]
});
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableColList`]
});
const tableData = await LinkApi.getLinkTableInfo(selectedTableInfo.link_sn);
const tableColList = await LinkApi.getLinkTableColList(selectedTableInfo.link_sn);
setSelectedTableInfo(tableData);
setTableColList(tableColList.content);
setSelectedColIds([]);
setDialogOpen(false);
alert('저장되었습니다.');
}
}
});
const { mutateAsync: updateLinkTableCol } = useMutation({
mutationFn: async (data: LinkTableColData) => await LinkApi.updateLinkTableCol({
...data,
mdfr: userUniqId,
}),
onSuccess: async () => {
if (selectedTableInfo) {
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableInfo`]
});
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableColList`]
});
const tableData = await LinkApi.getLinkTableInfo(selectedTableInfo.link_sn);
const tableColList = await LinkApi.getLinkTableColList(selectedTableInfo.link_sn);
setSelectedTableInfo(tableData);
setTableColList(tableColList.content);
setSelectedColIds([]);
setDialogOpen(false);
alert('수정되었습니다.');
}
}
});
const { mutateAsync: deleteLinkTableCol } = useMutation({
mutationFn: async (data: string[]) => await LinkApi.deleteLinkTableCol(data),
onSuccess: async () => {
if (selectedTableInfo) {
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableInfo`]
});
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableColList`]
});
const tableData = await LinkApi.getLinkTableInfo(selectedTableInfo.link_sn);
const tableColList = await LinkApi.getLinkTableColList(selectedTableInfo.link_sn);
setSelectedTableInfo(tableData);
setTableColList(tableColList.content);
setSelectedColIds([]);
setDialogOpen(false);
alert('삭제되었습니다.');
}
}
});
const { mutateAsync: insertLinkTableInfo } = useMutation({
mutationFn: async (data: LinkTableFormData) => await LinkApi.insertLinkTableInfo(data),
onSuccess: async () => {
if (selectedTableInfo) {
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableInfo`]
});
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableColList`]
});
const tableData = await LinkApi.getLinkTableInfo(selectedTableInfo.link_sn);
const tableColList = await LinkApi.getLinkTableColList(selectedTableInfo.link_sn);
tableForm.reset({
link_sn: tableData.link_sn,
link_nm: tableData.link_nm,
tbl_sn: tableData.tbl_sn ?? "",
sou_tbl_nm: tableData.sou_tbl_nm ?? "",
sou_tbl_korn_nm: tableData.sou_tbl_korn_nm ?? "",
sou_tbl_expln: tableData.sou_tbl_expln ?? "",
trsf_tbl_expln: tableData.trsf_tbl_expln ?? "",
trsf_tbl_nm: tableData.trsf_tbl_nm ?? "",
trsf_tbl_korn_nm: tableData.trsf_tbl_korn_nm ?? "",
});
setSelectedTableInfo(tableData);
setTableColList(tableColList.content);
setSelectedColIds([]);
alert('저장되었습니다.');
}
}
});
const { mutateAsync: updateLinkTableInfo } = useMutation({
mutationFn: async (data: LinkTableFormData) => await LinkApi.updateLinkTableInfo(data),
onSuccess: async () => {
if (selectedTableInfo) {
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableInfo`]
});
await queryClient.invalidateQueries({
queryKey: [`${process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST}/getLinkTableColList`]
});
const tableData = await LinkApi.getLinkTableInfo(selectedTableInfo.link_sn);
const tableColList = await LinkApi.getLinkTableColList(selectedTableInfo.link_sn);
setSelectedTableInfo(tableData);
setTableColList(tableColList.content);
setSelectedColIds([]);
alert('수정되었습니다.');
}
}
});
const tableCol = useMemo(
() =>
tableColumns({ selectedColIds, setSelectedColIds }),
[selectedColIds]
);
const colTable = useReactTable({
data: tableColList,
columns: tableCol,
getCoreRowModel: getCoreRowModel(),
});
const form = useForm<LinkTableColData>({
resolver: zodResolver(LinkTableColumnsSchema),
defaultValues: {
pk_yn: "N"
}
});
const tableForm = useForm<LinkTableFormData>({
resolver: zodResolver(LinkTableSchema),
defaultValues: {},
});
const handleResetSearchParam = async () => {
setSelectedTableInfo(null);
setTableColList([]);
setLinkSn('');
setLinkNm('');
setLinkSearchParam({
...linkSearchParam,
linkSn: '',
linkNm: '',
});
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setSelectedTableInfo(null);
setTableColList([]);
setLinkSearchParam({
...linkSearchParam,
linkSn,
linkNm
});
};
const handleRowClick = async (data: Link) => {
const tableData = await LinkApi.getLinkTableInfo(data.link_sn);
const tableColList = await LinkApi.getLinkTableColList(data.link_sn);
setSelectedTableInfo(tableData);
setTableColList(tableColList.content);
setSelectedColIds([]);
tableForm.reset({
link_sn: tableData.link_sn,
link_nm: tableData.link_nm,
tbl_sn: tableData.tbl_sn ?? "",
sou_tbl_nm: tableData.sou_tbl_nm ?? "",
sou_tbl_korn_nm: tableData.sou_tbl_korn_nm ?? "",
sou_tbl_expln: tableData.sou_tbl_expln ?? "",
trsf_tbl_expln: tableData.trsf_tbl_expln ?? "",
trsf_tbl_nm: tableData.trsf_tbl_nm ?? "",
trsf_tbl_korn_nm: tableData.trsf_tbl_korn_nm ?? "",
});
};
const handleColumnRowClick = async (data: LinkTableColumns) => {
const colInfo = await LinkApi.getLinkTableColInfo({ colSn: data.col_sn, tblSn: data.tbl_sn });
if (colInfo) {
let newData = { ...colInfo };
if (colInfo.mdfr) {
const userName = await fetchUserInfo();
newData = {
...colInfo,
mdfr: userName,
};
}
form.reset(newData);
}
setDialogOpen(true)
};
const fetchUserInfo = async () => {
const userData = await getUserInfo();
return userData.userName;
};
const handleDeleteParam = async () => {
if (selectedColIds.length === 0) {
alert('삭제할 컬럼을 선택해 주세요.');
} else {
await handleConfirm(async () => {
if (await confirm('선택한 컬럼 정보를 삭제하시겠습니까?')) {
deleteLinkTableCol(selectedColIds);
}
});
}
};
const handleTableSubmit = async (data: LinkTableFormData) => {
const regTblInfo = await LinkApi.countLinkTblNm(data.trsf_tbl_nm);
const confirmMsg = (regTblInfo.count > 0 && data.trsf_tbl_nm !== selectedTableInfo?.trsf_tbl_nm) ? `이미 사용중인 테이블 명입니다. 해당 테이블 명으로 ${!data.tbl_sn ? '저장' : '수정'}하시겠습니까?` : `${!data.tbl_sn ? '저장' : '수정'}하시겠습니까?`;
if (!data.tbl_sn) {
await handleConfirm(async () => {
if (await confirm(confirmMsg)) {
insertLinkTableInfo({
...data,
mdfr: userUniqId,
tbl_sn: (regTblInfo.count > 0) ? regTblInfo.tbl_sn : "",
});
}
});
} else {
await handleConfirm(async () => {
if (await confirm(confirmMsg)) {
updateLinkTableInfo({
...data,
tbl_sn: (regTblInfo.count > 0) ? regTblInfo.tbl_sn : "",
mdfr: userUniqId,
});
}
});
}
};
const { tableComponent } = useDataTable({
query,
tableOptions: {
columns,
state: {
pagination,
rowSelection,
},
manualPagination: true,
enableMultiRowSelection: true,
getCoreRowModel: getCoreRowModel(),
onPaginationChange: setPagination,
onRowSelectionChange: setRowSelection,
},
dataTableOptions: {
onRowClick: handleRowClick,
viewPagination: true,
},
});
return (
<div className="card card-border !mt-6">
<div className="card card-border">
<form className="flex items-center gap-2 p-2" onSubmit={handleSubmit}>
<Label htmlFor="liSnSearchInput" className="mr-2 text-label">
일련번호
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem] mr-4"
id="liSnSearchInput"
value={linkSn}
onChange={(e) => setLinkSn(e.target.value)}
autoComplete="off"
/>
<Label htmlFor="liNmSearchInput" className="mr-2 text-label">
연계 명
</Label>
<Input
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem] mr-2"
id="liNmSearchInput"
value={linkNm}
onChange={(e) => setLinkNm(e.target.value)}
autoComplete="off"
/>
<Button color="green" className="h-[3.2rem]" type="button" onClick={handleResetSearchParam}>
초기화
</Button>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
</form>
</div>
<div className="card !mb-0 flex h-[calc(100vh-28rem)] gap-5 !p-0">
<div className="card card-border w-1/2 !mx-0 flex flex-col">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">연계 목록</h3>
</div>
<div className="card !m-[1.2rem] overflow-auto !p-0 h-full">
{!query.isLoading ?
<div>{tableComponent}</div>
:
<div className="[data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center h-full">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
}
</div>
</div>
<div className="card card-border w-1/2 !mx-0 flex flex-col">
<div className="card-header">
<h3 className="text-2xl font-medium text-label">연계 테이블 정보</h3>
</div>
<div className="card !m-[1.2rem] !p-0 h-full overflow-auto flex flex-col">
<Form {...tableForm}>
<form onSubmit={tableForm.handleSubmit(handleTableSubmit)}>
{selectedTableInfo &&
<div className="flex justify-end mb-2">
<Button className="h-[3.2rem]" type="submit" color={selectedTableInfo.tbl_sn ? "green" : "primary"}>
{selectedTableInfo.tbl_sn ? "수정" : "저장"}
</Button>
</div>
}
<Table variant="secondary" className="flex-none">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<TableBody>
<TableRow>
<TableHead>연계 일련번호</TableHead>
<TableCell className="!p-2">
{selectedTableInfo ?
<FormField
control={tableForm.control}
name="link_sn"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem] w-[400px]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
:
<span className="px-2 py-[1.2rem]">-</span>
}
</TableCell>
</TableRow>
<TableRow>
<TableHead>연계 명</TableHead>
<TableCell className="!p-2">
{selectedTableInfo ?
<FormField
control={tableForm.control}
name="link_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem] w-[400px]"
disabled
/>
</FormControl>
</FormItem>
)}
/>
:
<span className="px-2 py-[1.2rem]">-</span>
}
</TableCell>
</TableRow>
<TableRow>
<TableHead>원천 테이블 명</TableHead>
<TableCell className="!p-2">
{selectedTableInfo ?
<FormField
control={tableForm.control}
name="sou_tbl_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem] w-[400px]"
placeholder={!field.value ? "-" : ""}
autoComplete="off"
/>
</FormControl>
{tableForm.formState.errors.sou_tbl_nm && (
<p className="text-red-500 text-base pt-2">
{tableForm.formState.errors.sou_tbl_nm.message}
</p>
)}
</FormItem>
)}
/>
:
<span className="px-2 py-[1.2rem]">-</span>
}
</TableCell>
</TableRow>
<TableRow>
<TableHead>원천 테이블 한글명</TableHead>
<TableCell className="!p-2">
{selectedTableInfo ?
<FormField
control={tableForm.control}
name="sou_tbl_korn_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem] w-[400px]"
placeholder={!field.value ? "-" : ""}
autoComplete="off"
/>
</FormControl>
{tableForm.formState.errors.sou_tbl_korn_nm && (
<p className="text-red-500 text-base pt-2">
{tableForm.formState.errors.sou_tbl_korn_nm.message}
</p>
)}
</FormItem>
)}
/>
:
<span className="px-2 py-[1.2rem]">-</span>
}
</TableCell>
</TableRow>
<TableRow>
<TableHead>원천 테이블 설명</TableHead>
<TableCell className="!p-2">
{selectedTableInfo ?
<FormField
control={tableForm.control}
name="sou_tbl_expln"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem] w-[400px]"
placeholder={!field.value ? "-" : ""}
autoComplete="off"
/>
</FormControl>
{tableForm.formState.errors.sou_tbl_expln && (
<p className="text-red-500 text-base pt-2">
{tableForm.formState.errors.sou_tbl_expln.message}
</p>
)}
</FormItem>
)}
/>
:
<span className="px-2 py-[1.2rem]">-</span>
}
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 변환 테이블 명</TableHead>
<TableCell className="!p-2">
{selectedTableInfo ?
<FormField
control={tableForm.control}
name="trsf_tbl_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem] w-[400px]"
placeholder={!field.value ? "-" : ""}
autoComplete="off"
/>
</FormControl>
{tableForm.formState.errors.trsf_tbl_nm && (
<p className="text-red-500 text-base pt-2">
{tableForm.formState.errors.trsf_tbl_nm.message}
</p>
)}
</FormItem>
)}
/>
:
<span className="px-2 py-[1.2rem]">-</span>
}
</TableCell>
</TableRow>
<TableRow>
<TableHead>* 변환 테이블 한글명</TableHead>
<TableCell className="!p-2">
{selectedTableInfo ?
<FormField
control={tableForm.control}
name="trsf_tbl_korn_nm"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem] w-[400px]"
placeholder={!field.value ? "-" : ""}
autoComplete="off"
/>
</FormControl>
{tableForm.formState.errors.trsf_tbl_korn_nm && (
<p className="text-red-500 text-base pt-2">
{tableForm.formState.errors.trsf_tbl_korn_nm.message}
</p>
)}
</FormItem>
)}
/>
:
<span className="px-2 py-[1.2rem]">-</span>
}
</TableCell>
</TableRow>
<TableRow>
<TableHead>변환 테이블 설명</TableHead>
<TableCell className="!p-2">
{selectedTableInfo ?
<FormField
control={tableForm.control}
name="trsf_tbl_expln"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
{...field}
value={field.value ?? ""}
className="!text-[1.3rem] w-[400px]"
placeholder={!field.value ? "-" : ""}
autoComplete="off"
/>
</FormControl>
{tableForm.formState.errors.trsf_tbl_expln && (
<p className="text-red-500 text-base pt-2">
{tableForm.formState.errors.trsf_tbl_expln.message}
</p>
)}
</FormItem>
)}
/>
:
<span className="px-2 py-[1.2rem]">-</span>
}
</TableCell>
</TableRow>
</TableBody>
</Table>
</form>
</Form>
{selectedTableInfo ?
<>
<div className="mb-2 mt-14 flex justify-end items-center flex-none">
{tableColList.length > 0 &&
<Button color="red" className="h-[3.2rem] mr-2" type="button" onClick={handleDeleteParam}>
행 삭제
</Button>
}
{selectedTableInfo.tbl_sn &&
<LinkTableDialog dialogOpen={dialogOpen} onOpenChange={setDialogOpen} form={form} tableInfo={selectedTableInfo} insertLinkTableCol={insertLinkTableCol} updateLinkTableCol={updateLinkTableCol} />
}
</div>
{selectedTableInfo.tbl_sn ?
(tableColList.length > 0 ?
<div className="flex-1 overflow-auto min-h-[300px]">
<DataTable table={colTable} onRowClick={handleColumnRowClick} />
</div>
:
<div className="flex items-center justify-center h-20 text-gray-500 text-3xl">
등록된 테이블 컬럼이 없습니다.
</div>)
:
<div className="flex items-center justify-center h-20 text-gray-500 text-3xl">
테이블 정보를 등록해주세요.
</div>
}
</>
:
<div className="flex items-center justify-center text-gray-500 text-3xl mt-14 flex-1">
연계 데이터를 선택해주세요.
</div>
}
</div>
</div>
</div>
<ConfirmDialog isOpen={onConfirm} />
</div >
)
};
export { LinkTablePage };
+10 -16
View File
@@ -7,7 +7,6 @@ import { getCoreRowModel, type PaginationState } from "@tanstack/react-table";
import {
Button,
Input,
InputDatePicker,
Label,
Select,
SelectContent,
@@ -16,10 +15,11 @@ import {
SelectValue,
LoadingWithImage,
} from "@common/components";
import { columns } from "@/pages/loginlog/model/table-columns";
import { LoginlogApi, type LoginlogParams } from "@/entities/loginlog";
import { useDataTable } from "@/shared/lib";
import { ENDPOINT } from "@/shared/config";
import { columns } from "@/pages/loginlog/model/table-columns";
import { InputDateRangePicker } from "@/shared/ui/input-date-range-picker";
type DateRange = {
from?: Date | undefined;
@@ -141,6 +141,11 @@ function LoginlogPage() {
setDateRange(presetDateRange || defaultDateRange);
};
const handleDateRangeChange = (dateRange: DateRange) => {
setDateRange(dateRange);
setPresetDateRange("");
};
return (
<div className="flex-1">
<div className="card card-border">
@@ -156,20 +161,9 @@ function LoginlogPage() {
<SelectItem value="3M">3개월</SelectItem>
</SelectContent>
</Select>
<InputDatePicker
value={dateRange.from}
onChange={(date) => {
setDateRange({ ...dateRange, from: date });
setPresetDateRange("");
}}
/>
~
<InputDatePicker
value={dateRange.to}
onChange={(date) => {
setDateRange({ ...dateRange, to: date });
setPresetDateRange("");
}}
<InputDateRangePicker
dateRange={dateRange}
setDateRange={handleDateRangeChange}
/>
<Label className="ml-4 mr-2 text-label">사용자ID</Label>
<Input
@@ -7,7 +7,6 @@ import { getCoreRowModel, type PaginationState } from "@tanstack/react-table";
import {
Button,
Input,
InputDatePicker,
Label,
Select,
SelectContent,
@@ -15,13 +14,14 @@ import {
SelectTrigger,
SelectValue,
} from "@common/components";
import { columns } from "@/pages/privacylog/model/table-columns";
import {
PrivacyLogPrivacy,
type PrivacyLogParams,
} from "@/entities/privacylog";
import { useDataTable } from "@/shared/lib";
import { ENDPOINT } from "@/shared/config";
import { columns } from "@/pages/privacylog/model/table-columns";
import { InputDateRangePicker } from "@/shared/ui/input-date-range-picker";
type DateRange = {
from?: Date | undefined;
@@ -132,6 +132,11 @@ function PrivacyLogPage() {
setDateRange(presetDateRange || defaultDateRange);
};
const handleDateRangeChange = (dateRange: DateRange) => {
setDateRange(dateRange);
setPresetDateRange("");
};
return (
<div className="flex-1">
<div className="card card-border">
@@ -147,20 +152,9 @@ function PrivacyLogPage() {
<SelectItem value="3M">3개월</SelectItem>
</SelectContent>
</Select>
<InputDatePicker
value={dateRange.from}
onChange={(date) => {
setDateRange({ ...dateRange, from: date });
setPresetDateRange("");
}}
/>
~
<InputDatePicker
value={dateRange.to}
onChange={(date) => {
setDateRange({ ...dateRange, to: date });
setPresetDateRange("");
}}
<InputDateRangePicker
dateRange={dateRange}
setDateRange={handleDateRangeChange}
/>
<Label className="ml-4 mr-2 text-label">조회정보</Label>
<Input
+16 -19
View File
@@ -13,7 +13,6 @@ import {
import {
Button,
Input,
InputDatePicker,
Label,
Select,
SelectContent,
@@ -31,8 +30,9 @@ import {
} from "@/entities/post";
import { BoardApi } from "@/entities/board";
import { AuthorityButton } from "@/entities/menu-authority";
import { useAlertStore, useSelectPrompt, useDataTable } from "@/shared/lib";
import { ENDPOINT } from "@/shared/config";
import { InputDateRangePicker } from "@/shared/ui/input-date-range-picker";
import { useAlertStore, useSelectPrompt, useDataTable } from "@/shared/lib";
import { columns } from "../model/table-columns";
import { MovePostDialog } from "./move-post-dialog";
@@ -58,7 +58,7 @@ function RecentPage() {
});
const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
const [presetDateRange, setPresetDateRange] = useState("");
const [dateRange, setDateRange] = useState<DateRange | undefined>({
const [dateRange, setDateRange] = useState<DateRange>({
from: undefined,
to: undefined,
});
@@ -169,7 +169,7 @@ function RecentPage() {
};
const handlePresetDateRange = (value: string) => {
let presetDateRange: DateRange | undefined;
let presetDateRange: DateRange;
switch (value) {
case "1W":
presetDateRange = {
@@ -190,12 +190,20 @@ function RecentPage() {
};
break;
default:
presetDateRange = undefined;
presetDateRange = {
from: undefined,
to: undefined,
};
}
setPresetDateRange(value);
setDateRange(presetDateRange);
};
const handleDateRangeChange = (dateRange: DateRange) => {
setDateRange(dateRange);
setPresetDateRange("");
};
const onSoftDeletePost = async () => {
const { resolved, value: delRsn } =
await prompt("삭제 사유를 입력해주세요.");
@@ -260,20 +268,9 @@ function RecentPage() {
<SelectItem value="3M">3개월</SelectItem>
</SelectContent>
</Select>
<InputDatePicker
value={dateRange?.from}
onChange={(date) => {
setDateRange({ ...dateRange, from: date });
setPresetDateRange("");
}}
/>
~
<InputDatePicker
value={dateRange?.to}
onChange={(date) => {
setDateRange({ ...dateRange, to: date });
setPresetDateRange("");
}}
<InputDateRangePicker
dateRange={dateRange}
setDateRange={handleDateRangeChange}
/>
<Label className="ml-4 mr-2 text-label">게시판</Label>
<Select
@@ -0,0 +1 @@
export { UserStatisticsApi } from "./user-statistics-service";
@@ -0,0 +1,138 @@
import {
type AccessLog,
type AccessLogParams,
type AccessLogService,
type PageableList,
} from "../model/user-statistics-interface";
// 목 데이터
const mockAccessLogs: AccessLog[] = [
{
no: 1,
accessTime: "2024-01-15 14:30:25",
accessIp: "192.168.1.100",
accessRegion: "서울특별시",
urlPath: "/index",
browser: "Chrome",
site: "SITE1",
accessType: "메인",
},
{
no: 2,
accessTime: "2024-01-15 14:28:15",
accessIp: "203.241.50.123",
accessRegion: "부산광역시",
urlPath: "/board/list",
browser: "Edge",
site: "SITE2",
accessType: "게시판",
},
{
no: 3,
accessTime: "2024-01-15 14:25:42",
accessIp: "175.223.45.67",
accessRegion: "대구광역시",
urlPath: "/statistics",
browser: "Safari",
site: "SITE1",
accessType: "통계",
},
{
no: 4,
accessTime: "2024-01-15 14:22:18",
accessIp: "211.252.87.45",
accessRegion: "인천광역시",
urlPath: "/contents/view",
browser: "Firefox",
site: "SITE3",
accessType: "컨텐츠",
},
{
no: 5,
accessTime: "2024-01-15 14:20:33",
accessIp: "121.254.12.89",
accessRegion: "광주광역시",
urlPath: "/search",
browser: "Chrome",
site: "SITE1",
accessType: "검색",
},
];
// 목 API 서비스
class UserStatisticsApiImpl implements AccessLogService {
async getAccessLogList(
params: AccessLogParams,
): Promise<PageableList<AccessLog>> {
// 실제 API 호출 대신 목 데이터 반환
const { page = 0, size = 10 } = params;
// 필터링 로직 (실제로는 서버에서 처리)
let filteredLogs = [...mockAccessLogs];
if (params.urlPath) {
filteredLogs = filteredLogs.filter((log) =>
log.urlPath.toLowerCase().includes(params.urlPath!.toLowerCase()),
);
}
if (params.accessIp) {
filteredLogs = filteredLogs.filter((log) =>
log.accessIp.includes(params.accessIp!),
);
}
if (params.accessRegion) {
filteredLogs = filteredLogs.filter((log) =>
log.accessRegion.includes(params.accessRegion!),
);
}
if (params.browser) {
filteredLogs = filteredLogs.filter(
(log) => log.browser.toLowerCase() === params.browser!.toLowerCase(),
);
}
if (params.siteId) {
filteredLogs = filteredLogs.filter((log) => log.site === params.siteId);
}
// 페이지네이션
const start = page * size;
const end = start + size;
const paginatedLogs = filteredLogs.slice(start, end);
// 목 응답 생성
return {
content: paginatedLogs,
pageable: {
pageNumber: page,
pageSize: size,
sort: {
empty: true,
sorted: false,
unsorted: true,
},
offset: page * size,
paged: true,
unpaged: false,
},
last: (page + 1) * size >= filteredLogs.length,
totalPages: Math.ceil(filteredLogs.length / size),
totalElements: filteredLogs.length,
size,
number: page,
sort: {
empty: true,
sorted: false,
unsorted: true,
},
first: page === 0,
numberOfElements: paginatedLogs.length,
empty: paginatedLogs.length === 0,
};
}
}
export const UserStatisticsApi = new UserStatisticsApiImpl();
@@ -0,0 +1 @@
export { UserStatisticsPage } from "./ui/user-statistics-page";
@@ -0,0 +1,148 @@
import { type ChartData, type ChartOptions } from "chart.js";
// 일별 접속 현황 차트 데이터
export const monthlyStatisticsData = {
labels: [
"1일",
"2일",
"3일",
"4일",
"5일",
"6일",
"7일",
"8일",
"9일",
"10일",
"11일",
"12일",
"13일",
"14일",
"15일",
],
datasets: [
{
type: "bar" as const,
label: "페이지뷰",
data: [
850, 1000, 750, 750, 700, 750, 780, 800, 850, 900, 1200, 1700, 2300,
2100, 2600,
],
backgroundColor: "rgba(54, 162, 235, 0.8)",
order: 2,
},
{
type: "line" as const,
label: "신규 접속자",
data: [
700, 600, 500, 550, 500, 550, 500, 550, 600, 850, 1200, 1500, 1700,
2300, 2200,
],
borderColor: "rgba(255, 99, 132, 0.8)",
borderWidth: 2,
tension: 0.4,
pointRadius: 3,
order: 0,
},
{
type: "line" as const,
label: "총 접속자",
data: [
200, 300, 400, 500, 600, 500, 550, 500, 400, 500, 350, 800, 900, 1200,
1300,
],
borderColor: "rgba(75, 192, 192, 0.8)",
borderWidth: 2,
tension: 0.4,
pointRadius: 3,
order: 1,
},
],
};
export const monthlyStatisticsOptions: ChartOptions<"bar"> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: "top" as const,
},
tooltip: {
mode: "index" as const,
intersect: false,
},
},
};
// 사이트별 접속자 차트 데이터
export const siteVisitorsData: ChartData<"bar"> = {
labels: ["SITE1", "SITE2", "SITE3", "SITE4", "SITE5"],
datasets: [
{
label: "사이트별 접속자",
data: [2500, 2000, 1500, 1200, 800],
backgroundColor: [
"rgba(54, 162, 235, 0.8)",
"rgba(153, 102, 255, 0.8)",
"rgba(255, 99, 132, 0.8)",
"rgba(255, 159, 64, 0.8)",
"rgba(255, 205, 86, 0.8)",
],
borderWidth: 1,
},
],
};
export const siteVisitorsOptions: ChartOptions<"bar"> = {
responsive: true,
maintainAspectRatio: false,
indexAxis: "y" as const,
plugins: {
legend: {
display: false,
},
},
};
// 브라우저별 접속자 차트 데이터
export const browserStatisticsData: ChartData<"doughnut"> = {
labels: ["Chrome", "Edge", "Safari", "Firefox", "Internet Explorer"],
datasets: [
{
data: [45, 25, 15, 10, 5],
backgroundColor: [
"rgba(54, 162, 235, 0.8)",
"rgba(153, 102, 255, 0.8)",
"rgba(255, 99, 132, 0.8)",
"rgba(255, 159, 64, 0.8)",
"rgba(255, 205, 86, 0.8)",
],
borderColor: [
"rgba(54, 162, 235, 1)",
"rgba(153, 102, 255, 1)",
"rgba(255, 99, 132, 1)",
"rgba(255, 159, 64, 1)",
"rgba(255, 205, 86, 1)",
],
borderWidth: 1,
},
],
};
export const browserStatisticsOptions: ChartOptions<"doughnut"> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: "bottom" as const,
},
},
};
export const chartData = {
monthlyStatisticsData,
monthlyStatisticsOptions,
siteVisitorsData,
siteVisitorsOptions,
browserStatisticsData,
browserStatisticsOptions,
};
@@ -0,0 +1,39 @@
import { createColumnHelper } from "@tanstack/react-table";
import { type AccessLog } from "./user-statistics-interface";
const columnHelper = createColumnHelper<AccessLog>();
export const columns = [
columnHelper.accessor("no", {
header: "No",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("accessTime", {
header: "접속일시",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("accessIp", {
header: "접속IP",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("accessRegion", {
header: "접속지역",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("urlPath", {
header: "URL경로",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("browser", {
header: "브라우저",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("site", {
header: "사이트",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("accessType", {
header: "메뉴명",
cell: (info) => info.getValue(),
}),
];
@@ -0,0 +1,56 @@
export interface AccessLog {
no: number;
accessTime: string;
accessIp: string;
accessRegion: string;
urlPath: string;
browser: string;
site: string;
accessType: string;
}
export interface AccessLogParams {
page?: number;
size?: number;
urlPath?: string;
accessIp?: string;
accessRegion?: string;
browser?: string;
accessDateStart?: string;
accessDateEnd?: string;
siteId?: string;
sort?: string;
}
export interface AccessLogService {
getAccessLogList(params: AccessLogParams): Promise<PageableList<AccessLog>>;
}
export interface PageableList<T> {
content: T[];
pageable: {
pageNumber: number;
pageSize: number;
sort: {
empty: boolean;
sorted: boolean;
unsorted: boolean;
};
offset: number;
paged: boolean;
unpaged: boolean;
};
last: boolean;
totalPages: number;
totalElements: number;
size: number;
number: number;
sort: {
empty: boolean;
sorted: boolean;
unsorted: boolean;
};
first: boolean;
numberOfElements: number;
empty: boolean;
}
@@ -0,0 +1,324 @@
"use client";
import dayjs from "dayjs";
import { useState } from "react";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import { getCoreRowModel, type PaginationState } from "@tanstack/react-table";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
BarElement,
ArcElement,
Filler,
Legend,
Tooltip,
type ChartData,
} from "chart.js";
import { Bar, Doughnut } from "react-chartjs-2";
import {
Button,
Input,
Label,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@common/components";
import { SiteSelect } from "@/entities/site";
import { useDataTable } from "@/shared/lib";
import { InputDateRangePicker } from "@/shared/ui/input-date-range-picker";
import { UserStatisticsApi } from "../api";
import { chartData } from "../model/chart-data";
import { columns } from "../model/table-columns";
import { type AccessLogParams } from "../model/user-statistics-interface";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
BarElement,
ArcElement,
Filler,
Legend,
Tooltip,
);
type DateRange = {
from?: Date | undefined;
to?: Date | undefined;
};
function UserStatisticsPage() {
const defaultDateRange: DateRange = {
from: dayjs().subtract(7, "day").toDate(),
to: dayjs().toDate(),
};
const [pagination, setPagination] = useState<PaginationState>({
pageIndex: 0,
pageSize: 10,
});
const [keywordType, setKeywordType] = useState("");
const [keyword, setKeyword] = useState("");
const [presetDateRange, setPresetDateRange] = useState("1W");
const [dateRange, setDateRange] = useState<DateRange>(defaultDateRange);
const [searchParams, setSearchParams] = useState<AccessLogParams>({
urlPath: "",
accessIp: "",
accessRegion: "",
browser: "",
accessDateStart: dayjs().subtract(7, "day").format("YYYY-MM-DD"),
accessDateEnd: dayjs().format("YYYY-MM-DD"),
sort: "accessTime,desc",
});
const query = useQuery({
queryKey: ["user-statistics", searchParams, pagination],
queryFn: () =>
UserStatisticsApi.getAccessLogList({
...searchParams,
page: pagination.pageIndex,
size: pagination.pageSize,
}),
placeholderData: keepPreviousData,
});
const { tableComponent, tableInstance: table } = useDataTable({
query,
tableOptions: {
columns,
state: {
pagination,
},
manualPagination: true,
getCoreRowModel: getCoreRowModel(),
onPaginationChange: setPagination,
},
dataTableOptions: {
viewPagination: true,
},
});
const handlePresetDateRange = (value: string) => {
let presetDateRange: DateRange;
switch (value) {
case "1W":
presetDateRange = {
from: dayjs().subtract(7, "day").toDate(),
to: dayjs().toDate(),
};
break;
case "1M":
presetDateRange = {
from: dayjs().subtract(30, "day").toDate(),
to: dayjs().toDate(),
};
break;
case "3M":
presetDateRange = {
from: dayjs().subtract(90, "day").toDate(),
to: dayjs().toDate(),
};
break;
default:
presetDateRange = defaultDateRange;
}
setPresetDateRange(value);
setDateRange(presetDateRange);
};
const handleDateRangeChange = (dateRange: DateRange) => {
setDateRange(dateRange);
setPresetDateRange("");
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
setPagination({
...pagination,
pageIndex: 0,
});
// 검색 조건에 따라 검색 파라미터 설정
const params: AccessLogParams = {
sort: "accessTime,desc",
accessDateStart: dateRange.from
? dayjs(dateRange.from).format("YYYY-MM-DD")
: "",
accessDateEnd: dateRange.to
? dayjs(dateRange.to).format("YYYY-MM-DD")
: "",
};
// 검색어 타입에 따라 파라미터 설정
switch (keywordType) {
case "urlPath":
params.urlPath = keyword;
break;
case "ip":
params.accessIp = keyword;
break;
case "region":
params.accessRegion = keyword;
break;
case "browser":
params.browser = keyword;
break;
}
setSearchParams(params);
};
const handleReset = () => {
setKeywordType("");
setKeyword("");
setDateRange(defaultDateRange);
setPresetDateRange("1W");
setSearchParams({
urlPath: "",
accessIp: "",
accessRegion: "",
browser: "",
accessDateStart: dayjs().subtract(7, "day").format("YYYY-MM-DD"),
accessDateEnd: dayjs().format("YYYY-MM-DD"),
sort: "accessTime,desc",
});
};
return (
<div className="card card-border !mt-6">
<div className="card card-border">
<form onSubmit={handleSubmit} className="flex items-center gap-2 p-2">
<Label className="mr-2">날짜</Label>
<Select value={presetDateRange} onValueChange={handlePresetDateRange}>
<SelectTrigger className="w-[12rem]">
<SelectValue placeholder="기간 선택" className="w-[24rem]" />
</SelectTrigger>
<SelectContent>
<SelectItem value="1W">일주일</SelectItem>
<SelectItem value="1M">1개월</SelectItem>
<SelectItem value="3M">3개월</SelectItem>
</SelectContent>
</Select>
<InputDateRangePicker
dateRange={dateRange}
setDateRange={handleDateRangeChange}
/>
<Label className="ml-4 mr-2 text-label">사이트</Label>
<SiteSelect enabledAllSite className="w-[16rem]" />
<Label className="ml-4 mr-2 text-label">검색</Label>
<Select
value={keywordType}
onValueChange={(value) => setKeywordType(value)}
>
<SelectTrigger className="h-[3.2rem] w-[10rem]">
<SelectValue placeholder="선택" />
</SelectTrigger>
<SelectContent>
<SelectItem value="urlPath">URL경로</SelectItem>
<SelectItem value="ip">접속IP</SelectItem>
<SelectItem value="region">접속지역</SelectItem>
<SelectItem value="browser">브라우저</SelectItem>
</SelectContent>
</Select>
<Input
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
className="h-[3.2rem] w-[24rem] rounded-sm !text-[1.3rem]"
/>
<Button className="h-[3.2rem]" type="submit">
조회
</Button>
<Button
type="button"
color="white"
className="h-[3.2rem]"
onClick={handleReset}
>
초기화
</Button>
</form>
</div>
{/* 차트 영역 */}
<div className="grid grid-cols-2">
{/* 일별 접속 현황 */}
<div className="card card-border">
<div className="card-header">
<h3 className="text-xl font-medium">일별 접속 현황</h3>
</div>
<div className="h-96 p-4">
<Bar
data={chartData.monthlyStatisticsData as ChartData<"bar">}
options={chartData.monthlyStatisticsOptions}
/>
</div>
</div>
<div className="grid grid-cols-2">
{/* 사이트별 접속자 */}
<div className="card card-border">
<div className="card-header">
<h3 className="text-xl font-medium">사이트별 접속자</h3>
</div>
<div className="h-96 p-4">
<Bar
data={chartData.siteVisitorsData}
options={chartData.siteVisitorsOptions}
/>
</div>
</div>
{/* 브라우저별 접속자 */}
<div className="card card-border">
<div className="card-header">
<h3 className="text-xl font-medium">브라우저별 접속자</h3>
</div>
<div className="h-96 p-4">
<Doughnut
data={chartData.browserStatisticsData}
options={chartData.browserStatisticsOptions}
/>
</div>
</div>
</div>
</div>
{/* 접속 로그 상세 */}
<div className="card card-border">
<div className="card-header">
<div className="flex w-full items-center justify-between">
<h3 className="text-2xl font-medium text-label">접속 로그 상세</h3>
<div className="flex gap-2">
<Select
value={table.getState().pagination.pageSize.toString()}
onValueChange={(value) => {
table.setPageSize(parseInt(value));
}}
>
<SelectTrigger className="h-[3.2rem] w-[12rem]">
<SelectValue placeholder="페이지 크기" />
</SelectTrigger>
<SelectContent>
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={pageSize.toString()}>
{pageSize}개씩 보기
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="card !m-[1.2rem] !p-0">{tableComponent}</div>
</div>
</div>
);
}
export { UserStatisticsPage };
+20 -22
View File
@@ -9,7 +9,6 @@ import {
Button,
Checkbox,
Input,
InputDatePicker,
Label,
Select,
SelectContent,
@@ -25,6 +24,7 @@ import {
} from "@/entities/user";
import { ENDPOINT } from "@/shared/config";
import { useDataTable } from "@/shared/lib";
import { InputDateRangePicker } from "@/shared/ui/input-date-range-picker";
import { columns } from "../model/table-columns";
type DateRange = {
@@ -40,7 +40,7 @@ function UsersPage() {
pageSize: 10,
});
const [presetDateRange, setPresetDateRange] = useState("");
const [dateRange, setDateRange] = useState<DateRange | undefined>({
const [dateRange, setDateRange] = useState<DateRange>({
from: undefined,
to: undefined,
});
@@ -62,7 +62,7 @@ function UsersPage() {
});
const { data: userSttsStats } = useQuery({
queryKey: [ENDPOINT.USER_SERVICE.USERS],
queryKey: [ENDPOINT.USER_SERVICE.USERS, "userStatusStatistics"],
queryFn: () => UserApi.selectUserSttsStats(),
});
@@ -145,7 +145,7 @@ function UsersPage() {
};
const handlePresetDateRange = (value: string) => {
let presetDateRange: DateRange | undefined;
let presetDateRange: DateRange;
switch (value) {
case "1M":
presetDateRange = {
@@ -166,15 +166,24 @@ function UsersPage() {
};
break;
default:
presetDateRange = undefined;
presetDateRange = {
from: undefined,
to: undefined,
};
}
setPresetDateRange(value);
setDateRange(presetDateRange);
};
const getUserSttsStatsCnt = (code: string): number => {
if (!Array.isArray(userSttsStats)) return 0;
return userSttsStats.find((item) => item.sttsCd === code)?.cnt ?? 0;
const handleDateRangeChange = (dateRange: DateRange) => {
setDateRange(dateRange);
setPresetDateRange("");
};
const getUserSttsStatsCnt = (code: string): string => {
if (!Array.isArray(userSttsStats)) return "0";
const count = userSttsStats.find((item) => item.sttsCd === code)?.cnt ?? 0;
return count.toLocaleString();
};
const handleUserStateCodeChange = (code: string, checked: boolean) => {
@@ -292,20 +301,9 @@ function UsersPage() {
<SelectItem value="6M">6개월</SelectItem>
</SelectContent>
</Select>
<InputDatePicker
value={dateRange?.from}
onChange={(date) => {
setDateRange({ ...dateRange, from: date });
setPresetDateRange("");
}}
/>
~
<InputDatePicker
value={dateRange?.to}
onChange={(date) => {
setDateRange({ ...dateRange, to: date });
setPresetDateRange("");
}}
<InputDateRangePicker
dateRange={dateRange}
setDateRange={handleDateRangeChange}
/>
</div>
</div>
@@ -0,0 +1,47 @@
import { InputDatePicker } from "@common/components";
import { useEffect } from "react";
import { useAlertStore } from "../lib";
type DateRange = {
from?: Date;
to?: Date;
};
type InputDateRangePickerProps = {
dateRange: DateRange;
setDateRange: (dateRange: DateRange) => void;
};
function InputDateRangePicker({
dateRange,
setDateRange,
}: InputDateRangePickerProps) {
const alert = useAlertStore((state) => state.setMessage);
useEffect(() => {
if (dateRange.from && dateRange.to && dateRange.from > dateRange.to) {
alert("시작일보다 종료일이 커야 합니다.");
setDateRange({ ...dateRange, to: dateRange.from });
}
}, [dateRange]);
return (
<>
<InputDatePicker
value={dateRange.from}
onChange={(date) => {
setDateRange({ ...dateRange, from: date });
}}
/>
~
<InputDatePicker
value={dateRange.to}
onChange={(date) => {
setDateRange({ ...dateRange, to: date });
}}
/>
</>
);
}
export { InputDateRangePicker };
@@ -21,7 +21,7 @@ const InputSection: React.FC<InputSectionProps> = ({ title, data, sectionKey, on
<TableHeader>
<TableRow>
<TableHead className="border border-gray-300 px-2 py-2 text-sm w-auto whitespace-nowrap">구분</TableHead>
<TableHead className="border border-gray-300 px-2 py-2 text-sm w-[80px] whitespace-nowrap">년도</TableHead>
<TableHead className="border border-gray-300 px-2 py-2 text-sm w-[80px] whitespace-nowrap">진단연도</TableHead>
<TableHead className="border border-gray-300 px-2 py-2 text-sm w-auto whitespace-nowrap">사업명</TableHead>
<TableHead className="border border-gray-300 px-2 py-2 text-sm w-auto whitespace-nowrap">유형</TableHead>
</TableRow>
@@ -40,7 +40,7 @@ const InputSection: React.FC<InputSectionProps> = ({ title, data, sectionKey, on
className="w-full text-xl border-radius-0 px-3 py-2 text-base text-center leading-normal"
/>
</TableCell>
<TableCell className="border border-gray-300 px-2 py-2 text-sm text-center leading-normal w-auto whitespace-nowrap">
<TableCell className="border border-gray-300 px-2 py-2 text-sm text-center leading-normal w-auto">
{row.bizNm}
</TableCell>
<TableCell className="border border-gray-300 px-2 py-2 text-sm text-center leading-normal w-auto whitespace-nowrap">
@@ -22,7 +22,7 @@ type LayerContentMap = {
// 레이어 이름과 컴포넌트를 매핑
// 레이어 선택시 변경되는 팝업 컨텐츠 동적으로 변경하도록 작업
const layerContentMap: LayerContentMap = {
"하수처리시설": { component: SwtrmtFclt, },
// "하수처리시설": { component: SwtrmtFclt, }, // 디지털 자료관 연계정보가 없으니 일단 주석 처리
"하수처리구역": {},
"우수토실": { component: Ssc, },
"중점우수토실": { component: Ssc, }, // 중점우수토실 여부 설정
@@ -28,10 +28,11 @@ export const MsSwagePplCol = [
// { id: 'lyrTypeNm', title: '레이어타입명' },
]
export const MsSwagePplCol2 = [
{ id: 'rowNumber', title: '일련번호' },
{ id: 'fcltMngNo', title: '시설 관리번호' },
{ id: 'instMngNo', title: '기관 관리번호' },
{ id: 'instlYmd', title: '설치일자' },
{ id: 'mapshtNo', title: '도엽번호' },
// { id: 'mapshtNo', title: '도엽번호' },
{ id: 'pdmt', title: '관경(mm)' },
{ id: 'prlg', title: '연장(m)' },
{ id: 'avgGrdn', title: '평균구배(m/m)' },
@@ -296,10 +297,11 @@ export const SwtrmtFcltCol = [
// { id: 'obsrvnSptCd', title: '관측지점코드' },
];
export const SwtrmtFcltCol2 = [
{ id: 'rowNumber', title: '일련번호' },
{ id: 'swtrmtFcltNm', title: '하수처리시설명' },
{ id: 'fcltCpct', title: '시설용량(㎥/d)' },
{ id: 'rgnExpln', title: '지역설명' },
{ id: 'cmcnYmd', title: '준공일자' },
// { id: 'cmcnYmd', title: '준공일자' },
{ id: 'oprtngStrtYmd', title: '가동개시일자' },
// { id: 'clsgYmd', title: '폐쇄일자' },
// { id: 'prcsMsrcCd', title: '처리공법코드' },
@@ -319,7 +321,7 @@ export const SwtrmtFcltCol2 = [
// { id: 'pllnArea', title: '부지면적(m²)' },
// { id: 'mngRprtvBzentyNm', title: '관리대행업체명' },
{ id: 'swtrmtPpltnCnt', title: '하수처리인구수(인)' },
{ id: 'prcsZoneAreaSum', title: '처리구역면적합계(m²)' },
// { id: 'prcsZoneAreaSum', title: '처리구역면적합계(m²)' },
// { id: 'xcrd', title: 'X좌표' },
// { id: 'ycrd', title: 'Y좌표' },
// { id: 'oprtngSttsCd', title: '가동상태코드' },
@@ -346,6 +348,7 @@ export const SwtrmtPrcsZoneCol = [
{ id: 'swtrmt_fclt_nm', title: '하수처리시설명' },
];
export const SwtrmtPrcsZoneCol2 = [
{ id: 'rowNumber', title: '일련번호' },
// { id: 'swtrmtZoneSn', title: '하수처리구역 일련번호' },
{ id: 'swtrmtZoneNm', title: '하수처리구역명' },
// { id: 'swtrmt_fclt_cd', title: '하수처리시설코드' },
@@ -380,12 +383,13 @@ export const MsSwageMhlCol = [
// { id: 'inst_mng_no', title: '기관관리번호' }
];
export const MsSwageMhlCol2 = [
{ id: 'rowNumber', title: '일련번호' },
// { id: 'fid', title: 'FID' },
// { id: 'geom', title: 'geometry' },
// { id: 'ftreSmbolCd', title: '지형지물부호코드' },
{ id: 'fcltMngNo', title: '시설관리번호' },
// { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
{ id: 'mapshtNo', title: '도엽번호' },
// { id: 'mapshtNo', title: '도엽번호' },
// { id: 'mngInstCd', title: '관리기관코드' },
{ id: 'instlYmd', title: '설치일자' },
// { id: 'lastDrdgnYmd', title: '최종준설일자' },
@@ -487,12 +491,13 @@ export const ExclnSewagePumpCol = [
// { id: 'instMngNo', title: '기관관리번호' },
]
export const ExclnSewagePumpCol2 = [
{ id: 'rowNumber', title: '일련번호' },
// { id: 'fid', title: 'FID' },
// { id: 'geom', title: 'geometry' },
// { id: 'ftreSmbolCd', title: '지형지물부호코드' },
{ id: 'fcltMngNo', title: '시설관리번호' },
// { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
{ id: 'mapshtNo', title: '도엽번호' },
// { id: 'mapshtNo', title: '도엽번호' },
// { id: 'mngInstCd', title: '관리기관코드' },
{ id: 'instlYmd', title: '설치일자' },
{ id: 'swagePmstnNm', title: '하수펌프장명' },
@@ -528,6 +533,7 @@ export const DrtwSewagePumpCol = [
// { id: 'instMngNo', title: '기관관리번호' },
]
export const DrtwSewagePumpCol2 = [
{ id: 'rowNumber', title: '일련번호' },
// { id: 'fid', title: 'FID' },
// { id: 'geom', title: 'geometry' },
// { id: 'ftreSmbolCd', title: '지형지물부호코드' },
@@ -574,6 +580,7 @@ export const stofcbrCol = [
{ id: 'drtn_angl', title: '방향각도(°)' },
]
export const stofcbrCol2 = [
{ id: 'rowNumber', title: '일련번호' },
// { id: 'ftreSmbolCd', title: '지형지물부호코드' },
{ id: 'fcltMngNo', title: '시설관리번호' },
// { id: 'pbadmsEmdCd', title: '행정읍면동코드' },
@@ -650,7 +657,8 @@ export const dateFields = [
// 🎯 camelCase 버전 추가
'instlYmd', 'lastDrdgnYmd', 'cmcnYmd', 'oprtngStrtYmd', 'clsgYmd',
'mesureBeginDt', 'mesureEndDt', 'qltwtrBeginDt', 'qltwtrEndDt',
'rainBeginDt', 'rainEndDt'
'rainBeginDt', 'rainEndDt',
'flfmtBgngYmd', 'flfmtEndYmd', 'flfmtYr'
];
// 🎯 연월 필드들 (yyyymm -> yyyy년 m월)
@@ -677,5 +685,6 @@ export const numberFields = [
'worflwWallHgt',
'swrPplEqpAr', 'swrTrtPopl', 'weirHg', 'weirLt',
'precdngDry', 'rainFall', 'cntncTime', 'rainIn',
'mesureIntrvl', 'qltwtrCo', 'rnysnFvlc', 'clarFvlc'
'mesureIntrvl', 'qltwtrCo', 'rnysnFvlc', 'clarFvlc',
'bizAmt', 'count'
];
@@ -122,18 +122,6 @@ const MsSwagePpl = ({ featureData, onSaveClick }: { featureData: any, onSaveClic
}
};
// 변환 함수: 객체 → [{ year, type }]
// function convertToYearTypeArray(obj: any): { year: string, type: string }[] {
// if (!obj || typeof obj !== "object") return [];
// // 이미 배열이면 그대로 반환
// if (Array.isArray(obj)) return obj;
// // 객체의 각 key를 type, value를 year로 변환
// return Object.entries(obj).map(([type, year]) => ({
// year: String(year ?? ""),
// type: String(type ?? ""),
// }));
// }
return (
<>
@@ -1,5 +1,5 @@
import {useState, useEffect} from 'react';
import { getData, getDcData } from '@/components/lib/api';
import { getData } from '@/components/lib/api';
import moment from "moment";
export type TInftwtAnls = {
@@ -64,9 +64,19 @@ export type TOilqData = {
mtrngDt: string; // 계측일시
oilq: number; // 유량
}
export type TRainData = {
rainInfwtAnlsSn: number;
mtrngDt: string;
amrf: number; // 강우량
}
function roundTo(n: number, digits: number): number {
const factor = Math.pow(10, digits);
return Math.round(n * factor) / factor;
}
const getOptionsAplcnYm = (yyyymms: string[]): { text: string; val: string, hidden?: boolean }[] => {
const yyyymms1 = yyyymms.map(dateStr => {
const yyyymms1 : { text: string; val: string; hidden?: boolean }[] = yyyymms.map(dateStr => {
const year = dateStr.slice(0, 4);
const month = dateStr.slice(4, 6);
return {
@@ -104,7 +114,7 @@ export const useAplcnYms = (gubun:string) => {
return data;
};
export const getOptionsInftwtAnlsInfo = (anlsArr: TInftwtAnls[]): { text: string; val: number, hidden?: boolean }[] => {
const options = anlsArr.map(anls => ({
const options : { text: string; val: number; hidden?: boolean }[] = anlsArr.map(anls => ({
text: anls.anlsInfo,
val: anls.inftwtAnlsSn,
}));
@@ -112,7 +122,7 @@ export const getOptionsInftwtAnlsInfo = (anlsArr: TInftwtAnls[]): { text: string
return options;
};
export const selectInftwtAnls = async(aplcnYm:String) => { // 침입수분석
export const selectInftwtAnls = async(aplcnYm:string) => { // 침입수분석
try {
const queryString = aplcnYm ? `aplcnYmFrom=${aplcnYm}&aplcnYmTo=${aplcnYm}` : '';
const result = await getData(`v1/inftwtAnls${queryString ? `?${queryString}` : ''}`);
@@ -127,7 +137,7 @@ export const selectInftwtAnls = async(aplcnYm:String) => { // 침입수분석
export const getChartDataInftwtAnlsRslt = (arr: TInftwtAnlsRslt[]): { label: string; val: number }[] => {
const options = arr.map(anlsRslt => ({
label: moment(anlsRslt.anlsTm, "YYYYMMDDHHmmss").format("HH시"),
val: anlsRslt.predcOilq,
val: roundTo(anlsRslt.predcOilq, 2),
}));
return options;
};
@@ -149,7 +159,7 @@ export const selectInftwtAnlsRslt = async(inftwtAnlsSn:number, pplMngNo:string)
export const getChartDataOilq = (arr: TOilqData[]): { label: string; val: number }[] => {
const options = arr.map(anlsRslt => ({
label: anlsRslt.mtrngDt,
val: anlsRslt.oilq,
val: roundTo(anlsRslt.oilq, 2),
}));
return options;
};
@@ -203,7 +213,7 @@ export const selectPplRdiiQty = async(rainInfwtAnlsSn:number, pplMngNo:string) =
};
export const getOptionsRdiiAnlsInfo = (anlsArr: TRdiiAnls[]): { text: string; val: number, hidden?: boolean }[] => {
const options = anlsArr.map(anls => ({
const options : { text: string; val: number; hidden?: boolean }[] = anlsArr.map(anls => ({
text: anls.anlsInfo,
val: anls.rainInfwtAnlsSn,
}));
@@ -211,7 +221,7 @@ export const getOptionsRdiiAnlsInfo = (anlsArr: TRdiiAnls[]): { text: string; va
return options;
};
export const selectRdiiAnls = async(aplcnYm:String) => { // 침입수분석
export const selectRdiiAnls = async(aplcnYm:string) => { // 침입수분석
try {
const queryString = aplcnYm ? `aplcnYmFrom=${aplcnYm}&aplcnYmTo=${aplcnYm}` : '';
const result = await getData(`v1/rdiiAnls${queryString ? `?${queryString}` : ''}`);
@@ -223,21 +233,22 @@ export const selectRdiiAnls = async(aplcnYm:String) => { // 침입수분석
console.error(error);
}
};
export const getChartDataRdiiAnlsRslt = (arr: TRdiiAnlsRslt[]): { label: string; val: number }[] => {
export const getChartDataRdiiAnlsRslt = (arr: TRdiiAnlsRslt[]): { label: string; lineVal0: number, barVal0:number }[] => {
const options = arr.map(anlsRslt => ({
label: moment(anlsRslt.anlsTm, "YYYYMMDDHHmmss").format("MM-DD HH시"),
val: anlsRslt.predcOilq,
lineVal0: roundTo(anlsRslt.predcOilq, 2),
barVal0: 0
}));
return options;
};
export const getChartDataRdiiAnlsRsltMinq = (arr: TRdiiAnlsRslt[]): { label: string; val: number }[] => {
const options = arr.map(anlsRslt => ({
label: moment(anlsRslt.anlsTm, "YYYYMMDDHHmmss").format("MM-DD HH시"),
val: anlsRslt.minq,
val: roundTo(anlsRslt.minq, 2),
}));
return options;
};
export const selectRdiiAnlsRslt = async(rainInfwtAnlsSn:number, pplMngNo:string) => { // 침입수분석 결과
export const selectRdiiAnlsRslt = async(rainInfwtAnlsSn:number, pplMngNo:string) => { // RDII분석 결과
try {
if ((rainInfwtAnlsSn === undefined || rainInfwtAnlsSn === 0) || !pplMngNo) {
console.warn("RdiiAnlsSn or pplMngNo is not provided");
@@ -245,10 +256,32 @@ export const selectRdiiAnlsRslt = async(rainInfwtAnlsSn:number, pplMngNo:string)
}
const result = await getData(`v1/rdiiAnlsRslt/ppl/${rainInfwtAnlsSn}/${pplMngNo}`);
if (result && result.numberOfElements > 0) {
console.log("selectRdiiAnlsRslt", result.content);
return result.content;
}
} catch (error) {
console.error(error);
}
};
export const selectRainData = async(rainInfwtAnlsSn:number) => { // 강우데이터
try {
if ((rainInfwtAnlsSn === undefined || rainInfwtAnlsSn === 0)) {
console.warn("RdiiAnlsSn or pplMngNo is not provided");
return [];
}
const result = await getData(`v1/rdiiAnlsRslt/rainData/${rainInfwtAnlsSn}`);
if (result && result.numberOfElements > 0) {
console.log("selectRainData", result.content);
return result.content;
}
} catch (error) {
console.error(error);
}
};
export const getChartDataRainData = (arr: TRainData[]): { label: string; lineVal0: number, barVal0: number }[] => {
const options = arr.map(data => ({
label: moment(data.mtrngDt, "YYYY-MM-DD HH:mm:ss").format("MM-DD HH시"),
lineVal0: 0,
barVal0: roundTo(data.amrf,2),
}));
return options;
};
@@ -5,7 +5,7 @@ import { Button, Input, Label } from '@common/components';
import React, { useEffect, useState } from 'react';
import moment from "moment";
import type { TInftwtAnls, TOilqData } from './aplcnYms';
import type { TInftwtAnls } from './aplcnYms';
import * as fn from './aplcnYms';
import { useInfilChartModalStore } from '../chartModalStore'; // 모달 상태 관리 스토어
type ModalOpenProp = {
@@ -20,13 +20,13 @@ const InfilChart = ({ pplMngNo }: ModalOpenProp) => {
const [popupPosition, setPopupPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 }); // 팝업 위치
const [selectedAplcnYm, setSelectedAplcnYm] = useState("");
const [inftwtAnlss, setInftwtAnlss] = useState<TInftwtAnls[]>([]);
const [inftwtAnlsInfos, setInftwtAnlsInfos] = useState<any[]>([{ val: 0, text: '선택' }]); // 침입수분석정보 options
const [inftwtAnlsInfos, setInftwtAnlsInfos] = useState<{ text: string; val: number; hidden?: boolean }[]>([{ val: 0, text: '선택' }]); // 침입수분석정보 options
const [inftwtAnls, setInftwtAnls] = useState<TInftwtAnls | null>(null); // 침입수분석정보
const [selectedInftwtAnls, setSelectedInftwtAnls] = useState<number>(0); // 침입수분석 정보 선택시 사용
const [chartData, setChartData] = useState<{ chartData1: DataType[]; chartData2: DataType[] }>({
chartData1: [], chartData2: [],
});
const [inftwtQty, setInftwtQty] = useState<number>(0); // 침입수량
const [inftwtQty, setInftwtQty] = useState<string>("0"); // 침입수량
const aplcnYms = fn.useAplcnYms('inftwtAnlsRslt'); // 상수사용월 데이터 가져오기
pplMngNo = "L" + pplMngNo; // inp파일에 하수관로와 맨홀의 번호가 같으면 분석 오류가 발행하여
@@ -56,7 +56,7 @@ const InfilChart = ({ pplMngNo }: ModalOpenProp) => {
setInftwtAnls(null); // 침입수분석정보 초기화
setSelectedInftwtAnls(0); // 침입수분석 일련번호 초기화
setChartData({ chartData1: [], chartData2: [], }); // 차트 데이터 초기화
setInftwtQty(0); // 침입수량 초기화
setInftwtQty("0"); // 침입수량 초기화
}
}, [isModalOpen]);
@@ -133,7 +133,7 @@ const InfilChart = ({ pplMngNo }: ModalOpenProp) => {
});
fn.selectPplInftwtQty(selectedInftwtAnls, pplMngNo).then((data) => {// 침입수량 조회
if (data > 0) {
setInftwtQty(data);
setInftwtQty(data.toLocaleString('ko-KR'));
}
});
setPopupOpen(false);
@@ -5,13 +5,20 @@ import { Button, Input, Label } from '@common/components';
import React, { useEffect, useState } from 'react';
import moment from "moment";
import type { TRdiiAnls, TRdiiAnlsRslt, TOilqData } from './aplcnYms';
import type { TRdiiAnls } from './aplcnYms';
import * as fn from './aplcnYms';
import { useRdiiChartModalStore } from '../chartModalStore'; // 모달 상태 관리 스토어
type ModalOpenProp = {
pplMngNo: string, // 관로관리번호
}
type DataType = {label: string; val: number};
// 차트
type lineBarChartData = {
label : string;
lineVal0 : number;
barVal0 : number;
}
const RdiiChart = ({ pplMngNo }: ModalOpenProp) => {
const { isOpen: isModalOpen, setIsOpen: setIsModalOpen } = useRdiiChartModalStore(); // 모달 상태 관리 스토어
@@ -20,17 +27,16 @@ const RdiiChart = ({ pplMngNo }: ModalOpenProp) => {
const [popupPosition, setPopupPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 }); // 팝업 위치
const [aplcnYm, setAplcnYm] = useState("");
const [rdiiAnlss, setRdiiAnlss] = useState<TRdiiAnls[]>([]);
const [rdiiAnlsInfos, setRdiiAnlsInfos] = useState<any[]>([{ val: 0, text: '선택' }]); // 강우유입수분석정보 options
const [rdiiAnlsInfos, setRdiiAnlsInfos] = useState<{ text: string; val: number; hidden?: boolean }[]>([{ val: 0, text: '선택' }]); // 강우유입수분석정보 options
const [rdiiAnls, setRdiiAnls] = useState<TRdiiAnls | null>(null); // 강우유입수분석정보
const [rainInfwtAnlsSn, setRainInfwtAnlsSn] = useState<number>(0); // 강우유입수분석 정보 선택시 사용
const [chartData, setChartData] = useState<{ chartData1: DataType[]; }>({
chartData1: [], //chartData2: [],
});
const [rdiiQty, setRdiiQty] = useState<number>(0); // 강우유입수량
const [totalVolume, setTotalVolume] = useState<number>(0); // 총체적 m³/mm
const [chartData, setChartData] = useState<lineBarChartData[]>([]);
const [rdiiQty, setRdiiQty] = useState<string>("0"); // 강우유입수량
const [rainTotal, setRainTotal] = useState<string>("0"); // 적용강우량
const [totalVolume, setTotalVolume] = useState<string>("0"); // 총체적 m³/mm
const aplcnYms = fn.useAplcnYms('rdiiAnlsRslt'); // 상수사용월 데이터 가져오기
pplMngNo = "L"+pplMngNo; // "L13101003";
console.log("pplMngNo", pplMngNo);
const openPopup = () => {
if (buttonRef.current) {
const rect = buttonRef.current.getBoundingClientRect(); // 버튼 위치 계산
@@ -42,10 +48,16 @@ const RdiiChart = ({ pplMngNo }: ModalOpenProp) => {
setPopupOpen(true); // 팝업 열기
};
const chartForm = CHART_FORM.LINE;
const chartForm = CHART_FORM.LINEBAR2;
const chartConfig = {
chartData1: { label: 'RDII', color: "red", },
//chartData2: { label: '순오수량(m³/h)', color: "orange", },
barVal0: {
label: '강수량',
color: "#33AAFF",
},
lineVal0: {
label: 'RDII',
color: "#FF0000",
},
} as ChartConfig;
useEffect(() => {
@@ -56,9 +68,10 @@ const RdiiChart = ({ pplMngNo }: ModalOpenProp) => {
setRdiiAnlsInfos([{ val: 0, text: '선택' }]); // 강우유입수분석정보 초기화
setRdiiAnls(null); // 강우유입수분석정보 초기화
setRainInfwtAnlsSn(0); // 강우유입수분석 일련번호 초기화
setChartData({chartData1: [], }); // 차트 데이터 초기화
setRdiiQty(0); // 강우유입수량 초기화
setTotalVolume(0); // 총체적 m³/mm 초기화
setChartData([]); // 차트 데이터 초기화
setRdiiQty("0"); // 강우유입수량 초기화
setRainTotal("0"); // 적용강우량 초기화
setTotalVolume("0"); // 총체적 m³/mm 초기화
}
}, [isModalOpen]);
@@ -70,7 +83,6 @@ const RdiiChart = ({ pplMngNo }: ModalOpenProp) => {
setRdiiAnlsInfos([]);
return;
}
console.log(moment(aplcnYm).format("YYYY-MM"));
fn.selectRdiiAnls(aplcnYm)
.then((data) => {
setRdiiAnlss(data ?? []); // 선택한 월의 분석성공한 RDII분석데이터[]
@@ -93,29 +105,38 @@ const RdiiChart = ({ pplMngNo }: ModalOpenProp) => {
if (selectedAnls) {
setRdiiAnls(selectedAnls);
}
}, [rainInfwtAnlsSn]);
}, [rainInfwtAnlsSn, rdiiAnlss]);
const closePopup = () => { // 팝업 닫기
setPopupOpen(false);
}
const rdiiRsltChart = () => { // 그래프 & 팝업 닫기
fn.selectRdiiAnlsRslt(rainInfwtAnlsSn, pplMngNo).then((data) => {// 강우유입수분석 결과 조회
const rsltData1 = fn.getChartDataRdiiAnlsRslt(data ?? []);
//const rsltData2 = fn.getChartDataRdiiAnlsRsltMinq(data ?? []);
setChartData(prev => ({
chartData1: rsltData1, // 순오수량(m³/h)
// chartData2: rsltData2 // RDII(m³/h) 강우유입수분석결과
}));
});
fetchFilteredData();
fn.selectPplRdiiQty(rainInfwtAnlsSn, pplMngNo).then((data) => {// 강우유입수량 조회
setRdiiQty(Math.round(data.rdiih*24)); // cmd: m³/d 단위로 변환
setRdiiQty(Math.round(data.rdiih*24).toLocaleString('ko-KR')); // cmd: m³/d 단위로 변환
if (data.raintotal && data.rainTotal !== 0) {
setTotalVolume(Math.round(data.rdiih * data.sustaintime / data.raintotal)); // 총체적 m³/mm
setRainTotal(data.raintotal.toLocaleString('ko-KR')); // 총강우량mm
setTotalVolume(Math.round(data.rdiih * data.sustaintime / data.raintotal).toLocaleString('ko-KR')); // 총체적 m³/mm
}
});
setPopupOpen(false);
};
const fetchFilteredData: () => Promise<void> = async () => {
const rsltData = await fn.selectRdiiAnlsRslt(rainInfwtAnlsSn, pplMngNo);
const rsltDataformatted = fn.getChartDataRdiiAnlsRslt(rsltData ?? []); // format 변경
const rainData = await fn.selectRainData(rainInfwtAnlsSn);
const rainDataformatted = fn.getChartDataRainData(rainData ?? []); // format 변경
const rainMap = new Map(rainDataformatted.map(item => [item.label, item.barVal0]));
rsltDataformatted.forEach(item => {
const matchedVal = rainMap.get(item.label);
if (matchedVal !== undefined) {
item.barVal0 = matchedVal;
}
});
setChartData(rsltDataformatted); // 차트 데이터 설정
}
const renderBody = () => (
<>
<div className="text-black text-3xl font-bold mb-5">RDII분석결과</div>
@@ -143,6 +164,11 @@ const RdiiChart = ({ pplMngNo }: ModalOpenProp) => {
<span className="w-[30px] inline-block text-right text-black text-xl font-bold"> {rdiiQty}</span>
<span className="ml-2 text-black"> m³/d</span>
</div>
<div className="flex items-center mt-2">
<span className="w-[95px] inline-block text-right text-black text-xl">적용강우량 : </span>
<span className="w-[30px] inline-block text-right text-black text-xl font-bold"> {rainTotal}</span>
<span className="ml-2 text-black"> mm</span>
</div>
<div className="flex items-center mt-2">
<span className="w-[95px] inline-block text-right text-black text-xl">강우량대비RDII : </span>
<span className="w-[30px] inline-block text-right text-black text-xl font-bold"> {totalVolume}</span>
@@ -153,7 +179,7 @@ const RdiiChart = ({ pplMngNo }: ModalOpenProp) => {
{/* 차트 */}
<div className="h-[90%] bg-white text-2xl">
<MainChart chartConfig={chartConfig} chartForm={chartForm} chartData={chartData} chartTitle={'RDII 그래프'}
yFieldText2="시간" yFieldText="유량(m³/h)" />
yFieldText2="강수량(mm)" yFieldText="유량(m³/h)" />
</div>
</div>
{popupOpen && (
@@ -2,14 +2,14 @@ import { VerticalTable } from '@/components/ui/verticalTable';
import React, { useState, useEffect } from 'react'
// 빗물펌프 자체 입력 정보
const exclnInputColumn = [
{ id: "swtrmtZoneCd", title: "배수구역", type: "input" },
{ id: "mltvDtdvNm", title: "배수분구", type: "input" },
{ id: "swtrmtZoneCd", title: "처리구역", type: "input" },
{ id: "mltvDtdvNm", title: "처리분구", type: "input" },
{ id: "dsgnFrqnc", title: "설계빈도(년)", type: "input" },
]
// 오수펌프 자체 입력 정보
const drtwInputColumn = [
{ id: "swtrmt_zone_cd", title: "배수구역", type: "input" },
{ id: "mltv_dtdv_nm", title: "배수분구", type: "input" },
{ id: "swtrmt_zone_cd", title: "처리구역", type: "input" },
{ id: "mltv_dtdv_nm", title: "처리분구", type: "input" },
]
// 하수펌프장
@@ -1,6 +1,7 @@
// 하수맨홀
import { VerticalTable } from '@/components/ui/verticalTable';
import React, { useState, useEffect } from 'react'
import { useEffect, useState } from 'react';
const inputColumn = [
{ id: "swtrmtZoneCd", title: "처리구역", type: "input" },
{ id: "mltvZoneNm", title: "배수구역", type: "input" },
@@ -12,6 +12,8 @@ import RdiiChart from './components/popupComponent/chart/rdiiChart';
import { useInfilChartModalStore, useRdiiChartModalStore } from "./components/popupComponent/chartModalStore";
import { formatDisplayData } from '@/components/lib/utils/formatDisplayValue';
import { codeMapper } from "./components/common/codeMapper";
import { searchUpperPpls } from '@common/business_components/ui/map/Gis';
import LoadingOverlay from '@/components/ui/LoadingBar';
const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void, featureData: any }) => {
@@ -33,6 +35,7 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
const { setIsOpen: setIsModalRdii } = useRdiiChartModalStore();
const [curPage, setCurPage] = useState(1); // 현재 페이지 상태
const [isClicked, setIsClicked] = useState(true); // 클릭 여부 상태
const [isLoading, setIsLoading] = useState(false); // 로딩 상태
// 🎯 관로관리번호 추출
const pplMngNo = featureData?.values_?.fclt_mng_no || "";
@@ -92,13 +95,13 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
else if (lyrTyNm === 'tb_ms_swage_pmstn') { // 하수펌프장
const drtwPumpCode = DRTW_SEWAGE_PUMP_USE_CODES.find(code => code.text === '오수펌프장');
if (drtwPumpCode && featureData.values_.usg_cd.trim() === drtwPumpCode.val) {
setIsDrtwSewagePump(false);
setHeadlist(ExclnSewagePumpCol);
}
else {
setIsDrtwSewagePump(true);
setHeadlist(DrtwSewagePumpCol);
}
else {
setIsDrtwSewagePump(false);
setHeadlist(ExclnSewagePumpCol);
}
setLayerSpecificNm(featureData.values_.fclt_mng_no);
result = '하수펌프장';
}
@@ -469,42 +472,59 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
return (
<div id="popup" className="absolute top-0 right-0 w-[350px] h-[calc(100vh-10rem)] bg-white border-r border-gray-300 flex flex-col overflow-hidden transition-all duration-300 z-[50]">
<div className="card-header bg-primary flex items-center justify-between p-4">
<div className="flex items-center">
<h3 className="text-2xl font-medium text-white text-label whitespace-nowrap mr-4">{layerNm}
<LoadingOverlay isLoading={isLoading} />
<div className="card-header bg-primary flex items-center justify-between relative p-4">
<div className="flex items-center space-x-4 flex-1">
<h3 className="text-2xl font-medium text-white text-label whitespace-nowrap">{layerNm}
{tableData?.usg_cd && (
<>
({tableData.usg_cd})
</>
)} 정보 <br />관리번호 : {layerSpecificNm}
</h3>
<div className="flex items-center space-x-3">
{/* 🎯 하수관로일 때만 Infil/RDII 버튼 표시 */}
{layerNm === '하수관로' && (
<>
<Button onClick={() => setIsModalInfil(true)}
className="py-1 text-xl text-blue-600 border border-blue-600 rounded hover:bg-gray-700"
color="white"
size="sm"
>
침입수분석
</Button>
<Button onClick={() => setIsModalRdii(true)}
className="py-1 text-xl text-gray-600 border border-gray-600 rounded hover:bg-gray-700"
color="white"
size="sm"
>
RDII분석
</Button>
</>
)}
{layerNm === '하수맨홀' && (
<>
<Button onClick={() => {
setIsLoading(true);
searchUpperPpls(layerSpecificNm).finally(() => setIsLoading(false));
}}
className="px-2 py-1 text-xl text-gray-600 border border-gray-600 rounded hover:bg-gray-700"
color="white"
>
상류관로 보기
</Button>
</>
)}
</div>
</div>
<div className="flex items-center space-x-3">
{/* 🎯 하수관로일 때만 Infil/RDII 버튼 표시 */}
{layerNm === '하수관로' && (
<>
<Button onClick={() => setIsModalInfil(true)}
className="px-2 py-1 text-xl text-blue-600 border border-blue-600 rounded hover:bg-gray-700"
color="white"
>
침입수분석
</Button>
<Button onClick={() => setIsModalRdii(true)}
className="px-2 py-1 text-xl text-gray-600 border border-gray-600 rounded hover:bg-gray-700"
color="white"
>
RDII분석
</Button>
</>
)}
<Button
onClick={onClose}
className="text-white hover:text-gray-300 focus:outline-none"
>
✕
</Button>
</div>
<Button
onClick={onClose}
// className="text-white hover:text-gray-300 focus:outline-none"
className="absolute top-8 right-4 text-white hover:text-gray-300 focus:outline-none"
size="xs"
>
✕
</Button>
</div>
<div className="overflow-y-auto overflow-x-hidden flex-1" ref={contentRef}>
<VerticalTable
@@ -5,13 +5,14 @@ import React, { useEffect, useMemo, useState } from 'react';
import { ExclnSewagePumpCol2, MsSwageMhlCol2, MsSwagePplCol2, stofcbrCol2, SwtrmtFcltCol2, SwtrmtPrcsZoneCol2 } from '../components/common/table';
//import { useDcTree, flattenFolders, useSggCd, useCityCd } from './components/searchModalReportApi';
import { type SelectDataType } from '../commonStore';
import { MS_SWAGE_PPL_CODES, MS_SWAGE_PPL_USE_CODES } from '../components/common/table';
import { MS_SWAGE_PPL_CODES, MS_SWAGE_PPL_USE_CODES, MS_SWAGE_MHL_CODES } from '../components/common/table';
import { addFileName, flattenFolders, getFileDownload, useCityCd, useDcTree, useSggCd } from '../components/searchModalReportApi';
// import { useBizByFcltStore } from "../../../store/StoreProvider";
import { getData } from "@/components/lib/api";
import BasicTab, { BASIC_TYPES } from './basicTab';
import OperationTab, { BIZ_TY_CD, operationCleaningTableHeadlist, operationInspectionTableHeadlist, operationMaintenanceTableHeadlist, operationTableHeadlist, WORK_TYPES } from './operationTab';
import ReportTab, { reportTableHeadlist } from './reportTab';
import { formatDisplayData } from '@/components/lib/utils/formatDisplayValue';
const API_URL = `${process.env.NEXT_PUBLIC_SEWERAGE_API_URL}`;
@@ -58,6 +59,12 @@ const SearchModal: React.FC<SearchModalProps> = ({
const [detailTableCount, setDetailTableCount] = useState(0);
const [curPage, setCurPage] = useState(1);
const [detailCurPage, setDetailCurPage] = useState(1);
const [isLoading, setIsLoading] = useState(false);
const [isDetailLoading, setIsDetailLoading] = useState(false);
const [isResetPage, setIsResetPage] = useState<boolean>(false);
const [isResetDetailPage, setIsResetDetailPage] = useState<boolean>(false);
const [isResetSelection, setIsResetSelection] = useState<boolean>(false);
const [isResetDetailSelection, setIsResetDetailSelection] = useState<boolean>(false);
const [detailBizId, setDetailBizId] = useState(0);
const [city, setCity] = useState(0);
const [sgg, setSgg] = useState(0);
@@ -76,10 +83,6 @@ const SearchModal: React.FC<SearchModalProps> = ({
const [yearFilter, setYearFilter] = useState({ start: "", end: "" });
const [filteredSiguns, setFilteredSiguns] = useState<SelectDataType[]>([{ val: '0', text: '전체', sido: '0' }]);
// 로딩바
const [isLoading, setIsLoading] = useState(false);
const [isDetailLoading, setIsDetailLoading] = useState(false);
const sidos = useCityCd();
const siguns = useSggCd();
const reportOriginData = useDcTree(""); //:Folder[]
@@ -138,10 +141,18 @@ const SearchModal: React.FC<SearchModalProps> = ({
end: "",
});
setShowTable(false);
setTableCount(0);
setTableData([]);
setDetailTableData([]);
setTableCount(0);
setDetailTableCount(0);
setCurPage(1); // 페이지를 1로 초기화
setDetailCurPage(1); // 페이지를 1로 초기화
setIsResetPage(true); // 페이지를 초기화
setIsResetDetailPage(true); // 디테일 페이지를 초기화
setIsResetSelection(true); // 선택 초기화
setIsResetDetailSelection(true); // 선택 초기화
// queryParams는 fetchFilteredData 내에서 매번 새로 생성되므로 별도 상태 초기화는 필요 없음
}, [activeTab, basicType, open]);
}, [activeTab, basicType, workType, open]);
useEffect(() => {
setActiveTab(TABS[0]?.val ?? "basic");
@@ -156,19 +167,27 @@ const SearchModal: React.FC<SearchModalProps> = ({
// 페이지 변경 시마다 데이터 fetch
useEffect(() => {
// showTable이 true일 때만 fetch (최초 렌더 방지)
setIsResetPage(false);
setIsResetDetailPage(true);
if (showTable) fetchFilteredData();
}, [curPage]);
// 페이지 변경 시마다 데이터 fetch
useEffect(() => {
setIsResetDetailSelection(false);
// showTable이 true일 때만 fetch (최초 렌더 방지)
if (showTable) handleOperationPageNation(Number(detailBizId));
if (showTable) {
handleOperationPageNation(Number(detailBizId));
}
}, [detailCurPage]);
// 검색 API 호출 함수
const fetchFilteredData = async () => {
setIsLoading(true); // 로딩 시작
setIsResetSelection(true); // 선택 초기화
setIsResetDetailSelection(true); // 선택 초기화
try {
let cqlFilters: string[] = [];
if (activeTab === 'basic') {
@@ -193,14 +212,30 @@ const SearchModal: React.FC<SearchModalProps> = ({
const res = await axios.get(`${API_URL}/v1/fclts?${queryParams.toString()}`);
console.log('필터링된 API 결과(개수):', res.data.count);
console.log('필터링된 API 결과(데이터):', res.data.data);
setTableData(res.data.data || []);
// 🎯 각 아이템을 개별적으로 포맷팅하면서 일련번호 추가
const dataWithRowNumber = (res.data.data || []).map((item: any, index: number) => {
// 🎯 먼저 각 아이템을 포맷팅
const formattedItem = formatDisplayData(item);
const matched = MS_SWAGE_MHL_CODES.find(code => code.val === item?.mqltCd?.trim());
// 추가 처리 및 일련번호 추가
return {
...formattedItem,
rowNumber: (curPage - 1) * 10 + index + 1, // 1부터 시작하는 일련번호 추가
scsYn: item.scsYn === null || item.scsYn === undefined ? 'N' : item.scsYn, // scsYn이 null이면 'N'으로 변경
mqltCd: matched ? matched.text : item.mqltCd,
};
});
setTableData(dataWithRowNumber);
setTableCount(res.data.count || []);
console.log('tableCount 상태 업데이트 후:', res.data.count); // tableCount 로그 추가
} else if (activeTab === 'operation') {
const RequestDTO: Record<string, string> = {
page: `${curPage - 1}`,
size: '5',
size: '4',
};
if (var1) RequestDTO.bizNm = var1;
if (var2 != '0' && var2) RequestDTO.bizTyCd = var2;
@@ -231,9 +266,11 @@ const SearchModal: React.FC<SearchModalProps> = ({
console.log('필터링된 API 결과(데이터):', res.content);
const mappedContent = (res.content || []).map((item: any) => {
console.log("item:", item);
const formattedItem = formatDisplayData(item);
const matched = BIZ_TY_CD.find(code => code.lwpoCd === item.bizTyCd);
return {
...item,
...formattedItem,
bizTyCd: matched ? matched.lwpoCdNm : item.bizTyCd,
};
});
@@ -285,6 +322,8 @@ const SearchModal: React.FC<SearchModalProps> = ({
setTableData([]);
} finally {
setIsLoading(false); // 로딩 종료
// setIsResetSelection(false);
// setIsResetDetailSelection(false);
}
};
@@ -448,9 +487,17 @@ const SearchModal: React.FC<SearchModalProps> = ({
// 조회 버튼 클릭 시 1페이지로 이동 및 데이터 초기화
const handleSearch = () => {
setCurPage(1); // 페이지를 1로 초기화
setDetailCurPage(1); // 페이지를 1로 초기화
setCurPage(1); // 페이지를 1로 초기화
// setDetailCurPage(1); // 페이지를 1로 초기화
// setIsResetPage(false); // 페이지를 초기화
// setIsResetDetailPage(true); // 디테일 페이지를 초기화
// setIsResetSelection(true); // 선택 초기화
// setIsResetDetailSelection(true); // 선택 초기화
fetchFilteredData();
setIsResetPage(true); // 페이지를 초기화
setIsResetDetailPage(true); // 디테일 페이지를 초기화
setIsResetSelection(false); // 선택 초기화
setIsResetDetailSelection(false); // 선택 초기화
setShowTable(true);
};
@@ -463,6 +510,10 @@ const SearchModal: React.FC<SearchModalProps> = ({
};
// 운영정보 테이블 cellClick 핸들러
const handleOperationCellClick = async (index?: number | undefined, headId?: String) => {
setIsResetDetailPage(true); // 페이지를 1로 초기화
setIsResetDetailSelection(true); // 선택 초기화
setIsResetDetailPage(true); // 디테일 페이지를 초기화
if (typeof index === "number") {
setIsDetailLoading(true);
setDetailBizId(tableData[index].bizId);
@@ -470,8 +521,8 @@ const SearchModal: React.FC<SearchModalProps> = ({
try {
const RequestDTO: Record<string, string> = {
page: `${detailCurPage - 1}`,
size: '5',
bizId: tableData[index % 5].bizId,
size: '4',
bizId: tableData[index % 4].bizId,
};
const res = await getData(`v1/bizInfo/fclts?${new URLSearchParams(RequestDTO).toString()}`);
@@ -494,6 +545,8 @@ const SearchModal: React.FC<SearchModalProps> = ({
console.error('운영정보 cellClick 에러:', error);
} finally {
setIsDetailLoading(false);
setIsResetDetailPage(false);
setIsResetDetailSelection(false);
}
}
};
@@ -504,7 +557,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
try {
const RequestDTO: Record<string, string> = {
page: `${detailCurPage - 1}`,
size: '5',
size: '4',
bizId: String(detailBizId),
};
const res = await getData(`v1/bizInfo/fclts?${new URLSearchParams(RequestDTO).toString()}`);
@@ -640,7 +693,7 @@ const SearchModal: React.FC<SearchModalProps> = ({
<UiTable
headName={(() => {
const label = BASIC_TYPES.find((type) => type.val === basicType)?.text
return (<>{label} 조회 결과 ({tableCount})건</>);
return (<>{label} 조회 결과 ({tableCount.toLocaleString('ko-KR')})건</>);
})()
}
tableData={tableData}
@@ -649,7 +702,8 @@ const SearchModal: React.FC<SearchModalProps> = ({
total={tableCount}
cellClick={activeTab === 'report' ? handleReportCellClick : handleBasicCellClick}
onPageChange={setCurPage}
resetPageNo={false}
resetPageNo={isResetPage}
resetSelection={isResetSelection}
/>
</div>
</div>
@@ -664,16 +718,17 @@ const SearchModal: React.FC<SearchModalProps> = ({
headName={
(() => {
const label = WORK_TYPES.find((type) => type.val === workType)?.text
return (<>{label} 사업 현황 ({tableCount})건</>);
return (<>{label} 사업 현황 ({tableCount.toLocaleString('ko-KR')})건</>);
})()
}
tableData={tableData}
headlist={dynamicHeadlist}
pageSize={5}
pageSize={4}
total={tableCount}
cellClick={handleOperationCellClick}
onPageChange={setCurPage}
resetPageNo={false}
resetPageNo={isResetPage}
resetSelection={isResetSelection}
/>
</div>
</div>
@@ -685,16 +740,17 @@ const SearchModal: React.FC<SearchModalProps> = ({
headName={
(() => {
const label = WORK_TYPES.find((type) => type.val === workType)?.text
return (<>{label} 결과표 ({detailTableCount})건</>);
return (<>{label} 결과표 ({detailTableCount.toLocaleString('ko-KR')})건</>);
})()
}
tableData={detailTableData}
headlist={dynamicHeadlist2}
pageSize={5}
pageSize={4}
total={detailTableCount}
cellClick={undefined}
onPageChange={setDetailCurPage}
resetPageNo={false}
resetPageNo={isResetDetailPage}
resetSelection={isResetDetailSelection}
/>
</div>
</div>
@@ -218,7 +218,7 @@ const BaseLayout = ({
<div className="flex items-center w-full">
{showDatePicker && ( // showDatePicker 값에 따라 DatePicker 렌더링
<>
<Label className="ml-4 w-20 text-xl text-gray-600 whitespace-nowrap">상수사용기간</Label>
<Label className="mr-4 w-20 text-xl text-gray-600 whitespace-nowrap">상수사용기간</Label>
<DateMonthPicker
field={{
value: aplcnYmFrom || (() => { // aplcnYm이 없으면 현재 연월을 기본값으로 설정
@@ -247,7 +247,7 @@ const BaseLayout = ({
setAplcnYmTo?.(value); // string 값을 직접 전달
}
}}
selectClass="ml-5 w-[100px]"
selectClass="w-[100px]"
startYear={1900} // 시작 연도 설정
/>
</>
@@ -258,7 +258,7 @@ const BaseLayout = ({
setRtnEnvPartSidoValue={(val) => setCtpvCd?.(val)}
setRtnEnvPartSigunValue={setSigungu} // 선택된 시군구 값을 받을 콜백 함수 전달
>
<SelectBox label={"하수처리장"} value={selectedSwageTreatmentPlant} selectArray={treatmentFacilityOptions} className="col-span-3" selectClass="rounded-lg bg-white truncate" onSelectValue={(val) => onSwageTreatmentPlantChange?.(val)} selectContentClass="z-[101]" />
<SelectBox label={"하수처리장"} value={selectedSwageTreatmentPlant} selectArray={treatmentFacilityOptions} className="col-span-3" selectClass="ml-5 rounded-lg bg-white truncate" onSelectValue={(val) => onSwageTreatmentPlantChange?.(val)} selectContentClass="z-[101]" />
{/* <SelectBox label={"하수처리구역"} value={selectedSwageProcessingZone} selectArray={processingZoneOptions} className="col-span-3" selectClass="rounded-lg bg-white truncate" onSelectValue={(val) => onSwageProcessingZoneChange?.(val)} selectContentClass="z-[101]" /> */}
</GovSidoSigunguSearchForm>
{selectBox?.searchChk ? <SearchFormRight><Button size="sm" onClick={() => selectBox.onSearchClick?.()}>조회</Button></SearchFormRight> : null}
@@ -1,5 +1,5 @@
'use client'
import { deleteData, getData } from '@/components/lib/api'
import { deleteData, getData, useCookieAuth } from '@/components/lib/api'
import { UiTable, downloadExcelWithKoreanHeaders } from '@common/business_components/ui'
import { zodResolver } from '@hookform/resolvers/zod'
import { useState, useEffect } from 'react'
@@ -53,6 +53,8 @@ const tableColumn = [
]
const Result = () => {
const AUTH = useCookieAuth();
const form = useForm<ResultFormValues>({
resolver: zodResolver(formSchema),
defaultValues: {
@@ -81,24 +83,36 @@ const Result = () => {
const [totalData, setTotalData] = useState(0) //총 데이터 수
const [isLoadingResult, setIsLoadingResult] = useState<boolean>(false); // 로딩 상태
const [selectedRowData, setSelectedRowData] = useState<any>(null);
const [selectedRowIndex, setSelectedRowIndex] = useState<number | undefined>(undefined);
const [resetSelection, setResetSelection] = useState<boolean>(false);
const [isResetPage, setIsResetPage] = useState<boolean>(false);
const [curPage, setCurPage] = useState(1); // 현재 페이지
useEffect(() => {
// setCurPage(1);
handleSearchButtonClick();
}, [])
// 페이지 변경 시마다 데이터 fetch
useEffect(() => {
setIsResetPage(false);
handleSearchButtonClick();
}, [curPage]);
const handleSearchButtonClick = async (customFormValues?: Partial<ResultFormValues>) => {
// 조회 버튼 클릭 시 1페이지로 이동 및 데이터 초기화
const handleSearch: () => Promise<void> = async () => {
setCurPage(1); // 페이지를 1로 초기화
setIsResetPage(true); // 페이지를 초기화
await handleSearchButtonClick();
};
const handleSearchButtonClick = async () => {
setIsLoadingResult(true);
setResetSelection(true);
const formValues = customFormValues || form.getValues(); // react-hook-form에서 현재 값 가져오기
const formValues = form.getValues(); // react-hook-form에서 현재 값 가져오기
console.log("formValues", formValues);
let inftwtAnlsSearchDto;
// swageTmplntCd 처리 로직 추가
const processedSwageTmplntCd = formValues.swageTmplntCd && formValues.swageTmplntCd !== '0'
? (() => {
@@ -108,30 +122,21 @@ const Result = () => {
})()
: null;
if (customFormValues) {
inftwtAnlsSearchDto = {
"aplcnYmFrom": formValues.aplcnYmFrom,
"aplcnYmTo": formValues.aplcnYmTo,
"enoCd": formValues.enoCd,
"ctpvCd": formValues.ctpvCd,
"sggCd": formValues.sggCd,
"swageTmplntCd": processedSwageTmplntCd,
};
} else {
inftwtAnlsSearchDto = {
"aplcnYmFrom": formValues.aplcnYmFrom && formValues.aplcnYmFrom !== '' ? formValues.aplcnYmFrom : null,
"aplcnYmTo": formValues.aplcnYmTo && formValues.aplcnYmTo !== '' ? formValues.aplcnYmTo : null,
"enoCd": formValues.enoCd === '0' ? null : formValues.enoCd,
"ctpvCd": formValues.ctpvCd === '0' ? null : formValues.ctpvCd,
"sggCd": formValues.sggCd?.val === '0' ? null : formValues.sggCd?.val,
"swageTmplntCd": processedSwageTmplntCd,
};
}
let inftwtAnlsSearchDto = {
"aplcnYmFrom": formValues.aplcnYmFrom && formValues.aplcnYmFrom !== '' ? formValues.aplcnYmFrom : null,
"aplcnYmTo": formValues.aplcnYmTo && formValues.aplcnYmTo !== '' ? formValues.aplcnYmTo : null,
"enoCd": formValues.enoCd === '0' ? null : formValues.enoCd,
"ctpvCd": formValues.ctpvCd === '0' ? null : formValues.ctpvCd,
"sggCd": formValues.sggCd?.val === '0' ? null : formValues.sggCd?.val,
"swageTmplntCd": processedSwageTmplntCd,
"auth": AUTH,
};
console.log("Search DTO:", inftwtAnlsSearchDto);
const queryParams = new URLSearchParams({
page: '0',
size: '10000000',
page: `${curPage - 1}`,
size: '10',
sort: 'rainInfwtAnlsSn,desc'
});
Object.entries(inftwtAnlsSearchDto).forEach(([key, value]) => {
@@ -153,14 +158,13 @@ const Result = () => {
// 추가 처리 및 일련번호 추가
return {
...formattedItem,
rowNumber: index + 1, // 1부터 시작하는 일련번호 추가
rowNumber: (curPage - 1) * 10 + index + 1, // 1부터 시작하는 일련번호 추가
scsYn: item.scsYn === null || item.scsYn === undefined ? 'N' : item.scsYn // scsYn이 null이면 'N'으로 변경
};
});
// 선택된 행 초기화
setSelectedRowData(null);
setSelectedRowIndex(undefined);
setTableData(dataWithRowNumber);
setTotalData(dataWithRowNumber.length);
@@ -173,6 +177,7 @@ const Result = () => {
alert("분석결과 조회 중 오류가 발생했습니다.");
setTableData([]);
setTotalData(0);
setSelectedRowData(null);
}
setResetSelection(false);
};
@@ -181,7 +186,6 @@ const Result = () => {
const handleCellClick = (index: number | undefined, headId: string) => {
if (index !== undefined && tableData[index]) {
setSelectedRowData(tableData[index]);
setSelectedRowIndex(index);
console.log("Selected row data:", tableData[index]);
}
};
@@ -258,16 +262,8 @@ const Result = () => {
// 테이블 선택 상태 초기화 트리거
setResetSelection(true);
// 삭제 후 테이블 새로고침을 위해 재검색
const customFormValues: Partial<ResultFormValues> = {
aplcnYmFrom: selectedRowData.aplcnYmFrom || null,
aplcnYmTo: selectedRowData.aplcnYmTo || null,
enoCd: selectedRowData.enoCd || null,
ctpvCd: selectedRowData.ctpvCd || null,
sggCd: selectedRowData.sggCd || null,
swageTmplntCd: selectedRowData.swageTmplntCd || null,
};
await handleSearchButtonClick(customFormValues);
// 검색 버튼 클릭 이벤트 트리거
await handleSearchButtonClick();
setIsLoadingResult(false);
@@ -285,7 +281,7 @@ const Result = () => {
return (
<BaseLayout
selectBox={{ title: '분석 대상지역 선택', searchChk: true, onSearchClick: handleSearchButtonClick }}
selectBox={{ title: '분석 대상지역 선택', searchChk: true, onSearchClick: handleSearch }}
titleName={{ mainTitle: '분석결과', firstCardTitle: 'RDII 산정결과 현황' }}
form={form} // form 인스턴스 전달
onSubmitEvent={() => { }} // BaseLayout의 form 태그에 연결될 onSubmit
@@ -320,10 +316,10 @@ const Result = () => {
tableData={tableData}
total={totalData}
pageSize={10}
children={undefined}
cellClick={handleCellClick}
onPageChange={(e) => { }}
onPageChange={setCurPage}
resetSelection={resetSelection}
resetPageNo={isResetPage}
/>
</div>
</div>
@@ -74,26 +74,41 @@ const Result = () => {
}
})
const AUTH = useCookieAuth();
const [tableData, setTableData] = useState<any[]>([]); // API 조회 결과 저장 상태
const [totalData, setTotalData] = useState(0) //총 데이터 수
const [totalData, setTotalData] = useState(0) //총 데이터 수l
const [isLoadingResult, setIsLoadingResult] = useState<boolean>(false); // 로딩 상태
const [selectedRowData, setSelectedRowData] = useState<any>(null);
const [selectedRowIndex, setSelectedRowIndex] = useState<number | undefined>(undefined);
const [resetSelection, setResetSelection] = useState<boolean>(false);
const [isResetPage, setIsResetPage] = useState<boolean>(false);
const [curPage, setCurPage] = useState(1); // 현재 페이지
useEffect(() => {
// setCurPage(1);
handleSearchButtonClick();
}, [])
const auth = useCookieAuth();
const handleSearchButtonClick = async (customFormValues?: Partial<ResultFormValues>) => {
// 페이지 변경 시마다 데이터 fetch
useEffect(() => {
setIsResetPage(false);
handleSearchButtonClick();
}, [curPage]);
// 조회 버튼 클릭 시 1페이지로 이동 및 데이터 초기화
const handleSearch: () => Promise<void> = async () => {
setCurPage(1); // 페이지를 1로 초기화
setIsResetPage(true); // 페이지를 초기화
await handleSearchButtonClick();
};
const handleSearchButtonClick = async () => {
setIsLoadingResult(true);
setResetSelection(true);
const formValues = customFormValues || form.getValues(); // react-hook-form에서 현재 값 가져오기
const formValues = form.getValues(); // react-hook-form에서 현재 값 가져오기
console.log("formValues", formValues);
let inftwtAnlsSearchDto;
// swageTmplntCd 처리 로직 추가
const processedSwageTmplntCd = formValues.swageTmplntCd && formValues.swageTmplntCd !== '0'
@@ -104,34 +119,22 @@ const Result = () => {
})()
: null;
if (customFormValues) {
inftwtAnlsSearchDto = {
"aplcnYmFrom": formValues.aplcnYmFrom,
"aplcnYmTo": formValues.aplcnYmTo,
"enoCd": formValues.enoCd,
"ctpvCd": formValues.ctpvCd,
"sggCd": formValues.sggCd,
"swageTmplntCd": processedSwageTmplntCd,
// "swtrmtZoneCd": formValues.swtrmtZoneCd,
"auth" : auth,
};
} else {
inftwtAnlsSearchDto = {
"aplcnYmFrom": formValues.aplcnYmFrom && formValues.aplcnYmFrom !== '' ? formValues.aplcnYmFrom : null,
"aplcnYmTo": formValues.aplcnYmTo && formValues.aplcnYmTo !== '' ? formValues.aplcnYmTo : null,
"enoCd": formValues.enoCd === '0' ? null : formValues.enoCd,
"ctpvCd": formValues.ctpvCd === '0' ? null : formValues.ctpvCd,
"sggCd": formValues.sggCd?.val === '0' ? null : formValues.sggCd?.val,
"swageTmplntCd": processedSwageTmplntCd,
// "swtrmtZoneCd": formValues.swtrmtZoneCd === '0' ? null : formValues.swtrmtZoneCd,
"auth" : auth,
};
}
let inftwtAnlsSearchDto = {
"aplcnYmFrom": formValues.aplcnYmFrom && formValues.aplcnYmFrom !== '' ? formValues.aplcnYmFrom : null,
"aplcnYmTo": formValues.aplcnYmTo && formValues.aplcnYmTo !== '' ? formValues.aplcnYmTo : null,
"enoCd": formValues.enoCd === '0' ? null : formValues.enoCd,
"ctpvCd": formValues.ctpvCd === '0' ? null : formValues.ctpvCd,
"sggCd": formValues.sggCd?.val === '0' ? null : formValues.sggCd?.val,
"swageTmplntCd": processedSwageTmplntCd,
// "swtrmtZoneCd": formValues.swtrmtZoneCd === '0' ? null : formValues.swtrmtZoneCd,
"auth": AUTH,
};
console.log("Search DTO:", inftwtAnlsSearchDto);
const queryParams = new URLSearchParams({
page: '0',
size: '10000000',
page: `${curPage - 1}`,
size: '10',
sort: 'inftwtAnlsSn,desc'
});
Object.entries(inftwtAnlsSearchDto).forEach(([key, value]) => {
@@ -144,6 +147,7 @@ const Result = () => {
console.log("API: ", `v1/inftwtAnls${queryString ? `?${queryString}` : ''}`);
try {
const data = await getData(`v1/inftwtAnls${queryString ? `?${queryString}` : ''}`);
console.log("API response:", data);
// 🎯 각 아이템을 개별적으로 포맷팅하면서 일련번호 추가
const dataWithRowNumber = (data.content || []).map((item: any, index: number) => {
@@ -153,17 +157,16 @@ const Result = () => {
// 추가 처리 및 일련번호 추가
return {
...formattedItem,
rowNumber: index + 1, // 1부터 시작하는 일련번호 추가
rowNumber: (curPage - 1) * 10 + index + 1, // 1부터 시작하는 일련번호 추가
scsYn: item.scsYn === null || item.scsYn === undefined ? 'N' : item.scsYn // scsYn이 null이면 'N'으로 변경
};
});
// 선택된 행 초기화
setSelectedRowData(null);
setSelectedRowIndex(undefined);
setTableData(dataWithRowNumber);
setTotalData(dataWithRowNumber.length);
setTotalData(data?.totalElements || 0); // totalElements가 없을 경우 0으로 설정
console.log("response:", data);
console.log("response data:", dataWithRowNumber);
setIsLoadingResult(false);
@@ -174,7 +177,6 @@ const Result = () => {
setTableData([]);
setTotalData(0);
setSelectedRowData(null);
setSelectedRowIndex(undefined);
}
setResetSelection(false);
};
@@ -183,7 +185,6 @@ const Result = () => {
const handleCellClick = (index: number | undefined, headId: string) => {
if (index !== undefined && tableData[index]) {
setSelectedRowData(tableData[index]);
setSelectedRowIndex(index);
console.log("Selected row data:", tableData[index]);
}
};
@@ -262,17 +263,8 @@ const Result = () => {
// 테이블 선택 상태 초기화 트리거
setResetSelection(true);
// 삭제 후 테이블 새로고침을 위해 재검색
const customFormValues: Partial<ResultFormValues> = {
aplcnYmFrom: selectedRowData.aplcnYmFrom || null,
aplcnYmTo: selectedRowData.aplcnYmTo || null,
enoCd: selectedRowData.enoCd || null,
ctpvCd: selectedRowData.ctpvCd || null,
sggCd: selectedRowData.sggCd || null,
swageTmplntCd: selectedRowData.swageTmplntCd || null,
// swtrmtZoneCd: selectedRowData.swtrmtZoneCd || null,
};
await handleSearchButtonClick(customFormValues);
// 검색 버튼 클릭 이벤트 트리거
await handleSearchButtonClick();
setIsLoadingResult(false);
@@ -287,10 +279,9 @@ const Result = () => {
};
return (
<BaseLayout
selectBox={{ title: '분석 대상지역 선택', searchChk: true, onSearchClick: handleSearchButtonClick }}
selectBox={{ title: '분석 대상지역 선택', searchChk: true, onSearchClick: handleSearch }}
titleName={{ mainTitle: '분석결과', firstCardTitle: '분석이력' }}
form={form} // form 인스턴스 전달
onSubmitEvent={() => { }} // BaseLayout의 form 태그에 연결될 onSubmit
@@ -325,10 +316,10 @@ const Result = () => {
tableData={tableData}
total={totalData}
pageSize={10}
children={undefined}
cellClick={handleCellClick}
onPageChange={(e) => { }}
onPageChange={setCurPage}
resetSelection={resetSelection}
resetPageNo={isResetPage}
/>
</div>
</div>
@@ -27,6 +27,25 @@ const Page = () => {
const [isLoading, setIsLoading] = useState(true) //로딩 상태
const [isModalOpen, setIsModalOpen] = useState(false) // 모달 상태
const [resetSelection, setResetSelection] = useState<boolean>(false); // 선택 초기화 상태
const [isResetPage, setIsResetPage] = useState<boolean>(false);
useEffect(() => {
setCurPage(1)
fetchData()
}, [])
// 페이지 변경 시마다 데이터 fetch
useEffect(() => {
setIsResetPage(false);
fetchData();
}, [curPage]);
// 조회 버튼 클릭 시 1페이지로 이동 및 데이터 초기화
const handleSearch: () => Promise<void> = async () => {
setCurPage(1); // 페이지를 1로 초기화
setIsResetPage(true); // 페이지를 초기화
await fetchData();
};
// 조회
const fetchData = async () => {
@@ -60,11 +79,6 @@ const Page = () => {
}
}
useEffect(() => {
setCurPage(1)
fetchData()
}, [])
// 파일 다운로드
const isChckFile = () => {
if (fileNm === '' || fileNm === undefined) {
@@ -106,7 +120,7 @@ const Page = () => {
if (data) {
alert('파일이 등록되었습니다.');
setIsModalOpen(false);
fetchData();
handleSearch();
}
}
@@ -160,7 +174,7 @@ const Page = () => {
</SearchFormLeft>
<SearchFormRight>
<div className='flex items-center gap-5'>
<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>
<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 handleSearch()} >조회</Button>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={handleRegisterClick} >등록</Button>
</div>
</SearchFormRight>
@@ -188,8 +202,9 @@ const Page = () => {
setSbmrgPrevntBizSn(tableData[index]?.sbmrgPrevntBizSn);
}
}}
onPageChange={async (page: number) => { setCurPage(page); await fetchData() }}
onPageChange={setCurPage}
resetSelection={resetSelection}
resetPageNo={isResetPage}
/>
</ListDiv>
{/* 파일 업로드 모달 */}
@@ -25,6 +25,25 @@ const Page = () => {
const [isLoading, setIsLoading] = useState(true) //로딩 상태
const [isModalOpen, setIsModalOpen] = useState(false) // 모달 상태
const [resetSelection, setResetSelection] = useState<boolean>(false); // 선택 초기화 상태
const [isResetPage, setIsResetPage] = useState<boolean>(false);
useEffect(() => {
setCurPage(1)
fetchData()
}, [])
// 페이지 변경 시마다 데이터 fetch
useEffect(() => {
setIsResetPage(false);
fetchData();
}, [curPage]);
// 조회 버튼 클릭 시 1페이지로 이동 및 데이터 초기화
const handleSearch: () => Promise<void> = async () => {
setCurPage(1); // 페이지를 1로 초기화
setIsResetPage(true); // 페이지를 초기화
await fetchData();
};
// 데이터 조회
const fetchData = async () => {
@@ -57,11 +76,6 @@ const Page = () => {
}
}
useEffect(() => {
setCurPage(1)
fetchData()
}, [])
// 파일 다운로드
const isChckFile = () => {
if (fileNm === '' || fileNm === undefined) {
@@ -103,7 +117,7 @@ const Page = () => {
if (data) {
alert('파일이 등록되었습니다.');
setIsModalOpen(false);
fetchData();
handleSearch();
}
}
@@ -155,7 +169,7 @@ const Page = () => {
</SearchFormLeft>
<SearchFormRight>
<div className='flex items-center gap-5'>
<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>
<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 handleSearch()} >조회</Button>
<Button className="px-4 py-2 bg-blue-600 text-white rounded-sm text-sm font-medium hover:bg-blue-700" size="sm" onClick={handleRegisterClick} >등록</Button>
</div>
</SearchFormRight>
@@ -184,7 +198,7 @@ const Page = () => {
setDcrpPplMtncBizSn(tableData[index]?.dcrpPplMtncBizSn);
}
}}
onPageChange={async (page: number) => { setCurPage(page); await fetchData() }}
onPageChange={setCurPage}
resetSelection={resetSelection}
/>
</ListDiv>
@@ -1,5 +1,5 @@
import { dateFields, numberFields, yearMonthFields, dateTimeFields } from "../../../(map-layout)/map/components/common/table";
import { isValidDateString, formatDateString } from "./date";
import { formatDateString } from "./date";
// 🎯 데이터 객체 전체를 포맷팅하는 함수
export const formatDisplayData = (data: { [key: string]: any }): { [key: string]: string } => {
+32 -10
View File
@@ -1,17 +1,39 @@
# NEXT_PUBLIC_SITE_ID = WR
# NEXT_PUBLIC_PORT = 3000
# NEXT_PUBLIC_PROXY_HOST = http://wr.hasuon.or.kr
# NEXT_PUBLIC_SERVER_API_URL = http://apigateway.iipbs-dev.svc.cluster.local:8000/api/v1
# NEXT_PUBLIC_FO_SERVER_API_URL = http://apigateway.iipbs-dev.svc.cluster.local:8000/operation-service/api/v1
# NEXT_PUBLIC_CS_SERVER_API_URL = http://apigateway.iipbs-dev.svc.cluster.local:8000
# NEXT_PUBLIC_CS_TUS_UPLOAD = /attach-service/api/v1/tus/upload
# NEXT_PUBLIC_GEOSERVER_URL = http://172.29.143.87:8080/geoserver
# NEXT_PUBLIC_LX_GEOSERVER_URL = http://172.29.143.87:8080/geoserver_swl
# NEXT_PUBLIC_CLAIM_NAME = Authorization
# NEXT_PUBLIC_AUTH_USER_ID = token-id
# NEXT_PUBLIC_ACCESS_TOKEN = access-token
# NEXT_PUBLIC_REFRESH_TOKEN = refresh-token
# NEXT_PUBLIC_SEWERAGE_API_URL = http://apigateway.iipbs-dev.svc.cluster.local:8000/sewerage-service/api
NEXT_PUBLIC_SITE_ID = WR
NEXT_PUBLIC_PORT = 3000
NEXT_PUBLIC_PROXY_HOST = http://wr.hasuon.or.kr
NEXT_PUBLIC_SERVER_API_URL = http://apigateway.iipbs-dev.svc.cluster.local:8000/api/v1
NEXT_PUBLIC_FO_SERVER_API_URL = http://apigateway.iipbs-dev.svc.cluster.local:8000/operation-service/api/v1
NEXT_PUBLIC_CS_SERVER_API_URL = http://apigateway.iipbs-dev.svc.cluster.local:8000
NEXT_PUBLIC_PORT = 11301
NEXT_PUBLIC_PROXY_HOST = http://con.mind-one.co.kr:11301
# NEXT_PUBLIC_SERVER_API_URL = http://dev.onasys.co.kr:8000
NEXT_PUBLIC_SERVER_API_URL = http://con.mind-one.co.kr:11080/api/v1
NEXT_PUBLIC_FO_SERVER_API_URL = http://con.mind-one.co.kr:11082/api/v1
NEXT_PUBLIC_CS_SERVER_API_URL = http://dev.onasys.co.kr:8000
NEXT_PUBLIC_CS_TUS_UPLOAD = /attach-service/api/v1/tus/upload
NEXT_PUBLIC_GEOSERVER_URL = http://172.29.143.87:8080/geoserver
NEXT_PUBLIC_LX_GEOSERVER_URL = http://172.29.143.87:8080/geoserver_swl
NEXT_PUBLIC_GEOSERVER_URL = http://rsone.iptime.org:10010/geoserver
NEXT_PUBLIC_LX_GEOSERVER_URL = http://con.mind-one.co.kr:11306/geoserver
NEXT_PUBLIC_CLAIM_NAME = Authorization
NEXT_PUBLIC_AUTH_USER_ID = token-id
NEXT_PUBLIC_ACCESS_TOKEN = access-token
NEXT_PUBLIC_REFRESH_TOKEN = refresh-token
NEXT_PUBLIC_SEWERAGE_API_URL = http://apigateway.iipbs-dev.svc.cluster.local:8000/sewerage-service/api
NEXT_PUBLIC_SEWERAGE_API_URL=http://con.mind-one.co.kr:11083/sewerage-service/api # 개발 서버 API
+170 -59
View File
@@ -7,12 +7,14 @@ import type { customRainBdst } from "@/app/store/ruseFcltMng/fcltReg/rainReg";
import type { customRswtBdst } from "@/app/store/ruseFcltMng/fcltReg/rswtReg";
import type { WaterReuseFacility } from "@/app/store/ruseFcltMng/fcltSttn/pbnstSttn/type";
import { fetchType, getFetch, postFectch } from "@/components/lib/api";
import { tableData } from "@/components/lib/func/commom";
import { formatPhoneNumber, tableData } from "@/components/lib/func/commom";
import { PbnstSttnModal } from "@/components/ui/modal/sttn/pbnstSttnModal/pbnstSttnModal";
import SttnDetailModal from "@/components/ui/modal/sttn/sttnDetailModal/sttnDetailModal";
import { Title, UITab, UiTable } from '@common/business_components';
import { useGisContext } from "@common/business_components/ui/map/Gis";
import type { DemandCompType } from '@common/business_components/ui/sdmInsertForm/form';
import { HeadMakeColSpan } from "@common/business_components/ui/table/HeadMakeColSpan";
import moment from 'moment';
import React, { useCallback, useEffect, useState } from 'react';
interface NewWindowPopupProps {
@@ -74,7 +76,7 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
// 온배수시설 변수
const { htdflSttn, htdflSttnSearch, initHtdfl } = useWrStore((state) => state);
const { htdflSttnRes,htdflSttnResCount } = htdflSttn;
const { htdflSttnRes, htdflSttnResCount } = htdflSttn;
const [htdflTable, setHtdflTable] = useState<customHtdflBdst[]>();
const [htdflDetailModal, setHtdflDetailModal] = useState<{ isOpen: boolean, data: customHtdflBdst | undefined }>({ data: undefined, isOpen: false });
const [htdflPage, setHtdflPage] = useState(1)
@@ -92,11 +94,31 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
}>({ data: undefined });
const [hasuTable, setHasuTable] = useState<pubHasuType[]>();
const [hasuPage, setHasuPage] = useState<number>(1);
// 수요처관리 변수
const {
coSttn,
coSttnInit,
coSttnSearch,
// getDemandCompList,
// regDemandCompany,
// updateDemandCompany,
// coSttnTxtSearch,
// demandCompList,
} = useWrStore((state) => state);
const [mngTable, setMngTable] = useState<DemandCompType[]>();
const [mngPage, setMngPage] = useState(1);
const { coSttnRes, coSttnResCount, coSttHeadList } = coSttn;
const [isDmdModal, setIsDmdModal] = useState<{
isMoal: boolean;
data: any | undefined;
}>({ isMoal: false, data: undefined});
const [mngList, setMngList] = useState<DemandCompType[]>(coSttnRes || []);
///////////////////////////////////////////// 피쳐데이터 선택 시 각 시설별 데이터 처리 ///////////////////////////////////////////////
const getSelectedLayers = () => {
let result = null;
const layers = gisMap ? gisMap.getLayers().getArray().filter((l: any) => l.getVisible()) : []; // gisMap이 null인지 확인 후 레이어 가져오기
let featureLayer: { get: (key: string) => any } = {get:()=> null};
let featureLayer: { get: (key: string) => any } = { get: () => null };
layers.forEach((layer: any) => {
const source = layer.getSource();
if (source && source.hasFeature && featureData
@@ -122,13 +144,13 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
const rainRes = await postFectch(`/prcsFclt/ruseInfo/1/10/A/0/0/1/SW/${featureCd}`, [data], fetchType.COMMON)
setHasuList(
rainRes.data.map((item: any) => {
return {
...item,
fctCpc: Number(item.fctCpc) || 0,
ruse: item.ruse === false ? "N" : "Y",
};
})
)
return {
...item,
fctCpc: Number(item.fctCpc) || 0,
ruse: item.ruse === false ? "N" : "Y",
};
})
)
} catch (error) {
console.error("Error fetching data:", error);
}
@@ -138,56 +160,63 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
const res = await getFetch(fetchType.WR, `/reuseFc/rainyInfoList/1/20/0/${featureCd}`)
setRainList(res)
}
else if(layerNm == '중수도시설'){
const res = await getFetch(fetchType.WR,`/reuseFc/waterreuseFc/1/20/0/${featureCd}`)
else if (layerNm == '중수도시설') {
const res = await getFetch(fetchType.WR, `/reuseFc/waterreuseFc/1/20/0/${featureCd}`)
setRswtrList(res)
}
else{
else if(layerNm =='수요처'){
const res = await getFetch(fetchType.WR, `/reuseFc/request/1/20/0/${featureCd}`)
setMngList(res)
}
else {
const res = await getFetch(fetchType.WR, `/drain/facilityList/1/20/0/${featureCd}`)
setHtdflList(res)
setHtdflDetailModal({ isOpen: true, data: htdflSttnRes[0] });
}
}
// 상세 목록 데이터 상태 처리
useEffect(()=>{
useEffect(() => {
if (hasuList.length > 0) setIsRuseReg({ data: [hasuList[0]] });
},[hasuList])
useEffect(()=>{
}, [hasuList])
useEffect(() => {
if (rainList.length > 0) setRainDetailModal({ isOpen: true, data: rainList[0] });
},[rainList])
useEffect(()=>{
}, [rainList])
useEffect(() => {
if (rswtrList.length > 0) setRswtrDetailModal({ isOpen: true, data: rswtrList[0] });
},[rswtrList])
useEffect(()=>{
}, [rswtrList])
useEffect(() => {
if (htdflList.length > 0) setHtdflDetailModal({ isOpen: true, data: htdflList[0] });
},[htdflList])
}, [htdflList])
useEffect(() => {
if(mngList.length > 0) setIsDmdModal({ isMoal: true, data: [mngList[0]] });
},[mngList])
const layerId = getSelectedLayers();
if (featureData && typeof featureData.getProperties === "function") {
const selectedVal = featureData.getProperties();
let featureCd = layerId == '하수재이용시설' ? selectedVal?.swtrmt_fclt_cd : layerId == '빗물이용시설' || layerId == '중수도시설' || layerId == '온배수시설' ? selectedVal?.bdst_nm : layerId == '하수처리시설' ? selectedVal?.swtrmt_fclt_nm : null;
if (featureCd && featureCd !== fcltPk) {
if (layerId == '하수재이용시설') {
featureCd = selectedVal?.swtrmt_fclt_cd;
setFcltPk(featureCd); // 현재 호출된 featureCd 저장
setActiveTab(featureCd)
fetchpbnstDetail(featureCd); // 상세정보
}
else if (layerId == '하수처리시설') {
featureCd = selectedVal?.swtrmt_fclt_nm;
setFcltPk(featureCd); // 현재 호출된 featureCd 저장
fetchHasuDetail(featureCd, selectedVal?.swtrmt_fclt_cd);
}
else {
featureCd = selectedVal?.bdst_nm;
setFcltPk(featureCd)
if (layerId) {
detainSttn(featureCd, layerId);
}
}
setViewMode("detail")
if (featureData && typeof featureData.getProperties === "function") {
const selectedVal = featureData.getProperties();
let featureCd = layerId == '하수재이용시설' ? selectedVal?.swtrmt_fclt_cd : layerId == '빗물이용시설' || layerId == '중수도시설' || layerId == '온배수시설' || layerId == '수요처' ? selectedVal?.bdst_nm : layerId == '하수처리시설' ? selectedVal?.swtrmt_fclt_nm : null;
if (featureCd && featureCd !== fcltPk) {
if (layerId == '하수재이용시설') {
featureCd = selectedVal?.swtrmt_fclt_cd;
setFcltPk(featureCd); // 현재 호출된 featureCd 저장
setActiveTab(featureCd)
fetchpbnstDetail(featureCd); // 상세정보
}
} else if (layerId === null && seletectedLayerNm) { setViewMode("list") }
else if (layerId == '하수처리시설') {
featureCd = selectedVal?.swtrmt_fclt_nm;
setFcltPk(featureCd); // 현재 호출된 featureCd 저장
fetchHasuDetail(featureCd, selectedVal?.swtrmt_fclt_cd);
}
else {
featureCd = selectedVal?.bdst_nm;
setFcltPk(featureCd)
if (layerId) {
detainSttn(featureCd, layerId);
}
}
setViewMode("detail")
}
} else if (layerId === null && seletectedLayerNm) { setViewMode("list") }
///////////////////////////////////////////// 피쳐데이터 선택 시 각 시설별 데이터 처리 ///////////////////////////////////////////////
///////////////////////////////////////////// 하수재이용시설 //////////////////////////////////////////////////
@@ -210,7 +239,7 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
getFlcts()
}
}, [seletectedLayerNm, pbnstSttn.isInit, getFlcts]);
useEffect(()=>{
useEffect(() => {
pbnSttnInit("1", "15", {
partValue: "A",
sidoValue: '0',
@@ -258,7 +287,7 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
String(new Date().getFullYear()), fclts
);
}, [fclts, pbnstSttnSearch]);
// FIXME: 윤선화차장님 요구사항으로 엑셀 다운로드 삭제.
// FIXME: 윤선화차장님 요구사항으로 엑셀 다운로드 삭제.
// const excelClick = useCallback(() => {
// // if (codeData) pbnstSttnSearch(1, "10000", codeData);
// excelDownload(
@@ -283,7 +312,7 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
onClose();
}
}
useEffect(() => {
if (!rainSttn.isInit) {
@@ -427,7 +456,7 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
useEffect(() => {
pubHasuInit(String(hasuPage), "0");
}, [hasuPage, pubHasuInit]);
const hasuCellClick = (index: number | undefined) => {
if (index !== undefined && pbnstHasuRes !== undefined) {
onFeatureSelect(pbnstHasuRes[index]);
@@ -436,10 +465,42 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
};
///////////////////////////////////////////// 하수처리 시설 //////////////////////////////////////////////////
///////////////////////////////////////////// 수요처 관리 //////////////////////////////////////////////////
useEffect(() => {
if (!coSttn.isInit) {
coSttnInit("1", "13", "0");
}
}, [coSttn.isInit, coSttnInit]);
const coMngCellClick = (index: number | undefined) => {
if (index !== undefined && mngTable !== undefined) {
onFeatureSelect(mngTable[index]);
onClose();
}
};
useEffect(() => {
if (coSttnRes) {
if (coSttnRes?.length > 0 && code.cityCd.length > 0) {
const data = tableData(coSttnRes, { code });
const chData = data.map((item: any) => ({
...item,
telno: formatPhoneNumber(item.telno || undefined),
regDt: moment(item.regDt).format("YYYY-MM-DD"),
dmdInfoId: `${item.dmdInfoId.slice(0, 3)}-${item.dmdInfoId.slice(3, 5)}-${item.dmdInfoId.slice(5, 10)}-${item.dmdInfoId.slice(10)}`
}));
// .filter((item: any) => item !== undefined);
setMngTable(chData);
}
}
}, [coSttnRes, code]);
useEffect(() => {
coSttnSearch(String(mngPage), "13", String(0));
}, [coSttnSearch, mngPage]);
///////////////////////////////////////////// 수요처 관리 //////////////////////////////////////////////////
// 체크된 레이어에 따른 조건부 컴포넌트 렌더링 함수
const renderConditionalContent = () => {
const actTabData = tabData.find((tab) => tab.id === activeTab);
let layerId:string | undefined | null = getSelectedLayers();
let layerId: string | undefined | null = getSelectedLayers();
if (layerId === null || layerId === undefined) {
layerId = seletectedLayerNm || '';
}
@@ -453,10 +514,12 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
const isRswt = layerId == '중수도시설';
// 온배수시설
const isHtdfl = layerId == '온배수시설';
// 수요처관리
const isReuseMng = layerId == '수요처';
if (isPrcsFclt) {
if (viewMode == 'list') {
return (
<div style={{overflowY:'auto'}}>
<div style={{ overflowY: 'auto' }}>
<div className="flex justify-between items-center mb-4">
<Title title="하수처리시설 현황" />
</div>
@@ -474,7 +537,7 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
)
} else {
return (
<div style={{overflowX:'hidden'}}>
<div style={{ overflowX: 'hidden' }}>
<div className="flex justify-between items-center mb-4">
<Title title="하수처리시설 상세정보" />
</div>
@@ -528,7 +591,7 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
} else {
// 재이용시설 목록
return (
<div style={{overflowY:'auto'}}>
<div style={{ overflowY: 'auto' }}>
<div className="flex justify-between items-center">
<Title title="하수재이용시설 현황" />
{/* <div className="flex gap-2 mt-8">
@@ -600,7 +663,7 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
} else {
// 중수도시설 목록
return (
<div style={{overflowY:'auto'}}>
<div style={{ overflowY: 'auto' }}>
<div className="flex justify-between items-center">
<Title title="중수도시설 현황" />
{/* <div className="flex gap-2 mt-8">
@@ -636,7 +699,7 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
} else {
// 온배수시설 목록
return (
<div style={{overflowY:'auto'}}>
<div style={{ overflowY: 'auto' }}>
<div className="flex justify-between items-center">
<Title title="온배수시설 현황" />
{/* <div className="flex gap-2 mt-8">
@@ -662,15 +725,63 @@ const NewWindowPopup: React.FC<NewWindowPopupProps> = ({
);
}
}
if (isReuseMng) {
if (viewMode == 'detail') {
return (
<div style={{ overflowX: 'hidden' }}>
<div className="flex justify-between items-center mb-4">
<Title title="수요처 상세정보" />
</div>
{/* 높이 조정 */}
<UiTable
tableData={isDmdModal?.data || []}
headlist={coSttHeadList.slice(0, 3)}
pageSize={1}
total={0}
headName={"위치정보"}
cellClick={() => { }}
onPageChange={() => { }}
/>
<UiTable
tableData={isDmdModal?.data || []}
headlist={coSttHeadList.slice(3)}
pageSize={1}
total={0}
headName={"기본정보"}
cellClick={() => { }}
onPageChange={() => { }}
/>
</div>
)
} else if(viewMode == 'list') {
return ( <div>
<div className="flex justify-between items-center">
<Title title="수요처 현황" />
</div>
<UiTable
headName={[]}
tableData={mngTable || []}
headlist={coSttHeadList}
pageSize={20}
total={coSttnResCount + 10 || 0}
cellClick={(index: number | undefined) => {
coMngCellClick(index);
// setUpdateData(coSttnRes[index as number]);
}}
onPageChange={(page) => {
setMngPage(page);
}}
></UiTable></div>)
}
}
return null; // 조건에 맞는 콘텐츠가 없을 경우
};
return (
viewMode == 'nothing' ? <></> :
<NewWindowPortal
onClose={memoizedOnClose}
title="시설 상세 정보"
<NewWindowPortal
onClose={memoizedOnClose}
title="시설 상세 정보"
width={viewMode == 'list' ? window.screen.availWidth : 1100}
height={viewMode == 'list' ? window.screen.availHeight : layerId == '하수처리시설' && viewMode == 'detail' ? 450 : 900}
scrollbars='yes'
@@ -125,6 +125,9 @@ export default function PrfmncPrfmncReg() {
};
if (prfmncRes[index]?.prfList) {
prfmncRes[index].prfList?.forEach((prfItem) => {
const yr = Number(prfItem.ym?.slice(0, 4)); // "YYYY"
if(yr === Number(searchYear)) {
const month = Number(prfItem?.ym?.slice(4)); // "MM"
const monthKey = `${month}월`;
@@ -155,7 +158,11 @@ export default function PrfmncPrfmncReg() {
outSubtotal.total += value;
}
});
}
});
if(inSubtotal.total!==0 && outSubtotal.total!==0) {
inUsageData.push(inSubtotal);
outUsageData.push(outSubtotal);
const usageTotalObj: { [key: string]: any } = {
@@ -174,18 +181,21 @@ export default function PrfmncPrfmncReg() {
const tableData = [...inUsageData, ...outUsageData, usageTotalObj];
setpbnstRuseFcltId(prfmncRes[index].pbnstRuseFcltId);
setInputData(tableData);
}else{
setInputData([]);
}
} else {
setInputData([]);
}
}
},
[prfmncRes]
[prfmncRes,searchYear]
);
useEffect(() => {
if (!prfmnc.isInit) {
const year = new Date().getFullYear()
prfmncHasuInit(1, "41", String(year));
prfmncHasuInit(1, '41', String(year));
}
}, [prfmnc.isInit, prfmncHasuInit]);
useEffect(() => {
@@ -305,7 +315,7 @@ export default function PrfmncPrfmncReg() {
}}
onPageChange={
(page) => {
prfmncHasuInit(page, "41", searchYear);
prfmncHasuInit(page, '41', searchYear);
setPageNation(page)
}}
/>
+1
View File
@@ -140,6 +140,7 @@ export default function RainStat() {
const excelData = [...sidoTotalSummary, ...sidoSummaryList, ...summaryExcelData];
console.log(' excelData ', excelData)
excelDownload(
excelData as unknown as [][],
"빗물이용시설 통계",
+3 -3
View File
@@ -133,7 +133,7 @@ export const rainStatActionsExport = (
tmp: 0,
instlCst: 0, //설치비
dtfcltCpct: 0, //저류조용량
wtrUsqty: 0, //연간사용량
bdstUsgCd: 0, //연간사용량
lndwtr: 0, //조경용수
cleanToilUswtr: 0, //청소화장실용수
resn: 0, //세척살수용수
@@ -153,8 +153,8 @@ export const rainStatActionsExport = (
totalObj.dtfcltCpct += !isNaN(Number(item.dtfcltCpct))
? Number(item.dtfcltCpct)
: 0;
totalObj.wtrUsqty += !isNaN(Number(item.wtrUsqty))
? Number(item.wtrUsqty)
totalObj.bdstUsgCd += !isNaN(Number(item.bdstUsgCd))
? Number(item.bdstUsgCd)
: 0;
totalObj.lndwtr += !isNaN(Number(item.lndwtr))
? Number(item.lndwtr)
+1 -1
View File
@@ -195,7 +195,7 @@ export const StoreZus = (
getMiddleRegionCd(set);
getUnitWaterShedCd(set);
getEnvPartCd(set);
LoginApi.login({userId: "admin1gmail", password: "test1234!"})
LoginApi.login({userId: "CLEANWATER", password: "gktneh12!@"})
return {
...initState,
...comFcltSearchAction(set),
@@ -94,6 +94,7 @@ export default function LineBarchart({
// 데이터의 최대값 계산
const getMaxValue = (data: any[], keyPrefix: string) => {
if (!data || data.length === 0) return 0;
return Math.max(...data.map(item =>
Object.keys(item)
.filter(key => key.includes(keyPrefix))
@@ -0,0 +1,186 @@
"use client"
import type { CSSProperties } from "react";
import { Bar, CartesianGrid, ComposedChart, Legend, Line, Tooltip, XAxis, YAxis } from "recharts";
import {
ChartContainer,
type ChartConfig
} from "./lib/chart";
import type { ContentType } from "recharts/types/component/DefaultLegendContent";
// 툴크 커스텀 css
/** 차트 기본 스타일 */
const customStyles = {
legendContainer: {
display: "flex",
justifyContent: "center",
gap: "20px",
fontSize: "9px",
fontWeight : "bold",
marginTop: "10px",
} as CSSProperties,
};
type LineBarChartProps = {
chartConfig: ChartConfig | undefined;
chartData: any[] | undefined;
chartTitle: string;
chartClassName?: string;
graphSize?: number;
yFieldText?: string | undefined;
yFieldText2?: string | undefined;
showLegend?: boolean;
}
type LegendEntry = {
value: string;
color: string;
type?: string;
payload?: unknown;
};
type LegendProps = {
payload?: LegendEntry[];
};
// 커스텀 툴팁
const CustomTooltip = ({ active, payload, label }: { active?: boolean; payload?: Array<{ name: string; value: number; color: string }>; label?: string }) => {
if (active && payload && payload.length) {
return (
<div className="w-[180px] rounded bg-white p-2.5 shadow-[0px_2px_10px_rgba(0,0,0,0.2)]">
<p className="text-[12px] font-bold m-3">{label}</p>
{payload.map((item, index) => (
<div key={index} style={{ marginTop: "10px", display: "flex", alignItems: "center", gap: "8px" }}>
{/* 색상 박스 추가 (범례 색상과 동일) */}
<div style={{ width: "10px", height: "10px", backgroundColor: item.color, borderRadius: "50%" }}></div>
<span className="text-[11px] font-bold">{` ${item.name} : ${item.value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`}</span>
</div>
))}
</div>
);
}
return null;
};
// 커스텀 범례 (글씨 크기 키우기 + 스타일 추가)
const CustomLegend = (props: LegendProps) => {
const { payload } = props;
if (!payload) return null;
return (
<div style={customStyles.legendContainer}>
{payload.map((entry: LegendEntry, index: number) => (
<div key={`legend-${index}`} className="flex items-center gap-2">
<div className="w-[14px] h-[14px] ml-10" style={{ backgroundColor: entry.color }}></div>
<span className="text-[12px]">{entry.value}</span>
</div>
))}
</div>
);
};
export default function LineBarchart2({
chartConfig,
chartData,
chartTitle,
chartClassName = 'w-full h-full',
graphSize = 40,
yFieldText,
yFieldText2,
showLegend = true
}: LineBarChartProps) {
if (!chartData || chartData.length === 0) {
return <div>데이터가 없습니다.</div>;
}
// 데이터의 최대값 계산
const getMaxValue = (data: any[], keyPrefix: string) => {
if (!data || data.length === 0) return 0;
return Math.max(...data.map(item =>
Object.keys(item)
.filter(key => key.includes(keyPrefix))
.map(key => item[key])
).flat());
};
const lineMaxValue = getMaxValue(chartData, 'lineVal');
const barMaxValue = getMaxValue(chartData, 'barVal');
return (
<div className={chartClassName}>
{chartTitle && chartTitle !== "" && chartTitle !== "undefined" ? (
<div style={{ textAlign: "left", fontSize: "13px", fontWeight: "bold", marginTop:"13px", marginBottom: "10px" }}>
{chartTitle}
</div>
) : null}
<div className="h-[calc(100%-42px)] flex justify-center">
<ChartContainer config={chartConfig ?? {}} className="h-full w-full">
<ComposedChart
data={chartData}
height={graphSize * 7.5}
width={graphSize * 12.5}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="label" fontSize="8px" fontWeight="bold"/>
{/* 왼쪽 Y축: lineVal */}
{yFieldText && <YAxis
yAxisId="left"
className="text-[12px] font-bold"
tickCount={6}
orientation="left"
domain={[0, Math.ceil(lineMaxValue * 1)*2]}
label={{ value: yFieldText, angle: -90, position: 'insideLeft', offset: -8 }}
/>}
{/* 오른쪽 Y축: barVal */}
{yFieldText2 && <YAxis
yAxisId="right"
className="text-[12px] font-bold"
tickCount={6}
orientation="right"
domain={[0, Math.ceil(barMaxValue * 1)*2]}
label={{ value: yFieldText2, angle: -90, position: 'insideRight' }}
reversed={true}
/>}
<Tooltip content={<CustomTooltip active={undefined} payload={undefined} label={undefined} />} />
{showLegend && <Legend content={CustomLegend as ContentType}/>}
{/* 바 차트 (오른쪽 Y축 사용) */}
{Object.keys(chartData[0]).map((key, index) => {
const config = chartConfig?.[key];
if(key.includes("barVal")) {
return (
<Bar
key={`bar-${key}-${index}`}
yAxisId="right"
dataKey={key}
fill={config?.color || "black"}
name={String(config?.label || "Y축")}
maxBarSize={80}
/>
);
}
return null;
})}
{/* 라인 차트 (왼쪽 Y축 사용) */}
{Object.keys(chartData[0]).map((key, index) => {
const config = chartConfig?.[key];
if(key.includes("lineVal")) {
return (
<Line
key={`line-${key}-${index}`}
yAxisId="left"
type="linear"
dataKey={key}
stroke={config?.color || "black"}
strokeWidth={2}
dot={{r: 0}}
name={String(config?.label || "X축")}
/>
);
}
return null;
})}
</ComposedChart>
</ChartContainer>
</div>
</div>
);
}
@@ -2,6 +2,7 @@
import DoubleBarChart from './DoubleBar';
import DoughnutChart from './DoughnutChart';
import LineBarchart from './LineBarChart';
import LineBarchart2 from './LineBarChart2';
import LineChart from './LineChart';
/**차트 FORM */
@@ -14,6 +15,8 @@ const CHART_FORM = {
DN :'daughnut',
/**LINE,BAR차트 */
LINEBAR : 'linebar',
/**LINE,BAR차트 */
LINEBAR2 : 'linebar2',
/**더블바 차트 형태*/
DOUBLEBAR : 'doublebar'
};
@@ -72,6 +75,10 @@ function MainChart(props: MainChartProps) {
return (
<LineBarchart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} yFieldText2={props.yFieldText2} showLegend={props.showLegend}/>
);
} else if (props.chartForm == CHART_FORM.LINEBAR2){
return (
<LineBarchart2 chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} yFieldText2={props.yFieldText2} showLegend={props.showLegend}/>
);
} else if (props.chartForm == CHART_FORM.DOUBLEBAR){
return (
<DoubleBarChart chartConfig={props.chartConfig} chartData={props.chartData} chartTitle={props.chartTitle} chartClassName={props.chartClassName} graphSize={props.graphSize} yFieldText={props.yFieldText} showLegend={props.showLegend}/>
@@ -20,6 +20,73 @@ import GisApp from './lib/gis.core';
export const GisContext = createContext({ gisCore: null, gisMap: null, treeData: null, checkedLayerIds: null });
export const useGisContext = () => useContext(GisContext);
export const searchUpperPpls = async (fcltMngNo) => {
const BASE_URL = process.env.NEXT_PUBLIC_SEWERAGE_API_URL || '';
const res = await fetch(`${BASE_URL}/v1/fcltmhl/upperPpls/${fcltMngNo}`, {
method: "GET",
});
let data = null;
if (res.ok) {
try {
// 응답이 비어있는지 확인
const contentLength = res.headers.get('content-length');
if (contentLength === '0') alert(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
// 응답 텍스트를 먼저 가져와서 빈 문자열인지 확인
const text = await res.text();
if (!text || text.trim() === '') alert(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
// JSON 파싱 시도
data = JSON.parse(text);
} catch (error) {
console.error('JSON parsing error:', error);
alert(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
}
}
const select = GisApp.Module.select;
const gisMap = GisApp.Module.core?.map;
let foundFeature = null;
data.forEach(item => {
const pplMngNo = item.ppl_mng_no.trim();
gisMap.getLayers().getArray().filter(e => e.get("lyrTyNm") == 'tb_ms_swage_ppl').forEach(layer => {
const source = layer.getSource?.();
if (source?.getFeatures) {
const features = source.getFeatures();
for (const f of features) {
if (f.values_.fclt_mng_no.trim() === pplMngNo) {
foundFeature = f;
break;
}
}
}
});
if (foundFeature) select.selectMultiFeature(foundFeature, true);
});
if (!foundFeature) alert(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
let geometry = foundFeature?.getGeometry();
if (geometry) {
let extent = geometry.getExtent();
gisMap.getView().fit(extent, {
duration: 300,
padding: [50, 50, 50, 50],
maxZoom: 14,
constrainResolution: true,
nearest: true,
});
}
};
function Gis({
isOpen,
@@ -96,7 +163,10 @@ function Gis({
featureId = data.bscFctCd;
} else if (layerName === '온배수시설') {
featureId = data.bdstRuseFcltSn;
} else {
} else if(layerName == '수요처'){
featureId = data.dmdInfoId.replaceAll('-','')
}
else {
console.warn('해당 레이어에 대한 featureId 매핑 없음', layerNm);
featureId = data.fid || data.id || data.ftrIdn;
}
@@ -418,6 +488,7 @@ function Gis({
onFeatureSelect={handleFeatureSelect}
/>
)}
{/* <GisLonLat /> */}
<GisToolBar />
<GisMapToggle />
<GisSelect onFeatureSelect={handleFeatureSelect} />
@@ -429,6 +429,19 @@ GisOlSelect.prototype = {
auto: auto,
});
},
/**
* 피처 다중 셀렉트
*/
selectMultiFeature: function (feature, auto) {
let me = this;
me.selectedFeatures.push(feature);
me.selectInteraction.dispatchEvent({
type: 'select',
selected: me.selectedFeatures,
deselected: [],
auto: auto,
});
},
};
export default GisOlSelect;
@@ -215,6 +215,8 @@ export function SdmRegForm({ form, onCheckboxChange, selectSidoData, selectSigun
useEffect(() => {
form.setValue('rgtr', '2d4b151d-1828-41e0-91d9-4cd28ea1cc7e');
if(updateList?.dmdInfoId){
form.reset(updateList)
if(updateList?.dmdInfoId.slice(10,14) !== '0000') {
@@ -322,7 +324,7 @@ export function SdmRegForm({ form, onCheckboxChange, selectSidoData, selectSigun
},
{
name: "bznmTotNo",
label: "종사업자등록번호",
label: "",
component: (field) => (
<FormUi
label="종사업자등록번호"
@@ -419,7 +421,7 @@ export function SdmRegForm({ form, onCheckboxChange, selectSidoData, selectSigun
name={name}
render={({ field }) => (
<div className="mb-4">
<label htmlFor={inputId} className="block text-gray-800 font-medium">
<label htmlFor={inputId} className="block text-gray-800 font-medium text-xl">
{label}
{isRequired && <span className="text-red-500 ml-1">*</span>}
</label>
@@ -432,7 +434,7 @@ export function SdmRegForm({ form, onCheckboxChange, selectSidoData, selectSigun
})}
{error?.message && (
<p id={errorId} role="alert" className="text-red-500 text-sm mt-1">
<p id={errorId} role="alert" className="text-red-500 text-lg mt-1">
{error.message}
</p>
)}
@@ -122,8 +122,8 @@ export function UiTable({
: cellClick
? "cursor-pointer"
: ""
} sticky z-40 bg-secondary !font-bold`}
style={{ top: `${headerHeight + index * 39}px` }}
} sticky top-20 z-40 bg-secondary !font-bold`}
style={{ top: `${headerHeight + index * 32-4}px` }}
onClick={() => handleCellClick(index, head.id)}
key={`cell-${head.id}-${index}`}
>
@@ -31,7 +31,7 @@ const TableHeader = React.forwardRef<
>(({ className, ...props }, ref) => (
<thead
ref={ref}
className={cn("sticky top-0 z-10 bg-secondary [&_tr]:border-b", className)}
className={cn("sticky -top-3 z-10 bg-secondary [&_tr]:border-b", className)}
{...props}
/>
));
+10 -10
View File
@@ -601,7 +601,7 @@ importers:
version: 2.5.2(react-dom@18.3.1)(react@18.3.1)
react-i18next:
specifier: ^15.6.0
version: 15.6.0(i18next@25.3.2)(react-dom@18.3.1)(react@18.3.1)(typescript@5.6.3)
version: 15.6.1(i18next@25.3.2)(react-dom@18.3.1)(react@18.3.1)(typescript@5.6.3)
tailwind-merge:
specifier: ^3.0.1
version: 3.0.2
@@ -1237,8 +1237,8 @@ packages:
dependencies:
regenerator-runtime: 0.14.1
/@babel/runtime@7.27.6:
resolution: {integrity: sha512-vbavdySgbTTrmFE+EsiqUTzlOr5bzlnJtUv9PynGCAKvfQqjIXbvFdumPM/GxMDfyuGMJaJAU6TO4zc1Jf1i8Q==}
/@babel/runtime@7.28.2:
resolution: {integrity: sha512-KHp2IflsnGywDjBWDkR9iEqiWSpc8GIi0lgTT3mOElT0PP1tG26P4tmFI2YvAdzgq9RGyoHZQEIEdZy6Ec5xCA==}
engines: {node: '>=6.9.0'}
dev: false
@@ -4333,7 +4333,7 @@ packages:
dependencies:
'@ampproject/remapping': 2.3.0
enhanced-resolve: 5.18.1
jiti: 2.4.2
jiti: 2.5.1
lightningcss: 1.30.1
magic-string: 0.30.17
source-map-js: 1.2.1
@@ -7186,7 +7186,7 @@ packages:
typescript:
optional: true
dependencies:
'@babel/runtime': 7.27.6
'@babel/runtime': 7.28.2
typescript: 5.6.3
dev: false
@@ -7531,8 +7531,8 @@ packages:
resolution: {integrity: sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==}
hasBin: true
/jiti@2.4.2:
resolution: {integrity: sha512-rg9zJN+G4n2nfJl5MW3BMygZX56zKPNVEYYqq7adpmMh4Jn2QNEwhvQlFy6jPVdcod7txZtKHWnyZiA3a0zP7A==}
/jiti@2.5.1:
resolution: {integrity: sha512-twQoecYPiVA5K/h6SxtORw/Bs3ar+mLUtoPSc7iMXzQzK8d7eJ/R09wmTwAjiamETn1cXYPGfNnu7DMoHgu12w==}
hasBin: true
dev: false
@@ -8933,8 +8933,8 @@ packages:
react-dom: 18.3.1(react@18.3.1)
dev: false
/react-i18next@15.6.0(i18next@25.3.2)(react-dom@18.3.1)(react@18.3.1)(typescript@5.6.3):
resolution: {integrity: sha512-W135dB0rDfiFmbMipC17nOhGdttO5mzH8BivY+2ybsQBbXvxWIwl3cmeH3T9d+YPBSJu/ouyJKFJTtkK7rJofw==}
/react-i18next@15.6.1(i18next@25.3.2)(react-dom@18.3.1)(react@18.3.1)(typescript@5.6.3):
resolution: {integrity: sha512-uGrzSsOUUe2sDBG/+FJq2J1MM+Y4368/QW8OLEKSFvnDflHBbZhSd1u3UkW0Z06rMhZmnB/AQrhCpYfE5/5XNg==}
peerDependencies:
i18next: '>= 23.2.3'
react: ^18.3.1
@@ -8949,7 +8949,7 @@ packages:
typescript:
optional: true
dependencies:
'@babel/runtime': 7.27.6
'@babel/runtime': 7.28.2
html-parse-stringify: 3.0.1
i18next: 25.3.2(typescript@5.6.3)
react: 18.3.1