Compare commits

...

14 Commits

Author SHA1 Message Date
f718342b93 v0.1.11 - 인증 UI 연결 2026-04-21 18:06:24 +09:00
5b1c4bcfca v0.1.10 - 플래너 저장 API 추가 2026-04-21 18:02:03 +09:00
20095a79db v0.1.9 - 인증 API 추가 2026-04-21 17:56:47 +09:00
d5aa7f8153 v0.1.8 - 백엔드 초안 추가 2026-04-21 17:48:34 +09:00
7ff8bd06b1 v0.1.7 - 저장 레이어 분리 시작 2026-04-21 17:41:20 +09:00
066cab311b v0.1.6 2026-04-21 17:32:18 +09:00
934f561f86 v0.1.5 2026-04-21 14:55:20 +09:00
c3202d0b92 v0.1.4 2026-04-21 14:51:44 +09:00
75f9590e45 v0.1.3 2026-04-21 14:47:31 +09:00
e87155f909 v0.1.2 2026-04-21 14:44:56 +09:00
f3b2c84758 v0.1.1 2026-04-21 14:36:43 +09:00
314dd7f649 v0.1.0 2026-04-21 14:31:26 +09:00
0206cfebf8 v0.0.9 2026-04-21 14:21:08 +09:00
85d21f5842 v0.0.8 2026-04-21 14:15:09 +09:00
26 changed files with 4199 additions and 150 deletions

4
.gitignore vendored
View File

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

View File

@@ -29,6 +29,7 @@
## 커밋 규칙
- 사용자가 버전형 체크포인트를 원할 경우 `v0.0.1` 같은 형식으로 커밋을 남긴다.
- 버전 커밋만 단독으로 쓰지 말고, `v0.1.7 - 저장 레이어 분리`처럼 버전 뒤에 작업 요약을 함께 남긴다.
- 의미를 알기 어려운 큰 커밋보다, 이해 가능한 작은 단위의 커밋을 선호한다.
## 디자인 구현 규칙

View File

@@ -4,7 +4,8 @@
- 프로젝트명: 10 Minute Planner 웹 UI
- 기술 스택: Vue 3 + Vite + TailwindCSS + JavaScript
- 현재 기준 버전: `v0.0.7`
- 현재 기준 버전: `v0.1.11`
- Git 원격 저장소: `https://git.sori.studio/zenn/planner.sori.studio.git`
## 기준 디자인
@@ -16,12 +17,21 @@
- 기본 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/lib/password.js`
- Tailwind 설정은 완료되어 있으며, 이 프로젝트의 스타일링 기준으로 유지한다.
- 현재 선택 날짜는 시스템 날짜 기준으로 시작한다.
- `COMMENT`, `TASKS`, `MEMO`는 화면에서 바로 편집할 수 있다.
@@ -31,12 +41,40 @@
- 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`로 세션 복원을 시도한다.
- 루트에서 `npm run dev:backend`, `npm run db:generate`, `npm run db:migrate`로 백엔드 명령을 호출할 수 있다.
- 상단 전환 버튼으로 `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 + SQLite` 조합이며, 현재는 `/health`, `/api/meta` 정도의 기본 라우트만 있다.
- 백엔드에는 `/api/auth/signup`, `/api/auth/login`, `/api/auth/me`가 추가되었다.
- 백엔드에는 `/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`은 코드 자체보다 실행 환경 제약에 가깝다.
## 확정된 결정사항
@@ -44,6 +82,9 @@
날짜 전환, 모드 토글, 사이드 패널 요약, 이후 저장 기능 등 상태 기반 상호작용이 많기 때문이다.
- TailwindCSS는 Vue를 사용하더라도 반드시 유지해야 하는 스타일링 방식이다.
- 현재 데이터는 레이아웃과 상호작용 검증을 위한 목업 데이터다.
- 현재 저장은 `localStorage`를 사용하지만, 적절한 시점에 DB를 붙여 사용자별 저장 구조로 전환해야 한다.
- 백엔드는 빠른 MVP라면 PocketBase도 가능하지만, 현재 요구사항에서는 전용 Node.js API + DB 구성이 더 유연하다.
- 이유는 회원가입, 사용자별 문서 관리, 통계 계산, 출력/이미지 저장, 이후 Docker Compose 배포까지 고려하면 서버 로직 제어권이 더 중요하기 때문이다.
- 상단 날짜는 시스템 날짜 또는 현재 선택된 플래너 날짜 기준으로 자동 표시되어야 한다.
- `D-DAY`는 지금은 보류이며, 이후 별도의 목표 관리 패널과 연결해서 계산한다.
- `COMMENT`, `TASKS`, `MEMO`는 모두 입력 가능한 필드가 되어야 한다.
@@ -55,12 +96,29 @@
- 달력에는 연/월 이동 기능이 필요하다.
- 내용이 저장된 날짜에는 달력에 빨간 점 표시가 필요하다.
- 현재 단계의 저장 방식은 `localStorage`이며, 이후 외부 저장소 도입 전까지 기본 저장 경로로 사용한다.
- 장기적으로는 회원 가입 후 사용자별로 각자 문서를 작성/관리할 수 있어야 한다.
- 공유 문서 서비스가 아니라, 사용자 개인 보관과 회고 중심의 서비스 구조를 목표로 한다.
- 사용자는 스스로 통계를 확인할 수 있어야 하고, 특정 날짜에 작성한 문서는 출력 가능해야 한다.
- 공유를 위해 나중에 이미지 저장 기능도 필요하지만, 실제 출력 품질과 텍스트 선명도는 HTML/CSS 인쇄 레이아웃을 우선 유지하는 편이 좋다.
- 원격 저장소 `origin``https://git.sori.studio/zenn/planner.sori.studio.git`로 연결되어 있다.
- 앞으로 버전 체크포인트 커밋은 `v0.1.7 - 작업 요약`처럼 버전 뒤에 짧은 작업 설명을 함께 남기는 형식으로 통일한다.
- 이후 배포 단계에서는 `docker-compose.yml`도 함께 작성해야 하며, 포트 번호와 서비스 구성은 추후 사용자와 확정한다.
- `backend/.env.example`에는 기본 `PORT`, `DB_FILE`, `CORS_ORIGIN` 예시가 들어 있다.
## 다음 권장 작업
- `TODO.md` 기준으로 작은 단위씩 구현을 진행한다.
- 목표나 통계 기능보다 먼저, 플래너 본문의 입력과 상호작용을 우선 구현한다.
- 달력 표시와 통계 기능을 본격화하기 전에 저장 구조를 먼저 정리하는 것이 좋다.
- 통계 화면 구현은 현재 `localStorage` 기반으로 먼저 진행해도 된다.
- DB는 기능 탐색 속도를 해치지 않는 선에서, 저장 레이어를 분리할 수 있는 적절한 시점에 붙이는 것이 좋다.
- 현재 기준 추천 백엔드 방향은 `Vue 프론트엔드 + Node.js API + SQLite 또는 PostgreSQL`이다.
- 현재는 SQLite로 시작하되, 확장 시 PostgreSQL로 옮길 수 있게 Drizzle 기반 스키마를 유지한다.
- 현재 인증 방식은 Bearer 토큰 기반의 간단한 세션 구조이며, 추후 쿠키/리프레시 토큰 전략으로 확장할 수 있다.
- 다음 프론트 단계에서는 `src/lib/plannerStorage.js`를 유지하되, 인증 이후 백엔드 저장소 adapter를 추가해서 `localStorage`와 전환 가능하게 만드는 흐름이 좋다.
- 현재 프론트는 인증만 연결된 상태이고, 플래너 저장은 아직 `localStorage` 기준이다.
- 다음 단계는 `plannerStorage`에 백엔드 adapter를 추가해서 로그인 시 서버 저장을 우선 사용하도록 연결하는 것이다.
- 이미지 저장 기능은 추후 `print-only` 또는 별도 export 전용 레이아웃을 기준으로 구현하면 화면/인쇄/공유 결과를 맞추기 쉽다.
- Docker Compose는 프론트엔드와 백엔드를 함께 올리는 기준으로 설계하되, NAS 환경에 맞는 볼륨과 재시작 정책도 함께 고려한다.
## 갱신 규칙

38
TODO.md
View File

@@ -47,6 +47,12 @@
- [x] 입력 데이터의 저장 위치를 결정한다.
- [x] 로컬 저장 또는 외부 저장 방식 중 우선 구현 방식을 정한다.
- [x] 입력 상태가 새로고침 후에도 유지되도록 만든다.
- [x] DB 전환 시점을 잡을 수 있도록 저장 레이어를 분리한다.
- [ ] 회원 가입 및 로그인 구조를 고려한 사용자별 데이터 모델을 설계한다.
- [x] 회원 가입 및 로그인 구조를 고려한 사용자별 데이터 모델을 설계한다.
- [ ] 사용자별 문서 저장/조회 흐름을 정리한다.
- [x] 사용자별 문서 저장/조회 흐름을 정리한다.
- [ ] 출력용 문서 포맷과 프린트 흐름을 고려한 데이터 구조를 정리한다.
## 추가 반영 메모
@@ -55,12 +61,38 @@
## 5단계: 확장 화면
- [ ] 통계 페이지 요구사항을 정리한다.
- [ ] 통계 페이지 라우팅 또는 화면 전환 구조를 설계한다.
- [ ] 집중 시간, 완료율, 연속 기록 같은 핵심 지표를 정의한다.
- [x] 통계 페이지 요구사항을 정리한다.
- [x] 통계 페이지 라우팅 또는 화면 전환 구조를 설계한다.
- [x] 집중 시간, 완료율, 연속 기록 같은 핵심 지표를 정의한다.
- [x] 사용자가 시작일과 종료일을 선택해서 기간별 통계를 볼 수 있게 한다.
- [ ] 사용자 개인 통계 화면 기준을 정리한다.
## 6단계: 계정 및 서비스 확장
- [ ] 회원 가입 / 로그인 방식 후보를 정리한다.
- [x] 회원 가입 / 로그인 방식 후보를 정리한다.
- [ ] 사용자별 문서 분리 저장 구조를 설계한다.
- [ ] 공유가 아닌 개인 보관용 서비스 흐름으로 요구사항을 정리한다.
- [x] 향후 출력 기능을 위한 인쇄 레이아웃 요구사항을 정리한다.
- [x] A4 가로 기준 2장 출력 모드를 지원한다.
- [x] `1-UP` 세로 인쇄 / `2-UP` 가로 인쇄 기준을 분리한다.
- [ ] 공유를 위한 이미지 저장 기능을 추가한다.
- [ ] Docker 배포 구조를 정리한다.
- [ ] UGREEN NAS 기준 `docker-compose.yml` 초안을 작성한다.
- [x] 백엔드 기본 스캐폴딩을 추가한다.
## 메모
- D-DAY는 현재 보류 상태다. 목표 패널 설계 후 연결한다.
- `TIME TABLE` 드래그는 단순 사각형 선택이 아니라 시간 셀 단위의 연속 선택으로 해석한다.
- 현재는 `localStorage`로 개발을 진행하지만, 적절한 시점에 DB를 붙여 사용자별 저장 구조로 확장해야 한다.
- 현재 `localStorage` 저장 로직은 분리 가능한 형태로 정리 중이며, 이후 API/DB adapter로 교체하기 쉽게 유지한다.
- 최종적으로는 회원 가입 후 각자 자신의 문서를 작성/관리하고, 개인 통계를 확인하며, 특정 날짜 문서를 출력할 수 있어야 한다.
- 실제 인쇄는 HTML/CSS 기반 프린트 레이아웃으로 유지하고, 공유용으로는 별도의 이미지 저장 기능을 추가하는 방향이 적합하다.
- 최종 배포는 UGREEN NAS에서 Docker 기반으로 동작할 예정이며, 포트와 실제 서비스 구성은 추후 확정한다.
- 백엔드는 빠른 목업이면 PocketBase도 가능하지만, 현재 방향상 커스텀 로직과 확장성을 생각하면 전용 Node.js API + DB 조합을 우선 검토한다.
- 현재 백엔드는 `backend/` 폴더에 `Fastify + Drizzle + SQLite` 기준 초안이 추가되었다.
- 현재 백엔드는 회원가입, 로그인, 현재 사용자 확인용 기본 인증 API까지 포함한다.
- 현재 백엔드는 사용자별 플래너 단건 저장/조회와 범위 조회 API까지 포함한다.
- 프론트에는 로그인/회원가입 모달과 현재 사용자 상태 표시가 추가되었다.
- 구현할 때마다 완료된 항목은 체크하고, 큰 결정사항은 `HANDOFF.md`에도 함께 반영한다.

3
backend/.env.example Normal file
View File

@@ -0,0 +1,3 @@
PORT=3001
DB_FILE=./data/planner.sqlite
CORS_ORIGIN=http://localhost:5173

17
backend/drizzle.config.js Normal file
View 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: 'sqlite',
dbCredentials: {
url: process.env.DB_FILE ?? './data/planner.sqlite',
},
}

2318
backend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

23
backend/package.json Normal file
View 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",
"better-sqlite3": "^11.8.1",
"dotenv": "^16.4.7",
"drizzle-orm": "^0.39.1",
"fastify": "^5.2.1",
"zod": "^3.24.2"
},
"devDependencies": {
"drizzle-kit": "^0.30.4"
}
}

18
backend/src/config.js Normal file
View File

@@ -0,0 +1,18 @@
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),
DB_FILE: z.string().default('./data/planner.sqlite'),
CORS_ORIGIN: z.string().default('http://localhost:5173'),
SESSION_TTL_DAYS: z.coerce.number().default(30),
})
export const env = envSchema.parse(process.env)

17
backend/src/db/client.js Normal file
View File

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

36
backend/src/db/init.js Normal file
View File

@@ -0,0 +1,36 @@
import { sqlite } from './client.js'
export function ensureDatabaseSchema() {
sqlite.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
nickname TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS auth_sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
expires_at INTEGER NOT NULL,
created_at INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS planner_entries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
entry_date TEXT NOT NULL,
payload TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);
CREATE UNIQUE INDEX IF NOT EXISTS planner_entries_user_date_unique
ON planner_entries (user_id, entry_date);
`)
}

33
backend/src/db/schema.js Normal file
View File

@@ -0,0 +1,33 @@
import { integer, sqliteTable, text, uniqueIndex } from 'drizzle-orm/sqlite-core'
export const users = sqliteTable('users', {
id: integer('id').primaryKey({ autoIncrement: true }),
email: text('email').notNull().unique(),
passwordHash: text('password_hash').notNull(),
nickname: text('nickname').notNull(),
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
})
export const authSessions = sqliteTable('auth_sessions', {
id: integer('id').primaryKey({ autoIncrement: true }),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
tokenHash: text('token_hash').notNull().unique(),
expiresAt: integer('expires_at', { mode: 'timestamp_ms' }).notNull(),
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
})
export const plannerEntries = sqliteTable(
'planner_entries',
{
id: integer('id').primaryKey({ autoIncrement: true }),
userId: integer('user_id').notNull().references(() => users.id, { onDelete: 'cascade' }),
entryDate: text('entry_date').notNull(),
payload: text('payload').notNull(),
createdAt: integer('created_at', { mode: 'timestamp_ms' }).notNull(),
updatedAt: integer('updated_at', { mode: 'timestamp_ms' }).notNull(),
},
(table) => ({
userDateUnique: uniqueIndex('planner_entries_user_date_unique').on(table.userId, table.entryDate),
}),
)

View 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
}

View 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')
}

132
backend/src/routes/auth.js Normal file
View File

@@ -0,0 +1,132 @@
import { eq } from 'drizzle-orm'
import { z } from 'zod'
import { db } from '../db/client.js'
import { users } from '../db/schema.js'
import { 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),
})
function sanitizeUser(user) {
return {
id: user.id,
email: user.email,
nickname: user.nickname,
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,
createdAt: now,
updatedAt: now,
})
.returning()
const { token } = await createSession(user.id)
return reply.code(201).send({
message: '회원가입이 완료되었습니다.',
token,
user: sanitizeUser(user),
})
})
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),
}
})
}

View File

@@ -0,0 +1,165 @@
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: entries.map((entry) => ({
...entry,
payload: JSON.parse(entry.payload),
})),
}
})
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
? {
...entry,
payload: JSON.parse(entry.payload),
}
: 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: JSON.stringify(payloadResult.data.payload),
createdAt: now,
updatedAt: now,
})
.onConflictDoUpdate({
target: [plannerEntries.userId, plannerEntries.entryDate],
set: {
payload: JSON.stringify(payloadResult.data.payload),
updatedAt: now,
},
})
.returning()
return {
message: '플래너가 저장되었습니다.',
entry: {
...entry,
payload: JSON.parse(entry.payload),
},
}
})
}

54
backend/src/server.js Normal file
View File

@@ -0,0 +1,54 @@
import Fastify from 'fastify'
import cors from '@fastify/cors'
import { env } from './config.js'
import { sqlite } from './db/client.js'
import { ensureDatabaseSchema } from './db/init.js'
import { registerAuthRoutes } from './routes/auth.js'
import { registerPlannerRoutes } from './routes/planner.js'
const app = Fastify({
logger: true,
})
ensureDatabaseSchema()
await app.register(cors, {
origin: env.CORS_ORIGIN,
credentials: true,
})
await registerAuthRoutes(app)
await registerPlannerRoutes(app)
app.get('/health', async () => {
const version = sqlite.prepare('select sqlite_version() as version').get()
return {
status: 'ok',
service: 'ten-minute-planner-backend',
database: {
client: 'sqlite',
version: version?.version ?? 'unknown',
},
}
})
app.get('/api/meta', async () => ({
auth: 'active',
storage: 'sqlite',
orm: 'drizzle',
notes: [
'회원가입, 로그인, 현재 사용자 확인 API가 준비되어 있습니다.',
'사용자별 플래너 저장 및 조회 API가 준비되어 있습니다.',
],
}))
try {
await app.listen({
port: env.PORT,
host: '0.0.0.0',
})
} catch (error) {
app.log.error(error)
process.exit(1)
}

4
package-lock.json generated
View File

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

View File

@@ -1,12 +1,15 @@
{
"name": "ten-minute-planner",
"private": true,
"version": "0.0.7",
"version": "0.1.11",
"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"

View File

@@ -1,12 +1,41 @@
<script setup>
import { computed, reactive, ref, watch } from 'vue'
import { computed, onMounted, reactive, ref, watch, nextTick } from 'vue'
import AuthDialog from './components/AuthDialog.vue'
import MiniCalendar from './components/MiniCalendar.vue'
import PlannerPage from './components/PlannerPage.vue'
import StatsDashboard from './components/StatsDashboard.vue'
import {
clearAuthState,
fetchCurrentUser,
login,
persistAuthState,
readAuthState,
signup,
} from './lib/authClient'
import {
createInitialPlannerRecords,
persistPlannerState,
restorePlannerUiState,
} from './lib/plannerStorage'
const STORAGE_KEY = 'ten-minute-planner-state'
const screenMode = ref('planner')
const viewMode = ref('focus')
const printLayout = ref('single')
const authDialogOpen = ref(false)
const authMode = ref('login')
const authBusy = ref(false)
const authMessage = ref('')
const authToken = ref('')
const currentUser = ref(null)
const selectedDate = ref(new Date())
const calendarViewDate = ref(new Date(selectedDate.value))
const statsRangeStart = ref(toKey(new Date(new Date().setDate(new Date().getDate() - 6))))
const statsRangeEnd = ref(toKey(new Date()))
const authForm = reactive({
nickname: '',
email: '',
password: '',
})
const hours = [
'6', '7', '8', '9', '10', '11', '12',
@@ -16,6 +45,7 @@ const hours = [
]
const timetableCellCount = hours.length * 6
let printPageStyleElement = null
function createEmptyTimetable() {
return Array.from({ length: timetableCellCount }, () => false)
@@ -134,6 +164,10 @@ function toDateValue(value, fallback = new Date()) {
return Number.isNaN(nextDate.getTime()) ? new Date(fallback) : nextDate
}
function startOfDay(date) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate())
}
function buildFallbackRecord(date) {
return {
dday: 'D-00 FOCUS',
@@ -180,55 +214,15 @@ function normalizeRecord(record) {
}
}
function createInitialPlannerRecords() {
const baseRecords = Object.fromEntries(
Object.entries(plannerSeed).map(([key, record]) => [key, normalizeRecord(record)]),
)
const plannerRecords = reactive(createInitialPlannerRecords(plannerSeed, normalizeRecord))
if (typeof window === 'undefined') {
return baseRecords
}
try {
const savedState = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? '{}')
const savedRecords = savedState.records ?? {}
Object.entries(savedRecords).forEach(([key, record]) => {
baseRecords[key] = normalizeRecord(record)
})
} catch (error) {
console.warn('저장된 플래너 상태를 불러오지 못했습니다.', error)
}
return baseRecords
}
const plannerRecords = reactive(createInitialPlannerRecords())
function restoreDateState() {
if (typeof window === 'undefined') {
return
}
try {
const savedState = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? '{}')
if (savedState.selectedDate) {
selectedDate.value = toDateValue(savedState.selectedDate, selectedDate.value)
}
if (savedState.calendarViewDate) {
calendarViewDate.value = toDateValue(savedState.calendarViewDate, selectedDate.value)
return
}
calendarViewDate.value = new Date(selectedDate.value)
} catch (error) {
console.warn('저장된 날짜 상태를 불러오지 못했습니다.', error)
}
}
restoreDateState()
restorePlannerUiState({
selectedDate,
calendarViewDate,
statsRangeStart,
statsRangeEnd,
toDateValue,
})
function getPlannerRecord(date) {
const key = toKey(date)
@@ -297,6 +291,8 @@ const markedDateKeys = computed(() =>
.map(([key]) => key),
)
const isAuthenticated = computed(() => Boolean(authToken.value && currentUser.value))
const filledTasks = computed(() =>
planner.value.tasks.filter((task) => task.title.trim()),
)
@@ -320,6 +316,21 @@ function formatTotalTime(record) {
return `${hoursPart}H ${minutesPart}M`
}
function getFocusedMinutes(record) {
return record.timetable.filter(Boolean).length * 10
}
function getCompletionRate(record) {
const activeTasks = record.tasks.filter((task) => task.title.trim())
if (activeTasks.length === 0) {
return 0
}
const doneTasks = activeTasks.filter((task) => task.checked).length
return Math.round((doneTasks / activeTasks.length) * 100)
}
function shiftDate(amount) {
const next = new Date(selectedDate.value)
next.setDate(next.getDate() + amount)
@@ -381,33 +392,160 @@ function hasPlannerContent(record) {
)
}
watch(
[plannerRecords, selectedDate, calendarViewDate],
() => {
if (typeof window === 'undefined') {
return
const plannerEntries = computed(() =>
Object.entries(plannerRecords)
.filter(([, record]) => hasPlannerContent(record))
.sort(([leftKey], [rightKey]) => leftKey.localeCompare(rightKey)),
)
const normalizedStatsRange = computed(() => {
const todayKey = toKey(new Date())
const startKey = statsRangeStart.value || todayKey
const endKey = statsRangeEnd.value || todayKey
if (startKey <= endKey) {
return { startKey, endKey }
}
return { startKey: endKey, endKey: startKey }
})
const rangeEntries = computed(() =>
plannerEntries.value.filter(([key]) =>
key >= normalizedStatsRange.value.startKey && key <= normalizedStatsRange.value.endKey,
),
)
const totalFocusedMinutes = computed(() =>
rangeEntries.value.reduce((total, [, record]) => total + getFocusedMinutes(record), 0),
)
const totalRecordedTasks = computed(() =>
rangeEntries.value.reduce(
(total, [, record]) => total + record.tasks.filter((task) => task.title.trim()).length,
0,
),
)
const completedRecordedTasks = computed(() =>
rangeEntries.value.reduce(
(total, [, record]) => total + record.tasks.filter((task) => task.title.trim() && task.checked).length,
0,
),
)
const aggregateCompletionRate = computed(() => {
if (totalRecordedTasks.value === 0) {
return 0
}
return Math.round((completedRecordedTasks.value / totalRecordedTasks.value) * 100)
})
const overviewCards = computed(() => [
{
label: 'TOTAL FOCUSED',
value: formatMinutes(totalFocusedMinutes.value),
caption: '지금까지 기록된 전체 집중 시간',
},
{
label: 'AVERAGE COMPLETION',
value: `${aggregateCompletionRate.value}%`,
caption: '입력된 할 일 기준 전체 평균 완료율',
},
{
label: 'RECORDED DAYS',
value: `${rangeEntries.value.length}`,
caption: '기록이 남아 있는 날짜 수',
},
{
label: 'COMPLETED TASKS',
value: `${completedRecordedTasks.value}/${totalRecordedTasks.value || 0}`,
caption: '완료된 할 일과 전체 입력된 할 일 수',
},
])
function formatMinutes(totalMinutes) {
const hoursPart = Math.floor(totalMinutes / 60)
const minutesPart = totalMinutes % 60
return `${hoursPart}H ${`${minutesPart}`.padStart(2, '0')}M`
}
function createDateLabel(dateKey) {
const date = toDateValue(dateKey)
const display = getDateDisplay(date)
return `${display.main} ${display.weekday}`
}
const weeklyRecords = computed(() => {
const entries = rangeEntries.value.map(([key, record]) => {
const date = toDateValue(key)
const weekdayShort = ['일', '월', '화', '수', '목', '금', '토'][date.getDay()]
const focusedMinutes = getFocusedMinutes(record)
return {
key,
weekday: weekdayShort,
focusedMinutes,
focusedTime: formatMinutes(focusedMinutes),
}
})
const serializableRecords = Object.fromEntries(
Object.entries(plannerRecords).map(([key, record]) => [
key,
{
...record,
tasks: record.tasks.map((task) => ({ ...task })),
memo: record.memo.map((item) => ({ ...item })),
timetable: [...record.timetable],
},
]),
)
if (entries.length === 0) {
return []
}
window.localStorage.setItem(
STORAGE_KEY,
JSON.stringify({
selectedDate: selectedDate.value.toISOString(),
calendarViewDate: calendarViewDate.value.toISOString(),
records: serializableRecords,
}),
)
const maxMinutes = Math.max(...entries.map((entry) => entry.focusedMinutes), 60)
return entries.map((entry) => ({
...entry,
barHeight: Math.max(12, Math.round((entry.focusedMinutes / maxMinutes) * 100)),
}))
})
const recentRecords = computed(() =>
[...rangeEntries.value]
.sort(([leftKey], [rightKey]) => rightKey.localeCompare(leftKey))
.slice(0, 5)
.map(([key, record]) => ({
key,
dateLabel: createDateLabel(key),
comment: record.comment.trim(),
focusedTime: formatTotalTime(record),
completionRate: getCompletionRate(record),
})),
)
const bestDay = computed(() => {
if (rangeEntries.value.length === 0) {
return null
}
const [bestKey, bestRecord] = [...rangeEntries.value].reduce((bestEntry, currentEntry) => {
const [, bestRecordValue] = bestEntry
const [, currentRecordValue] = currentEntry
return getFocusedMinutes(currentRecordValue) > getFocusedMinutes(bestRecordValue) ? currentEntry : bestEntry
})
return {
dateLabel: createDateLabel(bestKey),
summary: `${formatTotalTime(bestRecord)} 집중, 완료율 ${getCompletionRate(bestRecord)}%, 코멘트 "${
bestRecord.comment.trim() || '없음'
}"`,
}
})
watch(
[plannerRecords, selectedDate, calendarViewDate, statsRangeStart, statsRangeEnd],
() => {
persistPlannerState({
plannerRecords,
selectedDate: selectedDate.value,
calendarViewDate: calendarViewDate.value,
statsRangeStart: normalizedStatsRange.value.startKey,
statsRangeEnd: normalizedStatsRange.value.endKey,
})
},
{ deep: true },
)
@@ -423,12 +561,130 @@ function clearTaskLabels(record) {
task.label = ''
})
}
function resetAuthForm() {
authForm.nickname = ''
authForm.email = ''
authForm.password = ''
}
function openAuthDialog(mode = 'login') {
authMode.value = mode
authMessage.value = ''
authDialogOpen.value = true
}
function closeAuthDialog() {
authDialogOpen.value = false
authMessage.value = ''
resetAuthForm()
}
function updateAuthField({ field, value }) {
authForm[field] = value
}
function applyAuthSuccess(data) {
authToken.value = data.token
currentUser.value = data.user
persistAuthState({
token: data.token,
user: data.user,
})
closeAuthDialog()
}
async function submitAuthForm() {
authBusy.value = true
authMessage.value = ''
try {
const result =
authMode.value === 'login'
? await login({
email: authForm.email,
password: authForm.password,
})
: await signup({
nickname: authForm.nickname,
email: authForm.email,
password: authForm.password,
})
applyAuthSuccess(result)
} catch (error) {
authMessage.value = error.message || '인증 처리 중 문제가 발생했습니다.'
} finally {
authBusy.value = false
}
}
async function restoreAuthSession() {
const savedAuth = readAuthState()
if (!savedAuth.token) {
return
}
authToken.value = savedAuth.token
currentUser.value = savedAuth.user ?? null
try {
const result = await fetchCurrentUser(savedAuth.token)
currentUser.value = result.user
persistAuthState({
token: savedAuth.token,
user: result.user,
})
} catch (error) {
authToken.value = ''
currentUser.value = null
clearAuthState()
}
}
function logout() {
authToken.value = ''
currentUser.value = null
clearAuthState()
}
function applyPrintPageStyle(layout) {
if (typeof document === 'undefined') {
return
}
const pageRule =
layout === 'double'
? '@page { size: A4 landscape; margin: 0; }'
: '@page { size: A4 portrait; margin: 0; }'
if (!printPageStyleElement) {
printPageStyleElement = document.createElement('style')
printPageStyleElement.setAttribute('data-print-page-style', 'true')
document.head.appendChild(printPageStyleElement)
}
printPageStyleElement.textContent = pageRule
document.body.dataset.printLayout = layout
}
async function printSelectedPlanner(layout = 'single') {
printLayout.value = layout
applyPrintPageStyle(layout)
await nextTick()
window.print()
}
onMounted(() => {
restoreAuthSession()
})
</script>
<template>
<main class="min-h-screen px-4 py-6 text-ink sm:px-6 lg:px-10">
<div class="mx-auto flex max-w-[1680px] flex-col gap-6">
<header class="flex flex-col gap-4 rounded-[28px] border border-white/60 bg-white/70 p-5 backdrop-blur sm:p-6">
<div class="print-root mx-auto flex max-w-[1680px] flex-col gap-6">
<header class="print-hidden flex flex-col gap-4 rounded-[28px] border border-white/60 bg-white/70 p-5 backdrop-blur sm:p-6">
<div class="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
<div class="space-y-2">
<p class="text-[11px] font-bold uppercase tracking-[0.28em] text-stone-500">10 Minute Planner</p>
@@ -440,6 +696,57 @@ function clearTaskLabels(record) {
</p>
</div>
<div class="flex flex-wrap items-center gap-3">
<div class="inline-flex items-center gap-2 rounded-full border border-stone-200 bg-white px-2 py-2">
<template v-if="isAuthenticated">
<div class="px-2">
<p class="text-[10px] font-bold tracking-[0.16em] text-stone-500">SIGNED IN</p>
<p class="text-sm font-semibold tracking-[0.02em] text-stone-900">
{{ currentUser.nickname }}
</p>
</div>
<button
type="button"
class="rounded-full border border-stone-200 px-3 py-2 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
@click="logout"
>
LOGOUT
</button>
</template>
<template v-else>
<button
type="button"
class="rounded-full border border-stone-200 px-3 py-2 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
@click="openAuthDialog('login')"
>
LOGIN
</button>
<button
type="button"
class="rounded-full border border-stone-900 bg-stone-900 px-3 py-2 text-xs font-bold tracking-[0.14em] text-white transition hover:bg-stone-700"
@click="openAuthDialog('signup')"
>
SIGN UP
</button>
</template>
</div>
<div class="inline-flex rounded-full border border-stone-200 bg-stone-100 p-1">
<button
type="button"
class="rounded-full px-4 py-2 text-xs font-bold tracking-[0.14em] transition"
:class="screenMode === 'planner' ? 'bg-white text-ink shadow-sm' : 'text-stone-500'"
@click="screenMode = 'planner'"
>
PLANNER
</button>
<button
type="button"
class="rounded-full px-4 py-2 text-xs font-bold tracking-[0.14em] transition"
:class="screenMode === 'stats' ? 'bg-white text-ink shadow-sm' : 'text-stone-500'"
@click="screenMode = 'stats'"
>
STATS
</button>
</div>
<div class="inline-flex rounded-full border border-stone-200 bg-stone-100 p-1">
<button
type="button"
@@ -474,35 +781,56 @@ function clearTaskLabels(record) {
NEXT DAY
</button>
</div>
<div
v-if="screenMode === 'planner'"
class="inline-flex items-center gap-2 rounded-full border border-stone-200 bg-white px-2 py-2"
>
<button
type="button"
class="rounded-full border border-stone-200 px-3 py-2 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
@click="printSelectedPlanner('single')"
>
PRINT 1-UP
</button>
<button
type="button"
class="rounded-full border border-stone-200 px-3 py-2 text-xs font-bold tracking-[0.14em] text-stone-600 transition hover:border-stone-400 hover:text-ink"
@click="printSelectedPlanner('double')"
>
PRINT 2-UP
</button>
</div>
</div>
</div>
</header>
<section
v-if="viewMode === 'focus'"
class="grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]"
v-if="screenMode === 'planner' && viewMode === 'focus'"
class="print-hidden grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]"
>
<PlannerPage
:date-main="selectedDateDisplay.main"
:date-weekday="selectedDateDisplay.weekday"
:date-weekday-tone="selectedDateDisplay.weekdayTone"
:dday="planner.dday"
:comment="planner.comment"
:total-time="formatTotalTime(planner)"
:tasks="planner.tasks"
:memo="planner.memo"
:hours="hours"
:timetable="planner.timetable"
@update:comment="updateComment(planner, $event)"
@update:task-label="updateTaskLabel(planner, $event)"
@update:task-title="updateTaskTitle(planner, $event)"
@toggle:task="toggleTask(planner, $event)"
@update:memo-label="updateMemoLabel(planner, $event)"
@update:memo="updateMemo(planner, $event)"
@update:timetable="updateTimetable(planner, $event)"
/>
<div class="print-target">
<PlannerPage
:date-main="selectedDateDisplay.main"
:date-weekday="selectedDateDisplay.weekday"
:date-weekday-tone="selectedDateDisplay.weekdayTone"
:dday="planner.dday"
:comment="planner.comment"
:total-time="formatTotalTime(planner)"
:tasks="planner.tasks"
:memo="planner.memo"
:hours="hours"
:timetable="planner.timetable"
@update:comment="updateComment(planner, $event)"
@update:task-label="updateTaskLabel(planner, $event)"
@update:task-title="updateTaskTitle(planner, $event)"
@toggle:task="toggleTask(planner, $event)"
@update:memo-label="updateMemoLabel(planner, $event)"
@update:memo="updateMemo(planner, $event)"
@update:timetable="updateTimetable(planner, $event)"
/>
</div>
<aside class="flex flex-col gap-4">
<aside class="print-hidden flex flex-col gap-4">
<section class="border border-stone-200 bg-white/80 p-5">
<p class="mb-4 text-[11px] font-bold tracking-[0.22em] text-ink">PREV SNAPSHOT</p>
<div class="space-y-3">
@@ -583,7 +911,8 @@ function clearTaskLabels(record) {
<p class="text-[11px] font-bold tracking-[0.22em] text-ink">NEXT DAY</p>
<div class="mt-5 space-y-3">
<p class="text-lg font-semibold tracking-[-0.04em] text-stone-900">
{{ secondaryDateDisplay.main }} {{ secondaryDateDisplay.weekday }}
<span>{{ secondaryDateDisplay.main }}</span>
<span class="ml-1" :class="secondaryDateDisplay.weekdayTone">{{ secondaryDateDisplay.weekday }}</span>
</p>
<p class="text-[11px] font-semibold tracking-[0.08em] text-stone-600">
내일의 작업은 "{{ secondaryPlanner.tasks[0]?.title || '새 작업 추가' }}" 시작합니다.
@@ -594,48 +923,152 @@ function clearTaskLabels(record) {
</aside>
</section>
<section v-else class="overflow-x-auto rounded-[32px] border border-white/60 bg-white/40 p-4 sm:p-6">
<section
v-else-if="screenMode === 'planner'"
class="print-hidden overflow-x-auto rounded-[32px] border border-white/60 bg-white/40 p-4 sm:p-6"
>
<div class="flex min-w-[1260px] gap-6">
<PlannerPage
:date-main="selectedDateDisplay.main"
:date-weekday="selectedDateDisplay.weekday"
:date-weekday-tone="selectedDateDisplay.weekdayTone"
:dday="planner.dday"
:comment="planner.comment"
:total-time="formatTotalTime(planner)"
:tasks="planner.tasks"
:memo="planner.memo"
:hours="hours"
:timetable="planner.timetable"
@update:comment="updateComment(planner, $event)"
@update:task-label="updateTaskLabel(planner, $event)"
@update:task-title="updateTaskTitle(planner, $event)"
@toggle:task="toggleTask(planner, $event)"
@update:memo-label="updateMemoLabel(planner, $event)"
@update:memo="updateMemo(planner, $event)"
@update:timetable="updateTimetable(planner, $event)"
/>
<PlannerPage
:date-main="secondaryDateDisplay.main"
:date-weekday="secondaryDateDisplay.weekday"
:date-weekday-tone="secondaryDateDisplay.weekdayTone"
:dday="secondaryPlanner.dday"
:comment="secondaryPlanner.comment"
:total-time="formatTotalTime(secondaryPlanner)"
:tasks="secondaryPlanner.tasks"
:memo="secondaryPlanner.memo"
:hours="hours"
:timetable="secondaryPlanner.timetable"
@update:comment="updateComment(secondaryPlanner, $event)"
@update:task-label="updateTaskLabel(secondaryPlanner, $event)"
@update:task-title="updateTaskTitle(secondaryPlanner, $event)"
@toggle:task="toggleTask(secondaryPlanner, $event)"
@update:memo-label="updateMemoLabel(secondaryPlanner, $event)"
@update:memo="updateMemo(secondaryPlanner, $event)"
@update:timetable="updateTimetable(secondaryPlanner, $event)"
/>
<div class="print-target">
<PlannerPage
:date-main="selectedDateDisplay.main"
:date-weekday="selectedDateDisplay.weekday"
:date-weekday-tone="selectedDateDisplay.weekdayTone"
:dday="planner.dday"
:comment="planner.comment"
:total-time="formatTotalTime(planner)"
:tasks="planner.tasks"
:memo="planner.memo"
:hours="hours"
:timetable="planner.timetable"
@update:comment="updateComment(planner, $event)"
@update:task-label="updateTaskLabel(planner, $event)"
@update:task-title="updateTaskTitle(planner, $event)"
@toggle:task="toggleTask(planner, $event)"
@update:memo-label="updateMemoLabel(planner, $event)"
@update:memo="updateMemo(planner, $event)"
@update:timetable="updateTimetable(planner, $event)"
/>
</div>
<div class="print-hidden">
<PlannerPage
:date-main="secondaryDateDisplay.main"
:date-weekday="secondaryDateDisplay.weekday"
:date-weekday-tone="secondaryDateDisplay.weekdayTone"
:dday="secondaryPlanner.dday"
:comment="secondaryPlanner.comment"
:total-time="formatTotalTime(secondaryPlanner)"
:tasks="secondaryPlanner.tasks"
:memo="secondaryPlanner.memo"
:hours="hours"
:timetable="secondaryPlanner.timetable"
@update:comment="updateComment(secondaryPlanner, $event)"
@update:task-label="updateTaskLabel(secondaryPlanner, $event)"
@update:task-title="updateTaskTitle(secondaryPlanner, $event)"
@toggle:task="toggleTask(secondaryPlanner, $event)"
@update:memo-label="updateMemoLabel(secondaryPlanner, $event)"
@update:memo="updateMemo(secondaryPlanner, $event)"
@update:timetable="updateTimetable(secondaryPlanner, $event)"
/>
</div>
</div>
</section>
<StatsDashboard
v-else
class="print-hidden"
:overview-cards="overviewCards"
:weekly-records="weeklyRecords"
:recent-records="recentRecords"
:best-day="bestDay"
:selected-date-label="`${selectedDateDisplay.main} ${selectedDateDisplay.weekday}`"
:range-start="normalizedStatsRange.startKey"
:range-end="normalizedStatsRange.endKey"
@update:range-start="statsRangeStart = $event"
@update:range-end="statsRangeEnd = $event"
/>
<section class="print-only">
<div v-if="printLayout === 'single'" class="print-paper print-paper--single">
<div class="print-sheet-frame">
<PlannerPage
:date-main="selectedDateDisplay.main"
:date-weekday="selectedDateDisplay.weekday"
:date-weekday-tone="selectedDateDisplay.weekdayTone"
:dday="planner.dday"
:comment="planner.comment"
:total-time="formatTotalTime(planner)"
:tasks="planner.tasks"
:memo="planner.memo"
:hours="hours"
:timetable="planner.timetable"
@update:comment="updateComment(planner, $event)"
@update:task-label="updateTaskLabel(planner, $event)"
@update:task-title="updateTaskTitle(planner, $event)"
@toggle:task="toggleTask(planner, $event)"
@update:memo-label="updateMemoLabel(planner, $event)"
@update:memo="updateMemo(planner, $event)"
@update:timetable="updateTimetable(planner, $event)"
/>
</div>
</div>
<div v-else class="print-paper print-paper--double">
<div class="print-sheet-frame">
<PlannerPage
:date-main="selectedDateDisplay.main"
:date-weekday="selectedDateDisplay.weekday"
:date-weekday-tone="selectedDateDisplay.weekdayTone"
:dday="planner.dday"
:comment="planner.comment"
:total-time="formatTotalTime(planner)"
:tasks="planner.tasks"
:memo="planner.memo"
:hours="hours"
:timetable="planner.timetable"
@update:comment="updateComment(planner, $event)"
@update:task-label="updateTaskLabel(planner, $event)"
@update:task-title="updateTaskTitle(planner, $event)"
@toggle:task="toggleTask(planner, $event)"
@update:memo-label="updateMemoLabel(planner, $event)"
@update:memo="updateMemo(planner, $event)"
@update:timetable="updateTimetable(planner, $event)"
/>
</div>
<div class="print-sheet-frame">
<PlannerPage
:date-main="secondaryDateDisplay.main"
:date-weekday="secondaryDateDisplay.weekday"
:date-weekday-tone="secondaryDateDisplay.weekdayTone"
:dday="secondaryPlanner.dday"
:comment="secondaryPlanner.comment"
:total-time="formatTotalTime(secondaryPlanner)"
:tasks="secondaryPlanner.tasks"
:memo="secondaryPlanner.memo"
:hours="hours"
:timetable="secondaryPlanner.timetable"
@update:comment="updateComment(secondaryPlanner, $event)"
@update:task-label="updateTaskLabel(secondaryPlanner, $event)"
@update:task-title="updateTaskTitle(secondaryPlanner, $event)"
@toggle:task="toggleTask(secondaryPlanner, $event)"
@update:memo-label="updateMemoLabel(secondaryPlanner, $event)"
@update:memo="updateMemo(secondaryPlanner, $event)"
@update:timetable="updateTimetable(secondaryPlanner, $event)"
/>
</div>
</div>
</section>
</div>
<AuthDialog
:open="authDialogOpen"
:mode="authMode"
:form="authForm"
:busy="authBusy"
:message="authMessage"
@close="closeAuthDialog"
@submit="submitAuthForm"
@switch-mode="authMode = $event; authMessage = ''"
@update:field="updateAuthField"
/>
</main>
</template>

View 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>

View File

@@ -115,7 +115,7 @@ 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-6 py-6 text-[10px] font-bold tracking-[0.16em] text-ink shadow-paper sm:px-12 sm:py-12"
>
<div class="flex flex-col gap-4 py-[18px]">
<div class="flex gap-4">
@@ -230,7 +230,10 @@ onBeforeUnmount(() => {
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">
<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

View 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>

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

@@ -0,0 +1,81 @@
const AUTH_STORAGE_KEY = 'ten-minute-planner-auth'
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:3001'
function buildHeaders(token, extraHeaders = {}) {
return {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
...extraHeaders,
}
}
async function request(path, { method = 'GET', token, body } = {}) {
const response = await fetch(`${API_BASE_URL}${path}`, {
method,
headers: buildHeaders(token),
body: body ? JSON.stringify(body) : undefined,
})
const data = await response.json().catch(() => ({}))
if (!response.ok) {
throw new Error(data.message || '요청 처리 중 문제가 발생했습니다.')
}
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,
})
}

92
src/lib/plannerStorage.js Normal file
View File

@@ -0,0 +1,92 @@
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 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,
}) {
if (typeof window === 'undefined') {
return
}
const serializableRecords = Object.fromEntries(
Object.entries(plannerRecords).map(([key, record]) => [
key,
{
...record,
tasks: record.tasks.map((task) => ({ ...task })),
memo: record.memo.map((item) => ({ ...item })),
timetable: [...record.timetable],
},
]),
)
window.localStorage.setItem(
STORAGE_KEY,
JSON.stringify({
selectedDate: selectedDate.toISOString(),
calendarViewDate: calendarViewDate.toISOString(),
statsRangeStart,
statsRangeEnd,
records: serializableRecords,
}),
)
}

View File

@@ -20,3 +20,133 @@
@apply outline-none;
}
}
@media print {
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, 141mm);
justify-content: center;
align-content: center;
column-gap: 3mm;
}
body[data-print-layout='double'] .print-paper {
width: 287mm;
height: 198mm;
}
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: 141mm;
height: 198mm;
}
.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.978);
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.694);
box-shadow: none !important;
background: #ffffff !important;
}
.print-sheet-frame .planner-sheet * {
-webkit-print-color-adjust: exact;
print-color-adjust: exact;
}
}
@media screen {
.print-only {
display: none !important;
}
}