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>
This commit is contained in:
2026-07-19 10:12:17 +09:00
co-authored by Claude Sonnet 5
parent 55918d56d1
commit d212451fe0
15 changed files with 355 additions and 9 deletions
+39 -1
View File
@@ -1,5 +1,5 @@
import enum
from datetime import datetime, time
from datetime import date, datetime, time, timedelta
from sqlalchemy import Enum, ForeignKey, Integer, SmallInteger, String, Time
from sqlalchemy.orm import Mapped, mapped_column, relationship
@@ -21,6 +21,29 @@ class HabitStatus(str, enum.Enum):
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"
@@ -34,6 +57,9 @@ class Habit(Base):
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)
@@ -48,3 +74,15 @@ class Habit(Base):
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)
+9 -2
View File
@@ -9,12 +9,12 @@ from pydantic import ValidationError
from sqlalchemy.orm import Session
from app.database import get_db
from app.models.habit import HabitStatus, HabitType
from app.models.habit import HabitDifficulty, HabitStatus, HabitType
from app.models.user import User
from app.schemas.habit import HabitCreate, HabitUpdate
from app.security import get_current_user_optional
from app.services import habit_service, log_service
from app.template_utils import heatmap_opacity, is_milestone_streak, weekday_label
from app.template_utils import difficulty_label, goal_progress, heatmap_opacity, is_milestone_streak, weekday_label
router = APIRouter()
@@ -22,6 +22,9 @@ templates = Jinja2Templates(directory="app/templates")
templates.env.globals["weekday_label"] = weekday_label
templates.env.globals["heatmap_opacity"] = heatmap_opacity
templates.env.globals["is_milestone_streak"] = is_milestone_streak
templates.env.globals["difficulty_label"] = difficulty_label
templates.env.globals["goal_progress"] = goal_progress
templates.env.globals["habit_difficulties"] = list(HabitDifficulty)
def _current_user_or_redirect(request: Request, db: Session) -> User | RedirectResponse:
@@ -155,6 +158,7 @@ def create_habit_page(
name: str = Form(""),
habit_type: str = Form(...),
weekdays_mask: int = Form(...),
difficulty: str = Form(HabitDifficulty.MEDIUM.value),
condition_text: str | None = Form(None),
reminder_time: str | None = Form(None),
db: Session = Depends(get_db),
@@ -169,6 +173,7 @@ def create_habit_page(
name=name,
habit_type=HabitType(habit_type),
weekdays_mask=weekdays_mask,
difficulty=HabitDifficulty(difficulty),
condition_text=condition_text,
reminder_time=parsed_time,
)
@@ -190,6 +195,7 @@ def edit_habit_page(
habit_id: int,
name: str = Form(""),
weekdays_mask: int = Form(...),
difficulty: str = Form(HabitDifficulty.MEDIUM.value),
condition_text: str | None = Form(None),
reminder_time: str | None = Form(None),
db: Session = Depends(get_db),
@@ -208,6 +214,7 @@ def edit_habit_page(
name=name,
habit_type=habit.habit_type,
weekdays_mask=weekdays_mask,
difficulty=HabitDifficulty(difficulty),
condition_text=condition_text,
reminder_time=parsed_time,
)
+3 -1
View File
@@ -2,13 +2,14 @@ from datetime import datetime, time
from pydantic import BaseModel, ConfigDict, field_validator
from app.models.habit import ALL_WEEKDAYS_MASK, HabitStatus, HabitType
from app.models.habit import ALL_WEEKDAYS_MASK, HabitDifficulty, HabitStatus, HabitType
class HabitBase(BaseModel):
name: str
habit_type: HabitType
weekdays_mask: int = ALL_WEEKDAYS_MASK
difficulty: HabitDifficulty = HabitDifficulty.MEDIUM
condition_text: str | None = None
reminder_time: time | None = None
@@ -52,6 +53,7 @@ class HabitOut(BaseModel):
habit_type: HabitType
status: HabitStatus
weekdays_mask: int
difficulty: HabitDifficulty
condition_text: str | None
reminder_time: time | None
created_at: datetime
+2
View File
@@ -45,6 +45,7 @@ def create_habit(db: Session, user_id: int, data: HabitCreate) -> Habit:
name=data.name,
habit_type=data.habit_type,
weekdays_mask=data.weekdays_mask,
difficulty=data.difficulty,
condition_text=data.condition_text,
reminder_time=data.reminder_time,
status=HabitStatus.ACTIVE,
@@ -59,6 +60,7 @@ def update_habit(db: Session, habit: Habit, data: HabitUpdate) -> Habit:
habit.name = data.name
habit.habit_type = data.habit_type
habit.weekdays_mask = data.weekdays_mask
habit.difficulty = data.difficulty
habit.condition_text = data.condition_text
habit.reminder_time = data.reminder_time
db.commit()
+34
View File
@@ -409,6 +409,40 @@ label {
color: var(--color-accent);
}
/* 목표 기간 난이도 선택 */
.difficulty-picker {
display: flex;
gap: 6px;
flex-wrap: wrap;
}
.difficulty-pill {
border-radius: 999px;
border: 1px solid var(--color-border);
background: transparent;
color: var(--color-text-muted);
font-size: 13px;
padding: 8px 14px;
cursor: pointer;
}
.difficulty-pill.selected {
background: var(--color-accent);
border-color: var(--color-accent);
color: #fff;
}
.difficulty-hint {
font-size: 12px;
color: var(--color-text-muted);
margin-top: 6px;
}
.goal-progress-badge {
font-size: 12px;
color: var(--color-text-muted);
}
/* 습관 리스트 아이템 */
.habit-item {
display: flex;
+29 -1
View File
@@ -1,8 +1,17 @@
from app.models.habit import ALL_WEEKDAYS_MASK
from datetime import date
from app.models.habit import ALL_WEEKDAYS_MASK, HABIT_DIFFICULTY_TARGET_DAYS, Habit, HabitDifficulty
from app.services.log_service import MILESTONE_STREAKS
_DAY_LABELS = ["", "", "", "", "", "", ""]
_DIFFICULTY_LABELS: dict[HabitDifficulty, str] = {
HabitDifficulty.EASY: "하 (21일)",
HabitDifficulty.MEDIUM: "중 (66일)",
HabitDifficulty.HARD: "상 (254일)",
HabitDifficulty.UNLIMITED: "기간 무제한",
}
def is_milestone_streak(streak: int) -> bool:
return streak in MILESTONE_STREAKS
@@ -15,6 +24,25 @@ def weekday_label(mask: int) -> str:
return ", ".join(days) if days else "선택된 요일 없음"
def difficulty_label(difficulty: HabitDifficulty) -> str:
return _DIFFICULTY_LABELS[difficulty]
def goal_progress(habit: Habit) -> dict | None:
"""습관의 목표 기간 진행 상황. 기간 무제한(UNLIMITED)이면 None."""
target_days = HABIT_DIFFICULTY_TARGET_DAYS[habit.difficulty]
if target_days is None:
return None
elapsed = (date.today() - habit.created_at.date()).days + 1 # 시작일을 1일차로 계산
elapsed = max(elapsed, 1)
return {
"elapsed": min(elapsed, target_days),
"target": target_days,
"remaining": max(target_days - elapsed, 0),
"reached": elapsed >= target_days,
}
def heatmap_opacity(checked_count: int, scheduled_count: int) -> float:
"""월별 캘린더 히트맵 셀의 배경 투명도(0~0.9)를 계산한다."""
if not scheduled_count:
@@ -26,3 +26,18 @@
</label>
<input x-show="alarmOn" x-cloak type="time" name="reminder_time" value="{{ reminder_value|default('') }}" style="margin-top:6px;" />
</div>
<div class="field">
<label>목표 기간 난이도</label>
<div class="difficulty-picker">
{% for d in habit_difficulties %}
<button
type="button"
class="difficulty-pill"
:class="{ selected: difficulty === '{{ d.value }}' }"
@click="difficulty = '{{ d.value }}'"
>{{ difficulty_label(d) }}</button>
{% endfor %}
</div>
<p class="difficulty-hint">습관 자동화까지 걸리는 기간에 대한 실증 연구(Lally et al., 2010, UCL) 기준입니다 — 하는 단순한 습관이 자동화되는 데 걸리는 기간(약 3주), 중은 전체 중앙값, 상은 노력이 많이 드는 습관의 상한(약 8개월)입니다.</p>
</div>
+2
View File
@@ -3,6 +3,7 @@
x-data="{
open: false,
mask: 127,
difficulty: 'medium',
alarmOn: false,
days: ['월', '화', '수', '목', '금', '토', '일'],
}"
@@ -22,6 +23,7 @@
>
<input type="hidden" name="habit_type" value="{{ habit_type }}" />
<input type="hidden" name="weekdays_mask" :value="mask" />
<input type="hidden" name="difficulty" :value="difficulty" />
<div class="field">
<label for="name-{{ habit_type }}">습관 이름</label>
+10
View File
@@ -3,6 +3,7 @@
x-data="{
editing: false,
mask: {{ habit.weekdays_mask }},
difficulty: '{{ habit.difficulty.value }}',
alarmOn: {{ 'true' if habit.reminder_time else 'false' }},
days: ['월', '화', '수', '목', '금', '토', '일'],
}"
@@ -17,6 +18,14 @@
{{ weekday_label(habit.weekdays_mask) }}
{% if habit.reminder_time %}· 알람 {{ habit.reminder_time.strftime("%H:%M") }}{% endif %}
</div>
{% set progress = goal_progress(habit) %}
<div class="goal-progress-badge">
{% if progress %}
목표 {{ difficulty_label(habit.difficulty) }} · {{ progress.elapsed }}/{{ progress.target }}일차{% if progress.reached %} · 목표 기간 달성!{% else %} (D-{{ progress.remaining }}){% endif %}
{% else %}
{{ difficulty_label(habit.difficulty) }}
{% endif %}
</div>
{% set stats = stats_map[habit.id] %}
{% if stats.scheduled_days > 0 %}
<div class="habit-item-stats">
@@ -78,6 +87,7 @@
hx-swap="innerHTML"
>
<input type="hidden" name="weekdays_mask" :value="mask" />
<input type="hidden" name="difficulty" :value="difficulty" />
<div class="field">
<label for="edit-name-{{ habit.id }}">습관 이름</label>