diff --git a/alembic/versions/20261207_090000_spaced_repetition.py b/alembic/versions/20261207_090000_spaced_repetition.py
new file mode 100644
index 0000000..6cdb3ce
--- /dev/null
+++ b/alembic/versions/20261207_090000_spaced_repetition.py
@@ -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")
diff --git a/app/db/models/__init__.py b/app/db/models/__init__.py
index b323099..633749c 100644
--- a/app/db/models/__init__.py
+++ b/app/db/models/__init__.py
@@ -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",
@@ -18,5 +18,6 @@
"Category",
"QuestionCompany",
"QuestionCompletion",
+ "QuestionAttempt",
"QuestionFavorite",
]
diff --git a/app/db/models/question_utils.py b/app/db/models/question_utils.py
index 5345964..9ac8efa 100644
--- a/app/db/models/question_utils.py
+++ b/app/db/models/question_utils.py
@@ -6,6 +6,7 @@
CheckConstraint,
ForeignKey,
Index,
+ SmallInteger,
String,
UniqueConstraint,
func,
@@ -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(
@@ -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"),
# Частичный индекс для активных пользователей
@@ -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):
"""Модель добавления вопросов в избранное пользователями."""
diff --git a/app/repositories/question.py b/app/repositories/question.py
index e05fec6..8d8ce25 100644
--- a/app/repositories/question.py
+++ b/app/repositories/question.py
@@ -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
diff --git a/app/repositories/question_completion.py b/app/repositories/question_completion.py
index fa20078..a16de13 100644
--- a/app/repositories/question_completion.py
+++ b/app/repositories/question_completion.py
@@ -1,18 +1,56 @@
"""Репозиторий для работы с отметками выполнения вопросов."""
+from datetime import datetime, timezone
from typing import Any
from uuid import UUID
-from sqlalchemy import and_, delete, func, select
+from sqlalchemy import and_, case, delete, extract, func, select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.loggers import log
from app.db.models.auth import User
from app.db.models.question import Category, Question
-from app.db.models.question_utils import PASSED, QuestionCompletion
+from app.db.models.question_utils import PASSED, QuestionAttempt, QuestionCompletion
from app.repositories.base import BaseRepository
from app.repositories.question import visible_questions_clause
+from app.services.spaced_repetition import ReviewState, schedule
+
+#: Вклад оценки в готовность, пока срок повторения не прошёл.
+LEVEL_WEIGHT = {PASSED: 1.0, "partial": 0.5, "failed": 0.0}
+
+
+def strength_expr():
+ """Насколько вопрос «держится» сейчас, 0..1 (NULL — отметки нет).
+
+ До срока повторения — вес оценки. После срока знание тает вдвое за каждый пропущенный
+ интервал: ``0.5 ** (просрочка / интервал)``. Ответ, повторённый через 7 дней, но
+ просроченный на неделю, весит 0.5; на две недели — 0.25.
+ """
+ weight = case(
+ *((QuestionCompletion.level == lvl, w) for lvl, w in LEVEL_WEIGHT.items()), else_=0.0
+ )
+ overdue = extract("epoch", func.now() - QuestionCompletion.next_review_at)
+ interval = func.greatest(
+ extract("epoch", QuestionCompletion.next_review_at - QuestionCompletion.completed_at),
+ 86400,
+ )
+ decay = case(
+ (
+ and_(
+ QuestionCompletion.next_review_at.is_not(None),
+ QuestionCompletion.next_review_at < func.now(),
+ ),
+ func.power(0.5, overdue / interval),
+ ),
+ else_=1.0,
+ )
+ return weight * decay
+
+
+def due_clause():
+ """Отметка, которую пора повторить (срок наступил)."""
+ return QuestionCompletion.next_review_at <= func.now()
class QuestionCompletionRepository(BaseRepository[QuestionCompletion, dict, dict]):
@@ -35,19 +73,64 @@ async def mark_question_complete(self, user_id: UUID, question_id: UUID) -> None
"""Отметить вопрос пройденным (идемпотентно); «частично»/«не прошёл» меняется на passed."""
await self.set_level(user_id, question_id, PASSED)
- async def set_level(self, user_id: UUID, question_id: UUID, level: str) -> None:
- """Поставить степень знания; upsert, безопасен при параллельных запросах."""
- stmt = pg_insert(QuestionCompletion).values(
- user_id=user_id, question_id=question_id, level=level
- )
- await self.session.execute(
- stmt.on_conflict_do_update(
- index_elements=["user_id", "question_id"],
- set_={"level": stmt.excluded.level, "completed_at": func.now()},
- where=QuestionCompletion.level != stmt.excluded.level,
+ async def set_level(
+ self, user_id: UUID, question_id: UUID, level: str, now: datetime | None = None
+ ) -> datetime | None:
+ """Поставить оценку и назначить следующее повторение; вернуть его срок.
+
+ Строка блокируется (``FOR UPDATE``), поэтому параллельные запросы не продвинут серию
+ дважды. Повторная та же оценка до срока ничего не меняет и в историю не пишется.
+ """
+ now = now or datetime.now(timezone.utc)
+ row = await self._locked(user_id, question_id)
+ if row is None:
+ first = schedule(None, level, now)
+ assert first is not None
+ inserted = await self.session.scalar(
+ pg_insert(QuestionCompletion)
+ .values(
+ user_id=user_id,
+ question_id=question_id,
+ level=first.level,
+ stage=first.stage,
+ next_review_at=first.next_review_at,
+ completed_at=now,
+ )
+ .on_conflict_do_nothing(index_elements=["user_id", "question_id"])
+ .returning(QuestionCompletion.id)
)
+ if inserted is not None:
+ self._log_attempt(user_id, question_id, level, now)
+ return first.next_review_at
+ # параллельный запрос успел вставить строку — дальше как с существующей
+ row = await self._locked(user_id, question_id)
+ assert row is not None
+
+ prev = ReviewState(row.level, row.stage, row.next_review_at)
+ nxt = schedule(prev, level, now)
+ if nxt is None:
+ return row.next_review_at
+ row.level, row.stage, row.next_review_at = nxt.level, nxt.stage, nxt.next_review_at
+ row.completed_at = now
+ self._log_attempt(user_id, question_id, level, now)
+ log.info(f"✅ Вопрос {question_id}: {level}, повторить {nxt.next_review_at:%Y-%m-%d}")
+ return nxt.next_review_at
+
+ async def _locked(self, user_id: UUID, question_id: UUID) -> QuestionCompletion | None:
+ return await self.session.scalar(
+ select(QuestionCompletion)
+ .where(
+ QuestionCompletion.user_id == user_id,
+ QuestionCompletion.question_id == question_id,
+ )
+ .with_for_update()
+ .execution_options(populate_existing=True)
+ )
+
+ def _log_attempt(self, user_id: UUID, question_id: UUID, level: str, now: datetime) -> None:
+ self.session.add(
+ QuestionAttempt(user_id=user_id, question_id=question_id, level=level, created_at=now)
)
- log.info(f"✅ Вопрос {question_id}: уровень {level} для пользователя {user_id}")
async def unmark_question_complete(
self,
@@ -132,6 +215,8 @@ async def get_user_completion_stats(self, user: User) -> dict[str, Any]:
func.count(QuestionCompletion.id).filter(QuestionCompletion.level == PASSED),
func.count(QuestionCompletion.id).filter(QuestionCompletion.level == "partial"),
func.count(QuestionCompletion.id).filter(QuestionCompletion.level == "failed"),
+ func.coalesce(func.sum(strength_expr()), 0.0),
+ func.count(QuestionCompletion.id).filter(due_clause()),
)
.select_from(Question)
.outerjoin(
@@ -147,11 +232,13 @@ async def get_user_completion_stats(self, user: User) -> dict[str, Any]:
).all()
total = {"easy": 0, "medium": 0, "hard": 0}
done = {"easy": 0, "medium": 0, "hard": 0}
- partial = failed = 0
- for difficulty, count, completed, part, fail in rows:
+ partial = failed = due = 0
+ strength = 0.0
+ for difficulty, count, completed, part, fail, held, due_now in rows:
key = difficulty.value if hasattr(difficulty, "value") else difficulty
total[key], done[key] = count, completed
partial, failed = partial + part, failed + fail
+ strength, due = strength + float(held), due + due_now
all_total, all_done = sum(total.values()), sum(done.values())
return {
"total": all_total,
@@ -165,6 +252,8 @@ async def get_user_completion_stats(self, user: User) -> dict[str, Any]:
"total_hard": total["hard"],
"hard_completed": done["hard"],
"overall_percentage": percentage(all_done, all_total),
+ "readiness": readiness(strength, all_total),
+ "due_count": due,
}
async def get_user_completion_stats_by_category(self, user: User) -> list[dict[str, Any]]:
@@ -183,6 +272,8 @@ async def get_user_completion_stats_by_category(self, user: User) -> list[dict[s
func.count(QuestionCompletion.id)
.filter(QuestionCompletion.level == "failed")
.label("failed_count"),
+ func.coalesce(func.sum(strength_expr()), 0.0).label("strength"),
+ func.count(QuestionCompletion.id).filter(due_clause()).label("due_count"),
)
.select_from(Category)
.join(
@@ -208,8 +299,10 @@ async def get_user_completion_stats_by_category(self, user: User) -> list[dict[s
"failed_count": failed,
"total_count": total,
"percentage": percentage(completed, total),
+ "readiness": readiness(float(strength), total),
+ "due_count": due,
}
- for category_id, name, total, completed, partial, failed in rows
+ for category_id, name, total, completed, partial, failed, strength, due in rows
]
@@ -218,3 +311,10 @@ def percentage(done: int, total: int) -> float:
if total <= 0:
return 0.0
return round(min(done, total) / total * 100, 2)
+
+
+def readiness(strength: float, total: int) -> float:
+ """Готовность, %: сумма «силы» ответов (см. ``strength_expr``) от числа вопросов."""
+ if total <= 0:
+ return 0.0
+ return round(min(strength, total) / total * 100, 1)
diff --git a/app/repositories/question_progress.py b/app/repositories/question_progress.py
index b0dd3bd..416508b 100644
--- a/app/repositories/question_progress.py
+++ b/app/repositories/question_progress.py
@@ -2,7 +2,7 @@
from uuid import UUID
-from sqlalchemy import literal, select, union_all
+from sqlalchemy import func, literal, select, union_all
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.models.auth import User
@@ -14,20 +14,35 @@
async def get_progress_ids(session: AsyncSession, user: User) -> dict[str, list[UUID]]:
"""Идентификаторы по степени знания и избранное, только по вопросам, видимым пользователю.
- Ключи: ``passed``, ``partial``, ``failed``, ``favorite``.
+ Ключи: ``passed``, ``partial``, ``failed``, ``favorite`` и ``due`` — вопросы, которые пора
+ повторить (они же есть и в своём уровне).
"""
+ mine = (QuestionCompletion.user_id == user.id, visible_questions_clause(user))
+ joined = (Question, Question.id == QuestionCompletion.question_id)
completed = (
select(QuestionCompletion.level.label("kind"), QuestionCompletion.question_id.label("qid"))
- .join(Question, Question.id == QuestionCompletion.question_id)
- .where(QuestionCompletion.user_id == user.id, visible_questions_clause(user))
+ .join(*joined)
+ .where(*mine)
+ )
+ due = (
+ select(literal("d").label("kind"), QuestionCompletion.question_id.label("qid"))
+ .join(*joined)
+ .where(*mine, QuestionCompletion.next_review_at <= func.now())
)
favorites = (
select(literal("f").label("kind"), QuestionFavorite.question_id.label("qid"))
.join(Question, Question.id == QuestionFavorite.question_id)
.where(QuestionFavorite.user_id == user.id, visible_questions_clause(user))
)
- rows = (await session.execute(union_all(completed, favorites))).all()
- result: dict[str, list[UUID]] = {"passed": [], "partial": [], "failed": [], "favorite": []}
+ rows = (await session.execute(union_all(completed, due, favorites))).all()
+ result: dict[str, list[UUID]] = {
+ "passed": [],
+ "partial": [],
+ "failed": [],
+ "due": [],
+ "favorite": [],
+ }
+ kinds = {"f": "favorite", "d": "due"}
for kind, qid in rows:
- result["favorite" if kind == "f" else kind].append(qid)
+ result[kinds.get(kind, kind)].append(qid)
return result
diff --git a/app/routers/progress.py b/app/routers/progress.py
index c4d0ab7..802a880 100644
--- a/app/routers/progress.py
+++ b/app/routers/progress.py
@@ -31,5 +31,6 @@ async def get_my_progress(current_user: CurrentActiveUser, session: SessionDep):
completed_ids=ids["passed"],
partial_ids=ids["partial"],
failed_ids=ids["failed"],
+ due_ids=ids["due"],
favorite_ids=ids["favorite"],
)
diff --git a/app/routers/question_completion.py b/app/routers/question_completion.py
index 87bb9cc..38ca6f4 100644
--- a/app/routers/question_completion.py
+++ b/app/routers/question_completion.py
@@ -79,7 +79,8 @@ async def mark_question_complete(
status_code=status.HTTP_200_OK,
description=(
"Степень знания вопроса: passed — прошёл (полный ответ), partial — частично, "
- "failed — не прошёл, null — снять отметку. Идемпотентно."
+ "failed — не прошёл, null — снять отметку. Назначает следующее повторение "
+ "(next_review_at). Та же оценка до срока ничего не меняет — идемпотентно."
),
dependencies=[
require_access(
@@ -96,8 +97,8 @@ async def set_question_mastery(
session: SessionDep,
service: CompletionServiceDep,
):
- await service.set_level(current_user, question_id, body.level)
- return MasteryResponse(question_id=question_id, level=body.level)
+ next_review_at = await service.set_level(current_user, question_id, body.level)
+ return MasteryResponse(question_id=question_id, level=body.level, next_review_at=next_review_at)
@router.delete(
diff --git a/app/schemas/progress.py b/app/schemas/progress.py
index 06bc2ce..4ff3d29 100644
--- a/app/schemas/progress.py
+++ b/app/schemas/progress.py
@@ -14,4 +14,7 @@ class ProgressResponse(BaseModel):
completed_ids: list[UUID] = Field(default_factory=list)
partial_ids: list[UUID] = Field(default_factory=list)
failed_ids: list[UUID] = Field(default_factory=list)
+ due_ids: list[UUID] = Field(
+ default_factory=list, description="Пора повторить: срок интервального повторения наступил"
+ )
favorite_ids: list[UUID] = Field(default_factory=list)
diff --git a/app/schemas/question.py b/app/schemas/question.py
index 8da1786..cf11d9f 100644
--- a/app/schemas/question.py
+++ b/app/schemas/question.py
@@ -226,9 +226,12 @@ class QuestionFilterParams(BaseModel):
# доп.фильтры
is_completed: bool | None = None
- progress: Literal["new", "review", "passed"] | None = Field(
+ progress: Literal["new", "review", "passed", "due"] | None = Field(
None,
- description="Степень знания: new — без отметки, review — частично или не прошёл, passed — прошёл",
+ description=(
+ "Степень знания: new — без отметки, review — частично или не прошёл, "
+ "passed — прошёл, due — пора повторить (срок повторения наступил)"
+ ),
)
exclude_inactive_categories: bool | None = None
diff --git a/app/schemas/question_completion.py b/app/schemas/question_completion.py
index 4a9bbfa..a7781b7 100644
--- a/app/schemas/question_completion.py
+++ b/app/schemas/question_completion.py
@@ -1,3 +1,4 @@
+from datetime import datetime
from typing import Literal
from uuid import UUID
@@ -24,6 +25,9 @@ class MasteryRequest(BaseModel):
class MasteryResponse(BaseModel):
question_id: UUID
level: MasteryLevel | None
+ next_review_at: datetime | None = Field(
+ default=None, description="Когда вопрос снова пора повторить (null — отметки нет)"
+ )
class CompletionStatsResponse(BaseModel):
@@ -40,6 +44,10 @@ class CompletionStatsResponse(BaseModel):
total_hard: int
hard_completed: int
overall_percentage: float
+ readiness: float = Field(
+ default=0.0, description="Готовность, %: оценки с учётом забывания после срока повторения"
+ )
+ due_count: int = Field(default=0, description="Вопросов, которые пора повторить сегодня")
class CategoryCompletionStats(BaseModel):
@@ -52,6 +60,8 @@ class CategoryCompletionStats(BaseModel):
failed_count: int = 0
total_count: int
percentage: float
+ readiness: float = 0.0
+ due_count: int = 0
class CategoryCompletionStatsListResponse(BaseModel):
diff --git a/app/services/question_completion.py b/app/services/question_completion.py
index 0c50c16..41bb581 100644
--- a/app/services/question_completion.py
+++ b/app/services/question_completion.py
@@ -1,5 +1,6 @@
"""Сервис для работы с отметками выполнения вопросов."""
+from datetime import datetime
from typing import Any
from uuid import UUID
@@ -36,14 +37,19 @@ async def mark_question_complete(self, user_id: UUID, question_id: UUID, current
raise NotFoundError("Вопрос не найден")
await self.repository.mark_question_complete(user_id, question_id)
- async def set_level(self, current_user, question_id: UUID, level: str | None) -> None:
- """Поставить степень знания или снять отметку (``None``). Невидимый вопрос — 404."""
+ async def set_level(
+ self, current_user, question_id: UUID, level: str | None
+ ) -> datetime | None:
+ """Поставить степень знания или снять отметку (``None``); вернуть срок повторения.
+
+ Невидимый вопрос — 404.
+ """
if not await self.repository.question_visible(question_id, current_user):
raise NotFoundError("Вопрос не найден")
if level is None:
await self.repository.unmark_question_complete(current_user.id, question_id)
- else:
- await self.repository.set_level(current_user.id, question_id, level)
+ return None
+ return await self.repository.set_level(current_user.id, question_id, level)
async def get_level(self, user_id: UUID, question_id: UUID) -> str | None:
completion = await self.repository.get_completion(user_id, question_id)
diff --git a/app/services/spaced_repetition.py b/app/services/spaced_repetition.py
new file mode 100644
index 0000000..5b138ba
--- /dev/null
+++ b/app/services/spaced_repetition.py
@@ -0,0 +1,54 @@
+"""Интервальные повторения: когда вопрос снова пора повторить.
+
+Правила:
+
+- «Не прошёл» — повторить завтра, «Частично» — через 3 дня; серия успешных ответов обнуляется.
+- «Прошёл» — следующая ступень серии: 7 → 21 → 60 → 150 дней (дальше 150).
+- Повторение назначается на начало дня по Москве: вопрос, отмеченный вечером, появится
+ в «На сегодня» с утра нужного дня, а не в тот же час.
+- Та же оценка до срока ничего не меняет (двойной клик, повторная проверка ИИ):
+ серия не растёт от того, что вопрос открыли дважды за день.
+"""
+
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+from zoneinfo import ZoneInfo
+
+PASSED, PARTIAL, FAILED = "passed", "partial", "failed"
+
+REVIEW_TZ = ZoneInfo("Europe/Moscow")
+#: Интервалы для «Прошёл» по номеру ступени (1-я успешная отметка — 7 дней).
+PASSED_INTERVALS_DAYS = (7, 21, 60, 150)
+RESET_INTERVAL_DAYS = {PARTIAL: 3, FAILED: 1}
+
+
+@dataclass(frozen=True)
+class ReviewState:
+ """Состояние вопроса у пользователя: оценка, ступень серии и срок повторения."""
+
+ level: str
+ stage: int
+ next_review_at: datetime | None
+
+
+def review_day(now: datetime, days: int) -> datetime:
+ """Начало дня (по Москве) через ``days`` дней от ``now``, в UTC."""
+ local = now.astimezone(REVIEW_TZ) + timedelta(days=days)
+ start = local.replace(hour=0, minute=0, second=0, microsecond=0)
+ return start.astimezone(timezone.utc)
+
+
+def is_due(state: ReviewState, now: datetime) -> bool:
+ return state.next_review_at is None or state.next_review_at <= now
+
+
+def schedule(prev: ReviewState | None, level: str, now: datetime) -> ReviewState | None:
+ """Новое состояние после оценки ``level`` или ``None``, если оценка ничего не меняет."""
+ if prev is not None and prev.level == level and not is_due(prev, now):
+ return None
+ if level == PASSED:
+ streak = prev.stage if prev is not None and prev.level == PASSED else 0
+ stage = min(streak + 1, len(PASSED_INTERVALS_DAYS))
+ days = PASSED_INTERVALS_DAYS[stage - 1]
+ return ReviewState(PASSED, stage, review_day(now, days))
+ return ReviewState(level, 0, review_day(now, RESET_INTERVAL_DAYS[level]))
diff --git a/docs/api.md b/docs/api.md
index b875da7..50a651b 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -40,7 +40,7 @@ Access levels: **Public** — no authentication; **Authenticated** — a valid a
| `DELETE` | `/companies/{company_id}` | Admin | Удаление компании |
| `GET` | `/companies/{company_id}/questions` | Authenticated | Получение вопросов компании с пагинацией |
| `POST` | `/questions/{question_id}/complete` | Authenticated | Отметить вопрос как выполненный |
-| `PUT` | `/questions/{question_id}/mastery` | Authenticated | Степень знания вопроса: passed — прошёл (полный ответ), partial — частично, failed — не прошёл, null — снять отметку. Идемпотентно. |
+| `PUT` | `/questions/{question_id}/mastery` | Authenticated | Степень знания вопроса: passed — прошёл (полный ответ), partial — частично, failed — не прошёл, null — снять отметку. Назначает следующее повторение (next_review_at). Та же оценка до срока ничего не меняет — идемпотентно. |
| `DELETE` | `/questions/{question_id}/complete` | Authenticated | Снять отметку выполнения с вопроса |
| `GET` | `/questions/{question_id}/is-completed` | Authenticated | Проверить, выполнен ли вопрос пользователем |
| `GET` | `/questions/completion/stats` | Authenticated | Получить статистику выполнения вопросов |
diff --git a/frontend/openapi.json b/frontend/openapi.json
index 7b7523a..1515a42 100644
--- a/frontend/openapi.json
+++ b/frontend/openapi.json
@@ -575,6 +575,11 @@
"title": "Completed Count",
"type": "integer"
},
+ "due_count": {
+ "default": 0,
+ "title": "Due Count",
+ "type": "integer"
+ },
"failed_count": {
"default": 0,
"title": "Failed Count",
@@ -589,6 +594,11 @@
"title": "Percentage",
"type": "number"
},
+ "readiness": {
+ "default": 0.0,
+ "title": "Readiness",
+ "type": "number"
+ },
"total_count": {
"title": "Total Count",
"type": "integer"
@@ -1260,6 +1270,12 @@
"CompletionStatsResponse": {
"description": "Статистика выполнения вопросов.",
"properties": {
+ "due_count": {
+ "default": 0,
+ "description": "Вопросов, которые пора повторить сегодня",
+ "title": "Due Count",
+ "type": "integer"
+ },
"easy_completed": {
"title": "Easy Completed",
"type": "integer"
@@ -1276,6 +1292,12 @@
"title": "Overall Percentage",
"type": "number"
},
+ "readiness": {
+ "default": 0.0,
+ "description": "Готовность, %: оценки с учётом забывания после срока повторения",
+ "title": "Readiness",
+ "type": "number"
+ },
"total": {
"title": "Total",
"type": "integer"
@@ -1723,6 +1745,19 @@
],
"title": "Level"
},
+ "next_review_at": {
+ "anyOf": [
+ {
+ "format": "date-time",
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Когда вопрос снова пора повторить (null — отметки нет)",
+ "title": "Next Review At"
+ },
"question_id": {
"format": "uuid",
"title": "Question Id",
@@ -1747,6 +1782,15 @@
"title": "Completed Ids",
"type": "array"
},
+ "due_ids": {
+ "description": "Пора повторить: срок интервального повторения наступил",
+ "items": {
+ "format": "uuid",
+ "type": "string"
+ },
+ "title": "Due Ids",
+ "type": "array"
+ },
"failed_ids": {
"items": {
"format": "uuid",
@@ -4759,7 +4803,8 @@
"enum": [
"new",
"review",
- "passed"
+ "passed",
+ "due"
],
"type": "string"
},
@@ -6262,7 +6307,7 @@
},
"/api/v1/questions/{question_id}/mastery": {
"put": {
- "description": "Степень знания вопроса: passed — прошёл (полный ответ), partial — частично, failed — не прошёл, null — снять отметку. Идемпотентно.",
+ "description": "Степень знания вопроса: passed — прошёл (полный ответ), partial — частично, failed — не прошёл, null — снять отметку. Назначает следующее повторение (next_review_at). Та же оценка до срока ничего не меняет — идемпотентно.",
"operationId": "set_question_mastery_api_v1_questions__question_id__mastery_put",
"parameters": [
{
diff --git a/frontend/src/components/ui/Mastery.tsx b/frontend/src/components/ui/Mastery.tsx
index f8cfd5e..a541274 100644
--- a/frontend/src/components/ui/Mastery.tsx
+++ b/frontend/src/components/ui/Mastery.tsx
@@ -1,5 +1,5 @@
import { useState, type MouseEvent, type ReactNode } from 'react';
-import { Box, Button, CircularProgress, IconButton, ListItemIcon, ListItemText, Menu, MenuItem, Tooltip, alpha, type SxProps, type Theme } from '@mui/material';
+import { Box, Button, CircularProgress, IconButton, ListItemIcon, ListItemText, ListSubheader, Menu, MenuItem, Tooltip, alpha, type SxProps, type Theme } from '@mui/material';
import {
CheckCircle as PassedIcon,
HighlightOff as FailedIcon,
@@ -20,18 +20,23 @@ interface MenuProps {
onClose: () => void;
level: MasteryLevel | null;
onSelect: (level: MasteryLevel | null) => void;
+ /** Пора повторить: та же оценка засчитывается как повторение, а не игнорируется. */
+ due?: boolean;
}
-const MasteryMenu = ({ anchorEl, onClose, level, onSelect }: MenuProps) => {
+const MasteryMenu = ({ anchorEl, onClose, level, onSelect, due = false }: MenuProps) => {
const color = useMasteryColor();
const pick = (value: MasteryLevel | null) => {
onClose();
- if (value !== level) onSelect(value);
+ if (value !== level || (due && value !== null)) onSelect(value);
};
return (