Compare commits
45 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b18af56c3c | |||
| 3c3b0d20dd | |||
| bf62eb12bb | |||
| 370c169c1c | |||
| 249a68e89d | |||
| 2462d79053 | |||
| 4e1263348e | |||
| 4d48176555 | |||
| c372f325ab | |||
| f11c0d3cef | |||
| 98d4209958 | |||
| bf06cd28c1 | |||
| 962a338b3d | |||
| 9e96a57504 | |||
| 905a0caf75 | |||
| e221254c60 | |||
| 1738a7d3b6 | |||
| 9760c9dc0e | |||
| b972209c2f | |||
| bc2e981577 | |||
| 8ff4c979fa | |||
| 9b788406ea | |||
| fe538fc88b | |||
| 4355185203 | |||
| 440f0f46a1 | |||
| 1e58c58373 | |||
| 20564ba34b | |||
| a53ef4cc6f | |||
| 282d51daf6 | |||
| f718342b93 | |||
| 5b1c4bcfca | |||
| 20095a79db | |||
| d5aa7f8153 | |||
| 7ff8bd06b1 | |||
| 066cab311b | |||
| 934f561f86 | |||
| c3202d0b92 | |||
| 75f9590e45 | |||
| e87155f909 | |||
| f3b2c84758 | |||
| 314dd7f649 | |||
| 0206cfebf8 | |||
| 85d21f5842 | |||
| d6dda9639b | |||
| 5c380e0562 |
8
.dockerignore
Normal file
8
.dockerignore
Normal file
@@ -0,0 +1,8 @@
|
||||
node_modules
|
||||
dist
|
||||
.git
|
||||
.gitignore
|
||||
backend/node_modules
|
||||
backend/data
|
||||
backend/drizzle
|
||||
*.log
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,5 +1,7 @@
|
||||
node_modules/
|
||||
backend/node_modules/
|
||||
dist/
|
||||
.DS_Store
|
||||
*.log
|
||||
|
||||
backend/.env
|
||||
backend/data/
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
## 커밋 규칙
|
||||
|
||||
- 사용자가 버전형 체크포인트를 원할 경우 `v0.0.1` 같은 형식으로 커밋을 남긴다.
|
||||
- 버전 커밋만 단독으로 쓰지 말고, `v0.1.7 - 저장 레이어 분리`처럼 버전 뒤에 작업 요약을 함께 남긴다.
|
||||
- 의미를 알기 어려운 큰 커밋보다, 이해 가능한 작은 단위의 커밋을 선호한다.
|
||||
|
||||
## 디자인 구현 규칙
|
||||
|
||||
20
Dockerfile
Normal file
20
Dockerfile
Normal 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
|
||||
155
HANDOFF.md
155
HANDOFF.md
@@ -4,7 +4,8 @@
|
||||
|
||||
- 프로젝트명: 10 Minute Planner 웹 UI
|
||||
- 기술 스택: Vue 3 + Vite + TailwindCSS + JavaScript
|
||||
- 현재 기준 버전: `v0.0.5`
|
||||
- 현재 기준 버전: `v0.1.39` 준비 중
|
||||
- Git 원격 저장소: `https://git.sori.studio/zenn/planner.sori.studio.git`
|
||||
|
||||
## 기준 디자인
|
||||
|
||||
@@ -16,21 +17,76 @@
|
||||
- 기본 UX 방향은 `1페이지 + 추가 정보 패널`이다.
|
||||
- `2페이지 펼침 보기`는 비교용 보조 모드로 함께 유지한다.
|
||||
- 화면 인상은 종이 다이어리 같아야 하지만, 상호작용은 웹앱처럼 빠르고 자연스러워야 한다.
|
||||
- 현재는 개인용 단일 브라우저 흐름으로 개발 중이지만, 이후 회원 기반 개인 문서 관리 서비스로 확장해야 한다.
|
||||
- 최종적으로는 프론트엔드와 백엔드를 Docker로 묶어서 UGREEN NAS에서 구동할 예정이다.
|
||||
- `backend/` 폴더에 백엔드 초안이 추가되었고, 현재는 프론트와 분리된 구조로 관리한다.
|
||||
|
||||
## 현재 구현 상태
|
||||
|
||||
- 메인 화면 셸: `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`는 화면에서 바로 편집할 수 있다.
|
||||
- TASKS 왼쪽 라벨은 순번 고정이 아니라 자유 입력 가능하며, 기본값은 빈 상태다.
|
||||
- MEMO 왼쪽 라벨 칸도 자유 입력 가능하다.
|
||||
- TASKS 체크박스는 토글 가능하며, 체크 상태는 바로 시각적으로 반영된다.
|
||||
- STATS 완료율은 전체 15칸이 아니라, 실제로 입력된 TASKS만 기준으로 계산한다.
|
||||
- `TIME TABLE`은 드래그로 10분 블록을 연속 선택할 수 있다.
|
||||
- `TIME TABLE`은 우클릭 드래그 시 선택된 블록을 지우는 방식으로도 편집할 수 있다.
|
||||
- `TIME TABLE` 숫자 영역은 선택/드래그로 텍스트가 잡히지 않도록 막아두었다.
|
||||
- `TOTAL TIME`은 타임테이블에서 선택된 블록 수를 기준으로 자동 계산된다.
|
||||
- 달력은 연/월 이동이 가능하며, 현재 보이는 월과 선택된 날짜 상태를 분리해서 관리한다.
|
||||
- 달력 상단은 월 좌우 화살표, 클릭형 연도 선택, `TODAY` 버튼 구조로 동작한다.
|
||||
- 입력 내용이 있는 날짜는 달력 하단에 빨간 점으로 표시된다.
|
||||
- 상단 날짜 표시에서는 토요일의 `(토)`만 파란색, 일요일의 `(일)`만 빨간색으로 표시한다.
|
||||
- 플래너 상태는 `localStorage`에 저장되며, 날짜별 기록과 선택 날짜, 달력 보고 있던 월까지 복원된다.
|
||||
- `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일 흐름, 최근 기록, 베스트 데이를 보여준다.
|
||||
- 통계 화면은 시작일/종료일을 직접 선택해 그 기간 기준으로 지표를 다시 계산할 수 있다.
|
||||
- `NEXT DAY` 영역의 요일도 본문 날짜와 같은 규칙으로 주말 색상이 적용된다.
|
||||
- 플래너 화면에서는 `PRINT DAY` 버튼으로 현재 선택 날짜 문서를 바로 출력할 수 있다.
|
||||
- 인쇄 시에는 현재 선택된 하루 플래너 본문만 남기고, 헤더/사이드패널/통계 화면은 숨긴다.
|
||||
- 출력 버튼은 `PRINT 1-UP` / `PRINT 2-UP`으로 분리되어 있다.
|
||||
- `PRINT 2-UP`은 현재 날짜와 다음 날짜를 A4 가로 기준으로 나란히 출력하는 용도다.
|
||||
- 인쇄는 일반 화면을 그대로 찍는 방식이 아니라, 별도의 `print-only` 전용 레이아웃을 사용한다.
|
||||
- A5 원본 비율을 유지한 채 A4 가로 안에 들어가도록 `1-UP` / `2-UP` 각각 별도 배율로 압축한다.
|
||||
- `PRINT 1-UP`은 A4 세로, `PRINT 2-UP`은 A4 가로 기준으로 분리해서 처리한다.
|
||||
- 브라우저 기본 인쇄 머리말/꼬리말이 켜져 있어도 2장으로 넘어가지 않도록 실제 인쇄 영역은 종이보다 조금 작게 잡는다.
|
||||
- 인쇄 시 `main`, `print-only`, `print-paper` 래퍼의 패딩/높이/페이지 분할 규칙까지 함께 제어해야 빈 2페이지를 줄일 수 있다.
|
||||
- `1-UP`은 여백이 과하지 않도록 다시 확대했고, `2-UP`은 한 페이지 고정 안정성을 위해 가로 폭과 세로 높이를 조금 더 보수적으로 조정했다.
|
||||
- `1-UP`은 세로 가운데 정렬을 없애고 상단 기준으로 붙여야 여백이 덜 커 보인다.
|
||||
- 현재 `1-UP`은 프레임 자체를 A4 세로에 가깝게 키우고 배율을 크게 올려 빈 여백을 줄이는 방향으로 맞추고 있다.
|
||||
- 백엔드 초안은 `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/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`은 코드 자체보다 실행 환경 제약에 가깝다.
|
||||
|
||||
## 확정된 결정사항
|
||||
|
||||
@@ -38,20 +94,115 @@
|
||||
날짜 전환, 모드 토글, 사이드 패널 요약, 이후 저장 기능 등 상태 기반 상호작용이 많기 때문이다.
|
||||
- TailwindCSS는 Vue를 사용하더라도 반드시 유지해야 하는 스타일링 방식이다.
|
||||
- 현재 데이터는 레이아웃과 상호작용 검증을 위한 목업 데이터다.
|
||||
- 현재 저장은 `localStorage`를 사용하지만, 적절한 시점에 DB를 붙여 사용자별 저장 구조로 전환해야 한다.
|
||||
- 백엔드는 빠른 MVP라면 PocketBase도 가능하지만, 현재 요구사항에서는 전용 Node.js API + DB 구성이 더 유연하다.
|
||||
- 이유는 회원가입, 사용자별 문서 관리, 통계 계산, 출력/이미지 저장, 이후 Docker Compose 배포까지 고려하면 서버 로직 제어권이 더 중요하기 때문이다.
|
||||
- 상단 날짜는 시스템 날짜 또는 현재 선택된 플래너 날짜 기준으로 자동 표시되어야 한다.
|
||||
- `D-DAY`는 지금은 보류이며, 이후 별도의 목표 관리 패널과 연결해서 계산한다.
|
||||
- `COMMENT`, `TASKS`, `MEMO`는 모두 입력 가능한 필드가 되어야 한다.
|
||||
- TASKS 라벨은 번호만 고정하지 말고 자유 입력이 가능해야 한다.
|
||||
- 번호 사용이 필요한 경우를 위해 우측 패널에서 TASKS 라벨을 순번으로 한 번에 채울 수 있어야 한다.
|
||||
- `TOTAL TIME`은 타임테이블 선택 상태를 기반으로 자동 계산되어야 한다.
|
||||
- 타임테이블은 마우스 드래그로 여러 줄을 지나가더라도 시간 흐름 기준으로 연속 선택되도록 해석해야 한다.
|
||||
- 타임테이블 편집은 좌클릭 드래그로 칠하기, 우클릭 드래그로 지우기 방식이 더 자연스럽다.
|
||||
- 달력에는 연/월 이동 기능이 필요하다.
|
||||
- 내용이 저장된 날짜에는 달력에 빨간 점 표시가 필요하다.
|
||||
- 현재 단계의 저장 방식은 `localStorage`이며, 이후 외부 저장소 도입 전까지 기본 저장 경로로 사용한다.
|
||||
- 장기적으로는 회원 가입 후 사용자별로 각자 문서를 작성/관리할 수 있어야 한다.
|
||||
- 공유 문서 서비스가 아니라, 사용자 개인 보관과 회고 중심의 서비스 구조를 목표로 한다.
|
||||
- 사용자는 스스로 통계를 확인할 수 있어야 하고, 특정 날짜에 작성한 문서는 출력 가능해야 한다.
|
||||
- 공유를 위해 나중에 이미지 저장 기능도 필요하지만, 실제 출력 품질과 텍스트 선명도는 HTML/CSS 인쇄 레이아웃을 우선 유지하는 편이 좋다.
|
||||
- 원격 저장소 `origin`은 `https://git.sori.studio/zenn/planner.sori.studio.git`로 연결되어 있다.
|
||||
- 앞으로 버전 체크포인트 커밋은 `v0.1.7 - 작업 요약`처럼 버전 뒤에 짧은 작업 설명을 함께 남기는 형식으로 통일한다.
|
||||
- `docker-compose.yml` 초안은 이미 추가되었고, 포트 번호와 실제 외부 공개 범위는 NAS 배포 단계에서 다시 확정하면 된다.
|
||||
- `backend/.env.example`에는 기본 `PORT`, `DATABASE_URL`, `CORS_ORIGIN` 예시가 들어 있다.
|
||||
|
||||
## 다음 권장 작업
|
||||
|
||||
- `TODO.md` 기준으로 작은 단위씩 구현을 진행한다.
|
||||
- 목표나 통계 기능보다 먼저, 플래너 본문의 입력과 상호작용을 우선 구현한다.
|
||||
- 달력 표시와 통계 기능을 본격화하기 전에 저장 구조를 먼저 정리하는 것이 좋다.
|
||||
- 통계 화면 구현은 현재 `localStorage` 기반으로 먼저 진행해도 된다.
|
||||
- DB는 기능 탐색 속도를 해치지 않는 선에서, 저장 레이어를 분리할 수 있는 적절한 시점에 붙이는 것이 좋다.
|
||||
- 현재 기준 추천 백엔드 방향은 `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 무료 플랜은 도메인 1개 제약이 있어 현재 프로젝트 인증 메일에는 바로 쓰기 어렵다. 다음 단계에서는 AWS SES 또는 범용 SMTP 공급자 기준으로 메일 발송 추상화를 붙이는 쪽이 적합하다.
|
||||
- 현재 인증 메일/재설정 메일은 실제 발송 대신 개발용 `previewUrl`을 응답으로 돌려주는 단계다. 프론트 UI 연결과 실제 메일러 연결은 다음 단계에서 마무리하면 된다.
|
||||
- 미니 달력 날짜 버튼은 원형 비율이 흔들리지 않도록 고정 `width/height` 기준으로 다시 맞췄다.
|
||||
- 플래너 본문 D-DAY 텍스트는 3줄까지만 보이고, 넘치면 말줄임 처리되도록 정리했다.
|
||||
- 목표가 없는 빈 날짜에서는 `D-DAY 사용` 토글이 저장 상태와 무관하게 `OFF + 비활성`처럼 보이도록 보정했다.
|
||||
- 비로그인 랜딩 카드는 상단 고정이 아니라 화면 중앙에 오도록 정렬을 수정했다.
|
||||
- 현재 환경에서는 Docker 데몬이 꺼져 있어서 `docker compose build` 실검증은 하지 못했고, 데몬 시작 후 다시 확인이 필요하다.
|
||||
- 이미지 저장 기능은 추후 `print-only` 또는 별도 export 전용 레이아웃을 기준으로 구현하면 화면/인쇄/공유 결과를 맞추기 쉽다.
|
||||
- Docker Compose는 프론트엔드와 백엔드를 함께 올리는 기준으로 설계하되, NAS 환경에 맞는 볼륨과 재시작 정책도 함께 고려한다.
|
||||
|
||||
## 갱신 규칙
|
||||
|
||||
|
||||
57
README.md
Normal file
57
README.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# 10 Minute Planner
|
||||
|
||||
Vue 3 + TailwindCSS + Fastify + PostgreSQL 기반의 `10분 플래너 다이어리` 프로젝트다.
|
||||
|
||||
## 실행 방법
|
||||
|
||||
### 개발용
|
||||
|
||||
코드를 수정하면서 자동 새로고침까지 보려면 개발용 compose를 사용한다.
|
||||
|
||||
```bash
|
||||
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:8080`
|
||||
- PostgreSQL: `localhost:5432`
|
||||
|
||||
배포용 특징:
|
||||
|
||||
- 프론트는 빌드 결과물을 nginx로 서빙한다.
|
||||
- 브라우저에서는 `/api` 경로로 백엔드에 접근한다.
|
||||
- 수정 사항 반영 시에는 다시 빌드가 필요하다.
|
||||
|
||||
## 문서
|
||||
|
||||
- 작업 규칙: [`AGENTS.md`](./AGENTS.md)
|
||||
- 진행 상태 / 체크리스트: [`TODO.md`](./TODO.md)
|
||||
- 인수인계 메모: [`HANDOFF.md`](./HANDOFF.md)
|
||||
|
||||
## 현재 방향
|
||||
|
||||
- 기본 UX는 `1페이지 + 우측 정보 패널`
|
||||
- 보조 모드는 `2페이지 펼침 보기`
|
||||
- 스타일링은 Vue + TailwindCSS
|
||||
- 장기적으로는 Docker 기반으로 UGREEN NAS 배포 예정
|
||||
96
TODO.md
96
TODO.md
@@ -7,7 +7,7 @@
|
||||
- 기본 레이아웃은 `1페이지 + 우측 정보 패널`을 유지한다.
|
||||
- `2페이지 펼침 보기`는 비교용 보조 모드로 유지한다.
|
||||
- 스타일은 Vue + TailwindCSS 기준으로 구현한다.
|
||||
- D-DAY는 목표 관리 패널과 연결되는 기능으로 추후 구현한다.
|
||||
- D-DAY는 목표 관리 패널과 연결하는 구조로 전환했고, 세부 확장은 계속 진행한다.
|
||||
|
||||
## 1단계: 플래너 핵심 상호작용
|
||||
|
||||
@@ -24,30 +24,104 @@
|
||||
- [x] 달력에 연/월 이동 기능을 추가한다.
|
||||
- [x] 선택 날짜를 클릭하면 해당 날짜 플래너 데이터로 이동되게 한다.
|
||||
- [x] 입력값이 하나라도 있는 날짜에는 달력 하단에 빨간 점 표시를 추가한다.
|
||||
- [ ] `PREV DAY` / `NEXT DAY` 이동 시 현재 편집 중 데이터와 연결되도록 정리한다.
|
||||
- [x] `PREV DAY` / `NEXT DAY` 이동 시 현재 편집 중 데이터와 연결되도록 정리한다.
|
||||
|
||||
## 추가 반영 메모
|
||||
|
||||
- [x] TASKS 왼쪽 라벨은 자유 입력 가능해야 한다.
|
||||
- [x] 우측 패널에서 TASKS 번호를 한 번에 채우는 빠른 액션이 있어야 한다.
|
||||
- [x] 달력 상단은 좌우 화살표로 월 이동하는 구조가 더 적합하다.
|
||||
- [x] 연도 클릭 시 연도 선택 UI가 열려야 한다.
|
||||
- [x] 오늘 날짜로 즉시 돌아가는 버튼이 필요하다.
|
||||
|
||||
## 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] DB 전환 시점을 잡을 수 있도록 저장 레이어를 분리한다.
|
||||
- [x] 회원 가입 및 로그인 구조를 고려한 사용자별 데이터 모델을 설계한다.
|
||||
- [x] 사용자별 문서 저장/조회 흐름을 정리한다.
|
||||
- [ ] 출력용 문서 포맷과 프린트 흐름을 고려한 데이터 구조를 정리한다.
|
||||
|
||||
## 추가 반영 메모
|
||||
|
||||
- [x] 상단 날짜 표시에서 토요일 요일 텍스트만 파란색으로 표시한다.
|
||||
- [x] 상단 날짜 표시에서 일요일 요일 텍스트만 빨간색으로 표시한다.
|
||||
|
||||
## 5단계: 확장 화면
|
||||
|
||||
- [ ] 통계 페이지 요구사항을 정리한다.
|
||||
- [ ] 통계 페이지 라우팅 또는 화면 전환 구조를 설계한다.
|
||||
- [ ] 집중 시간, 완료율, 연속 기록 같은 핵심 지표를 정의한다.
|
||||
- [x] 통계 페이지 요구사항을 정리한다.
|
||||
- [x] 통계 페이지 라우팅 또는 화면 전환 구조를 설계한다.
|
||||
- [x] 집중 시간, 완료율, 연속 기록 같은 핵심 지표를 정의한다.
|
||||
- [x] 사용자가 시작일과 종료일을 선택해서 기간별 통계를 볼 수 있게 한다.
|
||||
- [ ] 사용자 개인 통계 화면 기준을 정리한다.
|
||||
|
||||
## 6단계: 계정 및 서비스 확장
|
||||
|
||||
- [x] 회원 가입 / 로그인 방식 후보를 정리한다.
|
||||
- [x] 사용자 설정 화면에서 닉네임 / 이메일 / 비밀번호 수정 흐름을 분리한다.
|
||||
- [x] 상단 헤더를 왼쪽 사이드 내비게이션 구조로 재배치한다.
|
||||
- [x] 본문과 오른쪽 패널이 각각 독립 스크롤되도록 조정한다.
|
||||
- [ ] 사용자별 문서 분리 저장 구조를 설계한다.
|
||||
- [ ] 공유가 아닌 개인 보관용 서비스 흐름으로 요구사항을 정리한다.
|
||||
- [x] 향후 출력 기능을 위한 인쇄 레이아웃 요구사항을 정리한다.
|
||||
- [x] A4 가로 기준 2장 출력 모드를 지원한다.
|
||||
- [x] `1-UP` 세로 인쇄 / `2-UP` 가로 인쇄 기준을 분리한다.
|
||||
- [ ] 공유를 위한 이미지 저장 기능을 추가한다.
|
||||
- [x] Docker 배포 구조를 정리한다.
|
||||
- [x] UGREEN NAS 기준 `docker-compose.yml` 초안을 작성한다.
|
||||
- [x] 백엔드 기본 스캐폴딩을 추가한다.
|
||||
- [x] PostgreSQL 전환 초안을 적용한다.
|
||||
- [ ] 이메일 인증 플로우를 설계하고 구현한다.
|
||||
- [ ] 비밀번호 찾기 / 재설정 토큰 흐름을 추가한다.
|
||||
- [ ] 로그인 및 인증 관련 rate limit / 잠금 정책을 추가한다.
|
||||
- [ ] 메일 발송 인프라와 발신 도메인 정책을 확정한다.
|
||||
- [ ] Resend 무료 플랜 대체 수단으로 SES 또는 일반 SMTP 연동 방식을 확정한다.
|
||||
|
||||
## 메모
|
||||
|
||||
- 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 + 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로 끌 수 있다.
|
||||
- 목표 생성 시 표시 시작일 기본값은 오늘, 표시 종료일 기본값은 목표일로 맞춘다.
|
||||
- 표시 기간이 다른 진행 중 목표와 겹치면 프론트와 백엔드 모두 저장을 막는다.
|
||||
- TASK LABELS는 버튼 묶음 대신 동일한 토글 패턴으로 단순화했다.
|
||||
- 구현할 때마다 완료된 항목은 체크하고, 큰 결정사항은 `HANDOFF.md`에도 함께 반영한다.
|
||||
- Resend 무료 플랜은 도메인 수 제약이 있으므로, 실제 인증 메일은 AWS SES 또는 별도 SMTP 서비스 전환을 전제로 설계하는 편이 안전하다.
|
||||
|
||||
3
backend/.env.example
Normal file
3
backend/.env.example
Normal file
@@ -0,0 +1,3 @@
|
||||
PORT=3001
|
||||
DATABASE_URL=postgresql://planner:planner1234@localhost:5432/ten_minute_planner
|
||||
CORS_ORIGIN=http://localhost:5173
|
||||
14
backend/Dockerfile
Normal file
14
backend/Dockerfile
Normal 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"]
|
||||
17
backend/drizzle.config.js
Normal file
17
backend/drizzle.config.js
Normal file
@@ -0,0 +1,17 @@
|
||||
import { config } from 'dotenv'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = path.dirname(__filename)
|
||||
|
||||
config({ path: path.join(__dirname, '.env') })
|
||||
|
||||
export default {
|
||||
schema: './src/db/schema.js',
|
||||
out: './drizzle',
|
||||
dialect: 'postgresql',
|
||||
dbCredentials: {
|
||||
url: process.env.DATABASE_URL ?? 'postgresql://planner:planner1234@localhost:5432/ten_minute_planner',
|
||||
},
|
||||
}
|
||||
2529
backend/package-lock.json
generated
Normal file
2529
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
23
backend/package.json
Normal file
23
backend/package.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "ten-minute-planner-backend",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node --watch src/server.js",
|
||||
"start": "node src/server.js",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^10.0.1",
|
||||
"dotenv": "^16.4.7",
|
||||
"drizzle-orm": "^0.39.1",
|
||||
"fastify": "^5.2.1",
|
||||
"pg": "^8.13.3",
|
||||
"zod": "^3.24.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"drizzle-kit": "^0.30.4"
|
||||
}
|
||||
}
|
||||
19
backend/src/config.js
Normal file
19
backend/src/config.js
Normal file
@@ -0,0 +1,19 @@
|
||||
import { config } from 'dotenv'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { z } from 'zod'
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const __dirname = path.dirname(__filename)
|
||||
|
||||
config({ path: path.join(__dirname, '..', '.env') })
|
||||
|
||||
const envSchema = z.object({
|
||||
PORT: z.coerce.number().default(3001),
|
||||
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'),
|
||||
})
|
||||
|
||||
export const env = envSchema.parse(process.env)
|
||||
12
backend/src/db/client.js
Normal file
12
backend/src/db/client.js
Normal file
@@ -0,0 +1,12 @@
|
||||
import { drizzle } from 'drizzle-orm/node-postgres'
|
||||
import pg from 'pg'
|
||||
import { env } from '../config.js'
|
||||
import * as schema from './schema.js'
|
||||
|
||||
const { Pool } = pg
|
||||
|
||||
export const pool = new Pool({
|
||||
connectionString: env.DATABASE_URL,
|
||||
})
|
||||
|
||||
export const db = drizzle(pool, { schema })
|
||||
83
backend/src/db/init.js
Normal file
83
backend/src/db/init.js
Normal file
@@ -0,0 +1,83 @@
|
||||
import { pool } from './client.js'
|
||||
|
||||
export async function ensureDatabaseSchema() {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
email VARCHAR(255) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(255) NOT NULL,
|
||||
nickname VARCHAR(60) NOT NULL,
|
||||
email_verified_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
ALTER TABLE users
|
||||
ADD COLUMN IF NOT EXISTS email_verified_at TIMESTAMPTZ;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auth_sessions (
|
||||
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 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);
|
||||
`)
|
||||
}
|
||||
98
backend/src/db/schema.js
Normal file
98
backend/src/db/schema.js
Normal file
@@ -0,0 +1,98 @@
|
||||
import {
|
||||
integer,
|
||||
index,
|
||||
jsonb,
|
||||
pgTable,
|
||||
serial,
|
||||
timestamp,
|
||||
uniqueIndex,
|
||||
varchar,
|
||||
} from 'drizzle-orm/pg-core'
|
||||
|
||||
export const users = pgTable('users', {
|
||||
id: serial('id').primaryKey(),
|
||||
email: varchar('email', { length: 255 }).notNull().unique(),
|
||||
passwordHash: varchar('password_hash', { length: 255 }).notNull(),
|
||||
nickname: varchar('nickname', { length: 60 }).notNull(),
|
||||
emailVerifiedAt: timestamp('email_verified_at', { withTimezone: true }),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).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 = 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),
|
||||
}),
|
||||
)
|
||||
65
backend/src/lib/authSession.js
Normal file
65
backend/src/lib/authSession.js
Normal file
@@ -0,0 +1,65 @@
|
||||
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 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)
|
||||
|
||||
return user ?? null
|
||||
}
|
||||
47
backend/src/lib/password.js
Normal file
47
backend/src/lib/password.js
Normal file
@@ -0,0 +1,47 @@
|
||||
import crypto from 'node:crypto'
|
||||
|
||||
const SCRYPT_KEY_LENGTH = 64
|
||||
|
||||
function scryptAsync(password, salt) {
|
||||
return new Promise((resolve, reject) => {
|
||||
crypto.scrypt(password, salt, SCRYPT_KEY_LENGTH, (error, derivedKey) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
return
|
||||
}
|
||||
|
||||
resolve(derivedKey)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export async function hashPassword(password) {
|
||||
const salt = crypto.randomBytes(16).toString('hex')
|
||||
const derivedKey = await scryptAsync(password, salt)
|
||||
return `${salt}:${derivedKey.toString('hex')}`
|
||||
}
|
||||
|
||||
export async function verifyPassword(password, storedHash) {
|
||||
const [salt, originalHash] = storedHash.split(':')
|
||||
|
||||
if (!salt || !originalHash) {
|
||||
return false
|
||||
}
|
||||
|
||||
const derivedKey = await scryptAsync(password, salt)
|
||||
const originalBuffer = Buffer.from(originalHash, 'hex')
|
||||
|
||||
if (originalBuffer.length !== derivedKey.length) {
|
||||
return false
|
||||
}
|
||||
|
||||
return crypto.timingSafeEqual(originalBuffer, derivedKey)
|
||||
}
|
||||
|
||||
export function createSessionToken() {
|
||||
return crypto.randomBytes(32).toString('hex')
|
||||
}
|
||||
|
||||
export function hashSessionToken(token) {
|
||||
return crypto.createHash('sha256').update(token).digest('hex')
|
||||
}
|
||||
487
backend/src/routes/auth.js
Normal file
487
backend/src/routes/auth.js
Normal file
@@ -0,0 +1,487 @@
|
||||
import { and, eq, gt, isNull } from 'drizzle-orm'
|
||||
import { env } from '../config.js'
|
||||
import { z } from 'zod'
|
||||
import { db } from '../db/client.js'
|
||||
import { authSessions, emailVerificationTokens, passwordResetTokens, users } from '../db/schema.js'
|
||||
import { createSessionToken, hashSessionToken, hashPassword, verifyPassword } from '../lib/password.js'
|
||||
import { createSession, findAuthenticatedUser } from '../lib/authSession.js'
|
||||
|
||||
const signupSchema = z.object({
|
||||
email: z.string().trim().email(),
|
||||
password: z.string().min(8).max(72),
|
||||
nickname: z.string().trim().min(2).max(30),
|
||||
})
|
||||
|
||||
const loginSchema = z.object({
|
||||
email: z.string().trim().email(),
|
||||
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 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,
|
||||
nickname: user.nickname,
|
||||
emailVerifiedAt: user.emailVerifiedAt,
|
||||
createdAt: user.createdAt,
|
||||
updatedAt: user.updatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
export async function registerAuthRoutes(app) {
|
||||
app.post('/api/auth/signup', async (request, reply) => {
|
||||
const payload = signupSchema.safeParse(request.body)
|
||||
|
||||
if (!payload.success) {
|
||||
return reply.code(400).send({
|
||||
message: '회원가입 입력값이 올바르지 않습니다.',
|
||||
issues: payload.error.flatten(),
|
||||
})
|
||||
}
|
||||
|
||||
const { email, password, nickname } = payload.data
|
||||
const normalizedEmail = email.toLowerCase()
|
||||
|
||||
const [existingUser] = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.email, normalizedEmail))
|
||||
.limit(1)
|
||||
|
||||
if (existingUser) {
|
||||
return reply.code(409).send({
|
||||
message: '이미 사용 중인 이메일입니다.',
|
||||
})
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
const passwordHash = await hashPassword(password)
|
||||
|
||||
const [user] = await db
|
||||
.insert(users)
|
||||
.values({
|
||||
email: normalizedEmail,
|
||||
passwordHash,
|
||||
nickname,
|
||||
emailVerifiedAt: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
.returning()
|
||||
|
||||
const { token } = await createSession(user.id)
|
||||
const verification = await createEmailVerificationToken(user.id)
|
||||
|
||||
return reply.code(201).send({
|
||||
message: '회원가입이 완료되었습니다.',
|
||||
token,
|
||||
user: sanitizeUser(user),
|
||||
verificationPreviewUrl: verification.previewUrl,
|
||||
})
|
||||
})
|
||||
|
||||
app.post('/api/auth/login', async (request, reply) => {
|
||||
const payload = loginSchema.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 reply.code(401).send({
|
||||
message: '이메일 또는 비밀번호가 올바르지 않습니다.',
|
||||
})
|
||||
}
|
||||
|
||||
const passwordMatches = await verifyPassword(payload.data.password, user.passwordHash)
|
||||
|
||||
if (!passwordMatches) {
|
||||
return reply.code(401).send({
|
||||
message: '이메일 또는 비밀번호가 올바르지 않습니다.',
|
||||
})
|
||||
}
|
||||
|
||||
const { token } = await createSession(user.id)
|
||||
|
||||
return {
|
||||
message: '로그인에 성공했습니다.',
|
||||
token,
|
||||
user: sanitizeUser(user),
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/api/auth/me', async (request, reply) => {
|
||||
const user = await findAuthenticatedUser(request)
|
||||
|
||||
if (!user) {
|
||||
return reply.code(401).send({
|
||||
message: '인증이 필요합니다.',
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
user: sanitizeUser(user),
|
||||
}
|
||||
})
|
||||
|
||||
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 [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.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)
|
||||
|
||||
return {
|
||||
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)
|
||||
|
||||
return {
|
||||
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
304
backend/src/routes/goals.js
Normal 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: '목표가 삭제되었습니다.',
|
||||
}
|
||||
})
|
||||
}
|
||||
185
backend/src/routes/planner.js
Normal file
185
backend/src/routes/planner.js
Normal 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,
|
||||
}
|
||||
})
|
||||
}
|
||||
58
backend/src/server.js
Normal file
58
backend/src/server.js
Normal file
@@ -0,0 +1,58 @@
|
||||
import Fastify from 'fastify'
|
||||
import cors from '@fastify/cors'
|
||||
import { env } from './config.js'
|
||||
import { pool } from './db/client.js'
|
||||
import { ensureDatabaseSchema } from './db/init.js'
|
||||
import { registerAuthRoutes } from './routes/auth.js'
|
||||
import { registerGoalRoutes } from './routes/goals.js'
|
||||
import { registerPlannerRoutes } from './routes/planner.js'
|
||||
|
||||
const app = Fastify({
|
||||
logger: true,
|
||||
})
|
||||
|
||||
await ensureDatabaseSchema()
|
||||
|
||||
await app.register(cors, {
|
||||
origin: env.CORS_ORIGIN,
|
||||
credentials: true,
|
||||
})
|
||||
|
||||
await registerAuthRoutes(app)
|
||||
await registerGoalRoutes(app)
|
||||
await registerPlannerRoutes(app)
|
||||
|
||||
app.get('/health', async () => {
|
||||
const versionResult = await pool.query('select version() as version')
|
||||
const version = versionResult.rows[0]
|
||||
|
||||
return {
|
||||
status: 'ok',
|
||||
service: 'ten-minute-planner-backend',
|
||||
database: {
|
||||
client: 'postgresql',
|
||||
version: version?.version ?? 'unknown',
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/api/meta', async () => ({
|
||||
auth: 'active',
|
||||
storage: 'postgresql',
|
||||
orm: 'drizzle',
|
||||
notes: [
|
||||
'회원가입, 로그인, 현재 사용자 확인 API가 준비되어 있습니다.',
|
||||
'사용자별 목표 목록, 수정, 삭제 API가 준비되어 있습니다.',
|
||||
'사용자별 플래너 저장 및 조회 API가 준비되어 있습니다.',
|
||||
],
|
||||
}))
|
||||
|
||||
try {
|
||||
await app.listen({
|
||||
port: env.PORT,
|
||||
host: '0.0.0.0',
|
||||
})
|
||||
} catch (error) {
|
||||
app.log.error(error)
|
||||
process.exit(1)
|
||||
}
|
||||
26
deploy/nginx/default.conf
Normal file
26
deploy/nginx/default.conf
Normal 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;
|
||||
}
|
||||
}
|
||||
61
docker-compose.dev.yml
Normal file
61
docker-compose.dev.yml
Normal file
@@ -0,0 +1,61 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: ten-minute-postgres-dev
|
||||
environment:
|
||||
POSTGRES_DB: ten_minute_planner
|
||||
POSTGRES_USER: planner
|
||||
POSTGRES_PASSWORD: planner1234
|
||||
volumes:
|
||||
- postgres_dev_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U planner -d ten_minute_planner"]
|
||||
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"
|
||||
environment:
|
||||
PORT: 3001
|
||||
DATABASE_URL: postgresql://planner:planner1234@postgres:5432/ten_minute_planner
|
||||
CORS_ORIGIN: http://localhost:5173
|
||||
SESSION_TTL_DAYS: 30
|
||||
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"
|
||||
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:
|
||||
49
docker-compose.yml
Normal file
49
docker-compose.yml
Normal file
@@ -0,0 +1,49 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
container_name: ten-minute-postgres
|
||||
environment:
|
||||
POSTGRES_DB: ten_minute_planner
|
||||
POSTGRES_USER: planner
|
||||
POSTGRES_PASSWORD: planner1234
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U planner -d ten_minute_planner"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
container_name: ten-minute-backend
|
||||
environment:
|
||||
PORT: 3001
|
||||
DATABASE_URL: postgresql://planner:planner1234@postgres:5432/ten_minute_planner
|
||||
CORS_ORIGIN: http://localhost:8080
|
||||
SESSION_TTL_DAYS: 30
|
||||
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
|
||||
depends_on:
|
||||
- backend
|
||||
ports:
|
||||
- "8080:80"
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ten-minute-planner",
|
||||
"version": "0.0.5",
|
||||
"version": "0.1.39",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ten-minute-planner",
|
||||
"version": "0.0.5",
|
||||
"version": "0.1.39",
|
||||
"dependencies": {
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
{
|
||||
"name": "ten-minute-planner",
|
||||
"private": true,
|
||||
"version": "0.0.5",
|
||||
"version": "0.1.39",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:backend": "npm --prefix backend run dev",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
"preview": "vite preview",
|
||||
"db:generate": "npm --prefix backend run db:generate",
|
||||
"db:migrate": "npm --prefix backend run db:migrate"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.5.13"
|
||||
|
||||
2382
src/App.vue
2382
src/App.vue
File diff suppressed because it is too large
Load Diff
129
src/components/AuthDialog.vue
Normal file
129
src/components/AuthDialog.vue
Normal file
@@ -0,0 +1,129 @@
|
||||
<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.value,
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="open"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-stone-900/45 px-4 py-8 backdrop-blur-sm"
|
||||
>
|
||||
<div class="w-full max-w-md rounded-[28px] border border-white/60 bg-[#f6f1e8] p-6 shadow-2xl sm:p-7">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div class="space-y-2">
|
||||
<p class="text-[11px] font-bold uppercase tracking-[0.24em] text-stone-500">Account</p>
|
||||
<h2 class="text-2xl font-semibold tracking-[-0.04em] text-stone-900">
|
||||
{{ mode === 'login' ? '로그인' : '회원가입' }}
|
||||
</h2>
|
||||
<p class="text-sm leading-6 text-stone-600">
|
||||
{{ mode === 'login' ? '저장된 플래너를 다시 이어서 볼 수 있습니다.' : '사용자별 기록과 통계를 연결하기 위한 계정을 만듭니다.' }}
|
||||
</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 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 class="space-y-2">
|
||||
<label class="text-[11px] font-bold tracking-[0.16em] text-stone-600">이메일</label>
|
||||
<input
|
||||
:value="form.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"
|
||||
placeholder="zenn@example.com"
|
||||
@input="updateField('email', $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div 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 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>
|
||||
|
||||
<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"
|
||||
>
|
||||
{{ busy ? '처리 중...' : mode === 'login' ? 'LOGIN' : 'SIGN UP' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="mt-5 flex items-center justify-between gap-3 rounded-2xl border border-stone-300 bg-white/70 px-4 py-3">
|
||||
<p class="text-sm font-semibold text-stone-600">
|
||||
{{ mode === 'login' ? '아직 계정이 없나요?' : '이미 계정이 있나요?' }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs font-bold tracking-[0.16em] text-stone-900 underline underline-offset-4"
|
||||
@click="emit('switch-mode', mode === 'login' ? 'signup' : 'login')"
|
||||
>
|
||||
{{ mode === 'login' ? '회원가입' : '로그인' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
216
src/components/GoalsDashboard.vue
Normal file
216
src/components/GoalsDashboard.vue
Normal 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>
|
||||
@@ -1,5 +1,7 @@
|
||||
<script setup>
|
||||
defineProps({
|
||||
import { computed, ref } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
monthLabel: {
|
||||
type: String,
|
||||
required: true,
|
||||
@@ -22,79 +24,130 @@ defineProps({
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits(['select', 'shift-month', 'shift-year'])
|
||||
const emit = defineEmits(['select', 'shift-month', 'shift-year', 'go-today'])
|
||||
|
||||
const isYearPickerOpen = ref(false)
|
||||
const currentYearNumber = computed(() => Number(props.yearLabel))
|
||||
const yearRangeStart = computed(() => currentYearNumber.value - (currentYearNumber.value % 12))
|
||||
const visibleYears = computed(() =>
|
||||
Array.from({ length: 12 }, (_, index) => yearRangeStart.value + index),
|
||||
)
|
||||
|
||||
function selectYear(year) {
|
||||
emit('shift-year', year - currentYearNumber.value)
|
||||
isYearPickerOpen.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="border border-stone-200 bg-white/80 p-5">
|
||||
<div class="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 space-y-1">
|
||||
<p class="text-base font-semibold tracking-[-0.04em] text-stone-900">{{ monthLabel }}</p>
|
||||
<p class="text-[11px] font-semibold tracking-[0.16em] text-stone-500">{{ yearLabel }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="mt-2 flex items-center gap-2 sm:gap-3">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-stone-200 px-3 py-1 text-[10px] font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
|
||||
@click="emit('shift-year', -1)"
|
||||
>
|
||||
-1Y
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-stone-200 px-3 py-1 text-[10px] font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
|
||||
@click="emit('shift-year', 1)"
|
||||
>
|
||||
+1Y
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-stone-200 px-3 py-1 text-[10px] font-bold tracking-[0.14em] 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)"
|
||||
>
|
||||
PREV
|
||||
←
|
||||
</button>
|
||||
<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-[10px] font-semibold tracking-[0.16em] text-stone-500 transition hover:bg-stone-100 hover:text-ink sm:text-[11px]"
|
||||
@click="isYearPickerOpen = !isYearPickerOpen"
|
||||
>
|
||||
{{ yearLabel }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-full border border-stone-200 px-3 py-1 text-[10px] font-bold tracking-[0.14em] 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)"
|
||||
>
|
||||
NEXT
|
||||
→
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
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
|
||||
</button>
|
||||
|
||||
<div
|
||||
v-if="isYearPickerOpen"
|
||||
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
|
||||
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"
|
||||
@click="emit('shift-year', -12)"
|
||||
>
|
||||
←
|
||||
</button>
|
||||
<p class="text-[11px] font-bold tracking-[0.16em] text-stone-500">
|
||||
{{ visibleYears[0] }} - {{ visibleYears[visibleYears.length - 1] }}
|
||||
</p>
|
||||
<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"
|
||||
@click="emit('shift-year', 12)"
|
||||
>
|
||||
→
|
||||
</button>
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-2">
|
||||
<button
|
||||
v-for="year in visibleYears"
|
||||
:key="year"
|
||||
type="button"
|
||||
class="rounded-xl border px-3 py-2 text-[11px] font-semibold transition"
|
||||
:class="year === currentYearNumber ? 'border-ink bg-ink text-white' : 'border-stone-200 text-stone-700 hover:border-stone-400 hover:bg-stone-50'"
|
||||
@click="selectYear(year)"
|
||||
>
|
||||
{{ year }}
|
||||
</button>
|
||||
</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>
|
||||
|
||||
@@ -2,14 +2,26 @@
|
||||
import { onBeforeUnmount } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
dateLabel: {
|
||||
dateMain: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
dday: {
|
||||
dateWeekday: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
dateWeekdayTone: {
|
||||
type: String,
|
||||
default: 'text-ink',
|
||||
},
|
||||
dday: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
showDday: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
comment: {
|
||||
type: String,
|
||||
required: true,
|
||||
@@ -42,14 +54,20 @@ const props = defineProps({
|
||||
|
||||
const emit = defineEmits([
|
||||
'update:comment',
|
||||
'update:task-label',
|
||||
'update:task-title',
|
||||
'toggle:task',
|
||||
'update:memo-label',
|
||||
'update:memo',
|
||||
'update:timetable',
|
||||
])
|
||||
|
||||
let dragState = null
|
||||
|
||||
function shouldShowTaskPlaceholder(index) {
|
||||
return index === 0 && props.tasks.every((task) => !task.title.trim())
|
||||
}
|
||||
|
||||
function buildTimedRange(baseTimetable, startIndex, endIndex, nextValue) {
|
||||
const nextTimetable = [...baseTimetable]
|
||||
const rangeStart = Math.min(startIndex, endIndex)
|
||||
@@ -101,61 +119,81 @@ onBeforeUnmount(() => {
|
||||
|
||||
<template>
|
||||
<article
|
||||
class="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]">
|
||||
<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="relative min-h-[82px] border-t border-ink px-[10px] pt-[10px]" :class="props.showDday ? 'w-full sm:w-[394px] sm:flex-1' : 'w-full flex-1'">
|
||||
<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">{{ dateLabel }}</p>
|
||||
<p class="pt-5 text-[11px] tracking-[0.2em] text-ink sm:pt-6 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]">
|
||||
<div v-if="props.showDday" class="relative min-h-[82px] w-full border-t border-ink px-[10px] pt-[10px] sm:w-[210px]">
|
||||
<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>
|
||||
<p
|
||||
class="pt-5 text-[11px] tracking-[0.14em] text-ink sm:pt-6 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]">
|
||||
<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="relative min-h-[82px] w-full flex-1 border-t border-ink px-[10px] pt-[10px] lg:w-[394px]">
|
||||
<span class="absolute -top-2 left-0 bg-paper px-[2px] text-muted">COMMENT</span>
|
||||
<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"
|
||||
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:mt-4 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="relative min-h-[82px] w-full border-t border-ink px-[10px] pt-[10px] lg:w-[210px]">
|
||||
<span class="absolute -top-2 left-0 bg-paper px-[2px] text-muted">총 시간</span>
|
||||
<p class="pt-5 text-[11px] tracking-[0.2em] text-ink sm:pt-6 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">
|
||||
<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-7 sm:gap-9 lg:w-[394px]">
|
||||
<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
|
||||
v-for="(task, index) in tasks"
|
||||
:key="task.id"
|
||||
class="flex h-[38px] items-center border-b"
|
||||
class="flex min-h-[38px] items-center border-b"
|
||||
:class="index % 5 === 4 || index === tasks.length - 1 ? 'border-ink' : 'border-line'"
|
||||
>
|
||||
<div class="h-full w-[62px] border-r border-dashed border-ink px-2 py-2 text-[9px] text-stone-500">
|
||||
{{ task.id }}
|
||||
<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"
|
||||
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: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 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"
|
||||
placeholder="할 일을 입력해 주세요."
|
||||
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) ? '할 일을 입력해 주세요.' : ''"
|
||||
@input="emit('update:task-title', { index, value: $event.target.value })"
|
||||
/>
|
||||
</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"
|
||||
@@ -175,16 +213,22 @@ onBeforeUnmount(() => {
|
||||
<div
|
||||
v-for="(memoItem, index) in memo"
|
||||
:key="`memo-${index}`"
|
||||
class="flex h-[38px] items-center border-b"
|
||||
class="flex min-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" />
|
||||
<div class="flex flex-1 items-center px-3">
|
||||
<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"
|
||||
:value="memoItem.label"
|
||||
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"
|
||||
placeholder="메모를 입력해 주세요."
|
||||
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-2 sm:px-3">
|
||||
<input
|
||||
:value="memoItem.text"
|
||||
type="text"
|
||||
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>
|
||||
@@ -193,27 +237,32 @@ onBeforeUnmount(() => {
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="relative w-[210px] shrink-0">
|
||||
<section class="planner-sheet__timetable relative w-full shrink-0 lg:w-[210px]">
|
||||
<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'"
|
||||
>
|
||||
<div class="flex h-full w-[30px] items-center justify-center border-r border-ink text-[9px] text-ink">
|
||||
{{ hour }}
|
||||
</div>
|
||||
<div class="planner-sheet__timetable-scroll overflow-x-auto pb-1">
|
||||
<div class="planner-sheet__timetable-grid min-w-[210px] border-t border-ink">
|
||||
<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)"
|
||||
/>
|
||||
v-for="(hour, index) in hours"
|
||||
:key="`${hour}-${index}`"
|
||||
class="flex h-[26px] border-b sm:h-[30px]"
|
||||
:class="index === hours.length - 1 ? 'border-ink' : 'border-line'"
|
||||
>
|
||||
<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>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
171
src/components/SettingsDashboard.vue
Normal file
171
src/components/SettingsDashboard.vue
Normal file
@@ -0,0 +1,171 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
user: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
profileForm: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
passwordForm: {
|
||||
type: Object,
|
||||
required: true,
|
||||
},
|
||||
profileBusy: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
passwordBusy: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
profileMessage: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
passwordMessage: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits([
|
||||
'update:profile-field',
|
||||
'update:password-field',
|
||||
'submit:profile',
|
||||
'submit:password',
|
||||
])
|
||||
|
||||
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,
|
||||
})
|
||||
}
|
||||
</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>
|
||||
</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>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
157
src/components/StatsDashboard.vue
Normal file
157
src/components/StatsDashboard.vue
Normal file
@@ -0,0 +1,157 @@
|
||||
<script setup>
|
||||
defineProps({
|
||||
overviewCards: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
weeklyRecords: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
recentRecords: {
|
||||
type: Array,
|
||||
required: true,
|
||||
},
|
||||
rangeStart: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
rangeEnd: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
bestDay: {
|
||||
type: Object,
|
||||
default: null,
|
||||
},
|
||||
selectedDateLabel: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits(['update:range-start', 'update:range-end'])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="grid gap-6">
|
||||
<article class="rounded-[28px] border border-white/60 bg-white/80 p-5 shadow-paper backdrop-blur">
|
||||
<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>
|
||||
<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">
|
||||
START DATE
|
||||
<input
|
||||
:value="rangeStart"
|
||||
type="date"
|
||||
class="rounded-2xl border border-stone-200 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-400"
|
||||
@input="emit('update:range-start', $event.target.value)"
|
||||
/>
|
||||
</label>
|
||||
<label class="flex flex-col gap-2 text-[11px] font-bold tracking-[0.14em] text-stone-500">
|
||||
END DATE
|
||||
<input
|
||||
:value="rangeEnd"
|
||||
type="date"
|
||||
class="rounded-2xl border border-stone-200 bg-white px-4 py-3 text-sm font-semibold text-stone-800 outline-none transition focus:border-stone-400"
|
||||
@input="emit('update:range-end', $event.target.value)"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<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"
|
||||
>
|
||||
<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>
|
||||
<p class="mt-2 text-[11px] font-semibold leading-5 tracking-[0.06em] text-stone-600">{{ card.caption }}</p>
|
||||
</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="flex items-end justify-between gap-4">
|
||||
<div>
|
||||
<p class="text-[11px] font-bold tracking-[0.22em] text-stone-500">WEEKLY FLOW</p>
|
||||
<h2 class="mt-2 text-2xl font-semibold tracking-[-0.05em] text-stone-900">
|
||||
선택 기간 기록 흐름
|
||||
</h2>
|
||||
</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
|
||||
v-for="record in weeklyRecords"
|
||||
:key="record.key"
|
||||
class="flex min-w-[56px] flex-col items-center gap-3"
|
||||
>
|
||||
<div class="flex h-40 items-end">
|
||||
<div
|
||||
class="w-10 rounded-full bg-stone-900/90 transition-all"
|
||||
:style="{ 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>
|
||||
</div>
|
||||
</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>
|
||||
<div v-if="bestDay" class="mt-4">
|
||||
<h2 class="text-2xl font-semibold tracking-[-0.05em] text-stone-900">
|
||||
{{ bestDay.dateLabel }}
|
||||
</h2>
|
||||
<p class="mt-3 text-[13px] font-semibold leading-6 text-stone-700">
|
||||
{{ bestDay.summary }}
|
||||
</p>
|
||||
</div>
|
||||
<p v-else class="mt-4 text-[13px] font-semibold leading-6 text-stone-600">
|
||||
아직 통계를 보여줄 기록이 충분하지 않습니다.
|
||||
</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>
|
||||
</section>
|
||||
</template>
|
||||
46
src/lib/apiBase.js
Normal file
46
src/lib/apiBase.js
Normal 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
|
||||
}
|
||||
98
src/lib/authClient.js
Normal file
98
src/lib/authClient.js
Normal file
@@ -0,0 +1,98 @@
|
||||
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 }
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(window.localStorage.getItem(AUTH_STORAGE_KEY) ?? '{"token":"","user":null}')
|
||||
} catch (error) {
|
||||
console.warn('저장된 인증 상태를 불러오지 못했습니다.', error)
|
||||
return { token: '', user: null }
|
||||
}
|
||||
}
|
||||
|
||||
export function persistAuthState({ token, user }) {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
window.localStorage.setItem(
|
||||
AUTH_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
token,
|
||||
user,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
export function clearAuthState() {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
window.localStorage.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 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 },
|
||||
})
|
||||
}
|
||||
65
src/lib/goalsApi.js
Normal file
65
src/lib/goalsApi.js
Normal 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
59
src/lib/plannerApi.js
Normal 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,
|
||||
})
|
||||
}
|
||||
102
src/lib/plannerStorage.js
Normal file
102
src/lib/plannerStorage.js
Normal file
@@ -0,0 +1,102 @@
|
||||
const STORAGE_KEY = 'ten-minute-planner-state'
|
||||
|
||||
function readStorageState() {
|
||||
if (typeof window === 'undefined') {
|
||||
return {}
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? '{}')
|
||||
} catch (error) {
|
||||
console.warn('저장된 플래너 상태를 불러오지 못했습니다.', error)
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
export function readPlannerStorageState() {
|
||||
return readStorageState()
|
||||
}
|
||||
|
||||
export function createInitialPlannerRecords(seedRecords, normalizeRecord) {
|
||||
const baseRecords = Object.fromEntries(
|
||||
Object.entries(seedRecords).map(([key, record]) => [key, normalizeRecord(record)]),
|
||||
)
|
||||
|
||||
const savedState = readStorageState()
|
||||
const savedRecords = savedState.records ?? {}
|
||||
|
||||
Object.entries(savedRecords).forEach(([key, record]) => {
|
||||
baseRecords[key] = normalizeRecord(record)
|
||||
})
|
||||
|
||||
return baseRecords
|
||||
}
|
||||
|
||||
export function restorePlannerUiState({
|
||||
selectedDate,
|
||||
calendarViewDate,
|
||||
statsRangeStart,
|
||||
statsRangeEnd,
|
||||
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)
|
||||
}
|
||||
|
||||
if (savedState.statsRangeStart) {
|
||||
statsRangeStart.value = savedState.statsRangeStart
|
||||
}
|
||||
|
||||
if (savedState.statsRangeEnd) {
|
||||
statsRangeEnd.value = savedState.statsRangeEnd
|
||||
}
|
||||
}
|
||||
|
||||
export function persistPlannerState({
|
||||
plannerRecords,
|
||||
selectedDate,
|
||||
calendarViewDate,
|
||||
statsRangeStart,
|
||||
statsRangeEnd,
|
||||
includeRecords = true,
|
||||
}) {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
|
||||
const previousState = readStorageState()
|
||||
const nextState = {
|
||||
...previousState,
|
||||
selectedDate: selectedDate.toISOString(),
|
||||
calendarViewDate: calendarViewDate.toISOString(),
|
||||
statsRangeStart,
|
||||
statsRangeEnd,
|
||||
}
|
||||
|
||||
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(nextState),
|
||||
)
|
||||
}
|
||||
216
src/style.css
216
src/style.css
@@ -20,3 +20,219 @@
|
||||
@apply outline-none;
|
||||
}
|
||||
}
|
||||
|
||||
@media print {
|
||||
@page {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
background: #ffffff !important;
|
||||
width: auto !important;
|
||||
height: auto !important;
|
||||
overflow: hidden !important;
|
||||
}
|
||||
|
||||
body {
|
||||
min-height: auto;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
main {
|
||||
min-height: auto !important;
|
||||
margin: 0 !important;
|
||||
padding: 0 !important;
|
||||
}
|
||||
|
||||
.print-hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.print-only {
|
||||
display: flex !important;
|
||||
width: 100% !important;
|
||||
height: 100% !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 {
|
||||
display: block !important;
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
margin: 0 !important;
|
||||
max-width: none !important;
|
||||
padding: 0 !important;
|
||||
gap: 0 !important;
|
||||
}
|
||||
|
||||
.print-paper {
|
||||
display: flex !important;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: #ffffff !important;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
body[data-print-layout='single'] .print-paper {
|
||||
width: 204mm;
|
||||
height: 291mm;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding-top: 3mm;
|
||||
}
|
||||
|
||||
.print-paper--double {
|
||||
display: grid !important;
|
||||
grid-template-columns: repeat(2, 139mm);
|
||||
justify-content: center;
|
||||
align-content: center;
|
||||
column-gap: 4mm;
|
||||
}
|
||||
|
||||
body[data-print-layout='double'] .print-paper {
|
||||
width: 285mm;
|
||||
height: 196mm;
|
||||
}
|
||||
|
||||
body[data-print-layout='single'] .print-paper--single .print-sheet-frame {
|
||||
width: 198mm;
|
||||
height: 281mm;
|
||||
}
|
||||
|
||||
.print-sheet-frame {
|
||||
overflow: hidden;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: flex-start;
|
||||
background: #ffffff !important;
|
||||
}
|
||||
|
||||
body[data-print-layout='double'] .print-paper--double .print-sheet-frame {
|
||||
width: 139mm;
|
||||
height: 196mm;
|
||||
}
|
||||
|
||||
.planner-sheet {
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
body[data-print-layout='single'] .print-paper--single .print-sheet-frame .planner-sheet {
|
||||
width: 762px !important;
|
||||
max-width: none !important;
|
||||
transform-origin: top left;
|
||||
transform: scale(0.982);
|
||||
box-shadow: none !important;
|
||||
background: #ffffff !important;
|
||||
}
|
||||
|
||||
body[data-print-layout='double'] .print-paper--double .print-sheet-frame .planner-sheet {
|
||||
width: 762px !important;
|
||||
max-width: none !important;
|
||||
transform-origin: top left;
|
||||
transform: scale(0.6894);
|
||||
box-shadow: none !important;
|
||||
background: #ffffff !important;
|
||||
}
|
||||
|
||||
.print-sheet-frame .planner-sheet * {
|
||||
-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;
|
||||
}
|
||||
|
||||
.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: auto !important;
|
||||
min-height: 48px !important;
|
||||
overflow: visible !important;
|
||||
padding-top: 4px !important;
|
||||
line-height: 1.55 !important;
|
||||
}
|
||||
|
||||
.print-paper--double .print-sheet-frame {
|
||||
align-items: flex-start !important;
|
||||
justify-content: flex-start !important;
|
||||
}
|
||||
}
|
||||
|
||||
@media screen {
|
||||
.print-only {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user