Compare commits

...
55 Commits
Author SHA1 Message Date
chanii8 2d044750ae Merge branch 'main' into deploy
Deploy Frontend / deploy (push) Successful in 2m47s
2026-05-07 13:37:02 +09:00
chanii8 5f04e775b4 Merge branch 'iipbs/st/dev' 2026-05-07 13:36:15 +09:00
chanii8 4d23e07be0 [st] feat: 알림톡 발송 파라미터 수정 2026-05-07 13:35:27 +09:00
chanii8 920922e21b Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 5m49s
2026-05-07 10:53:38 +09:00
chanii8 c66a0be0ea Merge branch 'iipbs/st/dev' of https://www.onasys.co.kr:3000/ONAANDALL/frontend 2026-05-07 10:52:28 +09:00
chanii8 74f14dec37 [st] WIP: 알림톡발송
[st] WIP: 알림톡발송
2026-05-07 10:49:04 +09:00
chanii8 2fcd735d18 [st] feat: 대시보드 미제출 지표 API 변경 적용 2026-05-07 10:47:14 +09:00
kiminchan 3302f7e8e0 Merge branch 'iipbs/sn/dev' 2026-05-06 14:55:46 +09:00
rsone001 9f9c6f30cb [st] feat: 검증 미통과 내역 - 조회 바로가기 기능 2026-05-04 18:04:32 +09:00
rsone001 4a57b363eb [st] feat: 검증 미통과 내역 메뉴 작업 2026-05-04 10:34:53 +09:00
rsone001 3637d09d03 [st] refactor: SearchForm 수정, 입력-하수관로 & 공공하수처리시설 작업중 2026-04-29 18:08:50 +09:00
chanii8 109c5b14e6 Merge branch 'main' into deploy
Deploy Frontend / deploy (push) Successful in 3m31s
2026-04-29 18:04:03 +09:00
chanii8 7baf877528 Merge branch 'iipbs/st/dev' 2026-04-29 18:03:06 +09:00
jcchoi 062e26c6d9 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend 2026-04-29 17:41:54 +09:00
chanii8 9ad2f3944a Merge branch 'main' into deploy
Deploy Frontend / deploy (push) Successful in 3m16s
2026-04-29 17:11:23 +09:00
chanii8 7e241f964c Merge branch 'iipbs/cs/dev' 2026-04-29 17:10:20 +09:00
chanii8 6d5ebdc739 [cs] feat: 알림톡 템플릿 등록 인터페이스 수정 및 스펙 문서 보완 2026-04-29 17:09:54 +09:00
chanii8 5f56e9a207 Merge branch 'main' into deploy
Deploy Frontend / deploy (push) Successful in 3m53s
2026-04-29 14:49:48 +09:00
chanii8 871e488216 Merge branch 'iipbs/cs/dev' 2026-04-29 14:48:28 +09:00
chanii8 216cec8cc7 [cs] chore: 하위코드 스키마 수정 2026-04-29 14:47:49 +09:00
jcchoi de1d6f9e43 코드관련 자리수 수정 2026-04-29 14:01:24 +09:00
chanii8 54f834ceff [st] feat: 대시보드 페이지 수정 2026-04-29 13:58:29 +09:00
jcchoi 2f7f128a48 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend 2026-04-29 13:34:14 +09:00
jcchoi aca72fa4e0 사용자 수정 변경 2026-04-29 13:34:08 +09:00
chanii8 f2aaf9696e Merge branch 'main' into deploy
Deploy Frontend / deploy (push) Successful in 2m36s
2026-04-29 11:40:13 +09:00
chanii8 d6d2900142 Merge branch 'iipbs/st/dev' 2026-04-29 11:38:46 +09:00
chanii8 4cd2aee92e Merge branch 'iipbs/st/dev' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs/st/dev 2026-04-29 11:37:20 +09:00
chanii8 9fc2fc8942 [st] feat: 대시보드 페이지 작업 2026-04-29 11:37:17 +09:00
rsone001 3f63cc915b Merge branch 'iipbs/st/dev' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs/st/dev 2026-04-28 17:09:08 +09:00
rsone001 3b170b0992 [st] feat: 입력- 저장,제출 로직 수정(01,02) & 02-6tab 로직 수정, 집계- 로직 수정 및 요약표 포함 조건 추가 2026-04-28 17:08:59 +09:00
chanii8 d6a049758e Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 3m32s
2026-04-28 15:24:23 +09:00
chanii8 f21e902edd Merge branch 'iipbs/st/dev' of https://www.onasys.co.kr:3000/ONAANDALL/frontend 2026-04-28 15:19:19 +09:00
chanii8 d98003b3ec [st] feat: 통계 검증 리포트 수정사항 반영 2026-04-28 15:13:54 +09:00
chanii8 78defdd050 [st] feat: HB 통계 검증 페이지 수정사항 반영 2026-04-28 10:59:10 +09:00
chanii8 47b582c5cc [st] WIP: 대시보드 페이지 2026-04-28 10:16:01 +09:00
chanii8 a72e4ae4bd Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 2m46s
2026-04-27 10:14:21 +09:00
chanii8 af5bbbd56e Merge branch 'iipbs/st/dev' of https://www.onasys.co.kr:3000/ONAANDALL/frontend 2026-04-27 10:12:03 +09:00
chanii8 d462c50684 [st] feat: 컴포넌트 경로 조합 방식 변경 2026-04-27 10:11:36 +09:00
chanii8 3da3b88d05 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 3m38s
2026-04-22 18:05:15 +09:00
chanii8 1715c8c88b Merge remote-tracking branch 'origin/main' into deploy
Deploy Frontend / deploy (push) Successful in 2m31s
2026-04-22 13:30:40 +09:00
chanii8 983075e4d0 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 6m40s
2026-04-21 18:10:26 +09:00
chanii8 237ec3bc88 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 4m56s
2026-04-20 17:37:06 +09:00
chanii8 b5bcdb168f Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 2m36s
2026-04-20 09:44:23 +09:00
chanii8 5376757f0f Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 3m31s
2026-04-15 17:26:02 +09:00
chanii8 3bfbc698fe Merge remote-tracking branch 'origin/main' into deploy
Deploy Frontend / deploy (push) Successful in 3m25s
2026-04-15 16:56:17 +09:00
chanii8 44431a7905 Merge remote-tracking branch 'origin/main' into deploy
Deploy Frontend / deploy (push) Successful in 5m21s
2026-04-15 13:32:17 +09:00
chanii8 97ae53ad5d Merge remote-tracking branch 'origin/main' into deploy
Deploy Frontend / deploy (push) Successful in 3m12s
2026-04-14 16:30:06 +09:00
chanii8 a2b0469275 Merge remote-tracking branch 'origin/main' into deploy
Deploy Frontend / deploy (push) Successful in 3m5s
2026-04-13 17:05:51 +09:00
chanii8 13219b7d4e Merge remote-tracking branch 'origin/main' into deploy
Deploy Frontend / deploy (push) Successful in 5m45s
2026-04-13 16:33:05 +09:00
chanii8 4d778af385 Merge remote-tracking branch 'origin/main' into deploy
Deploy Frontend / deploy (push) Successful in 4m16s
2026-04-13 11:18:17 +09:00
chanii8 d976e5fdfa Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 5m44s
2026-04-09 18:34:32 +09:00
chanii8 1d4329e058 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 56s
2026-04-09 16:30:44 +09:00
chanii8 6dc42ae4b1 Merge branch 'main' into deploy
Deploy Frontend / deploy (push) Successful in 56s
2026-04-09 15:09:09 +09:00
chanii8 ed5971aed7 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 56s
2026-04-09 10:53:45 +09:00
chanii8 d817292955 Merge branch 'main' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into deploy
Deploy Frontend / deploy (push) Successful in 59s
2026-04-08 17:17:33 +09:00
100 changed files with 6945 additions and 1035 deletions
+12 -11
View File
@@ -102,35 +102,35 @@ function UsersForm<T extends UserSaveData | UserUpdateData>({
return ( return (
authSeCd?.filter( authSeCd?.filter(
(code) => (code) =>
code.lwpoCd === "ROLE_USER1" || code.lwpoCd === "ROLE_USER01" ||
code.lwpoCd === "ROLE_USER2" || code.lwpoCd === "ROLE_USER02" ||
code.lwpoCd === "ROLE_USER3", code.lwpoCd === "ROLE_USER03",
) ?? [] ) ?? []
); );
if (watchOgdpSeCd === "3" || watchOgdpSeCd === "4") if (watchOgdpSeCd === "3" || watchOgdpSeCd === "4")
return ( return (
authSeCd?.filter( authSeCd?.filter(
(code) => (code) =>
code.lwpoCd === "ROLE_USER4" || code.lwpoCd === "ROLE_USER5", code.lwpoCd === "ROLE_USER04" || code.lwpoCd === "ROLE_USER05",
) ?? [] ) ?? []
); );
return []; return [];
}, [authSeCd, watchOgdpSeCd]); }, [authSeCd, watchOgdpSeCd]);
const laeSeCdSelectData = useMemo(() => { const laeSeCdSelectData = useMemo(() => {
if (watchDtlInstCd === "ROLE_USER1") if (watchDtlInstCd === "ROLE_USER01")
return laeSeCd?.filter((code) => code.lwpoCd === "G102") ?? []; return laeSeCd?.filter((code) => code.lwpoCd === "G102") ?? [];
if (watchDtlInstCd === "ROLE_USER2") if (watchDtlInstCd === "ROLE_USER02")
return laeSeCd?.filter((code) => code.lwpoCd === "G101") ?? []; return laeSeCd?.filter((code) => code.lwpoCd === "G101") ?? [];
if (watchDtlInstCd === "ROLE_USER3") if (watchDtlInstCd === "ROLE_USER03")
return laeSeCd?.filter((code) => code.lwpoCd.startsWith("G2")) ?? []; return laeSeCd?.filter((code) => code.lwpoCd.startsWith("G2")) ?? [];
if (watchDtlInstCd === "ROLE_USER4") if (watchDtlInstCd === "ROLE_USER04")
return ( return (
laeSeCd?.filter( laeSeCd?.filter(
(code) => code.lwpoCd.startsWith("G3") && code.lwpoCd.length === 4, (code) => code.lwpoCd.startsWith("G3") && code.lwpoCd.length === 4,
) ?? [] ) ?? []
); );
if (watchDtlInstCd === "ROLE_USER5") if (watchDtlInstCd === "ROLE_USER05")
return ( return (
laeSeCd?.filter( laeSeCd?.filter(
(code) => code.lwpoCd.startsWith("G3") && code.lwpoCd.length === 7, (code) => code.lwpoCd.startsWith("G3") && code.lwpoCd.length === 7,
@@ -622,8 +622,9 @@ function UsersForm<T extends UserSaveData | UserUpdateData>({
onValueChange={field.onChange} onValueChange={field.onChange}
disabled={ disabled={
!( !(
watchDtlInstCd === "ROLE_USER4" || watchDtlInstCd === "ROLE_USER03" ||
watchDtlInstCd === "ROLE_USER5" watchDtlInstCd === "ROLE_USER04" ||
watchDtlInstCd === "ROLE_USER05"
) )
} }
> >
+76
View File
@@ -260,3 +260,79 @@ BEGIN
END END
``` ```
---
## 9. 템플릿 등록 다이얼로그
대상 UI: `NtftalkTempRegistDialog` (`apps/cs/src/pages/ntftalk-temp/ui/ntftalk-temp-regist-dialog.tsx`)
### 9-1. 목적/오픈 조건
- 목적: 신규 알림톡 템플릿 1건을 등록한다.
- 오픈 조건: 영역 B 툴바의 `템플릿등록` 클릭 시 모달 오픈.
- 저장 성공 시: 목록 캐시 무효화 후 영역 B 재조회 상태로 복귀(모달 닫힘).
### 9-2. 다이얼로그 레이아웃
```
┌──────────────────────────────────────────────────────────────────────┐
│ 알림 템플릿 등록 │
├──────────────────────────────────────────────────────────────────────┤
│ 메시지 유형 [기본형(고정)] │
│ 채널 [Select(senderKey)] │
│ 템플릿코드 [Input] │
│ 템플릿명 [Input] │
│ 보안템플릿여부 ( )설정 ( )미설정 │
│ 템플릿내용 [+ 변수추가] │
│ [Textarea] │
│ 버튼 Table(버튼타입|버튼명|버튼링크) │
│ [CodeSelect(upCd: NTFBUTTONTYPE) | Input | Input] │
│ 바로연결 Table(바로연결타입|바로연결명|바로연결링크) │
│ [CodeSelect(upCd: NTFQRTYPE) | Input | Input] │
├──────────────────────────────────────────────────────────────────────┤
│ [저장] [취소] │
└──────────────────────────────────────────────────────────────────────┘
```
### 9-3. 필드 상세
| 표시명 | Form Key | 입력 유형 | 필수 | 기본값 | 검증/제약 | 저장 Payload 매핑 |
| -------------- | ----------------------- | ----------- | ---- | ------------------------------------- | -------------------- | --------------------- |
| 메시지 유형 | `templateMessageType` | 고정 텍스트 | Y | `BA` | UI에서 `기본형` 고정 | `templateMessageType` |
| 채널 | `senderKey` | Select | Y | `senderQuery.data.senderKey` 자동세팅 | 미선택 불가 | `senderKey` |
| 발신키 유형 | `senderKeyType` | hidden 상수 | Y | `S` | submit 시 강제 `S` | `senderKeyType` |
| 템플릿코드 | `templateCode` | Input | Y | `""` | 1자 이상 | `templateCode` |
| 템플릿명 | `templateName` | Input | Y | `""` | 1자 이상 | `templateName` |
| 보안템플릿여부 | `templateEmphasizeType` | Radio | N | `false` | `true` / `false` | `pcflag` |
| 템플릿내용 | `templateContent` | Textarea | Y | `""` | 1자 이상 | `templateContent` |
| 버튼 | `buttons` | Table | N | `[]` | 빈 배열 | `buttons` |
| 바로연결 | `quickReplies` | Table | N | `[]` | 빈 배열 | `quickReplies` |
### 9-4. 버튼/이벤트 상세
| 트리거 | 처리 로직 | 비고 |
| ---------------- | ----------------------------------------------- | ------------------------------------ |
| 템플릿등록(외부) | 다이얼로그 open = true, form reset | 진입 시 초기화 |
| 저장 | zod 검증 통과 후 `saveNtftalkTemp` 호출 | 성공 시 `등록되었습니다.` 알림 |
| 저장 성공 | `invalidateQueries([NTFTALK_TEMP])` → 모달 닫기 | 목록 최신화 |
| 저장 실패 | 공통 mutation error 처리 | 에러 메시지 표시 정책 공통 모듈 따름 |
| + 변수추가 | 변수 선택 팝업 open | 9-5 참조 |
### 9-5. 변수추가 팝업 상세
| 항목 | 내용 |
| ----------- | -------------------------------------------------------------------- |
| 팝업명 | 변수 목록 |
| 데이터 소스 | `NtftalkVarApi.getNtftalkVarPage` |
| 조회 조건 | `sort=regDt,desc`, 페이지네이션(`pageIndex/pageSize`) |
| 선택 방식 | 다중 선택 (`RowSelectionState`) |
| [추가] 동작 | 선택된 `varCd`를 줄바꿈(`\n`)으로 `templateContent` 하단에 append |
| 유효성 체크 | 선택 0건: "추가할 변수를 선택해 주세요." / `varCd` 공백 포함 시 에러 |
| [취소] 동작 | 팝업 닫기(선택값 유지 안 함) |
### 9-6. API 명세
| 기능 | Method | URL | Request DTO | Response DTO | 클라이언트 API |
| ----------- | ------ | --------------- | ------------------------ | ------------- | -------------------------------- |
| 템플릿 등록 | POST | `/ntftalk-temp` | `NtftalkTempSavePayload` | `NtftalkTemp` | `NtftalkTempApi.saveNtftalkTemp` |
@@ -1,5 +1,6 @@
import { z } from "zod"; import { z } from "zod";
import type { PageableParams, PageableList } from "@/shared/model";
import type { PageableList, PageableParams } from "@/shared/model";
export interface LwpoCodeParams extends PageableParams { export interface LwpoCodeParams extends PageableParams {
upCd?: string; upCd?: string;
@@ -36,11 +37,11 @@ export interface LwpoCodeDetail extends LwpoCodeFormData {
} }
export const LwpoCodeFormSchema = z.object({ export const LwpoCodeFormSchema = z.object({
lwpoCd: z.string().max(10).nonempty(), lwpoCd: z.string().max(30).nonempty(),
upCd: z.string().max(10).nonempty(), upCd: z.string().max(30).nonempty(),
lwpoCdNm: z.string().max(100).nonempty(), lwpoCdNm: z.string().max(100).nonempty(),
lwpoCdExpln: z.string().max(1000).nullish(), lwpoCdExpln: z.string().max(1000).nullish(),
unit: z.string().max(20).nullish(), unit: z.string().max(50).nullish(),
prntLwpoCd: z.string().max(10).nullish(), prntLwpoCd: z.string().max(10).nullish(),
useYn: z.string(), useYn: z.string(),
sortSeq: z.number(), sortSeq: z.number(),
@@ -38,7 +38,7 @@ export const upCodeFormSchema = z.object({
.nonempty("최소 1자 이상 입력해주세요."), .nonempty("최소 1자 이상 입력해주세요."),
upCdNm: z.string().max(100).nonempty("최소 1자 이상 입력해주세요."), upCdNm: z.string().max(100).nonempty("최소 1자 이상 입력해주세요."),
upCdExpln: z.string().max(1000).nullish(), upCdExpln: z.string().max(1000).nullish(),
cdSe: z.string().max(10).nonempty(), cdSe: z.string().max(30).nonempty(),
siteId: z.string().max(2).nullish(), siteId: z.string().max(2).nullish(),
useYn: z.string(), useYn: z.string(),
delYn: z.string(), delYn: z.string(),
@@ -46,6 +46,7 @@ export interface NtftalkTemp {
templateImageUrl: string; templateImageUrl: string;
inspectionStatus: string; inspectionStatus: string;
inspectionStatusNm: string; inspectionStatusNm: string;
pcflag: string;
status: string; status: string;
statusNm: string; statusNm: string;
createdAt: string; createdAt: string;
@@ -85,6 +86,7 @@ export interface NtftalkTempSavePayload {
templateEmphasizeType: string; templateEmphasizeType: string;
templateImageUrl?: string; templateImageUrl?: string;
inspectionStatus?: string; inspectionStatus?: string;
pcflag?: string;
buttons?: NtftalkBtnTempSavePayload[]; buttons?: NtftalkBtnTempSavePayload[];
quickReplies?: NtftalkQuickTempSavePayload[]; quickReplies?: NtftalkQuickTempSavePayload[];
} }
@@ -94,6 +96,7 @@ export interface NtftalkTempUpdatePayload {
templateContent: string; templateContent: string;
inspectionStatus?: string; inspectionStatus?: string;
status?: string; status?: string;
pcflag?: string;
buttons?: NtftalkBtnTempSavePayload[]; buttons?: NtftalkBtnTempSavePayload[];
quickReplies?: NtftalkQuickTempSavePayload[]; quickReplies?: NtftalkQuickTempSavePayload[];
} }
+8 -8
View File
@@ -102,29 +102,29 @@ function UsersForm<T extends UserSaveData | UserUpdateData>({
return ( return (
authSeCd?.filter( authSeCd?.filter(
(code) => (code) =>
code.lwpoCd === "ROLE_USER1" || code.lwpoCd === "ROLE_USER01" ||
code.lwpoCd === "ROLE_USER2" || code.lwpoCd === "ROLE_USER02" ||
code.lwpoCd === "ROLE_USER3", code.lwpoCd === "ROLE_USER03",
) ?? [] ) ?? []
); );
if (watchOgdpSeCd === "3" || watchOgdpSeCd === "4") if (watchOgdpSeCd === "3" || watchOgdpSeCd === "4")
return ( return (
authSeCd?.filter( authSeCd?.filter(
(code) => (code) =>
code.lwpoCd === "ROLE_USER4" || code.lwpoCd === "ROLE_USER5", code.lwpoCd === "ROLE_USER04" || code.lwpoCd === "ROLE_USER05",
) ?? [] ) ?? []
); );
return []; return [];
}, [authSeCd, watchOgdpSeCd]); }, [authSeCd, watchOgdpSeCd]);
const laeSeCdSelectData = useMemo(() => { const laeSeCdSelectData = useMemo(() => {
if (watchDtlInstCd === "ROLE_USER1") if (watchDtlInstCd === "ROLE_USER01")
return laeSeCd?.filter((code) => code.lwpoCd === "G102") ?? []; return laeSeCd?.filter((code) => code.lwpoCd === "G102") ?? [];
if (watchDtlInstCd === "ROLE_USER2") if (watchDtlInstCd === "ROLE_USER02")
return laeSeCd?.filter((code) => code.lwpoCd === "G101") ?? []; return laeSeCd?.filter((code) => code.lwpoCd === "G101") ?? [];
if (watchDtlInstCd === "ROLE_USER3") if (watchDtlInstCd === "ROLE_USER03")
return laeSeCd?.filter((code) => code.lwpoCd.startsWith("G2")) ?? []; return laeSeCd?.filter((code) => code.lwpoCd.startsWith("G2")) ?? [];
if (watchDtlInstCd === "ROLE_USER4") if (watchDtlInstCd === "ROLE_USER04")
return ( return (
laeSeCd?.filter( laeSeCd?.filter(
(code) => code.lwpoCd.startsWith("G3") && code.lwpoCd.length === 4, (code) => code.lwpoCd.startsWith("G3") && code.lwpoCd.length === 4,
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useCallback, useEffect, useMemo } from "react"; import { useCallback, useEffect, useMemo, useState } from "react";
import { usePathname } from "next/navigation"; import { usePathname } from "next/navigation";
import { import {
@@ -11,6 +11,7 @@ import { useQuery, useQueryClient } from "@tanstack/react-query";
import { ENDPOINT } from "@/shared/config"; import { ENDPOINT } from "@/shared/config";
import { getCookie, useAlertStore, useMenuStore } from "@/shared/lib"; import { getCookie, useAlertStore, useMenuStore } from "@/shared/lib";
import { isVerificationSelectionReportMenu } from "@/shared/lib/verification-selection-report";
import { StatisticsPageLayout } from "@/shared/ui/statistics-page-layout"; import { StatisticsPageLayout } from "@/shared/ui/statistics-page-layout";
import { tokenManager } from "@/entities/auth"; import { tokenManager } from "@/entities/auth";
import type { MenuItem } from "@/entities/menu"; import type { MenuItem } from "@/entities/menu";
@@ -20,6 +21,8 @@ import { getConfig } from "@common/config";
import { getTabStoreState, useTabStore } from "@/store/tab-store"; import { getTabStoreState, useTabStore } from "@/store/tab-store";
import VerificationSelectionReport from "@/components/statistics/VerificationSelectionReport";
const appConfig = getConfig(); const appConfig = getConfig();
const userId = getCookie(appConfig.AUTH_USER_ID ?? ""); const userId = getCookie(appConfig.AUTH_USER_ID ?? "");
const appSiteId = getCookie("site-id-key") ?? ""; const appSiteId = getCookie("site-id-key") ?? "";
@@ -33,6 +36,10 @@ export default function WithBaseLayout({
const pathname = usePathname(); const pathname = usePathname();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
/** 탭 추가 없이 메뉴만 눌렀을 때 패널 유지 (다른 메뉴 클릭해도 유지) */
const [isVerificationSelectionReportPanelOpen, setReportPanelOpen] =
useState(false);
const setCurrentMenuInfo = useMenuStore( const setCurrentMenuInfo = useMenuStore(
(state) => state.setCurrentMenuInfo, (state) => state.setCurrentMenuInfo,
); );
@@ -145,6 +152,12 @@ export default function WithBaseLayout({
const handleMenuClick = useCallback( const handleMenuClick = useCallback(
(item: MenuItem) => { (item: MenuItem) => {
setCurrentMenuInfo(item); setCurrentMenuInfo(item);
if (isVerificationSelectionReportMenu(item)) {
setReportPanelOpen(true);
return;
}
const addTabResult: boolean = addTab(item); const addTabResult: boolean = addTab(item);
// packages/rsone의 스토어에도 동기화 // packages/rsone의 스토어에도 동기화
@@ -153,11 +166,11 @@ export default function WithBaseLayout({
} }
if (!addTabResult) { if (!addTabResult) {
alert(`최대 추가 할 수 있는 화면 수를 초과 하였습니다. alert(`최대 추가 할 수 있는 화면 수(10개)를 \n초과 하였습니다.
기존 화면을 닫은 후 이용해주세요.`); 기존 화면을 닫은 후 이용해주세요.`);
} }
}, },
[setCurrentMenuInfo, addTab, addTabForGrid, alert], [setCurrentMenuInfo, addTab, addTabForGrid, alert, setReportPanelOpen],
); );
return ( return (
@@ -167,7 +180,14 @@ export default function WithBaseLayout({
currentPath={currentPath} currentPath={currentPath}
handleMenuClick={handleMenuClick} handleMenuClick={handleMenuClick}
> >
<StatisticsPageLayout>{children}</StatisticsPageLayout> <div className="flex flex-1 h-full">
{isVerificationSelectionReportPanelOpen && (
<VerificationSelectionReport
onClose={() => setReportPanelOpen(false)}
/>
)}
<StatisticsPageLayout>{children}</StatisticsPageLayout>
</div>
</BaseLayout> </BaseLayout>
); );
} }
+4 -1
View File
@@ -14,7 +14,9 @@
"@common/components": "workspace:*", "@common/components": "workspace:*",
"@common/config": "workspace:*", "@common/config": "workspace:*",
"@common/network": "workspace:*", "@common/network": "workspace:*",
"@rsone/components": "workspace:*", "@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^8.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@faker-js/faker": "^9.9.0", "@faker-js/faker": "^9.9.0",
"@fontsource-variable/noto-sans-kr": "^5.2.5", "@fontsource-variable/noto-sans-kr": "^5.2.5",
"@frontend-opensource/use-react-hooks": "^1.1.4", "@frontend-opensource/use-react-hooks": "^1.1.4",
@@ -29,6 +31,7 @@
"@radix-ui/react-label": "^2.1.2", "@radix-ui/react-label": "^2.1.2",
"@radix-ui/react-slot": "^1.1.2", "@radix-ui/react-slot": "^1.1.2",
"@radix-ui/react-tooltip": "^1.1.8", "@radix-ui/react-tooltip": "^1.1.8",
"@rsone/components": "workspace:*",
"@tanstack/react-query": "^5.67.1", "@tanstack/react-query": "^5.67.1",
"@tanstack/react-query-devtools": "^5.75.5", "@tanstack/react-query-devtools": "^5.75.5",
"@tanstack/react-table": "^8.21.2", "@tanstack/react-table": "^8.21.2",
-9
View File
@@ -1,9 +0,0 @@
const Dashboard = () => {
return (
<div>
Dashboard
</div>
);
};
export default Dashboard;
+14 -4
View File
@@ -35,6 +35,9 @@
.rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-rowtype-biz-sum { .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-rowtype-biz-sum {
@apply !bg-[#ffe9cf]; @apply !bg-[#ffe9cf];
} }
.rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-rowtype-summary {
@apply !bg-[#feee85];
}
.rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-rowtype-other { .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-rowtype-other {
@apply !bg-[#fff7bf]; @apply !bg-[#fff7bf];
} }
@@ -42,6 +45,9 @@
.rg-grid .rg-body .rg-data-cell.rg-cell-rowtype-biz-sum { .rg-grid .rg-body .rg-data-cell.rg-cell-rowtype-biz-sum {
@apply !bg-[#ffe9cf]; @apply !bg-[#ffe9cf];
} }
.rg-grid .rg-body .rg-data-cell.rg-cell-rowtype-summary {
@apply !bg-[#feee85];
}
.rg-grid .rg-body .rg-data-cell.rg-cell-rowtype-other { .rg-grid .rg-body .rg-data-cell.rg-cell-rowtype-other {
@apply !bg-[#fff7bf]; @apply !bg-[#fff7bf];
} }
@@ -49,6 +55,10 @@
.rg-grid .rg-fixed-body .rg-data-row .rg-data-cell.rg-cell-rowtype-biz-sum { .rg-grid .rg-fixed-body .rg-data-row .rg-data-cell.rg-cell-rowtype-biz-sum {
@apply !bg-[#ffe9cf]; @apply !bg-[#ffe9cf];
} }
.rg-grid .rg-fixed-body .rg-table .rg-data-row td.rg-cell-rowtype-summary,
.rg-grid .rg-fixed-body .rg-data-row .rg-data-cell.rg-cell-rowtype-summary {
@apply !bg-[#feee85];
}
.rg-grid .rg-fixed-body .rg-table .rg-data-row td.rg-cell-rowtype-other, .rg-grid .rg-fixed-body .rg-table .rg-data-row td.rg-cell-rowtype-other,
.rg-grid .rg-fixed-body .rg-data-row .rg-data-cell.rg-cell-rowtype-other { .rg-grid .rg-fixed-body .rg-data-row .rg-data-cell.rg-cell-rowtype-other {
@apply !bg-[#fff7bf]; @apply !bg-[#fff7bf];
@@ -56,13 +66,13 @@
/* 진행상황: 소프트 인라인 요약 (툴바와 자연스럽게 blend) */ /* 진행상황: 소프트 인라인 요약 (툴바와 자연스럽게 blend) */
.data-grid-status-bubble { .data-grid-status-bubble {
@apply rounded-lg border border-slate-200/80 bg-slate-50/90 px-4 py-2.5; @apply rounded-lg border border-slate-200/80 bg-white px-8 py-2.5;
box-shadow: none; box-shadow: none;
} }
.data-grid-status-bubble span { .data-grid-status-bubble > span {
@apply text-base text-slate-700; @apply text-xl text-slate-700 font-bold;
} }
.data-grid-status-bubble span + span { .data-grid-status-bubble > span + span {
@apply ml-4 border-l border-slate-200/70 pl-4; @apply ml-4 border-l border-slate-200/70 pl-4;
} }
@@ -25,6 +25,12 @@ interface RealGridDataProviderComparer {
getValue?(row: number, field: string | number): unknown; getValue?(row: number, field: string | number): unknown;
} }
type GridViewWithCheckApi = GridViewWithSetColumns & {
checkItem?: (itemIndex: number, checked: boolean, exclusive?: boolean) => void;
checkRow?: (dataRow: number, checked: boolean, exclusive?: boolean) => void;
checkAll?: (checked: boolean) => void;
};
/** columnInfo → RealGrid DataField 배열 (computed → valueCallback 포함, setFields용) */ /** columnInfo → RealGrid DataField 배열 (computed → valueCallback 포함, setFields용) */
function buildFieldsFromColumns(columns: { fieldName: string; valueType?: ValueType; computed?: import("../type/DataGrid.type").ComputedFieldConfig }[]) { function buildFieldsFromColumns(columns: { fieldName: string; valueType?: ValueType; computed?: import("../type/DataGrid.type").ComputedFieldConfig }[]) {
return columns.map((col) => { return columns.map((col) => {
@@ -72,6 +78,8 @@ const CompactDataGrid = ({
getGridDataRef, getGridDataRef,
cellStyleCallback, cellStyleCallback,
onRowClick, onRowClick,
onItemChecked,
onItemAllChecked,
compactFullWidth = false, compactFullWidth = false,
compactGridHeightClass = "h-[65vh]", compactGridHeightClass = "h-[65vh]",
}: DataGridProps) => { }: DataGridProps) => {
@@ -96,6 +104,32 @@ const CompactDataGrid = ({
(dataProvider as { setRows: (r: unknown[]) => void }).setRows(rowData); (dataProvider as { setRows: (r: unknown[]) => void }).setRows(rowData);
} }
// __checked 플래그(1/true/Y) 기반으로 체크바 상태 동기화
if (showHeaderCheckbox) {
const checkGrid = gridView as GridViewWithCheckApi;
const checkByRowFlag = (value: unknown) =>
value === true ||
value === 1 ||
value === "1" ||
value === "Y" ||
value === "y" ||
value === "true";
try {
checkGrid.checkAll?.(false);
rowData.forEach((row, itemIndex) => {
const checked = checkByRowFlag((row as Record<string, unknown>).__checked);
if (!checked) return;
if (checkGrid.checkItem) {
checkGrid.checkItem(itemIndex, true, false);
return;
}
checkGrid.checkRow?.(itemIndex, true, false);
});
} catch (e) {
console.warn("check sync:", e);
}
}
// setDataComparer로 숫자 정렬 (setFields 미사용 → 데이터 유실·필드 중복 오류 없음) // setDataComparer로 숫자 정렬 (setFields 미사용 → 데이터 유실·필드 중복 오류 없음)
const dp = dataProvider as RealGridDataProviderComparer; const dp = dataProvider as RealGridDataProviderComparer;
if (typeof dp.setDataComparer === "function" && typeof dp.getValue === "function") { if (typeof dp.setDataComparer === "function" && typeof dp.getValue === "function") {
@@ -337,6 +371,32 @@ const CompactDataGrid = ({
}; };
}, [onRowClick]); }, [onRowClick]);
useEffect(() => {
const gridView = gridRef.current?.gridView;
if (!gridView) return;
if (onItemChecked) {
gridView.onItemChecked = (_grid, itemIndex, checked) => {
onItemChecked(itemIndex, checked);
};
} else {
gridView.onItemChecked = undefined;
}
if (onItemAllChecked) {
gridView.onItemAllChecked = (_grid, checked) => {
onItemAllChecked(checked);
};
} else {
gridView.onItemAllChecked = undefined;
}
return () => {
if (gridView.onItemChecked) gridView.onItemChecked = undefined;
if (gridView.onItemAllChecked) gridView.onItemAllChecked = undefined;
};
}, [onItemChecked, onItemAllChecked]);
return ( return (
<div className={`flex flex-col gap-[0.6rem] ${compactFullWidth ? "w-full min-w-0" : "w-1/2"}`}> <div className={`flex flex-col gap-[0.6rem] ${compactFullWidth ? "w-full min-w-0" : "w-1/2"}`}>
<div className={compactGridHeightClass}> <div className={compactGridHeightClass}>
+81 -71
View File
@@ -580,10 +580,10 @@ const DataGrid = ({
) { ) {
const cell = const cell =
worksheet[ worksheet[
XLSX.utils.encode_cell({ XLSX.utils.encode_cell({
r: rowIndex, r: rowIndex,
c: col, c: col,
}) })
]; ];
if ( if (
cell && cell &&
@@ -659,7 +659,7 @@ const DataGrid = ({
const col = range.s.c + colIndex; const col = range.s.c + colIndex;
const cell = const cell =
worksheet[ worksheet[
XLSX.utils.encode_cell({ r: row, c: col }) XLSX.utils.encode_cell({ r: row, c: col })
]; ];
const headerName = const headerName =
headers[colIndex] || `Column${colIndex + 1}`; headers[colIndex] || `Column${colIndex + 1}`;
@@ -783,13 +783,13 @@ const DataGrid = ({
onSorting?: (g: unknown, f: unknown[], d: unknown[]) => boolean; onSorting?: (g: unknown, f: unknown[], d: unknown[]) => boolean;
} }
).onSorting = enableSort ).onSorting = enableSort
? createOnSortingHandler( ? createOnSortingHandler(
columns, columns,
setRowData, setRowData,
sortDirRef, sortDirRef,
originalRowsRef, originalRowsRef,
) )
: () => false; : () => false;
(gridView.displayOptions as DisplayOptions).fitStyle = (gridView.displayOptions as DisplayOptions).fitStyle =
GridFitStyle.EVEN; GridFitStyle.EVEN;
@@ -959,7 +959,7 @@ const DataGrid = ({
) { ) {
( (
column.footer[ column.footer[
index index
] as FooterItemWithCallback ] as FooterItemWithCallback
).valueCallback = ).valueCallback =
footerItem.valueCallback; footerItem.valueCallback;
@@ -1012,11 +1012,11 @@ const DataGrid = ({
getGridDataRef.current = () => { getGridDataRef.current = () => {
const gv = gridRef.current?.gridView as const gv = gridRef.current?.gridView as
| { | {
getDataSource?: () => { getDataSource?: () => {
getRowCount(): number; getRowCount(): number;
getValue(r: number, f: string): unknown; getValue(r: number, f: string): unknown;
}; };
} }
| undefined; | undefined;
if (!gv?.getDataSource) return []; if (!gv?.getDataSource) return [];
const ds = gv.getDataSource(); const ds = gv.getDataSource();
@@ -1189,29 +1189,37 @@ const DataGrid = ({
style={{ display: "none" }} style={{ display: "none" }}
onChange={handleFileChange} onChange={handleFileChange}
/> />
<div className="flex items-center justify-end gap-[0.6rem] px-[1.2rem]"> <div className={`flex items-center ${statusInfo ? 'justify-between' : 'justify-end'} gap-[0.6rem] pr-[1.2rem]`}>
{statusInfo && ( {statusInfo && (
<div className="data-grid-status-bubble flex flex-wrap items-center gap-x-4 gap-y-1"> <div className="data-grid-status-bubble flex flex-wrap items-center gap-x-4 gap-y-1">
<span> <span>
진행상황:{" "} 진행상황:{" "}
{statusInfo.laeSbmsnSttsCd === null || {statusInfo.laeSbmsnSttsCd === null ||
statusInfo.laeSbmsnSttsCd === "0" statusInfo.laeSbmsnSttsCd === "0"
? "미작성" ? "미작성"
: statusInfo.laeSbmsnSttsCd === "1" : statusInfo.laeSbmsnSttsCd === "1"
? "작성중" ? <span className="animate-pulse">작성중</span>
: statusInfo.laeSbmsnSttsCd === "2" : statusInfo.laeSbmsnSttsCd === "2"
? "제출" ? <span className="!text-[#2094fa]">제출</span>
: statusInfo.laeSbmsnSttsCd === "3" : statusInfo.laeSbmsnSttsCd === "3"
? "승인" ? <span className="!text-[#1fd078]">승인</span>
: statusInfo.laeSbmsnSttsCd === "4" : statusInfo.laeSbmsnSttsCd === "4"
? "반려" ? (
: "검증중"} <span className="relative inline-flex !text-[#ff6c64] pr-3">
반려
<span className="absolute -right-0.5 -top-0.5 inline-flex size-[0.6125rem]">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-[#ff6c64] opacity-75" />
<span className="relative inline-flex size-[0.6125rem] rounded-full bg-[#ff6c64]" />
</span>
</span>
)
: <span className="animate-pulse">검증중</span>}
</span> </span>
<span> <span>
제출일:{" "} 제출일:{" "}
{statusInfo.laeSbmsnYmd {statusInfo.laeSbmsnYmd
? statusInfo.laeSbmsnYmd.length === 8 && ? statusInfo.laeSbmsnYmd.length === 8 &&
/^\d{8}$/.test(statusInfo.laeSbmsnYmd) /^\d{8}$/.test(statusInfo.laeSbmsnYmd)
? `${statusInfo.laeSbmsnYmd.slice(0, 4)}-${statusInfo.laeSbmsnYmd.slice(4, 6)}-${statusInfo.laeSbmsnYmd.slice(6, 8)}` ? `${statusInfo.laeSbmsnYmd.slice(0, 4)}-${statusInfo.laeSbmsnYmd.slice(4, 6)}-${statusInfo.laeSbmsnYmd.slice(6, 8)}`
: statusInfo.laeSbmsnYmd : statusInfo.laeSbmsnYmd
: "미제출"} : "미제출"}
@@ -1228,26 +1236,28 @@ const DataGrid = ({
</span> </span>
</div> </div>
)} )}
{isExcelImport && ( <div className="flex items-center gap-[0.6rem]">
<Button {isExcelImport && (
className="h-[3.2rem] w-[96px] bg-gradient-green px-6 hover:bg-gradient-green-hover" <Button
type="button" className="h-[3.2rem] w-[96px] bg-gradient-green px-6 hover:bg-gradient-green-hover"
onClick={importExcel} type="button"
> onClick={importExcel}
<i className="diveicon di-file-excel" /> >
<span>가져오기</span> <i className="diveicon di-file-excel" />
</Button> <span>가져오기</span>
)} </Button>
{isExcelExport && ( )}
<Button {isExcelExport && (
className="h-[3.2rem] w-[96px] bg-gradient-green px-6 hover:bg-gradient-green-hover" <Button
type="button" className="h-[3.2rem] w-[96px] bg-gradient-green px-6 hover:bg-gradient-green-hover"
onClick={exportExcel} type="button"
> onClick={exportExcel}
<i className="diveicon di-file-excel" /> >
<span>내보내기</span> <i className="diveicon di-file-excel" />
</Button> <span>내보내기</span>
)} </Button>
)}
</div>
</div> </div>
<div style={{ height: `${gridHeight}vh` }}> <div style={{ height: `${gridHeight}vh` }}>
<RealGridReact <RealGridReact
@@ -1266,24 +1276,24 @@ const DataGrid = ({
) => boolean; ) => boolean;
} }
).onSorting = enableSort ).onSorting = enableSort
? createOnSortingHandler( ? createOnSortingHandler(
columns, columns,
setRowData, setRowData,
sortDirRef, sortDirRef,
originalRowsRef, originalRowsRef,
) )
: () => false; : () => false;
const dataProvider = gridRef.current const dataProvider = gridRef.current
?.dataProvider as unknown as ?.dataProvider as unknown as
| { | {
setFields?(f: unknown[]): void; setFields?(f: unknown[]): void;
setRows?( setRows?(
r: Record<string, string | number>[], r: Record<string, string | number>[],
): void; ): void;
getJsonRow?( getJsonRow?(
r: number, r: number,
): Record<string, unknown>; ): Record<string, unknown>;
} }
| undefined; | undefined;
if (dataProvider?.setFields) { if (dataProvider?.setFields) {
dataProvider.setFields( dataProvider.setFields(
@@ -1436,14 +1446,14 @@ const DataGrid = ({
})} })}
footer={ footer={
column.footer && column.footer &&
!Array.isArray(column.footer) !Array.isArray(column.footer)
? { ? {
text: column.footer.text, text: column.footer.text,
expression: expression:
column.footer.expression, column.footer.expression,
numberFormat: numberFormat:
column.footer.numberFormat, column.footer.numberFormat,
} }
: undefined : undefined
} }
mergeRule={ mergeRule={
@@ -4,15 +4,20 @@ import { useState } from "react";
import { Button, Dialog, DialogContent, DialogHeader, DialogTitle } from "@common/components"; import { Button, Dialog, DialogContent, DialogHeader, DialogTitle } from "@common/components";
import SidoSggFacilityNameSearchForm from "./SidoSggFacilityNameSearchForm"; import SidoSggFacilityNameSearchForm from "./SidoSggFacilityNameSearchForm";
import type { SearchFormValues } from "../type/SearchForm.type";
type GridTopActionButtonProps = { type GridTopActionButtonProps = {
text: string; text: string;
onClick?: (helpers: { openDialog: (title?: string) => void; closeDialog: () => void }) => void; onClick?: (helpers: { openDialog: (title?: string) => void; closeDialog: () => void }) => void;
/** 상위 화면 검색 통계연도 — 시설 조회 다이얼로그에 전달 */ /** 상위 화면 검색 통계연도 — 시설 조회 다이얼로그에 전달 */
statsYr?: string; statsYr?: string;
/** 상위 화면 최근 검색조건 */
initialSearchValues?: Pick<SearchFormValues, "sido" | "gugun" | "bsnmCd"> | null;
/** 다이얼로그 저장 성공 후 부모 갱신 */
onSaveSuccess?: () => Promise<void> | void;
}; };
const GridTopActionButton = ({ text, onClick, statsYr }: GridTopActionButtonProps) => { const GridTopActionButton = ({ text, onClick, statsYr, initialSearchValues, onSaveSuccess }: GridTopActionButtonProps) => {
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [title, setTitle] = useState(text); const [title, setTitle] = useState(text);
@@ -41,7 +46,11 @@ const GridTopActionButton = ({ text, onClick, statsYr }: GridTopActionButtonProp
<DialogHeader> <DialogHeader>
<DialogTitle>{title}</DialogTitle> <DialogTitle>{title}</DialogTitle>
</DialogHeader> </DialogHeader>
<SidoSggFacilityNameSearchForm statsYr={statsYr} /> <SidoSggFacilityNameSearchForm
statsYr={statsYr}
initialSearchValues={initialSearchValues}
onSaveSuccess={onSaveSuccess}
/>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</> </>
+51 -39
View File
@@ -89,6 +89,7 @@ const SearchForm = (props: SearchFormProps = {}) => {
fctName: props.defaultValues?.fctName || "", fctName: props.defaultValues?.fctName || "",
bsnmCd: props.defaultValues?.bsnmCd || "", bsnmCd: props.defaultValues?.bsnmCd || "",
isDetail: false, isDetail: false,
isSummary: props.defaultValues?.isSummary || "",
}); });
const sggKey: [string, string, string, string] | null = const sggKey: [string, string, string, string] | null =
@@ -132,6 +133,7 @@ const SearchForm = (props: SearchFormProps = {}) => {
fctName: "", fctName: "",
bsnmCd: "", bsnmCd: "",
isDetail: false, isDetail: false,
isSummary: "",
}; };
setValues(resetValues); setValues(resetValues);
props.onReset?.(); props.onReset?.();
@@ -153,7 +155,7 @@ const SearchForm = (props: SearchFormProps = {}) => {
const selectedBsnm = const selectedBsnm =
value === "ALL" value === "ALL"
? sidoList?.data.sidoList.find((v) => v.sido === values.sido) ? sidoList?.data.sidoList.find((v) => v.sido === values.sido)
?.bsnmCd || "" ?.bsnmCd || ""
: listForBsnm.find((v) => v.gugun === value)?.bsnmCd || ""; : listForBsnm.find((v) => v.gugun === value)?.bsnmCd || "";
setValues((prev) => ({ setValues((prev) => ({
@@ -248,12 +250,35 @@ const SearchForm = (props: SearchFormProps = {}) => {
</Select> </Select>
</div> </div>
)} )}
{mergedProps.fctName && (
<div className="flex items-center gap-2">
<Label
htmlFor="fctNmSearchInput"
className="mr-2 text-label"
>
시설명
</Label>
<Input
className="mr-4 h-[3.2rem] w-[14rem] rounded-sm !text-[1.3rem]"
id="fctNmSearchInput"
value={values.fctName}
onChange={(e) =>
setValues({
...values,
fctName: e.target.value,
})
}
autoComplete="off"
/>
</div>
)}
{mergedProps.isDetail && ( {mergedProps.isDetail && (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Label className="text-label"> <Label className="text-label cursor-pointer" htmlFor="isDetail">
세부 데이터 포함 세부 데이터 포함
</Label> </Label>
<Checkbox <Checkbox
id="isDetail"
checked={values.isDetail} checked={values.isDetail}
onCheckedChange={(value) => onCheckedChange={(value) =>
setValues({ setValues({
@@ -264,6 +289,30 @@ const SearchForm = (props: SearchFormProps = {}) => {
/> />
</div> </div>
)} )}
{mergedProps.isSummary && (
<div className="flex items-center gap-2">
<Label className="text-label cursor-pointer">
요약표 포함
</Label>
<Select
value={values.isSummary}
onValueChange={(value) =>
setValues({ ...values, isSummary: value })
}
>
<SelectTrigger className="w-[10rem]">
<SelectValue placeholder="선택 안함"></SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="ALL">선택 안함</SelectItem>
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((i) => (
<SelectItem value={i.toString()} key={i.toString()}>{`${i}개년`}</SelectItem>
))
}
</SelectContent>
</Select>
</div>
)}
{mergedProps.order && ( {mergedProps.order && (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Label className="text-label">차수</Label> <Label className="text-label">차수</Label>
@@ -296,43 +345,6 @@ const SearchForm = (props: SearchFormProps = {}) => {
</Button> </Button>
</div> </div>
</div> </div>
{(mergedProps.fctName || mergedProps.userMenual) && (
<div className="flex items-center p-2">
{mergedProps.fctName && (
<div className="flex items-center gap-2">
<Label
htmlFor="fctNmSearchInput"
className="mr-2 text-label"
>
시설명
</Label>
<Input
className="mr-4 h-[3.2rem] w-[14rem] rounded-sm !text-[1.3rem]"
id="fctNmSearchInput"
value={values.fctName}
onChange={(e) =>
setValues({
...values,
fctName: e.target.value,
})
}
autoComplete="off"
/>
</div>
)}
{mergedProps.userMenual && (
<div className="ml-auto flex items-center gap-2">
<Button
className="h-[3.2rem] w-[124px]"
type="button"
>
<i className="diveicon di-person-fill" />
사용자 메뉴얼
</Button>
</div>
)}
</div>
)}
</form> </form>
</div> </div>
); );
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useState } from "react"; import { useEffect, useRef, useState } from "react";
import useSWR from "swr"; import useSWR from "swr";
import { ValueType } from "realgrid"; import { ValueType } from "realgrid";
@@ -29,8 +29,13 @@ import type { ColumnInfo } from "../type/DataGrid.type";
import type { import type {
SeweragePipeFacilitiesListRequest, SeweragePipeFacilitiesListRequest,
SeweragePipeFacilityAdminAreaListRequest, SeweragePipeFacilityAdminAreaListRequest,
SeweragePipeFactConnectionSaveRequest,
SeweragePipeFactConnectionSaveItem,
} from "@/entities/statistics/model/input/statistics-sewage-pipe-input-interface"; } from "@/entities/statistics/model/input/statistics-sewage-pipe-input-interface";
import { statisticsInputSewPipeApiService } from "@/entities/statistics/api/input/statistics-sewage-pipe-input-service"; import { statisticsInputSewPipeApiService } from "@/entities/statistics/api/input/statistics-sewage-pipe-input-service";
import type { SearchFormValues } from "../type/SearchForm.type";
import { doNameList } from "../util/column/input/DoList";
import { getUserInfo } from "../../../../../packages/common/components/src/api";
/** 다이얼로그 좌측: 처리시설 정보 (순번 없음) */ /** 다이얼로그 좌측: 처리시설 정보 (순번 없음) */
const treatmentFacilityColumnInfo: ColumnInfo = { const treatmentFacilityColumnInfo: ColumnInfo = {
@@ -48,21 +53,35 @@ const treatmentFacilityColumnInfo: ColumnInfo = {
editable: false, editable: false,
}, },
{ {
name: "fctNm", name: "fcltNm",
fieldName: "fctNm", fieldName: "fcltNm",
header: { text: "시설명" }, header: { text: "시설명" },
editable: false, editable: false,
}, },
{ {
name: "fctCpc", name: "fcltCd",
fieldName: "fctCpc", fieldName: "fcltCd",
header: { text: "시설코드" },
editable: false,
visible: false,
},
{
name: "fcltSn",
fieldName: "fcltSn",
header: { text: "시설일련번호" },
editable: false,
visible: false,
},
{
name: "fcltCpct",
fieldName: "fcltCpct",
header: { text: "시설용량(m³/일)" }, header: { text: "시설용량(m³/일)" },
valueType: ValueType.NUMBER, valueType: ValueType.NUMBER,
dataFormat: "#,##0", dataFormat: "#,##0",
editable: false, editable: false,
}, },
], ],
columnLayout: ["ctpvNm", "sggNm", "fctNm", "fctCpc"], columnLayout: ["ctpvNm", "sggNm", "fcltNm", "fcltCpct", "fcltCd"],
}; };
/** 다이얼로그 우측: 행정구역 정보 (순번 없음, 헤더 체크박스는 showHeaderCheckbox) */ /** 다이얼로그 우측: 행정구역 정보 (순번 없음, 헤더 체크박스는 showHeaderCheckbox) */
@@ -103,12 +122,26 @@ const getSggAllListFetcher = async (
type SidoSggFacilityNameSearchFormProps = { type SidoSggFacilityNameSearchFormProps = {
/** 상위(SewagePipeInp 등) 검색 조건의 통계연도 — facilitiesList 등 API 필수값 */ /** 상위(SewagePipeInp 등) 검색 조건의 통계연도 — facilitiesList 등 API 필수값 */
statsYr?: string; statsYr?: string;
/** 상위(SewagePipeInp) 마지막 검색 조건 */
initialSearchValues?: Pick<SearchFormValues, "sido" | "gugun" | "bsnmCd"> | null;
/** 저장 성공 후 부모 탭 데이터 재조회 훅 */
onSaveSuccess?: () => Promise<void> | void;
}; };
const SidoSggFacilityNameSearchForm = ({ const SidoSggFacilityNameSearchForm = ({
statsYr, statsYr,
initialSearchValues,
onSaveSuccess,
}: SidoSggFacilityNameSearchFormProps) => { }: SidoSggFacilityNameSearchFormProps) => {
const { setMessage: alert } = useAlertStore((state) => state); const { setMessage: alert } = useAlertStore((state) => state);
const initialSidoValue =
initialSearchValues?.sido && initialSearchValues.sido !== "ALL"
? initialSearchValues.sido
: "ALL";
const initialGugunValue =
initialSearchValues?.gugun && initialSearchValues.gugun !== "ALL"
? initialSearchValues.gugun
: "ALL";
const { data: sidoList } = useSWR<ApiResponse<SearchCondition>>( const { data: sidoList } = useSWR<ApiResponse<SearchCondition>>(
"sido-list", "sido-list",
@@ -134,9 +167,9 @@ const SidoSggFacilityNameSearchForm = ({
}, },
); );
const [sido, setSido] = useState<string>("ALL"); const [sido, setSido] = useState<string>(initialSidoValue);
const [gugun, setGugun] = useState<string>("ALL"); const [gugun, setGugun] = useState<string>(initialGugunValue);
const [fctNm, setFctNm] = useState<string>(""); const [fcltNm, setFcltNm] = useState<string>("");
const [isLoading, setIsLoading] = useState<boolean>(false); const [isLoading, setIsLoading] = useState<boolean>(false);
const [treatmentFacilityRows, setTreatmentFacilityRows] = useState< const [treatmentFacilityRows, setTreatmentFacilityRows] = useState<
@@ -145,6 +178,10 @@ const SidoSggFacilityNameSearchForm = ({
const [adminRegionRows, setAdminRegionRows] = useState< const [adminRegionRows, setAdminRegionRows] = useState<
Record<string, string | number>[] Record<string, string | number>[]
>([]); >([]);
const [selectedFacilityRow, setSelectedFacilityRow] = useState<
Record<string, string | number> | null
>(null);
const didAutoFetchRef = useRef(false);
const sggKey: [string, string] | null = const sggKey: [string, string] | null =
sido && sido !== "ALL" ? ["sgg-all", sido] : null; sido && sido !== "ALL" ? ["sgg-all", sido] : null;
@@ -198,7 +235,7 @@ const SidoSggFacilityNameSearchForm = ({
alert("시도를 선택해주세요."); alert("시도를 선택해주세요.");
return; return;
} }
const trimmedFclty = fctNm.trim(); const trimmedFclty = fcltNm.trim();
const sewerBzmnCd = resolveSewerBzmnCd(); const sewerBzmnCd = resolveSewerBzmnCd();
@@ -225,13 +262,15 @@ const SidoSggFacilityNameSearchForm = ({
list.map((item) => ({ list.map((item) => ({
ctpvNm: item.ctpvNm, ctpvNm: item.ctpvNm,
sggNm: item.sggNm, sggNm: item.sggNm,
fctNm: item.bscFctNm, fcltNm: item.fcltNm,
fctCpc: item.fctCpc, fcltCpct: item.fcltCpct,
bscFctCd: item.bscFctCd, fcltCd: item.fcltCd,
fcltSn: item.fcltSn,
admdstCd: item.admdstCd, admdstCd: item.admdstCd,
statsYr: item.statsYr, statsYr: item.statsYr,
})), })),
); );
setSelectedFacilityRow(null);
setAdminRegionRows([]); setAdminRegionRows([]);
} catch { } catch {
alert("처리시설 목록 조회 중 오류가 발생했습니다."); alert("처리시설 목록 조회 중 오류가 발생했습니다.");
@@ -247,7 +286,7 @@ const SidoSggFacilityNameSearchForm = ({
alert("상단에서 통계연도로 조회한 뒤 이용해 주세요."); alert("상단에서 통계연도로 조회한 뒤 이용해 주세요.");
return; return;
} }
const swtrmtFcltCd = String(row.bscFctCd ?? "").trim(); const swtrmtFcltCd = String(row.fcltCd ?? "").trim();
if (!swtrmtFcltCd) { if (!swtrmtFcltCd) {
alert("처리시설 코드가 없습니다."); alert("처리시설 코드가 없습니다.");
return; return;
@@ -261,13 +300,14 @@ const SidoSggFacilityNameSearchForm = ({
const params: SeweragePipeFacilityAdminAreaListRequest = { const params: SeweragePipeFacilityAdminAreaListRequest = {
statsYr: statsYr.trim(), statsYr: statsYr.trim(),
swtrmtFcltCd, swtrmtFcltCd,
sewerBzmnCd: String(row.admdstCd ?? "").trim(), sewerBzmnCd: initialSearchValues?.bsnmCd || '',
ctpvNm, ctpvNm,
sggNm, ...(doNameList.includes(ctpvNm) ? { sggNm } : {}),
}; };
try { try {
setIsLoading(true); setIsLoading(true);
setSelectedFacilityRow(row);
const response = const response =
await statisticsInputSewPipeApiService.getFacilityAdminAreaList( await statisticsInputSewPipeApiService.getFacilityAdminAreaList(
params, params,
@@ -283,6 +323,8 @@ const SidoSggFacilityNameSearchForm = ({
sggNm: item.sggNm, sggNm: item.sggNm,
emdNm: item.admdstNm, emdNm: item.admdstNm,
admdstCd: item.admdstCd, admdstCd: item.admdstCd,
isConnection: item.isConnection,
__checked: item.isConnection === "1" ? "1" : "0",
})), })),
); );
} catch { } catch {
@@ -293,9 +335,172 @@ const SidoSggFacilityNameSearchForm = ({
}; };
const handleSaveAdminRegions = () => { const handleSaveAdminRegions = () => {
alert("저장 API 연동 예정입니다."); if (!statsYr?.trim()) {
alert("상단에서 통계연도로 조회한 뒤 이용해 주세요.");
return;
}
if (!selectedFacilityRow) {
alert("처리시설을 먼저 선택해주세요.");
return;
}
const hasChanged = adminRegionRows.some(
(row) =>
(row.__checked === "1" && row.isConnection !== "1") ||
(row.__checked !== "1" && row.isConnection === "1"),
);
const saveList: SeweragePipeFactConnectionSaveItem[] = adminRegionRows
.filter((row) => row.__checked === "1")
.map((row) => ({
admdstCd: String(row.admdstCd ?? ""),
admdstNm: String(row.emdNm ?? ""),
}))
.filter((row) => row.admdstCd && row.admdstNm);
const deleteList = adminRegionRows
.filter((row) => row.__checked !== "1" && row.isConnection === "1")
.map((row) => String(row.admdstCd ?? ""))
.filter(Boolean);
if (!hasChanged) {
alert("변경된 연결 정보가 없습니다.");
return;
}
const run = async () => {
try {
setIsLoading(true);
const userInfo = await getUserInfo();
const request: SeweragePipeFactConnectionSaveRequest = {
ctpvNm: String(selectedFacilityRow.ctpvNm ?? ""),
sggNm: String(selectedFacilityRow.sggNm ?? ""),
fcltSn: String(selectedFacilityRow.fcltSn ?? ""),
statsYr: statsYr.trim(),
swtrmtFcltCd: String(selectedFacilityRow.fcltCd ?? ""),
swtrmtFcltNm: String(selectedFacilityRow.fcltNm ?? ""),
prcsFcltCpct: Number(selectedFacilityRow.fcltCpct ?? 0),
sewerBzmnCd: initialSearchValues?.bsnmCd?.trim() ?? "",
userId: userInfo.userUnqId,
saveList,
deleteList,
};
const response =
await statisticsInputSewPipeApiService.saveFactConnection(
request,
);
if (response.status !== "success") {
alert(response.message ?? "연결관계 저장에 실패했습니다.");
return;
}
setAdminRegionRows((prev) =>
prev.map((row) => ({
...row,
isConnection: row.__checked === "1" ? "1" : "0",
})),
);
await onSaveSuccess?.();
alert("저장되었습니다.");
} catch {
alert("연결관계 저장 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
};
void run();
}; };
const handleAdminRegionItemChecked = (
itemIndex: number,
checked: boolean,
) => {
setAdminRegionRows((prev) =>
prev.map((row, idx) =>
idx === itemIndex
? { ...row, __checked: checked ? "1" : "0" }
: row,
),
);
};
const handleAdminRegionItemAllChecked = (checked: boolean) => {
setAdminRegionRows((prev) =>
prev.map((row) => ({ ...row, __checked: checked ? "1" : "0" })),
);
};
useEffect(() => {
if (!initialSearchValues?.sido || initialSearchValues.sido === "ALL") return;
setSido(initialSearchValues.sido);
setGugun(
initialSearchValues.gugun && initialSearchValues.gugun !== "ALL"
? initialSearchValues.gugun
: "ALL",
);
}, [initialSearchValues?.sido, initialSearchValues?.gugun]);
useEffect(() => {
if (didAutoFetchRef.current) return;
if (!statsYr?.trim()) return;
if (!initialSearchValues?.sido || initialSearchValues.sido === "ALL") return;
const nextSido = initialSearchValues.sido;
const nextGugun =
initialSearchValues.gugun && initialSearchValues.gugun !== "ALL"
? initialSearchValues.gugun
: "ALL";
didAutoFetchRef.current = true;
setSido(nextSido);
setGugun(nextGugun);
const params: SeweragePipeFacilitiesListRequest = {
statsYr: statsYr.trim(),
...(initialSearchValues.bsnmCd?.trim()
? { sewerBzmnCd: initialSearchValues.bsnmCd.trim() }
: {}),
ctpvNm: nextSido,
...(nextGugun !== "ALL" ? { sggNm: nextGugun } : {}),
};
const run = async () => {
try {
setIsLoading(true);
const response =
await statisticsInputSewPipeApiService.getFacilitiesList(params);
if (response.status !== "success") {
alert(response.message ?? "처리시설 목록 조회에 실패했습니다.");
return;
}
const list = response.data ?? [];
setTreatmentFacilityRows(
list.map((item) => ({
ctpvNm: item.ctpvNm,
sggNm: item.sggNm,
fcltNm: item.fcltNm,
fcltCpct: item.fcltCpct,
fcltCd: item.fcltCd,
fcltSn: item.fcltSn,
admdstCd: item.admdstCd,
statsYr: item.statsYr,
})),
);
setSelectedFacilityRow(null);
setAdminRegionRows([]);
} catch {
alert("처리시설 목록 조회 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
};
void run();
}, [statsYr, initialSearchValues, alert]);
return ( return (
<div className="flex flex-col gap-4 pt-2"> <div className="flex flex-col gap-4 pt-2">
<form onSubmit={handleSubmit} className="flex flex-col gap-4"> <form onSubmit={handleSubmit} className="flex flex-col gap-4">
@@ -346,8 +551,8 @@ const SidoSggFacilityNameSearchForm = ({
<Label className="shrink-0 text-label">시설명</Label> <Label className="shrink-0 text-label">시설명</Label>
<Input <Input
className="min-w-[12rem] flex-1" className="min-w-[12rem] flex-1"
value={fctNm} value={fcltNm}
onChange={(e) => setFctNm(e.target.value)} onChange={(e) => setFcltNm(e.target.value)}
placeholder="시설명 입력" placeholder="시설명 입력"
/> />
</div> </div>
@@ -396,6 +601,8 @@ const SidoSggFacilityNameSearchForm = ({
rowData={adminRegionRows} rowData={adminRegionRows}
setRowData={setAdminRegionRows} setRowData={setAdminRegionRows}
showHeaderCheckbox showHeaderCheckbox
onItemChecked={handleAdminRegionItemChecked}
onItemAllChecked={handleAdminRegionItemAllChecked}
compactFullWidth compactFullWidth
// compactGridHeightClass="h-[min(40vh,28rem)] min-h-[16rem]" // compactGridHeightClass="h-[min(40vh,28rem)] min-h-[16rem]"
/> />
@@ -1,5 +1,16 @@
"use client"; "use client";
import {
type Dispatch,
type MutableRefObject,
type SetStateAction,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import type { RealGridReact } from "realgrid-react";
import { import {
Button, Button,
Dialog, Dialog,
@@ -8,25 +19,477 @@ import {
DialogFooter, DialogFooter,
DialogHeader, DialogHeader,
DialogTitle, DialogTitle,
LoadingWithAnimation,
} from "@common/components"; } from "@common/components";
import DataGrid from "@/components/module/DataGrid";
import { VerificationResultHistoryPagination } from "@/components/module/VerificationResultHistoryPagination";
import type { CellEditedCallbackParams, ColumnInfo } from "@/components/type/DataGrid.type";
import { statisticsApi } from "@/entities/statistics/api/statistics-service";
import type { VerificationResultListRequest, VerificationResultReportItem } from "@/entities/statistics/model/statistics-interface";
import { useAlertStore } from "@/shared/lib";
type VerificationResultGridRow = Record<string, string | number>;
export type VerificationExceptionSubmitItem = {
vrfcSn: number;
prcsOpnnExpln: string;
};
type GridViewWithCheckItem = {
checkItem?: (itemIndex: number, checked: boolean, exclusive?: boolean) => void;
};
function setRowCheckByItemIndex(
gridRef: MutableRefObject<RealGridReact | null>,
itemIndex: number,
checked: boolean,
) {
const gv = gridRef.current?.gridView as GridViewWithCheckItem | undefined;
try {
gv?.checkItem?.(itemIndex, checked, false);
} catch {
/* RealGrid 체크 API 미지원 등 */
}
}
const PRCS_YN_LABEL: Record<string, string> = {
"0": "미통과",
"1": "통과",
"2": "예외처리",
"3": "반려",
};
/** History와 동일 + 편집 가능한 처리의견(예외사유, API 필드명 `prcsOpnnExpln`과 동일) */
const verificationSubmitResultColumnInfo: ColumnInfo = {
columns: [
{ name: "ctpvNm", fieldName: "ctpvNm", header: { text: "시도" }, editable: false },
{ name: "sggNm", fieldName: "sggNm", header: { text: "시군구" }, editable: false },
{ name: "vrfcTrgtNm", fieldName: "vrfcTrgtNm", header: { text: "검증대상" }, editable: false },
{ name: "rsnExpln", fieldName: "rsnExpln", header: { text: "사유" }, editable: false },
{ name: "nowVlCn", fieldName: "nowVlCn", header: { text: "입력값" }, editable: false },
{ name: "compVlCn", fieldName: "compVlCn", header: { text: "기준값" }, editable: false },
{ name: "prcsYn", fieldName: "prcsYn", header: { text: "처리여부" }, editable: false },
{ name: "pbcpAprvYn", fieldName: "pbcpAprvYn", header: { text: "공단승인여부" }, editable: false },
{ name: "regDt", fieldName: "regDt", header: { text: "등록일시" }, editable: false },
{ name: "mdfcnDt", fieldName: "mdfcnDt", header: { text: "갱신일시" }, editable: false },
{
name: "prcsOpnnExpln",
fieldName: "prcsOpnnExpln",
header: { text: "예외사유" },
editable: true,
},
],
columnLayout: [
"ctpvNm",
"sggNm",
"vrfcTrgtNm",
"rsnExpln",
"nowVlCn",
"compVlCn",
"prcsYn",
"pbcpAprvYn",
"regDt",
"mdfcnDt",
"prcsOpnnExpln",
],
};
export interface VerificationResultDialogQueryContext {
sewerBzmnCd: string;
ctpvNm: string;
sggNm: string;
statsYr: string;
statsCd: string;
}
export interface VerificationResultDialogProps { export interface VerificationResultDialogProps {
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
queryContext?: VerificationResultDialogQueryContext | null;
title?: string;
emptyMessage?: string;
} }
export function VerificationResultDialog({ export function VerificationResultDialog({
open, open,
onOpenChange, onOpenChange,
queryContext,
title = "검증 결과",
emptyMessage = "표시할 검증 결과가 없습니다.",
}: VerificationResultDialogProps) { }: VerificationResultDialogProps) {
/** 부모가 매 렌더마다 새 객체를 넘기면 queryContext 참조만 바뀌어 loadInitial이 재실행되므로 필드 값 기준으로 안정화 */
const stableQueryContext = useMemo((): VerificationResultDialogQueryContext | null => {
if (!queryContext) return null;
return queryContext;
}, [
queryContext?.sewerBzmnCd,
queryContext?.ctpvNm,
queryContext?.sggNm,
queryContext?.statsYr,
queryContext?.statsCd,
]);
const [normalPageIndex, setNormalPageIndex] = useState(0);
const [imrPageIndex, setImrPageIndex] = useState(0);
const [normalPageCount, setNormalPageCount] = useState(1);
const [imrPageCount, setImrPageCount] = useState(1);
const [normalLoading, setNormalLoading] = useState(false);
const [imrLoading, setImrLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [normalRows, setNormalRows] = useState<VerificationResultGridRow[]>([]);
const [imrRows, setImrRows] = useState<VerificationResultGridRow[]>([]);
const [normalCheckedIndices, setNormalCheckedIndices] = useState<Set<number>>(
() => new Set(),
);
const [imrCheckedIndices, setImrCheckedIndices] = useState<Set<number>>(() => new Set());
const normalGridRef = useRef<RealGridReact | null>(null);
const imrGridRef = useRef<RealGridReact | null>(null);
const alert = useAlertStore((state) => state.setMessage);
const onNormalPrcsOpnnExplnEdited = useCallback((params: CellEditedCallbackParams) => {
if (params.fieldName !== "prcsOpnnExpln") return;
const text = String(params.newValue ?? "");
const hasValue = text.trim().length > 0;
/** DataGrid는 onCellEdited 시 React rowData를 갱신하지 않아, 제출용 상태를 여기서 맞춤 */
setNormalRows((prev) => {
const next = [...prev];
const row = next[params.itemIndex];
if (!row) return prev;
next[params.itemIndex] = { ...row, prcsOpnnExpln: text };
return next;
});
setRowCheckByItemIndex(normalGridRef, params.itemIndex, hasValue);
setNormalCheckedIndices((prev) => {
const next = new Set(prev);
if (hasValue) next.add(params.itemIndex);
else next.delete(params.itemIndex);
return next;
});
}, []);
const onImrPrcsOpnnExplnEdited = useCallback((params: CellEditedCallbackParams) => {
if (params.fieldName !== "prcsOpnnExpln") return;
const text = String(params.newValue ?? "");
const hasValue = text.trim().length > 0;
setImrRows((prev) => {
const next = [...prev];
const row = next[params.itemIndex];
if (!row) return prev;
next[params.itemIndex] = { ...row, prcsOpnnExpln: text };
return next;
});
setRowCheckByItemIndex(imrGridRef, params.itemIndex, hasValue);
setImrCheckedIndices((prev) => {
const next = new Set(prev);
if (hasValue) next.add(params.itemIndex);
else next.delete(params.itemIndex);
return next;
});
}, []);
const resetState = useCallback(() => {
setNormalPageIndex(0);
setImrPageIndex(0);
setNormalPageCount(1);
setImrPageCount(1);
setNormalLoading(false);
setImrLoading(false);
setErrorMessage(null);
setNormalRows([]);
setImrRows([]);
setNormalCheckedIndices(new Set());
setImrCheckedIndices(new Set());
}, []);
const mapItemToRow = useCallback((item: VerificationResultReportItem): VerificationResultGridRow => {
return {
vrfcSn: item.vrfcSn,
ctpvNm: item.ctpvNm,
sggNm: item.sggNm,
vrfcTrgtNm: item.vrfcTrgtNm,
rsnExpln: item.rsnExpln,
nowVlCn: item.nowVlCn ?? "-",
compVlCn: item.compVlCn ?? "-",
prcsYn: PRCS_YN_LABEL[item.prcsYn] ?? item.prcsYn,
pbcpAprvYn: item.pbcpAprvYn,
regDt: (item.regDt ?? "").slice(0, 16),
mdfcnDt: (item.mdfcnDt ?? "").slice(0, 16),
prcsOpnnExpln: item.prcsOpnnExpln ?? "",
};
}, []);
const fetchVerificationResultPage = useCallback(
async (vrfcMthdCd: "NV" | "IMR", pageIndex: number) => {
if (!stableQueryContext) return null;
const param: VerificationResultListRequest = {
sewerBzmnCd: stableQueryContext.sewerBzmnCd,
ctpvNm: stableQueryContext.ctpvNm,
sggNm: stableQueryContext.sggNm,
statsYr: stableQueryContext.statsYr,
statsCd: stableQueryContext.statsCd,
pbcpAprvYn: "N",
vrfcMthdCd,
prcsYnList: "0",
page: pageIndex + 1,
size: 10000,
};
return statisticsApi.getVerificationResultList(param);
},
[stableQueryContext],
);
const loadInitial = useCallback(async () => {
if (!stableQueryContext) {
setErrorMessage("조회 조건이 없어 검증 결과를 불러올 수 없습니다.");
return;
}
setErrorMessage(null);
setNormalLoading(true);
setImrLoading(true);
setNormalPageIndex(0);
setImrPageIndex(0);
try {
const [nvRes, imrRes] = await Promise.all([
fetchVerificationResultPage("NV", 0),
fetchVerificationResultPage("IMR", 0),
]);
const nvList = nvRes?.data?.verifyResultList ?? [];
const imrList = imrRes?.data?.verifyResultList ?? [];
setNormalRows(nvList.map(mapItemToRow));
setImrRows(imrList.map(mapItemToRow));
setNormalPageCount(nvRes?.data?.pageInfo?.totalPages ?? 1);
setImrPageCount(imrRes?.data?.pageInfo?.totalPages ?? 1);
} catch {
setNormalRows([]);
setImrRows([]);
setNormalPageCount(1);
setImrPageCount(1);
setErrorMessage("검증 결과 조회 중 오류가 발생했습니다.");
} finally {
setNormalLoading(false);
setImrLoading(false);
setNormalCheckedIndices(new Set());
setImrCheckedIndices(new Set());
}
}, [fetchVerificationResultPage, mapItemToRow, stableQueryContext]);
const handleNormalPageChange = useCallback(
async (pageIndex: number) => {
if (pageIndex === normalPageIndex || !stableQueryContext) return;
setErrorMessage(null);
setNormalLoading(true);
try {
const response = await fetchVerificationResultPage("NV", pageIndex);
const list = response?.data?.verifyResultList ?? [];
setNormalRows(list.map(mapItemToRow));
setNormalPageCount(response?.data?.pageInfo?.totalPages ?? 1);
setNormalPageIndex(pageIndex);
} catch {
setErrorMessage("일반검증 내역 조회 중 오류가 발생했습니다.");
} finally {
setNormalLoading(false);
setNormalCheckedIndices(new Set());
}
},
[fetchVerificationResultPage, mapItemToRow, normalPageIndex, stableQueryContext],
);
const handleImrPageChange = useCallback(
async (pageIndex: number) => {
if (pageIndex === imrPageIndex || !stableQueryContext) return;
setErrorMessage(null);
setImrLoading(true);
try {
const response = await fetchVerificationResultPage("IMR", pageIndex);
const list = response?.data?.verifyResultList ?? [];
setImrRows(list.map(mapItemToRow));
setImrPageCount(response?.data?.pageInfo?.totalPages ?? 1);
setImrPageIndex(pageIndex);
} catch {
setErrorMessage("I-MR 검증내역 조회 중 오류가 발생했습니다.");
} finally {
setImrLoading(false);
setImrCheckedIndices(new Set());
}
},
[fetchVerificationResultPage, mapItemToRow, imrPageIndex, stableQueryContext],
);
useEffect(() => {
if (!open) {
resetState();
return;
}
void loadInitial();
}, [loadInitial, open, resetState]);
/** 조회된 행에 예외사유 텍스트가 있으면 체크바·체크 인덱스와 맞춤 */
useEffect(() => {
if (normalLoading) return;
const id = requestAnimationFrame(() => {
setNormalCheckedIndices((prev) => {
const next = new Set(prev);
normalRows.forEach((row, itemIndex) => {
const has = String(row.prcsOpnnExpln ?? "").trim().length > 0;
setRowCheckByItemIndex(normalGridRef, itemIndex, has);
if (has) next.add(itemIndex);
});
return next;
});
});
return () => cancelAnimationFrame(id);
}, [normalRows, normalLoading]);
useEffect(() => {
if (imrLoading) return;
const id = requestAnimationFrame(() => {
setImrCheckedIndices((prev) => {
const next = new Set(prev);
imrRows.forEach((row, itemIndex) => {
const has = String(row.prcsOpnnExpln ?? "").trim().length > 0;
setRowCheckByItemIndex(imrGridRef, itemIndex, has);
if (has) next.add(itemIndex);
});
return next;
});
});
return () => cancelAnimationFrame(id);
}, [imrRows, imrLoading]);
const handleExceptionSubmitClick = useCallback(() => {
const payload: VerificationExceptionSubmitItem[] = [];
const pushIfHasExpln = (row: VerificationResultGridRow | undefined) => {
if (!row) return;
const prcsOpnnExpln = String(row.prcsOpnnExpln ?? "").trim();
if (!prcsOpnnExpln) return;
payload.push({
vrfcSn: Number(row.vrfcSn),
prcsOpnnExpln,
});
};
normalCheckedIndices.forEach((idx) => pushIfHasExpln(normalRows[idx]));
imrCheckedIndices.forEach((idx) => pushIfHasExpln(imrRows[idx]));
if (payload.length === 0) {
alert("작성된 예외 제출 항목이 없습니다.");
return;
}
console.log(payload);
}, [alert, imrCheckedIndices, imrRows, normalCheckedIndices, normalRows]);
const renderGrid = (
rows: VerificationResultGridRow[],
setRows: Dispatch<SetStateAction<VerificationResultGridRow[]>>,
pageIndex: number,
pageCount: number,
onPageIndexChange: (page: number) => void,
loading: boolean,
gridRef: MutableRefObject<RealGridReact | null>,
onPrcsOpnnExplnCellEdited: (params: CellEditedCallbackParams) => void,
setCheckedIndices: Dispatch<SetStateAction<Set<number>>>,
) => {
if (!loading && rows.length === 0) {
return <p className="p-6 text-center text-[1.3rem] text-muted-foreground">{emptyMessage}</p>;
}
return (
<div className="relative space-y-2">
<DataGrid
columnInfo={verificationSubmitResultColumnInfo}
rowData={rows}
setRowData={setRows as Dispatch<SetStateAction<Record<string, string | number>[]>>}
isExcelImport={false}
isExcelExport={false}
showHeaderCheckbox
enableSort={false}
getGridRef={gridRef}
onCellEdited={onPrcsOpnnExplnCellEdited}
onItemChecked={(itemIndex, checked) => {
setCheckedIndices((prev) => {
const next = new Set(prev);
if (checked) next.add(itemIndex);
else next.delete(itemIndex);
return next;
});
}}
onItemAllChecked={(checked) => {
setCheckedIndices(
checked ? new Set(rows.map((_, i) => i)) : new Set(),
);
}}
/>
<VerificationResultHistoryPagination
pageCount={Math.max(pageCount, 1)}
pageIndex={Math.max(pageIndex, 0)}
onPageIndexChange={onPageIndexChange}
className="mx-2 mb-2"
/>
{loading && (
<div className="absolute inset-0 z-10 rounded-md [data-theme='black']:bg-transparent bg-white/40 flex items-center justify-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
</div>
);
};
const titleSuffix = useMemo(() => {
if (!stableQueryContext) return "";
const sgg = stableQueryContext.sggNm?.trim() ? ` ${stableQueryContext.sggNm}` : "";
return ` - ${stableQueryContext.statsYr} ${stableQueryContext.ctpvNm}${sgg}`;
}, [stableQueryContext]);
return ( return (
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[640px]" aria-describedby={undefined}> <DialogContent className="max-w-[80%]" aria-describedby={undefined}>
<DialogHeader> <DialogHeader>
<DialogTitle>검증 결과</DialogTitle> <DialogTitle>
{title}
{titleSuffix}
</DialogTitle>
</DialogHeader> </DialogHeader>
<div className="min-h-[120px]" /> <div className="max-h-[85vh] space-y-5 overflow-auto">
{errorMessage && (
<p className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-[1.2rem] text-destructive">
{errorMessage}
</p>
)}
<section className="rounded-md border border-border">
<h3 className="border-b border-border px-4 py-2 text-[1.35rem] font-semibold">일반검증 내역</h3>
{renderGrid(
normalRows,
setNormalRows,
normalPageIndex,
normalPageCount,
handleNormalPageChange,
normalLoading,
normalGridRef,
onNormalPrcsOpnnExplnEdited,
setNormalCheckedIndices,
)}
</section>
<section className="rounded-md border border-border">
<h3 className="border-b border-border px-4 py-2 text-[1.35rem] font-semibold">I-MR 검증내역</h3>
{renderGrid(
imrRows,
setImrRows,
imrPageIndex,
imrPageCount,
handleImrPageChange,
imrLoading,
imrGridRef,
onImrPrcsOpnnExplnEdited,
setImrCheckedIndices,
)}
</section>
</div>
<DialogFooter> <DialogFooter>
<Button type="button" color="primary" onClick={handleExceptionSubmitClick}>
예외 제출
</Button>
<DialogClose asChild> <DialogClose asChild>
<Button type="button" color="gray"> <Button type="button" color="gray">
닫기 닫기
@@ -37,4 +500,3 @@ export function VerificationResultDialog({
</Dialog> </Dialog>
); );
} }
@@ -0,0 +1,93 @@
"use client";
import { useEffect, useState } from "react";
import { closestCenter, DndContext } from "@dnd-kit/core";
import { rectSortingStrategy, SortableContext } from "@dnd-kit/sortable";
import dayjs from "dayjs";
import { useUserStore } from "@/shared/lib";
import { Skeleton } from "@common/components";
import { useDndSensors } from "@/pages/statistics/lib/hooks/use-dnd-sensors";
import { usePanelOrder } from "@/pages/statistics/lib/hooks/use-panel-order";
import { getInitialPanels } from "@/pages/statistics/model/panel-config";
import { SortablePanel } from "@/pages/statistics/ui/sortable-panel";
interface PanelItem {
id: string;
component: React.ReactNode;
className?: string;
}
function Dashboard() {
const userInfo = useUserStore((state) => state.userInfo);
const [initialPanels, setInitialPanels] = useState<PanelItem[]>([]);
const [isMounted, setIsMounted] = useState(false);
const sensors = useDndSensors();
const { panels, handleDragEnd } = usePanelOrder({
initialPanels,
storageKey: "statistics-dashboard-panels-order",
});
useEffect(() => {
setIsMounted(true);
}, []);
useEffect(() => {
if (!userInfo) return;
const initialPanels = getInitialPanels({
dashboardParams: {
statsYr: String(dayjs().year() - 1),
dtlInstCd: userInfo.dtlInstCd,
enoCd: userInfo.enoCd,
laeSeCd: userInfo.laeSeCd,
},
scheduleInfoParams: {
statsYr: String(dayjs().year() - 1),
},
});
setInitialPanels(initialPanels);
}, [userInfo]);
return (
<>
{isMounted && initialPanels.length > 0 ? (
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={panels.map((p) => p.id)}
strategy={rectSortingStrategy}
>
<div className="grid grid-cols-1 gap-4 p-2 md:grid-cols-2 lg:grid-cols-3">
{panels.map((panel) => (
<SortablePanel
key={panel.id}
id={panel.id}
className={panel.className}
>
{panel.component}
</SortablePanel>
))}
</div>
</SortableContext>
</DndContext>
) : (
<div className="grid grid-cols-1 gap-4 p-2 md:grid-cols-2 lg:grid-cols-3">
<Skeleton className="h-[20rem] rounded-xl bg-muted" />
<Skeleton className="h-[20rem] rounded-xl bg-muted" />
<Skeleton className="h-[20rem] rounded-xl bg-muted" />
<Skeleton className="h-[20rem] rounded-xl bg-muted" />
<Skeleton className="h-[20rem] rounded-xl bg-muted" />
<Skeleton className="h-[20rem] rounded-xl bg-muted" />
</div>
)}
</>
);
}
export default Dashboard;
@@ -0,0 +1,260 @@
"use client";
import { useCallback } from "react";
import { useQueries } from "@tanstack/react-query";
import { useTabStore as useGridTabStore } from "@rsone/components";
import { statisticsApi } from "@/entities/statistics/api/statistics-service";
import type { VerificationResultReportItem } from "@/entities/statistics/model/statistics-interface";
import { useAlertStore, useMenuStore } from "@/shared/lib";
import {
findMenuItemByUrlPath,
resolveInputPageNavigationFromStatsCd,
} from "@/shared/lib/stats-cd-input-navigation";
import { useStatisticsInputFocusStore } from "@/store/statistics-input-focus-store";
import { useTabStore } from "@/store/tab-store";
import dayjs from "dayjs";
import {
Badge,
type BadgeProps,
LoadingWithAnimation,
} from "@common/components";
const TYPE_CODE_COLOR_MAP: Record<string, BadgeProps["color"]> = {
NV: "gray",
IMR: "red",
};
const TYPE_CODE_NAME_MAP: Record<string, string> = {
NV: "일반",
IMR: "I-MR",
};
type VerificationSelectionReportProps = {
onClose?: () => void;
};
const VerificationSelectionReport = ({
onClose,
}: VerificationSelectionReportProps) => {
const menuList = useTabStore((s) => s.menuList);
const addTab = useTabStore((s) => s.addTab);
const setCurrentMenuInfo = useMenuStore((s) => s.setCurrentMenuInfo);
const addTabForGrid = useGridTabStore((s) => s.addTab);
const setPendingInputTab = useStatisticsInputFocusStore(
(s) => s.setPendingInputTab,
);
const alert = useAlertStore((s) => s.setMessage);
const statsYr = String(dayjs().year() - 1);
const baseRequest = {
statsYr,
pbcpAprvYn: "N" as const,
page: 1,
size: 10000,
prcsYnList: "0",
};
const [nvQuery, imrQuery] = useQueries({
queries: [
{
queryKey: [
"verificationResultList",
statsYr,
"NV",
baseRequest.pbcpAprvYn,
baseRequest.page,
baseRequest.size,
baseRequest.prcsYnList,
],
queryFn: () =>
statisticsApi.getVerificationResultList({
...baseRequest,
vrfcMthdCd: "NV",
}),
},
{
queryKey: [
"verificationResultList",
statsYr,
"IMR",
baseRequest.pbcpAprvYn,
baseRequest.page,
baseRequest.size,
baseRequest.prcsYnList,
],
queryFn: () =>
statisticsApi.getVerificationResultList({
...baseRequest,
vrfcMthdCd: "IMR",
}),
},
],
});
const isLoading = nvQuery.isLoading || imrQuery.isLoading;
const error = nvQuery.error ?? imrQuery.error;
const nvList = nvQuery.data?.data?.verifyResultList ?? [];
const imrList = imrQuery.data?.data?.verifyResultList ?? [];
const openInputFromStatsCd = useCallback(
(item: VerificationResultReportItem) => {
const nav = resolveInputPageNavigationFromStatsCd(item.statsCd);
if (!nav) {
alert(
`입력 화면으로 연결되지 않는 통계코드입니다: ${item.statsCd}`,
);
return;
}
if (!menuList) {
alert(
"메뉴 정보를 불러오는 중입니다. 잠시 후 다시 시도해 주세요.",
);
return;
}
const menu = findMenuItemByUrlPath(menuList, nav.urlPath);
if (!menu) {
alert(
"해당 입력 메뉴를 찾을 수 없습니다. 메뉴 권한을 확인해 주세요.",
);
return;
}
setPendingInputTab(nav.urlPath, nav.tabKey, {
statsYr: item.statsYr,
sewerBzmnCd: item.sewerBzmnCd,
ctpvNm: item.ctpvNm,
sggNm: item.sggNm ?? "",
});
setCurrentMenuInfo(menu);
const ok = addTab(menu);
if (ok) {
addTabForGrid(menu);
} else {
alert(`최대 추가 할 수 있는 화면 수(10개)를 \n초과 하였습니다.
기존 화면을 닫은 후 이용해주세요.`);
}
},
[
menuList,
addTab,
addTabForGrid,
setCurrentMenuInfo,
setPendingInputTab,
alert,
],
);
const renderSection = (
typeCode: "IMR" | "NV",
items: VerificationResultReportItem[],
) => (
<section className="flex min-h-0 flex-1 flex-col rounded-sm border border-border h-[50rem]">
<div className="flex items-center justify-between border-b border-border px-3 py-2">
<Badge color={TYPE_CODE_COLOR_MAP[typeCode]} className="rounded-full px-2 py-1 text-lg">
{TYPE_CODE_NAME_MAP[typeCode]} {items.length}
</Badge>
</div>
<div className="min-h-0 flex-1 overflow-y-auto p-2">
{items.length === 0 ? (
<div className="flex h-full min-h-[8rem] items-center justify-center text-lg text-muted-foreground">
항목이 없습니다.
</div>
) : (
<div className="space-y-2 tracking-tight">
{items.map((item) => (
<div
key={`${typeCode}-${item.vrfcSn}`}
role="button"
tabIndex={0}
className="flex flex-col rounded-sm border border-border p-3 cursor-pointer hover:bg-gray-100"
onClick={() => openInputFromStatsCd(item)}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
openInputFromStatsCd(item);
}
}}
>
<div className="mb-2 flex items-center justify-between">
<span className="font-medium">
{item.statsNm}
</span>
<Badge
color={
TYPE_CODE_COLOR_MAP[item.vrfcMthdCd] ??
"gray"
}
className="text-sm"
>
{TYPE_CODE_NAME_MAP[item.vrfcMthdCd] ??
item.vrfcMthdNm}
</Badge>
</div>
<p className="text-lg text-muted-foreground">
{item.rsnExpln}
</p>
<div className="flex justify-between text-lg text-muted-foreground">
<span>{item.admdstNm}</span>
<span>
현재: {item.nowVlCn ?? "-"} / 비교:{" "}
{item.compVlCn ?? "-"}
</span>
</div>
</div>
))}
</div>
)}
</div>
</section>
);
return (
<div className="w-1/5 bg-container p-4 !pb-2 flex border-r border-border">
<div className="card card-border flex-1 bg-background !px-0">
<div className="border-b border-border flex justify-between">
<h2 className="text-[2.4rem] font-semibold text-title p-4 ">검증 미통과 내역</h2>
<span
role="button"
tabIndex={0}
aria-label="닫기"
className="mt-2 mr-4 flex flex-shrink-0 cursor-pointer items-start justify-center text-3xl leading-none hover:text-[#2094fa]"
onClick={() => onClose?.()}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onClose?.();
}
}}
>
<i className="ri-close-line" />
</span>
</div>
<div className="card-body max-h-[calc(100%-3.25rem)] p-2.5">
{isLoading && (
<div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
{error && (
<div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center">
데이터를 불러올 수 없습니다.
</div>
)}
{!isLoading && !error && (
<div className="grid grid-rows-2 gap-6">
{renderSection("IMR", imrList)}
{renderSection("NV", nvList)}
</div>
)}
</div>
</div>
</div>
);
};
export default VerificationSelectionReport;
@@ -1,24 +1,20 @@
import { useState } from 'react'; import { useState } from 'react';
import SearchForm from '@/components/module/SearchForm'; import SearchForm from '@/components/module/SearchForm';
import { DataGrid } from '@rsone/components'; import DataGrid from '@/components/module/DataGrid';
import SplitDataGrid from '@/components/module/SplitDataGrid';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@common/components';
import SubmitButton from '@/components/button/SumitButton'; import SubmitButton from '@/components/button/SumitButton';
import SaveButton from '@/components/button/SaveButton'; import SaveButton from '@/components/button/SaveButton';
import SubmitExceptionButton from '@/components/button/SubmitExceptionButton';
import OperateDataButton from '@/components/button/OperateDataButton'; import OperateDataButton from '@/components/button/OperateDataButton';
import UpdateOperateDataButton from "@/components/button/UpdateOperateDataButton" import UpdateOperateDataButton from '@/components/button/UpdateOperateDataButton';
import NotApplicableCheckButton from "@/components/button/NotApplicableCheckButton";
import { PublicSewageFactInpColumn } from '@/components/util/column/input/PublicSewageFactInpColumn'; import type { ColumnInfo, ColumnInfoList } from '@/components/type/DataGrid.type';
import { PublicSewageFactInpColumnList } from '@/components/util/column/input/PublicSewageFactInpColumn/PublicSewageFactInpColumn';
// 하수도 통계 관리 > 06. 공공하수처리시설 // 하수도 통계 관리 > 06. 공공하수처리시설
const PublicSewageFacilityInp = () => { const PublicSewageFacilityInp = () => {
const SubmitExceptionFunc = () => {
console.log('submitException');
// 예외제출 로직
};
const submitFunc = () => { const submitFunc = () => {
console.log('submit'); console.log('submit');
// 제출 로직 // 제출 로직
@@ -39,33 +35,109 @@ const PublicSewageFacilityInp = () => {
// 운영 데이터 업데이트 로직 // 운영 데이터 업데이트 로직
}; };
const [rowData, setRowData] = useState<Record<string, string | number>[]>([]); const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(new Map());
const [isNotApplicable, setIsNotApplicable] = useState(false); const [activeTab, setActiveTab] = useState<string>(
PublicSewageFactInpColumnList[0]?.tabKey ?? 'ST00060001',
);
const getGridColumnInfo = (
tab: ColumnInfoList,
): ColumnInfo => ({
columns: tab.columns ?? [],
columnLayout: tab.columnLayout ?? [],
});
return ( return (
<> <>
<SearchForm fctName={true} /> <SearchForm fctName={true} />
<div className="card !py-0"> <div className="card !py-0">
<div className="flex justify-end items-center gap-[0.6rem] m-[0.6rem]"> <div className="flex justify-end items-center gap-[0.6rem] m-[0.6rem]">
<SubmitExceptionButton SubmitExceptionFunc={SubmitExceptionFunc} /> <UpdateOperateDataButton updateOperateDataButtonFunc={updateOperateDataButtonFunc} />
<OperateDataButton getOperateDataFunc={getOperateDataFunc} />
<SubmitButton submitFunc={submitFunc} /> <SubmitButton submitFunc={submitFunc} />
<SaveButton saveFunc={saveFunc} /> <SaveButton saveFunc={saveFunc} />
</div> </div>
</div> </div>
<div className="card !py-0"> <Tabs value={activeTab} onValueChange={setActiveTab}>
<div className="flex justify-end items-center gap-[0.6rem] m-[0.6rem]"> <TabsList>
<NotApplicableCheckButton isCheck={isNotApplicable} setIsCheck={setIsNotApplicable} /> {PublicSewageFactInpColumnList.map((tab) => (
<UpdateOperateDataButton updateOperateDataButtonFunc={updateOperateDataButtonFunc} /> <TabsTrigger key={tab.tabKey} value={tab.tabKey}>
<OperateDataButton getOperateDataFunc={getOperateDataFunc} /> {tab.tabLabel || tab.tabKey}
</div> </TabsTrigger>
</div> ))}
<DataGrid </TabsList>
columnInfo={ PublicSewageFactInpColumn }
rowStartNum={3} {PublicSewageFactInpColumnList.map((tab) => {
fixedColumns={2} if (tab.isSplitGrid && tab.left && tab.right) {
rowData={rowData} const leftKey = tab.left.tabKey ?? `${tab.tabKey}_left`;
setRowData={setRowData} const rightKey = tab.right.tabKey ?? `${tab.tabKey}_right`;
/> return (
<TabsContent key={tab.tabKey} value={tab.tabKey}>
<SplitDataGrid
leftColumnInfo={getGridColumnInfo(tab.left)}
rightColumnInfo={getGridColumnInfo(tab.right)}
leftFixedColumns={tab.left.fixedColumns}
rightFixedColumns={tab.right.fixedColumns}
showHeaderCheckbox={false}
enableSort={false}
leftRowData={rowDataMap.get(leftKey) ?? []}
rightRowData={rowDataMap.get(rightKey) ?? []}
setLeftRowData={(updater) => {
setRowDataMap((prev) => {
const next = new Map(prev);
const cur = next.get(leftKey) ?? [];
const n =
typeof updater === 'function'
? (updater as (p: Record<string, string | number>[]) => Record<string, string | number>[])(cur)
: updater;
next.set(leftKey, n);
return next;
});
}}
setRightRowData={(updater) => {
setRowDataMap((prev) => {
const next = new Map(prev);
const cur = next.get(rightKey) ?? [];
const n =
typeof updater === 'function'
? (updater as (p: Record<string, string | number>[]) => Record<string, string | number>[])(cur)
: updater;
next.set(rightKey, n);
return next;
});
}}
/>
</TabsContent>
);
}
const gridColumnInfo = getGridColumnInfo(tab);
return (
<TabsContent key={tab.tabKey} value={tab.tabKey}>
<DataGrid
columnInfo={gridColumnInfo}
rowStartNum={tab.rowStartNum}
fixedColumns={tab.fixedColumns}
rowData={rowDataMap.get(tab.tabKey) ?? []}
setRowData={(updater) => {
setRowDataMap((prev) => {
const next = new Map(prev);
const cur = next.get(tab.tabKey) ?? [];
const n =
typeof updater === 'function'
? (updater as (p: Record<string, string | number>[]) => Record<string, string | number>[])(cur)
: updater;
next.set(tab.tabKey, n);
return next;
});
}}
showHeaderCheckbox={false}
enableSort={false}
/>
</TabsContent>
);
})}
</Tabs>
</> </>
); );
}; };
File diff suppressed because it is too large Load Diff
@@ -1,6 +1,10 @@
import { useRef, useState } from "react"; import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useAlertStore } from "@/shared/lib"; import { useAlertStore } from "@/shared/lib";
import {
STATISTICS_INPUT_URL_PATH,
verificationSearchToFormValues,
} from "@/shared/lib/stats-cd-input-navigation";
import { statisticsInputSewSupplyRateApi } from "@/entities/statistics/api/input/statistics-input-sew-supply-rate-service"; import { statisticsInputSewSupplyRateApi } from "@/entities/statistics/api/input/statistics-input-sew-supply-rate-service";
import { sewagePipeMaintainApiService } from "@/entities/statistics/api/input/statistics-input-sewage-pipe-maintain-service"; import { sewagePipeMaintainApiService } from "@/entities/statistics/api/input/statistics-input-sewage-pipe-maintain-service";
import type { SewagePipeMaintainRequestParams } from "@/entities/statistics/model/input/statistics-input-sewage-pipe-maintain-interface"; import type { SewagePipeMaintainRequestParams } from "@/entities/statistics/model/input/statistics-input-sewage-pipe-maintain-interface";
@@ -16,6 +20,8 @@ import type { SearchFormValues } from "@/components/type/SearchForm.type";
import { PipeDredgingStatusInpColumn } from "@/components/util/column/input/sewagePipeMaintain/PipeDredgingStatusInpColumn"; import { PipeDredgingStatusInpColumn } from "@/components/util/column/input/sewagePipeMaintain/PipeDredgingStatusInpColumn";
import { RepairStatusInpColumn } from "@/components/util/column/input/sewagePipeMaintain/RepairStatusInpColumn"; import { RepairStatusInpColumn } from "@/components/util/column/input/sewagePipeMaintain/RepairStatusInpColumn";
import { toGridRows } from "@/components/util/grid/gridFunction"; import { toGridRows } from "@/components/util/grid/gridFunction";
import { useStatisticsInputFocusStore } from "@/store/statistics-input-focus-store";
import { useTabStore } from "@/store/tab-store";
function buildSewagePipeMaintainSearchParam( function buildSewagePipeMaintainSearchParam(
values: SearchFormValues, values: SearchFormValues,
@@ -40,6 +46,13 @@ const SewagePipeMaintainInp = () => {
const [lastSearchedYear, setLastSearchedYear] = useState<string | null>(null); const [lastSearchedYear, setLastSearchedYear] = useState<string | null>(null);
const [hasSearched, setHasSearched] = useState(false); const [hasSearched, setHasSearched] = useState(false);
const searchParamRef = useRef<SewagePipeMaintainRequestParams | null>(null); const searchParamRef = useRef<SewagePipeMaintainRequestParams | null>(null);
const postVerificationSearchRef = useRef<{
values: SearchFormValues;
tabKey: string;
} | null>(null);
const [verificationSearchDefaults, setVerificationSearchDefaults] =
useState<SearchFormValues | null>(null);
const [searchFormRemountKey, setSearchFormRemountKey] = useState(0);
// tab List // tab List
const SewagePipeMaintainInpTabList = [ const SewagePipeMaintainInpTabList = [
@@ -47,6 +60,24 @@ const SewagePipeMaintainInp = () => {
PipeDredgingStatusInpColumn PipeDredgingStatusInpColumn
]; ];
const activeTabId = useTabStore((s) => s.activeTabId);
const inputFocusNonce = useStatisticsInputFocusStore((s) => s.nonce);
useLayoutEffect(() => {
if (activeTabId !== STATISTICS_INPUT_URL_PATH.SEWAGE_PIPE_MAINTAIN) return;
const pending = useStatisticsInputFocusStore
.getState()
.takePendingForUrl(STATISTICS_INPUT_URL_PATH.SEWAGE_PIPE_MAINTAIN);
if (!pending) return;
const { tabKey, search } = pending;
setActiveTab(tabKey);
if (search) {
const values = verificationSearchToFormValues(search);
setVerificationSearchDefaults(values);
postVerificationSearchRef.current = { values, tabKey };
setSearchFormRemountKey((k) => k + 1);
}
}, [activeTabId, inputFocusNonce]);
const SubmitExceptionFunc = () => { const SubmitExceptionFunc = () => {
console.log('submit exception'); console.log('submit exception');
// 예외 제출 로직 // 예외 제출 로직
@@ -136,9 +167,14 @@ const SewagePipeMaintainInp = () => {
setLastSearchedYear(null); setLastSearchedYear(null);
setHasSearched(false); setHasSearched(false);
searchParamRef.current = null; searchParamRef.current = null;
setVerificationSearchDefaults(null);
setSearchFormRemountKey((k) => k + 1);
}; };
const handleSearch = async (values: SearchFormValues) => { const handleSearch = async (
values: SearchFormValues,
opts?: { forcedTabKey?: string },
) => {
if (!values.sido || values.sido === "ALL") { if (!values.sido || values.sido === "ALL") {
alert("시도를 선택해주세요."); alert("시도를 선택해주세요.");
return; return;
@@ -151,13 +187,18 @@ const SewagePipeMaintainInp = () => {
return; return;
} }
const tabForLoad = opts?.forcedTabKey ?? activeTab;
if (opts?.forcedTabKey) {
setActiveTab(opts.forcedTabKey);
}
setIsLoading(true); setIsLoading(true);
const searchParam = buildSewagePipeMaintainSearchParam(values); const searchParam = buildSewagePipeMaintainSearchParam(values);
searchParamRef.current = searchParam; searchParamRef.current = searchParam;
setLastSearchedValues(values); setLastSearchedValues(values);
setLastSearchedYear(values.year ?? null); setLastSearchedYear(values.year ?? null);
setHasSearched(true); setHasSearched(true);
await loadActiveTabData(activeTab, searchParam, false); await loadActiveTabData(tabForLoad, searchParam, false);
} catch { } catch {
alert("데이터 조회 중 오류가 발생했습니다."); alert("데이터 조회 중 오류가 발생했습니다.");
} finally { } finally {
@@ -165,6 +206,14 @@ const SewagePipeMaintainInp = () => {
} }
}; };
useEffect(() => {
const job = postVerificationSearchRef.current;
if (!job) return;
postVerificationSearchRef.current = null;
void handleSearch(job.values, { forcedTabKey: job.tabKey });
// eslint-disable-next-line react-hooks/exhaustive-deps -- 검색폼 remount 직후 1회 자동 조회
}, [searchFormRemountKey]);
const handleActiveTabChange = async (tabKey: string) => { const handleActiveTabChange = async (tabKey: string) => {
setActiveTab(tabKey); setActiveTab(tabKey);
const hasRows = (rowDataMap.get(tabKey) ?? []).length > 0; const hasRows = (rowDataMap.get(tabKey) ?? []).length > 0;
@@ -183,7 +232,13 @@ const SewagePipeMaintainInp = () => {
return ( return (
<> <>
<SearchForm onSubmit={handleSearch} onReset={handleReset} onValuesChange={setSearchValues} /> <SearchForm
key={searchFormRemountKey}
defaultValues={verificationSearchDefaults ?? undefined}
onSubmit={handleSearch}
onReset={handleReset}
onValuesChange={setSearchValues}
/>
{(hasRowData || hasSearched) && ( {(hasRowData || hasSearched) && (
<div className="card !py-0"> <div className="card !py-0">
<div className="flex justify-end items-center gap-[0.6rem] m-[0.6rem]"> <div className="flex justify-end items-center gap-[0.6rem] m-[0.6rem]">
@@ -1,4 +1,4 @@
import { useState, useMemo, useRef } from "react"; import { useState, useMemo, useRef, useLayoutEffect, useEffect } from "react";
import SearchForm from "@/components/module/SearchForm"; import SearchForm from "@/components/module/SearchForm";
// import { DataGrid } from "@rsone/components"; // import { DataGrid } from "@rsone/components";
@@ -15,6 +15,10 @@ import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import SubmitDailog from "./SubmitDailog"; import SubmitDailog from "./SubmitDailog";
import { useAlertStore, useGlobalProgressStore } from "@/shared/lib"; import { useAlertStore, useGlobalProgressStore } from "@/shared/lib";
import {
STATISTICS_INPUT_URL_PATH,
verificationSearchToFormValues,
} from "@/shared/lib/stats-cd-input-navigation";
import { useAdminStore } from "@/store/admin-store"; import { useAdminStore } from "@/store/admin-store";
import { statisticsInputSewSupplyRateApi } from "@/entities/statistics/api/input/statistics-input-sew-supply-rate-service"; import { statisticsInputSewSupplyRateApi } from "@/entities/statistics/api/input/statistics-input-sew-supply-rate-service";
import { statisticsApi } from "@/entities/statistics/api/statistics-service"; import { statisticsApi } from "@/entities/statistics/api/statistics-service";
@@ -24,13 +28,16 @@ import { getUserInfo } from "../../../../../../packages/common/components/src/ap
import { useConfirm } from "@frontend-opensource/use-react-hooks"; import { useConfirm } from "@frontend-opensource/use-react-hooks";
import type { SearchFormValues } from "@/components/type/SearchForm.type"; import type { SearchFormValues } from "@/components/type/SearchForm.type";
import type { import {
SewerageSupplyRateItem, type CheckInputPeriodItem,
SewerageSupplyRateRequestParams, type SewerageSupplyRateItem,
SewerageSupplyRateSaveItem, type SewerageSupplyRateRequestParams,
SewerageSupplyRateVerificationResult, type SewerageSupplyRateSaveItem,
SewerageSupplyRateSaveRequest, type SewerageSupplyRateVerificationResult,
SewerageSupplyRateStatusInfo, type SewerageSupplyRateSaveRequest,
type SewerageSupplyRateStatusInfo,
getVerificationPeriodActionBlockedMessage,
isInputPeriodCurrent,
} from "@/entities/statistics/model/input/statistics-sewage-supply-rate-input-interface"; } from "@/entities/statistics/model/input/statistics-sewage-supply-rate-input-interface";
import type { import type {
cancelSubmitRequest, cancelSubmitRequest,
@@ -40,6 +47,8 @@ import type {
import type { StatisticsInputSubmitInfoFormData } from "@/entities/statistics/model/statistics-input-submit-info-schema"; import type { StatisticsInputSubmitInfoFormData } from "@/entities/statistics/model/statistics-input-submit-info-schema";
import { SeweragePenetrationRateInpColumn } from "@/components/util/column/input/SeweragePenetrationRateInpColumn"; import { SeweragePenetrationRateInpColumn } from "@/components/util/column/input/SeweragePenetrationRateInpColumn";
import { doList } from "@/components/util/column/input/DoList"; import { doList } from "@/components/util/column/input/DoList";
import { useStatisticsInputFocusStore } from "@/store/statistics-input-focus-store";
import { useTabStore } from "@/store/tab-store";
type GridRowWithVerification = Record<string, string | number> & { type GridRowWithVerification = Record<string, string | number> & {
@@ -100,6 +109,8 @@ const SeweragePenetrationRateInp = () => {
const [lastSearchedYear, setLastSearchedYear] = useState<string | null>(null); const [lastSearchedYear, setLastSearchedYear] = useState<string | null>(null);
const [lastSearchedValues, setLastSearchedValues] = useState<SearchFormValues | null>(null); const [lastSearchedValues, setLastSearchedValues] = useState<SearchFormValues | null>(null);
const [statusInfo, setStatusInfo] = useState<SewerageSupplyRateStatusInfo | null>(null); const [statusInfo, setStatusInfo] = useState<SewerageSupplyRateStatusInfo | null>(null);
/** 마지막 조회 시 check-input-period 응답 (검증기간 여부 판단) */
const [periodCheckList, setPeriodCheckList] = useState<CheckInputPeriodItem[]>([]);
const [showDailog, setShowDailog] = useState<boolean>(false); const [showDailog, setShowDailog] = useState<boolean>(false);
const [verificationHistoryOpen, setVerificationHistoryOpen] = useState(false); const [verificationHistoryOpen, setVerificationHistoryOpen] = useState(false);
const [verificationResultDialogOpen, setVerificationResultDialogOpen] = useState(false); const [verificationResultDialogOpen, setVerificationResultDialogOpen] = useState(false);
@@ -113,6 +124,27 @@ const SeweragePenetrationRateInp = () => {
const hideGlobalProgress = useGlobalProgressStore((state) => state.hide); const hideGlobalProgress = useGlobalProgressStore((state) => state.hide);
const globalProgressVisible = useGlobalProgressStore((state) => state.visible); const globalProgressVisible = useGlobalProgressStore((state) => state.visible);
const postVerificationSearchRef = useRef<SearchFormValues | null>(null);
const [verificationSearchDefaults, setVerificationSearchDefaults] =
useState<SearchFormValues | null>(null);
const [searchFormRemountKey, setSearchFormRemountKey] = useState(0);
const activeTabId = useTabStore((s) => s.activeTabId);
const inputFocusNonce = useStatisticsInputFocusStore((s) => s.nonce);
useLayoutEffect(() => {
if (activeTabId !== STATISTICS_INPUT_URL_PATH.SEWERAGE_PENETRATION_RATE) {
return;
}
const pending = useStatisticsInputFocusStore
.getState()
.takePendingForUrl(STATISTICS_INPUT_URL_PATH.SEWERAGE_PENETRATION_RATE);
if (!pending?.search) return;
const values = verificationSearchToFormValues(pending.search);
setVerificationSearchDefaults(values);
postVerificationSearchRef.current = values;
setSearchFormRemountKey((k) => k + 1);
}, [activeTabId, inputFocusNonce]);
const { isAdminInfo } = useAdminStore(); const { isAdminInfo } = useAdminStore();
const getGridDataRef = useRef<(() => Record<string, string | number>[]) | null>(null); const getGridDataRef = useRef<(() => Record<string, string | number>[]) | null>(null);
@@ -147,9 +179,12 @@ const SeweragePenetrationRateInp = () => {
const handleReset = () => { const handleReset = () => {
setRowData([]); setRowData([]);
setStatusInfo(null); setStatusInfo(null);
setPeriodCheckList([]);
setLastSearchedYear(null); setLastSearchedYear(null);
setLastSearchedValues(null); setLastSearchedValues(null);
setFooterFromApi(null); setFooterFromApi(null);
setVerificationSearchDefaults(null);
setSearchFormRemountKey((k) => k + 1);
}; };
const fetchSewerageSupplyRate = async (params: SewerageSupplyRateRequestParams, isEnterable: boolean) => { const fetchSewerageSupplyRate = async (params: SewerageSupplyRateRequestParams, isEnterable: boolean) => {
@@ -218,8 +253,9 @@ const SeweragePenetrationRateInp = () => {
const response = await statisticsInputSewSupplyRateApi.checkInputPeriod(values.year || ''); const response = await statisticsInputSewSupplyRateApi.checkInputPeriod(values.year || '');
if (response.status === 'success') { if (response.status === 'success') {
const checkEnterable = response.data; const periods = Array.isArray(response.data) ? response.data : [];
// setIsEnterable(response.data); setPeriodCheckList(periods);
const checkEnterable = isInputPeriodCurrent(periods);
setLastSearchedYear(values.year || null); setLastSearchedYear(values.year || null);
await fetchSewerageSupplyRate(getSewerageSupplyRateParams(values), checkEnterable); await fetchSewerageSupplyRate(getSewerageSupplyRateParams(values), checkEnterable);
setLastSearchedValues(values); setLastSearchedValues(values);
@@ -231,7 +267,20 @@ const SeweragePenetrationRateInp = () => {
} }
}; };
useEffect(() => {
const values = postVerificationSearchRef.current;
if (!values) return;
postVerificationSearchRef.current = null;
void handleSearch(values);
// eslint-disable-next-line react-hooks/exhaustive-deps -- 검색폼 remount 직후 1회 자동 조회
}, [searchFormRemountKey]);
const SubmitExceptionFunc = async (submitInfo: StatisticsInputSubmitInfoFormData) => { const SubmitExceptionFunc = async (submitInfo: StatisticsInputSubmitInfoFormData) => {
const verificationBlocked = getVerificationPeriodActionBlockedMessage(periodCheckList);
if (verificationBlocked) {
alert(verificationBlocked);
return;
}
const userInfo = await getUserInfo(); const userInfo = await getUserInfo();
const params: SubmitExceptionRequest = { const params: SubmitExceptionRequest = {
@@ -309,6 +358,11 @@ const SeweragePenetrationRateInp = () => {
}; };
const executeSubmit = async (submitInfo: StatisticsInputSubmitInfoFormData) => { const executeSubmit = async (submitInfo: StatisticsInputSubmitInfoFormData) => {
const verificationBlocked = getVerificationPeriodActionBlockedMessage(periodCheckList);
if (verificationBlocked) {
alert(verificationBlocked);
return;
}
try { try {
showGlobalProgress({ label: "제출 진행 중...", progress: 0 }); showGlobalProgress({ label: "제출 진행 중...", progress: 0 });
const userInfo = await getUserInfo(); const userInfo = await getUserInfo();
@@ -442,6 +496,11 @@ const SeweragePenetrationRateInp = () => {
const saveFunc = async () => { const saveFunc = async () => {
try { try {
if (await confirm('저장 하시겠습니까?')) { if (await confirm('저장 하시겠습니까?')) {
const verificationBlocked = getVerificationPeriodActionBlockedMessage(periodCheckList);
if (verificationBlocked) {
alert(verificationBlocked);
return;
}
showGlobalProgress({ label: "저장 진행 중...", progress: 0 }); showGlobalProgress({ label: "저장 진행 중...", progress: 0 });
const userInfo = await getUserInfo(); const userInfo = await getUserInfo();
@@ -520,9 +579,9 @@ const SeweragePenetrationRateInp = () => {
sewerBzmnFrgnrWholPpltnCnt: footerFromApi?.sewerBzmnFrgnrWholPpltnCnt // 행정참고자료 외국인 합계 sewerBzmnFrgnrWholPpltnCnt: footerFromApi?.sewerBzmnFrgnrWholPpltnCnt // 행정참고자료 외국인 합계
}; };
// if (isAdminInfo) { if (isAdminInfo) {
// requestData.superAdmin = 'superAdmin'; requestData.superAdmin = 'superAdmin';
// } }
const response = await statisticsInputSewSupplyRateApi.saveSewerageSupplyRate(requestData); const response = await statisticsInputSewSupplyRateApi.saveSewerageSupplyRate(requestData);
@@ -547,6 +606,11 @@ const SeweragePenetrationRateInp = () => {
const cnacelSubmitFunc = async () => { const cnacelSubmitFunc = async () => {
try { try {
if (await confirm('제출된 내용을 취소하시겠습니까?')) { if (await confirm('제출된 내용을 취소하시겠습니까?')) {
const verificationBlocked = getVerificationPeriodActionBlockedMessage(periodCheckList);
if (verificationBlocked) {
alert(verificationBlocked);
return;
}
const userInfo = await getUserInfo(); const userInfo = await getUserInfo();
@@ -596,15 +660,21 @@ const SeweragePenetrationRateInp = () => {
return ( return (
<> <>
<div className="relative"> <div className="relative">
<SearchForm onSubmit={handleSearch} onReset={handleReset} onValuesChange={setSearchValues} /> <SearchForm
key={searchFormRemountKey}
defaultValues={verificationSearchDefaults ?? undefined}
onSubmit={handleSearch}
onReset={handleReset}
onValuesChange={setSearchValues}
/>
{showActionToolbarCard && ( {showActionToolbarCard && (
<div className="card !py-0"> <div className="card !py-0">
<div className="flex justify-end items-center gap-[0.6rem] mx-[0.6rem]"> <div className="flex justify-end items-center gap-[0.6rem] mx-[0.6rem]">
<VerificationResultButton
VerificationResultButtonFunc={openVerificationHistoryDialog}
/>
{showEnterableToolbarButtons && ( {showEnterableToolbarButtons && (
<> <>
<VerificationResultButton
VerificationResultButtonFunc={openVerificationHistoryDialog}
/>
<LastYearDataButton getLastYearDataFunc={() => getLastYearDataFunc(searchValues ?? {})} /> <LastYearDataButton getLastYearDataFunc={() => getLastYearDataFunc(searchValues ?? {})} />
<SubmitButton submitFunc={() => submitFunc(false)} /> <SubmitButton submitFunc={() => submitFunc(false)} />
</> </>
@@ -686,6 +756,20 @@ const SeweragePenetrationRateInp = () => {
<VerificationResultDialog <VerificationResultDialog
open={verificationResultDialogOpen} open={verificationResultDialogOpen}
onOpenChange={setVerificationResultDialogOpen} onOpenChange={setVerificationResultDialogOpen}
queryContext={
searchValues?.year && searchValues?.sido && searchValues?.bsnmCd && statsCd
? {
sewerBzmnCd: searchValues.bsnmCd,
ctpvNm: searchValues.sido,
sggNm:
searchValues.gugun === "ALL"
? ""
: (searchValues.gugun ?? ""),
statsYr: searchValues.year,
statsCd,
}
: null
}
/> />
</> </>
); );
@@ -175,12 +175,12 @@ const SubmitDailog = ({
</TableBody> </TableBody>
</Table> </Table>
<DialogFooter className="mt-6"> <DialogFooter className="mt-6">
<Button type="button" color="gray" onClick={handleCancel}>
취소
</Button>
<Button type="submit" color="primary"> <Button type="submit" color="primary">
{submitMode === 'normal' ? '제출' : '예외 제출'} {submitMode === 'normal' ? '제출' : '예외 제출'}
</Button> </Button>
<Button type="button" color="gray" onClick={handleCancel}>
취소
</Button>
</DialogFooter> </DialogFooter>
</form> </form>
</DialogContent> </DialogContent>
@@ -12,7 +12,6 @@ import type {
ApiResponse, ApiResponse,
SearchCondition, SearchCondition,
Sgg, Sgg,
StatisticsLog,
StatisticsLogRequest, StatisticsLogRequest,
} from "@/entities/statistics/model/statistics-interface"; } from "@/entities/statistics/model/statistics-interface";
import { import {
@@ -0,0 +1,973 @@
"use client";
import { useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import {
type ColumnDef,
getCoreRowModel,
type RowSelectionState,
useReactTable,
} from "@tanstack/react-table";
import { client } from "@/shared/api/client";
import { ENDPOINT } from "@/shared/config";
import { useAlertStore } from "@/shared/lib";
import type { PageableList } from "@/shared/model";
import {
type AdstZoneResponseDto,
type SewerStUserItem,
useSewerStUserList,
useStAnlsSidoCombo,
useStAnlsSigunguCombo,
} from "@/entities/statistics";
import {
Button,
Checkbox,
DataTable,
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
Input,
Label,
LoadingWithAnimation,
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@common/components";
interface NtftalkTemplate {
templateCode: string;
templateName: string;
templateContent: string;
}
interface TemplateVariablesResponse {
templateCode: string;
variables: string[];
count: number;
}
interface BusinessSendRequest {
templateCode: string;
callback?: string;
fixedRecipientNum?: string;
recipients: Record<string, string>[];
}
interface BusinessSendResponse {
success: boolean;
sentCount: number;
message: string;
}
interface SelectedRecipient extends SewerStUserItem {
variableOverrides: Record<string, string>;
}
const EMPTY_ADST_LIST: AdstZoneResponseDto[] = [];
const GUBUN_OPTIONS = [
{ value: "PIC", label: "입력자" },
{ value: "IDFR", label: "승인자" },
{ value: "MCTPV", label: "검토자" },
] as const;
const DEFAULT_TEMPLATE_PARAMS = {
sort: "createdAt,desc",
senderKey: "",
inspectionStatus: "APR",
templateMessageType: "BA",
page: 0,
size: 10,
};
function getDefaultStatsYear(): string {
return String(new Date().getFullYear() - 1);
}
function buildTemplateMessage(
templateContent: string,
variables: Record<string, string>,
): string {
return templateContent.replace(/#?\{([^}]+)\}/g, (_, key: string) => {
const value = variables[key.trim()];
return value ?? "";
});
}
function getMergedVariables(
recipient: SelectedRecipient,
commonValues: Record<string, string>,
): Record<string, string> {
return {
...commonValues,
...recipient.variableOverrides,
TEL_NUM: recipient.telNo,
};
}
function NtitlkSndng() {
const alert = useAlertStore((state) => state.setMessage);
const [searchStatsYr, setSearchStatsYr] = useState(getDefaultStatsYear());
const [searchSido, setSearchSido] = useState("");
const [searchSigungu, setSearchSigungu] = useState("");
const [searchGubun, setSearchGubun] = useState("");
const [appliedParams, setAppliedParams] = useState({
statsYr: getDefaultStatsYear(),
sewerBzmnCd: "",
gubun: "",
});
const [selectedTemplateCode, setSelectedTemplateCode] = useState("");
const [selectedRecipients, setSelectedRecipients] = useState<
SelectedRecipient[]
>([]);
const [commonVariableValues, setCommonVariableValues] = useState<
Record<string, string>
>({});
const [commonVariableMapping, setCommonVariableMapping] = useState<
Record<
string,
| "userNm"
| "sido"
| "gugun"
| "gubunNm"
| "deptNm"
| "jbgdNm"
| "telNo"
| "custom"
| ""
>
>({});
const [previewRecipient, setPreviewRecipient] =
useState<SelectedRecipient | null>(null);
const [isPreviewOpen, setIsPreviewOpen] = useState(false);
const [isSending, setIsSending] = useState(false);
const [userListRowSelection, setUserListRowSelection] =
useState<RowSelectionState>({});
const { data: templatePageData } = useQuery({
queryKey: [
ENDPOINT.NTFTALK_SERVICE.TEMP,
"ntitlk-sndng",
DEFAULT_TEMPLATE_PARAMS,
],
queryFn: async () => {
const response = await client.get<PageableList<NtftalkTemplate>>(
ENDPOINT.NTFTALK_SERVICE.TEMP,
{ params: DEFAULT_TEMPLATE_PARAMS },
);
return response.data;
},
});
const templates = templatePageData?.content ?? [];
const { data: templateVariablesData } = useQuery({
queryKey: [
ENDPOINT.NTFTALK_SERVICE.ATA_SEND,
"template-variables",
selectedTemplateCode,
],
queryFn: async () => {
const response = await client.get<TemplateVariablesResponse>(
`${ENDPOINT.NTFTALK_SERVICE.ATA_SEND}/template-variables/${selectedTemplateCode}`,
);
return response.data;
},
enabled: Boolean(selectedTemplateCode),
});
const variableNames = templateVariablesData?.variables ?? [];
const { data: sidoData } = useStAnlsSidoCombo();
const { data: sigunguData } = useStAnlsSigunguCombo(searchSido);
const sidoOptions = sidoData ?? EMPTY_ADST_LIST;
const sigunguOptions = sigunguData ?? EMPTY_ADST_LIST;
const { data: userListResponse, isLoading: isUserListLoading } =
useSewerStUserList(appliedParams);
const userList = (userListResponse as unknown as SewerStUserItem[]) ?? [];
const userListColumns = useMemo<ColumnDef<SewerStUserItem>[]>(
() => [
{
id: "select",
header: ({ table }) => (
<div
className="flex justify-center"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
role="presentation"
>
<Checkbox
checked={
table.getIsAllPageRowsSelected() ||
(table.getIsSomePageRowsSelected() &&
"indeterminate")
}
onCheckedChange={(value) =>
table.toggleAllPageRowsSelected(!!value)
}
aria-label="전체 선택"
/>
</div>
),
cell: ({ row }) => (
<div
className="flex justify-center"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
role="presentation"
>
<Checkbox
checked={row.getIsSelected()}
onCheckedChange={(value) =>
row.toggleSelected(!!value)
}
aria-label="행 선택"
/>
</div>
),
enableSorting: false,
enableHiding: false,
},
{
accessorKey: "userNm",
header: "이름",
},
{
accessorKey: "sido",
header: "시도",
},
{
accessorKey: "gugun",
header: "시군구",
},
{
accessorKey: "gubunNm",
header: "구분",
},
{
accessorKey: "deptNm",
header: "소속",
},
{
accessorKey: "jbgdNm",
header: "직급",
},
{
accessorKey: "telNo",
header: "전화번호",
},
],
[],
);
const userListTable = useReactTable({
data: userList,
columns: userListColumns,
getCoreRowModel: getCoreRowModel(),
enableRowSelection: true,
enableMultiRowSelection: true,
state: {
rowSelection: userListRowSelection,
},
onRowSelectionChange: setUserListRowSelection,
getRowId: (row) => `${row.userNm}-${row.telNo}`,
});
const selectedTemplate = useMemo(
() =>
templates.find(
(template) => template.templateCode === selectedTemplateCode,
),
[templates, selectedTemplateCode],
);
const previewMessage = useMemo(() => {
if (!previewRecipient || !selectedTemplate?.templateContent) return "";
return buildTemplateMessage(
selectedTemplate.templateContent,
getMergedVariables(previewRecipient, commonVariableValues),
);
}, [previewRecipient, selectedTemplate, commonVariableValues]);
const handleTemplateChange = (templateCode: string) => {
setSelectedTemplateCode(templateCode);
setCommonVariableValues({});
setCommonVariableMapping({});
setSelectedRecipients((prev) =>
prev.map((recipient) => ({ ...recipient, variableOverrides: {} })),
);
};
const handleSearch = () => {
const sewerBzmnCd =
searchSido !== ""
? searchSigungu !== ""
? searchSigungu
: searchSido
: "";
setAppliedParams({
statsYr: searchStatsYr,
sewerBzmnCd,
gubun: searchGubun,
});
setUserListRowSelection({});
};
const handleReset = () => {
const defaultYear = getDefaultStatsYear();
setSearchStatsYr(defaultYear);
setSearchSido("");
setSearchSigungu("");
setSearchGubun("");
setAppliedParams({
statsYr: defaultYear,
sewerBzmnCd: "",
gubun: "",
});
setUserListRowSelection({});
};
const handleRemoveRecipient = (telNo: string) => {
setSelectedRecipients((prev) =>
prev.filter((recipient) => recipient.telNo !== telNo),
);
};
const handleAddSelectedToRecipients = () => {
const rows = userListTable.getSelectedRowModel().rows;
if (rows.length === 0) {
alert("추가할 담당자를 선택해주세요.");
return;
}
setSelectedRecipients((prev) => {
const existingTelNos = new Set(prev.map((r) => r.telNo));
const newRecipients = rows
.map((row) => row.original)
.filter((recipient) => !existingTelNos.has(recipient.telNo))
.map((recipient) => ({
...recipient,
variableOverrides: {},
}));
return [...prev, ...newRecipients];
});
setUserListRowSelection({});
};
const handleApplyCommonValues = () => {
setSelectedRecipients((prev) =>
prev.map((recipient) => {
const newOverrides: Record<string, string> = {};
variableNames.forEach((variableName) => {
const mappingType = commonVariableMapping[variableName];
if (!mappingType) return;
if (mappingType === "custom") {
newOverrides[variableName] =
commonVariableValues[variableName] ?? "";
} else {
newOverrides[variableName] =
(recipient[
mappingType as keyof SewerStUserItem
] as string) ?? "";
}
});
return {
...recipient,
variableOverrides: {
...recipient.variableOverrides,
...newOverrides,
},
};
}),
);
setCommonVariableMapping({});
};
const handleResetCommonValues = () => {
setCommonVariableMapping({});
setCommonVariableValues({});
};
const handleRecipientVariableChange = (
telNo: string,
variableName: string,
value: string,
) => {
setSelectedRecipients((prev) =>
prev.map((recipient) =>
recipient.telNo === telNo
? {
...recipient,
variableOverrides: {
...recipient.variableOverrides,
[variableName]: value,
},
}
: recipient,
),
);
};
const handlePreview = (recipient: SelectedRecipient) => {
if (!selectedTemplate) {
alert("알림톡 템플릿을 먼저 선택해주세요.");
return;
}
setPreviewRecipient(recipient);
setIsPreviewOpen(true);
};
const handleSend = async () => {
if (!selectedTemplateCode) {
alert("알림톡 템플릿을 선택해주세요.");
return;
}
if (selectedRecipients.length === 0) {
alert("발송할 담당자를 1명 이상 선택해주세요.");
return;
}
const missingVariable = selectedRecipients.some((recipient) =>
variableNames.some((name) => {
const mergedValue =
recipient.variableOverrides[name] ??
commonVariableValues[name] ??
"";
return mergedValue.trim() === "";
}),
);
if (missingVariable) {
alert("필수 변수값이 입력되지 않은 발송 대상이 있습니다.");
return;
}
const payload: BusinessSendRequest = {
templateCode: selectedTemplateCode,
callback: "032-590-4000",
recipients: selectedRecipients.map((recipient) =>
getMergedVariables(recipient, commonVariableValues),
),
};
try {
setIsSending(true);
const response = await client.post<BusinessSendResponse>(
`${ENDPOINT.NTFTALK_SERVICE.ATA_SEND}/business`,
payload,
);
const data = response.data;
if (!data.success) {
alert(data.message || "알림톡 발송 요청에 실패했습니다.");
return;
}
alert(
data.message ||
`${data.sentCount}건의 알림톡 발송이 요청되었습니다.`,
);
setSelectedRecipients([]);
setCommonVariableValues({});
} catch {
alert("알림톡 발송 중 오류가 발생했습니다.");
} finally {
setIsSending(false);
}
};
return (
<div>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-[32rem_minmax(0,1fr)]">
<section className="card card-border space-y-6 p-4 pb-0">
<div className="space-y-2">
<h3 className="text-xl font-semibold">
알림톡 템플릿 선택
</h3>
<div className="flex items-center gap-3">
<Select
value={selectedTemplateCode}
onValueChange={handleTemplateChange}
>
<SelectTrigger className="w-full">
<SelectValue placeholder="템플릿 선택" />
</SelectTrigger>
<SelectContent>
{templates.map((template) => (
<SelectItem
key={template.templateCode}
value={template.templateCode}
>
{template.templateName}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="space-y-3">
<p className="text-lg font-medium">미리보기</p>
<div className="relative">
<div className="h-[32rem] overflow-auto rounded-[20px] rounded-b-none bg-[rgb(176,192,207)] p-8 pb-0 before:absolute before:left-0 before:top-0 before:block before:h-full before:w-full before:rounded-[20px] before:rounded-b-none before:border-[10px] before:border-b-0 before:border-black before:content-['']">
<div className="w-[calc(100%-2rem)] pb-5">
<span className="text-[1.1rem] text-black">
하수도통계시스템
</span>
<div className="mt-2 rounded-t-[12px] bg-[rgb(247,228,54)] p-4 text-[1.2rem] font-medium text-black">
알림톡 도착
</div>
<div className="whitespace-pre-wrap rounded-b-[12px] bg-white p-4 text-[1.2rem] leading-normal tracking-tight text-black">
{selectedTemplate?.templateContent ??
"알림톡 템플릿을 선택하면 미리보기 메시지가 표시됩니다."}
</div>
</div>
</div>
</div>
</div>
</section>
<section className="card card-border p-4">
<h3 className="text-xl font-semibold">통계 담당자 목록</h3>
<div className="card card-border mx-0 flex items-center p-4">
<div className="flex items-center gap-6">
<div className="flex items-center gap-2">
<Label className="whitespace-nowrap">
시도
</Label>
<Select
value={searchSido}
onValueChange={(value) => {
setSearchSido(value);
setSearchSigungu("");
}}
>
<SelectTrigger className="w-[16rem]">
<SelectValue placeholder="전체" />
</SelectTrigger>
<SelectContent>
{sidoOptions.map((option) => (
<SelectItem
key={option.adstCd}
value={option.adstCd}
>
{option.adstNm}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-2">
<Label className="whitespace-nowrap">
시군구
</Label>
<Select
value={searchSigungu}
onValueChange={setSearchSigungu}
disabled={!searchSido}
>
<SelectTrigger className="w-[16rem]">
<SelectValue placeholder="전체" />
</SelectTrigger>
<SelectContent>
{sigunguOptions.map((option) => (
<SelectItem
key={option.adstCd}
value={option.adstCd}
>
{option.adstNm}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-2">
<Label className="whitespace-nowrap">
구분
</Label>
<Select
value={searchGubun}
onValueChange={setSearchGubun}
>
<SelectTrigger className="w-[16rem]">
<SelectValue placeholder="전체" />
</SelectTrigger>
<SelectContent>
{GUBUN_OPTIONS.map((option) => (
<SelectItem
key={option.value || "ALL"}
value={option.value}
>
{option.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="flex w-full justify-end gap-2">
<Button
color="white"
type="button"
onClick={handleReset}
>
초기화
</Button>
<Button type="button" onClick={handleSearch}>
검색
</Button>
</div>
</div>
<div className="h-[32rem] overflow-x-auto rounded-md border">
{isUserListLoading ? (
<div className="flex items-center justify-center p-6">
<div className="relative flex size-[6rem] justify-center">
<LoadingWithAnimation color="primary" />
</div>
</div>
) : userList.length === 0 ? (
<div className="p-6 text-center text-muted-foreground">
조회된 담당자가 없습니다.
</div>
) : (
<DataTable
table={userListTable}
className="min-w-[72rem] text-sm"
/>
)}
</div>
{!isUserListLoading && userList.length > 0 && (
<div className="mt-3 flex items-center justify-end gap-4">
<p className="text-xl text-muted-foreground">
선택{" "}
<span className="font-semibold text-foreground">
{
userListTable.getSelectedRowModel().rows
.length
}
명
</span>{" "}
/ 전체{" "}
<span className="font-semibold text-foreground">
{userList.length}명
</span>
</p>
<Button
type="button"
onClick={handleAddSelectedToRecipients}
>
+ 발송 목록 추가
</Button>
</div>
)}
</section>
</div>
<section className="card card-border p-4">
<div className="mb-3 flex items-center justify-between">
<h3 className="text-xl font-semibold">발송 목록</h3>
<div className="flex items-center gap-4">
<span className="text-xl font-semibold text-foreground">
{selectedRecipients.length}명
</span>
<Button
type="button"
color="green"
onClick={handleSend}
disabled={isSending}
>
발송
</Button>
</div>
</div>
{variableNames.length > 0 && (
<div className="mb-4 rounded-md border p-3">
<div className="flex items-center justify-between">
<p className="text-lg font-medium">
변수 일괄 적용
</p>
<div className="flex gap-2">
<Button
type="button"
size="sm"
color="white"
onClick={handleResetCommonValues}
>
초기화
</Button>
<Button
type="button"
size="sm"
onClick={handleApplyCommonValues}
>
적용하기
</Button>
</div>
</div>
<div className="grid grid-cols-1 gap-6 md:grid-cols-4 lg:grid-cols-6">
{variableNames.map((variableName) => (
<div key={variableName} className="space-y-2">
<Label className="whitespace-nowrap">{`#{${variableName}}`}</Label>
<Select
value={
commonVariableMapping[
variableName
] ?? ""
}
onValueChange={(value) =>
setCommonVariableMapping(
(prev) => ({
...prev,
[variableName]: value as
| "userNm"
| "sido"
| "gugun"
| "gubunNm"
| "deptNm"
| "jbgdNm"
| "telNo"
| "custom"
| "",
}),
)
}
>
<SelectTrigger>
<SelectValue placeholder="선택하세요" />
</SelectTrigger>
<SelectContent>
<SelectItem value="userNm">
이름
</SelectItem>
<SelectItem value="sido">
시도
</SelectItem>
<SelectItem value="gugun">
시군구
</SelectItem>
<SelectItem value="gubunNm">
구분
</SelectItem>
<SelectItem value="deptNm">
소속
</SelectItem>
<SelectItem value="jbgdNm">
직급
</SelectItem>
<SelectItem value="telNo">
전화번호
</SelectItem>
<SelectItem value="custom">
직접입력
</SelectItem>
</SelectContent>
</Select>
{commonVariableMapping[variableName] ===
"custom" && (
<Input
placeholder="값을 입력하세요"
value={
commonVariableValues[
variableName
] ?? ""
}
onChange={(event) =>
setCommonVariableValues(
(prev) => ({
...prev,
[variableName]:
event.target.value,
}),
)
}
/>
)}
</div>
))}
</div>
</div>
)}
<div className="space-y-4">
{selectedRecipients.length === 0 ? (
<p className="rounded-md border p-6 text-center text-muted-foreground">
선택된 발송 대상이 없습니다.
</p>
) : (
<div className="overflow-x-auto rounded-md border">
<Table variant="line" className="text-sm">
<TableHeader>
<TableRow>
<TableHead className="min-w-[100px]">
이름
</TableHead>
<TableHead className="min-w-[120px]">
전화번호
</TableHead>
{/* <TableHead className="min-w-[80px]">
시도
</TableHead>
<TableHead className="min-w-[100px]">
시군구
</TableHead>
<TableHead className="min-w-[120px]">
소속
</TableHead> */}
{variableNames.map((variableName) => (
<TableHead
key={variableName}
className="min-w-[180px]"
>
#{variableName}
</TableHead>
))}
<TableHead className="min-w-[160px] text-center">
액션
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{selectedRecipients.map((recipient) => (
<TableRow key={recipient.telNo}>
<TableCell align="center">
{recipient.userNm}
</TableCell>
<TableCell align="center">
{recipient.telNo}
</TableCell>
{/* <TableCell align="center">
{recipient.sido}
</TableCell>
<TableCell align="center">
{recipient.gugun}
</TableCell>
<TableCell align="center">
{recipient.deptNm}
</TableCell> */}
{variableNames.map(
(variableName) => (
<TableCell
key={`${recipient.telNo}-${variableName}`}
>
<Input
value={
recipient
.variableOverrides[
variableName
] ?? ""
}
onChange={(event) =>
handleRecipientVariableChange(
recipient.telNo,
variableName,
event.target
.value,
)
}
className="w-full min-w-[150px]"
/>
</TableCell>
),
)}
<TableCell align="center">
<div className="flex justify-center gap-1">
<Button
type="button"
size="sm"
color="gray"
onClick={() =>
handlePreview(
recipient,
)
}
>
미리보기
</Button>
<Button
type="button"
size="sm"
color="red"
onClick={() =>
handleRemoveRecipient(
recipient.telNo,
)
}
>
제거
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</div>
</section>
<Dialog open={isPreviewOpen} onOpenChange={setIsPreviewOpen}>
<DialogContent
className="max-w-[36rem]"
aria-describedby={undefined}
>
<DialogHeader>
<DialogTitle>알림톡 미리보기</DialogTitle>
<DialogDescription className="text-[1.1rem] tracking-tight">
수신자: {previewRecipient?.userNm ?? "-"} /{" "}
{previewRecipient?.telNo ?? "-"}
</DialogDescription>
</DialogHeader>
<div className="relative">
<div className="h-[32rem] overflow-auto rounded-[20px] rounded-b-none bg-[rgb(176,192,207)] p-8 pb-0 before:absolute before:left-0 before:top-0 before:block before:h-full before:w-full before:rounded-[20px] before:rounded-b-none before:border-[10px] before:border-b-0 before:border-black before:content-['']">
<div className="w-[calc(100%-2rem)] pb-5">
<span className="text-[1.1rem] text-black">
하수도통계시스템
</span>
<div className="mt-2 rounded-t-[12px] bg-[rgb(247,228,54)] p-4 text-[1.2rem] font-medium text-black">
알림톡 도착
</div>
<div className="whitespace-pre-wrap rounded-b-[12px] bg-white p-4 text-[1.2rem] leading-normal tracking-tight text-black">
{previewMessage ||
"메시지를 생성할 수 없습니다."}
</div>
</div>
</div>
</div>
<DialogFooter>
<DialogClose asChild>
<Button type="button" color="white">
닫기
</Button>
</DialogClose>
</DialogFooter>
</DialogContent>
</Dialog>
</div>
);
}
export default NtitlkSndng;
@@ -0,0 +1,22 @@
const CellColorInfo = () => {
return (
<div className="m-[0.6rem] flex justify-end">
<div className="flex justify-end items-center gap-[1.2rem] !text-xl bg-white w-fit py-3 px-5 border border-slate-200/80 rounded-md">
<div className="flex justify-center items-center gap-x-2">
<div className="w-8 h-6 bg-[#feee85]"></div>
<span>요약표</span>
</div>
<div className="flex justify-center items-center gap-x-2">
<div className="w-8 h-6 bg-[#fff7bf]"></div>
<span>합계</span>
</div>
<div className="flex justify-center items-center gap-x-2">
<div className="w-8 h-6 bg-[#ffe9cf]"></div>
<span>소계</span>
</div>
</div>
</div>
);
};
export default CellColorInfo;
@@ -1,10 +1,202 @@
import { useRef, useState } from "react";
import { useAlertStore } from "@/shared/lib";
import { statisticsTotalStatusApi } from "@/entities/statistics/api/statistics-total-service";
import { LoadingWithAnimation, Tabs, TabsContent, TabsList, TabsTrigger } from "@common/components";
import SearchForm from "@/components/module/SearchForm"; import SearchForm from "@/components/module/SearchForm";
import DataGrid from "@/components/module/DataGrid";
import type { ColumnInfo } from "@/components/type/DataGrid.type";
import type { SearchFormValues } from "@/components/type/SearchForm.type";
import { SewagePipeMaintainColumnListTot } from "@/components/util/column/total/sewagePipeMaintain/sewagePipeMaintainColumn";
import { toGridRows } from "@/components/util/grid/gridFunction";
import type { SewagePipeMaintainTotalRequest } from "@/entities/statistics/model/statistics-total/statistics-sewage-pipe-maintain-total-interface";
const firstTabKey = SewagePipeMaintainColumnListTot[0]?.tabKey ?? "ST00030001";
function buildSewagePipeMaintainTotSearchParam(values: SearchFormValues): SewagePipeMaintainTotalRequest {
return {
ctpvNm: values.sido === "ALL" ? "" : values.sido,
sggNm: values.gugun === "ALL" ? "" : values.gugun,
sewerBzmnCd: values.bsnmCd,
statsYr: values.year,
rowDataYn: values.isDetail,
};
}
const SewagePipeMaintainTot = () => { const SewagePipeMaintainTot = () => {
const { setMessage: alert } = useAlertStore((state) => state);
const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(new Map());
const [isLoading, setIsLoading] = useState(false);
const [activeTab, setActiveTab] = useState(firstTabKey);
const lastSearchedValuesRef = useRef<SearchFormValues | null>(null);
const columnInfo = SewagePipeMaintainColumnListTot;
const handleReset = () => {
setRowDataMap(new Map());
setActiveTab(firstTabKey);
lastSearchedValuesRef.current = null;
};
const loadSewagePipeMaintainTotTabData = async (
tabKey: string,
values: SearchFormValues,
mergeIntoExistingMap: boolean,
): Promise<boolean> => {
const param = buildSewagePipeMaintainTotSearchParam(values);
const applyRows = (rows: Record<string, string | number>[]) => {
if (mergeIntoExistingMap) {
setRowDataMap((prev) => {
const next = new Map(prev);
next.set(tabKey, rows);
return next;
});
} else {
const next = new Map<string, Record<string, string | number>[]>();
next.set(tabKey, rows);
setRowDataMap(next);
}
};
if (tabKey === "ST00030001") {
const response = await statisticsTotalStatusApi.getSewagePipeMaintainRepairTotal(param);
if (response.status === "success" && response.data) {
applyRows(toGridRows(response.data as object[]));
return true;
}
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
return false;
}
if (tabKey === "ST00030002") {
const response = await statisticsTotalStatusApi.getSewagePipeMaintainDredgingTotal(param);
if (response.status === "success" && response.data) {
applyRows(toGridRows(response.data as object[]));
return true;
}
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
return false;
}
return false;
};
const handleSearch = async (values: SearchFormValues) => {
try {
setIsLoading(true);
let ok = false;
if (activeTab === "ST00030001" || activeTab === "ST00030002") {
ok = await loadSewagePipeMaintainTotTabData(activeTab, values, true);
}
if (ok) {
lastSearchedValuesRef.current = values;
} else {
lastSearchedValuesRef.current = null;
}
} catch {
alert("데이터 조회 중 오류가 발생했습니다.");
lastSearchedValuesRef.current = null;
} finally {
setIsLoading(false);
}
};
const handleActiveTabChange = async (tabKey: string) => {
setActiveTab(tabKey);
const values = lastSearchedValuesRef.current;
if (!values) return;
const existing = rowDataMap.get(tabKey);
const hasData = Array.isArray(existing) && existing.length > 0;
if (hasData) return;
if (tabKey === "ST00030001" || tabKey === "ST00030002") {
try {
setIsLoading(true);
await loadSewagePipeMaintainTotTabData(tabKey, values, true);
} catch {
alert("데이터 조회 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
}
};
return ( return (
<> <div className="relative">
<SearchForm /> <SearchForm isDetail={true} onSubmit={handleSearch} onReset={handleReset} sidoSelectText="전체" />
</> {isLoading && (
<div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
<div className="flex flex-col gap-[0.6rem] mx-[0.6rem]">
<Tabs
value={activeTab}
onValueChange={(v) => void handleActiveTabChange(v)}
className="w-full"
variant="default"
>
<TabsList>
{columnInfo.map((info) => (
<TabsTrigger key={info.tabKey} value={info.tabKey}>
{info.tabLabel || info.tabKey}
</TabsTrigger>
))}
</TabsList>
{columnInfo.map((info) => {
const tabKey = info.tabKey;
if (!info.columns || !info.columnLayout) {
return null;
}
const rowData = rowDataMap.get(tabKey) ?? [];
const gridColumnInfo: ColumnInfo = {
columns: info.columns,
columnLayout: info.columnLayout,
};
return (
<TabsContent key={tabKey} value={tabKey}>
<DataGrid
columnInfo={gridColumnInfo}
rowStartNum={info.rowStartNum}
excelExportFileSuffix={info.tabLabel || tabKey}
rowData={rowData}
setRowData={(updater) => {
setRowDataMap((prev) => {
const next = new Map(prev);
const cur = next.get(tabKey) ?? [];
const n =
typeof updater === "function" ? updater(cur) : updater;
next.set(tabKey, n);
return next;
});
}}
isExcelImport={false}
isExcelExport
showHeaderCheckbox={false}
fixedColumns={info.fixedColumns}
enableSort={false}
cellStyleCallback={({ row }) => {
const rowType = String(row.rowType ?? "");
if (rowType === "DETAIL") return undefined;
if (rowType === "BIZ_SUM") return "rg-cell-rowtype-biz-sum";
return "rg-cell-rowtype-other";
}}
/>
</TabsContent>
);
})}
</Tabs>
</div>
</div>
); );
}; };
@@ -1,4 +1,4 @@
import { useMemo, useState } from "react"; import { useRef, useState } from "react";
import { useAlertStore } from "@/shared/lib"; import { useAlertStore } from "@/shared/lib";
import { statisticsTotalStatusApi } from "@/entities/statistics/api/statistics-total-service"; import { statisticsTotalStatusApi } from "@/entities/statistics/api/statistics-total-service";
@@ -6,71 +6,165 @@ import { LoadingWithAnimation, Tabs, TabsContent, TabsList, TabsTrigger } from "
import SearchForm from "@/components/module/SearchForm"; import SearchForm from "@/components/module/SearchForm";
import DataGrid from "@/components/module/DataGrid"; import DataGrid from "@/components/module/DataGrid";
import type { ColumnConfig, ColumnInfo, ColumnInfoList } from "@/components/type/DataGrid.type"; import type { ColumnInfo } from "@/components/type/DataGrid.type";
import type { SearchFormValues } from "@/components/type/SearchForm.type"; import type { SearchFormValues } from "@/components/type/SearchForm.type";
import { SewagePipeColumnInfoListTot } from "@/components/util/column/total/SewagePipeTotColumn"; import { SewagePipeColumnInfoListTot } from "@/components/util/column/total/SewagePipeTotColumn";
import { toGridRows } from "@/components/util/grid/gridFunction"; import { toGridRows } from "@/components/util/grid/gridFunction";
import type { SewagePipeTotalRequest } from "@/entities/statistics/model/statistics-total/statistics-sewage-pipe-total-interface";
const firstTabKey = SewagePipeColumnInfoListTot[0]?.tabKey ?? "ST00020001"; const firstTabKey = SewagePipeColumnInfoListTot[0]?.tabKey ?? "ST00020001";
function buildSewagePipeTotSearchParam(values: SearchFormValues): SewagePipeTotalRequest {
return {
ctpvNm: values.sido === "ALL" ? "" : values.sido,
sggNm: values.gugun === "ALL" ? "" : values.gugun,
sewerBzmnCd: values.bsnmCd,
statsYr: values.year,
rowDataYn: values.isDetail,
};
}
const SewagePipeTot = () => { const SewagePipeTot = () => {
const { setMessage: alert } = useAlertStore((state) => state); const { setMessage: alert } = useAlertStore((state) => state);
const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(new Map()); const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(new Map());
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [activeTab, setActiveTab] = useState(firstTabKey); const [activeTab, setActiveTab] = useState(firstTabKey);
/** 조회 성공 후 탭 전환 시 동일 조건으로 지연 조회 */
const lastSearchedValuesRef = useRef<SearchFormValues | null>(null);
const columnInfo = useMemo( const columnInfo = SewagePipeColumnInfoListTot;
() =>
SewagePipeColumnInfoListTot.map((tab: ColumnInfoList) => ({
...tab,
columns: (tab.columns ?? []).map((col: ColumnConfig) => ({
...col,
editable: false as const,
styleName: col.styleName ?? ("rg-cell-readonly" as const),
})),
})),
[],
);
const handleReset = () => { const handleReset = () => {
setRowDataMap(new Map()); setRowDataMap(new Map());
setActiveTab(firstTabKey); setActiveTab(firstTabKey);
lastSearchedValuesRef.current = null;
};
/** SewagePipeInp의 `loadSewagePipeActiveTabData`와 동일 역할: 탭키별 API 호출 후 `rowDataMap` 반영 */
const loadSewagePipeTotTabData = async (
tabKey: string,
values: SearchFormValues,
mergeIntoExistingMap: boolean,
): Promise<boolean> => {
const param = buildSewagePipeTotSearchParam(values);
const applyRows = (rows: Record<string, string | number>[]) => {
if (mergeIntoExistingMap) {
setRowDataMap((prev) => {
const next = new Map(prev);
next.set(tabKey, rows);
return next;
});
} else {
const next = new Map<string, Record<string, string | number>[]>();
next.set(tabKey, rows);
setRowDataMap(next);
}
};
if (tabKey === "ST00020001") {
const response = await statisticsTotalStatusApi.getSewagePipeRegionalStatusList(param);
if (response.status === "success" && response.data) {
applyRows(toGridRows(response.data as object[]));
return true;
}
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
return false;
}
if (tabKey === "ST00020002") {
const response = await statisticsTotalStatusApi.getSewagePipeFactInstallStatus(param);
if (response.status === "success" && response.data) {
applyRows(toGridRows(response.data as object[]));
return true;
}
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
return false;
}
if (tabKey === "ST00020003") {
const response = await statisticsTotalStatusApi.getSewagePipePipeTypeFacilityStatus(param);
if (response.status === "success" && response.data) {
applyRows(toGridRows(response.data as object[]));
return true;
}
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
return false;
}
if (tabKey === "ST00020004") {
const response = await statisticsTotalStatusApi.getSewagePipePipeDiamStatus(param);
if (response.status === "success" && response.data) {
applyRows(toGridRows(response.data as object[]));
return true;
}
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
return false;
}
return false;
}; };
const handleSearch = async (values: SearchFormValues) => { const handleSearch = async (values: SearchFormValues) => {
setActiveTab(firstTabKey);
setRowDataMap(new Map());
try { try {
setIsLoading(true); setIsLoading(true);
const param = { // SewagePipeInp과 동일: 검색 시 활성 탭 데이터만 조회·맵 병합
ctpvNm: values.sido === "ALL" ? "" : values.sido, let ok = false;
sggNm: values.gugun === "ALL" ? "" : values.gugun, if (
sewerBzmnCd: values.bsnmCd, activeTab === "ST00020001" ||
statsYr: values.year, activeTab === "ST00020002" ||
rowDataYn: values.isDetail, activeTab === "ST00020003" ||
}; activeTab === "ST00020004"
) {
const response = await statisticsTotalStatusApi.getSewagePipeRegionalStatusList(param); ok = await loadSewagePipeTotTabData(activeTab, values, true);
}
if (response.status === "success" && response.data) { if (ok) {
const next = new Map<string, Record<string, string | number>[]>(); lastSearchedValuesRef.current = values;
next.set("ST00020001", toGridRows(response.data as object[]));
setRowDataMap(next);
} else { } else {
alert(response.message || "데이터 조회 중 오류가 발생했습니다."); lastSearchedValuesRef.current = null;
} }
} catch { } catch {
alert("데이터 조회 중 오류가 발생했습니다."); alert("데이터 조회 중 오류가 발생했습니다.");
lastSearchedValuesRef.current = null;
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
const handleActiveTabChange = async (tabKey: string) => {
setActiveTab(tabKey);
const values = lastSearchedValuesRef.current;
if (!values) return;
const existing = rowDataMap.get(tabKey);
const hasData = Array.isArray(existing) && existing.length > 0;
if (hasData) return;
if (
tabKey === "ST00020001" ||
tabKey === "ST00020002" ||
tabKey === "ST00020003" ||
tabKey === "ST00020004"
) {
try {
setIsLoading(true);
await loadSewagePipeTotTabData(tabKey, values, true);
} catch {
alert("데이터 조회 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
return;
}
console.log("[SewagePipeTot] tabKey (API 미연결):", tabKey);
};
return ( return (
<div className="relative"> <div className="relative">
<SearchForm isDetail={true} onSubmit={handleSearch} onReset={handleReset} /> <SearchForm isDetail={true} onSubmit={handleSearch} onReset={handleReset} sidoSelectText="전체" />
{isLoading && ( {isLoading && (
<div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center"> <div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center">
<div className="relative size-[5rem]"> <div className="relative size-[5rem]">
@@ -81,7 +175,7 @@ const SewagePipeTot = () => {
<div className="flex flex-col gap-[0.6rem] mx-[0.6rem]"> <div className="flex flex-col gap-[0.6rem] mx-[0.6rem]">
<Tabs <Tabs
value={activeTab} value={activeTab}
onValueChange={setActiveTab} onValueChange={(v) => void handleActiveTabChange(v)}
className="w-full" className="w-full"
variant="default" variant="default"
> >
@@ -8,6 +8,7 @@ import { useAlertStore } from "@/shared/lib";
import SearchForm from "@/components/module/SearchForm"; import SearchForm from "@/components/module/SearchForm";
import DataGrid from "@/components/module/DataGrid"; import DataGrid from "@/components/module/DataGrid";
import CellColorInfo from "./CellColorInfo";
import { LoadingWithAnimation } from "@common/components"; import { LoadingWithAnimation } from "@common/components";
const SeweragePenetrationRateTot = () => { const SeweragePenetrationRateTot = () => {
@@ -19,12 +20,17 @@ const SeweragePenetrationRateTot = () => {
try { try {
setIsLoading(true); setIsLoading(true);
const isSummaryEnabled = values.isSummary !== 'ALL';
const summaryYearCnt = isSummaryEnabled ? Number(values.isSummary) : undefined;
const param = { const param = {
ctpvNm: values.sido === 'ALL' ? '' : values.sido, ctpvNm: values.sido === 'ALL' ? '' : values.sido,
sggNm: values.gugun === 'ALL' ? '' : values.gugun, sggNm: values.gugun === 'ALL' ? '' : values.gugun,
sewerBzmnCd: values.bsnmCd, sewerBzmnCd: values.bsnmCd,
statsYr: values.year, statsYr: values.year,
rowDataYn: values.isDetail rowDataYn: values.isDetail,
summaryYn: isSummaryEnabled,
...(isSummaryEnabled ? { summaryYearCnt } : {}),
}; };
const response = await statisticsTotalStatusApi.getSewerageSupplyRateList(param); const response = await statisticsTotalStatusApi.getSewerageSupplyRateList(param);
@@ -35,7 +41,8 @@ const SeweragePenetrationRateTot = () => {
} else { } else {
alert(response.message || '데이터 조회 중 오류가 발생했습니다.'); alert(response.message || '데이터 조회 중 오류가 발생했습니다.');
} }
} catch { } catch (error) {
console.log(error)
alert('데이터 조회 중 오류가 발생했습니다.'); alert('데이터 조회 중 오류가 발생했습니다.');
} finally { } finally {
setIsLoading(false); setIsLoading(false);
@@ -44,12 +51,13 @@ const SeweragePenetrationRateTot = () => {
return ( return (
<> <>
<SearchForm isDetail={true} onSubmit={handleSearch} sidoSelectText="전체" /> <SearchForm isDetail={true} isSummary={true} onSubmit={handleSearch} sidoSelectText="전체" />
{isLoading && <div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center"> {isLoading && <div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center">
<div className="relative size-[5rem]"> <div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" /> <LoadingWithAnimation color="primary" />
</div> </div>
</div>} </div>}
<CellColorInfo />
<DataGrid <DataGrid
columnInfo={SeweragePentrationRateTotColumn} columnInfo={SeweragePentrationRateTotColumn}
rowStartNum={2} rowStartNum={2}
@@ -61,6 +69,7 @@ const SeweragePenetrationRateTot = () => {
const rowType = String(row.rowType ?? ''); const rowType = String(row.rowType ?? '');
if (rowType === 'DETAIL') return undefined; if (rowType === 'DETAIL') return undefined;
if (rowType === 'BIZ_SUM') return 'rg-cell-rowtype-biz-sum'; if (rowType === 'BIZ_SUM') return 'rg-cell-rowtype-biz-sum';
if (rowType === 'SUMMARY') return 'rg-cell-rowtype-summary';
return 'rg-cell-rowtype-other'; return 'rg-cell-rowtype-other';
}} }}
/> />
@@ -1,14 +1,14 @@
import { useEffect, useMemo, useState } from "react"; import { useRef, useState } from "react";
import { useAlertStore } from "@/shared/lib"; import { useAlertStore } from "@/shared/lib";
import { statisticsTotalStatusApi } from "@/entities/statistics/api/statistics-total-service"; import { statisticsTotalStatusApi } from "@/entities/statistics/api/statistics-total-service";
import { toGridRows } from "@/components/util/grid/gridFunction"; import { toGridRows } from "@/components/util/grid/gridFunction";
import SearchForm from "@/components/module/SearchForm"; import SearchForm from "@/components/module/SearchForm";
import TabDataGrid from "@/components/module/TabDataGrid"; import DataGrid from "@/components/module/DataGrid";
import { LoadingWithAnimation } from "@common/components"; import { LoadingWithAnimation, Tabs, TabsContent, TabsList, TabsTrigger } from "@common/components";
import type { ColumnConfig, ColumnInfoList } from "@/components/type/DataGrid.type"; import type { ColumnInfo } from "@/components/type/DataGrid.type";
import type { SearchFormValues } from "@/components/type/SearchForm.type"; import type { SearchFormValues } from "@/components/type/SearchForm.type";
import { ComplaintInpColumn } from "@/components/util/column/total/sewerageServiceLevel/ComplaintTotColumn"; import { ComplaintInpColumn } from "@/components/util/column/total/sewerageServiceLevel/ComplaintTotColumn";
import { ResidentFriendlyFactTotColumn } from "@/components/util/column/total/sewerageServiceLevel/ResidentFriendlyFactTotColumn"; import { ResidentFriendlyFactTotColumn } from "@/components/util/column/total/sewerageServiceLevel/ResidentFriendlyFactTotColumn";
@@ -17,81 +17,111 @@ const SewerageServiceLevelInpTabList = [
ComplaintInpColumn, ComplaintInpColumn,
ResidentFriendlyFactTotColumn, ResidentFriendlyFactTotColumn,
]; ];
const SUPPORTED_TAB_KEYS = [ComplaintInpColumn.tabKey, ResidentFriendlyFactTotColumn.tabKey] as const;
const SewerageServiceLevelTot = () => { const SewerageServiceLevelTot = () => {
const { setMessage: alert } = useAlertStore((state) => state); const { setMessage: alert } = useAlertStore((state) => state);
const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(new Map()); const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(new Map());
const [isLoading, setIsLoading] = useState<boolean>(false); const [isLoading, setIsLoading] = useState<boolean>(false);
const [activeTab, setActiveTab] = useState(ComplaintInpColumn.tabKey); const [activeTab, setActiveTab] = useState(ComplaintInpColumn.tabKey);
const [lastSearchValues, setLastSearchValues] = useState<SearchFormValues | null>(null); const lastSearchValuesRef = useRef<SearchFormValues | null>(null);
const columnInfo = useMemo( const columnInfo = SewerageServiceLevelInpTabList;
() =>
SewerageServiceLevelInpTabList.map((tab: ColumnInfoList) => ({
...tab,
columns: (tab.columns ?? []).map((col: ColumnConfig) => ({
...col,
editable: false as const,
styleName: col.styleName ?? ("rg-cell-readonly" as const),
})),
})),
[],
);
const handleReset = () => { const handleReset = () => {
setRowDataMap(new Map()); setRowDataMap(new Map());
setActiveTab(ComplaintInpColumn.tabKey); setActiveTab(ComplaintInpColumn.tabKey);
setLastSearchValues(null); lastSearchValuesRef.current = null;
}; };
const fetchByTab = async (tabKey: string, values: SearchFormValues) => { const loadSewerageServiceLevelTotTabData = async (
try { tabKey: string,
setIsLoading(true); values: SearchFormValues,
mergeIntoExistingMap: boolean,
) => {
const param = {
ctpvNm: values.sido === "ALL" ? "" : values.sido,
sggNm: values.gugun === "ALL" ? "" : values.gugun,
sewerBzmnCd: values.bsnmCd,
statsYr: values.year,
rowDataYn: values.isDetail,
};
const param = { const fetcherMap = {
ctpvNm: values.sido === "ALL" ? "" : values.sido, [ComplaintInpColumn.tabKey]: statisticsTotalStatusApi.getSewerageServiceLevelComplaint.bind(
sggNm: values.gugun === "ALL" ? "" : values.gugun, statisticsTotalStatusApi,
sewerBzmnCd: values.bsnmCd, ),
statsYr: values.year, [ResidentFriendlyFactTotColumn.tabKey]:
rowDataYn: values.isDetail, statisticsTotalStatusApi.getSewerageServiceLevelResidentFriendlyFact.bind(
}; statisticsTotalStatusApi,
),
};
const fetcher = fetcherMap[tabKey];
if (!fetcher) {
return false;
}
const response = await fetcher(param);
let response; if (response.status === "success" && response.data) {
if (tabKey === ResidentFriendlyFactTotColumn.tabKey) { const rows = toGridRows(response.data as object[]);
response = if (mergeIntoExistingMap) {
await statisticsTotalStatusApi.getSewerageServiceLevelResidentFriendlyFact(param);
} else {
response =
await statisticsTotalStatusApi.getSewerageServiceLevelComplaint(param);
}
if (response.status === "success" && response.data) {
setRowDataMap((prev) => { setRowDataMap((prev) => {
const next = new Map(prev); const next = new Map(prev);
next.set(tabKey, toGridRows(response.data as object[])); next.set(tabKey, rows);
return next; return next;
}); });
} else { } else {
alert(response.message || "데이터 조회 중 오류가 발생했습니다."); const next = new Map<string, Record<string, string | number>[]>();
next.set(tabKey, rows);
setRowDataMap(next);
}
return true;
}
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
return false;
};
const handleSearch = async (values: SearchFormValues) => {
try {
setIsLoading(true);
let ok = false;
if (SUPPORTED_TAB_KEYS.includes(activeTab)) {
ok = await loadSewerageServiceLevelTotTabData(activeTab, values, true);
}
if (ok) {
lastSearchValuesRef.current = values;
} else {
lastSearchValuesRef.current = null;
} }
} catch { } catch {
alert("데이터 조회 중 오류가 발생했습니다."); alert("데이터 조회 중 오류가 발생했습니다.");
lastSearchValuesRef.current = null;
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
const handleSearch = async (values: SearchFormValues) => { const handleActiveTabChange = async (tabKey: string) => {
setLastSearchValues(values); setActiveTab(tabKey);
setRowDataMap(new Map());
await fetchByTab(activeTab, values);
};
useEffect(() => { const values = lastSearchValuesRef.current;
if (lastSearchValues == null) return; if (!values) return;
if (rowDataMap.has(activeTab)) return;
void fetchByTab(activeTab, lastSearchValues); const existing = rowDataMap.get(tabKey);
}, [activeTab]); const hasData = Array.isArray(existing) && existing.length > 0;
if (hasData) return;
if (SUPPORTED_TAB_KEYS.includes(tabKey)) {
try {
setIsLoading(true);
await loadSewerageServiceLevelTotTabData(tabKey, values, true);
} catch {
alert("데이터 조회 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
}
};
return ( return (
<div className="relative"> <div className="relative">
@@ -103,20 +133,60 @@ const SewerageServiceLevelTot = () => {
</div> </div>
</div> </div>
)} )}
<TabDataGrid <div className="flex flex-col gap-[0.6rem] mx-[0.6rem]">
columnInfo={columnInfo} <Tabs value={activeTab} onValueChange={(v) => void handleActiveTabChange(v)} className="w-full" variant="default">
isExcelImport={false} <TabsList>
rowDataMap={rowDataMap} {columnInfo.map((info) => (
setRowDataMap={setRowDataMap} <TabsTrigger key={info.tabKey} value={info.tabKey}>
activeTab={activeTab} {info.tabLabel || info.tabKey}
onActiveTabChange={setActiveTab} </TabsTrigger>
cellStyleCallback={({ row }) => { ))}
const rowType = String(row.rowType ?? ""); </TabsList>
if (rowType === "DETAIL") return undefined; {columnInfo.map((info) => {
if (rowType === "BIZ_SUM") return "rg-cell-rowtype-biz-sum"; const tabKey = info.tabKey;
return "rg-cell-rowtype-other"; if (!info.columns || !info.columnLayout) {
}} return null;
/> }
const rowData = rowDataMap.get(tabKey) ?? [];
const gridColumnInfo: ColumnInfo = {
columns: info.columns,
columnLayout: info.columnLayout,
};
return (
<TabsContent key={tabKey} value={tabKey}>
<DataGrid
columnInfo={gridColumnInfo}
rowStartNum={info.rowStartNum}
excelExportFileSuffix={info.tabLabel || tabKey}
rowData={rowData}
setRowData={(updater) => {
setRowDataMap((prev) => {
const next = new Map(prev);
const cur = next.get(tabKey) ?? [];
const n = typeof updater === "function" ? updater(cur) : updater;
next.set(tabKey, n);
return next;
});
}}
isExcelImport={false}
isExcelExport
showHeaderCheckbox={false}
fixedColumns={info.fixedColumns}
enableSort={false}
cellStyleCallback={({ row }) => {
const rowType = String(row.rowType ?? "");
if (rowType === "DETAIL") return undefined;
if (rowType === "BIZ_SUM") return "rg-cell-rowtype-biz-sum";
return "rg-cell-rowtype-other";
}}
/>
</TabsContent>
);
})}
</Tabs>
</div>
</div> </div>
); );
}; };
@@ -129,6 +129,7 @@ const DEFAULT_FILTERS: StatisticsVerificationFilterState = {
statsYr: String(dayjs().year() - 1), statsYr: String(dayjs().year() - 1),
sewerBzmnCd: null, sewerBzmnCd: null,
statsCd: null, statsCd: null,
laeSbmsnSttsCd: "2",
}; };
const DEFAULT_SUB_FILTERS: StatisticsVerificationSubFilterState = { const DEFAULT_SUB_FILTERS: StatisticsVerificationSubFilterState = {
@@ -156,15 +157,6 @@ function StatisticsVerificationReport() {
useState<StatisticsVerificationFilterState>(DEFAULT_FILTERS); useState<StatisticsVerificationFilterState>(DEFAULT_FILTERS);
const [subFilters, setSubFilters] = const [subFilters, setSubFilters] =
useState<StatisticsVerificationSubFilterState>(DEFAULT_SUB_FILTERS); useState<StatisticsVerificationSubFilterState>(DEFAULT_SUB_FILTERS);
const [submittedFilters, setSubmittedFilters] =
useState<StatisticsVerificationFilterState>(DEFAULT_FILTERS);
const [submittedParams, setSubmittedParams] = useState<{
main: StatisticsVerificationFilterState;
sub: StatisticsVerificationSubFilterState;
}>({
main: DEFAULT_FILTERS,
sub: DEFAULT_SUB_FILTERS,
});
const [selectedReportRows, setSelectedReportRows] = useState< const [selectedReportRows, setSelectedReportRows] = useState<
StatsInputStatusList[] StatsInputStatusList[]
>([]); >([]);
@@ -182,11 +174,30 @@ function StatisticsVerificationReport() {
const { data: sigunguData } = useStAnlsSigunguCombo( const { data: sigunguData } = useStAnlsSigunguCombo(
filters.sewerBzmnCd ?? "", filters.sewerBzmnCd ?? "",
); );
const detailParams = useMemo(
() => ({
statsYr: filters.statsYr,
ctpvNm:
subFilters.ctpvNm !== "" ? subFilters.ctpvNm : filters.ctpvNm,
sggNm: subFilters.sggNm !== "" ? subFilters.sggNm : filters.sggNm,
sewerBzmnCd:
subFilters.sewerBzmnCd !== ""
? subFilters.sewerBzmnCd
: filters.sewerBzmnCd,
statsCd:
subFilters.statsCd !== ""
? subFilters.statsCd
: filters.statsCd,
prcsYnList: subFilters.prcsYnList,
pbcpAprvYn: subFilters.pbcpAprvYn,
laeSbmsnSttsCd: subFilters.laeSbmsnSttsCd,
}),
[filters, subFilters],
);
const statisticsVerificationReportQuery = const statisticsVerificationReportQuery = useStatsVrfcRptData(filters);
useStatsVrfcRptData(submittedFilters);
const statisticsVerificationResultQuery = const statisticsVerificationResultQuery =
useStatsVrfcRsltData(submittedParams); useStatsVrfcRsltData(detailParams);
const statisticsVerificationReportData = const statisticsVerificationReportData =
statisticsVerificationReportQuery.data ?? []; statisticsVerificationReportQuery.data ?? [];
@@ -253,11 +264,17 @@ function StatisticsVerificationReport() {
const nextRows = statisticsVerificationResultGridRows; const nextRows = statisticsVerificationResultGridRows;
const prevLength = prevLengthRef.current; const prevLength = prevLengthRef.current;
if (!dataProvider || nextRows.length === 0) { if (!dataProvider) {
prevLengthRef.current = nextRows.length; prevLengthRef.current = nextRows.length;
return; return;
} }
if (nextRows.length === 0) {
dataProvider.setRows?.([]);
prevLengthRef.current = 0;
return;
}
if (nextRows.length > prevLength && prevLength > 0) { if (nextRows.length > prevLength && prevLength > 0) {
// 무한스크롤 시 데이터 처리 // 무한스크롤 시 데이터 처리
const newRows = nextRows.slice(prevLength); const newRows = nextRows.slice(prevLength);
@@ -327,17 +344,16 @@ function StatisticsVerificationReport() {
statisticsVerificationReportQuery.isError, statisticsVerificationReportQuery.isError,
]); ]);
function handleSearch( function resetResultState() {
nextFilters: StatisticsVerificationFilterState,
nextSubFilters: StatisticsVerificationSubFilterState,
) {
setSelectedReportRows([]);
setSelectedResultRows([]); setSelectedResultRows([]);
setSubmittedFilters({ ...nextFilters }); editedResultRowMapRef.current = new Map();
setSubmittedParams({ prevLengthRef.current = 0;
main: { ...nextFilters }, resultGridRef.current?.dataProvider?.setRows?.([]);
sub: { ...nextSubFilters }, }
});
function resetReportState() {
setSelectedReportRows([]);
resetResultState();
} }
async function handleLoadMoreDetail() { async function handleLoadMoreDetail() {
@@ -350,14 +366,6 @@ function StatisticsVerificationReport() {
} }
} }
function handleResultSearch() {
setSelectedResultRows([]);
setSubmittedParams({
main: { ...filters },
sub: { ...subFilters },
});
}
function handleFilterChange< function handleFilterChange<
K extends keyof StatisticsVerificationFilterState, K extends keyof StatisticsVerificationFilterState,
>(key: K) { >(key: K) {
@@ -365,6 +373,7 @@ function StatisticsVerificationReport() {
value?: StatisticsVerificationFilterState[K], value?: StatisticsVerificationFilterState[K],
optionData?: { label: string; value: string }, optionData?: { label: string; value: string },
) => { ) => {
resetReportState();
if (key === "sewerBzmnCd") { if (key === "sewerBzmnCd") {
setFilters((prev) => ({ setFilters((prev) => ({
...prev, ...prev,
@@ -372,8 +381,17 @@ function StatisticsVerificationReport() {
sewerBzmnCd: optionData?.value, sewerBzmnCd: optionData?.value,
sggNm: "", sggNm: "",
})); }));
setSubFilters((prev) => ({
...prev,
ctpvNm: "",
sggNm: "",
sewerBzmnCd: "",
}));
return; return;
} }
if (key === "statsCd") {
setSubFilters((prev) => ({ ...prev, statsCd: "" }));
}
setFilters((prev) => ({ ...prev, [key]: value })); setFilters((prev) => ({ ...prev, [key]: value }));
}; };
} }
@@ -382,10 +400,16 @@ function StatisticsVerificationReport() {
K extends keyof StatisticsVerificationSubFilterState, K extends keyof StatisticsVerificationSubFilterState,
>(key: K) { >(key: K) {
return (value?: StatisticsVerificationSubFilterState[K]) => { return (value?: StatisticsVerificationSubFilterState[K]) => {
resetResultState();
setSubFilters((prev) => ({ ...prev, [key]: value })); setSubFilters((prev) => ({ ...prev, [key]: value }));
}; };
} }
function handleSubFilterReset() {
setSubFilters(DEFAULT_SUB_FILTERS);
resetResultState();
}
function handleCellEdited(params: CellEditedCallbackParams) { function handleCellEdited(params: CellEditedCallbackParams) {
const { itemIndex, fieldName, newValue } = params; const { itemIndex, fieldName, newValue } = params;
const dataProvider = resultGridRef.current?.dataProvider as const dataProvider = resultGridRef.current?.dataProvider as
@@ -403,11 +427,7 @@ function StatisticsVerificationReport() {
function handleReset() { function handleReset() {
setFilters(DEFAULT_FILTERS); setFilters(DEFAULT_FILTERS);
setSubFilters(DEFAULT_SUB_FILTERS); setSubFilters(DEFAULT_SUB_FILTERS);
setSelectedReportRows([]); resetReportState();
setSelectedResultRows([]);
editedResultRowMapRef.current = new Map();
prevLengthRef.current = 0;
handleSearch(DEFAULT_FILTERS, DEFAULT_SUB_FILTERS);
} }
function handleApprove() { function handleApprove() {
@@ -532,9 +552,6 @@ function StatisticsVerificationReport() {
<Button color="white" onClick={handleReset}> <Button color="white" onClick={handleReset}>
초기화 초기화
</Button> </Button>
<Button onClick={() => handleSearch(filters, subFilters)}>
조회
</Button>
<Button <Button
color="green" color="green"
onClick={handleApprove} onClick={handleApprove}
@@ -557,6 +574,15 @@ function StatisticsVerificationReport() {
setRowData={() => {}} setRowData={() => {}}
showHeaderCheckbox={true} showHeaderCheckbox={true}
gridHeight={30} gridHeight={30}
onRowClick={(row: StatsInputStatusList) => {
setSubFilters((prev) => ({
...prev,
ctpvNm: row?.ctpvNm ?? "",
sggNm: row?.sggNm ?? "",
sewerBzmnCd: row?.sewerBzmnCd ?? "",
statsCd: row?.statsCd ?? "",
}));
}}
/> />
<h3 className="mt-10 px-2 text-[1.8rem] font-bold text-title"> <h3 className="mt-10 px-2 text-[1.8rem] font-bold text-title">
@@ -578,14 +604,15 @@ function StatisticsVerificationReport() {
/> />
</div> </div>
<div className="flex items-end justify-end gap-2"> <div className="flex items-end justify-end gap-2">
<Button onClick={handleResultSearch}>조회</Button> <Button color="white" onClick={handleSubFilterReset}>
초기화
</Button>
<Button <Button
color="red" color="red"
onClick={handleReject} onClick={handleReject}
disabled={ disabled={
selectedResultRows.length === 0 selectedResultRows.length === 0 ||
// || selectedResultRows.some((row) => row.prcsYn !== "2")
// selectedResultRows.some((row) => row.prcsYn !== "2")
} }
> >
반려 반려
@@ -65,21 +65,15 @@ const Indicators: React.FC<IndicatorsProps> = ({ anlsSn, vrfcTrgtSn }) => {
return ( return (
<div className="card card-border !m-0 grid min-h-[10rem] grid-cols-4 gap-2"> <div className="card card-border !m-0 grid min-h-[10rem] grid-cols-4 gap-2">
<IndicatorItem label="r 중위수" value={dtl?.rtCnterVl} /> <IndicatorItem label="R 중위수" value={dtl?.rtCnterVl} />
<IndicatorItem label="E 중위수" value={dtl?.lastTrsfScrCnterVl} />
<IndicatorItem label="하위 기준값" value={dtl?.lastTrsfScrLlmtVl} />
<IndicatorItem <IndicatorItem
label="(E_m)E 중위수" label="상위 기준값"
value={dtl?.lastTrsfScrCnterVl}
/>
<IndicatorItem
label="(E_l)E 하한값"
value={dtl?.lastTrsfScrLlmtVl}
/>
<IndicatorItem
label="(E_u)E 상한값"
value={dtl?.lastTrsfScrUplmtVl} value={dtl?.lastTrsfScrUplmtVl}
/> />
<IndicatorItem label="E_D_L" value={dtl?.llmtVl} /> <IndicatorItem label="이상치 하한값" value={dtl?.llmtVl} />
<IndicatorItem label="E_D_U" value={dtl?.uplmtVl} /> <IndicatorItem label="이상치 상한값" value={dtl?.uplmtVl} />
<IndicatorItem label="이상치 하한선" value={dtl?.otlrLlmtLine} /> <IndicatorItem label="이상치 하한선" value={dtl?.otlrLlmtLine} />
<IndicatorItem label="이상치 상한선" value={dtl?.otlrUplmtLine} /> <IndicatorItem label="이상치 상한선" value={dtl?.otlrUplmtLine} />
</div> </div>
@@ -46,11 +46,6 @@ const RegionalGrid: React.FC<RegionalGridProps> = ({
selectedRowId, selectedRowId,
appliedFilter, appliedFilter,
}) => { }) => {
const [selectedSido, setSelectedSido] = useState<string>("");
const [selectedGugun, setSelectedGugun] = useState<string>("");
const [selectedStatus, setSelectedStatus] = useState<string>("");
const [showAllOnEmptyFilter, setShowAllOnEmptyFilter] =
useState<boolean>(true);
const [isDownloading, setIsDownloading] = useState<boolean>(false); const [isDownloading, setIsDownloading] = useState<boolean>(false);
const [gridRowData, setGridRowData] = useState< const [gridRowData, setGridRowData] = useState<
@@ -58,7 +53,7 @@ const RegionalGrid: React.FC<RegionalGridProps> = ({
>([]); >([]);
const { data: sidoData } = useStAnlsSidoCombo(); const { data: sidoData } = useStAnlsSidoCombo();
const { data: gugunData } = useStAnlsSigunguCombo(selectedSido); const { data: gugunData } = useStAnlsSigunguCombo(appliedFilter.sido ?? "");
const sidoOptions = sidoData ?? EMPTY_ADST_LIST; const sidoOptions = sidoData ?? EMPTY_ADST_LIST;
const gugunOptions = gugunData ?? EMPTY_ADST_LIST; const gugunOptions = gugunData ?? EMPTY_ADST_LIST;
@@ -69,14 +64,7 @@ const RegionalGrid: React.FC<RegionalGridProps> = ({
const rowData = useMemo(() => { const rowData = useMemo(() => {
let data = (resultData?.content ?? []) as StAnlsRsltResponse[]; let data = (resultData?.content ?? []) as StAnlsRsltResponse[];
{
if (
!appliedFilter.sido &&
!appliedFilter.gugun &&
!appliedFilter.status
) {
data = showAllOnEmptyFilter ? data : [];
} else {
const sidoCd = appliedFilter.sido; const sidoCd = appliedFilter.sido;
if (sidoCd) { if (sidoCd) {
data = data.filter((item) => data = data.filter((item) =>
@@ -116,32 +104,18 @@ const RegionalGrid: React.FC<RegionalGridProps> = ({
})); }));
return mappedData; return mappedData;
}, [resultData, appliedFilter, showAllOnEmptyFilter]); }, [resultData, appliedFilter]);
const handleSidoChange = (val: string) => { const handleSidoChange = (val: string) => {
setSelectedSido(val); onFilterChange({ ...appliedFilter, sido: val, gugun: "" });
setSelectedGugun("");
};
const handleSearch = () => {
onFilterChange({
sido: selectedSido,
gugun: selectedGugun,
status: selectedStatus,
});
setShowAllOnEmptyFilter(false);
}; };
const handleReset = () => { const handleReset = () => {
setSelectedSido("");
setSelectedGugun("");
setSelectedStatus("");
onFilterChange({ onFilterChange({
sido: "", sido: "",
gugun: "", gugun: "",
status: "", status: "",
}); });
setShowAllOnEmptyFilter(true);
}; };
const handleDownload = async () => { const handleDownload = async () => {
@@ -182,7 +156,7 @@ const RegionalGrid: React.FC<RegionalGridProps> = ({
<div className="flex justify-between"> <div className="flex justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Select <Select
value={selectedSido || ""} value={appliedFilter.sido || ""}
onValueChange={handleSidoChange} onValueChange={handleSidoChange}
> >
<SelectTrigger className="w-[12rem] bg-white"> <SelectTrigger className="w-[12rem] bg-white">
@@ -197,9 +171,11 @@ const RegionalGrid: React.FC<RegionalGridProps> = ({
</SelectContent> </SelectContent>
</Select> </Select>
<Select <Select
value={selectedGugun} value={appliedFilter.gugun || ""}
onValueChange={setSelectedGugun} onValueChange={(val) =>
disabled={!selectedSido} onFilterChange({ ...appliedFilter, gugun: val })
}
disabled={!appliedFilter.sido}
> >
<SelectTrigger className="w-[12rem] bg-white"> <SelectTrigger className="w-[12rem] bg-white">
<SelectValue placeholder="시군구 선택" /> <SelectValue placeholder="시군구 선택" />
@@ -213,8 +189,10 @@ const RegionalGrid: React.FC<RegionalGridProps> = ({
</SelectContent> </SelectContent>
</Select> </Select>
<Select <Select
value={selectedStatus} value={appliedFilter.status || ""}
onValueChange={setSelectedStatus} onValueChange={(val) =>
onFilterChange({ ...appliedFilter, status: val })
}
> >
<SelectTrigger className="w-[10rem] bg-white"> <SelectTrigger className="w-[10rem] bg-white">
<SelectValue placeholder="상태 선택" /> <SelectValue placeholder="상태 선택" />
@@ -231,7 +209,7 @@ const RegionalGrid: React.FC<RegionalGridProps> = ({
<Button color="white" onClick={handleReset}> <Button color="white" onClick={handleReset}>
초기화 초기화
</Button> </Button>
<Button onClick={handleSearch}>조회</Button> {/* <Button onClick={handleSearch}>조회</Button> */}
<Button <Button
color="green" color="green"
onClick={handleDownload} onClick={handleDownload}
@@ -104,10 +104,12 @@ const ScatterChart: React.FC<ScatterChartProps> = ({
anlsSn, anlsSn,
vrfcTrgtSn, vrfcTrgtSn,
); );
console.log("resultData: ", resultData);
const { data: chartData, isLoading: isLoadingChart } = useStAnlsChartData( const { data: chartData, isLoading: isLoadingChart } = useStAnlsChartData(
anlsSn, anlsSn,
vrfcTrgtSn, vrfcTrgtSn,
); );
console.log("chartData: ", chartData);
const isLoading = isLoadingGrid || isLoadingChart; const isLoading = isLoadingGrid || isLoadingChart;
@@ -158,10 +160,12 @@ const ScatterChart: React.FC<ScatterChartProps> = ({
item, item,
}; };
if (item.otlrYnCd === "0") { if (item.otlrYnCd === "2") {
normalPoints.push(pt); return;
} else { } else if (item.otlrYnCd === "1") {
outlierPoints.push(pt); outlierPoints.push(pt);
} else {
normalPoints.push(pt);
} }
}); });
@@ -3,7 +3,6 @@ import { useEffect, useRef, useState } from 'react';
import { NoData } from '@/shared/ui/no-data'; import { NoData } from '@/shared/ui/no-data';
import { import {
Button, Button,
Input,
Table, Table,
TableBody, TableBody,
TableCell, TableCell,
+80 -74
View File
@@ -3,9 +3,15 @@ import React from "react";
import { ValueType } from "realgrid"; import { ValueType } from "realgrid";
import type { RealGridReact } from "realgrid-react"; import type { RealGridReact } from "realgrid-react";
import { type SewerageSupplyRateStatusInfo } from "@/entities/statistics/model/input/statistics-sewage-supply-rate-input-interface";
// RealGrid 타입 정의 // RealGrid 타입 정의
/** DataGrid 상단 진행상황/제출일/담당자 표시에 사용 (보급률·하수관로 등 공통) */
export type DataGridStatusBannerInfo = {
laeSbmsnSttsCd: string | null;
laeSbmsnYmd: string | null;
laePicNm: string | null;
laePicTelNo: string | null;
};
/** setColumns에 전달하는 컬럼 정보 (footer 배열/단일 객체 포함) */ /** setColumns에 전달하는 컬럼 정보 (footer 배열/단일 객체 포함) */
export type RealGridColumnInfo = { export type RealGridColumnInfo = {
name: string; name: string;
@@ -19,30 +25,30 @@ export type RealGridColumnInfo = {
mergeRule?: { criteria: "value" | string }; mergeRule?: { criteria: "value" | string };
sortable?: boolean; sortable?: boolean;
footer?: footer?:
| { | {
text?: string; text?: string;
expression?: "sum" | "avg" | "count" | "max" | "min"; expression?: "sum" | "avg" | "count" | "max" | "min";
numberFormat?: string; numberFormat?: string;
valueCallback?: ( valueCallback?: (
grid: GridView, grid: GridView,
column: DataColumn, column: DataColumn,
footerIndex: number, footerIndex: number,
columnFooter: ColumnFooter, columnFooter: ColumnFooter,
value: number | string | undefined, value: number | string | undefined,
) => number | string; ) => number | string;
} }
| Array<{ | Array<{
text?: string; text?: string;
expression?: "sum" | "avg" | "count" | "max" | "min"; expression?: "sum" | "avg" | "count" | "max" | "min";
numberFormat?: string; numberFormat?: string;
valueCallback?: ( valueCallback?: (
grid: GridView, grid: GridView,
column: DataColumn, column: DataColumn,
footerIndex: number, footerIndex: number,
columnFooter: ColumnFooter, columnFooter: ColumnFooter,
value: number | string | undefined, value: number | string | undefined,
) => number | string; ) => number | string;
}>; }>;
}; };
/** setColumns 메서드가 있는 GridView */ /** setColumns 메서드가 있는 GridView */
@@ -111,21 +117,21 @@ export type DataFieldValueCallback = (
export type ComputedFieldConfig = export type ComputedFieldConfig =
| { fields: string[]; type: "sum" | "avg" } | { fields: string[]; type: "sum" | "avg" }
| { | {
numeratorFields: string[]; numeratorFields: string[];
denominatorFields: string[]; denominatorFields: string[];
type: "pblswrgPopltnSuprtRate"; type: "pblswrgPopltnSuprtRate";
} }
| { | {
numeratorFields: string[]; numeratorFields: string[];
denominatorFields: string[]; denominatorFields: string[];
type: "adtrtPopltnSuprtRate"; type: "adtrtPopltnSuprtRate";
} }
| { | {
numeratorFields: string[]; numeratorFields: string[];
denominatorFields: string[]; denominatorFields: string[];
thirdFields: string[]; thirdFields: string[];
type: "swrgInstlrtRate"; type: "swrgInstlrtRate";
}; };
export type ColumnConfig = { export type ColumnConfig = {
name: string; name: string;
@@ -148,31 +154,31 @@ export type ColumnConfig = {
valueType?: ValueType; valueType?: ValueType;
dataFormat?: string; dataFormat?: string;
footer?: footer?:
| { | {
text?: string; text?: string;
expression?: "sum" | "avg" | "count" | "max" | "min"; expression?: "sum" | "avg" | "count" | "max" | "min";
numberFormat?: string; numberFormat?: string;
valueCallback?: ( valueCallback?: (
grid: GridView, grid: GridView,
column: DataColumn, column: DataColumn,
footerIndex: number, footerIndex: number,
columnFooter: ColumnFooter, columnFooter: ColumnFooter,
value: number | string | undefined, value: number | string | undefined,
) => number | string; ) => number | string;
multiRow?: boolean; // 여러 행 footer 사용 여부 multiRow?: boolean; // 여러 행 footer 사용 여부
} }
| Array<{ | Array<{
text?: string; text?: string;
expression?: "sum" | "avg" | "count" | "max" | "min"; expression?: "sum" | "avg" | "count" | "max" | "min";
numberFormat?: string; numberFormat?: string;
valueCallback?: ( valueCallback?: (
grid: GridView, grid: GridView,
column: DataColumn, column: DataColumn,
footerIndex: number, footerIndex: number,
columnFooter: ColumnFooter, columnFooter: ColumnFooter,
value: number | string | undefined, value: number | string | undefined,
) => number | string; ) => number | string;
}>; // RealGrid에서 footer를 배열로 설정할 수 있음 }>; // RealGrid에서 footer를 배열로 설정할 수 있음
}; };
export type FooterUserSpan = { export type FooterUserSpan = {
@@ -184,16 +190,16 @@ export type FooterUserSpan = {
export type ColumnLayoutItem = export type ColumnLayoutItem =
| string | string
| { | {
name: string; name: string;
hideChildHeaders?: boolean; hideChildHeaders?: boolean;
header: { text: string }; header: { text: string };
items: (string | ColumnLayoutItem)[]; items: (string | ColumnLayoutItem)[];
footerUserSpans?: FooterUserSpan[]; // footer 병합 설정 footerUserSpans?: FooterUserSpan[]; // footer 병합 설정
} }
| { | {
column: string; // 컬럼 이름 (footerUserSpans 사용 시) column: string; // 컬럼 이름 (footerUserSpans 사용 시)
footerUserSpans?: FooterUserSpan[]; // footer 병합 설정 footerUserSpans?: FooterUserSpan[]; // footer 병합 설정
}; };
export type ColumnInfo = { export type ColumnInfo = {
columns: ColumnConfig[]; columns: ColumnConfig[];
@@ -285,7 +291,7 @@ export type DataGridProps = {
/** CheckBar 헤더 전체 선택/해제 */ /** CheckBar 헤더 전체 선택/해제 */
onItemAllChecked?: (checked: boolean) => void; onItemAllChecked?: (checked: boolean) => void;
onScrollToBottom?: () => void; onScrollToBottom?: () => void;
statusInfo?: SewerageSupplyRateStatusInfo | null; statusInfo?: DataGridStatusBannerInfo | null;
/** 강조 및 스크롤할 행의 ID */ /** 강조 및 스크롤할 행의 ID */
highlightedRowId?: string | number | null; highlightedRowId?: string | number | null;
/** ID로 사용할 필드명 (기본값: 'id') */ /** ID로 사용할 필드명 (기본값: 'id') */
@@ -6,6 +6,7 @@ export type SearchFormValues = {
fctName?: string; fctName?: string;
bsnmCd?: string; bsnmCd?: string;
isDetail?: boolean; isDetail?: boolean;
isSummary?: string;
}; };
export type SearchFormProps = { export type SearchFormProps = {
@@ -17,6 +18,7 @@ export type SearchFormProps = {
fctName?: boolean; fctName?: boolean;
userMenual?: boolean; userMenual?: boolean;
isDetail?: boolean; isDetail?: boolean;
isSummary?: boolean;
onSubmit?: (values: SearchFormValues) => void; onSubmit?: (values: SearchFormValues) => void;
onReset?: () => void; onReset?: () => void;
onValuesChange?: (values: SearchFormValues) => void; onValuesChange?: (values: SearchFormValues) => void;
@@ -33,4 +35,5 @@ export const defaultSearchFormProps: Required<
fctName: false, fctName: false,
userMenual: false, userMenual: false,
isDetail: false, isDetail: false,
isSummary: false,
}; };
@@ -0,0 +1,33 @@
/**
* statistics/input 화면과 탭(·분할 그리드) 키 매칭용 상수.
* 각 컴포넌트에 실제로 쓰이는 `tabKey`를 모두 포함합니다.
*/
/** `SewagePipeInp.tsx` — 메인 탭 + `ConnectionStatusInpColumn` 좌·우 그리드 서브 키 */
export const SEWAGE_PIPE_INP_TAB_KEYS = [
"ST00020001",
"ST00020002",
"ST00020003",
"ST00020004",
"ST00020005",
"ST00020006",
"treatmentPlantConnectionInp",
"adminAreaConnectionInp",
] as const;
/** `SewagePipeMaintainInp.tsx` — 보수·준설 탭 */
export const SEWAGE_PIPE_MAINTAIN_INP_TAB_KEYS = ["ST00030001", "ST00030002"] as const;
/** `SeweragePenetrationRateInp.tsx` — 단일 그리드(통계코드) */
export const SEWERAGE_PENETRATION_RATE_INP_TAB_KEYS = ["ST00010001"] as const;
export type SewagePipeInpTabKey = (typeof SEWAGE_PIPE_INP_TAB_KEYS)[number];
export type SewagePipeMaintainInpTabKey = (typeof SEWAGE_PIPE_MAINTAIN_INP_TAB_KEYS)[number];
export type SeweragePenetrationRateInpTabKey = (typeof SEWERAGE_PENETRATION_RATE_INP_TAB_KEYS)[number];
/** 컴포넌트 파일명 기준 묶음 (메뉴·라우트 매칭 시 참고) */
export const STATISTICS_INPUT_TAB_KEYS_BY_SCREEN = {
SewagePipeInp: SEWAGE_PIPE_INP_TAB_KEYS,
SewagePipeMaintainInp: SEWAGE_PIPE_MAINTAIN_INP_TAB_KEYS,
SeweragePenetrationRateInp: SEWERAGE_PENETRATION_RATE_INP_TAB_KEYS,
} as const;
@@ -21,3 +21,14 @@ export const needBsnmFrgnrPoplSmSidoList = [
"4800000000", "4800000000",
"5000000000", "5000000000",
]; ];
export const doNameList = [
"경기도",
"강원특별자치도",
"충청북도",
"충청남도",
"전북특별자치도",
"전라남도",
"경상북도",
"경상남도",
];
@@ -1,211 +0,0 @@
import { footerInt, footerDecimal1, footerDecimal3 } from "@/components/util/grid/footerSummary";
import { ValueType } from "realgrid";
/**
* 하수도 통계 관리 > 06. 공공하수처리시설
* 단일 Tab
*/
export const PublicSewageFactInpColumn = {
columns: [
// 행정구역
{ name: 'sidoCd', fieldName: '시도', header: { text: '시도' }, editable: false },
{ name: 'gugun', fieldName: '시군구', header: { text: '시군구' }, editable: false, footer: { text: '합계' } },
// 시설명
{ name: 'bscFctNm', fieldName: '시설명(500m³/일 이상/미만)', header: { text: '시설명(500m³/일 이상/미만)' }, editable: false },
// 소재지
{ name: 'addr', fieldName: '소재지', header: { text: '소재지' }, editable: false },
// 시설용량
{ name: 'fctCpc', fieldName: '시설용량(500m³/일 이상/미만)', header: { text: '시설용량(500m³/일 이상/미만)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// (m³/일)
{ name: 'fctCpc1', fieldName: '물리적', header: { text: '물리적' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'fctCpc2', fieldName: '생물학적', header: { text: '생물학적' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'fctCpc3', fieldName: '고도', header: { text: '고도' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 유입하수량
{ name: 'totInflAmntAve', fieldName: '유입하수량(500m³/일 이상/미만)', header: { text: '유입하수량(500m³/일 이상/미만)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// (m³/일)
{ name: 'pInflAmntAve', fieldName: '물리적', header: { text: '물리적' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'oInflAmntAve', fieldName: '생물학적', header: { text: '생물학적' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'aInflAmntAve', fieldName: '고도', header: { text: '고도' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 방류량
{ name: 'totTputAve', fieldName: '방류량(500m³/일 이상/미만)', header: { text: '방류량(500m³/일 이상/미만)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 방류량 - (m³/일)
{ name: 'pTputAve', fieldName: '물리적', header: { text: '물리적' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'oTputAve', fieldName: '생물학적', header: { text: '생물학적' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'aTputAve', fieldName: '고도', header: { text: '고도' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 수질
{ name: 'inflAssctBfrWqltBod', fieldName: '유입BOD', header: { text: '유입BOD' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'efflWqltBod', fieldName: '방류BOD', header: { text: '방류BOD' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'inflAssctBfrWqltToc', fieldName: '유입TOC', header: { text: '유입TOC' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'efflWqltToc', fieldName: '방류TOC', header: { text: '방류TOC' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'inflAssctBfrWqltSs', fieldName: '유입SS', header: { text: '유입SS' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'efflWqltSs', fieldName: '방류SS', header: { text: '방류SS' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'inflAssctBfrWqltTn', fieldName: '유입T-N', header: { text: '유입T-N' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000' },
{ name: 'efflWqltTn', fieldName: '방류T-N', header: { text: '방류T-N' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000' },
{ name: 'inflAssctBfrWqltTp', fieldName: '유입T-P', header: { text: '유입T-P' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000' },
{ name: 'efflWqltTp', fieldName: '방류T-P', header: { text: '방류T-P' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000' },
{ name: 'inflAssctBfrWqltClfgrpcnt', fieldName: '유입총대장균군수', header: { text: '유입총대장균군수' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'efflWqltClfgrpcnt', fieldName: '방류총대장균군수', header: { text: '방류총대장균군수' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 처리특성
{ name: 'tmEfficiency', fieldName: '처리효율(%)', header: { text: '처리효율(%)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'pcLoad', fieldName: '처리부하량(kgBOD/D)', header: { text: '처리부하량(kgBOD/D)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'trtFrfHanNm', fieldName: '처리방법', header: { text: '처리방법' }, editable: false },
// 연계처리량
{ name: 'excretionsTot', fieldName: '분뇨', header: { text: '분뇨' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'stkrsngWstwtrTot', fieldName: '축산', header: { text: '축산' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'lchtTot', fieldName: '침출수', header: { text: '침출수' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'etcTot', fieldName: '기타', header: { text: '기타' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 시설정보
{ name: 'tel', fieldName: '전화번호', header: { text: '전화번호' }, editable: false },
{ name: 'rnDt', fieldName: '준공일', header: { text: '준공일' }, editable: false },
{ name: 'compDt', fieldName: '가동개시일', header: { text: '가동개시일' }, editable: false },
{ name: 'tot', fieldName: '사업비', header: { text: '사업비' }, editable: false, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 방류수 소독방법
{ name: 'dsfctNm', fieldName: '방류수 소독방법', header: { text: '방류수 소독방법' }, editable: false },
// 방류수역
{ name: 'wbsnNm', fieldName: '수계', header: { text: '수계' }, editable: false },
{ name: 'rvNm', fieldName: '지류', header: { text: '지류' }, editable: false },
{ name: 'mdmbsn', fieldName: '세부단위구역', header: { text: '세부단위구역' }, editable: false },
{ name: 'efflWqltStndrdNm', fieldName: '지역구분', header: { text: '지역구분' }, editable: false },
// 방류수역 > 중권역
{ name: 'lgbsn', fieldName: '명칭', header: { text: '명칭' }, editable: false },
{ name: 'lgbsnBod', fieldName: '목표수질(BOD)', header: { text: '목표수질(BOD)' }, editable: false },
// 에너지 자립률
{ name: 'toeRt', fieldName: '에너지자립률(%)', header: { text: '에너지자립률(%)' }, editable: false, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 에너지 자체 생산량
{ name: 'useQnty', fieldName: '에너지자체생산량(TOE)', header: { text: '에너지자체생산량(TOE)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 연간 총 에너지 사용량
{ name: 'toeSum', fieldName: '계(TOE)', header: { text: '계(TOE)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'elcpwAmnt', fieldName: '총 전력사용량(kWh)', header: { text: '총 전력사용량(kWh)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'toeQnty', fieldName: '자체 에너지사용량(TOE)', header: { text: '자체 에너지사용량(TOE)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 하수처리량당 CO2배출량
{ name: 'co2Emissions', fieldName: '하수처리량당 CO2배출량(kgCO2/m³)', header: { text: '하수처리량당 CO2배출량(kgCO2/m³)' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000' },
// 운영주체
{ name: 'oprClsNm', fieldName: '운영주체(자체/공기업/민간대행)', header: { text: '운영주체(자체/공기업/민간대행)' }, editable: false },
// 위탁현황
{ name: 'trstOprEtpNm', fieldName: '위탁업체명', header: { text: '위탁업체명' } },
{ name: 'yrstpTrstCst', fieldName: '위탁비용(백만원/년)', header: { text: '위탁비용(백만원/년)' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'trstOprDt', fieldName: '위탁계약기간(yyyy-mm-dd~yyyy-mm-dd)', header: { text: '위탁계약기간(yyyy-mm-dd~yyyy-mm-dd)' } },
// 기타
{ name: 'cntrTrtFctNm', fieldName: '중심처리시설', header: { text: '중심처리시설' } },
{ name: 'totWtrQrm', fieldName: '직원총수(명)', header: { text: '직원총수(명)' }, footer: footerInt, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'safeAcdntCo', fieldName: '안전사고건수', header: { text: '안전사고건수' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'rmk', fieldName: '비고', header: { text: '비고' } },
],
columnLayout: [
{
name: 'administrative',
hideChildHeaders: false,
header: { text: '행정구역' },
items: ['sidoCd', 'gugun'],
},
'bscFctNm',
'addr',
'fctCpc',
{
name: 'facilityCapacityDetail',
hideChildHeaders: false,
header: { text: '(m³/일)' },
items: ['fctCpc1', 'fctCpc2', 'fctCpc3'],
},
'totInflAmntAve',
{
name: 'influentWaterDetail',
hideChildHeaders: false,
header: { text: '(m³/일)' },
items: ['pInflAmntAve', 'oInflAmntAve', 'aInflAmntAve'],
},
'totTputAve',
{
name: 'effluentWaterDetail',
hideChildHeaders: false,
header: { text: '(m³/일)' },
items: ['pTputAve', 'oTputAve', 'aTputAve'],
},
'inflAssctBfrWqltBod',
'efflWqltBod',
'inflAssctBfrWqltToc',
'efflWqltToc',
'inflAssctBfrWqltSs',
'efflWqltSs',
'inflAssctBfrWqltTn',
'efflWqltTn',
'inflAssctBfrWqltTp',
'efflWqltTp',
'inflAssctBfrWqltClfgrpcnt',
'efflWqltClfgrpcnt',
'tmEfficiency',
'pcLoad',
'trtFrfHanNm',
{
name: 'linkedTreatment',
hideChildHeaders: false,
header: { text: '연계처리량(m³/일) (500m³/일 이상/미만)' },
items: ['excretionsTot', 'stkrsngWstwtrTot', 'lchtTot', 'etcTot'],
},
'tel',
'rnDt',
'compDt',
'tot',
'dsfctNm',
{
name: 'dischargeArea',
hideChildHeaders: false,
header: { text: '방류수역' },
items: [
'wbsnNm',
'rvNm',
'mdmbsn',
'efflWqltStndrdNm',
{
name: 'mediumWatershed',
hideChildHeaders: false,
header: { text: '중권역' },
items: ['lgbsn', 'lgbsnBod'],
},
],
},
'toeRt',
'useQnty',
{
name: 'energy',
hideChildHeaders: false,
header: { text: '연간 총 에너지 사용량(TOE)' },
items: ['toeSum', 'elcpwAmnt', 'toeQnty'],
},
'co2Emissions',
'oprClsNm',
{
name: 'consignmentStatus',
hideChildHeaders: false,
header: { text: '위탁현황' },
items: ['trstOprEtpNm', 'yrstpTrstCst', 'trstOprDt'],
},
'cntrTrtFctNm',
'totWtrQrm',
'safeAcdntCo',
'rmk',
]
};
@@ -0,0 +1,73 @@
import { ValueType } from "realgrid";
export const MainFacilityColumn = {
columns: [
{ name: 'swtrmtFcltNm', fieldName: 'swtrmtFcltNm', header: { text: '시설명' }, editable: false },
{ name: 'fcltPstnCn', fieldName: 'fcltPstnCn', header: { text: '소재지' }, editable: false },
{ name: 'prxyBzentyNmCn', fieldName: 'prxyBzentyNmCn', header: { text: '위탁업체명' }, editable: false },
{ name: 'cnsgnCstVl', fieldName: 'cnsgnCstVl', header: { text: '위탁비용(백만원/년)' }, editable: false },
{ name: 'prxyCtrtCn', fieldName: 'prxyCtrtCn', header: { text: '위탁계약기간' }, editable: false },
{ name: 'isMainYn', fieldName: 'isMainYn', header: { text: '중심처리시설여부' }, editable: false },
{ name: 'admdstCd', fieldName: 'admdstCd', header: { text: '행정구역코드' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'fcltSn', fieldName: 'fcltSn', header: { text: '처리시설일련번호' }, visible: false, editable: false, valueType: ValueType.TEXT, styleName: 'rg-cell-readonly' },
{ name: 'swtrmtFcltCd', fieldName: 'swtrmtFcltCd', header: { text: '하수처리시설코드' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'sggNm', fieldName: 'sggNm', header: { text: '시군구' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'admdstNm', fieldName: 'admdstNm', header: { text: '행정구역명' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
],
columnLayout: [
'swtrmtFcltNm',
'fcltPstnCn',
'prxyBzentyNmCn',
'cnsgnCstVl',
'prxyCtrtCn',
'isMainYn',
'admdstCd',
'fcltSn',
'swtrmtFcltCd',
'sggNm',
'admdstNm',
],
rowStartNum: 1,
fixedColumns: 1,
tabKey: 'MainFacility',
tabLabel: '지자체별공공하수처리시설'
};
// Tab 6-2: 하수처리장별 연결 현황 (왼쪽 그리드)
export const MainFacilityTargetColumn = {
columns: [
// 하수처리장 정보
{ name: 'swtrmtFcltNm', fieldName: 'swtrmtFcltNm', header: { text: '시설명' }, editable: false },
{ name: 'fcltPstnCn', fieldName: 'fcltPstnCn', header: { text: '소재지' }, editable: false },
{ name: 'mappedYn', fieldName: 'mappedYn', header: { text: '연결여부' }, editable: false },
{ name: 'fcltSn', fieldName: 'fcltSn', header: { text: '처리시설일련번호' }, visible: false, editable: false, valueType: ValueType.TEXT, styleName: 'rg-cell-readonly' },
{ name: 'swtrmtFcltCd', fieldName: 'swtrmtFcltCd', header: { text: '하수처리시설코드' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'admdstNm', fieldName: 'admdstNm', header: { text: '행정구역명' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'mainFcltSn', fieldName: 'mainFcltSn', header: { text: '연결된중심시설일련번호' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'isMainYn', fieldName: 'isMainYn', header: { text: '중심처리시설여부' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
],
columnLayout: [
'swtrmtFcltNm',
'fcltPstnCn',
'mappedYn',
'fcltSn',
'swtrmtFcltCd',
'admdstNm',
'mainFcltSn',
'isMainYn',
],
rowStartNum: 1,
fixedColumns: 1,
tabKey: 'MainFacilityTarget',
tabLabel: '연결대상시설'
};
export const MainFacilityInpColumn = {
tabKey: 'ST00060002',
tabLabel: '중심 처리 시설',
isSplitGrid: true,
left: MainFacilityColumn,
right: MainFacilityTargetColumn,
};
@@ -0,0 +1,220 @@
import { footerInt, footerDecimal1, footerDecimal3 } from "@/components/util/grid/footerSummary";
import { ValueType } from "realgrid";
/**
* 하수도 통계 관리 > 06. 공공하수처리시설
*/
export const PublicSewageFactColumn = {
columns: [
// 행정구역
{ name: 'ctpvNm', fieldName: 'ctpvNm', header: { text: '시도' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'sggNm', fieldName: 'sggNm', header: { text: '시군구' }, editable: false, footer: { text: '합계' }, styleName: 'rg-cell-readonly' },
// 시설명
{ name: 'swtrmtFcltNm', fieldName: 'swtrmtFcltNm', header: { text: '시설명(500m³/일 이상/미만)' }, editable: false, styleName: 'rg-cell-readonly' },
// 소재지
{ name: 'impdFcltPstnCn', fieldName: 'impdFcltPstnCn', header: { text: '소재지' }, editable: false, styleName: 'rg-cell-readonly' },
// 시설용량
{ name: 'prcsFcltCpct', fieldName: 'prcsFcltCpct', header: { text: '시설용량(500m³/일 이상/미만)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-total' },
// (m³/일)
{ name: 'prcsFcltPhysCpct', fieldName: 'prcsFcltPhysCpct', header: { text: '물리적' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'prcsFcltBoilCpct', fieldName: 'prcsFcltBoilCpct', header: { text: '생물학적' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'prcsFcltAltdCpct', fieldName: 'prcsFcltAltdCpct', header: { text: '고도' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 유입하수량
{ name: 'inflwSwageQnt', fieldName: 'inflwSwageQnt', header: { text: '유입하수량(500m³/일 이상/미만)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
// (m³/일)
{ name: 'inflwSwagePhysQnt', fieldName: 'inflwSwagePhysQnt', header: { text: '물리적' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'inflwSwageBoilQnt', fieldName: 'inflwSwageBoilQnt', header: { text: '생물학적' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'inflwSwageAltdQnt', fieldName: 'inflwSwageAltdQnt', header: { text: '고도' }, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 방류량
{ name: 'prcsQnt', fieldName: 'prcsQnt', header: { text: '방류량(500m³/일 이상/미만)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
// 방류량 - (m³/일)
{ name: 'prcsPhysCpct', fieldName: 'prcsPhysCpct', header: { text: '물리적' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'prcsBoilCpct', fieldName: 'prcsBoilCpct', header: { text: '생물학적' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'prcsAltdCpct', fieldName: 'prcsAltdCpct', header: { text: '고도' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
// 수질
{ name: 'inflwBodVl', fieldName: 'inflwBodVl', header: { text: '유입BOD' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'dschgBodVl', fieldName: 'dschgBodVl', header: { text: '방류BOD' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'inflwTocQnt', fieldName: 'inflwTocQnt', header: { text: '유입TOC' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'dschgTocQnt', fieldName: 'dschgTocQnt', header: { text: '방류TOC' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'inflwSsQnt', fieldName: 'inflwSsQnt', header: { text: '유입SS' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'dschgSsQnt', fieldName: 'dschgSsQnt', header: { text: '방류SS' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'inflwTnVl', fieldName: 'inflwTnVl', header: { text: '유입T-N' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000', styleName: 'rg-cell-readonly' },
{ name: 'dschgTnVl', fieldName: 'dschgTnVl', header: { text: '방류T-N' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000', styleName: 'rg-cell-readonly' },
{ name: 'inflwTpVl', fieldName: 'inflwTpVl', header: { text: '유입T-P' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000', styleName: 'rg-cell-readonly' },
{ name: 'dschgTpVl', fieldName: 'dschgTpVl', header: { text: '방류T-P' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000', styleName: 'rg-cell-readonly' },
{ name: 'inflwGrssClfgVl', fieldName: 'inflwGrssClfgVl', header: { text: '유입총대장균군수' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'dschgGrssClfgVl', fieldName: 'dschgGrssClfgVl', header: { text: '방류총대장균군수' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
// 처리특성
{ name: 'prcsRt', fieldName: 'prcsRt', header: { text: '처리효율(%)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-total' },
{ name: 'prcsLodQnt', fieldName: 'prcsLodQnt', header: { text: '처리부하량(kgBOD/D)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-total' },
{ name: 'prcsMthdExpln', fieldName: 'prcsMthdExpln', header: { text: '처리방법' }, editable: false, styleName: 'rg-cell-readonly' },
// 연계처리량
{ name: 'wholHmnQnt', fieldName: 'wholHmnQnt', header: { text: '분뇨' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'wholLvstQnt', fieldName: 'wholLvstQnt', header: { text: '축산' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'wholEfntQnt', fieldName: 'wholEfntQnt', header: { text: '침출수' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'wholEtcQnt', fieldName: 'wholEtcQnt', header: { text: '기타' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
// 시설정보
{ name: 'telNo', fieldName: 'telNo', header: { text: '전화번호' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'cmptnStrtYmd', fieldName: 'cmptnStrtYmd', header: { text: '준공일' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'oprtngStrtYmd', fieldName: 'oprtngStrtYmd', header: { text: '가동개시일' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'wholBizVl', fieldName: 'wholBizVl', header: { text: '사업비' }, editable: false, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
// 방류수 소독방법
{ name: 'eflntDsnfMthdExpln', fieldName: 'eflntDsnfMthdExpln', header: { text: '방류수 소독방법' }, editable: false, styleName: 'rg-cell-readonly' },
// 방류수역
{ name: 'wtsysNm', fieldName: 'wtsysNm', header: { text: '수계' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'trbtrNm', fieldName: 'trbtrNm', header: { text: '지류' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'dtlUnitZoneCn', fieldName: 'dtlUnitZoneCn', header: { text: '세부단위구역' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'rgnSeNm', fieldName: 'rgnSeNm', header: { text: '지역구분' }, editable: false, styleName: 'rg-cell-readonly' },
// 방류수역 > 중권역
{ name: 'msirbCn', fieldName: 'msirbCn', header: { text: '명칭' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'goalWqNo', fieldName: 'goalWqNo', header: { text: '목표수질(BOD)' }, editable: false, styleName: 'rg-cell-readonly' },
// 에너지 자립률
{ name: 'engySrlneRt', fieldName: 'engySrlneRt', header: { text: '에너지자립률(%)' }, editable: false, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
// 에너지 자체 생산량
{ name: 'engyItslfPrdctnQnt', fieldName: 'engyItslfPrdctnQnt', header: { text: '에너지자체생산량(TOE)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
// 연간 총 에너지 사용량
{ name: 'anlEngyWholUseQnt', fieldName: 'anlEngyWholUseQnt', header: { text: '계(TOE)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'anlElpwrUseQnt', fieldName: 'anlElpwrUseQnt', header: { text: '총 전력사용량(kWh)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'itslfEngyUseQnt', fieldName: 'itslfEngyUseQnt', header: { text: '자체 에너지사용량(TOE)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
// 하수처리량당 CO2배출량
{ name: 'swtrmtEmsnQnt', fieldName: 'swtrmtEmsnQnt', header: { text: '하수처리량당 CO2배출량(kgCO2/m³)' }, editable: false, footer: footerDecimal3, valueType: ValueType.NUMBER, dataFormat: '#,##0.000', styleName: 'rg-cell-total' },
// 운영주체
{ name: 'operMnbdCn', fieldName: 'operMnbdCn', header: { text: '운영주체(자체/공기업/민간대행)' }, editable: false, styleName: 'rg-cell-readonly' },
// 위탁현황
{ name: 'prxyBzentyNmCn', fieldName: 'prxyBzentyNmCn', header: { text: '위탁업체명' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'cnsgnCstVl', fieldName: 'cnsgnCstVl', header: { text: '위탁비용(백만원/년)' }, editable: false, footer: footerDecimal1, valueType: ValueType.NUMBER, dataFormat: '#,##0.0', styleName: 'rg-cell-readonly' },
{ name: 'prxyCtrtCn', fieldName: 'prxyCtrtCn', header: { text: '위탁계약기간' } },
// 기타
{ name: 'intgPrcsFcltCn', fieldName: 'intgPrcsFcltCn', header: { text: '중심처리시설' }, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'wholNope', fieldName: 'wholNope', header: { text: '직원총수(명)' }, editable: false, footer: footerInt, valueType: ValueType.NUMBER, dataFormat: '#,##0', styleName: 'rg-cell-readonly' },
{ name: 'sftyAcdntEvntcsCnt', fieldName: 'sftyAcdntEvntcsCnt', header: { text: '안전사고건수' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'rmk', fieldName: '비고', header: { text: '비고' } },
{ name: 'admdstCd', fieldName: 'admdstCd', header: { text: '행정구역코드' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'fcltSn', fieldName: 'fcltSn', header: { text: '처리시설일련번호' }, visible: false, editable: false, valueType: ValueType.TEXT, styleName: 'rg-cell-readonly' },
{ name: 'swtrmtFcltCd', fieldName: 'swtrmtFcltCd', header: { text: '하수처리시설코드' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
],
columnLayout: [
{
name: 'administrative',
hideChildHeaders: false,
header: { text: '행정구역' },
items: ['ctpvNm', 'sggNm'],
},
'swtrmtFcltNm',
'impdFcltPstnCn',
'prcsFcltCpct',
{
name: 'facilityCapacityDetail',
hideChildHeaders: false,
header: { text: '(m³/일)' },
items: ['prcsFcltPhysCpct', 'prcsFcltBoilCpct', 'prcsFcltAltdCpct'],
},
'inflwSwageQnt',
{
name: 'influentWaterDetail',
hideChildHeaders: false,
header: { text: '(m³/일)' },
items: ['inflwSwagePhysQnt', 'inflwSwageBoilQnt', 'inflwSwageAltdQnt'],
},
'prcsQnt',
{
name: 'effluentWaterDetail',
hideChildHeaders: false,
header: { text: '(m³/일)' },
items: ['prcsPhysCpct', 'prcsBoilCpct', 'prcsAltdCpct'],
},
'inflwBodVl',
'dschgBodVl',
'inflwTocQnt',
'dschgTocQnt',
'inflwSsQnt',
'dschgSsQnt',
'inflwTnVl',
'dschgTnVl',
'inflwTpVl',
'dschgTpVl',
'inflwGrssClfgVl',
'dschgGrssClfgVl',
'prcsRt',
'prcsLodQnt',
'prcsMthdExpln',
{
name: 'linkedTreatment',
hideChildHeaders: false,
header: { text: '연계처리량(m³/일) (500m³/일 이상/미만)' },
items: ['wholHmnQnt', 'wholLvstQnt', 'wholEfntQnt', 'wholEtcQnt'],
},
'telNo',
'cmptnStrtYmd',
'oprtngStrtYmd',
'wholBizVl',
'eflntDsnfMthdExpln',
{
name: 'dischargeArea',
hideChildHeaders: false,
header: { text: '방류수역' },
items: [
'wtsysNm',
'trbtrNm',
'dtlUnitZoneCn',
'rgnSeNm',
{
name: 'mediumWatershed',
hideChildHeaders: false,
header: { text: '중권역' },
items: ['msirbCn', 'goalWqNo'],
},
],
},
'engySrlneRt',
'engyItslfPrdctnQnt',
{
name: 'energy',
hideChildHeaders: false,
header: { text: '연간 총 에너지 사용량(TOE)' },
items: ['anlEngyWholUseQnt', 'anlElpwrUseQnt', 'itslfEngyUseQnt'],
},
'swtrmtEmsnQnt',
'operMnbdCn',
{
name: 'consignmentStatus',
hideChildHeaders: false,
header: { text: '위탁현황' },
items: ['prxyBzentyNmCn', 'cnsgnCstVl', 'prxyCtrtCn'],
},
'intgPrcsFcltCn',
'wholNope',
'sftyAcdntEvntcsCnt',
'rmk',
'admdstCd',
'fcltSn',
'swtrmtFcltCd',
],
rowStartNum: 3,
fixedColumns: 2,
tabKey: 'ST00060001',
tabLabel: '공공 하수처리 시설'
};
@@ -0,0 +1,8 @@
import type { ColumnInfoList } from "@/components/type/DataGrid.type";
import { MainFacilityInpColumn } from "./MainFacilityInpColumn";
import { PublicSewageFactColumn } from "./PublicSewageFactColumn";
export const PublicSewageFactInpColumnList: ColumnInfoList[] = [
PublicSewageFactColumn,
MainFacilityInpColumn,
];
@@ -49,18 +49,18 @@ export const AdminAreaConnectionInpColumn = {
export const TreatPlantConnectionInpColumn = { export const TreatPlantConnectionInpColumn = {
columns: [ columns: [
// 하수처리장 정보 // 하수처리장 정보
{ name: 'bscFctNm', fieldName: 'bscFctNm', header: { text: '하수처리장명' }, editable: false }, { name: 'fcltNm', fieldName: 'fcltNm', header: { text: '하수처리장명' }, editable: false },
{ name: 'fctCpc', fieldName: 'fctCpc', header: { text: '용량' }, valueType: ValueType.NUMBER, dataFormat: '#,##0', editable: false }, { name: 'fcltCpct', fieldName: 'fcltCpct', header: { text: '용량' }, valueType: ValueType.NUMBER, dataFormat: '#,##0', editable: false },
{ name: 'bscFctCd', fieldName: 'bscFctCd', header: { text: '하수처리장코드' }, editable: false }, { name: 'fcltSn', fieldName: 'fcltSn', header: { text: '하수처리장코드' }, editable: false },
// 연결여부 // 연결여부
{ name: 'isConnection', fieldName: 'isConnection', header: { text: '연결여부' }, editable: false }, { name: 'isConnection', fieldName: 'isConnection', header: { text: '연결여부' }, editable: false },
// 연결지역 // 연결지역
{ name: 'connectionAreaList', fieldName: 'connectionAreaList', header: { text: '연결지역' }, editable: false }, { name: 'connectionAreaList', fieldName: 'connectionAreaList', header: { text: '연결지역' }, editable: false },
], ],
columnLayout: [ columnLayout: [
'bscFctNm', 'fcltNm',
'fctCpc', 'fcltCpct',
'bscFctCd', 'fcltSn',
'isConnection', 'isConnection',
'connectionAreaList', 'connectionAreaList',
], ],
@@ -58,7 +58,7 @@ export const FactInstallStatusInpColumn = {
// 식별·키 필드 (API SeweragePipeInputFactInstallStatusItem, 그리드 비표시 — fixedColumns와 겹치지 않도록 맨 뒤) // 식별·키 필드 (API SeweragePipeInputFactInstallStatusItem, 그리드 비표시 — fixedColumns와 겹치지 않도록 맨 뒤)
{ name: 'admdstCd', fieldName: 'admdstCd', header: { text: '행정구역코드' }, visible: false, editable: false, styleName: 'rg-cell-readonly' }, { name: 'admdstCd', fieldName: 'admdstCd', header: { text: '행정구역코드' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
{ name: 'prcsFcltSn', fieldName: 'prcsFcltSn', header: { text: '처리시설일련번호' }, visible: false, editable: false, valueType: ValueType.NUMBER, dataFormat: '#,##0' }, { name: 'fcltSn', fieldName: 'fcltSn', header: { text: '처리시설일련번호' }, visible: false, editable: false, valueType: ValueType.TEXT },
{ name: 'swtrmtFcltCd', fieldName: 'swtrmtFcltCd', header: { text: '하수처리시설코드' }, visible: false, editable: false, styleName: 'rg-cell-readonly' }, { name: 'swtrmtFcltCd', fieldName: 'swtrmtFcltCd', header: { text: '하수처리시설코드' }, visible: false, editable: false, styleName: 'rg-cell-readonly' },
], ],
columnLayout: [ columnLayout: [
@@ -146,7 +146,7 @@ export const FactInstallStatusInpColumn = {
}, },
'rmrk', 'rmrk',
'admdstCd', 'admdstCd',
'prcsFcltSn', 'fcltSn',
'swtrmtFcltCd', 'swtrmtFcltCd',
], ],
rowStartNum: 4, rowStartNum: 4,
@@ -1,5 +1,3 @@
import dayjs from "dayjs";
import { headers } from "next/headers";
import { ValueType } from "realgrid"; import { ValueType } from "realgrid";
/** /**
@@ -7,9 +5,9 @@ import { ValueType } from "realgrid";
* 항목은 검토(SewagePipeRvwColumn)와 동일하나 footer·mergeCells·구분(displayYear)·비고(rmrk) 제외. * 항목은 검토(SewagePipeRvwColumn)와 동일하나 footer·mergeCells·구분(displayYear)·비고(rmrk) 제외.
* 표시 형식은 SeweragePentrationRateTotColumn과 같이 dataFormat + editable: false. * 표시 형식은 SeweragePentrationRateTotColumn과 같이 dataFormat + editable: false.
*/ */
const currentYear = dayjs().year() - 1;
const startYear = 1996; /** ST00020003 관종별: 입력 `SeweragePipeInputPipeTypeStatusItem`·합계 `SewagePipePipeTypeFacilityStatusItem`과 동일 (yy1=1996년 이전 … yy30) */
const totalCount = currentYear - startYear + 1 + 1; const YY_PIPE_TYPE_FACILITY_MAX = 30;
const rawSewagePipeTotList = [ const rawSewagePipeTotList = [
{ {
@@ -642,11 +640,11 @@ const rawSewagePipeTotList = [
dataFormat: "#,##0.0", dataFormat: "#,##0.0",
editable: false, editable: false,
}, },
...Array.from({ length: totalCount }, (_, i) => { ...Array.from({ length: YY_PIPE_TYPE_FACILITY_MAX }, (_, i) => {
const dtoNum = totalCount - i; const yyIdx = i + 1;
const wholField = `yy${dtoNum}PrlgWhol`; const wholField = `yy${yyIdx}PrlgWhol`;
const lyngField = `yy${dtoNum}LyngPrlg`; const lyngField = `yy${yyIdx}LyngPrlg`;
const dmltnField = `yy${dtoNum}DmltnPrlg`; const dmltnField = `yy${yyIdx}DmltnPrlg`;
return [ return [
{ {
name: wholField, name: wholField,
@@ -687,13 +685,18 @@ const rawSewagePipeTotList = [
header: { text: "총계" }, header: { text: "총계" },
items: ["pipeByPrstWholSum", "lyngPrlgSum", "dmltnPrlgSum"], items: ["pipeByPrstWholSum", "lyngPrlgSum", "dmltnPrlgSum"],
}, },
...Array.from({ length: totalCount }, (_, i) => { {
const dtoNum = totalCount - i; name: "year1996Before",
const yearLabel = i === 0 ? "1996년이전" : `${startYear + (i - 1)}년`; header: { text: "1996년이전" },
items: ["yy1PrlgWhol", "yy1LyngPrlg", "yy1DmltnPrlg"],
},
...Array.from({ length: YY_PIPE_TYPE_FACILITY_MAX - 1 }, (_, i) => {
const yyIdx = i + 2;
const year = 1994 + yyIdx;
return { return {
name: `group_${yearLabel}`, name: `group_yy${yyIdx}`,
header: { text: yearLabel }, header: { text: `${year}년` },
items: [`yy${dtoNum}PrlgWhol`, `yy${dtoNum}LyngPrlg`, `yy${dtoNum}DmltnPrlg`], items: [`yy${yyIdx}PrlgWhol`, `yy${yyIdx}LyngPrlg`, `yy${yyIdx}DmltnPrlg`],
}; };
}), }),
], ],
@@ -0,0 +1,79 @@
import { ValueType } from "realgrid";
// 하수도 통계 관리 > 03.하수관로 유지관리 > tab 2. 관로준설
export const PipeDredgingStatusTotColumn = {
columns: [
// 행정구역
{ name: 'ctpvNm', fieldName: 'ctpvNm', header: { text: '시도' } },
{ name: 'sggNm', fieldName: 'sggNm', header: { text: '시군구명' } },
{ name: 'admdstNm', fieldName: 'admdstNm', header: { text: '행정구역명' } },
// 하수관로 총 시설연장
{ name: 'wholFcltPrlg', fieldName: 'wholFcltPrlg', header: { text: '하수관로총시설연장(m)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.00' },
// 준설연장 및 개소수 > 관로(m)
{ name: 'wholSwagePpl', fieldName: 'wholSwagePpl', header: { text: '합계' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'cbsysPplPrlg', fieldName: 'cbsysPplPrlg', header: { text: '합류식' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 준설연장 및 개소수 > 관로(m) > 분류식
{ name: 'sprsysExlnPrlg', fieldName: 'sprsysExlnPrlg', header: { text: '우수' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'sprsysDrtwPrlg', fieldName: 'sprsysDrtwPrlg', header: { text: '오수' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 준설연장 및 개소수 > 맨홀, 오·우수받이, 토실·토구
{ name: 'mnhlCnt', fieldName: 'mnhlCnt', header: { text: '맨홀(개소)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'exlnDrtwRcvprpCnt', fieldName: 'exlnDrtwRcvprpCnt', header: { text: '오·우수받이(개소)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'stofcbrOtflCnt', fieldName: 'stofcbrOtflCnt', header: { text: '토실·토구(개소)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
// 계획 & 비율
{ name: 'drdgnPlanPrlg', fieldName: 'drdgnPlanPrlg', header: { text: '준설 계획 연장(m)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'drdgnTrgtCtrsDrdgnRt', fieldName: 'drdgnTrgtCtrsDrdgnRt', header: { text: '계획대비 준설율(%)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'wholPrlgCtrsDrdgnRt', fieldName: 'wholPrlgCtrsDrdgnRt', header: { text: '총시설연장대비 준설율(%)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 준설실적
{ name: 'drdgnAmt', fieldName: 'drdgnAmt', header: { text: '금액(백만원)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'drdgnQnt', fieldName: 'drdgnQnt', header: { text: '준설량(m³)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
// 준설토사처리
{ name: 'drdgnUntprcAmt', fieldName: 'drdgnUntprcAmt', header: { text: '준설토처리비(백만원)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'wholDrdgnPrcsQnt', fieldName: 'wholDrdgnPrcsQnt', header: { text: '처리량 계(톤)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'rclmQnt', fieldName: 'rclmQnt', header: { text: '매립' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'oceanEmsnQnt', fieldName: 'oceanEmsnQnt', header: { text: '해양투기' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'rcycQnt', fieldName: 'rcycQnt', header: { text: '재활용' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'etcQnt', fieldName: 'etcQnt', header: { text: '기타(소각, 고형화, 시멘트원료 등)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
].map((col) => ({ ...col, editable: false })),
columnLayout: [
{ name: 'group_admin', header: { text: '행정구역' }, items: ['ctpvNm', 'sggNm', 'admdstNm'] },
'wholFcltPrlg',
{
name: 'group_dredge_info',
header: { text: '준설연장 및 개소수' },
items: [
{
name: 'group_pipe',
header: { text: '관로(m)' },
items: [
'wholSwagePpl', 'cbsysPplPrlg',
{ name: 'group_sep', header: { text: '분류식' }, items: ['sprsysExlnPrlg', 'sprsysDrtwPrlg'] }
]
},
'mnhlCnt', 'exlnDrtwRcvprpCnt', 'stofcbrOtflCnt'
]
},
'drdgnPlanPrlg', 'drdgnTrgtCtrsDrdgnRt', 'wholPrlgCtrsDrdgnRt',
{
name: 'group_perf',
header: { text: '준설실적' },
items: ['drdgnAmt', 'drdgnQnt']
},
{
name: 'group_soil_treat',
header: { text: '준설토사처리' },
items: ['drdgnUntprcAmt', 'wholDrdgnPrcsQnt', 'rclmQnt', 'oceanEmsnQnt', 'rcycQnt', 'etcQnt']
},
],
rowStartNum: 4,
fixedColumns: 1,
tabKey: 'ST00030002',
tabLabel: '관로준설'
};
@@ -0,0 +1,112 @@
import { ValueType } from "realgrid";
// 하수도 통계 관리 > 03.하수관로 유지관리 > tab 1. 개보수
export const RepairStatusTotColumn = {
columns: [
// 행정구역
{ name: 'ctpvNm', fieldName: 'ctpvNm', header: { text: '시도' }, editable: false },
{ name: 'sggNm', fieldName: 'sggNm', header: { text: '시군구명' }, editable: false },
{ name: 'admdstNm', fieldName: 'admdstNm', header: { text: '행정구역명' }, editable: false },
// 개·보수관로 > 전체보수(m)
{ name: 'mendngWhol', fieldName: 'mendngWhol', header: { text: '계' }, editable: false, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'cbsysMendngPrlg', fieldName: 'cbsysMendngPrlg', header: { text: '합류식' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 개·보수관로 > 전체보수(m) > 분류식
{ name: 'sprsysExlnPrlg', fieldName: 'sprsysExlnPrlg', header: { text: '우수' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
{ name: 'sprsysDrtwPrlg', fieldName: 'sprsysDrtwPrlg', header: { text: '오수' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
// 개·보수관로 > 부분보수(개소)
{ name: 'partMendngWhol', fieldName: 'partMendngWhol', header: { text: '계' }, editable: false, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'cbsysPartMendngPrlg', fieldName: 'cbsysPartMendngPrlg', header: { text: '합류식' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
// 개·보수관로 > 부분보수(개소) > 분류식
{ name: 'sprsysExlnMendngPrlg', fieldName: 'sprsysExlnMendngPrlg', header: { text: '우수' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'sprsysDrtwMendngPrlg', fieldName: 'sprsysDrtwMendngPrlg', header: { text: '오수' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
// 맨홀(개소)
{ name: 'cbsysMnhlCnt', fieldName: 'cbsysMnhlCnt', header: { text: '합류식맨홀' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
// 맨홀(개소) > 분류식
{ name: 'sprsysDrtwMnhlCnt', fieldName: 'sprsysDrtwMnhlCnt', header: { text: '오수맨홀' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'sprsysExlnMnhlCnt', fieldName: 'sprsysExlnMnhlCnt', header: { text: '우수맨홀' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
// 받이
{ name: 'drtwRcvprpCnt', fieldName: 'drtwRcvprpCnt', header: { text: '오수받이(개소)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'exlnRcvprpCnt', fieldName: 'exlnRcvprpCnt', header: { text: '빗물받이(개소)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
// 토실, 토구
{ name: 'stofcbrCnt', fieldName: 'stofcbrCnt', header: { text: '토실(개소)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
{ name: 'otflCnt', fieldName: 'otflCnt', header: { text: '토구(개소)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0' },
// 수밀검사CCTV조사량(m)
{ name: 'cctvExmnPrlg', fieldName: 'cctvExmnPrlg', header: { text: '수밀검사·CCTV조사량(m)' }, valueType: ValueType.NUMBER, dataFormat: '#,##0.0' },
].map((col) => ({ ...col, editable: false })),
columnLayout: [
{
name: 'group_admin',
header: { text: '행정구역' },
items: ['ctpvNm', 'sggNm', 'admdstNm']
},
{
name: 'group_repair_main',
header: { text: '개·보수관로' },
items: [
{
name: 'group_full_repair',
header: { text: '전체보수(m)' },
items: [
'mendngWhol',
'cbsysMendngPrlg',
{
name: 'group_full_sep',
header: { text: '분류식' },
items: ['sprsysExlnPrlg', 'sprsysDrtwPrlg']
}
]
},
{
name: 'group_part_repair',
header: { text: '부분보수(개소)' },
items: [
'partMendngWhol',
'cbsysPartMendngPrlg',
{
name: 'group_part_sep',
header: { text: '분류식' },
items: ['sprsysExlnMendngPrlg', 'sprsysDrtwMendngPrlg']
}
]
}
]
},
{
name: 'group_manhole',
header: { text: '맨홀(개소)' },
items: [
'cbsysMnhlCnt',
{
name: 'group_mh_sep',
header: { text: '분류식' },
items: ['sprsysDrtwMnhlCnt', 'sprsysExlnMnhlCnt']
}
]
},
{
name: 'group_inlet',
header: { text: '받이' },
items: ['drtwRcvprpCnt', 'exlnRcvprpCnt']
},
{
name: 'group_chamber',
header: { text: '토실,토구' },
items: ['stofcbrCnt', 'otflCnt']
},
'cctvExmnPrlg',
],
rowStartNum: 4,
fixedColumns: 1,
tabKey: 'ST00030001',
tabLabel: '개보수'
};
@@ -0,0 +1,12 @@
import { PipeDredgingStatusTotColumn } from "./PipeDredgingStatusTotColumn"
import { RepairStatusTotColumn } from "./RepairStatusTotColumn"
const sewagePipeMaintainColumn = [
RepairStatusTotColumn,
PipeDredgingStatusTotColumn
];
export const SewagePipeMaintainColumnListTot = sewagePipeMaintainColumn.map((tab) => ({
...tab,
columns: tab.columns.map((col) => ({ ...col, editable: false as const })),
}));
@@ -0,0 +1,31 @@
import { useQuery } from "@tanstack/react-query";
import { ENDPOINT } from "@/shared/config";
import type { RecentPostSearchParams } from "../model/post-interface";
import { postApi } from "./post-service";
export function useRecentPostList(params?: RecentPostSearchParams) {
return useQuery({
queryKey: createRecentPostListQueryKey(params),
queryFn: () => postApi.getRecentPostList(params),
refetchOnWindowFocus: false,
});
}
function createRecentPostListQueryKey(params?: RecentPostSearchParams) {
return [
ENDPOINT.BOARD_SERVICE.POSTS,
"recentPosts",
params?.page ?? "",
params?.size ?? "",
params?.sort ?? "",
params?.keywordType ?? "",
params?.keyword ?? "",
params?.bbsId ?? "",
params?.delYn ?? "",
params?.frDateYmd ?? "",
params?.toDateYmd ?? "",
];
}
@@ -0,0 +1,22 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
PostService,
RecentPostListResponse,
RecentPostSearchParams,
} from "../model/post-interface";
async function getRecentPostList(
params?: RecentPostSearchParams,
): Promise<RecentPostListResponse> {
const response = await client.get<RecentPostListResponse>(
`${ENDPOINT.BOARD_SERVICE.POSTS}/recentPosts`,
{ params },
);
return response.data;
}
export const postApi: PostService = {
getRecentPostList,
};
+8
View File
@@ -0,0 +1,8 @@
export { useRecentPostList } from "./api/post-queries";
export { postApi } from "./api/post-service";
export {
type PostService,
type PstRecentListResponse,
type RecentPostListResponse,
type RecentPostSearchParams,
} from "./model/post-interface";
@@ -0,0 +1,42 @@
import type { PageableList, PageableParams } from "@/shared/model";
export interface RecentPostSearchParams extends PageableParams {
keywordType?: string;
keyword?: string;
bbsId?: number;
delYn?: string;
frDateYmd?: string;
toDateYmd?: string;
}
export interface PstRecentListResponse {
rowNo: number;
bbsId: number;
pstNo: number;
pstTtl: string;
pstCn: string;
inqNocs: number;
rfrncUrl: string;
popupYn: string;
upndFixYn: string;
prdPstgYn: string;
rootPath: string;
pstPath: string;
ansPstn: number;
wrtrNm: string;
wrtrCplc: string;
atflCd: string;
regDt: string;
rgtrNm: string;
cmntCnt: number;
bbsTypeCd: string;
bbsNm: string;
}
export type RecentPostListResponse = PageableList<PstRecentListResponse>;
export interface PostService {
getRecentPostList(
params?: RecentPostSearchParams,
): Promise<RecentPostListResponse>;
}
@@ -0,0 +1,29 @@
import { useQuery } from "@tanstack/react-query";
import { ENDPOINT } from "@/shared/config";
import type { ScheduleSearchParams } from "../model/schedule-interface";
import { scheduleApi } from "./schedule-service";
export function useSchedules(params?: ScheduleSearchParams) {
return useQuery({
queryKey: createSchedulesQueryKey(params),
queryFn: () => scheduleApi.getSchedules(params),
refetchOnWindowFocus: false,
});
}
function createSchedulesQueryKey(params?: ScheduleSearchParams) {
return [
ENDPOINT.CMS_SERVICE.SCHEDULES,
"list",
params?.siteId ?? "",
params?.schdlTtl ?? "",
params?.schdlSeCd ?? "",
params?.schdlBgngYmd ?? "",
params?.schdlEndYmd ?? "",
params?.reptYn ?? "",
params?.commSchdlYn ?? "",
];
}
@@ -0,0 +1,22 @@
import { client } from "@/shared/api";
import { ENDPOINT } from "@/shared/config";
import type {
Schedule,
ScheduleSearchParams,
ScheduleService,
} from "../model/schedule-interface";
async function getSchedules(
params?: ScheduleSearchParams,
): Promise<Schedule[]> {
const response = await client.get<Schedule[]>(
ENDPOINT.CMS_SERVICE.SCHEDULES,
{ params },
);
return response.data;
}
export const scheduleApi: ScheduleService = {
getSchedules,
};
+7
View File
@@ -0,0 +1,7 @@
export { useSchedules } from "./api/schedule-queries";
export { scheduleApi } from "./api/schedule-service";
export {
type Schedule,
type ScheduleSearchParams,
type ScheduleService,
} from "./model/schedule-interface";
@@ -0,0 +1,27 @@
export interface ScheduleSearchParams {
siteId?: string;
schdlTtl?: string;
schdlSeCd?: string;
schdlBgngYmd?: string;
schdlEndYmd?: string;
reptYn?: string;
commSchdlYn?: string;
}
export interface Schedule {
schdlBgngDt: string;
schdlEndDt: string;
actualDate: string;
schdlSn: number;
siteId: string;
schdlTtl: string;
schdlSeCd: string;
schdlCn: string;
reptYn: string;
commSchdlYn: string;
atflCd: string;
}
export interface ScheduleService {
getSchedules(params?: ScheduleSearchParams): Promise<Schedule[]>;
}
@@ -0,0 +1,109 @@
import { useQuery } from "@tanstack/react-query";
import { ENDPOINT } from "@/shared/config";
import type { DashboardSearchParams } from "../../model/dashboard/dashboard-interface";
import { dashboardApi } from "./dashboard-service";
// 이상치 선별보고서 조회
export function useDashboardVrfcReport(params: DashboardSearchParams | null) {
return useQuery({
queryKey: createDashboardQueryKey("vrfc-report", params),
queryFn: async () => {
if (!params)
throw new Error("Dashboard search params are required.");
const response = await dashboardApi.getVrfcReport(params);
return response.data;
},
enabled: hasRequiredDashboardParams(params),
refetchOnWindowFocus: false,
});
}
// 검증오류 수 조회
export function useDashboardVrfcErrCount(params: DashboardSearchParams | null) {
return useQuery({
queryKey: createDashboardQueryKey("vrfc-err-count", params),
queryFn: async () => {
if (!params)
throw new Error("Dashboard search params are required.");
const response = await dashboardApi.getVrfcErrCount(params);
return response.data;
},
enabled: hasRequiredDashboardParams(params),
refetchOnWindowFocus: false,
});
}
// 미제출 수 & 목록 조회
export function useDashboardUnSubmitCount(
params: DashboardSearchParams | null,
) {
return useQuery({
queryKey: createDashboardQueryKey("submission-status", params),
queryFn: async () => {
if (!params)
throw new Error("Dashboard search params are required.");
const response = await dashboardApi.getUnSubmitCount({
...params,
unSubmitOnly: true,
});
return response.data;
},
enabled: hasRequiredDashboardParams(params),
refetchOnWindowFocus: false,
});
}
// 통계입력현황 조회
export function useDashboardStatsSubmissionRate(
params: DashboardSearchParams | null,
) {
return useQuery({
queryKey: createDashboardQueryKey("stats-submission-rate", params),
queryFn: async () => {
if (!params)
throw new Error("Dashboard search params are required.");
const response = await dashboardApi.getStatsSubmissionRate(params);
return response.data;
},
enabled: hasRequiredDashboardParams(params),
refetchOnWindowFocus: false,
});
}
// 예외신청 수 조회
export function useDashboardEcptReqCount(params: DashboardSearchParams | null) {
return useQuery({
queryKey: createDashboardQueryKey("ecpt-req-count", params),
queryFn: async () => {
if (!params)
throw new Error("Dashboard search params are required.");
const response = await dashboardApi.getEcptReqCount(params);
return response.data;
},
enabled: hasRequiredDashboardParams(params),
refetchOnWindowFocus: false,
});
}
function createDashboardQueryKey(
name: string,
params: DashboardSearchParams | null,
) {
return [
ENDPOINT.ST_SERVICE.DASHBOARD,
name,
params?.statsYr ?? "",
params?.dtlInstCd ?? "",
params?.enoCd ?? "",
params?.laeSeCd ?? "",
];
}
function hasRequiredDashboardParams(
params: DashboardSearchParams | null,
): params is DashboardSearchParams {
return Boolean(params?.statsYr && params.dtlInstCd);
}
@@ -0,0 +1,66 @@
import { stClient } from "@/shared/api/client";
import { ENDPOINT } from "@/shared/config";
import type {
DashboardApiResponse,
DashboardSearchParams,
DashboardService,
EcptReqCountResponse,
StatsSubmissionResponse,
UnSubmitCountResponse,
VrfcErrCountResponse,
VrfcReportResponse,
} from "../../model/dashboard/dashboard-interface";
async function getVrfcReport(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<VrfcReportResponse>> {
const response = await stClient.get<
DashboardApiResponse<VrfcReportResponse>
>(`${ENDPOINT.ST_SERVICE.DASHBOARD}/vrfc-report`, { params });
return response.data;
}
async function getVrfcErrCount(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<VrfcErrCountResponse>> {
const response = await stClient.get<
DashboardApiResponse<VrfcErrCountResponse>
>(`${ENDPOINT.ST_SERVICE.DASHBOARD}/vrfc-err-count`, { params });
return response.data;
}
async function getUnSubmitCount(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<UnSubmitCountResponse>> {
const response = await stClient.get<
DashboardApiResponse<UnSubmitCountResponse>
>(`${ENDPOINT.ST_SERVICE.DASHBOARD}/submission-status`, { params });
return response.data;
}
async function getStatsSubmissionRate(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<StatsSubmissionResponse>> {
const response = await stClient.get<
DashboardApiResponse<StatsSubmissionResponse>
>(`${ENDPOINT.ST_SERVICE.DASHBOARD}/stats-submission-rate`, { params });
return response.data;
}
async function getEcptReqCount(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<EcptReqCountResponse>> {
const response = await stClient.get<
DashboardApiResponse<EcptReqCountResponse>
>(`${ENDPOINT.ST_SERVICE.DASHBOARD}/ecpt-req-count`, { params });
return response.data;
}
export const dashboardApi: DashboardService = {
getVrfcReport,
getVrfcErrCount,
getUnSubmitCount,
getStatsSubmissionRate,
getEcptReqCount,
};
@@ -0,0 +1,35 @@
import { useQuery } from "@tanstack/react-query";
import { ENDPOINT } from "@/shared/config";
import type { ScheduleInfoSearchParams } from "../../model/dashboard/schedule-info-interface";
import { scheduleInfoApi } from "./schedule-info-service";
export function useScheduleInfo(params: ScheduleInfoSearchParams | null) {
return useQuery({
queryKey: createScheduleInfoQueryKey(params),
queryFn: async () => {
if (!params)
throw new Error("Schedule info search params are required.");
const response = await scheduleInfoApi.getScheduleInfo(params);
return response.data;
},
enabled: hasRequiredScheduleInfoParams(params),
refetchOnWindowFocus: false,
});
}
function createScheduleInfoQueryKey(params: ScheduleInfoSearchParams | null) {
return [
ENDPOINT.ST_SERVICE.DASHBOARD,
"schedule-info",
params?.statsYr ?? "",
];
}
function hasRequiredScheduleInfoParams(
params: ScheduleInfoSearchParams | null,
): params is ScheduleInfoSearchParams {
return Boolean(params?.statsYr);
}
@@ -0,0 +1,22 @@
import { stClient } from "@/shared/api/client";
import { ENDPOINT } from "@/shared/config";
import type {
ScheduleInfoApiResponse,
ScheduleInfoResponse,
ScheduleInfoSearchParams,
ScheduleInfoService,
} from "../../model/dashboard/schedule-info-interface";
async function getScheduleInfo(
params: ScheduleInfoSearchParams,
): Promise<ScheduleInfoApiResponse<ScheduleInfoResponse>> {
const response = await stClient.get<
ScheduleInfoApiResponse<ScheduleInfoResponse>
>(`${ENDPOINT.ST_SERVICE.DASHBOARD}/schedule-info`, { params });
return response.data;
}
export const scheduleInfoApi: ScheduleInfoService = {
getScheduleInfo,
};
@@ -3,6 +3,8 @@ import { stClient } from "@/shared/api/client";
import type { import type {
SeweragePipeFacilityAdminAreaListRequest, SeweragePipeFacilityAdminAreaListRequest,
SeweragePipeFacilityAdminAreaListResponse, SeweragePipeFacilityAdminAreaListResponse,
SeweragePipeFactConnectionSaveRequest,
SeweragePipeFactConnectionSaveResponse,
SeweragePipeFacilitiesListRequest, SeweragePipeFacilitiesListRequest,
SeweragePipeFacilitiesListResponse, SeweragePipeFacilitiesListResponse,
SeweragePipeInputConnectionStatusResponse, SeweragePipeInputConnectionStatusResponse,
@@ -12,9 +14,13 @@ import type {
SeweragePipeInputPipeTypeResponse, SeweragePipeInputPipeTypeResponse,
SeweragePipeInputRegionalFactStatusSaveRequest, SeweragePipeInputRegionalFactStatusSaveRequest,
SeweragePipeInputRegionalFactStatusSaveResponse, SeweragePipeInputRegionalFactStatusSaveResponse,
SeweragePipeInputRegionalFactStatusSubmitRequest,
SeweragePipeInputRegionalFactStatusSubmitResponse,
SeweragePipeInputRegionalResponse, SeweragePipeInputRegionalResponse,
SeweragePipeRequestParams, SeweragePipeRequestParams,
StatisticsInputSewPipeService, StatisticsInputSewPipeService,
SeweragePipeInputFactInstallStatusSaveRequest,
SeweragePipeInputFactInstallStatusSaveResponse,
} from "../../model/input/statistics-sewage-pipe-input-interface"; } from "../../model/input/statistics-sewage-pipe-input-interface";
export class StatisticsInputSewPipeApiService implements StatisticsInputSewPipeService { export class StatisticsInputSewPipeApiService implements StatisticsInputSewPipeService {
@@ -82,6 +88,14 @@ export class StatisticsInputSewPipeApiService implements StatisticsInputSewPipeS
return response.data; return response.data;
} }
public async saveFactConnection(param: SeweragePipeFactConnectionSaveRequest): Promise<SeweragePipeFactConnectionSaveResponse> {
const response = await stClient.post<SeweragePipeFactConnectionSaveResponse>(
`${ENDPOINT.ST_SERVICE.INPUT}/sewage-pipe/facility-connection-status/popup/save`,
param,
);
return response.data;
}
public async saveRegionalFactStatus(param: SeweragePipeInputRegionalFactStatusSaveRequest): Promise<SeweragePipeInputRegionalFactStatusSaveResponse> { public async saveRegionalFactStatus(param: SeweragePipeInputRegionalFactStatusSaveRequest): Promise<SeweragePipeInputRegionalFactStatusSaveResponse> {
const response = await stClient.post<SeweragePipeInputRegionalFactStatusSaveResponse>( const response = await stClient.post<SeweragePipeInputRegionalFactStatusSaveResponse>(
`${ENDPOINT.ST_SERVICE.INPUT}/sewage-pipe/regional-facility-status/save`, `${ENDPOINT.ST_SERVICE.INPUT}/sewage-pipe/regional-facility-status/save`,
@@ -89,6 +103,22 @@ export class StatisticsInputSewPipeApiService implements StatisticsInputSewPipeS
); );
return response.data; return response.data;
} }
public async submitRegionalFactStatus(param: SeweragePipeInputRegionalFactStatusSubmitRequest): Promise<SeweragePipeInputRegionalFactStatusSubmitResponse> {
const response = await stClient.post<SeweragePipeInputRegionalFactStatusSubmitResponse>(
`${ENDPOINT.ST_SERVICE.INPUT}/sewage-pipe/regional-facility-status/submit`,
param,
);
return response.data;
}
public async saveFactInstallStatus(param: SeweragePipeInputFactInstallStatusSaveRequest): Promise<SeweragePipeInputFactInstallStatusSaveResponse> {
const response = await stClient.post<SeweragePipeInputFactInstallStatusSaveResponse>(
`${ENDPOINT.ST_SERVICE.INPUT}/sewage-pipe/facility-install-status/save`,
param,
);
return response.data;
}
}; };
export const statisticsInputSewPipeApiService = new StatisticsInputSewPipeApiService(); export const statisticsInputSewPipeApiService = new StatisticsInputSewPipeApiService();
+34 -22
View File
@@ -9,16 +9,14 @@ import type {
StatisticsVerificationSubFilterState, StatisticsVerificationSubFilterState,
} from "@/entities/statistics/model/statistics-verification-report/statistics-verification-report-types"; } from "@/entities/statistics/model/statistics-verification-report/statistics-verification-report-types";
import type { SewerStUserSearchParams } from "../model/sewer-st-user-interface";
import { sewerStUserApi } from "./sewer-st-user-service";
import { stAnlsMstApi } from "./statistics-analysis-master-api"; import { stAnlsMstApi } from "./statistics-analysis-master-api";
import { stAnlsRsltApi } from "./statistics-analysis-result-api"; import { stAnlsRsltApi } from "./statistics-analysis-result-api";
const DETAIL_PAGE_SIZE = 100; const DETAIL_PAGE_SIZE = 100;
interface StatisticsVerificationDetailSubmittedParams {
main: StatisticsVerificationFilterState;
sub: StatisticsVerificationSubFilterState;
}
export const useStAnlsSidoCombo = () => { export const useStAnlsSidoCombo = () => {
return useQuery({ return useQuery({
queryKey: [ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_MST, "sido"], queryKey: [ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_MST, "sido"],
@@ -102,23 +100,24 @@ export const useStatsVrfcRptData = (
}; };
export const useStatsVrfcRsltData = ( export const useStatsVrfcRsltData = (
submittedDetailParams: StatisticsVerificationDetailSubmittedParams | null, params: StatisticsVerificationSubFilterState | null,
) => { ) => {
return useInfiniteQuery({ return useInfiniteQuery({
queryKey: [ queryKey: [
ENDPOINT.ST_SERVICE.INPUTVERIFY, ENDPOINT.ST_SERVICE.INPUTVERIFY,
"verify-results", "verify-results",
submittedDetailParams?.main.statsYr ?? "", params?.statsYr ?? "",
submittedDetailParams?.main.ctpvNm ?? "", params?.ctpvNm ?? "",
submittedDetailParams?.main.sggNm ?? "", params?.sggNm ?? "",
submittedDetailParams?.main.sewerBzmnCd ?? "", params?.sewerBzmnCd ?? "",
submittedDetailParams?.main.statsCd ?? "", params?.statsCd ?? "",
submittedDetailParams?.sub.prcsYnList ?? "", params?.prcsYnList ?? "",
submittedDetailParams?.sub.pbcpAprvYn ?? "", params?.pbcpAprvYn ?? "",
params?.laeSbmsnSttsCd ?? "",
], ],
initialPageParam: 1, initialPageParam: 1,
queryFn: async ({ pageParam }) => { queryFn: async ({ pageParam }) => {
if (!submittedDetailParams) if (!params)
return { return {
verifyResultList: [], verifyResultList: [],
pageInfo: { pageInfo: {
@@ -134,13 +133,14 @@ export const useStatsVrfcRsltData = (
page: pageParam, page: pageParam,
size: DETAIL_PAGE_SIZE, size: DETAIL_PAGE_SIZE,
searchDto: { searchDto: {
statsYr: submittedDetailParams.main.statsYr, statsYr: params.statsYr,
ctpvNm: submittedDetailParams.main.ctpvNm, ctpvNm: params.ctpvNm,
sggNm: submittedDetailParams.main.sggNm, sggNm: params.sggNm,
sewerBzmnCd: submittedDetailParams.main.sewerBzmnCd, sewerBzmnCd: params.sewerBzmnCd,
statsCd: submittedDetailParams.main.statsCd, statsCd: params.statsCd,
prcsYnList: submittedDetailParams.sub.prcsYnList, prcsYnList: params.prcsYnList,
pbcpAprvYn: submittedDetailParams.sub.pbcpAprvYn, pbcpAprvYn: params.pbcpAprvYn,
laeSbmsnSttsCd: params.laeSbmsnSttsCd,
}, },
}); });
@@ -153,7 +153,19 @@ export const useStatsVrfcRsltData = (
if (currentPage + 1 <= totalPages) return currentPage + 1; if (currentPage + 1 <= totalPages) return currentPage + 1;
return undefined; return undefined;
}, },
enabled: Boolean(submittedDetailParams), enabled: Boolean(params),
refetchOnWindowFocus: false, refetchOnWindowFocus: false,
}); });
}; };
export const useSewerStUserList = (params: SewerStUserSearchParams) => {
return useQuery({
queryKey: [
ENDPOINT.STATVERIFY_SERVICE.SEWERST_USER,
"user-list",
params,
],
queryFn: () => sewerStUserApi.getUserList(params),
enabled: Boolean(params.statsYr),
});
};
@@ -0,0 +1,29 @@
import { stClient } from "@/shared/api/client";
import { ENDPOINT } from "@/shared/config";
import type {
SewerStUserListResponse,
SewerStUserSearchParams,
} from "../model/sewer-st-user-interface";
/**
* 하수도 통계 사용자 목록 API 서비스
*/
export class SewerStUserApiService {
/**
* 하수도 통계 제출현황 사용자 목록 조회
* @param params 검색 조건 (statsYr, sewerBzmnCd, gubun)
* @returns 사용자 목록 (입력자·승인자·검토자)
*/
public async getUserList(
params: SewerStUserSearchParams,
): Promise<SewerStUserListResponse> {
const response = await stClient.get<SewerStUserListResponse>(
`${ENDPOINT.STATVERIFY_SERVICE.SEWERST_USER}/user-list`,
{ params },
);
return response.data;
}
}
export const sewerStUserApi = new SewerStUserApiService();
@@ -26,6 +26,8 @@ import {
type SubmitExceptionResponse, type SubmitExceptionResponse,
type ImrResponse, type ImrResponse,
type ImrStatusResponse, type ImrStatusResponse,
type SubmitVerifyExceptionRequest,
type SubmitVerifyExceptionResponse,
} from "../model/statistics-interface"; } from "../model/statistics-interface";
export class StatisticsApiService implements StatisticsService { export class StatisticsApiService implements StatisticsService {
@@ -164,6 +166,14 @@ export class StatisticsApiService implements StatisticsService {
); );
return response.data; return response.data;
} }
public async SubmitVerifyException(param: SubmitVerifyExceptionRequest): Promise<SubmitVerifyExceptionResponse> {
const response = await stClient.put<SubmitVerifyExceptionResponse>(
`${ENDPOINT.ST_SERVICE.INPUTVERIFY}/results/exception`,
param,
);
return response.data;
}
} }
export const statisticsApi = new StatisticsApiService(); export const statisticsApi = new StatisticsApiService();
@@ -2,7 +2,18 @@ import { ENDPOINT } from "@/shared/config";
import { stClient } from "@/shared/api/client"; import { stClient } from "@/shared/api/client";
import type { SewerageSupplyRateRequest, SewerageSupplyRateResponse } from "../model/statistics-total/statistics-sewage-supply-rate-total-interface"; import type { SewerageSupplyRateRequest, SewerageSupplyRateResponse } from "../model/statistics-total/statistics-sewage-supply-rate-total-interface";
import type { SewagePipeTotalRequest, SewagePipeTotalResponse } from "../model/statistics-total/statistics-sewage-pipe-total-interface"; import type {
SewagePipeMaintainDredgingTotalResponse,
SewagePipeMaintainTotalRequest,
SewagePipeMaintainRepairTotalResponse,
} from "../model/statistics-total/statistics-sewage-pipe-maintain-total-interface";
import type {
SewagePipeFactInstallStatusResponse,
SewagePipePipeDiamStatusResponse,
SewagePipePipeTypeFacilityStatusResponse,
SewagePipeTotalRequest,
SewagePipeTotalResponse,
} from "../model/statistics-total/statistics-sewage-pipe-total-interface";
import type { import type {
SewerageServiceLevelComplaintResponse, SewerageServiceLevelComplaintResponse,
SewerageServiceLevelRequest, SewerageServiceLevelRequest,
@@ -41,6 +52,60 @@ export class StatisticsTotalApiService {
); );
return response.data; return response.data;
} }
public async getSewagePipeFactInstallStatus(
params: SewagePipeTotalRequest,
): Promise<SewagePipeFactInstallStatusResponse> {
const response = await stClient.get<SewagePipeFactInstallStatusResponse>(
`${ENDPOINT.ST_SERVICE.TOTAL}/sewer-pipe/facility-installation-status`,
{ params },
);
return response.data;
}
/** ST00020003 — 관종·관경별 시설현황(합계) */
public async getSewagePipePipeTypeFacilityStatus(
params: SewagePipeTotalRequest,
): Promise<SewagePipePipeTypeFacilityStatusResponse> {
const response = await stClient.get<SewagePipePipeTypeFacilityStatusResponse>(
`${ENDPOINT.ST_SERVICE.TOTAL}/sewer-pipe/pipe-type-facility-status`,
{ params },
);
return response.data;
}
/** ST00020004 — 관경별 시설현황(합계) */
public async getSewagePipePipeDiamStatus(
params: SewagePipeTotalRequest,
): Promise<SewagePipePipeDiamStatusResponse> {
const response = await stClient.get<SewagePipePipeDiamStatusResponse>(
`${ENDPOINT.ST_SERVICE.TOTAL}/sewer-pipe/pipe-diam-status`,
{ params },
);
return response.data;
}
/** ST00030001 — 하수관로 유지관리 > 개보수(합계) */
public async getSewagePipeMaintainRepairTotal(
params: SewagePipeMaintainTotalRequest,
): Promise<SewagePipeMaintainRepairTotalResponse> {
const response = await stClient.get<SewagePipeMaintainRepairTotalResponse>(
`${ENDPOINT.ST_SERVICE.TOTAL}/sewer-pipe-mtc/repair`,
{ params },
);
return response.data;
}
/** ST00030002 — 하수관로 유지관리 > 관로준설(합계) */
public async getSewagePipeMaintainDredgingTotal(
params: SewagePipeMaintainTotalRequest,
): Promise<SewagePipeMaintainDredgingTotalResponse> {
const response = await stClient.get<SewagePipeMaintainDredgingTotalResponse>(
`${ENDPOINT.ST_SERVICE.TOTAL}/sewer-pipe-mtc/dredging`,
{ params },
);
return response.data;
}
} }
export const statisticsTotalStatusApi = new StatisticsTotalApiService(); export const statisticsTotalStatusApi = new StatisticsTotalApiService();
+35
View File
@@ -1,9 +1,21 @@
export { export {
useDashboardEcptReqCount,
useDashboardStatsSubmissionRate,
useDashboardUnSubmitCount,
useDashboardVrfcErrCount,
useDashboardVrfcReport,
} from "./api/dashboard/dashboard-queries";
export { dashboardApi } from "./api/dashboard/dashboard-service";
export { useScheduleInfo } from "./api/dashboard/schedule-info-queries";
export { scheduleInfoApi } from "./api/dashboard/schedule-info-service";
export {
useSewerStUserList,
useStAnlsSidoCombo, useStAnlsSidoCombo,
useStAnlsSigunguCombo, useStAnlsSigunguCombo,
useStatsVrfcRptData, useStatsVrfcRptData,
useStatsVrfcRsltData, useStatsVrfcRsltData,
} from "./api/queries"; } from "./api/queries";
export { sewerStUserApi } from "./api/sewer-st-user-service";
export { statisticsApprovalApi } from "./api/statistics-approval-service"; export { statisticsApprovalApi } from "./api/statistics-approval-service";
export { export {
type AnalysisHistoryListApiResponse, type AnalysisHistoryListApiResponse,
@@ -14,6 +26,24 @@ export {
type JobStatusDto, type JobStatusDto,
type OutlierRecordDto, type OutlierRecordDto,
} from "./model/analysis/analysis-interface"; } from "./model/analysis/analysis-interface";
export {
type DashboardApiResponse,
type DashboardSearchParams,
type DashboardService,
type EcptReqCountResponse,
type StatsSubmissionResponse,
type UnSubmitCountResponse,
type UnSubmitStatsResponse,
type VrfcErrCountResponse,
type VrfcReportResponse,
type VrfcReportSelect,
} from "./model/dashboard/dashboard-interface";
export {
type ScheduleInfoApiResponse,
type ScheduleInfoResponse,
type ScheduleInfoSearchParams,
type ScheduleInfoService,
} from "./model/dashboard/schedule-info-interface";
export { type VerifyResultItem } from "./model/general-verification-interface"; export { type VerifyResultItem } from "./model/general-verification-interface";
export { export {
IMR_DETAIL_VISIBLE_COLUMNS_BY_STATS_CD, IMR_DETAIL_VISIBLE_COLUMNS_BY_STATS_CD,
@@ -34,6 +64,11 @@ export {
} from "./model/imr/imr-interface"; } from "./model/imr/imr-interface";
export { imrVerificationHistoryColumns } from "./model/imr/imr-verification-history-columns"; export { imrVerificationHistoryColumns } from "./model/imr/imr-verification-history-columns";
export { type StatsInputStatusList } from "./model/input/statistics-input-status-interface"; export { type StatsInputStatusList } from "./model/input/statistics-input-status-interface";
export {
type SewerStUserItem,
type SewerStUserListResponse,
type SewerStUserSearchParams,
} from "./model/sewer-st-user-interface";
export { export {
type StAnlsDtlListApiResponse, type StAnlsDtlListApiResponse,
type StAnlsDtlResponse, type StAnlsDtlResponse,
@@ -0,0 +1,84 @@
export interface DashboardSearchParams {
statsYr: string;
dtlInstCd: string;
enoCd?: string;
laeSeCd?: string;
sewerBzmnCd?: string;
sido?: string;
sggNm?: string;
unSubmitOnly?: boolean;
}
export interface DashboardApiResponse<T> {
status: string;
message: string;
data: T;
code: string;
httpStatus: number;
}
export interface VrfcReportResponse {
typeCounts: Record<string, number>;
list: VrfcReportSelect[];
}
export interface VrfcReportSelect {
vrfcCd: string;
statsNm: string;
rsnExpln: string;
admdstNm: string;
nowVlCn: string;
compVlCn: string;
}
export interface VrfcErrCountResponse {
statsYr: string;
vrfcErrCount: number;
}
export interface UnSubmitCountResponse {
statsYr: string;
statusList: UnSubmitStatsResponse[];
submittedCount: number;
totalCount: number;
unSubmittedCount: number;
}
export interface UnSubmitStatsResponse {
sbmsnYn: string;
sidoSggNm: string;
statsCd: string;
statsNm: string;
statusCd: string;
statusNm: string;
}
export interface StatsSubmissionResponse {
totalCount: number;
submittedCount: number;
submissionRate: number;
statusLevel: string;
}
export interface EcptReqCountResponse {
statsYr: string;
ecptReqCount: number;
}
export interface DashboardService {
getVrfcReport(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<VrfcReportResponse>>;
getVrfcErrCount(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<VrfcErrCountResponse>>;
getUnSubmitCount(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<UnSubmitCountResponse>>;
getStatsSubmissionRate(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<StatsSubmissionResponse>>;
getEcptReqCount(
params: DashboardSearchParams,
): Promise<DashboardApiResponse<EcptReqCountResponse>>;
}
@@ -0,0 +1,30 @@
export interface ScheduleInfoSearchParams {
statsYr: string;
}
export interface ScheduleInfoApiResponse<T> {
status: string;
message: string;
data: T;
code: string;
httpStatus: number;
}
export interface ScheduleInfoResponse {
statsYr: string;
inptSeCd: number;
inptBgngYmd: string;
inptEndYmd: string;
vrfcSeCd: number;
vrfcBgngYmd: string;
vrfcEndYmd: string;
currentSe: string;
dday: string;
ddayLabel: string;
}
export interface ScheduleInfoService {
getScheduleInfo(
params: ScheduleInfoSearchParams,
): Promise<ScheduleInfoApiResponse<ScheduleInfoResponse>>;
}
@@ -196,11 +196,12 @@ export interface CopyVerifyDataRequest {
} }
export interface VerifyResultSearchRequest { export interface VerifyResultSearchRequest {
sewerBzmnCd?: string | null;
ctpvNm?: string | null; ctpvNm?: string | null;
sggNm?: string | null; sggNm?: string | null;
sewerBzmnCd?: string | null;
statsYr: string; statsYr: string;
statsCd?: string | null; statsCd?: string | null;
laeSbmsnSttsCd?: string | null;
vrfcMthdCd?: string; vrfcMthdCd?: string;
prcsYnList?: string; // 검증 상태 리스트 (0: 미검증, 1: 수정완료, 2:예외통과, 3: 반려) prcsYnList?: string; // 검증 상태 리스트 (0: 미검증, 1: 수정완료, 2:예외통과, 3: 반려)
pbcpAprvYn?: string; // 공단 승인 여부 (Y/N) pbcpAprvYn?: string; // 공단 승인 여부 (Y/N)
@@ -6,6 +6,7 @@ export interface StatsInputStatusListRequestParams {
sewerBzmnCd?: string | null; sewerBzmnCd?: string | null;
statsYr: string; statsYr: string;
statsCd?: string | null; statsCd?: string | null;
laeSbmsnSttsCd?: string | null;
} }
export interface StatsInputStatusList { export interface StatsInputStatusList {
@@ -22,6 +22,10 @@ export interface SeweragePipeInputStatusInfo {
export interface VerifyResultItem { export interface VerifyResultItem {
vrfcCd: string; vrfcCd: string;
rsnExpln: string; rsnExpln: string;
/** 현재값(문자열로 내려오는 경우가 많음) */
nowVlCn?: string;
/** 비교값 */
compVlCn?: string;
} }
/** 필드명 -> 검증 결과 배열 */ /** 필드명 -> 검증 결과 배열 */
@@ -106,6 +110,12 @@ export type SeweragePipeInputRegionalFactStatusSaveItem = Omit<
"verificationResult" "verificationResult"
>; >;
/** Tab2 저장 — saveList */
export type SeweragePipeInputFactInstallStatusSaveItem = Omit<
SeweragePipeInputFactInstallStatusItem,
"verificationResult"
>;
/** 지역별 시설현황 저장 API 요청 */ /** 지역별 시설현황 저장 API 요청 */
export interface SeweragePipeInputRegionalFactStatusSaveRequest { export interface SeweragePipeInputRegionalFactStatusSaveRequest {
statsYr: string; statsYr: string;
@@ -118,7 +128,50 @@ export interface SeweragePipeInputRegionalFactStatusSaveRequest {
} }
export interface SeweragePipeInputRegionalFactStatusSaveResponse { export interface SeweragePipeInputRegionalFactStatusSaveResponse {
data: string; data?: string;
message?: string;
status: string;
}
/** 지역별 시설현황 제출 API 요청 (save item 구조 재사용) */
export interface SeweragePipeInputRegionalFactStatusSubmitRequest {
statsYr: string;
ctpvNm: string;
sggNm: string;
sewerBzmnCd: string;
userId: string;
laePicNm: string;
laePicTelNo: string;
laeKbrdrDeptNm: string;
laeKbrdrJbgdNm: string;
laeIdfrNm: string;
laeIdfrTelNo: string;
laeIdfrDeptNm: string;
laeIdfrJbgdNm: string;
submitList: SeweragePipeInputRegionalFactStatusSaveItem[];
}
export interface SeweragePipeInputRegionalFactStatusSubmitResponse {
data: {
finalStatus: string;
nvpassed: boolean;
}
message?: string;
status: string;
}
export interface SeweragePipeInputFactInstallStatusSaveRequest {
statsYr: string;
ctpvNm: string;
sggNm: string;
sewerBzmnCd: string;
userId: string;
superAdmin: string;
saveList: SeweragePipeInputFactInstallStatusSaveItem[];
}
export interface SeweragePipeInputFactInstallStatusSaveResponse {
data?: string;
message?: string; message?: string;
status: string; status: string;
} }
@@ -128,7 +181,7 @@ export interface SeweragePipeInputFactInstallStatusItem {
admdstCd: string; admdstCd: string;
sggNm: string; sggNm: string;
admdstNm: string; admdstNm: string;
prcsFcltSn: number; fcltSn: string;
swtrmtFcltCd: string; swtrmtFcltCd: string;
swtrmtFcltNm: string; swtrmtFcltNm: string;
prcsFcltCpct: number; prcsFcltCpct: number;
@@ -425,9 +478,9 @@ export interface SeweragePipeInputManholeResponse {
/** 시설별 현황 관리 - 하수처리장별 연결 현황 목록 항목 */ /** 시설별 현황 관리 - 하수처리장별 연결 현황 목록 항목 */
export interface SeweragePipeInputFacilityConnectionItem { export interface SeweragePipeInputFacilityConnectionItem {
bscFctNm: string; fcltNm: string;
fctCpc: number; fcltCpct: number;
bscFctCd: string; fcltSn: string;
isConnection: string; isConnection: string;
connectionAreaList: string; connectionAreaList: string;
} }
@@ -472,9 +525,10 @@ export interface SeweragePipeFacilitiesListItem {
ctpvNm: string; ctpvNm: string;
sggNm: string; sggNm: string;
admdstCd: string; admdstCd: string;
bscFctNm: string; fcltNm: string;
fctCpc: number; fcltCpct: number;
bscFctCd: string; fcltCd: string;
fcltSn: string;
} }
/** facilitiesList API 응답 */ /** facilitiesList API 응답 */
@@ -490,7 +544,7 @@ export interface SeweragePipeFacilityAdminAreaListRequest {
swtrmtFcltCd: string; swtrmtFcltCd: string;
sewerBzmnCd: string; sewerBzmnCd: string;
ctpvNm: string; ctpvNm: string;
sggNm: string; sggNm?: string;
} }
/** 처리시설별 행정구역 목록 항목 */ /** 처리시설별 행정구역 목록 항목 */
@@ -509,6 +563,34 @@ export interface SeweragePipeFacilityAdminAreaListResponse {
message?: string; message?: string;
} }
/** 시설별 연결관계 저장 — saveList 항목 */
export interface SeweragePipeFactConnectionSaveItem {
admdstCd: string;
admdstNm: string;
}
/** 시설별 연결관계 저장 요청 */
export interface SeweragePipeFactConnectionSaveRequest {
ctpvNm: string;
sggNm: string;
fcltSn: string;
statsYr: string;
swtrmtFcltCd: string;
swtrmtFcltNm: string;
prcsFcltCpct: number;
sewerBzmnCd: string;
userId: string;
saveList: SeweragePipeFactConnectionSaveItem[];
deleteList: string[];
}
/** 시설별 연결관계 저장 응답 */
export interface SeweragePipeFactConnectionSaveResponse {
status: string;
data?: string;
message?: string;
}
export interface StatisticsInputSewPipeService { export interface StatisticsInputSewPipeService {
getRegionalFactStatus(param: SeweragePipeRequestParams): Promise<SeweragePipeInputRegionalResponse>; getRegionalFactStatus(param: SeweragePipeRequestParams): Promise<SeweragePipeInputRegionalResponse>;
getFactInstallStatus(param: SeweragePipeRequestParams): Promise<SeweragePipeInputFactInstallResponse>; getFactInstallStatus(param: SeweragePipeRequestParams): Promise<SeweragePipeInputFactInstallResponse>;
@@ -518,7 +600,8 @@ export interface StatisticsInputSewPipeService {
getConnectionStatus(param: SeweragePipeRequestParams): Promise<SeweragePipeInputConnectionStatusResponse>; getConnectionStatus(param: SeweragePipeRequestParams): Promise<SeweragePipeInputConnectionStatusResponse>;
getFacilitiesList(param: SeweragePipeFacilitiesListRequest): Promise<SeweragePipeFacilitiesListResponse>; getFacilitiesList(param: SeweragePipeFacilitiesListRequest): Promise<SeweragePipeFacilitiesListResponse>;
getFacilityAdminAreaList(param: SeweragePipeFacilityAdminAreaListRequest): Promise<SeweragePipeFacilityAdminAreaListResponse>; getFacilityAdminAreaList(param: SeweragePipeFacilityAdminAreaListRequest): Promise<SeweragePipeFacilityAdminAreaListResponse>;
saveRegionalFactStatus( saveFactConnection(param: SeweragePipeFactConnectionSaveRequest): Promise<SeweragePipeFactConnectionSaveResponse>;
param: SeweragePipeInputRegionalFactStatusSaveRequest, saveRegionalFactStatus(param: SeweragePipeInputRegionalFactStatusSaveRequest): Promise<SeweragePipeInputRegionalFactStatusSaveResponse>;
): Promise<SeweragePipeInputRegionalFactStatusSaveResponse>; submitRegionalFactStatus(param: SeweragePipeInputRegionalFactStatusSubmitRequest): Promise<SeweragePipeInputRegionalFactStatusSubmitResponse>;
saveFactInstallStatus(param: SeweragePipeInputFactInstallStatusSaveRequest): Promise<SeweragePipeInputFactInstallStatusSaveResponse>;
} }
@@ -167,11 +167,61 @@ export interface SewerageSupplyRateSubmitResponse {
status: string; status: string;
} }
// 하수도 통계 입력 기간 조회 // 하수도 통계 입력 기간 조회 (입력 INPT / 검증 VRFC 구간)
export interface CheckInputPeriodItem {
statsYr: string;
seCd: number;
seType: string;
bgngYmd: string;
endYmd: string;
current: boolean;
}
export interface CheckInputPeriodResponse { export interface CheckInputPeriodResponse {
status: string; status: string;
message: string; message: string;
data: boolean; data: CheckInputPeriodItem[];
}
/** 입력기간(INPT) 중 현재 구간이면 true */
export function isInputPeriodCurrent(periods: CheckInputPeriodItem[] | null | undefined): boolean {
return (periods ?? []).some((p) => p.seType === "INPT" && p.current === true);
}
/** `YYYYMMDD` → `yyyy-mm-dd` (그 외 형식은 그대로 반환) */
export function formatCheckInputYmdAsDash(ymd: string | null | undefined): string {
if (ymd == null || ymd === "") return "";
if (ymd.length === 8 && /^\d{8}$/.test(ymd)) {
return `${ymd.slice(0, 4)}-${ymd.slice(4, 6)}-${ymd.slice(6, 8)}`;
}
return ymd;
}
/** 검증기간(VRFC) 중 `current`인 항목 (없으면 null) */
export function getCurrentVerificationPeriod(
periods: CheckInputPeriodItem[] | null | undefined,
): CheckInputPeriodItem | null {
return (periods ?? []).find((p) => p.seType === "VRFC" && p.current === true) ?? null;
}
/** 검증기간(VRFC) 중 현재 구간이면 true — 저장·제출·제출 취소 불가 */
export function isVerificationPeriodCurrent(periods: CheckInputPeriodItem[] | null | undefined): boolean {
return getCurrentVerificationPeriod(periods) !== null;
}
/**
* 검증기간이면 차단 안내 문구(줄바꿈 + yyyy-mm-dd ~ yyyy-mm-dd), 아니면 null
*/
export function getVerificationPeriodActionBlockedMessage(
periods: CheckInputPeriodItem[] | null | undefined,
): string | null {
const v = getCurrentVerificationPeriod(periods);
if (!v) return null;
const from = formatCheckInputYmdAsDash(v.bgngYmd);
const to = formatCheckInputYmdAsDash(v.endYmd);
const range =
from && to ? `${from} ~ ${to}` : [from, to].filter(Boolean).join(" ~ ");
return `검증기간에는 저장, 제출, 제출 취소를\n 할 수 없습니다.\n(검증기간: ${range})`;
} }
export interface StatisticsInputSewSupplyRateService { export interface StatisticsInputSewSupplyRateService {
@@ -47,7 +47,7 @@ export const regionalGridColumnInfo: ColumnInfo = {
{ {
name: "chgRt", name: "chgRt",
fieldName: "chgRt", fieldName: "chgRt",
header: { text: "R" }, header: { text: "전년대비 비율" },
width: 60, width: 60,
valueType: ValueType.NUMBER, valueType: ValueType.NUMBER,
dataFormat: "#,##0.00", dataFormat: "#,##0.00",
@@ -55,7 +55,7 @@ export const regionalGridColumnInfo: ColumnInfo = {
{ {
name: "trsfRt", name: "trsfRt",
fieldName: "trsfRt", fieldName: "trsfRt",
header: { text: "S" }, header: { text: "S_i" },
width: 60, width: 60,
valueType: ValueType.NUMBER, valueType: ValueType.NUMBER,
dataFormat: "#,##0.00", dataFormat: "#,##0.00",
@@ -63,7 +63,7 @@ export const regionalGridColumnInfo: ColumnInfo = {
{ {
name: "otlrTrsfRt", name: "otlrTrsfRt",
fieldName: "otlrTrsfRt", fieldName: "otlrTrsfRt",
header: { text: "E" }, header: { text: "기준값" },
width: 60, width: 60,
valueType: ValueType.NUMBER, valueType: ValueType.NUMBER,
dataFormat: "#,##0.00", dataFormat: "#,##0.00",
@@ -0,0 +1,46 @@
/**
* 하수도 통계 제출현황 사용자 목록 조회 인터페이스
*/
/**
* 하수도 통계 사용자 목록 검색 조건
*/
export interface SewerStUserSearchParams {
/** 통계연도 (예: "2024") */
statsYr?: string;
/** 하수도 사업자코드 (예: "4145000000") */
sewerBzmnCd?: string;
/** 구분 코드 (PIC: 입력자, IDFR: 승인자, MCTPV: 검토자, null: 전체) */
gubun?: string;
}
/**
* 하수도 통계 사용자 목록 한 행
*/
export interface SewerStUserItem {
/** 시도 */
sido: string;
/** 시군구 */
gugun: string;
/** 이름 */
userNm: string;
/** 전화번호 */
telNo: string;
/** 소속 */
deptNm: string;
/** 직급 */
jbgdNm: string;
/** 구분 코드 (PIC: 입력자, IDFR: 승인자, MCTPV: 검토자) */
gubun: string;
/** 구분명 (입력자 / 승인자 / 검토자) */
gubunNm: string;
}
/**
* 하수도 통계 사용자 목록 조회 API 응답
*/
export interface SewerStUserListResponse {
status: string;
message?: string;
data?: SewerStUserItem[];
}
@@ -268,6 +268,24 @@ export interface ReviewSubmitResponse {
message?: string; message?: string;
} }
export interface SubmitVerifyExceptionRequest {
sewerBzmnCd: string;
statsYr: string;
statsCd: string;
userId: string;
exceptionList: [
{
vrfcSn: number;
prcsOpnnExpln: string;
}
];
}
export interface SubmitVerifyExceptionResponse {
status: string;
message?: string;
}
export interface StatisticsService { export interface StatisticsService {
getSidoList(params?: { instSeCd?: string }): Promise<ApiResponse<SearchCondition>>; getSidoList(params?: { instSeCd?: string }): Promise<ApiResponse<SearchCondition>>;
getSggList(sidoName: string, params?: { instSeCd?: string; gugunSkipYn?: "Y" | "N" }): Promise<ApiResponse<Sgg[]>>; getSggList(sidoName: string, params?: { instSeCd?: string; gugunSkipYn?: "Y" | "N" }): Promise<ApiResponse<Sgg[]>>;
@@ -280,7 +298,8 @@ export interface StatisticsService {
saveReviewOpinion(param: ReviewOpinionSaveRequest): Promise<ReviewOpinionSaveResponse>; saveReviewOpinion(param: ReviewOpinionSaveRequest): Promise<ReviewOpinionSaveResponse>;
getReviewOpinionDetail(param: getReviewOpinionDetailRequest): Promise<getReviewOpinionDetailResponse>; getReviewOpinionDetail(param: getReviewOpinionDetailRequest): Promise<getReviewOpinionDetailResponse>;
saveReviewReturn(param: ReviewReturnSaveRequest): Promise<ReviewReturnSaveResponse>; saveReviewReturn(param: ReviewReturnSaveRequest): Promise<ReviewReturnSaveResponse>;
submitReview(param :ReviewSubmitRequest): Promise<ReviewSubmitResponse>; submitReview(param: ReviewSubmitRequest): Promise<ReviewSubmitResponse>;
getVerificationResultList(param: VerificationResultListRequest): Promise<VerificationResultListResponse>; getVerificationResultList(param: VerificationResultListRequest): Promise<VerificationResultListResponse>;
getImrStatus(param: string): Promise<ImrStatusResponse>; getImrStatus(param: string): Promise<ImrStatusResponse>;
SubmitVerifyException(param: SubmitVerifyExceptionRequest): Promise<SubmitVerifyExceptionResponse>;
} }
@@ -0,0 +1,77 @@
export interface SewagePipeMaintainTotalRequest {
ctpvNm?: string;
sggNm?: string;
statsYr?: string;
sewerBzmnCd?: string;
rowDataYn?: boolean;
}
export interface SewagePipeMaintainRepairTotalItem {
ctpvNm: string;
sggNm: string | null;
statsYr: string;
rowType: string;
sewerBzmnCd: string | null;
admdstNm: string;
mendngWhol: number;
cbsysMendngPrlg: number;
sprsysDrtwPrlg: number;
sprsysExlnPrlg: number;
partMendngWhol: number;
cbsysPartMendngPrlg: number;
sprsysDrtwMendngPrlg: number;
sprsysExlnMendngPrlg: number;
cbsysMnhlCnt: number;
sprsysDrtwMnhlCnt: number;
sprsysExlnMnhlCnt: number;
drtwRcvprpCnt: number;
exlnRcvprpCnt: number;
stofcbrCnt: number;
otflCnt: number;
cctvExmnPrlg: number;
rmrk: string | null;
}
export interface SewagePipeMaintainRepairTotalResponse {
status: string;
message?: string;
data: SewagePipeMaintainRepairTotalItem[];
}
/** `GET .../sewer-pipe-mtc/dredging` 목록 항목 */
export interface SewagePipeMaintainDredgingTotalItem {
ctpvNm: string;
sggNm: string | null;
admdstNm: string;
admdstCd: string;
statsYr: string;
rowType: string;
sewerBzmnCd: string | null;
wholFcltPrlg: number;
wholSwagePpl: number;
cbsysPplPrlg: number;
sprsysDrtwPrlg: number;
sprsysExlnPrlg: number;
mnhlCnt: number;
exlnDrtwRcvprpCnt: number;
stofcbrOtflCnt: number;
drdgnPlanPrlg: number;
drdgnTrgtCtrsDrdgnRt: number;
wholPrlgCtrsDrdgnRt: number;
drdgnAmt: number;
drdgnQnt: number;
drdgnUntprcAmt: number;
wholDrdgnPrcsQnt: number;
rclmQnt: number;
oceanEmsnQnt: number;
rcycQnt: number;
etcQnt: number;
rmrk: string | null;
}
/** `GET .../sewer-pipe-mtc/dredging` 응답 */
export interface SewagePipeMaintainDredgingTotalResponse {
status: string;
message?: string;
data: SewagePipeMaintainDredgingTotalItem[];
}
@@ -57,3 +57,180 @@ export interface SewagePipeTotalResponse {
message: string; message: string;
data: SewagePipeTotalItem[]; data: SewagePipeTotalItem[];
} }
export interface SewagePipeFactInstallStatusItem {
statsYr: string;
ctpvNm: string;
sggNm: string | null;
admdstCd: string;
admdstNm: string;
swtrmtFcltNm: string;
prcsFcltCpct: number | null;
rowType: string;
prcsZoneArea: number;
cbsysPrcsZoneArea: number;
sprsysPrcsZoneArea: number;
sprsysVartnRt: number;
mltvEqpmCnt: number;
cbsysMltvEqpmCnt: number;
sprsysMltvEqpmCnt: number;
sprsysMltvLnkgCnt: number;
sprsysMltvYetLnkgCnt: number;
planPrcsZoneArea: number;
cbsysPlanPrcsZoneArea: number;
sprsysPlanPrcsZoneArea: number;
wholFcltPrlg: number;
wholIcptgAtlfcPrlg: number | null;
icptgPrlg: number;
atlfcsPrlg: number;
cbsysStofcbrCnt: number;
sprsysStofcbrCnt: number;
sprsysExlnOtflCnt: number;
wholBrchlnPrlg: number;
cbsysBrchlnPrlg: number;
exlnBrchlnPrlg: number;
drtwBrchlnPrlg: number;
}
export interface SewagePipeFactInstallStatusResponse {
status: string;
message?: string;
data: SewagePipeFactInstallStatusItem[];
}
/** ST00020003 합계 — `GET .../sewer-pipe/pipe-type-facility-status` */
export interface SewagePipePipeTypeFacilityStatusItem {
pipeByPrstWhol: number;
lyngPrlg: number;
dmltnPrlg: number;
yy1PrlgWhol: number;
yy1LyngPrlg: number;
yy1DmltnPrlg: number;
yy2PrlgWhol: number;
yy2LyngPrlg: number;
yy2DmltnPrlg: number;
yy3PrlgWhol: number;
yy3LyngPrlg: number;
yy3DmltnPrlg: number;
yy4PrlgWhol: number;
yy4LyngPrlg: number;
yy4DmltnPrlg: number;
yy5PrlgWhol: number;
yy5LyngPrlg: number;
yy5DmltnPrlg: number;
yy6PrlgWhol: number;
yy6LyngPrlg: number;
yy6DmltnPrlg: number;
yy7PrlgWhol: number;
yy7LyngPrlg: number;
yy7DmltnPrlg: number;
yy8PrlgWhol: number;
yy8LyngPrlg: number;
yy8DmltnPrlg: number;
yy9PrlgWhol: number;
yy9LyngPrlg: number;
yy9DmltnPrlg: number;
yy10PrlgWhol: number;
yy10LyngPrlg: number;
yy10DmltnPrlg: number;
yy11PrlgWhol: number;
yy11LyngPrlg: number;
yy11DmltnPrlg: number;
yy12PrlgWhol: number;
yy12LyngPrlg: number;
yy12DmltnPrlg: number;
yy13PrlgWhol: number;
yy13LyngPrlg: number;
yy13DmltnPrlg: number;
yy14PrlgWhol: number;
yy14LyngPrlg: number;
yy14DmltnPrlg: number;
yy15PrlgWhol: number;
yy15LyngPrlg: number;
yy15DmltnPrlg: number;
yy16PrlgWhol: number;
yy16LyngPrlg: number;
yy16DmltnPrlg: number;
yy17PrlgWhol: number;
yy17LyngPrlg: number;
yy17DmltnPrlg: number;
yy18PrlgWhol: number;
yy18LyngPrlg: number;
yy18DmltnPrlg: number;
yy19PrlgWhol: number;
yy19LyngPrlg: number;
yy19DmltnPrlg: number;
yy20PrlgWhol: number;
yy20LyngPrlg: number;
yy20DmltnPrlg: number;
yy21PrlgWhol: number;
yy21LyngPrlg: number;
yy21DmltnPrlg: number;
yy22PrlgWhol: number;
yy22LyngPrlg: number;
yy22DmltnPrlg: number;
yy23PrlgWhol: number;
yy23LyngPrlg: number;
yy23DmltnPrlg: number;
yy24PrlgWhol: number;
yy24LyngPrlg: number;
yy24DmltnPrlg: number;
yy25PrlgWhol: number;
yy25LyngPrlg: number;
yy25DmltnPrlg: number;
yy26PrlgWhol: number;
yy26LyngPrlg: number;
yy26DmltnPrlg: number;
yy27PrlgWhol: number;
yy27LyngPrlg: number;
yy27DmltnPrlg: number;
yy28PrlgWhol: number;
yy28LyngPrlg: number;
yy28DmltnPrlg: number;
yy29PrlgWhol: number;
yy29LyngPrlg: number;
yy29DmltnPrlg: number;
yy30PrlgWhol: number;
yy30LyngPrlg: number;
yy30DmltnPrlg: number;
ctpvNm: string;
sggNm: string | null;
admdstCd: string;
admdstNm: string;
swrgPipeNm: string;
statsYr: string;
rowType: string;
rmrk: string | null;
}
export interface SewagePipePipeTypeFacilityStatusResponse {
status: string;
message?: string;
data: SewagePipePipeTypeFacilityStatusItem[];
}
/** ST00020004 합계 — `GET .../sewer-pipe/pipe-diam-status` */
export interface SewagePipePipeDiamStatusItem {
ctpvNm: string;
sggNm: string | null;
admdstCd: string;
admdstNm: string;
statsYr: string;
swrgPipeNm: string;
rowType: string;
pdmtByTsmWhol: number;
step1PdmtPrlg: number;
step2PdmtPrlg: number;
step3PdmtPrlg: number;
step4PdmtPrlg: number;
step5PdmtPrlg: number;
sqrePdmtPrlg: number;
etcPdmtPrlg: number;
rmrk: string | null;
}
export interface SewagePipePipeDiamStatusResponse {
status: string;
message?: string;
data: SewagePipePipeDiamStatusItem[];
}
@@ -4,6 +4,8 @@ export interface SewerageSupplyRateRequest {
statsYr?: string; statsYr?: string;
sewerBzmnCd?: string; sewerBzmnCd?: string;
rowDataYn?: boolean; rowDataYn?: boolean;
summaryYn?: boolean;
summaryYearCnt?: number;
} }
export interface SewerageSupplyRateTotalItem { export interface SewerageSupplyRateTotalItem {
@@ -0,0 +1,16 @@
import {
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
} from "@dnd-kit/core";
import { sortableKeyboardCoordinates } from "@dnd-kit/sortable";
export function useDndSensors() {
return useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
}),
);
}
@@ -0,0 +1,64 @@
import { useEffect, useState } from "react";
import type { DragEndEvent } from "@dnd-kit/core";
import { arrayMove } from "@dnd-kit/sortable";
import type { PanelItem } from "../../model/types";
interface UsePanelOrderProps {
initialPanels: PanelItem[];
storageKey: string;
}
export function usePanelOrder({
initialPanels,
storageKey,
}: UsePanelOrderProps) {
const [panels, setPanels] = useState<PanelItem[]>(initialPanels);
const [isInitialized, setIsInitialized] = useState(false);
useEffect(() => {
if (initialPanels.length === 0 || isInitialized) return;
const saved = localStorage.getItem(storageKey);
if (saved) {
try {
const savedIds = JSON.parse(saved);
const restoredPanels = savedIds
.map((id: string) => initialPanels.find((p) => p.id === id))
.filter(Boolean);
if (restoredPanels.length === initialPanels.length) {
setPanels(restoredPanels);
}
} catch {
setPanels(initialPanels);
}
} else {
setPanels(initialPanels);
}
setIsInitialized(true);
}, [storageKey, initialPanels, isInitialized]);
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (over && active.id !== over.id) {
setPanels((items) => {
const oldIndex = items.findIndex(
(item) => item.id === active.id,
);
const newIndex = items.findIndex((item) => item.id === over.id);
const newItems = arrayMove(items, oldIndex, newIndex);
localStorage.setItem(
storageKey,
JSON.stringify(newItems.map((item) => item.id)),
);
return newItems;
});
}
};
return { panels, handleDragEnd };
}
@@ -0,0 +1,60 @@
import type { DashboardSearchParams } from "@/entities/statistics/model/dashboard/dashboard-interface";
import type { ScheduleInfoSearchParams } from "@/entities/statistics/model/dashboard/schedule-info-interface";
import { NoticePanel } from "../ui/panels/notice-panel";
import { ScheduleCalendarPanel } from "../ui/panels/schedule-calendar-panel";
import { ScheduleInfoPanel } from "../ui/panels/schedule-info-panel";
import { StatsSubmissionPanel } from "../ui/panels/stats-submission-panel";
import { UnSubmitPanel } from "../ui/panels/unsubmit-panel";
// import { VrfcErrPanel } from "../ui/panels/vrfc-err-panel";
import { VrfcReportPanel } from "../ui/panels/vrfc-report-panel";
import type { PanelItem } from "./types";
interface GetInitialPanelsParams {
dashboardParams: DashboardSearchParams | null;
scheduleInfoParams: ScheduleInfoSearchParams | null;
}
export function getInitialPanels({
dashboardParams,
scheduleInfoParams,
}: GetInitialPanelsParams): PanelItem[] {
return [
{
id: "panel-a",
component: <StatsSubmissionPanel params={dashboardParams} />,
className: "",
},
{
id: "panel-b",
component: <ScheduleInfoPanel params={scheduleInfoParams} />,
className: "",
},
{
id: "panel-c",
component: <NoticePanel />,
className: "",
},
// {
// id: "panel-d",
// component: <VrfcErrPanel params={dashboardParams} />,
// className: "",
// },
{
id: "panel-d",
component: <UnSubmitPanel params={dashboardParams} />,
className: "",
},
{
id: "panel-e",
component: <VrfcReportPanel params={dashboardParams} />,
className: "",
},
{
id: "panel-f",
component: <ScheduleCalendarPanel />,
className: "",
},
];
}
@@ -0,0 +1,5 @@
export interface PanelItem {
id: string;
component: React.ReactNode;
className?: string;
}
@@ -0,0 +1,90 @@
"use client";
import { useRouter } from "next/navigation";
import { createColumnHelper, getCoreRowModel } from "@tanstack/react-table";
import dayjs from "dayjs";
import { useDataTable } from "@/shared/lib";
import { type PstRecentListResponse, useRecentPostList } from "@/entities/post";
import { Button } from "@common/components";
import { useDragHandle } from "../sortable-panel";
export function NoticePanel() {
const { dragHandleProps, isDragging } = useDragHandle();
const router = useRouter();
const recentPostListQuery = useRecentPostList({
page: 0,
size: 4,
keywordType: "bbsTypeCd",
keyword: "BBSNOTICE",
});
const handleRowClick = (post: PstRecentListResponse) => {
router.push(
`/cms/${post.bbsTypeCd.toLowerCase()}/${post.bbsId}/${post.pstNo}`,
);
};
const handleMoreClick = () => {
router.push("/cms/bbsnotice/7");
};
const { tableComponent } = useDataTable({
query: recentPostListQuery,
tableOptions: {
columns: noticeColumns,
getCoreRowModel: getCoreRowModel(),
},
dataTableOptions: {
variant: "line",
onRowClick: handleRowClick,
},
});
return (
<div className="card card-border !m-0 h-full border-border bg-background text-foreground">
<div
className={`card-header cursor-grab border-border active:cursor-grabbing ${isDragging ? "opacity-50" : ""}`}
{...dragHandleProps}
title="헤더를 드래그하여 패널 순서 변경"
>
<h3 className="text-2xl font-semibold">공지사항</h3>
<Button
size="sm"
className="!text-xl"
onClick={handleMoreClick}
>
더보기
</Button>
</div>
{tableComponent}
</div>
);
}
const columnHelper = createColumnHelper<PstRecentListResponse>();
const noticeColumns = [
columnHelper.accessor("pstTtl", {
header: () => <div className="text-left">제목</div>,
cell: ({ row }) => (
<div className="min-w-[20rem] truncate px-2 text-left">
{row.original.pstTtl}
</div>
),
}),
columnHelper.accessor("wrtrNm", {
header: "작성자",
}),
columnHelper.accessor("regDt", {
header: "등록일",
cell: ({ row }) => formatDate(row.original.regDt),
}),
];
function formatDate(value: string) {
return dayjs(value).format("YYYY-MM-DD");
}
@@ -0,0 +1,81 @@
"use client";
import dynamic from "next/dynamic";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import dayjs from "dayjs";
import { SITE_ID } from "@/shared/config";
import { useSchedules } from "@/entities/schedule";
import { LoadingWithAnimation } from "@common/components";
import { useDragHandle } from "../sortable-panel";
// FullCalendar는 클라이언트 전용이므로 dynamic import
const FullCalendar = dynamic(() => import("@fullcalendar/react"), {
ssr: false,
});
export function ScheduleCalendarPanel() {
const { dragHandleProps, isDragging } = useDragHandle();
// TBD: 초기 날짜 범위 설정 로직
const today = dayjs();
const startOfMonth = today.startOf("month").format("YYYY-MM-DD");
const endOfMonth = today.endOf("month").format("YYYY-MM-DD");
const { data, isLoading } = useSchedules({
siteId: SITE_ID,
schdlBgngYmd: startOfMonth,
schdlEndYmd: endOfMonth,
});
return (
<div className="card card-border !m-0 h-full border-border bg-background text-foreground">
<div
className={`card-header cursor-grab border-border active:cursor-grabbing ${isDragging ? "opacity-50" : ""}`}
{...dragHandleProps}
title="헤더를 드래그하여 패널 순서 변경"
>
<h3 className="text-2xl font-semibold">일정관리</h3>
</div>
<div className="card-body max-h-[calc(100%-3.25rem)] py-2.5">
{isLoading && (
<div className="flex h-full items-center justify-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
{data && (
<div className="h-[48rem]">
<FullCalendar
plugins={[dayGridPlugin, timeGridPlugin]}
initialView="dayGridMonth"
locale="ko"
headerToolbar={{
left: "prev,next",
center: "title",
right: "dayGridMonth,timeGridWeek",
}}
buttonText={{
month: "월",
week: "주",
}}
events={data.map((schedule) => ({
id: schedule.schdlSn.toString(),
title: schedule.schdlTtl,
start: schedule.schdlBgngDt,
end: schedule.schdlEndDt,
// TBD: allDay 판단 기준 (1439분 이상?)
allDay: true,
}))}
height="100%"
/>
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,135 @@
"use client";
import dayjs from "dayjs";
import type { ScheduleInfoSearchParams } from "@/entities/statistics";
import { useScheduleInfo } from "@/entities/statistics";
import {
Badge,
type BadgeProps,
LoadingWithAnimation,
} from "@common/components";
import { useDragHandle } from "../sortable-panel";
interface ScheduleInfoPanelProps {
params: ScheduleInfoSearchParams | null;
}
const CURRENT_STATUS_LABEL_MAP = {
INPT: "입력중",
VRFC: "검증중",
NONE: "기간외",
};
const CURRENT_STATUS_COLOR_MAP = {
INPT: "",
VRFC: "gray",
NONE: "lightGray",
};
export function ScheduleInfoPanel({ params }: ScheduleInfoPanelProps) {
const { dragHandleProps, isDragging } = useDragHandle();
const { data, isLoading, error } = useScheduleInfo(params);
return (
<div className="card card-border !m-0 h-full border-border bg-background text-foreground">
<div
className={`card-header cursor-grab border-border active:cursor-grabbing ${isDragging ? "opacity-50" : ""}`}
{...dragHandleProps}
title="헤더를 드래그하여 패널 순서 변경"
>
<h3 className="text-2xl font-semibold">일정안내</h3>
</div>
<div className="card-body max-h-[calc(100%-3.25rem)] py-2.5">
{isLoading && (
<div className="flex h-full items-center justify-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
{error && (
<div className="flex h-full items-center justify-center">
데이터를 불러올 수 없습니다.
</div>
)}
{data && (
<>
<div className="space-y-4">
<div className="mt-2 flex items-center justify-between">
<h4 className="px-2 text-2xl font-semibold tracking-tight text-label">
이번 주 주요 일정
</h4>
<div className="flex items-center gap-2">
<span className="tracking-tight text-label">
현재 진행 상태
</span>
<Badge
color={
CURRENT_STATUS_COLOR_MAP[
data.currentSe as keyof typeof CURRENT_STATUS_COLOR_MAP
] as BadgeProps["color"]
}
className="rounded-full !px-3"
>
{
CURRENT_STATUS_LABEL_MAP[
data.currentSe as keyof typeof CURRENT_STATUS_LABEL_MAP
]
}
</Badge>
</div>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between rounded-sm border border-border p-3">
<Badge size="lg" className="font-semibold">
{data.inptSeCd}차 입력기간
</Badge>
<p className="text-2xl">
{dayjs(data.inptBgngYmd).format(
"YYYY.MM.DD",
)}{" "}
~{" "}
{dayjs(data.inptEndYmd).format(
"YYYY.MM.DD",
)}
</p>
</div>
<div className="flex items-center justify-between rounded-sm border border-border p-3">
<Badge
size="lg"
color="gray"
className="font-semibold"
>
{data.vrfcSeCd}차 검증기간
</Badge>
<p className="text-2xl">
{dayjs(data.vrfcBgngYmd).format(
"YYYY.MM.DD",
)}{" "}
~{" "}
{dayjs(data.vrfcEndYmd).format(
"YYYY.MM.DD",
)}
</p>
</div>
</div>
<div className="flex items-center justify-center gap-4 py-4 tracking-tight">
<span className="text-3xl font-semibold">
{data.ddayLabel}
</span>
<Badge
size="lg"
className="rounded-sm !py-4 !text-5xl font-bold"
>
{data.dday}
</Badge>
</div>
</div>
</>
)}
</div>
</div>
);
}
@@ -0,0 +1,163 @@
"use client";
import { Frown, Laugh, Meh, OctagonAlert, OctagonX, Smile } from "lucide-react";
import {
useDashboardEcptReqCount,
useDashboardStatsSubmissionRate,
useDashboardVrfcErrCount,
} from "@/entities/statistics";
import type { DashboardSearchParams } from "@/entities/statistics/model/dashboard/dashboard-interface";
import { LoadingWithAnimation, Progress } from "@common/components";
import { useDragHandle } from "../sortable-panel";
interface StatsSubmissionPanelProps {
params: DashboardSearchParams | null;
}
const STATUS_LEVEL_TEXT_COLOR = {
GREAT: "text-blue-500",
GOOD: "text-green-500",
WARNING: "text-yellow-500",
BAD: "text-red-500",
};
const STATUS_LEVEL_EMOJI = {
GREAT: <Laugh size={160} className={STATUS_LEVEL_TEXT_COLOR.GREAT} />,
GOOD: <Smile size={160} className={STATUS_LEVEL_TEXT_COLOR.GOOD} />,
WARNING: <Meh size={160} className={STATUS_LEVEL_TEXT_COLOR.WARNING} />,
BAD: <Frown size={160} className={STATUS_LEVEL_TEXT_COLOR.BAD} />,
};
export function StatsSubmissionPanel({ params }: StatsSubmissionPanelProps) {
const { dragHandleProps, isDragging } = useDragHandle();
const { data, isLoading, error } = useDashboardStatsSubmissionRate(params);
const vrfcErrQuery = useDashboardVrfcErrCount(params);
const ecptReqQuery = useDashboardEcptReqCount(params);
return (
<div className="card card-border !m-0 h-full border-border bg-background text-foreground">
{/* <div
className={`card-header cursor-grab border-border active:cursor-grabbing ${isDragging ? "opacity-50" : ""}`}
{...dragHandleProps}
title="헤더를 드래그하여 패널 순서 변경"
>
<h3 className="text-2xl font-semibold">통계입력현황</h3>
</div> */}
<div
className={`card-body cursor-grab py-2 active:cursor-grabbing ${isDragging ? "opacity-50" : ""}`}
{...dragHandleProps}
>
<div className="flex h-full gap-6 px-2">
<div className="h-full flex-1 flex-col">
<h3 className="text-2xl font-semibold">통계입력현황</h3>
{isLoading && (
<div className="flex h-full items-center justify-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
{error && (
<div className="flex h-full items-center justify-center py-8 text-center">
데이터를 불러올 수 없습니다.
</div>
)}
<div className="h-full">
{data && (
<div className="flex h-full flex-col items-center gap-2">
{/* 통계제출률 상태 이모지 */}
<div className="flex justify-center">
{
STATUS_LEVEL_EMOJI[
data.statusLevel as keyof typeof STATUS_LEVEL_EMOJI
]
}
</div>
{/* 통계제출률 프로그레스바 */}
<div className="w-full space-y-3">
<div className="flex w-full justify-between">
<span className="text-2xl">
통계제출률
</span>
<span className="text-2xl font-semibold">
{data.submissionRate?.toFixed(
1,
)}
%
<span className="ml-1">
({data.submittedCount}/
{data.totalCount})
</span>
</span>
</div>
<Progress
value={data.submissionRate}
className="h-10 bg-muted"
/>
</div>
</div>
)}
</div>
</div>
<div className="h-full flex-[0.5]">
<h3 className="text-2xl font-semibold">
검증오류 및 예외
</h3>
<div className="mt-4 space-y-4">
{/* 검증오류 수 카드 */}
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-red-200 bg-red-100 p-4 text-center">
<div className="flex flex-col items-center gap-2">
<OctagonX
className="text-red-600"
size={20}
/>
<span className="text-lg">검증오류 수</span>
</div>
{vrfcErrQuery.isLoading && (
<div className="text-2xl font-bold">-</div>
)}
{vrfcErrQuery.error && (
<div className="text-sm">
데이터를 불러올 수 없습니다.
</div>
)}
{vrfcErrQuery.data && (
<div className="text-5xl font-bold text-red-600">
{vrfcErrQuery.data.vrfcErrCount.toLocaleString()}
</div>
)}
</div>
{/* 예외신청 수 카드 */}
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-orange-200 bg-orange-100 p-4 text-center">
<div className="flex flex-col items-center gap-2">
<OctagonAlert
className="text-orange-600"
size={20}
/>
<span className="text-lg">예외신청 수</span>
</div>
{ecptReqQuery.isLoading && (
<div className="text-2xl font-bold">-</div>
)}
{ecptReqQuery.error && (
<div className="text-sm">
데이터를 불러올 수 없습니다.
</div>
)}
{ecptReqQuery.data && (
<div className="text-5xl font-bold text-orange-600">
{ecptReqQuery.data.ecptReqCount.toLocaleString()}
</div>
)}
</div>
</div>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,75 @@
"use client";
import { useDashboardUnSubmitCount } from "@/entities/statistics";
import type { DashboardSearchParams } from "@/entities/statistics/model/dashboard/dashboard-interface";
import { Badge, LoadingWithAnimation } from "@common/components";
import { useDragHandle } from "../sortable-panel";
interface UnSubmitPanelProps {
params: DashboardSearchParams | null;
}
export function UnSubmitPanel({ params }: UnSubmitPanelProps) {
const { dragHandleProps, isDragging } = useDragHandle();
const { data, isLoading, error } = useDashboardUnSubmitCount(params);
return (
<div className="card card-border !m-0 h-full border-border bg-background text-foreground">
<div
className={`card-header cursor-grab border-border active:cursor-grabbing ${isDragging ? "opacity-50" : ""}`}
{...dragHandleProps}
title="헤더를 드래그하여 패널 순서 변경"
>
<h3 className="text-2xl font-semibold">미제출 지표</h3>
{data && (
<Badge size="lg" className="rounded-full !px-3">
{data.unSubmittedCount ?? 0}건
</Badge>
)}
</div>
<div className="card-body max-h-[calc(100%-3.25rem)] py-2.5">
{isLoading && (
<div className="flex h-full items-center justify-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
{error && (
<div className="flex h-full items-center justify-center">
데이터를 불러올 수 없습니다.
</div>
)}
{data && (
<div className="h-full">
{data.statusList.length === 0 ? (
<div className="flex h-full items-center justify-center">
미제출 지표가 없습니다.
</div>
) : (
<div className="max-h-[48rem] space-y-2 overflow-y-auto">
{data.statusList.map((item, i) => (
<div
key={`${i}-${item.statsCd}`}
className="flex items-center justify-between gap-4 rounded-sm border border-border p-3"
>
<p className="font-medium">
{item.statsNm}
</p>
{params?.dtlInstCd !==
"ROLE_USER05" && (
<span className="whitespace-nowrap text-lg text-muted-foreground">
{item.sidoSggNm}
</span>
)}
</div>
))}
</div>
)}
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,81 @@
"use client";
import { OctagonAlert, OctagonX } from "lucide-react";
import {
useDashboardEcptReqCount,
useDashboardVrfcErrCount,
} from "@/entities/statistics";
import type { DashboardSearchParams } from "@/entities/statistics/model/dashboard/dashboard-interface";
import { useDragHandle } from "../sortable-panel";
interface VrfcErrPanelProps {
params: DashboardSearchParams | null;
}
export function VrfcErrPanel({ params }: VrfcErrPanelProps) {
const { dragHandleProps, isDragging } = useDragHandle();
const vrfcErrQuery = useDashboardVrfcErrCount(params);
const ecptReqQuery = useDashboardEcptReqCount(params);
return (
<div className="card card-border !m-0 h-full border-border bg-background text-foreground">
<div
className={`card-header cursor-grab border-border active:cursor-grabbing ${isDragging ? "opacity-50" : ""}`}
{...dragHandleProps}
title="헤더를 드래그하여 패널 순서 변경"
>
<h3 className="text-2xl font-semibold">검증오류 및 예외</h3>
</div>
<div className="card-body max-h-[calc(100%-3.25rem)] py-2.5">
<div className="grid h-full grid-cols-2 gap-4">
{/* 검증오류 수 카드 */}
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-red-200 bg-red-100 p-4 text-center">
<div className="flex flex-col items-center gap-2">
<OctagonX className="text-red-600" size={20} />
<span className="text-lg">검증오류 수</span>
</div>
{vrfcErrQuery.isLoading && (
<div className="text-2xl font-bold">-</div>
)}
{vrfcErrQuery.error && (
<div className="text-sm">
데이터를 불러올 수 없습니다.
</div>
)}
{vrfcErrQuery.data && (
<div className="text-5xl font-bold text-red-600">
{vrfcErrQuery.data.vrfcErrCount.toLocaleString()}
</div>
)}
</div>
{/* 예외신청 수 카드 */}
<div className="flex flex-col items-center justify-center gap-2 rounded-lg border border-orange-200 bg-orange-100 p-4 text-center">
<div className="flex flex-col items-center gap-2">
<OctagonAlert
className="text-orange-600"
size={20}
/>
<span className="text-lg">예외신청 수</span>
</div>
{ecptReqQuery.isLoading && (
<div className="text-2xl font-bold">-</div>
)}
{ecptReqQuery.error && (
<div className="text-sm">
데이터를 불러올 수 없습니다.
</div>
)}
{ecptReqQuery.data && (
<div className="text-5xl font-bold text-orange-600">
{ecptReqQuery.data.ecptReqCount.toLocaleString()}
</div>
)}
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,131 @@
"use client";
import { useDashboardVrfcReport } from "@/entities/statistics";
import type { DashboardSearchParams } from "@/entities/statistics/model/dashboard/dashboard-interface";
import {
Badge,
type BadgeProps,
LoadingWithAnimation,
} from "@common/components";
import { useDragHandle } from "../sortable-panel";
interface VrfcReportPanelProps {
params: DashboardSearchParams | null;
}
const TYPE_CODE_NAME_MAP: Record<string, string> = {
NV: "일반",
IMR: "I-MR",
};
const TYPE_CODE_COLOR_MAP: Record<string, BadgeProps["color"]> = {
NV: "gray",
IMR: "red",
};
export function VrfcReportPanel({ params }: VrfcReportPanelProps) {
const { dragHandleProps, isDragging } = useDragHandle();
const { data, isLoading, error } = useDashboardVrfcReport(params);
return (
<div className="card card-border !m-0 h-full border-border bg-background text-foreground">
<div
className={`card-header cursor-grab border-border active:cursor-grabbing ${isDragging ? "opacity-50" : ""}`}
{...dragHandleProps}
title="헤더를 드래그하여 패널 순서 변경"
>
<h3 className="text-2xl font-semibold">이상치 선별보고서</h3>
</div>
<div className="card-body max-h-[calc(100%-3.25rem)] py-2.5">
{isLoading && (
<div className="flex h-full items-center justify-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
{error && (
<div className="flex h-full items-center justify-center">
데이터를 불러올 수 없습니다.
</div>
)}
{data && (
<div className="space-y-2">
{/* TBD: typeCounts 표시 방법 (탭? 필터?) */}
{data.typeCounts &&
Object.keys(data.typeCounts).length > 0 && (
<div className="flex flex-wrap gap-2">
{Object.entries(data.typeCounts).map(
([type, count]) => (
<Badge
key={type}
color={
TYPE_CODE_COLOR_MAP[type]
}
className="rounded-full px-2 py-1 text-lg"
>
{TYPE_CODE_NAME_MAP[type]}:{" "}
{count}
</Badge>
),
)}
</div>
)}
{/* TBD: 테이블 컬럼 정의, 증감 표시 방법 */}
<div className="max-h-[44rem] overflow-y-auto">
{data.list.length === 0 ? (
<div className="flex h-full items-center justify-center">
이상치 항목이 없습니다.
</div>
) : (
<div className="space-y-2 tracking-tight">
{data.list.map((item, index) => (
<div
key={index}
className="flex flex-col rounded-sm border border-border p-3"
>
<div className="mb-2 flex items-center justify-between">
<span className="font-medium">
{item.statsNm}
</span>
<Badge
color={
TYPE_CODE_COLOR_MAP[
item.vrfcCd
]
}
className="text-sm"
>
{
TYPE_CODE_NAME_MAP[
item.vrfcCd
]
}
</Badge>
</div>
<p className="text-lg text-muted-foreground">
{item.rsnExpln}
</p>
<div className="flex justify-between text-lg text-muted-foreground">
<span>{item.admdstNm}</span>
<span>
{/* TBD: 증감 표시 방법 (nowVlCn - compVlCn 계산?) */}
현재: {item.nowVlCn ?? "-"}{" "}
/ 비교:{" "}
{item.compVlCn ?? "-"}
</span>
</div>
{/* TBD: 등급/점수/단계/업데이트 시각 필드 미제공 */}
</div>
))}
</div>
)}
</div>
</div>
)}
</div>
</div>
);
}
@@ -0,0 +1,60 @@
import { createContext, useContext } from "react";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
interface SortablePanelProps {
id: string;
children: React.ReactNode;
className?: string;
}
interface DragHandleContextValue {
dragHandleProps: React.HTMLAttributes<HTMLElement>;
isDragging: boolean;
}
const DragHandleContext = createContext<DragHandleContextValue | null>(null);
export function SortablePanel({ id, children, className }: SortablePanelProps) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
const contextValue: DragHandleContextValue = {
dragHandleProps: { ...attributes, ...listeners },
isDragging,
};
return (
<DragHandleContext.Provider value={contextValue}>
<div ref={setNodeRef} style={style} className={className}>
{children}
</div>
</DragHandleContext.Provider>
);
}
export function useDragHandle() {
const context = useContext(DragHandleContext);
if (!context) {
return {
dragHandleProps: {},
isDragging: false,
};
}
return context;
}
@@ -1,16 +1,27 @@
"use client"; "use client";
import { Suspense, useRef, useEffect } from "react"; import { Suspense, useEffect, useMemo, useRef } from "react";
import dynamic from "next/dynamic"; import dynamic from "next/dynamic";
import { useTabStore } from "@/store/tab-store";
import { useAdminStore } from "@/store/admin-store";
import Dashboard from "@/components/Dashboard";
import { SkeletonPage } from "@/shared/ui/skeleton-page"; import { SkeletonPage } from "@/shared/ui/skeleton-page";
import "@rsone/components/index.css"; import "@rsone/components/index.css";
import Dashboard from "@/components/statistics/Dashboard";
import { isVerificationSelectionReportMenu } from "@/shared/lib/verification-selection-report";
import { useAdminStore } from "@/store/admin-store";
import { useTabStore } from "@/store/tab-store";
const StatisticsPage = () => { const StatisticsPage = () => {
const { tabs, activeTabId } = useTabStore(); const { tabs, activeTabId } = useTabStore();
const tabsForBody = useMemo(
() =>
tabs.filter(
(tab) => !isVerificationSelectionReportMenu(tab.menuItem),
),
[tabs],
);
const fetchAdminInfo = useAdminStore((state) => state.fetchAdminInfo); const fetchAdminInfo = useAdminStore((state) => state.fetchAdminInfo);
// 컴포넌트 캐시를 useRef로 유지 (재렌더링 시에도 유지됨) // 컴포넌트 캐시를 useRef로 유지 (재렌더링 시에도 유지됨)
@@ -18,7 +29,7 @@ const StatisticsPage = () => {
// 닫힌 탭의 컴포넌트는 캐시에서 제거 (메모리 정리) // 닫힌 탭의 컴포넌트는 캐시에서 제거 (메모리 정리)
useEffect(() => { useEffect(() => {
const currentTabIds = new Set(tabs.map(tab => tab.id)); const currentTabIds = new Set(tabs.map((tab) => tab.id));
const cachedTabIds = Array.from(componentCache.current.keys()); const cachedTabIds = Array.from(componentCache.current.keys());
cachedTabIds.forEach((cachedId) => { cachedTabIds.forEach((cachedId) => {
@@ -35,26 +46,26 @@ const StatisticsPage = () => {
// 탭이 없으면 Dashboard 표시 // 탭이 없으면 Dashboard 표시
if (tabs.length === 0) { if (tabs.length === 0) {
return ( return (
<div className="card card-border !mt-6"> <div className="card card-border !mt-6 border-border bg-background">
<Dashboard /> <Dashboard />
</div> </div>
); );
} }
return ( return (
<div className="card card-border !mt-6"> <div className="card card-border !mt-6 border-border bg-background">
{tabs.map((tab) => { {tabsForBody.map((tab) => {
// 렌더링 시점에 컴포넌트가 없으면 바로 로드 // 렌더링 시점에 컴포넌트가 없으면 바로 로드
if (!componentCache.current.has(tab.id)) { if (!componentCache.current.has(tab.id)) {
const componentName = tab.urlPath; const componentName = tab.urlPath;
const parentComponentName = tab.parentEngNm; const parentComponentName = tab.parentEngNm;
const DynamicComponent = dynamic( const DynamicComponent = dynamic(
() => import(`@/components/statistics/${parentComponentName}/${componentName}`), () =>
{ import(
ssr: false, `@/components/statistics${parentComponentName ? `/${parentComponentName}` : ""}/${componentName}`
loading: () => <SkeletonPage /> ),
} { ssr: false, loading: () => <SkeletonPage /> },
); );
componentCache.current.set(tab.id, DynamicComponent); componentCache.current.set(tab.id, DynamicComponent);
@@ -68,7 +79,7 @@ const StatisticsPage = () => {
return ( return (
<div <div
key={tab.id} key={tab.id}
style={{ display: isActive ? 'block' : 'none' }} style={{ display: isActive ? "block" : "none" }}
> >
<Suspense fallback={<SkeletonPage />}> <Suspense fallback={<SkeletonPage />}>
<Component /> <Component />
+6
View File
@@ -74,6 +74,11 @@ export const ENDPOINT = {
INPUTVERIFY: "/st-input-service/api/v1/verify", INPUTVERIFY: "/st-input-service/api/v1/verify",
TOTAL: "/st-management-service/api/v1/stats", TOTAL: "/st-management-service/api/v1/stats",
APPROVAL: "/st-management-service/api/stats", APPROVAL: "/st-management-service/api/stats",
DASHBOARD: "/st-management-service/api/v1/dashboard",
},
NTFTALK_SERVICE: {
TEMP: "/ntftalk-service/api/v1/ntftalk-temp",
ATA_SEND: "/ntftalk-service/api/v1/ata/send",
}, },
STATVERIFY_SERVICE: { STATVERIFY_SERVICE: {
VRFCTGT_MNG: "/statverify-service/api/v1/vrfc-trgt-mng", VRFCTGT_MNG: "/statverify-service/api/v1/vrfc-trgt-mng",
@@ -82,6 +87,7 @@ export const ENDPOINT = {
ST_ANLS_DTL: "/statverify-service/api/v1/st-anls-dtl", ST_ANLS_DTL: "/statverify-service/api/v1/st-anls-dtl",
ST_ANLS_RSLT: "/statverify-service/api/v1/st-anls-rslt", ST_ANLS_RSLT: "/statverify-service/api/v1/st-anls-rslt",
IMR: "/statverify-service/api/v1/imr/outlier/detect", IMR: "/statverify-service/api/v1/imr/outlier/detect",
SEWERST_USER: "/statverify-service/api/v1/sewerst",
}, },
}; };
@@ -0,0 +1,99 @@
import type { MenuItem } from "@/entities/menu";
import type { SearchFormValues } from "@/components/type/SearchForm.type";
import { doNameList } from "@/components/util/column/input/DoList";
import {
SEWAGE_PIPE_INP_TAB_KEYS,
SEWAGE_PIPE_MAINTAIN_INP_TAB_KEYS,
SEWERAGE_PENETRATION_RATE_INP_TAB_KEYS,
} from "@/components/util/MenuMatchList";
/** 검증 결과에서 입력 화면 자동 조회에 사용하는 조건 */
export type StatisticsInputPendingSearch = {
statsYr: string;
sewerBzmnCd: string;
ctpvNm: string;
sggNm: string;
};
export function verificationSearchToFormValues(
s: StatisticsInputPendingSearch,
): SearchFormValues {
const ctpvNmTrimmed = s.ctpvNm?.trim() ?? "";
const sggNmTrimmed = s.sggNm?.trim() ?? "";
/** 시군구 필수 도(`DoList.ts`의 `doNameList`)일 때만 API `sggNm`을 검색폼에 반영 */
const useSggNm =
sggNmTrimmed.length > 0 && doNameList.includes(ctpvNmTrimmed);
return {
year: s.statsYr,
bsnmCd: s.sewerBzmnCd,
sido: s.ctpvNm,
gugun: useSggNm ? sggNmTrimmed : "ALL",
};
}
/** `statistics-page` 동적 import 경로의 파일명(확장자 제외)과 일치해야 함 */
export const STATISTICS_INPUT_URL_PATH = {
SEWAGE_PIPE: "SewagePipeInp",
SEWAGE_PIPE_MAINTAIN: "SewagePipeMaintainInp",
SEWERAGE_PENETRATION_RATE: "SeweragePenetrationRateInp",
} as const;
function normalizeSewagePipeTabKey(tabKey: string): string {
if (
tabKey === "adminAreaConnectionInp" ||
tabKey === "treatmentPlantConnectionInp"
) {
return "ST00020006";
}
return tabKey;
}
const NAV_ROWS: { urlPath: string; tabKeys: readonly string[] }[] = [
{ urlPath: STATISTICS_INPUT_URL_PATH.SEWAGE_PIPE, tabKeys: SEWAGE_PIPE_INP_TAB_KEYS },
{
urlPath: STATISTICS_INPUT_URL_PATH.SEWAGE_PIPE_MAINTAIN,
tabKeys: SEWAGE_PIPE_MAINTAIN_INP_TAB_KEYS,
},
{
urlPath: STATISTICS_INPUT_URL_PATH.SEWERAGE_PENETRATION_RATE,
tabKeys: SEWERAGE_PENETRATION_RATE_INP_TAB_KEYS,
},
];
/**
* 검증 결과 등의 `statsCd`(또는 입력 화면 탭 키와 동일한 코드)로
* 열 입력 화면 `urlPath`와 활성 탭 키를 반환합니다.
*/
export function resolveInputPageNavigationFromStatsCd(statsCd: string): {
urlPath: string;
tabKey: string;
} | null {
const trimmed = statsCd.trim();
if (!trimmed) return null;
for (const row of NAV_ROWS) {
if (row.tabKeys.includes(trimmed)) {
const tabKey =
row.urlPath === STATISTICS_INPUT_URL_PATH.SEWAGE_PIPE
? normalizeSewagePipeTabKey(trimmed)
: trimmed;
return { urlPath: row.urlPath, tabKey };
}
}
return null;
}
export function findMenuItemByUrlPath(
menus: MenuItem[],
urlPath: string,
): MenuItem | null {
for (const item of menus) {
if (item.urlPath === urlPath) return item;
if (item.children?.length) {
const found = findMenuItemByUrlPath(item.children, urlPath);
if (found) return found;
}
}
return null;
}
+30 -26
View File
@@ -1,42 +1,46 @@
import type { HTMLAttributes } from "react"; import type { HTMLAttributes } from "react";
import type { UseQueryResult } from "@tanstack/react-query"; import type { UseQueryResult } from "@tanstack/react-query";
import { useReactTable, type TableOptions } from "@tanstack/react-table"; import { type TableOptions, useReactTable } from "@tanstack/react-table";
import { DataTable } from "@common/components"; import { DataTable } from "@common/components";
import { NoData } from "../ui/no-data";
import type { PageableList } from "../model"; import type { PageableList } from "../model";
import { NoData } from "../ui/no-data";
import { matchQueryStatus } from "./match-query-status"; import { matchQueryStatus } from "./match-query-status";
type UseDataTableOptions<T> = { type UseDataTableOptions<T> = {
query: UseQueryResult<PageableList<T>>; query: UseQueryResult<PageableList<T>>;
tableOptions: Omit<TableOptions<T>, "data" | "rowCount">; tableOptions: Omit<TableOptions<T>, "data" | "rowCount">;
dataTableOptions?: DataTableOptions<T>; dataTableOptions?: DataTableOptions<T>;
}; };
type DataTableOptions<T> = { type DataTableOptions<T> = {
variant?: "default" | "secondary" | "line"; variant?: "default" | "secondary" | "line";
className?: HTMLAttributes<HTMLTableElement>["className"]; className?: HTMLAttributes<HTMLTableElement>["className"];
viewPagination?: boolean; viewPagination?: boolean;
onRowClick?: (row: T) => void; onRowClick?: (row: T) => void;
}; };
export const useDataTable = <T,>({ export const useDataTable = <T,>({
query, query,
tableOptions, tableOptions,
dataTableOptions, dataTableOptions,
}: UseDataTableOptions<T>) => { }: UseDataTableOptions<T>) => {
const table = useReactTable({ const table = useReactTable({
...tableOptions, ...tableOptions,
data: query.data?.content ?? [], data: query.data?.content ?? [],
rowCount: query.data?.totalElements ?? 0, rowCount: query.data?.totalElements ?? 0,
}); });
return { return {
tableComponent: matchQueryStatus(query, { tableComponent: matchQueryStatus(query, {
Empty: <NoData />, Empty: <NoData />,
Success: () => { Success: () => {
return <DataTable table={table} {...dataTableOptions} />; return <DataTable table={table} {...dataTableOptions} />;
}, },
}), }),
tableInstance: table, tableInstance: table,
}; };
}; };
+9 -7
View File
@@ -1,14 +1,16 @@
import { useStore } from "zustand";
import { useContext } from "react"; import { useContext } from "react";
import type { UserStore } from "../store/user-store";
import { useStore } from "zustand";
import { StoreContext } from "../providers/store-provider"; import { StoreContext } from "../providers/store-provider";
import type { UserStore } from "../store/user-store";
export const useUserStore = <T>(selector: (store: UserStore) => T): T => { export const useUserStore = <T>(selector: (store: UserStore) => T): T => {
const storeContext = useContext(StoreContext); const storeContext = useContext(StoreContext);
if (!storeContext) { if (!storeContext) {
throw new Error("useUserStore must be used within StoreProvider"); throw new Error("useUserStore must be used within StoreProvider");
} }
return useStore(storeContext.userStore, selector); return useStore(storeContext.userStore, selector);
}; };
@@ -0,0 +1,11 @@
import type { MenuItem } from "@/entities/menu";
export const VERIFICATION_SELECTION_REPORT_MARKER =
"VerificationSelectionReport";
export function isVerificationSelectionReportMenu(item: MenuItem): boolean {
return (
item.menuEngNm === VERIFICATION_SELECTION_REPORT_MARKER ||
!!item.urlPath?.includes(VERIFICATION_SELECTION_REPORT_MARKER)
);
}
+43 -41
View File
@@ -1,59 +1,61 @@
import { createStore } from "zustand/vanilla"; import { createStore } from "zustand/vanilla";
export interface IUserInfo { export interface IUserInfo {
regDt: string; regDt: string;
mdfcnDt: string; mdfcnDt: string;
rgtr: string; rgtr: string;
mdfr: string; mdfr: string;
adminRoleYn: string; adminRoleYn: string;
userUnqId: string; userUnqId: string;
userId: string; userId: string;
userName: string; userName: string;
email: string; email: string;
encryptedPassword: string; encryptedPassword: string;
refreshToken: string; enoCd: string;
userStateCode: string; refreshToken: string;
lastLoginDate: string; userStateCode: string;
loginFailCount: number; lastLoginDate: string;
pswdHnt: string; loginFailCount: number;
pswdAns: string; pswdHnt: string;
mphn: string; pswdAns: string;
telno: string; mphn: string;
zip: string; telno: string;
addr: string; zip: string;
daddr: string; addr: string;
laeSeCd: string; daddr: string;
/** 기관 구분 코드 — 통계 공통 조회 등 query `instSeCd`로 전달 */ dtlInstCd: string;
instSeCd?: string; laeSeCd: string;
ogdpSeCd: string; /** 기관 구분 코드 — 통계 공통 조회 등 query `instSeCd`로 전달 */
aprvYn: string; instSeCd?: string;
autzrId: string; ogdpSeCd: string;
expryYmd: string; aprvYn: string;
lastPswdChgDt: string; autzrId: string;
googleId: string; expryYmd: string;
kakaoId: string; lastPswdChgDt: string;
naverId: string; googleId: string;
isSocialUser: boolean; kakaoId: string;
hasPassword: boolean; naverId: string;
isSocialUser: boolean;
hasPassword: boolean;
} }
export type UserState = { export type UserState = {
userInfo: IUserInfo | null; userInfo: IUserInfo | null;
}; };
export type UserActions = { export type UserActions = {
setUserInfo: (userInfo: IUserInfo | null) => void; setUserInfo: (userInfo: IUserInfo | null) => void;
}; };
export type UserStore = UserState & UserActions; export type UserStore = UserState & UserActions;
export const defaultInitState: UserState = { export const defaultInitState: UserState = {
userInfo: null, userInfo: null,
}; };
export const createUserStore = (initState: UserState = defaultInitState) => { export const createUserStore = (initState: UserState = defaultInitState) => {
return createStore<UserStore>()((set) => ({ return createStore<UserStore>()((set) => ({
...initState, ...initState,
setUserInfo: (userInfo: IUserInfo | null) => set(() => ({ userInfo })), setUserInfo: (userInfo: IUserInfo | null) => set(() => ({ userInfo })),
})); }));
}; };
@@ -10,7 +10,7 @@ function StatisticsPageLayout({ children }: { children: React.ReactNode }) {
const menuPaths = pageTitle?.path?.split(">").map((path) => path.trim()); const menuPaths = pageTitle?.path?.split(">").map((path) => path.trim());
return ( return (
<div className="h-auto min-h-full bg-container pb-2"> <div className="h-auto min-h-full bg-container pb-2 flex-1">
<TabBar /> <TabBar />
<PageTitle <PageTitle
title={pageTitle?.label ?? ""} title={pageTitle?.label ?? ""}
@@ -0,0 +1,41 @@
import { create } from "zustand";
import type { StatisticsInputPendingSearch } from "@/shared/lib/stats-cd-input-navigation";
type Pending = {
urlPath: string;
tabKey: string;
search: StatisticsInputPendingSearch | null;
};
export interface StatisticsInputFocusStore {
pending: Pending | null;
/** `setPendingInputTab` 호출 시마다 증가 — 이미 해당 화면이 활성일 때도 탭 적용 effect가 돌도록 함 */
nonce: number;
setPendingInputTab: (
urlPath: string,
tabKey: string,
search?: StatisticsInputPendingSearch | null,
) => void;
takePendingForUrl: (
urlPath: string,
) => { tabKey: string; search: StatisticsInputPendingSearch | null } | undefined;
}
export const useStatisticsInputFocusStore = create<StatisticsInputFocusStore>(
(set, get) => ({
pending: null,
nonce: 0,
setPendingInputTab: (urlPath, tabKey, search = null) =>
set((state) => ({
pending: { urlPath, tabKey, search: search ?? null },
nonce: state.nonce + 1,
})),
takePendingForUrl: (urlPath) => {
const p = get().pending;
if (!p || p.urlPath !== urlPath) return undefined;
set({ pending: null });
return { tabKey: p.tabKey, search: p.search };
},
}),
);