Files
habit-tracker/app/models/habit.py
T
shinalokandClaude Sonnet 5 d212451fe0 add habit goal-period difficulty and habit formation research notes
Ground the 21-day habit myth in actual research (Lally et al. 2010) and let
users pick a target period (21/66/254 days or unlimited) matching that
study's easy/median/hard automaticity timelines when creating a habit,
with progress shown on the habits list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-19 10:12:17 +09:00

89 lines
3.4 KiB
Python

import enum
from datetime import date, datetime, time, timedelta
from sqlalchemy import Enum, ForeignKey, Integer, SmallInteger, String, Time
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func
from app.database import Base
ALL_WEEKDAYS_MASK = 0b1111111 # 월~일 전부 (bit0=월 ... bit6=일)
class HabitType(str, enum.Enum):
BUILD = "build" # 만들고 싶은 습관
QUIT = "quit" # 멈추고 싶은 습관
class HabitStatus(str, enum.Enum):
ACTIVE = "active"
COMPLETED = "completed"
ABANDONED = "abandoned"
class HabitDifficulty(str, enum.Enum):
"""목표 기간 난이도. Lally et al.(2010, UCL)의 습관 자동화 소요 기간 실증 연구를 근거로 한다
(자세한 내용은 habit-formation-research.md 참고).
- EASY: 기존 습관에 붙이기 쉬운 단순 행동이 자동화되는 데 걸린 기간(약 3주)
- MEDIUM: 전체 참가자의 자동화 소요 기간 중앙값
- HARD: 노력이 많이 드는 행동이 자동화되는 데 걸린 기간의 상한(연구 관찰 범위 18~254일 중 최대값)
- UNLIMITED: 목표 종료 시점 없이 계속 트래킹만 하는 습관
"""
EASY = "easy"
MEDIUM = "medium"
HARD = "hard"
UNLIMITED = "unlimited"
HABIT_DIFFICULTY_TARGET_DAYS: dict[HabitDifficulty, int | None] = {
HabitDifficulty.EASY: 21,
HabitDifficulty.MEDIUM: 66,
HabitDifficulty.HARD: 254,
HabitDifficulty.UNLIMITED: None,
}
class Habit(Base):
__tablename__ = "habit"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
user_id: Mapped[int | None] = mapped_column(
ForeignKey("user.id", ondelete="CASCADE"), nullable=True
)
name: Mapped[str] = mapped_column(String(200), nullable=False)
habit_type: Mapped[HabitType] = mapped_column(Enum(HabitType, native_enum=False, length=20), nullable=False)
status: Mapped[HabitStatus] = mapped_column(
Enum(HabitStatus, native_enum=False, length=20), nullable=False, default=HabitStatus.ACTIVE
)
weekdays_mask: Mapped[int] = mapped_column(SmallInteger, nullable=False, default=ALL_WEEKDAYS_MASK)
difficulty: Mapped[HabitDifficulty] = mapped_column(
Enum(HabitDifficulty, native_enum=False, length=20), nullable=False, default=HabitDifficulty.MEDIUM
)
condition_text: Mapped[str | None] = mapped_column(String(300), nullable=True)
reminder_time: Mapped[time | None] = mapped_column(Time, nullable=True)
sort_order: Mapped[int | None] = mapped_column(Integer, nullable=True)
created_at: Mapped[datetime] = mapped_column(server_default=func.now(), nullable=False)
completed_at: Mapped[datetime | None] = mapped_column(nullable=True)
abandoned_at: Mapped[datetime | None] = mapped_column(nullable=True)
logs: Mapped[list["HabitLog"]] = relationship(
back_populates="habit", cascade="all, delete-orphan", passive_deletes=True
)
def is_scheduled_on(self, weekday: int) -> bool:
"""weekday: Python date.weekday() 기준 (월=0 ... 일=6)"""
return bool(self.weekdays_mask & (1 << weekday))
@property
def target_days(self) -> int | None:
return HABIT_DIFFICULTY_TARGET_DAYS[self.difficulty]
@property
def goal_target_date(self) -> date | None:
"""목표 기간이 끝나는 날짜. UNLIMITED면 None."""
days = self.target_days
if days is None:
return None
return self.created_at.date() + timedelta(days=days - 1)