Initial commit: 용산 공중케이블 주민 안전 협의회 홈페이지

- Next.js 16 App Router + TypeScript + Tailwind CSS 4
- Prisma/SQLite 기반 공지사항·자료실·관리자·문의/제보
- 네이버 블로그 RSS 최신 글 5개 노출
- OCI 운영 배포 스크립트 및 문서
This commit is contained in:
user01
2026-10-26 00:52:53 +09:00
commit 46bc36a1f5
88 changed files with 11750 additions and 0 deletions
+73
View File
@@ -0,0 +1,73 @@
"use server";
import bcrypt from "bcryptjs";
import { redirect } from "next/navigation";
import { getClientIp, createSession, destroySession } from "@/lib/auth";
import { writeAudit } from "@/lib/audit";
import { prisma } from "@/lib/db";
import { rateLimit } from "@/lib/rate-limit";
import { loginSchema } from "@/lib/validation";
export type LoginState = {
error?: string;
};
export async function loginAction(_prevState: LoginState, formData: FormData): Promise<LoginState> {
const parsed = loginSchema.safeParse({
loginId: String(formData.get("loginId") ?? "").trim(),
password: String(formData.get("password") ?? ""),
});
if (!parsed.success) {
return { error: parsed.error.errors[0]?.message ?? "입력값을 확인해 주세요." };
}
const ip = await getClientIp();
const limit = rateLimit(`login:${ip ?? "unknown"}`, 6, 10 * 60 * 1000);
if (!limit.ok) {
return {
error: `로그인 시도가 너무 많습니다. ${limit.retryAfterSeconds}초 후 다시 시도해 주세요.`,
};
}
const admin = await prisma.adminUser.findUnique({
where: { loginId: parsed.data.loginId },
});
if (!admin) {
return { error: "아이디 또는 비밀번호가 올바르지 않습니다." };
}
const valid = await bcrypt.compare(parsed.data.password, admin.passwordHash);
if (!valid) {
return { error: "아이디 또는 비밀번호가 올바르지 않습니다." };
}
await createSession({
sub: admin.id,
loginId: admin.loginId,
name: admin.name,
role: admin.role,
});
await prisma.adminUser.update({
where: { id: admin.id },
data: { lastLoginAt: new Date() },
});
await writeAudit({
adminId: admin.id,
action: "LOGIN",
targetType: "ADMIN",
targetId: admin.id,
ip,
});
redirect("/admin");
}
export async function logoutAction() {
await destroySession();
redirect("/admin/login");
}
+117
View File
@@ -0,0 +1,117 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { getClientIp, requireAdmin } from "@/lib/auth";
import { writeAudit } from "@/lib/audit";
import { prisma } from "@/lib/db";
import { rateLimit } from "@/lib/rate-limit";
import { getString, inquirySchema } from "@/lib/validation";
export type InquiryState = {
error?: string;
};
export async function submitInquiryAction(
_prevState: InquiryState,
formData: FormData,
): Promise<InquiryState> {
// 허니팟: 자동 입력 봇은 이 필드를 채웁니다.
if (getString(formData, "website")) {
return { error: "요청을 처리할 수 없습니다." };
}
const parsed = inquirySchema.safeParse({
name: getString(formData, "name"),
email: getString(formData, "email"),
phone: getString(formData, "phone"),
title: getString(formData, "title"),
content: getString(formData, "content"),
consent: formData.get("consent") === "on",
});
if (!parsed.success) {
return { error: parsed.error.errors[0]?.message ?? "입력값을 확인해 주세요." };
}
const ip = await getClientIp();
const limit = rateLimit(`inquiry:${ip ?? "unknown"}`, 5, 60 * 60 * 1000);
if (!limit.ok) {
return {
error: `문의 접수가 너무 많습니다. ${Math.ceil(limit.retryAfterSeconds / 60)}분 후 다시 시도해 주세요.`,
};
}
await prisma.inquiry.create({
data: {
...parsed.data,
ip,
},
});
revalidatePath("/admin");
revalidatePath("/admin/inquiries");
redirect("/contact?submitted=1");
}
export async function updateInquiryStatusAction(formData: FormData) {
const admin = await requireAdmin();
const ip = await getClientIp();
const id = Number(getString(formData, "id"));
const status = getString(formData, "status");
if (!Number.isInteger(id) || id <= 0) {
redirect("/admin/inquiries?error=invalid-id");
}
if (!["NEW", "IN_PROGRESS", "DONE"].includes(status)) {
redirect("/admin/inquiries?error=invalid-status");
}
const existing = await prisma.inquiry.findUnique({ where: { id }, select: { id: true } });
if (!existing) {
redirect("/admin/inquiries?error=not-found");
}
await prisma.inquiry.update({ where: { id }, data: { status } });
await writeAudit({
adminId: admin.id,
action: "INQUIRY_STATUS",
targetType: "INQUIRY",
targetId: id,
ip,
});
revalidatePath("/admin");
revalidatePath("/admin/inquiries");
redirect("/admin/inquiries?updated=1");
}
export async function deleteInquiryAction(formData: FormData) {
const admin = await requireAdmin();
const ip = await getClientIp();
const id = Number(getString(formData, "id"));
if (!Number.isInteger(id) || id <= 0) {
redirect("/admin/inquiries?error=invalid-id");
}
const existing = await prisma.inquiry.findUnique({ where: { id }, select: { id: true } });
if (!existing) {
redirect("/admin/inquiries?error=not-found");
}
await prisma.inquiry.delete({ where: { id } });
await writeAudit({
adminId: admin.id,
action: "INQUIRY_DELETE",
targetType: "INQUIRY",
targetId: id,
ip,
});
revalidatePath("/admin");
revalidatePath("/admin/inquiries");
redirect("/admin/inquiries?deleted=1");
}
+254
View File
@@ -0,0 +1,254 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { getClientIp, requireAdmin } from "@/lib/auth";
import { writeAudit } from "@/lib/audit";
import { prisma } from "@/lib/db";
import { deleteStoredFile, saveUploadedFile, type SavedFile } from "@/lib/files";
import { getBoolean, getString, postSchema } from "@/lib/validation";
function errorRedirect(path: string, message: string): never {
redirect(`${path}${path.includes("?") ? "&" : "?"}error=${encodeURIComponent(message)}`);
}
function successRedirect(type: string, message = "saved") {
revalidatePath("/");
revalidatePath("/news/notice");
revalidatePath("/archive");
revalidatePath("/admin/posts");
redirect(`/admin/posts?type=${type}&${message}=1`);
}
async function readPostForm(formData: FormData) {
const parsed = postSchema.safeParse({
type: getString(formData, "type"),
category: getString(formData, "category"),
title: getString(formData, "title"),
content: getString(formData, "content"),
isPinned: getBoolean(formData, "isPinned"),
status: getString(formData, "status"),
});
return parsed;
}
function uploadFilesFrom(formData: FormData) {
return formData
.getAll("attachments")
.filter((value): value is File => value instanceof File && value.size > 0)
.slice(0, 10);
}
export async function createPostAction(formData: FormData) {
const admin = await requireAdmin();
const ip = await getClientIp();
const parsed = await readPostForm(formData);
const type = getString(formData, "type") || "NOTICE";
if (!parsed.success) {
errorRedirect(`/admin/posts/new?type=${type}`, parsed.error.errors[0]?.message ?? "입력값을 확인해 주세요.");
}
const files = uploadFilesFrom(formData);
const savedFiles: SavedFile[] = [];
try {
for (const file of files) {
savedFiles.push(await saveUploadedFile(file));
}
} catch (error) {
errorRedirect(
`/admin/posts/new?type=${type}`,
error instanceof Error ? error.message : "파일 업로드에 실패했습니다.",
);
}
const post = await prisma.post.create({
data: {
type: parsed.data.type,
category: parsed.data.category || null,
title: parsed.data.title,
content: parsed.data.content,
isPinned: parsed.data.type === "NOTICE" ? parsed.data.isPinned : false,
status: parsed.data.status,
authorId: admin.id,
publishedAt: new Date(),
attachments: {
create: savedFiles.map((file) => ({
originalName: file.originalName,
storageKey: file.storageKey,
mimeType: file.mimeType,
size: file.size,
})),
},
},
});
await writeAudit({
adminId: admin.id,
action: "POST_CREATE",
targetType: parsed.data.type,
targetId: post.id,
ip,
});
successRedirect(parsed.data.type, "created");
}
export async function updatePostAction(formData: FormData) {
const admin = await requireAdmin();
const ip = await getClientIp();
const id = Number(getString(formData, "id"));
const type = getString(formData, "type") || "NOTICE";
if (!Number.isInteger(id) || id <= 0) {
errorRedirect("/admin/posts", "잘못된 게시글 번호입니다.");
}
const parsed = await readPostForm(formData);
if (!parsed.success) {
errorRedirect(
`/admin/posts/${id}/edit`,
parsed.error.errors[0]?.message ?? "입력값을 확인해 주세요.",
);
}
const removeIds = formData
.getAll("removeAttachment")
.map((value) => Number(value))
.filter((value) => Number.isInteger(value) && value > 0);
const existing = await prisma.post.findUnique({
where: { id },
include: { attachments: true },
});
if (!existing) {
errorRedirect("/admin/posts", "게시글을 찾을 수 없습니다.");
}
const files = uploadFilesFrom(formData);
const savedFiles: SavedFile[] = [];
try {
for (const file of files) {
savedFiles.push(await saveUploadedFile(file));
}
} catch (error) {
errorRedirect(
`/admin/posts/${id}/edit`,
error instanceof Error ? error.message : "파일 업로드에 실패했습니다.",
);
}
await prisma.$transaction(async (tx) => {
await tx.post.update({
where: { id },
data: {
type: parsed.data.type,
category: parsed.data.category || null,
title: parsed.data.title,
content: parsed.data.content,
isPinned: parsed.data.type === "NOTICE" ? parsed.data.isPinned : false,
status: parsed.data.status,
},
});
if (removeIds.length > 0) {
await tx.attachment.deleteMany({
where: { id: { in: removeIds }, postId: id },
});
}
if (savedFiles.length > 0) {
await tx.attachment.createMany({
data: savedFiles.map((file) => ({
postId: id,
originalName: file.originalName,
storageKey: file.storageKey,
mimeType: file.mimeType,
size: file.size,
})),
});
}
});
const removed = existing.attachments.filter((attachment) => removeIds.includes(attachment.id));
await Promise.all(removed.map((attachment) => deleteStoredFile(attachment.storageKey)));
await writeAudit({
adminId: admin.id,
action: "POST_UPDATE",
targetType: parsed.data.type,
targetId: id,
ip,
});
successRedirect(parsed.data.type, "updated");
}
export async function deletePostAction(formData: FormData) {
const admin = await requireAdmin();
const ip = await getClientIp();
const id = Number(getString(formData, "id"));
if (!Number.isInteger(id) || id <= 0) {
errorRedirect("/admin/posts", "잘못된 게시글 번호입니다.");
}
const post = await prisma.post.findUnique({
where: { id },
include: { attachments: true },
});
if (!post) {
errorRedirect("/admin/posts", "게시글을 찾을 수 없습니다.");
}
await prisma.post.delete({ where: { id } });
await Promise.all(post.attachments.map((attachment) => deleteStoredFile(attachment.storageKey)));
await writeAudit({
adminId: admin.id,
action: "POST_DELETE",
targetType: post.type,
targetId: id,
ip,
});
successRedirect(post.type, "deleted");
}
export async function deleteAttachmentAction(formData: FormData) {
const admin = await requireAdmin();
const ip = await getClientIp();
const id = Number(getString(formData, "id"));
const postId = Number(getString(formData, "postId"));
if (!Number.isInteger(id) || id <= 0) {
errorRedirect("/admin/posts", "잘못된 첨부파일 번호입니다.");
}
const attachment = await prisma.attachment.findFirst({
where: { id, postId },
});
if (!attachment) {
errorRedirect(`/admin/posts/${postId}/edit`, "첨부파일을 찾을 수 없습니다.");
}
await prisma.attachment.delete({ where: { id } });
await deleteStoredFile(attachment.storageKey);
await writeAudit({
adminId: admin.id,
action: "ATTACHMENT_DELETE",
targetType: "ATTACHMENT",
targetId: id,
ip,
});
revalidatePath(`/admin/posts/${postId}/edit`);
redirect(`/admin/posts/${postId}/edit?deletedAttachment=1`);
}
+50
View File
@@ -0,0 +1,50 @@
"use server";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import { getClientIp, requireAdmin } from "@/lib/auth";
import { writeAudit } from "@/lib/audit";
import { prisma } from "@/lib/db";
import { getString, settingsSchema } from "@/lib/validation";
export async function updateSettingsAction(formData: FormData) {
const admin = await requireAdmin();
const ip = await getClientIp();
const parsed = settingsSchema.safeParse({
siteName: getString(formData, "siteName"),
shortName: getString(formData, "shortName"),
description: getString(formData, "description"),
contactEmail: getString(formData, "contactEmail"),
contactPhone: getString(formData, "contactPhone"),
address: getString(formData, "address"),
blogUrl: getString(formData, "blogUrl"),
mapUrl: getString(formData, "mapUrl"),
footerText: getString(formData, "footerText"),
});
if (!parsed.success) {
redirect(`/admin/settings?error=${encodeURIComponent(parsed.error.errors[0]?.message ?? "입력값을 확인해 주세요.")}`);
}
await prisma.$transaction(
Object.entries(parsed.data).map(([key, value]) =>
prisma.setting.upsert({
where: { key },
update: { value },
create: { key, value },
}),
),
);
await writeAudit({
adminId: admin.id,
action: "SETTINGS_UPDATE",
targetType: "SETTING",
ip,
});
revalidatePath("/", "layout");
redirect("/admin/settings?saved=1");
}
+275
View File
@@ -0,0 +1,275 @@
import Image from "next/image";
import Link from "next/link";
import type { Metadata } from "next";
import { ArrowRight, CheckCircle2, MapPin, Megaphone, Users } from "lucide-react";
import { PageHero } from "@/components/site/page-hero";
import { getSettings } from "@/lib/settings";
export const metadata: Metadata = {
title: "협의회 소개",
description:
"용산 공중케이블 주민 안전 협의회의 비전, 활동, 연혁과 조직을 소개합니다.",
alternates: { canonical: "/about" },
};
export const dynamic = "force-dynamic";
const HISTORY = [
{
year: "2023",
items: ["11월 · 용산구 시설관리공단 지역문제 해결 제안모집 공모 제안 응모"],
},
{
year: "2024",
items: [
"1월 · 제안모집 공모 제안 채택 통지",
"1차 · 시설관리공단 안전관리팀장, 경영지원팀장, KT 용산담당자 미팅",
"2차 · 용산구 꿈나무지원센터, 경영지원팀장, 부회장, 윤성태 외 2명 미팅",
"3차 · 용산구청 시설관리공단 담당자와 주민활동 지원협의",
"6월 · 용산구 난립전선 현황 파악을 위한 전신주 촬영 활동 시작",
"9월·10월 · 공중케이블 정비를 위한 간담회 개최",
"12월 · 용산 공중케이블 주민 안전 협의회 결성",
],
},
{
year: "2025",
items: [
"난립 전선 현황 조사 및 데이터베이스 구축",
"주민 의견 수렴과 조례 제정 추진",
"구청·통신업체와의 정기 간담회",
"주민 참여 캠페인과 홍보 활동",
],
},
{
year: "2026",
items: [
"홈페이지 개편 및 공지사항·자료실 운영",
"현장 조사 기록의 체계적 관리",
"주민 제보 접수와 정비 요청 지속",
],
},
];
const ACTIVITIES = [
{
icon: MapPin,
title: "현장 조사와 기록",
body: "용산구의 공중케이블 현황을 정기적으로 촬영하고 기록합니다. 축적된 데이터를 바탕으로 체계적인 개선 방안을 마련합니다.",
},
{
icon: Megaphone,
title: "주민 의견 수렴·정책 제안",
body: "주민의 목소리를 듣고, 복잡한 전선 문제를 해결하기 위한 조례 제정과 제도 개선을 추진합니다.",
},
{
icon: Users,
title: "기관·통신사 협력",
body: "용산구청, 지방의회, 통신사 담당자와 정기 간담회를 통해 실질적인 정비 방안을 함께 논의합니다.",
},
];
export default async function AboutPage() {
const settings = await getSettings();
return (
<>
<PageHero
eyebrow="About"
title="협의회 소개"
description="용산의 안전하고 깨끗한 거리 환경을 위해 주민이 직접 나섭니다."
breadcrumb={[{ label: "협의회 소개" }]}
/>
<section className="site-container py-14 sm:py-20">
<div className="grid gap-10 lg:grid-cols-[1.1fr_0.9fr] lg:items-center">
<div>
<p className="text-xs font-bold uppercase tracking-[0.2em] text-brand-600">Our Story</p>
<h2 className="mt-3 text-3xl font-black leading-tight tracking-tight text-brand-950 sm:text-4xl">
주민의 작은 관심이
<br />
도시의 큰 변화를 만듭니다
</h2>
<div className="mt-6 space-y-4 text-sm leading-7 text-slate-600 sm:text-base">
<p>
용산공중케이블 주민 안전 협의회는 복잡한 공중케이블 지역 문제 해결과 용산의 거리·환경
개선을 위해 활동하는 주민 모임입니다.
</p>
<p>
2023년 용산구 시설관리공단의 지역문제 해결 제안모집에 응모한 것을 시작으로, 현장 조사와
기관·통신사 간담회를 이어오며 2024년 12월 협의회를 결성했습니다.
</p>
<p>
앞으로도 주민과 함께 기록하고, 목소리를 모으고, 실제 정비로 이어질 수 있도록 꾸준히
활동하겠습니다.
</p>
</div>
<div className="mt-8 flex flex-wrap gap-3">
<Link
href="/contact"
className="inline-flex items-center gap-2 rounded-xl bg-brand-900 px-5 py-3 text-sm font-bold text-white transition hover:bg-brand-800"
>
함께 참여하기
<ArrowRight className="h-4 w-4" aria-hidden />
</Link>
<a
href={settings.mapUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-5 py-3 text-sm font-bold text-slate-700 transition hover:border-brand-200 hover:text-brand-800"
>
조사 현황 보기
</a>
</div>
</div>
<div className="relative">
<div className="overflow-hidden rounded-3xl border border-slate-200 bg-white shadow-sm">
<Image
src="/images/exam-good.jpg"
alt="정비 후 깔끔해진 용산의 전신주"
width={800}
height={1067}
sizes="(min-width: 1024px) 40vw, 90vw"
className="h-auto w-full object-cover"
/>
</div>
<div className="absolute -bottom-5 -left-4 rounded-2xl border border-slate-200 bg-white px-5 py-4 shadow-lg sm:-left-6">
<p className="text-[11px] font-bold uppercase tracking-[0.16em] text-brand-600">Since</p>
<p className="mt-1 text-2xl font-black text-brand-950">2024</p>
<p className="text-xs text-slate-500">주민 안전 협의회 결성</p>
</div>
</div>
</div>
</section>
<section className="border-y border-slate-200 bg-white py-14 sm:py-20">
<div className="site-container">
<div className="max-w-2xl">
<p className="text-xs font-bold uppercase tracking-[0.2em] text-brand-600">Vision</p>
<h2 className="mt-3 text-2xl font-black tracking-tight text-brand-950 sm:text-3xl">
우리가 만드는 변화
</h2>
<p className="mt-3 text-sm leading-7 text-slate-500">
정부와 관련 기관이 공중케이블 정비에 나설 수 있도록 촉구하고, 주민이 체감할 수 있는 개선을
만들어갑니다.
</p>
</div>
<div className="mt-8 grid gap-5 md:grid-cols-3">
{[
"도시 미관 개선",
"폐전선으로 인한 사고 방지",
"지속 가능한 도시 환경 조성",
].map((item) => (
<div key={item} className="rounded-2xl border border-slate-200 bg-slate-50/70 p-6">
<CheckCircle2 className="h-6 w-6 text-brand-600" aria-hidden />
<p className="mt-4 text-base font-bold text-brand-950">{item}</p>
</div>
))}
</div>
<div className="mt-12 grid gap-5 md:grid-cols-3">
{ACTIVITIES.map((activity) => (
<article key={activity.title} className="rounded-2xl border border-slate-200 bg-white p-6">
<span className="grid h-11 w-11 place-items-center rounded-xl bg-brand-50 text-brand-700">
<activity.icon className="h-5 w-5" aria-hidden />
</span>
<h3 className="mt-4 text-base font-bold text-brand-950">{activity.title}</h3>
<p className="mt-2 text-sm leading-7 text-slate-500">{activity.body}</p>
</article>
))}
</div>
</div>
</section>
<section className="site-container py-14 sm:py-20">
<div className="max-w-2xl">
<p className="text-xs font-bold uppercase tracking-[0.2em] text-brand-600">History</p>
<h2 className="mt-3 text-2xl font-black tracking-tight text-brand-950 sm:text-3xl">주요 연혁</h2>
</div>
<ol className="mt-8 space-y-8 border-l border-slate-200 pl-6 sm:pl-8">
{HISTORY.map((group) => (
<li key={group.year} className="relative">
<span className="absolute -left-[31px] top-1 grid h-3.5 w-3.5 place-items-center rounded-full border-2 border-brand-700 bg-white sm:-left-[39px]" />
<h3 className="text-lg font-black text-brand-950">{group.year}</h3>
<ul className="mt-3 space-y-2">
{group.items.map((item) => (
<li key={item} className="text-sm leading-7 text-slate-600">
{item}
</li>
))}
</ul>
</li>
))}
</ol>
</section>
<section className="border-y border-slate-200 bg-white py-14 sm:py-20">
<div className="site-container">
<div className="max-w-2xl">
<p className="text-xs font-bold uppercase tracking-[0.2em] text-brand-600">Organization</p>
<h2 className="mt-3 text-2xl font-black tracking-tight text-brand-950 sm:text-3xl">조직도</h2>
<p className="mt-3 text-sm leading-7 text-slate-500">
주민과 함께하는 협의회의 조직 구성입니다.
</p>
</div>
<div className="mt-8 overflow-hidden rounded-2xl border border-slate-200 bg-slate-50 p-4 sm:p-8">
<Image
src="/images/organization-chart.png"
alt="용산 공중케이블 주민 안전 협의회 조직도"
width={1479}
height={906}
sizes="(min-width: 1024px) 960px, 90vw"
className="mx-auto h-auto w-full max-w-4xl"
/>
</div>
</div>
</section>
<section className="site-container py-14 sm:py-20">
<div className="grid gap-8 rounded-3xl border border-slate-200 bg-white p-6 sm:p-10 lg:grid-cols-[0.9fr_1.1fr]">
<div>
<p className="text-xs font-bold uppercase tracking-[0.2em] text-brand-600">Contact</p>
<h2 className="mt-3 text-2xl font-black tracking-tight text-brand-950">
함께하고 싶으신가요?
</h2>
<p className="mt-3 text-sm leading-7 text-slate-500">
협의회 활동에 관심이 있거나 참여를 원하시는 분은 언제든 연락해 주세요. 주민 제보와 제안을
기다립니다.
</p>
<div className="mt-6 space-y-2 text-sm text-slate-600">
<p className="flex items-start gap-2">
<MapPin className="mt-0.5 h-4 w-4 shrink-0 text-brand-600" aria-hidden />
{settings.address}
</p>
{settings.contactPhone ? <p>전화 · {settings.contactPhone}</p> : null}
{settings.contactEmail ? <p>이메일 · {settings.contactEmail}</p> : null}
</div>
<Link
href="/contact"
className="mt-6 inline-flex items-center gap-2 rounded-xl bg-brand-900 px-5 py-3 text-sm font-bold text-white transition hover:bg-brand-800"
>
문의·제보 남기기
<ArrowRight className="h-4 w-4" aria-hidden />
</Link>
</div>
<div className="rounded-2xl bg-brand-50 p-6">
<h3 className="text-sm font-bold text-brand-950">이런 내용을 알려주세요</h3>
<ul className="mt-4 space-y-3 text-sm leading-7 text-slate-600">
<li>· 전선이 과도하게 얽혀 있거나 늘어진 위치</li>
<li>· 폐선으로 의심되는 전선</li>
<li>· 보행자·차량 통행에 위험이 있는 낮은 전선</li>
<li>· 전신주·통신 설비의 훼손 상태</li>
<li>· 정비가 필요하다고 생각하는 기타 의견</li>
</ul>
<p className="mt-4 text-xs leading-6 text-slate-500">
위치(동명, 도로명, 건물 주변)를 구체적으로 알려주시면 확인에 도움이 됩니다.
</p>
</div>
</div>
</section>
</>
);
}
+145
View File
@@ -0,0 +1,145 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, Eye } from "lucide-react";
import { AttachmentList } from "@/components/site/attachment-list";
import { MarkdownContent } from "@/components/site/markdown-content";
import { formatDateTime } from "@/lib/constants";
import { getAdjacentPosts, getPost, incrementViewCount } from "@/lib/posts";
export const dynamic = "force-dynamic";
type Params = Promise<{ id: string }>;
function plainText(content: string) {
return content
.replace(/[#>*_`~\-[\]()]/g, " ")
.replace(/\s+/g, " ")
.trim()
.slice(0, 150);
}
export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
const { id } = await params;
const post = await getPost(Number(id), "ARCHIVE");
if (!post || post.status !== "PUBLISHED") {
return { title: "자료실" };
}
const canonical = `/archive/${post.id}`;
return {
title: post.title,
description: plainText(post.content),
alternates: { canonical },
openGraph: {
title: post.title,
description: plainText(post.content),
url: canonical,
type: "article",
publishedTime: post.publishedAt.toISOString(),
},
};
}
export default async function ArchiveDetailPage({ params }: { params: Params }) {
const { id } = await params;
const postId = Number(id);
if (!Number.isInteger(postId) || postId <= 0) notFound();
await incrementViewCount(postId);
const post = await getPost(postId, "ARCHIVE");
if (!post || post.status !== "PUBLISHED") notFound();
const { prev, next } = await getAdjacentPosts(post);
const articleJsonLd = {
"@context": "https://schema.org",
"@type": "Article",
headline: post.title,
datePublished: post.publishedAt.toISOString(),
dateModified: post.updatedAt.toISOString(),
author: { "@type": "Organization", name: post.author?.name ?? "용산 공중케이블 주민 안전 협의회" },
publisher: { "@type": "Organization", name: "용산 공중케이블 주민 안전 협의회" },
};
return (
<>
<article className="site-container py-10 sm:py-14">
<Link
href="/archive"
className="inline-flex items-center gap-1.5 text-xs font-bold text-slate-500 transition hover:text-brand-700"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden />
자료실 목록
</Link>
<header className="mt-5 border-b border-slate-200 pb-7">
<div className="flex flex-wrap items-center gap-2">
<span className="rounded-md bg-brand-50 px-2.5 py-1 text-[11px] font-bold text-brand-700">
{post.category || "자료"}
</span>
</div>
<h1 className="mt-4 text-2xl font-black leading-snug tracking-tight text-brand-950 sm:text-3xl">
{post.title}
</h1>
<div className="mt-4 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-slate-400">
<span>{post.author?.name ?? "관리자"}</span>
<time dateTime={post.publishedAt.toISOString()}>{formatDateTime(post.publishedAt)}</time>
<span className="inline-flex items-center gap-1">
<Eye className="h-3.5 w-3.5" aria-hidden />
{post.viewCount.toLocaleString("ko-KR")}
</span>
</div>
</header>
<AttachmentList attachments={post.attachments} />
<div className="mt-8">
<MarkdownContent content={post.content} />
</div>
<nav className="mt-10 divide-y divide-slate-200 border-y border-slate-200" aria-label="이전·다음 자료">
<div className="flex gap-4 py-4">
<span className="w-14 shrink-0 text-xs font-bold text-slate-400">이전 자료</span>
{prev ? (
<Link href={`/archive/${prev.id}`} className="line-clamp-1 text-sm font-semibold text-slate-600 hover:text-brand-800">
{prev.title}
</Link>
) : (
<span className="text-sm text-slate-300">이전 자료가 없습니다.</span>
)}
</div>
<div className="flex gap-4 py-4">
<span className="w-14 shrink-0 text-xs font-bold text-slate-400">다음 자료</span>
{next ? (
<Link href={`/archive/${next.id}`} className="line-clamp-1 text-sm font-semibold text-slate-600 hover:text-brand-800">
{next.title}
</Link>
) : (
<span className="text-sm text-slate-300">다음 자료가 없습니다.</span>
)}
</div>
</nav>
<div className="mt-8 text-center">
<Link
href="/archive"
className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-5 py-3 text-sm font-bold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
<ArrowLeft className="h-4 w-4" aria-hidden />
목록으로
</Link>
</div>
</article>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(articleJsonLd) }}
/>
</>
);
}
+149
View File
@@ -0,0 +1,149 @@
import type { Metadata } from "next";
import Link from "next/link";
import { Search } from "lucide-react";
import { BoardList } from "@/components/site/board-list";
import { EmptyState } from "@/components/site/empty-state";
import { PageHero } from "@/components/site/page-hero";
import { Pagination } from "@/components/site/pagination";
import { getCategories, getPosts } from "@/lib/posts";
export const metadata: Metadata = {
title: "자료실",
description: "용산 공중케이블 주민 안전 협의회의 보고서, 회의자료, 서식과 홍보물을 내려받을 수 있습니다.",
alternates: { canonical: "/archive" },
};
export const dynamic = "force-dynamic";
type SearchParams = Promise<{
page?: string;
q?: string;
category?: string;
}>;
export default async function ArchivePage({ searchParams }: { searchParams: SearchParams }) {
const params = await searchParams;
const page = Math.max(1, Number.parseInt(params.page ?? "1", 10) || 1);
const query = (params.q ?? "").trim();
const category = (params.category ?? "").trim();
const [{ posts, total, totalPages }, categories] = await Promise.all([
getPosts({ type: "ARCHIVE", page, query, category }),
getCategories("ARCHIVE"),
]);
function categoryHref(value: string) {
const next = new URLSearchParams();
if (query) next.set("q", query);
if (value) next.set("category", value);
const search = next.toString();
return `/archive${search ? `?${search}` : ""}`;
}
return (
<>
<PageHero
eyebrow="Archive"
title="자료실"
description="조사 보고서, 회의자료, 서식과 홍보물을 한곳에서 확인하고 내려받으세요."
breadcrumb={[{ label: "자료실" }]}
/>
<div className="site-container py-10 sm:py-14">
<div className="flex flex-wrap items-center justify-between gap-4">
<p className="text-sm text-slate-500">
전체 <span className="font-bold text-brand-800">{total.toLocaleString("ko-KR")}</span>건
</p>
<form action="/archive" method="get" className="flex w-full max-w-md items-center gap-2 sm:w-auto">
<label htmlFor="archive-category" className="sr-only">
분류
</label>
<select
id="archive-category"
name="category"
defaultValue={category}
className="h-10 rounded-lg border border-slate-200 bg-white px-3 text-sm text-slate-600 focus:border-brand-400"
>
<option value="">전체 분류</option>
{categories.map((item) => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
<div className="relative min-w-0 flex-1 sm:w-64">
<label htmlFor="archive-search" className="sr-only">
검색어
</label>
<input
id="archive-search"
name="q"
defaultValue={query}
placeholder="제목·내용 검색"
className="h-10 w-full rounded-lg border border-slate-200 bg-white pl-9 pr-3 text-sm text-slate-700 placeholder:text-slate-400 focus:border-brand-400"
/>
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" aria-hidden />
</div>
<button
type="submit"
className="h-10 shrink-0 rounded-lg bg-brand-900 px-4 text-sm font-bold text-white transition hover:bg-brand-800"
>
검색
</button>
</form>
</div>
<div className="mt-4 flex flex-wrap gap-2">
<Link
href={categoryHref("")}
className={`rounded-full px-3.5 py-1.5 text-xs font-bold transition ${
category === "" ? "bg-brand-900 text-white" : "border border-slate-200 bg-white text-slate-600 hover:border-brand-200"
}`}
>
전체
</Link>
{categories.map((item) => (
<Link
key={item}
href={categoryHref(item)}
className={`rounded-full px-3.5 py-1.5 text-xs font-bold transition ${
category === item
? "bg-brand-900 text-white"
: "border border-slate-200 bg-white text-slate-600 hover:border-brand-200"
}`}
>
{item}
</Link>
))}
</div>
<div className="mt-6">
{posts.length > 0 ? (
<BoardList posts={posts} basePath="/archive" variant="archive" />
) : (
<EmptyState
title={query ? "검색 결과가 없습니다." : "등록된 자료가 없습니다."}
description={query ? "다른 검색어로 다시 시도해 보세요." : "새로운 자료가 등록되면 이곳에서 확인하실 수 있습니다."}
action={
query ? (
<Link href="/archive" className="text-sm font-bold text-brand-700 hover:text-brand-500">
전체 목록 보기
</Link>
) : null
}
/>
)}
</div>
<Pagination
currentPage={page}
totalPages={totalPages}
basePath="/archive"
query={{ q: query || undefined, category: category || undefined }}
/>
</div>
</>
);
}
+117
View File
@@ -0,0 +1,117 @@
import type { Metadata } from "next";
import { CheckCircle2, Clock, Mail, MapPin, Phone } from "lucide-react";
import { InquiryForm } from "@/components/site/inquiry-form";
import { PageHero } from "@/components/site/page-hero";
import { getSettings } from "@/lib/settings";
export const metadata: Metadata = {
title: "문의·제보",
description: "용산 공중케이블 관련 문의와 현장 제보를 접수합니다.",
alternates: { canonical: "/contact" },
};
export const dynamic = "force-dynamic";
type SearchParams = Promise<{ submitted?: string }>;
export default async function ContactPage({ searchParams }: { searchParams: SearchParams }) {
const [params, settings] = await Promise.all([searchParams, getSettings()]);
const submitted = params.submitted === "1";
return (
<>
<PageHero
eyebrow="Contact"
title="문의·제보"
description="위험한 전선, 정비가 필요한 위치, 협의회 활동에 대한 궁금증을 남겨 주세요."
breadcrumb={[{ label: "문의·제보" }]}
/>
<div className="site-container grid gap-8 py-10 sm:py-14 lg:grid-cols-[1.3fr_0.7fr]">
<section className="rounded-2xl border border-slate-200 bg-white p-6 sm:p-8">
<h2 className="text-lg font-black text-brand-950">제보·문의 작성</h2>
<p className="mt-2 text-sm leading-7 text-slate-500">
접수된 내용은 협의회에서 확인한 뒤 처리 결과를 이메일로 안내드립니다. 답변까지 다소 시간이 걸릴 수 있습니다.
</p>
{submitted ? (
<div className="mt-6 flex items-start gap-3 rounded-xl bg-emerald-50 px-4 py-4">
<CheckCircle2 className="mt-0.5 h-5 w-5 shrink-0 text-emerald-600" aria-hidden />
<div>
<p className="text-sm font-bold text-emerald-800">문의가 정상 접수되었습니다.</p>
<p className="mt-1 text-xs leading-6 text-emerald-700">
확인 후 기재하신 이메일로 답변드리겠습니다. 감사합니다.
</p>
</div>
</div>
) : null}
<div className="mt-6">
<InquiryForm />
</div>
</section>
<aside className="space-y-5">
<div className="rounded-2xl border border-slate-200 bg-white p-6">
<h2 className="text-sm font-bold text-brand-950">연락처</h2>
<ul className="mt-4 space-y-3 text-sm text-slate-600">
<li className="flex items-start gap-2.5">
<MapPin className="mt-0.5 h-4 w-4 shrink-0 text-brand-600" aria-hidden />
{settings.address}
</li>
{settings.contactPhone ? (
<li className="flex items-center gap-2.5">
<Phone className="h-4 w-4 shrink-0 text-brand-600" aria-hidden />
<a href={`tel:${settings.contactPhone}`} className="hover:text-brand-800">
{settings.contactPhone}
</a>
</li>
) : null}
{settings.contactEmail ? (
<li className="flex items-center gap-2.5">
<Mail className="h-4 w-4 shrink-0 text-brand-600" aria-hidden />
<a href={`mailto:${settings.contactEmail}`} className="break-all hover:text-brand-800">
{settings.contactEmail}
</a>
</li>
) : null}
<li className="flex items-start gap-2.5">
<Clock className="mt-0.5 h-4 w-4 shrink-0 text-brand-600" aria-hidden />
<span>
홈페이지 문의는 상시 접수됩니다.
<br />
답변은 영업일 기준 2~3일 소요될 수 있습니다.
</span>
</li>
</ul>
</div>
<div className="rounded-2xl border border-brand-200 bg-brand-50 p-6">
<h2 className="text-sm font-bold text-brand-950">이런 내용을 알려주세요</h2>
<ul className="mt-3 space-y-2 text-xs leading-6 text-slate-600">
<li>· 전선이 과도하게 얽혀 있거나 늘어진 위치</li>
<li>· 폐선으로 의심되는 전선</li>
<li>· 보행자·차량 통행에 위험이 있는 낮은 전선</li>
<li>· 전신주·통신 설비의 훼손 상태</li>
</ul>
<p className="mt-3 text-xs leading-6 text-slate-500">
위치는 동명, 도로명, 건물 주변 등 최대한 구체적으로 적어 주시면 확인에 도움이 됩니다.
</p>
</div>
<div className="rounded-2xl border border-slate-200 bg-white p-6">
<h2 className="text-sm font-bold text-brand-950">개인정보 안내</h2>
<p className="mt-3 text-xs leading-6 text-slate-500">
입력하신 정보는 문의 처리 목적으로만 사용되며, 처리 완료 후 관련 법령에 따라 파기합니다. 자세한 내용은{" "}
<a href="/privacy" className="font-semibold text-brand-700 underline underline-offset-2">
개인정보처리방침
</a>
을 참고해 주세요.
</p>
</div>
</aside>
</div>
</>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { getSettings } from "@/lib/settings";
import { SiteFooter } from "@/components/site/site-footer";
import { SiteHeader } from "@/components/site/site-header";
export const dynamic = "force-dynamic";
export default async function SiteLayout({ children }: { children: React.ReactNode }) {
const settings = await getSettings();
const organizationJsonLd = {
"@context": "https://schema.org",
"@type": "Organization",
name: settings.siteName,
alternateName: settings.shortName,
description: settings.description,
url: process.env.NEXT_PUBLIC_SITE_URL ?? "https://saftyovhcable.kr",
address: {
"@type": "PostalAddress",
addressLocality: "서울특별시 용산구",
addressCountry: "KR",
},
};
return (
<>
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-50 focus:rounded-lg focus:bg-brand-900 focus:px-4 focus:py-2 focus:text-sm focus:font-semibold focus:text-white"
>
본문 바로가기
</a>
<SiteHeader settings={settings} />
<main id="main-content">{children}</main>
<SiteFooter settings={settings} />
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(organizationJsonLd) }}
/>
</>
);
}
+153
View File
@@ -0,0 +1,153 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, Eye, Pin } from "lucide-react";
import { AttachmentList } from "@/components/site/attachment-list";
import { MarkdownContent } from "@/components/site/markdown-content";
import { formatDateTime } from "@/lib/constants";
import { getAdjacentPosts, getPost, incrementViewCount } from "@/lib/posts";
export const dynamic = "force-dynamic";
type Params = Promise<{ id: string }>;
function plainText(content: string) {
return content
.replace(/[#>*_`~\-[\]()]/g, " ")
.replace(/\s+/g, " ")
.trim()
.slice(0, 150);
}
export async function generateMetadata({ params }: { params: Params }): Promise<Metadata> {
const { id } = await params;
const post = await getPost(Number(id), "NOTICE");
if (!post || post.status !== "PUBLISHED") {
return { title: "공지사항" };
}
const canonical = `/news/notice/${post.id}`;
return {
title: post.title,
description: plainText(post.content),
alternates: { canonical },
openGraph: {
title: post.title,
description: plainText(post.content),
url: canonical,
type: "article",
publishedTime: post.publishedAt.toISOString(),
},
};
}
export default async function NoticeDetailPage({ params }: { params: Params }) {
const { id } = await params;
const postId = Number(id);
if (!Number.isInteger(postId) || postId <= 0) notFound();
await incrementViewCount(postId);
const post = await getPost(postId, "NOTICE");
if (!post || post.status !== "PUBLISHED") notFound();
const { prev, next } = await getAdjacentPosts(post);
const articleJsonLd = {
"@context": "https://schema.org",
"@type": "Article",
headline: post.title,
datePublished: post.publishedAt.toISOString(),
dateModified: post.updatedAt.toISOString(),
author: { "@type": "Organization", name: post.author?.name ?? "용산 공중케이블 주민 안전 협의회" },
publisher: { "@type": "Organization", name: "용산 공중케이블 주민 안전 협의회" },
};
return (
<>
<article className="site-container py-10 sm:py-14">
<Link
href="/news/notice"
className="inline-flex items-center gap-1.5 text-xs font-bold text-slate-500 transition hover:text-brand-700"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden />
공지사항 목록
</Link>
<header className="mt-5 border-b border-slate-200 pb-7">
<div className="flex flex-wrap items-center gap-2">
<span className="rounded-md bg-brand-50 px-2.5 py-1 text-[11px] font-bold text-brand-700">
{post.category || "공지"}
</span>
{post.isPinned ? (
<span className="inline-flex items-center gap-1 rounded-md bg-accent-500/15 px-2.5 py-1 text-[11px] font-bold text-accent-700">
<Pin className="h-3 w-3" aria-hidden />
고정
</span>
) : null}
</div>
<h1 className="mt-4 text-2xl font-black leading-snug tracking-tight text-brand-950 sm:text-3xl">
{post.title}
</h1>
<div className="mt-4 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-slate-400">
<span>{post.author?.name ?? "관리자"}</span>
<time dateTime={post.publishedAt.toISOString()}>{formatDateTime(post.publishedAt)}</time>
<span className="inline-flex items-center gap-1">
<Eye className="h-3.5 w-3.5" aria-hidden />
{post.viewCount.toLocaleString("ko-KR")}
</span>
</div>
</header>
<div className="mt-8">
<MarkdownContent content={post.content} />
</div>
<AttachmentList attachments={post.attachments} />
<nav className="mt-10 divide-y divide-slate-200 border-y border-slate-200" aria-label="이전·다음 글">
<div className="flex gap-4 py-4">
<span className="w-14 shrink-0 text-xs font-bold text-slate-400">이전 글</span>
{prev ? (
<Link href={`/news/notice/${prev.id}`} className="line-clamp-1 text-sm font-semibold text-slate-600 hover:text-brand-800">
{prev.title}
</Link>
) : (
<span className="text-sm text-slate-300">이전 글이 없습니다.</span>
)}
</div>
<div className="flex gap-4 py-4">
<span className="w-14 shrink-0 text-xs font-bold text-slate-400">다음 글</span>
{next ? (
<Link href={`/news/notice/${next.id}`} className="line-clamp-1 text-sm font-semibold text-slate-600 hover:text-brand-800">
{next.title}
</Link>
) : (
<span className="text-sm text-slate-300">다음 글이 없습니다.</span>
)}
</div>
</nav>
<div className="mt-8 text-center">
<Link
href="/news/notice"
className="inline-flex items-center gap-2 rounded-xl border border-slate-200 bg-white px-5 py-3 text-sm font-bold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
<ArrowLeft className="h-4 w-4" aria-hidden />
목록으로
</Link>
</div>
</article>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(articleJsonLd) }}
/>
</>
);
}
+149
View File
@@ -0,0 +1,149 @@
import type { Metadata } from "next";
import Link from "next/link";
import { Search } from "lucide-react";
import { BoardList } from "@/components/site/board-list";
import { EmptyState } from "@/components/site/empty-state";
import { PageHero } from "@/components/site/page-hero";
import { Pagination } from "@/components/site/pagination";
import { getCategories, getPosts } from "@/lib/posts";
export const metadata: Metadata = {
title: "공지사항",
description: "용산 공중케이블 주민 안전 협의회의 공지사항과 행사 소식을 확인하세요.",
alternates: { canonical: "/news/notice" },
};
export const dynamic = "force-dynamic";
type SearchParams = Promise<{
page?: string;
q?: string;
category?: string;
}>;
export default async function NoticePage({ searchParams }: { searchParams: SearchParams }) {
const params = await searchParams;
const page = Math.max(1, Number.parseInt(params.page ?? "1", 10) || 1);
const query = (params.q ?? "").trim();
const category = (params.category ?? "").trim();
const [{ posts, total, totalPages }, categories] = await Promise.all([
getPosts({ type: "NOTICE", page, query, category }),
getCategories("NOTICE"),
]);
function categoryHref(value: string) {
const next = new URLSearchParams();
if (query) next.set("q", query);
if (value) next.set("category", value);
const search = next.toString();
return `/news/notice${search ? `?${search}` : ""}`;
}
return (
<>
<PageHero
eyebrow="News"
title="공지사항"
description="협의회의 주요 소식과 행사, 주민 안내를 전합니다."
breadcrumb={[{ label: "공지사항" }]}
/>
<div className="site-container py-10 sm:py-14">
<div className="flex flex-wrap items-center justify-between gap-4">
<p className="text-sm text-slate-500">
전체 <span className="font-bold text-brand-800">{total.toLocaleString("ko-KR")}</span>건
</p>
<form action="/news/notice" method="get" className="flex w-full max-w-md items-center gap-2 sm:w-auto">
<label htmlFor="notice-category" className="sr-only">
분류
</label>
<select
id="notice-category"
name="category"
defaultValue={category}
className="h-10 rounded-lg border border-slate-200 bg-white px-3 text-sm text-slate-600 focus:border-brand-400"
>
<option value="">전체 분류</option>
{categories.map((item) => (
<option key={item} value={item}>
{item}
</option>
))}
</select>
<div className="relative min-w-0 flex-1 sm:w-64">
<label htmlFor="notice-search" className="sr-only">
검색어
</label>
<input
id="notice-search"
name="q"
defaultValue={query}
placeholder="제목·내용 검색"
className="h-10 w-full rounded-lg border border-slate-200 bg-white pl-9 pr-3 text-sm text-slate-700 placeholder:text-slate-400 focus:border-brand-400"
/>
<Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" aria-hidden />
</div>
<button
type="submit"
className="h-10 shrink-0 rounded-lg bg-brand-900 px-4 text-sm font-bold text-white transition hover:bg-brand-800"
>
검색
</button>
</form>
</div>
<div className="mt-4 flex flex-wrap gap-2">
<Link
href={categoryHref("")}
className={`rounded-full px-3.5 py-1.5 text-xs font-bold transition ${
category === "" ? "bg-brand-900 text-white" : "border border-slate-200 bg-white text-slate-600 hover:border-brand-200"
}`}
>
전체
</Link>
{categories.map((item) => (
<Link
key={item}
href={categoryHref(item)}
className={`rounded-full px-3.5 py-1.5 text-xs font-bold transition ${
category === item
? "bg-brand-900 text-white"
: "border border-slate-200 bg-white text-slate-600 hover:border-brand-200"
}`}
>
{item}
</Link>
))}
</div>
<div className="mt-6">
{posts.length > 0 ? (
<BoardList posts={posts} basePath="/news/notice" />
) : (
<EmptyState
title={query ? "검색 결과가 없습니다." : "등록된 공지사항이 없습니다."}
description={query ? "다른 검색어로 다시 시도해 보세요." : "새로운 소식이 등록되면 이곳에서 확인하실 수 있습니다."}
action={
query ? (
<Link href="/news/notice" className="text-sm font-bold text-brand-700 hover:text-brand-500">
전체 목록 보기
</Link>
) : null
}
/>
)}
</div>
<Pagination
currentPage={page}
totalPages={totalPages}
basePath="/news/notice"
query={{ q: query || undefined, category: category || undefined }}
/>
</div>
</>
);
}
+46
View File
@@ -0,0 +1,46 @@
import Link from "next/link";
import { ArrowLeft, SearchX } from "lucide-react";
export default function SiteNotFound() {
return (
<div className="site-container flex min-h-[60vh] flex-col items-center justify-center py-20 text-center">
<span className="grid h-14 w-14 place-items-center rounded-2xl bg-brand-50 text-brand-600">
<SearchX className="h-6 w-6" aria-hidden />
</span>
<p className="mt-6 text-xs font-bold uppercase tracking-[0.2em] text-brand-600">404 Not Found</p>
<h1 className="mt-2 text-2xl font-black tracking-tight text-brand-950 sm:text-3xl">
요청하신 페이지를 찾을 수 없습니다.
</h1>
<p className="mt-3 max-w-md text-sm leading-7 text-slate-500">
주소가 변경되었거나 삭제된 페이지일 수 있습니다. 아래 메뉴에서 원하시는 내용을 찾아보세요.
</p>
<div className="mt-7 flex flex-wrap justify-center gap-2">
<Link
href="/"
className="inline-flex items-center gap-2 rounded-xl bg-brand-900 px-5 py-3 text-sm font-bold text-white transition hover:bg-brand-800"
>
<ArrowLeft className="h-4 w-4" aria-hidden />
홈으로
</Link>
<Link
href="/news/notice"
className="rounded-xl border border-slate-200 bg-white px-5 py-3 text-sm font-bold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
공지사항
</Link>
<Link
href="/archive"
className="rounded-xl border border-slate-200 bg-white px-5 py-3 text-sm font-bold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
자료실
</Link>
<Link
href="/contact"
className="rounded-xl border border-slate-200 bg-white px-5 py-3 text-sm font-bold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
문의·제보
</Link>
</div>
</div>
);
}
+402
View File
@@ -0,0 +1,402 @@
import Image from "next/image";
import Link from "next/link";
import type { Metadata } from "next";
import {
ArrowRight,
ExternalLink,
FileText,
MapPin,
Megaphone,
Rss,
ShieldCheck,
Sparkles,
} from "lucide-react";
import { SectionHeading } from "@/components/site/section-heading";
import { getLatestBlogPosts } from "@/lib/blog";
import { formatDate, SURVEY_COUNT_LABEL } from "@/lib/constants";
import { getLatestPosts } from "@/lib/posts";
import { getSettings } from "@/lib/settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = {
alternates: { canonical: "/" },
};
export default async function HomePage() {
const [settings, notices, archives, blogPosts] = await Promise.all([
getSettings(),
getLatestPosts("NOTICE", 4),
getLatestPosts("ARCHIVE", 3),
getLatestBlogPosts(),
]);
return (
<>
<section className="relative overflow-hidden bg-brand-950 text-white">
<div
className="pointer-events-none absolute inset-0 opacity-80"
style={{
background:
"radial-gradient(circle at 12% 18%, rgba(64,160,191,0.38), transparent 34%), radial-gradient(circle at 88% 8%, rgba(242,183,5,0.16), transparent 30%), linear-gradient(180deg, rgba(11,37,50,0) 60%, rgba(11,37,50,0.75) 100%)",
}}
aria-hidden
/>
<div className="site-container relative grid items-center gap-12 py-16 sm:py-20 lg:grid-cols-[1.05fr_0.95fr] lg:py-24">
<div>
<p className="inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 px-3 py-1.5 text-[11px] font-bold tracking-wide text-brand-100">
<Sparkles className="h-3.5 w-3.5 text-accent-400" aria-hidden />
용산의 안전한 거리 환경을 위해
</p>
<h1 className="mt-5 text-4xl font-black leading-[1.18] tracking-tight sm:text-5xl lg:text-[3.4rem]">
깨끗한 도시를 위한
<br />
<span className="text-accent-400">첫걸음</span>
</h1>
<p className="mt-5 max-w-xl text-sm leading-7 text-slate-300 sm:text-base">
전신주 정비로 안전하고 아름다운 도시를 만듭니다. 용산 공중케이블 주민 안전 협의회는
주민의 눈으로 문제를 기록하고, 관련 기관과 함께 해결책을 만들어갑니다.
</p>
<div className="mt-8 flex flex-wrap gap-3">
<a
href={settings.mapUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-2 rounded-xl bg-accent-500 px-5 py-3 text-sm font-bold text-brand-950 transition hover:bg-accent-400"
>
<MapPin className="h-4 w-4" aria-hidden />
조사 현황 보기
<ExternalLink className="h-3.5 w-3.5" aria-hidden />
</a>
<Link
href="/about"
className="inline-flex items-center gap-2 rounded-xl border border-white/20 bg-white/5 px-5 py-3 text-sm font-bold text-white transition hover:bg-white/10"
>
협의회 소개
<ArrowRight className="h-4 w-4" aria-hidden />
</Link>
</div>
<dl className="mt-10 grid max-w-lg grid-cols-3 gap-4 border-t border-white/10 pt-6">
<div>
<dt className="text-[11px] font-semibold text-slate-400">현장 조사</dt>
<dd className="mt-1 text-2xl font-black text-white">{SURVEY_COUNT_LABEL}</dd>
</div>
<div>
<dt className="text-[11px] font-semibold text-slate-400">활동 시작</dt>
<dd className="mt-1 text-2xl font-black text-white">2024</dd>
</div>
<div>
<dt className="text-[11px] font-semibold text-slate-400">활동 지역</dt>
<dd className="mt-1 text-2xl font-black text-white">용산구</dd>
</div>
</dl>
</div>
<div className="relative mx-auto w-full max-w-md lg:max-w-none">
<div className="relative aspect-[4/5] overflow-hidden rounded-[2rem] border border-white/10 shadow-2xl">
<Image
src="/images/exam-bad.jpg"
alt="공중케이블이 복잡하게 얽힌 전신주"
fill
priority
sizes="(min-width: 1024px) 42vw, 90vw"
className="object-cover"
/>
<div className="absolute inset-0 bg-gradient-to-t from-brand-950/70 via-transparent to-transparent" />
<div className="absolute bottom-5 left-5 right-5 rounded-2xl border border-white/15 bg-brand-950/70 p-4 backdrop-blur">
<p className="text-xs font-bold text-accent-400">현장의 기록</p>
<p className="mt-1 text-sm font-semibold leading-6 text-white">
복잡한 공중케이블, 주민이 직접 기록하고 있습니다.
</p>
</div>
</div>
<div className="absolute -bottom-6 -right-3 hidden w-36 overflow-hidden rounded-2xl border-4 border-brand-950 shadow-xl sm:block lg:-right-6 lg:w-44">
<Image
src="/images/exam-good.jpg"
alt="정비 후 깔끔해진 전신주"
width={800}
height={1067}
sizes="176px"
className="h-auto w-full object-cover"
/>
</div>
</div>
</div>
</section>
<section className="site-container py-16 sm:py-20">
<SectionHeading
eyebrow="Why"
title="왜 공중케이블 문제를 다루나요?"
description="도시에 산재한 공중케이블은 미관뿐 아니라 안전과 생활환경에 직접 영향을 줍니다."
/>
<div className="mt-8 grid gap-5 md:grid-cols-3">
{[
{
icon: Sparkles,
title: "도시 미관 훼손",
body: "전신주를 뒤덮은 전선과 폐선은 거리의 경관을 해치고 도시의 인상을 복잡하게 만듭니다.",
},
{
icon: ShieldCheck,
title: "안전사고 위험",
body: "늘어진 전선, 낮은 높이의 전선, 노후 설비는 보행자와 주민에게 위험 요소가 됩니다.",
},
{
icon: Megaphone,
title: "주민 참여로 해결",
body: "현장 조사와 주민 제보를 바탕으로 구청, 통신사와 함께 실질적인 정비 방안을 논의합니다.",
},
].map((item) => (
<article key={item.title} className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
<span className="grid h-11 w-11 place-items-center rounded-xl bg-brand-50 text-brand-700">
<item.icon className="h-5 w-5" aria-hidden />
</span>
<h3 className="mt-4 text-base font-bold text-brand-950">{item.title}</h3>
<p className="mt-2 text-sm leading-7 text-slate-500">{item.body}</p>
</article>
))}
</div>
<div className="mt-8 grid gap-5 lg:grid-cols-2">
<figure className="overflow-hidden rounded-3xl border border-slate-200 bg-white">
<div className="relative aspect-[16/10]">
<Image
src="/images/exam-bad.jpg"
alt="정비 전 복잡한 공중케이블"
fill
sizes="(min-width: 1024px) 50vw, 90vw"
className="object-cover"
/>
</div>
<figcaption className="flex items-center justify-between gap-3 px-5 py-4">
<span className="text-sm font-bold text-slate-700">정비 전</span>
<span className="rounded-full bg-rose-50 px-2.5 py-1 text-[11px] font-bold text-rose-600">개선 필요</span>
</figcaption>
</figure>
<figure className="overflow-hidden rounded-3xl border border-slate-200 bg-white">
<div className="relative aspect-[16/10]">
<Image
src="/images/exam-good.jpg"
alt="정비 후 깔끔해진 전신주"
fill
sizes="(min-width: 1024px) 50vw, 90vw"
className="object-cover"
/>
</div>
<figcaption className="flex items-center justify-between gap-3 px-5 py-4">
<span className="text-sm font-bold text-slate-700">정비 후</span>
<span className="rounded-full bg-emerald-50 px-2.5 py-1 text-[11px] font-bold text-emerald-600">
안전·쾌적
</span>
</figcaption>
</figure>
</div>
</section>
<section className="border-y border-slate-200 bg-white py-16 sm:py-20">
<div className="site-container">
<SectionHeading
eyebrow="News"
title="협의회 소식"
description="공지사항·자료실과 블로그의 최신 소식을 확인하세요."
href="/news/notice"
/>
<div className="mt-8 grid gap-8 lg:grid-cols-[1.35fr_0.65fr]">
<div className="rounded-2xl border border-slate-200 bg-slate-50/60 p-2 sm:p-4">
<ul className="divide-y divide-slate-200">
{notices.map((post) => (
<li key={post.id}>
<Link
href={`/news/notice/${post.id}`}
className="group flex flex-wrap items-center gap-x-3 gap-y-1 rounded-xl px-3 py-4 transition hover:bg-white"
>
<span className="rounded-md bg-brand-50 px-2 py-1 text-[11px] font-bold text-brand-700">
{post.category || "공지"}
</span>
{post.isPinned ? (
<span className="rounded-md bg-accent-500/15 px-2 py-1 text-[11px] font-bold text-accent-700">
고정
</span>
) : null}
<span className="min-w-0 flex-1 truncate text-sm font-semibold text-slate-700 group-hover:text-brand-800">
{post.title}
</span>
<span className="text-xs text-slate-400">{formatDate(post.publishedAt)}</span>
</Link>
</li>
))}
{notices.length === 0 ? (
<li className="px-3 py-10 text-center text-sm text-slate-400">등록된 공지사항이 없습니다.</li>
) : null}
</ul>
<div className="px-3 pb-3 pt-2">
<Link
href="/news/notice"
className="inline-flex items-center gap-1.5 text-xs font-bold text-brand-700 hover:text-brand-500"
>
공지사항 전체보기
<ArrowRight className="h-3.5 w-3.5" aria-hidden />
</Link>
</div>
</div>
<div className="rounded-2xl border border-slate-200 bg-white p-5">
<h3 className="flex items-center gap-2 text-sm font-bold text-brand-950">
<FileText className="h-4 w-4 text-brand-600" aria-hidden />
최신 자료
</h3>
<ul className="mt-4 space-y-4">
{archives.map((post) => (
<li key={post.id}>
<Link href={`/archive/${post.id}`} className="group block">
<p className="text-[11px] font-bold text-brand-600">{post.category || "자료"}</p>
<p className="mt-1 line-clamp-2 text-sm font-semibold leading-6 text-slate-700 group-hover:text-brand-800">
{post.title}
</p>
<p className="mt-1 text-[11px] text-slate-400">
{formatDate(post.publishedAt)} · 첨부 {post._count.attachments}개
</p>
</Link>
</li>
))}
{archives.length === 0 ? (
<li className="py-6 text-center text-sm text-slate-400">등록된 자료가 없습니다.</li>
) : null}
</ul>
<Link
href="/archive"
className="mt-5 inline-flex items-center gap-1.5 text-xs font-bold text-brand-700 hover:text-brand-500"
>
자료실 전체보기
<ArrowRight className="h-3.5 w-3.5" aria-hidden />
</Link>
</div>
</div>
{blogPosts.length > 0 ? (
<div className="mt-6 rounded-2xl border border-slate-200 bg-white p-5 sm:p-6">
<div className="flex flex-wrap items-center justify-between gap-3">
<h3 className="flex items-center gap-2 text-sm font-bold text-brand-950">
<Rss className="h-4 w-4 text-brand-600" aria-hidden />
블로그 최신글
</h3>
<a
href={settings.blogUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1.5 text-xs font-bold text-brand-700 hover:text-brand-500"
>
블로그 전체보기
<ExternalLink className="h-3.5 w-3.5" aria-hidden />
</a>
</div>
<ul className="mt-3 divide-y divide-slate-100">
{blogPosts.map((post) => (
<li key={post.url}>
<a
href={post.url}
target="_blank"
rel="noreferrer"
className="group flex items-center gap-3 py-3"
>
<span className="min-w-0 flex-1 truncate text-sm font-semibold text-slate-700 group-hover:text-brand-800">
{post.title}
</span>
{post.publishedAt ? (
<span className="shrink-0 text-xs text-slate-400">
{formatDate(post.publishedAt)}
</span>
) : null}
<ExternalLink
className="h-3.5 w-3.5 shrink-0 text-slate-300 group-hover:text-brand-600"
aria-hidden
/>
</a>
</li>
))}
</ul>
</div>
) : null}
</div>
</section>
<section className="site-container py-16 sm:py-20">
<div className="grid gap-6 lg:grid-cols-[1.2fr_0.8fr]">
<div className="relative overflow-hidden rounded-3xl bg-brand-900 p-8 text-white sm:p-10">
<div
className="pointer-events-none absolute inset-0 opacity-60"
style={{
background:
"radial-gradient(circle at 85% 15%, rgba(242,183,5,0.22), transparent 30%), radial-gradient(circle at 10% 90%, rgba(64,160,191,0.3), transparent 34%)",
}}
aria-hidden
/>
<div className="relative">
<p className="text-xs font-bold uppercase tracking-[0.2em] text-accent-400">Survey Map</p>
<h2 className="mt-3 text-2xl font-black tracking-tight sm:text-3xl">
용산구 곳곳의 조사 기록을 지도에서 확인하세요
</h2>
<p className="mt-4 max-w-xl text-sm leading-7 text-slate-300">
주민이 직접 촬영하고 기록한 전신주·공중케이블 조사 현황을 동별, 시기별로 살펴볼 수 있습니다.
현재는 기존 조사 지도로 연결되며, 지도 통합은 다음 단계에서 진행됩니다.
</p>
<a
href={settings.mapUrl}
target="_blank"
rel="noreferrer"
className="mt-6 inline-flex items-center gap-2 rounded-xl bg-white px-5 py-3 text-sm font-bold text-brand-900 transition hover:bg-slate-100"
>
<MapPin className="h-4 w-4" aria-hidden />
조사 현황 지도 열기
<ExternalLink className="h-3.5 w-3.5" aria-hidden />
</a>
</div>
</div>
<div className="flex flex-col justify-between rounded-3xl border border-slate-200 bg-white p-8">
<div>
<p className="text-xs font-bold uppercase tracking-[0.2em] text-brand-600">Together</p>
<h2 className="mt-3 text-xl font-black tracking-tight text-brand-950">
주민의 제보가 정비의 시작입니다
</h2>
<p className="mt-3 text-sm leading-7 text-slate-500">
위험한 전선, 늘어진 케이블, 정비가 필요한 위치를 알려주세요. 협의회가 확인하고 관련 기관과
함께 해결 방안을 찾겠습니다.
</p>
</div>
<Link
href="/contact"
className="mt-6 inline-flex items-center justify-center gap-2 rounded-xl bg-brand-900 px-5 py-3 text-sm font-bold text-white transition hover:bg-brand-800"
>
문의·제보 남기기
<ArrowRight className="h-4 w-4" aria-hidden />
</Link>
</div>
</div>
</section>
<section className="border-t border-slate-200 bg-white py-14">
<div className="site-container flex flex-col items-start justify-between gap-6 sm:flex-row sm:items-center">
<div>
<h2 className="text-lg font-black text-brand-950">협의회의 활동 소식이 궁금하신가요?</h2>
<p className="mt-2 text-sm text-slate-500">
네이버 블로그에서 현장 활동과 일상의 기록을 더 자세히 만나보세요.
</p>
</div>
<a
href={settings.blogUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-5 py-3 text-sm font-bold text-brand-800 transition hover:bg-brand-100"
>
네이버 블로그 바로가기
<ExternalLink className="h-4 w-4" aria-hidden />
</a>
</div>
</section>
</>
);
}
+113
View File
@@ -0,0 +1,113 @@
import type { Metadata } from "next";
import { PageHero } from "@/components/site/page-hero";
import { SITE_NAME } from "@/lib/constants";
export const metadata: Metadata = {
title: "개인정보처리방침",
description: `${SITE_NAME}의 개인정보처리방침입니다.`,
alternates: { canonical: "/privacy" },
};
export default function PrivacyPage() {
return (
<>
<PageHero
eyebrow="Privacy"
title="개인정보처리방침"
description="협의회는 이용자의 개인정보를 소중히 여기며 관련 법령을 준수합니다."
breadcrumb={[{ label: "개인정보처리방침" }]}
/>
<div className="site-container py-10 sm:py-14">
<div className="prose-yg max-w-3xl rounded-2xl border border-slate-200 bg-white p-6 sm:p-10">
<p className="text-sm text-slate-500">
시행일: 2026년 10월 1일
</p>
<h2>제1조 (총칙)</h2>
<p>
{SITE_NAME}(이하 &ldquo;협의회&rdquo;)는 「개인정보 보호법」 등 관련 법령에 따라 이용자의 개인정보를 보호하고,
이와 관련한 고충을 신속하게 처리할 수 있도록 다음과 같이 개인정보처리방침을 수립·공개합니다.
</p>
<h2>제2조 (수집하는 개인정보의 항목 및 수집 방법)</h2>
<p>협의회는 문의·제보 접수 시 아래와 같은 최소한의 개인정보를 수집합니다.</p>
<ul>
<li>
<strong>필수 항목</strong>: 성함, 이메일 주소, 문의 내용
</li>
<li>
<strong>선택 항목</strong>: 연락처
</li>
<li>
<strong>자동 수집 항목</strong>: 접속 IP, 접속 일시 (서비스 안정성 확보 및 부정 이용 방지 목적)
</li>
</ul>
<p>수집 방법: 홈페이지 문의·제보 게시판을 통한 이용자 직접 입력</p>
<h2>제3조 (개인정보의 처리 목적)</h2>
<ul>
<li>문의·제보 내용 확인 및 답변</li>
<li>현장 조사 및 정비 요청 업무 수행</li>
<li>서비스 부정 이용 방지 및 접속 기록 관리</li>
</ul>
<h2>제4조 (개인정보의 보유 및 이용 기간)</h2>
<p>
수집된 개인정보는 처리 목적이 달성된 후 지체 없이 파기합니다. 다만 관련 법령에 따라 보존이 필요한 경우 아래 기간
동안 보관합니다.
</p>
<ul>
<li>문의·제보 처리 기록: 처리 완료 후 3년</li>
<li>접속 기록: 3개월</li>
</ul>
<h2>제5조 (개인정보의 제3자 제공)</h2>
<p>
협의회는 이용자의 개인정보를 원칙적으로 제3자에게 제공하지 않습니다. 다만 이용자가 사전에 동의한 경우 또는 법령의
규정에 따라 요구되는 경우에는 예외로 합니다.
</p>
<h2>제6조 (개인정보 처리의 위탁)</h2>
<p>협의회는 현재 개인정보 처리 업무를 외부에 위탁하고 있지 않습니다. 위탁이 발생할 경우 본 방침을 통해 사전에
안내하겠습니다.</p>
<h2>제7조 (정보주체의 권리·의무 및 행사 방법)</h2>
<p>
이용자는 언제든지 자신의 개인정보에 대한 열람·정정·삭제·처리정지를 요구할 수 있습니다. 요청은 아래 연락처로
접수해 주시면 지체 없이 처리하겠습니다.
</p>
<h2>제8조 (개인정보의 파기 절차 및 방법)</h2>
<ul>
<li>파기 절차: 보유 기간이 경과하거나 처리 목적이 달성된 개인정보는 내부 절차에 따라 파기합니다.</li>
<li>파기 방법: 전자적 파일 형태는 복구할 수 없는 방법으로 삭제하며, 출력물은 분쇄 또는 소각합니다.</li>
</ul>
<h2>제9조 (쿠키의 운영)</h2>
<p>
협의회 홈페이지는 관리자 로그인 유지 목적 외에는 쿠키를 사용하지 않습니다. 관리자 세션 쿠키는 로그인한 관리자에게만
발급되며, 로그아웃 또는 세션 만료 시 삭제됩니다.
</p>
<h2>제10조 (개인정보 보호책임자)</h2>
<p>
협의회는 개인정보 처리에 관한 업무를 총괄하고 관련 문의를 처리하기 위해 아래와 같이 개인정보 보호책임자를
지정하고 있습니다.
</p>
<ul>
<li>개인정보 보호책임자: {SITE_NAME} 운영진</li>
<li>문의: 홈페이지 문의·제보 메뉴 이용</li>
</ul>
<h2>제11조 (방침의 변경)</h2>
<p>
본 개인정보처리방침은 법령·정책 또는 서비스 변경에 따라 개정될 수 있습니다. 개정 시 홈페이지 공지사항을 통해
안내합니다.
</p>
</div>
</div>
</>
);
}
+102
View File
@@ -0,0 +1,102 @@
import type { Metadata } from "next";
import { PageHero } from "@/components/site/page-hero";
import { SITE_NAME } from "@/lib/constants";
export const metadata: Metadata = {
title: "이용약관",
description: `${SITE_NAME} 홈페이지 이용약관입니다.`,
alternates: { canonical: "/terms" },
};
export default function TermsPage() {
return (
<>
<PageHero
eyebrow="Terms"
title="이용약관"
description="홈페이지 이용에 관한 기본적인 사항을 안내합니다."
breadcrumb={[{ label: "이용약관" }]}
/>
<div className="site-container py-10 sm:py-14">
<div className="prose-yg max-w-3xl rounded-2xl border border-slate-200 bg-white p-6 sm:p-10">
<p className="text-sm text-slate-500">시행일: 2026년 10월 1일</p>
<h2>제1조 (목적)</h2>
<p>
본 약관은 {SITE_NAME}(이하 &ldquo;협의회&rdquo;)가 운영하는 홈페이지의 이용 조건과 절차, 이용자와 협의회의 권리·의무
및 책임 사항을 규정함을 목적으로 합니다.
</p>
<h2>제2조 (용어의 정의)</h2>
<ul>
<li>&ldquo;홈페이지&rdquo;란 협의회가 정보 제공 및 소통을 위해 운영하는 웹사이트를 말합니다.</li>
<li>&ldquo;이용자&rdquo;란 홈페이지에 접속하여 서비스를 이용하는 모든 사람을 말합니다.</li>
<li>&ldquo;게시물&rdquo;이란 이용자가 홈페이지에 게시한 문의, 제보, 의견 등을 말합니다.</li>
</ul>
<h2>제3조 (약관의 효력 및 변경)</h2>
<p>
본 약관은 홈페이지에 게시함으로써 효력이 발생합니다. 협의회는 필요한 경우 약관을 변경할 수 있으며, 변경된 약관은
홈페이지 공지사항을 통해 안내합니다.
</p>
<h2>제4조 (서비스의 제공)</h2>
<p>협의회는 다음의 서비스를 제공합니다.</p>
<ul>
<li>협의회 소개 및 활동 안내</li>
<li>공지사항 및 자료실 게시</li>
<li>문의·제보 접수</li>
<li>기타 협의회가 정하는 정보 제공 서비스</li>
</ul>
<p>
서비스는 연중무휴 제공을 원칙으로 하나, 시스템 점검·장애·천재지변 등 부득이한 사유로 일시 중단될 수 있습니다.
</p>
<h2>제5조 (이용자의 의무)</h2>
<p>이용자는 다음 행위를 하여서는 안 됩니다.</p>
<ul>
<li>허위 사실을 유포하거나 타인을 비방하는 행위</li>
<li>타인의 개인정보를 무단으로 수집·이용하는 행위</li>
<li>홈페이지의 정상 운영을 방해하는 행위</li>
<li>관련 법령 및 본 약관에 위반되는 행위</li>
</ul>
<h2>제6조 (게시물의 관리)</h2>
<p>
협의회는 이용자가 게시한 내용이 다음 각 호에 해당한다고 판단하는 경우 사전 통지 없이 삭제하거나 이동할 수 있습니다.
</p>
<ul>
<li>관련 법령에 위반되는 내용</li>
<li>타인의 명예를 훼손하거나 권리를 침해하는 내용</li>
<li>광고·홍보 등 서비스 목적에 맞지 않는 내용</li>
<li>개인정보가 포함되어 공개에 부적절한 내용</li>
</ul>
<h2>제7조 (지식재산권)</h2>
<p>
홈페이지에 게시된 콘텐츠의 저작권은 협의회 또는 해당 콘텐츠 제공자에게 있습니다. 이용자는 협의회의 사전 동의 없이
콘텐츠를 복제·배포·상업적으로 이용할 수 없습니다.
</p>
<h2>제8조 (면책)</h2>
<p>
협의회는 이용자가 홈페이지를 통해 제공한 정보의 정확성·신뢰성에 대해 보증하지 않으며, 이용자가 이를 신뢰하여
취한 조치로 발생한 손해에 대해 책임을 지지 않습니다. 다만 협의회의 고의 또는 중대한 과실이 있는 경우에는
그러하지 않습니다.
</p>
<h2>제9조 (분쟁의 해결)</h2>
<p>
본 약관과 관련한 분쟁은 대한민국 법률을 준거법으로 하며, 협의회 소재지를 관할하는 법원을 전속 관할 법원으로
합니다.
</p>
<h2>부칙</h2>
<p>본 약관은 2026년 10월 1일부터 시행합니다.</p>
</div>
</div>
</>
);
}
@@ -0,0 +1,201 @@
import type { Metadata } from "next";
import Link from "next/link";
import { ChevronDown, Mail, Phone, Trash2 } from "lucide-react";
import { deleteInquiryAction, updateInquiryStatusAction } from "@/actions/inquiries";
import { ConfirmForm } from "@/components/admin/confirm-form";
import { Pagination } from "@/components/site/pagination";
import { ADMIN_PAGE_SIZE, formatDateTime, INQUIRY_STATUSES } from "@/lib/constants";
import { prisma } from "@/lib/db";
export const metadata: Metadata = { title: "문의·제보 관리" };
export const dynamic = "force-dynamic";
type SearchParams = Promise<{
status?: string;
page?: string;
updated?: string;
deleted?: string;
error?: string;
}>;
const STATUS_STYLES: Record<string, string> = {
NEW: "bg-rose-50 text-rose-600",
IN_PROGRESS: "bg-amber-50 text-amber-700",
DONE: "bg-emerald-50 text-emerald-700",
};
export default async function AdminInquiriesPage({ searchParams }: { searchParams: SearchParams }) {
const params = await searchParams;
const status = ["NEW", "IN_PROGRESS", "DONE"].includes(params.status ?? "") ? params.status! : "";
const page = Math.max(1, Number.parseInt(params.page ?? "1", 10) || 1);
const where = status ? { status } : {};
const [total, inquiries, counts] = await Promise.all([
prisma.inquiry.count({ where }),
prisma.inquiry.findMany({
where,
orderBy: { createdAt: "desc" },
skip: (page - 1) * ADMIN_PAGE_SIZE,
take: ADMIN_PAGE_SIZE,
}),
prisma.inquiry.groupBy({ by: ["status"], _count: { _all: true } }),
]);
const countByStatus = Object.fromEntries(counts.map((row) => [row.status, row._count._all]));
const totalPages = Math.max(1, Math.ceil(total / ADMIN_PAGE_SIZE));
const notice = params.updated
? "문의 상태가 변경되었습니다."
: params.deleted
? "문의가 삭제되었습니다."
: "";
return (
<div className="space-y-5">
<div>
<h1 className="text-2xl font-black tracking-tight text-brand-950">문의·제보 관리</h1>
<p className="mt-1 text-sm text-slate-500">홈페이지를 통해 접수된 문의와 제보를 확인하고 처리 상태를 관리합니다.</p>
</div>
{params.error ? (
<p role="alert" className="rounded-xl bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">
잘못된 요청입니다. 다시 시도해 주세요.
</p>
) : null}
{notice ? (
<p role="status" className="rounded-xl bg-emerald-50 px-4 py-3 text-sm font-semibold text-emerald-700">
{notice}
</p>
) : null}
<div className="flex flex-wrap items-center gap-2">
{[
{ value: "", label: "전체", count: Object.values(countByStatus).reduce((sum, value) => sum + value, 0) },
{ value: "NEW", label: "접수", count: countByStatus.NEW ?? 0 },
{ value: "IN_PROGRESS", label: "처리중", count: countByStatus.IN_PROGRESS ?? 0 },
{ value: "DONE", label: "완료", count: countByStatus.DONE ?? 0 },
].map((item) => (
<Link
key={item.value || "all"}
href={item.value ? `/admin/inquiries?status=${item.value}` : "/admin/inquiries"}
className={`rounded-full px-3.5 py-1.5 text-xs font-bold transition ${
status === item.value
? "bg-brand-900 text-white"
: "border border-slate-200 bg-white text-slate-600 hover:border-brand-200"
}`}
>
{item.label} {item.count.toLocaleString("ko-KR")}
</Link>
))}
</div>
<ul className="space-y-3">
{inquiries.map((inquiry) => (
<li key={inquiry.id} className="overflow-hidden rounded-xl border border-slate-200 bg-white">
<details className="group">
<summary className="flex cursor-pointer list-none items-start justify-between gap-3 px-5 py-4 [&::-webkit-details-marker]:hidden">
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span
className={`rounded-md px-2 py-0.5 text-[10px] font-bold ${
STATUS_STYLES[inquiry.status] ?? "bg-slate-100 text-slate-500"
}`}
>
{INQUIRY_STATUSES[inquiry.status as keyof typeof INQUIRY_STATUSES] ?? inquiry.status}
</span>
<span className="text-[11px] text-slate-400">#{inquiry.id}</span>
</div>
<p className="mt-2 truncate text-sm font-bold text-slate-700">{inquiry.title}</p>
<p className="mt-1 text-[11px] text-slate-400">
{inquiry.name} · {inquiry.email} · {formatDateTime(inquiry.createdAt)}
</p>
</div>
<ChevronDown
className="mt-1 h-4 w-4 shrink-0 text-slate-400 transition group-open:rotate-180"
aria-hidden
/>
</summary>
<div className="border-t border-slate-100 px-5 py-4">
<div className="flex flex-wrap gap-4 text-xs text-slate-500">
<span className="inline-flex items-center gap-1.5">
<Mail className="h-3.5 w-3.5" aria-hidden />
<a href={`mailto:${inquiry.email}`} className="hover:text-brand-700">
{inquiry.email}
</a>
</span>
{inquiry.phone ? (
<span className="inline-flex items-center gap-1.5">
<Phone className="h-3.5 w-3.5" aria-hidden />
<a href={`tel:${inquiry.phone}`} className="hover:text-brand-700">
{inquiry.phone}
</a>
</span>
) : null}
{inquiry.ip ? <span className="text-slate-400">IP {inquiry.ip}</span> : null}
</div>
<div className="mt-3 whitespace-pre-wrap rounded-lg bg-slate-50 px-4 py-3 text-sm leading-7 text-slate-700">
{inquiry.content}
</div>
<div className="mt-4 flex flex-wrap items-end justify-between gap-3">
<form action={updateInquiryStatusAction} className="flex items-end gap-2">
<input type="hidden" name="id" value={inquiry.id} />
<div>
<label htmlFor={`status-${inquiry.id}`} className="mb-1 block text-[11px] font-bold text-slate-500">
처리 상태
</label>
<select
id={`status-${inquiry.id}`}
name="status"
defaultValue={inquiry.status}
className="h-9 rounded-lg border border-slate-200 bg-white px-2.5 text-sm text-slate-700"
>
<option value="NEW">접수</option>
<option value="IN_PROGRESS">처리중</option>
<option value="DONE">완료</option>
</select>
</div>
<button
type="submit"
className="h-9 rounded-lg bg-brand-900 px-3.5 text-xs font-bold text-white transition hover:bg-brand-800"
>
상태 변경
</button>
</form>
<ConfirmForm action={deleteInquiryAction} message="이 문의를 삭제하시겠습니까? 삭제 후 복구할 수 없습니다.">
<input type="hidden" name="id" value={inquiry.id} />
<button
type="submit"
className="inline-flex h-9 items-center gap-1.5 rounded-lg border border-slate-200 px-3 text-xs font-bold text-slate-500 transition hover:border-rose-200 hover:text-rose-600"
>
<Trash2 className="h-3.5 w-3.5" aria-hidden />
삭제
</button>
</ConfirmForm>
</div>
</div>
</details>
</li>
))}
{inquiries.length === 0 ? (
<li className="rounded-xl border border-dashed border-slate-300 bg-white px-5 py-16 text-center text-sm text-slate-400">
접수된 문의가 없습니다.
</li>
) : null}
</ul>
<Pagination
currentPage={page}
totalPages={totalPages}
basePath="/admin/inquiries"
query={{ status: status || undefined }}
/>
</div>
);
}
+54
View File
@@ -0,0 +1,54 @@
import type { Metadata } from "next";
import Link from "next/link";
import { Menu } from "lucide-react";
import { AdminNav } from "@/components/admin/admin-nav";
import { requireAdmin } from "@/lib/auth";
export const metadata: Metadata = {
title: {
default: "관리자",
template: "%s | 관리자",
},
robots: { index: false, follow: false },
};
export const dynamic = "force-dynamic";
export default async function AdminDashboardLayout({ children }: { children: React.ReactNode }) {
const admin = await requireAdmin();
return (
<div className="min-h-screen bg-slate-100 lg:grid lg:grid-cols-[15rem_1fr]">
<aside className="hidden bg-brand-950 lg:sticky lg:top-0 lg:block lg:h-screen">
<AdminNav adminName={admin.name} loginId={admin.loginId} />
</aside>
<div className="min-w-0">
<header className="sticky top-0 z-30 border-b border-slate-200 bg-white lg:hidden">
<div className="flex items-center justify-between gap-3 px-4 py-3">
<Link href="/admin" className="flex items-center gap-2">
<span className="grid h-8 w-8 place-items-center rounded-lg bg-brand-900 text-[9px] font-black text-white">
용공협
</span>
<span className="text-sm font-bold text-brand-950">관리자</span>
</Link>
<details className="relative">
<summary className="flex h-9 w-9 cursor-pointer list-none items-center justify-center rounded-lg border border-slate-200 text-slate-600 [&::-webkit-details-marker]:hidden">
<Menu className="h-5 w-5" aria-hidden />
<span className="sr-only">관리자 메뉴 열기</span>
</summary>
<div className="absolute right-0 top-11 w-60 overflow-hidden rounded-xl border border-slate-200 bg-brand-950 shadow-2xl">
<AdminNav adminName={admin.name} loginId={admin.loginId} />
</div>
</details>
</div>
</header>
<main className="p-4 sm:p-6 lg:p-8">
<div className="mx-auto max-w-5xl">{children}</div>
</main>
</div>
</div>
);
}
+199
View File
@@ -0,0 +1,199 @@
import Link from "next/link";
import {
ArrowRight,
FileText,
FolderOpen,
MessageSquare,
Plus,
Settings,
} from "lucide-react";
import { formatDate, formatDateTime, INQUIRY_STATUSES } from "@/lib/constants";
import { prisma } from "@/lib/db";
import { getDashboardCounts } from "@/lib/posts";
export const dynamic = "force-dynamic";
export default async function AdminDashboardPage() {
const [counts, recentInquiries, recentPosts] = await Promise.all([
getDashboardCounts(),
prisma.inquiry.findMany({ orderBy: { createdAt: "desc" }, take: 5 }),
prisma.post.findMany({
orderBy: { createdAt: "desc" },
take: 6,
include: { author: { select: { name: true } } },
}),
]);
const stats = [
{
label: "공지사항",
value: counts.noticeCount,
href: "/admin/posts?type=NOTICE",
icon: FileText,
},
{
label: "자료실",
value: counts.archiveCount,
href: "/admin/posts?type=ARCHIVE",
icon: FolderOpen,
},
{
label: "새 문의",
value: counts.inquiryNew,
href: "/admin/inquiries?status=NEW",
icon: MessageSquare,
accent: counts.inquiryNew > 0,
},
{
label: "전체 문의",
value: counts.inquiryTotal,
href: "/admin/inquiries",
icon: MessageSquare,
},
];
return (
<div className="space-y-6">
<div className="flex flex-wrap items-end justify-between gap-3">
<div>
<h1 className="text-2xl font-black tracking-tight text-brand-950">대시보드</h1>
<p className="mt-1 text-sm text-slate-500">게시글과 문의 현황을 한눈에 확인하세요.</p>
</div>
<div className="flex gap-2">
<Link
href="/admin/posts/new?type=NOTICE"
className="inline-flex items-center gap-1.5 rounded-lg bg-brand-900 px-3.5 py-2 text-sm font-bold text-white transition hover:bg-brand-800"
>
<Plus className="h-4 w-4" aria-hidden />
새 공지
</Link>
<Link
href="/admin/posts/new?type=ARCHIVE"
className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3.5 py-2 text-sm font-bold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
<Plus className="h-4 w-4" aria-hidden />
새 자료
</Link>
</div>
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((stat) => (
<Link
key={stat.label}
href={stat.href}
className={`rounded-xl border bg-white p-5 transition hover:border-brand-200 hover:shadow-sm ${
stat.accent ? "border-accent-300" : "border-slate-200"
}`}
>
<div className="flex items-center justify-between">
<span className="text-xs font-bold text-slate-500">{stat.label}</span>
<stat.icon className="h-4 w-4 text-brand-500" aria-hidden />
</div>
<p className="mt-2 text-3xl font-black text-brand-950">{stat.value.toLocaleString("ko-KR")}</p>
</Link>
))}
</div>
<div className="grid gap-5 lg:grid-cols-2">
<section className="min-w-0 overflow-hidden rounded-xl border border-slate-200 bg-white">
<div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
<h2 className="text-sm font-bold text-brand-950">최근 문의</h2>
<Link href="/admin/inquiries" className="inline-flex items-center gap-1 text-xs font-bold text-brand-700 hover:text-brand-500">
전체보기
<ArrowRight className="h-3.5 w-3.5" aria-hidden />
</Link>
</div>
<ul className="divide-y divide-slate-100">
{recentInquiries.map((inquiry) => (
<li key={inquiry.id} className="px-5 py-3.5">
<div className="flex items-center justify-between gap-3">
<p className="min-w-0 flex-1 truncate text-sm font-semibold text-slate-700">{inquiry.title}</p>
<span
className={`shrink-0 rounded-md px-2 py-0.5 text-[10px] font-bold ${
inquiry.status === "NEW"
? "bg-rose-50 text-rose-600"
: inquiry.status === "IN_PROGRESS"
? "bg-amber-50 text-amber-700"
: "bg-emerald-50 text-emerald-700"
}`}
>
{INQUIRY_STATUSES[inquiry.status as keyof typeof INQUIRY_STATUSES] ?? inquiry.status}
</span>
</div>
<p className="mt-1 text-[11px] text-slate-400">
{inquiry.name} · {formatDateTime(inquiry.createdAt)}
</p>
</li>
))}
{recentInquiries.length === 0 ? (
<li className="px-5 py-10 text-center text-sm text-slate-400">접수된 문의가 없습니다.</li>
) : null}
</ul>
</section>
<section className="min-w-0 overflow-hidden rounded-xl border border-slate-200 bg-white">
<div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
<h2 className="text-sm font-bold text-brand-950">최근 게시글</h2>
<Link href="/admin/posts" className="inline-flex items-center gap-1 text-xs font-bold text-brand-700 hover:text-brand-500">
전체보기
<ArrowRight className="h-3.5 w-3.5" aria-hidden />
</Link>
</div>
<ul className="divide-y divide-slate-100">
{recentPosts.map((post) => (
<li key={post.id} className="px-5 py-3.5">
<div className="flex items-center justify-between gap-3">
<Link
href={`/admin/posts/${post.id}/edit`}
className="min-w-0 flex-1 truncate text-sm font-semibold text-slate-700 hover:text-brand-800"
>
{post.title}
</Link>
<span className="shrink-0 rounded-md bg-slate-100 px-2 py-0.5 text-[10px] font-bold text-slate-500">
{post.type === "NOTICE" ? "공지" : "자료"}
</span>
</div>
<p className="mt-1 text-[11px] text-slate-400">
{post.status === "DRAFT" ? "임시저장 · " : ""}
{formatDate(post.publishedAt)} · {post.author?.name ?? "관리자"}
</p>
</li>
))}
{recentPosts.length === 0 ? (
<li className="px-5 py-10 text-center text-sm text-slate-400">등록된 게시글이 없습니다.</li>
) : null}
</ul>
</section>
</div>
<section className="rounded-xl border border-slate-200 bg-white p-5">
<h2 className="text-sm font-bold text-brand-950">빠른 작업</h2>
<div className="mt-3 grid gap-2 sm:grid-cols-3">
<Link
href="/admin/posts/new?type=NOTICE"
className="flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2.5 text-sm font-semibold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
<FileText className="h-4 w-4" aria-hidden />
공지사항 작성
</Link>
<Link
href="/admin/posts/new?type=ARCHIVE"
className="flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2.5 text-sm font-semibold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
<FolderOpen className="h-4 w-4" aria-hidden />
자료실 자료 등록
</Link>
<Link
href="/admin/settings"
className="flex items-center gap-2 rounded-lg border border-slate-200 px-3 py-2.5 text-sm font-semibold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
<Settings className="h-4 w-4" aria-hidden />
사이트 정보 수정
</Link>
</div>
</section>
</div>
);
}
@@ -0,0 +1,107 @@
import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, ExternalLink } from "lucide-react";
import { updatePostAction } from "@/actions/posts";
import { PostForm } from "@/components/admin/post-form";
import { formatDateTime } from "@/lib/constants";
import { prisma } from "@/lib/db";
export const metadata: Metadata = { title: "게시글 수정" };
export const dynamic = "force-dynamic";
type Params = Promise<{ id: string }>;
type SearchParams = Promise<{ error?: string; deletedAttachment?: string }>;
export default async function EditPostPage({
params,
searchParams,
}: {
params: Params;
searchParams: SearchParams;
}) {
const [{ id }, query] = await Promise.all([params, searchParams]);
const postId = Number(id);
if (!Number.isInteger(postId) || postId <= 0) notFound();
const post = await prisma.post.findUnique({
where: { id: postId },
include: { attachments: { orderBy: { id: "asc" } } },
});
if (!post) notFound();
const type = post.type === "ARCHIVE" ? "ARCHIVE" : "NOTICE";
const typeLabel = type === "NOTICE" ? "공지사항" : "자료실";
const publicHref = type === "NOTICE" ? `/news/notice/${post.id}` : `/archive/${post.id}`;
return (
<div className="space-y-5">
<div className="flex flex-wrap items-end justify-between gap-3">
<div>
<Link
href={`/admin/posts?type=${type}`}
className="inline-flex items-center gap-1.5 text-xs font-bold text-slate-500 transition hover:text-brand-700"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden />
게시글 목록
</Link>
<h1 className="mt-3 text-2xl font-black tracking-tight text-brand-950">게시글 수정</h1>
<p className="mt-1 text-xs text-slate-400">
{typeLabel} · #{post.id} · 최종 수정 {formatDateTime(post.updatedAt)}
</p>
</div>
{post.status === "PUBLISHED" ? (
<Link
href={publicHref}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3.5 py-2 text-sm font-bold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
<ExternalLink className="h-4 w-4" aria-hidden />
사이트에서 보기
</Link>
) : (
<span className="rounded-lg border border-slate-200 bg-slate-50 px-3.5 py-2 text-sm font-semibold text-slate-400">
임시저장 상태 (공개되지 않음)
</span>
)}
</div>
{query.error ? (
<p role="alert" className="rounded-xl bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">
{query.error}
</p>
) : null}
{query.deletedAttachment ? (
<p role="status" className="rounded-xl bg-emerald-50 px-4 py-3 text-sm font-semibold text-emerald-700">
첨부파일이 삭제되었습니다.
</p>
) : null}
<PostForm
action={updatePostAction}
defaultType={type}
submitLabel="수정 내용 저장"
cancelHref={`/admin/posts?type=${type}`}
post={{
id: post.id,
type: post.type,
category: post.category,
title: post.title,
content: post.content,
isPinned: post.isPinned,
status: post.status,
attachments: post.attachments.map((attachment) => ({
id: attachment.id,
originalName: attachment.originalName,
size: attachment.size,
})),
}}
/>
</div>
);
}
@@ -0,0 +1,46 @@
import type { Metadata } from "next";
import Link from "next/link";
import { ArrowLeft } from "lucide-react";
import { createPostAction } from "@/actions/posts";
import { PostForm } from "@/components/admin/post-form";
export const metadata: Metadata = { title: "새 게시글" };
export const dynamic = "force-dynamic";
type SearchParams = Promise<{ type?: string; error?: string }>;
export default async function NewPostPage({ searchParams }: { searchParams: SearchParams }) {
const params = await searchParams;
const type = params.type === "ARCHIVE" ? "ARCHIVE" : "NOTICE";
const typeLabel = type === "NOTICE" ? "공지사항" : "자료실";
return (
<div className="space-y-5">
<div>
<Link
href={`/admin/posts?type=${type}`}
className="inline-flex items-center gap-1.5 text-xs font-bold text-slate-500 transition hover:text-brand-700"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden />
게시글 목록
</Link>
<h1 className="mt-3 text-2xl font-black tracking-tight text-brand-950">{typeLabel} 작성</h1>
<p className="mt-1 text-sm text-slate-500">제목과 내용을 입력하고 첨부파일을 등록하세요.</p>
</div>
{params.error ? (
<p role="alert" className="rounded-xl bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">
{params.error}
</p>
) : null}
<PostForm
action={createPostAction}
defaultType={type}
submitLabel="게시글 등록"
cancelHref={`/admin/posts?type=${type}`}
/>
</div>
);
}
+230
View File
@@ -0,0 +1,230 @@
import type { Metadata } from "next";
import Link from "next/link";
import { Eye, Paperclip, Pencil, Pin, Plus, Search, Trash2 } from "lucide-react";
import { deletePostAction } from "@/actions/posts";
import { ConfirmForm } from "@/components/admin/confirm-form";
import { Pagination } from "@/components/site/pagination";
import { ADMIN_PAGE_SIZE, formatDate } from "@/lib/constants";
import { prisma } from "@/lib/db";
export const metadata: Metadata = { title: "게시글 관리" };
export const dynamic = "force-dynamic";
type SearchParams = Promise<{
type?: string;
page?: string;
q?: string;
status?: string;
created?: string;
updated?: string;
deleted?: string;
error?: string;
}>;
export default async function AdminPostsPage({ searchParams }: { searchParams: SearchParams }) {
const params = await searchParams;
const type = params.type === "ARCHIVE" ? "ARCHIVE" : "NOTICE";
const page = Math.max(1, Number.parseInt(params.page ?? "1", 10) || 1);
const query = (params.q ?? "").trim();
const status = ["PUBLISHED", "DRAFT"].includes(params.status ?? "") ? params.status! : "";
const where = {
type,
...(status ? { status } : {}),
...(query ? { OR: [{ title: { contains: query } }, { content: { contains: query } }] } : {}),
};
const [total, posts] = await Promise.all([
prisma.post.count({ where }),
prisma.post.findMany({
where,
orderBy: [{ isPinned: "desc" }, { publishedAt: "desc" }, { id: "desc" }],
skip: (page - 1) * ADMIN_PAGE_SIZE,
take: ADMIN_PAGE_SIZE,
include: {
author: { select: { name: true } },
_count: { select: { attachments: true } },
},
}),
]);
const totalPages = Math.max(1, Math.ceil(total / ADMIN_PAGE_SIZE));
const typeLabel = type === "NOTICE" ? "공지사항" : "자료실";
const basePath = "/admin/posts";
const listQuery = { type, q: query || undefined, status: status || undefined };
const notice = params.created
? "게시글이 등록되었습니다."
: params.updated
? "게시글이 수정되었습니다."
: params.deleted
? "게시글이 삭제되었습니다."
: "";
return (
<div className="space-y-5">
<div className="flex flex-wrap items-end justify-between gap-3">
<div>
<h1 className="text-2xl font-black tracking-tight text-brand-950">게시글 관리</h1>
<p className="mt-1 text-sm text-slate-500">공지사항과 자료실 게시글을 작성·수정·삭제합니다.</p>
</div>
<Link
href={`/admin/posts/new?type=${type}`}
className="inline-flex items-center gap-1.5 rounded-lg bg-brand-900 px-3.5 py-2 text-sm font-bold text-white transition hover:bg-brand-800"
>
<Plus className="h-4 w-4" aria-hidden />
{typeLabel} 작성
</Link>
</div>
{params.error ? (
<p role="alert" className="rounded-xl bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">
{params.error}
</p>
) : null}
{notice ? (
<p role="status" className="rounded-xl bg-emerald-50 px-4 py-3 text-sm font-semibold text-emerald-700">
{notice}
</p>
) : null}
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="inline-flex rounded-xl border border-slate-200 bg-white p-1">
{(["NOTICE", "ARCHIVE"] as const).map((item) => (
<Link
key={item}
href={`/admin/posts?type=${item}`}
className={`rounded-lg px-3.5 py-1.5 text-sm font-bold transition ${
type === item ? "bg-brand-900 text-white" : "text-slate-500 hover:text-brand-800"
}`}
>
{item === "NOTICE" ? "공지사항" : "자료실"}
</Link>
))}
</div>
<form action={basePath} method="get" className="flex flex-wrap items-center gap-2">
<input type="hidden" name="type" value={type} />
<select
name="status"
defaultValue={status}
className="h-9 rounded-lg border border-slate-200 bg-white px-2.5 text-sm text-slate-600"
aria-label="공개 상태"
>
<option value="">전체 상태</option>
<option value="PUBLISHED">공개</option>
<option value="DRAFT">임시저장</option>
</select>
<div className="relative">
<input
name="q"
defaultValue={query}
placeholder="제목·내용 검색"
className="h-9 w-52 rounded-lg border border-slate-200 bg-white pl-8 pr-3 text-sm text-slate-700 placeholder:text-slate-400"
aria-label="검색어"
/>
<Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" aria-hidden />
</div>
<button
type="submit"
className="h-9 rounded-lg bg-slate-900 px-3 text-sm font-bold text-white transition hover:bg-slate-700"
>
검색
</button>
</form>
</div>
<p className="text-sm text-slate-500">
전체 <span className="font-bold text-brand-800">{total.toLocaleString("ko-KR")}</span>건
</p>
<div className="overflow-hidden rounded-xl border border-slate-200 bg-white">
<div className="overflow-x-auto">
<table className="w-full min-w-[46rem] border-collapse text-left text-sm">
<caption className="sr-only">{typeLabel} 게시글 목록</caption>
<thead>
<tr className="border-b border-slate-200 bg-slate-50 text-xs font-bold text-slate-500">
<th scope="col" className="w-16 px-4 py-3">번호</th>
<th scope="col" className="w-20 px-4 py-3">분류</th>
<th scope="col" className="px-4 py-3">제목</th>
<th scope="col" className="w-20 px-4 py-3">상태</th>
<th scope="col" className="w-28 px-4 py-3">작성일</th>
<th scope="col" className="w-24 px-4 py-3 text-right">관리</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{posts.map((post) => (
<tr key={post.id} className="align-middle hover:bg-slate-50/70">
<td className="px-4 py-3 text-xs text-slate-400">{post.id}</td>
<td className="px-4 py-3">
<span className="inline-flex items-center gap-1 rounded-md bg-slate-100 px-2 py-0.5 text-[11px] font-bold text-slate-600">
{post.isPinned ? <Pin className="h-3 w-3 text-accent-600" aria-hidden /> : null}
{post.category || "미분류"}
</span>
</td>
<td className="px-4 py-3">
<Link href={`/admin/posts/${post.id}/edit`} className="line-clamp-1 font-semibold text-slate-700 hover:text-brand-800">
{post.title}
</Link>
<span className="mt-0.5 flex items-center gap-3 text-[11px] text-slate-400">
<span className="inline-flex items-center gap-1">
<Eye className="h-3 w-3" aria-hidden />
{post.viewCount.toLocaleString("ko-KR")}
</span>
<span className="inline-flex items-center gap-1">
<Paperclip className="h-3 w-3" aria-hidden />
{post._count.attachments}
</span>
<span>{post.author?.name ?? "관리자"}</span>
</span>
</td>
<td className="px-4 py-3">
<span
className={`rounded-md px-2 py-0.5 text-[11px] font-bold ${
post.status === "PUBLISHED" ? "bg-emerald-50 text-emerald-700" : "bg-slate-100 text-slate-500"
}`}
>
{post.status === "PUBLISHED" ? "공개" : "임시저장"}
</span>
</td>
<td className="px-4 py-3 text-xs text-slate-400">{formatDate(post.publishedAt)}</td>
<td className="px-4 py-3">
<div className="flex items-center justify-end gap-1">
<Link
href={`/admin/posts/${post.id}/edit`}
className="grid h-8 w-8 place-items-center rounded-lg border border-slate-200 text-slate-500 transition hover:border-brand-200 hover:text-brand-700"
aria-label={`${post.title} 수정`}
>
<Pencil className="h-3.5 w-3.5" aria-hidden />
</Link>
<ConfirmForm action={deletePostAction} message={`"${post.title}" 게시글을 삭제하시겠습니까?`}>
<input type="hidden" name="id" value={post.id} />
<button
type="submit"
className="grid h-8 w-8 place-items-center rounded-lg border border-slate-200 text-slate-400 transition hover:border-rose-200 hover:text-rose-600"
aria-label={`${post.title} 삭제`}
>
<Trash2 className="h-3.5 w-3.5" aria-hidden />
</button>
</ConfirmForm>
</div>
</td>
</tr>
))}
{posts.length === 0 ? (
<tr>
<td colSpan={6} className="px-4 py-14 text-center text-sm text-slate-400">
{query ? "검색 결과가 없습니다." : `등록된 ${typeLabel} 게시글이 없습니다.`}
</td>
</tr>
) : null}
</tbody>
</table>
</div>
</div>
<Pagination currentPage={page} totalPages={totalPages} basePath={basePath} query={listQuery} />
</div>
);
}
+161
View File
@@ -0,0 +1,161 @@
import type { Metadata } from "next";
import { Save } from "lucide-react";
import { updateSettingsAction } from "@/actions/settings";
import { getSettings } from "@/lib/settings";
export const metadata: Metadata = { title: "사이트 설정" };
export const dynamic = "force-dynamic";
type SearchParams = Promise<{ saved?: string; error?: string }>;
const inputClass =
"h-11 w-full rounded-lg border border-slate-200 bg-white px-3.5 text-sm text-slate-800 placeholder:text-slate-400 focus:border-brand-400 focus:outline-none";
const labelClass = "mb-1.5 block text-xs font-bold text-slate-600";
export default async function AdminSettingsPage({ searchParams }: { searchParams: SearchParams }) {
const [params, settings] = await Promise.all([searchParams, getSettings()]);
return (
<div className="space-y-5">
<div>
<h1 className="text-2xl font-black tracking-tight text-brand-950">사이트 설정</h1>
<p className="mt-1 text-sm text-slate-500">
홈페이지 상단·하단에 표시되는 사이트 정보와 외부 링크를 관리합니다.
</p>
</div>
{params.error ? (
<p role="alert" className="rounded-xl bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">
{params.error}
</p>
) : null}
{params.saved ? (
<p role="status" className="rounded-xl bg-emerald-50 px-4 py-3 text-sm font-semibold text-emerald-700">
설정이 저장되었습니다. 홈페이지에 바로 반영됩니다.
</p>
) : null}
<form action={updateSettingsAction} className="space-y-5">
<section className="grid gap-4 rounded-xl border border-slate-200 bg-white p-5 sm:grid-cols-2">
<div className="sm:col-span-2">
<h2 className="text-sm font-bold text-brand-950">기본 정보</h2>
<p className="mt-1 text-xs text-slate-400">사이트 이름은 헤더·푸터·검색 결과에 사용됩니다.</p>
</div>
<div>
<label htmlFor="siteName" className={labelClass}>
사이트 이름
</label>
<input id="siteName" name="siteName" required defaultValue={settings.siteName} maxLength={100} className={inputClass} />
</div>
<div>
<label htmlFor="shortName" className={labelClass}>
약칭
</label>
<input id="shortName" name="shortName" required defaultValue={settings.shortName} maxLength={30} className={inputClass} />
</div>
<div className="sm:col-span-2">
<label htmlFor="description" className={labelClass}>
사이트 설명
</label>
<textarea
id="description"
name="description"
rows={3}
defaultValue={settings.description}
maxLength={300}
className="w-full resize-y rounded-lg border border-slate-200 bg-white px-3.5 py-3 text-sm leading-6 text-slate-800 focus:border-brand-400 focus:outline-none"
/>
</div>
<div className="sm:col-span-2">
<label htmlFor="footerText" className={labelClass}>
푸터 문구
</label>
<input id="footerText" name="footerText" defaultValue={settings.footerText} maxLength={300} className={inputClass} />
</div>
</section>
<section className="grid gap-4 rounded-xl border border-slate-200 bg-white p-5 sm:grid-cols-2">
<div className="sm:col-span-2">
<h2 className="text-sm font-bold text-brand-950">연락처</h2>
<p className="mt-1 text-xs text-slate-400">입력한 정보는 푸터와 문의·제보 페이지에 표시됩니다.</p>
</div>
<div>
<label htmlFor="contactPhone" className={labelClass}>
전화번호
</label>
<input
id="contactPhone"
name="contactPhone"
defaultValue={settings.contactPhone}
maxLength={50}
placeholder="02-000-0000"
className={inputClass}
/>
</div>
<div>
<label htmlFor="contactEmail" className={labelClass}>
이메일
</label>
<input
id="contactEmail"
name="contactEmail"
type="email"
defaultValue={settings.contactEmail}
maxLength={200}
placeholder="contact@example.com"
className={inputClass}
/>
</div>
<div className="sm:col-span-2">
<label htmlFor="address" className={labelClass}>
주소
</label>
<input id="address" name="address" defaultValue={settings.address} maxLength={200} className={inputClass} />
</div>
</section>
<section className="grid gap-4 rounded-xl border border-slate-200 bg-white p-5">
<div>
<h2 className="text-sm font-bold text-brand-950">외부 링크</h2>
<p className="mt-1 text-xs text-slate-400">
조사 현황 지도와 네이버 블로그 주소입니다. 2차 지도 통합 전까지 기존 지도 주소를 사용합니다.
</p>
</div>
<div>
<label htmlFor="mapUrl" className={labelClass}>
조사 현황 지도 URL
</label>
<input id="mapUrl" name="mapUrl" type="url" required defaultValue={settings.mapUrl} maxLength={300} className={inputClass} />
</div>
<div>
<label htmlFor="blogUrl" className={labelClass}>
네이버 블로그 URL
</label>
<input id="blogUrl" name="blogUrl" type="url" required defaultValue={settings.blogUrl} maxLength={300} className={inputClass} />
</div>
</section>
<div className="flex justify-end">
<button
type="submit"
className="inline-flex items-center gap-2 rounded-lg bg-brand-900 px-5 py-2.5 text-sm font-bold text-white transition hover:bg-brand-800"
>
<Save className="h-4 w-4" aria-hidden />
설정 저장
</button>
</div>
</form>
</div>
);
}
+50
View File
@@ -0,0 +1,50 @@
import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { ArrowLeft, ShieldCheck } from "lucide-react";
import { LoginForm } from "@/components/admin/login-form";
import { getSession } from "@/lib/auth";
export const metadata: Metadata = {
title: "관리자 로그인",
robots: { index: false, follow: false },
};
export const dynamic = "force-dynamic";
export default async function AdminLoginPage() {
const session = await getSession();
if (session) redirect("/admin");
return (
<main className="grid min-h-screen place-items-center bg-brand-950 px-4 py-12">
<div className="w-full max-w-sm">
<div className="mb-6 text-center">
<span className="mx-auto grid h-12 w-12 place-items-center rounded-2xl bg-white/10 text-[11px] font-black text-white">
용공협
</span>
<h1 className="mt-4 text-xl font-black tracking-tight text-white">관리자 로그인</h1>
<p className="mt-2 flex items-center justify-center gap-1.5 text-xs text-slate-400">
<ShieldCheck className="h-3.5 w-3.5" aria-hidden />
허가된 관리자만 접속할 수 있습니다.
</p>
</div>
<div className="rounded-2xl border border-white/10 bg-white p-6 shadow-2xl">
<LoginForm />
</div>
<div className="mt-5 text-center">
<Link
href="/"
className="inline-flex items-center gap-1.5 text-xs font-semibold text-slate-400 transition hover:text-white"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden />
홈페이지로 돌아가기
</Link>
</div>
</div>
</main>
);
}
+59
View File
@@ -0,0 +1,59 @@
import { NextResponse } from "next/server";
import { getCurrentAdmin, getClientIp } from "@/lib/auth";
import { writeAudit } from "@/lib/audit";
import { saveUploadedFile } from "@/lib/files";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request) {
const admin = await getCurrentAdmin();
if (!admin) {
return NextResponse.json({ error: "로그인이 필요합니다." }, { status: 401 });
}
const contentType = request.headers.get("content-type") ?? "";
if (!contentType.includes("multipart/form-data")) {
return NextResponse.json({ error: "multipart/form-data 요청이 아닙니다." }, { status: 415 });
}
let formData: FormData;
try {
formData = await request.formData();
} catch {
return NextResponse.json({ error: "요청 본문을 읽을 수 없습니다." }, { status: 400 });
}
const files = formData
.getAll("file")
.concat(formData.getAll("files"))
.filter((value): value is File => value instanceof File && value.size > 0)
.slice(0, 10);
if (files.length === 0) {
return NextResponse.json({ error: "업로드할 파일이 없습니다." }, { status: 400 });
}
const saved = [];
for (const file of files) {
try {
saved.push(await saveUploadedFile(file));
} catch (error) {
return NextResponse.json(
{ error: error instanceof Error ? error.message : "파일 업로드에 실패했습니다." },
{ status: 400 },
);
}
}
await writeAudit({
adminId: admin.id,
action: "FILE_UPLOAD",
targetType: "ATTACHMENT",
targetId: saved.map((file) => file.storageKey).join(","),
ip: await getClientIp(),
});
return NextResponse.json({ files: saved }, { status: 201 });
}
+69
View File
@@ -0,0 +1,69 @@
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import type { ReadableStream as NodeReadableStream } from "node:stream/web";
import { prisma } from "@/lib/db";
import { resolveStoredPath, safeDownloadName } from "@/lib/files";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
type Params = Promise<{ id: string }>;
export async function GET(request: Request, { params }: { params: Params }) {
const { id } = await params;
const attachmentId = Number(id);
if (!Number.isInteger(attachmentId) || attachmentId <= 0) {
return new Response("잘못된 요청입니다.", { status: 400 });
}
const attachment = await prisma.attachment.findUnique({ where: { id: attachmentId } });
if (!attachment) {
return new Response("파일을 찾을 수 없습니다.", { status: 404 });
}
let fullPath: string;
try {
fullPath = resolveStoredPath(attachment.storageKey);
} catch {
return new Response("잘못된 파일 경로입니다.", { status: 400 });
}
let fileStat;
try {
fileStat = await stat(fullPath);
} catch {
return new Response("파일이 존재하지 않습니다.", { status: 404 });
}
if (!fileStat.isFile()) {
return new Response("파일이 존재하지 않습니다.", { status: 404 });
}
const url = new URL(request.url);
const download = url.searchParams.get("download") === "1";
const encodedName = encodeURIComponent(safeDownloadName(attachment.originalName));
const disposition = `${download ? "attachment" : "inline"}; filename*=UTF-8''${encodedName}`;
if (download) {
// 다운로드 횟수 증가는 실패해도 응답에 영향을 주지 않습니다.
prisma.attachment
.update({ where: { id: attachmentId }, data: { downloadCount: { increment: 1 } } })
.catch(() => undefined);
}
const nodeStream = createReadStream(fullPath);
const webStream = Readable.toWeb(nodeStream) as unknown as NodeReadableStream<Uint8Array>;
return new Response(webStream as unknown as ReadableStream, {
headers: {
"Content-Type": attachment.mimeType || "application/octet-stream",
"Content-Length": String(fileStat.size),
"Content-Disposition": disposition,
"Cache-Control": "private, max-age=0, must-revalidate",
"X-Content-Type-Options": "nosniff",
},
});
}
+22
View File
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function GET() {
try {
await prisma.$queryRaw`SELECT 1`;
return NextResponse.json({
status: "ok",
database: "up",
timestamp: new Date().toISOString(),
});
} catch {
return NextResponse.json(
{ status: "error", database: "down", timestamp: new Date().toISOString() },
{ status: 503 },
);
}
}
+71
View File
@@ -0,0 +1,71 @@
import { prisma } from "@/lib/db";
import { SITE_DESCRIPTION, SITE_NAME, SITE_URL } from "@/lib/constants";
export const dynamic = "force-dynamic";
export const revalidate = 0;
function escapeXml(value: string) {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
function plainText(content: string) {
return content
.replace(/[#>*_`~\-[\]()]/g, " ")
.replace(/\s+/g, " ")
.trim()
.slice(0, 300);
}
export async function GET() {
const base = SITE_URL.replace(/\/$/, "");
let items = "";
try {
const posts = await prisma.post.findMany({
where: { status: "PUBLISHED" },
orderBy: [{ isPinned: "desc" }, { publishedAt: "desc" }],
take: 30,
});
items = posts
.map((post) => {
const link = `${base}${post.type === "NOTICE" ? "/news/notice" : "/archive"}/${post.id}`;
return ` <item>
<title>${escapeXml(post.title)}</title>
<link>${escapeXml(link)}</link>
<guid isPermaLink="true">${escapeXml(link)}</guid>
<category>${escapeXml(post.type === "NOTICE" ? "공지사항" : "자료실")}</category>
<pubDate>${post.publishedAt.toUTCString()}</pubDate>
<description>${escapeXml(plainText(post.content))}</description>
</item>`;
})
.join("\n");
} catch {
items = "";
}
const xml = `<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>${escapeXml(SITE_NAME)}</title>
<link>${escapeXml(base)}</link>
<description>${escapeXml(SITE_DESCRIPTION)}</description>
<language>ko</language>
<lastBuildDate>${new Date().toUTCString()}</lastBuildDate>
<atom:link href="${escapeXml(`${base}/feed.xml`)}" rel="self" type="application/rss+xml" />
${items}
</channel>
</rss>`;
return new Response(xml, {
headers: {
"Content-Type": "application/rss+xml; charset=utf-8",
"Cache-Control": "public, max-age=600, s-maxage=600",
},
});
}
+241
View File
@@ -0,0 +1,241 @@
@import "tailwindcss";
@theme {
--font-sans:
"Pretendard Variable", Pretendard, "Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic",
system-ui, sans-serif;
--color-brand-50: #eef8fb;
--color-brand-100: #d7edf5;
--color-brand-200: #b1dce9;
--color-brand-300: #7cc2d8;
--color-brand-400: #40a0bf;
--color-brand-500: #2183a4;
--color-brand-600: #176a8a;
--color-brand-700: #145671;
--color-brand-800: #15485d;
--color-brand-900: #153d4f;
--color-brand-950: #0b2532;
--color-accent-300: #f9d976;
--color-accent-400: #f6c945;
--color-accent-500: #f2b705;
--color-accent-600: #d99e00;
--color-accent-700: #b37d00;
--color-ink: #0f172a;
--color-paper: #f6f8fa;
}
@layer base {
* {
border-color: theme("colors.slate.200");
}
html {
scroll-behavior: smooth;
}
body {
background-color: var(--color-paper);
color: var(--color-ink);
font-family: var(--font-sans);
-webkit-font-smoothing: antialiased;
word-break: keep-all;
}
::selection {
background-color: var(--color-accent-300);
color: var(--color-brand-950);
}
:focus-visible {
outline: 3px solid var(--color-accent-500);
outline-offset: 2px;
}
a,
button {
-webkit-tap-highlight-color: transparent;
}
}
@layer components {
.site-container {
width: 100%;
max-width: 72rem;
margin-inline: auto;
padding-inline: 1rem;
}
@media (min-width: 640px) {
.site-container {
padding-inline: 1.5rem;
}
}
.prose-yg {
color: #334155;
font-size: 1.0625rem;
line-height: 1.9;
}
.prose-yg > :first-child {
margin-top: 0;
}
.prose-yg > :last-child {
margin-bottom: 0;
}
.prose-yg h2 {
margin: 2.5rem 0 0.9rem;
color: var(--color-brand-950);
font-size: 1.4rem;
font-weight: 800;
letter-spacing: -0.02em;
line-height: 1.45;
}
.prose-yg h3 {
margin: 2rem 0 0.7rem;
color: var(--color-brand-900);
font-size: 1.15rem;
font-weight: 750;
letter-spacing: -0.015em;
}
.prose-yg p {
margin: 1rem 0;
}
.prose-yg strong {
color: var(--color-brand-900);
font-weight: 700;
}
.prose-yg ul,
.prose-yg ol {
margin: 1rem 0;
padding-left: 1.4rem;
}
.prose-yg ul {
list-style: disc;
}
.prose-yg ol {
list-style: decimal;
}
.prose-yg li {
margin: 0.4rem 0;
}
.prose-yg li::marker {
color: var(--color-brand-500);
}
.prose-yg a {
color: var(--color-brand-700);
font-weight: 600;
text-decoration: underline;
text-decoration-thickness: 1px;
text-underline-offset: 3px;
}
.prose-yg a:hover {
color: var(--color-brand-500);
}
.prose-yg img {
display: block;
max-width: 100%;
height: auto;
margin: 1.75rem auto;
border-radius: 0.9rem;
border: 1px solid #e2e8f0;
}
.prose-yg blockquote {
margin: 1.5rem 0;
border-left: 4px solid var(--color-accent-500);
background: #fffbeb;
padding: 1rem 1.25rem;
color: #475569;
}
.prose-yg hr {
margin: 2.5rem 0;
border: 0;
border-top: 1px solid #e2e8f0;
}
.prose-yg table {
width: 100%;
margin: 1.5rem 0;
border-collapse: collapse;
font-size: 0.95rem;
}
.prose-yg th,
.prose-yg td {
border: 1px solid #e2e8f0;
padding: 0.6rem 0.8rem;
text-align: left;
}
.prose-yg th {
background: #f1f5f9;
color: var(--color-brand-900);
font-weight: 700;
}
.prose-yg code {
border-radius: 0.35rem;
background: #f1f5f9;
padding: 0.15rem 0.35rem;
font-size: 0.9em;
}
.prose-yg pre {
overflow-x: auto;
border-radius: 0.8rem;
background: #0f172a;
padding: 1rem 1.25rem;
color: #e2e8f0;
}
.prose-yg pre code {
background: transparent;
padding: 0;
color: inherit;
}
.card-lift {
transition:
transform 180ms ease,
box-shadow 180ms ease,
border-color 180ms ease;
}
.card-lift:hover {
transform: translateY(-3px);
border-color: var(--color-brand-200);
box-shadow: 0 18px 40px -24px rgb(15 23 42 / 0.28);
}
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="용공협">
<rect width="64" height="64" rx="16" fill="#153d4f" />
<path d="M32 13v29" stroke="#f2b705" stroke-width="5" stroke-linecap="round" />
<path d="M22 20h20M20 28h24M18 36h28" stroke="#ffffff" stroke-width="3.5" stroke-linecap="round" />
<path d="M25 47h14" stroke="#7cc2d8" stroke-width="4" stroke-linecap="round" />
<circle cx="32" cy="13" r="3.5" fill="#f2b705" />
</svg>

After

Width:  |  Height:  |  Size: 477 B

+50
View File
@@ -0,0 +1,50 @@
import type { Metadata, Viewport } from "next";
import { SITE_DESCRIPTION, SITE_NAME, SITE_SHORT_NAME, SITE_URL } from "@/lib/constants";
import "./globals.css";
export const metadata: Metadata = {
metadataBase: new URL(SITE_URL),
title: {
default: `${SITE_NAME} | ${SITE_SHORT_NAME}`,
template: `%s | ${SITE_SHORT_NAME}`,
},
description: SITE_DESCRIPTION,
keywords: ["용산", "공중케이블", "전신주", "주민안전", "용공협", "용산구"],
openGraph: {
type: "website",
locale: "ko_KR",
url: SITE_URL,
siteName: SITE_NAME,
title: `${SITE_NAME} | ${SITE_SHORT_NAME}`,
description: SITE_DESCRIPTION,
images: [{ url: "/images/og-default.jpg", width: 800, height: 1067, alt: SITE_NAME }],
},
robots: { index: true, follow: true },
alternates: {
types: {
"application/rss+xml": "/feed.xml",
},
},
};
export const viewport: Viewport = {
width: "device-width",
initialScale: 1,
themeColor: "#0f3d50",
};
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
return (
<html lang="ko" data-scroll-behavior="smooth">
<head>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/gh/orioncactus/pretendard@v1.3.9/dist/web/variable/pretendardvariable-dynamic-subset.min.css"
/>
</head>
<body>{children}</body>
</html>
);
}
+41
View File
@@ -0,0 +1,41 @@
import Link from "next/link";
import { SearchX } from "lucide-react";
export default function NotFound() {
return (
<main className="grid min-h-screen place-items-center bg-brand-950 px-4 py-16 text-center">
<div className="w-full max-w-lg">
<span className="mx-auto grid h-14 w-14 place-items-center rounded-2xl bg-white/10 text-brand-100">
<SearchX className="h-6 w-6" aria-hidden />
</span>
<p className="mt-6 text-xs font-bold uppercase tracking-[0.2em] text-accent-400">404 Not Found</p>
<h1 className="mt-2 text-2xl font-black tracking-tight text-white sm:text-3xl">
요청하신 페이지를 찾을 수 없습니다.
</h1>
<p className="mt-3 text-sm leading-7 text-slate-400">
주소가 변경되었거나 삭제된 페이지일 수 있습니다.
</p>
<div className="mt-7 flex flex-wrap justify-center gap-2">
<Link
href="/"
className="rounded-xl bg-accent-500 px-5 py-3 text-sm font-bold text-brand-950 transition hover:bg-accent-400"
>
홈으로
</Link>
<Link
href="/news/notice"
className="rounded-xl border border-white/20 bg-white/5 px-5 py-3 text-sm font-bold text-white transition hover:bg-white/10"
>
공지사항
</Link>
<Link
href="/archive"
className="rounded-xl border border-white/20 bg-white/5 px-5 py-3 text-sm font-bold text-white transition hover:bg-white/10"
>
자료실
</Link>
</div>
</div>
</main>
);
}
+19
View File
@@ -0,0 +1,19 @@
import type { MetadataRoute } from "next";
import { SITE_URL } from "@/lib/constants";
export default function robots(): MetadataRoute.Robots {
const base = SITE_URL.replace(/\/$/, "");
return {
rules: [
{
userAgent: "*",
allow: "/",
disallow: ["/admin", "/admin/", "/api/"],
},
],
sitemap: `${base}/sitemap.xml`,
host: base,
};
}
+40
View File
@@ -0,0 +1,40 @@
import type { MetadataRoute } from "next";
import { SITE_URL } from "@/lib/constants";
import { prisma } from "@/lib/db";
export const dynamic = "force-dynamic";
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const base = SITE_URL.replace(/\/$/, "");
const staticRoutes: MetadataRoute.Sitemap = [
{ url: `${base}/`, changeFrequency: "weekly", priority: 1 },
{ url: `${base}/about`, changeFrequency: "monthly", priority: 0.8 },
{ url: `${base}/news/notice`, changeFrequency: "daily", priority: 0.9 },
{ url: `${base}/archive`, changeFrequency: "weekly", priority: 0.8 },
{ url: `${base}/contact`, changeFrequency: "monthly", priority: 0.6 },
{ url: `${base}/privacy`, changeFrequency: "yearly", priority: 0.3 },
{ url: `${base}/terms`, changeFrequency: "yearly", priority: 0.3 },
];
try {
const posts = await prisma.post.findMany({
where: { status: "PUBLISHED" },
select: { id: true, type: true, updatedAt: true },
orderBy: { publishedAt: "desc" },
take: 500,
});
const postRoutes: MetadataRoute.Sitemap = posts.map((post) => ({
url: `${base}${post.type === "NOTICE" ? "/news/notice" : "/archive"}/${post.id}`,
lastModified: post.updatedAt,
changeFrequency: "monthly",
priority: 0.7,
}));
return [...staticRoutes, ...postRoutes];
} catch {
return staticRoutes;
}
}
+97
View File
@@ -0,0 +1,97 @@
"use client";
import Link from "next/link";
import { usePathname, useSearchParams } from "next/navigation";
import {
ExternalLink,
FileText,
FolderOpen,
LayoutDashboard,
LogOut,
MessageSquare,
Settings,
} from "lucide-react";
import { logoutAction } from "@/actions/auth";
const ITEMS = [
{ href: "/admin", label: "대시보드", icon: LayoutDashboard, match: "dashboard" },
{ href: "/admin/posts?type=NOTICE", label: "공지사항", icon: FileText, match: "notice" },
{ href: "/admin/posts?type=ARCHIVE", label: "자료실", icon: FolderOpen, match: "archive" },
{ href: "/admin/inquiries", label: "문의·제보", icon: MessageSquare, match: "inquiries" },
{ href: "/admin/settings", label: "사이트 설정", icon: Settings, match: "settings" },
] as const;
export function AdminNav({ adminName, loginId }: { adminName: string; loginId: string }) {
const pathname = usePathname();
const searchParams = useSearchParams();
const type = searchParams.get("type") ?? "NOTICE";
function isActive(match: (typeof ITEMS)[number]["match"]) {
if (match === "dashboard") return pathname === "/admin";
if (match === "notice") return pathname.startsWith("/admin/posts") && type === "NOTICE";
if (match === "archive") return pathname.startsWith("/admin/posts") && type === "ARCHIVE";
if (match === "inquiries") return pathname.startsWith("/admin/inquiries");
return pathname.startsWith("/admin/settings");
}
return (
<div className="flex h-full flex-col">
<div className="px-5 py-6">
<Link href="/admin" className="flex items-center gap-2.5">
<span className="grid h-9 w-9 place-items-center rounded-xl bg-accent-500 text-[10px] font-black text-brand-950">
용공협
</span>
<span>
<span className="block text-sm font-bold text-white">관리자</span>
<span className="block text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-500">
Admin Console
</span>
</span>
</Link>
</div>
<nav className="flex-1 space-y-1 px-3" aria-label="관리자 메뉴">
{ITEMS.map((item) => {
const active = isActive(item.match);
return (
<Link
key={item.href}
href={item.href}
className={`flex items-center gap-2.5 rounded-lg px-3 py-2.5 text-sm font-semibold transition ${
active ? "bg-white/10 text-white" : "text-slate-400 hover:bg-white/5 hover:text-slate-200"
}`}
aria-current={active ? "page" : undefined}
>
<item.icon className="h-4 w-4" aria-hidden />
{item.label}
</Link>
);
})}
</nav>
<div className="border-t border-white/10 p-4">
<p className="truncate text-xs font-semibold text-slate-300">{adminName}</p>
<p className="truncate text-[11px] text-slate-500">{loginId}</p>
<div className="mt-3 space-y-1">
<Link
href="/"
className="flex items-center gap-2 rounded-lg px-2 py-2 text-xs font-semibold text-slate-400 transition hover:bg-white/5 hover:text-slate-200"
>
<ExternalLink className="h-3.5 w-3.5" aria-hidden />
사이트 보기
</Link>
<form action={logoutAction}>
<button
type="submit"
className="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-xs font-semibold text-slate-400 transition hover:bg-white/5 hover:text-rose-300"
>
<LogOut className="h-3.5 w-3.5" aria-hidden />
로그아웃
</button>
</form>
</div>
</div>
</div>
);
}
+29
View File
@@ -0,0 +1,29 @@
"use client";
import type { ReactNode } from "react";
export function ConfirmForm({
action,
message,
className,
children,
}: {
action: (formData: FormData) => void | Promise<void>;
message: string;
className?: string;
children: ReactNode;
}) {
return (
<form
action={action}
className={className}
onSubmit={(event) => {
if (!window.confirm(message)) {
event.preventDefault();
}
}}
>
{children}
</form>
);
}
+61
View File
@@ -0,0 +1,61 @@
"use client";
import { useActionState } from "react";
import { AlertCircle, Loader2, LogIn } from "lucide-react";
import { loginAction, type LoginState } from "@/actions/auth";
const initialState: LoginState = {};
export function LoginForm() {
const [state, formAction, pending] = useActionState(loginAction, initialState);
return (
<form action={formAction} className="space-y-4">
{state.error ? (
<p role="alert" className="flex items-start gap-2 rounded-xl bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
{state.error}
</p>
) : null}
<div>
<label htmlFor="loginId" className="mb-1.5 block text-xs font-bold text-slate-600">
관리자 아이디
</label>
<input
id="loginId"
name="loginId"
required
autoComplete="username"
maxLength={50}
className="h-11 w-full rounded-lg border border-slate-200 bg-white px-3.5 text-sm text-slate-800 focus:border-brand-400 focus:outline-none"
/>
</div>
<div>
<label htmlFor="password" className="mb-1.5 block text-xs font-bold text-slate-600">
비밀번호
</label>
<input
id="password"
name="password"
type="password"
required
autoComplete="current-password"
maxLength={200}
className="h-11 w-full rounded-lg border border-slate-200 bg-white px-3.5 text-sm text-slate-800 focus:border-brand-400 focus:outline-none"
/>
</div>
<button
type="submit"
disabled={pending}
className="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-brand-900 px-5 py-3 text-sm font-bold text-white transition hover:bg-brand-800 disabled:cursor-not-allowed disabled:opacity-60"
>
{pending ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <LogIn className="h-4 w-4" aria-hidden />}
{pending ? "로그인 중…" : "로그인"}
</button>
</form>
);
}
+218
View File
@@ -0,0 +1,218 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { Loader2, Paperclip, Save, Trash2 } from "lucide-react";
import { formatBytes } from "@/lib/constants";
import { ALLOWED_EXTENSIONS } from "@/lib/file-types";
type Attachment = {
id: number;
originalName: string;
size: number;
};
type PostFormProps = {
action: (formData: FormData) => void | Promise<void>;
defaultType: "NOTICE" | "ARCHIVE";
submitLabel: string;
cancelHref: string;
post?: {
id: number;
type: string;
category: string | null;
title: string;
content: string;
isPinned: boolean;
status: string;
attachments: Attachment[];
};
};
const inputClass =
"h-11 w-full rounded-lg border border-slate-200 bg-white px-3.5 text-sm text-slate-800 placeholder:text-slate-400 focus:border-brand-400 focus:outline-none";
const labelClass = "mb-1.5 block text-xs font-bold text-slate-600";
export function PostForm({ action, defaultType, submitLabel, cancelHref, post }: PostFormProps) {
const [type, setType] = useState<"NOTICE" | "ARCHIVE">(
post?.type === "ARCHIVE" ? "ARCHIVE" : defaultType,
);
const [contentLength, setContentLength] = useState(post?.content.length ?? 0);
return (
<form action={action} className="space-y-5">
{post ? <input type="hidden" name="id" value={post.id} /> : null}
<div className="grid gap-4 rounded-xl border border-slate-200 bg-white p-5 sm:grid-cols-2">
<div>
<label htmlFor="type" className={labelClass}>
게시판 <span className="text-rose-500">*</span>
</label>
<select
id="type"
name="type"
value={type}
onChange={(event) => setType(event.target.value === "ARCHIVE" ? "ARCHIVE" : "NOTICE")}
className={inputClass}
>
<option value="NOTICE">공지사항</option>
<option value="ARCHIVE">자료실</option>
</select>
</div>
<div>
<label htmlFor="category" className={labelClass}>
분류
</label>
<input
id="category"
name="category"
defaultValue={post?.category ?? ""}
maxLength={30}
list={type === "NOTICE" ? "notice-categories" : "archive-categories"}
className={inputClass}
placeholder={type === "NOTICE" ? "예: 공지, 행사, 보도" : "예: 보고서, 회의자료, 서식"}
/>
<datalist id="notice-categories">
{["공지", "행사", "보도", "성명"].map((item) => (
<option key={item} value={item} />
))}
</datalist>
<datalist id="archive-categories">
{["보고서", "회의자료", "서식", "홍보물", "사진"].map((item) => (
<option key={item} value={item} />
))}
</datalist>
</div>
<div className="sm:col-span-2">
<label htmlFor="title" className={labelClass}>
제목 <span className="text-rose-500">*</span>
</label>
<input
id="title"
name="title"
required
defaultValue={post?.title ?? ""}
maxLength={200}
className={inputClass}
placeholder="게시글 제목을 입력해 주세요."
/>
</div>
</div>
<div className="rounded-xl border border-slate-200 bg-white p-5">
<div className="flex flex-wrap items-center justify-between gap-2">
<label htmlFor="content" className={labelClass}>
내용 <span className="text-rose-500">*</span>
</label>
<span className="mb-1.5 text-[11px] text-slate-400">마크다운 문법 사용 가능 · {contentLength.toLocaleString()}자</span>
</div>
<textarea
id="content"
name="content"
required
rows={18}
defaultValue={post?.content ?? ""}
onChange={(event) => setContentLength(event.target.value.length)}
maxLength={200_000}
className="w-full resize-y rounded-lg border border-slate-200 bg-white px-3.5 py-3 font-mono text-[13px] leading-7 text-slate-800 placeholder:text-slate-400 focus:border-brand-400 focus:outline-none"
placeholder={"## 소제목\n\n본문 내용을 입력해 주세요.\n\n- 목록 항목\n- **강조** 표시"}
/>
</div>
{post && post.attachments.length > 0 ? (
<div className="rounded-xl border border-slate-200 bg-white p-5">
<h2 className="flex items-center gap-2 text-xs font-bold text-slate-600">
<Paperclip className="h-3.5 w-3.5" aria-hidden />
기존 첨부파일
</h2>
<ul className="mt-3 divide-y divide-slate-100">
{post.attachments.map((attachment) => (
<li key={attachment.id} className="flex items-center justify-between gap-3 py-2.5">
<div className="min-w-0">
<p className="truncate text-sm font-semibold text-slate-700">{attachment.originalName}</p>
<p className="text-[11px] text-slate-400">{formatBytes(attachment.size)}</p>
</div>
<label className="inline-flex shrink-0 cursor-pointer items-center gap-1.5 text-[11px] font-bold text-rose-600">
<input type="checkbox" name="removeAttachment" value={attachment.id} className="h-3.5 w-3.5 rounded border-slate-300" />
<Trash2 className="h-3 w-3" aria-hidden />
삭제
</label>
</li>
))}
</ul>
<p className="mt-2 text-[11px] text-slate-400">삭제를 선택한 파일은 저장 시 함께 삭제됩니다.</p>
</div>
) : null}
<div className="rounded-xl border border-slate-200 bg-white p-5">
<label htmlFor="attachments" className={labelClass}>
첨부파일 추가
</label>
<input
id="attachments"
name="attachments"
type="file"
multiple
className="block w-full cursor-pointer rounded-lg border border-dashed border-slate-300 bg-slate-50 px-3 py-3 text-sm text-slate-600 file:mr-3 file:rounded-md file:border-0 file:bg-brand-900 file:px-3 file:py-1.5 file:text-xs file:font-bold file:text-white"
/>
<p className="mt-2 text-[11px] leading-5 text-slate-400">
파일당 최대 50MB, 최대 10개(요청 전체 60MB 이내). 지원 형식: {ALLOWED_EXTENSIONS.join(", ")}
</p>
</div>
<div className="grid gap-4 rounded-xl border border-slate-200 bg-white p-5 sm:grid-cols-2">
<div>
<label htmlFor="status" className={labelClass}>
공개 상태
</label>
<select id="status" name="status" defaultValue={post?.status ?? "PUBLISHED"} className={inputClass}>
<option value="PUBLISHED">공개</option>
<option value="DRAFT">임시저장</option>
</select>
</div>
<div className="flex items-end">
<label
className={`flex w-full items-center gap-2.5 rounded-lg border px-3.5 py-3 text-sm font-semibold ${
type === "NOTICE" ? "border-slate-200 text-slate-700" : "cursor-not-allowed border-slate-100 bg-slate-50 text-slate-400"
}`}
>
<input
type="checkbox"
name="isPinned"
defaultChecked={post?.isPinned ?? false}
disabled={type !== "NOTICE"}
className="h-4 w-4 rounded border-slate-300 text-brand-700 focus:ring-brand-400"
/>
공지사항 상단 고정
</label>
</div>
</div>
<div className="flex flex-wrap items-center justify-end gap-2">
<Link
href={cancelHref}
className="rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm font-bold text-slate-600 transition hover:border-slate-300"
>
취소
</Link>
<button
type="submit"
className="inline-flex items-center gap-2 rounded-lg bg-brand-900 px-5 py-2.5 text-sm font-bold text-white transition hover:bg-brand-800"
>
<Save className="h-4 w-4" aria-hidden />
{submitLabel}
</button>
</div>
<p className="flex items-center justify-end gap-1.5 text-[11px] text-slate-400">
<Loader2 className="h-3 w-3" aria-hidden />
저장 중에는 페이지를 닫지 마세요.
</p>
</form>
);
}
+57
View File
@@ -0,0 +1,57 @@
import { Download, FileText, ImageIcon } from "lucide-react";
import { formatBytes } from "@/lib/constants";
import { isImageFile } from "@/lib/file-types";
type Attachment = {
id: number;
originalName: string;
mimeType: string;
size: number;
downloadCount: number;
};
export function AttachmentList({
attachments,
showDownloadCount = true,
}: {
attachments: Attachment[];
showDownloadCount?: boolean;
}) {
if (attachments.length === 0) return null;
return (
<section className="mt-10 rounded-2xl border border-slate-200 bg-slate-50/80 p-5 sm:p-6" aria-label="첨부파일">
<h2 className="flex items-center gap-2 text-sm font-bold text-brand-950">
<FileText className="h-4 w-4 text-brand-600" aria-hidden />
첨부파일 <span className="font-semibold text-slate-400">{attachments.length}</span>
</h2>
<ul className="mt-3 divide-y divide-slate-200">
{attachments.map((attachment) => {
const image = isImageFile(attachment.originalName, attachment.mimeType);
return (
<li key={attachment.id} className="flex flex-wrap items-center gap-3 py-3">
<span className="grid h-9 w-9 shrink-0 place-items-center rounded-lg bg-white text-brand-600 ring-1 ring-slate-200">
{image ? <ImageIcon className="h-4 w-4" /> : <FileText className="h-4 w-4" />}
</span>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-semibold text-slate-700">{attachment.originalName}</p>
<p className="mt-0.5 text-xs text-slate-400">
{formatBytes(attachment.size)}
{showDownloadCount ? ` · 다운로드 ${attachment.downloadCount}회` : ""}
</p>
</div>
<a
href={`/api/files/${attachment.id}?download=1`}
className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3 py-2 text-xs font-semibold text-slate-600 transition hover:border-brand-200 hover:text-brand-700"
>
<Download className="h-3.5 w-3.5" aria-hidden />
다운로드
</a>
</li>
);
})}
</ul>
</section>
);
}
+129
View File
@@ -0,0 +1,129 @@
import Link from "next/link";
import { Eye, Paperclip, Pin } from "lucide-react";
import { formatDate } from "@/lib/constants";
type BoardPost = {
id: number;
category: string | null;
title: string;
isPinned: boolean;
publishedAt: Date;
viewCount: number;
_count: { attachments: number };
};
export function BoardList({
posts,
basePath,
variant = "notice",
}: {
posts: BoardPost[];
basePath: string;
variant?: "notice" | "archive";
}) {
return (
<>
<div className="hidden overflow-hidden rounded-2xl border border-slate-200 bg-white md:block">
<table className="w-full table-fixed border-collapse text-left">
<caption className="sr-only">게시글 목록</caption>
<thead>
<tr className="border-b border-slate-200 bg-slate-50 text-xs font-bold text-slate-500">
<th scope="col" className="w-28 px-5 py-3.5">
분류
</th>
<th scope="col" className="px-5 py-3.5">
제목
</th>
<th scope="col" className="w-32 px-5 py-3.5 text-right">
작성일
</th>
<th scope="col" className="w-24 px-5 py-3.5 text-right">
{variant === "archive" ? "첨부" : "조회"}
</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{posts.map((post) => (
<tr key={post.id} className={`group transition hover:bg-brand-50/40 ${post.isPinned ? "bg-amber-50/40" : ""}`}>
<td className="px-5 py-4">
<span className="inline-flex items-center gap-1.5 rounded-md bg-slate-100 px-2 py-1 text-[11px] font-bold text-slate-600">
{post.isPinned ? <Pin className="h-3 w-3 text-accent-600" aria-hidden /> : null}
{post.category || (variant === "archive" ? "자료" : "공지")}
</span>
</td>
<td className="px-5 py-4">
<Link
href={`${basePath}/${post.id}`}
className="line-clamp-1 text-sm font-semibold text-slate-700 transition group-hover:text-brand-800"
>
{post.isPinned ? <span className="mr-1.5 text-[11px] font-bold text-accent-700">[고정]</span> : null}
{post.title}
</Link>
</td>
<td className="px-5 py-4 text-right text-xs text-slate-400">{formatDate(post.publishedAt)}</td>
<td className="px-5 py-4">
<span className="flex items-center justify-end gap-1.5 text-xs text-slate-400">
{variant === "archive" ? (
<>
<Paperclip className="h-3.5 w-3.5" aria-hidden />
{post._count.attachments}
</>
) : (
<>
<Eye className="h-3.5 w-3.5" aria-hidden />
{post.viewCount.toLocaleString("ko-KR")}
</>
)}
</span>
</td>
</tr>
))}
</tbody>
</table>
</div>
<ul className="space-y-3 md:hidden">
{posts.map((post) => (
<li key={post.id}>
<Link
href={`${basePath}/${post.id}`}
className={`block rounded-2xl border bg-white p-4 transition active:bg-slate-50 ${
post.isPinned ? "border-accent-300" : "border-slate-200"
}`}
>
<div className="flex items-center gap-2">
<span className="rounded-md bg-slate-100 px-2 py-1 text-[10px] font-bold text-slate-600">
{post.category || (variant === "archive" ? "자료" : "공지")}
</span>
{post.isPinned ? (
<span className="inline-flex items-center gap-1 rounded-md bg-accent-500/15 px-2 py-1 text-[10px] font-bold text-accent-700">
<Pin className="h-2.5 w-2.5" aria-hidden />
고정
</span>
) : null}
</div>
<p className="mt-2 line-clamp-2 text-sm font-semibold leading-6 text-slate-700">{post.title}</p>
<div className="mt-2 flex items-center justify-between text-[11px] text-slate-400">
<span>{formatDate(post.publishedAt)}</span>
<span className="flex items-center gap-1">
{variant === "archive" ? (
<>
<Paperclip className="h-3 w-3" aria-hidden />
첨부 {post._count.attachments}
</>
) : (
<>
<Eye className="h-3 w-3" aria-hidden />
{post.viewCount.toLocaleString("ko-KR")}
</>
)}
</span>
</div>
</Link>
</li>
))}
</ul>
</>
);
}
+23
View File
@@ -0,0 +1,23 @@
import type { ReactNode } from "react";
import { Inbox } from "lucide-react";
export function EmptyState({
title = "등록된 게시글이 없습니다.",
description = "새로운 소식이 등록되면 이곳에서 확인하실 수 있습니다.",
action,
}: {
title?: string;
description?: string;
action?: ReactNode;
}) {
return (
<div className="flex flex-col items-center justify-center rounded-2xl border border-dashed border-slate-300 bg-white px-6 py-16 text-center">
<span className="grid h-12 w-12 place-items-center rounded-full bg-slate-100 text-slate-400">
<Inbox className="h-5 w-5" aria-hidden />
</span>
<p className="mt-4 text-sm font-bold text-slate-700">{title}</p>
<p className="mt-1 text-xs leading-6 text-slate-400">{description}</p>
{action ? <div className="mt-5">{action}</div> : null}
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
"use client";
import { useActionState } from "react";
import { AlertCircle, Loader2, Send } from "lucide-react";
import { submitInquiryAction, type InquiryState } from "@/actions/inquiries";
const initialState: InquiryState = {};
const inputClass =
"h-11 w-full rounded-lg border border-slate-200 bg-white px-3.5 text-sm text-slate-800 placeholder:text-slate-400 focus:border-brand-400 focus:outline-none";
const labelClass = "mb-1.5 block text-xs font-bold text-slate-600";
export function InquiryForm() {
const [state, formAction, pending] = useActionState(submitInquiryAction, initialState);
return (
<form action={formAction} className="space-y-5">
{state.error ? (
<p role="alert" className="flex items-start gap-2 rounded-xl bg-rose-50 px-4 py-3 text-sm font-semibold text-rose-700">
<AlertCircle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
{state.error}
</p>
) : null}
<div className="grid gap-4 sm:grid-cols-2">
<div>
<label htmlFor="name" className={labelClass}>
성함 <span className="text-rose-500">*</span>
</label>
<input id="name" name="name" required maxLength={50} autoComplete="name" className={inputClass} placeholder="홍길동" />
</div>
<div>
<label htmlFor="phone" className={labelClass}>
연락처
</label>
<input id="phone" name="phone" maxLength={30} autoComplete="tel" className={inputClass} placeholder="010-0000-0000" />
</div>
</div>
<div>
<label htmlFor="email" className={labelClass}>
이메일 <span className="text-rose-500">*</span>
</label>
<input
id="email"
name="email"
type="email"
required
maxLength={200}
autoComplete="email"
className={inputClass}
placeholder="example@email.com"
/>
</div>
<div>
<label htmlFor="title" className={labelClass}>
제목 <span className="text-rose-500">*</span>
</label>
<input id="title" name="title" required maxLength={200} className={inputClass} placeholder="문의 또는 제보 제목" />
</div>
<div>
<label htmlFor="content" className={labelClass}>
내용 <span className="text-rose-500">*</span>
</label>
<textarea
id="content"
name="content"
required
rows={8}
maxLength={5000}
className="w-full resize-y rounded-lg border border-slate-200 bg-white px-3.5 py-3 text-sm leading-7 text-slate-800 placeholder:text-slate-400 focus:border-brand-400 focus:outline-none"
placeholder="정비가 필요한 위치(동명, 도로명, 건물 주변)와 문제 상황을 구체적으로 적어 주세요."
/>
</div>
<div className="rounded-xl bg-slate-50 p-4">
<label htmlFor="consent" className="flex items-start gap-2.5 text-xs leading-6 text-slate-600">
<input id="consent" name="consent" type="checkbox" required className="mt-1 h-4 w-4 rounded border-slate-300 text-brand-700 focus:ring-brand-400" />
<span>
<span className="font-bold text-slate-700">[필수]</span> 문의 접수 및 답변을 위한 개인정보(성함, 이메일, 연락처) 수집·이용에
동의합니다. 수집된 정보는 문의 처리 목적으로만 사용되며 처리 완료 후 파기됩니다.
</span>
</label>
</div>
{/* 허니팟: 화면에는 보이지 않으며 봇이 채우면 접수를 거부합니다. */}
<div className="hidden" aria-hidden>
<label htmlFor="website">웹사이트</label>
<input id="website" name="website" tabIndex={-1} autoComplete="off" />
</div>
<button
type="submit"
disabled={pending}
className="inline-flex w-full items-center justify-center gap-2 rounded-xl bg-brand-900 px-5 py-3.5 text-sm font-bold text-white transition hover:bg-brand-800 disabled:cursor-not-allowed disabled:opacity-60 sm:w-auto sm:px-8"
>
{pending ? <Loader2 className="h-4 w-4 animate-spin" aria-hidden /> : <Send className="h-4 w-4" aria-hidden />}
{pending ? "접수 중…" : "문의 접수하기"}
</button>
</form>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { ComponentProps } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
export function MarkdownContent({ content }: { content: string }) {
return (
<div className="prose-yg">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
a: ({ node: _node, href, children, ...props }: ComponentProps<"a"> & { node?: unknown }) => {
const external = href?.startsWith("http");
return (
<a
href={href}
{...(external ? { target: "_blank", rel: "noreferrer" } : {})}
{...props}
>
{children}
</a>
);
},
img: ({ node: _node, src, alt }: ComponentProps<"img"> & { node?: unknown }) => {
if (typeof src !== "string") return null;
return <img src={src} alt={alt ?? ""} loading="lazy" />;
},
}}
>
{content}
</ReactMarkdown>
</div>
);
}
+52
View File
@@ -0,0 +1,52 @@
import Link from "next/link";
import { ChevronRight } from "lucide-react";
type PageHeroProps = {
eyebrow?: string;
title: string;
description?: string;
breadcrumb?: { label: string; href?: string }[];
};
export function PageHero({ eyebrow, title, description, breadcrumb }: PageHeroProps) {
return (
<section className="relative overflow-hidden bg-brand-950 text-white">
<div
className="pointer-events-none absolute inset-0 opacity-70"
style={{
background:
"radial-gradient(circle at 15% 20%, rgba(64,160,191,0.35), transparent 32%), radial-gradient(circle at 85% 10%, rgba(242,183,5,0.18), transparent 28%)",
}}
aria-hidden
/>
<div className="site-container relative py-12 sm:py-16">
{breadcrumb?.length ? (
<nav className="mb-5 flex flex-wrap items-center gap-1 text-xs text-slate-400" aria-label="breadcrumb">
<Link href="/" className="hover:text-white">
홈
</Link>
{breadcrumb.map((item) => (
<span key={item.label} className="inline-flex items-center gap-1">
<ChevronRight className="h-3 w-3" aria-hidden />
{item.href ? (
<Link href={item.href} className="hover:text-white">
{item.label}
</Link>
) : (
<span className="text-slate-200">{item.label}</span>
)}
</span>
))}
</nav>
) : null}
{eyebrow ? (
<p className="text-xs font-bold uppercase tracking-[0.2em] text-accent-400">{eyebrow}</p>
) : null}
<h1 className="mt-3 text-3xl font-black tracking-tight sm:text-4xl">{title}</h1>
{description ? (
<p className="mt-4 max-w-2xl text-sm leading-7 text-slate-300 sm:text-base">{description}</p>
) : null}
</div>
</section>
);
}
+85
View File
@@ -0,0 +1,85 @@
import Link from "next/link";
import { ChevronLeft, ChevronRight } from "lucide-react";
type PaginationProps = {
currentPage: number;
totalPages: number;
basePath: string;
query?: Record<string, string | undefined>;
};
function buildHref(basePath: string, page: number, query: Record<string, string | undefined>) {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(query)) {
if (value) params.set(key, value);
}
if (page > 1) params.set("page", String(page));
const queryString = params.toString();
return queryString ? `${basePath}?${queryString}` : basePath;
}
export function Pagination({ currentPage, totalPages, basePath, query = {} }: PaginationProps) {
if (totalPages <= 1) return null;
const pages: (number | "ellipsis")[] = [];
for (let page = 1; page <= totalPages; page += 1) {
if (page === 1 || page === totalPages || Math.abs(page - currentPage) <= 2) {
pages.push(page);
} else if (pages[pages.length - 1] !== "ellipsis") {
pages.push("ellipsis");
}
}
return (
<nav className="mt-8 flex items-center justify-center gap-1.5" aria-label="페이지 이동">
{currentPage > 1 ? (
<Link
href={buildHref(basePath, currentPage - 1, query)}
className="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:border-brand-200 hover:text-brand-700"
aria-label="이전 페이지"
>
<ChevronLeft className="h-4 w-4" />
</Link>
) : (
<span className="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-slate-100 text-slate-300">
<ChevronLeft className="h-4 w-4" />
</span>
)}
{pages.map((page, index) =>
page === "ellipsis" ? (
<span key={`ellipsis-${index}`} className="px-1 text-sm text-slate-400">
…
</span>
) : (
<Link
key={page}
href={buildHref(basePath, page, query)}
aria-current={page === currentPage ? "page" : undefined}
className={`inline-flex h-9 min-w-9 items-center justify-center rounded-lg px-2 text-sm font-semibold transition ${
page === currentPage
? "bg-brand-900 text-white"
: "border border-slate-200 bg-white text-slate-600 hover:border-brand-200 hover:text-brand-700"
}`}
>
{page}
</Link>
),
)}
{currentPage < totalPages ? (
<Link
href={buildHref(basePath, currentPage + 1, query)}
className="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:border-brand-200 hover:text-brand-700"
aria-label="다음 페이지"
>
<ChevronRight className="h-4 w-4" />
</Link>
) : (
<span className="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-slate-100 text-slate-300">
<ChevronRight className="h-4 w-4" />
</span>
)}
</nav>
);
}
+33
View File
@@ -0,0 +1,33 @@
import Link from "next/link";
import { ArrowRight } from "lucide-react";
type SectionHeadingProps = {
eyebrow?: string;
title: string;
description?: string;
href?: string;
linkLabel?: string;
};
export function SectionHeading({ eyebrow, title, description, href, linkLabel = "전체보기" }: SectionHeadingProps) {
return (
<div className="flex flex-wrap items-end justify-between gap-4">
<div>
{eyebrow ? (
<p className="text-xs font-bold uppercase tracking-[0.18em] text-brand-600">{eyebrow}</p>
) : null}
<h2 className="mt-2 text-2xl font-black tracking-tight text-brand-950 sm:text-3xl">{title}</h2>
{description ? <p className="mt-2 text-sm leading-6 text-slate-500">{description}</p> : null}
</div>
{href ? (
<Link
href={href}
className="inline-flex items-center gap-1.5 rounded-lg border border-slate-200 bg-white px-3.5 py-2 text-sm font-semibold text-slate-600 transition hover:border-brand-200 hover:text-brand-800"
>
{linkLabel}
<ArrowRight className="h-4 w-4" aria-hidden />
</Link>
) : null}
</div>
);
}
+102
View File
@@ -0,0 +1,102 @@
import Link from "next/link";
import { ExternalLink, Mail, MapPin, Phone } from "lucide-react";
import type { SiteSettings } from "@/lib/settings";
export function SiteFooter({ settings }: { settings: SiteSettings }) {
return (
<footer className="mt-20 bg-brand-950 text-slate-300">
<div className="site-container grid gap-10 py-12 md:grid-cols-[1.4fr_1fr_1fr]">
<div>
<div className="flex items-center gap-2.5">
<span className="grid h-9 w-9 place-items-center rounded-lg bg-white/10 text-[9px] font-black text-white">
용공협
</span>
<span className="text-sm font-bold text-white">{settings.siteName}</span>
</div>
<p className="mt-4 max-w-md text-sm leading-7 text-slate-400">{settings.footerText}</p>
<p className="mt-4 text-xs leading-6 text-slate-500">
{settings.description}
</p>
</div>
<div>
<h2 className="text-xs font-bold uppercase tracking-[0.18em] text-slate-500">바로가기</h2>
<ul className="mt-4 space-y-2.5 text-sm">
<li>
<Link href="/about" className="transition hover:text-white">
협의회 소개
</Link>
</li>
<li>
<Link href="/news/notice" className="transition hover:text-white">
공지사항
</Link>
</li>
<li>
<Link href="/archive" className="transition hover:text-white">
자료실
</Link>
</li>
<li>
<Link href="/contact" className="transition hover:text-white">
문의·제보
</Link>
</li>
</ul>
</div>
<div>
<h2 className="text-xs font-bold uppercase tracking-[0.18em] text-slate-500">연락</h2>
<ul className="mt-4 space-y-3 text-sm">
<li className="flex items-start gap-2">
<MapPin className="mt-0.5 h-4 w-4 shrink-0 text-brand-300" aria-hidden />
<span>{settings.address}</span>
</li>
{settings.contactPhone ? (
<li className="flex items-center gap-2">
<Phone className="h-4 w-4 shrink-0 text-brand-300" aria-hidden />
<a href={`tel:${settings.contactPhone}`} className="transition hover:text-white">
{settings.contactPhone}
</a>
</li>
) : null}
{settings.contactEmail ? (
<li className="flex items-center gap-2">
<Mail className="h-4 w-4 shrink-0 text-brand-300" aria-hidden />
<a href={`mailto:${settings.contactEmail}`} className="transition hover:text-white">
{settings.contactEmail}
</a>
</li>
) : null}
<li>
<a
href={settings.blogUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1.5 text-brand-300 transition hover:text-white"
>
네이버 블로그
<ExternalLink className="h-3.5 w-3.5" aria-hidden />
</a>
</li>
</ul>
</div>
</div>
<div className="border-t border-white/10">
<div className="site-container flex flex-col gap-3 py-5 text-xs text-slate-500 sm:flex-row sm:items-center sm:justify-between">
<p>© {new Date().getFullYear()} {settings.siteName}. All rights reserved.</p>
<div className="flex gap-4">
<Link href="/privacy" className="transition hover:text-slate-300">
개인정보처리방침
</Link>
<Link href="/terms" className="transition hover:text-slate-300">
이용약관
</Link>
</div>
</div>
</div>
</footer>
);
}
+28
View File
@@ -0,0 +1,28 @@
import Link from "next/link";
import type { SiteSettings } from "@/lib/settings";
import { SiteNav } from "./site-nav";
export function SiteHeader({ settings }: { settings: SiteSettings }) {
return (
<header className="sticky top-0 z-40 border-b border-slate-200/80 bg-white/90 backdrop-blur">
<div className="site-container relative flex h-16 items-center justify-between gap-4 sm:h-[4.5rem]">
<Link href="/" className="flex min-w-0 items-center gap-2.5" aria-label={`${settings.siteName} 홈`}>
<span className="grid h-10 w-10 shrink-0 place-items-center rounded-xl bg-brand-900 text-[10px] font-black tracking-tight text-white">
용공협
</span>
<span className="min-w-0">
<span className="block truncate text-[14px] font-extrabold tracking-tight text-brand-950 sm:text-[15px]">
{settings.siteName}
</span>
<span className="mt-0.5 hidden text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-400 sm:block">
Yongsan Safety Council
</span>
</span>
</Link>
<SiteNav mapUrl={settings.mapUrl} blogUrl={settings.blogUrl} />
</div>
</header>
);
}
+138
View File
@@ -0,0 +1,138 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { ExternalLink, Menu, X } from "lucide-react";
type NavItem = {
href: string;
label: string;
external?: boolean;
};
const NAV_ITEMS: NavItem[] = [
{ href: "/about", label: "협의회 소개" },
{ href: "/news/notice", label: "공지사항" },
{ href: "/archive", label: "자료실" },
];
export function SiteNav({ mapUrl, blogUrl }: { mapUrl: string; blogUrl: string }) {
const pathname = usePathname();
const [open, setOpen] = useState(false);
useEffect(() => {
setOpen(false);
}, [pathname]);
const items: NavItem[] = [
...NAV_ITEMS,
{ href: mapUrl, label: "조사 현황", external: true },
{ href: "/contact", label: "문의·제보" },
];
function isActive(href: string) {
if (href === "/about") return pathname.startsWith("/about");
if (href === "/news/notice") return pathname.startsWith("/news");
if (href === "/archive") return pathname.startsWith("/archive");
if (href === "/contact") return pathname.startsWith("/contact");
return false;
}
return (
<>
<nav className="hidden items-center gap-1 lg:flex" aria-label="주 메뉴">
{items.map((item) =>
item.external ? (
<a
key={item.href}
href={item.href}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 rounded-lg px-3 py-2 text-sm font-semibold text-slate-600 transition hover:bg-brand-50 hover:text-brand-800"
>
{item.label}
<ExternalLink className="h-3.5 w-3.5" aria-hidden />
</a>
) : (
<Link
key={item.href}
href={item.href}
className={`rounded-lg px-3 py-2 text-sm font-semibold transition ${
isActive(item.href)
? "bg-brand-50 text-brand-800"
: "text-slate-600 hover:bg-brand-50 hover:text-brand-800"
}`}
aria-current={isActive(item.href) ? "page" : undefined}
>
{item.label}
</Link>
),
)}
<a
href={blogUrl}
target="_blank"
rel="noreferrer"
className="ml-2 inline-flex items-center gap-1.5 rounded-lg bg-brand-900 px-3.5 py-2 text-sm font-semibold text-white transition hover:bg-brand-800"
>
블로그
<ExternalLink className="h-3.5 w-3.5" aria-hidden />
</a>
</nav>
<button
type="button"
className="inline-flex h-10 w-10 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-700 lg:hidden"
onClick={() => setOpen((value) => !value)}
aria-expanded={open}
aria-controls="mobile-menu"
aria-label={open ? "메뉴 닫기" : "메뉴 열기"}
>
{open ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
</button>
{open ? (
<div
id="mobile-menu"
className="absolute inset-x-0 top-full border-b border-slate-200 bg-white shadow-xl lg:hidden"
>
<nav className="site-container flex flex-col py-3" aria-label="모바일 메뉴">
{items.map((item) =>
item.external ? (
<a
key={item.href}
href={item.href}
target="_blank"
rel="noreferrer"
className="flex items-center justify-between rounded-xl px-3 py-3.5 text-[15px] font-semibold text-slate-700 hover:bg-slate-50"
>
{item.label}
<ExternalLink className="h-4 w-4 text-slate-400" aria-hidden />
</a>
) : (
<Link
key={item.href}
href={item.href}
className={`rounded-xl px-3 py-3.5 text-[15px] font-semibold ${
isActive(item.href) ? "bg-brand-50 text-brand-800" : "text-slate-700 hover:bg-slate-50"
}`}
>
{item.label}
</Link>
),
)}
<a
href={blogUrl}
target="_blank"
rel="noreferrer"
className="mt-2 flex items-center justify-between rounded-xl bg-brand-900 px-3 py-3.5 text-[15px] font-semibold text-white"
>
네이버 블로그
<ExternalLink className="h-4 w-4" aria-hidden />
</a>
</nav>
</div>
) : null}
</>
);
}
+27
View File
@@ -0,0 +1,27 @@
import "server-only";
import { prisma } from "@/lib/db";
type AuditInput = {
adminId?: string | null;
action: string;
targetType?: string | null;
targetId?: string | number | null;
ip?: string | null;
};
export async function writeAudit({ adminId, action, targetType, targetId, ip }: AuditInput) {
try {
await prisma.auditLog.create({
data: {
adminId: adminId ?? null,
action,
targetType: targetType ?? null,
targetId: targetId === undefined || targetId === null ? null : String(targetId),
ip: ip ?? null,
},
});
} catch (error) {
console.error("감사 로그 기록 실패", error);
}
}
+97
View File
@@ -0,0 +1,97 @@
import "server-only";
import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { SignJWT, jwtVerify } from "jose";
import { prisma } from "@/lib/db";
const COOKIE_NAME = "yg_admin_session";
const SESSION_HOURS = 8;
export type SessionPayload = {
sub: string;
loginId: string;
name: string;
role: string;
};
function getSecret() {
const secret = process.env.AUTH_SECRET;
if (!secret) {
throw new Error("AUTH_SECRET 환경변수가 설정되지 않았습니다.");
}
return new TextEncoder().encode(secret);
}
export async function createSession(payload: SessionPayload) {
const token = await new SignJWT({ ...payload })
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setIssuer("yonggong-web")
.setAudience("yonggong-admin")
.setExpirationTime(`${SESSION_HOURS}h`)
.sign(getSecret());
const cookieStore = await cookies();
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? "";
cookieStore.set(COOKIE_NAME, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production" && siteUrl.startsWith("https://"),
sameSite: "lax",
path: "/",
maxAge: SESSION_HOURS * 60 * 60,
});
}
export async function destroySession() {
const cookieStore = await cookies();
cookieStore.delete(COOKIE_NAME);
}
export async function getSession(): Promise<SessionPayload | null> {
const cookieStore = await cookies();
const token = cookieStore.get(COOKIE_NAME)?.value;
if (!token) return null;
try {
const { payload } = await jwtVerify(token, getSecret(), {
issuer: "yonggong-web",
audience: "yonggong-admin",
});
if (!payload.sub || typeof payload.loginId !== "string") return null;
return {
sub: payload.sub,
loginId: payload.loginId,
name: typeof payload.name === "string" ? payload.name : payload.loginId,
role: typeof payload.role === "string" ? payload.role : "ADMIN",
};
} catch {
return null;
}
}
export async function getCurrentAdmin() {
const session = await getSession();
if (!session) return null;
return prisma.adminUser.findUnique({
where: { id: session.sub },
select: { id: true, loginId: true, name: true, role: true, lastLoginAt: true },
});
}
export async function requireAdmin() {
const admin = await getCurrentAdmin();
if (!admin) redirect("/admin/login");
return admin;
}
export async function getClientIp() {
const headerStore = await headers();
const forwarded = headerStore.get("x-forwarded-for");
if (forwarded) return forwarded.split(",")[0]?.trim() ?? null;
return headerStore.get("x-real-ip");
}
+80
View File
@@ -0,0 +1,80 @@
import "server-only";
const BLOG_RSS_URL = "https://rss.blog.naver.com/safetyovhcable.xml";
const BLOG_FEED_LIMIT = 5;
const FEED_REVALIDATE_SECONDS = 1800;
export type BlogPost = {
title: string;
url: string;
publishedAt: string | null;
};
function decodeEntities(value: string) {
const named: Record<string, string> = {
amp: "&",
lt: "<",
gt: ">",
quot: '"',
apos: "'",
nbsp: " ",
};
return value
.replace(/&#x([0-9a-f]+);/gi, (_, hex: string) => String.fromCodePoint(Number.parseInt(hex, 16)))
.replace(/&#(\d+);/g, (_, dec: string) => String.fromCodePoint(Number.parseInt(dec, 10)))
.replace(/&([a-z]+);/gi, (match, name: string) => named[name.toLowerCase()] ?? match);
}
function cleanText(value: string) {
const withoutCdata = value.replace(/^<!\[CDATA\[/, "").replace(/\]\]>$/, "");
return decodeEntities(withoutCdata.replace(/<[^>]*>/g, "")).trim();
}
function readTag(item: string, tag: string) {
const match = item.match(new RegExp(`<${tag}[^>]*>([\\s\\S]*?)</${tag}>`, "i"));
return match ? cleanText(match[1]) : "";
}
function parseFeed(xml: string): BlogPost[] {
const items = xml.match(/<item[\s>][\s\S]*?<\/item>/gi) ?? [];
return items
.map((item) => {
const title = readTag(item, "title");
const url = readTag(item, "link").split("?")[0];
const pubDate = readTag(item, "pubDate");
const published = pubDate ? new Date(pubDate) : null;
return {
title,
url,
publishedAt:
published && !Number.isNaN(published.getTime()) ? published.toISOString() : null,
};
})
.filter((post) => post.title && post.url)
.sort((a, b) => (b.publishedAt ?? "").localeCompare(a.publishedAt ?? ""))
.slice(0, BLOG_FEED_LIMIT);
}
export async function getLatestBlogPosts(): Promise<BlogPost[]> {
try {
const response = await fetch(BLOG_RSS_URL, {
cache: "force-cache",
next: { revalidate: FEED_REVALIDATE_SECONDS },
headers: {
"User-Agent": "Mozilla/5.0 (compatible; yonggong-site/1.0)",
Accept: "application/rss+xml, application/xml, text/xml",
},
signal: AbortSignal.timeout(5000),
});
if (!response.ok) return [];
return parseFeed(await response.text());
} catch {
// 블로그 RSS 장애가 홈페이지 렌더링을 막지 않도록 빈 목록을 돌려줍니다.
return [];
}
}
+66
View File
@@ -0,0 +1,66 @@
export const SITE_NAME = "용산 공중케이블 주민 안전 협의회";
export const SITE_SHORT_NAME = "용공협";
export const SITE_DESCRIPTION =
"용산구 공중케이블 문제 해결과 안전한 거리 환경 조성을 위해 활동하는 주민 모임입니다.";
export const SITE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "https://saftyovhcable.kr";
export const BLOG_URL = "https://blog.naver.com/safetyovhcable";
export const LEGACY_MAP_URL =
process.env.NEXT_PUBLIC_LEGACY_MAP_URL ?? "https://saftyovhcable.kr/addMarker.html";
export const POST_TYPES = {
NOTICE: "공지사항",
ARCHIVE: "자료실",
} as const;
export type PostType = keyof typeof POST_TYPES;
export const NOTICE_CATEGORIES = ["공지", "행사", "보도", "성명"] as const;
export const ARCHIVE_CATEGORIES = ["보고서", "회의자료", "서식", "홍보물", "사진"] as const;
export const POST_STATUSES = {
PUBLISHED: "공개",
DRAFT: "임시저장",
} as const;
export const INQUIRY_STATUSES = {
NEW: "접수",
IN_PROGRESS: "처리중",
DONE: "완료",
} as const;
export const PAGE_SIZE = 10;
export const ADMIN_PAGE_SIZE = 15;
export const SURVEY_COUNT_LABEL = "1,700+";
export const ACTIVITY_START_YEAR = "2024";
export function formatDate(value: Date | string) {
const date = typeof value === "string" ? new Date(value) : value;
return new Intl.DateTimeFormat("ko-KR", {
year: "numeric",
month: "2-digit",
day: "2-digit",
timeZone: "Asia/Seoul",
})
.format(date)
.replace(/\.$/, "");
}
export function formatDateTime(value: Date | string) {
const date = typeof value === "string" ? new Date(value) : value;
return new Intl.DateTimeFormat("ko-KR", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
timeZone: "Asia/Seoul",
}).format(date);
}
export function formatBytes(bytes: number) {
if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
const units = ["B", "KB", "MB", "GB"];
const index = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1);
return `${(bytes / 1024 ** index).toFixed(index === 0 ? 0 : 1)} ${units[index]}`;
}
+15
View File
@@ -0,0 +1,15 @@
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as {
prisma?: PrismaClient;
};
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({
log: process.env.NODE_ENV === "development" ? ["error", "warn"] : ["error"],
});
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
+44
View File
@@ -0,0 +1,44 @@
export const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB
const MIME_BY_EXTENSION: Record<string, string> = {
pdf: "application/pdf",
hwp: "application/x-hwp",
hwpx: "application/vnd.hancom.hwpx",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xls: "application/vnd.ms-excel",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
ppt: "application/vnd.ms-powerpoint",
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
zip: "application/zip",
jpg: "image/jpeg",
jpeg: "image/jpeg",
png: "image/png",
webp: "image/webp",
gif: "image/gif",
txt: "text/plain; charset=utf-8",
csv: "text/csv; charset=utf-8",
};
export const ALLOWED_EXTENSIONS = Object.keys(MIME_BY_EXTENSION);
export function getExtension(filename: string) {
// 파일명에서 확장자만 안전하게 추출합니다. (브라우저/서버 공용)
const base = filename.split(/[\\/]/).pop() ?? "";
const index = base.lastIndexOf(".");
if (index <= 0 || index === base.length - 1) return "";
return base.slice(index + 1).toLowerCase();
}
export function mimeFromExtension(filename: string) {
return MIME_BY_EXTENSION[getExtension(filename)] ?? "application/octet-stream";
}
export function isImageFile(filename: string, mimeType?: string) {
const ext = getExtension(filename);
return ["jpg", "jpeg", "png", "webp", "gif"].includes(ext) || Boolean(mimeType?.startsWith("image/"));
}
export function safeDownloadName(filename: string) {
return filename.replace(/[\r\n"]/g, "").trim() || "download";
}
+95
View File
@@ -0,0 +1,95 @@
import "server-only";
import crypto from "node:crypto";
import fs from "node:fs/promises";
import path from "node:path";
import {
ALLOWED_EXTENSIONS,
MAX_FILE_SIZE,
getExtension,
mimeFromExtension,
} from "@/lib/file-types";
export { ALLOWED_EXTENSIONS, MAX_FILE_SIZE, getExtension, isImageFile, mimeFromExtension, safeDownloadName } from "@/lib/file-types";
export type SavedFile = {
storageKey: string;
originalName: string;
mimeType: string;
size: number;
};
export function getUploadRoot() {
// 업로드 경로는 배포 환경마다 다르므로 런타임에 결정합니다.
// (Turbopack이 프로젝트 전체를 번들에 포함하지 않도록 ignore 처리)
return path.resolve(/* turbopackIgnore: true */ process.env.UPLOAD_DIR ?? "./storage/uploads");
}
function hasExpectedSignature(buffer: Buffer, ext: string) {
const hex = buffer.subarray(0, 12).toString("hex").toUpperCase();
if (["jpg", "jpeg"].includes(ext)) return hex.startsWith("FFD8FF");
if (ext === "png") return hex.startsWith("89504E47");
if (ext === "gif") return hex.startsWith("47494638");
if (ext === "webp") return hex.startsWith("52494646") && buffer.subarray(8, 12).toString() === "WEBP";
if (ext === "pdf") return hex.startsWith("25504446");
if (["zip", "hwpx", "docx", "xlsx", "pptx"].includes(ext)) return hex.startsWith("504B0304");
if (ext === "hwp") return hex.startsWith("D0CF11E0");
return true;
}
export async function saveUploadedFile(file: File): Promise<SavedFile> {
if (!file || typeof file === "string" || file.size === 0) {
throw new Error("업로드할 파일이 비어 있습니다.");
}
if (file.size > MAX_FILE_SIZE) {
throw new Error("파일은 50MB 이하만 업로드할 수 있습니다.");
}
const originalName = path.basename(file.name || "file");
const ext = getExtension(originalName);
if (!ext || !ALLOWED_EXTENSIONS.includes(ext)) {
throw new Error(`지원하지 않는 파일 형식입니다. (${ALLOWED_EXTENSIONS.join(", ")})`);
}
const buffer = Buffer.from(await file.arrayBuffer());
if (!hasExpectedSignature(buffer, ext)) {
throw new Error("파일 형식과 확장자가 일치하지 않습니다.");
}
const now = new Date();
const year = String(now.getFullYear());
const month = String(now.getMonth() + 1).padStart(2, "0");
const storageKey = `${year}/${month}/${crypto.randomUUID()}.${ext}`;
const fullPath = path.join(getUploadRoot(), storageKey);
await fs.mkdir(path.dirname(fullPath), { recursive: true });
await fs.writeFile(fullPath, buffer);
return {
storageKey,
originalName,
mimeType: mimeFromExtension(originalName),
size: buffer.length,
};
}
export function resolveStoredPath(storageKey: string) {
const root = getUploadRoot();
const fullPath = path.resolve(root, storageKey);
if (!fullPath.startsWith(`${root}${path.sep}`)) {
throw new Error("잘못된 파일 경로입니다.");
}
return fullPath;
}
export async function deleteStoredFile(storageKey: string) {
try {
await fs.unlink(resolveStoredPath(storageKey));
} catch {
// 파일이 이미 없어도 삭제는 성공으로 처리합니다.
}
}
+137
View File
@@ -0,0 +1,137 @@
import "server-only";
import type { Prisma } from "@prisma/client";
import { prisma } from "@/lib/db";
import { PAGE_SIZE } from "@/lib/constants";
type ListParams = {
type: "NOTICE" | "ARCHIVE";
page?: number;
query?: string;
category?: string;
pageSize?: number;
includeDrafts?: boolean;
};
export async function getPosts({
type,
page = 1,
query = "",
category = "",
pageSize = PAGE_SIZE,
includeDrafts = false,
}: ListParams) {
const safePage = Math.max(1, page);
const where: Prisma.PostWhereInput = {
type,
...(includeDrafts ? {} : { status: "PUBLISHED" }),
...(category ? { category } : {}),
...(query
? {
OR: [{ title: { contains: query } }, { content: { contains: query } }],
}
: {}),
};
const [total, posts] = await Promise.all([
prisma.post.count({ where }),
prisma.post.findMany({
where,
orderBy: [{ isPinned: "desc" }, { publishedAt: "desc" }, { id: "desc" }],
skip: (safePage - 1) * pageSize,
take: pageSize,
include: {
_count: { select: { attachments: true } },
},
}),
]);
return {
posts,
total,
page: safePage,
totalPages: Math.max(1, Math.ceil(total / pageSize)),
};
}
export async function getPost(id: number, type?: "NOTICE" | "ARCHIVE") {
if (!Number.isInteger(id) || id <= 0) return null;
return prisma.post.findFirst({
where: { id, ...(type ? { type } : {}) },
include: {
author: { select: { name: true } },
attachments: { orderBy: { id: "asc" } },
},
});
}
export async function getAdjacentPosts(post: { id: number; type: string; publishedAt: Date }) {
const [prev, next] = await Promise.all([
prisma.post.findFirst({
where: {
type: post.type,
status: "PUBLISHED",
OR: [
{ publishedAt: { lt: post.publishedAt } },
{ publishedAt: post.publishedAt, id: { lt: post.id } },
],
},
orderBy: [{ publishedAt: "desc" }, { id: "desc" }],
select: { id: true, title: true },
}),
prisma.post.findFirst({
where: {
type: post.type,
status: "PUBLISHED",
OR: [
{ publishedAt: { gt: post.publishedAt } },
{ publishedAt: post.publishedAt, id: { gt: post.id } },
],
},
orderBy: [{ publishedAt: "asc" }, { id: "asc" }],
select: { id: true, title: true },
}),
]);
return { prev, next };
}
export async function getLatestPosts(type: "NOTICE" | "ARCHIVE", take = 4) {
return prisma.post.findMany({
where: { type, status: "PUBLISHED" },
orderBy: [{ isPinned: "desc" }, { publishedAt: "desc" }],
take,
include: { _count: { select: { attachments: true } } },
});
}
export async function getCategories(type: "NOTICE" | "ARCHIVE") {
const rows = await prisma.post.findMany({
where: { type, status: "PUBLISHED", category: { not: null } },
distinct: ["category"],
select: { category: true },
orderBy: { category: "asc" },
});
return rows.map((row) => row.category).filter((value): value is string => Boolean(value));
}
export async function incrementViewCount(id: number) {
try {
await prisma.post.update({ where: { id }, data: { viewCount: { increment: 1 } } });
} catch {
// 조회수 증가 실패가 페이지 렌더링을 막지 않도록 합니다.
}
}
export async function getDashboardCounts() {
const [noticeCount, archiveCount, inquiryNew, inquiryTotal, postTotal] = await Promise.all([
prisma.post.count({ where: { type: "NOTICE" } }),
prisma.post.count({ where: { type: "ARCHIVE" } }),
prisma.inquiry.count({ where: { status: "NEW" } }),
prisma.inquiry.count(),
prisma.post.count(),
]);
return { noticeCount, archiveCount, inquiryNew, inquiryTotal, postTotal };
}
+46
View File
@@ -0,0 +1,46 @@
type Bucket = {
count: number;
resetAt: number;
};
const buckets = new Map<string, Bucket>();
export type RateLimitResult = {
ok: boolean;
retryAfterSeconds: number;
};
/**
* 단일 서버(OCI/VPS) 운영을 전제로 한 메모리 기반 제한입니다.
* 서버를 여러 대로 늘릴 경우 Redis/DB 기반으로 교체해야 합니다.
*/
export function rateLimit(key: string, limit: number, windowMs: number): RateLimitResult {
const now = Date.now();
const current = buckets.get(key);
if (!current || current.resetAt <= now) {
buckets.set(key, { count: 1, resetAt: now + windowMs });
return { ok: true, retryAfterSeconds: 0 };
}
if (current.count >= limit) {
return {
ok: false,
retryAfterSeconds: Math.max(1, Math.ceil((current.resetAt - now) / 1000)),
};
}
current.count += 1;
return { ok: true, retryAfterSeconds: 0 };
}
// 오래된 버킷이 무한히 쌓이지 않도록 가끔 정리합니다.
if (typeof setInterval !== "undefined") {
const timer = setInterval(() => {
const now = Date.now();
for (const [key, bucket] of buckets) {
if (bucket.resetAt <= now) buckets.delete(key);
}
}, 10 * 60 * 1000);
if (typeof timer === "object" && "unref" in timer) timer.unref();
}
+28
View File
@@ -0,0 +1,28 @@
import "server-only";
import { prisma } from "@/lib/db";
import { BLOG_URL, LEGACY_MAP_URL, SITE_DESCRIPTION, SITE_NAME, SITE_SHORT_NAME } from "@/lib/constants";
export const DEFAULT_SETTINGS = {
siteName: SITE_NAME,
shortName: SITE_SHORT_NAME,
description: SITE_DESCRIPTION,
contactEmail: "",
contactPhone: "",
address: "서울특별시 용산구 일대",
blogUrl: BLOG_URL,
mapUrl: LEGACY_MAP_URL,
footerText: "용산의 안전하고 깨끗한 거리 환경을 위해 주민과 함께합니다.",
};
export type SiteSettings = typeof DEFAULT_SETTINGS;
export async function getSettings(): Promise<SiteSettings> {
try {
const rows = await prisma.setting.findMany();
const values = Object.fromEntries(rows.map((row) => [row.key, row.value]));
return { ...DEFAULT_SETTINGS, ...values };
} catch {
return DEFAULT_SETTINGS;
}
}
+44
View File
@@ -0,0 +1,44 @@
import { z } from "zod";
export const loginSchema = z.object({
loginId: z.string().trim().min(2, "아이디를 입력해 주세요.").max(50),
password: z.string().min(4, "비밀번호를 입력해 주세요.").max(200),
});
export const postSchema = z.object({
type: z.enum(["NOTICE", "ARCHIVE"]),
category: z.string().trim().max(30).optional().default(""),
title: z.string().trim().min(2, "제목을 2자 이상 입력해 주세요.").max(200, "제목은 200자 이하로 입력해 주세요."),
content: z.string().trim().min(1, "내용을 입력해 주세요.").max(200_000),
isPinned: z.boolean().default(false),
status: z.enum(["PUBLISHED", "DRAFT"]).default("PUBLISHED"),
});
export const inquirySchema = z.object({
name: z.string().trim().min(2, "성함을 2자 이상 입력해 주세요.").max(50),
email: z.string().trim().email("올바른 이메일 주소를 입력해 주세요.").max(200),
phone: z.string().trim().max(30).optional().default(""),
title: z.string().trim().min(2, "제목을 2자 이상 입력해 주세요.").max(200),
content: z.string().trim().min(5, "내용을 5자 이상 입력해 주세요.").max(5000),
consent: z.boolean().refine((value) => value, "개인정보 수집·이용에 동의해 주세요."),
});
export const settingsSchema = z.object({
siteName: z.string().trim().min(2).max(100),
shortName: z.string().trim().min(1).max(30),
description: z.string().trim().max(300),
contactEmail: z.string().trim().max(200),
contactPhone: z.string().trim().max(50),
address: z.string().trim().max(200),
blogUrl: z.string().trim().url("올바른 URL을 입력해 주세요.").max(300),
mapUrl: z.string().trim().url("올바른 URL을 입력해 주세요.").max(300),
footerText: z.string().trim().max(300),
});
export function getString(formData: FormData, key: string) {
return String(formData.get(key) ?? "").trim();
}
export function getBoolean(formData: FormData, key: string) {
return formData.get(key) === "on" || formData.get(key) === "true" || formData.get(key) === "1";
}