260506_01_fst: First Commit

This commit is contained in:
2026-05-06 17:00:45 +09:00
parent dd5cac3d78
commit 934a71e47a
76 changed files with 9488 additions and 222 deletions

View File

@@ -3,7 +3,9 @@
<component name="MaterialThemeProjectNewConfig">
<option name="metadata">
<MTProjectMetadataState>
<option name="userId" value="-67d14294:19ddb8a68ca:-7fe5" />
<option name="migrated" value="true" />
<option name="pristineConfig" value="false" />
<option name="userId" value="-7d165310:19d50f53563:-7ff9" />
</MTProjectMetadataState>
</option>
</component>

View File

@@ -1,5 +0,0 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
<!-- END:nextjs-agent-rules -->

View File

@@ -1 +0,0 @@
@AGENTS.md

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -1,26 +0,0 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}

View File

@@ -1,65 +0,0 @@
import Image from "next/image";
export default function Home() {
return (
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black">
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={100}
height={20}
priority
/>
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
To get started, edit the page.tsx file.
</h1>
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
Looking for a starting point or more instructions? Head over to{" "}
<a
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={16}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
}

25
components.json Normal file
View File

@@ -0,0 +1,25 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "radix-nova",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"menuColor": "default",
"menuAccent": "subtle",
"registries": {}
}

View File

@@ -13,6 +13,16 @@ const eslintConfig = defineConfig([
"build/**",
"next-env.d.ts",
]),
{
rules: {
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/no-explicit-any": "warn",
"react-hooks/exhaustive-deps": "off",
"react/no-did-mount-set-state": "off",
"react/no-direct-mutation-state": "warn",
"react-hooks/set-state-in-effect":"off",
},
},
]);
export default eslintConfig;

View File

@@ -2,6 +2,8 @@ import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
output: "standalone",
reactCompiler: true,
};
export default nextConfig;

6258
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,24 +3,42 @@
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"dev": "next dev -p 6102",
"build": "next build",
"start": "next start",
"start": "next start -p 6102",
"lint": "eslint"
},
"dependencies": {
"@tanstack/react-query": "^5.90.21",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"crypto-js": "^4.2.0",
"echarts": "^6.0.0",
"echarts-for-react": "^3.0.5",
"exceljs": "^4.4.0",
"jotai": "^2.16.2",
"lucide-react": "^0.562.0",
"next": "16.2.4",
"radix-ui": "^1.4.3",
"react": "19.2.4",
"react-dom": "19.2.4"
"react-dom": "19.2.4",
"shadcn": "^4.1.0",
"sonner": "^2.0.7",
"tailwind-merge": "^3.5.0"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@tanstack/react-query-devtools": "^5.91.3",
"@types/crypto-js": "^4.2.2",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"babel-plugin-react-compiler": "1.0.0",
"eslint": "^9",
"eslint-config-next": "16.2.4",
"postcss": "^8.5.6",
"tailwindcss": "^4",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -1 +0,0 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

Before

Width:  |  Height:  |  Size: 391 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

Before

Width:  |  Height:  |  Size: 1.0 KiB

BIN
public/head_logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

Before

Width:  |  Height:  |  Size: 128 B

View File

@@ -1 +0,0 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

Before

Width:  |  Height:  |  Size: 385 B

View File

@@ -0,0 +1,9 @@
'use client'
const BridgePlatformPage = () => {
return (
<div>BridgePlatformPage</div>
)
}
export default BridgePlatformPage;

View File

@@ -0,0 +1,9 @@
'use client'
const ConsultingPage = () => {
return (
<div>ConsultingPage</div>
)
}
export default ConsultingPage;

View File

@@ -0,0 +1,10 @@
'use client'
const FireInvestigationPage = () => {
return (
<div>FireInvestigationPage</div>
)
}
export default FireInvestigationPage;

View File

@@ -0,0 +1,9 @@
'use client'
const InsuranceOperationPage = () => {
return (
<div>InsuranceOperationPage</div>
)
}
export default InsuranceOperationPage;

View File

@@ -0,0 +1,19 @@
import {cookies} from "next/headers";
import MainLayout from "@/components/layout/MainLayout";
const MainLayoutWrapper = async ({
children,
}: Readonly<{
children: React.ReactNode;
}>) => {
const cookieStore = await cookies();
const accessToken = cookieStore.get("access_token")?.value;
return(
<MainLayout>
{children}
</MainLayout>
);
}
export default MainLayoutWrapper;

View File

@@ -0,0 +1,7 @@
import {redirect} from "next/navigation";
const MainPage = () => {
redirect("/safety-inspection");
}
export default MainPage;

View File

@@ -0,0 +1,13 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutCategoryContext";
const SafetyInspectionPage = () => {
const { selectedDiv } = useLayoutFilter();
return (
<div>SafetyInspectionPage {selectedDiv}</div>
)
}
export default SafetyInspectionPage;

View File

@@ -0,0 +1,9 @@
'use client'
const BridgePage = () => {
return (
<div>test</div>
)
}
export default BridgePage;

View File

@@ -0,0 +1,28 @@
import {NextRequest, NextResponse} from "next/server";
import {createBackApi} from "@/lib/server-api";
import {LoginRequest, LoginResponse} from "@/types/auth";
import {serverEnv} from "@/lib/env.server";
import {errorToResponse} from "@/lib/http-util";
export const POST = async (req: NextRequest) => {
try {
const backApi = await createBackApi();
const body = (await req.json()) as LoginRequest;
const result = await backApi.post<LoginResponse>("/auth/login", body);
const res = NextResponse.json(result.user, { status: 200 });
res.cookies.set("access_token", result.accessToken, {
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 24 * 60 * 60, // 24시간
});
return res;
} catch (error : unknown) {
return errorToResponse(error);
}
}

View File

@@ -0,0 +1,30 @@
import {createBackApi} from "@/lib/server-api";
import {serverEnv} from "@/lib/env.server";
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {errorToResponse} from "@/lib/http-util";
export async function POST(
req: NextRequest,
context: RouteContext
) {
try {
const {slug = []} = await context.params;
const backApi = await createBackApi();
const [userId] = slug;
const res = NextResponse.json({ ok: true });
res.cookies.set("access_token", "", {
httpOnly: true,
secure: serverEnv.ENV === "prod",
sameSite: "lax",
path: "/",
maxAge: 0,
});
return res;
} catch (error: unknown) {
return errorToResponse(error);
}
}

579
src/app/globals.css Normal file
View File

@@ -0,0 +1,579 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@custom-variant dark (&:is(.dark *));
/* =============================
Tailwind v4 Theme Tokens
(shadcn/ui + custom tokens)
============================= */
@theme inline {
/* Fonts */
--font-sans: var(--font-sans);
--font-mono: var(--font-mono);
/* Radius scale */
--radius-sm: calc(var(--radius) - 4px);
--radius-md: calc(var(--radius) - 2px);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) + 4px);
--radius-2xl: calc(var(--radius) + 8px);
--radius-3xl: calc(var(--radius) + 12px);
--radius-4xl: calc(var(--radius) + 16px);
/* Core semantic colors */
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
/* Status */
--color-success: var(--success);
--color-warning: var(--warning);
--color-info: var(--info);
--color-chart-border: var(--chart-border);
/* Sidebar (shadcn sidebar tokens) */
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--font-heading: var(--font-sans);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
}
/* =============================
Base Tokens
============================= */
@layer base {
:root {
--radius: 0.75rem;
--content-font-size: 14px;
/* =============================
Brand Core
============================= */
--kfpa-black: #231f20;
--kfpa-gray-600: #d1d2d2;
--kfpa-gray-500: #dcdddd;
--kfpa-gray-400: #e5e6e6;
--kfpa-gray-300: #eceeee;
--kfpa-gray-200: #f3f4f4;
--kfpa-gray-100: #fafafa;
--kfpa-green-600: #00803e;
--kfpa-green-500: #159151;
--kfpa-green-400: #34a369;
--kfpa-green-300: #67bd8f;
--kfpa-green-200: #9bd7b6;
--kfpa-green-100: #ccebdc;
--kfpa-green-50: #e8f4ee;
--kfpa-red-600: #ed1c24;
--kfpa-red-500: #a8172f;
--kfpa-red-400: #c1203b;
--kfpa-red-300: #d94060;
--kfpa-red-200: #e8748a;
--kfpa-red-100: #f2a8b5;
--kfpa-red-50: #fae6ea;
/* =============================
Surface
============================= */
--background: #f7f8f8;
--foreground: #231f20;
--card: #ffffff;
--card-foreground: #231f20;
--popover: #ffffff;
--popover-foreground: #231f20;
/* =============================
Semantic
============================= */
/* primary: brand red */
--primary: #ed1c24;
--primary-foreground: #ffffff;
/* secondary: brand black */
--secondary: #231f20;
--secondary-foreground: #ffffff;
/* muted: light gray background */
--muted: #f3f4f4;
--muted-foreground: #646464;
/* accent: light red tint */
--accent: #fae6ea; /* kfpa-red-50 */
--accent-foreground: #ed1c24; /* kfpa-red-600 */
/* =============================
Status Colors
============================= */
--success: #1a7f3c;
--warning: #c47d00;
--info: #0072a3;
--destructive: #c1203b; /* kfpa-red-400 */
/* Excel */
--excel: #1d6f42;
--excel-foreground: #ffffff;
/* =============================
Borders / Ring
============================= */
--border: #e5e6e6;
--input: #d1d2d2;
--ring: #ed1c24; /* kfpa-red-600 */
/* =============================
Chart Colors
Series:
1~3 red
4 black
5~6 gray
7~10 support colors
Stack:
1~6 red scale
7 black
8~10 gray scale
============================= */
--chart-1: #ed1c24; /* red-600 */
--chart-2: #c1203b; /* red-400 */
--chart-3: #e8748a; /* red-200 */
--chart-4: #231f20; /* black */
--chart-5: #d1d2d2; /* gray-600 */
--chart-6: #e5e6e6; /* gray-400 */
--chart-7: #00803e; /* green-600 */
--chart-8: #c47d00; /* warning amber */
--chart-9: #0072a3; /* info blue */
--chart-10: #3c3c3c; /* gray-700 */
--chart-stack-1: #ed1c24; /* red-600 */
--chart-stack-2: #a8172f; /* red-500 */
--chart-stack-3: #c1203b; /* red-400 */
--chart-stack-4: #d94060; /* red-300 */
--chart-stack-5: #e8748a; /* red-200 */
--chart-stack-6: #fae6ea; /* red-50 */
--chart-stack-7: #231f20; /* black */
--chart-stack-8: #d1d2d2; /* gray-600 */
--chart-stack-9: #e5e6e6; /* gray-400 */
--chart-stack-10: #f3f4f4; /* gray-200 */
--chart-border: #ebebeb;
/* =============================
Sidebar
============================= */
--sidebar: #ffffff;
--sidebar-foreground: #231f20;
--sidebar-primary: #ed1c24;
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #f3f4f4;
--sidebar-accent-foreground: #231f20;
--sidebar-border: #e5e6e6;
--sidebar-ring: #ed1c24;
}
/* =============================
Dark Mode
============================= */
.dark {
/* Surface */
--background: #1a1614;
--foreground: #f0eeec;
--card: #231f1d;
--card-foreground: #f0eeec;
--popover: #231f1d;
--popover-foreground: #f0eeec;
/* primary */
--primary: #e03355;
--primary-foreground: #ffffff;
/* secondary */
--secondary: #a0a0a0; /* gray-300 */
--secondary-foreground: #1e1e1e;
/* muted */
--muted: #2c2928;
--muted-foreground: #a0a0a0; /* gray-300 */
/* accent */
--accent: #3a1f24;
--accent-foreground: #f2a8b5; /* red-100 */
/* Status */
--success: #28a852;
--warning: #f0a000;
--info: #00a0d4;
--destructive: #e03355;
/* Excel */
--excel: #28a852;
--excel-foreground: #ffffff;
/* Borders / Ring */
--border: #3a3330;
--input: #3a3330;
--ring: #ed1c24;
/* Chart */
--chart-1: #e03355;
--chart-2: #d94060;
--chart-3: #f2a8b5; /* red-100 */
--chart-4: #7e7e7e; /* gray-400 */
--chart-5: #c8c8c8; /* gray-200 */
--chart-6: #4f4f4f; /* gray-600 */
--chart-7: #28a852;
--chart-8: #f0a000;
--chart-9: #00a0d4;
--chart-10: #a0a0a0;
--chart-stack-1: #e03355;
--chart-stack-2: #c1203b;
--chart-stack-3: #d94060;
--chart-stack-4: #e8748a;
--chart-stack-5: #f2a8b5;
--chart-stack-6: #3a1f24;
--chart-stack-7: #f0eeec;
--chart-stack-8: #a0a0a0;
--chart-stack-9: #646464;
--chart-stack-10: #3c3c3c;
--chart-border: #3a3330;
/* Sidebar */
--sidebar: #231f1d;
--sidebar-foreground: #f0eeec;
--sidebar-primary: #ed1c24;
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #3a1f24;
--sidebar-accent-foreground: #f0eeec;
--sidebar-border: #3a3330;
--sidebar-ring: #ed1c24;
}
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
html {
@apply font-sans;
}
}
/* =============================
Convenience Classes
(project compatibility)
============================= */
* { border-color: var(--border); }
/* Token based bg/text */
.bg-white-hover { background-color: #fff; }
.bg-white-hover:hover {
background-color: var(--primary);
color: #fff;
}
.bg-background { background-color: var(--background); }
.bg-card { background-color: var(--card); }
.bg-primary { background-color: var(--primary); }
.bg-secondary { background-color: var(--secondary); }
.bg-accent { background-color: var(--accent); }
.bg-muted { background-color: var(--muted); }
.bg-success { background-color: var(--success); }
.bg-warning { background-color: var(--warning); }
.bg-info { background-color: var(--info); }
.bg-destructive { background-color: var(--destructive); }
.bg-excel { background-color: var(--excel); }
.text-foreground { color: var(--foreground); }
.text-primary { color: var(--primary); }
.text-secondary { color: var(--secondary); }
.text-secondary-hover { color: var(--secondary); }
.text-secondary-hover:hover { color: var(--primary) !important; }
.text-primary-foreground { color: var(--primary-foreground); }
.text-muted-foreground { color: var(--muted-foreground); }
.text-success { color: var(--success); }
.text-warning { color: var(--warning); }
.text-info { color: var(--info); }
.text-destructive { color: var(--destructive); }
.text-excel { color: var(--excel); }
.text-excel-foreground { color: var(--excel-foreground); }
.border-border { border-color: var(--border); }
/* KFPA neutral scale */
.bg-black { background-color: var(--kfpa-black) !important; }
.bg-gray-600 { background-color: var(--kfpa-gray-600) !important; }
.bg-gray-500 { background-color: var(--kfpa-gray-500) !important; }
.bg-gray-400 { background-color: var(--kfpa-gray-400) !important; }
.bg-gray-300 { background-color: var(--kfpa-gray-300) !important; }
.bg-gray-200 { background-color: var(--kfpa-gray-200) !important; }
.bg-gray-100 { background-color: var(--kfpa-gray-100) !important; }
.border-gray-600 { border-color: var(--kfpa-gray-600) !important; }
.border-gray-500 { border-color: var(--kfpa-gray-500) !important; }
.border-gray-400 { border-color: var(--kfpa-gray-400) !important; }
.border-gray-300 { border-color: var(--kfpa-gray-300) !important; }
.border-gray-200 { border-color: var(--kfpa-gray-200) !important; }
.border-gray-100 { border-color: var(--kfpa-gray-100) !important; }
/* KFPA Red scale */
.bg-red-600 { background-color: var(--kfpa-red-600) !important; }
.bg-red-500 { background-color: var(--kfpa-red-500) !important; }
.bg-red-400 { background-color: var(--kfpa-red-400) !important; }
.bg-red-300 { background-color: var(--kfpa-red-300) !important; }
.bg-red-200 { background-color: var(--kfpa-red-200) !important; }
.bg-red-100 { background-color: var(--kfpa-red-100) !important; }
.bg-red-50 { background-color: var(--kfpa-red-50) !important; }
/* KFPA Green scale */
.bg-green-600 { background-color: var(--kfpa-green-600) !important; }
.bg-green-500 { background-color: var(--kfpa-green-500) !important; }
.bg-green-400 { background-color: var(--kfpa-green-400) !important; }
.bg-green-300 { background-color: var(--kfpa-green-300) !important; }
.bg-green-200 { background-color: var(--kfpa-green-200) !important; }
.bg-green-100 { background-color: var(--kfpa-green-100) !important; }
.bg-green-50 { background-color: var(--kfpa-green-50) !important; }
/* =============================
Content Text Size Utilities
============================= */
.content-text-xs { font-size: calc(var(--content-font-size) * 0.75); }
.content-text-sm { font-size: calc(var(--content-font-size) * 0.875); }
.content-text-base { font-size: calc(var(--content-font-size) * 1); }
.content-text-lg { font-size: calc(var(--content-font-size) * 1.125); }
.content-text-xl { font-size: calc(var(--content-font-size) * 1.25); }
.content-text-2xl { font-size: calc(var(--content-font-size) * 1.5); }
.content-text-3xl { font-size: calc(var(--content-font-size) * 1.875); }
.content-text-4xl { font-size: calc(var(--content-font-size) * 2.25); }
@layer utilities {
.placeholder-content-text-xs::placeholder { font-size: calc(var(--content-font-size) * 0.75); }
.placeholder-content-text-sm::placeholder { font-size: calc(var(--content-font-size) * 0.875); }
.placeholder-content-text-base::placeholder { font-size: calc(var(--content-font-size) * 1); }
.placeholder-content-text-lg::placeholder { font-size: calc(var(--content-font-size) * 1.125); }
.placeholder-content-text-xl::placeholder { font-size: calc(var(--content-font-size) * 1.25); }
.placeholder-content-text-2xl::placeholder { font-size: calc(var(--content-font-size) * 1.5); }
.placeholder-content-text-3xl::placeholder { font-size: calc(var(--content-font-size) * 1.875); }
.placeholder-content-text-4xl::placeholder { font-size: calc(var(--content-font-size) * 2.25); }
.bg-kfpa-login-body {
background-color: var(--background);
background-image: linear-gradient(
135deg,
color-mix(in srgb, var(--kfpa-black) 12%, transparent) 0%,
var(--background) 30%,
var(--background) 70%,
color-mix(in srgb, var(--kfpa-black) 12%, transparent) 100%
);
}
.app-header {
background: #ffffff;
border-bottom: 1px solid rgba(35, 31, 32, 0.08);
box-shadow: 0 4px 14px rgba(35, 31, 32, 0.08);
}
.app-sidebar {
background: #ffffff;
border-right: 1px solid rgba(35, 31, 32, 0.08);
box-shadow: 4px 0 14px rgba(35, 31, 32, 0.06);
}
.text-header-color { color: var(--kfpa-black); }
.text-header-primary {
color: var(--kfpa-black);
font-weight: 600;
position: relative;
padding-bottom: 4px;
}
.text-header-primary::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 3px;
background: linear-gradient(90deg, var(--kfpa-red-600) 0%, #ffffff 100%);
border-radius: 2px 2px 0 0;
}
.text-header-secondary-hover {
color: #4f4f4f;
transition: all 0.3s ease;
cursor: pointer;
}
.text-header-secondary-hover:hover {
color: var(--kfpa-black) !important;
}
.bg-kfpa-main-body {
background-color: var(--background);
background-image: linear-gradient(
135deg,
color-mix(in srgb, var(--kfpa-black) 5%, transparent) 0%,
var(--background) 30%,
var(--background) 70%,
color-mix(in srgb, var(--kfpa-black) 5%, transparent) 100%
);
}
}
/* =============================
KFPA Components
(Table / Category Card)
============================= */
@layer components {
.kfpa-table {
width: 100%;
min-width: 980px;
border-collapse: collapse;
table-layout: fixed;
border: 0px !important;
border-bottom: 3px solid var(--kfpa-gray-200) !important;
}
.kfpa-table th,
.kfpa-table td {
border: 1px solid var(--kfpa-gray-200) !important;
padding: 10px 12px;
font-size: 13px;
line-height: 1.15;
text-align: center;
word-wrap: break-word;
word-break: auto-phrase;
}
.kfpa-table thead tr.kfpa-table__group th {
background: var(--kfpa-gray-400);
color: var(--kfpa-black);
font-weight: 700;
}
.kfpa-table thead tr.kfpa-table__subhead th {
background: var(--kfpa-gray-600);
color: var(--kfpa-black);
font-weight: 700;
}
.kfpa-table tbody th.kfpa-table__rowhead {
text-align: left;
font-weight: 700;
color: var(--foreground);
background: var(--background);
word-wrap: break-word;
word-break: auto-phrase;
}
.kfpa-table .kfpa-table__sep-l {
border-left: 3px solid var(--kfpa-gray-200) !important;
}
.kfpa-table .kfpa-table__sep-r {
border-right: 3px solid var(--kfpa-gray-200) !important;
}
.kfpa-num-pos {
color: var(--destructive);
font-weight: 700;
}
.kfpa-num-neg {
color: #1d4ed8;
font-weight: 700;
}
.kfpa-tab-content {
position: relative;
background: #fff;
border: 2px solid var(--kfpa-gray-300) !important;
border-radius: 0px 10px 10px 10px;
padding: 18px;
box-shadow: 0 6px 14px rgba(0, 0, 0, 0.25);
display: flex;
flex-direction: column;
min-height: 0;
}
.kfpa-category-card {
position: relative;
background: #fff;
border: 2px solid var(--kfpa-gray-300) !important;
border-radius: 10px;
padding: 18px;
box-shadow: 0 6px 14px rgba(0, 0, 0, 0.25);
}
.kfpa-category-card__label {
position: absolute;
top: -16px;
left: 16px;
background: var(--kfpa-black);
color: #fff;
padding: 6px 16px;
border-radius: 9999px;
font-weight: 800;
font-size: 13px;
letter-spacing: -0.02em;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.18);
}
.kfpa-category-card__slot {
height: 240px;
width: 100%;
}
.dark .kfpa-category-card {
background: var(--card);
border-color: var(--kfpa-gray-600) !important;
}
}

View File

@@ -1,6 +1,8 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import {AppProvider} from "@/components/providers/AppProvider";
import {Toaster} from "sonner";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -13,8 +15,8 @@ const geistMono = Geist_Mono({
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: "화재보험협회 대시보드",
description: "화재보험협회 CX 대시보드",
};
export default function RootLayout({
@@ -23,11 +25,11 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
>
<body className="min-h-full flex flex-col">{children}</body>
</html>
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
<AppProvider>{children}</AppProvider>
<Toaster />
</body>
</html>
);
}

View File

@@ -0,0 +1,230 @@
import {ChartData, NewNumber} from "@/components/chart/types";
import {AXIS_HIDE_Y_STYLE, BAR_WIDTHS, CHART_GRID_DEFAULTS} from "@/components/chart/chart.config";
export function reverseCategories<T extends ChartData>(data: T): T {
const categories = [...data.categories].reverse();
const series = data.series.map((s) => ({
...s,
data: [...s.data].reverse(),
}));
return { ...data, categories, series };
}
export function reverseSeries<T extends ChartData>(data: T): T {
return {
...data,
series: [...data.series].reverse(),
};
}
/**
* 기본 Tooltip 옵션 생성
* @param valueFormatter - 값 포맷터 함수 (기본값: 정수는 그대로, 소수는 toLocaleString)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createDefaultTooltip(
valueFormatter?: (v: number) => string,
overrides?: any
): any {
const defaultFmt = (v: number) =>
Number.isInteger(v) ? String(v) : v.toLocaleString();
return {
trigger: "axis",
axisPointer: { type: "shadow" },
valueFormatter: (v: unknown) =>
typeof v === "number" ? (valueFormatter ?? defaultFmt)(v) : String(v),
...overrides,
};
}
/**
* 기본 Legend 옵션 생성
* @param overrides - 추가/덮어쓸 옵션
*/
export function createDefaultLegend(
overrides?: any
): any {
return {
...overrides,
top: 0,
};
}
export function createReverseLegend(
originalData: ChartData,
overrides?: any
): any {
const order = originalData.series.map((s) => s.name);
return createDefaultLegend({
...overrides,
data: order,
});
}
export function createReverseTooltip(
originalData: ChartData,
valueFormatter?: (v: number) => string,
overrides?: any
): any {
const order = originalData.series.map((s) => s.name);
// 기본 tooltip 생성(내부 defaultFmt 포함)
const base = createDefaultTooltip(valueFormatter, overrides);
const fmt = base.valueFormatter ?? ((v: unknown) => String(v));
const extractVal = (p: any): unknown => {
const v = p?.value;
if (typeof v === "number") return v;
if (Array.isArray(v)) return v[v.length - 1]; // dataset/encode 케이스 대비
if (typeof p?.data === "number") return p.data;
if (p?.data && typeof p.data.value === "number") return p.data.value;
return v;
};
return {
...base,
formatter: (params: any) => {
const arr = Array.isArray(params) ? params : [params];
if (arr.length === 0) return "";
const title = arr[0]?.axisValueLabel ?? arr[0]?.name ?? "";
const byName = new Map<string, any>();
for (const p of arr) byName.set(p.seriesName, p);
const lines = order
.map((name) => byName.get(name))
.filter(Boolean)
.map((p) => {
const v = extractVal(p);
const printed =
typeof v === "number" ? fmt(v) : v == null ? "-" : String(v);
return `${p.marker ?? ""}${p.seriesName} ${printed}`;
});
return [title, ...lines].join("<br/>");
},
};
}
/**
* 기본 Grid 옵션 생성
* @param preset - 프리셋 타입 (default | compact)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createDefaultGrid(
preset: "default" | "compact" = "default",
overrides?: any
): any {
const base =
preset === "compact"
? CHART_GRID_DEFAULTS.COMPACT
: CHART_GRID_DEFAULTS.DEFAULT;
return {
...base,
...overrides,
};
}
/**
* Category Axis 옵션 생성
* @param data - 카테고리 데이터 배열
* @param hideStyle - 축 스타일 숨김 여부 (라벨, 틱, 라인 등)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createCategoryAxis(
data: string[],
hideStyle?: boolean,
overrides?: any
): any {
const base: any = {
type: "category",
data,
};
if (hideStyle) {
return {
...base,
axisLabel: { show: false },
axisTick: { show: false },
axisLine: { show: false },
splitLine: { show: false },
...overrides,
};
}
return {
...base,
...overrides,
};
}
/**
* Value Axis 옵션 생성
* @param hideStyle - 축 스타일 숨김 여부 (라벨, 틱, 라인 등)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createValueAxis(
hideStyle?: boolean,
overrides?: any
): any {
const base: any = {
type: "value",
};
if (hideStyle) {
return {
...base,
...AXIS_HIDE_Y_STYLE,
splitLine: { show: false },
...overrides,
};
}
return {
...base,
...overrides,
};
}
/**
* Bar 시리즈 기본 옵션 생성
* @param name - 시리즈 이름
* @param data - 데이터 배열
* @param options - 추가 옵션 (stack, barMaxWidth 등)
*/
export function createBarSeries(
name: string,
data: NewNumber[],
options?: {
stack?: string;
barMaxWidth?: number;
emphasis?: boolean;
label?: object;
}
): {
name: string;
type: "bar";
data: NewNumber[];
stack?: string;
barMaxWidth?: number;
emphasis?: { disabled: boolean };
label?: object;
} {
const { stack, barMaxWidth, emphasis = false, label } = options ?? {};
return {
name,
type: "bar",
data,
...(stack && { stack }),
barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT,
emphasis: { disabled: !emphasis },
...(label && { label }),
};
}

View File

@@ -0,0 +1,70 @@
/**
* 차트 기본 높이 설정
*/
export const CHART_HEIGHTS = {
DEFAULT: "100%",
COMPACT: 200,
EXPANDED: 320,
} as const;
/**
* Bar 차트의 Bar 너비 설정
*/
export const BAR_WIDTHS = {
DEFAULT: 42,
NARROW: 30,
WIDE: 60,
} as const;
/**
* 차트 Grid 기본 패딩 설정
*/
export const CHART_GRID_DEFAULTS = {
DEFAULT: {
left: 16,
right: 16,
top: 36,
bottom: 12,
containLabel: true,
},
COMPACT: {
left: 10,
right: 10,
top: 20,
bottom: 8,
containLabel: true,
},
} as const;
/**
* Legend 아이템 크기 설정 (GroupedOverlayBar, GroupedStackBar에서 사용)
*/
export const LEGEND_ITEM_SIZE = {
WIDTH: 25,
HEIGHT: 14,
RADIUS: 4,
} as const;
/**
* 테이블 크기 설정
*/
export const TABLE_DIMENSIONS = {
CELL_HEIGHT: {
DEFAULT: 26,
COMPACT: 20,
EXPANDED: 32,
},
MIN_WIDTH: {
STANDARD: 1600,
COMPACT: 1200,
WIDE: 2000,
},
} as const;
/** X 축 패딩 없앤 GridOption*/
export const GRID_X_NOT_PADDING = { left: 0, right: 0, top: 50, bottom: 10, containLabel: false } as const;
/** T 축 패딩 없앤 GridOption*/
export const GRID_Y_NOT_PADDING = { left: 10, right: 10, top: 0, bottom: 0, containLabel: false } as const;
/** 축 스타일 감춤 */
export const AXIS_HIDE_STYLE = { axisLabel: { show: false }, axisTick: { show: false }, axisLine: { show: false }} as const;
export const AXIS_HIDE_Y_STYLE = { min:0, max:100, axisLabel: { show: false }, axisTick: { show: false }, axisLine: { show: false }} as const;

View File

@@ -0,0 +1,17 @@
export type NewNumber = number | null | undefined;
export type ChartSeries = {
/** legend에 노출될 이름 */
name: string;
/** categories와 동일 길이 */
data: NewNumber[];
/** stacked bar 용 */
stack?: string; // 같은 stack 값끼리 누적
};
export type ChartData = {
/** x(세로바)/y(가로바) 카테고리 */
categories: string[];
/** 시리즈(막대/스택 등) */
series: ChartSeries[];
};

View File

@@ -0,0 +1,17 @@
"use client";
import { useAtomValue } from "jotai";
import { loadingAtom } from "@/store/jotai/loading";
export function LoadingOverlay({ force = false }: { force?: boolean }) {
const isLoading = useAtomValue(loadingAtom);
if (!force && !isLoading) return null;
return (
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
{/* 심플 로딩 인디케이터 */}
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
</div>
);
}

View File

@@ -0,0 +1,19 @@
"use client";
import {useIsFetching} from "@tanstack/react-query";
import {useLoading} from "@/hooks/useLoading";
import {useEffect} from "react";
const ReactQueryLoadingSync = () => {
const fetching = useIsFetching();
const { showLoading, hideLoading } = useLoading();
useEffect(() => {
if (fetching > 0) showLoading();
else hideLoading();
}, [fetching, showLoading, hideLoading]);
return null;
};
export default ReactQueryLoadingSync;

View File

@@ -0,0 +1,164 @@
'use client'
import {useEffect, useRef, useState} from "react";
import {apiError} from "@/lib/http-util";
import {NONE_HTTP_ERROR} from "@/const/commonConst";
import {DialogId} from "@/store/jotai/dialog";
import {useDialog} from "@/hooks/useDialog";
import {useLoginMutation} from "@/query/auth";
import {Input} from "@/components/ui/input";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle
} from "@/components/ui/dialog";
import {Button} from "@/components/ui/button";
export type LoginDialogProps = {
/** Jotai로 관리할 다이얼로그 ID */
dialogId?: DialogId
/** 필요하면 외부에서 open 상태를 제어할 수 있게 함 */
open?: boolean
onOpenChange?: (open: boolean) => void
}
const LoginDialog = ({
dialogId = 'loginDialog',
open,
onOpenChange,
}: LoginDialogProps) => {
const { isDialogOpen, showDialog, hideDialog } = useDialog();
const resolvedOpen = open ?? isDialogOpen(dialogId);
const loginMutation = useLoginMutation();
const [error, setError] = useState<string | null>(null);
const [userId, setUserId] = useState<string>("");
const [userPw, setUserPw] = useState<string>("");
const passwordInputRef = useRef<HTMLInputElement | null>(null);
const handleOpenChange = (nextOpen: boolean) => {
onOpenChange?.(nextOpen);
if (nextOpen) {
showDialog(dialogId);
setUserId("");
setUserPw("");
setError(null);
} else {
hideDialog(dialogId);
}
}
const handleIdKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
passwordInputRef.current?.focus();
}
};
const handlePwKeyDown: React.KeyboardEventHandler<HTMLInputElement> = (e) => {
if (e.key === "Enter") {
e.preventDefault();
tryLogin();
}
};
const tryLogin = async () => {
if (!userId) return alert("아이디를 입력해 주세요.");
if (!userPw) return alert("비밀번호를 입력해 주세요.");
setError(null);
try {
await loginMutation.mutateAsync({ userId, userPw });
handleOpenChange(false);
} catch (e) {
const err = apiError(e);
if (err.status === 401 || err.status === 403) {
setError("아이디 또는 비밀번호를 다시 확인해 주세요.");
} else if (err.code === NONE_HTTP_ERROR) {
setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
} else {
setError(`로그인에 실패했습니다. (${err.message})`);
}
}
}
useEffect(() => {
setUserId("");
setUserPw("");
setError(null);
}, [resolvedOpen])
return (
<Dialog open={resolvedOpen} onOpenChange={handleOpenChange}>
<DialogContent className="sm:max-w-[500px] content-text-sm">
<DialogHeader>
<DialogTitle className="content-text-sxl">
로그인
</DialogTitle>
</DialogHeader>
<div className="grid gap-6 py-4">
<div className="grid gap-2">
<label className="text-sm font-medium">ID</label>
<Input
id="id"
name="id"
type="text"
className="mt-1"
required
placeholder="아이디를 입력하세요."
value={userId}
onChange={(e) => setUserId(e.currentTarget.value)}
onKeyDown={handleIdKeyDown}
/>
</div>
<div className="grid gap-2">
<label className="text-sm font-medium">Password</label>
<Input
id="password"
name="password"
type="password"
className="mt-1"
autoComplete="current-password"
required
placeholder="비밀번호를 입력하세요."
value={userPw}
onChange={(e) => setUserPw(e.currentTarget.value)}
onKeyDown={handlePwKeyDown}
ref={passwordInputRef}
/>
</div>
{error && (
<p className="text-sm text-destructive">
{error}
</p>
)}
</div>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => handleOpenChange(false)}
>
취소
</Button>
<Button
type="submit"
onClick={tryLogin}
disabled={loginMutation.isPending}
>
로그인
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
export default LoginDialog

View File

@@ -0,0 +1,99 @@
'use client'
import Image from "next/image";
import {Button} from "@/components/ui/button";
import {LogIn, LogOut} from "lucide-react";
import {cn} from "@/lib/utils";
import {SITE_TITLE} from "@/config/kfpaConfig";
import {TopMenuItem} from "@/config/menu.type";
import {usePathname} from "next/navigation";
interface HeaderProps {
topMenus: TopMenuItem[];
userName: string;
isAuthenticated: boolean;
onNavigate: (path: string) => void;
onLogin: () => void;
onLogout: () => void;
}
const Header = ({
topMenus,
userName,
isAuthenticated,
onNavigate,
onLogin,
onLogout,
}: HeaderProps) => {
const pathname = usePathname();
return (
<header className="app-header sticky top-0 z-40">
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center gap-4 px-4 h-16">
<div className="flex min-w-0 items-center gap-4">
<div className="flex items-center gap-2 cursor-pointer w-37 h-15 justify-center">
<Image
src="/head_logo.png"
alt="logo"
width={150}
height={90}
className="object-contain"
onClick={() => onNavigate("/safety-inspection")}
priority
/>
</div>
<nav className="flex min-w-0 items-center gap-3 ml-5 overflow-hidden">
{topMenus.map((topMenu) => {
const active = topMenu.match?.(pathname) ?? pathname === topMenu.path;
return (
<button
key={topMenu.id}
type="button"
onClick={() => onNavigate(topMenu.path)}
className={cn(
"relative h-8 inline-flex items-center font-bold transition-colors cursor-pointer",
"content-text-lg bg-transparent px-1",
active
? "text-header-primary"
: "text-header-secondary-hover"
)}
>
{topMenu.label}
</button>
);
})}
</nav>
</div>
<div className="flex items-center justify-center">
<h1 className="font-bold content-text-2xl text-header-color">{SITE_TITLE}</h1>
</div>
<div className="flex min-w-0 items-center justify-end gap-4">
{isAuthenticated && (
<span className="content-text-base text-header-color hidden max-w-40 truncate sm:inline font-bold">
{userName}
</span>
)}
<Button
className="gap-2 border border-transparent bg-green-600 text-white w-25 shadow-sm hover:bg-green-500 hover:text-white"
onClick={isAuthenticated ? onLogout : onLogin}
>
{isAuthenticated ? (
<>
<LogOut className="w-4 h-4" />
<span className="hidden sm:inline">{"로그아웃"}</span>
</>
) : (
<>
<LogIn className="w-4 h-4" />
<span className="hidden sm:inline">{"로그인"}</span>
</>
)}
</Button>
</div>
</div>
</header>
);
}
export default Header;

View File

@@ -0,0 +1,54 @@
"use client";
import React, { createContext, useCallback, useContext, useMemo, useRef } from "react";
import {DivKey} from "@/types/kfpa";
type ExcelExporter = (ctx: DivKey) => void | Promise<void>;
type LayoutCategoryContextValue = {
selectedDiv: DivKey;
registerExcelExporter: (exporter: ExcelExporter | null) => void;
requestExcelExport: () => Promise<void>;
};
const LayoutCategoryContext = createContext<LayoutCategoryContextValue | null>(null);
export const LayoutCategoryProvider = ({
selectedDiv,
children,
}: {
selectedDiv: DivKey;
children: React.ReactNode;
}) => {
const exporterRef = useRef<ExcelExporter | null>(null);
const registerExcelExporter = useCallback((exporter: ExcelExporter | null) => {
exporterRef.current = exporter;
}, []);
const requestExcelExport = useCallback(async () => {
const exporter = exporterRef.current;
if (!exporter) {
console.warn("Excel exporter is not registered.");
return;
}
await exporter(selectedDiv);
}, [selectedDiv]);
const ctxValue = useMemo<LayoutCategoryContextValue>(
() => ({
selectedDiv,
registerExcelExporter,
requestExcelExport,
}),
[selectedDiv, registerExcelExporter, requestExcelExport]
);
return <LayoutCategoryContext.Provider value={ctxValue}>{children}</LayoutCategoryContext.Provider>;
};
export const useLayoutFilter = () => {
const ctx = useContext(LayoutCategoryContext);
if (!ctx) throw new Error("useLayoutFilter must be used within LayoutCategoryProvider");
return ctx;
};

View File

@@ -0,0 +1,86 @@
"use client"
import {ReactNode, useEffect, useState} from "react";
import {useRouter} from "next/navigation";
import {DivKey} from "@/types/kfpa";
import {useAuth} from "@/hooks/useAuth";
import {LayoutCategoryProvider} from "./LayoutCategoryContext";
import Header from "@/components/layout/Header";
import {useMounted} from "@/hooks/useMounted";
import {Sidebar} from "@/components/layout/Sidebar";
import {TOP_MENUS, SIDE_MENUS} from "@/config/menu.data";
import {useLogoutMutation} from "@/query/auth";
import {useDialog} from "@/hooks/useDialog";
import LoginDialog from "@/components/dialog/loginDialog";
type MainLayoutProps = {
children: ReactNode;
};
const getDivKey = () => {
return "-1";
}
const MainLayout = ({ children }: MainLayoutProps) => {
const { auth, logout } = useAuth();
const { showDialog } = useDialog();
const logoutMutation = useLogoutMutation();
const router = useRouter();
const isMounted = useMounted();
const [menuOpen, setMenuOpen] = useState(true);
const [selectedDiv, setSelectedDiv] = useState<DivKey>(getDivKey());
const movePage = (path: string) => {
router.push(path);
};
const openLoginDialog = () => {
showDialog("loginDialog");
};
const handleLogout = () => {
logoutMutation.mutate();
};
useEffect(() => {
const handleAuthExpired = () => {
logout();
};
window.addEventListener("auth:expired", handleAuthExpired);
return () => window.removeEventListener("auth:expired", handleAuthExpired);
}, [logout]);
if(!isMounted) return null;
return (
<div className="h-screen flex flex-col bg-transparent overflow-hidden">
<LayoutCategoryProvider selectedDiv={selectedDiv}>
<Header
topMenus={TOP_MENUS}
userName={auth.user?.userName || ""}
isAuthenticated={auth.user != null}
onNavigate={movePage}
onLogin={openLoginDialog}
onLogout={handleLogout}
/>
<div className="flex flex-1">
<Sidebar
sideMenus={SIDE_MENUS}
isOpen={menuOpen}
selectedDiv={selectedDiv}
onChangeDiv={setSelectedDiv}
/>
<main className="flex-1 p-4">
{children}
</main>
</div>
<LoginDialog />
</LayoutCategoryProvider>
</div>
);
}
export default MainLayout;

View File

@@ -0,0 +1,72 @@
"use client";
import { cn } from "@/lib/utils";
import {SideMenuItem} from "@/config/menu.type";
import {DivKey} from "@/types/kfpa";
interface SidebarProps {
sideMenus: SideMenuItem[];
isOpen: boolean;
selectedDiv: DivKey;
onChangeDiv: (div: DivKey) => void;
}
export const Sidebar = ({
sideMenus,
isOpen,
selectedDiv,
onChangeDiv,
}: SidebarProps) => {
const activeMenuClassName =
"text-foreground bg-muted shadow-[inset_4px_0_0_#ed1c24]";
return (
<aside
className={cn(
"fixed lg:static top-16 lg:top-0 left-0",
"h-[calc(100vh-4rem)] app-sidebar",
"transition-all duration-300 z-30 overflow-y-auto",
"lg:translate-x-0",
isOpen
? "w-45 translate-x-0"
: "w-45 -translate-x-full lg:w-0 lg:border-r-0"
)}
>
<div className="py-4 overflow-y-auto h-full">
<nav className="space-y-0.5 pl-2">
{sideMenus.map((item) => {
const active = selectedDiv === item.id;
return (
<button
key={item.id}
type="button"
onClick={() => onChangeDiv(item.id as DivKey)}
aria-current={active ? "true" : undefined}
className={cn(
"w-full flex items-center gap-2.5 px-3 py-2 rounded-md",
"content-text-base font-bold transition-all duration-200 cursor-pointer",
active
? activeMenuClassName
: "text-header-secondary-hover hover:bg-muted"
)}
>
<item.icon
strokeWidth={active ? 2.4 : 2}
className={cn(
"shrink-0 transition-all duration-200",
active ? "text-primary" : "text-muted-foreground",
active ? "w-[18px] h-[18px]" : "w-4 h-4"
)}
/>
<span className={cn("transition-all duration-200", active ? "text-foreground text-[15px]" : "text-[14px]")}>
{item.label}
</span>
</button>
);
})}
</nav>
</div>
</aside>
);
};

View File

@@ -0,0 +1,33 @@
'use client'
import { Provider as JotaiProvider } from "jotai";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import ReactQueryLoadingSync from "@/components/common/ReactQueryLoadingSync";
import {useState} from "react";
import {QueryClient} from "@tanstack/query-core";
import { QueryClientProvider } from "@tanstack/react-query";
export function AppProvider({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: 1,
},
},
})
);
return (
<JotaiProvider>
<QueryClientProvider client={queryClient}>
<ReactQueryLoadingSync />
<LoadingOverlay />
{children}
</QueryClientProvider>
</JotaiProvider>
);
}

View File

@@ -0,0 +1,67 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 cursor-pointer",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
outline:
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
destructive:
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default:
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
icon: "size-8",
"icon-xs":
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
"icon-sm":
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
"icon-lg": "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@@ -0,0 +1,168 @@
"use client"
import * as React from "react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { XIcon } from "lucide-react"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close data-slot="dialog-close" asChild>
<Button
variant="ghost"
className="absolute top-2 right-2 cursor-pointer"
size="icon-sm"
>
<XIcon
/>
<span className="sr-only">Close</span>
</Button>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn(
"font-heading text-base leading-none font-medium",
className
)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn(
"text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,19 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
)
}
export { Input }

46
src/config/kfpaConfig.ts Normal file
View File

@@ -0,0 +1,46 @@
export const SITE_TITLE = "화재보험협회 대시보드"
export const CATEGORY_KEY_MAP: Record<string, string> = {
'2601009_A': '안전점검',
'2604005_E': 'UCIS',
'2604005_D': 'Bridge플랫폼',
'2604005_C': '방재컨설팅',
'2604005_A': '보험 공동인수',
'2604005_B': '화재조사',
};
export const CATEGORY_PATH_MAP: Record<string, string> = {
'2601009_A': 'safety-inspection',
'2604005_E': 'ucis',
'2604005_D': 'bridge-platform',
'2604005_C': 'consulting',
'2604005_A': 'insurance-operations',
'2604005_B': 'fire-investigation',
};
export const CATEGORY_KEYS = Object.keys(CATEGORY_KEY_MAP) as Array<keyof typeof CATEGORY_KEY_MAP>;
export const CATEGORIES = Object.values(CATEGORY_KEY_MAP) as Array<string>;
export const DIV_KEY_MAP: Record<string, string> = {
'-1': '전체',
'1': '서울인천지역본부',
'2': '경기강원지역본부',
'3': '부산경남지역본부',
'4': '대구경북지역본부',
'5': '대전충청지역본부',
'6': '광주호남지역본부',
};
export const DIV_KEYS = Object.keys(DIV_KEY_MAP) as Array<keyof typeof DIV_KEY_MAP>;
export const DIVS = Object.values(DIV_KEY_MAP) as Array<string>;
export const REGION_KEY_MAP: Record<string, string> = {
'1': '서울',
'2': '경기',
'3': '부산',
'4': '대구',
'5': '대전',
'6': '광주',
};

28
src/config/menu.data.ts Normal file
View File

@@ -0,0 +1,28 @@
import {SideMenuItem, TopMenuItem} from "@/config/menu.type";
import {CATEGORY_KEY_MAP, CATEGORY_PATH_MAP, DIV_KEY_MAP} from "./kfpaConfig";
import { Building } from 'lucide-react';
export const TOP_MENUS: TopMenuItem[] = Object.entries(CATEGORY_KEY_MAP).map(
([key, value]) => {
const path = `/${CATEGORY_PATH_MAP[key].replace(/^\/+/, "")}`;
return {
id: key,
label: value,
path,
match: (pathname: string) => pathname === path,
};
}
);
export const SIDE_MENUS :SideMenuItem[] = Object.entries(DIV_KEY_MAP)
.sort(([a], [b]) => {
if (a === "-1") return -1;
if (b === "-1") return 1;
return Number(a) - Number(b);
})
.map(([key, value]) => ({
id: key,
label: value,
icon: Building,
}));

14
src/config/menu.type.ts Normal file
View File

@@ -0,0 +1,14 @@
import {LucideIcon} from "lucide-react";
export type TopMenuItem = {
id: string;
label: string;
path: string;
match?: (pathname: string) => boolean;
};
export type SideMenuItem = {
id: string;
label: string;
icon: LucideIcon;
};

3
src/const/commonConst.ts Normal file
View File

@@ -0,0 +1,3 @@
export const UNKNOWN_HTTP_ERROR = 'UNKNOWN_HTTP_ERROR';
export const NONE_HTTP_ERROR = 'NONE_HTTP_ERROR';
export const CLIENT_ROLE = 2002;

40
src/hooks/useAuth.ts Normal file
View File

@@ -0,0 +1,40 @@
"use client";
import { useCallback } from "react";
import { useAtom } from "jotai";
import { authStateAtom, type AuthState } from "@/store/jotai/auth";
import type { LoginUser } from "@/types/auth";
export const useAuth = () => {
const [auth, setAuth] = useAtom(authStateAtom);
// 로그인 성공 후 LoginResponse 를 바로 넣어줄 수 있게
const setFromLoginResponse = useCallback(
(res: LoginUser) => {
setAuth({
user: res
});
},
[setAuth],
);
const updateAuth = useCallback(
(next: AuthState | ((prev: AuthState) => AuthState)) => {
setAuth(next);
},
[setAuth],
);
const logout = useCallback(() => {
setAuth({
user: null,
});
}, [setAuth]);
return {
auth,
setAuth: updateAuth,
setFromLoginResponse,
logout,
};
}

View File

@@ -0,0 +1,12 @@
import { useEffect, useState } from "react";
export function useDebouncedValue<T>(value: T, delayMs = 1200) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const t = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(t);
}, [value, delayMs]);
return debounced;
}

54
src/hooks/useDialog.ts Normal file
View File

@@ -0,0 +1,54 @@
import { useAtom } from 'jotai'
import {DialogId, openDialogIdsAtom} from "@/store/jotai/dialog";
export function useDialog() {
const [openDialogIds, setOpenDialogIds] = useAtom(openDialogIdsAtom)
/**
* 다이얼로그 열기
* @param dialogId 다이얼로그를 구분할 ID
* @param onlyThis true 이면 기존 다이얼로그 전부 닫고 이 것만 연다.
* false 이면 기존 배열에 추가한다.
*/
const showDialog = (dialogId: DialogId, onlyThis: boolean = true) => {
setOpenDialogIds(prev => {
if (onlyThis) {
// 이 다이얼로그만 열기
return [dialogId]
}
// 이미 열려 있으면 그대로
if (prev.includes(dialogId)) {
return prev
}
// 여러 개 동시에 열기 허용
return [...prev, dialogId]
})
}
/**
* 다이얼로그 닫기
*/
const hideDialog = (dialogId: DialogId) => {
setOpenDialogIds(prev => prev.filter(id => id !== dialogId))
}
/**
* 다이얼로그 열려있는지 여부
*/
const isDialogOpen = (dialogId: DialogId) => openDialogIds.includes(dialogId)
/**
* 모든 다이얼로그 닫기 (있으면 편하니까 같이 제공)
*/
const hideAll = () => setOpenDialogIds([])
return {
openDialogIds,
isDialogOpen,
showDialog,
hideDialog,
hideAll,
}
}

56
src/hooks/useLoading.ts Normal file
View File

@@ -0,0 +1,56 @@
"use client";
import { useAtom } from "jotai";
import { useCallback } from "react";
import { loadingAtom } from "@/store/jotai/loading";
export const useLoading = () => {
const [isLoading, setIsLoading] = useAtom(loadingAtom);
const showLoading = useCallback(() => {
setIsLoading(true);
}, [setIsLoading]);
const hideLoading = useCallback(() => {
setIsLoading(false);
}, [setIsLoading]);
/**
* 비동기 함수 호출 시 편하게 쓸 수 있는 래퍼
*
* 예)
* const { withLoading } = useLoading();
* await withLoading(() => apiCall());
*/
const withLoadingAsync = useCallback(
async <T,>(fn: () => Promise<T>): Promise<T> => {
showLoading();
try {
return await fn();
} finally {
hideLoading();
}
},
[showLoading, hideLoading],
);
const withLoading = useCallback(
<T,>(fn: () => T): T => {
showLoading();
try {
return fn();
} finally {
hideLoading();
}
},
[showLoading, hideLoading],
);
return {
isLoading,
showLoading,
hideLoading,
withLoading,
withLoadingAsync,
} as const;
}

7
src/hooks/useMounted.ts Normal file
View File

@@ -0,0 +1,7 @@
import { useEffect, useState } from "react";
export const useMounted = () => {
const [mounted, setMounted] = useState(false);
useEffect(() => setMounted(true), []);
return mounted;
};

22
src/hooks/useResize.ts Normal file
View File

@@ -0,0 +1,22 @@
import { useEffect, useState } from "react";
export const useResizeKey = (debounceMs = 150) => {
const [key, setKey] = useState(0);
useEffect(() => {
let t: number | undefined;
const onResize = () => {
window.clearTimeout(t);
t = window.setTimeout(() => setKey((k) => k + 1), debounceMs);
};
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
window.clearTimeout(t);
};
}, [debounceMs]);
return key;
}

49
src/hooks/useStorage.ts Normal file
View File

@@ -0,0 +1,49 @@
"use client";
import {
setLocalStorage,
getLocalStorage,
removeLocalStorage,
setSessionStorage,
getSessionStorage,
removeSessionStorage,
} from "@/store/storage/secure-storage";
import { StorageKey, StorageType } from "@/store/storage/storage-keys";
/**
* 사용법:
* const { set, get, remove } = useStorage(StorageKeys.SeatNumber);
*/
export const useStorage = <T>(key: StorageKey) => {
const storageType = StorageType[key]; // "local" | "session"
const set = (value: T): void => {
if (storageType === "session") {
setSessionStorage(key, value);
} else {
setLocalStorage(key, value);
}
};
const get = (): T => {
if (storageType === "session") {
return getSessionStorage(key);
} else {
return getLocalStorage(key);
}
};
const remove = (): void => {
if (storageType === "session") {
removeSessionStorage(key);
} else {
removeLocalStorage(key);
}
};
return {
set,
get,
remove,
} as const;
};

15
src/lib/env.client.ts Normal file
View File

@@ -0,0 +1,15 @@
const required = <K extends keyof typeof RAW_PUBLIC_ENV>(name: K) => {
const v = RAW_PUBLIC_ENV[name];
if (!v) throw new Error(`Missing env: ${name}`);
return v;
};
const RAW_PUBLIC_ENV = {
NEXT_PUBLIC_ENV: process.env.NEXT_PUBLIC_ENV,
NEXT_PUBLIC_API_BASE: process.env.NEXT_PUBLIC_API_BASE,
} as const;
export const clientEnv = {
ENV: required("NEXT_PUBLIC_ENV"),
API_BASE: required("NEXT_PUBLIC_API_BASE"),
};

10
src/lib/env.server.ts Normal file
View File

@@ -0,0 +1,10 @@
const required = (name: string) => {
const v = process.env[name];
if (!v) throw new Error(`Missing env: ${name}`);
return v;
};
export const serverEnv = {
ENV: required("ENV"),
API_BACK_SERVER: required("API_BACK_SERVER"),
};

307
src/lib/http-client.ts Normal file
View File

@@ -0,0 +1,307 @@
import { clientEnv } from "@/lib/env.client";
export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH";
export class HttpError extends Error {
public readonly status: number;
public readonly data: unknown;
public readonly url: string;
private readonly headerMap: Record<string, string>;
constructor(status: number, data: unknown, url: string, headers?: Headers) {
super(`HTTP ${status}`);
this.name = "HttpError";
this.status = status;
this.data = data;
this.url = url;
this.headerMap =
headers && typeof headers.entries === "function"
? Object.fromEntries(headers.entries())
: {};
}
get headers(): Record<string, string> {
return this.headerMap;
}
get traceId(): string | undefined {
return this.headerMap["x-trace-id"] ?? this.headerMap["x-request-id"];
}
}
export type QueryValue = string | string[] | undefined;
export type Query = Record<string, QueryValue>;
export type PathParams = Record<string, string | number | boolean>;
export type NextFetchOptions = {
revalidate?: number;
tags?: string[];
};
export type RequestOptions = {
method?: HttpMethod;
pathParams?: PathParams;
query?: Query;
json?: unknown;
rawBody?: string;
form?: FormData;
headers?: Record<string, string>;
timeoutMs?: number;
suppressAlert?: boolean;
onAuthError?: () => void;
autoLogoutOnAuthError?: boolean;
expectText?: boolean;
expectBinary?: boolean;
cache?: RequestCache; // "force-cache" | "no-store" | ...
next?: NextFetchOptions; // Next 서버 fetch 확장 옵션
};
export type HttpClientOptions = {
getToken?: () => string | null;
defaultTimeoutMs?: number;
defaultHeaders?: Record<string, string>;
setErrorMessage?: (status: number, serverMsg?: string) => string;
};
const replacePathParams = (path: string, params?: PathParams): string => {
if (!params) return path;
let out = path;
for (const [k, v] of Object.entries(params)) {
const ph = `:${k}`;
if (out.includes(ph)) out = out.replace(ph, encodeURIComponent(String(v)));
}
return out;
};
const appendQuery = (u: URL, query?: Query): void => {
if (!query) return;
for (const [k, v] of Object.entries(query)) {
if (Array.isArray(v)) v.forEach((it) => u.searchParams.append(k, it));
else if (v !== undefined) u.searchParams.set(k, v);
}
};
const buildHeaders = (base: Record<string, string>, extra?: Record<string, string>): Headers => {
const h = new Headers(base);
if (extra) for (const [k, v] of Object.entries(extra)) h.set(k, v);
return h;
};
const isAbortError = (err: unknown): boolean => {
if (!err || typeof err !== "object") return false;
const e = err as { name?: unknown; code?: unknown; message?: unknown };
return (
e.name === "AbortError" || // browser fetch abort
e.code === "ABORT_ERR" || // some runtimes
(typeof e.message === "string" && e.message.toLowerCase().includes("aborted"))
);
};
const isJsonContentType = (ctype: string) => {
const ct = (ctype ?? "").toLowerCase()
return ct.includes("application/json") || ct.includes("+json")
}
export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => {
const {
getToken,
defaultTimeoutMs = 60_000,
defaultHeaders = { "content-type": "application/json" },
setErrorMessage,
} = opts;
const request = async <T = unknown>(path: string, options: RequestOptions = {}): Promise<T> => {
const replaced = replacePathParams(path, options.pathParams);
let url: URL;
if (/^https?:\/\//i.test(replaced)) {
url = new URL(replaced);
} else if (replaced.startsWith("/")) {
const base = new URL(baseURL);
const joinedPath = `${base.pathname.replace(/\/+$/, "")}/${replaced.replace(/^\/+/, "")}`;
url = new URL(base.toString());
url.pathname = joinedPath;
} else {
url = new URL(replaced, new URL(baseURL));
}
appendQuery(url, options.query);
const base: Record<string, string> = { ...defaultHeaders };
const token = getToken?.();
if (token) base["authorization"] = `Bearer ${token}`;
const headers = buildHeaders(base, options.headers);
let body: BodyInit | undefined;
if (options.form) {
headers.delete("content-type");
body = options.form;
} else if (options.rawBody !== undefined) {
if (!headers.has("content-type")) headers.set("content-type", "text/plain;charset=utf-8");
body = options.rawBody;
} else if (options.json !== undefined) {
if (!headers.has("content-type")) headers.set("content-type", "application/json");
body = typeof options.json === "string" ? options.json : JSON.stringify(options.json);
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs);
const isServer = typeof window === "undefined";
const cacheMode: RequestCache = options.cache ?? (isServer && options.next ? "force-cache" : "no-store");
const nextOpt = isServer ? options.next : undefined;
try {
const res = await fetch(url.toString(), {
method: options.method ?? (body ? "POST" : "GET"),
headers,
body,
cache: cacheMode,
...(nextOpt ? ({ next: nextOpt } as any) : {}),
signal: controller.signal,
});
if (options.expectBinary) {
if (!res.ok) {
const rawText = await res.text().catch(() => "");
const ctype = res.headers.get("content-type") ?? ""
const isJson = isJsonContentType(ctype)
let parsedError: unknown;
if (isJson && rawText) {
try {
parsedError = JSON.parse(rawText);
} catch {
parsedError = rawText;
}
} else {
parsedError = rawText || null;
}
const autoLogout = options.autoLogoutOnAuthError ?? true;
const suppressAlert = options.suppressAlert ?? true;
if (res.status === 401) options.onAuthError?.();
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
try {
window.dispatchEvent(new CustomEvent("auth:expired"));
} catch {}
throw new HttpError(res.status, parsedError, url.toString(), res.headers);
}
if (!suppressAlert && typeof window !== "undefined") {
const serverMsg =
typeof parsedError === "object" && parsedError !== null && "message" in parsedError
? String((parsedError as { message?: unknown }).message ?? "")
: typeof parsedError === "string"
? parsedError
: undefined;
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
alert(`[${res.status}] ${msg}`);
}
throw new HttpError(res.status, parsedError, url.toString(), res.headers);
}
const buffer = await res.arrayBuffer();
return buffer as T;
}
const ctype = res.headers.get("content-type") ?? "";
const isJson = isJsonContentType(ctype)
const rawText = await res.text().catch(() => "");
const parsed: unknown = options.expectText
? rawText
: isJson
? rawText
? JSON.parse(rawText)
: null
: rawText;
if (!res.ok) {
const autoLogout = options.autoLogoutOnAuthError ?? true;
const suppressAlert = options.suppressAlert ?? true;
if (res.status === 401) options.onAuthError?.();
if ((res.status === 401 || res.status === 403) && autoLogout && typeof window !== "undefined") {
try {
window.dispatchEvent(new CustomEvent("auth:expired"));
} catch {}
throw new HttpError(res.status, parsed, url.toString(), res.headers);
}
if (!suppressAlert && typeof window !== "undefined") {
const serverMsg =
typeof parsed === "object" && parsed !== null && "message" in parsed
? String((parsed as { message?: unknown }).message ?? "")
: typeof parsed === "string"
? parsed
: undefined;
const msg = setErrorMessage?.(res.status, serverMsg) ?? (serverMsg ?? `HTTP ${res.status}`);
alert(`[${res.status}] ${msg}`);
}
throw new HttpError(res.status, parsed, url.toString(), res.headers);
}
return parsed as T;
} catch (err: unknown) {
if (isAbortError(err)) {
throw new HttpError(
408,
{ message: "요청 시간이 초과되었습니다.", timeoutMs: options.timeoutMs ?? defaultTimeoutMs },
url.toString()
);
}
let code: string | undefined;
if (typeof err === "object" && err !== null) {
const anyErr = err as { cause?: unknown; code?: unknown };
if (anyErr.cause && typeof anyErr.cause === "object") {
const cause = anyErr.cause as { code?: unknown };
if (typeof cause.code === "string") code = cause.code;
}
if (!code && typeof anyErr.code === "string") code = anyErr.code;
}
if (code === "ECONNREFUSED") {
throw new HttpError(404, { message: "백엔드 서버를 찾을 수 없습니다." }, url.toString());
}
throw err;
} finally {
clearTimeout(timer);
}
};
const get = <T = unknown>(path: string, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "GET" });
const post = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "POST", json });
const put = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PUT", json });
const patch = <T = unknown>(path: string, json?: unknown, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PATCH", json });
const del = <T = unknown>(path: string, o?: Omit<RequestOptions, "method">) =>
request<T>(path, { ...o, method: "DELETE" });
const postForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "POST", form });
const putForm = <T = unknown>(path: string, form: FormData, o?: Omit<RequestOptions, "method" | "json" | "rawBody" | "form">) =>
request<T>(path, { ...o, method: "PUT", form });
return { request, get, post, put, patch, del, postForm, putForm };
};
export const nextApi = createHttpClient(clientEnv.API_BASE);

52
src/lib/http-util.ts Normal file
View File

@@ -0,0 +1,52 @@
import {NextResponse} from "next/server";
import {HttpError} from "@/lib/http-client";
import {clientEnv} from "@/lib/env.client";
import {NONE_HTTP_ERROR, UNKNOWN_HTTP_ERROR} from "@/const/commonConst";
export type ApiError = {
status: number
code: string
message: string
}
export const errorToResponse = (error: unknown) => {
if (error instanceof HttpError) {
const payload = error.data ?? { message: "서버에서 오류 응답을 받았습니다." }
return NextResponse.json(payload, { status: error.status })
}
return NextResponse.json(
{ message: "서버 내부 오류가 발생했습니다." },
{ status: 500 }
)
}
const isDev = clientEnv.ENV !== "prod"
export const apiError = (e: unknown): ApiError => {
if (e instanceof HttpError) {
const d = e.data as any
const code = typeof d?.code === "string" ? d.code : UNKNOWN_HTTP_ERROR
const message =
(typeof d?.detail === "string" && d.detail) ||
(typeof d?.message === "string" && d.message) ||
(typeof d?.errMessage === "string" && d.errMessage) ||
(typeof d === "string" && d) ||
`HTTP ${e.status}`
if (isDev) {
console.groupCollapsed(
`[API ERROR] ${e.status}${code ? ` / ${code}` : ""}`
)
console.log("url:", e.url)
if (e.traceId) console.log("traceId:", e.traceId)
console.log("raw data:", d)
console.groupEnd()
}
return { status: e.status, code, message }
}
if (isDev) console.error("[NON-HTTP ERROR]", e)
return { status: 500, code: NONE_HTTP_ERROR, message: "저장에 실패했습니다." }
}

196
src/lib/security.ts Normal file
View File

@@ -0,0 +1,196 @@
import CryptoJS from "crypto-js";
const KEY = CryptoJS.enc.Utf8.parse("kr!-Kfp@-fr0nT-CrypT0-Key-STR");
const IV = CryptoJS.enc.Utf8.parse("kr!-Kfp@-IVST");
export type WordArray = CryptoJS.lib.WordArray;
export class Security {
public static encryptBase64UrlObject(input: unknown): string {
const data = JSON.stringify(input);
return this.encryptBase64Url(data);
}
public static decryptBase64UrlObject(input: string): unknown {
const data = this.decryptBase64Url(input);
return JSON.parse(data);
}
public static encryptBase64Object(input: unknown): string {
const data = JSON.stringify(input);
return this.encryptBase64(data);
}
public static decryptBase64Object(input: string): unknown {
const data = this.decryptBase64(input);
return JSON.parse(data);
}
public static encryptBase64Url(input: string): string {
const data = this.decodeUtf8(input);
const params = this.encrypt(data);
return this.encodeBase64Url(params);
}
public static decryptBase64Url(input: string): string {
const data = this.decodeBase64Url(input);
const decryptedData = this.decrypt(data);
return this.encodeUtf8(decryptedData);
}
public static encryptBase64(input: string): string {
const data = this.decodeUtf8(input);
const params = this.encrypt(data);
return this.encodeBase64(params);
}
public static decryptBase64(input: string): string {
try {
const data = this.decodeBase64(input);
const decryptedData = this.decrypt(data);
return this.encodeUtf8(decryptedData);
} catch (error) {
console.error("SecurityFunction.decryptBase64 오류:", {
input: input?.substring(0, 50) + "...", // 처음 50자만 로그
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
}
public static encrypt(input: WordArray): WordArray {
const params = CryptoJS.AES.encrypt(input, KEY, {
iv: IV,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
});
return params.ciphertext;
}
public static decrypt(input: WordArray): WordArray {
const params = CryptoJS.lib.CipherParams.create({
ciphertext: input,
});
return CryptoJS.AES.decrypt(params, KEY, {
iv: IV,
padding: CryptoJS.pad.Pkcs7,
mode: CryptoJS.mode.CBC,
});
}
public static convertUint8ArrayToWordArray(input: Uint8Array): WordArray {
const words: number[] = [];
let i = 0;
while (i < input.length) {
const word =
(input[i++] << 24) |
(input[i++] << 16) |
(input[i++] << 8) |
input[i++];
words.push(word);
}
return CryptoJS.lib.WordArray.create(words, words.length * 4);
}
public static convertWordArrayToUint8Array(input: WordArray): Uint8Array {
const array = new Uint8Array(input.words.length << 2);
for (let i = 0, j = 0; i < input.words.length; i++) {
const word = input.words[i];
array[j++] = word >> 24;
array[j++] = (word >> 16) & 0xff;
array[j++] = (word >> 8) & 0xff;
array[j++] = word & 0xff;
}
return array;
}
public static computeHmacSha256Hex(input: WordArray, key: WordArray): string {
return this.encodeHex(this.computeHmacSha256(input, key));
}
public static computeHmacSha256(input: WordArray, key: WordArray): WordArray {
return CryptoJS.HmacSHA256(input, key);
}
public static computeSha256Hex(input: WordArray): string {
return this.encodeHex(this.computeSha256(input));
}
public static computeSha256(input: WordArray): WordArray {
return CryptoJS.SHA256(input);
}
private static convertToSpecialChars(base64: string): string {
return Array.from(base64)
.map((char) => char.charCodeAt(0).toString(2).padStart(16, "0"))
.map((binary) => binary.replace(/0/g, "\u200b").replace(/1/g, "\u200c"))
.join("ㅤ");
}
private static convertFromSpecialChars(input: string): string {
return input
.split("ㅤ")
.map((bin) => bin.replace(/\u200b/g, "0").replace(/\u200c/g, "1"))
.map((binary) => String.fromCharCode(parseInt(binary, 2)))
.join("");
}
public static encodeBase64UrlUtf8(input: string): string {
return this.encodeBase64Url(this.decodeUtf8(input));
}
public static decodeBase64UrlUtf8(input: string): string {
return this.encodeUtf8(this.decodeBase64Url(input));
}
public static encodeBase64Url(input: WordArray): string {
const base64url = CryptoJS.enc.Base64url.stringify(input);
return this.convertToSpecialChars(base64url);
}
public static decodeBase64Url(input: string): WordArray {
try {
const base64url = this.convertFromSpecialChars(input);
return CryptoJS.enc.Base64url.parse(base64url);
} catch {
return CryptoJS.enc.Base64url.parse(input);
}
}
public static encodeBase64Utf8(input: string): string {
return this.encodeBase64(this.decodeUtf8(input));
}
public static decodeBase64Utf8(input: string): string {
return this.encodeUtf8(this.decodeBase64(input));
}
public static encodeBase64(input: WordArray): string {
const base64 = CryptoJS.enc.Base64.stringify(input);
return this.convertToSpecialChars(base64);
}
public static decodeBase64(input: string): WordArray {
try {
const base64 = this.convertFromSpecialChars(input);
return CryptoJS.enc.Base64.parse(base64);
} catch {
return CryptoJS.enc.Base64.parse(input);
}
}
public static encodeHex(input: WordArray): string {
return CryptoJS.enc.Hex.stringify(input);
}
public static decodeHex(input: string): WordArray {
return CryptoJS.enc.Hex.parse(input);
}
public static encodeUtf8(input: WordArray): string {
return CryptoJS.enc.Utf8.stringify(input);
}
public static decodeUtf8(input: string): WordArray {
return CryptoJS.enc.Utf8.parse(input);
}
}

20
src/lib/server-api.ts Normal file
View File

@@ -0,0 +1,20 @@
import { cookies } from "next/headers";
import { createHttpClient } from "@/lib/http-client";
import { serverEnv } from "@/lib/env.server";
const createServerApi = async (rootUrl: string, defaultHeaders?: Record<string, string>) => {
const cookieStore = await cookies();
const accessToken = cookieStore.get("access_token")?.value ?? null;
return createHttpClient(rootUrl, {
getToken: () => accessToken, // 이미 위에서 읽은 값만 참조
defaultHeaders: {
"content-type": "application/json",
...(defaultHeaders ?? {}),
},
});
};
export const createBackApi = () => {
return createServerApi(serverEnv.API_BACK_SERVER);
}

6
src/lib/utils.ts Normal file
View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

39
src/query/auth.ts Normal file
View File

@@ -0,0 +1,39 @@
import {useAuth} from "@/hooks/useAuth";
import {useMutation, useQueryClient} from "@tanstack/react-query";
import {nextApi} from "@/lib/http-client";
import {LoginUser} from "@/types/auth";
export const useLoginMutation = () => {
const { setFromLoginResponse } = useAuth();
return useMutation({
mutationFn: async (v: { userId: string; userPw: string }) => {
return nextApi.post<LoginUser>("/login", { userId: v.userId, userPw: v.userPw }, { autoLogoutOnAuthError: false });
},
onSuccess: (data, v) => {
setFromLoginResponse(data);
},
});
}
export const useLogoutMutation = () => {
const qc = useQueryClient();
const { auth, logout } = useAuth();
return useMutation({
mutationFn: async () => {
const userId = auth.user?.userId ?? "";
try {
if (userId){
await nextApi.post(`/logout/${userId}`, null, { autoLogoutOnAuthError: false });
}
} catch (e) {
console.error(e);
}
},
onSettled: () => {
logout();
qc.clear(); // 다음 사용자/세션에 서버상태 남지 않게
},
});
}

0
src/query/key/keys.ts Normal file
View File

View File

@@ -0,0 +1,11 @@
export const CookieKeys = {
//FontSize: "kri_fontSize",
// 필요하면 여기 계속 추가 (예: Theme: "kri_theme", ...)
} as const;
export const CookieType: Record<CookieKey, "session" | "persistence-http-only" | "persistence"> = {
//[CookieKeys.FontSize]: "persistence",
};
export type CookieKey = (typeof CookieKeys)[keyof typeof CookieKeys];

105
src/store/cookie/cookie.ts Normal file
View File

@@ -0,0 +1,105 @@
"use client";
import type { CookieKey } from "./cookie-keys";
export type CookieSetOptions = {
days?: number; // 만료일: 기본 365일
path?: string; // 기본 "/"
secure?: boolean;
sameSite?: "Lax" | "Strict" | "None";
};
function isBrowser() {
return typeof document !== "undefined";
}
function buildCookieString(
key: CookieKey,
value: string,
options: CookieSetOptions = {},
): string {
const {
days = 365,
path = "/",
secure = false,
sameSite = "Lax",
} = options;
let cookie = `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
// 만료일
if (Number.isFinite(days)) {
const expires = new Date();
expires.setDate(expires.getDate() + days);
cookie += `; Expires=${expires.toUTCString()}`;
}
if (path) {
cookie += `; Path=${path}`;
}
if (secure) {
cookie += "; Secure";
}
if (sameSite) {
cookie += `; SameSite=${sameSite}`;
}
return cookie;
}
export const cookieStore = {
/**
* 문자열 값 가져오기 (없으면 null)
*/
get(key: CookieKey): string | null {
if (!isBrowser()) return null;
try {
const name = encodeURIComponent(key) + "=";
const cookies = document.cookie ? document.cookie.split("; ") : [];
for (const c of cookies) {
if (c.startsWith(name)) {
const value = c.substring(name.length);
return decodeURIComponent(value);
}
}
return null;
} catch {
return null;
}
},
/**
* 문자열 값 저장
*/
set(key: CookieKey, value: string, options?: CookieSetOptions) {
if (!isBrowser()) return;
try {
const cookie = buildCookieString(key, value, options);
document.cookie = cookie;
} catch {
// 쿠키 설정 실패는 조용히 무시
}
},
/**
* 쿠키 삭제
*/
remove(key: CookieKey, options?: Omit<CookieSetOptions, "days">) {
if (!isBrowser()) return;
try {
document.cookie = buildCookieString(key, "", {
...(options ?? {}),
days: -1, // 과거로 설정해서 삭제
});
} catch {
// 무시
}
},
};

20
src/store/jotai/auth.ts Normal file
View File

@@ -0,0 +1,20 @@
"use client";
import { createLocalStorageAtom } from "@/store/jotai/utils";
import { StorageKeys } from "@/store/storage/storage-keys";
import type { LoginUser } from "@/types/auth";
export type AuthState = {
user: LoginUser | null;
};
const initialAuthState: AuthState = {
user: null,
};
/**
* AES 암호화된 localStorage 기반 로그인 상태 Atom
*/
export const authStateAtom = createLocalStorageAtom<AuthState>(
StorageKeys.AuthState,
initialAuthState,
);

View File

@@ -0,0 +1,9 @@
import { atom } from 'jotai'
// 사용할 수 있는 DialogId를 타입으로 고정
// Dialog추가 할 때만다 추가하기
export type DialogId =
| 'loginDialog'
// 현재 열려 있는 다이얼로그 ID 리스트
export const openDialogIdsAtom = atom<DialogId[]>([])

View File

@@ -0,0 +1,8 @@
"use client";
import { atom } from "jotai";
/**
* 전역 로딩 상태
*/
export const loadingAtom = atom(false);

108
src/store/jotai/utils.ts Normal file
View File

@@ -0,0 +1,108 @@
"use client";
import { atom, type PrimitiveAtom } from "jotai";
import {
setLocalStorage,
getLocalStorage,
removeLocalStorage,
setSessionStorage,
getSessionStorage,
removeSessionStorage
} from "@/store/storage/secure-storage";
import {StorageKey} from "@/store/storage/storage-keys";
const loadInitialState = <T>(storageType: "local"|"session", key: StorageKey, initialValue: T): T => {
if (typeof window === "undefined") {
// SSR 시에는 그냥 기본값 사용
return initialValue;
}
const stored = storageType == "local" ? getLocalStorage(key) : getSessionStorage(key);
if (stored && typeof stored === "object") {
return stored as T;
}
return initialValue;
}
/**
* localStorage(AES 암호화) + Jotai 연동용 Atom 생성기
* - initialValue: SSR 시/최초 렌더 시 기본값
* - 마운트 후 localStorage에서 실제 값 읽어와서 덮어씀
*/
export const createLocalStorageAtom = <T>(
key: StorageKey,
initialValue: T,
) => {
const realInitialValue = loadInitialState("local", key, initialValue);
const baseAtom: PrimitiveAtom<T> = atom<T>(realInitialValue);
// 하이드레이션(저장소 주입)과 사용자 set 경합 방지용 플래그
let wasOverridden = false; // 마운트 이후 사용자가 값을 쓴 적이 있는지
const persistentAtom = atom(
(get) => get(baseAtom),
(get, set, update: T | ((prev: T) => T)) => {
const prev = get(baseAtom);
const next =
typeof update === "function"
? (update as (prev: T) => T)(prev)
: update;
// 메모리 상태 갱신
set(baseAtom, next);
// 사용자 쓰기 발생 표시 (하이드레이션이 도착해도 무시하도록)
wasOverridden = true;
if (next === null || (next as unknown) === undefined) {
// 암호화 localStorage 및 캐시 제거
removeLocalStorage(key);
} else {
// 동기 API로 캐시를 먼저 기록하고 암호화 저장은 백그라운드 처리
setLocalStorage(key, next);
}
},
);
return persistentAtom;
}
/**
* sessionStorage + Jotai 연동용 Atom 생성기
* - 탭 단위로 유지, 탭/브라우저 닫히면 삭제
* - 새로고침 시 유지
*/
export const createSessionStorageAtom = <T>(
key: StorageKey,
initialValue: T,
) => {
const realInitialValue = loadInitialState("session", key, initialValue);
const baseAtom: PrimitiveAtom<T> = atom<T>(realInitialValue);
const persistentAtom = atom(
(get) => get(baseAtom),
(get, set, update: T | ((prev: T) => T)) => {
const prev = get(baseAtom);
const next =
typeof update === "function"
? (update as (prev: T) => T)(prev)
: update;
set(baseAtom, next);
if (typeof window === "undefined") return;
try {
if (next === null || (next as unknown) === undefined) {
removeSessionStorage(key)
} else {
setSessionStorage(key, next);
}
} catch {
// sessionStorage 에러는 조용히 무시
}
},
);
return persistentAtom;
}

View File

@@ -0,0 +1,128 @@
import { Security } from "@/lib/security";
import {clientEnv} from "@/lib/env.client";
type StorageValue = any; // 요청대로 any 유지
// --- 내부 헬퍼 함수들 ---
const getDecryptedValue = (value: string): StorageValue => {
try {
if (!value || value.trim() === "") {
return null;
}
const decryptValue = clientEnv.ENV ==="prod" ? Security.decryptBase64(value) : value;
if (!decryptValue || decryptValue.trim() === "") {
return null;
}
return JSON.parse(decryptValue);
} catch (error) {
// 손상된 데이터인 경우 null 반환
return null;
}
};
const getEncryptedValue = (value: StorageValue): string => {
const stringifyValue = JSON.stringify(value);
return clientEnv.ENV ==="prod" ? Security.encryptBase64(stringifyValue) : stringifyValue;
};
// --- LocalStorage 함수들 ---
export const setLocalStorage = (key: string, value: StorageValue): void => {
try {
const encryptValue = getEncryptedValue(value);
localStorage.setItem(key, encryptValue);
} catch (error) {
// 필요하면 로깅 추가
}
};
export const getLocalStorage = (key: string): StorageValue => {
try {
const encryptValue: string | null = localStorage.getItem(key);
if (encryptValue === null || encryptValue === "") {
return null;
}
let value: StorageValue = null;
try {
// 암호화된 값 복호화 시도
value = getDecryptedValue(encryptValue);
} catch (decryptError) {
// 복호화 실패 시 평문으로 파싱 시도 (fallback)
try {
value = JSON.parse(encryptValue);
} catch (fallbackError) {
// 완전히 실패한 경우 저장된 데이터 제거
localStorage.removeItem(key);
return null;
}
}
return value;
} catch (error) {
return null;
}
};
export const removeLocalStorage = (key: string): void => {
localStorage.removeItem(key);
};
export const clearLocalStorage = (): void => {
localStorage.clear();
};
// --- SessionStorage 함수들 ---
// 세션스토리지는 테스트/실제 서버 모두 암호화 없음
export const setSessionStorage = (key: string, value: StorageValue): void => {
try {
const encryptValue = getEncryptedValue(value);
sessionStorage.setItem(key, encryptValue);
} catch (error) {
// 필요하면 로깅 추가
}
};
export const getSessionStorage = (key: string): StorageValue => {
try {
const encryptValue: string | null = sessionStorage.getItem(key);
if (encryptValue === null || encryptValue === "") {
return null;
}
let value: StorageValue = null;
try {
// 암호화된 값 복호화 시도
value = getDecryptedValue(encryptValue);
} catch (decryptError) {
// 복호화 실패 시 평문으로 파싱 시도 (fallback)
try {
value = JSON.parse(encryptValue);
} catch (fallbackError) {
// 완전히 실패한 경우 저장된 데이터 제거
localStorage.removeItem(key);
return null;
}
}
return value;
} catch (error) {
return null;
}
};
export const removeSessionStorage = (key: string): void => {
sessionStorage.removeItem(key);
};
export const clearSessionStorage = (): void => {
sessionStorage.clear();
};

View File

@@ -0,0 +1,13 @@
export const StorageKeys = {
AuthState: "kfpa:authState",
//CategoriFilter: "kri:categoryFilter",
//SidebarCollapsed: "kri:sidebarCollapsed",
// 필요하면 여기 계속 추가
} as const;
export const StorageType: Record<StorageKey, "local" | "session"> = {
[StorageKeys.AuthState]: "local",
//[StorageKeys.CategoriFilter]: "local",
};
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];

17
src/types/auth.ts Normal file
View File

@@ -0,0 +1,17 @@
export type LoginRequest = {
userId: string;
userPw: string;
};
export type LoginResponse = {
accessToken: string;
user: LoginUser;
};
export type LoginUser = {
userId: string;
userName: string;
userCmpn: string;
userTeam: string;
userRole: number;
};

28
src/types/common.ts Normal file
View File

@@ -0,0 +1,28 @@
export type DataVerification = {
success: boolean;
fieldName : string;
errMessage: string;
}
export type RouteContext = { params: Promise<{ slug?: string[] }> };
export type PageRequest = {
pageIndex: number;
pageSize: number;
sortBy: string;
sortDir: "asc" | "desc";
}
export type PageResponse<T> = {
content: T[];
totalElements: number;
totalPages: number;
pageIndex: number;
pageSize: number;
numberOfElements: number;
first: boolean;
last: boolean;
empty: boolean;
}
export type SelectedMap = Record<string, string>;

5
src/types/kfpa.ts Normal file
View File

@@ -0,0 +1,5 @@
import {CATEGORY_KEY_MAP, DIV_KEY_MAP} from "@/config/kfpaConfig";
export type CategoryKey = keyof typeof CATEGORY_KEY_MAP;
export type DivKey = keyof typeof DIV_KEY_MAP;

View File

@@ -19,7 +19,7 @@
}
],
"paths": {
"@/*": ["./*"]
"@/*": ["./src/*"]
}
},
"include": [