Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions alembic/versions/20261207_090000_spaced_repetition.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
"""spaced repetition: question_completions.stage/next_review_at, question_attempts

Revision ID: d9e7a3b61f05
Revises: c8d6f2a50e94
Create Date: 2026-12-07 09:00:00

1. question_completions.stage и next_review_at: ступень серии успешных ответов и срок
следующего повторения. Существующие отметки получают срок от даты отметки по тем же
правилам, что и новые (app/services/spaced_repetition.py): passed — ступень 1 и +7 дней,
partial — +3 дня, failed — +1 день, начало дня по Москве. Старые отметки поэтому сразу
попадают в «На сегодня» — так и задумано: их давно пора повторить.
2. Новая таблица question_attempts — история оценок; заполняется текущими отметками.
Downgrade удаляет таблицу и колонки; сами отметки (level) не меняются.
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql

revision: str = 'd9e7a3b61f05'
down_revision: Union[str, Sequence[str], None] = 'c8d6f2a50e94'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
op.add_column(
"question_completions",
sa.Column("stage", sa.SmallInteger(), server_default="0", nullable=False,
comment="Ступень интервального повторения: сколько раз подряд «прошёл»"),
)
op.add_column(
"question_completions",
sa.Column("next_review_at", sa.TIMESTAMP(timezone=True), nullable=True,
comment="Когда вопрос снова пора повторить"),
)
op.execute(
"""
UPDATE question_completions
SET stage = CASE WHEN level = 'passed' THEN 1 ELSE 0 END,
next_review_at = (
date_trunc('day', completed_at AT TIME ZONE 'Europe/Moscow')
+ make_interval(days => CASE level WHEN 'passed' THEN 7
WHEN 'partial' THEN 3 ELSE 1 END)
) AT TIME ZONE 'Europe/Moscow'
"""
)
op.create_index(
"idx_completions_user_next_review",
"question_completions",
["user_id", "next_review_at"],
)

op.create_table(
"question_attempts",
sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False,
comment="Уникальный идентификатор записи"),
sa.Column("user_id", postgresql.UUID(as_uuid=True), nullable=False,
comment="ID пользователя"),
sa.Column("question_id", postgresql.UUID(as_uuid=True), nullable=False,
comment="ID вопроса"),
sa.Column("level", sa.String(length=16), nullable=False,
comment="passed | partial | failed"),
sa.Column("created_at", sa.TIMESTAMP(timezone=True), server_default=sa.text("now()"),
nullable=False, comment="Когда поставлена оценка"),
sa.CheckConstraint("level IN ('passed', 'partial', 'failed')",
name="ck_question_attempts_level"),
sa.ForeignKeyConstraint(["question_id"], ["questions.id"], ondelete="CASCADE"),
sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_question_attempts_question_id", "question_attempts", ["question_id"])
op.create_index(
"idx_attempts_user_question_created",
"question_attempts",
["user_id", "question_id", "created_at"],
)
op.execute(
"""
INSERT INTO question_attempts (id, user_id, question_id, level, created_at)
SELECT gen_random_uuid(), user_id, question_id, level, completed_at
FROM question_completions
"""
)


def downgrade() -> None:
op.drop_index("idx_attempts_user_question_created", table_name="question_attempts")
op.drop_index("ix_question_attempts_question_id", table_name="question_attempts")
op.drop_table("question_attempts")
op.drop_index("idx_completions_user_next_review", table_name="question_completions")
op.drop_column("question_completions", "next_review_at")
op.drop_column("question_completions", "stage")
3 changes: 2 additions & 1 deletion app/db/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from app.db.models.auth import AdminAuditLog, Feedback, PasswordResetToken, User
from app.db.models.base import Base
from app.db.models.question import Answer, Category, Question, QuestionCompany
from app.db.models.question_utils import QuestionCompletion, QuestionFavorite
from app.db.models.question_utils import QuestionAttempt, QuestionCompletion, QuestionFavorite

__all__ = [
"Base",
Expand All @@ -18,5 +18,6 @@
"Category",
"QuestionCompany",
"QuestionCompletion",
"QuestionAttempt",
"QuestionFavorite",
]
56 changes: 56 additions & 0 deletions app/db/models/question_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
CheckConstraint,
ForeignKey,
Index,
SmallInteger,
String,
UniqueConstraint,
func,
Expand Down Expand Up @@ -54,6 +55,18 @@ class QuestionCompletion(Base):
server_default=PASSED,
comment="passed | partial | failed",
)
stage: Mapped[int] = mapped_column(
SmallInteger,
nullable=False,
default=0,
server_default="0",
comment="Ступень интервального повторения: сколько раз подряд «прошёл»",
)
next_review_at: Mapped[datetime | None] = mapped_column(
TIMESTAMP(timezone=True),
nullable=True,
comment="Когда вопрос снова пора повторить",
)

############# Metadata #############
completed_at: Mapped[datetime] = mapped_column(
Expand Down Expand Up @@ -84,6 +97,7 @@ class QuestionCompletion(Base):
),
# Индекс для быстрого поиска по пользователю и дате
Index("idx_completions_user_completed_at", "user_id", "completed_at"),
Index("idx_completions_user_next_review", "user_id", "next_review_at"),
# Индекс для быстрого подсчета выполненных вопросов
Index("idx_completions_question_count", "question_id", "completed_at"),
# Частичный индекс для активных пользователей
Expand All @@ -96,6 +110,48 @@ class QuestionCompletion(Base):
)


class QuestionAttempt(Base):
"""История оценок вопроса: каждая засчитанная отметка (для динамики знаний)."""

__tablename__ = "question_attempts"

id: Mapped[UUID] = mapped_column(
UUID(as_uuid=True),
primary_key=True,
default=uuid4,
comment="Уникальный идентификатор записи",
)
user_id: Mapped[UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("users.id", ondelete="CASCADE"),
nullable=False,
comment="ID пользователя",
)
question_id: Mapped[UUID] = mapped_column(
UUID(as_uuid=True),
ForeignKey("questions.id", ondelete="CASCADE"),
nullable=False,
index=True,
comment="ID вопроса",
)
level: Mapped[str] = mapped_column(
String(16), nullable=False, comment="passed | partial | failed"
)
created_at: Mapped[datetime] = mapped_column(
TIMESTAMP(timezone=True),
server_default=func.now(),
nullable=False,
comment="Когда поставлена оценка",
)

__table_args__ = (
CheckConstraint(
"level IN ('passed', 'partial', 'failed')", name="ck_question_attempts_level"
),
Index("idx_attempts_user_question_created", "user_id", "question_id", "created_at"),
)


class QuestionFavorite(Base):
"""Модель добавления вопросов в избранное пользователями."""

Expand Down
4 changes: 4 additions & 0 deletions app/repositories/question.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,10 @@ def _filter_clauses(
clauses.append(~exists().where(*mine))
elif progress == "passed":
clauses.append(exists().where(*mine, QuestionCompletion.level == PASSED))
elif progress == "due":
clauses.append(
exists().where(*mine, QuestionCompletion.next_review_at <= func.now())
)
else:
clauses.append(exists().where(*mine, QuestionCompletion.level != PASSED))
return clauses
Expand Down
Loading
Loading