Initial commit: 용산 공중케이블 주민 안전 협의회 홈페이지
- Next.js 16 App Router + TypeScript + Tailwind CSS 4 - Prisma/SQLite 기반 공지사항·자료실·관리자·문의/제보 - 네이버 블로그 RSS 최신 글 5개 노출 - OCI 운영 배포 스크립트 및 문서
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
node_modules
|
||||
.next
|
||||
.git
|
||||
.gitignore
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
storage/uploads/*
|
||||
!storage/uploads/.gitkeep
|
||||
data
|
||||
prisma/*.db
|
||||
prisma/*.db-journal
|
||||
npm-debug.log*
|
||||
README.md
|
||||
docs
|
||||
@@ -0,0 +1,18 @@
|
||||
# 데이터베이스 (개발: SQLite, 운영: MySQL 전환 가능)
|
||||
DATABASE_URL="file:./dev.db"
|
||||
|
||||
# 관리자 세션 서명 키 (32자 이상 권장)
|
||||
AUTH_SECRET="change-this-to-a-long-random-string"
|
||||
|
||||
# 사이트 공개 주소
|
||||
NEXT_PUBLIC_SITE_URL="http://localhost:3000"
|
||||
|
||||
# 최초 관리자 계정 (seed 실행 시 사용)
|
||||
ADMIN_LOGIN_ID="admin"
|
||||
ADMIN_INITIAL_PASSWORD="Yonggong1234!"
|
||||
|
||||
# 업로드 파일 저장 경로 (웹루트 밖 권장)
|
||||
UPLOAD_DIR="./storage/uploads"
|
||||
|
||||
# 2차 지도 통합 전까지 사용할 기존 지도 주소
|
||||
NEXT_PUBLIC_LEGACY_MAP_URL="https://saftyovhcable.kr/addMarker.html"
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# dependencies
|
||||
/node_modules
|
||||
|
||||
# next.js
|
||||
/.next
|
||||
/out
|
||||
next-env.d.ts
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# env
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# database
|
||||
/prisma/*.db
|
||||
/prisma/*.db-journal
|
||||
/prisma/migrations/*_dev.db
|
||||
|
||||
# docker volumes / backups
|
||||
/data
|
||||
/mysql-data
|
||||
/backups
|
||||
|
||||
# uploaded files
|
||||
/storage/uploads/*
|
||||
!/storage/uploads/.gitkeep
|
||||
|
||||
# logs
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
# editor / os
|
||||
.DS_Store
|
||||
*.pem
|
||||
*.tsbuildinfo
|
||||
|
||||
# deploy staging (deploy/publish.sh)
|
||||
/.deploy
|
||||
@@ -0,0 +1,9 @@
|
||||
<!-- BEGIN:nextjs-agent-rules -->
|
||||
|
||||
## This is NOT the Next.js you know
|
||||
|
||||
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
|
||||
|
||||
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
|
||||
|
||||
<!-- END:nextjs-agent-rules -->
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ---------- base ----------
|
||||
FROM node:22-bookworm-slim AS base
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends openssl ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& groupadd --system --gid 1001 nodejs \
|
||||
&& useradd --system --uid 1001 --gid nodejs --create-home nextjs
|
||||
|
||||
# ---------- dependencies ----------
|
||||
FROM base AS deps
|
||||
COPY package.json package-lock.json ./
|
||||
COPY prisma ./prisma
|
||||
RUN npm ci
|
||||
|
||||
# ---------- build ----------
|
||||
FROM base AS builder
|
||||
# 빌드 단계에서는 DB에 접속하지 않지만 Prisma가 env를 요구할 수 있어 더미 값을 둡니다.
|
||||
ENV DATABASE_URL="file:/tmp/build.db"
|
||||
ARG NEXT_PUBLIC_SITE_URL="https://saftyovhcable.kr"
|
||||
ARG NEXT_PUBLIC_LEGACY_MAP_URL="https://saftyovhcable.kr/addMarker.html"
|
||||
ENV NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL \
|
||||
NEXT_PUBLIC_LEGACY_MAP_URL=$NEXT_PUBLIC_LEGACY_MAP_URL
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
COPY . .
|
||||
RUN npx prisma generate && npm run build
|
||||
|
||||
# ---------- migration helper (일회성 실행용) ----------
|
||||
# docker compose run --rm migrate
|
||||
FROM builder AS migrator
|
||||
ENV NODE_ENV=production
|
||||
RUN mkdir -p /app/data /app/storage/uploads \
|
||||
&& chown -R nextjs:nodejs /app/data /app/storage
|
||||
USER nextjs
|
||||
CMD ["npx", "prisma", "migrate", "deploy"]
|
||||
|
||||
# ---------- runtime ----------
|
||||
FROM base AS runner
|
||||
ENV NODE_ENV=production \
|
||||
PORT=3000 \
|
||||
HOSTNAME=0.0.0.0
|
||||
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||
COPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma
|
||||
|
||||
RUN mkdir -p /app/storage/uploads /app/data \
|
||||
&& chown -R nextjs:nodejs /app/storage /app/data
|
||||
|
||||
USER nextjs
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["node", "server.js"]
|
||||
@@ -0,0 +1,206 @@
|
||||
# 용산 공중케이블 주민 안전 협의회 홈페이지
|
||||
|
||||
기존 `saftyovhcable.kr` 정적 홈페이지를 Next.js 기반으로 새로 만든 프로젝트입니다.
|
||||
1차 범위는 **사이트 리디자인 + 공지사항 + 자료실 + 관리자 + 문의·제보**이며,
|
||||
지도 통합·회원·후원·뉴스레터는 2차로 분리했습니다.
|
||||
|
||||
## 주요 기능
|
||||
|
||||
### 공개 페이지
|
||||
- `/` 홈: 주요 메시지, 정비 전/후 사진, 최신 공지·자료, 블로그 최신글 5개, 조사 지도·블로그 링크
|
||||
- `/about` 협의회 소개: 비전, 활동, 연혁, 조직도
|
||||
- `/news/notice` 공지사항 목록: 분류 필터, 검색, 페이지네이션
|
||||
- `/news/notice/[id]` 공지사항 상세: 마크다운 본문, 첨부파일, 이전/다음 글
|
||||
- `/archive` 자료실 목록
|
||||
- `/archive/[id]` 자료실 상세: 첨부파일 다운로드
|
||||
- `/contact` 문의·제보: 스팸 방지(허니팟 + IP rate limit), 개인정보 동의
|
||||
- `/privacy`, `/terms` 개인정보처리방침·이용약관
|
||||
- `/feed.xml` RSS, `/sitemap.xml`, `/robots.txt`
|
||||
|
||||
### 관리자 `/admin`
|
||||
- 아이디/비밀번호 로그인 (JWT 세션 쿠키, 8시간)
|
||||
- 대시보드: 게시글·문의 현황
|
||||
- 공지사항/자료실 CRUD: 마크다운 본문, 상단 고정, 임시저장, 첨부파일(최대 10개, 파일당 50MB·요청 전체 60MB)
|
||||
- 문의·제보 관리: 상태(접수/처리중/완료) 변경, 삭제
|
||||
- 사이트 설정: 사이트명, 연락처, 주소, 지도·블로그 URL, 푸터 문구
|
||||
- 감사 로그: 로그인, 게시글/첨부파일/문의/설정 변경 기록
|
||||
|
||||
## 기술 스택
|
||||
|
||||
| 구분 | 사용 기술 |
|
||||
| --- | --- |
|
||||
| 프레임워크 | Next.js 16 (App Router, Turbopack) |
|
||||
| 언어 | TypeScript 5.9 |
|
||||
| 스타일 | Tailwind CSS 4 |
|
||||
| DB/ORM | Prisma 6 + SQLite(개발) → MySQL 8(운영 권장) |
|
||||
| 인증 | `jose` JWT + `bcryptjs` (관리자 전용) |
|
||||
| 콘텐츠 | 마크다운 (`react-markdown` + `remark-gfm`) |
|
||||
| 파일 저장 | 서버 로컬 디스크 (`storage/uploads`, 웹루트 밖) |
|
||||
| 아이콘 | `lucide-react` |
|
||||
|
||||
## 로컬 실행
|
||||
|
||||
```bash
|
||||
# 1. 의존성 설치
|
||||
npm ci
|
||||
|
||||
# 2. 환경변수 준비
|
||||
cp .env.example .env
|
||||
# AUTH_SECRET 은 반드시 32자 이상 임의 문자열로 변경하세요.
|
||||
|
||||
# 3. DB 생성 + 샘플 데이터
|
||||
npm run db:migrate # 최초 1회 (마이그레이션 생성/적용)
|
||||
npm run db:seed # 관리자 계정 + 샘플 공지 3건 + 자료 3건
|
||||
|
||||
# 4. 개발 서버
|
||||
npm run dev # http://localhost:3000
|
||||
```
|
||||
|
||||
기본 관리자 계정은 `.env`의 `ADMIN_LOGIN_ID` / `ADMIN_INITIAL_PASSWORD` 값으로 생성됩니다.
|
||||
(`seed`는 계정이 이미 있으면 비밀번호를 덮어쓰지 않습니다.)
|
||||
|
||||
### 관리자 비밀번호 변경
|
||||
|
||||
```bash
|
||||
npm run admin:password -- admin '새로운비밀번호'
|
||||
```
|
||||
|
||||
### 자주 쓰는 명령
|
||||
|
||||
```bash
|
||||
npm run build # prisma generate + next build
|
||||
npm start # 프로덕션 서버 (build 후)
|
||||
npm run db:studio # Prisma Studio
|
||||
npm run typecheck # 타입 검사
|
||||
```
|
||||
|
||||
## 환경변수
|
||||
|
||||
| 변수 | 설명 | 예시 |
|
||||
| --- | --- | --- |
|
||||
| `DATABASE_URL` | DB 접속 문자열 | `file:./dev.db` |
|
||||
| `AUTH_SECRET` | 관리자 세션 서명 키 (32자 이상) | 임의 문자열 |
|
||||
| `NEXT_PUBLIC_SITE_URL` | 공개 사이트 주소 (SEO/OG/RSS) | `https://saftyovhcable.kr` |
|
||||
| `ADMIN_LOGIN_ID` | 최초 관리자 아이디 | `admin` |
|
||||
| `ADMIN_INITIAL_PASSWORD` | 최초 관리자 비밀번호 | `********` |
|
||||
| `UPLOAD_DIR` | 첨부파일 저장 경로 | `./storage/uploads` |
|
||||
| `NEXT_PUBLIC_LEGACY_MAP_URL` | 1차에서 연결할 기존 지도 주소 | `https://saftyovhcable.kr/addMarker.html` |
|
||||
|
||||
## 콘텐츠 관리 방법
|
||||
|
||||
1. `/admin` 로그인 → 공지사항/자료실 선택 → **작성**
|
||||
2. 본문은 **마크다운**으로 작성합니다.
|
||||
```markdown
|
||||
## 소제목
|
||||
|
||||
본문 내용입니다. **강조**, [링크](https://example.com)
|
||||
|
||||
- 목록 항목
|
||||
- 두 번째 항목
|
||||
|
||||

|
||||
```
|
||||
3. 첨부파일은 최대 10개, 파일당 50MB까지 업로드됩니다.
|
||||
지원 형식: pdf, hwp, hwpx, doc(x), xls(x), ppt(x), zip, jpg, jpeg, png, webp, gif, txt, csv
|
||||
4. **임시저장** 상태의 글은 공개 사이트에 노출되지 않습니다.
|
||||
5. 공지사항은 **상단 고정**을 설정할 수 있습니다.
|
||||
|
||||
## 파일 저장·백업
|
||||
|
||||
- 첨부파일은 `storage/uploads/YYYY/MM/<uuid>.<ext>`에 저장되며 웹루트에 직접 노출되지 않습니다.
|
||||
- 다운로드는 `/api/files/[id]`를 통해 스트리밍되고, 다운로드 횟수가 기록됩니다.
|
||||
- 백업 대상:
|
||||
- DB: `prisma/dev.db` (SQLite) 또는 MySQL 덤프
|
||||
- 업로드: `storage/uploads/`
|
||||
- 환경변수: `.env` / `.env.production`
|
||||
|
||||
## 배포
|
||||
|
||||
현재 운영 서버는 OCI VM(`saftyovhcable-www`, Ubuntu 24.04, 2 vCPU / 1GB RAM)이며,
|
||||
nginx → `127.0.0.1:3000`(systemd `yonggong.service`) 구조로 서비스합니다.
|
||||
서버 RAM이 1GB뿐이라 **서버에서 빌드하지 않고, 로컬에서 빌드한 standalone 산출물만 업로드**합니다.
|
||||
|
||||
```bash
|
||||
./deploy/publish.sh # 빌드 + 업로드 + 재시작 + 헬스 체크
|
||||
SKIP_BUILD=1 ./deploy/publish.sh # 이미 빌드된 산출물만 업로드
|
||||
```
|
||||
|
||||
배포 파일은 `deploy/`에 있습니다.
|
||||
|
||||
| 파일 | 용도 |
|
||||
| --- | --- |
|
||||
| `deploy/publish.sh` | 로컬 빌드 → 서버 업로드 → 재시작 |
|
||||
| `deploy/yonggong.service` | systemd 유닛 (`/etc/systemd/system/`) |
|
||||
| `deploy/nginx/saftyovhcable.kr.conf` | nginx 사이트 설정 (한글 도메인 포함) |
|
||||
| `deploy/nginx/yonggong-upstream.conf` | nginx upstream (`/etc/nginx/conf.d/`) |
|
||||
| `deploy/backup.sh` | 서버 일일 백업 (`/usr/local/sbin/yonggong-backup.sh`, cron 03:30) |
|
||||
|
||||
Docker 방식으로 배포하려면 아래를 사용합니다.
|
||||
|
||||
```bash
|
||||
cp .env.example .env.production # 값 채우기 (AUTH_SECRET, NEXT_PUBLIC_SITE_URL ...)
|
||||
docker compose build
|
||||
docker compose --profile tools run --rm migrate # DB 마이그레이션
|
||||
docker compose --profile tools run --rm migrate npx prisma db seed # 최초 1회
|
||||
docker compose up -d
|
||||
```
|
||||
|
||||
> 도메인이 `saftyovhcable.kr`이 아니면 `docker compose build --build-arg NEXT_PUBLIC_SITE_URL=https://내도메인`으로 빌드하세요.
|
||||
|
||||
자세한 OCI/VPS 배포, Nginx 리버스 프록시, HTTPS, systemd, 백업 방법은
|
||||
[`docs/deployment.md`](docs/deployment.md)를 참고하세요.
|
||||
|
||||
### 운영 DB를 MySQL 8로 전환
|
||||
|
||||
로컬은 SQLite로 개발하지만 운영에서는 MySQL 8을 권장합니다.
|
||||
전환 절차는 [`docs/mysql-migration.md`](docs/mysql-migration.md)를 참고하세요.
|
||||
|
||||
## 프로젝트 구조
|
||||
|
||||
```
|
||||
src/
|
||||
app/
|
||||
(site)/ 공개 사이트 (헤더·푸터 레이아웃)
|
||||
about/ contact/ news/notice/ archive/ privacy/ terms/
|
||||
admin/
|
||||
login/ 관리자 로그인
|
||||
(dashboard)/ 인증이 필요한 관리자 화면
|
||||
api/
|
||||
files/[id]/ 첨부파일 스트리밍/다운로드
|
||||
admin/upload/ 관리자 파일 업로드 API
|
||||
health/ 헬스체크
|
||||
feed.xml/ RSS
|
||||
sitemap.ts robots.ts
|
||||
actions/ 서버 액션 (auth/posts/inquiries/settings)
|
||||
components/
|
||||
site/ 공개 UI
|
||||
admin/ 관리자 UI
|
||||
lib/ DB, 인증, 파일, 게시글, 설정, 검증, rate limit, 감사 로그
|
||||
prisma/ schema, migrations, seed
|
||||
storage/uploads/ 첨부파일 저장소 (git 제외)
|
||||
scripts/ 운영 스크립트
|
||||
docs/ 배포/마이그레이션 문서
|
||||
```
|
||||
|
||||
## 보안 메모
|
||||
|
||||
- 관리자 화면은 서버 레이아웃에서 `requireAdmin()`으로 보호합니다. (`/admin/*`, API 포함)
|
||||
- 비밀번호는 bcrypt(12 rounds)로 저장합니다.
|
||||
- 로그인 실패는 IP당 10분에 6회, 문의 접수는 IP당 1시간에 5회로 제한합니다.
|
||||
(단일 서버 메모리 기반이므로 서버를 여러 대로 늘릴 경우 Redis/DB 기반으로 교체 필요)
|
||||
- 업로드 파일은 확장자 + 시그니처 검사를 하고, 저장 경로를 웹루트 밖에 둡니다.
|
||||
- 응답에 `X-Content-Type-Options`, `X-Frame-Options`, `Referrer-Policy` 등을 설정했습니다.
|
||||
- 운영 배포 시 반드시 `AUTH_SECRET`을 새 값으로 교체하고 기본 비밀번호를 변경하세요.
|
||||
|
||||
## 2차 범위 (예정)
|
||||
|
||||
- 기존 `addMarker.html` 지도(약 1,795개 조사 지점)를 Next.js로 통합
|
||||
- 네이버 블로그 본문·이미지 전체 연동 (현재는 RSS로 최신 글 5개 제목만 노출)
|
||||
- 회원 가입/로그인, 후원, 뉴스레터
|
||||
- 관리자 2단계 인증(TOTP), 권한 분리(EDITOR)
|
||||
- 이미지 최적화/썸네일, S3 등 오브젝트 스토리지 이전
|
||||
|
||||
## 라이선스 / 저작권
|
||||
|
||||
- 사이트 콘텐츠: 용산 공중케이블 주민 안전 협의회
|
||||
- 기존 사이트에서 이관한 사진: 협의회 제공 자료
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# 운영 서버(/srv/yonggong)에서 실행하는 백업 스크립트.
|
||||
# DB는 SQLite 백업 API로, 첨부파일은 tar로 보관하고 14일이 지난 백업은 지웁니다.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT=/srv/yonggong
|
||||
STAMP=$(date +%Y%m%d-%H%M%S)
|
||||
DEST="$ROOT/backups"
|
||||
|
||||
mkdir -p "$DEST"
|
||||
|
||||
# 서비스 중에도 안전한 SQLite 온라인 백업
|
||||
python3 - "$ROOT/data/prod.db" "$DEST/db-$STAMP.db" <<'PY'
|
||||
import sqlite3, sys
|
||||
src, dst = sys.argv[1], sys.argv[2]
|
||||
with sqlite3.connect(src) as s, sqlite3.connect(dst) as d:
|
||||
s.backup(d)
|
||||
PY
|
||||
|
||||
tar -czf "$DEST/uploads-$STAMP.tar.gz" -C "$ROOT/storage" uploads
|
||||
|
||||
find "$DEST" -type f -mtime +14 -delete
|
||||
echo "[$(date -Is)] backup ok: db-$STAMP.db, uploads-$STAMP.tar.gz"
|
||||
@@ -0,0 +1,88 @@
|
||||
# saftyovhcable.kr — Next.js(yonggong) 리버스 프록시
|
||||
# 레거시 정적 자산(/addMarker.html, /res/, /blogload.js)은 /var/www/html 에서 계속 서비스합니다.
|
||||
# /etc/nginx/sites-available/saftyovhcable.kr
|
||||
# 한글 도메인(용공협.kr)은 퓨니코드로 같은 server 블록에서 함께 처리합니다.
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name saftyovhcable.kr xn--ob0bs83a9mfulcsua52c2xubym.xn--3e0b707e;
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/www/html;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://saftyovhcable.kr$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
server_name saftyovhcable.kr xn--ob0bs83a9mfulcsua52c2xubym.xn--3e0b707e;
|
||||
|
||||
root /var/www/html;
|
||||
index index.html;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/saftyovhcable.kr/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/saftyovhcable.kr/privkey.pem;
|
||||
include /etc/letsencrypt/options-ssl-nginx.conf;
|
||||
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
|
||||
|
||||
client_max_body_size 60m;
|
||||
client_body_timeout 120s;
|
||||
|
||||
# HTTPS 전용 (인증서 자동 갱신 검증 완료)
|
||||
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||
|
||||
# --- 레거시 지도/정적 자산 ---
|
||||
location = /addMarker.html {
|
||||
try_files $uri =404;
|
||||
}
|
||||
location ^~ /res/ {
|
||||
try_files $uri =404;
|
||||
expires 7d;
|
||||
access_log off;
|
||||
}
|
||||
location = /blogload.js {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location ^~ /.well-known/acme-challenge/ {
|
||||
root /var/www/html;
|
||||
}
|
||||
|
||||
# 짧은 주소 / 옛 정적 페이지
|
||||
location = /index.html { return 301 /; }
|
||||
location = /index.htm { return 301 /; }
|
||||
location = /news { return 301 /news/notice; }
|
||||
location = /board { return 301 /news/notice; }
|
||||
|
||||
# --- Next.js 정적 자산 (캐시 헤더는 앱이 직접 설정) ---
|
||||
location /_next/static/ {
|
||||
proxy_pass http://yonggong_app;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
access_log off;
|
||||
}
|
||||
|
||||
# --- 애플리케이션 ---
|
||||
location / {
|
||||
proxy_pass http://yonggong_app;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Host $host;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "";
|
||||
proxy_read_timeout 120s;
|
||||
proxy_send_timeout 120s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# saftyovhcable.kr Next.js 앱 업스트림 (systemd: yonggong.service)
|
||||
# /etc/nginx/conf.d/yonggong-upstream.conf
|
||||
upstream yonggong_app {
|
||||
server 127.0.0.1:3000;
|
||||
keepalive 32;
|
||||
}
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env bash
|
||||
# 로컬 PC에서 실행: 빌드한 산출물만 운영 서버로 업로드합니다.
|
||||
# (서버 RAM이 1GB뿐이므로 서버에서 next build를 돌리지 않습니다.)
|
||||
#
|
||||
# ./deploy/publish.sh # 빌드 + 업로드 + 재시작
|
||||
# SKIP_BUILD=1 ./deploy/publish.sh # 이미 빌드된 산출물만 업로드
|
||||
#
|
||||
# 환경변수로 덮어쓸 수 있습니다: HOST, SSH_KEY, REMOTE_STAGE
|
||||
set -euo pipefail
|
||||
|
||||
HOST="${HOST:-ubuntu@134.185.113.7}"
|
||||
SSH_KEY="${SSH_KEY:-$HOME/Workspace/YSOVHCable_Project/Server/SSH/oci_web/ssh-key-2025-01-10-2.key}"
|
||||
REMOTE_STAGE="${REMOTE_STAGE:-/home/ubuntu/yonggong-deploy}"
|
||||
APP_DIR="/srv/yonggong/app"
|
||||
SITE_URL="${SITE_URL:-https://saftyovhcable.kr}"
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
cd "$ROOT"
|
||||
|
||||
log() { printf '\n== %s\n' "$*"; }
|
||||
|
||||
log "1/6 빌드"
|
||||
if [ "${SKIP_BUILD:-0}" != "1" ]; then
|
||||
# NEXT_PUBLIC_* 값은 빌드 시 임베드되므로, 로컬 .env 값이 아니라 운영 값을 강제합니다.
|
||||
export NEXT_PUBLIC_SITE_URL="${NEXT_PUBLIC_SITE_URL:-https://saftyovhcable.kr}"
|
||||
export NEXT_PUBLIC_LEGACY_MAP_URL="${NEXT_PUBLIC_LEGACY_MAP_URL:-https://saftyovhcable.kr/addMarker.html}"
|
||||
echo "NEXT_PUBLIC_SITE_URL=$NEXT_PUBLIC_SITE_URL"
|
||||
npm run build
|
||||
fi
|
||||
test -f .next/standalone/server.js || { echo "standalone 산출물이 없습니다. npm run build 를 확인하세요."; exit 1; }
|
||||
|
||||
log "2/6 산출물 스테이징"
|
||||
STAGE="$ROOT/.deploy/stage"
|
||||
rm -rf "$STAGE"
|
||||
mkdir -p "$STAGE"
|
||||
cp -a .next/standalone/. "$STAGE/"
|
||||
mkdir -p "$STAGE/.next"
|
||||
cp -a .next/static "$STAGE/.next/static"
|
||||
cp -a public "$STAGE/public"
|
||||
rm -f "$STAGE/.env" "$STAGE"/.env.* # 환경변수는 서버의 /srv/yonggong/.env.production 사용
|
||||
du -sh "$STAGE"
|
||||
|
||||
SSH_OPTS=(-i "$SSH_KEY" -o BatchMode=yes -o StrictHostKeyChecking=accept-new)
|
||||
|
||||
log "3/6 업로드 ($HOST:$REMOTE_STAGE)"
|
||||
ssh "${SSH_OPTS[@]}" "$HOST" "mkdir -p '$REMOTE_STAGE' && rm -rf '$REMOTE_STAGE/app'"
|
||||
rsync -az --delete -e "ssh ${SSH_OPTS[*]}" "$STAGE/" "$HOST:$REMOTE_STAGE/app/"
|
||||
|
||||
log "4/6 서버 반영 (데이터/첨부파일은 보존)"
|
||||
ssh "${SSH_OPTS[@]}" "$HOST" "bash -s" <<EOF
|
||||
set -euo pipefail
|
||||
sudo -n rm -rf '$APP_DIR'
|
||||
sudo -n mkdir -p '$APP_DIR'
|
||||
sudo -n cp -a '$REMOTE_STAGE/app/.' '$APP_DIR/'
|
||||
sudo -n chown -R yonggong:yonggong '$APP_DIR'
|
||||
EOF
|
||||
|
||||
log "5/6 서비스 재시작"
|
||||
ssh "${SSH_OPTS[@]}" "$HOST" "sudo -n systemctl restart yonggong && sleep 3 && sudo -n systemctl is-active yonggong"
|
||||
|
||||
log "6/6 상태 확인"
|
||||
ssh "${SSH_OPTS[@]}" "$HOST" "curl -fsS -m 10 http://127.0.0.1:3000/api/health"
|
||||
printf '\n'
|
||||
curl -fsS -m 15 -o /dev/null -w "site: %{http_code}\n" "$SITE_URL/"
|
||||
printf '배포 완료: %s\n' "$SITE_URL"
|
||||
@@ -0,0 +1,32 @@
|
||||
[Unit]
|
||||
Description=Yonggong (saftyovhcable.kr) Next.js site
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=yonggong
|
||||
Group=yonggong
|
||||
WorkingDirectory=/srv/yonggong/app
|
||||
EnvironmentFile=/srv/yonggong/.env.production
|
||||
Environment=NODE_ENV=production
|
||||
Environment=HOSTNAME=127.0.0.1
|
||||
Environment=PORT=3000
|
||||
Environment=NEXT_TELEMETRY_DISABLED=1
|
||||
ExecStart=/usr/bin/node server.js
|
||||
Restart=always
|
||||
RestartSec=3
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=yonggong
|
||||
|
||||
# 보안 강화: 앱이 쓸 수 있는 경로만 열어 둡니다.
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=full
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/srv/yonggong/data /srv/yonggong/storage
|
||||
UMask=0027
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,38 @@
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
target: runner
|
||||
image: yonggong-web:latest
|
||||
env_file:
|
||||
- .env.production
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
DATABASE_URL: file:/app/data/prod.db
|
||||
UPLOAD_DIR: /app/storage/uploads
|
||||
PORT: "3000"
|
||||
HOSTNAME: 0.0.0.0
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- ./storage:/app/storage
|
||||
restart: unless-stopped
|
||||
|
||||
# 마이그레이션/시드 전용 일회성 컨테이너
|
||||
# docker compose --profile tools run --rm migrate
|
||||
# docker compose --profile tools run --rm migrate npx prisma db seed
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
target: migrator
|
||||
image: yonggong-web:migrator
|
||||
profiles: ["tools"]
|
||||
env_file:
|
||||
- .env.production
|
||||
environment:
|
||||
DATABASE_URL: file:/app/data/prod.db
|
||||
UPLOAD_DIR: /app/storage/uploads
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- ./storage:/app/storage
|
||||
@@ -0,0 +1,352 @@
|
||||
# 배포 가이드 (OCI VM / VPS)
|
||||
|
||||
## 0. 현재 운영 구성 (2026-10 기준)
|
||||
|
||||
`saftyovhcable.kr`은 아래 구성으로 **이미 운영 중**입니다. 재배포/이전 시 참고하세요.
|
||||
|
||||
| 항목 | 값 |
|
||||
| --- | --- |
|
||||
| 서버 | OCI VM `saftyovhcable-www` · `134.185.113.7` · Ubuntu 24.04.4 LTS · 2 vCPU / RAM 1GB |
|
||||
| 접속 | `ssh -i <oci key> ubuntu@134.185.113.7` (sudo 가능) |
|
||||
| 앱 경로 | `/srv/yonggong/app` (standalone 산출물, `yonggong:yonggong`) |
|
||||
| 데이터 | `/srv/yonggong/data/prod.db` (SQLite, 640) |
|
||||
| 첨부파일 | `/srv/yonggong/storage/uploads` |
|
||||
| 환경변수 | `/srv/yonggong/.env.production` (600, root/서비스 계정만) |
|
||||
| 실행 | systemd `yonggong.service` → `/usr/bin/node server.js` · `127.0.0.1:3000` |
|
||||
| 웹서버 | nginx 1.24 + certbot(nginx 인증서) · `/var/www/html` 레거시 자산 유지 |
|
||||
| 백업 | `/usr/local/sbin/yonggong-backup.sh` + `/etc/cron.d/yonggong-backup` (매일 03:30, 14일 보관) |
|
||||
| 백업 위치 | `/srv/yonggong/backups` |
|
||||
|
||||
핵심 원칙:
|
||||
|
||||
- **서버에서 빌드하지 않습니다.** RAM 1GB라 Turbopack 빌드가 OOM 위험 → 로컬에서 빌드 후 `deploy/publish.sh`로 산출물만 업로드합니다.
|
||||
- 데이터(`data/`, `storage/`)는 앱 디렉터리와 분리되어 있어 재배포해도 보존됩니다.
|
||||
- 레거시 정적 자산(`/addMarker.html`, `/res/`, `/blogload.js`)은 계속 `/var/www/html`에서 nginx가 직접 서비스합니다.
|
||||
- 한글 도메인(`용공협.kr`)은 퓨니코드로 같은 nginx `server` 블록에서 처리합니다.
|
||||
|
||||
### 재배포
|
||||
|
||||
```bash
|
||||
./deploy/publish.sh # 로컬 빌드 → 업로드 → 재시작 → 헬스 체크
|
||||
SKIP_BUILD=1 ./deploy/publish.sh # 산출물만 다시 올릴 때
|
||||
```
|
||||
|
||||
### 상태 확인
|
||||
|
||||
```bash
|
||||
ssh ubuntu@134.185.113.7
|
||||
sudo systemctl status yonggong --no-pager
|
||||
sudo journalctl -u yonggong -n 50 --no-pager
|
||||
curl -s http://127.0.0.1:3000/api/health
|
||||
sudo nginx -t
|
||||
```
|
||||
|
||||
### 블로그 최신글
|
||||
|
||||
홈 "협의회 소식"은 네이버 블로그 RSS(`https://rss.blog.naver.com/safetyovhcable.xml`)에서 최신 글 5개 제목을 가져옵니다.
|
||||
|
||||
- Next.js fetch 캐시로 30분간 보관합니다.
|
||||
- RSS 응답이 실패해도 블록만 숨기고 나머지 홈은 정상 렌더링합니다.
|
||||
- RSS 주소·표시 개수는 `src/lib/blog.ts`에서 조정합니다.
|
||||
|
||||
### 데이터 백업/복구
|
||||
|
||||
```bash
|
||||
sudo /usr/local/sbin/yonggong-backup.sh # 즉시 백업
|
||||
sudo ls -la /srv/yonggong/backups # db-*.db, uploads-*.tar.gz
|
||||
# 복구: 서비스 정지 → db 복원 → 첨부 복원 → 서비스 시작
|
||||
sudo systemctl stop yonggong
|
||||
sudo cp /srv/yonggong/backups/db-YYYYmmdd-HHMMSS.db /srv/yonggong/data/prod.db
|
||||
sudo chown yonggong:yonggong /srv/yonggong/data/prod.db && sudo chmod 640 /srv/yonggong/data/prod.db
|
||||
sudo tar -xzf /srv/yonggong/backups/uploads-YYYYmmdd-HHMMSS.tar.gz -C /srv/yonggong/storage
|
||||
sudo systemctl start yonggong
|
||||
```
|
||||
|
||||
> 운영 DB를 MySQL 8로 옮길 경우에는 `mysqldump` 기반 백업으로 교체하세요.
|
||||
|
||||
---
|
||||
|
||||
## A. Docker 배포 (OCI VM 기준)
|
||||
|
||||
> 현재 운영 서버에는 Docker를 설치하지 않았습니다. 다른 서버로 이전하거나 Docker 기반 운영을 원할 때 사용하세요.
|
||||
|
||||
|
||||
### 1. 서버 준비
|
||||
|
||||
- Ubuntu 22.04/24.04, 최소 2 vCPU / 2GB RAM / 40GB 디스크
|
||||
- 보안 그룹(OCI Security List)에서 22, 80, 443 포트 허용
|
||||
- 도메인 A 레코드를 서버 공인 IP로 설정
|
||||
|
||||
```bash
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y ca-certificates curl git
|
||||
# Docker 공식 설치 스크립트
|
||||
curl -fsSL https://get.docker.com | sudo sh
|
||||
sudo usermod -aG docker "$USER"
|
||||
# 재로그인 후 확인
|
||||
docker --version && docker compose version
|
||||
```
|
||||
|
||||
### 2. 코드 업로드
|
||||
|
||||
```bash
|
||||
sudo mkdir -p /srv/yonggong && sudo chown "$USER":"$USER" /srv/yonggong
|
||||
# git 사용 시
|
||||
git clone <저장소 URL> /srv/yonggong
|
||||
# 또는 로컬에서 rsync
|
||||
# rsync -av --exclude node_modules --exclude .next ./ user@server:/srv/yonggong/
|
||||
```
|
||||
|
||||
### 3. 환경변수
|
||||
|
||||
```bash
|
||||
cd /srv/yonggong
|
||||
cp .env.example .env.production
|
||||
```
|
||||
|
||||
`.env.production` 예시:
|
||||
|
||||
```dotenv
|
||||
DATABASE_URL="file:/app/data/prod.db"
|
||||
AUTH_SECRET="<openssl rand -base64 48 로 생성한 값>"
|
||||
NEXT_PUBLIC_SITE_URL="https://saftyovhcable.kr"
|
||||
ADMIN_LOGIN_ID="admin"
|
||||
ADMIN_INITIAL_PASSWORD="<최초 로그인 후 변경할 강한 비밀번호>"
|
||||
UPLOAD_DIR="/app/storage/uploads"
|
||||
NEXT_PUBLIC_LEGACY_MAP_URL="https://saftyovhcable.kr/addMarker.html"
|
||||
```
|
||||
|
||||
```bash
|
||||
openssl rand -base64 48 # AUTH_SECRET 생성
|
||||
mkdir -p data storage/uploads
|
||||
# 컨테이너는 UID 1001(nextjs)로 실행되므로 데이터 폴더 소유권을 맞춰 줍니다.
|
||||
sudo chown -R 1001:1001 data storage
|
||||
```
|
||||
|
||||
### 4. 빌드 · 마이그레이션 · 실행
|
||||
|
||||
```bash
|
||||
docker compose build
|
||||
docker compose --profile tools run --rm migrate # DB 마이그레이션
|
||||
docker compose --profile tools run --rm migrate npx prisma db seed # 최초 1회 샘플/관리자 생성
|
||||
docker compose up -d
|
||||
docker compose logs -f app
|
||||
```
|
||||
|
||||
> 도메인이 `saftyovhcable.kr`이 아니라면 빌드할 때 주소를 넘겨 주세요.
|
||||
> `docker compose build --build-arg NEXT_PUBLIC_SITE_URL=https://example.com`
|
||||
> (`NEXT_PUBLIC_*` 값은 빌드 시점에 일부 코드에 포함되므로, 도메인 변경 후에는 재빌드가 필요합니다.)
|
||||
|
||||
확인:
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:3000/api/health
|
||||
```
|
||||
|
||||
### 5. Nginx 리버스 프록시 + HTTPS
|
||||
|
||||
```bash
|
||||
sudo apt-get install -y nginx certbot python3-certbot-nginx
|
||||
```
|
||||
|
||||
`/etc/nginx/sites-available/yonggong`:
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 80;
|
||||
server_name saftyovhcable.kr www.saftyovhcable.kr;
|
||||
|
||||
client_max_body_size 60m;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_read_timeout 120s;
|
||||
proxy_send_timeout 120s;
|
||||
}
|
||||
|
||||
# 정적 자산은 Next가 캐시 헤더를 제공하므로 그대로 통과
|
||||
location /_next/static/ {
|
||||
proxy_pass http://127.0.0.1:3000;
|
||||
proxy_cache_valid 200 30d;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```bash
|
||||
sudo ln -s /etc/nginx/sites-available/yonggong /etc/nginx/sites-enabled/yonggong
|
||||
sudo nginx -t && sudo systemctl reload nginx
|
||||
sudo certbot --nginx -d saftyovhcable.kr -d www.saftyovhcable.kr
|
||||
```
|
||||
|
||||
> HTTPS 적용 후 `.env.production`의 `NEXT_PUBLIC_SITE_URL`이 `https://...`인지 확인하고 재빌드하세요.
|
||||
> (`NEXT_PUBLIC_*` 값은 빌드 시 임베드됩니다.)
|
||||
|
||||
### 6. 업데이트 배포
|
||||
|
||||
```bash
|
||||
cd /srv/yonggong
|
||||
git pull # 또는 새 파일 업로드
|
||||
docker compose build
|
||||
docker compose --profile tools run --rm migrate
|
||||
docker compose up -d
|
||||
docker image prune -f
|
||||
```
|
||||
|
||||
### 7. 백업
|
||||
|
||||
`/srv/yonggong/backup.sh`:
|
||||
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
cd /srv/yonggong
|
||||
STAMP=$(date +%Y%m%d-%H%M%S)
|
||||
mkdir -p backups
|
||||
|
||||
# SQLite 백업 (서비스 중단 없이 안전하게)
|
||||
docker compose exec -T app sh -c 'cp /app/data/prod.db /app/data/backup.tmp'
|
||||
cp data/backup.tmp "backups/db-$STAMP.db"
|
||||
rm -f data/backup.tmp
|
||||
|
||||
# 첨부파일 백업
|
||||
tar -czf "backups/uploads-$STAMP.tar.gz" storage/uploads
|
||||
|
||||
# 14일 지난 백업 삭제
|
||||
find backups -type f -mtime +14 -delete
|
||||
```
|
||||
|
||||
```bash
|
||||
chmod +x backup.sh
|
||||
crontab -e
|
||||
# 매일 03:30
|
||||
30 3 * * * /srv/yonggong/backup.sh >> /srv/yonggong/backup.log 2>&1
|
||||
```
|
||||
|
||||
> 운영 DB를 MySQL로 전환한 경우에는 `mysqldump`로 백업하세요.
|
||||
|
||||
---
|
||||
|
||||
## B. Node.js 직접 실행 (현재 운영 방식)
|
||||
|
||||
서버에는 **Node.js 22 LTS만** 설치하고, 빌드는 로컬에서 합니다.
|
||||
|
||||
### 1. 서버 최초 준비 (1회)
|
||||
|
||||
```bash
|
||||
# Node.js 22
|
||||
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
|
||||
sudo apt-get install -y nodejs
|
||||
|
||||
# 전용 서비스 계정 + 디렉터리
|
||||
sudo useradd --system --home /srv/yonggong --shell /usr/sbin/nologin yonggong
|
||||
sudo mkdir -p /srv/yonggong/{app,data,storage/uploads,backups}
|
||||
sudo chown -R yonggong:yonggong /srv/yonggong
|
||||
sudo chmod 750 /srv/yonggong
|
||||
```
|
||||
|
||||
### 2. 환경변수
|
||||
|
||||
`/srv/yonggong/.env.production` (반드시 `600`, 소유자 `yonggong`):
|
||||
|
||||
```dotenv
|
||||
DATABASE_URL="file:/srv/yonggong/data/prod.db"
|
||||
AUTH_SECRET="<openssl rand -base64 48>"
|
||||
NEXT_PUBLIC_SITE_URL="https://saftyovhcable.kr"
|
||||
UPLOAD_DIR="/srv/yonggong/storage/uploads"
|
||||
NEXT_PUBLIC_LEGACY_MAP_URL="https://saftyovhcable.kr/addMarker.html"
|
||||
```
|
||||
|
||||
> `NEXT_PUBLIC_*` 값은 **빌드 시점에 임베드**됩니다. 도메인을 바꾸면 로컬에서 다시 빌드해 배포해야 합니다.
|
||||
|
||||
### 3. DB 준비
|
||||
|
||||
```bash
|
||||
# 로컬에서 만든 DB를 올리는 경우 (권장: 서버에서 마이그레이션/시드 불필요)
|
||||
rsync -az prisma/dev.db ubuntu@134.185.113.7:/home/ubuntu/yonggong-deploy/prod.db
|
||||
# 서버에서
|
||||
sudo install -o yonggong -g yonggong -m 640 /home/ubuntu/yonggong-deploy/prod.db /srv/yonggong/data/prod.db
|
||||
```
|
||||
|
||||
스키마를 변경했다면 로컬에서 `npm run db:deploy`로 마이그레이션을 적용한 DB를 올리거나,
|
||||
서버에서 `npx prisma migrate deploy`를 실행합니다(서버에 `node_modules`가 있을 때).
|
||||
|
||||
### 4. systemd 유닛
|
||||
|
||||
`deploy/yonggong.service`를 그대로 사용합니다.
|
||||
|
||||
```bash
|
||||
sudo cp deploy/yonggong.service /etc/systemd/system/yonggong.service
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now yonggong
|
||||
sudo journalctl -u yonggong -f
|
||||
```
|
||||
|
||||
유닛은 `ProtectSystem=full`, `ProtectHome=true`, `ReadWritePaths=/srv/yonggong/{data,storage}`로
|
||||
앱이 쓸 수 있는 경로를 최소화합니다.
|
||||
|
||||
### 5. 산출물 배포
|
||||
|
||||
```bash
|
||||
./deploy/publish.sh
|
||||
```
|
||||
|
||||
`publish.sh`가 하는 일:
|
||||
|
||||
1. `npm run build` (standalone)
|
||||
2. `.next/standalone` + `.next/static` + `public` 스테이징
|
||||
3. `/home/ubuntu/yonggong-deploy`로 rsync
|
||||
4. `sudo rm -rf /srv/yonggong/app` 후 새 산출물 복사, `yonggong` 소유권 부여
|
||||
5. `systemctl restart yonggong` + `/api/health` 확인
|
||||
|
||||
> 데이터(`data/`, `storage/`)와 `.env.production`은 앱 디렉터리 밖에 있어 재배포해도 그대로 유지됩니다.
|
||||
|
||||
### 6. Nginx
|
||||
|
||||
`/etc/nginx/conf.d/yonggong-upstream.conf` ← `deploy/nginx/yonggong-upstream.conf`
|
||||
`/etc/nginx/sites-available/saftyovhcable.kr` ← `deploy/nginx/saftyovhcable.kr.conf`
|
||||
|
||||
```bash
|
||||
sudo ln -sf /etc/nginx/sites-available/saftyovhcable.kr /etc/nginx/sites-enabled/saftyovhcable.kr
|
||||
sudo nginx -t && sudo systemctl reload nginx
|
||||
```
|
||||
|
||||
포인트:
|
||||
|
||||
- `client_max_body_size 60m` — 첨부 10개 × 50MB 업로드를 고려한 값(앱 `bodySizeLimit`과 동일)
|
||||
- `location ^~ /res/`, `= /addMarker.html`, `= /blogload.js` — 레거시 정적 자산은 `/var/www/html`에서 직접 서비스
|
||||
- `/.well-known/acme-challenge/` — certbot(nginx 인증서) 갱신용 webroot
|
||||
- `/_next/static/` — 1년 immutable 캐시
|
||||
|
||||
인증서는 `certbot --nginx`로 발급되어 있으며 `certbot renew --dry-run`으로 갱신을 검증할 수 있습니다.
|
||||
한글 도메인(`xn--ob0bs83a9mfulcsua52c2xubym.xn--3e0b707e`)은 같은 서버 블록의 `server_name`에 함께 등록되어 있습니다.
|
||||
|
||||
## C. 관리형 호스팅 사용 시 주의
|
||||
|
||||
- 첨부파일이 서버 로컬 디스크에 저장되므로, 서버리스/임시 파일시스템 환경에서는 파일이 사라집니다.
|
||||
→ S3, Cloudflare R2, Supabase Storage 등으로 `src/lib/files.ts`를 교체해야 합니다.
|
||||
- SQLite도 영구 디스크가 필요합니다. 운영에서는 MySQL/PostgreSQL을 권장합니다.
|
||||
|
||||
---
|
||||
|
||||
## 배포 전 체크리스트
|
||||
|
||||
- [ ] `AUTH_SECRET`을 새 임의 값으로 설정
|
||||
- [ ] 관리자 기본 비밀번호 변경 (`npm run admin:password -- admin '...'`)
|
||||
- [ ] `NEXT_PUBLIC_SITE_URL`을 실제 도메인(https)으로 설정 후 재빌드
|
||||
- [ ] `.env*` 파일이 저장소에 커밋되지 않았는지 확인
|
||||
- [ ] `storage/`, `data/` 볼륨이 영구 디스크에 마운트되어 있는지 확인
|
||||
- [ ] HTTPS 인증서 발급 및 자동 갱신(`certbot renew --dry-run`)
|
||||
- [ ] 백업 크론 등록 및 복구 테스트
|
||||
- [ ] `/api/health` 모니터링 등록
|
||||
- [ ] 기존 `addMarker.html` 지도 파일이 새 서버에서도 접근 가능한지 확인
|
||||
- [ ] 레거시 자산(`/res/`, `/blogload.js`) 응답 확인
|
||||
- [ ] 모바일에서 가로 스크롤이 없는지 확인
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
# 운영 DB를 MySQL 8로 전환하기
|
||||
|
||||
이 프로젝트는 개발 편의를 위해 **SQLite**로 시작하지만, 운영에서는 **MySQL 8**을 권장합니다.
|
||||
(SQLite도 단일 서버·소규모 트래픽에서는 충분히 안정적입니다. 백업만 제대로 하면 됩니다.)
|
||||
|
||||
> ⚠️ Prisma의 `provider`를 바꾸면 기존 SQLite 마이그레이션 파일을 그대로 사용할 수 없습니다.
|
||||
> 운영 오픈 전, 데이터가 적을 때 전환하는 것을 권장합니다.
|
||||
|
||||
---
|
||||
|
||||
## 1. MySQL 준비
|
||||
|
||||
Docker를 쓰는 경우 `docker-compose.yml`에 아래 서비스를 추가합니다.
|
||||
|
||||
```yaml
|
||||
services:
|
||||
db:
|
||||
image: mysql:8.4
|
||||
command: --character-set-server=utf8mb4 --collation-server=utf8mb4_0900_ai_ci
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: "<root 비밀번호>"
|
||||
MYSQL_DATABASE: yonggong
|
||||
MYSQL_USER: yonggong
|
||||
MYSQL_PASSWORD: "<앱 비밀번호>"
|
||||
volumes:
|
||||
- ./mysql-data:/var/lib/mysql
|
||||
restart: unless-stopped
|
||||
```
|
||||
|
||||
앱의 `DATABASE_URL`:
|
||||
|
||||
```dotenv
|
||||
DATABASE_URL="mysql://yonggong:<앱 비밀번호>@db:3306/yonggong?connection_limit=10&pool_timeout=20"
|
||||
```
|
||||
|
||||
> 호스트에서 직접 MySQL을 설치한 경우 `@127.0.0.1:3306`을 사용합니다.
|
||||
> `utf8mb4` 문자셋이어야 이모지·한글 확장 문자가 깨지지 않습니다.
|
||||
|
||||
## 2. Prisma 스키마 변경
|
||||
|
||||
`prisma/schema.prisma`:
|
||||
|
||||
```prisma
|
||||
datasource db {
|
||||
provider = "mysql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
```
|
||||
|
||||
MySQL에서는 `String`이 기본 `VARCHAR(191)`로 매핑됩니다. 본문·제목은 충분한 길이를 명시하는 것이 안전합니다.
|
||||
|
||||
```prisma
|
||||
model Post {
|
||||
// ...
|
||||
title String @db.VarChar(200)
|
||||
content String @db.LongText
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
`category`, `type`, `status` 등은 `@db.VarChar(30)` 정도로 지정해도 됩니다.
|
||||
(지정하지 않아도 Prisma가 기본값으로 생성하지만, 긴 본문은 `LongText`를 권장합니다.)
|
||||
|
||||
## 3. 마이그레이션 재생성
|
||||
|
||||
기존 SQLite 마이그레이션은 MySQL에서 실행할 수 없으므로 새 기준(baseline)을 만듭니다.
|
||||
|
||||
```bash
|
||||
# 기존 SQLite 마이그레이션 보관(필요 시)
|
||||
mv prisma/migrations prisma/migrations-sqlite
|
||||
|
||||
# MySQL 기준 마이그레이션 생성
|
||||
npx prisma migrate dev --name init_mysql
|
||||
|
||||
# 또는 운영 DB에 직접 적용만 할 경우
|
||||
npx prisma migrate deploy
|
||||
```
|
||||
|
||||
생성된 `prisma/migrations/*_init_mysql/migration.sql`을 커밋합니다.
|
||||
|
||||
## 4. 데이터 이전
|
||||
|
||||
런칭 전이라면 게시글 수가 적으므로 **관리자 화면에서 다시 입력**하는 것이 가장 안전합니다.
|
||||
데이터가 많다면 아래 방법 중 하나를 사용하세요.
|
||||
|
||||
### 방법 A. CSV 내보내기/가져오기 (권장)
|
||||
|
||||
```bash
|
||||
# SQLite → CSV
|
||||
sqlite3 prisma/dev.db <<'SQL'
|
||||
.headers on
|
||||
.mode csv
|
||||
.output posts.csv
|
||||
SELECT id, type, category, title, content, isPinned, status, viewCount, publishedAt, createdAt, updatedAt FROM Post;
|
||||
.output stdout
|
||||
SQL
|
||||
```
|
||||
|
||||
MySQL Workbench / DBeaver의 CSV Import 기능으로 `Post` 테이블에 적재합니다.
|
||||
`Attachment`는 파일 자체(`storage/uploads`)를 그대로 복사하고, `storageKey` 값만 맞춰 주면 됩니다.
|
||||
|
||||
```bash
|
||||
rsync -av storage/uploads/ user@server:/srv/yonggong/storage/uploads/
|
||||
```
|
||||
|
||||
### 방법 B. 관리자 화면에서 재입력
|
||||
|
||||
- 공지 3건 + 자료 3건 수준이라면 `/admin`에서 다시 작성하는 편이 빠릅니다.
|
||||
- 첨부파일은 기존 `storage/uploads` 폴더를 그대로 복사한 뒤 다시 업로드하면 됩니다.
|
||||
|
||||
> `AdminUser`는 새 환경에서 `npm run db:seed`로 다시 생성합니다.
|
||||
> 비밀번호는 `ADMIN_INITIAL_PASSWORD` 또는 `npm run admin:password`로 설정하세요.
|
||||
|
||||
## 5. 전환 후 확인
|
||||
|
||||
```bash
|
||||
npm run db:deploy # 운영: prisma migrate deploy
|
||||
npm run build
|
||||
npm start
|
||||
```
|
||||
|
||||
- `/api/health` → `{"status":"ok","database":"up"}`
|
||||
- 공지사항/자료실 목록·상세·첨부 다운로드
|
||||
- 관리자 로그인 및 게시글 작성
|
||||
- 한글·이모지 저장/출력 확인
|
||||
- 문의 접수 및 상태 변경
|
||||
|
||||
## 6. 주의 사항
|
||||
|
||||
| 항목 | SQLite | MySQL |
|
||||
| --- | --- | --- |
|
||||
| 문자열 검색 대소문자 | 대소문자 구분 | 콜레이션에 따라 다름 (`utf8mb4_0900_ai_ci`는 구분 안 함) |
|
||||
| Boolean | 0/1 | TINYINT(1) |
|
||||
| `contains` 검색 | 단순 LIKE | 기본 LIKE (필요 시 FULLTEXT 인덱스 고려) |
|
||||
| 동시 쓰기 | 제한적 | 다중 접속에 유리 |
|
||||
| 백업 | 파일 복사 | `mysqldump` |
|
||||
|
||||
- 검색 성능이 중요해지면 `title`, `content`에 FULLTEXT 인덱스를 추가하고
|
||||
`getPosts()`의 `contains` 조건을 `search` 기반으로 바꾸는 것을 검토하세요.
|
||||
- MySQL 백업 예시:
|
||||
```bash
|
||||
docker compose exec -T db mysqldump -u yonggong -p"$MYSQL_PASSWORD" --single-transaction yonggong > backups/db-$(date +%F).sql
|
||||
```
|
||||
- 전환 후에는 `prisma/migrations-sqlite` 폴더를 삭제하거나 별도 브랜치에 보관하세요.
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
output: "standalone",
|
||||
poweredByHeader: false,
|
||||
compress: true,
|
||||
// 업로드 경로를 런타임에 결정하다 보니 Turbopack이 프로젝트 전체를 추적합니다.
|
||||
// 실제 실행에 필요 없는 소스/문서/개발 데이터는 standalone 결과에서 제외합니다.
|
||||
outputFileTracingExcludes: {
|
||||
"/*": [
|
||||
"./docs/**/*",
|
||||
"./src/**/*",
|
||||
"./scripts/**/*",
|
||||
"./storage/**/*",
|
||||
"./prisma/dev.db",
|
||||
"./README.md",
|
||||
"./AGENTS.md",
|
||||
"./.env",
|
||||
"./.env.*",
|
||||
"./Dockerfile",
|
||||
"./docker-compose.yml",
|
||||
// Node.js 런타임에서는 바이너리 엔진을 사용하므로 Edge용 wasm 사본은 불필요합니다.
|
||||
"./node_modules/@prisma/client/runtime/*.wasm-base64.js",
|
||||
"./node_modules/@prisma/client/runtime/*.wasm-base64.mjs",
|
||||
],
|
||||
},
|
||||
experimental: {
|
||||
serverActions: {
|
||||
// 첨부파일 업로드(최대 10개 × 50MB)를 고려한 값입니다.
|
||||
bodySizeLimit: "60mb",
|
||||
},
|
||||
},
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/:path*",
|
||||
headers: [
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
{ key: "X-Frame-Options", value: "SAMEORIGIN" },
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{ key: "Permissions-Policy", value: "geolocation=(), microphone=(), camera=()" },
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
Generated
+4301
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "yonggong-website",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "prisma generate && next build",
|
||||
"start": "next start",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"db:generate": "prisma generate",
|
||||
"db:migrate": "prisma migrate dev",
|
||||
"db:deploy": "prisma migrate deploy",
|
||||
"db:seed": "prisma db seed",
|
||||
"db:studio": "prisma studio",
|
||||
"admin:password": "tsx scripts/set-admin-password.ts"
|
||||
},
|
||||
"prisma": {
|
||||
"seed": "tsx prisma/seed.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@prisma/client": "6.19.3",
|
||||
"bcryptjs": "3.0.3",
|
||||
"jose": "6.2.13",
|
||||
"lucide-react": "1.61.0",
|
||||
"next": "16.4.3",
|
||||
"react": "19.3.1",
|
||||
"react-dom": "19.3.1",
|
||||
"react-markdown": "10.1.0",
|
||||
"remark-gfm": "4.0.1",
|
||||
"server-only": "^0.0.1",
|
||||
"zod": "3.25.76"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "4.3.3",
|
||||
"@types/node": "26.6.5",
|
||||
"@types/react": "19.3.0",
|
||||
"@types/react-dom": "19.3.0",
|
||||
"prisma": "6.19.3",
|
||||
"tailwindcss": "4.3.3",
|
||||
"tsx": "4.23.15",
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"@prisma/client@6.19.3": true,
|
||||
"@prisma/engines@6.19.3": true,
|
||||
"esbuild@0.28.2": true,
|
||||
"prisma@6.19.3": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
const config = {
|
||||
plugins: {
|
||||
"@tailwindcss/postcss": {},
|
||||
},
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,96 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "AdminUser" (
|
||||
"id" TEXT NOT NULL PRIMARY KEY,
|
||||
"loginId" TEXT NOT NULL,
|
||||
"passwordHash" TEXT NOT NULL,
|
||||
"name" TEXT NOT NULL,
|
||||
"role" TEXT NOT NULL DEFAULT 'ADMIN',
|
||||
"totpSecret" TEXT,
|
||||
"lastLoginAt" DATETIME,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Post" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"type" TEXT NOT NULL,
|
||||
"category" TEXT,
|
||||
"title" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL,
|
||||
"isPinned" BOOLEAN NOT NULL DEFAULT false,
|
||||
"status" TEXT NOT NULL DEFAULT 'PUBLISHED',
|
||||
"viewCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"authorId" TEXT,
|
||||
"publishedAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" DATETIME NOT NULL,
|
||||
CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "AdminUser" ("id") ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Attachment" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"postId" INTEGER,
|
||||
"originalName" TEXT NOT NULL,
|
||||
"storageKey" TEXT NOT NULL,
|
||||
"mimeType" TEXT NOT NULL,
|
||||
"size" INTEGER NOT NULL,
|
||||
"downloadCount" INTEGER NOT NULL DEFAULT 0,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "Attachment_postId_fkey" FOREIGN KEY ("postId") REFERENCES "Post" ("id") ON DELETE CASCADE ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Inquiry" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"name" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"phone" TEXT,
|
||||
"title" TEXT NOT NULL,
|
||||
"content" TEXT NOT NULL,
|
||||
"consent" BOOLEAN NOT NULL DEFAULT false,
|
||||
"status" TEXT NOT NULL DEFAULT 'NEW',
|
||||
"ip" TEXT,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "AuditLog" (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"adminId" TEXT,
|
||||
"action" TEXT NOT NULL,
|
||||
"targetType" TEXT,
|
||||
"targetId" TEXT,
|
||||
"ip" TEXT,
|
||||
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "AuditLog_adminId_fkey" FOREIGN KEY ("adminId") REFERENCES "AdminUser" ("id") ON DELETE SET NULL ON UPDATE CASCADE
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "Setting" (
|
||||
"key" TEXT NOT NULL PRIMARY KEY,
|
||||
"value" TEXT NOT NULL,
|
||||
"updatedAt" DATETIME NOT NULL
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "AdminUser_loginId_key" ON "AdminUser"("loginId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Post_type_status_publishedAt_idx" ON "Post"("type", "status", "publishedAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Post_type_category_idx" ON "Post"("type", "category");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "Attachment_storageKey_key" ON "Attachment"("storageKey");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Attachment_postId_idx" ON "Attachment"("postId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "Inquiry_status_createdAt_idx" ON "Inquiry"("status", "createdAt");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt");
|
||||
@@ -0,0 +1,3 @@
|
||||
# Please do not edit this file manually
|
||||
# It should be added in your version-control system (e.g., Git)
|
||||
provider = "sqlite"
|
||||
@@ -0,0 +1,93 @@
|
||||
// 개발 환경에서는 SQLite를 사용합니다.
|
||||
// 운영 환경에서 MySQL로 전환할 때는 provider와 DATABASE_URL만 변경하고
|
||||
// `prisma migrate dev`로 마이그레이션을 다시 생성하세요.
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "sqlite"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model AdminUser {
|
||||
id String @id @default(cuid())
|
||||
loginId String @unique
|
||||
passwordHash String
|
||||
name String
|
||||
role String @default("ADMIN") // ADMIN | EDITOR
|
||||
totpSecret String?
|
||||
lastLoginAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
posts Post[]
|
||||
auditLogs AuditLog[]
|
||||
}
|
||||
|
||||
model Post {
|
||||
id Int @id @default(autoincrement())
|
||||
type String // NOTICE | ARCHIVE
|
||||
category String?
|
||||
title String
|
||||
content String
|
||||
isPinned Boolean @default(false)
|
||||
status String @default("PUBLISHED") // DRAFT | PUBLISHED
|
||||
viewCount Int @default(0)
|
||||
authorId String?
|
||||
author AdminUser? @relation(fields: [authorId], references: [id], onDelete: SetNull)
|
||||
publishedAt DateTime @default(now())
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
attachments Attachment[]
|
||||
|
||||
@@index([type, status, publishedAt])
|
||||
@@index([type, category])
|
||||
}
|
||||
|
||||
model Attachment {
|
||||
id Int @id @default(autoincrement())
|
||||
postId Int?
|
||||
post Post? @relation(fields: [postId], references: [id], onDelete: Cascade)
|
||||
originalName String
|
||||
storageKey String @unique
|
||||
mimeType String
|
||||
size Int
|
||||
downloadCount Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([postId])
|
||||
}
|
||||
|
||||
model Inquiry {
|
||||
id Int @id @default(autoincrement())
|
||||
name String
|
||||
email String
|
||||
phone String?
|
||||
title String
|
||||
content String
|
||||
consent Boolean @default(false)
|
||||
status String @default("NEW") // NEW | IN_PROGRESS | DONE
|
||||
ip String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([status, createdAt])
|
||||
}
|
||||
|
||||
model AuditLog {
|
||||
id Int @id @default(autoincrement())
|
||||
adminId String?
|
||||
admin AdminUser? @relation(fields: [adminId], references: [id], onDelete: SetNull)
|
||||
action String
|
||||
targetType String?
|
||||
targetId String?
|
||||
ip String?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
model Setting {
|
||||
key String @id
|
||||
value String
|
||||
updatedAt DateTime @updatedAt
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import bcrypt from "bcryptjs";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
const uploadRoot = path.resolve(process.env.UPLOAD_DIR ?? "./storage/uploads");
|
||||
|
||||
async function saveSampleFile(name: string, content: string) {
|
||||
const key = `samples/${name}`;
|
||||
const fullPath = path.join(uploadRoot, key);
|
||||
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
||||
await fs.writeFile(fullPath, content, "utf8");
|
||||
return {
|
||||
storageKey: key,
|
||||
originalName: name,
|
||||
mimeType: "text/plain; charset=utf-8",
|
||||
size: Buffer.byteLength(content),
|
||||
};
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const loginId = process.env.ADMIN_LOGIN_ID ?? "admin";
|
||||
const password = process.env.ADMIN_INITIAL_PASSWORD ?? "Yonggong1234!";
|
||||
const passwordHash = await bcrypt.hash(password, 12);
|
||||
|
||||
const admin = await prisma.adminUser.upsert({
|
||||
where: { loginId },
|
||||
update: {
|
||||
name: "홈페이지 관리자",
|
||||
role: "ADMIN",
|
||||
},
|
||||
create: {
|
||||
loginId,
|
||||
passwordHash,
|
||||
name: "홈페이지 관리자",
|
||||
role: "ADMIN",
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`관리자 계정 준비 완료: ${loginId}`);
|
||||
|
||||
const existing = await prisma.post.count();
|
||||
if (existing > 0) {
|
||||
console.log(`게시글 ${existing}건이 이미 있어 샘플 게시글은 건너뜁니다.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const notice1 = await prisma.post.create({
|
||||
data: {
|
||||
type: "NOTICE",
|
||||
category: "공지",
|
||||
title: "용산 공중케이블 주민 안전 협의회 홈페이지 개편 안내",
|
||||
isPinned: true,
|
||||
status: "PUBLISHED",
|
||||
authorId: admin.id,
|
||||
publishedAt: new Date("2026-10-20T09:00:00+09:00"),
|
||||
viewCount: 128,
|
||||
content: `## 홈페이지 개편 안내
|
||||
|
||||
용산 공중케이블 주민 안전 협의회 홈페이지가 새롭게 단장했습니다.
|
||||
|
||||
앞으로 공지사항과 자료실을 통해 협의회의 활동 소식과 조사 자료를 더 편리하게 확인하실 수 있습니다.
|
||||
|
||||
### 주요 변경 사항
|
||||
|
||||
- 공지사항·자료실 게시판 신설
|
||||
- 모바일 화면 최적화
|
||||
- 자료실 첨부파일 다운로드 기능 제공
|
||||
- 기존 조사 현황 지도는 별도 메뉴로 계속 제공
|
||||
|
||||
주민 여러분의 많은 관심과 참여 부탁드립니다.
|
||||
|
||||
문의는 **문의·제보** 메뉴를 이용해 주세요.`,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.post.create({
|
||||
data: {
|
||||
type: "NOTICE",
|
||||
category: "행사",
|
||||
title: "2026년 공중케이블 정비 사업 주민 설명회 개최 안내",
|
||||
status: "PUBLISHED",
|
||||
authorId: admin.id,
|
||||
publishedAt: new Date("2026-10-12T10:00:00+09:00"),
|
||||
viewCount: 86,
|
||||
content: `## 2026년 공중케이블 정비 사업 주민 설명회
|
||||
|
||||
용산구 관내 공중케이블 정비 사업과 관련하여 주민 설명회를 개최합니다.
|
||||
|
||||
- **일시**: 2026년 11월 5일(목) 오후 2시
|
||||
- **장소**: 용산구 주민커뮤니티센터 (추후 공지)
|
||||
- **대상**: 용산구 주민 누구나
|
||||
- **내용**: 정비 사업 추진 현황, 주민 의견 수렴, 질의응답
|
||||
|
||||
참석을 원하시는 분은 문의·제보 메뉴로 성함과 연락처를 남겨 주시기 바랍니다.
|
||||
|
||||
일정과 장소는 사정에 따라 변경될 수 있으며, 변경 시 본 공지사항을 통해 안내드립니다.`,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.post.create({
|
||||
data: {
|
||||
type: "NOTICE",
|
||||
category: "공지",
|
||||
title: "공중케이블 정비 관련 주민 의견을 수렴합니다",
|
||||
status: "PUBLISHED",
|
||||
authorId: admin.id,
|
||||
publishedAt: new Date("2026-09-30T09:00:00+09:00"),
|
||||
viewCount: 54,
|
||||
content: `## 주민 의견 수렴 안내
|
||||
|
||||
용산구 곳곳의 공중케이블로 인한 불편 사항과 정비가 필요한 위치를 제보해 주세요.
|
||||
|
||||
### 제보 방법
|
||||
|
||||
1. **문의·제보** 메뉴에서 내용을 작성합니다.
|
||||
2. 위치(동명, 도로명, 건물 주변)를 최대한 구체적으로 적어 주세요.
|
||||
3. 사진이 있는 경우 자료실 또는 문의 답변을 통해 전달해 주세요.
|
||||
|
||||
접수된 내용은 협의회에서 검토한 뒤 관련 기관과 협의 과정에서 활용합니다.
|
||||
|
||||
개인정보는 제보 처리 목적으로만 사용하며, 처리 완료 후 관련 법령에 따라 파기합니다.`,
|
||||
},
|
||||
});
|
||||
|
||||
const sample1 = await saveSampleFile(
|
||||
"2025-용산구-공중케이블-실태조사-요약.txt",
|
||||
`2025년 용산구 공중케이블 실태조사 요약\n\n- 조사 기간: 2025년 1월 ~ 2025년 12월\n- 조사 대상: 용산구 관내 전신주 및 공중케이블\n- 주요 내용: 전선 과밀, 폐선 의심, 저고도 전선, 시설 훼손\n\n본 문서는 홈페이지 기능 확인을 위한 샘플 자료입니다.\n`,
|
||||
);
|
||||
|
||||
const archive1 = await prisma.post.create({
|
||||
data: {
|
||||
type: "ARCHIVE",
|
||||
category: "보고서",
|
||||
title: "2025년 용산구 공중케이블 실태조사 결과 요약",
|
||||
status: "PUBLISHED",
|
||||
authorId: admin.id,
|
||||
publishedAt: new Date("2026-10-05T09:00:00+09:00"),
|
||||
viewCount: 210,
|
||||
content: `## 2025년 용산구 공중케이블 실태조사 결과 요약
|
||||
|
||||
2025년 한 해 동안 용산구 관내 전신주와 공중케이블을 조사한 결과를 요약했습니다.
|
||||
|
||||
### 주요 결과
|
||||
|
||||
- 전선 과밀 구간과 폐선 의심 구간이 반복적으로 확인됨
|
||||
- 주거지 인근 저고도 전선에 대한 정비 필요
|
||||
- 통신사별 중복 설치 구간 존재
|
||||
|
||||
### 활용 방안
|
||||
|
||||
조사 결과는 용산구청, 통신사와의 간담회 및 정비 요청 자료로 활용됩니다.
|
||||
|
||||
자세한 내용은 첨부파일을 참고해 주세요.`,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.attachment.create({
|
||||
data: { ...sample1, postId: archive1.id },
|
||||
});
|
||||
|
||||
const sample2 = await saveSampleFile(
|
||||
"주민간담회-회의자료.txt",
|
||||
`용산 공중케이블 정비 주민간담회 회의자료\n\n1. 추진 경과\n2. 현장 조사 결과\n3. 정비 요청 사항\n4. 향후 일정\n\n본 문서는 홈페이지 기능 확인을 위한 샘플 자료입니다.\n`,
|
||||
);
|
||||
|
||||
const archive2 = await prisma.post.create({
|
||||
data: {
|
||||
type: "ARCHIVE",
|
||||
category: "회의자료",
|
||||
title: "공중케이블 정비 주민간담회 회의자료",
|
||||
status: "PUBLISHED",
|
||||
authorId: admin.id,
|
||||
publishedAt: new Date("2026-09-18T09:00:00+09:00"),
|
||||
viewCount: 97,
|
||||
content: `## 공중케이블 정비 주민간담회 회의자료
|
||||
|
||||
용산구청, 통신사 관계자와 함께한 주민간담회 자료입니다.
|
||||
|
||||
### 논의 사항
|
||||
|
||||
- 지역별 정비 우선순위
|
||||
- 통신사 협의 절차
|
||||
- 주민 제보 접수 및 처리 방법
|
||||
- 정비 후 유지관리 방안
|
||||
|
||||
첨부된 회의자료를 확인해 주세요.`,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.attachment.create({
|
||||
data: { ...sample2, postId: archive2.id },
|
||||
});
|
||||
|
||||
const sample3 = await saveSampleFile(
|
||||
"공중케이블-정비-요청서-서식.txt",
|
||||
`공중케이블 정비 요청서\n\n- 제보자 성명:\n- 연락처:\n- 위치(동/도로명):\n- 문제 유형:\n- 상세 내용:\n- 사진 첨부 여부:\n\n본 문서는 홈페이지 기능 확인을 위한 샘플 서식입니다.\n`,
|
||||
);
|
||||
|
||||
const archive3 = await prisma.post.create({
|
||||
data: {
|
||||
type: "ARCHIVE",
|
||||
category: "서식",
|
||||
title: "공중케이블 정비 요청서 서식",
|
||||
status: "PUBLISHED",
|
||||
authorId: admin.id,
|
||||
publishedAt: new Date("2026-09-01T09:00:00+09:00"),
|
||||
viewCount: 63,
|
||||
content: `## 공중케이블 정비 요청서 서식
|
||||
|
||||
주민께서 직접 정비 요청서를 작성해 제출하실 수 있도록 서식을 제공합니다.
|
||||
|
||||
### 작성 방법
|
||||
|
||||
1. 첨부파일을 내려받습니다.
|
||||
2. 위치와 문제 유형을 구체적으로 작성합니다.
|
||||
3. 작성한 파일을 문의·제보 메뉴 또는 협의회 이메일로 보내 주세요.
|
||||
|
||||
첨부파일은 샘플 서식이며, 운영 과정에서 실제 서식으로 교체할 수 있습니다.`,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.attachment.create({
|
||||
data: { ...sample3, postId: archive3.id },
|
||||
});
|
||||
|
||||
console.log(`샘플 게시글 생성 완료: 공지 3건, 자료 3건 (대표 공지 ID: ${notice1.id})`);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 382 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 228 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 228 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 138 KiB |
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* 관리자 비밀번호를 변경하거나 새 관리자 계정을 만듭니다.
|
||||
*
|
||||
* 사용법:
|
||||
* npm run admin:password -- <아이디> <새비밀번호>
|
||||
*
|
||||
* 예시:
|
||||
* npm run admin:password -- admin 'NewStrongPassword!2026'
|
||||
*/
|
||||
import { PrismaClient } from "@prisma/client";
|
||||
import bcrypt from "bcryptjs";
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
const [, , loginIdArg, passwordArg] = process.argv;
|
||||
const loginId = (loginIdArg ?? process.env.ADMIN_LOGIN_ID ?? "").trim();
|
||||
const password = passwordArg ?? process.env.ADMIN_NEW_PASSWORD ?? "";
|
||||
|
||||
if (!loginId) {
|
||||
console.error("아이디를 입력해 주세요. 예: npm run admin:password -- admin '새비밀번호'");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (password.length < 8) {
|
||||
console.error("비밀번호는 8자 이상이어야 합니다.");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const passwordHash = await bcrypt.hash(password, 12);
|
||||
|
||||
const admin = await prisma.adminUser.upsert({
|
||||
where: { loginId },
|
||||
update: { passwordHash },
|
||||
create: {
|
||||
loginId,
|
||||
passwordHash,
|
||||
name: "홈페이지 관리자",
|
||||
role: "ADMIN",
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`관리자 계정이 준비되었습니다: ${admin.loginId} (${admin.name})`);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
})
|
||||
.finally(async () => {
|
||||
await prisma.$disconnect();
|
||||
});
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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`);
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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) }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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) }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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) }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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}(이하 “협의회”)는 「개인정보 보호법」 등 관련 법령에 따라 이용자의 개인정보를 보호하고,
|
||||
이와 관련한 고충을 신속하게 처리할 수 있도록 다음과 같이 개인정보처리방침을 수립·공개합니다.
|
||||
</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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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}(이하 “협의회”)가 운영하는 홈페이지의 이용 조건과 절차, 이용자와 협의회의 권리·의무
|
||||
및 책임 사항을 규정함을 목적으로 합니다.
|
||||
</p>
|
||||
|
||||
<h2>제2조 (용어의 정의)</h2>
|
||||
<ul>
|
||||
<li>“홈페이지”란 협의회가 정보 제공 및 소통을 위해 운영하는 웹사이트를 말합니다.</li>
|
||||
<li>“이용자”란 홈페이지에 접속하여 서비스를 이용하는 모든 사람을 말합니다.</li>
|
||||
<li>“게시물”이란 이용자가 홈페이지에 게시한 문의, 제보, 의견 등을 말합니다.</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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -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",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
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",
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 |
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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 [];
|
||||
}
|
||||
}
|
||||
@@ -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]}`;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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 {
|
||||
// 파일이 이미 없어도 삭제는 성공으로 처리합니다.
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [
|
||||
{
|
||||
"name": "next"
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./src/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"next-env.d.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx",
|
||||
".next/types/**/*.ts",
|
||||
".next/dev/types/**/*.ts"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user