- Habits and the account now accumulate XP and levels from check streaks, with streak/level-up celebration banners and push notifications. - The "yesterday missed" banner on /today now lets a habit be explicitly marked failed (not just checked done), backed by a new HabitLog.status column so completion-rate/streak calculations never count a failed day as done. - The habit management tabs scroll horizontally on narrow screens instead of wrapping to two lines, with a pure-CSS edge shadow indicating more content.
105 lines
4.2 KiB
Python
105 lines
4.2 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=일)
|
|
|
|
|
|
def _by_value(enum_cls: type[enum.Enum]) -> list[str]:
|
|
"""SQLAlchemy Enum이 DB에 멤버 이름(예: "MEDIUM")이 아니라 값(예: "medium")을 쓰도록 강제한다.
|
|
|
|
values_callable을 안 주면 SQLAlchemy는 기본적으로 .name을 저장하는데, 이 앱의 CHECK 제약조건과
|
|
마이그레이션 기본값(server_default)은 전부 소문자 .value를 기준으로 작성되어 있어 불일치가 생긴다
|
|
(실제로 difficulty 컬럼에서 이 불일치로 LookupError가 발생한 사례가 있었음).
|
|
"""
|
|
return [member.value for member in enum_cls]
|
|
|
|
|
|
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, values_callable=_by_value), nullable=False
|
|
)
|
|
status: Mapped[HabitStatus] = mapped_column(
|
|
Enum(HabitStatus, native_enum=False, length=20, values_callable=_by_value),
|
|
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, values_callable=_by_value),
|
|
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)
|