diff --git a/.env b/.env new file mode 100644 index 0000000..e69de29 diff --git a/.env.development b/.env.development new file mode 100644 index 0000000..03b72de --- /dev/null +++ b/.env.development @@ -0,0 +1,4 @@ +NEXT_PUBLIC_ENV=dev +NEXT_PUBLIC_API_BASE=http://localhost:3000 + +API_INTRANET=http://10.10.10.11:8081 \ No newline at end of file diff --git a/.env.local b/.env.local new file mode 100644 index 0000000..9cca8f7 --- /dev/null +++ b/.env.local @@ -0,0 +1,4 @@ +NEXT_PUBLIC_ENV=local +NEXT_PUBLIC_API_BASE=http://localhost:3000 + +API_INTRANET=http://10.10.10.11:8081 \ No newline at end of file diff --git a/.env.production b/.env.production new file mode 100644 index 0000000..7ea6d2b --- /dev/null +++ b/.env.production @@ -0,0 +1,4 @@ +NEXT_PUBLIC_ENV=prod +NEXT_PUBLIC_API_BASE=http://localhost:3000 + +API_INTRANET=http://10.10.10.11:8081 \ No newline at end of file diff --git a/.gitignore b/.gitignore index 5ef6a52..e03c9fb 100644 --- a/.gitignore +++ b/.gitignore @@ -31,7 +31,8 @@ yarn-error.log* .pnpm-debug.log* # env files (can opt-in for committing if needed) -.env* +#.env* #하위 env 파일 모두 금지 +#.env.local #.env.local 파일만 금지 # vercel .vercel diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml new file mode 100644 index 0000000..03d9549 --- /dev/null +++ b/.idea/inspectionProfiles/Project_Default.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/components.json b/components.json new file mode 100644 index 0000000..edcaef2 --- /dev/null +++ b/components.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://ui.shadcn.com/schema.json", + "style": "new-york", + "rsc": true, + "tsx": true, + "tailwind": { + "config": "", + "css": "src/app/globals.css", + "baseColor": "neutral", + "cssVariables": true, + "prefix": "" + }, + "iconLibrary": "lucide", + "aliases": { + "components": "@/components", + "utils": "@/lib/utils", + "ui": "@/components/ui", + "lib": "@/lib", + "hooks": "@/hooks" + }, + "registries": {} +} diff --git a/package-lock.json b/package-lock.json index c3929a0..61edfd0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,9 +8,16 @@ "name": "contact-front", "version": "0.1.0", "dependencies": { + "@radix-ui/react-slot": "^1.2.4", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^0.553.0", "next": "16.0.2", + "next-themes": "^0.4.6", "react": "19.2.0", - "react-dom": "19.2.0" + "react-dom": "19.2.0", + "sonner": "^2.0.7", + "tailwind-merge": "^3.4.0" }, "devDependencies": { "@tailwindcss/postcss": "^4", @@ -21,6 +28,7 @@ "eslint": "^9", "eslint-config-next": "16.0.2", "tailwindcss": "^4", + "tw-animate-css": "^1.4.0", "typescript": "^5" } }, @@ -1148,6 +1156,37 @@ "node": ">=12.4.0" } }, + "node_modules/@radix-ui/react-compose-refs": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@radix-ui/react-compose-refs/-/react-compose-refs-1.1.2.tgz", + "integrity": "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==", + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/@radix-ui/react-slot": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.2.4.tgz", + "integrity": "sha512-Jl+bCv8HxKnlTLVrcDE8zTMJ09R9/ukw4qBs/oZClOfoQk/cOTbDn+NceXfV7j09YPVQUryJPHurafcSg6EVKA==", + "dependencies": { + "@radix-ui/react-compose-refs": "1.1.2" + }, + "peerDependencies": { + "@types/react": "*", + "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, "node_modules/@rtsao/scc": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", @@ -1459,7 +1498,7 @@ "version": "19.2.4", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.4.tgz", "integrity": "sha512-tBFxBp9Nfyy5rsmefN+WXc1JeW/j2BpBHFdLZbEVfs9wn3E3NRFxwV0pJg8M1qQAexFpvz73hJXFofV0ZAu92A==", - "dev": true, + "devOptional": true, "dependencies": { "csstype": "^3.0.2" } @@ -2445,11 +2484,30 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/class-variance-authority": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz", + "integrity": "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==", + "dependencies": { + "clsx": "^2.1.1" + }, + "funding": { + "url": "https://polar.sh/cva" + } + }, "node_modules/client-only": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==" }, + "node_modules/clsx": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.1.tgz", + "integrity": "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==", + "engines": { + "node": ">=6" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -2498,7 +2556,7 @@ "version": "3.1.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", "integrity": "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw==", - "dev": true + "devOptional": true }, "node_modules/damerau-levenshtein": { "version": "1.0.8", @@ -4564,6 +4622,14 @@ "yallist": "^3.0.2" } }, + "node_modules/lucide-react": { + "version": "0.553.0", + "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.553.0.tgz", + "integrity": "sha512-BRgX5zrWmNy/lkVAe0dXBgd7XQdZ3HTf+Hwe3c9WK6dqgnj9h+hxV+MDncM88xDWlCq27+TKvHGE70ViODNILw==", + "peerDependencies": { + "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -4720,6 +4786,15 @@ } } }, + "node_modules/next-themes": { + "version": "0.4.6", + "resolved": "https://registry.npmjs.org/next-themes/-/next-themes-0.4.6.tgz", + "integrity": "sha512-pZvgD5L0IEvX5/9GWyHMf3m8BKiVQwsCMHfoFosXtXBMnaS0ZnIJ9ST4b4NqLVKDEm8QBxoNNGNaBv2JNF6XNA==", + "peerDependencies": { + "react": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc", + "react-dom": "^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc" + } + }, "node_modules/next/node_modules/postcss": { "version": "8.4.31", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", @@ -5470,6 +5545,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/sonner": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz", + "integrity": "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==", + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", + "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" + } + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", @@ -5671,6 +5755,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/tailwind-merge": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.4.0.tgz", + "integrity": "sha512-uSaO4gnW+b3Y2aWoWfFpX62vn2sR3skfhbjsEnaBI81WD1wBLlHZe5sWf0AqjksNdYTbGBEd0UasQMT3SNV15g==", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/dcastil" + } + }, "node_modules/tailwindcss": { "version": "4.1.17", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.17.tgz", @@ -5788,6 +5881,15 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==" }, + "node_modules/tw-animate-css": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/tw-animate-css/-/tw-animate-css-1.4.0.tgz", + "integrity": "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==", + "dev": true, + "funding": { + "url": "https://github.com/sponsors/Wombosvideo" + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", diff --git a/package.json b/package.json index 719d1a6..ca2965a 100644 --- a/package.json +++ b/package.json @@ -9,19 +9,27 @@ "lint": "eslint" }, "dependencies": { + "@radix-ui/react-slot": "^1.2.4", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^0.553.0", + "next": "16.0.2", + "next-themes": "^0.4.6", "react": "19.2.0", "react-dom": "19.2.0", - "next": "16.0.2" + "sonner": "^2.0.7", + "tailwind-merge": "^3.4.0" }, "devDependencies": { - "babel-plugin-react-compiler": "1.0.0", - "typescript": "^5", + "@tailwindcss/postcss": "^4", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", - "@tailwindcss/postcss": "^4", - "tailwindcss": "^4", + "babel-plugin-react-compiler": "1.0.0", "eslint": "^9", - "eslint-config-next": "16.0.2" + "eslint-config-next": "16.0.2", + "tailwindcss": "^4", + "tw-animate-css": "^1.4.0", + "typescript": "^5" } } diff --git a/src/api/auth.ts b/src/api/auth.ts new file mode 100644 index 0000000..66d36c2 --- /dev/null +++ b/src/api/auth.ts @@ -0,0 +1,12 @@ +import { createHttpClient } from "@/lib/http-client"; +import {LoginRequest, LoginResponse} from "@/types/auth"; +import {serverEnv} from "@/lib/env.server"; + +console.log("[server] API_INTRANET =", serverEnv.API_INTRANET); + +const http = createHttpClient(serverEnv.API_INTRANET); +// 인트라넷 백엔드로 실제 로그인 요청 +export const intranetApi = { + login: (payload: LoginRequest) => + http.post("/auth/login", payload), +}; \ No newline at end of file diff --git a/src/app/api/login/route.ts b/src/app/api/login/route.ts new file mode 100644 index 0000000..2d01e07 --- /dev/null +++ b/src/app/api/login/route.ts @@ -0,0 +1,74 @@ +import { NextRequest, NextResponse } from "next/server"; +import { intranetApi } from "@/api/auth"; +import {LoginRequest} from "@/types/auth"; + +export const POST = async (req: NextRequest) => { + try { + const body = (await req.json()) as LoginRequest; + const result = await intranetApi.login({ + userId: body.userId, + userPw: body.userPw, + }); + + return NextResponse.json(result, { status: 200 }); + } catch (error : unknown) { + console.error("login error:", error); + + const err = error as { status?: number; data?: unknown }; + const status = typeof err.status === "number" ? err.status : 500; + const payload = err.data !== undefined ? err.data : { message: "서버에서 오류 응답을 받았습니다." }; + + return NextResponse.json(payload, { status }); + } +} + + +/* + if (error instanceof HttpError) { + const status = error.status; + + // 서버에서 내려준 message 추출 (있으면) + let serverMessage: string | undefined; + if (typeof error.data === "object" && error.data !== null && "message" in error.data) { + serverMessage = String((error.data as { message?: unknown }).message ?? ""); + } else if (typeof error.data === "string") { + serverMessage = error.data; + } + + // status별로 클라이언트에 내려줄 메시지 매핑 + let clientMessage: string; + + switch (status) { + case 400: + clientMessage = serverMessage || "요청 형식이 올바르지 않습니다."; + break; + case 401: + clientMessage = serverMessage || "아이디 또는 비밀번호를 다시 확인해주세요."; + break; + case 403: + clientMessage = serverMessage || "해당 계정으로는 접근할 수 없습니다."; + break; + case 404: + clientMessage = serverMessage || "로그인 정보를 확인할 수 없습니다."; + break; + case 429: + clientMessage = serverMessage || "로그인 시도가 너무 많습니다. 잠시 후 다시 시도해주세요."; + break; + default: + // 5xx 등 기타 + clientMessage = serverMessage || "로그인 처리 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요."; + break; + } + + // traceId가 있으면 같이 내려줘서 디버깅에 활용 + return NextResponse.json( + { + message: clientMessage, + traceId: error.traceId, + }, + { + status, + } + ); + } + */ \ No newline at end of file diff --git a/src/app/globals.css b/src/app/globals.css index a2dc41e..dc98be7 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1,26 +1,122 @@ @import "tailwindcss"; +@import "tw-animate-css"; -:root { - --background: #ffffff; - --foreground: #171717; -} +@custom-variant dark (&:is(.dark *)); @theme inline { --color-background: var(--background); --color-foreground: var(--foreground); --font-sans: var(--font-geist-sans); --font-mono: var(--font-geist-mono); + --color-sidebar-ring: var(--sidebar-ring); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar: var(--sidebar); + --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); + --color-ring: var(--ring); + --color-input: var(--input); + --color-border: var(--border); + --color-destructive: var(--destructive); + --color-accent-foreground: var(--accent-foreground); + --color-accent: var(--accent); + --color-muted-foreground: var(--muted-foreground); + --color-muted: var(--muted); + --color-secondary-foreground: var(--secondary-foreground); + --color-secondary: var(--secondary); + --color-primary-foreground: var(--primary-foreground); + --color-primary: var(--primary); + --color-popover-foreground: var(--popover-foreground); + --color-popover: var(--popover); + --color-card-foreground: var(--card-foreground); + --color-card: var(--card); + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) + 4px); } -@media (prefers-color-scheme: dark) { - :root { - --background: #0a0a0a; - --foreground: #ededed; +:root { + --radius: 0.625rem; + --background: oklch(1 0 0); + --foreground: oklch(0.145 0 0); + --card: oklch(1 0 0); + --card-foreground: oklch(0.145 0 0); + --popover: oklch(1 0 0); + --popover-foreground: oklch(0.145 0 0); + --primary: oklch(0.205 0 0); + --primary-foreground: oklch(0.985 0 0); + --secondary: oklch(0.97 0 0); + --secondary-foreground: oklch(0.205 0 0); + --muted: oklch(0.97 0 0); + --muted-foreground: oklch(0.556 0 0); + --accent: oklch(0.97 0 0); + --accent-foreground: oklch(0.205 0 0); + --destructive: oklch(0.577 0.245 27.325); + --border: oklch(0.922 0 0); + --input: oklch(0.922 0 0); + --ring: oklch(0.708 0 0); + --chart-1: oklch(0.646 0.222 41.116); + --chart-2: oklch(0.6 0.118 184.704); + --chart-3: oklch(0.398 0.07 227.392); + --chart-4: oklch(0.828 0.189 84.429); + --chart-5: oklch(0.769 0.188 70.08); + --sidebar: oklch(0.985 0 0); + --sidebar-foreground: oklch(0.145 0 0); + --sidebar-primary: oklch(0.205 0 0); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.97 0 0); + --sidebar-accent-foreground: oklch(0.205 0 0); + --sidebar-border: oklch(0.922 0 0); + --sidebar-ring: oklch(0.708 0 0); +} + +.dark { + --background: oklch(0.145 0 0); + --foreground: oklch(0.985 0 0); + --card: oklch(0.205 0 0); + --card-foreground: oklch(0.985 0 0); + --popover: oklch(0.205 0 0); + --popover-foreground: oklch(0.985 0 0); + --primary: oklch(0.922 0 0); + --primary-foreground: oklch(0.205 0 0); + --secondary: oklch(0.269 0 0); + --secondary-foreground: oklch(0.985 0 0); + --muted: oklch(0.269 0 0); + --muted-foreground: oklch(0.708 0 0); + --accent: oklch(0.269 0 0); + --accent-foreground: oklch(0.985 0 0); + --destructive: oklch(0.704 0.191 22.216); + --border: oklch(1 0 0 / 10%); + --input: oklch(1 0 0 / 15%); + --ring: oklch(0.556 0 0); + --chart-1: oklch(0.488 0.243 264.376); + --chart-2: oklch(0.696 0.17 162.48); + --chart-3: oklch(0.769 0.188 70.08); + --chart-4: oklch(0.627 0.265 303.9); + --chart-5: oklch(0.645 0.246 16.439); + --sidebar: oklch(0.205 0 0); + --sidebar-foreground: oklch(0.985 0 0); + --sidebar-primary: oklch(0.488 0.243 264.376); + --sidebar-primary-foreground: oklch(0.985 0 0); + --sidebar-accent: oklch(0.269 0 0); + --sidebar-accent-foreground: oklch(0.985 0 0); + --sidebar-border: oklch(1 0 0 / 10%); + --sidebar-ring: oklch(0.556 0 0); +} + +@layer base { + * { + @apply border-border outline-ring/50; + } + body { + @apply bg-background text-foreground; } } - -body { - background: var(--background); - color: var(--foreground); - font-family: Arial, Helvetica, sans-serif; -} diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx new file mode 100644 index 0000000..cfbb414 --- /dev/null +++ b/src/app/login/page.tsx @@ -0,0 +1,129 @@ +"use client"; + +import {Button} from "@/components/ui/button"; +import {Card, CardContent, CardHeader} from "@/components/ui/card"; +import {Input} from "@/components/ui/input"; +import {MouseEventHandler, useState} from "react"; +import {HttpError, nextApi} from "@/lib/http-client"; +import {useRouter} from "next/navigation"; +import {LoginResponse} from "@/types/auth"; + +const LoginPage = () => { + const router = useRouter(); + const [isLoading, setIsLoading] = useState(false); + const [error, setError] = useState(null); + + const [userId, setUserId] = useState(""); + const [userPw, setUserPw] = useState(""); + const [seatNum, setSeatNum] = useState(""); + + const tryLogin = () => { + setError(null); + setIsLoading(true); + + const data = nextApi.post("/api/login", { + userId, + userPw, + }).then((data) => { + console.log(data) + + // 🔐 토큰 저장 예시 (실제에선 cookie, secure storage 등으로 변경 가능) + /*if (typeof window !== "undefined") { + localStorage.setItem("accessToken", data.accessToken); + }*/ + + // 로그인 성공 후 메인으로 이동 (원하는 경로로 변경) + //router.push("/"); + }).catch((err) => { + if (err instanceof HttpError) { + if (err.status === 401) { + setError("이메일 또는 비밀번호를 다시 확인해주세요."); + } else { + setError(`로그인에 실패했습니다. (status: ${err.status})`); + } + } else { + console.error(err); + setError("알 수 없는 오류가 발생했습니다. 잠시 후 다시 시도해주세요."); + } + }) + .finally(() => { + setIsLoading(false); + }); + } + + return ( +
+ + +
+
+ LOGO +
+
+
+ +
+
+ + setUserId(e.currentTarget.value)} + /> +
+ +
+ + setUserPw(e.currentTarget.value)} + /> +
+ +
+ + setSeatNum(e.currentTarget.value)} + /> +
+ + {error && ( +

+ {error} +

+ )} + + +
+
+
+
+ ); +} + +export default LoginPage; \ No newline at end of file diff --git a/src/app/page.tsx b/src/app/page.tsx index 295f8fd..182a9b3 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -1,65 +1,7 @@ -import Image from "next/image"; +import { redirect } from "next/navigation"; +import { buildUrlWithParams } from "@/lib/utils"; -export default function Home() { - return ( -
-
- Next.js logo -
-

- To get started, edit the page.tsx file. -

-

- Looking for a starting point or more instructions? Head over to{" "} - - Templates - {" "} - or the{" "} - - Learning - {" "} - center. -

-
- -
-
- ); -} +export default function Page({ searchParams }: { searchParams: Record }) { + const url = buildUrlWithParams("/login", searchParams, { ref: "root" }); + redirect(url); +} \ No newline at end of file diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx new file mode 100644 index 0000000..21409a0 --- /dev/null +++ b/src/components/ui/button.tsx @@ -0,0 +1,60 @@ +import * as React from "react" +import { Slot } from "@radix-ui/react-slot" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" + +const buttonVariants = cva( + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/90", + destructive: + "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", + outline: + "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: + "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2 has-[>svg]:px-3", + sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5", + lg: "h-10 rounded-md px-6 has-[>svg]:px-4", + icon: "size-9", + "icon-sm": "size-8", + "icon-lg": "size-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +function Button({ + className, + variant, + size, + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean + }) { + const Comp = asChild ? Slot : "button" + + return ( + + ) +} + +export { Button, buttonVariants } diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsx new file mode 100644 index 0000000..681ad98 --- /dev/null +++ b/src/components/ui/card.tsx @@ -0,0 +1,92 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Card({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardHeader({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardTitle({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardDescription({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardAction({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardContent({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function CardFooter({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +export { + Card, + CardHeader, + CardFooter, + CardTitle, + CardAction, + CardDescription, + CardContent, +} diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsx new file mode 100644 index 0000000..8916905 --- /dev/null +++ b/src/components/ui/input.tsx @@ -0,0 +1,21 @@ +import * as React from "react" + +import { cn } from "@/lib/utils" + +function Input({ className, type, ...props }: React.ComponentProps<"input">) { + return ( + + ) +} + +export { Input } diff --git a/src/components/ui/sonner.tsx b/src/components/ui/sonner.tsx new file mode 100644 index 0000000..9b20afe --- /dev/null +++ b/src/components/ui/sonner.tsx @@ -0,0 +1,40 @@ +"use client" + +import { + CircleCheckIcon, + InfoIcon, + Loader2Icon, + OctagonXIcon, + TriangleAlertIcon, +} from "lucide-react" +import { useTheme } from "next-themes" +import { Toaster as Sonner, type ToasterProps } from "sonner" + +const Toaster = ({ ...props }: ToasterProps) => { + const { theme = "system" } = useTheme() + + return ( + , + info: , + warning: , + error: , + loading: , + }} + style={ + { + "--normal-bg": "var(--popover)", + "--normal-text": "var(--popover-foreground)", + "--normal-border": "var(--border)", + "--border-radius": "var(--radius)", + } as React.CSSProperties + } + {...props} + /> + ) +} + +export { Toaster } diff --git a/src/lib/env.client.ts b/src/lib/env.client.ts new file mode 100644 index 0000000..d1dff90 --- /dev/null +++ b/src/lib/env.client.ts @@ -0,0 +1,8 @@ +export const clientEnv = { + API_BASE: process.env.NEXT_PUBLIC_API_BASE as string, + // 다른 클라이언트 전용 env들 추가 가능 +}; + +if (!clientEnv.API_BASE) { + throw new Error("Missing env: NEXT_PUBLIC_API_BASE"); +} \ No newline at end of file diff --git a/src/lib/env.server.ts b/src/lib/env.server.ts new file mode 100644 index 0000000..4c3aefb --- /dev/null +++ b/src/lib/env.server.ts @@ -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 = { + API_INTRANET: required("API_INTRANET"), + // 다른 서버 전용 env들 추가 가능 +}; \ No newline at end of file diff --git a/src/lib/http-client.ts b/src/lib/http-client.ts new file mode 100644 index 0000000..be1a7a0 --- /dev/null +++ b/src/lib/http-client.ts @@ -0,0 +1,253 @@ +// src/lib/http-client.ts +import { clientEnv } from "@/lib/env.client"; + +export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE"; + +export class HttpError extends Error { + public readonly status: number; + public readonly data: unknown; + public readonly url: string; + private readonly headerMap: Record; + + 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()) + : {}; + } + + /** Plain object headers (safe for logging/serialization) */ + get headers(): Record { + return this.headerMap; + } + + /** Convenience accessor for common trace headers */ + 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; +export type PathParams = Record; + +export type RequestOptions = { + /** HTTP method (default: GET or POST when body exists) */ + method?: HttpMethod; + /** Replace placeholders in path, e.g., /users/:id */ + pathParams?: PathParams; + /** Query string key-values (arrays supported) */ + query?: Query; + /** JSON body (auto-serialized) */ + json?: unknown; + /** Send raw text body */ + rawBody?: string; + /** Send multipart/form-data */ + form?: FormData; + /** Extra headers (merged over defaults) */ + headers?: Record; + /** Per-request timeout (ms), default from client */ + timeoutMs?: number; + /** Suppress user alert on error */ + suppressAlert?: boolean; + /** Hook for 401 responses */ + onAuthError?: () => void; + /** Force treat response as text (skip JSON parse) */ + expectText?: boolean; +}; + +export type HttpClientOptions = { + /** Provide latest token per request (e.g., from storage) */ + getToken?: () => string | null; + /** Default timeout (ms) */ + defaultTimeoutMs?: number; + /** Default headers (e.g., content-type) */ + defaultHeaders?: Record; + /** Map server status/message to user-friendly text */ + 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, + extra?: Record +): Headers => { + const h = new Headers(base); + if (extra) for (const [k, v] of Object.entries(extra)) h.set(k, v); + return h; +}; + +/** + * Create a minimal, fetch-based HTTP client with: + * - path params (:id), query, JSON/FormData/raw body + * - default/extra headers + token injection + * - timeout, 401 hook, optional alert suppression + */ +export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {}) => { + const { + getToken, + defaultTimeoutMs = 10_000, + defaultHeaders = { "content-type": "application/json" }, + setErrorMessage, + } = opts; + + const request = async (path: string, options: RequestOptions = {}): Promise => { + // 1) URL + const replaced = replacePathParams(path, options.pathParams); + const url = /^https?:\/\//i.test(replaced) + ? new URL(replaced) + : new URL(replaced, baseURL); + appendQuery(url, options.query); + + // 2) headers (defaults + token + per-call) + const base: Record = { ...defaultHeaders }; + const token = getToken?.(); + if (token) base["authorization"] = `Bearer ${token}`; + const headers = buildHeaders(base, options.headers); + + // 3) body + let body: BodyInit | undefined; + if (options.form) { + headers.delete("content-type"); // let browser set multipart boundary + 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); + } + + // 4) timeout + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs); + + try { + // 5) fetch + const res = await fetch(url.toString(), { + method: options.method ?? (body ? "POST" : "GET"), + headers, + body, + cache: "no-store", + signal: controller.signal, + }); + + // 6) parse + const ctype = res.headers.get("content-type") ?? ""; + const isJson = ctype.includes("application/json"); + const rawText = await res.text().catch(() => ""); + const parsed: unknown = options.expectText + ? rawText + : isJson + ? rawText + ? JSON.parse(rawText) + : null + : rawText; + + // 7) error (HTTP status 에러) + if (!res.ok) { + if (res.status === 401) options.onAuthError?.(); + + if (!options.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}`); + // eslint-disable-next-line no-alert + alert(`[${res.status}] ${msg}`); + } + + throw new HttpError(res.status, parsed, url.toString(), res.headers); + } + + return parsed as T; + } catch (err: any) { + // 🔻 여기서 네트워크 레벨 에러 처리 + const code = err?.cause?.code ?? err?.code; + + if (code === "ECONNREFUSED") { + // 네트워크 연결 실패 → HttpError(404)로 변환 + throw new HttpError( + 404, + { message: "백엔드 서버를 찾을 수 없습니다." }, + url.toString(), + ); + } + + // 그 외 에러는 그대로 던지기 + throw err; + } finally { + // timeout 정리 + clearTimeout(timer); + } + }; + + // Convenience methods (all arrow functions) + const get = ( + path: string, + o?: Omit + ) => request(path, { ...o, method: "GET" }); + + const post = ( + path: string, + json?: unknown, + o?: Omit + ) => request(path, { ...o, method: "POST", json }); + + const put = ( + path: string, + json?: unknown, + o?: Omit + ) => request(path, { ...o, method: "PUT", json }); + + const del = ( + path: string, + o?: Omit + ) => request(path, { ...o, method: "DELETE" }); + + const postForm = ( + path: string, + form: FormData, + o?: Omit + ) => request(path, { ...o, method: "POST", form }); + + const putForm = ( + path: string, + form: FormData, + o?: Omit + ) => request(path, { ...o, method: "PUT", form }); + + return { request, get, post, put, del, postForm, putForm }; +}; + +export const nextApi = createHttpClient(clientEnv.API_BASE); \ No newline at end of file diff --git a/src/lib/utils.ts b/src/lib/utils.ts new file mode 100644 index 0000000..534703c --- /dev/null +++ b/src/lib/utils.ts @@ -0,0 +1,20 @@ +import { clsx, type ClassValue } from "clsx" +import { twMerge } from "tailwind-merge" + +export function cn(...inputs: ClassValue[]) { + return twMerge(clsx(inputs)) +} + +export function buildUrlWithParams( + targetPath: string, + from: Record, + extra?: Record, +) { + const qs = new URLSearchParams(); + for (const [k, v] of Object.entries(from)) { + if (Array.isArray(v)) v.forEach((val) => qs.append(k, val)); + else if (v !== undefined) qs.set(k, v); + } + if (extra) for (const [k, v] of Object.entries(extra)) if (v) qs.set(k, v); + return `${targetPath}${qs.toString() ? `?${qs}` : ""}`; +} \ No newline at end of file diff --git a/src/types/auth.ts b/src/types/auth.ts new file mode 100644 index 0000000..7a2b320 --- /dev/null +++ b/src/types/auth.ts @@ -0,0 +1,16 @@ +export type LoginRequest = { + userId: string; + userPw: string; +}; + +export type LoginUser = { + id: string; + name: string; + email: string; +}; + +export type LoginResponse = { + accessToken: string; + refreshToken?: string; + user: LoginUser; +}; \ No newline at end of file