Compare commits

...

58 Commits

Author SHA1 Message Date
c442e0d8bb v0.1.46 - TODO 우선순위와 메일 정책 정리 2026-04-24 11:35:35 +09:00
6d4f2228cc v0.1.45 - 로그아웃 API와 세션 상태 안내 추가 2026-04-24 10:39:42 +09:00
684413a098 v0.1.44 - 날짜 기준과 TODO 정리 2026-04-24 10:10:34 +09:00
a38714dfe4 v0.1.43 - 인증 강제와 회원 탈퇴 흐름 정리 2026-04-24 10:04:44 +09:00
54f4b34e5e v0.1.62 - 운영 인증 링크 노출 제한 2026-04-23 18:01:48 +09:00
d59795b089 v0.1.61 - Resend 메일 발송 연결 2026-04-23 17:18:11 +09:00
8a46c507e9 v0.1.60 - 닉네임 중복 검증과 비밀번호 재설정 연결 2026-04-23 16:47:37 +09:00
a78ad7e8fb v0.1.59 - 랜딩 문구 표시 정리 2026-04-23 16:36:32 +09:00
477d453888 v0.1.58 - 1페이지 인쇄 A4 중앙 기준 정리 2026-04-23 16:32:42 +09:00
75abcd7333 v0.1.57 - 2페이지 인쇄 중앙 정렬 2026-04-23 16:31:30 +09:00
803ecb34ad v0.1.56 - 인쇄 모달 출력 제외 2026-04-23 16:28:35 +09:00
c1c7288127 v0.1.55 - 기간 인쇄 모달 추가 2026-04-23 16:23:27 +09:00
cb309cf0fa v0.1.54 - 통계 그래프 반응형 폭 조정 2026-04-23 15:55:09 +09:00
e9839d85e2 v0.1.53 - 통계 기록 목록과 차트 드래그 보정 2026-04-23 15:40:21 +09:00
b80994d114 v0.1.52 - 이월 배지와 통계 설명 팝업 정리 2026-04-23 15:32:48 +09:00
6c69658d33 v0.1.51 - 통계 차트와 플래너 하단 정렬 보정 2026-04-23 15:20:43 +09:00
bebd8ed8a6 v0.1.50 - 이월 할 일 흐름과 사이드 패널 정리 2026-04-23 15:01:50 +09:00
6d9aa2c002 v0.1.49 - 데모 페이지 스크롤 구조 단순화 2026-04-23 13:56:19 +09:00
33ba9a2ab1 v0.1.48 - 데모 읽기 전용 스크롤 수정 2026-04-23 13:52:45 +09:00
ff20e90768 v0.1.47 - 데모 스크롤과 2페이지 보기 보정 2026-04-23 13:51:06 +09:00
744202077f v0.1.46 - 비로그인 데모 화면 추가 2026-04-23 13:48:40 +09:00
e847ddd227 v0.1.45 - 로그인 유지 옵션과 랜딩 문구 정리 2026-04-23 13:42:53 +09:00
1f2d9ddc54 v0.1.44 - 로그인 화면 모바일 정리 2026-04-23 13:39:16 +09:00
44932f9724 v0.1.43 - 플래너 라벨과 가이드 동작 정리 2026-04-23 13:34:48 +09:00
4a80721824 v0.1.42 - 관리자 자동 계정과 로그인 정리 2026-04-22 18:44:15 +09:00
403d0a0c5a v0.1.41 - 배포 설정과 계정 화면 정리 반영 2026-04-22 18:39:05 +09:00
8f96c22c6d v0.1.40 - 관리자 대시보드 기본 구조 추가 2026-04-22 18:38:31 +09:00
b18af56c3c v0.1.39 - 달력 원형과 D-DAY 표시 상태 보정 2026-04-22 18:13:50 +09:00
3c3b0d20dd v0.1.38 - 인쇄 출력 보정과 인증 토큰 기반 확장 2026-04-22 18:02:23 +09:00
bf62eb12bb v0.1.37 - 총 시간 한글화와 인쇄 타임테이블 보정 2026-04-22 17:53:10 +09:00
370c169c1c v0.1.37 - 총 시간 한글화와 인쇄 타임테이블 보정 2026-04-22 17:49:01 +09:00
249a68e89d v0.1.36 - 사이드 소개 영역 서비스 톤으로 정리 2026-04-22 17:44:41 +09:00
2462d79053 v0.1.35 - 사용자 노출 문구 한글화와 펼침 폭 보정 2026-04-22 17:38:57 +09:00
4e1263348e v0.1.34 - 모바일 달력 카드 밀도와 버튼 크기 조정 2026-04-22 17:32:39 +09:00
4d48176555 v0.1.33 - 모바일 플래너 본문 레이아웃 개선 2026-04-22 17:29:07 +09:00
c372f325ab v0.1.32 - 패널 드로어 애니메이션과 모바일 밀도 조정 2026-04-22 17:12:41 +09:00
f11c0d3cef v0.1.31 - 집중 시간 한글 표기와 통계 문구 정리 2026-04-22 16:42:25 +09:00
98d4209958 v0.1.30 - 태블릿과 모바일용 내비게이션 드로어 정리 2026-04-22 16:30:21 +09:00
bf06cd28c1 v0.1.29 - 반응형 우측 패널 오버레이와 2페이지 보기 배율 조정 2026-04-22 15:43:41 +09:00
962a338b3d v0.1.28 - 사이드 레이아웃 재정리와 2페이지 인쇄 보정 2026-04-22 12:10:21 +09:00
9e96a57504 v0.1.27 - 달력 기준과 우측 패널 레이아웃 정리 2026-04-22 11:33:17 +09:00
905a0caf75 v0.1.26 - 빈 날짜 이동 시 불필요한 삭제 알림 제거 2026-04-22 11:25:09 +09:00
e221254c60 v0.1.25 - 빈 JSON 본문 요청 오류 수정 2026-04-22 11:20:22 +09:00
1738a7d3b6 v0.1.24 - 개발용과 배포용 실행 문서 추가 2026-04-22 11:14:29 +09:00
9760c9dc0e v0.1.23 - 개발용 자동 새로고침과 로그인 화면 정렬 2026-04-22 11:08:58 +09:00
b972209c2f v0.1.22 - 로그인 오류 문구와 비로그인 화면 정리 2026-04-22 11:05:46 +09:00
bc2e981577 v0.1.21 - 우측 요약 패널 실제 데이터 연결 2026-04-22 10:59:30 +09:00
8ff4c979fa v0.1.20 - PostgreSQL 전환 및 Docker Compose 초안 추가 2026-04-22 10:48:24 +09:00
9b788406ea v0.1.19 - 사이드 네비게이션과 D-DAY 중복 방지 적용 2026-04-22 10:19:23 +09:00
fe538fc88b v0.1.18 - 설정 화면과 기간형 D-DAY 관리 추가 2026-04-22 09:47:04 +09:00
4355185203 v0.1.17 - 목표 패널 및 D-DAY 선택 추가 2026-04-21 18:37:06 +09:00
440f0f46a1 v0.1.16 - 토스트 축소 및 D-DAY 구조 정리 2026-04-21 18:29:57 +09:00
1e58c58373 v0.1.15 - 로그인 필수 및 동기화 토스트 2026-04-21 18:24:39 +09:00
20564ba34b v0.1.14 - 서버 삭제 동기화 추가 2026-04-21 18:20:33 +09:00
a53ef4cc6f v0.1.13 - 로컬·클라우드 데이터 분리 2026-04-21 18:16:50 +09:00
282d51daf6 v0.1.12 - 서버 저장 연결 시작 2026-04-21 18:13:58 +09:00
f718342b93 v0.1.11 - 인증 UI 연결 2026-04-21 18:06:24 +09:00
5b1c4bcfca v0.1.10 - 플래너 저장 API 추가 2026-04-21 18:02:03 +09:00
46 changed files with 7170 additions and 606 deletions

8
.dockerignore Normal file
View File

@@ -0,0 +1,8 @@
node_modules
dist
.git
.gitignore
backend/node_modules
backend/data
backend/drizzle
*.log

13
.env.example Normal file
View File

@@ -0,0 +1,13 @@
POSTGRES_DB=ten_minute_planner
POSTGRES_USER=replace-with-private-db-user
POSTGRES_PASSWORD=replace-with-private-db-password
DATABASE_URL=postgresql://replace-with-private-db-user:replace-with-private-db-password@postgres:5432/ten_minute_planner
ADMIN_ACCOUNT_ID=replace-with-private-admin-id
ADMIN_ACCOUNT_PASSWORD=replace-with-private-admin-password
ADMIN_ACCOUNT_EMAIL=admin@example.com
ADMIN_ACCOUNT_NICKNAME=Planner Admin
APP_BASE_URL=https://planner.sori.studio
RESEND_API_KEY=replace-with-private-resend-api-key
MAIL_FROM_EMAIL=planner@sori.studio
MAIL_FROM_NAME=10 Minute Planner
AUTH_PREVIEW_LINKS=false

2
.gitignore vendored
View File

@@ -3,5 +3,7 @@ backend/node_modules/
dist/
.DS_Store
*.log
.env
.env.dev
backend/.env
backend/data/

20
Dockerfile Normal file
View File

@@ -0,0 +1,20 @@
FROM node:22-alpine AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
ARG VITE_API_BASE_URL=/api
ENV VITE_API_BASE_URL=${VITE_API_BASE_URL}
RUN npm run build
FROM nginx:1.27-alpine
COPY deploy/nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80

View File

@@ -4,7 +4,7 @@
- 프로젝트명: 10 Minute Planner 웹 UI
- 기술 스택: Vue 3 + Vite + TailwindCSS + JavaScript
- 현재 기준 버전: `v0.1.9`
- 현재 기준 버전: `v0.1.46` 준비 중
- Git 원격 저장소: `https://git.sori.studio/zenn/planner.sori.studio.git`
## 기준 디자인
@@ -26,10 +26,18 @@
- 메인 화면 셸: `src/App.vue`
- 플래너 종이 레이아웃: `src/components/PlannerPage.vue`
- 우측 달력 컴포넌트: `src/components/MiniCalendar.vue`
- 프론트 인증 모달: `src/components/AuthDialog.vue`
- 프론트 인증 클라이언트: `src/lib/authClient.js`
- 백엔드 엔트리 포인트: `backend/src/server.js`
- 백엔드 DB 스키마: `backend/src/db/schema.js`
- 백엔드 인증 라우트: `backend/src/routes/auth.js`
- 백엔드 목표 라우트: `backend/src/routes/goals.js`
- 백엔드 비밀번호/세션 유틸: `backend/src/lib/password.js`
- Docker Compose 진입점: `docker-compose.yml`
- 프론트 Dockerfile: `Dockerfile`
- 백엔드 Dockerfile: `backend/Dockerfile`
- nginx 프록시 설정: `deploy/nginx/default.conf`
- 실행 가이드 문서: `README.md`
- Tailwind 설정은 완료되어 있으며, 이 프로젝트의 스타일링 기준으로 유지한다.
- 현재 선택 날짜는 시스템 날짜 기준으로 시작한다.
- `COMMENT`, `TASKS`, `MEMO`는 화면에서 바로 편집할 수 있다.
@@ -45,9 +53,16 @@
- 달력 상단은 월 좌우 화살표, 클릭형 연도 선택, `TODAY` 버튼 구조로 동작한다.
- 입력 내용이 있는 날짜는 달력 하단에 빨간 점으로 표시된다.
- 상단 날짜 표시에서는 토요일의 `(토)`만 파란색, 일요일의 `(일)`만 빨간색으로 표시한다.
- 플래너 상태는 `localStorage`에 저장되며, 날짜별 기록과 선택 날짜, 달력 보고 있던 월까지 복원다.
- 플래너 상태는 `localStorage`에 저장되며, 날짜별 기록과 통계 범위 같은 UI 상태를 복원다.
- 플래너 기록 자체는 로컬에 남기되, 앱을 새로 열 때 기본 기준 날짜는 마지막 열람 날짜가 아니라 항상 오늘 날짜로 맞춘다.
- `localStorage` 접근 로직은 `src/lib/plannerStorage.js`로 분리하기 시작했고, 이후 API/DB adapter로 교체하기 쉬운 구조로 정리 중이다.
- 프론트는 헤더에서 `LOGIN` / `SIGN UP` 모달을 열 수 있고, 로그인 상태면 닉네임과 `LOGOUT` 버튼을 표시한다.
- 인증 토큰과 현재 사용자 정보는 프론트 로컬 저장소에 따로 유지하고, 앱 시작 시 `/api/auth/me`로 세션 복원을 시도한다.
- 프론트 플래너 API 클라이언트는 `src/lib/plannerApi.js`에 추가되었다.
- 프론트 목표 API 클라이언트는 `src/lib/goalsApi.js`에 추가되었다.
- 루트에서 `npm run dev:backend`, `npm run db:generate`, `npm run db:migrate`로 백엔드 명령을 호출할 수 있다.
- 화면 탭은 `PLANNER / STATS / GOALS / SETTINGS` 기준으로 확장되었다.
- 기존 상단 헤더는 왼쪽 사이드 내비게이션으로 재구성되었고, A5 본문이 더 넓게 보이도록 조정되었다.
- 상단 전환 버튼으로 `PLANNER / STATS` 화면을 오갈 수 있다.
- 통계 화면에서는 전체 집중 시간, 평균 완료율, 기록 일수, 최근 7일 흐름, 최근 기록, 베스트 데이를 보여준다.
- 통계 화면은 시작일/종료일을 직접 선택해 그 기간 기준으로 지표를 다시 계산할 수 있다.
@@ -64,10 +79,15 @@
- `1-UP`은 여백이 과하지 않도록 다시 확대했고, `2-UP`은 한 페이지 고정 안정성을 위해 가로 폭과 세로 높이를 조금 더 보수적으로 조정했다.
- `1-UP`은 세로 가운데 정렬을 없애고 상단 기준으로 붙여야 여백이 덜 커 보인다.
- 현재 `1-UP`은 프레임 자체를 A4 세로에 가깝게 키우고 배율을 크게 올려 빈 여백을 줄이는 방향으로 맞추고 있다.
- 백엔드 초안은 `Fastify + Drizzle + SQLite` 조합이며, 현재는 `/health`, `/api/meta` 정도의 기본 라우트만 있다.
- 백엔드 초안은 `Fastify + Drizzle + PostgreSQL` 조합으로 전환되었다.
- 백엔드에는 `/api/auth/signup`, `/api/auth/login`, `/api/auth/me`가 추가되었다.
- 백엔드에는 `/api/auth/verification/request`, `/api/auth/verification/confirm` 이메일 인증 토큰 API가 추가되었다.
- 백엔드에는 `/api/auth/password-reset/request`, `/api/auth/password-reset/confirm` 비밀번호 재설정 토큰 API가 추가되었다.
- 백엔드에는 `/api/admin/overview` 관리자 요약 API가 추가되었다.
- 백엔드에는 `/api/planner/:entryDate` 단건 조회/저장과 `/api/planner?from=...&to=...` 범위 조회가 추가되었다.
- 비밀번호는 Node 내장 `crypto.scrypt` 기반 해시로 저장하고, 세션 토큰은 `auth_sessions` 테이블에 해시 형태로 저장한다.
- 초기 실행 시 `backend/src/db/init.js`에서 테이블이 없으면 자동 생성하도록 맞춰두었다.
- 플래너 저장은 `planner_entries (user_id, entry_date)` 고유 키 기준으로 upsert 하도록 구성했다.
- 현재 샌드박스에서는 포트 바인딩 제한 때문에 백엔드 실제 리슨 확인이 막힐 수 있다. `listen EPERM 0.0.0.0:3001`은 코드 자체보다 실행 환경 제약에 가깝다.
## 확정된 결정사항
@@ -96,8 +116,8 @@
- 공유를 위해 나중에 이미지 저장 기능도 필요하지만, 실제 출력 품질과 텍스트 선명도는 HTML/CSS 인쇄 레이아웃을 우선 유지하는 편이 좋다.
- 원격 저장소 `origin``https://git.sori.studio/zenn/planner.sori.studio.git`로 연결되어 있다.
- 앞으로 버전 체크포인트 커밋은 `v0.1.7 - 작업 요약`처럼 버전 뒤에 짧은 작업 설명을 함께 남기는 형식으로 통일한다.
- 이후 배포 단계에서는 `docker-compose.yml`도 함께 작성해야 하며, 포트 번호와 서비스 구성은 추후 사용자와 확정한다.
- `backend/.env.example`에는 기본 `PORT`, `DB_FILE`, `CORS_ORIGIN` 예시가 들어 있다.
- `docker-compose.yml` 초안은 이미 추가되었고, 포트 번호와 실제 외부 공개 범위는 NAS 배포 단계에서 다시 확정하면 된다.
- `backend/.env.example`에는 기본 `PORT`, `DATABASE_URL`, `CORS_ORIGIN` 예시가 들어 있다.
## 다음 권장 작업
@@ -105,11 +125,133 @@
- 목표나 통계 기능보다 먼저, 플래너 본문의 입력과 상호작용을 우선 구현한다.
- 통계 화면 구현은 현재 `localStorage` 기반으로 먼저 진행해도 된다.
- DB는 기능 탐색 속도를 해치지 않는 선에서, 저장 레이어를 분리할 수 있는 적절한 시점에 붙이는 것이 좋다.
- 현재 기준 추천 백엔드 방향은 `Vue 프론트엔드 + Node.js API + SQLite 또는 PostgreSQL`이다.
- 현재는 SQLite로 시작하되, 확장 시 PostgreSQL로 옮길 수 있게 Drizzle 기반 스키마를 유지한다.
- 현재 기준 추천 백엔드 방향은 `Vue 프론트엔드 + Node.js API + PostgreSQL`이다.
- Docker 배포를 시작하는 시점이므로 SQLite보다 PostgreSQL을 기본 저장소로 유지하는 편이 낫다.
- 현재 인증 방식은 Bearer 토큰 기반의 간단한 세션 구조이며, 추후 쿠키/리프레시 토큰 전략으로 확장할 수 있다.
- 다음 프론트 단계에서는 `src/lib/plannerStorage.js`를 유지하되, 인증 이후 백엔드 저장소 adapter를 추가해서 `localStorage`와 전환 가능하게 만드는 흐름이 좋다.
- 현재 프론트는 인증만 연결된 상태이고, 플래너 저장은 아직 `localStorage` 기준이다.
- 로그인 상태에서는 플래너 수정 시 날짜별 서버 저장을 예약하고, 로그인 직후에는 서버 데이터를 먼저 가져오도록 연결하기 시작했다.
- 현재는 로컬 저장도 계속 유지하면서 서버 저장을 병행하는 과도기 구조다.
- 로그인 시 서버 플래너 데이터로 `plannerRecords`를 교체하고, 로그아웃 시에는 로컬 저장 기반 데이터로 다시 복귀하도록 정리했다.
- 이로 인해 다른 사용자 로그인 시 이전 로컬 데이터가 서버 계정 데이터와 섞일 위험을 줄였다.
- 로그인 상태에서 특정 날짜의 플래너 내용을 완전히 비우면, 서버 저장 대신 해당 날짜 엔트리를 삭제하도록 정리했다.
- 현재는 로그인 전 플래너 진입을 막고, 인증 후에만 실제 플래너/통계 화면을 사용하도록 변경했다.
- 클라우드 저장 상태는 헤더가 아니라 오른쪽 하단의 작은 토스트 형태로 표시되도록 변경했다.
- 저장 완료 토스트는 한 줄짜리의 작은 상태 문구로 줄여서 존재감을 낮췄다.
- D-DAY는 플래너 안에서 목표를 고르는 구조가 아니라, GOALS 화면에서 목표와 표시 기간을 먼저 설정하는 구조로 정리했다.
- 플래너 화면 오른쪽 패널에서는 현재 날짜에 적용된 목표가 있을 때만 D-DAY 토글을 켤 수 있고, 목표 검색 UI는 제거했다.
- 목표는 `active_from`, `active_until` 기간을 가질 수 있고, 현재 날짜가 그 범위에 들어올 때만 플래너 본문 D-DAY 후보가 된다.
- TASK LABELS도 별도 버튼 2개 대신 동일한 토글 UI로 단순화했다. ON이면 01~15를 채우고 OFF이면 비운다.
- SETTINGS 화면이 추가되어 닉네임, 이메일, 비밀번호 변경을 분리해서 관리할 수 있다.
- 백엔드에는 `/api/auth/profile`, `/api/auth/password`, `/api/goals/:goalId` 수정 API가 추가되었다.
- 백엔드에는 `/api/goals/:goalId` 삭제 API도 추가되었다.
- 왼쪽 사이드, 플래너 본문 래퍼, 오른쪽 정보 패널 모두 둥근 카드 톤으로 맞춰서 화면 전체의 통일감을 높였다.
- 플래너 집중 보기에서는 본문과 오른쪽 패널이 각각 독립 스크롤되도록 바뀌어서 동시에 참조하기 쉽다.
- TASK LABELS, D-DAY 토글은 공통 사이즈의 스위치로 통일했고, `translate` 기반 애니메이션으로 부드럽게 움직이게 했다.
- 목표 생성 폼은 기본적으로 `표시 시작일 = 오늘`, `표시 종료일 = 목표일` 흐름으로 자동 채워진다.
- D-DAY 기간은 서로 겹칠 수 없고, 프론트와 백엔드 모두 중복 기간을 감지하면 저장을 막는다.
- 현재 날짜에 적용된 목표가 있는 경우 D-DAY는 기본적으로 보이고, 해당 날짜에서만 토글로 숨길 수 있다.
- 목표 상태 개념은 제거했고, 목표는 기간이 있으면 곧바로 D-DAY 후보가 되는 단순 구조로 정리했다.
- GOALS 화면에서는 수정 중인 카드가 시각적으로 강조되고, 목표 삭제 버튼이 추가되었다.
- 목표 삭제 시 과거 날짜를 포함해 어떤 날짜에서도 해당 목표는 더 이상 표시되지 않는다.
- 우측 패널의 `PREV SNAPSHOT`은 선택 날짜 이전의 가장 최근 기록을 읽어서 날짜, 집중 시간, 완료 개수, 코멘트 또는 대표 작업을 보여준다.
- 우측 패널의 `READ NEXT`는 다음 날 첫 작업, 오늘의 미완료 작업, 오늘 코멘트를 기반으로 이어보기 문구를 자동 생성한다.
- 백엔드는 SQLite 파일 기반 구조에서 PostgreSQL 연결 구조로 교체되었다.
- `planner_entries.payload`는 문자열이 아니라 PostgreSQL `JSONB`로 저장되도록 바뀌었다.
- `docker-compose.yml` 기준으로 `postgres`, `backend`, `frontend(nginx)` 3개 서비스 초안이 추가되었다.
- 프론트는 nginx에서 `/api`를 백엔드로 프록시하는 구조라서, 배포 시 브라우저가 별도 API 포트를 직접 알 필요가 없다.
- 프론트 API 클라이언트는 `VITE_API_BASE_URL` 끝에 `/api`가 포함되어 있어도 `/api/api/...` 중복 주소가 생기지 않도록 정규화한다.
- 로그인 실패 시에는 내부 라우트 문자열이나 서버 경로를 그대로 노출하지 않고, 사용자용 안내 문구만 보여준다.
- 비로그인 상태에서는 왼쪽 사이드 내비게이션을 숨기고, 중앙 로그인 안내 화면만 보여주도록 정리했다.
- 배포용 `docker-compose.yml`과 별도로 개발용 `docker-compose.dev.yml`을 추가했다.
- 개발용 compose는 프론트 `5173`, 백엔드 `3001`, PostgreSQL `5432`를 열고, 소스 마운트 + Vite HMR + Node watch 기반으로 자동 반영된다.
- 개발/배포 실행 방법은 루트 `README.md`에 먼저 적고, `HANDOFF.md`에는 변경 이유와 주의사항 위주로 남긴다.
- API 클라이언트는 body가 없는 `GET`, `DELETE` 요청에 `Content-Type: application/json`을 붙이지 않도록 수정했다. 날짜 선택 시 발생하던 `Body cannot be empty...` 오류는 이 문제였다.
- 날짜 이동 중 목표 자동 보정으로 `goalEnabled`만 꺼지는 경우에는, 실제 내용이 없는 기록이라면 클라우드 동기화 토스트를 띄우지 않도록 정리했다.
- 집중 보기에서 오른쪽 패널 폭을 넓혀 `1920x1080` 기준 활용도를 높였고, `TASK LABELS / D-DAY / CALENDAR`는 상단 고정 영역으로 올렸다.
- `STATS``NEXT DAY`는 반반 카드가 아니라 각각 한 줄씩 쓰도록 바꿔서 날짜 길이에 따라 높이가 흔들리는 문제를 줄였다.
- 미니 달력은 42칸 기준으로 렌더링하고, 요일 헤더를 `SUN ~ SAT` 순서로 고정해서 일요일 시작 달력 기준을 더 명확하게 맞췄다.
- 집중 보기 오른쪽 패널은 다시 정리해서 `왼쪽 컬럼: CALENDAR / TASK LABELS / D-DAY`, `오른쪽 컬럼: STATS / NEXT DAY`, `하단 전체 폭: READ NEXT / PREV SNAPSHOT` 구조로 맞췄다.
- 달력은 과하게 키우지 않고 컴팩트한 크기를 유지한 채, 우측 정보 패널 내부 배치만 다시 조정하는 쪽으로 방향을 잡았다.
- `PRINT 2-UP`은 브라우저/프린터 기본 여백 차이로 오른쪽 페이지가 잘릴 수 있어서, 프레임 폭과 스케일을 조금 더 보수적으로 줄여 안정성을 높였다.
- 플래너 집중 보기 반응형 기준은 `1620px 이상: 우측 패널 2열`, `1280px 이상 ~ 1619px 이하: 우측 패널 1열 + 최대 360px`, `1280px 미만: 우측 패널 오버레이` 구조로 다시 정리했다.
- 오버레이 구간에서는 본문 오른쪽 위의 `OPEN SIDE PANEL` 버튼으로 패널을 열고, 배경 클릭이나 `CLOSE` 버튼으로 닫는다.
- `2 PAGE SPREAD`는 화면 폭을 기준으로 배율을 자동 계산해서 오른쪽 페이지가 잘리는 현상을 줄이는 방향으로 조정했다.
- `1280px` 미만에서는 왼쪽 내비게이션도 본문 위에 쌓이지 않고 `MENU` 버튼으로 여는 드로어형 패널로 전환된다.
- 태블릿/모바일 구간에서는 `왼쪽 내비게이션 드로어 + 오른쪽 정보 패널 오버레이 + 본문 단일 컬럼` 조합으로 보는 흐름을 기본값으로 삼는다.
- 통계 화면과 우측 `FOCUSED TIME` 요약처럼 사용자에게 보여주는 집중 시간 표기는 `00H 00M` 대신 `00시간 00분` 한글 형식으로 바꿨다.
- 좌측 메뉴 드로어와 우측 정보 패널 오버레이는 이제 열고 닫힐 때 페이드 + 슬라이드 애니메이션이 적용된다.
- 모바일처럼 좁은 화면에서는 본문 래퍼 패딩을 조금 줄이고, 우측 패널 열기 버튼 문구를 `INFO`로 축약해 밀도를 낮췄다.
- 플래너 본문은 작은 화면에서 상단 정보 영역이 세로로 쌓이고, `TIME TABLE`이 아래로 내려가도록 조정했다.
- 모바일 구간에서는 TASKS / MEMO 행 높이와 좌우 패딩을 조금 줄여 입력 밀도를 낮췄고, 타임테이블은 필요할 때만 최소 가로 스크롤이 생기도록 바뀌었다.
- 미니 달력은 모바일 구간에서 패딩, 월 이동 버튼, 요일 헤더, 날짜 셀 크기를 한 단계 더 줄여서 카드 내부 밀도를 정리했다.
- 연도 선택 팝오버는 좁은 화면에서 카드 전체 폭을 활용하고, 넓은 화면에서는 기존 우측 드롭다운 폭을 유지한다.
- 플래너 본문 안의 `TOTAL TIME` 라벨도 `총 시간`으로 바꿔서 영어 라벨을 줄였다.
- 사용자 노출 메뉴 문구는 `보기 방식 / 날짜 이동 / 인쇄 / 1페이지 + 정보 / 2페이지 펼침 / 이전 날 / 다음 날 / 1장 인쇄 / 2장 인쇄`처럼 한글 중심으로 정리하기 시작했다.
- 2페이지 펼침 보기 배율 계산에서 데스크톱 여유 폭을 더 보수적으로 잡아, `1920px` 근처에서 우측 페이지가 잘려 가로 스크롤이 생기던 문제를 줄이는 방향으로 조정했다.
- 달력 날짜 버튼은 셀 안쪽에 고정 크기 원형 버튼으로 다시 배치해서 모바일에서 서로 겹쳐 보이는 현상을 줄였다.
- 좌측 상단 소개 영역은 개발 설명 문장을 빼고, 서비스 소개용 짧은 카피와 배지 스타일로 다시 구성했다.
- 달력 날짜 버튼은 의도상 원형이며, 현재는 `size` 고정 기준으로 다시 맞춰서 타원처럼 보이는 인상을 줄이는 방향으로 정리했다.
- 플래너 본문, 2페이지 펼침, 인쇄 전용 `PlannerPage` 모두 `총 시간` 값은 `00시간 00분` 한글 포맷으로 통일했다.
- 모바일 대응 이후 인쇄에서 `TIME TABLE`이 사라지던 문제를 막기 위해, print 시에는 `PlannerPage` 내부 레이아웃을 다시 가로 배치로 고정하고 타임테이블 오버플로를 해제하도록 보정했다.
- 인쇄 레이아웃은 추가로 미세 조정해 `COMMENT` 영역이 잘리지 않도록 textarea 높이/행간을 print 전용으로 풀고, `1-UP` / `2-UP` 배율도 프레임 실측 기준으로 다시 계산했다.
- `TODO.md`는 중복 체크 항목을 정리했고, 인증 확장을 위해 `이메일 인증 / 비밀번호 재설정 / rate limit / 메일 인프라` 작업을 별도 항목으로 추가했다.
- 메일 발송은 현재 Resend 기준으로 운영한다. 도메인 정책이나 플랜 조건이 실제 운영과 어긋나는 시점이 오면 그때 대체 수단을 재검토한다.
- 현재 인증 메일/재설정 메일은 실제 발송 대신 개발용 `previewUrl`을 응답으로 돌려주는 단계다. 프론트 UI 연결과 실제 메일러 연결은 다음 단계에서 마무리하면 된다.
- 미니 달력 날짜 버튼은 원형 비율이 흔들리지 않도록 고정 `width/height` 기준으로 다시 맞췄다.
- 플래너 본문 D-DAY 텍스트는 3줄까지만 보이고, 넘치면 말줄임 처리되도록 정리했다.
- 목표가 없는 빈 날짜에서는 `D-DAY 사용` 토글이 저장 상태와 무관하게 `OFF + 비활성`처럼 보이도록 보정했다.
- 관리자 전용 `ADMIN` 메뉴와 기본 대시보드가 추가되었다. 현재는 사용자 수, 최근 접속, 문서 수, 목표 수, 계정별 최종 접속일을 읽기 전용으로 확인할 수 있다.
- `users` 테이블에 `login_id`, `role`, `last_login_at` 컬럼이 추가되었다.
- 관리자 계정은 이제 이메일이 아니라 별도 자동 생성 계정으로 관리한다.
- 관리자 계정은 서버 시작 시 `ADMIN_ACCOUNT_ID`, `ADMIN_ACCOUNT_PASSWORD`, `ADMIN_ACCOUNT_EMAIL`, `ADMIN_ACCOUNT_NICKNAME` 환경변수 조합으로 자동 생성된다.
- 관리자 아이디와 비밀번호는 저장소 문서에 실제 값을 남기지 않고, Docker 배포 시 루트 `.env` 같은 비공개 환경변수 파일에서만 관리한다.
- 관리자 대시보드는 현재 읽기 전용이며, 계정 정지/삭제/강제 로그아웃 같은 실제 운영 액션은 아직 없다.
- 배포용 `docker-compose.yml`은 현재 PostgreSQL 외부 포트 `45432`, 프론트 외부 포트 `48081` 기준이며, DB 계정/비밀번호는 루트 `.env`에서 주입한다.
- 설정 화면의 보조 메모 카드는 주석 처리되어 현재는 보이지 않는다.
- 비로그인 랜딩 카드는 상단 고정이 아니라 화면 중앙에 오도록 정렬을 수정했다.
- 로그인/회원가입 문구와 플레이스홀더는 일반 사용자 기준으로 정리했고, 사이드바 계정 카드의 `ADMIN/USER` 역할 텍스트는 숨겼다.
- 오른쪽 정보 패널에 `미완료 항목 이월` 버튼을 추가했다. 현재 날짜의 체크 안 된 할 일을 다음 날짜의 비어 있는 할 일 칸에 순서대로 복사한다.
- TASK 체크 버튼은 키보드 탭 이동 시 focus ring이 보이도록 개선했다. TASK 행은 클릭만으로 선택되지 않고, 포인터를 누른 채 다른 행까지 드래그했을 때부터 전역 pointer move 기준으로 여러 행을 선택한다. input에서 드래그를 시작해도 두 번째 행으로 넘어가면 기존 input 포커스를 blur 처리해 `Delete` / `Backspace`는 선택한 할 일 제목과 체크 상태를 한 번에 비우고, `Escape`는 선택만 해제하도록 했다.
- 인쇄 전용 CSS에서 COMMENT와 총 시간 영역의 폭을 고정하고 textarea overflow를 숨겨, PRINT 시 COMMENT가 우측 시간 영역과 겹치지 않도록 보정했다.
- 오른쪽 패널의 `TASK LABELS``D-DAY 사용`은 한 카드 안의 두 줄 토글로 압축했다. 설명 문구는 공통 `GuideTooltip` 컴포넌트로 옮겼고, 물음표 버튼 클릭으로 열고 다시 클릭하거나 외부 클릭으로 닫는다. 각 툴팁은 `더 이상 보지 않기`로 숨길 수 있으며 SETTINGS의 `가이드 다시 보기`에서 전체 복원할 수 있다.
- 오른쪽 패널의 `READ NEXT``PREV SNAPSHOT`은 별도 가로 카드가 아니라 `NEXT DAY` 카드 아래쪽에 세로로 배치했다.
- READ NEXT는 내일 첫 작업과 오늘 미처리 할 일 개수만 보여주도록 줄였고, 오늘 코멘트 반복 노출은 제거했다.
- 플래너 본문 시간 라벨은 `총 시간`에서 `FOCUSED TIME`으로 바꿨다. 인쇄 CSS에서 COMMENT/FOCUSED TIME 라벨이 잘리지 않도록 부모 overflow를 열고, COMMENT는 남는 폭을 채우며 FOCUSED TIME은 오른쪽 210px 칸에 붙도록 조정했다.
- Docker 배포용 루트 `.env`와 개발용 `.env.dev`를 분리했다. `docker-compose.yml`은 운영 `.env`, `docker-compose.dev.yml`은 기존 dev Postgres 볼륨과 맞는 `.env.dev`를 읽는다.
- STATS의 `RANGE FLOW`는 항목 수에 따라 막대 폭과 간격을 조정한다. 1주일 내외는 넓은 막대로 카드 폭을 채우고, 1달 내외는 좁은 막대와 요약 라벨로 한 화면에서 흐름을 보며, 세부 날짜와 집중 시간은 막대 hover 팝업으로 확인한다.
- 왼쪽 사이드바의 인쇄 영역은 `PRINT` 버튼 하나로 줄이고, 클릭 시 모달에서 시작일/종료일과 `1페이지씩` 또는 `2페이지씩` 출력 방식을 선택한다. 인쇄 전용 렌더링은 선택 기간의 날짜를 순서대로 여러 장 생성하며, 2페이지씩 출력에서 홀수 날짜가 남으면 오른쪽은 빈 페이지 프레임으로 둔다.
- 회원가입과 프로필 수정 시 이메일뿐 아니라 닉네임 중복도 서버에서 409로 막는다. 비밀번호 재설정 API는 로그인 모달의 `비밀번호 찾기` 흐름과 연결되어 있고, `/reset-password?token=...` URL로 들어오면 새 비밀번호 설정 모드가 열린다. 실제 메일 발송 전까지는 백엔드 응답의 `resetPreviewUrl`을 개발용 링크로 표시한다.
- Resend 메일러가 추가되었다. `RESEND_API_KEY`, `MAIL_FROM_EMAIL`, `MAIL_FROM_NAME`, `APP_BASE_URL` 환경변수를 설정하면 이메일 인증과 비밀번호 재설정 메일을 실제로 발송한다. API 키는 저장소에 커밋하지 말고 루트 `.env`/`.env.dev`에만 넣는다.
- 메일 발송 인프라는 현재 Resend 기준으로 확정했다. 자동 로그아웃 옵션은 플래너를 오래 띄워두는 사용 흐름과 맞지 않아 TODO 대상에서 제외했다.
- 인증/비밀번호 재설정 개발용 링크는 `AUTH_PREVIEW_LINKS=true`일 때만 API 응답에 포함된다. 운영 `.env`는 반드시 `AUTH_PREVIEW_LINKS=false`로 두어야 하며, 현재 예시 파일도 false가 기본값이다.
- 회원가입은 이제 자동 로그인되지 않는다. 인증 메일 발송 후 `이메일 인증 후 로그인` 안내만 보여주고, 일반 사용자는 이메일 인증 전까지 로그인할 수 없다.
- 기존에 발급된 세션이라도 일반 사용자 이메일 인증이 안 되어 있으면 `/api/auth/me` 단계에서 세션을 즉시 폐기한다. 운영 중 인증 정책을 켠 뒤에도 미인증 세션이 남지 않게 하기 위한 장치다.
- 비밀번호 재설정/이메일 인증용 개발 링크는 `AUTH_PREVIEW_LINKS=true`여도 `APP_BASE_URL``localhost` 또는 `127.0.0.1`일 때만 응답에 포함한다. 상용 서버에서 링크가 그대로 보이면 이 조건부터 확인한다.
- 프론트는 `/verify-email?token=...` 진입 시 인증을 바로 확정하고 로그인 모달에 결과 메시지를 띄운다. `/reset-password?token=...`은 기존처럼 비밀번호 재설정 모달을 연다.
- SETTINGS 화면에 일반 사용자 전용 `회원 탈퇴` 카드가 추가되었다. 현재 비밀번호 확인 후 계정, 플래너 기록, 목표, 세션, 인증 토큰이 함께 삭제된다. 기본 관리자 계정은 이 경로에서 삭제하지 못하게 막는다.
- `/api/auth/logout`이 추가되어 로그아웃 시 프론트 저장 토큰만 지우는 것이 아니라 서버 세션도 함께 폐기한다.
- SETTINGS 화면 왼쪽 카드에 현재 기기 로그인 유지 방식(`로그인 유지` 또는 브라우저 세션만 유지), 최근 로그인 시각, 이메일 인증 상태를 보여준다.
- 현재 로그인 유지 방식은 `authPersist` 상태로 함께 들고 가며, 프로필 저장 후에도 원래 저장 방식(localStorage/sessionStorage)을 유지하도록 정리했다.
- `5173` 포트가 직접 `npm run dev` 없이 열려 있으면 대부분 `ten-minute-frontend-dev` 컨테이너가 떠 있는 상태다. 개발용 Docker를 끄려면 `docker compose -f docker-compose.dev.yml down`을 사용한다.
- 현재 환경에서는 Docker 데몬이 꺼져 있어서 `docker compose build` 실검증은 하지 못했고, 데몬 시작 후 다시 확인이 필요하다.
- 이미지 저장 기능은 추후 `print-only` 또는 별도 export 전용 레이아웃을 기준으로 구현하면 화면/인쇄/공유 결과를 맞추기 쉽다.
- Docker Compose는 프론트엔드와 백엔드를 함께 올리는 기준으로 설계하되, NAS 환경에 맞는 볼륨과 재시작 정책도 함께 고려한다.
- Docker Compose 개발/배포 파일에는 `TZ=Asia/Seoul`을 명시해 NAS와 컨테이너 내부 기준 시간이 한국 시간으로 맞도록 유지한다.
- 플래너 본문 라벨은 더 이상 `bg-paper` 배경으로 선을 덮지 않는다. `라벨 + 오른쪽 선` 구조로 바꿔 화면과 인쇄에서 노란 배경이 튀지 않도록 정리했다.
- 날짜에 적용되는 목표가 새로 생기면 D-DAY는 기본 표시된다. 사용자가 해당 날짜에서 직접 `D-DAY 사용`을 끈 경우에만 로컬 숨김 목록에 저장해 다시 숨긴다.
- 비로그인 랜딩은 모바일에서 `카드 안 카드`처럼 보이지 않도록 기능 설명 카드를 얇은 리스트로 단순화했고, `LOGIN` / `SIGN UP` 버튼은 같은 너비와 높이로 맞췄다. 로그인/회원가입 모달도 하단 전환 영역을 별도 카드 대신 구분선 형태로 정리했다.
- 로그인 모달에 `로그인 유지` 체크박스를 추가했다. 기본값은 OFF이며, OFF 상태에서는 인증 토큰을 `sessionStorage`에 저장해 브라우저 세션이 끝나면 사라지고, ON 상태에서만 `localStorage`에 저장한다.
- 현재 로그아웃은 `/api/auth/logout`으로 서버 세션까지 함께 폐기한다. 자동 로그아웃 옵션은 플래너를 오래 열어두는 사용 흐름과 맞지 않아 추가 대상에서 제외했다.
- 비로그인 랜딩에 `DEMO VIEW`를 추가했다. 데모는 실제 저장/로그인 상태와 분리된 읽기 전용 샘플이며, 어제/오늘/내일 3일치 플래너를 전환해서 제품 감각을 먼저 볼 수 있다.
- 플래너 본문 `MEMO``TIME TABLE` 하단 높이를 맞추기 위해 TASK/MEMO 리스트 간격과 행 높이를 조정했다. TASK 드래그 선택 피드백은 레이아웃 흔들림을 줄이도록 ring 대신 배경색만 사용한다.
- 이월된 할 일은 `carryoverFrom` 날짜를 가진다. TASK 본문에는 `이월` 배지를 표시하고, 클릭하면 오른쪽 `READ NEXT` 영역에 원래 시작 날짜를 안내한다.
- 이월된 할 일을 완료할 때는 이전 날짜의 같은 이월 항목까지 모두 체크할지, 현재 날짜만 체크할지 선택한다. 기본값은 `항상 물어보기`이며, SETTINGS의 `CARRYOVER CHECK`에서 `항상 이전까지 체크` / `항상 오늘만 체크`로 바꿀 수 있다.
- 오른쪽 플래너 사이드바의 중복 `STATS` 카드는 제거했다. 미완료 항목 이월 버튼은 `READ NEXT` 카드 아래로 이동했다.
- 통계 화면은 진입 시 END DATE를 오늘로 보정한다. `최근 1주`, `최근 1달` 빠른 선택을 추가했고, 기존 `WEEKLY FLOW`는 선택 범위 안에서 기록이 있는 날짜별 집중 흐름을 보여주는 `RANGE FLOW`로 이름과 라벨을 정리했다.
- `BEST DAY`는 선택 기간 안에서 집중 시간이 가장 긴 날짜를 고르고, `RECENT RECORDS`는 선택 기간 안의 기록을 날짜 내림차순으로 최대 5개 보여준다.
- `CARRYOVER TASK` 선택 모달은 ESC로 닫힌다. 이월 배지의 시작일 안내는 오른쪽 패널 메시지 대신 배지 옆 팝업으로 표시한다.
- 통계의 `BEST DAY`, `RECENT RECORDS` 기준 설명은 본문 문장 대신 물음표 가이드 팝업으로 제공한다.
## 갱신 규칙

189
README.md Normal file
View File

@@ -0,0 +1,189 @@
# 10 Minute Planner
Vue 3 + TailwindCSS + Fastify + PostgreSQL 기반의 `10분 플래너 다이어리` 프로젝트다.
## 시작 전에
이 프로젝트는 `Docker``Docker Compose`가 설치된 환경을 기준으로 실행한다.
NAS나 서버에서 처음 올리는 경우 흐름은 아래처럼 생각하면 된다.
1. 프로젝트를 받을 폴더로 이동한다.
2. `git clone`으로 저장소를 내려받는다.
3. 내려받은 프로젝트 폴더로 들어간다.
4. `docker compose`로 컨테이너를 빌드하고 실행한다.
예시:
```bash
cd /volume1/docker
git clone https://git.sori.studio/zenn/planner.sori.studio.git .
cd planner.sori.studio
cp .env.example .env
docker compose up -d --build
```
처음 한 번은 이미지 빌드 때문에 시간이 걸릴 수 있다.
실행 전에 `.env`의 DB와 관리자 계정 환경변수는 운영자만 아는 값으로 반드시 바꾼다.
## 초보자용 빠른 실행
### 1. 프로젝트 받기
원하는 작업 폴더로 이동한 뒤 저장소를 내려받는다.
```bash
cd /원하는/폴더
git clone https://git.sori.studio/zenn/planner.sori.studio.git
cd planner.sori.studio
```
### 2. 배포용으로 바로 실행하기
실제 동작 확인이나 NAS 상시 실행은 아래 명령으로 시작한다.
```bash
cp .env.example .env
# .env에서 POSTGRES_*, DATABASE_URL, ADMIN_ACCOUNT_* 값을 비공개 운영 값으로 수정한다.
docker compose up -d --build
```
의미:
- `up`: 컨테이너를 실행한다.
- `-d`: 백그라운드에서 실행한다.
- `--build`: 이미지가 없거나 코드가 바뀌었을 때 다시 빌드한다.
브라우저 접속 주소:
- 프론트엔드: `http://NAS주소:48081`
- PostgreSQL: `NAS주소:45432`
관리자 계정은 백엔드 시작 시 `.env``ADMIN_ACCOUNT_*` 값으로 자동 생성된다.
관리자 아이디와 비밀번호는 저장소 문서에 적지 말고, 운영자만 접근 가능한 비공개 환경변수 파일에서 관리한다.
일반 사용자는 회원가입 후 이메일 인증을 완료해야 로그인할 수 있다.
운영 서버에서는 비밀번호 재설정/이메일 인증용 미리보기 링크가 API 응답에 노출되지 않도록 유지한다.
현재 `docker-compose.yml` 기준 내부 구성:
- 프론트엔드 nginx
- 백엔드 Fastify
- PostgreSQL
- 배포/개발 컨테이너 시간대: `Asia/Seoul`
### 3. 실행 상태 확인하기
```bash
docker compose ps
```
로그를 보고 싶으면:
```bash
docker compose logs -f
```
특정 서비스만 보고 싶으면:
```bash
docker compose logs -f frontend
docker compose logs -f backend
docker compose logs -f postgres
```
### 4. 종료하기
```bash
docker compose down
```
데이터베이스 볼륨까지 완전히 지우고 처음부터 다시 시작하고 싶을 때만 아래 명령을 사용한다.
```bash
docker compose down -v
```
주의:
- `-v`는 PostgreSQL 데이터까지 지울 수 있으니 정말 초기화가 필요할 때만 사용한다.
### 5. 코드 수정 후 다시 반영하기
배포용 compose는 코드가 자동 반영되지 않는다.
코드를 수정했다면 프로젝트 폴더 안에서 다시 실행한다.
```bash
docker compose up -d --build
```
즉, NAS에서 배포용으로 돌릴 때는 보통 아래 순서를 반복한다.
```bash
cd /volume1/docker/planner.sori.studio
git pull
docker compose up -d --build
```
## 실행 방법
### 개발용
코드를 수정하면서 자동 새로고침까지 보려면 개발용 compose를 사용한다.
```bash
docker compose -f docker-compose.dev.yml up
```
개발용도 처음 시작할 때는 아래처럼 프로젝트 폴더 안에서 실행하면 된다.
```bash
cd /원하는/폴더
git clone https://git.sori.studio/zenn/planner.sori.studio.git
cd planner.sori.studio
docker compose -f docker-compose.dev.yml up
```
개발용 포트:
- 프론트엔드: `http://localhost:5173`
- 백엔드 API: `http://localhost:3001`
- PostgreSQL: `localhost:5432`
개발용 특징:
- 프론트는 Vite HMR로 저장 즉시 화면이 반영된다.
- 백엔드는 `node --watch`로 파일 변경 시 자동 재시작된다.
- 즉, 개발 중에는 매번 새로 빌드할 필요 없이 `docker compose -f docker-compose.dev.yml up`만 켜두면 된다.
### 배포용
실서비스나 최종 확인용으로는 배포용 compose를 사용한다.
```bash
docker compose up -d --build
```
배포용 포트:
- 프론트엔드: `http://localhost:48081`
- PostgreSQL: `localhost:45432`
배포용 특징:
- 프론트는 빌드 결과물을 nginx로 서빙한다.
- 브라우저에서는 `/api` 경로로 백엔드에 접근한다.
- 수정 사항 반영 시에는 다시 빌드가 필요하다.
## 문서
- 작업 규칙: [`AGENTS.md`](./AGENTS.md)
- 진행 상태 / 체크리스트: [`TODO.md`](./TODO.md)
- 인수인계 메모: [`HANDOFF.md`](./HANDOFF.md)
## 현재 방향
- 기본 UX는 `1페이지 + 우측 정보 패널`
- 보조 모드는 `2페이지 펼침 보기`
- 스타일링은 Vue + TailwindCSS
- 장기적으로는 Docker 기반으로 UGREEN NAS 배포 예정

79
TODO.md
View File

@@ -7,7 +7,7 @@
- 기본 레이아웃은 `1페이지 + 우측 정보 패널`을 유지한다.
- `2페이지 펼침 보기`는 비교용 보조 모드로 유지한다.
- 스타일은 Vue + TailwindCSS 기준으로 구현한다.
- D-DAY는 목표 관리 패널과 연결기능으로 추후 구현한다.
- D-DAY는 목표 관리 패널과 연결구조로 전환했고, 세부 확장은 계속 진행한다.
## 1단계: 플래너 핵심 상호작용
@@ -36,22 +36,29 @@
## 3단계: 목표와 회고 기능
- [ ] 목표 관리 패널 설계한다.
- [ ] 선택한 목표 기준으로 `D-DAY`가 자동 계산되게 한다.
- [ ] 우측 요약 패널의 `PREV SNAPSHOT`, `READ NEXT`를 실제 데이터 기반으로 연결한다.
- [x] 목표 관리 패널 기본 구조를 설계한다.
- [x] 선택한 목표 기준으로 `D-DAY`가 자동 계산되게 한다.
- [x] 우측 요약 패널의 `PREV SNAPSHOT`, `READ NEXT`를 실제 데이터 기반으로 연결한다.
- [ ] 다음날 할 일 자동 제안 규칙을 정리한다.
- [x] 오른쪽 패널에 `D-DAY 사용` 토글과 목표 검색/선택 UI를 추가한다.
- [x] 목표를 여러 개 생성하고 날짜별 대표 목표를 선택할 수 있게 한다.
- [x] 목표 관리 화면을 별도로 분리하고, 플래너에서는 D-DAY 표시 ON/OFF만 제어한다.
- [x] 목표별로 D-DAY 표시 시작일과 종료일을 설정할 수 있게 한다.
- [x] 목표 표시 기간이 서로 겹치면 저장되지 않도록 막는다.
- [ ] 목표 완료 처리와 보관 상태를 구분한다.
- [x] 목표 편집/삭제 UI를 추가한다.
- [ ] 목표 목록 정렬 규칙과 검색 UX를 다듬는다.
## 4단계: 데이터 구조와 저장
- [ ] 플래너 데이터 구조를 날짜별 상태 중심으로 정리한다.
- [x] 플래너 데이터 구조를 날짜별 상태 중심으로 정리한다.
- [x] 입력 데이터의 저장 위치를 결정한다.
- [x] 로컬 저장 또는 외부 저장 방식 중 우선 구현 방식을 정한다.
- [x] 입력 상태가 새로고침 후에도 유지되도록 만든다.
- [x] DB 전환 시점을 잡을 수 있도록 저장 레이어를 분리한다.
- [ ] 회원 가입 및 로그인 구조를 고려한 사용자별 데이터 모델을 설계한다.
- [x] 회원 가입 및 로그인 구조를 고려한 사용자별 데이터 모델을 설계한다.
- [ ] 사용자별 문서 저장/조회 흐름을 정리한다.
- [ ] 출력용 문서 포맷과 프린트 흐름을 고려한 데이터 구조를 정리한다.
- [x] 사용자별 문서 저장/조회 흐름을 정리한다.
- [x] 출력용 문서 포맷과 프린트 흐름을 고려한 데이터 구조를 정리한다.
## 추가 반영 메모
@@ -64,32 +71,68 @@
- [x] 통계 페이지 라우팅 또는 화면 전환 구조를 설계한다.
- [x] 집중 시간, 완료율, 연속 기록 같은 핵심 지표를 정의한다.
- [x] 사용자가 시작일과 종료일을 선택해서 기간별 통계를 볼 수 있게 한다.
- [ ] 사용자 개인 통계 화면 기준을 정리한다.
- [x] 사용자 개인 통계 화면 기준을 정리한다.
## 6단계: 계정 및 서비스 확장
- [ ] 회원 가입 / 로그인 방식 후보를 정리한다.
- [x] 회원 가입 / 로그인 방식 후보를 정리한다.
- [ ] 사용자별 문서 분리 저장 구조를 설계한다.
- [ ] 공유가 아닌 개인 보관용 서비스 흐름으로 요구사항을 정리한다.
- [x] 사용자 설정 화면에서 닉네임 / 이메일 / 비밀번호 수정 흐름을 분리한다.
- [x] 상단 헤더를 왼쪽 사이드 내비게이션 구조로 재배치한다.
- [x] 본문과 오른쪽 패널이 각각 독립 스크롤되도록 조정한다.
- [x] 사용자별 문서 분리 저장 구조를 설계한다.
- [x] 공유가 아닌 개인 보관용 서비스 흐름으로 요구사항을 정리한다.
- [x] 향후 출력 기능을 위한 인쇄 레이아웃 요구사항을 정리한다.
- [x] A4 가로 기준 2장 출력 모드를 지원한다.
- [x] `1-UP` 세로 인쇄 / `2-UP` 가로 인쇄 기준을 분리한다.
- [ ] 공유를 위한 이미지 저장 기능을 추가한다.
- [ ] Docker 배포 구조를 정리한다.
- [ ] UGREEN NAS 기준 `docker-compose.yml` 초안을 작성한다.
- [x] Docker 배포 구조를 정리한다.
- [x] UGREEN NAS 기준 `docker-compose.yml` 초안을 작성한다.
- [x] 백엔드 기본 스캐폴딩을 추가한다.
- [x] PostgreSQL 전환 초안을 적용한다.
- [x] 로그인 화면 문구와 관리자 정보 노출 지점을 일반 사용자 기준으로 정리한다.
- [x] 비로그인 사용자가 저장 없이 볼 수 있는 3일치 샘플 데모 화면을 추가한다.
- [x] 미완료 항목을 다음 날짜 빈칸으로 이월하는 버튼을 추가한다.
- [x] 이월된 할 일에 배지를 표시하고 원래 시작 날짜를 확인할 수 있게 한다.
- [x] 이월된 할 일을 체크할 때 이전 날짜까지 함께 완료할지 선택하는 정책을 추가한다.
- [x] 이메일 인증 플로우를 설계하고 구현한다.
- [x] 비밀번호 찾기 / 재설정 토큰 흐름을 추가한다.
- [ ] 로그인 및 인증 관련 rate limit / 잠금 정책을 추가한다.
- [x] 로그인 유지 여부를 사용자가 선택할 수 있게 한다.
- [x] 설정 화면에서 현재 기기 로그인 상태와 저장 방식을 안내한다.
- [x] 서버 세션을 명시적으로 폐기하는 로그아웃 API를 추가한다.
- [x] 메일 발송 인프라와 발신 도메인 정책을 Resend 기준으로 확정한다.
- [ ] 관리자 페이지에서 계정 비활성화 / 강제 로그아웃 / 삭제 기능을 추가한다.
- [ ] 관리자 페이지에서 사용자별 문서 상세 조회 기능을 추가한다.
- [ ] 관리자 페이지에서 검색 / 정렬 / 필터 UX를 추가한다.
## 메모
- D-DAY는 현재 보류 상태다. 목표 패널 설계 후 연결한다.
- D-DAY는 본문에 직접 입력하는 방식보다, 별도 목표 목록에서 선택한 대표 목표를 보여주는 구조가 더 적합하다.
- 목표가 없는 경우 본문 D-DAY 영역은 숨기고, 오른쪽 패널의 `D-DAY 사용` 메뉴에서 검색/선택하도록 유도한다.
- `TIME TABLE` 드래그는 단순 사각형 선택이 아니라 시간 셀 단위의 연속 선택으로 해석한다.
- 현재는 `localStorage`로 개발을 진행하지만, 적절한 시점에 DB를 붙여 사용자별 저장 구조로 확장해야 한다.
- 현재 `localStorage` 저장 로직은 분리 가능한 형태로 정리 중이며, 이후 API/DB adapter로 교체하기 쉽게 유지한다.
- 로컬 저장은 비로그인/데모 보조 용도로만 남기고, 로그인 상태에서는 사용자별 서버 저장을 우선한다.
- 최종적으로는 회원 가입 후 각자 자신의 문서를 작성/관리하고, 개인 통계를 확인하며, 특정 날짜 문서를 출력할 수 있어야 한다.
- 실제 인쇄는 HTML/CSS 기반 프린트 레이아웃으로 유지하고, 공유용으로는 별도의 이미지 저장 기능을 추가하는 방향이 적합하다.
- 최종 배포는 UGREEN NAS에서 Docker 기반으로 동작할 예정이며, 포트와 실제 서비스 구성은 추후 확정한다.
- 백엔드는 빠른 목업이면 PocketBase도 가능하지만, 현재 방향상 커스텀 로직과 확장성을 생각하면 전용 Node.js API + DB 조합을 우선 검토한다.
- 현재 백엔드는 `backend/` 폴더에 `Fastify + Drizzle + SQLite` 기준 초안이 추가되었다.
- 현재 백엔드는 `backend/` 폴더에 `Fastify + Drizzle + PostgreSQL` 기준으로 전환 중이다.
- 현재 백엔드는 회원가입, 로그인, 현재 사용자 확인용 기본 인증 API까지 포함한다.
- 현재 백엔드는 사용자별 플래너 단건 저장/조회와 범위 조회 API까지 포함한다.
- 현재 백엔드는 사용자별 목표 목록 조회와 목표 생성 API까지 포함한다.
- 현재는 `docker-compose.yml``postgres + backend + frontend(nginx)` 초안을 올릴 수 있게 정리했다.
- 현재 환경에서는 Docker 데몬이 꺼져 있어 `docker compose build` 실검증은 아직 완료하지 못했다.
- 프론트에는 로그인/회원가입 모달과 현재 사용자 상태 표시가 추가되었다.
- 로그인 상태일 때는 서버 저장을 우선 사용하는 흐름으로 전환 중이다.
- 로그인 전에는 플래너 본문을 사용하지 못하도록 막고, 인증 후 사용 흐름으로 정리했다.
- 현재는 각 날짜 플래너가 대표 목표 하나를 선택해 `D-DAY`에 연결하는 구조다.
- 목표는 별도 GOALS 화면에서 검색/생성/기간 설정을 관리하고, 플래너에서는 표시 ON/OFF만 다룬다.
- 목표가 현재 날짜에 적용되지 않았거나 `D-DAY 사용`이 꺼져 있으면 본문 `D-DAY` 영역은 숨긴다.
- 현재 날짜에 적용된 목표가 있으면 D-DAY는 기본적으로 보이고, 사용자가 해당 날짜에서만 OFF로 끌 수 있다.
- 목표 생성 시 표시 시작일 기본값은 오늘, 표시 종료일 기본값은 목표일로 맞춘다.
- 표시 기간이 다른 진행 중 목표와 겹치면 프론트와 백엔드 모두 저장을 막는다.
- 앱을 새로 열면 마지막 열람 날짜가 아니라 항상 오늘 날짜부터 시작하고, Docker/NAS 컨테이너 시간대는 `Asia/Seoul` 기준으로 맞춘다.
- TASK LABELS는 버튼 묶음 대신 동일한 토글 패턴으로 단순화했다.
- 구현할 때마다 완료된 항목은 체크하고, 큰 결정사항은 `HANDOFF.md`에도 함께 반영한다.
- 메일 발송은 현재 Resend 기준으로 운영한다. 무료 플랜/도메인 제약이 바뀌는 시점에만 별도 대체 수단을 다시 검토한다.
- 관리자 기능은 읽기 전용 대시보드부터 시작하고, 실제 정리 액션은 권한/감사 로그 정책을 정한 뒤 추가하는 편이 안전하다.
- 관리자 아이디/비밀번호는 README나 HANDOFF에 실제 값으로 남기지 않고, Docker 배포용 비공개 `.env`에서만 관리한다.

View File

@@ -1,3 +1,8 @@
PORT=3001
DB_FILE=./data/planner.sqlite
DATABASE_URL=postgresql://planner:planner1234@localhost:5432/ten_minute_planner
CORS_ORIGIN=http://localhost:5173
APP_BASE_URL=http://localhost:5173
ADMIN_ACCOUNT_ID=replace-with-private-admin-id
ADMIN_ACCOUNT_PASSWORD=replace-with-private-admin-password
ADMIN_ACCOUNT_EMAIL=admin@example.com
ADMIN_ACCOUNT_NICKNAME=Planner Admin

14
backend/Dockerfile Normal file
View File

@@ -0,0 +1,14 @@
FROM node:22-alpine AS base
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY src ./src
COPY .env.example ./.env.example
COPY drizzle.config.js ./drizzle.config.js
EXPOSE 3001
CMD ["node", "src/server.js"]

View File

@@ -10,8 +10,8 @@ config({ path: path.join(__dirname, '.env') })
export default {
schema: './src/db/schema.js',
out: './drizzle',
dialect: 'sqlite',
dialect: 'postgresql',
dbCredentials: {
url: process.env.DB_FILE ?? './data/planner.sqlite',
url: process.env.DATABASE_URL ?? 'postgresql://planner:planner1234@localhost:5432/ten_minute_planner',
},
}

View File

@@ -9,10 +9,10 @@
"version": "0.1.0",
"dependencies": {
"@fastify/cors": "^10.0.1",
"better-sqlite3": "^11.8.1",
"dotenv": "^16.4.7",
"drizzle-orm": "^0.39.1",
"fastify": "^5.2.1",
"pg": "^8.13.3",
"zod": "^3.24.2"
},
"devDependencies": {
@@ -1083,7 +1083,9 @@
"url": "https://feross.org/support"
}
],
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/better-sqlite3": {
"version": "11.10.0",
@@ -1091,6 +1093,8 @@
"integrity": "sha512-EwhOpyXiOEL/lKzHz9AW1msWFNzGc/z+LzeB3/jnFJpxu+th2yqvzsSWas1v9jgs9+xiXJcD5A8CJxAG2TaghQ==",
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"bindings": "^1.5.0",
"prebuild-install": "^7.1.1"
@@ -1101,6 +1105,8 @@
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
"integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"file-uri-to-path": "1.0.0"
}
@@ -1110,6 +1116,8 @@
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
"integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"buffer": "^5.5.0",
"inherits": "^2.0.4",
@@ -1135,6 +1143,8 @@
}
],
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.1.13"
@@ -1151,7 +1161,9 @@
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz",
"integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==",
"license": "ISC"
"license": "ISC",
"optional": true,
"peer": true
},
"node_modules/cookie": {
"version": "1.1.1",
@@ -1189,6 +1201,8 @@
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
"integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"mimic-response": "^3.1.0"
},
@@ -1204,6 +1218,8 @@
"resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz",
"integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==",
"license": "MIT",
"optional": true,
"peer": true,
"engines": {
"node": ">=4.0.0"
}
@@ -1222,6 +1238,8 @@
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
"integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
"license": "Apache-2.0",
"optional": true,
"peer": true,
"engines": {
"node": ">=8"
}
@@ -1377,6 +1395,8 @@
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"once": "^1.4.0"
}
@@ -1451,6 +1471,8 @@
"resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz",
"integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==",
"license": "(MIT OR WTFPL)",
"optional": true,
"peer": true,
"engines": {
"node": ">=6"
}
@@ -1578,7 +1600,9 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz",
"integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/find-my-way": {
"version": "9.5.0",
@@ -1598,7 +1622,9 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
"integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/gel": {
"version": "2.2.0",
@@ -1638,7 +1664,9 @@
"version": "0.0.0",
"resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz",
"integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/ieee754": {
"version": "1.2.1",
@@ -1658,19 +1686,25 @@
"url": "https://feross.org/support"
}
],
"license": "BSD-3-Clause"
"license": "BSD-3-Clause",
"optional": true,
"peer": true
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"license": "ISC"
"license": "ISC",
"optional": true,
"peer": true
},
"node_modules/ini": {
"version": "1.3.8",
"resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz",
"integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==",
"license": "ISC"
"license": "ISC",
"optional": true,
"peer": true
},
"node_modules/ipaddr.js": {
"version": "2.3.0",
@@ -1758,6 +1792,8 @@
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
"integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
"license": "MIT",
"optional": true,
"peer": true,
"engines": {
"node": ">=10"
},
@@ -1770,6 +1806,8 @@
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"license": "MIT",
"optional": true,
"peer": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
@@ -1778,7 +1816,9 @@
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz",
"integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/mnemonist": {
"version": "0.40.0",
@@ -1800,13 +1840,17 @@
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
"integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/node-abi": {
"version": "3.89.0",
"resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.89.0.tgz",
"integrity": "sha512-6u9UwL0HlAl21+agMN3YAMXcKByMqwGx+pq+P76vii5f7hTPtKDp08/H9py6DY+cfDw7kQNTGEj/rly3IgbNQA==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"semver": "^7.3.5"
},
@@ -1834,10 +1878,101 @@
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"license": "ISC",
"optional": true,
"peer": true,
"dependencies": {
"wrappy": "1"
}
},
"node_modules/pg": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.20.0.tgz",
"integrity": "sha512-ldhMxz2r8fl/6QkXnBD3CR9/xg694oT6DZQ2s6c/RI28OjtSOpxnPrUCGOBJ46RCUxcWdx3p6kw/xnDHjKvaRA==",
"license": "MIT",
"dependencies": {
"pg-connection-string": "^2.12.0",
"pg-pool": "^3.13.0",
"pg-protocol": "^1.13.0",
"pg-types": "2.2.0",
"pgpass": "1.0.5"
},
"engines": {
"node": ">= 16.0.0"
},
"optionalDependencies": {
"pg-cloudflare": "^1.3.0"
},
"peerDependencies": {
"pg-native": ">=3.0.1"
},
"peerDependenciesMeta": {
"pg-native": {
"optional": true
}
}
},
"node_modules/pg-cloudflare": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.3.0.tgz",
"integrity": "sha512-6lswVVSztmHiRtD6I8hw4qP/nDm1EJbKMRhf3HCYaqud7frGysPv7FYJ5noZQdhQtN2xJnimfMtvQq21pdbzyQ==",
"license": "MIT",
"optional": true
},
"node_modules/pg-connection-string": {
"version": "2.12.0",
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.12.0.tgz",
"integrity": "sha512-U7qg+bpswf3Cs5xLzRqbXbQl85ng0mfSV/J0nnA31MCLgvEaAo7CIhmeyrmJpOr7o+zm0rXK+hNnT5l9RHkCkQ==",
"license": "MIT"
},
"node_modules/pg-int8": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
"license": "ISC",
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/pg-pool": {
"version": "3.13.0",
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.13.0.tgz",
"integrity": "sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==",
"license": "MIT",
"peerDependencies": {
"pg": ">=8.0"
}
},
"node_modules/pg-protocol": {
"version": "1.13.0",
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.13.0.tgz",
"integrity": "sha512-zzdvXfS6v89r6v7OcFCHfHlyG/wvry1ALxZo4LqgUoy7W9xhBDMaqOuMiF3qEV45VqsN6rdlcehHrfDtlCPc8w==",
"license": "MIT"
},
"node_modules/pg-types": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
"license": "MIT",
"dependencies": {
"pg-int8": "1.0.1",
"postgres-array": "~2.0.0",
"postgres-bytea": "~1.0.0",
"postgres-date": "~1.0.4",
"postgres-interval": "^1.1.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/pgpass": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
"license": "MIT",
"dependencies": {
"split2": "^4.1.0"
}
},
"node_modules/pino": {
"version": "10.3.1",
"resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz",
@@ -1875,12 +2010,53 @@
"integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",
"license": "MIT"
},
"node_modules/postgres-array": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/postgres-bytea": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-date": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/postgres-interval": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
"license": "MIT",
"dependencies": {
"xtend": "^4.0.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/prebuild-install": {
"version": "7.1.3",
"resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz",
"integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==",
"deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"detect-libc": "^2.0.0",
"expand-template": "^2.0.3",
@@ -1923,6 +2099,8 @@
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
@@ -1939,6 +2117,8 @@
"resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz",
"integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==",
"license": "(BSD-2-Clause OR MIT OR Apache-2.0)",
"optional": true,
"peer": true,
"dependencies": {
"deep-extend": "^0.6.0",
"ini": "~1.3.0",
@@ -1954,6 +2134,8 @@
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
@@ -2034,7 +2216,9 @@
"url": "https://feross.org/support"
}
],
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/safe-regex2": {
"version": "5.1.1",
@@ -2132,7 +2316,9 @@
"url": "https://feross.org/support"
}
],
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/simple-get": {
"version": "4.0.1",
@@ -2153,6 +2339,8 @@
}
],
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"decompress-response": "^6.0.0",
"once": "^1.3.1",
@@ -2203,6 +2391,8 @@
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"safe-buffer": "~5.2.0"
}
@@ -2212,6 +2402,8 @@
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz",
"integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==",
"license": "MIT",
"optional": true,
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -2221,6 +2413,8 @@
"resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz",
"integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"chownr": "^1.1.1",
"mkdirp-classic": "^0.5.2",
@@ -2233,6 +2427,8 @@
"resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
"integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"bl": "^4.0.3",
"end-of-stream": "^1.4.1",
@@ -2270,6 +2466,8 @@
"resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz",
"integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==",
"license": "Apache-2.0",
"optional": true,
"peer": true,
"dependencies": {
"safe-buffer": "^5.0.1"
},
@@ -2281,7 +2479,9 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/which": {
"version": "4.0.0",
@@ -2303,7 +2503,18 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
"license": "ISC",
"optional": true,
"peer": true
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
"license": "MIT",
"engines": {
"node": ">=0.4"
}
},
"node_modules/zod": {
"version": "3.25.76",

View File

@@ -11,10 +11,10 @@
},
"dependencies": {
"@fastify/cors": "^10.0.1",
"better-sqlite3": "^11.8.1",
"dotenv": "^16.4.7",
"drizzle-orm": "^0.39.1",
"fastify": "^5.2.1",
"pg": "^8.13.3",
"zod": "^3.24.2"
},
"devDependencies": {

View File

@@ -10,9 +10,18 @@ config({ path: path.join(__dirname, '..', '.env') })
const envSchema = z.object({
PORT: z.coerce.number().default(3001),
DB_FILE: z.string().default('./data/planner.sqlite'),
DATABASE_URL: z.string().min(1).default('postgresql://planner:planner1234@localhost:5432/ten_minute_planner'),
CORS_ORIGIN: z.string().default('http://localhost:5173'),
SESSION_TTL_DAYS: z.coerce.number().default(30),
APP_BASE_URL: z.string().default('http://localhost:5173'),
RESEND_API_KEY: z.string().optional(),
MAIL_FROM_EMAIL: z.string().email().default('planner@sori.studio'),
MAIL_FROM_NAME: z.string().default('10 Minute Planner'),
AUTH_PREVIEW_LINKS: z.coerce.boolean().default(false),
ADMIN_ACCOUNT_ID: z.string().min(1),
ADMIN_ACCOUNT_PASSWORD: z.string().min(12),
ADMIN_ACCOUNT_EMAIL: z.string().email(),
ADMIN_ACCOUNT_NICKNAME: z.string().min(1),
})
export const env = envSchema.parse(process.env)

View File

@@ -1,17 +1,12 @@
import fs from 'node:fs'
import path from 'node:path'
import Database from 'better-sqlite3'
import { drizzle } from 'drizzle-orm/better-sqlite3'
import { drizzle } from 'drizzle-orm/node-postgres'
import pg from 'pg'
import { env } from '../config.js'
import * as schema from './schema.js'
function ensureDatabaseDirectory(dbFile) {
const absoluteDbPath = path.resolve(dbFile)
fs.mkdirSync(path.dirname(absoluteDbPath), { recursive: true })
return absoluteDbPath
}
const { Pool } = pg
const sqlite = new Database(ensureDatabaseDirectory(env.DB_FILE))
export const pool = new Pool({
connectionString: env.DATABASE_URL,
})
export const db = drizzle(sqlite, { schema })
export { sqlite }
export const db = drizzle(pool, { schema })

View File

@@ -1,36 +1,95 @@
import { sqlite } from './client.js'
import { pool } from './client.js'
export function ensureDatabaseSchema() {
sqlite.exec(`
export async function ensureDatabaseSchema() {
await pool.query(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
nickname TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
id SERIAL PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
login_id VARCHAR(60) UNIQUE,
password_hash VARCHAR(255) NOT NULL,
nickname VARCHAR(60) NOT NULL,
role VARCHAR(20) NOT NULL DEFAULT 'user',
email_verified_at TIMESTAMPTZ,
last_login_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
ALTER TABLE users
ADD COLUMN IF NOT EXISTS login_id VARCHAR(60);
ALTER TABLE users
ADD COLUMN IF NOT EXISTS role VARCHAR(20) NOT NULL DEFAULT 'user';
ALTER TABLE users
ADD COLUMN IF NOT EXISTS email_verified_at TIMESTAMPTZ;
ALTER TABLE users
ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
CREATE TABLE IF NOT EXISTS auth_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(255) NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS auth_sessions_user_id_idx
ON auth_sessions (user_id);
CREATE TABLE IF NOT EXISTS planner_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
entry_date TEXT NOT NULL,
payload TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
entry_date VARCHAR(10) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS planner_entries_user_date_unique
ON planner_entries (user_id, entry_date);
CREATE INDEX IF NOT EXISTS planner_entries_user_id_idx
ON planner_entries (user_id);
CREATE TABLE IF NOT EXISTS goals (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(120) NOT NULL,
target_date VARCHAR(10) NOT NULL,
active_from VARCHAR(10),
active_until VARCHAR(10),
color VARCHAR(32) NOT NULL DEFAULT '#1c1917',
created_at TIMESTAMPTZ NOT NULL,
updated_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS goals_user_id_idx
ON goals (user_id);
CREATE TABLE IF NOT EXISTS email_verification_tokens (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(255) NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS email_verification_tokens_user_id_idx
ON email_verification_tokens (user_id);
CREATE TABLE IF NOT EXISTS password_reset_tokens (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(255) NOT NULL UNIQUE,
expires_at TIMESTAMPTZ NOT NULL,
used_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS password_reset_tokens_user_id_idx
ON password_reset_tokens (user_id);
`)
}

View File

@@ -1,27 +1,101 @@
import { integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'
import {
integer,
index,
jsonb,
pgTable,
serial,
timestamp,
uniqueIndex,
varchar,
} from 'drizzle-orm/pg-core'
export const users = sqliteTable('users', {
id: integer('id').primaryKey({ autoIncrement: true }),
email: text('email').notNull().unique(),
passwordHash: text('password_hash').notNull(),
nickname: text('nickname').notNull(),
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
export const users = pgTable('users', {
id: serial('id').primaryKey(),
email: varchar('email', { length: 255 }).notNull().unique(),
loginId: varchar('login_id', { length: 60 }).unique(),
passwordHash: varchar('password_hash', { length: 255 }).notNull(),
nickname: varchar('nickname', { length: 60 }).notNull(),
role: varchar('role', { length: 20 }).notNull().default('user'),
emailVerifiedAt: timestamp('email_verified_at', { withTimezone: true }),
lastLoginAt: timestamp('last_login_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull(),
})
export const authSessions = sqliteTable('auth_sessions', {
id: integer('id').primaryKey({ autoIncrement: true }),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
tokenHash: text('token_hash').notNull().unique(),
expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
})
export const authSessions = pgTable(
'auth_sessions',
{
id: serial('id').primaryKey(),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
tokenHash: varchar('token_hash', { length: 255 }).notNull().unique(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
},
(table) => ({
userIndex: index('auth_sessions_user_id_idx').on(table.userId),
}),
)
export const plannerEntries = sqliteTable('planner_entries', {
id: integer('id').primaryKey({ autoIncrement: true }),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
entryDate: text('entry_date').notNull(),
payload: text('payload').notNull(),
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
})
export const plannerEntries = pgTable(
'planner_entries',
{
id: serial('id').primaryKey(),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
entryDate: varchar('entry_date', { length: 10 }).notNull(),
payload: jsonb('payload').notNull(),
createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull(),
},
(table) => ({
userDateUnique: uniqueIndex('planner_entries_user_date_unique').on(table.userId, table.entryDate),
userIndex: index('planner_entries_user_id_idx').on(table.userId),
}),
)
export const goals = pgTable(
'goals',
{
id: serial('id').primaryKey(),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
title: varchar('title', { length: 120 }).notNull(),
targetDate: varchar('target_date', { length: 10 }).notNull(),
activeFrom: varchar('active_from', { length: 10 }),
activeUntil: varchar('active_until', { length: 10 }),
color: varchar('color', { length: 32 }).notNull().default('#1c1917'),
createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull(),
},
(table) => ({
userIndex: index('goals_user_id_idx').on(table.userId),
}),
)
export const emailVerificationTokens = pgTable(
'email_verification_tokens',
{
id: serial('id').primaryKey(),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
tokenHash: varchar('token_hash', { length: 255 }).notNull().unique(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
usedAt: timestamp('used_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
},
(table) => ({
userIndex: index('email_verification_tokens_user_id_idx').on(table.userId),
}),
)
export const passwordResetTokens = pgTable(
'password_reset_tokens',
{
id: serial('id').primaryKey(),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
tokenHash: varchar('token_hash', { length: 255 }).notNull().unique(),
expiresAt: timestamp('expires_at', { withTimezone: true }).notNull(),
usedAt: timestamp('used_at', { withTimezone: true }),
createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
},
(table) => ({
userIndex: index('password_reset_tokens_user_id_idx').on(table.userId),
}),
)

View File

@@ -0,0 +1,69 @@
import { and, eq, isNull, ne, or } from 'drizzle-orm'
import { env } from '../config.js'
import { db } from '../db/client.js'
import { users } from '../db/schema.js'
import { hashPassword } from './password.js'
export async function ensureAdminAccount() {
const loginId = env.ADMIN_ACCOUNT_ID.trim()
const email = env.ADMIN_ACCOUNT_EMAIL.trim().toLowerCase()
const nickname = env.ADMIN_ACCOUNT_NICKNAME.trim()
const password = env.ADMIN_ACCOUNT_PASSWORD
const now = new Date()
await db
.update(users)
.set({
role: 'user',
updatedAt: now,
})
.where(
and(
eq(users.role, 'admin'),
or(
ne(users.loginId, loginId),
isNull(users.loginId),
),
),
)
const [existingAdmin] = await db
.select()
.from(users)
.where(
or(
eq(users.loginId, loginId),
eq(users.email, email),
),
)
.limit(1)
if (existingAdmin) {
await db
.update(users)
.set({
email,
nickname,
role: 'admin',
updatedAt: now,
})
.where(eq(users.id, existingAdmin.id))
return
}
const passwordHash = await hashPassword(password)
await db.insert(users).values({
email,
loginId,
passwordHash,
nickname,
role: 'admin',
emailVerifiedAt: now,
lastLoginAt: null,
createdAt: now,
updatedAt: now,
})
}

View File

@@ -0,0 +1,88 @@
import { eq } from 'drizzle-orm'
import { env } from '../config.js'
import { db } from '../db/client.js'
import { authSessions, users } from '../db/schema.js'
import { createSessionToken, hashSessionToken } from './password.js'
function getBearerToken(request) {
const authorization = request.headers.authorization
if (!authorization?.startsWith('Bearer ')) {
return null
}
return authorization.slice('Bearer '.length).trim()
}
export function getSessionTokenFromRequest(request) {
return getBearerToken(request)
}
export async function createSession(userId) {
const token = createSessionToken()
const tokenHash = hashSessionToken(token)
const now = Date.now()
const expiresAt = now + env.SESSION_TTL_DAYS * 24 * 60 * 60 * 1000
const [session] = await db
.insert(authSessions)
.values({
userId,
tokenHash,
expiresAt: new Date(expiresAt),
createdAt: new Date(now),
})
.returning()
return {
token,
session,
}
}
export async function findAuthenticatedUser(request) {
const token = getBearerToken(request)
if (!token) {
return null
}
const tokenHash = hashSessionToken(token)
const [session] = await db
.select()
.from(authSessions)
.where(eq(authSessions.tokenHash, tokenHash))
.limit(1)
if (!session || new Date(session.expiresAt).getTime() <= Date.now()) {
return null
}
const [user] = await db
.select()
.from(users)
.where(eq(users.id, session.userId))
.limit(1)
if (user && user.role !== 'admin' && !user.emailVerifiedAt) {
await db.delete(authSessions).where(eq(authSessions.id, session.id))
return null
}
return user ?? null
}
export async function revokeSessionByToken(token) {
if (!token) {
return false
}
const tokenHash = hashSessionToken(token)
const deletedSessions = await db
.delete(authSessions)
.where(eq(authSessions.tokenHash, tokenHash))
.returning({ id: authSessions.id })
return deletedSessions.length > 0
}

89
backend/src/lib/mailer.js Normal file
View File

@@ -0,0 +1,89 @@
import { env } from '../config.js'
const RESEND_API_URL = 'https://api.resend.com/emails'
function getFromAddress() {
return `${env.MAIL_FROM_NAME} <${env.MAIL_FROM_EMAIL}>`
}
async function sendWithResend({ to, subject, html, text }) {
if (!env.RESEND_API_KEY) {
return {
skipped: true,
reason: 'RESEND_API_KEY is not configured.',
}
}
const response = await fetch(RESEND_API_URL, {
method: 'POST',
headers: {
Authorization: `Bearer ${env.RESEND_API_KEY}`,
'Content-Type': 'application/json',
'User-Agent': 'ten-minute-planner/1.0',
},
body: JSON.stringify({
from: getFromAddress(),
to,
subject,
html,
text,
}),
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
throw new Error(data.message || data.error?.message || 'Resend 메일 발송에 실패했습니다.')
}
return {
skipped: false,
id: data.id,
}
}
function buildLinkHtml({ title, description, linkUrl, buttonLabel }) {
return `
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; color: #1c1917; line-height: 1.6;">
<p style="font-size: 12px; letter-spacing: 0.18em; text-transform: uppercase; color: #78716c;">10 Minute Planner</p>
<h1 style="font-size: 24px; margin: 12px 0;">${title}</h1>
<p style="font-size: 15px; color: #57534e;">${description}</p>
<p style="margin: 24px 0;">
<a href="${linkUrl}" style="display: inline-block; border-radius: 999px; background: #1c1917; color: #ffffff; padding: 12px 18px; font-size: 13px; font-weight: 700; text-decoration: none;">
${buttonLabel}
</a>
</p>
<p style="font-size: 12px; color: #78716c;">버튼이 열리지 않으면 아래 링크를 복사해서 브라우저에 붙여넣어 주세요.</p>
<p style="font-size: 12px; word-break: break-all; color: #57534e;">${linkUrl}</p>
<p style="font-size: 12px; color: #a8a29e;">이 링크는 30분 동안 사용할 수 있습니다.</p>
</div>
`
}
export function sendVerificationEmail({ to, linkUrl }) {
return sendWithResend({
to,
subject: '[10 Minute Planner] 이메일 인증',
html: buildLinkHtml({
title: '이메일 인증을 완료해 주세요.',
description: '아래 버튼을 눌러 10 Minute Planner 계정의 이메일 인증을 완료할 수 있습니다.',
linkUrl,
buttonLabel: '이메일 인증하기',
}),
text: `10 Minute Planner 이메일 인증 링크입니다.\n${linkUrl}\n이 링크는 30분 동안 사용할 수 있습니다.`,
})
}
export function sendPasswordResetEmail({ to, linkUrl }) {
return sendWithResend({
to,
subject: '[10 Minute Planner] 비밀번호 재설정',
html: buildLinkHtml({
title: '비밀번호를 재설정해 주세요.',
description: '아래 버튼을 눌러 새 비밀번호를 설정할 수 있습니다. 요청하지 않았다면 이 메일은 무시해 주세요.',
linkUrl,
buttonLabel: '비밀번호 재설정',
}),
text: `10 Minute Planner 비밀번호 재설정 링크입니다.\n${linkUrl}\n요청하지 않았다면 이 메일은 무시해 주세요.`,
})
}

103
backend/src/routes/admin.js Normal file
View File

@@ -0,0 +1,103 @@
import { sql } from 'drizzle-orm'
import { db } from '../db/client.js'
import { findAuthenticatedUser } from '../lib/authSession.js'
import { users } from '../db/schema.js'
async function requireAdminUser(request, reply) {
const user = await findAuthenticatedUser(request)
if (!user) {
reply.code(401).send({
message: '인증이 필요합니다.',
})
return null
}
if (user.role !== 'admin') {
reply.code(403).send({
message: '관리자만 접근할 수 있습니다.',
})
return null
}
return user
}
export async function registerAdminRoutes(app) {
app.get('/api/admin/overview', async (request, reply) => {
const adminUser = await requireAdminUser(request, reply)
if (!adminUser) {
return
}
const [summary] = await db
.select({
totalUsers: sql`count(*)::int`,
totalAdmins: sql`count(*) filter (where ${users.role} = 'admin')::int`,
verifiedUsers: sql`count(*) filter (where ${users.emailVerifiedAt} is not null)::int`,
activeUsers30d: sql`count(*) filter (where ${users.lastLoginAt} >= now() - interval '30 days')::int`,
newUsers7d: sql`count(*) filter (where ${users.createdAt} >= now() - interval '7 days')::int`,
})
.from(users)
const plannerCountResult = await db.execute(
sql`select count(*)::int as count from planner_entries`,
)
const goalCountResult = await db.execute(
sql`select count(*)::int as count from goals`,
)
const userRowsResult = await db.execute(sql`
select
u.id,
u.nickname,
u.email,
u.role,
u.created_at as "createdAt",
u.email_verified_at as "emailVerifiedAt",
u.last_login_at as "lastLoginAt",
count(distinct pe.id)::int as "plannerEntryCount",
count(distinct g.id)::int as "goalCount",
max(pe.entry_date) as "lastEntryDate",
max(pe.updated_at) as "lastEntryUpdatedAt"
from users u
left join planner_entries pe on pe.user_id = u.id
left join goals g on g.user_id = u.id
group by u.id
order by coalesce(u.last_login_at, u.created_at) desc, u.id desc
`)
const recentLoginsResult = await db.execute(sql`
select
id,
nickname,
email,
role,
last_login_at as "lastLoginAt"
from users
where last_login_at is not null
order by last_login_at desc
limit 5
`)
return {
summary: {
totalUsers: summary?.totalUsers ?? 0,
totalAdmins: summary?.totalAdmins ?? 0,
verifiedUsers: summary?.verifiedUsers ?? 0,
activeUsers30d: summary?.activeUsers30d ?? 0,
newUsers7d: summary?.newUsers7d ?? 0,
totalPlannerEntries: plannerCountResult.rows[0]?.count ?? 0,
totalGoals: goalCountResult.rows[0]?.count ?? 0,
},
users: userRowsResult.rows.map((row) => ({
...row,
isActiveRecently: row.lastLoginAt
? new Date(row.lastLoginAt).getTime() >= Date.now() - 30 * 24 * 60 * 60 * 1000
: false,
})),
recentLogins: recentLoginsResult.rows,
}
})
}

View File

@@ -1,14 +1,11 @@
import { eq } from 'drizzle-orm'
import { and, eq, gt, isNull, or } from 'drizzle-orm'
import { z } from 'zod'
import { db } from '../db/client.js'
import { authSessions, users } from '../db/schema.js'
import { authSessions, emailVerificationTokens, passwordResetTokens, users } from '../db/schema.js'
import { createSessionToken, hashSessionToken, hashPassword, verifyPassword } from '../lib/password.js'
import { createSession, findAuthenticatedUser, getSessionTokenFromRequest, revokeSessionByToken } from '../lib/authSession.js'
import { sendPasswordResetEmail, sendVerificationEmail } from '../lib/mailer.js'
import { env } from '../config.js'
import {
createSessionToken,
hashPassword,
hashSessionToken,
verifyPassword,
} from '../lib/password.js'
const signupSchema = z.object({
email: z.string().trim().email(),
@@ -17,75 +14,125 @@ const signupSchema = z.object({
})
const loginSchema = z.object({
email: z.string().trim().email(),
email: z.string().trim().min(1).max(255),
password: z.string().min(1).max(72),
})
const profileSchema = z.object({
email: z.string().trim().email(),
nickname: z.string().trim().min(2).max(30),
})
const passwordSchema = z.object({
currentPassword: z.string().min(1).max(72),
newPassword: z.string().min(8).max(72),
})
const deleteAccountSchema = z.object({
currentPassword: z.string().min(1).max(72),
})
const verificationRequestSchema = z.object({
email: z.string().trim().email().optional(),
})
const verificationConfirmSchema = z.object({
token: z.string().trim().min(20).max(255),
})
const passwordResetRequestSchema = z.object({
email: z.string().trim().email(),
})
const passwordResetConfirmSchema = z.object({
token: z.string().trim().min(20).max(255),
newPassword: z.string().min(8).max(72),
})
const TOKEN_TTL_MS = 1000 * 60 * 30
function buildPreviewUrl(pathname, token) {
const url = new URL(pathname, env.APP_BASE_URL)
url.searchParams.set('token', token)
return url.toString()
}
async function createEmailVerificationToken(userId) {
const token = createSessionToken()
const tokenHash = hashSessionToken(token)
const now = new Date()
const expiresAt = new Date(now.getTime() + TOKEN_TTL_MS)
await db.delete(emailVerificationTokens).where(eq(emailVerificationTokens.userId, userId))
await db.insert(emailVerificationTokens).values({
userId,
tokenHash,
expiresAt,
createdAt: now,
})
return {
token,
previewUrl: buildPreviewUrl('/verify-email', token),
}
}
async function createPasswordResetToken(userId) {
const token = createSessionToken()
const tokenHash = hashSessionToken(token)
const now = new Date()
const expiresAt = new Date(now.getTime() + TOKEN_TTL_MS)
await db.delete(passwordResetTokens).where(eq(passwordResetTokens.userId, userId))
await db.insert(passwordResetTokens).values({
userId,
tokenHash,
expiresAt,
createdAt: now,
})
return {
token,
previewUrl: buildPreviewUrl('/reset-password', token),
}
}
function sanitizeUser(user) {
return {
id: user.id,
email: user.email,
loginId: user.loginId,
nickname: user.nickname,
role: user.role,
emailVerifiedAt: user.emailVerifiedAt,
lastLoginAt: user.lastLoginAt,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
}
}
function getBearerToken(request) {
const authorization = request.headers.authorization
function withPreviewUrl(payload, key, previewUrl) {
const allowPreviewLinks =
env.AUTH_PREVIEW_LINKS &&
/localhost|127\.0\.0\.1/i.test(env.APP_BASE_URL)
if (!authorization?.startsWith('Bearer ')) {
return null
if (!allowPreviewLinks) {
return payload
}
return authorization.slice('Bearer '.length).trim()
}
async function createSession(userId) {
const token = createSessionToken()
const tokenHash = hashSessionToken(token)
const now = Date.now()
const expiresAt = now + env.SESSION_TTL_DAYS * 24 * 60 * 60 * 1000
const [session] = await db
.insert(authSessions)
.values({
userId,
tokenHash,
expiresAt: new Date(expiresAt),
createdAt: new Date(now),
})
.returning()
return {
token,
session,
...payload,
[key]: previewUrl,
}
}
async function findAuthenticatedUser(request) {
const token = getBearerToken(request)
if (!token) {
return null
}
const tokenHash = hashSessionToken(token)
const [session] = await db
.select()
.from(authSessions)
.where(eq(authSessions.tokenHash, tokenHash))
.limit(1)
if (!session || new Date(session.expiresAt).getTime() <= Date.now()) {
return null
}
async function findUserByNickname(nickname) {
const [user] = await db
.select()
.from(users)
.where(eq(users.id, session.userId))
.where(eq(users.nickname, nickname))
.limit(1)
return user ?? null
@@ -117,27 +164,41 @@ export async function registerAuthRoutes(app) {
})
}
const existingNicknameUser = await findUserByNickname(nickname)
if (existingNicknameUser) {
return reply.code(409).send({
message: '이미 사용 중인 닉네임입니다.',
})
}
const now = new Date()
const passwordHash = await hashPassword(password)
const [user] = await db
.insert(users)
.values({
email: normalizedEmail,
loginId: null,
passwordHash,
nickname,
role: 'user',
emailVerifiedAt: null,
lastLoginAt: null,
createdAt: now,
updatedAt: now,
})
.returning()
const { token } = await createSession(user.id)
return reply.code(201).send({
message: '회원가입이 완료되었습니다.',
token,
user: sanitizeUser(user),
const verification = await createEmailVerificationToken(user.id)
await sendVerificationEmail({
to: user.email,
linkUrl: verification.previewUrl,
})
return reply.code(201).send(withPreviewUrl({
message: '회원가입이 완료되었습니다. 이메일 인증 후 로그인해 주세요.',
requiresEmailVerification: true,
}, 'verificationPreviewUrl', verification.previewUrl))
})
app.post('/api/auth/login', async (request, reply) => {
@@ -150,17 +211,23 @@ export async function registerAuthRoutes(app) {
})
}
const normalizedEmail = payload.data.email.toLowerCase()
const identifier = payload.data.email.trim()
const normalizedEmail = identifier.toLowerCase()
const [user] = await db
.select()
.from(users)
.where(eq(users.email, normalizedEmail))
.where(
or(
eq(users.email, normalizedEmail),
eq(users.loginId, identifier),
),
)
.limit(1)
if (!user) {
return reply.code(401).send({
message: '이메일 또는 비밀번호가 올바르지 않습니다.',
message: '이메일, 아이디 또는 비밀번호가 올바르지 않습니다.',
})
}
@@ -168,16 +235,33 @@ export async function registerAuthRoutes(app) {
if (!passwordMatches) {
return reply.code(401).send({
message: '이메일 또는 비밀번호가 올바르지 않습니다.',
message: '이메일, 아이디 또는 비밀번호가 올바르지 않습니다.',
})
}
if (user.role !== 'admin' && !user.emailVerifiedAt) {
return reply.code(403).send({
message: '이메일 인증을 완료한 뒤 로그인해 주세요.',
})
}
const now = new Date()
const [updatedUser] = await db
.update(users)
.set({
lastLoginAt: now,
updatedAt: now,
})
.where(eq(users.id, user.id))
.returning()
const { token } = await createSession(user.id)
return {
message: '로그인에 성공했습니다.',
token,
user: sanitizeUser(user),
user: sanitizeUser(updatedUser),
}
})
@@ -194,4 +278,347 @@ export async function registerAuthRoutes(app) {
user: sanitizeUser(user),
}
})
app.post('/api/auth/logout', async (request, reply) => {
const token = getSessionTokenFromRequest(request)
if (!token) {
return reply.code(401).send({
message: '인증이 필요합니다.',
})
}
await revokeSessionByToken(token)
return {
message: '로그아웃되었습니다.',
}
})
app.put('/api/auth/profile', async (request, reply) => {
const user = await findAuthenticatedUser(request)
if (!user) {
return reply.code(401).send({
message: '인증이 필요합니다.',
})
}
const payload = profileSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '프로필 입력값이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
const normalizedEmail = payload.data.email.toLowerCase()
const [existingUser] = await db
.select()
.from(users)
.where(eq(users.email, normalizedEmail))
.limit(1)
if (existingUser && existingUser.id !== user.id) {
return reply.code(409).send({
message: '이미 사용 중인 이메일입니다.',
})
}
const existingNicknameUser = await findUserByNickname(payload.data.nickname)
if (existingNicknameUser && existingNicknameUser.id !== user.id) {
return reply.code(409).send({
message: '이미 사용 중인 닉네임입니다.',
})
}
const [updatedUser] = await db
.update(users)
.set({
email: normalizedEmail,
nickname: payload.data.nickname,
updatedAt: new Date(),
})
.where(eq(users.id, user.id))
.returning()
return {
message: '프로필이 수정되었습니다.',
user: sanitizeUser(updatedUser),
}
})
app.put('/api/auth/password', async (request, reply) => {
const user = await findAuthenticatedUser(request)
if (!user) {
return reply.code(401).send({
message: '인증이 필요합니다.',
})
}
const payload = passwordSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '비밀번호 입력값이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
const passwordMatches = await verifyPassword(payload.data.currentPassword, user.passwordHash)
if (!passwordMatches) {
return reply.code(401).send({
message: '현재 비밀번호가 올바르지 않습니다.',
})
}
const passwordHash = await hashPassword(payload.data.newPassword)
await db
.update(users)
.set({
passwordHash,
updatedAt: new Date(),
})
.where(eq(users.id, user.id))
return {
message: '비밀번호가 변경되었습니다.',
}
})
app.delete('/api/auth/account', async (request, reply) => {
const user = await findAuthenticatedUser(request)
if (!user) {
return reply.code(401).send({
message: '인증이 필요합니다.',
})
}
if (user.role === 'admin') {
return reply.code(403).send({
message: '기본 관리자 계정은 여기서 삭제할 수 없습니다.',
})
}
const payload = deleteAccountSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '회원 탈퇴 확인 비밀번호를 입력해 주세요.',
issues: payload.error.flatten(),
})
}
const passwordMatches = await verifyPassword(payload.data.currentPassword, user.passwordHash)
if (!passwordMatches) {
return reply.code(401).send({
message: '현재 비밀번호가 올바르지 않습니다.',
})
}
await db.delete(authSessions).where(eq(authSessions.userId, user.id))
await db.delete(users).where(eq(users.id, user.id))
return {
message: '회원 탈퇴가 완료되었습니다.',
}
})
app.post('/api/auth/verification/request', async (request, reply) => {
const authenticatedUser = await findAuthenticatedUser(request)
const payload = verificationRequestSchema.safeParse(request.body ?? {})
if (!payload.success) {
return reply.code(400).send({
message: '이메일 입력값이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
const normalizedEmail = (payload.data.email || authenticatedUser?.email || '').toLowerCase()
if (!normalizedEmail) {
return reply.code(400).send({
message: '인증 메일을 받을 이메일이 필요합니다.',
})
}
const [user] = await db
.select()
.from(users)
.where(eq(users.email, normalizedEmail))
.limit(1)
if (!user) {
return {
message: '입력한 이메일로 인증 안내를 보낼 준비가 되면 처리됩니다.',
}
}
if (user.emailVerifiedAt) {
return {
message: '이미 이메일 인증이 완료된 계정입니다.',
}
}
const verification = await createEmailVerificationToken(user.id)
await sendVerificationEmail({
to: user.email,
linkUrl: verification.previewUrl,
})
return withPreviewUrl({
message: '이메일 인증 링크를 준비했습니다.',
}, 'verificationPreviewUrl', verification.previewUrl)
})
app.post('/api/auth/verification/confirm', async (request, reply) => {
const payload = verificationConfirmSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '인증 토큰이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
const tokenHash = hashSessionToken(payload.data.token)
const [verification] = await db
.select()
.from(emailVerificationTokens)
.where(
and(
eq(emailVerificationTokens.tokenHash, tokenHash),
isNull(emailVerificationTokens.usedAt),
gt(emailVerificationTokens.expiresAt, new Date()),
),
)
.limit(1)
if (!verification) {
return reply.code(400).send({
message: '이미 사용했거나 만료된 인증 링크입니다.',
})
}
const now = new Date()
await db
.update(users)
.set({
emailVerifiedAt: now,
updatedAt: now,
})
.where(eq(users.id, verification.userId))
await db
.update(emailVerificationTokens)
.set({
usedAt: now,
})
.where(eq(emailVerificationTokens.id, verification.id))
return {
message: '이메일 인증이 완료되었습니다.',
}
})
app.post('/api/auth/password-reset/request', async (request, reply) => {
const payload = passwordResetRequestSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '이메일 입력값이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
const normalizedEmail = payload.data.email.toLowerCase()
const [user] = await db
.select()
.from(users)
.where(eq(users.email, normalizedEmail))
.limit(1)
if (!user) {
return {
message: '입력한 이메일로 재설정 안내를 보낼 준비가 되면 처리됩니다.',
}
}
const reset = await createPasswordResetToken(user.id)
await sendPasswordResetEmail({
to: user.email,
linkUrl: reset.previewUrl,
})
return withPreviewUrl({
message: '비밀번호 재설정 링크를 준비했습니다.',
}, 'resetPreviewUrl', reset.previewUrl)
})
app.post('/api/auth/password-reset/confirm', async (request, reply) => {
const payload = passwordResetConfirmSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '비밀번호 재설정 입력값이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
const tokenHash = hashSessionToken(payload.data.token)
const [resetToken] = await db
.select()
.from(passwordResetTokens)
.where(
and(
eq(passwordResetTokens.tokenHash, tokenHash),
isNull(passwordResetTokens.usedAt),
gt(passwordResetTokens.expiresAt, new Date()),
),
)
.limit(1)
if (!resetToken) {
return reply.code(400).send({
message: '이미 사용했거나 만료된 재설정 링크입니다.',
})
}
const now = new Date()
const passwordHash = await hashPassword(payload.data.newPassword)
await db
.update(users)
.set({
passwordHash,
updatedAt: now,
})
.where(eq(users.id, resetToken.userId))
await db
.update(passwordResetTokens)
.set({
usedAt: now,
})
.where(eq(passwordResetTokens.id, resetToken.id))
await db.delete(authSessions).where(eq(authSessions.userId, resetToken.userId))
return {
message: '비밀번호가 재설정되었습니다. 다시 로그인해 주세요.',
}
})
}

304
backend/src/routes/goals.js Normal file
View File

@@ -0,0 +1,304 @@
import { and, asc, desc, eq, like } from 'drizzle-orm'
import { z } from 'zod'
import { db } from '../db/client.js'
import { goals } from '../db/schema.js'
import { findAuthenticatedUser } from '../lib/authSession.js'
const goalSchema = z.object({
title: z.string().trim().min(1).max(80),
targetDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
activeFrom: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().nullable(),
activeUntil: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().nullable(),
color: z.string().trim().min(4).max(32).optional(),
})
const goalUpdateSchema = z.object({
title: z.string().trim().min(1).max(80).optional(),
targetDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
activeFrom: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().nullable(),
activeUntil: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().nullable(),
color: z.string().trim().min(4).max(32).optional(),
})
const goalQuerySchema = z.object({
query: z.string().trim().optional(),
})
async function requireAuthenticatedUser(request, reply) {
const user = await findAuthenticatedUser(request)
if (!user) {
reply.code(401).send({
message: '인증이 필요합니다.',
})
return null
}
return user
}
function hasGoalRangeOverlap(leftStart, leftEnd, rightStart, rightEnd) {
return leftStart <= rightEnd && leftEnd >= rightStart
}
async function validateGoalSchedule({
userId,
activeFrom,
activeUntil,
excludeGoalId = null,
}) {
if (!activeFrom || !activeUntil) {
return null
}
const existingGoals = await db
.select()
.from(goals)
.where(eq(goals.userId, userId))
return existingGoals.find((goal) => {
if (excludeGoalId && goal.id === excludeGoalId) {
return false
}
if (!goal.activeFrom || !goal.activeUntil) {
return false
}
return hasGoalRangeOverlap(activeFrom, activeUntil, goal.activeFrom, goal.activeUntil)
}) ?? null
}
export async function registerGoalRoutes(app) {
app.get('/api/goals', async (request, reply) => {
const user = await requireAuthenticatedUser(request, reply)
if (!user) {
return
}
const query = goalQuerySchema.safeParse(request.query ?? {})
if (!query.success) {
return reply.code(400).send({
message: '목표 조회 조건이 올바르지 않습니다.',
issues: query.error.flatten(),
})
}
const filters = [eq(goals.userId, user.id)]
if (query.data.query) {
filters.push(like(goals.title, `%${query.data.query}%`))
}
const items = await db
.select()
.from(goals)
.where(and(...filters))
.orderBy(desc(goals.updatedAt), asc(goals.targetDate), asc(goals.id))
return { goals: items }
})
app.post('/api/goals', async (request, reply) => {
const user = await requireAuthenticatedUser(request, reply)
if (!user) {
return
}
const payload = goalSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '목표 입력값이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
if ((payload.data.activeFrom && !payload.data.activeUntil) || (!payload.data.activeFrom && payload.data.activeUntil)) {
return reply.code(400).send({
message: '표시 시작일과 종료일은 함께 입력해 주세요.',
})
}
if (payload.data.activeFrom && payload.data.activeUntil && payload.data.activeFrom > payload.data.activeUntil) {
return reply.code(400).send({
message: '표시 종료일은 시작일보다 빠를 수 없습니다.',
})
}
const overlappedGoal = await validateGoalSchedule({
userId: user.id,
activeFrom: payload.data.activeFrom ?? null,
activeUntil: payload.data.activeUntil ?? null,
})
if (overlappedGoal) {
return reply.code(409).send({
message: `표시 기간이 "${overlappedGoal.title}" 목표와 겹칩니다. D-DAY 기간은 하나만 설정할 수 있습니다.`,
})
}
const now = new Date()
const [goal] = await db
.insert(goals)
.values({
userId: user.id,
title: payload.data.title,
targetDate: payload.data.targetDate,
activeFrom: payload.data.activeFrom ?? null,
activeUntil: payload.data.activeUntil ?? null,
color: payload.data.color ?? '#1c1917',
createdAt: now,
updatedAt: now,
})
.returning()
return reply.code(201).send({
message: '목표가 추가되었습니다.',
goal,
})
})
app.patch('/api/goals/:goalId', async (request, reply) => {
const user = await requireAuthenticatedUser(request, reply)
if (!user) {
return
}
const params = z.object({
goalId: z.coerce.number().int().positive(),
}).safeParse(request.params)
if (!params.success) {
return reply.code(400).send({
message: '목표 식별자가 올바르지 않습니다.',
})
}
const payload = goalUpdateSchema.safeParse(request.body)
if (!payload.success) {
return reply.code(400).send({
message: '목표 수정값이 올바르지 않습니다.',
issues: payload.error.flatten(),
})
}
const [existingGoal] = await db
.select()
.from(goals)
.where(and(eq(goals.id, params.data.goalId), eq(goals.userId, user.id)))
.limit(1)
if (!existingGoal) {
return reply.code(404).send({
message: '목표를 찾을 수 없습니다.',
})
}
const nextActiveFrom = payload.data.activeFrom !== undefined ? payload.data.activeFrom : existingGoal.activeFrom
const nextActiveUntil = payload.data.activeUntil !== undefined ? payload.data.activeUntil : existingGoal.activeUntil
if ((nextActiveFrom && !nextActiveUntil) || (!nextActiveFrom && nextActiveUntil)) {
return reply.code(400).send({
message: '표시 시작일과 종료일은 함께 입력해 주세요.',
})
}
if (nextActiveFrom && nextActiveUntil && nextActiveFrom > nextActiveUntil) {
return reply.code(400).send({
message: '표시 종료일은 시작일보다 빠를 수 없습니다.',
})
}
const overlappedGoal = await validateGoalSchedule({
userId: user.id,
activeFrom: nextActiveFrom,
activeUntil: nextActiveUntil,
excludeGoalId: existingGoal.id,
})
if (overlappedGoal) {
return reply.code(409).send({
message: `표시 기간이 "${overlappedGoal.title}" 목표와 겹칩니다. D-DAY 기간은 하나만 설정할 수 있습니다.`,
})
}
const nextValues = {
updatedAt: new Date(),
}
if (payload.data.title !== undefined) {
nextValues.title = payload.data.title
}
if (payload.data.targetDate !== undefined) {
nextValues.targetDate = payload.data.targetDate
}
if (payload.data.activeFrom !== undefined) {
nextValues.activeFrom = payload.data.activeFrom
}
if (payload.data.activeUntil !== undefined) {
nextValues.activeUntil = payload.data.activeUntil
}
if (payload.data.color !== undefined) {
nextValues.color = payload.data.color
}
const [goal] = await db
.update(goals)
.set(nextValues)
.where(and(eq(goals.id, params.data.goalId), eq(goals.userId, user.id)))
.returning()
return {
message: '목표가 수정되었습니다.',
goal,
}
})
app.delete('/api/goals/:goalId', async (request, reply) => {
const user = await requireAuthenticatedUser(request, reply)
if (!user) {
return
}
const params = z.object({
goalId: z.coerce.number().int().positive(),
}).safeParse(request.params)
if (!params.success) {
return reply.code(400).send({
message: '목표 식별자가 올바르지 않습니다.',
})
}
const [existingGoal] = await db
.select()
.from(goals)
.where(and(eq(goals.id, params.data.goalId), eq(goals.userId, user.id)))
.limit(1)
if (!existingGoal) {
return reply.code(404).send({
message: '목표를 찾을 수 없습니다.',
})
}
await db
.delete(goals)
.where(and(eq(goals.id, params.data.goalId), eq(goals.userId, user.id)))
return {
message: '목표가 삭제되었습니다.',
}
})
}

View File

@@ -0,0 +1,185 @@
import { and, asc, eq, gte, lte } from 'drizzle-orm'
import { z } from 'zod'
import { db } from '../db/client.js'
import { plannerEntries } from '../db/schema.js'
import { findAuthenticatedUser } from '../lib/authSession.js'
const dateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/)
const plannerPayloadSchema = z.object({
payload: z.record(z.any()),
})
const plannerRangeQuerySchema = z.object({
from: dateSchema.optional(),
to: dateSchema.optional(),
})
async function requireAuthenticatedUser(request, reply) {
const user = await findAuthenticatedUser(request)
if (!user) {
reply.code(401).send({
message: '인증이 필요합니다.',
})
return null
}
return user
}
export async function registerPlannerRoutes(app) {
app.get('/api/planner', async (request, reply) => {
const user = await requireAuthenticatedUser(request, reply)
if (!user) {
return
}
const query = plannerRangeQuerySchema.safeParse(request.query ?? {})
if (!query.success) {
return reply.code(400).send({
message: '조회 범위가 올바르지 않습니다.',
issues: query.error.flatten(),
})
}
const filters = [eq(plannerEntries.userId, user.id)]
if (query.data.from) {
filters.push(gte(plannerEntries.entryDate, query.data.from))
}
if (query.data.to) {
filters.push(lte(plannerEntries.entryDate, query.data.to))
}
const entries = await db
.select({
entryDate: plannerEntries.entryDate,
payload: plannerEntries.payload,
createdAt: plannerEntries.createdAt,
updatedAt: plannerEntries.updatedAt,
})
.from(plannerEntries)
.where(and(...filters))
.orderBy(asc(plannerEntries.entryDate))
return {
entries,
}
})
app.get('/api/planner/:entryDate', async (request, reply) => {
const user = await requireAuthenticatedUser(request, reply)
if (!user) {
return
}
const dateResult = dateSchema.safeParse(request.params.entryDate)
if (!dateResult.success) {
return reply.code(400).send({
message: '날짜 형식이 올바르지 않습니다.',
})
}
const [entry] = await db
.select()
.from(plannerEntries)
.where(
and(
eq(plannerEntries.userId, user.id),
eq(plannerEntries.entryDate, dateResult.data),
),
)
.limit(1)
return {
entry: entry ?? null,
}
})
app.put('/api/planner/:entryDate', async (request, reply) => {
const user = await requireAuthenticatedUser(request, reply)
if (!user) {
return
}
const dateResult = dateSchema.safeParse(request.params.entryDate)
if (!dateResult.success) {
return reply.code(400).send({
message: '날짜 형식이 올바르지 않습니다.',
})
}
const payloadResult = plannerPayloadSchema.safeParse(request.body)
if (!payloadResult.success) {
return reply.code(400).send({
message: '플래너 저장 데이터가 올바르지 않습니다.',
issues: payloadResult.error.flatten(),
})
}
const now = new Date()
const [entry] = await db
.insert(plannerEntries)
.values({
userId: user.id,
entryDate: dateResult.data,
payload: payloadResult.data.payload,
createdAt: now,
updatedAt: now,
})
.onConflictDoUpdate({
target: [plannerEntries.userId, plannerEntries.entryDate],
set: {
payload: payloadResult.data.payload,
updatedAt: now,
},
})
.returning()
return {
message: '플래너가 저장되었습니다.',
entry,
}
})
app.delete('/api/planner/:entryDate', async (request, reply) => {
const user = await requireAuthenticatedUser(request, reply)
if (!user) {
return
}
const dateResult = dateSchema.safeParse(request.params.entryDate)
if (!dateResult.success) {
return reply.code(400).send({
message: '날짜 형식이 올바르지 않습니다.',
})
}
const deletedEntries = await db
.delete(plannerEntries)
.where(
and(
eq(plannerEntries.userId, user.id),
eq(plannerEntries.entryDate, dateResult.data),
),
)
.returning()
return {
message: deletedEntries.length > 0 ? '플래너가 삭제되었습니다.' : '삭제할 플래너가 없습니다.',
deleted: deletedEntries.length > 0,
}
})
}

View File

@@ -1,15 +1,20 @@
import Fastify from 'fastify'
import cors from '@fastify/cors'
import { env } from './config.js'
import { sqlite } from './db/client.js'
import { pool } from './db/client.js'
import { ensureDatabaseSchema } from './db/init.js'
import { ensureAdminAccount } from './lib/adminAccount.js'
import { registerAuthRoutes } from './routes/auth.js'
import { registerAdminRoutes } from './routes/admin.js'
import { registerGoalRoutes } from './routes/goals.js'
import { registerPlannerRoutes } from './routes/planner.js'
const app = Fastify({
logger: true,
})
ensureDatabaseSchema()
await ensureDatabaseSchema()
await ensureAdminAccount()
await app.register(cors, {
origin: env.CORS_ORIGIN,
@@ -17,15 +22,19 @@ await app.register(cors, {
})
await registerAuthRoutes(app)
await registerAdminRoutes(app)
await registerGoalRoutes(app)
await registerPlannerRoutes(app)
app.get('/health', async () => {
const version = sqlite.prepare('select sqlite_version() as version').get()
const versionResult = await pool.query('select version() as version')
const version = versionResult.rows[0]
return {
status: 'ok',
service: 'ten-minute-planner-backend',
database: {
client: 'sqlite',
client: 'postgresql',
version: version?.version ?? 'unknown',
},
}
@@ -33,11 +42,13 @@ app.get('/health', async () => {
app.get('/api/meta', async () => ({
auth: 'active',
storage: 'sqlite',
storage: 'postgresql',
orm: 'drizzle',
notes: [
'회원가입, 로그인, 현재 사용자 확인 API가 준비되어 있습니다.',
'플래너 저장 API는 로컬 저장 레이어 분리 이후 연결 예정',
'관리자용 사용자 현황 요약 API가 준비되어 있습니다.',
'사용자별 목표 목록, 수정, 삭제 API가 준비되어 있습니다.',
'사용자별 플래너 저장 및 조회 API가 준비되어 있습니다.',
],
}))

26
deploy/nginx/default.conf Normal file
View File

@@ -0,0 +1,26 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://backend:3001/api/;
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;
}
location /health {
proxy_pass http://backend:3001/health;
proxy_http_version 1.1;
proxy_set_header Host $host;
}
location / {
try_files $uri $uri/ /index.html;
}
}

64
docker-compose.dev.yml Normal file
View File

@@ -0,0 +1,64 @@
services:
postgres:
image: postgres:16-alpine
container_name: ten-minute-postgres-dev
env_file:
- ./.env.dev
environment:
TZ: Asia/Seoul
volumes:
- postgres_dev_data:/var/lib/postgresql/data
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
interval: 10s
timeout: 5s
retries: 10
restart: unless-stopped
backend:
image: node:22-alpine
container_name: ten-minute-backend-dev
working_dir: /app
command: sh -c "npm install && npm run dev"
env_file:
- ./.env.dev
environment:
PORT: 3001
CORS_ORIGIN: http://localhost:5173
SESSION_TTL_DAYS: 30
TZ: Asia/Seoul
volumes:
- ./backend:/app
- backend_node_modules:/app/node_modules
depends_on:
postgres:
condition: service_healthy
ports:
- "3001:3001"
restart: unless-stopped
frontend:
image: node:22-alpine
container_name: ten-minute-frontend-dev
working_dir: /app
command: sh -c "npm install && npm run dev"
environment:
VITE_API_BASE_URL: http://localhost:3001
CHOKIDAR_USEPOLLING: "true"
TZ: Asia/Seoul
volumes:
- .:/app
- /app/backend
- frontend_node_modules:/app/node_modules
depends_on:
- backend
ports:
- "5173:5173"
restart: unless-stopped
volumes:
postgres_dev_data:
backend_node_modules:
frontend_node_modules:

53
docker-compose.yml Normal file
View File

@@ -0,0 +1,53 @@
services:
postgres:
image: postgres:16-alpine
container_name: ten-minute-postgres
env_file:
- ./.env
environment:
TZ: Asia/Seoul
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "45432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
interval: 10s
timeout: 5s
retries: 10
restart: unless-stopped
backend:
build:
context: ./backend
container_name: ten-minute-backend
env_file:
- ./.env
environment:
PORT: 3001
CORS_ORIGIN: http://localhost:48081
SESSION_TTL_DAYS: 30
TZ: Asia/Seoul
depends_on:
postgres:
condition: service_healthy
expose:
- "3001"
restart: unless-stopped
frontend:
build:
context: .
args:
VITE_API_BASE_URL: /api
container_name: ten-minute-frontend
environment:
TZ: Asia/Seoul
depends_on:
- backend
ports:
- "48081:80"
restart: unless-stopped
volumes:
postgres_data:

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "ten-minute-planner",
"version": "0.1.9",
"version": "0.1.46",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ten-minute-planner",
"version": "0.1.9",
"version": "0.1.46",
"dependencies": {
"vue": "^3.5.13"
},

View File

@@ -1,7 +1,7 @@
{
"name": "ten-minute-planner",
"private": true,
"version": "0.1.9",
"version": "0.1.46",
"type": "module",
"scripts": {
"dev": "vite",

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,185 @@
<script setup>
const props = defineProps({
summary: {
type: Object,
required: true,
},
users: {
type: Array,
required: true,
},
recentLogins: {
type: Array,
required: true,
},
busy: {
type: Boolean,
default: false,
},
message: {
type: String,
default: '',
},
})
function formatDate(value) {
if (!value) {
return '기록 없음'
}
const date = new Date(value)
if (Number.isNaN(date.getTime())) {
return '기록 없음'
}
return new Intl.DateTimeFormat('ko-KR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(date)
}
</script>
<template>
<section class="grid gap-6">
<div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
<article class="rounded-[28px] border border-white/60 bg-white/80 p-6">
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">Total Users</p>
<p class="mt-4 text-4xl font-semibold tracking-[-0.06em] text-stone-900">{{ summary.totalUsers }}</p>
<p class="mt-2 text-sm font-semibold text-stone-500">현재 가입된 전체 계정 </p>
</article>
<article class="rounded-[28px] border border-white/60 bg-white/80 p-6">
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">Active 30 Days</p>
<p class="mt-4 text-4xl font-semibold tracking-[-0.06em] text-stone-900">{{ summary.activeUsers30d }}</p>
<p class="mt-2 text-sm font-semibold text-stone-500">최근 30 안에 접속한 사용자</p>
</article>
<article class="rounded-[28px] border border-white/60 bg-white/80 p-6">
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">Planner Entries</p>
<p class="mt-4 text-4xl font-semibold tracking-[-0.06em] text-stone-900">{{ summary.totalPlannerEntries }}</p>
<p class="mt-2 text-sm font-semibold text-stone-500">전체 작성된 날짜 문서 </p>
</article>
<article class="rounded-[28px] border border-white/60 bg-white/80 p-6">
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">Verified / Admin</p>
<p class="mt-4 text-3xl font-semibold tracking-[-0.06em] text-stone-900">{{ summary.verifiedUsers }} / {{ summary.totalAdmins }}</p>
<p class="mt-2 text-sm font-semibold text-stone-500">인증 완료 계정 / 관리자 </p>
</article>
</div>
<div class="grid gap-6 xl:grid-cols-[320px_minmax(0,1fr)]">
<aside class="rounded-[28px] border border-white/60 bg-white/75 p-6">
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">운영 요약</p>
<div class="mt-5 space-y-4">
<div class="rounded-2xl border border-stone-200 bg-white px-4 py-4">
<p class="text-[10px] font-bold tracking-[0.18em] text-stone-500">최근 7 신규 가입</p>
<p class="mt-2 text-2xl font-semibold tracking-[-0.05em] text-stone-900">{{ summary.newUsers7d }}</p>
</div>
<div class="rounded-2xl border border-stone-200 bg-white px-4 py-4">
<p class="text-[10px] font-bold tracking-[0.18em] text-stone-500">전체 목표 </p>
<p class="mt-2 text-2xl font-semibold tracking-[-0.05em] text-stone-900">{{ summary.totalGoals }}</p>
</div>
</div>
<div class="mt-6">
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">최근 접속</p>
<div class="mt-4 space-y-3">
<article
v-for="user in recentLogins"
:key="`recent-${user.id}`"
class="rounded-2xl border border-stone-200 bg-white px-4 py-4"
>
<div class="flex items-center justify-between gap-3">
<p class="text-sm font-semibold text-stone-900">{{ user.nickname }}</p>
<span class="rounded-full bg-stone-100 px-2 py-1 text-[10px] font-bold tracking-[0.12em] text-stone-600">
{{ user.role }}
</span>
</div>
<p class="mt-1 text-xs font-semibold text-stone-500">{{ user.email }}</p>
<p class="mt-3 text-[11px] font-semibold text-stone-600">{{ formatDate(user.lastLoginAt) }}</p>
</article>
<p v-if="recentLogins.length === 0" class="rounded-2xl border border-dashed border-stone-300 bg-white/80 px-4 py-4 text-sm font-semibold text-stone-500">
아직 접속 기록이 없습니다.
</p>
</div>
</div>
</aside>
<section class="rounded-[28px] border border-white/60 bg-white/75 p-6">
<div class="flex items-center justify-between gap-4">
<div>
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">사용자 목록</p>
<p class="mt-2 text-sm font-semibold text-stone-500">최종 접속일, 작성 문서 , 목표 수를 번에 있습니다.</p>
</div>
<div v-if="busy" class="rounded-full bg-stone-900 px-4 py-2 text-[11px] font-bold tracking-[0.16em] text-white">
불러오는 중...
</div>
</div>
<p
v-if="message"
class="mt-4 rounded-2xl border border-stone-300 bg-white/80 px-4 py-3 text-sm font-semibold leading-6 text-stone-700"
>
{{ message }}
</p>
<div class="mt-5 overflow-hidden rounded-[24px] border border-stone-200 bg-white">
<div class="hidden grid-cols-[84px_minmax(0,1.4fr)_120px_150px_110px_100px_150px] gap-3 border-b border-stone-200 bg-[#f8f4ed] px-5 py-4 text-[10px] font-bold uppercase tracking-[0.18em] text-stone-500 xl:grid">
<span>ID</span>
<span>사용자</span>
<span>권한</span>
<span>최종 접속</span>
<span>문서 </span>
<span>목표 </span>
<span>상태</span>
</div>
<div class="divide-y divide-stone-200">
<article
v-for="user in users"
:key="user.id"
class="px-5 py-4"
>
<div class="grid gap-3 xl:grid-cols-[84px_minmax(0,1.4fr)_120px_150px_110px_100px_150px] xl:items-center">
<p class="text-xs font-bold tracking-[0.14em] text-stone-500">#{{ user.id }}</p>
<div>
<p class="text-sm font-semibold text-stone-900">{{ user.nickname }}</p>
<p class="mt-1 text-xs font-semibold text-stone-500">{{ user.email }}</p>
</div>
<p class="text-sm font-semibold text-stone-700">{{ user.role }}</p>
<p class="text-sm font-semibold text-stone-700">{{ formatDate(user.lastLoginAt) }}</p>
<p class="text-sm font-semibold text-stone-700">{{ user.plannerEntryCount }}</p>
<p class="text-sm font-semibold text-stone-700">{{ user.goalCount }}</p>
<div class="flex flex-wrap items-center gap-2">
<span
class="rounded-full px-3 py-1 text-[10px] font-bold tracking-[0.14em]"
:class="user.isActiveRecently ? 'bg-emerald-100 text-emerald-700' : 'bg-stone-100 text-stone-500'"
>
{{ user.isActiveRecently ? '활동 중' : '휴면 가능성' }}
</span>
<span
class="rounded-full px-3 py-1 text-[10px] font-bold tracking-[0.14em]"
:class="user.emailVerifiedAt ? 'bg-sky-100 text-sky-700' : 'bg-amber-100 text-amber-700'"
>
{{ user.emailVerifiedAt ? '이메일 인증' : '미인증' }}
</span>
</div>
</div>
</article>
<div
v-if="!busy && users.length === 0"
class="px-5 py-10 text-center text-sm font-semibold text-stone-500"
>
표시할 사용자가 없습니다.
</div>
</div>
</div>
</section>
</div>
</section>
</template>

View File

@@ -0,0 +1,227 @@
<script setup>
const props = defineProps({
open: {
type: Boolean,
default: false,
},
mode: {
type: String,
default: 'login',
},
form: {
type: Object,
required: true,
},
busy: {
type: Boolean,
default: false,
},
message: {
type: String,
default: '',
},
})
const emit = defineEmits([
'close',
'submit',
'switch-mode',
'update:field',
])
function updateField(field, event) {
emit('update:field', {
field,
value: event.target.type === 'checkbox' ? event.target.checked : event.target.value,
})
}
function getTitle(mode) {
if (mode === 'signup') {
return '회원가입'
}
if (mode === 'reset-request') {
return '비밀번호 찾기'
}
if (mode === 'reset-confirm') {
return '새 비밀번호 설정'
}
return '로그인'
}
function getDescription(mode) {
if (mode === 'signup') {
return '기록을 저장할 계정을 만들어요.'
}
if (mode === 'reset-request') {
return '가입한 이메일로 재설정 링크를 받을 수 있습니다.'
}
if (mode === 'reset-confirm') {
return '메일로 받은 링크의 토큰과 새 비밀번호를 확인합니다.'
}
return '내 플래너를 이어서 열어요.'
}
function getSubmitLabel(mode, busy) {
if (busy) {
return '처리 중...'
}
if (mode === 'signup') {
return '가입하기'
}
if (mode === 'reset-request') {
return '재설정 링크 받기'
}
if (mode === 'reset-confirm') {
return '비밀번호 재설정'
}
return '로그인하기'
}
</script>
<template>
<div
v-if="open"
class="fixed inset-0 z-50 flex items-center justify-center bg-stone-900/45 px-4 py-6 backdrop-blur-sm"
>
<div class="w-full max-w-[420px] rounded-[26px] border border-white/70 bg-[#f7f2ea] p-5 shadow-[0_24px_80px_rgba(28,25,23,0.2)] sm:p-6">
<div class="flex items-start justify-between gap-4">
<div>
<p class="text-[10px] font-bold uppercase tracking-[0.24em] text-stone-500">10 Minute Planner</p>
<h2 class="mt-2 text-2xl font-semibold tracking-[-0.04em] text-stone-900">
{{ getTitle(mode) }}
</h2>
<p class="mt-2 text-sm leading-6 text-stone-600">
{{ getDescription(mode) }}
</p>
</div>
<button
type="button"
class="rounded-full border border-stone-300 px-3 py-2 text-[10px] font-bold tracking-[0.16em] text-stone-500 transition hover:border-stone-500 hover:text-stone-900"
@click="emit('close')"
>
CLOSE
</button>
</div>
<form class="mt-6 space-y-4" @submit.prevent="emit('submit')">
<div v-if="mode === 'signup'" class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">닉네임</label>
<input
:value="form.nickname"
type="text"
class="w-full rounded-2xl border border-stone-300 bg-white/90 px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
placeholder="닉네임을 입력해 주세요."
@input="updateField('nickname', $event)"
/>
</div>
<div v-if="mode !== 'reset-confirm'" class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">
{{ mode === 'login' ? '이메일 또는 아이디' : '이메일' }}
</label>
<input
:value="form.email"
:type="mode === 'login' ? 'text' : 'email'"
class="w-full rounded-2xl border border-stone-300 bg-white/90 px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
:placeholder="mode === 'login' ? '이메일 또는 아이디를 입력해 주세요.' : 'you@example.com'"
@input="updateField('email', $event)"
/>
</div>
<div v-if="mode === 'reset-confirm'" class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">재설정 토큰</label>
<input
:value="form.resetToken"
type="text"
class="w-full rounded-2xl border border-stone-300 bg-white/90 px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
placeholder="메일 링크의 토큰"
@input="updateField('resetToken', $event)"
/>
</div>
<div v-if="mode === 'login' || mode === 'signup'" class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">비밀번호</label>
<input
:value="form.password"
type="password"
class="w-full rounded-2xl border border-stone-300 bg-white/90 px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
placeholder="8자 이상 입력해 주세요."
@input="updateField('password', $event)"
/>
</div>
<div v-if="mode === 'reset-confirm'" class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600"> 비밀번호</label>
<input
:value="form.newPassword"
type="password"
class="w-full rounded-2xl border border-stone-300 bg-white/90 px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
placeholder="8자 이상 입력해 주세요."
@input="updateField('newPassword', $event)"
/>
</div>
<label
v-if="mode === 'login'"
class="-mt-1 flex items-center gap-2 px-1 text-left"
>
<input
:checked="form.rememberSession"
type="checkbox"
class="h-4 w-4 shrink-0 accent-stone-900"
@change="updateField('rememberSession', $event)"
/>
<span class="text-xs font-bold tracking-[0.08em] text-stone-700">로그인 상태 유지</span>
</label>
<p
v-if="message"
class="rounded-2xl border border-stone-300 bg-white/80 px-4 py-3 text-sm font-semibold leading-6 text-stone-700"
>
{{ message }}
</p>
<button
type="submit"
class="w-full rounded-full bg-stone-900 px-5 py-3 text-xs font-bold tracking-[0.18em] text-white transition hover:bg-stone-700 disabled:cursor-not-allowed disabled:bg-stone-400"
:disabled="busy"
>
{{ getSubmitLabel(mode, busy) }}
</button>
</form>
<button
v-if="mode === 'login'"
type="button"
class="mt-4 w-full text-center text-xs font-bold tracking-[0.14em] text-stone-500 underline underline-offset-4 transition hover:text-stone-900"
@click="emit('switch-mode', 'reset-request')"
>
비밀번호를 잊으셨나요?
</button>
<div class="mt-5 flex items-center justify-center gap-2 border-t border-stone-300/70 pt-4">
<p class="text-sm font-semibold text-stone-600">
{{ mode === 'signup' ? '이미 계정이 있나요?' : '계정 화면으로 돌아갈까요?' }}
</p>
<button
type="button"
class="text-xs font-bold tracking-[0.14em] text-stone-900 underline underline-offset-4"
@click="emit('switch-mode', mode === 'login' ? 'signup' : 'login')"
>
{{ mode === 'login' ? '회원가입' : '로그인' }}
</button>
</div>
</div>
</div>
</template>

View File

@@ -0,0 +1,216 @@
<script setup>
const props = defineProps({
goals: {
type: Array,
default: () => [],
},
query: {
type: String,
default: '',
},
form: {
type: Object,
required: true,
},
editingGoalId: {
type: Number,
default: null,
},
busy: {
type: Boolean,
default: false,
},
message: {
type: String,
default: '',
},
selectedDateKey: {
type: String,
default: '',
},
})
const emit = defineEmits([
'update:query',
'update:form-field',
'submit:create',
'start-edit',
'cancel-edit',
'submit:update',
'delete-goal',
])
function updateField(field, event) {
emit('update:form-field', {
field,
value: event.target.value,
})
}
function isActiveOnSelectedDate(goal) {
if (!goal.activeFrom || !goal.activeUntil || !props.selectedDateKey) {
return false
}
return props.selectedDateKey >= goal.activeFrom && props.selectedDateKey <= goal.activeUntil
}
</script>
<template>
<section class="grid gap-6 xl:grid-cols-[380px_minmax(0,1fr)]">
<form class="rounded-[28px] border border-white/60 bg-white/75 p-6" @submit.prevent="emit(editingGoalId ? 'submit:update' : 'submit:create')">
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">
{{ editingGoalId ? 'Edit Goal' : 'Create Goal' }}
</p>
<div class="mt-5 space-y-4">
<div class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">목표 이름</label>
<input
:value="form.title"
type="text"
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
placeholder="예: 자격증 시험 / 프로젝트 런칭 / 운동 루틴"
@input="updateField('title', $event)"
/>
</div>
<div class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">목표일</label>
<input
:value="form.targetDate"
type="date"
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
@input="updateField('targetDate', $event)"
/>
</div>
<div class="grid gap-4 sm:grid-cols-2">
<div class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">표시 시작일</label>
<input
:value="form.activeFrom"
type="date"
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
@input="updateField('activeFrom', $event)"
/>
</div>
<div class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">표시 종료일</label>
<input
:value="form.activeUntil"
type="date"
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
@input="updateField('activeUntil', $event)"
/>
</div>
</div>
<p class="rounded-2xl border border-stone-200 bg-[#fbf7f0] px-4 py-3 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-600">
여기서 목표와 표시 기간을 설정해 두면, 플래너 작성 화면에서는 해당 날짜에 보여줄지 여부만 간단히 ON/OFF 있습니다.
</p>
<p
v-if="message"
class="rounded-2xl border border-stone-300 bg-white/80 px-4 py-3 text-sm font-semibold leading-6 text-stone-700"
>
{{ message }}
</p>
<div class="flex flex-wrap gap-2">
<button
type="submit"
class="rounded-full bg-stone-900 px-5 py-3 text-xs font-bold tracking-[0.18em] text-white transition hover:bg-stone-700 disabled:cursor-not-allowed disabled:bg-stone-400"
:disabled="busy"
>
{{ busy ? '저장 중...' : editingGoalId ? '목표 수정' : '목표 추가' }}
</button>
<button
v-if="editingGoalId"
type="button"
class="rounded-full border border-stone-300 px-5 py-3 text-xs font-bold tracking-[0.18em] text-stone-600 transition hover:border-stone-500 hover:text-stone-900"
@click="emit('cancel-edit')"
>
취소
</button>
</div>
</div>
</form>
<section class="rounded-[28px] border border-white/60 bg-white/75 p-6">
<div class="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
<div>
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">Goal Library</p>
<p class="mt-2 text-sm font-semibold leading-6 text-stone-600">
목표가 많아져도 플래너 작성 화면이 길어지지 않도록, 전체 관리는 화면에서 처리합니다.
</p>
</div>
<div class="grid gap-2 sm:grid-cols-[220px]">
<input
:value="query"
type="text"
class="rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
placeholder="목표 검색"
@input="emit('update:query', $event.target.value)"
/>
</div>
</div>
<div class="mt-5 grid gap-4">
<article
v-for="goal in goals"
:key="goal.id"
class="rounded-[24px] border px-5 py-5 transition"
:class="editingGoalId === goal.id ? 'border-stone-900 bg-[#f7f1e7] shadow-[0_18px_40px_rgba(28,25,23,0.10)]' : 'border-stone-200 bg-white'"
>
<div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
<div class="space-y-2">
<div class="flex flex-wrap items-center gap-2">
<p class="text-lg font-semibold tracking-[-0.03em] text-stone-900">{{ goal.title }}</p>
<span
v-if="editingGoalId === goal.id"
class="rounded-full bg-stone-900 px-3 py-1 text-[10px] font-bold tracking-[0.16em] text-white"
>
수정
</span>
<span
v-if="isActiveOnSelectedDate(goal)"
class="rounded-full bg-amber-100 px-3 py-1 text-[10px] font-bold tracking-[0.16em] text-amber-700"
>
현재 날짜에 표시
</span>
</div>
<p class="text-sm font-semibold text-stone-600">목표일 {{ goal.targetDate }}</p>
<p class="text-[11px] font-semibold tracking-[0.06em] text-stone-500">
{{ goal.activeFrom && goal.activeUntil ? `표시 기간 ${goal.activeFrom} ~ ${goal.activeUntil}` : '표시 기간 미설정' }}
</p>
</div>
<div class="flex flex-wrap gap-2">
<button
type="button"
class="rounded-full border border-stone-300 px-4 py-2 text-[11px] font-bold tracking-[0.16em] text-stone-600 transition hover:border-stone-500 hover:text-stone-900"
@click="emit('start-edit', goal)"
>
수정
</button>
<button
type="button"
class="rounded-full border border-red-200 px-4 py-2 text-[11px] font-bold tracking-[0.16em] text-red-500 transition hover:border-red-400 hover:bg-red-50"
@click="emit('delete-goal', goal)"
>
삭제
</button>
</div>
</div>
</article>
<div
v-if="goals.length === 0"
class="rounded-[24px] border border-dashed border-stone-300 bg-white px-5 py-8 text-center"
>
<p class="text-sm font-semibold text-stone-600">조건에 맞는 목표가 없습니다.</p>
</div>
</div>
</section>
</section>
</template>

View File

@@ -0,0 +1,99 @@
<script setup>
import { onBeforeUnmount, ref } from 'vue'
const props = defineProps({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
visible: {
type: Boolean,
default: true,
},
dismissible: {
type: Boolean,
default: true,
},
buttonLabel: {
type: String,
default: '?',
},
})
const emit = defineEmits(['dismiss'])
const open = ref(false)
const rootRef = ref(null)
function close() {
open.value = false
}
function toggle() {
if (!props.visible) {
return
}
open.value = !open.value
}
function closeFromOutside(event) {
if (!open.value || rootRef.value?.contains(event.target)) {
return
}
close()
}
function dismiss() {
emit('dismiss')
close()
}
if (typeof window !== 'undefined') {
window.addEventListener('pointerdown', closeFromOutside)
}
onBeforeUnmount(() => {
window.removeEventListener('pointerdown', closeFromOutside)
})
</script>
<template>
<span
v-if="visible"
ref="rootRef"
class="relative inline-flex"
>
<button
type="button"
class="flex h-5 w-5 items-center justify-center rounded-full border border-stone-300 bg-white text-[10px] font-bold text-stone-500 transition hover:border-stone-500 hover:text-stone-900 focus-visible:ring-2 focus-visible:ring-stone-900 focus-visible:ring-offset-2"
aria-label="가이드 보기"
:aria-expanded="open"
@click.stop="toggle"
>
{{ buttonLabel }}
</button>
<span
v-if="open"
class="absolute left-0 top-7 z-50 w-64 rounded-2xl border border-stone-200 bg-white p-4 text-left shadow-[0_18px_50px_rgba(28,25,23,0.16)]"
@pointerdown.stop
>
<span class="block text-[10px] font-bold uppercase tracking-[0.2em] text-stone-500">{{ title }}</span>
<span class="mt-2 block text-[11px] font-semibold leading-5 tracking-[0.04em] text-stone-700">{{ description }}</span>
<button
v-if="dismissible"
type="button"
class="mt-3 rounded-full border border-stone-200 px-3 py-2 text-[10px] font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-500 hover:text-stone-900"
@click="dismiss"
>
이상 보지 않기
</button>
</span>
</span>
</template>

View File

@@ -40,23 +40,23 @@ function selectYear(year) {
</script>
<template>
<section class="border border-stone-200 bg-white/80 p-5">
<div class="relative mb-4 flex items-start justify-between gap-4">
<div>
<section class="rounded-[24px] border border-stone-200 bg-white/82 p-4 shadow-[0_12px_36px_rgba(28,25,23,0.05)] sm:p-5">
<div class="relative mb-4 flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between sm:gap-4">
<div class="min-w-0">
<h2 class="text-[11px] font-bold tracking-[0.22em] text-ink">CALENDAR</h2>
<div class="mt-2 flex items-center gap-3">
<div class="mt-2 flex items-center gap-2 sm:gap-3">
<button
type="button"
class="rounded-full border border-stone-200 px-2 py-1 text-xs font-bold text-stone-600 transition hover:border-stone-400 hover:text-ink"
class="flex h-9 w-9 items-center justify-center rounded-full border border-stone-200 text-xs font-bold text-stone-600 transition hover:border-stone-400 hover:text-ink sm:h-auto sm:w-auto sm:px-2 sm:py-1"
@click="emit('shift-month', -1)"
>
</button>
<div class="flex items-center gap-2">
<p class="text-base font-semibold tracking-[-0.04em] text-stone-900">{{ monthLabel }}</p>
<div class="flex min-w-0 items-center gap-1.5 sm:gap-2">
<p class="text-[15px] font-semibold tracking-[-0.04em] text-stone-900 sm:text-base">{{ monthLabel }}</p>
<button
type="button"
class="rounded-full px-2 py-1 text-[11px] font-semibold tracking-[0.16em] text-stone-500 transition hover:bg-stone-100 hover:text-ink"
class="rounded-full px-2 py-1 text-[10px] font-semibold tracking-[0.16em] text-stone-500 transition hover:bg-stone-100 hover:text-ink sm:text-[11px]"
@click="isYearPickerOpen = !isYearPickerOpen"
>
{{ yearLabel }}
@@ -64,7 +64,7 @@ function selectYear(year) {
</div>
<button
type="button"
class="rounded-full border border-stone-200 px-2 py-1 text-xs font-bold text-stone-600 transition hover:border-stone-400 hover:text-ink"
class="flex h-9 w-9 items-center justify-center rounded-full border border-stone-200 text-xs font-bold text-stone-600 transition hover:border-stone-400 hover:text-ink sm:h-auto sm:w-auto sm:px-2 sm:py-1"
@click="emit('shift-month', 1)"
>
@@ -73,7 +73,7 @@ function selectYear(year) {
</div>
<button
type="button"
class="rounded-full border border-stone-200 px-3 py-2 text-[10px] font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
class="shrink-0 self-start rounded-full border border-stone-200 px-3 py-2 text-[10px] font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink sm:self-auto"
@click="emit('go-today')"
>
TODAY
@@ -81,7 +81,7 @@ function selectYear(year) {
<div
v-if="isYearPickerOpen"
class="absolute right-0 top-14 z-10 w-[220px] rounded-2xl border border-stone-200 bg-white p-4 shadow-lg"
class="absolute left-0 right-0 top-[88px] z-10 rounded-2xl border border-stone-200 bg-white p-4 shadow-lg sm:left-auto sm:right-0 sm:top-14 sm:w-[220px]"
>
<div class="mb-3 flex items-center justify-between">
<button
@@ -116,31 +116,38 @@ function selectYear(year) {
</div>
</div>
</div>
<div class="mb-3 grid grid-cols-7 gap-2 text-center text-[10px] font-bold tracking-[0.12em] text-stone-400">
<span v-for="weekday in ['S', 'M', 'T', 'W', 'T', 'F', 'S']" :key="weekday">{{ weekday }}</span>
<div class="mb-3 grid grid-cols-7 gap-1.5 text-center text-[9px] font-bold tracking-[0.1em] text-stone-400 sm:gap-2 sm:text-[10px] sm:tracking-[0.12em]">
<span
v-for="weekday in ['일', '월', '화', '수', '목', '금', '토']"
:key="weekday"
>
{{ weekday }}
</span>
</div>
<div class="grid grid-cols-7 gap-2">
<button
<div class="grid grid-cols-7 gap-1.5 sm:gap-2">
<div
v-for="day in days"
:key="day.key"
type="button"
class="aspect-square rounded-full border text-[11px] font-semibold transition"
:class="[
day.key === selectedKey
? 'border-ink bg-ink text-white'
: 'border-stone-200 bg-stone-50 text-stone-700 hover:border-stone-400 hover:bg-white',
day.isCurrentMonth ? '' : 'opacity-35',
]"
@click="emit('select', day.date)"
class="flex items-center justify-center"
>
<span class="relative flex h-full w-full items-center justify-center">
<button
type="button"
class="relative flex h-10 w-10 shrink-0 items-center justify-center rounded-full border text-[10px] font-semibold transition sm:h-[44px] sm:w-[44px] sm:text-[11px]"
:class="[
day.key === selectedKey
? 'border-ink bg-ink text-white'
: 'border-stone-200 bg-stone-50 text-stone-700 hover:border-stone-400 hover:bg-white',
day.isCurrentMonth ? '' : 'opacity-35',
]"
@click="emit('select', day.date)"
>
<span>{{ day.label }}</span>
<span
v-if="markedKeys.includes(day.key)"
class="absolute bottom-[3px] h-[5px] w-[5px] rounded-full bg-red-500"
class="absolute bottom-[3px] h-1 w-1 rounded-full bg-red-500 sm:h-[5px] sm:w-[5px]"
/>
</span>
</button>
</button>
</div>
</div>
</section>
</template>

View File

@@ -1,5 +1,6 @@
<script setup>
import { onBeforeUnmount } from 'vue'
import { onBeforeUnmount, ref } from 'vue'
import GuideTooltip from './GuideTooltip.vue'
const props = defineProps({
dateMain: {
@@ -16,7 +17,11 @@ const props = defineProps({
},
dday: {
type: String,
required: true,
default: '',
},
showDday: {
type: Boolean,
default: true,
},
comment: {
type: String,
@@ -46,6 +51,10 @@ const props = defineProps({
type: String,
default: 'SORI.STUDIO',
},
readonly: {
type: Boolean,
default: false,
},
})
const emit = defineEmits([
@@ -53,12 +62,15 @@ const emit = defineEmits([
'update:task-label',
'update:task-title',
'toggle:task',
'clear:tasks',
'update:memo-label',
'update:memo',
'update:timetable',
])
let dragState = null
let taskSelectionDrag = null
const selectedTaskIndexes = ref(new Set())
function shouldShowTaskPlaceholder(index) {
return index === 0 && props.tasks.every((task) => !task.title.trim())
@@ -77,6 +89,10 @@ function buildTimedRange(baseTimetable, startIndex, endIndex, nextValue) {
}
function startTimetableDrag(index, event) {
if (props.readonly) {
return
}
if (event.button !== 0 && event.button !== 2) {
return
}
@@ -93,7 +109,7 @@ function startTimetableDrag(index, event) {
}
function moveTimetableDrag(index) {
if (!dragState) {
if (props.readonly || !dragState) {
return
}
@@ -107,80 +123,245 @@ function stopTimetableDrag() {
dragState = null
}
function isTaskSelectionBlockedTarget(target) {
return Boolean(target.closest('button, textarea, [contenteditable="true"]'))
}
function getTaskSelectionRange(startIndex, endIndex) {
const rangeStart = Math.min(startIndex, endIndex)
const rangeEnd = Math.max(startIndex, endIndex)
return new Set(Array.from({ length: rangeEnd - rangeStart + 1 }, (_, offset) => rangeStart + offset))
}
function isTaskSelected(index) {
return selectedTaskIndexes.value.has(index)
}
function clearTaskSelection() {
selectedTaskIndexes.value = new Set()
taskSelectionDrag = null
}
function clearTaskSelectionOnFocus() {
if (taskSelectionDrag) {
return
}
clearTaskSelection()
}
function startTaskSelection(index, event) {
if (props.readonly) {
return
}
if (event.button !== 0 || isTaskSelectionBlockedTarget(event.target)) {
return
}
selectedTaskIndexes.value = new Set()
taskSelectionDrag = {
startIndex: index,
isSelecting: false,
}
}
function moveTaskSelection(index) {
if (!taskSelectionDrag) {
return
}
if (!taskSelectionDrag.isSelecting && index === taskSelectionDrag.startIndex) {
return
}
if (!taskSelectionDrag.isSelecting) {
taskSelectionDrag.isSelecting = true
document.activeElement?.blur?.()
window.getSelection()?.removeAllRanges?.()
}
selectedTaskIndexes.value = getTaskSelectionRange(taskSelectionDrag.startIndex, index)
}
function moveTaskSelectionFromPointer(event) {
if (!taskSelectionDrag) {
return
}
const taskRow = document.elementFromPoint(event.clientX, event.clientY)?.closest('[data-task-index]')
const index = Number(taskRow?.dataset.taskIndex)
if (Number.isInteger(index)) {
moveTaskSelection(index)
}
}
function stopTaskSelection() {
if (taskSelectionDrag && !taskSelectionDrag.isSelecting) {
selectedTaskIndexes.value = new Set()
}
taskSelectionDrag = null
}
function clearSelectedTasks(event) {
if (props.readonly) {
return
}
if (selectedTaskIndexes.value.size === 0) {
return
}
if (event.key === 'Escape') {
event.preventDefault()
clearTaskSelection()
return
}
if (!['Backspace', 'Delete'].includes(event.key)) {
return
}
event.preventDefault()
emit('clear:tasks', [...selectedTaskIndexes.value])
clearTaskSelection()
}
window.addEventListener('pointerup', stopTimetableDrag)
window.addEventListener('pointermove', moveTaskSelectionFromPointer)
window.addEventListener('pointerup', stopTaskSelection)
window.addEventListener('keydown', clearSelectedTasks)
onBeforeUnmount(() => {
window.removeEventListener('pointerup', stopTimetableDrag)
window.removeEventListener('pointermove', moveTaskSelectionFromPointer)
window.removeEventListener('pointerup', stopTaskSelection)
window.removeEventListener('keydown', clearSelectedTasks)
})
</script>
<template>
<article
class="planner-sheet flex w-full max-w-[762px] flex-col gap-3 bg-paper px-6 py-6 text-[10px] font-bold tracking-[0.16em] text-ink shadow-paper sm:px-12 sm:py-12"
class="planner-sheet flex w-full max-w-[762px] flex-col gap-3 bg-paper px-4 py-4 text-[10px] font-bold tracking-[0.16em] text-ink shadow-paper sm:px-8 sm:py-8 lg:px-12 lg:py-12"
>
<div class="flex flex-col gap-4 py-[18px]">
<div class="flex gap-4">
<div class="relative h-[90px] w-[394px] flex-1 border-t border-ink px-[10px] pt-[10px]">
<span class="absolute -top-2 left-0 bg-paper px-[2px] text-muted">YEAR / MONTH / DAY</span>
<p class="pt-6 text-xs tracking-[0.24em] text-ink sm:text-sm">
<div class="planner-sheet__meta flex flex-col gap-4 py-3 sm:py-[18px]">
<div class="planner-sheet__meta-top flex flex-col gap-3 sm:gap-4" :class="props.showDday ? 'sm:flex-row' : ''">
<div class="planner-field min-h-[82px] px-[10px] pt-[10px]" :class="props.showDday ? 'w-full sm:w-[394px] sm:flex-1' : 'w-full flex-1'">
<div class="planner-field__header flex items-center gap-2 text-muted">
<span class="shrink-0">YEAR / MONTH / DAY</span>
<span class="h-px flex-1 bg-ink"></span>
</div>
<p class="pt-6 text-[11px] tracking-[0.2em] text-ink sm:text-sm">
<span>{{ dateMain }}</span>
<span class="ml-1" :class="dateWeekdayTone">{{ dateWeekday }}</span>
</p>
</div>
<div class="relative h-[90px] w-[210px] border-t border-ink px-[10px] pt-[10px]">
<span class="absolute -top-2 left-0 bg-paper px-[2px] text-muted">D-DAY</span>
<p class="pt-6 text-xs tracking-[0.24em] text-ink sm:text-sm">{{ dday }}</p>
<div v-if="props.showDday" class="planner-field min-h-[82px] w-full px-[10px] pt-[10px] sm:w-[210px]">
<div class="planner-field__header flex items-center gap-2 text-muted">
<span class="shrink-0">D-DAY</span>
<span class="h-px flex-1 bg-ink"></span>
</div>
<p
class="pt-6 text-[11px] tracking-[0.14em] text-ink sm:text-sm"
style="
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-word;
"
>
{{ dday }}
</p>
</div>
</div>
<div class="flex gap-4 border-b border-ink pb-[18px]">
<div class="relative h-[90px] w-[394px] flex-1 border-t border-ink px-[10px] pt-[10px]">
<span class="absolute -top-2 left-0 bg-paper px-[2px] text-muted">COMMENT</span>
<div class="planner-sheet__meta-bottom flex flex-col gap-3 border-b border-ink pb-3 sm:gap-4 sm:pb-[18px] lg:flex-row">
<div class="planner-field min-h-[82px] w-full flex-1 px-[10px] pt-[10px] lg:w-[394px]">
<div class="planner-field__header flex items-center gap-2 text-muted">
<span class="shrink-0">COMMENT</span>
<span class="h-px flex-1 bg-ink"></span>
</div>
<textarea
:value="comment"
rows="3"
class="mt-4 h-[56px] w-full resize-none bg-transparent pt-2 text-[11px] font-semibold normal-case tracking-[0.08em] text-stone-700 outline-none placeholder:text-stone-400 sm:text-xs"
:readonly="props.readonly"
class="mt-3 h-[54px] w-full resize-none bg-transparent pt-2 text-[11px] font-semibold normal-case tracking-[0.06em] text-stone-700 outline-none placeholder:text-stone-400 sm:text-xs"
placeholder="오늘의 코멘트를 적어 주세요."
@input="emit('update:comment', $event.target.value)"
/>
</div>
<div class="relative h-[90px] w-[210px] border-t border-ink px-[10px] pt-[10px]">
<span class="absolute -top-2 left-0 bg-paper px-[2px] text-muted">TOTAL TIME</span>
<p class="pt-6 text-xs tracking-[0.24em] text-ink sm:text-sm">{{ totalTime }}</p>
<div class="planner-field min-h-[82px] w-full px-[10px] pt-[10px] lg:w-[210px]">
<div class="planner-field__header flex items-center gap-2 text-muted">
<span class="shrink-0">FOCUSED TIME</span>
<span class="h-px flex-1 bg-ink"></span>
</div>
<p class="pt-6 text-[11px] tracking-[0.2em] text-ink sm:text-sm">{{ totalTime }}</p>
</div>
</div>
</div>
<div class="flex gap-4 py-[10px]">
<div class="flex w-[394px] flex-1 flex-col gap-9">
<section class="relative">
<div class="absolute -top-[9px] left-0 bg-paper px-[2px] text-muted">TASKS</div>
<div class="border-t border-ink">
<div class="planner-sheet__body flex flex-col gap-5 py-[10px] lg:flex-row lg:gap-4">
<div class="planner-sheet__lists flex w-full flex-1 flex-col gap-[21px] lg:w-[394px]">
<section>
<div class="flex items-center gap-2 text-muted">
<span class="shrink-0">TASKS</span>
<span
v-if="selectedTaskIndexes.size > 0"
class="shrink-0 rounded-full border border-ink/30 px-2 py-[1px] text-[8px] tracking-[0.12em] text-ink"
>
선택 {{ selectedTaskIndexes.size }} · DEL 삭제 · ESC 취소
</span>
<span class="h-px flex-1 bg-ink"></span>
</div>
<div>
<div
v-for="(task, index) in tasks"
:key="task.id"
class="flex h-[38px] items-center border-b"
:class="index % 5 === 4 || index === tasks.length - 1 ? 'border-ink' : 'border-line'"
:key="task.id ?? index"
:data-task-index="index"
class="flex h-[38px] select-none items-center border-b transition-colors"
:class="[
index % 5 === 4 || index === tasks.length - 1 ? 'border-ink' : 'border-line',
isTaskSelected(index) ? 'bg-amber-100/55' : '',
]"
@pointerdown="startTaskSelection(index, $event)"
@pointerenter="moveTaskSelection(index)"
>
<div class="h-full w-[62px] border-r border-dashed border-ink px-2 py-[7px]">
<div class="h-full w-[52px] shrink-0 border-r border-dashed border-ink px-1.5 py-[7px] sm:w-[62px] sm:px-2">
<input
:value="task.label"
type="text"
:readonly="props.readonly"
class="w-full bg-transparent text-center text-[9px] font-semibold tracking-[0.08em] text-stone-500 outline-none placeholder:text-stone-300"
@focus="clearTaskSelectionOnFocus"
@input="emit('update:task-label', { index, value: $event.target.value })"
/>
</div>
<div class="flex min-w-0 flex-1 items-center px-3">
<div class="flex min-w-0 flex-1 items-center gap-2 px-2 sm:px-3">
<input
:value="task.title"
type="text"
class="w-full truncate bg-transparent text-[11px] font-semibold normal-case tracking-[0.06em] text-stone-800 outline-none placeholder:text-stone-400"
:readonly="props.readonly"
class="w-full truncate bg-transparent text-[10px] font-semibold normal-case tracking-[0.04em] text-stone-800 outline-none placeholder:text-stone-400 sm:text-[11px] sm:tracking-[0.06em]"
:placeholder="shouldShowTaskPlaceholder(index) ? '할 일을 입력해 주세요.' : ''"
@focus="clearTaskSelectionOnFocus"
@input="emit('update:task-title', { index, value: $event.target.value })"
/>
<GuideTooltip
v-if="task.carryoverFrom"
:title="'이월된 할 일'"
:description="`이 항목은 ${task.carryoverFrom}부터 이월된 할 일입니다.`"
:dismissible="false"
button-label="이월"
/>
</div>
<div class="flex h-full w-[42px] items-center justify-center p-[10px]">
<div class="flex h-full w-[36px] shrink-0 items-center justify-center p-[8px] sm:w-[42px] sm:p-[10px]">
<button
type="button"
class="flex h-full w-full items-center justify-center border border-dashed transition"
:disabled="props.readonly"
class="flex h-full w-full items-center justify-center border border-dashed transition focus-visible:ring-2 focus-visible:ring-ink focus-visible:ring-offset-2 focus-visible:ring-offset-paper"
:class="task.checked ? 'border-ink bg-stone-100 text-ink' : 'border-ink/60 text-transparent'"
@click="emit('toggle:task', index)"
>
@@ -191,28 +372,33 @@ onBeforeUnmount(() => {
</div>
</section>
<section class="relative">
<div class="absolute -top-2 left-0 bg-paper px-[2px] text-muted">MEMO</div>
<div class="border-t border-ink">
<section>
<div class="flex items-center gap-2 text-muted">
<span class="shrink-0">MEMO</span>
<span class="h-px flex-1 bg-ink"></span>
</div>
<div>
<div
v-for="(memoItem, index) in memo"
:key="`memo-${index}`"
class="flex h-[38px] items-center border-b"
:class="index === memo.length - 1 ? 'border-ink' : 'border-line'"
>
<div class="h-full w-[62px] border-r border-dashed border-ink px-2 py-[7px]">
<div class="h-full w-[52px] shrink-0 border-r border-dashed border-ink px-1.5 py-[7px] sm:w-[62px] sm:px-2">
<input
:value="memoItem.label"
type="text"
:readonly="props.readonly"
class="w-full bg-transparent text-center text-[9px] font-semibold tracking-[0.08em] text-stone-500 outline-none placeholder:text-stone-300"
@input="emit('update:memo-label', { index, value: $event.target.value })"
/>
</div>
<div class="flex flex-1 items-center px-3">
<div class="flex flex-1 items-center px-2 sm:px-3">
<input
:value="memoItem.text"
type="text"
class="w-full bg-transparent text-[11px] font-semibold normal-case tracking-[0.06em] text-stone-700 outline-none placeholder:text-stone-400"
:readonly="props.readonly"
class="w-full bg-transparent text-[10px] font-semibold normal-case tracking-[0.04em] text-stone-700 outline-none placeholder:text-stone-400 sm:text-[11px] sm:tracking-[0.06em]"
@input="emit('update:memo', { index, value: $event.target.value })"
/>
</div>
@@ -221,30 +407,35 @@ onBeforeUnmount(() => {
</section>
</div>
<section class="relative w-[210px] shrink-0">
<div class="absolute -top-2 left-0 bg-paper px-[2px] text-muted">TIME TABLE</div>
<div class="border-t border-ink">
<div
v-for="(hour, index) in hours"
:key="`${hour}-${index}`"
class="flex h-[30px] border-b"
:class="index === hours.length - 1 ? 'border-ink' : 'border-line'"
>
<section class="planner-sheet__timetable w-full shrink-0 lg:w-[210px]">
<div class="flex items-center gap-2 text-muted">
<span class="shrink-0">TIME TABLE</span>
<span class="h-px flex-1 bg-ink"></span>
</div>
<div class="planner-sheet__timetable-scroll overflow-x-auto pb-1">
<div class="planner-sheet__timetable-grid min-w-[210px]">
<div
class="flex h-full w-[30px] touch-none select-none items-center justify-center border-r border-ink text-[9px] text-ink"
@pointerdown.prevent
v-for="(hour, index) in hours"
:key="`${hour}-${index}`"
class="flex h-[25px] border-b sm:h-[30px]"
:class="index === hours.length - 1 ? 'border-ink' : 'border-line'"
>
{{ hour }}
<div
class="flex h-full w-[30px] touch-none select-none items-center justify-center border-r border-ink text-[9px] text-ink"
@pointerdown.prevent
>
{{ hour }}
</div>
<div
v-for="quarter in 6"
:key="quarter"
:class="props.timetable[index * 6 + quarter - 1] ? 'bg-stone-800/90' : 'bg-transparent'"
class="h-full w-[30px] cursor-crosshair border-r border-dashed border-line transition-colors last:border-r-0 touch-none select-none"
@contextmenu.prevent
@pointerdown.prevent="startTimetableDrag(index * 6 + quarter - 1, $event)"
@pointerenter="moveTimetableDrag(index * 6 + quarter - 1)"
/>
</div>
<div
v-for="quarter in 6"
:key="quarter"
:class="props.timetable[index * 6 + quarter - 1] ? 'bg-stone-800/90' : 'bg-transparent'"
class="h-full w-[30px] cursor-crosshair border-r border-dashed border-line transition-colors last:border-r-0 touch-none select-none"
@contextmenu.prevent
@pointerdown.prevent="startTimetableDrag(index * 6 + quarter - 1, $event)"
@pointerenter="moveTimetableDrag(index * 6 + quarter - 1)"
/>
</div>
</div>
</section>

View File

@@ -0,0 +1,307 @@
<script setup>
import { computed } from 'vue'
const props = defineProps({
user: {
type: Object,
required: true,
},
profileForm: {
type: Object,
required: true,
},
passwordForm: {
type: Object,
required: true,
},
accountDeleteForm: {
type: Object,
required: true,
},
authSessionInfo: {
type: Object,
required: true,
},
profileBusy: {
type: Boolean,
default: false,
},
passwordBusy: {
type: Boolean,
default: false,
},
profileMessage: {
type: String,
default: '',
},
passwordMessage: {
type: String,
default: '',
},
accountDeleteBusy: {
type: Boolean,
default: false,
},
accountDeleteMessage: {
type: String,
default: '',
},
guideTooltipResetMessage: {
type: String,
default: '',
},
carryoverCheckPolicy: {
type: String,
default: 'ask',
},
})
const emit = defineEmits([
'update:profile-field',
'update:password-field',
'submit:profile',
'submit:password',
'update:account-delete-field',
'submit:delete-account',
'reset-guide-tooltips',
'update:carryover-check-policy',
])
const initials = computed(() =>
`${props.user.nickname?.slice(0, 1) ?? ''}${props.user.email?.slice(0, 1) ?? ''}`.toUpperCase(),
)
function updateProfileField(field, event) {
emit('update:profile-field', {
field,
value: event.target.value,
})
}
function updatePasswordField(field, event) {
emit('update:password-field', {
field,
value: event.target.value,
})
}
function updateAccountDeleteField(field, event) {
emit('update:account-delete-field', {
field,
value: event.target.value,
})
}
</script>
<template>
<section class="grid gap-6 xl:grid-cols-[360px_minmax(0,1fr)]">
<aside class="rounded-[28px] border border-white/60 bg-white/70 p-6">
<p class="text-[11px] font-bold uppercase tracking-[0.28em] text-stone-500">Settings</p>
<div class="mt-6 flex items-center gap-4">
<div class="flex h-20 w-20 items-center justify-center rounded-full bg-stone-900 text-2xl font-bold tracking-[0.04em] text-white">
{{ initials || 'U' }}
</div>
<div>
<p class="text-xl font-semibold tracking-[-0.04em] text-stone-900">{{ user.nickname }}</p>
<p class="mt-1 text-sm font-semibold text-stone-500">{{ user.email }}</p>
</div>
</div>
<!-- <div class="mt-6 space-y-3 rounded-[24px] border border-stone-200 bg-[#fbf7f0] p-4">
<p class="text-[10px] font-bold tracking-[0.18em] text-stone-500">PROFILE NOTE</p>
<p class="text-sm font-semibold leading-6 text-stone-700">
...
</p>
</div> -->
<div class="mt-6 rounded-[24px] border border-stone-200 bg-white/80 p-4">
<p class="text-[10px] font-bold tracking-[0.18em] text-stone-500">GUIDE TOOLTIPS</p>
<p class="mt-3 text-sm font-semibold leading-6 text-stone-700">
숨긴 가이드 툴팁을 다시 표시합니다.
</p>
<button
type="button"
class="mt-4 rounded-full border border-stone-900 px-4 py-3 text-xs font-bold tracking-[0.14em] text-stone-900 transition hover:bg-stone-900 hover:text-white"
@click="emit('reset-guide-tooltips')"
>
가이드 다시 보기
</button>
<p
v-if="guideTooltipResetMessage"
class="mt-3 rounded-2xl border border-stone-200 bg-[#fbf7f0] px-4 py-3 text-xs font-semibold leading-5 text-stone-600"
>
{{ guideTooltipResetMessage }}
</p>
</div>
<div class="mt-4 rounded-[24px] border border-stone-200 bg-white/80 p-4">
<p class="text-[10px] font-bold tracking-[0.18em] text-stone-500">CARRYOVER CHECK</p>
<p class="mt-3 text-sm font-semibold leading-6 text-stone-700">
이월된 일을 완료할 이전 날짜 항목까지 함께 체크할지 정합니다.
</p>
<div class="mt-4 grid gap-2">
<button
v-for="option in [
{ value: 'ask', label: '항상 물어보기' },
{ value: 'all', label: '항상 이전까지 체크' },
{ value: 'current', label: '항상 오늘만 체크' },
]"
:key="option.value"
type="button"
class="rounded-2xl border px-4 py-3 text-left text-xs font-bold tracking-[0.12em] transition"
:class="carryoverCheckPolicy === option.value ? 'border-stone-900 bg-stone-900 text-white' : 'border-stone-200 bg-white text-stone-600 hover:border-stone-400 hover:text-stone-900'"
@click="emit('update:carryover-check-policy', option.value)"
>
{{ option.label }}
</button>
</div>
</div>
<div class="mt-4 rounded-[24px] border border-stone-200 bg-white/80 p-4">
<p class="text-[10px] font-bold tracking-[0.18em] text-stone-500">LOGIN STATUS</p>
<div class="mt-3 space-y-3">
<div class="rounded-2xl border border-stone-200 bg-[#fbf7f0] px-4 py-3">
<p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">현재 기기 저장 방식</p>
<p class="mt-2 text-sm font-semibold leading-6 text-stone-800">{{ authSessionInfo.storageLabel }}</p>
<p class="mt-1 text-xs font-semibold leading-5 text-stone-500">{{ authSessionInfo.storageDescription }}</p>
</div>
<div class="rounded-2xl border border-stone-200 bg-[#fbf7f0] px-4 py-3">
<p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">최근 로그인</p>
<p class="mt-2 text-sm font-semibold leading-6 text-stone-800">{{ authSessionInfo.lastLoginLabel }}</p>
</div>
<div
v-if="authSessionInfo.verificationLabel"
class="rounded-2xl border border-stone-200 bg-[#fbf7f0] px-4 py-3"
>
<p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">이메일 인증</p>
<p class="mt-2 text-sm font-semibold leading-6 text-stone-800">{{ authSessionInfo.verificationLabel }}</p>
</div>
</div>
</div>
</aside>
<div class="grid gap-6">
<form class="rounded-[28px] border border-white/60 bg-white/75 p-6" @submit.prevent="emit('submit:profile')">
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">Account Profile</p>
<div class="mt-5 grid gap-4 md:grid-cols-2">
<div class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">닉네임</label>
<input
:value="profileForm.nickname"
type="text"
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
@input="updateProfileField('nickname', $event)"
/>
</div>
<div class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">이메일</label>
<input
:value="profileForm.email"
type="email"
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
@input="updateProfileField('email', $event)"
/>
</div>
</div>
<p
v-if="profileMessage"
class="mt-4 rounded-2xl border border-stone-300 bg-white/80 px-4 py-3 text-sm font-semibold leading-6 text-stone-700"
>
{{ profileMessage }}
</p>
<button
type="submit"
class="mt-5 rounded-full bg-stone-900 px-5 py-3 text-xs font-bold tracking-[0.18em] text-white transition hover:bg-stone-700 disabled:cursor-not-allowed disabled:bg-stone-400"
:disabled="profileBusy"
>
{{ profileBusy ? '저장 중...' : '프로필 저장' }}
</button>
</form>
<form class="rounded-[28px] border border-white/60 bg-white/75 p-6" @submit.prevent="emit('submit:password')">
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">Password</p>
<div class="mt-5 grid gap-4 md:grid-cols-2">
<div class="space-y-2 md:col-span-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">현재 비밀번호</label>
<input
:value="passwordForm.currentPassword"
type="password"
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
@input="updatePasswordField('currentPassword', $event)"
/>
</div>
<div class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">새 비밀번호</label>
<input
:value="passwordForm.newPassword"
type="password"
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
@input="updatePasswordField('newPassword', $event)"
/>
</div>
<div class="space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">새 비밀번호 확인</label>
<input
:value="passwordForm.confirmPassword"
type="password"
class="w-full rounded-2xl border border-stone-300 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-500"
@input="updatePasswordField('confirmPassword', $event)"
/>
</div>
</div>
<p
v-if="passwordMessage"
class="mt-4 rounded-2xl border border-stone-300 bg-white/80 px-4 py-3 text-sm font-semibold leading-6 text-stone-700"
>
{{ passwordMessage }}
</p>
<button
type="submit"
class="mt-5 rounded-full border border-stone-900 px-5 py-3 text-xs font-bold tracking-[0.18em] text-stone-900 transition hover:bg-stone-900 hover:text-white disabled:cursor-not-allowed disabled:border-stone-300 disabled:text-stone-400"
:disabled="passwordBusy"
>
{{ passwordBusy ? '변경 중...' : '비밀번호 변경' }}
</button>
</form>
<form
v-if="user.role !== 'admin'"
class="rounded-[28px] border border-rose-200 bg-white/75 p-6"
@submit.prevent="emit('submit:delete-account')"
>
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-rose-500">Delete Account</p>
<p class="mt-4 text-sm font-semibold leading-6 text-stone-700">
회원 탈퇴를 진행하면 플래너 기록, 목표, 계정 정보가 함께 삭제됩니다.
</p>
<div class="mt-5 space-y-2">
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">현재 비밀번호 확인</label>
<input
:value="accountDeleteForm.currentPassword"
type="password"
class="w-full rounded-2xl border border-rose-200 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-rose-400"
@input="updateAccountDeleteField('currentPassword', $event)"
/>
</div>
<p
v-if="accountDeleteMessage"
class="mt-4 rounded-2xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm font-semibold leading-6 text-rose-700"
>
{{ accountDeleteMessage }}
</p>
<button
type="submit"
class="mt-5 rounded-full border border-rose-500 px-5 py-3 text-xs font-bold tracking-[0.18em] text-rose-600 transition hover:bg-rose-500 hover:text-white disabled:cursor-not-allowed disabled:border-rose-200 disabled:text-rose-300"
:disabled="accountDeleteBusy"
>
{{ accountDeleteBusy ? '처리 중...' : '회원 탈퇴' }}
</button>
</form>
</div>
</section>
</template>

View File

@@ -1,5 +1,8 @@
<script setup>
defineProps({
import { computed, ref } from 'vue'
import GuideTooltip from './GuideTooltip.vue'
const props = defineProps({
overviewCards: {
type: Array,
required: true,
@@ -30,18 +33,161 @@ defineProps({
},
})
const emit = defineEmits(['update:range-start', 'update:range-end'])
const emit = defineEmits(['update:range-start', 'update:range-end', 'quick-range'])
const flowScrollerRef = ref(null)
const flowDragState = ref(null)
const hoveredFlowRecord = ref(null)
const flowTooltipPosition = ref({ x: 0, y: 0 })
const flowGapClass = computed(() => {
if (props.weeklyRecords.length > 14) {
return 'gap-1'
}
return 'gap-3'
})
const flowItemStyle = computed(() => {
const count = props.weeklyRecords.length
if (count <= 0) {
return {}
}
const gap = count > 14 ? 4 : 12
const minWidth = count <= 7 ? 76 : count <= 14 ? 46 : 18
if (count <= 31) {
return {
flex: '0 0 auto',
width: `max(${minWidth}px, calc((100% - ${(count - 1) * gap}px) / ${count}))`,
}
}
return {
flex: '0 0 auto',
width: '18px',
}
})
const flowBarWidth = computed(() => {
if (props.weeklyRecords.length <= 7) {
return '48px'
}
if (props.weeklyRecords.length <= 14) {
return '30px'
}
return '12px'
})
const shouldShowFlowTime = computed(() => props.weeklyRecords.length <= 14)
function shouldShowFlowLabel(index) {
const count = props.weeklyRecords.length
if (count <= 14) {
return true
}
const interval = Math.ceil(count / 8)
return index === 0 || index === count - 1 || index % interval === 0
}
function updateFlowTooltipPosition(event) {
const tooltipWidth = 176
const tooltipHeight = 86
const margin = 12
const viewportWidth = window.innerWidth || tooltipWidth
const safeX = Math.min(
Math.max(event.clientX, margin + tooltipWidth / 2),
viewportWidth - margin - tooltipWidth / 2,
)
const safeY = Math.max(event.clientY - 18, margin + tooltipHeight)
flowTooltipPosition.value = {
x: safeX,
y: safeY,
}
}
function showFlowTooltip(record, event) {
hoveredFlowRecord.value = record
updateFlowTooltipPosition(event)
}
function moveFlowTooltip(event) {
if (!hoveredFlowRecord.value) {
return
}
updateFlowTooltipPosition(event)
}
function hideFlowTooltip() {
hoveredFlowRecord.value = null
}
function startFlowDrag(event) {
if (!flowScrollerRef.value || event.button !== 0) {
return
}
flowDragState.value = {
pointerId: event.pointerId,
startX: event.clientX,
scrollLeft: flowScrollerRef.value.scrollLeft,
}
flowScrollerRef.value.setPointerCapture?.(event.pointerId)
}
function moveFlowDrag(event) {
if (!flowDragState.value || !flowScrollerRef.value) {
return
}
event.preventDefault()
flowScrollerRef.value.scrollLeft =
flowDragState.value.scrollLeft - (event.clientX - flowDragState.value.startX)
}
function stopFlowDrag(event) {
if (!flowDragState.value) {
return
}
flowScrollerRef.value?.releasePointerCapture?.(event.pointerId)
flowDragState.value = null
}
</script>
<template>
<section class="grid gap-6">
<article class="rounded-[28px] border border-white/60 bg-white/80 p-5 shadow-paper backdrop-blur">
<article class="rounded-[28px] border border-stone-200 bg-white/86 p-5">
<div class="flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between">
<div>
<p class="text-[11px] font-bold tracking-[0.22em] text-stone-500">RANGE</p>
<h2 class="mt-2 text-2xl font-semibold tracking-[-0.05em] text-stone-900">
원하는 기간 기준으로 통계 보기
</h2>
<div class="mt-4 flex flex-wrap gap-2">
<button
type="button"
class="rounded-full border border-stone-200 bg-white px-4 py-2 text-[11px] font-bold tracking-[0.12em] text-stone-600 transition hover:border-stone-500 hover:text-stone-900"
@click="emit('quick-range', 7)"
>
최근 1
</button>
<button
type="button"
class="rounded-full border border-stone-200 bg-white px-4 py-2 text-[11px] font-bold tracking-[0.12em] text-stone-600 transition hover:border-stone-500 hover:text-stone-900"
@click="emit('quick-range', 30)"
>
최근 1
</button>
</div>
</div>
<div class="grid gap-3 sm:grid-cols-2">
<label class="flex flex-col gap-2 text-[11px] font-bold tracking-[0.14em] text-stone-500">
@@ -70,7 +216,7 @@ const emit = defineEmits(['update:range-start', 'update:range-end'])
<article
v-for="card in overviewCards"
:key="card.label"
class="rounded-[28px] border border-white/60 bg-white/80 p-5 shadow-paper backdrop-blur"
class="rounded-[28px] border border-stone-200 bg-white/86 p-5"
>
<p class="text-[11px] font-bold tracking-[0.22em] text-stone-500">{{ card.label }}</p>
<p class="mt-4 text-[34px] font-semibold tracking-[-0.06em] text-stone-900">{{ card.value }}</p>
@@ -78,43 +224,95 @@ const emit = defineEmits(['update:range-start', 'update:range-end'])
</article>
</div>
<div class="grid gap-6 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.7fr)]">
<article class="rounded-[28px] border border-white/60 bg-white/80 p-6 shadow-paper backdrop-blur">
<div class="grid items-start gap-6 xl:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.7fr)]">
<article class="rounded-[28px] border border-stone-200 bg-white/86 p-6">
<div class="flex items-end justify-between gap-4">
<div>
<p class="text-[11px] font-bold tracking-[0.22em] text-stone-500">WEEKLY FLOW</p>
<p class="text-[11px] font-bold tracking-[0.22em] text-stone-500">RANGE FLOW</p>
<h2 class="mt-2 text-2xl font-semibold tracking-[-0.05em] text-stone-900">
선택 기간 기록 흐름
선택 기간 날짜별 집중 흐름
</h2>
<p class="mt-2 text-[12px] font-semibold leading-5 text-stone-500">
기록이 있는 날짜만 날짜순으로 표시합니다.
</p>
</div>
<p class="text-[11px] font-semibold tracking-[0.06em] text-stone-500">
기준 날짜: {{ selectedDateLabel }}
</p>
</div>
<div class="mt-8 flex gap-3 overflow-x-auto pb-2">
<div
ref="flowScrollerRef"
class="mt-8 flex h-[268px] select-none items-stretch overflow-x-auto overscroll-x-contain border-b border-stone-200 pb-4 cursor-grab active:cursor-grabbing"
:class="flowGapClass"
@pointerdown="startFlowDrag"
@pointermove="moveFlowDrag"
@pointerup="stopFlowDrag"
@pointercancel="stopFlowDrag"
@pointerleave="stopFlowDrag"
>
<div
v-for="record in weeklyRecords"
v-for="(record, index) in weeklyRecords"
:key="record.key"
class="flex min-w-[56px] flex-col items-center gap-3"
class="relative flex flex-col items-center justify-end gap-3"
:style="flowItemStyle"
@mouseenter="showFlowTooltip(record, $event)"
@mousemove="moveFlowTooltip"
@mouseleave="hideFlowTooltip"
>
<div class="flex h-40 items-end">
<div class="flex h-44 items-end">
<div
class="w-10 rounded-full bg-stone-900/90 transition-all"
:style="{ height: `${record.barHeight}%` }"
class="rounded-t-full bg-stone-900/90 transition-all"
:style="{ width: flowBarWidth, height: `${record.barHeight}%` }"
/>
</div>
<div class="text-center">
<p class="text-[11px] font-bold tracking-[0.12em] text-stone-500">{{ record.weekday }}</p>
<p class="mt-1 text-[11px] font-semibold text-stone-800">{{ record.focusedTime }}</p>
<div class="h-14 text-center">
<template v-if="shouldShowFlowLabel(index)">
<p class="select-none text-[11px] font-bold tracking-[0.12em] text-stone-500">{{ record.dateLabel }}</p>
<p class="mt-1 select-none text-[10px] font-bold tracking-[0.12em] text-stone-400">{{ record.weekday }}</p>
</template>
<p
v-if="shouldShowFlowTime"
class="mt-1 select-none text-[11px] font-semibold text-stone-800"
>
{{ record.focusedTime }}
</p>
</div>
</div>
<p
v-if="weeklyRecords.length === 0"
class="flex min-h-[180px] w-full items-center justify-center rounded-2xl border border-dashed border-stone-300 text-sm font-semibold text-stone-500"
>
선택 기간에 기록이 없습니다.
</p>
</div>
<div
v-if="hoveredFlowRecord"
class="pointer-events-none fixed z-[80] w-44 -translate-x-1/2 -translate-y-full rounded-2xl border border-stone-200 bg-white px-3 py-2 text-left shadow-[0_16px_40px_rgba(28,25,23,0.14)]"
:style="{ left: `${flowTooltipPosition.x}px`, top: `${flowTooltipPosition.y}px` }"
>
<p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">
{{ hoveredFlowRecord.dateLabel }} {{ hoveredFlowRecord.weekday }}
</p>
<p class="mt-1 text-[11px] font-semibold text-stone-900">
FOCUSED {{ hoveredFlowRecord.focusedTime }}
</p>
<p class="mt-1 text-[10px] font-semibold tracking-[0.04em] text-stone-500">
TASKS {{ hoveredFlowRecord.completedTasks }} / {{ hoveredFlowRecord.totalTasks }}
</p>
</div>
</article>
<div class="grid gap-6">
<article class="rounded-[28px] border border-white/60 bg-white/80 p-6 shadow-paper backdrop-blur">
<p class="text-[11px] font-bold tracking-[0.22em] text-stone-500">BEST DAY</p>
<article class="rounded-[28px] border border-stone-200 bg-white/86 p-6">
<div class="flex items-center gap-2">
<p class="text-[11px] font-bold tracking-[0.22em] text-stone-500">BEST DAY</p>
<GuideTooltip
title="Best Day"
description="선택 범위 안에서 FOCUSED TIME이 가장 큰 날짜를 보여줍니다."
:dismissible="false"
/>
</div>
<div v-if="bestDay" class="mt-4">
<h2 class="text-2xl font-semibold tracking-[-0.05em] text-stone-900">
{{ bestDay.dateLabel }}
@@ -127,31 +325,44 @@ const emit = defineEmits(['update:range-start', 'update:range-end'])
아직 통계를 보여줄 기록이 충분하지 않습니다.
</p>
</article>
<article class="rounded-[28px] border border-white/60 bg-white/80 p-6 shadow-paper backdrop-blur">
<p class="text-[11px] font-bold tracking-[0.22em] text-stone-500">RECENT RECORDS</p>
<div class="mt-4 space-y-4">
<div
v-for="record in recentRecords"
:key="record.key"
class="rounded-2xl border border-stone-200 bg-stone-50/80 p-4"
>
<div class="flex items-start justify-between gap-4">
<div>
<p class="text-[12px] font-bold tracking-[0.08em] text-stone-900">{{ record.dateLabel }}</p>
<p class="mt-2 text-[11px] font-semibold leading-5 text-stone-600">
{{ record.comment || '코멘트 없음' }}
</p>
</div>
<div class="text-right">
<p class="text-sm font-semibold tracking-[-0.03em] text-stone-900">{{ record.focusedTime }}</p>
<p class="mt-1 text-[11px] font-semibold text-stone-500">{{ record.completionRate }}%</p>
</div>
</div>
</div>
</div>
</article>
</div>
</div>
<article class="rounded-[28px] border border-stone-200 bg-white/86 p-6">
<div class="flex items-center gap-2">
<p class="text-[11px] font-bold tracking-[0.22em] text-stone-500">RECENT RECORDS</p>
<GuideTooltip
title="Recent Records"
description="선택 범위 안의 기록을 날짜 내림차순으로 최대 5개까지 보여줍니다."
:dismissible="false"
/>
</div>
<div class="mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-5">
<div
v-for="record in recentRecords"
:key="record.key"
class="rounded-2xl border border-stone-200 bg-stone-50/80 p-4"
>
<div class="flex h-full flex-col justify-between gap-4">
<div>
<p class="text-[12px] font-bold tracking-[0.08em] text-stone-900">{{ record.dateLabel }}</p>
<p class="mt-2 text-[11px] font-semibold leading-5 text-stone-600">
{{ record.comment || '코멘트 없음' }}
</p>
</div>
<div>
<p class="text-sm font-semibold tracking-[-0.03em] text-stone-900">{{ record.focusedTime }}</p>
<p class="mt-1 text-[11px] font-semibold text-stone-500">완료율 {{ record.completionRate }}%</p>
</div>
</div>
</div>
<p
v-if="recentRecords.length === 0"
class="rounded-2xl border border-dashed border-stone-300 px-4 py-8 text-sm font-semibold text-stone-500"
>
선택 기간에 최근 기록이 없습니다.
</p>
</div>
</article>
</section>
</template>

21
src/lib/adminApi.js Normal file
View File

@@ -0,0 +1,21 @@
import { buildApiUrl, toUserFacingApiError } from './apiBase'
async function request(path, token) {
const response = await fetch(buildApiUrl(path), {
headers: {
Authorization: `Bearer ${token}`,
},
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
throw new Error(toUserFacingApiError(data, '관리자 데이터를 불러오지 못했습니다.'))
}
return data
}
export async function fetchAdminOverview(token) {
return request('/api/admin/overview', token)
}

46
src/lib/apiBase.js Normal file
View File

@@ -0,0 +1,46 @@
const DEFAULT_API_BASE_URL = 'http://localhost:3001'
function normalizeBaseUrl(baseUrl) {
return (baseUrl || DEFAULT_API_BASE_URL).replace(/\/+$/, '')
}
function normalizePath(path) {
return path.startsWith('/') ? path : `/${path}`
}
export function buildApiUrl(path) {
const baseUrl = normalizeBaseUrl(import.meta.env.VITE_API_BASE_URL)
const normalizedPath = normalizePath(path)
if (baseUrl.endsWith('/api') && normalizedPath.startsWith('/api/')) {
return `${baseUrl}${normalizedPath.slice(4)}`
}
return `${baseUrl}${normalizedPath}`
}
export function toUserFacingApiError(error, fallbackMessage) {
const rawMessage = `${error?.message ?? ''}`.trim()
if (!rawMessage) {
return fallbackMessage
}
if (
rawMessage.includes('Failed to fetch') ||
rawMessage.includes('NetworkError') ||
rawMessage.includes('Load failed')
) {
return '서버에 연결하지 못했습니다. 잠시 후 다시 시도해 주세요.'
}
if (
rawMessage.includes('Route ') ||
rawMessage.includes('not found') ||
rawMessage.includes('/api/')
) {
return '로그인 요청을 처리하지 못했습니다. 잠시 후 다시 시도해 주세요.'
}
return rawMessage
}

145
src/lib/authClient.js Normal file
View File

@@ -0,0 +1,145 @@
const AUTH_STORAGE_KEY = 'ten-minute-planner-auth'
import { buildApiUrl, toUserFacingApiError } from './apiBase'
function buildHeaders(token, hasBody, extraHeaders = {}) {
return {
...(hasBody ? { 'Content-Type': 'application/json' } : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
...extraHeaders,
}
}
async function request(path, { method = 'GET', token, body } = {}) {
const hasBody = body !== undefined
const response = await fetch(buildApiUrl(path), {
method,
headers: buildHeaders(token, hasBody),
body: hasBody ? JSON.stringify(body) : undefined,
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
throw new Error(toUserFacingApiError(data, '요청 처리 중 문제가 발생했습니다.'))
}
return data
}
export function readAuthState() {
if (typeof window === 'undefined') {
return { token: '', user: null, persist: false }
}
try {
const localState = JSON.parse(window.localStorage.getItem(AUTH_STORAGE_KEY) ?? 'null')
if (localState?.token) {
return { ...localState, persist: true }
}
const sessionState = JSON.parse(window.sessionStorage.getItem(AUTH_STORAGE_KEY) ?? 'null')
if (sessionState?.token) {
return { ...sessionState, persist: false }
}
return { token: '', user: null, persist: false }
} catch (error) {
console.warn('저장된 인증 상태를 불러오지 못했습니다.', error)
return { token: '', user: null, persist: false }
}
}
export function persistAuthState({ token, user, persist = false }) {
if (typeof window === 'undefined') {
return
}
const targetStorage = persist ? window.localStorage : window.sessionStorage
const unusedStorage = persist ? window.sessionStorage : window.localStorage
unusedStorage.removeItem(AUTH_STORAGE_KEY)
targetStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify({ token, user }))
}
export function clearAuthState() {
if (typeof window === 'undefined') {
return
}
window.localStorage.removeItem(AUTH_STORAGE_KEY)
window.sessionStorage.removeItem(AUTH_STORAGE_KEY)
}
export async function signup({ email, password, nickname }) {
return request('/api/auth/signup', {
method: 'POST',
body: { email, password, nickname },
})
}
export async function login({ email, password }) {
return request('/api/auth/login', {
method: 'POST',
body: { email, password },
})
}
export async function fetchCurrentUser(token) {
return request('/api/auth/me', {
token,
})
}
export async function logout(token) {
return request('/api/auth/logout', {
method: 'POST',
token,
})
}
export async function updateProfile(token, { email, nickname }) {
return request('/api/auth/profile', {
method: 'PUT',
token,
body: { email, nickname },
})
}
export async function updatePassword(token, { currentPassword, newPassword }) {
return request('/api/auth/password', {
method: 'PUT',
token,
body: { currentPassword, newPassword },
})
}
export async function deleteAccount(token, { currentPassword }) {
return request('/api/auth/account', {
method: 'DELETE',
token,
body: { currentPassword },
})
}
export async function requestPasswordReset({ email }) {
return request('/api/auth/password-reset/request', {
method: 'POST',
body: { email },
})
}
export async function confirmPasswordReset({ token, newPassword }) {
return request('/api/auth/password-reset/confirm', {
method: 'POST',
body: { token, newPassword },
})
}
export async function confirmVerification({ token }) {
return request('/api/auth/verification/confirm', {
method: 'POST',
body: { token },
})
}

65
src/lib/goalsApi.js Normal file
View File

@@ -0,0 +1,65 @@
import { buildApiUrl, toUserFacingApiError } from './apiBase'
function buildHeaders(token, hasBody) {
return {
...(hasBody ? { 'Content-Type': 'application/json' } : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
}
}
async function request(path, { method = 'GET', token, body } = {}) {
const hasBody = body !== undefined
const response = await fetch(buildApiUrl(path), {
method,
headers: buildHeaders(token, hasBody),
body: hasBody ? JSON.stringify(body) : undefined,
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
throw new Error(toUserFacingApiError(data, '목표 데이터를 처리하지 못했습니다.'))
}
return data
}
export async function fetchGoals(token, { query = '', status = 'active' } = {}) {
const searchParams = new URLSearchParams()
if (query) {
searchParams.set('query', query)
}
if (status) {
searchParams.set('status', status)
}
const queryString = searchParams.toString()
return request(`/api/goals${queryString ? `?${queryString}` : ''}`, {
token,
})
}
export async function createGoal(token, payload) {
return request('/api/goals', {
method: 'POST',
token,
body: payload,
})
}
export async function updateGoal(token, goalId, payload) {
return request(`/api/goals/${goalId}`, {
method: 'PATCH',
token,
body: payload,
})
}
export async function deleteGoal(token, goalId) {
return request(`/api/goals/${goalId}`, {
method: 'DELETE',
token,
})
}

59
src/lib/plannerApi.js Normal file
View File

@@ -0,0 +1,59 @@
import { buildApiUrl, toUserFacingApiError } from './apiBase'
function buildHeaders(token, hasBody) {
return {
...(hasBody ? { 'Content-Type': 'application/json' } : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
}
}
async function request(path, { method = 'GET', token, body } = {}) {
const hasBody = body !== undefined
const response = await fetch(buildApiUrl(path), {
method,
headers: buildHeaders(token, hasBody),
body: hasBody ? JSON.stringify(body) : undefined,
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
throw new Error(toUserFacingApiError(data, '플래너 데이터를 처리하지 못했습니다.'))
}
return data
}
export async function fetchPlannerEntries(token, range = {}) {
const searchParams = new URLSearchParams()
if (range.from) {
searchParams.set('from', range.from)
}
if (range.to) {
searchParams.set('to', range.to)
}
const query = searchParams.toString()
return request(`/api/planner${query ? `?${query}` : ''}`, {
token,
})
}
export async function savePlannerEntry(token, entryDate, payload) {
return request(`/api/planner/${entryDate}`, {
method: 'PUT',
token,
body: {
payload,
},
})
}
export async function deletePlannerEntry(token, entryDate) {
return request(`/api/planner/${entryDate}`, {
method: 'DELETE',
token,
})
}

View File

@@ -13,6 +13,10 @@ function readStorageState() {
}
}
export function readPlannerStorageState() {
return readStorageState()
}
export function createInitialPlannerRecords(seedRecords, normalizeRecord) {
const baseRecords = Object.fromEntries(
Object.entries(seedRecords).map(([key, record]) => [key, normalizeRecord(record)]),
@@ -36,16 +40,8 @@ export function restorePlannerUiState({
toDateValue,
}) {
const savedState = readStorageState()
if (savedState.selectedDate) {
selectedDate.value = toDateValue(savedState.selectedDate, selectedDate.value)
}
if (savedState.calendarViewDate) {
calendarViewDate.value = toDateValue(savedState.calendarViewDate, selectedDate.value)
} else {
calendarViewDate.value = new Date(selectedDate.value)
}
selectedDate.value = toDateValue(new Date(), selectedDate.value)
calendarViewDate.value = new Date(selectedDate.value)
if (savedState.statsRangeStart) {
statsRangeStart.value = savedState.statsRangeStart
@@ -62,31 +58,38 @@ export function persistPlannerState({
calendarViewDate,
statsRangeStart,
statsRangeEnd,
includeRecords = true,
}) {
if (typeof window === 'undefined') {
return
}
const serializableRecords = Object.fromEntries(
Object.entries(plannerRecords).map(([key, record]) => [
key,
{
...record,
tasks: record.tasks.map((task) => ({ ...task })),
memo: record.memo.map((item) => ({ ...item })),
timetable: [...record.timetable],
},
]),
)
const previousState = readStorageState()
const nextState = {
...previousState,
statsRangeStart,
statsRangeEnd,
}
delete nextState.selectedDate
delete nextState.calendarViewDate
if (includeRecords) {
nextState.records = Object.fromEntries(
Object.entries(plannerRecords).map(([key, record]) => [
key,
{
...record,
tasks: record.tasks.map((task) => ({ ...task })),
memo: record.memo.map((item) => ({ ...item })),
timetable: [...record.timetable],
},
]),
)
}
window.localStorage.setItem(
STORAGE_KEY,
JSON.stringify({
selectedDate: selectedDate.toISOString(),
calendarViewDate: calendarViewDate.toISOString(),
statsRangeStart,
statsRangeEnd,
records: serializableRecords,
}),
JSON.stringify(nextState),
)
}

View File

@@ -22,12 +22,16 @@
}
@media print {
@page {
margin: 0;
}
html,
body {
background: #ffffff !important;
width: auto !important;
height: auto !important;
overflow: hidden !important;
overflow: visible !important;
}
body {
@@ -46,17 +50,11 @@
}
.print-only {
display: flex !important;
display: block !important;
width: 100% !important;
height: 100% !important;
height: auto !important;
margin: 0 !important;
padding: 0 !important;
align-items: center;
justify-content: center;
break-inside: avoid-page;
page-break-inside: avoid;
break-after: avoid-page;
page-break-after: avoid;
}
.print-root {
@@ -75,28 +73,37 @@
justify-content: center;
background: #ffffff !important;
padding: 0;
margin: 0 auto;
overflow: hidden;
break-after: page;
page-break-after: always;
break-inside: avoid-page;
page-break-inside: avoid;
}
.print-paper:last-child {
break-after: avoid-page;
page-break-after: avoid;
}
body[data-print-layout='single'] .print-paper {
width: 204mm;
height: 291mm;
align-items: flex-start;
width: 210mm;
height: 297mm;
align-items: center;
justify-content: center;
padding-top: 3mm;
}
.print-paper--double {
display: grid !important;
grid-template-columns: repeat(2, 141mm);
grid-template-columns: repeat(2, 139mm);
justify-content: center;
align-content: center;
column-gap: 3mm;
column-gap: 4mm;
}
body[data-print-layout='double'] .print-paper {
width: 287mm;
height: 198mm;
width: 297mm;
height: 210mm;
}
body[data-print-layout='single'] .print-paper--single .print-sheet-frame {
@@ -112,9 +119,13 @@
background: #ffffff !important;
}
.print-sheet-frame--blank {
background: #ffffff !important;
}
body[data-print-layout='double'] .print-paper--double .print-sheet-frame {
width: 141mm;
height: 198mm;
width: 139mm;
height: 196mm;
}
.planner-sheet {
@@ -125,7 +136,7 @@
width: 762px !important;
max-width: none !important;
transform-origin: top left;
transform: scale(0.978);
transform: scale(0.982);
box-shadow: none !important;
background: #ffffff !important;
}
@@ -134,7 +145,7 @@
width: 762px !important;
max-width: none !important;
transform-origin: top left;
transform: scale(0.694);
transform: scale(0.6894);
box-shadow: none !important;
background: #ffffff !important;
}
@@ -143,6 +154,89 @@
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
.planner-sheet__meta-top,
.planner-sheet__meta-bottom,
.planner-sheet__body {
display: flex !important;
flex-direction: row !important;
gap: 16px !important;
}
.planner-sheet__meta {
gap: 14px !important;
padding-top: 10px !important;
padding-bottom: 10px !important;
}
.planner-sheet__meta-top > div,
.planner-sheet__meta-bottom > div {
min-height: 78px !important;
overflow: visible !important;
}
.planner-sheet__meta-bottom > div:first-child {
width: auto !important;
max-width: none !important;
flex: 1 1 auto !important;
min-width: 0 !important;
}
.planner-sheet__meta-bottom > div:last-child {
width: 210px !important;
max-width: 210px !important;
flex: 0 0 210px !important;
}
.planner-field__header {
width: 100% !important;
min-width: 0 !important;
}
.planner-field__header > span:first-child {
white-space: nowrap !important;
letter-spacing: 0.16em !important;
}
.planner-sheet__meta-bottom > div:last-child > p {
padding-top: 24px !important;
white-space: nowrap !important;
}
.planner-sheet__lists {
width: 394px !important;
flex: 1 1 auto !important;
}
.planner-sheet__timetable {
width: 210px !important;
flex-shrink: 0 !important;
}
.planner-sheet__timetable-scroll {
overflow: visible !important;
padding-bottom: 0 !important;
}
.planner-sheet__timetable-grid {
min-width: 210px !important;
}
.planner-sheet textarea {
height: 58px !important;
min-height: 58px !important;
max-height: 58px !important;
overflow: hidden !important;
padding-top: 4px !important;
line-height: 1.55 !important;
white-space: pre-wrap !important;
word-break: break-word !important;
}
.print-paper--double .print-sheet-frame {
align-items: flex-start !important;
justify-content: flex-start !important;
}
}
@media screen {
@@ -150,3 +244,34 @@
display: none !important;
}
}
.panel-fade-enter-active,
.panel-fade-leave-active {
transition: opacity 220ms ease;
}
.panel-fade-enter-from,
.panel-fade-leave-to {
opacity: 0;
}
.drawer-left-enter-active,
.drawer-left-leave-active,
.drawer-right-enter-active,
.drawer-right-leave-active {
transition:
transform 260ms cubic-bezier(0.22, 1, 0.36, 1),
opacity 220ms ease;
}
.drawer-left-enter-from,
.drawer-left-leave-to {
opacity: 0;
transform: translateX(-24px) scale(0.985);
}
.drawer-right-enter-from,
.drawer-right-leave-to {
opacity: 0;
transform: translateX(24px) scale(0.985);
}

View File

@@ -3,4 +3,12 @@ import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
host: '0.0.0.0',
port: 5173,
strictPort: true,
watch: {
usePolling: true,
},
},
})