diff --git a/.gitignore b/.gitignore index 7175c78d4..ee2cfd052 100644 --- a/.gitignore +++ b/.gitignore @@ -4,10 +4,7 @@ # dependencies node_modules/ - -# build -.next/ -dist/ +.idea/ # build .next @@ -22,9 +19,14 @@ apps/fo/.next/**/* #.env* .qodo +# next-agents-md +.next-docs/ + pnpm-lock.yaml settings.json .npmrc .cursor +.agent - +apps/**/tsconfig.tsbuildinfo +logs/ diff --git a/.husky/pre-push b/.husky/pre-push index 0ddfdb46e..2adeaead9 100755 --- a/.husky/pre-push +++ b/.husky/pre-push @@ -3,4 +3,8 @@ BRANCH=$(git rev-parse --abbrev-ref HEAD) if [ "$BRANCH" != "main" ]; then exit 0 fi +echo "Branch: $BRANCH" +echo "Changed packages (dry-run):" +pnpm turbo run build --filter="...[origin/$BRANCH]" --dry-run +echo "Starting build..." pnpm turbo run build --filter="...[origin/$BRANCH]" diff --git a/apps/_template/.env.example b/apps/_template/.env.example index b2d706024..f9794a6f8 100644 --- a/apps/_template/.env.example +++ b/apps/_template/.env.example @@ -3,3 +3,6 @@ NEXT_PUBLIC_PORT= NEXT_PUBLIC_PROXY_HOST= NEXT_PUBLIC_SITE_ID= NEXT_PUBLIC_SERVER_API_URL= + +# 401 시 브라우저 리다이렉트 대상 +NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL=/auth/login diff --git a/apps/_template/package.json b/apps/_template/package.json index fb27f8af7..17b53990f 100644 --- a/apps/_template/package.json +++ b/apps/_template/package.json @@ -25,7 +25,7 @@ }, "devDependencies": { "eslint": "^9.0.0", - "eslint-config-next": "15.4.0", + "eslint-config-next": "15.3.8", "postcss": "^8.4.49", "prettier": "^3.4.2", "prettier-plugin-tailwindcss": "^0.6.11", diff --git a/apps/cm/package.json b/apps/cm/package.json index 9d4e1da8f..bde698393 100644 --- a/apps/cm/package.json +++ b/apps/cm/package.json @@ -52,7 +52,7 @@ "@types/node": "^22.13.1", "@types/webpack": "^5.28.5", "eslint": "^9.0.0", - "eslint-config-next": "15.4.0", + "eslint-config-next": "15.3.8", "postcss": "^8.4.49", "prettier": "^3.4.2", "prettier-plugin-tailwindcss": "^0.6.11", diff --git a/apps/cm/src/entities/auth/lib/auth-wrapper.tsx b/apps/cm/src/entities/auth/lib/auth-wrapper.tsx index 1aa4f8e61..5366696f7 100644 --- a/apps/cm/src/entities/auth/lib/auth-wrapper.tsx +++ b/apps/cm/src/entities/auth/lib/auth-wrapper.tsx @@ -5,16 +5,15 @@ import { useRouter } from "next/navigation"; import { client } from "@/shared/api"; import type { IUserInfo } from "@/shared/store"; import { getCookie, useUserStore } from "@/shared/lib"; +import { isAtLoginRedirectUrl } from "@common/network"; import { ENDPOINT, AUTH_USER_ID } from "@/shared/config"; -import { LoginApi } from "../api/login-service"; const AuthWrapper = ({ children }: { children: React.ReactNode }) => { const router = useRouter(); const { userInfo, setUserInfo } = useUserStore((state) => state); async function authCheck() { - // 로그인 페이지에서는 인증 체크를 건너뜀 - if (window.location.pathname === '/auth/login') { + if (isAtLoginRedirectUrl("/auth/login")) { return; } @@ -35,13 +34,8 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { await authCheck(); } catch (error) { console.error(error); - - try { - await LoginApi.silentRefresh(); - await authCheck(); - } catch (refreshError) { - console.error("Token refresh failed:", refreshError); - setUserInfo(null); + setUserInfo(null); + if (!isAtLoginRedirectUrl("/auth/login")) { router.push("/auth/login"); } } diff --git a/apps/cm/src/pages/auth/login/ui/login-page.tsx b/apps/cm/src/pages/auth/login/ui/login-page.tsx index fed7be4ad..297d28a8f 100644 --- a/apps/cm/src/pages/auth/login/ui/login-page.tsx +++ b/apps/cm/src/pages/auth/login/ui/login-page.tsx @@ -145,11 +145,11 @@ function LoginPage() {

- 유역하수도 통합플랫폼 + 유역하수도통합플랫폼
- 통합관리시스템 + 하수도 포탈

-

유역하수도 통합플랫폼에 오신 것을 환영합니다.

+

유역하수도통합플랫폼 하수도 포탈에 오신 것을 환영합니다.

logo diff --git a/apps/common/features/next.config.ts b/apps/common/features/next.config.ts index 34965cf32..8a50ea611 100644 --- a/apps/common/features/next.config.ts +++ b/apps/common/features/next.config.ts @@ -1,6 +1,21 @@ import type { NextConfig } from "next"; const nextConfig: NextConfig = { + output: "standalone", + experimental: { + proxyTimeout: 600000, + }, + eslint: { + ignoreDuringBuilds: true, + }, + typescript: { + ignoreBuildErrors: true, + }, + logging: { + fetches: { + fullUrl: true, + }, + }, async rewrites() { return { afterFiles: [ diff --git a/apps/common/features/package.json b/apps/common/features/package.json index 14a96b6f8..7118ae49d 100644 --- a/apps/common/features/package.json +++ b/apps/common/features/package.json @@ -46,7 +46,7 @@ "@types/node": "^22.13.1", "@types/webpack": "^5.28.5", "eslint": "^9", - "eslint-config-next": "15.1.7", + "eslint-config-next": "15.3.8", "postcss": "^8", "prettier": "^3.4.2", "prettier-plugin-tailwindcss": "^0.6.11", diff --git a/apps/common/features/src/entities/auth/lib/auth-wrapper.tsx b/apps/common/features/src/entities/auth/lib/auth-wrapper.tsx index e518f938a..d514569e0 100644 --- a/apps/common/features/src/entities/auth/lib/auth-wrapper.tsx +++ b/apps/common/features/src/entities/auth/lib/auth-wrapper.tsx @@ -4,13 +4,17 @@ import { useEffect } from "react"; import { client } from "@/shared/api"; import type { IUserInfo } from "@/shared/store"; import { getCookie, useUserStore } from "@/shared/lib"; +import { getAuthLoginRedirectUrl, isAtLoginRedirectUrl } from "@common/network"; import { ENDPOINT, AUTH_USER_ID } from "@/shared/config"; -import { LoginApi } from "../api/login-service"; const AuthWrapper = ({ children }: { children: React.ReactNode }) => { const { userInfo, setUserInfo } = useUserStore((state) => state); async function authCheck() { + if (isAtLoginRedirectUrl(getAuthLoginRedirectUrl())) { + return; + } + const userId = getCookie(AUTH_USER_ID); if (!userId) { throw new Error("Missing required authentication tokens"); @@ -28,8 +32,6 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { await authCheck(); } catch (error) { console.error(error); - await LoginApi.silentRefresh(); - await authCheck(); } })(); }, []); diff --git a/apps/cs/.gitignore b/apps/cs/.gitignore index b63718b61..f80a96304 100644 --- a/apps/cs/.gitignore +++ b/apps/cs/.gitignore @@ -38,4 +38,5 @@ yarn-error.log* next-env.d.ts .env* -!.env.example \ No newline at end of file +!.env.example +/start_cs.log diff --git a/apps/cs/package.json b/apps/cs/package.json index 03ec06fcf..27f43fcc1 100644 --- a/apps/cs/package.json +++ b/apps/cs/package.json @@ -52,7 +52,7 @@ "@types/node": "^22.13.1", "@types/webpack": "^5.28.5", "eslint": "^9.0.0", - "eslint-config-next": "15.4.0", + "eslint-config-next": "15.3.8", "postcss": "^8.4.49", "prettier": "^3.4.2", "prettier-plugin-tailwindcss": "^0.6.11", diff --git a/apps/cs/src/entities/auth/lib/auth-wrapper.tsx b/apps/cs/src/entities/auth/lib/auth-wrapper.tsx index c0be4c2dd..57ae75c34 100644 --- a/apps/cs/src/entities/auth/lib/auth-wrapper.tsx +++ b/apps/cs/src/entities/auth/lib/auth-wrapper.tsx @@ -1,18 +1,24 @@ "use client"; import { useEffect } from "react"; -import { useRouter } from "next/navigation"; import { client } from "@/shared/api"; import type { IUserInfo } from "@/shared/store"; import { getCookie, useUserStore } from "@/shared/lib"; -import { ENDPOINT, AUTH_USER_ID } from "@/shared/config"; -import { LoginApi } from "../api/login-service"; +import { isAtLoginRedirectUrl } from "@common/network"; +import { + ENDPOINT, + AUTH_USER_ID, + AUTH_LOGIN_REDIRECT_URL, +} from "@/shared/config"; const AuthWrapper = ({ children }: { children: React.ReactNode }) => { - const router = useRouter(); const { userInfo, setUserInfo } = useUserStore((state) => state); async function authCheck() { + if (isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) { + return; + } + const userId = getCookie(AUTH_USER_ID); if (!userId) { throw new Error("Missing required authentication tokens"); @@ -30,14 +36,9 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { await authCheck(); } catch (error) { console.error(error); - - try { - await LoginApi.silentRefresh(); - await authCheck(); - } catch (refreshError) { - console.error("Token refresh failed:", refreshError); - setUserInfo(null); - router.push("/auth/login"); + setUserInfo(null); + if (!isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) { + window.location.assign(AUTH_LOGIN_REDIRECT_URL); } } })(); diff --git a/apps/cs/src/pages/loginlog/ui/loginlog-page.tsx b/apps/cs/src/pages/loginlog/ui/loginlog-page.tsx index 7ae7990a1..d94d79c9a 100644 --- a/apps/cs/src/pages/loginlog/ui/loginlog-page.tsx +++ b/apps/cs/src/pages/loginlog/ui/loginlog-page.tsx @@ -39,10 +39,10 @@ function LoginlogPage() { const [presetDateRange, setPresetDateRange] = useState(""); const [dateRange, setDateRange] = useState(defaultDateRange); const [userId, setUserId] = useState(""); - const [errOcrnYn, setErrOcrnYn] = useState("N"); + const [errOcrnYn, setErrOcrnYn] = useState("ALL"); const [searchParams, setSearchParams] = useState({ userId: "", - errOcrnYn: "N", + errOcrnYn: "", searchDateFrom: dayjs().subtract(7, "day").format("YYYY-MM-DD"), searchDateTo: dayjs().format("YYYY-MM-DD"), sort: "lgnDt,desc", @@ -87,7 +87,7 @@ function LoginlogPage() { setSearchParams({ ...searchParams, userId, - errOcrnYn, + errOcrnYn: errOcrnYn === "ALL" ? "" : errOcrnYn, searchDateFrom: dateRange.from ? dayjs(dateRange.from).format("YYYY-MM-DD") : "", @@ -102,12 +102,12 @@ function LoginlogPage() { const handleReset = () => { setUserId(""); - setErrOcrnYn("N"); + setErrOcrnYn("ALL"); setDateRange(defaultDateRange); setSearchParams({ ...searchParams, userId: "", - errOcrnYn: "N", + errOcrnYn: "", searchDateFrom: dayjs().subtract(7, "day").format("YYYY-MM-DD"), searchDateTo: dayjs().format("YYYY-MM-DD"), }); @@ -180,6 +180,7 @@ function LoginlogPage() { + 전체 정상 오류 diff --git a/apps/cs/src/shared/config/env.ts b/apps/cs/src/shared/config/env.ts index c6373724f..95d1a4477 100644 --- a/apps/cs/src/shared/config/env.ts +++ b/apps/cs/src/shared/config/env.ts @@ -2,6 +2,8 @@ export const PORT = process.env.NEXT_PUBLIC_PORT || "3000"; export const PROXY_HOST = process.env.NEXT_PUBLIC_PROXY_HOST || `http://localhost:${PORT}`; export const SERVER_API_URL = process.env.NEXT_PUBLIC_SERVER_API_URL; +export const AUTH_LOGIN_REDIRECT_URL = + process.env.NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL || "/auth/login"; export const SITE_ID = process.env.NEXT_PUBLIC_SITE_ID || "CS"; export const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization"; export const ACCESS_TOKEN = diff --git a/apps/dc/package.json b/apps/dc/package.json index 747cdf91e..5835b9ab6 100644 --- a/apps/dc/package.json +++ b/apps/dc/package.json @@ -41,7 +41,7 @@ "@types/node": "^22.17.0", "@types/webpack": "^5.28.5", "eslint": "^9.0.0", - "eslint-config-next": "15.4.0", + "eslint-config-next": "15.3.8", "postcss": "^8.4.49", "prettier": "^3.4.2", "prettier-plugin-tailwindcss": "^0.6.11", diff --git a/apps/dc/src/entities/auth/lib/auth-wrapper.tsx b/apps/dc/src/entities/auth/lib/auth-wrapper.tsx index 1f196ed52..57ae75c34 100644 --- a/apps/dc/src/entities/auth/lib/auth-wrapper.tsx +++ b/apps/dc/src/entities/auth/lib/auth-wrapper.tsx @@ -1,20 +1,24 @@ "use client"; import { useEffect } from "react"; -import { useRouter } from "next/navigation"; import { client } from "@/shared/api"; import type { IUserInfo } from "@/shared/store"; import { getCookie, useUserStore } from "@/shared/lib"; -import { ENDPOINT, AUTH_USER_ID } from "@/shared/config"; -import { LoginApi } from "../api/login-service"; - -const CLAIM_NAME = process.env.NEXT_PUBLIC_CLAIM_NAME || "Authorization"; +import { isAtLoginRedirectUrl } from "@common/network"; +import { + ENDPOINT, + AUTH_USER_ID, + AUTH_LOGIN_REDIRECT_URL, +} from "@/shared/config"; const AuthWrapper = ({ children }: { children: React.ReactNode }) => { - const router = useRouter(); const { userInfo, setUserInfo } = useUserStore((state) => state); async function authCheck() { + if (isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) { + return; + } + const userId = getCookie(AUTH_USER_ID); if (!userId) { throw new Error("Missing required authentication tokens"); @@ -32,14 +36,9 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { await authCheck(); } catch (error) { console.error(error); - - try { - await LoginApi.silentRefresh(); - await authCheck(); - } catch (refreshError) { - console.error("Token refresh failed:", refreshError); - setUserInfo(null); - router.push("/auth/login"); + setUserInfo(null); + if (!isAtLoginRedirectUrl(AUTH_LOGIN_REDIRECT_URL)) { + window.location.assign(AUTH_LOGIN_REDIRECT_URL); } } })(); diff --git a/apps/dc/src/shared/config/env.ts b/apps/dc/src/shared/config/env.ts index 89d2c039c..9edea0e2d 100644 --- a/apps/dc/src/shared/config/env.ts +++ b/apps/dc/src/shared/config/env.ts @@ -3,10 +3,14 @@ export const PROXY_HOST = process.env.NEXT_PUBLIC_PROXY_HOST || `http://localhost:${PORT}`; export const SERVER_API_URL = process.env.NEXT_PUBLIC_SERVER_API_URL; -export const NEXT_PUBLIC_DC_SERVICE_API_URL = process.env.NEXT_PUBLIC_DC_SERVICE_API_URL || `http://localhost:${PORT}`; +export const NEXT_PUBLIC_DC_SERVICE_API_URL = + process.env.NEXT_PUBLIC_DC_SERVICE_API_URL || `http://localhost:${PORT}`; +export const AUTH_LOGIN_REDIRECT_URL = + process.env.NEXT_PUBLIC_AUTH_LOGIN_REDIRECT_URL || "/auth/login"; // Flask API URL -export const FLASK_API_URL = process.env.NEXT_PUBLIC_FLASK_API_URL || "http://localhost:5000"; +export const FLASK_API_URL = + process.env.NEXT_PUBLIC_FLASK_API_URL || "http://localhost:5000"; //export const SITE_ID = process.env.NEXT_PUBLIC_SITE_ID || "DC"; export const SITE_ID = "DC"; diff --git a/apps/dm/package.json b/apps/dm/package.json index 71d504f50..844e0b1aa 100644 --- a/apps/dm/package.json +++ b/apps/dm/package.json @@ -29,7 +29,7 @@ "@eslint/eslintrc": "^3", "@types/webpack": "^5.28.5", "eslint": "^9", - "eslint-config-next": "15.1.7", + "eslint-config-next": "15.3.8", "postcss": "^8", "tailwindcss": "^3.4.1", "typescript": "^5" diff --git a/apps/dm_new/package.json b/apps/dm_new/package.json index f318baf0b..3df43f28e 100644 --- a/apps/dm_new/package.json +++ b/apps/dm_new/package.json @@ -29,8 +29,8 @@ "@eslint/eslintrc": "^3", "@types/webpack": "^5.28.5", "eslint": "^9", - "eslint-config-next": "15.1.7", - "postcss": "^8", + "eslint-config-next": "15.3.8", + "postcss": "^8", "tailwindcss": "^3.4.1", "typescript": "^5" } diff --git a/apps/fo/.env.local b/apps/fo/.env.local index 1b80d302e..646d80c2c 100644 --- a/apps/fo/.env.local +++ b/apps/fo/.env.local @@ -16,8 +16,8 @@ NEXT_PUBLIC_DC_URL = https://apigateway.apps.rsonesoft.com/dc-service NEXT_PUBLIC_SEWERAGE_API_URL = http://con.mind-one.co.kr:11083/sewerage-service # 개발 서버 API NEXT_PUBLIC_NGII_URL = https://map.ngii.go.kr NEXT_PUBLIC_NGII_PARAM = 04trYP9_xwLAfALjwZ-B8g&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={x}&tilerow={y} -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login - +# NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login +NEXT_PUBLIC_CM_LOGIN_PAGE_URL = / #NEXT_PUBLIC_SERVER_API_URL = http://localhost:8883/operation-service diff --git a/apps/fo/.env.mindone b/apps/fo/.env.mindone index f014168c2..2fd7e91c2 100644 --- a/apps/fo/.env.mindone +++ b/apps/fo/.env.mindone @@ -7,7 +7,6 @@ NEXT_PUBLIC_REFRESH_TOKEN = refresh-token NEXT_PUBLIC_PROXY_HOST = http://con.mind-one.co.kr:11300 NEXT_PUBLIC_SUB_DOMAIN = http://con.mind-one.co.kr:13000 NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login -#NEXT_PUBLIC_SERVER_API_URL = http://con.mind-one.co.kr:11082 NEXT_PUBLIC_SERVER_API_URL = http://con.mind-one.co.kr:11083/operation-service NEXT_PUBLIC_WR_SERVER_API_URL = http://con.mind-one.co.kr:11083/reuse-service/ NEXT_PUBLIC_CS_SERVER_API_URL = http://dev.onasys.co.kr:8000 @@ -17,3 +16,4 @@ NEXT_PUBLIC_DC_URL = https://apigateway.apps.rsonesoft.com/dc-service NEXT_PUBLIC_SEWERAGE_API_URL = http://con.mind-one.co.kr:11083/sewerage-service NEXT_PUBLIC_NGII_URL = https://map.ngii.go.kr NEXT_PUBLIC_NGII_PARAM = 04trYP9_xwLAfALjwZ-B8g&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={x}&tilerow={y} +NEXT_PUBLIC_CM_LOGIN_PAGE_URL = / \ No newline at end of file diff --git a/apps/fo/.env.production b/apps/fo/.env.production index d6940b0e9..bd0d0f04b 100644 --- a/apps/fo/.env.production +++ b/apps/fo/.env.production @@ -17,3 +17,4 @@ NEXT_PUBLIC_DC_URL = http://apigateway.iipbs-was.svc.cluster.local:8000/dc-s NEXT_PUBLIC_SEWERAGE_API_URL = http://apigateway.iipbs-was.svc.cluster.local:8000/sewerage-service NEXT_PUBLIC_NGII_URL = http://172.29.143.87/poiact NEXT_PUBLIC_NGII_PARAM = BDE2BEF39DAFEC293AB6730150F222AC&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={y}&tilerow={x} +NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login \ No newline at end of file diff --git a/apps/fo/package.json b/apps/fo/package.json index 6993fe17c..9408ca885 100644 --- a/apps/fo/package.json +++ b/apps/fo/package.json @@ -37,7 +37,7 @@ "devDependencies": { "@eslint/eslintrc": "^3", "eslint": "^9", - "eslint-config-next": "15.1.7", + "eslint-config-next": "15.3.8", "postcss": "^8", "tailwindcss": "^3.4.17", "typescript": "^5.6.3" diff --git a/apps/fo/src/entities/auth/lib/auth-wrapper.tsx b/apps/fo/src/entities/auth/lib/auth-wrapper.tsx index 864b54ce0..21fd87180 100644 --- a/apps/fo/src/entities/auth/lib/auth-wrapper.tsx +++ b/apps/fo/src/entities/auth/lib/auth-wrapper.tsx @@ -1,21 +1,23 @@ "use client"; import { useEffect } from "react"; -import { useRouter } from "next/navigation"; import { client } from "@/src/shared/api"; import type { IUserInfo } from "@/src/shared/store"; +import { isAtLoginRedirectUrl } from "@common/network"; import { useUserStore, getCookie } from "@/src/shared/lib"; import { ENDPOINT, AUTH_USER_ID } from "@/src/shared/config"; -import { LoginApi } from "../api/login-service"; -const LOGIN_PAGE_URL = process.env.NEXT_PUBLIC_CM_LOGIN_PAGE_URL || "http://localhost:3001/auth/login"; // 개발 환경 URL +const LOGIN_PAGE_URL = + process.env.NEXT_PUBLIC_CM_LOGIN_PAGE_URL || "/auth/login"; const AuthWrapper = ({ children }: { children: React.ReactNode }) => { - const router = useRouter(); - // const pathname = usePathname(); const { userInfo, setUserInfo } = useUserStore((state) => state); async function authCheck() { + if (isAtLoginRedirectUrl(LOGIN_PAGE_URL)) { + return; + } + const userId = getCookie(AUTH_USER_ID); if (!userId) { throw new Error("Missing required authentication tokens"); @@ -33,24 +35,29 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { await authCheck(); } catch (error) { console.error(error); - - try { - await LoginApi.silentRefresh(); - await authCheck(); - } catch (refreshError) { - console.error("Token refresh failed:", refreshError); - setUserInfo(null); - - const hostname = window.location.hostname; - - // 개발 환경에서는 localhost 도메인 사용 - if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "con.mind-one.co.kr") - router.push("/"); // 개발시 홈으로 돌아가기 - - // 운영 환경에서는 서브도메인을 포함한 최상위 도메인 사용 - // router.push는 같은 Next.js 앱 내에서만 작동하므로 다른 앱으로 이동할 때는 window.location.href 사용 - if (hostname.includes("hasuon.or.kr")) window.location.href = LOGIN_PAGE_URL; // 세션 만료 시 CM 로그인 페이지로 리다이렉트 + setUserInfo(null); + if (isAtLoginRedirectUrl(LOGIN_PAGE_URL)) { + return; } + + // const hostname = window.location.hostname; + + // // 개발 환경에서는 localhost 도메인 사용 + // if ( + // hostname === "localhost" || + // hostname === "127.0.0.1" || + // hostname === "con.mind-one.co.kr" + // ) { + // router.push("/"); // 개발시 홈으로 돌아가기 + // } + + // // 운영 환경에서는 서브도메인을 포함한 최상위 도메인 사용 + // // router.push는 같은 Next.js 앱 내에서만 작동하므로 다른 앱으로 이동할 때는 window.location.href 사용 + // if (hostname.includes("hasuon.or.kr")) + // window.location.assign(LOGIN_PAGE_URL); // 세션 만료 시 CM 로그인 페이지로 리다이렉트 + + // 개발/운영 환경에서 로그인 URL 분기는 환경 변수로 처리 (.env.*) + window.location.assign(LOGIN_PAGE_URL); } })(); }, []); @@ -58,4 +65,4 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { return <>{children}; }; -export { AuthWrapper }; \ No newline at end of file +export { AuthWrapper }; diff --git a/apps/sn/.env.local b/apps/sn/.env.local index 997f50518..1d4c11d21 100644 --- a/apps/sn/.env.local +++ b/apps/sn/.env.local @@ -14,7 +14,6 @@ NEXT_PUBLIC_NGII_PARAM = 04trYP9_xwLAfALjwZ-B8g&service=WMTS&request=GetTile&ver NEXT_PUBLIC_SERVER_API_URL = http://dev.onasys.co.kr:8000 NEXT_PUBLIC_SEWERAGE_API_URL = http://con.mind-one.co.kr:11083 NEXT_PUBLIC_DC_URL = https://apigateway.apps.rsonesoft.com -NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login -#NEXT_PUBLIC_SEWERAGE_API_URL=http://con.mind-one.co.kr:11083 -#NEXT_PUBLIC_SEWERAGE_API_URL=http://192.168.1.222:8883 +# NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login +NEXT_PUBLIC_CM_LOGIN_PAGE_URL = / # NEXT_PUBLIC_SEWERAGE_API_URL=http://192.168.1.66:8883 diff --git a/apps/sn/.env.mindone b/apps/sn/.env.mindone index cea5518db..847103c97 100644 --- a/apps/sn/.env.mindone +++ b/apps/sn/.env.mindone @@ -12,4 +12,5 @@ NEXT_PUBLIC_LX_GEOSERVER_URL = http://con.mind-one.co.kr:11306/geoserver NEXT_PUBLIC_NGII_URL = https://map.ngii.go.kr NEXT_PUBLIC_NGII_PARAM = 04trYP9_xwLAfALjwZ-B8g&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={x}&tilerow={y} NEXT_PUBLIC_SEWERAGE_API_URL = http://con.mind-one.co.kr:11083 -NEXT_PUBLIC_DC_URL = https://apigateway.apps.rsonesoft.com \ No newline at end of file +NEXT_PUBLIC_DC_URL = https://apigateway.apps.rsonesoft.com +NEXT_PUBLIC_CM_LOGIN_PAGE_URL = / \ No newline at end of file diff --git a/apps/sn/.env.production b/apps/sn/.env.production index c68db7859..4a7c15edc 100644 --- a/apps/sn/.env.production +++ b/apps/sn/.env.production @@ -15,4 +15,4 @@ NEXT_PUBLIC_NGII_URL = http://172.29.143.87/poiact NEXT_PUBLIC_NGII_PARAM = BDE2BEF39DAFEC293AB6730150F222AC&service=WMTS&request=GetTile&version=1.0.0&format=image/png&layer=korean_map&style=korean&tilematrixset=korean&tilematrix={z}&tilecol={y}&tilerow={x} NEXT_PUBLIC_SEWERAGE_API_URL = http://apigateway.iipbs-was.svc.cluster.local:8000 NEXT_PUBLIC_DC_URL = http://apigateway.iipbs-was.svc.cluster.local:8000 - +NEXT_PUBLIC_CM_LOGIN_PAGE_URL = http://dev.onasys.co.kr:3000/auth/login diff --git a/apps/sn/package.json b/apps/sn/package.json index 1041df157..20aa6581d 100644 --- a/apps/sn/package.json +++ b/apps/sn/package.json @@ -49,7 +49,7 @@ "@types/node": "^22.13.1", "@types/webpack": "^5.28.5", "eslint": "^9", - "eslint-config-next": "15.1.7", + "eslint-config-next": "15.3.8", "postcss": "^8", "prettier": "^3.4.2", "prettier-plugin-tailwindcss": "^0.6.11", diff --git a/apps/sn/src/entities/auth/lib/auth-wrapper.tsx b/apps/sn/src/entities/auth/lib/auth-wrapper.tsx index 1c27e6fe3..bc4a82aab 100644 --- a/apps/sn/src/entities/auth/lib/auth-wrapper.tsx +++ b/apps/sn/src/entities/auth/lib/auth-wrapper.tsx @@ -1,23 +1,26 @@ "use client"; import { useEffect } from "react"; -import { useRouter, usePathname } from "next/navigation"; +import { usePathname } from "next/navigation"; import { client } from "@/shared/api"; import type { IUserInfo } from "@/shared/store"; import { useUserStore } from "@/shared/lib"; import { ENDPOINT, AUTH_USER_ID } from "@/shared/config"; +import { isAtLoginRedirectUrl } from "@common/network"; import { getCookie } from "@/shared/lib"; -import { LoginApi } from "../api/login-service"; - -const LOGIN_PAGE_URL = process.env.NEXT_PUBLIC_CM_LOGIN_PAGE_URL || "http://dev.onasys.co.kr:3000/auth/login"; // 로그인 페이지 URL +const LOGIN_PAGE_URL = + process.env.NEXT_PUBLIC_CM_LOGIN_PAGE_URL || "/auth/login"; const AuthWrapper = ({ children }: { children: React.ReactNode }) => { - const router = useRouter(); const pathname = usePathname(); const { userInfo, setUserInfo } = useUserStore((state) => state); async function authCheck() { + if (isAtLoginRedirectUrl(LOGIN_PAGE_URL)) { + return; + } + const userId = getCookie(AUTH_USER_ID); if (!userId) { throw new Error("Missing required authentication tokens"); @@ -35,24 +38,27 @@ const AuthWrapper = ({ children }: { children: React.ReactNode }) => { await authCheck(); } catch (error) { console.error(error); + setUserInfo(null); - try { - await LoginApi.silentRefresh(); - await authCheck(); - } catch (refreshError) { - console.error("Token refresh failed:", refreshError); - setUserInfo(null); + if (isAtLoginRedirectUrl(LOGIN_PAGE_URL)) return; - const hostname = window.location.hostname; + // const hostname = window.location.hostname; - // 개발 환경에서는 localhost 도메인 사용 - if (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "con.mind-one.co.kr") - window.location.href = "/"; + // // 개발 환경에서는 localhost 도메인 사용 + // if ( + // hostname === "localhost" || + // hostname === "127.0.0.1" || + // hostname === "con.mind-one.co.kr" + // ) + // window.location.href = "/"; - // 운영 환경에서는 서브도메인을 포함한 최상위 도메인 사용 - // router.push는 같은 Next.js 앱 내에서만 작동하므로 다른 앱으로 이동할 때는 window.location.href 사용 - if (hostname.includes("hasuon.or.kr")) window.location.href = LOGIN_PAGE_URL; // 세션 만료 시 CM 로그인 페이지로 리다이렉트 - } + // // 운영 환경에서는 서브도메인을 포함한 최상위 도메인 사용 + // // router.push는 같은 Next.js 앱 내에서만 작동하므로 다른 앱으로 이동할 때는 window.location.href 사용 + // if (hostname.includes("hasuon.or.kr")) + // window.location.href = LOGIN_PAGE_URL; // 세션 만료 시 CM 로그인 페이지로 리다이렉트 + + // 개발/운영 환경에서 로그인 URL 분기는 환경 변수로 처리 (.env.*) + window.location.assign(LOGIN_PAGE_URL); } })(); }, [pathname]); diff --git a/apps/st/.gitignore b/apps/st/.gitignore index f06d9d40b..3f74d9ee3 100644 --- a/apps/st/.gitignore +++ b/apps/st/.gitignore @@ -39,4 +39,7 @@ next-env.d.ts .env* !.env.example -*.md \ No newline at end of file +*.md + +# next-agents-md +.next-docs/ diff --git a/apps/st/app/(auth)/auth/layout.tsx b/apps/st/app/(auth)/auth/layout.tsx new file mode 100644 index 000000000..33651c590 --- /dev/null +++ b/apps/st/app/(auth)/auth/layout.tsx @@ -0,0 +1,17 @@ +import "@/app/styles/base.css"; + +export const metadata = { + title: "유역하수도 통합 정보플랫폼", +}; + +export default function AuthLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + + {children} + + ); +} diff --git a/apps/st/app/auth/login/page.tsx b/apps/st/app/(auth)/auth/login/page.tsx similarity index 100% rename from apps/st/app/auth/login/page.tsx rename to apps/st/app/(auth)/auth/login/page.tsx diff --git a/apps/st/app/(main)/(with-base-layout)/layout.tsx b/apps/st/app/(main)/(with-base-layout)/layout.tsx new file mode 100644 index 000000000..6faa92cc1 --- /dev/null +++ b/apps/st/app/(main)/(with-base-layout)/layout.tsx @@ -0,0 +1,171 @@ +"use client"; + +import { useCallback, useEffect, useMemo } from "react"; +import { usePathname } from "next/navigation"; + +import { + getTabStoreState as getGridTabStoreState, + useTabStore as gridTabStore, +} from "@rsone/components"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; + +import { ENDPOINT } from "@/shared/config"; +import { getCookie, useAlertStore, useMenuStore } from "@/shared/lib"; +import { StatisticsPageLayout } from "@/shared/ui/statistics-page-layout"; +import { MenuApi } from "@/entities/menu"; +import type { MenuItem } from "@/entities/menu"; +import { BaseLayout } from "@common/components"; +import { getConfig } from "@common/config"; + +import { getTabStoreState, useTabStore } from "@/store/tab-store"; + +const appConfig = getConfig(); +const userId = getCookie(appConfig.AUTH_USER_ID ?? ""); +const appSiteId = getCookie("site-id-key") ?? ""; +const isLoggedIn = !!userId; + +export default function WithBaseLayout({ + children, +}: { + children: React.ReactNode; +}) { + const pathname = usePathname(); + const queryClient = useQueryClient(); + + const setCurrentMenuInfo = useMenuStore( + (state) => state.setCurrentMenuInfo, + ); + const currentMenuInfo = useMenuStore((state) => state.currentMenuInfo); + + const addTab = useTabStore((state) => state.addTab); + const setActiveTab = useTabStore((state) => state.setActiveTab); + const setMenuList = useTabStore((state) => state.setMenuList); + const activeTabId = useTabStore((state) => state.activeTabId); + const menuList = useTabStore((state) => state.menuList); + const tabs = useTabStore((state) => state.tabs); + const addTabForGrid = gridTabStore((state) => state.addTab); + const setActiveTabForGrid = gridTabStore((state) => state.setActiveTab); + const setMenuListForGrid = gridTabStore((state) => state.setMenuList); + const alert = useAlertStore((state) => state.setMessage); + + const { data: menuListData } = useQuery({ + queryKey: [ENDPOINT.CMS_SERVICE.MENU_ROLES], + queryFn: () => MenuApi.getMenuRoles(appSiteId), + enabled: isLoggedIn, + }); + + useEffect(() => { + if (menuListData) { + setMenuList(menuListData); + setMenuListForGrid(menuListData); + } + }, [menuListData, setMenuList, setMenuListForGrid]); + + // 새로고침 후 persist로 앱 탭만 복원된 경우 rsone 그리드 스토어에 탭을 맞춤 + useEffect(() => { + if (!menuList) return; + const appTabs = getTabStoreState().tabs; + if (appTabs.length === 0) return; + if (getGridTabStoreState().tabs.length > 0) return; + + for (const tab of appTabs) { + getGridTabStoreState().addTab(tab.menuItem); + } + + const activeId = getTabStoreState().activeTabId; + if (activeId) { + const activeTab = appTabs.find((t) => t.id === activeId); + const gridActiveId = activeTab?.menuItem.menuEngNm; + if (gridActiveId) { + getGridTabStoreState().setActiveTab(gridActiveId); + } + } + }, [menuList, tabs]); + + useEffect(() => { + if (!pathname) return; + + // pathname이 변경될 때만 실행되도록 tabs를 직접 가져옴 + const currentTabs = getTabStoreState().tabs; + const tab = currentTabs.find((t) => t.path === pathname); + if (tab) { + setActiveTab(tab.id); + const gridActiveId = tab.menuItem.menuEngNm; + if (gridActiveId) { + setActiveTabForGrid(gridActiveId); + } + } + }, [pathname, setActiveTab, setActiveTabForGrid]); + + // 활성 탭의 메뉴를 찾아서 urlPath를 가져옴. 탭이 전부 닫히면 ''를 넘겨 LNB에서 메뉴 강조 제거 + const currentPath = useMemo(() => { + if (tabs.length === 0) return ""; + + if (activeTabId && menuList) { + // menuList에서 활성 탭의 메뉴 찾기 + const findMenuByEngNm = (items: MenuItem[]): MenuItem | null => { + for (const item of items) { + if (item.urlPath === activeTabId) { + return item; + } + if (item.children) { + const found = findMenuByEngNm(item.children); + if (found) return found; + } + } + return null; + }; + + const activeMenu = findMenuByEngNm(menuList); + + if (activeMenu?.urlPath) { + return activeMenu.urlPath; + } + } + + // 탭에서 직접 찾기 + if (activeTabId) { + const currentTabs = getTabStoreState().tabs; + const activeTab = currentTabs.find((t) => t.id === activeTabId); + if (activeTab?.menuItem?.urlPath) { + return activeTab.menuItem.urlPath; + } + } + + // currentMenuInfo에서 가져오기 + if (currentMenuInfo?.urlPath) { + return currentMenuInfo.urlPath; + } + + // 기본값으로 pathname 사용 + return pathname ?? ""; + }, [tabs.length, activeTabId, menuList, currentMenuInfo, pathname]); + + const handleMenuClick = useCallback( + (item: MenuItem) => { + setCurrentMenuInfo(item); + const addTabResult: boolean = addTab(item); + + // packages/rsone의 스토어에도 동기화 + if (addTabResult) { + addTabForGrid(item); + } + + if (!addTabResult) { + alert(`최대 추가 할 수 있는 화면 수를 초과 하였습니다. + 기존 화면을 닫은 후 이용해주세요.`); + } + }, + [setCurrentMenuInfo, addTab, addTabForGrid, alert], + ); + + return ( + + {children} + + ); +} diff --git a/apps/st/app/(with-base-layout)/loading.tsx b/apps/st/app/(main)/(with-base-layout)/loading.tsx similarity index 100% rename from apps/st/app/(with-base-layout)/loading.tsx rename to apps/st/app/(main)/(with-base-layout)/loading.tsx diff --git a/apps/st/app/(with-base-layout)/statistics/page.tsx b/apps/st/app/(main)/(with-base-layout)/statistics/page.tsx similarity index 98% rename from apps/st/app/(with-base-layout)/statistics/page.tsx rename to apps/st/app/(main)/(with-base-layout)/statistics/page.tsx index f32417f76..23feaf7e1 100644 --- a/apps/st/app/(with-base-layout)/statistics/page.tsx +++ b/apps/st/app/(main)/(with-base-layout)/statistics/page.tsx @@ -1,3 +1,2 @@ import { StatisticsPage } from "@/pages/statistics"; - export default StatisticsPage; diff --git a/apps/st/app/layout.tsx b/apps/st/app/(main)/layout.tsx similarity index 100% rename from apps/st/app/layout.tsx rename to apps/st/app/(main)/layout.tsx diff --git a/apps/st/app/(with-base-layout)/layout.tsx b/apps/st/app/(with-base-layout)/layout.tsx deleted file mode 100644 index 3fe61855e..000000000 --- a/apps/st/app/(with-base-layout)/layout.tsx +++ /dev/null @@ -1,139 +0,0 @@ -"use client"; - -import { useEffect, useCallback, useMemo } from "react"; -import { usePathname } from "next/navigation"; -import { useQueryClient, useQuery } from "@tanstack/react-query"; - -import type { MenuItem } from "@/entities/menu"; -import { useMenuStore, useAlertStore } from "@/shared/lib"; -import { useTabStore, getTabStoreState } from "@/store/tab-store"; -import { useTabStore as gridTabStore } from "@rsone/components"; -import { getConfig } from "@common/config"; -import { getCookie } from "@/shared/lib"; -import { getMenuList } from "../../../../packages/common/components/src/api"; -import { ENDPOINT } from "@/shared/config"; - -import { BaseLayout } from "@common/components"; -import { StatisticsPageLayout } from "@/shared/ui/statistics-page-layout"; - -const appConfig = getConfig(); -const userId = getCookie(appConfig.AUTH_USER_ID ?? ""); -const appSiteId = getCookie("site-id-key") ?? ""; -const isLoggedIn = !!userId; - -export default function WithBaseLayout({ - children, -}: { - children: React.ReactNode; -}) { - const pathname = usePathname(); - const queryClient = useQueryClient(); - - const setCurrentMenuInfo = useMenuStore((state) => state.setCurrentMenuInfo); - const currentMenuInfo = useMenuStore((state) => state.currentMenuInfo); - - const addTab = useTabStore((state) => state.addTab); - const setActiveTab = useTabStore((state) => state.setActiveTab); - const setMenuList = useTabStore((state) => state.setMenuList); - const activeTabId = useTabStore((state) => state.activeTabId); - const menuList = useTabStore((state) => state.menuList); - const tabs = useTabStore((state) => state.tabs); - const addTabForGrid = gridTabStore((state) => state.addTab); - const setActiveTabForGrid = gridTabStore((state) => state.setActiveTab); - const setMenuListForGrid = gridTabStore((state) => state.setMenuList); - const alert = useAlertStore((state) => state.setMessage); - - const { data: menuListData } = useQuery({ - queryKey: [ENDPOINT.CMS_SERVICE.MENU_ROLES], - queryFn: () => getMenuList(appSiteId), - enabled: isLoggedIn, - }); - - useEffect(() => { - if (menuListData) { - setMenuList(menuListData); - setMenuListForGrid(menuListData); - } - }, [menuListData, setMenuList, setMenuListForGrid]); - - useEffect(() => { - if (!pathname) return; - - // pathname이 변경될 때만 실행되도록 tabs를 직접 가져옴 - const currentTabs = getTabStoreState().tabs; - const tab = currentTabs.find((t) => t.path === pathname); - if (tab) { - setActiveTab(tab.id); - setActiveTabForGrid(tab.id); - } - }, [pathname, setActiveTab, setActiveTabForGrid]); - - // 활성 탭의 메뉴를 찾아서 urlPath를 가져옴. 탭이 전부 닫히면 ''를 넘겨 LNB에서 메뉴 강조 제거 - const currentPath = useMemo(() => { - if (tabs.length === 0) return ""; - - if (activeTabId && menuList) { - // menuList에서 활성 탭의 메뉴 찾기 - const findMenuByEngNm = (items: MenuItem[]): MenuItem | null => { - for (const item of items) { - if (item.menuEngNm === activeTabId) { - return item; - } - if (item.children) { - const found = findMenuByEngNm(item.children); - if (found) return found; - } - } - return null; - }; - - const activeMenu = findMenuByEngNm(menuList); - - if (activeMenu?.urlPath) { - return activeMenu.urlPath; - } - } - - // 탭에서 직접 찾기 - if (activeTabId) { - const currentTabs = getTabStoreState().tabs; - const activeTab = currentTabs.find((t) => t.id === activeTabId); - if (activeTab?.menuItem?.urlPath) { - return activeTab.menuItem.urlPath; - } - } - - // currentMenuInfo에서 가져오기 - if (currentMenuInfo?.urlPath) { - return currentMenuInfo.urlPath; - } - - // 기본값으로 pathname 사용 - return pathname ?? ""; - }, [tabs.length, activeTabId, menuList, currentMenuInfo, pathname]); - - const handleMenuClick = useCallback((item: MenuItem) => { - setCurrentMenuInfo(item); - const addTabResult: boolean = addTab(item); - - // packages/rsone의 스토어에도 동기화 - if (addTabResult) { - addTabForGrid(item); - } - - if (!addTabResult) { - alert(`최대 추가 할 수 있는 화면 수를 초과 하였습니다. - 기존 화면을 닫은 후 이용해주세요.`); - } - }, [setCurrentMenuInfo, addTab, addTabForGrid, alert]); - - return ( - - {children} - - ); -} diff --git a/apps/st/app/api/proxy/[...url]/route.ts b/apps/st/app/api/proxy/[...url]/route.ts index 7442c702f..c9f0d3730 100644 --- a/apps/st/app/api/proxy/[...url]/route.ts +++ b/apps/st/app/api/proxy/[...url]/route.ts @@ -1,104 +1,106 @@ import { - ACCESS_TOKEN, - AUTH_USER_ID, - CLAIM_NAME, - REFRESH_TOKEN, - SERVER_API_URL, - SITE_ID, + ACCESS_TOKEN, + AUTH_USER_ID, + CLAIM_NAME, + REFRESH_TOKEN, + SERVER_API_URL, + SITE_ID, } from "@/shared/config"; import { cookies } from "next/headers"; import { NextResponse } from "next/server"; async function handler( - request: Request, - params: { url: string[] }, - method: "GET" | "POST" | "PUT" | "DELETE", + request: Request, + params: { url: string[] }, + method: "GET" | "POST" | "PUT" | "DELETE", ) { - const cookieStore = await cookies(); - const headers: Record = { - "Content-Type": "application/json", - "X-Site-Id": SITE_ID, - }; - let body = {}; - const isRefreshHandler = params.url.includes("refresh"); + const cookieStore = await cookies(); + const headers: Record = { + "Content-Type": "application/json", + "X-Site-Id": SITE_ID, + }; + let body = {}; + const isRefreshHandler = params.url.includes("refresh"); - // silent refresh - if (isRefreshHandler) { - const refreshToken = cookieStore.get(REFRESH_TOKEN); - headers[CLAIM_NAME] = refreshToken?.value ?? ""; + // silent refresh + if (isRefreshHandler) { + const refreshToken = cookieStore.get(REFRESH_TOKEN); + headers[CLAIM_NAME] = refreshToken?.value ?? ""; - if (!headers[CLAIM_NAME]) { - return NextResponse.json({ message: "Can't refresh" }, { status: 401 }); - } - } - - try { - if (!isRefreshHandler) { - body = await request.json(); + if (!headers[CLAIM_NAME]) { + return NextResponse.json( + { message: "Can't refresh" }, + { status: 401 }, + ); + } } - const result = await fetch(`${SERVER_API_URL}/${params.url.join("/")}`, { - method, - headers, - body: JSON.stringify(body), - }); + try { + if (!isRefreshHandler) { + body = await request.json(); + } - if (!result.ok) { - return NextResponse.json( - { message: "Invalid Credentials" }, - { status: 401 }, - ); + const result = await fetch( + `${SERVER_API_URL}/${params.url.join("/")}`, + { + method, + headers, + body: JSON.stringify(body), + }, + ); + + if (!result.ok) { + return NextResponse.json( + { message: "Invalid Credentials" }, + { status: 401 }, + ); + } + + const accessToken = result.headers.get(ACCESS_TOKEN); + const refreshToken = result.headers.get(REFRESH_TOKEN); + const userId = result.headers.get(AUTH_USER_ID); + + if (accessToken && userId) { + const response = NextResponse.json({ + [ACCESS_TOKEN]: accessToken, + [AUTH_USER_ID]: userId, + }); + + if (refreshToken) { + cookieStore.set(REFRESH_TOKEN, refreshToken, { + httpOnly: true, + sameSite: "lax", + path: "/", + }); + } + + return response; + } + + return NextResponse.json( + { message: "Invalid Credentials" }, + { status: 401 }, + ); + } catch (error) { + return NextResponse.json( + { message: "Server Error", error }, + { status: 500 }, + ); } - - const accessToken = result.headers.get(ACCESS_TOKEN); - const refreshToken = result.headers.get(REFRESH_TOKEN); - const userId = result.headers.get(AUTH_USER_ID); - - if (accessToken && userId) { - const response = NextResponse.json({ - [ACCESS_TOKEN]: accessToken, - [AUTH_USER_ID]: userId, - }); - - - - if (refreshToken) { - cookieStore.set(REFRESH_TOKEN, refreshToken, { - httpOnly: true, - sameSite: "lax", -// domain: domain, - path: "/", - }); - } - - return response; - } - - return NextResponse.json( - { message: "Invalid Credentials" }, - { status: 401 }, - ); - } catch (error) { - return NextResponse.json( - { message: "Server Error", error }, - { status: 500 }, - ); - } } - export async function POST( - request: Request, - props: { params: Promise<{ url: string[] }> }, + request: Request, + props: { params: Promise<{ url: string[] }> }, ) { - const params = await props.params; - return handler(request, params, "POST"); + const params = await props.params; + return handler(request, params, "POST"); } export async function PUT( - request: Request, - props: { params: Promise<{ url: string[] }> }, + request: Request, + props: { params: Promise<{ url: string[] }> }, ) { - const params = await props.params; - return handler(request, params, "PUT"); + const params = await props.params; + return handler(request, params, "PUT"); } diff --git a/apps/st/eslint.config.mjs b/apps/st/eslint.config.mjs index 18107f0ca..55ef02fb5 100644 --- a/apps/st/eslint.config.mjs +++ b/apps/st/eslint.config.mjs @@ -1,6 +1,7 @@ +import { FlatCompat } from "@eslint/eslintrc"; import { dirname } from "path"; import { fileURLToPath } from "url"; -import { FlatCompat } from "@eslint/eslintrc"; +import baseEsLintConfig from "../../eslint.config.mjs"; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); @@ -11,6 +12,7 @@ const compat = new FlatCompat({ const eslintConfig = [ ...compat.extends("next/core-web-vitals", "next/typescript"), + ...baseEsLintConfig, { rules: { "react-hooks/exhaustive-deps": "off", diff --git a/apps/st/middleware.ts b/apps/st/middleware.ts index 8b1ecb501..9a2a48cb1 100644 --- a/apps/st/middleware.ts +++ b/apps/st/middleware.ts @@ -12,10 +12,10 @@ import { const serverApiUrl = process.env.NEXT_PUBLIC_SERVER_API_URL ?? "http://localhost:3000"; -const linkBackendApiHost = process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST ?? "http://localhost:8080"; - const stServiceUrl = ST_SERVICE_URL; +const linkBackendApiHost = process.env.NEXT_PUBLIC_LINK_BACKEND_API_HOST ?? "http://localhost:8080"; + // CSP 헤더 설정 함수 (img-src만) function addSecurityHeaders(response: NextResponse): NextResponse { response.headers.set("Content-Security-Policy", "img-src 'self' data: https: blob:;"); @@ -28,41 +28,46 @@ export function middleware(req: NextRequest) { const logMessages: string[] = [ `[Middleware Request] ${new Date().toISOString()}`, - `[Environment]\n Mode: ${process.env.NODE_ENV}\n Port: ${PORT}\n Proxy Host: ${PROXY_HOST}\n Server API URL: ${SERVER_API_URL}\n Site ID: ${SITE_ID}`, + `[Environment]\n Mode: ${process.env.NODE_ENV}\n Port: ${PORT}\n Proxy Host: ${PROXY_HOST}\n Server API URL: ${SERVER_API_URL}\n Site ID: ${SITE_ID}\n ST Service URL: ${stServiceUrl}`, `[Request]\n Original Pathname: ${pathname}`, ]; - if (pathname.startsWith("/st-management-service") || pathname.startsWith("/st-input-service")) { + // ST Service 처리 (dc의 /server/dc-service 패턴과 동일) + if (pathname.startsWith("/server/st-management-service") || pathname.startsWith("/server/st-input-service")) { const requestHeaders = new Headers(req.headers); const token = req.cookies.get(CLAIM_NAME)?.value; const userId = req.cookies.get(AUTH_USER_ID)?.value; - + const queryParams = searchParams.toString(); - const newUrl = `${stServiceUrl}${pathname}${ + const newUrl = `${stServiceUrl}${pathname.replace("/server", "")}${ queryParams ? `?${queryParams}` : "" }`; if (token) requestHeaders.set(CLAIM_NAME, token); if (userId) requestHeaders.set(AUTH_USER_ID, userId); - - // 디버깅을 위한 토큰 정보 로그 - logMessages.push(` Token Debug: ${token ? 'EXISTS' : 'MISSING'}`); - logMessages.push(` UserId Debug: ${userId ? 'EXISTS' : 'MISSING'}`); + + logMessages.push(` Token Debug: ${token ? "EXISTS" : "MISSING"}`); + logMessages.push(` UserId Debug: ${userId ? "EXISTS" : "MISSING"}`); logMessages.push(` ST Service Rewritten URL: ${newUrl}`); logMessages.push("\n--------------------------------\n"); console.log(logMessages.join("\n")); - + const response = NextResponse.rewrite(new URL(newUrl), { headers: requestHeaders, }); return addSecurityHeaders(response); } - if (pathname.startsWith("/server")) { + // 일반 Server API 처리 (ST 서비스 제외) + if ( + pathname.startsWith("/server") && + !pathname.startsWith("/server/st-management-service") && + !pathname.startsWith("/server/st-input-service") + ) { const requestHeaders = new Headers(req.headers); const token = req.cookies.get(CLAIM_NAME)?.value; const userId = req.cookies.get(AUTH_USER_ID)?.value; - + const queryParams = searchParams.toString(); const newUrl = `${serverApiUrl}${pathname.replace("/server", "")}${ queryParams ? `?${queryParams}` : "" @@ -138,5 +143,5 @@ export function middleware(req: NextRequest) { } export const config = { - matcher: ["/server/:path*", "/attach-service/:path*", "/api/link/:path*", "/st-management-service/:path*", "/st-input-service/:path*", "/"], + matcher: ["/server/:path*", "/attach-service/:path*", "/api/link/:path*", "/"], }; diff --git a/apps/st/package.json b/apps/st/package.json index cd951af0d..0c120b1e2 100644 --- a/apps/st/package.json +++ b/apps/st/package.json @@ -34,6 +34,7 @@ "@types/xlsx": "^0.0.36", "axios": "^1.8.1", "chart.js": "^4.4.8", + "chartjs-plugin-zoom": "^2.2.0", "dayjs": "^1.11.13", "js-cookie": "^3.0.5", "jszip": "^3.10.1", @@ -61,7 +62,8 @@ "@types/node": "^22.13.1", "@types/webpack": "^5.28.5", "eslint": "^9", - "eslint-config-next": "15.1.7", + "eslint-config-next": "15.3.8", + "eslint-plugin-react-hooks": "^5.0.0", "postcss": "^8", "prettier": "^3.4.2", "prettier-plugin-tailwindcss": "^0.6.11", diff --git a/apps/st/src/app/styles/components.css b/apps/st/src/app/styles/components.css index 5b9742c0f..e69de29bb 100644 --- a/apps/st/src/app/styles/components.css +++ b/apps/st/src/app/styles/components.css @@ -1,129 +0,0 @@ -.card { - position: relative; - margin: 0.6rem; - box-sizing: border-box; - min-height: 2rem; - border-radius: 0.5rem; - padding: 0.6rem; - font-size: 1.3rem; - color: #666; -} - -.card_width10 { - width: calc(10% - 12px); -} - -.card_width20 { - width: calc(20% - 12px); -} - -.card_width25 { - width: calc(25% - 12px); -} - -.card_width30 { - width: calc(30% - 12px); -} - -.card_width33 { - width: calc(33.333% - 12px); -} - -.card_width40 { - width: calc(40% - 12px); -} - -.card_width45 { - width: calc(45% - 12px); -} - -.card_width50 { - width: calc(50% - 12px); -} - -.card_width60 { - width: calc(60% - 12px); -} - -.card_width66 { - width: calc(66.666% - 12px); -} - -.card_width70 { - width: calc(70% - 12px); -} - -.card_width75 { - width: calc(75% - 12px); -} - -.card_width80 { - width: calc(80% - 12px); -} - -.card_width90 { - width: calc(90% - 12px); -} - -.card_width100 { - width: calc(100% - 12px); -} - -.card_nopadding { - padding: 0 !important; -} - -.card_nomargin { - width: 100%; - margin: 0 !important; - padding: 0 !important; -} - -.topline { - border-top: 1px solid #ccc; -} - -.bottomline { - border-bottom: 1px solid #e6eef3; - background: #fff; -} - -.card-border { - border: 1px solid #dbe2e6; - background-color: rgba(255, 255, 255, 0.6); - box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); -} - -.card-header { - margin-top: -0.6rem; - margin-left: -0.6rem; - margin-right: -0.6rem; - display: flex; - align-items: center; - justify-content: space-between; - border-bottom: 1px solid #e1e7eb; - padding: 1rem; -} - -.card-footer { - margin-left: -0.6rem; - margin-right: -0.6rem; - margin-top: 0.5rem; - display: flex; - align-items: center; - justify-content: center; - border-top: 1px solid #e1e7eb; - padding-top: 1rem; - padding-bottom: 1rem; -} - -/* 블랙 테마 */ -[data-theme="black"] { - .card-border { - background-color: rgba(255, 255, 255, 0.065); - border-color: #38383a; - } - .card-header { - border-bottom-color: #3f4042; - } -} diff --git a/apps/st/src/components/button/CancelSubmitButton.tsx b/apps/st/src/components/button/CancelSubmitButton.tsx new file mode 100644 index 000000000..c8b7c510f --- /dev/null +++ b/apps/st/src/components/button/CancelSubmitButton.tsx @@ -0,0 +1,16 @@ +import { Button } from "@common/components"; + +interface CancelSubmitButtonProps { + cnacelSubmitFunc: () => void; +} + +const CancelSubmitButton = ({ cnacelSubmitFunc }: CancelSubmitButtonProps) => { + return ( + + ); +}; + +export default CancelSubmitButton; \ No newline at end of file diff --git a/apps/st/src/components/css/DataGrid.css b/apps/st/src/components/css/DataGrid.css index f602400c7..68ab82f50 100644 --- a/apps/st/src/components/css/DataGrid.css +++ b/apps/st/src/components/css/DataGrid.css @@ -4,9 +4,24 @@ .rg-grid .rg-header .rg-table .rg-header-group-cell { @apply !bg-[#466995] !text-[#fff]; } - .rg-grid .rg-header .rg-table .rg-header-cell { + .rg-grid .rg-header .rg-table { @apply !bg-[#5987bf] !text-[#fff]; } + + /* 상태바·체크바 헤더 */ + .rg-grid .rg-head .rg-table tr:first-child td:first-child, + .rg-grid .rg-head .rg-table tr:first-child td:nth-child(2), + .rg-grid .rg-header .rg-table tr:first-child td:first-child, + .rg-grid .rg-header .rg-table tr:first-child td:nth-child(2) { + @apply !bg-[#5987bf] !text-[#fff]; + } + + .rg-grid .rg-header .rg-table tr td, + .rg-grid .rg-head .rg-table tr td { + border: none; + border-bottom: 1px solid #e5e7eb; + } + .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell { @apply !bg-white; } @@ -17,9 +32,30 @@ .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-verify-error { @apply !bg-[#ffe6e6] !text-[#c00]; } + .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-verify-error-imr { + @apply !bg-[#fff7bf] !text-[#b45309]; + } .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-total { @apply !bg-[#e3eaf2]; } + .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-rowtype-biz-sum { + @apply !bg-[#ffe9cf]; + } + .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell.rg-cell-rowtype-other { + @apply !bg-[#fff7bf]; + } + + /* 진행상황: 소프트 인라인 요약 (툴바와 자연스럽게 blend) */ + .data-grid-status-bubble { + @apply rounded-lg border border-slate-200/80 bg-slate-50/90 px-4 py-2.5; + box-shadow: none; + } + .data-grid-status-bubble span { + @apply text-base text-slate-700; + } + .data-grid-status-bubble span + span { + @apply ml-4 border-l border-slate-200/70 pl-4; + } [data-theme="black"] { .rg-grid .rg-header .rg-table .rg-header-group-cell { @@ -28,6 +64,12 @@ .rg-grid .rg-header .rg-table .rg-header-cell { @apply !bg-[#62686d] !text-[#fff]; } + .rg-grid .rg-head .rg-table tr:first-child td:first-child, + .rg-grid .rg-head .rg-table tr:first-child td:nth-child(2), + .rg-grid .rg-header .rg-table tr:first-child td:first-child, + .rg-grid .rg-header .rg-table tr:first-child td:nth-child(2) { + @apply !bg-[#62686d] !text-[#fff]; + } .rg-grid .rg-body .rg-table .rg-data-row .rg-data-cell { @apply !bg-[#545556] !text-[#fff]; } @@ -40,6 +82,12 @@ .rg-grid .rg-header .rg-table .rg-header-cell { @apply !bg-[#8d8d94] !text-[#fff]; } + .rg-grid .rg-head .rg-table tr:first-child td:first-child, + .rg-grid .rg-head .rg-table tr:first-child td:nth-child(2), + .rg-grid .rg-header .rg-table tr:first-child td:first-child, + .rg-grid .rg-header .rg-table tr:first-child td:nth-child(2) { + @apply !bg-[#8d8d94] !text-[#fff]; + } } [data-theme="green"] { @@ -49,5 +97,15 @@ .rg-grid .rg-header .rg-table .rg-header-cell { @apply !bg-[#6bafae] !text-[#fff]; } + .rg-grid .rg-head .rg-table tr:first-child td:first-child, + .rg-grid .rg-head .rg-table tr:first-child td:nth-child(2), + .rg-grid .rg-header .rg-table tr:first-child td:first-child, + .rg-grid .rg-header .rg-table tr:first-child td:nth-child(2) { + @apply !bg-[#6bafae] !text-[#fff]; + } } } + +.tabs-content { + margin-top: 0.6rem !important; +} \ No newline at end of file diff --git a/apps/st/src/components/module/CompactDataGrid.tsx b/apps/st/src/components/module/CompactDataGrid.tsx index 4377eb762..b1f97eb14 100644 --- a/apps/st/src/components/module/CompactDataGrid.tsx +++ b/apps/st/src/components/module/CompactDataGrid.tsx @@ -1,9 +1,9 @@ -import { useRef, useEffect } from "react" +import { useRef, useEffect, useLayoutEffect } from "react" import { ValueType } from "realgrid" import RealGrid, { GridFitStyle } from "realgrid" import { RealGridReact, RGDataColumn } from "realgrid-react" -import type { DataGridProps, RealGridColumnInfo, GridViewWithSetColumns, FooterItemWithCallback } from "../type/DataGrid.type" +import type { DataGridProps, RealGridColumnInfo, GridViewWithSetColumns, FooterItemWithCallback, CellStyleCallback } from "../type/DataGrid.type" import { getComputedValueCallback } from "@/components/util/grid/computedFieldCallbacks" // RealGrid 타입 확장 @@ -62,15 +62,37 @@ function createNumberComparer(dp: RealGridDataProviderComparer): (field: string }; } -const CompactDataGrid = ({ columnInfo, fixedColumns, showHeaderCheckbox = false, rowData, setRowData }: DataGridProps) => { +const CompactDataGrid = ({ + columnInfo, + fixedColumns, + showHeaderCheckbox = false, + rowData, + enableSort = false, + // setRowData, + getGridDataRef, + cellStyleCallback, + onRowClick, +}: DataGridProps) => { const { columns, columnLayout } = columnInfo; const gridRef = useRef(null); + const rowDataRef = useRef[]>(rowData); + const cellStyleCallbackRef = useRef(cellStyleCallback); + rowDataRef.current = rowData; + cellStyleCallbackRef.current = cellStyleCallback; + + useLayoutEffect(() => { + if (!cellStyleCallback || !gridRef.current?.gridView) return; + gridRef.current.gridView.refresh(); + }, [cellStyleCallback, rowData]); useEffect(() => { if (!gridRef.current?.gridView || !gridRef.current?.dataProvider) return; const gridView = gridRef.current.gridView; const dataProvider = gridRef.current.dataProvider; + if ((dataProvider as { setRows?: (r: unknown[]) => void })?.setRows && rowData) { + (dataProvider as { setRows: (r: unknown[]) => void }).setRows(rowData); + } // setDataComparer로 숫자 정렬 (setFields 미사용 → 데이터 유실·필드 중복 오류 없음) const dp = dataProvider as RealGridDataProviderComparer; @@ -231,11 +253,11 @@ const CompactDataGrid = ({ columnInfo, fixedColumns, showHeaderCheckbox = false, // footer가 단일 객체이고 valueCallback이 있는 경우 columns.forEach(col => { if (!col.footer || Array.isArray(col.footer)) return; - + try { const column = currentGridView.columnByName(col.name); if (!column || !column.footer) return; - + if (col.footer.valueCallback) { (column.footer as { valueCallback?: typeof col.footer.valueCallback }).valueCallback = col.footer.valueCallback; } @@ -243,9 +265,75 @@ const CompactDataGrid = ({ columnInfo, fixedColumns, showHeaderCheckbox = false, console.warn(`Error setting footer valueCallback for column ${col.name}:`, e); } }); + + // cellStyleCallback이 있으면 컬럼별 styleCallback 설정 + if (cellStyleCallbackRef.current) { + columns.forEach((column) => { + const baseStyleName = column.styleName; + const gridCol = currentGridView.columnByName(column.name) as { + styleCallback?: (g: unknown, dataCell: { itemIndex?: number; index?: { itemIndex?: number }; dataField?: string; fieldName?: string }) => string; + } | null; + if (gridCol) { + gridCol.styleCallback = (_g, dataCell) => { + const itemIndex = dataCell?.index?.itemIndex ?? dataCell?.itemIndex ?? -1; + const fieldName = (dataCell?.dataField ?? dataCell?.fieldName ?? column.fieldName) ?? ''; + const data = rowDataRef.current; + if (itemIndex < 0 || itemIndex >= data.length) return baseStyleName ?? ''; + const row = data[itemIndex] as Record; + const extra = cellStyleCallbackRef.current?.({ rowIndex: itemIndex, fieldName, row }); + if (!extra) return baseStyleName ?? ''; + return baseStyleName ? `${extra} ${baseStyleName}` : extra; + }; + } + }); + } + currentGridView.refresh?.(); }, 200); - }, [columns, columnLayout, fixedColumns, rowData, showHeaderCheckbox]); + if (getGridDataRef) { + const fieldNames = columns.map((c) => c.fieldName).filter(Boolean) as string[]; + getGridDataRef.current = () => { + const gv = gridRef.current?.gridView as { + getDataSource?: () => { getRowCount(): number; getValue(r: number, f: string): unknown }; + } | undefined; + if (!gv?.getDataSource) return []; + const ds = gv.getDataSource(); + if (!ds) return []; + const cnt = ds.getRowCount(); + const rows: Record[] = []; + for (let i = 0; i < cnt; i++) { + const r: Record = {}; + for (const f of fieldNames) r[f] = ds.getValue(i, f) as string | number; + rows.push(r); + } + return rows; + }; + } + + return () => { + if (getGridDataRef) getGridDataRef.current = null; + }; + }, [columns, columnLayout, fixedColumns, rowData, showHeaderCheckbox, getGridDataRef]); + + // 행 클릭 이벤트 + useEffect(() => { + const gridView = gridRef.current?.gridView; + if (!gridView || !onRowClick) return; + + gridView.onCellClicked = (grid, clickData) => { + if (clickData.cellType !== "data" || clickData.itemIndex === undefined) return; + try { + const row = rowDataRef.current[clickData.itemIndex]; + onRowClick((row ?? {}) as Record); + } catch (error) { + console.error("행 데이터 가져오기 오류:", error); + } + }; + + return () => { + gridView.onCellClicked = undefined; + }; + }, [onRowClick]); return (
@@ -255,11 +343,16 @@ const CompactDataGrid = ({ columnInfo, fixedColumns, showHeaderCheckbox = false, autoGenerateField={true} layout={columnLayout} rows={rowData} - onInitialized={(grid) => { - const dp = gridRef.current?.dataProvider as { setFields?: (fields: unknown[]) => void } | undefined; + onInitialized={() => { + const dp = gridRef.current?.dataProvider as + | { setFields?(f: unknown[]): void; setRows?(r: Record[]): void } + | undefined; if (dp?.setFields) { dp.setFields(buildFieldsFromColumns(columns)); } + if (dp?.setRows && rowData?.length) { + dp.setRows(rowData); + } }} > {columns.map((column) => ( @@ -283,7 +376,7 @@ const CompactDataGrid = ({ columnInfo, fixedColumns, showHeaderCheckbox = false, numberFormat: column.footer.numberFormat, } : undefined} mergeRule={column.mergeCells ? { criteria: 'value' } : undefined} - sortable={!column.sortdisable} + sortable={enableSort && !column.sortdisable} /> ))} diff --git a/apps/st/src/components/module/DataGrid.tsx b/apps/st/src/components/module/DataGrid.tsx index 7d7f925ee..d85693a53 100644 --- a/apps/st/src/components/module/DataGrid.tsx +++ b/apps/st/src/components/module/DataGrid.tsx @@ -1,23 +1,25 @@ -import { useRef, useEffect, useLayoutEffect } from "react"; -import { ValueType } from "realgrid"; +import { useEffect, useLayoutEffect, useRef } from "react"; -import RealGrid, { GridFitStyle, type DisplayOptions } from "realgrid"; -import { RealGridReact, RGDataColumn } from "realgrid-react"; -import type { - DataGridProps, - RealGridColumnInfo, - GridViewWithSetColumns, - FooterItemWithCallback, - ColumnLayoutItem, - CellStyleCallback, -} from "../type/DataGrid.type"; -import { getComputedValueCallback } from "@/components/util/grid/computedFieldCallbacks"; import JSZip from "jszip"; +import { ValueType } from "realgrid"; +import RealGrid, { type DisplayOptions, GridFitStyle } from "realgrid"; +import { RealGridReact, RGDataColumn } from "realgrid-react"; import * as XLSX from "xlsx"; import { useAlertStore } from "@/shared/lib"; - import { Button } from "@common/components"; + +import type { + CellStyleCallback, + CellTooltipCallback, + ColumnLayoutItem, + DataGridProps, + FooterItemWithCallback, + GridViewWithSetColumns, + RealGridColumnInfo, +} from "../type/DataGrid.type"; + +import { getComputedValueCallback } from "@/components/util/grid/computedFieldCallbacks"; import { useTabStore } from "@/store/tab-store"; // RealGrid 타입 확장 @@ -86,110 +88,6 @@ function toNum(v: unknown): number { return parseFloat(String(v).replace(/,/g, "")) || NaN; } -/** 헤더에 정렬 화살표 표시 (CSS 방식) */ -function updateHeaderSortIndicator( - gridView: { - columnByIndex?: ( - i: number, - ) => { fieldName?: string; name?: string } | undefined; - columnByName?: ( - name: string, - ) => { fieldName?: string; name?: string } | undefined; - getColumn?: ( - i: number, - ) => { fieldName?: string; name?: string } | undefined; - }, - columns: { fieldName?: string; name: string }[], - sortDir: Record, -) { - try { - columns.forEach((col) => { - if (!col.fieldName && !col.name) return; - - // 컬럼 찾기 - let gridCol: { fieldName?: string; name?: string } | undefined; - for (let i = 0; i < 100; i++) { - const c = - gridView.columnByIndex?.(i) ?? gridView.getColumn?.(i); - if (!c) break; - if ( - c.fieldName === (col.fieldName || col.name) || - c.name === (col.fieldName || col.name) - ) { - gridCol = c; - break; - } - } - if (!gridCol) { - gridCol = gridView.columnByName?.(col.name); - } - - if (!gridCol) return; - - const fieldName = - gridCol.fieldName || gridCol.name || col.fieldName || col.name; - const direction = sortDir[fieldName] || sortDir[col.name] || "none"; - - // DOM에서 헤더 요소 찾기 - const gridEl1 = document.querySelector( - "[data-grid-id]", - ) as HTMLElement | null; - const gridEl2 = document.querySelector( - ".rg-grid", - ) as HTMLElement | null; - const gridEl = gridEl1 || gridEl2; - if (!gridEl) return; - - // 헤더 셀 찾기 (fieldName 또는 name으로) - const headerCells = gridEl.querySelectorAll( - '.rg-header-cell, [class*="header"]', - ); - let targetCell: HTMLElement | null = null; - - headerCells.forEach((cell) => { - const el = cell as HTMLElement; - const text = el.textContent?.trim(); - const colName = col.name; - const colFieldName = col.fieldName; - if ( - text && - (text.includes(colName) || - (colFieldName && text.includes(colFieldName))) - ) { - targetCell = el; - } - }); - - if (!targetCell) return; - - const headerCell = targetCell as HTMLElement; - - // 기존 화살표 제거 - const existingIndicator = headerCell.querySelector( - ".rg-sort-indicator", - ) as HTMLElement | null; - if (existingIndicator) { - existingIndicator.remove(); - } - - // 화살표 추가 - if (direction === "asc" || direction === "desc") { - const indicator = document.createElement("span"); - indicator.className = "rg-sort-indicator"; - indicator.textContent = direction === "asc" ? "▲" : "▼"; - indicator.style.marginLeft = "4px"; - indicator.style.fontSize = "10px"; - indicator.style.color = "#666"; - indicator.style.display = "inline-block"; - indicator.style.verticalAlign = "middle"; - headerCell.appendChild(indicator); - } - }); - } catch (e) { - console.warn("updateHeaderSortIndicator error:", e); - } -} - /** onSorting: mergeCells: true인 컬럼이 있으면 그룹 내 순서 유지 정렬, 없으면 RealGrid 기본 정렬 */ function createOnSortingHandler( columns: { @@ -215,12 +113,14 @@ function createOnSortingHandler( ), ]; // mergeCells: true인 컬럼 찾기 (시군구 등) - 그룹 필드로 사용 - // 시군구를 우선으로 찾고, 없으면 첫 번째 mergeCells 컬럼 사용 + // 시군구(sggNm) 우선, 없으면 행정구역명(admdstNm), 없으면 첫 번째 mergeCells 컬럼 const mergeCellCols = columns.filter( (c) => c.mergeCells === true && c.fieldName, ); const mergeCellCol = - mergeCellCols.find((c) => c.fieldName === "gugun") || mergeCellCols[0]; + mergeCellCols.find((c) => c.fieldName === "sggNm") || + mergeCellCols.find((c) => c.fieldName === "admdstNm") || + mergeCellCols[0]; const groupField = mergeCellCol?.fieldName || null; const orderByField = "displayYear"; // 고정값 또는 설정 가능하게 할 수 있음 const hasMergeCells = mergeCellCols.length > 0; @@ -251,7 +151,8 @@ function createOnSortingHandler( const col = columns.find( (c) => c.fieldName === sortField || c.name === sortField, ); - if (!col || col.sortdisable) return true; + // sortdisable 컬럼은 정렬 불가(클릭 무시) + if (!col || col.sortdisable) return false; // mergeCells: true인 컬럼이 없으면 RealGrid 기본 정렬 사용 if (!hasMergeCells || !groupField) return true; @@ -276,6 +177,7 @@ function createOnSortingHandler( if (orig && setRows) { setRows(orig); setRowData(orig); + (g as { refresh?: () => void }).refresh?.(); } sortDirRef.current[sortField] = "none"; return false; @@ -294,11 +196,13 @@ function createOnSortingHandler( ); setRows?.(sorted); setRowData(sorted); + // 데이터 변경 후 merge 재적용 + (g as { refresh?: () => void }).refresh?.(); return false; }; } -/** sortPreserveGroupOrder: 그룹 간에는 sortField로 정렬, 그룹 내에서는 원본 순서 유지. */ +/** sortPreserveGroupOrder: 그룹 간에는 sortField로 정렬, 그룹 내에서는 원본 순서 유지(구분 포함). */ function sortRowsGroupPreserving( rows: Record[], sortField: string, @@ -415,17 +319,46 @@ const DataGrid = ({ setRowData, getGridDataRef, cellStyleCallback, + cellTooltipCallback, onRowClick, + statusInfo, + highlightedRowId, + idFieldName = "id", + enableSort = false, }: DataGridProps) => { const { columns, columnLayout } = columnInfo; const gridRef = useRef(null); const fileInputRef = useRef(null); const sortDirRef = useRef>({}); - const originalRowsRef = useRef[]>>({}); + const originalRowsRef = useRef< + Record[]> + >({}); const rowDataRef = useRef[]>(rowData); - const cellStyleCallbackRef = useRef(cellStyleCallback); + const cellStyleCallbackRef = useRef( + cellStyleCallback, + ); + const cellTooltipCallbackRef = useRef( + cellTooltipCallback, + ); rowDataRef.current = rowData; cellStyleCallbackRef.current = cellStyleCallback; + cellTooltipCallbackRef.current = cellTooltipCallback; + + // highlightedRowId가 변경될 때 해당 행으로 스크롤 및 선택 + useEffect(() => { + if (!gridRef.current?.gridView || highlightedRowId == null) return; + + const gridView = gridRef.current.gridView; + const index = rowData.findIndex( + (row) => String(row[idFieldName]) === String(highlightedRowId), + ); + + if (index !== -1) { + // 해당 행으로 포커스 이동 및 스크롤 + gridView.setCurrent({ itemIndex: index }); + gridView.setFocus(); + } + }, [highlightedRowId, rowData, idFieldName]); useLayoutEffect(() => { if (!cellStyleCallback || !gridRef.current?.gridView) return; @@ -542,6 +475,7 @@ const DataGrid = ({ target: "local", fileName: `${menuName}.xlsx`, footer: "hidden", + allColumns: true, // 숨김(visible: false) 컬럼도 엑셀에 포함 done: () => { // 헤더 원복 columns.forEach((col) => { @@ -624,10 +558,10 @@ const DataGrid = ({ ) { const cell = worksheet[ - XLSX.utils.encode_cell({ - r: rowIndex, - c: col, - }) + XLSX.utils.encode_cell({ + r: rowIndex, + c: col, + }) ]; if ( cell && @@ -703,7 +637,7 @@ const DataGrid = ({ const col = range.s.c + colIndex; const cell = worksheet[ - XLSX.utils.encode_cell({ r: row, c: col }) + XLSX.utils.encode_cell({ r: row, c: col }) ]; const headerName = headers[colIndex] || `Column${colIndex + 1}`; @@ -826,12 +760,14 @@ const DataGrid = ({ gridView as { onSorting?: (g: unknown, f: unknown[], d: unknown[]) => boolean; } - ).onSorting = createOnSortingHandler( - columns, - setRowData, - sortDirRef, - originalRowsRef, - ); + ).onSorting = enableSort + ? createOnSortingHandler( + columns, + setRowData, + sortDirRef, + originalRowsRef, + ) + : () => false; (gridView.displayOptions as DisplayOptions).fitStyle = GridFitStyle.EVEN; @@ -945,12 +881,14 @@ const DataGrid = ({ editable: col.editable, valueType: col.valueType, dataFormat: col.dataFormat, + ...(col.width != null && { width: col.width }), ...(col.styleName != null && { styleName: col.styleName, }), ...(col.mergeCells && { mergeRule: { criteria: "value" as const }, }), + sortable: !col.sortdisable, }; if (col.footer) { @@ -999,7 +937,7 @@ const DataGrid = ({ ) { ( column.footer[ - index + index ] as FooterItemWithCallback ).valueCallback = footerItem.valueCallback; @@ -1041,6 +979,8 @@ const DataGrid = ({ ); } }); + // valueCallback 적용 후 푸터 셀 다시 그리기 (API 합계 등 우선 표시 반영) + currentGridView.refresh?.(); }, 200); if (getGridDataRef) { @@ -1050,11 +990,11 @@ const DataGrid = ({ getGridDataRef.current = () => { const gv = gridRef.current?.gridView as | { - getDataSource?: () => { - getRowCount(): number; - getValue(r: number, f: string): unknown; - }; - } + getDataSource?: () => { + getRowCount(): number; + getValue(r: number, f: string): unknown; + }; + } | undefined; if (!gv?.getDataSource) return []; const ds = gv.getDataSource(); @@ -1083,38 +1023,72 @@ const DataGrid = ({ getGridDataRef, ]); - // 행 클릭 이벤트 설정 + // 행 클릭 이벤트 + 검증 오류 셀 클릭 시 showMessage (공식 문서 방식) useEffect(() => { - if (!gridRef.current?.gridView || !onRowClick) return; + const gridView = gridRef.current?.gridView; + if (!gridView || (!onRowClick && !cellTooltipCallback)) return; - const gridView = gridRef.current.gridView; - - // onCellClicked 이벤트 핸들러 설정 gridView.onCellClicked = (grid, clickData) => { - // 데이터 셀만 처리 (헤더, 푸터 등 제외) if ( - clickData.cellType === "data" && - clickData.itemIndex !== undefined - ) { - try { - // 행 전체 데이터 가져오기 - const row = rowData[clickData.itemIndex]; - - // 부모 컴포넌트로 데이터 전달 - onRowClick(row ?? {}); - } catch (error) { - console.error("행 데이터 가져오기 오류:", error); + clickData.cellType !== "data" || + clickData.itemIndex === undefined + ) + return; + try { + const row = rowDataRef.current[clickData.itemIndex]; + const cellIndex = ( + grid as { + getCurrent?: () => { + itemIndex: number; + column?: string; + fieldName?: string; + }; + } + ).getCurrent?.(); + // cellTooltipCallback 있으면 해당 셀 메시지로 showMessage (공식 문서: TooltipOptions + CellIndex) + if (cellTooltipCallbackRef.current && row && cellIndex) { + const fieldName = + cellIndex.fieldName ?? cellIndex.column ?? ""; + const msg = cellTooltipCallbackRef.current({ + row: row as Record, + fieldName, + }); + if (msg) { + const colName = + columns.find( + (c) => + c.fieldName === fieldName || + c.name === cellIndex.column, + )?.name ?? + cellIndex.column ?? + fieldName; + ( + gridView as { + showMessage?: ( + opts: { + message: string; + hideDuration?: number; + }, + idx: { itemIndex: number; column: string }, + ) => void; + } + ).showMessage?.( + { message: msg, hideDuration: 5000 }, + { itemIndex: cellIndex.itemIndex, column: colName }, + ); + } } + if (onRowClick) + onRowClick((row ?? {}) as Record); + } catch (error) { + console.error("행 데이터 가져오기 오류:", error); } }; - // cleanup: 컴포넌트 언마운트 시 이벤트 핸들러 제거 return () => { - if (gridView.onCellClicked) { - gridView.onCellClicked = undefined; - } + if (gridView.onCellClicked) gridView.onCellClicked = undefined; }; - }, [onRowClick]); + }, [onRowClick, cellTooltipCallback, columns]); return (
@@ -1126,6 +1100,44 @@ const DataGrid = ({ onChange={handleFileChange} />
+ {statusInfo && ( +
+ + 진행상황:{" "} + {statusInfo.laeSbmsnSttsCd === null || + statusInfo.laeSbmsnSttsCd === "0" + ? "미작성" + : statusInfo.laeSbmsnSttsCd === "1" + ? "작성중" + : statusInfo.laeSbmsnSttsCd === "2" + ? "제출" + : statusInfo.laeSbmsnSttsCd === "3" + ? "승인" + : statusInfo.laeSbmsnSttsCd === "4" + ? "반려" + : "검증중"} + + + 제출일:{" "} + {statusInfo.laeSbmsnYmd + ? statusInfo.laeSbmsnYmd.length === 8 && + /^\d{8}$/.test(statusInfo.laeSbmsnYmd) + ? `${statusInfo.laeSbmsnYmd.slice(0, 4)}-${statusInfo.laeSbmsnYmd.slice(4, 6)}-${statusInfo.laeSbmsnYmd.slice(6, 8)}` + : statusInfo.laeSbmsnYmd + : "미제출"} + + + 담당자:{" "} + {statusInfo.laePicNm ? statusInfo.laePicNm : "-"} + + + 연락처:{" "} + {statusInfo.laePicTelNo + ? statusInfo.laePicTelNo + : "-"} + +
+ )} {isExcelImport && ( + + + + + + ); +}; + +export default SubmitDailog; \ No newline at end of file diff --git a/apps/st/src/components/statistics/management/LogHistory.tsx b/apps/st/src/components/statistics/management/LogHistory.tsx new file mode 100644 index 000000000..2938343f8 --- /dev/null +++ b/apps/st/src/components/statistics/management/LogHistory.tsx @@ -0,0 +1,112 @@ +"use client"; + +import { useState } from 'react'; +// import useSWR from 'swr'; + +import { + Button, + // Input, + Label, + // Select, + // SelectTrigger, + // SelectContent, + // SelectItem, + // SelectValue +} + from "@common/components"; +import DataGrid from '@/components/module/DataGrid'; +import { CodeSelect } from '@/entities/code'; + +import { LogHistoryColumn } from '@/components/util/column/management/LogHistoryColumn'; +// import { LwpoCodeApi } from "@/entities/code"; + +// const getStateCdListFetcher = async () => { +// return LwpoCodeApi.getLwpoCodeList({ +// sort: 'regDt,desc', +// upCd: 'STITEM', +// page: 0, +// size: 100, +// }); +// } + +const LogHistory = () => { + // const { setMessage: alert } = useAlertStore((state) => state); + const [statsCd, setStatsCd] = useState(''); + + // const { data: lwpoCdList } = useSWR( + // "lwpo-code-list", + // getStateCdListFetcher, + // { + // revalidateOnFocus: false, + // revalidateOnReconnect: false, + // revalidateIfStale: false, + // dedupingInterval: 2000, + // shouldRetryOnError: false, + // onSuccess: (data) => { + // if (!data.content || data.content.length == 0) { + // alert(`시도 목록을 불러오는데 실패했습니다. + // 새로고침 후 다시 시도해주세요.`); + // } + // }, + // onError: () => { + // alert(`시도 목록을 불러오는데 실패했습니다. + // 새로고침 후 다시 시도해주세요.`); + // }, + // } + // ); + + return ( +
+
+
+
+
+ + {/* */} + +
+
+ + +
+
+
+
+ {}} + /> +
+ ); +}; + +export default LogHistory; \ No newline at end of file diff --git a/apps/st/src/components/statistics/review/PumpingStationRvw.tsx b/apps/st/src/components/statistics/review/PumpingStationRvw.tsx index 8a9df541a..fc5d8c2c6 100644 --- a/apps/st/src/components/statistics/review/PumpingStationRvw.tsx +++ b/apps/st/src/components/statistics/review/PumpingStationRvw.tsx @@ -1,26 +1,92 @@ -import { useState } from "react"; - -import { DataGrid } from "@rsone/components"; +import { useState, useMemo } from "react"; +import DataGrid from "@/components/module/DataGrid"; import SearchForm from "@/components/module/SearchForm"; import SaveButton from "@/components/button/SaveButton"; import ApproveButton from "@/components/button/ApproveButton"; import ReviewOpinionButton from "@/components/button/ReviewOpinionButton"; import ReturnButton from "@/components/button/ReturnButton"; +import { LoadingWithAnimation } from "@common/components"; +import { useAlertStore } from "@/shared/lib"; import { PumpingStationInfoList } from "@/components/util/column/review/PumpingStationRvwColumn"; +import { statisticsManagementApi } from "@/entities/statistics/api/statistics-management-service"; +import type { SearchFormValues } from "@/components/type/SearchForm.type"; +import { toGridRows } from "@/components/util/grid/gridFunction"; +import type { MediationPumpStationItem } from "@/entities/statistics/model/statistics-pumping-station-review-interface"; -// 하수도 통계 관리 05.펌프장 +/** + * 하수도 통계 검토 05.중계펌프장 + */ const PumpingStationRvw = () => { + const { setMessage: alert } = useAlertStore((state) => state); const [rowData, setRowData] = useState[]>([]); + const [isLoading, setIsLoading] = useState(false); - const approveFunc = () => { console.log('approveFunc'); }; - const saveFunc = () => { console.log('submit'); }; - const reviewOpinionFunc = () => { console.log('reviewOpinionFunc'); }; - const returnFunc = () => { console.log('returnFunc'); }; + const columnInfo = useMemo(() => { + const { columns, columnLayout, fixedColumns, rowStartNum } = PumpingStationInfoList; + return { + columnLayout, + fixedColumns, + rowStartNum, + columns: columns.map((col) => ({ + ...col, + editable: false as const, + styleName: col.styleName ?? ("rg-cell-readonly" as const), + })), + }; + }, []); + + const handleReset = () => { + setRowData([]); + }; + + const handleSearch = async (values: SearchFormValues) => { + if (!values.sido || values.sido === 'ALL') { + alert('시도를 선택해주세요.'); + return; + } + + try { + setIsLoading(true); + + const response = await statisticsManagementApi.getMediationPumpStationList({ + ctpvNm: values.sido, + sggNm: values.gugun === 'ALL' ? '' : values.gugun, + sewerBzmnCd: values.bsnmCd, + statsYr: values.year, + pumpstNm: values.fctName, + }); + + if (response.status === 'success' && response.data) { + const rawList = response.data as MediationPumpStationItem[]; + + const convertedData = rawList.map(item => ({ + ...item, + rmrk: item.rmrk || '' + })); + + setRowData(toGridRows(convertedData)); + } else { + setRowData([]); + alert(response.message || "데이터가 없습니다."); + } + } catch (error) { + console.error("중계펌프장 조회 중 에러 발생:", error); + alert('데이터 조회 중 오류가 발생했습니다.'); + } finally { + setIsLoading(false); + } + }; + + const approveFunc = () => console.log('approveFunc'); + const saveFunc = () => console.log('submit'); + const reviewOpinionFunc = () => console.log('reviewOpinionFunc'); + const returnFunc = () => console.log('returnFunc'); return ( - <> - +
+ +
@@ -29,8 +95,24 @@ const PumpingStationRvw = () => {
- - + + {isLoading && ( +
+
+ +
+
+ )} + + +
); }; diff --git a/apps/st/src/components/statistics/review/SewagePipeMaintainRvw.tsx b/apps/st/src/components/statistics/review/SewagePipeMaintainRvw.tsx index 03549083e..26629d3a5 100644 --- a/apps/st/src/components/statistics/review/SewagePipeMaintainRvw.tsx +++ b/apps/st/src/components/statistics/review/SewagePipeMaintainRvw.tsx @@ -1,51 +1,161 @@ -import { useState } from "react"; - -import { TabDataGrid } from "@rsone/components"; +import { useState, useMemo, useRef } from "react"; +import TabDataGrid from "@/components/module/TabDataGrid"; import SearchForm from "@/components/module/SearchForm"; import SaveButton from "@/components/button/SaveButton"; import ApproveButton from "@/components/button/ApproveButton"; import ReviewOpinionButton from "@/components/button/ReviewOpinionButton"; import ReturnButton from "@/components/button/ReturnButton"; +import { LoadingWithAnimation } from "@common/components"; +import { useAlertStore } from "@/shared/lib"; +import { statisticsManagementApi } from "@/entities/statistics/api/statistics-management-service"; import { SewagePipeMaintainColumnInfoList } from "@/components/util/column/review/SewagePipeMaintainRvwColumn"; +import type { ColumnInfoList, ColumnConfig } from "@/components/type/DataGrid.type"; +import type { SearchFormValues } from "@/components/type/SearchForm.type"; +import { toGridRows } from "@/components/util/grid/gridFunction"; +import type { SewerPipeMtcRequestParams } from "@/entities/statistics/model/statistics-sewage-pipe-mtc-review-interface"; -// 하수도 통계 관리 03. 하수관로 유지 관리 + +// 하수도 통계 검토 03. 하수관로 유지 관리 const SewagePipeMaintainRvw = () => { + const { setMessage: alert } = useAlertStore((state) => state); const [rowDataMap, setRowDataMap] = useState[]>>(new Map()); + const [isLoading, setIsLoading] = useState(false); + const [activeTab, setActiveTab] = useState('ST00030001'); - const approveFunc = () => { - console.log('approveFunc'); - // 승인 로직 + const searchParamRef = useRef(null); + + const columnInfo = useMemo(() => { + return SewagePipeMaintainColumnInfoList.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 = () => { + setRowDataMap(new Map()); + setActiveTab('ST00030001'); + searchParamRef.current = null; }; - const saveFunc = () => { - console.log('submit'); - // 저장 로직 + const handleSearch = async (values: SearchFormValues) => { + if (!values.sido || values.sido === 'ALL') { + alert('시도를 선택해주세요.'); + return; + } + + setActiveTab('ST00030001'); + setRowDataMap(new Map()); + + try { + setIsLoading(true); + + const searchParam: SewerPipeMtcRequestParams = { + statsYr: values.year, + sewerBzmnCd: values.bsnmCd, + ctpvNm: values.sido, + sggNm: values.gugun === 'ALL' ? '' : values.gugun + }; + + searchParamRef.current = searchParam; + const response = await statisticsManagementApi.getSewerPipeMtcList(searchParam); + + if (response?.status === 'success' && response.data) { + const newRowDataMap = new Map[]>(); + + const listData = Array.isArray(response.data) + ? response.data + : (response.data.mtcStatusList || []); + + newRowDataMap.set('ST00030001', toGridRows(listData as object[])); + setRowDataMap(newRowDataMap); + } else { + alert(response?.message || "데이터가 없습니다."); + } + } catch { + alert('데이터 조회 중 오류가 발생했습니다.'); + } finally { + setIsLoading(false); + } }; - const reviewOpinionFunc = () => { - console.log('reviewOpinionFunc'); - // 검토의견 작성 - }; + const handleActiveTabChange = async (tabKey: string) => { + setActiveTab(tabKey); - const returnFunc = () => { - console.log('returnFunc'); - // 반려 + const existingAData = rowDataMap.get('ST00030001'); + const activeTabData = rowDataMap.get(tabKey); + + const hasAData = Array.isArray(existingAData) && existingAData.length > 0; + const hasActiveTabData = Array.isArray(activeTabData) && activeTabData.length > 0; + + if (hasAData && !hasActiveTabData && searchParamRef.current) { + try { + setIsLoading(true); + + let response; + + if (tabKey === 'ST00030001') { + response = await statisticsManagementApi.getSewerPipeMtcList(searchParamRef.current); + } else if (tabKey === 'ST00030002') { + response = await statisticsManagementApi.getSewerPipeDrdgList(searchParamRef.current); + } + + if (response?.status === 'success' && response.data) { + setRowDataMap(prev => { + const next = new Map(prev); + + const listData = Array.isArray(response.data) + ? response.data + : (response.data.mtcStatusList || []); + + next.set(tabKey, toGridRows(listData as object[])); + return next; + }); + } else { + alert(response?.message || "데이터가 없습니다."); + } + } catch { + alert('데이터 조회 중 오류가 발생했습니다.'); + } finally { + setIsLoading(false); + } + } }; return ( - <> - +
+ +
- - - - + { }} /> + { }} /> + { }} /> + { }} />
- - + + {isLoading && ( +
+
+ +
+
+ )} + + +
); }; diff --git a/apps/st/src/components/statistics/review/SewagePipeRvw.tsx b/apps/st/src/components/statistics/review/SewagePipeRvw.tsx index 34fe00910..77d3a5d88 100644 --- a/apps/st/src/components/statistics/review/SewagePipeRvw.tsx +++ b/apps/st/src/components/statistics/review/SewagePipeRvw.tsx @@ -13,15 +13,17 @@ import { SewagePipeColumnInfoListRvw } from "@/components/util/column/review/Sew import type { ColumnInfoList, ColumnConfig } from "@/components/type/DataGrid.type"; import type { SearchFormValues } from "@/components/type/SearchForm.type"; import { toGridRows } from "@/components/util/grid/gridFunction"; +import type { SewagePipeReviewRequestParams } from "@/entities/statistics/model/statistics-sewage-pipe-review-interface"; + // 하수도 통계 검토 02.하수관로 const SewagePipeRvw = () => { const { setMessage: alert } = useAlertStore((state) => state); const [rowDataMap, setRowDataMap] = useState[]>>(new Map()); const [isLoading, setIsLoading] = useState(false); - const [activeTab, setActiveTab] = useState('a'); + const [activeTab, setActiveTab] = useState('ST00020001'); - const searchParamRef = useRef(null); + const searchParamRef = useRef(null); const columnInfo = useMemo(() => { return SewagePipeColumnInfoListRvw.map((tab: ColumnInfoList) => ({ @@ -36,7 +38,7 @@ const SewagePipeRvw = () => { const handleReset = () => { setRowDataMap(new Map()); - setActiveTab('a'); + setActiveTab('ST00020001'); }; const handleSearch = async (values: SearchFormValues) => { @@ -45,18 +47,18 @@ const SewagePipeRvw = () => { return; } - setActiveTab('a'); + setActiveTab('ST00020001'); setRowDataMap(new Map()); try { setIsLoading(true); - const searchParam = { - sido: values.sido, - gugun: values.gugun === 'ALL' ? '' : values.gugun, - bsnmCd: values.bsnmCd, - yr: values.year, + const searchParam: SewagePipeReviewRequestParams = { + statsYr: values.year, + sewerBzmnCd: values.bsnmCd, + ctpvNm: values.sido, + sggNm: values.gugun === 'ALL' ? '' : values.gugun }; searchParamRef.current = searchParam; @@ -64,12 +66,12 @@ const SewagePipeRvw = () => { if (response?.status === 'success' && response.data) { const newRowDataMap = new Map[]>(); - newRowDataMap.set('a', toGridRows(response.data as object[])); + newRowDataMap.set('ST00020001', toGridRows(response.data as object[])); setRowDataMap(newRowDataMap); } else { alert(response?.message || "데이터가 없습니다."); } - } catch (error) { + } catch { alert('데이터 조회 중 오류가 발생했습니다.'); } finally { setIsLoading(false); @@ -79,7 +81,7 @@ const SewagePipeRvw = () => { const handleActiveTabChange = async (tabKey: string) => { setActiveTab(tabKey); - const existingAData = rowDataMap.get('a'); + const existingAData = rowDataMap.get('ST00020001'); const activeTabData = rowDataMap.get(tabKey); const hasAData = Array.isArray(existingAData) && existingAData.length > 0; @@ -92,11 +94,16 @@ const SewagePipeRvw = () => { let response; - if (tabKey === 'b') { + if (tabKey === 'ST00020002') { response = await statisticsManagementApi.getSewagePipeFacilityList(searchParamRef.current); + }else if(tabKey === 'ST00020003'){ + response = await statisticsManagementApi.getSewagePipeTypeList(searchParamRef.current); + }else if(tabKey === 'ST00020004'){ + response = await statisticsManagementApi.getSewagePipeDiamList(searchParamRef.current); } if (response?.status === 'success' && response.data) { + setRowDataMap(prev => { const next = new Map(prev); next.set(tabKey, toGridRows(response.data as object[])); diff --git a/apps/st/src/components/statistics/review/SewageReservoirPumpRvw.tsx b/apps/st/src/components/statistics/review/SewageReservoirPumpRvw.tsx index a2b5e8de7..4a250d2aa 100644 --- a/apps/st/src/components/statistics/review/SewageReservoirPumpRvw.tsx +++ b/apps/st/src/components/statistics/review/SewageReservoirPumpRvw.tsx @@ -1,52 +1,156 @@ -import { useState } from "react"; - -import { TabDataGrid } from "@rsone/components"; +import { useState, useMemo, useRef } from "react"; +import TabDataGrid from "@/components/module/TabDataGrid"; import SearchForm from "@/components/module/SearchForm"; import SaveButton from "@/components/button/SaveButton"; import ApproveButton from "@/components/button/ApproveButton"; import ReviewOpinionButton from "@/components/button/ReviewOpinionButton"; import ReturnButton from "@/components/button/ReturnButton"; +import { LoadingWithAnimation } from "@common/components"; +import { useAlertStore } from "@/shared/lib"; +import { statisticsManagementApi } from "@/entities/statistics/api/statistics-management-service"; import { SewageReservoirPumpInfoListRvw } from "@/components/util/column/review/SewageReservoirPumpRvwColumn"; +import type { ColumnInfoList, ColumnConfig } from "@/components/type/DataGrid.type"; +import type { SearchFormValues } from "@/components/type/SearchForm.type"; +import { toGridRows } from "@/components/util/grid/gridFunction"; +import type { SewerReservoirRequestParams } from "@/entities/statistics/model/sewage-reservoir-pump-review-interface"; -// 하수도 통계 관리 04. 하수저류 시설 및 빗물 펌프장 +/** + * 하수도 통계 검토 04. 하수저류 시설 및 빗물 펌프장 + * Tab A: 하수저류시설 (ST00040001) + * Tab B: 빗물펌프장 (ST00040002) + */ const SewageReservoirPumpRvw = () => { + const { setMessage: alert } = useAlertStore((state) => state); const [rowDataMap, setRowDataMap] = useState[]>>(new Map()); + const [isLoading, setIsLoading] = useState(false); + const [activeTab, setActiveTab] = useState('ST00040001'); - const approveFunc = () => { - console.log('approveFunc'); - // 승인 로직 + const searchParamRef = useRef(null); + + const columnInfo = useMemo(() => { + return SewageReservoirPumpInfoListRvw.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 = () => { + setRowDataMap(new Map()); + setActiveTab('ST00040001'); + searchParamRef.current = null; }; - const saveFunc = () => { - console.log('submit'); - // 저장 로직 + const handleSearch = async (values: SearchFormValues) => { + if (!values.sido || values.sido === 'ALL') { + alert('시도를 선택해주세요.'); + return; + } + + setActiveTab('ST00040001'); + setRowDataMap(new Map()); + + try { + setIsLoading(true); + + const searchParam: SewerReservoirRequestParams = { + statsYr: values.year, + sewerBzmnCd: values.bsnmCd, + ctpvNm: values.sido, + sggNm: values.gugun === 'ALL' ? '' : values.gugun, + }; + + searchParamRef.current = searchParam; + + const response = await statisticsManagementApi.getSewerReservoirList(searchParam); + + if (response?.status === 'success' && response.data) { + const newRowDataMap = new Map[]>(); + newRowDataMap.set('ST00040001', toGridRows(response.data as object[])); + setRowDataMap(newRowDataMap); + } else { + alert(response?.message || "데이터가 없습니다."); + } + } catch { + alert('데이터 조회 중 오류가 발생했습니다.'); + } finally { + setIsLoading(false); + } }; - const reviewOpinionFunc = () => { - console.log('reviewOpinionFunc'); - // 검토의견 작성 - }; + const handleActiveTabChange = async (tabKey: string) => { + setActiveTab(tabKey); - const returnFunc = () => { - console.log('returnFunc'); - // 반려 + const existingAData = rowDataMap.get('ST00040001'); + const activeTabData = rowDataMap.get(tabKey); + + const hasAData = Array.isArray(existingAData) && existingAData.length > 0; + const hasActiveTabData = Array.isArray(activeTabData) && activeTabData.length > 0; + + if (hasAData && !hasActiveTabData && searchParamRef.current) { + try { + setIsLoading(true); + + let response; + + if (tabKey === 'ST00040001') { + response = await statisticsManagementApi.getSewerReservoirList(searchParamRef.current); + } else if (tabKey === 'ST00040002') { + response = await statisticsManagementApi.getPumpStationList(searchParamRef.current); + } + + if (response?.status === 'success' && response.data) { + setRowDataMap(prev => { + const next = new Map(prev); + next.set(tabKey, toGridRows(response.data as object[])); + return next; + }); + } else if (response) { + alert(response?.message || "데이터가 없습니다."); + } + } catch { + alert('데이터 조회 중 오류가 발생했습니다.'); + } finally { + setIsLoading(false); + } + } }; return ( - <> - +
+ +
- - - - + { }} /> + { }} /> + { }} /> + { }} />
- - + + {isLoading && ( +
+
+ +
+
+ )} + + +
); }; -export default SewageReservoirPumpRvw; +export default SewageReservoirPumpRvw; \ No newline at end of file diff --git a/apps/st/src/components/statistics/review/SeweragePenetrationRateRvw.tsx b/apps/st/src/components/statistics/review/SeweragePenetrationRateRvw.tsx index 8ad001c4c..b404015a4 100644 --- a/apps/st/src/components/statistics/review/SeweragePenetrationRateRvw.tsx +++ b/apps/st/src/components/statistics/review/SeweragePenetrationRateRvw.tsx @@ -1,11 +1,9 @@ import { useState, useMemo } from "react"; import DataGrid from "@/components/module/DataGrid"; import SearchForm from "@/components/module/SearchForm"; -import SaveButton from "@/components/button/SaveButton"; -import ApproveButton from "@/components/button/ApproveButton"; import ReviewOpinionButton from "@/components/button/ReviewOpinionButton"; import ReturnButton from "@/components/button/ReturnButton"; -import { LoadingWithAnimation } from "@common/components"; +import { LoadingWithAnimation } from "@common/components"; import { useAlertStore } from "@/shared/lib"; import { SeweragePenetrationRateInfoList } from "@/components/util/column/review/SeweragePenetrationRateRvwColumn"; @@ -17,8 +15,8 @@ import { toGridRows } from "@/components/util/grid/gridFunction"; // 하수도 통계 검토 01.하수도 보급률 const SeweragePenetrationRateRvw = () => { const { setMessage: alert } = useAlertStore((state) => state); - const [rowData, setRowData] = useState([]); - const [isLoading, setIsLoading] = useState(false); + const [rowData, setRowData] = useState[]>([]); + const [isLoading, setIsLoading] = useState(false); const columnInfo = useMemo(() => { const { columns, columnLayout, fixedColumns, rowStartNum } = SeweragePenetrationRateInfoList; @@ -39,6 +37,7 @@ const SeweragePenetrationRateRvw = () => { }; const handleSearch = async (values: SearchFormValues) => { + if (values.sido === '' || values.sido === 'ALL') { alert('시도를 선택해주세요.'); return; @@ -48,17 +47,18 @@ const SeweragePenetrationRateRvw = () => { setIsLoading(true); const response = await statisticsManagementApi.getSewerageSupplyRateReviewList({ - sido: values.sido, - gugun: values.gugun === 'ALL' ? '' : values.gugun, - bsnmCd: values.bsnmCd, - yr: values.year, + ctpvNm: values.sido, + sggNm: values.gugun === 'ALL' ? '' : values.gugun, + sewerBzmnCd: values.bsnmCd, + statsYr: values.year, }); if (response.status === 'success' && response.data) { const rawList = response.data.sewerageSupplyRateList; const convertedData: SewerageSupplyRateReviewItem[] = rawList.map((item) => ({ ...item, - speclCntrplnAr: !item.speclCntrplnAr ? '해당없음' : item.speclCntrplnAr, + + spcCtpnRgnCn: !item.spcCtpnRgnCn ? '해당없음' : item.spcCtpnRgnCn, })); setRowData(toGridRows(convertedData)); @@ -70,7 +70,7 @@ const SeweragePenetrationRateRvw = () => { console.error("조회 중 에러 발생:", error); alert('데이터 조회 중 오류가 발생했습니다.'); } finally { - setIsLoading(false); + setIsLoading(false); } }; @@ -80,15 +80,13 @@ const SeweragePenetrationRateRvw = () => { const returnFunc = () => console.log('returnFunc'); return ( -
+
- +
- -
diff --git a/apps/st/src/components/statistics/review/StatsInputStatusRvw.tsx b/apps/st/src/components/statistics/review/StatsInputStatusRvw.tsx index 2c11f7abc..8fdd74d4f 100644 --- a/apps/st/src/components/statistics/review/StatsInputStatusRvw.tsx +++ b/apps/st/src/components/statistics/review/StatsInputStatusRvw.tsx @@ -11,12 +11,13 @@ import { useAlertStore } from "@/shared/lib"; import { StatsInputStatusInfoList } from "@/components/util/column/review/StatsInputStatusRvwColumn"; import { statisticsManagementApi } from "@/entities/statistics/api/statistics-management-service"; import type { StatsInputStatusReviewItem } from "@/entities/statistics/model/statistics-input-review-interface"; -import { toGridRows } from "@/components/util/grid/gridFunction"; +import { toGridRows } from "@/components/util/grid/gridFunction"; +import type { SearchFormValues } from "@/components/type/SearchForm.type"; // 하수도 통계 검토 00. 통계 입력 현황 const StatsInputStatusRvw = () => { const { setMessage: alert } = useAlertStore((state) => state); - const [rowData, setRowData] = useState([]); + const [rowData, setRowData] = useState[]>([]); const [isLoading, setIsLoading] = useState(false); const columnInfo = useMemo(() => { @@ -34,7 +35,7 @@ const StatsInputStatusRvw = () => { setRowData([]); }; - const handleSearch = async (values: any) => { + const handleSearch = async (values: SearchFormValues) => { if (!values.sido || values.sido === 'ALL') { alert('시도를 선택해주세요.'); return; @@ -46,14 +47,13 @@ const StatsInputStatusRvw = () => { const response = await statisticsManagementApi.getStatsInputStatusList({ sido: values.sido, gugun: values.gugun === 'ALL' ? '' : values.gugun, - yr: values.year || values.yr, + yr: values.year, bsnmCd: values.bsnmCd }); if (response.status === 'success' && response.data) { - const rawList = response.data.sewerageSupplyRateList || response.data; - - const convertedData: StatsInputStatusReviewItem[] = rawList.map((item: any) => ({ + const rawList = response.data.sewerageSupplyRateList ?? []; + const convertedData: StatsInputStatusReviewItem[] = rawList.map((item: StatsInputStatusReviewItem) => ({ ...item, status: item.status || '미확인', })); diff --git a/apps/st/src/components/statistics/total/SeweragePenetrationRateTot.tsx b/apps/st/src/components/statistics/total/SeweragePenetrationRateTot.tsx index fe266e743..597cb8b6c 100644 --- a/apps/st/src/components/statistics/total/SeweragePenetrationRateTot.tsx +++ b/apps/st/src/components/statistics/total/SeweragePenetrationRateTot.tsx @@ -1,140 +1,69 @@ -import SearchForm from "@/components/module/SearchForm"; -import DataGrid from "@/components/module/DataGrid"; -import SubmitButton from "@/components/button/SumitButton"; -import SaveButton from "@/components/button/SaveButton"; -import LastYearDataButton from "@/components/button/LastYearDataButton"; -import SubmitExceptionButton from "@/components/button/SubmitExceptionButton"; import { useState } from "react"; +import type { SearchFormValues } from "@/components/type/SearchForm.type"; +import { SeweragePentrationRateTotColumn } from "@/components/util/column/total/SeweragePentrationRateTotColumn"; +import { statisticsTotalStatusApi } from "@/entities/statistics/api/statistics-total-service"; +import { toGridRows } from "@/components/util/grid/gridFunction"; +import { useAlertStore } from "@/shared/lib"; + +import SearchForm from "@/components/module/SearchForm"; +import DataGrid from "@/components/module/DataGrid"; +import { LoadingWithAnimation } from "@common/components"; + const SeweragePenetrationRateTot = () => { - const columns = [ - { name: 'sido', fieldName: '시도', header: { text: '시도' } }, - { name: 'sgg', fieldName: '시군구', header: { text: '시군구' } }, - { name: 'rvbsn', fieldName: '수계', header: { text: '수계' } }, - { name: 'bstrm', fieldName: '지류', header: { text: '지류' } }, - { name: 'mdbsn', fieldName: '세부단위유역', header: { text: '세부단위유역' } }, - { name: 'lgbsn', fieldName: '중권역', header: { text: '중권역' } }, - { name: 'mdmbsn', fieldName: '소권역', header: { text: '소권역' } }, - { name: 'specl_cntrpln_ar', fieldName: '특별대책지역', header: { text: '특별대책지역' } }, - { name: 'total_popl', fieldName: '총인구', header: { text: '총인구' } }, - { name: 'popl_sm', fieldName: '내국인', header: { text: '내국인' } }, - { name: 'frgnr_popl_sm', fieldName: '외국인', header: { text: '외국인' } }, - { name: 'area', fieldName: '행정참고자료면적(㎢)', header: { text: '행정참고자료면적(㎢)' } }, - { name: 'popltn_sm', fieldName: '총인구(명)', header: { text: '총인구(명)' } }, - { name: 'ar_sm', fieldName: '총면적(㎢)', header: { text: '총면적(㎢)' } }, - { name: 'swge_proc_zone_inner_sm', fieldName: '합계', header: { text: '합계' } }, - { name: 'pblswrg_popltn_sm', fieldName: '소계', header: { text: '소계' } }, - { name: 'pblswrg_prm_trt', fieldName: '물리적처리', header: { text: '물리적처리' } }, - { name: 'pblswrg_scd_trt', fieldName: '생물학적처리', header: { text: '생물학적처리' } }, - { name: 'pblswrg_tert_trt', fieldName: '고도처리', header: { text: '고도처리' } }, - { name: 'wstr_popltn_sm', fieldName: '소계', header: { text: '소계' } }, - { name: 'wstr_prm_trt', fieldName: '물리적처리', header: { text: '물리적처리' } }, - { name: 'wstr_scd_trt', fieldName: '생물학적처리', header: { text: '생물학적처리' } }, - { name: 'wstr_tert_trt', fieldName: '고도처리', header: { text: '고도처리' } }, - { name: 'not_conect_popltn', fieldName: '미접속인구', header: { text: '미접속인구' } }, - { name: 'swge_proc_zone_inner_ar', fieldName: '면적(㎢)', header: { text: '면적(㎢)' } }, - { name: 'swge_proc_zone_outer_sm', fieldName: '합계', header: { text: '합계' } }, - { name: 'town_unproc_popltn', fieldName: '미처리인구', header: { text: '미처리인구' } }, - { name: 'town_swtt_popltn', fieldName: '오수처리인구', header: { text: '오수처리인구' } }, - { name: 'town_wrrtn_popltn', fieldName: '정화조인구', header: { text: '정화조인구' } }, - { name: 'swge_proc_zone_outer_ar', fieldName: '면적(㎢)', header: { text: '면적(㎢)' } }, - { name: 'pblswrg_popltn_suprt', fieldName: '공공하수처리구역인구보급율(%)', header: { text: '공공하수처리구역인구보급율(%)' } }, - { name: 'adtrt_popltn_suprt', fieldName: '고도처리인구보급율(%)', header: { text: `고도처리인구보급율(%)` } }, - { name: 'swrg_instlrt', fieldName: '하수도설치율(%)', header: { text: '하수도설치율(%)' } }, - { name: 'rmk', fieldName: '비고', header: { text: '비고' } }, - ]; - - const columnLayout = [ - { - name: 'groupA', - hideChildHeaders: false, - header: { text: '행정구역' }, - items: ['sido', 'sgg'], - }, - 'rvbsn', - 'bstrm', - { - name: 'groupB', - hideChildHeaders: false, - header: { text: '수계영향권별분류류' }, - items: ['mdbsn', 'lgbsn', 'mdmbsn'], - }, - 'specl_cntrpln_ar', - { - name: 'groupC', - hideChildHeaders: false, - header: { text: '행정참고자료인구' }, - items: ['total_popl', 'popl_sm', 'frgnr_popl_sm'], - }, - 'area', - 'popltn_sm', - 'ar_sm', - { - name: 'groupD', - hideChildHeaders: false, - header: { text: '하수처리구역내' }, - items: [ - 'swge_proc_zone_inner_sm', - { - name: 'pblswrgGroup', - hideChildHeaders: false, - header: { text: '공공하수처리인구(명)' }, - items: ['pblswrg_popltn_sm', 'pblswrg_prm_trt', 'pblswrg_scd_trt', 'pblswrg_tert_trt'], - }, - { - name: 'wstrGroup', - hideChildHeaders: false, - header: { text: '폐수처리인구(명)' }, - items: ['wstr_popltn_sm', 'wstr_prm_trt', 'wstr_scd_trt', 'wstr_tert_trt'], - }, - 'not_conect_popltn', - 'swge_proc_zone_inner_ar' - ], - }, - { - name: 'groupE', - hideChildHeaders: false, - header: { text: '하수처리구역외' }, - items: ['swge_proc_zone_outer_sm', 'town_swtt_popltn', 'town_unproc_popltn', 'town_wrrtn_popltn', 'swge_proc_zone_outer_ar'], - }, - 'pblswrg_popltn_suprt', - 'adtrt_popltn_suprt', - 'swrg_instlrt', - 'rmk', - ]; - - const submitFunc = () => { - console.log('submit'); - // 제출 로직 - }; - - const saveFunc = () => { - console.log('submit'); - // 저장 로직 - }; - - const getLastYearDataFunc = () => { - console.log('get last year data'); - // 지난연도 데이터 가져오기 로직 - }; - - const SubmitExceptionFunc = () => { - console.log('submit exception'); - // 예외 제출 로직 - }; - const [rowData, setRowData] = useState[]>([]); + const [isLoading, setIsLoading] = useState(false); + const { setMessage: alert } = useAlertStore((state) => state); + + const handleSearch = async (values: SearchFormValues) => { + try { + setIsLoading(true); + + const param = { + ctpvNm: values.sido === 'ALL' ? '' : values.sido, + sggNm: values.gugun === 'ALL' ? '' : values.gugun, + sewerBzmnCd: values.bsnmCd, + statsYr: values.year, + rowDataYn: values.isDetail + }; + + const response = await statisticsTotalStatusApi.getSewerageSupplyRateList(param); + + if (response.status === 'success') { + setRowData(toGridRows(response.data)); + + } else { + alert(response.message || '데이터 조회 중 오류가 발생했습니다.'); + } + } catch { + alert('데이터 조회 중 오류가 발생했습니다.'); + } finally { + setIsLoading(false); + } + }; return ( <> - -
- - - - -
- + + {isLoading &&
+
+ +
+
} + { + 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'; + }} + /> ); }; diff --git a/apps/st/src/components/statistics/verification/GeneralVerificationManagement.tsx b/apps/st/src/components/statistics/verification/GeneralVerificationManagement.tsx new file mode 100644 index 000000000..474b2993b --- /dev/null +++ b/apps/st/src/components/statistics/verification/GeneralVerificationManagement.tsx @@ -0,0 +1,241 @@ +"use client"; + +import { useEffect, useMemo, useState } from "react"; + +import { getCoreRowModel, useReactTable } from "@tanstack/react-table"; + +import { useAlertStore } from "@/shared/lib"; +import { NoData } from "@/shared/ui/no-data"; +import { CodeSelectWithAll } from "@/entities/code"; +import { generalverificationApiService } from "@/entities/statistics/api/general-verification-service"; +import type { GeneralverificationList } from "@/entities/statistics/model/general-verification-interface"; +import { + Button, + DataTable, + Label, + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@common/components"; +import { LoadingWithAnimation } from "@common/components"; + +import DetailComponent from "./generalVerification/DetailComponent"; +import RegistDialog from "./generalVerification/RegistDialog"; + +import { getGeneralVerificationColumns } from "@/components/util/column/management/GeneralVerificationColumn"; + +const GeneralVerificationManagement = () => { + const [searchValues, setSearchValues] = useState<{ + statsCd: string; + useYn: string; + vrfcClsfCd: string; + }>({ + statsCd: "", + useYn: "", + vrfcClsfCd: "", + }); + const [vrfcMasterData, setVrfcMasterData] = useState< + GeneralverificationList[] + >([]); + const [rowSelection, setRowSelection] = useState>( + {}, + ); + const [isLoading, setIsLoading] = useState(false); + const [selectedVrfcRow, setSelectedVrfcRow] = useState(null); + const [showRegistForm, setShowRegistForm] = useState(false); + + const { setMessage: alert } = useAlertStore((state) => state); + + const handleSearch = async () => { + try { + setIsLoading(true); + + const params = Object.fromEntries( + Object.entries({ + trgtStatsCd: searchValues.statsCd, + vrfcClsfCd: searchValues.vrfcClsfCd, + useYn: searchValues.useYn, + }).filter(([, value]) => value !== "" && value !== "ALL"), + ); + + const response = + await generalverificationApiService.getGeneralverificationList( + params, + ); + + if (response.status === "success") { + setVrfcMasterData(response.data); + setRowSelection({}); + setSelectedVrfcRow(null); + setShowRegistForm(false); + } else { + alert( + response.message || "데이터 조회 중 오류가 발생했습니다.", + ); + } + } catch { + alert("데이터 조회 중 오류가 발생했습니다."); + } finally { + setIsLoading(false); + } + }; + + const columns = useMemo( + () => getGeneralVerificationColumns(handleSearch), + [searchValues.statsCd, searchValues.vrfcClsfCd, searchValues.useYn], + ); + + const table = useReactTable({ + data: vrfcMasterData, + columns, + getCoreRowModel: getCoreRowModel(), + getRowId: (row) => String(row.vrfcSn), + state: { rowSelection }, + onRowSelectionChange: setRowSelection, + }); + + const handleVrfcMasterRowClick = async (row: GeneralverificationList) => { + setRowSelection({ [row.vrfcSn]: true }); + setSelectedVrfcRow(row.vrfcSn); + setShowRegistForm(false); + }; + + const handleReset = () => { + setRowSelection({}); + setSelectedVrfcRow(null); + handleSearch(); + setShowRegistForm(false); + }; + + useEffect(() => { + handleSearch(); + }, []); + + return ( + <> +
+
+
+ + + setSearchValues({ + ...searchValues, + statsCd: value, + }) + } + placeholder="전체" + className="w-[16rem]" + /> +
+
+ + +
+
+ + +
+
+ + +
+
+
+
+
+
+

+ 일반 검증 목록 +

+ + + +
+
+ {isLoading && ( +
+
+ +
+
+ )} + {isLoading ? null : vrfcMasterData.length > 0 ? ( + + handleVrfcMasterRowClick(value) + } + /> + ) : ( +
+ +
+ )} +
+
+ +
+ + ); +}; + +export default GeneralVerificationManagement; diff --git a/apps/st/src/components/statistics/verification/HbStatisticsVerification.tsx b/apps/st/src/components/statistics/verification/HbStatisticsVerification.tsx index 81fa83b2a..722fd3eca 100644 --- a/apps/st/src/components/statistics/verification/HbStatisticsVerification.tsx +++ b/apps/st/src/components/statistics/verification/HbStatisticsVerification.tsx @@ -1,482 +1,775 @@ "use client"; -import { useState } from "react"; -// import { DataGrid } from "@rsone/components"; -import DataGrid from "@/components/module/DataGrid"; -import SearchForm from "@/components/module/SearchForm"; +import { useEffect, useMemo, useState } from "react"; + +import { + keepPreviousData, + useMutation, + useQuery, + useQueryClient, +} from "@tanstack/react-query"; +import { + getCoreRowModel, + getPaginationRowModel, + useReactTable, +} from "@tanstack/react-table"; +import type { AxiosError } from "axios"; +import dayjs from "dayjs"; + +import { ENDPOINT } from "@/shared/config"; +import { useAlertStore } from "@/shared/lib"; +import type { ApiErrorResponse } from "@/shared/model"; +import { CodeSelect } from "@/entities/code"; +import type { + AnalysisRequestPayload, + AnalysisResponseDto, + StAnlsMstResponse, + StAnlsMstSearchParams, + StAnlsOutlierListResponse, +} from "@/entities/statistics"; +import { verificationHistoryColumns } from "@/entities/statistics"; +import { analysisApi } from "@/entities/statistics/api/analysis-api"; +import { stAnlsMstApi } from "@/entities/statistics/api/statistics-analysis-master-api"; +import { verificationTargetManagementApi } from "@/entities/statistics/api/verification-target-management-service"; +import type { VerificationTargetCodeResponse } from "@/entities/statistics/model/verification-target-management-interface"; import { Button, + Checkbox, + DataTable, + DateRangePicker, + Dialog, + DialogContent, + DialogHeader, + DialogTitle, Input, Label, + LoadingWithAnimation, + RadioGroup, + RadioGroupItem, Select, - SelectTrigger, SelectContent, SelectItem, + SelectTrigger, SelectValue, - Checkbox, + Table, + TableBody, + TableCell, + TableHead, + TableHeader, + TableRow, } from "@common/components"; -import { verificationHistoryColumnInfo } from "@/entities/statistics/model/verification-history-column"; -import { verificationHistoryMockData } from "@/entities/statistics/model/verification-history-mock"; -interface VerificationFormValues { +import HbVerificationDetail from "./detail/HbVerificationDetail"; + +type DateRangeValue = { + from: Date; + to?: Date; +}; + +type VerifyType = "ALL" | "SELECT"; + +interface VerificationFormState { mu: string; percentile: string; a: string; c: string; verificationYear: string; - checkboxOptions: { - sidoDistribution: boolean; - countyDistribution: boolean; - countyDistributionUserManagement: boolean; - lowerDistribution: boolean; - sidoServiceAvailability: boolean; - individualService: boolean; - legalServiceUsage: boolean; - excessUse: boolean; - lowerOrgStatistics: boolean; - studentStatistics: boolean; - developmentStatistics: boolean; - lowerManagementEnterprise: boolean; - }; +} + +interface OutlierDialogState { + open: boolean; + anlsSn: number | null; +} + +function getDefaultHistoryDateRange(): DateRangeValue { + const to = dayjs().endOf("day").toDate(); + const from = dayjs().subtract(7, "day").startOf("day").toDate(); + return { from, to }; +} + +function getVerificationYearOptions(): string[] { + const currentYear = dayjs().year(); + const startYear = 2017; + const endYear = currentYear - 1; + if (endYear < startYear) return []; + return Array.from({ length: endYear - startYear + 1 }, (_, index) => + String(startYear + index), + ); +} + +function toNumber(value: string): number { + const parsed = Number(value); + return Number.isNaN(parsed) ? 0 : parsed; } const HbStatisticsVerification = () => { - const [verificationHistoryRowData, setVerificationHistoryRowData] = - useState[]>( - verificationHistoryMockData, - ); + const { setMessage: alert } = useAlertStore((state) => state); + const queryClient = useQueryClient(); - const [formValues, setFormValues] = useState({ + const yearOptions = useMemo(() => getVerificationYearOptions(), []); + const defaultYear: string = + yearOptions.length > 0 + ? (yearOptions[yearOptions.length - 1] ?? "") + : ""; + + const [verifyType, setVerifyType] = useState("ALL"); + const [formState, setFormState] = useState({ mu: "0", percentile: "0", a: "0", c: "0", - verificationYear: "2025", - checkboxOptions: { - sidoDistribution: false, - countyDistribution: false, - countyDistributionUserManagement: false, - lowerDistribution: false, - sidoServiceAvailability: false, - individualService: false, - legalServiceUsage: false, - excessUse: false, - lowerOrgStatistics: false, - studentStatistics: false, - developmentStatistics: false, - lowerManagementEnterprise: false, + verificationYear: defaultYear, + }); + const [selectedTargets, setSelectedTargets] = useState([]); + const [outlierDialog, setOutlierDialog] = useState({ + open: false, + anlsSn: null, + }); + const [selectedStatsCd, setSelectedStatsCd] = useState(""); + const [selectedAnlsSn, setSelectedAnlsSn] = useState(null); + + const defaultHistoryDateRange = useMemo( + () => getDefaultHistoryDateRange(), + [], + ); + const [historyDateRange, setHistoryDateRange] = useState< + DateRangeValue | undefined + >(defaultHistoryDateRange); + const [appliedHistoryDateRange, setAppliedHistoryDateRange] = useState< + DateRangeValue | undefined + >(defaultHistoryDateRange); + + const [historyPagination, setHistoryPagination] = useState({ + pageIndex: 0, + pageSize: 10, + }); + + const { data: verificationTargetCodes } = useQuery< + VerificationTargetCodeResponse[] + >({ + queryKey: [ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG, "codes"], + queryFn: () => + verificationTargetManagementApi.getVerificationTargetCodes(), + }); + + const filteredVerificationTargetCodes = useMemo(() => { + return verificationTargetCodes?.filter((item) => + selectedStatsCd + ? item.vrfcTrgtSn.startsWith(selectedStatsCd) + : true, + ); + }, [verificationTargetCodes, selectedStatsCd]); + + const allVerificationTargetIds = useMemo( + () => + (filteredVerificationTargetCodes ?? []).map( + (item) => item.vrfcTrgtSn, + ), + [filteredVerificationTargetCodes], + ); + + const isAllSelected = useMemo(() => { + const count = filteredVerificationTargetCodes?.length ?? 0; + return count > 0 && selectedTargets.length === count; + }, [filteredVerificationTargetCodes, selectedTargets]); + + const handleToggleAll = () => { + setSelectedTargets(isAllSelected ? [] : allVerificationTargetIds); + }; + + useEffect(() => { + setSelectedTargets(allVerificationTargetIds); + }, [allVerificationTargetIds]); + + const { data: analysisHistory } = useQuery({ + queryKey: [ + ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_MST, + historyPagination, + appliedHistoryDateRange, + ], + queryFn: () => { + const params: StAnlsMstSearchParams = { + page: historyPagination.pageIndex, + size: historyPagination.pageSize, + sort: "anlsSn,desc", + vrfcMthdCd: "HB", + }; + + if (appliedHistoryDateRange?.from) { + params.verifyDtStart = dayjs( + appliedHistoryDateRange.from, + ).format("YYYY-MM-DD"); + } + + if (appliedHistoryDateRange?.to || appliedHistoryDateRange?.from) { + const to = + appliedHistoryDateRange.to ?? appliedHistoryDateRange.from!; + params.verifyDtEnd = dayjs(to).format("YYYY-MM-DD"); + } + + return stAnlsMstApi.getAnalysisHistoryList(params); + }, + refetchInterval: (query) => { + const data = query.state.data; + if (!data?.content?.length) return false; + const hasProcessing = (data.content as StAnlsMstResponse[]).some( + (item) => item.anlsSttsCd === "PROCESSING", + ); + return hasProcessing ? 3000 : false; + }, + placeholderData: keepPreviousData, + }); + + const historyRowData: StAnlsMstResponse[] = analysisHistory?.content ?? []; + + const table = useReactTable({ + data: historyRowData, + columns: verificationHistoryColumns, + getCoreRowModel: getCoreRowModel(), + getPaginationRowModel: getPaginationRowModel(), + manualPagination: true, + pageCount: analysisHistory?.totalPages ?? 0, + state: { + pagination: historyPagination, + }, + onPaginationChange: setHistoryPagination, + meta: { + onOutlierCellClick: (row: StAnlsMstResponse) => { + setOutlierDialog({ open: true, anlsSn: row.anlsSn }); + }, }, }); - const handleCheckboxChange = ( - key: keyof VerificationFormValues["checkboxOptions"], - ) => { - setFormValues((prev) => ({ - ...prev, - checkboxOptions: { - ...prev.checkboxOptions, - [key]: !prev.checkboxOptions[key], - }, - })); - }; + const { data: outlierList, isLoading: isLoadingOutlier } = useQuery({ + queryKey: [ + ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_MST, + "outlier", + outlierDialog.anlsSn, + ], + queryFn: async () => { + if (!outlierDialog.anlsSn) return []; + const response = await stAnlsMstApi.getOutlierList( + outlierDialog.anlsSn, + ); + return response; + }, + enabled: outlierDialog.open && !!outlierDialog.anlsSn, + }); - const handleInputChange = ( - key: keyof Omit, + const analysisMutation = useMutation< + AnalysisResponseDto, + AxiosError, + AnalysisRequestPayload + >({ + mutationFn: async (payload) => analysisApi.analyze(payload), + onSuccess: () => { + alert("검증을 요청했습니다."); + queryClient.invalidateQueries({ + queryKey: [ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_MST], + }); + }, + onError: (error) => { + alert( + error.response?.data?.message ?? + "검증 실행 중 오류가 발생했습니다.", + ); + }, + }); + + function handleFormChange( + key: Key, value: string, - ) => { - setFormValues((prev) => ({ + ) { + setFormState((prev) => ({ ...prev, [key]: value, })); - }; + } - const handleSubmit = () => { - console.log("검증 실행:", formValues); - }; + function handleTargetToggle(statsCd: string) { + setSelectedTargets((prev) => + prev.includes(statsCd) + ? prev.filter((cd) => cd !== statsCd) + : [...prev, statsCd], + ); + } - const handleReset = () => { - console.log("초기화"); - }; + async function handleSubmit() { + if (!formState.verificationYear) { + alert("검증년도를 선택해 주세요."); + return; + } + + if (verifyType === "SELECT" && selectedTargets.length === 0) { + alert("검증 대상을 1개 이상 선택해 주세요."); + return; + } + + const yearNew = toNumber(formState.verificationYear); + const payload: AnalysisRequestPayload = { + dataset: + verifyType === "ALL" + ? allVerificationTargetIds.length > 0 + ? allVerificationTargetIds.join(",") + : undefined + : selectedTargets.length > 0 + ? selectedTargets.join(",") + : undefined, + yearNew, + yearOld: yearNew - 1, + mu: toNumber(formState.mu), + percentile: toNumber(formState.percentile), + a: toNumber(formState.a), + c: toNumber(formState.c), + vrfcMthdCd: "HB", + allVerifyYn: verifyType === "ALL" ? "Y" : "N", + }; + + analysisMutation.mutate(payload); + } + + function handleReset() { + setFormState({ + mu: "0", + percentile: "0", + a: "0", + c: "0", + verificationYear: defaultYear, + }); + setSelectedTargets([]); + } + + function handleHistoryRowClick(row: StAnlsMstResponse) { + const anlsSn = Number(row.anlsSn ?? 0); + if (!anlsSn) return; + setSelectedAnlsSn(anlsSn); + } + + function applyHistoryDateSearch(nextRange: DateRangeValue | undefined) { + setAppliedHistoryDateRange(nextRange); + setHistoryPagination((prev) => ({ + ...prev, + pageIndex: 0, + })); + } + + function handleHistoryDateSearch() { + applyHistoryDateSearch(historyDateRange); + } + + function handleHistoryDateReset() { + const resetRange = getDefaultHistoryDateRange(); + setHistoryDateRange(resetRange); + applyHistoryDateSearch(resetRange); + } + + function closeOutlierDialog() { + setOutlierDialog({ open: false, anlsSn: null }); + } return ( -
-
- {/* 통계 검증 섹션 */} -
-

- 통계 검증 -

- -
- {/* 왼쪽: 검증 변수 */} -
-

- 검증 변수 -

- -
-
- - - handleInputChange( - "mu", - e.target.value, - ) - } - className="flex-1" - /> -
- -
- - - handleInputChange( - "percentile", - e.target.value, - ) - } - className="flex-1" - /> -
- -
- - - handleInputChange( - "a", - e.target.value, - ) - } - className="flex-1" - /> -
- -
- - - handleInputChange( - "c", - e.target.value, - ) - } - className="flex-1" - /> -
- -
-
-
+ + + + 이상건수 상세 + + {isLoadingOutlier && ( +
+
+ +
+
+ )} + {!isLoadingOutlier && (outlierList?.length ?? 0) === 0 && ( +

+ 표시할 이상치 데이터가 없습니다. +

+ )} + {!isLoadingOutlier && (outlierList?.length ?? 0) > 0 && ( +
+ {outlierList?.map( + (item: StAnlsOutlierListResponse) => ( + + + + + {item.vrfcTrgtNm} + + + + + 시도 + + + 시군구 + + + 행정구역 + + + 시설명 + + + 입력값 + + + + + {item.outlierDataList.map( + (data) => ( + + + {data.sido ?? "-"} + + + {data.gugun ?? "-"} + + + {data.adstDong ?? + "-"} + + + {/* 시설명: DTO에 해당 필드 없음 */} + - + + + {data.cryrVl != null + ? String( + data.cryrVl, + ) + : "-"} + + + ), + )} + +
+ ), + )} +
+ )} +
+
+ ); }; diff --git a/apps/st/src/components/statistics/verification/ImrVerificationHistory.tsx b/apps/st/src/components/statistics/verification/ImrVerificationHistory.tsx new file mode 100644 index 000000000..3695cf25e --- /dev/null +++ b/apps/st/src/components/statistics/verification/ImrVerificationHistory.tsx @@ -0,0 +1,547 @@ +"use client"; + +import { useEffect, useMemo, useState } from "react"; +import { Line } from "react-chartjs-2"; + +import { keepPreviousData, useQuery } from "@tanstack/react-query"; +import { + getCoreRowModel, + getPaginationRowModel, + useReactTable, +} from "@tanstack/react-table"; +import type { ChartOptions } from "chart.js"; +import { + CategoryScale, + Chart as ChartJS, + Legend, + LinearScale, + LineElement, + PointElement, + Title, + Tooltip as ChartTooltip, +} from "chart.js"; +import dayjs from "dayjs"; + +import { ENDPOINT } from "@/shared/config"; +import { CodeSelect } from "@/entities/code"; +import type { + AdstZoneResponseDto, + StAnlsMstResponse, + StAnlsMstSearchParams, + StAnlsRsltResponse, +} from "@/entities/statistics"; +import { + IMR_DETAIL_VISIBLE_COLUMNS_BY_STATS_CD, + IMR_DETAIL_VISIBLE_COLUMNS_DEFAULT, + imrDetailGridColumnInfo, + imrVerificationHistoryColumns, +} from "@/entities/statistics"; +import { imrApi } from "@/entities/statistics/api/imr-api"; +import { + useStAnlsSidoCombo, + useStAnlsSigunguCombo, +} from "@/entities/statistics/api/queries"; +import { stAnlsMstApi } from "@/entities/statistics/api/statistics-analysis-master-api"; +import { stAnlsRsltApi } from "@/entities/statistics/api/statistics-analysis-result-api"; +import { + Button, + DataTable, + DateRangePicker, + Label, + LoadingWithAnimation, + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@common/components"; + +import DataGrid from "@/components/module/DataGrid"; +import type { ColumnInfo } from "@/components/type/DataGrid.type"; + +ChartJS.register( + CategoryScale, + LinearScale, + PointElement, + LineElement, + Title, + ChartTooltip, + Legend, +); + +type DateRangeValue = { + from: Date; + to?: Date; +}; + +const EMPTY_DATA: never[] = []; +const EMPTY_ADST_LIST: AdstZoneResponseDto[] = []; + +function getImrDetailGridColumnInfo(statsCd: string): ColumnInfo { + const visible = + IMR_DETAIL_VISIBLE_COLUMNS_BY_STATS_CD[statsCd] ?? + IMR_DETAIL_VISIBLE_COLUMNS_DEFAULT; + const visibleSet = new Set(visible); + return { + columns: imrDetailGridColumnInfo.columns.map((col) => + visibleSet.has(col.name) ? col : { ...col, visible: false }, + ), + columnLayout: imrDetailGridColumnInfo.columnLayout, + }; +} + +const ImrVerificationHistory = () => { + // Area A Search States + const [searchSido, setSearchSido] = useState(""); + const [searchSigungu, setSearchSigungu] = useState(""); + const [searchStatsCd, setSearchStatsCd] = useState(""); + const [dateRange, setDateRange] = useState({ + from: dayjs().subtract(1, "month").toDate(), + to: dayjs().toDate(), + }); + const [appliedSearchParams, setAppliedSearchParams] = + useState({ + page: 0, + size: 10, + vrfcMthdCd: "IMR", + sort: "anlsSn,desc", + }); + + // Selected States + const [selectedHistory, setSelectedHistory] = + useState(null); + const [selectedDetail, setSelectedDetail] = + useState(null); + const [isDownloading, setIsDownloading] = useState(false); + + // Area B Grid State + const [gridRowData, setGridRowData] = useState< + Record[] + >([]); + + // Area A Pagination + const [historyPagination, setHistoryPagination] = useState({ + pageIndex: 0, + pageSize: 5, + }); + + const { data: sidoData } = useStAnlsSidoCombo(); + const { data: sigunguData } = useStAnlsSigunguCombo(searchSido); + const sidoOptions = sidoData ?? EMPTY_ADST_LIST; + const sigunguOptions = sigunguData ?? EMPTY_ADST_LIST; + + const imrDetailColumnInfo = useMemo( + () => getImrDetailGridColumnInfo(selectedHistory?.statsCd ?? ""), + [selectedHistory?.statsCd], + ); + + // Area A Data Fetching + const { data: historyData } = useQuery({ + queryKey: [ + ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_MST, + "imr", + appliedSearchParams, + historyPagination, + ], + queryFn: () => + stAnlsMstApi.getImrAnalysisMasterList({ + ...appliedSearchParams, + page: historyPagination.pageIndex, + size: historyPagination.pageSize, + }), + placeholderData: keepPreviousData, + }); + + const historyTable = useReactTable({ + data: historyData?.content ?? EMPTY_DATA, + columns: imrVerificationHistoryColumns, + getRowId: (row) => String(row.anlsSn), + getCoreRowModel: getCoreRowModel(), + getPaginationRowModel: getPaginationRowModel(), + manualPagination: true, + pageCount: historyData?.totalPages ?? 0, + state: { + pagination: historyPagination, + rowSelection: selectedHistory + ? { [selectedHistory.anlsSn]: true } + : {}, + }, + onPaginationChange: setHistoryPagination, + }); + + // Area B Data Fetching + const { data: detailData, isLoading: isDetailLoading } = useQuery({ + queryKey: [ + ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_RSLT, + selectedHistory?.anlsSn, + ], + queryFn: () => + stAnlsRsltApi.getImrResultList(selectedHistory!.anlsSn, { + page: 0, + size: 100, + sort: "admdstCd,asc", + }), + enabled: !!selectedHistory, + }); + + useEffect(() => { + if (!detailData || !detailData.content) { + setGridRowData([]); + return; + } + const mapped = detailData.content.map((item) => ({ + ...item, + statsNm: selectedHistory?.vrfcTrgtNm ?? "-", + })); + setGridRowData(mapped as Record[]); + }, [detailData, selectedHistory]); + + // Area C Data Fetching + const { data: chartData, isLoading: isChartLoading } = useQuery({ + queryKey: [ + ENDPOINT.STATVERIFY_SERVICE.IMR, + selectedHistory?.anlsSn, + selectedDetail?.vrfcTrgtSn, + selectedDetail?.admdstCd, + ], + queryFn: () => + imrApi.getOutliersLog({ + jobUuid: selectedHistory!.jobUuid, + anlsSn: selectedDetail!.anlsSn, + vrfcTrgtSn: selectedDetail!.vrfcTrgtSn, + admdstCd: selectedDetail!.admdstCd, + }), + enabled: !!selectedHistory && !!selectedDetail, + }); + + const handleSearch = () => { + const params: StAnlsMstSearchParams = { + vrfcMthdCd: "IMR", + sort: "anlsSn,desc", + }; + if (searchSido !== "") + params.sewerBzmnCd = + searchSigungu !== "" ? searchSigungu : searchSido; + if (searchStatsCd) params.statsCd = searchStatsCd; + if (dateRange?.from) + params.verifyDtStart = dayjs(dateRange.from).format("YYYY-MM-DD"); + if (dateRange?.to) + params.verifyDtEnd = dayjs(dateRange.to).format("YYYY-MM-DD"); + + setAppliedSearchParams(params); + setHistoryPagination((prev) => ({ ...prev, pageIndex: 0 })); + setSelectedHistory(null); + setSelectedDetail(null); + }; + + const handleReset = () => { + setSearchSido(""); + setSearchSigungu(""); + setSearchStatsCd(""); + const defaultRange = { + from: dayjs().subtract(1, "month").toDate(), + to: dayjs().toDate(), + }; + setDateRange(defaultRange); + }; + + const handleDownload = async () => { + if (!selectedHistory || isDownloading) return; + setIsDownloading(true); + + try { + const blob = await stAnlsRsltApi.downloadExcelImr( + selectedHistory.anlsSn, + ); + const url = window.URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `IMR_분석결과.xlsx`; + document.body.appendChild(a); + a.click(); + window.URL.revokeObjectURL(url); + document.body.removeChild(a); + } catch (error) { + console.error("Failed to download IMR excel", error); + } finally { + setIsDownloading(false); + } + }; + + const chartOptions: ChartOptions<"line"> = useMemo( + () => ({ + responsive: true, + maintainAspectRatio: false, + plugins: { + legend: { + position: "top" as const, + labels: { + font: { + size: 12, + }, + }, + }, + title: { + display: true, + text: "I-MR 잔차 관리도", + font: { + size: 16, + weight: "bold", + }, + }, + }, + scales: { + y: { + beginAtZero: false, + title: { + display: true, + text: "수치", + }, + }, + x: { + title: { + display: true, + text: "연도", + }, + }, + }, + }), + [selectedDetail], + ); + + const lineChartData = useMemo(() => { + if (!chartData || !chartData.history) return null; + + const labels = chartData.history.map((h) => String(h.year)); + const actualData = chartData.history.map((h) => h.x); + const uclData = chartData.history.map((h) => h.ucl); + const lclData = chartData.history.map((h) => h.lcl); + const predictedData = chartData.history.map((h) => h.predicted); + + return { + labels, + datasets: [ + { + label: "실측치 (X)", + data: actualData, + borderColor: "rgb(75, 192, 192)", + backgroundColor: "rgba(75, 192, 192, 0.5)", + tension: 0.1, + pointRadius: 4, + pointHoverRadius: 6, + }, + { + label: "상한선 (UCL)", + data: uclData, + borderColor: "rgb(255, 99, 132)", + backgroundColor: "rgba(255, 99, 132, 0.2)", + borderDash: [5, 5], + pointStyle: "false", + fill: false, + }, + { + label: "하한선 (LCL)", + data: lclData, + borderColor: "rgb(54, 162, 235)", + backgroundColor: "rgba(54, 162, 235, 0.2)", + borderDash: [5, 5], + pointStyle: "false", + fill: false, + }, + { + label: "예측치 (Predicted)", + data: predictedData, + borderColor: "rgb(153, 102, 255)", + backgroundColor: "rgba(153, 102, 255, 0.5)", + borderDash: [2, 2], + pointStyle: "false", + fill: false, + }, + ], + }; + }, [chartData]); + + return ( +
+ {/* 영역 A: 검증 이력 그리드 + 검색 필터 */} +
+
+
+ + +
+ +
+ + +
+ +
+ + + setDateRange( + val + ? { from: val.from!, to: val.to } + : undefined, + ) + } + className="w-[20rem]" + /> +
+ +
+ + +
+ +
+ + +
+
+ +
+ { + setSelectedHistory(row); + setSelectedDetail(null); + }} + viewPagination={true} + className="[&_td]:!p-0" + /> +
+
+ +
+ {/* 영역 B: 상세 데이터 그리드 */} +
+
+

+ 이상치 데이터 +

+ +
+
+ {isDetailLoading ? ( +
+
+ +
+
+ ) : !selectedHistory || gridRowData.length === 0 ? ( +
+ {!selectedHistory + ? "항목을 선택해주세요." + : "표시할 항목이 없습니다."} +
+ ) : ( + { + if (!e.anlsSn) return; + const row = detailData?.content?.find( + (item) => + String(item.rsltSn) === + String(e.rsltSn), + ); + if (row) setSelectedDetail(row); + }} + /> + )} +
+
+ + {/* 영역 C: Line Chart */} +
+ {isChartLoading ? ( +
+ +
+ ) : lineChartData ? ( + + ) : ( +
+ 이상치 데이터를 선택하면 차트가 표시됩니다. +
+ )} +
+
+
+ ); +}; + +export default ImrVerificationHistory; diff --git a/apps/st/src/components/statistics/verification/VerificationArticleManagement.tsx b/apps/st/src/components/statistics/verification/VerificationArticleManagement.tsx index caef0180b..c91b520ce 100644 --- a/apps/st/src/components/statistics/verification/VerificationArticleManagement.tsx +++ b/apps/st/src/components/statistics/verification/VerificationArticleManagement.tsx @@ -1,13 +1,30 @@ "use client"; -import DataGrid from "@/components/module/DataGrid"; +import { useState } from "react"; + +import { useConfirm } from "@frontend-opensource/use-react-hooks"; +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; + +import { ENDPOINT } from "@/shared/config"; +import { CodeSelect } from "@/entities/code/ui/code-select"; import { hbArticleColumnInfo, imrArticleColumnInfo, validationArticleColumnInfo, -} from "@/entities/statistics/model/verification-article-column"; +} from "@/entities/statistics"; +import { verificationTargetManagementApi } from "@/entities/statistics/api/verification-target-management-service"; +import type { + VerificationTargetManagementResponse, + VerificationTargetManagementSearchParams, +} from "@/entities/statistics/model/verification-target-management-interface"; import { Button, + cn, + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, Input, Label, Tabs, @@ -15,24 +32,18 @@ import { TabsList, TabsTrigger, } from "@common/components"; -import { CodeSelect } from "@/entities/code/ui/code-select"; -import { verificationTargetManagementApi } from "@/entities/statistics/api/verification-target-management-service"; -import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; -import { useState } from "react"; -import { ENDPOINT } from "@/shared/config"; -import type { - VerificationTargetManagementSearchParams, - VerificationTargetManagementResponse, -} from "@/entities/statistics/model/verification-target-management-interface"; + +import GeneralVerificationManagement from "./GeneralVerificationManagement"; import { VerificationTargetDialog } from "./VerificationTargetDialog"; -import { useConfirm } from "@frontend-opensource/use-react-hooks"; + +import DataGrid from "@/components/module/DataGrid"; const TAB_CONFIG = { HB: { value: "HB", label: "H-B", columnInfo: hbArticleColumnInfo }, IMR: { value: "IMR", label: "I-MR", columnInfo: imrArticleColumnInfo }, - VV: { - value: "VV", - label: "Validation", + GENERAL: { + value: "GENERAL", + label: "일반", columnInfo: validationArticleColumnInfo, }, } as const; @@ -54,6 +65,8 @@ function VerificationArticleManagement() { const [dialogOpen, setDialogOpen] = useState(false); const [selectedData, setSelectedData] = useState(null); + const [resultDialogOpen, setResultDialogOpen] = useState(false); + const [resultDialogMessage, setResultDialogMessage] = useState(""); const { data: verificationData } = useQuery({ queryKey: [ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG, searchParams], @@ -64,6 +77,7 @@ function VerificationArticleManagement() { vrfcMthdCd: searchParams.vrfcMthdCd, statsCd: searchParams.statsCd || undefined, vrfcTrgtNm: searchParams.vrfcTrgtNm || undefined, + sort: ["statsCd,asc", "vrfcTrgtNm,asc"], }, ); return response; @@ -104,6 +118,30 @@ function VerificationArticleManagement() { }); } + const saveMutation = useMutation({ + mutationFn: (data: VerificationTargetManagementResponse) => + verificationTargetManagementApi.saveVerificationTargetManagement({ + vrfcMthdCd: data.vrfcMthdCd || activeTab, + statsCd: data.statsCd, + schmNm: data.schmNm, + tblNm: data.tblNm, + colNm: data.colNm, + pkColNm: data.pkColNm, + ipcrCntVl: data.ipcrCntVl, + pctlCrtrVl: data.pctlCrtrVl, + scopCntCntVl: data.scopCntCntVl, + thrsCntVl: data.thrsCntVl, + useYn: data.useYn, + vrfcTrgtNm: data.vrfcTrgtNm, + }), + onSuccess: () => { + queryClient.invalidateQueries({ + queryKey: [ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG], + }); + setDialogOpen(false); + }, + }); + const updateMutation = useMutation({ mutationFn: (data: VerificationTargetManagementResponse) => verificationTargetManagementApi.updateVerificationTargetManagement( @@ -144,6 +182,23 @@ function VerificationArticleManagement() { }, }); + const checkColumnsMutation = useMutation({ + mutationFn: () => + verificationTargetManagementApi.checkColumnsExist({ + vrfcMthdCd: activeTab, + }), + onSuccess: (response) => { + setResultDialogMessage( + response.message || "컬럼 검사가 완료되었습니다.", + ); + setResultDialogOpen(true); + }, + onError: () => { + setResultDialogMessage("컬럼 검사 중 오류가 발생했습니다."); + setResultDialogOpen(true); + }, + }); + function handleRowClick(rowData: Record) { setSelectedData( rowData as unknown as VerificationTargetManagementResponse, @@ -151,6 +206,11 @@ function VerificationArticleManagement() { setDialogOpen(true); } + function handleRegister() { + setSelectedData(null); + setDialogOpen(true); + } + function handleSubmit(e: React.FormEvent) { e.preventDefault(); handleSearch(); @@ -158,7 +218,11 @@ function VerificationArticleManagement() { async function handleSave(data: VerificationTargetManagementResponse) { if (await confirm("저장하시겠습니까?")) { - updateMutation.mutate(data); + if (data.vrfcTrgtSn) { + updateMutation.mutate(data); + } else { + saveMutation.mutate(data); + } } } @@ -168,94 +232,144 @@ function VerificationArticleManagement() { } } + async function handleCheckColumns() { + if (!(await confirm("컬럼 검사를 실행하시겠습니까?"))) return; + checkColumnsMutation.mutate(); + } + return ( - - + <> + + + {Object.entries(TAB_CONFIG).map(([key, config]) => ( + + {config.label} + + ))} + + {activeTab !== "GENERAL" && ( +
+
+
+
+ + +
+ +
+ + + setVrfcTrgtNm(e.target.value) + } + placeholder="검증명" + className="w-[20rem]" + /> +
+ +
+ + + + +
+
+
+
+ )} + {Object.entries(TAB_CONFIG).map(([key, config]) => ( - - {config.label} - + {activeTab !== "GENERAL" ? ( + {}} + onRowClick={handleRowClick} + isExcelImport={false} + /> + ) : ( + + )} + ))} -
-
-
-
-
- - -
- -
- - setVrfcTrgtNm(e.target.value)} - placeholder="검증명" - className="w-[20rem]" - /> -
- -
- - -
+ + + + + + 컬럼 검사 결과 + +
+ {resultDialogMessage}
- -
- - {Object.entries(TAB_CONFIG).map(([key, config]) => ( - - {}} - onRowClick={handleRowClick} - isExcelImport={false} - /> - - ))} - - - + + + + + + ); } diff --git a/apps/st/src/components/statistics/verification/VerificationTargetDialog.tsx b/apps/st/src/components/statistics/verification/VerificationTargetDialog.tsx index 40fa92826..ce9b1d26e 100644 --- a/apps/st/src/components/statistics/verification/VerificationTargetDialog.tsx +++ b/apps/st/src/components/statistics/verification/VerificationTargetDialog.tsx @@ -1,5 +1,21 @@ "use client"; +import { useEffect, useState } from "react"; +import { Controller, useForm } from "react-hook-form"; + +import { zodResolver } from "@hookform/resolvers/zod"; +import { Search } from "lucide-react"; + +import { CodeSelect } from "@/entities/code/ui/code-select"; +import { verificationTargetManagementApi } from "@/entities/statistics/api/verification-target-management-service"; +import type { + NumericColumnDto, + VerificationTargetManagementResponse, +} from "@/entities/statistics/model/verification-target-management-interface"; +import { + type VerificationTargetManagementFormData, + verificationTargetManagementSchema, +} from "@/entities/statistics/model/verification-target-management-schema"; import { Button, Dialog, @@ -12,17 +28,10 @@ import { TableBody, TableCell, TableHead, + TableHeader, TableRow, } from "@common/components"; -import { CodeSelect } from "@/entities/code/ui/code-select"; -import type { VerificationTargetManagementResponse } from "@/entities/statistics/model/verification-target-management-interface"; -import { - verificationTargetManagementSchema, - type VerificationTargetManagementFormData, -} from "@/entities/statistics/model/verification-target-management-schema"; -import { useEffect } from "react"; -import { useForm, Controller } from "react-hook-form"; -import { zodResolver } from "@hookform/resolvers/zod"; + import type { TabValue } from "./VerificationArticleManagement"; interface VerificationTargetDialogProps { @@ -42,24 +51,49 @@ export function VerificationTargetDialog({ onSave, onDelete, }: VerificationTargetDialogProps) { - const { - control, - handleSubmit, - reset, - formState: { errors }, - } = useForm({ - resolver: zodResolver(verificationTargetManagementSchema), - defaultValues: data || undefined, - }); + const { control, handleSubmit, reset, watch, getValues, setValue } = + useForm({ + resolver: zodResolver(verificationTargetManagementSchema), + defaultValues: data || { + vrfcMthdCd: tabValue, + statsCd: "", + vrfcTrgtNm: "", + schmNm: "", + tblNm: "", + colNm: "", + pkColNm: "", + useYn: "Y", + }, + }); + const watchStatsCd = watch("statsCd"); + + const [isColumnDialogOpen, setIsColumnDialogOpen] = useState(false); + const [numericColumns, setNumericColumns] = useState( + [], + ); useEffect(() => { - if (data && open) reset(data); - }, [data, open, reset]); + if (open) { + reset( + data || { + vrfcMthdCd: tabValue, + statsCd: "", + vrfcTrgtNm: "", + schmNm: "", + tblNm: "", + colNm: "", + pkColNm: "", + useYn: "Y", + }, + ); + } else { + setNumericColumns([]); + } + }, [data, open, reset, tabValue]); function onSubmit(formData: VerificationTargetManagementFormData) { - if (!data) return; onSave({ - ...data, + ...(data || {}), ...formData, } as VerificationTargetManagementResponse); } @@ -70,307 +104,468 @@ export function VerificationTargetDialog({ } } - if (!data) return null; + async function handleSearchTableMetadata(e?: React.MouseEvent) { + e?.preventDefault(); + const statsCd = getValues("statsCd"); + if (!statsCd) { + alert("통계항목을 선택해주세요."); + return; + } + + try { + const metadata = + await verificationTargetManagementApi.getTableInfo(statsCd); + + setValue("schmNm", metadata.schmNm, { shouldValidate: true }); + setValue("tblNm", metadata.tblNm, { shouldValidate: true }); + + if (metadata.pkColumns && metadata.pkColumns.length > 0) { + setValue("pkColNm", metadata.pkColumns.join(", "), { + shouldValidate: true, + }); + } + + setNumericColumns(metadata.numericColumns || []); + setIsColumnDialogOpen(true); + } catch (error) { + alert("테이블 정보를 조회하는 중 오류가 발생했습니다."); + console.error(error); + } + } + + function handleOpenColumnDialog(e?: React.MouseEvent) { + e?.preventDefault(); + if (numericColumns.length === 0) { + handleSearchTableMetadata(); + } else { + setIsColumnDialogOpen(true); + } + } + + function handleSelectColumn(colNm: string) { + setValue("colNm", colNm, { shouldValidate: true }); + setIsColumnDialogOpen(false); + } return ( - - - - 검증 항목 상세 - + <> + + + + + {data ? "검증 항목 상세" : "검증 항목 등록"} + + -
- - - - - 통계항목 - - - ( -
- -
- )} - /> -
- - 검증명 - - - ( - +
+ + + + + + + + + + 통계항목 + + +
+ ( + + )} /> - )} - /> - - - - - - 스키마명 - - - ( -
- -
- )} - /> -
- - 테이블명 - - - ( -
- -
- )} - /> -
-
- - - - 컬럼명 - - - ( -
- -
- )} - /> -
- - PK 키 - - - ( -
- -
- )} - /> -
-
- - {tabValue !== "IMR" && ( - - - 중요도 계수(μ) + +
+
+ + 검증명 ( + + )} + /> + +
+ + + + 스키마명 + + + (
- field.onChange( - e.target.value - ? Number( - e.target - .value, - ) - : null, - ) - } - placeholder="(0 ~ 1, 0.1 단위)" + {...field} + placeholder="스키마명" />
)} />
- - 백분위수 기준값(pct) + + 테이블명 (
- field.onChange( - e.target.value - ? Number( - e.target - .value, - ) - : null, - ) - } - placeholder="(0 ~ 0.5, 0.1 단위)" + {...field} + placeholder="테이블명" />
)} />
- )} - {tabValue !== "IMR" && ( - - 스케일 조정 계수(A) + + 컬럼명 - ( -
+
+ ( - field.onChange( - e.target.value - ? Number( - e.target - .value, - ) - : null, - ) - } - placeholder="(0 ~ 1, 0.01 단위)" + {...field} + placeholder="컬럼명" + className="flex-1" /> -
- )} - /> + )} + /> + +
- - 임계 계수(c) + + PK 키 (
- field.onChange( - e.target.value - ? Number( - e.target - .value, - ) - : null, - ) - } - placeholder="(0 ~ 100, 1 단위)" + {...field} + placeholder="PK 키" />
)} />
- )} -
-
- - - - - -
-
-
+ {tabValue !== "IMR" && ( + + + 중요도 계수(μ) + + + ( +
+ + field.onChange( + e.target + .value + ? Number( + e + .target + .value, + ) + : null, + ) + } + placeholder="(0 ~ 1, 0.1 단위)" + /> +
+ )} + /> +
+ + 백분위수 기준값(pct) + + + ( +
+ + field.onChange( + e.target + .value + ? Number( + e + .target + .value, + ) + : null, + ) + } + placeholder="(0 ~ 0.5, 0.1 단위)" + /> +
+ )} + /> +
+
+ )} + + {tabValue !== "IMR" && ( + + + 스케일 조정 계수(A) + + + ( +
+ + field.onChange( + e.target + .value + ? Number( + e + .target + .value, + ) + : null, + ) + } + placeholder="(0 ~ 1, 0.01 단위)" + /> +
+ )} + /> +
+ + 임계 계수(c) + + + ( +
+ + field.onChange( + e.target + .value + ? Number( + e + .target + .value, + ) + : null, + ) + } + placeholder="(0 ~ 100, 1 단위)" + /> +
+ )} + /> +
+
+ )} + + + + + + {data && ( + + )} + + + +
+
+ + + + + 숫자형 컬럼 목록 + +
+ + + + + 컬럼명 + + + 데이터 타입 + + + 코멘트 + + + 선택 + + + + + {numericColumns.length === 0 ? ( + + + 조회된 숫자형 컬럼이 없습니다. + + + ) : ( + numericColumns.map((col, idx) => ( + + + {col.columnName} + + + {col.dataType} + + + {col.columnComment} + + + + + + )) + )} + +
+
+
+
+ ); } diff --git a/apps/st/src/components/statistics/verification/detail/HbVerificationDetail.tsx b/apps/st/src/components/statistics/verification/detail/HbVerificationDetail.tsx new file mode 100644 index 000000000..89a988fda --- /dev/null +++ b/apps/st/src/components/statistics/verification/detail/HbVerificationDetail.tsx @@ -0,0 +1,125 @@ +import React, { useState } from "react"; + +import type { StAnlsDtlResponse } from "@/entities/statistics"; +import { Button } from "@common/components"; + +import Indicators from "./Indicators"; +import RegionalGrid from "./RegionalGrid"; +import ScatterChart from "./ScatterChart"; +import VerificationList from "./VerificationList"; + +interface HbVerificationDetailProps { + anlsSn: number; + onBack: () => void; +} + +export interface AppliedFilter { + sido: string | null; + gugun: string; + status: string; +} + +const HbVerificationDetail: React.FC = ({ + anlsSn, + onBack, +}) => { + const [selectedVrfcTrgtSn, setSelectedVrfcTrgtSn] = useState( + null, + ); + const [checkedSns, setCheckedSns] = useState([]); + const [appliedFilter, setAppliedFilter] = useState({ + sido: "", + gugun: "", + status: "", + }); + const [selectedRowId, setSelectedRowId] = useState(null); + const [selectedTargetInfo, setSelectedTargetInfo] = useState<{ + statsNm: string; + vrfcTrgtNm: string; + } | null>(null); + + const handleTargetSelect = (row: StAnlsDtlResponse) => { + setSelectedVrfcTrgtSn(String(row.vrfcTrgtSn)); + setSelectedTargetInfo({ + statsNm: row.statsNm, + vrfcTrgtNm: row.vrfcTrgtNm, + }); + setSelectedRowId(null); + setAppliedFilter({ + sido: "", + gugun: "", + status: "", + }); + }; + + return ( +
+
+
+ +

+ 검증 상세 +

+
+ +
+ +
+
+ +
+ +
+

+ 검증 결과 상세 +

+
+
+ +
+
+ + + +
+
+
+
+
+ ); +}; + +export default HbVerificationDetail; diff --git a/apps/st/src/components/statistics/verification/detail/Indicators.tsx b/apps/st/src/components/statistics/verification/detail/Indicators.tsx new file mode 100644 index 000000000..f311e1667 --- /dev/null +++ b/apps/st/src/components/statistics/verification/detail/Indicators.tsx @@ -0,0 +1,89 @@ +import React from "react"; + +import { useQuery } from "@tanstack/react-query"; + +import { ENDPOINT } from "@/shared/config"; +import { stAnlsRsltApi } from "@/entities/statistics/api/statistics-analysis-result-api"; +import { LoadingWithAnimation } from "@common/components"; + +interface IndicatorsProps { + anlsSn: number; + vrfcTrgtSn: string | null; +} + +const Indicators: React.FC = ({ anlsSn, vrfcTrgtSn }) => { + const { data: chartData, isLoading } = useQuery({ + queryKey: [ + ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_RSLT, + "chart", + anlsSn, + vrfcTrgtSn, + ], + queryFn: () => stAnlsRsltApi.getChartData(anlsSn, Number(vrfcTrgtSn)), + enabled: !!anlsSn && !!vrfcTrgtSn, + }); + + const dtl = chartData?.dtl; + + if (!vrfcTrgtSn) { + return ( +
+ 항목을 선택해주세요 +
+ ); + } + + if (isLoading) { + return ( +
+
+ +
+
+ ); + } + + const IndicatorItem = ({ + label, + value, + }: { + label: string; + value: number | null | undefined; + }) => ( +
+

+ {label} +

+
+ {value != null ? Number(value).toFixed(4) : "-"} +
+
+ ); + + return ( +
+ + + + + + + + +
+ ); +}; + +export default Indicators; diff --git a/apps/st/src/components/statistics/verification/detail/RegionalGrid.tsx b/apps/st/src/components/statistics/verification/detail/RegionalGrid.tsx new file mode 100644 index 000000000..8f5c420da --- /dev/null +++ b/apps/st/src/components/statistics/verification/detail/RegionalGrid.tsx @@ -0,0 +1,276 @@ +import React, { useEffect, useMemo, useState } from "react"; + +import type { + AdstZoneResponseDto, + StAnlsRsltResponse, +} from "@/entities/statistics"; +import { + useStAnlsRsltList, + useStAnlsSidoCombo, + useStAnlsSigunguCombo, +} from "@/entities/statistics/api/queries"; +import { stAnlsRsltApi } from "@/entities/statistics/api/statistics-analysis-result-api"; +import { regionalGridColumnInfo as columnInfo } from "@/entities/statistics/model/regional-grid-columns"; +import { + Button, + LoadingWithAnimation, + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@common/components"; + +import type { AppliedFilter } from "./HbVerificationDetail"; + +import DataGrid from "@/components/module/DataGrid"; + +const EMPTY_ADST_LIST: AdstZoneResponseDto[] = []; + +interface RegionalGridProps { + anlsSn: number; + vrfcTrgtSn: string | null; + statsNm: string; + vrfcTrgtNm: string; + onFilterChange: (filter: AppliedFilter) => void; + selectedRowId?: number | null; + appliedFilter: AppliedFilter; +} + +const RegionalGrid: React.FC = ({ + anlsSn, + vrfcTrgtSn, + statsNm, + vrfcTrgtNm, + onFilterChange, + selectedRowId, + appliedFilter, +}) => { + const [selectedSido, setSelectedSido] = useState(""); + const [selectedGugun, setSelectedGugun] = useState(""); + const [selectedStatus, setSelectedStatus] = useState(""); + const [showAllOnEmptyFilter, setShowAllOnEmptyFilter] = + useState(true); + const [isDownloading, setIsDownloading] = useState(false); + + const [gridRowData, setGridRowData] = useState< + Record[] + >([]); + + const { data: sidoData } = useStAnlsSidoCombo(); + const { data: gugunData } = useStAnlsSigunguCombo(selectedSido); + const sidoOptions = sidoData ?? EMPTY_ADST_LIST; + const gugunOptions = gugunData ?? EMPTY_ADST_LIST; + + const { data: resultData, isLoading } = useStAnlsRsltList( + anlsSn, + vrfcTrgtSn, + ); + + const rowData = useMemo(() => { + let data = (resultData?.content ?? []) as StAnlsRsltResponse[]; + + if ( + !appliedFilter.sido && + !appliedFilter.gugun && + !appliedFilter.status + ) { + data = showAllOnEmptyFilter ? data : []; + } else { + const sidoCd = appliedFilter.sido; + if (sidoCd) { + data = data.filter((item) => + item.admdstCd.startsWith(sidoCd.slice(0, 2)), + ); + } + + const gugunCd = appliedFilter.gugun; + if (gugunCd) { + data = data.filter((item) => item.admdstCd === gugunCd); + } + + if (appliedFilter.status) { + data = data.filter( + (item) => + item.otlrYnCd.toLowerCase() === appliedFilter.status, + ); + } + } + + const mapOtlrToLabel = (otlrYn: string) => { + switch (otlrYn) { + case "0": + return "정상"; + case "1": + return "이상치"; + case "2": + return "제외"; + default: + return ""; + } + }; + + const mappedData = data.map((item) => ({ + ...item, + otlrYn: mapOtlrToLabel(item.otlrYnCd), + })); + + return mappedData; + }, [resultData, appliedFilter, showAllOnEmptyFilter]); + + const handleSidoChange = (val: string) => { + setSelectedSido(val); + setSelectedGugun(""); + }; + + const handleSearch = () => { + onFilterChange({ + sido: selectedSido, + gugun: selectedGugun, + status: selectedStatus, + }); + setShowAllOnEmptyFilter(false); + }; + + const handleReset = () => { + setSelectedSido(""); + setSelectedGugun(""); + setSelectedStatus(""); + onFilterChange({ + sido: "", + gugun: "", + status: "", + }); + setShowAllOnEmptyFilter(true); + }; + + const handleDownload = async () => { + if (!vrfcTrgtSn) return; + setIsDownloading(true); + + try { + const blob = await stAnlsRsltApi.downloadExcel( + anlsSn, + Number(vrfcTrgtSn), + ); + + const url = window.URL.createObjectURL(blob); + const a = document.createElement("a"); + a.href = url; + a.download = `분석결과_${statsNm}-${vrfcTrgtNm}.xlsx`; + document.body.appendChild(a); + a.click(); + window.URL.revokeObjectURL(url); + document.body.removeChild(a); + } catch (error) { + console.error("Failed to download excel", error); + } finally { + setIsDownloading(false); + } + }; + + useEffect(() => { + setGridRowData(rowData as Record[]); + }, [rowData]); + + useEffect(() => { + handleReset(); + }, [vrfcTrgtSn]); + + return ( +
+
+
+ + + +
+ +
+ + + +
+
+ +
+ {isLoading && ( +
+
+ +
+
+ )} + {!isLoading && (!vrfcTrgtSn || rowData.length === 0) && ( +
+ {vrfcTrgtSn + ? "표시할 항목이 없습니다." + : "항목을 선택해주세요."} +
+ )} + {!isLoading && rowData.length > 0 && ( + + )} +
+
+ ); +}; + +export default RegionalGrid; diff --git a/apps/st/src/components/statistics/verification/detail/ScatterChart.tsx b/apps/st/src/components/statistics/verification/detail/ScatterChart.tsx new file mode 100644 index 000000000..d5387f122 --- /dev/null +++ b/apps/st/src/components/statistics/verification/detail/ScatterChart.tsx @@ -0,0 +1,317 @@ +import React, { useMemo } from "react"; +import { Scatter } from "react-chartjs-2"; + +import { + Chart as ChartJS, + type ChartData, + type ChartOptions, + Legend, + LinearScale, + LineController, + LineElement, + PointElement, + ScatterController, + Tooltip, + type TooltipItem, +} from "chart.js"; +import zoomPlugin from "chartjs-plugin-zoom"; + +import type { StAnlsRsltResponse } from "@/entities/statistics"; +import { + useStAnlsChartData, + useStAnlsRsltList, +} from "@/entities/statistics/api/queries"; +import { LoadingWithAnimation } from "@common/components"; + +import type { AppliedFilter } from "./HbVerificationDetail"; + +ChartJS.register( + LinearScale, + LineController, + LineElement, + PointElement, + ScatterController, + Legend, + Tooltip, + zoomPlugin, +); + +interface ScatterChartProps { + anlsSn: number; + vrfcTrgtSn: string | null; + appliedFilter: AppliedFilter; + onPointClick?: (rsltSn: number | null) => void; +} + +interface LinePoint { + x: number; + y: number; +} + +interface DataPoint extends LinePoint { + item: StAnlsRsltResponse; +} + +/** 모든 점의 x·y를 합쳐 두 축이 같은 [min, max] 구간을 쓰도록 할 때 사용 */ +function getUnifiedLinearRange(data: ChartData<"scatter">): { + min: number; + max: number; +} | null { + const values: number[] = []; + for (const ds of data.datasets) { + for (const pt of ds.data) { + if (pt && typeof pt === "object" && "x" in pt && "y" in pt) { + const p = pt as LinePoint; + if (Number.isFinite(p.x)) values.push(p.x); + if (Number.isFinite(p.y)) values.push(p.y); + } + } + } + if (values.length === 0) return null; + const min = Math.min(...values); + const max = Math.max(...values); + if (min === max) { + const pad = Math.abs(min) * 0.05 || 1; + return { min: min - pad, max: max + pad }; + } + const padding = (max - min) * 0.02; + return { min: min - padding, max: max + padding }; +} + +function matchesAdmdstFilter( + admdstCd: string, + sidoCd: string | null | undefined, + gugunCd: string | undefined, +): boolean { + const gugun = (gugunCd ?? "").trim(); + if (gugun) { + return admdstCd === gugun; + } + const sido = (sidoCd ?? "").trim(); + if (!sido) { + return true; + } + return admdstCd.startsWith(sido.slice(0, 2)); +} + +const ScatterChart: React.FC = ({ + anlsSn, + vrfcTrgtSn, + appliedFilter, + onPointClick, +}) => { + const { data: resultData, isLoading: isLoadingGrid } = useStAnlsRsltList( + anlsSn, + vrfcTrgtSn, + ); + const { data: chartData, isLoading: isLoadingChart } = useStAnlsChartData( + anlsSn, + vrfcTrgtSn, + ); + + const isLoading = isLoadingGrid || isLoadingChart; + + const chartConfig = useMemo(() => { + if (!resultData || !chartData) return null; + + const rawPoints = (resultData.content ?? []) as StAnlsRsltResponse[]; + const boundaries = chartData.list ?? []; + + const sortedBoundaries = [...boundaries].sort( + (a, b) => a.xprev - b.xprev, + ); + + const upperLineData: LinePoint[] = sortedBoundaries.map((b) => ({ + x: b.yupper, + y: b.xprev, + })); + + const lowerLineData: LinePoint[] = sortedBoundaries.map((b) => ({ + x: b.xprev, + y: b.ylower, + })); + + const normalPoints: DataPoint[] = []; + const outlierPoints: DataPoint[] = []; + + rawPoints.forEach((item) => { + if ( + !matchesAdmdstFilter( + item.admdstCd, + appliedFilter.sido, + appliedFilter.gugun, + ) + ) { + return; + } + + if ( + appliedFilter.status && + item.otlrYnCd.toLowerCase() !== appliedFilter.status + ) { + return; + } + + const pt: DataPoint = { + x: Number(item.prvyrVl ?? 0), + y: Number(item.cryrVl ?? 0), + item, + }; + + if (item.otlrYnCd === "0") { + normalPoints.push(pt); + } else { + outlierPoints.push(pt); + } + }); + + const data: ChartData<"scatter"> = { + datasets: [ + { + label: "상한선", + data: upperLineData, + showLine: true, + borderColor: "rgba(255, 99, 132, 0.8)", + pointRadius: 0, + }, + { + label: "하한선", + data: lowerLineData, + showLine: true, + borderColor: "rgba(54, 162, 235, 0.8)", + pointRadius: 0, + }, + { + label: "이상치", + data: outlierPoints, + backgroundColor: "rgba(255, 99, 132, 0.7)", + pointRadius: 4, + pointHoverRadius: 8, + }, + { + label: "정상", + data: normalPoints, + backgroundColor: "rgba(75, 192, 192, 0.7)", + pointRadius: 4, + pointHoverRadius: 8, + }, + ], + }; + + const axisRange = getUnifiedLinearRange(data); + + const options: ChartOptions<"scatter"> = { + responsive: true, + maintainAspectRatio: false, + onClick: (event, elements) => { + if (elements.length > 0) { + const element = elements[0]; + if (!element) return; + const datasetIndex = element.datasetIndex; + const index = element.index; + const dataset = data.datasets[datasetIndex]; + + if (!dataset) return; + + // 상한선/하한선 클릭 시 무시 + if (dataset.showLine) return; + + const pt = dataset.data[index] as DataPoint; + if (pt?.item?.rsltSn) { + onPointClick?.(pt.item.rsltSn); + } + } else { + onPointClick?.(null); + } + }, + plugins: { + zoom: { + pan: { + enabled: true, + mode: "xy", + }, + zoom: { + wheel: { + enabled: true, + }, + pinch: { + enabled: true, + }, + mode: "xy", + }, + }, + tooltip: { + callbacks: { + label: (context: TooltipItem<"scatter">) => { + const dataset = context.dataset; + if (dataset.showLine) { + return `${context.dataset.label}: (${context?.parsed?.x?.toFixed(2) ?? "-"}, ${context?.parsed?.y?.toFixed(2) ?? "-"})`; + } + + const pt = (context.raw as DataPoint) ?? {}; + return `${pt?.item?.sido ?? "시/도"} ${pt?.item?.gugun ?? "구/군"}: 이전(${pt?.x ?? "-"}), 당해(${pt?.y ?? "-"})`; + }, + }, + }, + }, + scales: { + x: { + type: "linear", + position: "bottom", + min: axisRange?.min, + max: axisRange?.max, + title: { + display: true, + text: "이전년도 값", + }, + }, + y: { + type: "linear", + min: axisRange?.min, + max: axisRange?.max, + title: { + display: true, + text: "당해년도 값", + }, + }, + }, + }; + + return { data, options }; + }, [ + resultData, + chartData, + appliedFilter.sido, + appliedFilter.gugun, + appliedFilter.status, + ]); + + return ( +
+ {!vrfcTrgtSn ? ( +
+ 항목을 선택해주세요 +
+ ) : isLoading ? ( +
+
+ +
+
+ ) : chartConfig ? ( +
+ +
+ ) : ( +
+ 표시할 데이터가 없습니다. +
+ )} +
+ ); +}; + +export default ScatterChart; diff --git a/apps/st/src/components/statistics/verification/detail/VerificationList.tsx b/apps/st/src/components/statistics/verification/detail/VerificationList.tsx new file mode 100644 index 000000000..3966b3131 --- /dev/null +++ b/apps/st/src/components/statistics/verification/detail/VerificationList.tsx @@ -0,0 +1,92 @@ +import React, { useEffect, useMemo } from "react"; + +import { useQuery } from "@tanstack/react-query"; +import { getCoreRowModel, useReactTable } from "@tanstack/react-table"; + +import { ENDPOINT } from "@/shared/config"; +import type { StAnlsDtlResponse } from "@/entities/statistics"; +import { getVerificationListColumns } from "@/entities/statistics"; +import { stAnlsDtlApi } from "@/entities/statistics/api/statistics-analysis-detail-api"; +import { DataTable } from "@common/components"; + +interface VerificationListProps { + anlsSn: number; + selectedVrfcTrgtSn: string | null; + onSelect: (row: StAnlsDtlResponse) => void; + checkedSns: string[]; + onCheck: (checkedSns: string[], rows: StAnlsDtlResponse[]) => void; +} + +const VerificationList: React.FC = ({ + anlsSn, + selectedVrfcTrgtSn, + onSelect, + checkedSns, + onCheck, +}) => { + const { data: detailData, isLoading } = useQuery({ + queryKey: [ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_DTL, "list", anlsSn], + queryFn: () => + stAnlsDtlApi.getDetailList({ anlsSn, page: 0, size: 100 }), + enabled: !!anlsSn, + }); + + const rowData = useMemo(() => { + return (detailData?.content ?? []) as StAnlsDtlResponse[]; + }, [detailData]); + + const columns = useMemo( + () => getVerificationListColumns({ rowData, checkedSns, onCheck }), + [rowData, checkedSns, onCheck], + ); + + const table = useReactTable({ + data: rowData, + columns, + state: { + rowSelection: selectedVrfcTrgtSn + ? { [selectedVrfcTrgtSn]: true } + : {}, + }, + enableMultiRowSelection: false, + getRowId: (row) => String(row.vrfcTrgtSn), + getCoreRowModel: getCoreRowModel(), + }); + + const handleRowClick = (row: StAnlsDtlResponse) => { + onSelect(row); + }; + + useEffect(() => { + if (!selectedVrfcTrgtSn && rowData.length > 0) { + const firstRow = rowData[0]; + if (firstRow) onSelect(firstRow); + } + }, [selectedVrfcTrgtSn, rowData, onSelect]); + + return ( +
+ {isLoading && ( +
+ 데이터를 불러오는 중... +
+ )} + {!isLoading && rowData.length === 0 && ( +
+ 표시할 항목이 없습니다. +
+ )} + {!isLoading && rowData.length > 0 && ( + + )} +
+ ); +}; + +export default VerificationList; diff --git a/apps/st/src/components/statistics/verification/generalVerification/CopyDialog.tsx b/apps/st/src/components/statistics/verification/generalVerification/CopyDialog.tsx new file mode 100644 index 000000000..556d3f54a --- /dev/null +++ b/apps/st/src/components/statistics/verification/generalVerification/CopyDialog.tsx @@ -0,0 +1,146 @@ +import { useState, useEffect } from "react"; + +import { + Button, + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, + DialogTrigger, + DialogClose, + Label, + Input, +} from "@common/components"; +import { CodeSelect } from "@/entities/code"; +import { useAlertStore } from "@/shared/lib"; +import { useConfirm } from "@frontend-opensource/use-react-hooks"; +import { getUserInfo } from "../../../../../../../packages/common/components/src/api"; +import { LoadingWithAnimation } from "@common/components"; + +import { generalverificationApiService } from "@/entities/statistics/api/general-verification-service"; + +import type { GeneralverificationList } from "@/entities/statistics/model/general-verification-interface"; + +interface CopyDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + children?: React.ReactNode; + row?: GeneralverificationList; + /** 수정/등록 성공 시 부모에서 목록 재조회 등 실행 */ + onSuccess?: () => void; +} + +const CopyDialog = ({ + children, + open, + onOpenChange, + row, + onSuccess, + ...props +}: CopyDialogProps) => { + + const [selectedCode, setSelectedCode] = useState(''); + const [isLoading, setIsLoading] = useState(false); + const { setMessage: alert } = useAlertStore((state) => state); + const { confirm } = useConfirm(); + + const handleChangeCode = (value: string) => { + if (row?.trgtStatsCd === value) { + alert('원본과 동일한 통계항목으로 복사할 경우\n복사 완료 후 검증 분류를 꼭 수정해주세요.'); + } + + setSelectedCode(value); + }; + + const handleCopyItem = async () => { + if (!selectedCode) { + alert('복사 대상 통계항목을 선택해주세요.'); + return; + } + + if (await confirm('복사하시겠습니까?')) { + try { + setIsLoading(true); + const userInfo = await getUserInfo(); + const response = await generalverificationApiService.CopyVrfcData({ + vrfcSn: row?.vrfcSn ?? null, + targetStatsCd: selectedCode ?? '', + rgtrId: userInfo.userUnqId + }); + + if (response.status === 'success') { + alert('복사되었습니다.'); + onOpenChange(false); + onSuccess?.(); + } else { + alert(response.message || '데이터 복사 중 오류가 발생했습니다.'); + } + } catch { + alert('데이터 복사 중 오류가 발생했습니다.') + } finally { + setIsLoading(false); + } + } + }; + + useEffect(() => { + if (!open) setSelectedCode(''); + }, [open]); + + return ( + + {children} + + + + {row?.vrfcNm} + + + {isLoading && +
+
+ +
+
+ } +
+
+ + +
+
+ + +
+
+ + + + + + +
+
+ ); +} + +export default CopyDialog; \ No newline at end of file diff --git a/apps/st/src/components/statistics/verification/generalVerification/DetailComponent.tsx b/apps/st/src/components/statistics/verification/generalVerification/DetailComponent.tsx new file mode 100644 index 000000000..0f9da9e01 --- /dev/null +++ b/apps/st/src/components/statistics/verification/generalVerification/DetailComponent.tsx @@ -0,0 +1,375 @@ +import { useEffect, useRef, useState } from 'react'; + +import { NoData } from '@/shared/ui/no-data'; +import { + Button, + Input, + Table, + TableBody, + TableCell, + TableHead, + TableRow, +} from "@common/components"; +import FormulaComponents from './FormulaComponents'; +import { LoadingWithAnimation } from '@common/components'; +import FomulaDialog from './FomulaDialog'; + +import { useAlertStore } from '@/shared/lib'; +import { useConfirm } from '@frontend-opensource/use-react-hooks'; + +import { generalverificationApiService } from '@/entities/statistics/api/general-verification-service'; +import type { VerifyDetailData, VerifyDetailResponseDto } from '@/entities/statistics/model/general-verification-interface'; +import { getUserInfo } from '../../../../../../../packages/common/components/src/api'; + +interface DetailComponentProps { + selectedVrfcRow: number | null; +} + +const DetailComponent = ({ selectedVrfcRow }: DetailComponentProps) => { + + const [detailInfo, setDetailInfo] = useState(null); + const [formulaList, setFormulaList] = useState<(VerifyDetailResponseDto | null)[]>([]); + const [hasPersistedDetails, setHasPersistedDetails] = useState(false); + const [isLoading, setIsLoading] = useState(false); + const [showFomulaDialog, setShowFomulaDialog] = useState(false); + const [selectedFormula, setSelectedFormula] = useState(null); + const [selectedFormulaIndex, setSelectedFormulaIndex] = useState(0); + const { confirm } = useConfirm(); + + const { setMessage: alert } = useAlertStore((state) => state); + + const persistedFormulaSignatureRef = useRef(''); + + const normalizeFormulaListForCompare = (list: (VerifyDetailResponseDto | null)[]) => { + return list.map((row) => + row + ? { + vrfcDtlSn: row.vrfcDtlSn ?? null, + refStatsCd: row.refStatsCd ?? null, + kornArtopnEqtnCn: row.kornArtopnEqtnCn ?? '', + engArtopnEqtnCn: row.engArtopnEqtnCn ?? '', + cmprOpert: row.cmprOpert ?? null, + } + : null, + ); + }; + + const handleSaveClick = async () => { + const trgtStatsCd = detailInfo?.commonInfo.trgtStatsCd; + if (!trgtStatsCd) { + alert('대상 통계항목(trgtStatsCd) 정보가 없습니다.'); + return; + } + const rows = formulaList.map((row, idx) => ({ + eqtnCombSeq: idx + 1, + trgtStatsCd, + refStatsCd: row?.refStatsCd ?? null, + kornArtopnEqtnCn: row?.kornArtopnEqtnCn ?? '', + engArtopnEqtnCn: row?.engArtopnEqtnCn ?? '', + cmprOpert: row?.cmprOpert ?? null, + })); + + const UNARY_TERMINAL_OPERATORS = new Set(['is_null', '!is_null', 'floor']); + const lastOperator = rows.at(-1)?.cmprOpert ?? null; + const lastIsUnary = rows.length > 0 && lastOperator != null && UNARY_TERMINAL_OPERATORS.has(lastOperator); + const isSingleUnaryFormula = rows.length === 1 && lastIsUnary; + + // 단항 연산자일 때만 row 1개 허용 + if (rows.length === 1 && !isSingleUnaryFormula) { + alert('해당 연산자는 최소 2개 항목이 필요합니다.'); + return; + } + + // 단항 연산자(is_null, !is_null, floor)는 반드시 맨 마지막 항목에만 허용 + if (rows.length > 1) { + const unaryAtWrongIdx = rows.findIndex( + (r, idx) => idx < rows.length - 1 && r.cmprOpert != null && UNARY_TERMINAL_OPERATORS.has(r.cmprOpert), + ); + if (unaryAtWrongIdx !== -1) { + alert(`단항 연산자(is_null, !is_null, floor)는 맨 마지막 항목에만 사용할 수 있습니다.\n(순번: ${unaryAtWrongIdx + 1})`); + return; + } + } + + const invalidIdx = rows.findIndex( + (r) => r.kornArtopnEqtnCn.trim().length === 0 || r.engArtopnEqtnCn.trim().length === 0, + ); + if (invalidIdx !== -1) { + alert(`수식이 비어있는 항목이 있습니다.\n(순번: ${invalidIdx + 1})`); + return; + } + + // 마지막이 단항 연산자가 아닐 때만: 마지막을 제외한 항목들은 연산자(cmprOpert) 필수 + if (rows.length > 1 && !lastIsUnary) { + const invalidOpertIdx = rows.slice(0, -1).findIndex((r) => r.cmprOpert == null); + if (invalidOpertIdx !== -1) { + alert(`연산자가 선택되지 않은 항목이 있습니다.\n(순번: ${invalidOpertIdx + 1})`); + return; + } + } + + // 여러 항목일 때 마지막이 단항 연산자면: 이전 항목들 연산자는 무조건 null + if (rows.length > 1 && lastIsUnary) { + for (let i = 0; i < rows.length - 1; i++) { + const prev = rows[i]; + if (prev) prev.cmprOpert = null; + } + setFormulaList((prev) => { + if (prev.length <= 1) return prev; + const next = prev.map((item, idx) => + idx < prev.length - 1 && item != null ? { ...item, cmprOpert: null } : item, + ); + return next; + }); + } + + // 마지막 항목의 연산자는 (단항 연산자 케이스 제외) 무조건 null 처리 + if (rows.length > 1 && !lastIsUnary) { + const lastRow = rows[rows.length - 1]; + if (lastRow) lastRow.cmprOpert = null; + setFormulaList((prev) => { + if (prev.length === 0) return prev; + const last = prev[prev.length - 1]; + if (!last) return prev; + if (last.cmprOpert == null) return prev; + const next = [...prev]; + next[next.length - 1] = { ...last, cmprOpert: null }; + return next; + }); + } + + if (await confirm('등록하시겠습니까?')) { + try { + const userInfo = await getUserInfo(); + let response; + + if (!hasPersistedDetails) { + response = await generalverificationApiService.RegistVrfcDetail({ vrfcSn: detailInfo?.commonInfo.vrfcSn ?? null, detailList: rows, rgtrId: userInfo.userUnqId }); + } else { + response = await generalverificationApiService.UpdateVrfcDetail({ vrfcSn: detailInfo?.commonInfo.vrfcSn ?? null, detailList: rows, mdfrId: userInfo.userUnqId }); + } + + if (response?.status === 'success') { + alert('등록되었습니다.'); + getVrfcDetail(); + } else { + alert(response?.message || '데이터 등록 중 오류가 발생했습니다.'); + } + } catch { + alert('데이터 등록 중 오류가 발생했습니다.'); + } + } + }; + + const getVrfcDetail = async () => { + try { + setIsLoading(true); + + const response = await generalverificationApiService.getVrfcDetail(selectedVrfcRow!); + + if (response.status === 'success') { + setDetailInfo(response.data); + const list = response.data.verifyDetailResponseDtoList; + setFormulaList(list?.length ? [...list] : [null]); + setHasPersistedDetails((list?.length ?? 0) > 0); + // "기존 데이터" 스냅샷(서버 응답 기준)을 시그니처로 저장 + persistedFormulaSignatureRef.current = JSON.stringify( + normalizeFormulaListForCompare(list?.length ? [...list] : [null]), + ); + } else { + alert(response.message || '데이터 조회 중 오류가 발생했습니다.'); + } + } catch { + alert('데이터 조회 중 오류가 발생했습니다.'); + } finally { + setIsLoading(false); + } + }; + + const handleClickVrfcDetail = (formula?: VerifyDetailResponseDto | null, index?: number) => { + setSelectedFormula(formula ?? null); + setSelectedFormulaIndex(index ?? 0); + setShowFomulaDialog(true); + }; + + const handleFormulaConfirm = (payload: { kornArtopnEqtnCn: string; engArtopnEqtnCn: string; refStatsCd: string | null }) => { + setFormulaList((prev) => { + const next = [...prev]; + const i = selectedFormulaIndex; + if (i < 0 || i >= next.length) return prev; + const item = next[i]; + next[i] = item + ? { + ...item, + kornArtopnEqtnCn: payload.kornArtopnEqtnCn, + engArtopnEqtnCn: payload.engArtopnEqtnCn, + refStatsCd: payload.refStatsCd, + } + : { + vrfcDtlSn: null, + refStatsCd: payload.refStatsCd, + refStatsNm: null, + kornArtopnEqtnCn: payload.kornArtopnEqtnCn, + engArtopnEqtnCn: payload.engArtopnEqtnCn, + cmprOpert: null, + }; + return next; + }); + setShowFomulaDialog(false); + setSelectedFormula(null); + }; + + const handleResetClick = async () => { + const currentSignature = JSON.stringify(normalizeFormulaListForCompare(formulaList)); + if (currentSignature === persistedFormulaSignatureRef.current) { + alert('변경된 내용이 없습니다.'); + return; + } + + if (await confirm(`변경 전 데이터로 리셋하시겠습니까?\n등록 완료된 데이터는 등록 전 데이터를 불러올 수 없습니다.`)) { + getVrfcDetail(); + } + }; + + useEffect(() => { + if (selectedVrfcRow != null) { + getVrfcDetail(); + } + }, [selectedVrfcRow]); + + return ( + <> +
+
+

검증 상세 정보

+
+
+ {selectedVrfcRow ? + isLoading ? +
+
+ +
+
+ : +
+ + + + + + + + + + 검증명 + {detailInfo?.commonInfo.vrfcNm ?? "-"} + 통계항목 + {detailInfo?.commonInfo.trgtStatsNm ?? "-"} + + + 검증분류 + {detailInfo?.commonInfo.vrfcClsfNm ?? "-"} + 소수점처리방식 + + {detailInfo?.commonInfo.dcptDigtCnt === 0 ? + '소수점 생략' + : + `${detailInfo?.commonInfo.dcptDigtCnt}자리에서 ${detailInfo?.commonInfo.dcptPrcsMthNm}` + } + + + +
+
+

수식 정보

+ {formulaList.map((data, index) => ( + { + setFormulaList((prev) => { + const next = [...prev]; + if (index < 0 || index >= next.length) return prev; + const current = next[index]; + const cmprOpert = v === 'none' ? null : v; + next[index] = current + ? { ...current, cmprOpert } + : { + vrfcDtlSn: null, + refStatsCd: null, + refStatsNm: null, + kornArtopnEqtnCn: '', + engArtopnEqtnCn: '', + cmprOpert, + }; + return next; + }); + }} + onDelete={() => { + setFormulaList((prev) => { + const next = prev.filter((_, i) => i !== index); + return next.length > 0 ? next : [null]; + }); + }} + handleFomulaDialog={(show, formula, idx) => { + if (show) handleClickVrfcDetail(formula, idx ?? index); + else setShowFomulaDialog(false); + }} + /> + ))} +
+
+ +
+
+ + +
+
+ : +
+ +
+ } +
+
+ { + setShowFomulaDialog(open); + if (!open) setSelectedFormula(null); + }} + data={selectedFormula} + trgtStatsCd={detailInfo?.commonInfo.trgtStatsCd} + trgtStatsNm={detailInfo?.commonInfo.trgtStatsNm} + onConfirm={handleFormulaConfirm} + /> + + ); +}; + +export default DetailComponent; \ No newline at end of file diff --git a/apps/st/src/components/statistics/verification/generalVerification/FomulaDialog.tsx b/apps/st/src/components/statistics/verification/generalVerification/FomulaDialog.tsx new file mode 100644 index 000000000..b2873d155 --- /dev/null +++ b/apps/st/src/components/statistics/verification/generalVerification/FomulaDialog.tsx @@ -0,0 +1,673 @@ +import { useEffect, useRef, useState } from "react"; + +import { + Button, + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, + DialogClose, + Textarea, + Skeleton, + Input, +} from "@common/components"; +import { CodeSelect } from "@/entities/code"; + +import { generalverificationApiService } from "@/entities/statistics/api/general-verification-service"; +import type { VerifyDetailResponseDto, VerifyColumnListResponseData, SelectedVerifyColumnListResponseData } from "@/entities/statistics/model/general-verification-interface"; + +import { useAlertStore } from "@/shared/lib"; + +export interface FomulaDialogConfirmPayload { + kornArtopnEqtnCn: string; + engArtopnEqtnCn: string; + /** 참조 통계코드 (선택 안 했으면 null) */ + refStatsCd: string | null; +} + +interface FomulaDialogProps { + open: boolean; + onOpenChange?: (open: boolean) => void; + data?: VerifyDetailResponseDto | null; + trgtStatsCd?: string; + trgtStatsNm?: string; + /** 확인 클릭 시 검사 통과 후 호출. 해당 행에 반영 후 다이얼로그 닫기는 부모에서 처리 */ + onConfirm?: (payload: FomulaDialogConfirmPayload) => void; +} + +const FomulaDialog = ({ open, onOpenChange, data, trgtStatsCd, trgtStatsNm, onConfirm }: FomulaDialogProps) => { + const [columnInfo, setColumnInfo] = useState(null); + const [selectedColumnInfo, setSelectedColumnInfo] = useState(null); + const [showCommonColumns, setShowCommonColumns] = useState(true); + const [showTargetColumns, setShowTargetColumns] = useState(true); + const [showRefColumns, setShowRefColumns] = useState(true); + const [commonColumnSearchValue, setCommonColumnSearchValue] = useState(''); + const [targetColumnSearchValue, setTargetColumnSearchValue] = useState(''); + const [refColumnSearchValue, setRefColumnSearchValue] = useState(''); + /** 참조 통계 - 다이얼로그 내부에서만 사용. 열 때마다 해당 행(data)의 저장값으로 초기화, 저장 시에만 부모에 반영 예정 */ + const [refStatsCdLocal, setRefStatsCdLocal] = useState(''); + /** 수식 = 토큰 배열. 한글명 중복 시 출처(공통/대상/참조)별 engColNm 보존 */ + const [formulaDisplaySegments, setFormulaDisplaySegments] = useState([]); + const [formulaValueSegments, setFormulaValueSegments] = useState([]); + /** 확인 클릭 시 검사 실패 메시지 (Textarea 아래 빨간 글씨) */ + const [formulaSaveError, setFormulaSaveError] = useState(null); + /** 참조 통계 변경 시 안내 메시지 */ + const [refStatsChangeNotice, setRefStatsChangeNotice] = useState(null); + + const formulaTextareaRef = useRef(null); + + const { setMessage: alert } = useAlertStore((state) => state); + + /** 다이얼로그에서 쓰는 기호 → 제출용 value. 백엔드 규격에 맞게 수정 가능 */ + const OPERATOR_SYMBOL_TO_VALUE: Record = { + '+': '+', + '-': '-', + '×': '*', + '%': '/', + '(': '(', + ')': ')', + }; + + /** 공통 → 대상 → 참조 순, 첫 등장 kornColNm만 사용 (로드/직접입력 시 파싱용) */ + const getKornToEngMapForParse = (): Map => { + const map = new Map(); + const refCols = selectedColumnInfo?.targetColumnInfo?.colList ?? columnInfo?.refColumnInfo?.colList ?? []; + [...(columnInfo?.commonColumnInfo ?? []), ...(columnInfo?.targetColumnInfo?.colList ?? []), ...refCols].forEach( + (item) => { + if (!map.has(item.kornColNm)) map.set(item.kornColNm, item.engColNm); + } + ); + return map; + }; + + /** 한글 수식 문자열을 토큰(표시/값) 배열로 파싱. 컬럼명은 longest match */ + const parseDisplayToSegments = (displayStr: string): { display: string[]; value: string[] } => { + if (displayStr.length === 0) return { display: [], value: [] }; + const kornToEng = getKornToEngMapForParse(); + const kornList = [...kornToEng.keys()].filter(Boolean).sort((a, b) => b.length - a.length); + const display: string[] = []; + const value: string[] = []; + let i = 0; + while (i < displayStr.length) { + let matched = false; + for (const korn of kornList) { + if (displayStr.slice(i, i + korn.length) === korn) { + display.push(korn); + value.push(kornToEng.get(korn) ?? korn); + i += korn.length; + matched = true; + break; + } + } + if (!matched) { + const ch = displayStr[i]; + if (ch != null) { + display.push(ch); + value.push(ch); + } + i += 1; + } + } + return { display, value }; + }; + + const handleFormulaKey = (val: string) => { + setFormulaSaveError(null); + if (val === 'backspace') { + setFormulaDisplaySegments((prev) => prev.slice(0, -1)); + setFormulaValueSegments((prev) => prev.slice(0, -1)); + } else if (val === 'ac') { + setFormulaDisplaySegments([]); + setFormulaValueSegments([]); + } else { + setFormulaDisplaySegments((prev) => [...prev, val]); + setFormulaValueSegments((prev) => [...prev, val]); + } + }; + + /** 컬럼 버튼: 한글 표시 + 해당 출처의 영문명 저장 (한글 중복 시에도 구분) */ + const handleFormulaColumn = (kornColNm: string, engColNm: string) => { + setFormulaSaveError(null); + setFormulaDisplaySegments((prev) => [...prev, kornColNm]); + setFormulaValueSegments((prev) => [...prev, engColNm]); + }; + + /** 제출/저장 시 사용할 영문 수식 (컬럼 engColNm + 연산자 기호 → value 치환) */ + const getFormulaValueForSubmit = (): string => + formulaValueSegments.map((seg) => OPERATOR_SYMBOL_TO_VALUE[seg] ?? seg).join(''); + + const OPERATORS = ['+', '-', '×', '/', '%'] as const; + const isOperator = (s: string) => s.length === 1 && (OPERATORS as readonly string[]).includes(s); + const isParen = (s: string) => s === '(' || s === ')'; + const isValueToken = (s: string) => + s.length > 1 || (s.length === 1 && !isOperator(s) && !isParen(s)); + const isDigit = (s: string) => s.length === 1 && /[0-9]/.test(s); + + /** 저장 시 수식 규칙 검사. 오류 시 메시지 반환, 통과 시 null */ + const validateFormulaForSave = (segments: string[]): string | null => { + if (segments.length === 0) return null; + + for (let i = 0; i < segments.length - 1; i++) { + const a = segments[i]; + const b = segments[i + 1]; + if (a != null && b != null && isValueToken(a) && isValueToken(b) && !(isDigit(a) && isDigit(b))) { + return '컬럼(또는 숫자) 사이에 더하기, 빼기, 나누기, 곱하기 기호가 있어야 합니다.'; + } + } + + // "(값)"도 하나의 값으로 취급: 값/닫는괄호 뒤에는 '(' 또는 값이 올 수 없고, 사이에 연산자가 있어야 함. + // 예: 컬럼(100), 값)(100) 같은 형태는 연산자 누락으로 간주 + for (let i = 0; i < segments.length - 1; i++) { + const a = segments[i]; + const b = segments[i + 1]; + if (a == null || b == null) continue; + // 연속 숫자(예: 50)는 예외 허용 + if (isDigit(a) && isDigit(b)) continue; + + const aIsValueBoundary = isValueToken(a) || a === ')'; + const bIsValueBoundary = b === '(' || isValueToken(b); + if (aIsValueBoundary && bIsValueBoundary) { + return '컬럼(또는 숫자) 사이에 더하기, 빼기, 나누기, 곱하기 기호가 있어야 합니다.'; + } + } + + const last = segments[segments.length - 1]; + if (last && isOperator(last)) { + return '수식은 기호로 끝날 수 없습니다. (닫는 괄호 제외)'; + } + + const stack: boolean[] = []; + for (let i = 0; i < segments.length; i++) { + const s = segments[i]; + if (s == null) continue; + if (s === '(') { + stack.push(false); + } else if (s === ')') { + if (stack.length === 0) return '닫는 괄호가 여는 괄호 없이 사용되었습니다.'; + const hadValue = stack.pop(); + if (!hadValue) return '괄호 안에 값이 있어야 합니다.'; + if (stack.length > 0) stack[stack.length - 1] = true; + } else if (stack.length > 0 && isValueToken(s)) { + stack[stack.length - 1] = true; + } + } + if (stack.length > 0) return '여는 괄호에 대응하는 닫는 괄호가 없습니다.'; + + return null; + }; + + const getVerifyColumnList = async () => { + try { + if (!trgtStatsCd) return; + let response; + + if (data?.vrfcDtlSn == null || data.vrfcDtlSn <= 0) { + response = await generalverificationApiService.getSelectedVerifyColumnList(trgtStatsCd) + } else { + response = await generalverificationApiService.getVerifyColumnList({ + trgtStatsCd, + vrfcDtlSn: data.vrfcDtlSn, + refStatsCd: data.refStatsCd, + }); + } + + + if (response?.status === 'success') { + setColumnInfo(response.data); + } else { + alert(response?.message || '데이터 조회 중 오류가 발생했습니다.'); + } + } catch { + alert('데이터 조회 중 오류가 발생했습니다.'); + } + }; + + const getSelectedVerifyColumnList = async (statsCd: string) => { + try { + const response = await generalverificationApiService.getSelectedVerifyColumnList(statsCd); + if (response?.status === 'success' && response.data) { + setSelectedColumnInfo({ + targetColumnInfo: response.data.targetColumnInfo ?? { statsCd: statsCd, colList: [] }, + commonColumnInfo: response.data.commonColumnInfo ?? [], + }); + } else { + setSelectedColumnInfo(null); + } + } catch { + setSelectedColumnInfo(null); + } + }; + + useEffect(() => { + if (open) { + setColumnInfo(null); + setSelectedColumnInfo(null); + } + if (open) void getVerifyColumnList(); + }, [open, trgtStatsCd, data?.vrfcDtlSn]); + + useEffect(() => { + if (open) setRefStatsCdLocal(data?.refStatsCd ?? ''); + }, [open, data?.refStatsCd, data?.vrfcDtlSn]); + + useEffect(() => { + if (!open) { + setSelectedColumnInfo(null); + setRefStatsCdLocal(''); + setFormulaDisplaySegments([]); + setFormulaValueSegments([]); + setFormulaSaveError(null); + setRefStatsChangeNotice(null); + } + }, [open]); + + useEffect(() => { + if (open) { + const str = data?.kornArtopnEqtnCn ?? ''; + const { display, value } = parseDisplayToSegments(str); + setFormulaDisplaySegments(display); + setFormulaValueSegments(value); + } + }, [open, data?.kornArtopnEqtnCn, data?.vrfcDtlSn]); + + /** + * 재오픈 직후에는 columnInfo가 아직 없어서 parseDisplayToSegments가 컬럼명을 매칭 못하고 + * 한글을 1글자씩 토큰화하는 경우가 있음. + * 컬럼 목록 로딩 후(= map이 채워진 후) "표시 문자열이 원본과 동일 + 값 토큰이 표시 토큰과 동일"한 케이스만 재파싱해서 + * engColNm 치환이 반영되도록 보정한다. + */ + useEffect(() => { + if (!open) return; + const src = data?.kornArtopnEqtnCn ?? ''; + if (!src) return; + + const displayJoined = formulaDisplaySegments.join(''); + const valueJoined = formulaValueSegments.join(''); + // 아직 컬럼 치환이 안 된 상태(= value가 display와 동일)에서만 재파싱 + if (displayJoined !== src) return; + if (valueJoined !== displayJoined) return; + + // 컬럼 목록이 준비된 이후에만 의미가 있음 + const hasColumns = + (columnInfo?.commonColumnInfo?.length ?? 0) > 0 || + (columnInfo?.targetColumnInfo?.colList?.length ?? 0) > 0 || + (columnInfo?.refColumnInfo?.colList?.length ?? 0) > 0 || + (selectedColumnInfo?.targetColumnInfo?.colList?.length ?? 0) > 0; + if (!hasColumns) return; + + const { display, value } = parseDisplayToSegments(src); + const nextDisplayJoined = display.join(''); + const nextValueJoined = value.join(''); + // 파싱 결과가 현재와 완전히 같으면 setState 반복으로 무한 렌더가 날 수 있으니 중단 + if (nextDisplayJoined === displayJoined && nextValueJoined === valueJoined) return; + // 컬럼 치환이 전혀 안 됐다면(= value가 display와 동일) 보정의 의미가 없으니 중단 + if (nextValueJoined === nextDisplayJoined) return; + + setFormulaDisplaySegments(display); + setFormulaValueSegments(value); + }, [ + open, + data?.kornArtopnEqtnCn, + columnInfo?.commonColumnInfo, + columnInfo?.targetColumnInfo?.colList, + columnInfo?.refColumnInfo?.colList, + selectedColumnInfo?.targetColumnInfo?.colList, + formulaDisplaySegments, + formulaValueSegments, + ]); + + useEffect(() => { + if (!open || columnInfo?.kornArtopnEqtnCn == null) return; + if (data?.kornArtopnEqtnCn !== columnInfo.kornArtopnEqtnCn) return; + const { display, value } = parseDisplayToSegments(columnInfo.kornArtopnEqtnCn); + setFormulaDisplaySegments(display); + setFormulaValueSegments(value); + }, [open, data?.kornArtopnEqtnCn, columnInfo?.kornArtopnEqtnCn]); + + const handleChangeRefStatsCd = (next: string) => { + if (!open) return; + + // 현재 refStatsCdLocal에 해당하는 참조 컬럼이 수식에 포함돼 있으면 변경을 막고 안내만 표시 + const currentRefCols = refColList ?? []; + const currentRefEngSet = new Set(currentRefCols.map((c) => c.engColNm).filter(Boolean)); + const hasCurrentRefToken = + currentRefEngSet.size > 0 && formulaValueSegments.some((seg) => currentRefEngSet.has(seg)); + + if (hasCurrentRefToken) { + setRefStatsChangeNotice('수식에 기존 참조 컬럼이 포함되어 있어 참조 통계를 변경할 수 없습니다. 먼저 해당 참조 컬럼을 제거해주세요.'); + return; + } + + setRefStatsChangeNotice(null); + setRefStatsCdLocal(next); + }; + + /** 참조 통계 선택 시 해당 통계의 컬럼 목록으로 교체 */ + useEffect(() => { + if (!open) return; + if (refStatsCdLocal) { + void getSelectedVerifyColumnList(refStatsCdLocal); + } else { + setSelectedColumnInfo(null); + } + }, [open, refStatsCdLocal]); + + /** 참조 컬럼: 선택한 참조 통계로 조회한 목록이 있으면 사용, 없으면 getVerifyColumnList 결과 사용 */ + const refColList = selectedColumnInfo?.targetColumnInfo?.colList ?? columnInfo?.refColumnInfo?.colList ?? []; + + const handleOpenChange = (nextOpen: boolean) => { + if (!nextOpen) { + setFormulaDisplaySegments([]); + setFormulaValueSegments([]); + setFormulaSaveError(null); + setSelectedColumnInfo(null); + setRefStatsCdLocal(''); + setCommonColumnSearchValue(''); + setTargetColumnSearchValue(''); + setRefColumnSearchValue(''); + } + onOpenChange?.(nextOpen); + }; + + const handleSearchColumn = (value: string, type: string) => { + if (type === 'common') { + setCommonColumnSearchValue(value); + } else if (type === 'target') { + setTargetColumnSearchValue(value); + } else { + setRefColumnSearchValue(value); + } + }; + + const normalizeSearch = (v: string) => v.replace(/\s+/g, "").toLowerCase(); + + const commonSearch = normalizeSearch(commonColumnSearchValue); + const commonColumns = columnInfo?.commonColumnInfo ?? []; + const filteredCommonColumns = + commonSearch.length > 0 + ? commonColumns.filter((c) => { + const korn = normalizeSearch(c.kornColNm ?? ''); + const eng = normalizeSearch(c.engColNm ?? ''); + return korn.includes(commonSearch) || eng.includes(commonSearch); + }) + : commonColumns; + + const targetSearch = normalizeSearch(targetColumnSearchValue); + const targetColumns = columnInfo?.targetColumnInfo?.colList ?? []; + const filteredTargetColumns = + targetSearch.length > 0 + ? targetColumns.filter((t) => { + const korn = normalizeSearch(t.kornColNm ?? ''); + const eng = normalizeSearch(t.engColNm ?? ''); + return korn.includes(targetSearch) || eng.includes(targetSearch); + }) + : targetColumns; + + const refSearch = normalizeSearch(refColumnSearchValue); + const filterdRefColumns = + refSearch.length > 0 + ? refColList.filter((r) => { + const korn = normalizeSearch(r.kornColNm ?? ''); + const eng = normalizeSearch(r.engColNm ?? ''); + return korn.includes(refSearch) || eng.includes(refSearch); + }) + : refColList; + + return ( + + + + + 수식 상세 정보 + + +
+
+
+

기호 및 숫자

+
+ + + + + + + {[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '⌫', 'AC'].map((n) => { + const keyVal = n !== 'AC' && n !== '⌫' ? String(n) : n === '⌫' ? 'backspace' : 'ac'; + return ( + + ); + })} +
+
+
+

수식 미리보기

+