diff --git a/app/content/loader.py b/app/content/loader.py
index c49bf37..f4a5f74 100644
--- a/app/content/loader.py
+++ b/app/content/loader.py
@@ -156,26 +156,61 @@ class BuildStep(Strict):
indent: int = Field(0, ge=0, le=3)
+IDENT_RE = re.compile(r"^[a-z_][a-z0-9_]*$")
+
+
+class SchemaField(Strict):
+ name: str = Field(min_length=1, max_length=40)
+ # ref: внешний ключ — на какую таблицу ссылается поле
+ ref: str | None = None
+
+
+class SchemaTable(Strict):
+ name: str = Field(min_length=1, max_length=40)
+ # Поле — строка (имя) или {name, ref} для внешнего ключа
+ fields: list[str | SchemaField] = Field(min_length=1, max_length=8)
+
+ @property
+ def columns(self) -> list[SchemaField]:
+ return [f if isinstance(f, SchemaField) else SchemaField(name=f) for f in self.fields]
+
+
class BuildTask(Strict):
- """Задание-конструктор: решение собирается из блоков (задача Парсонса).
+ """Задание-конструктор: решение собирается из блоков.
- Шаги пишутся в правильном порядке; в вопрос уходят перемешанные куски вместе
- с отвлекающими, в эталонный ответ — решение с вложенностью.
+ sequence — алгоритм из шагов (задача Парсонса): шаги пишутся в правильном порядке,
+ в вопрос уходят перемешанные куски, в эталон — решение с вложенностью.
+ schema — схема БД: таблицы заданы, кандидат раскладывает по ним поля и отмечает
+ внешние ключи; в вопрос уходят имена таблиц и перемешанные поля, в эталон — схема.
"""
- kind: Literal["sequence"] = "sequence"
+ kind: Literal["sequence", "schema"] = "sequence"
# replace — конструктор вместо текстового ответа; with_text — рядом с ним
mode: Literal["replace", "with_text"] = "replace"
prompt: str = Field(min_length=5, max_length=300)
# with_text: что кандидат объясняет словами (ИИ оценивает только эту часть)
text_prompt: str | None = Field(None, min_length=5, max_length=300)
- steps: list[BuildStep] = Field(min_length=3, max_length=12)
+ steps: list[BuildStep] = Field(default_factory=list, max_length=12)
+ tables: list[SchemaTable] = Field(default_factory=list, max_length=6)
distractors: list[str] = Field(default_factory=list, max_length=4)
@model_validator(mode="after")
- def check_steps(self) -> BuildTask:
+ def check_task(self) -> BuildTask:
if (self.mode == "with_text") != (self.text_prompt is not None):
raise ValueError("text_prompt нужен для mode: with_text и только для него")
+ if any(not d.strip() for d in self.distractors):
+ raise ValueError("пустой отвлекающий блок")
+ if self.kind == "sequence":
+ self._check_sequence()
+ else:
+ self._check_schema()
+ return self
+
+ def _check_sequence(self) -> None:
+ if self.tables:
+ raise ValueError("tables допустимы только для kind: schema")
+ if not 3 <= len(self.steps) <= 12:
+ raise ValueError("steps: от 3 до 12 шагов")
if self.steps[0].indent != 0:
raise ValueError("первый шаг конструктора должен быть без отступа")
for prev, cur in zip(self.steps, self.steps[1:], strict=False):
@@ -184,32 +219,85 @@ def check_steps(self) -> BuildTask:
texts = [_norm(s.text) for s in self.steps] + [_norm(d) for d in self.distractors]
if len(set(texts)) != len(texts):
raise ValueError("тексты шагов и отвлекающих блоков должны различаться")
- if any(not d.strip() for d in self.distractors):
- raise ValueError("пустой отвлекающий блок")
- return self
+
+ def _check_schema(self) -> None:
+ if self.steps:
+ raise ValueError("steps допустимы только для kind: sequence")
+ if not 2 <= len(self.tables) <= 6:
+ raise ValueError("tables: от 2 до 6 таблиц")
+ names = [t.name for t in self.tables]
+ if len(set(names)) != len(names):
+ raise ValueError("имена таблиц повторяются")
+ field_names: set[str] = set()
+ for t in self.tables:
+ cols = [c.name for c in t.columns]
+ for ident in (t.name, *cols):
+ if not IDENT_RE.match(ident):
+ raise ValueError(f"«{ident}»: имя из a-z, 0-9 и _, начинается с буквы или _")
+ if len(set(cols)) != len(cols):
+ raise ValueError(f"таблица {t.name}: поля повторяются")
+ for c in t.columns:
+ if c.ref is not None and c.ref not in names:
+ raise ValueError(f"{t.name}.{c.name}: ссылка на неизвестную таблицу {c.ref}")
+ field_names.update(cols)
+ for d in self.distractors:
+ if not IDENT_RE.match(d.strip()):
+ raise ValueError(f"«{d}»: имя из a-z, 0-9 и _, начинается с буквы или _")
+ if d.strip() in field_names:
+ raise ValueError(f"отвлекающее поле {d} совпадает с настоящим")
+ if len(set(self.distractors)) != len(self.distractors):
+ raise ValueError("отвлекающие поля повторяются")
def _piece_id(self, slug: str, text: str) -> str:
- # id не выдаёт позицию шага: короткий хэш текста
+ # id не выдаёт позицию шага или таблицу поля: короткий хэш
return hashlib.sha1(f"{slug}:{_norm(text)}".encode()).hexdigest()[:8]
- def question_block(self, slug: str) -> dict[str, Any]:
- """Куски для сборки: правильные и отвлекающие вперемешку, порядок стабилен между импортами."""
- texts = [s.text.strip() for s in self.steps] + [d.strip() for d in self.distractors]
- pieces = [{"id": self._piece_id(slug, t), "text": t} for t in texts]
+ def _shuffle(self, slug: str, pieces: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Порядок кусков стабилен между импортами и не совпадает с ответом."""
shuffled = sorted(
pieces, key=lambda p: hashlib.sha1(f"{slug}:{p['id']}".encode()).hexdigest()
)
- step_ids = [p["id"] for p in pieces[: len(self.steps)]]
- if [p["id"] for p in shuffled if p["id"] in step_ids] == step_ids:
- shuffled.reverse() # перемешивание не должно случайно совпасть с ответом
+ real = [p["id"] for p in pieces if not p.get("distractor")]
+ if [p["id"] for p in shuffled if p["id"] in real] == real:
+ shuffled.reverse()
+ return [{"id": p["id"], "text": p["text"]} for p in shuffled]
+
+ def question_block(self, slug: str) -> dict[str, Any]:
+ """Куски для сборки: правильные и отвлекающие вперемешку."""
data: dict[str, Any] = {"kind": self.kind, "mode": self.mode, "prompt": self.prompt.strip()}
if self.text_prompt:
data["text_prompt"] = self.text_prompt.strip()
- data["pieces"] = shuffled
+ if self.kind == "sequence":
+ texts = [s.text.strip() for s in self.steps]
+ pieces = [{"id": self._piece_id(slug, t), "text": t} for t in texts]
+ else:
+ data["tables"] = [t.name for t in self.tables]
+ # поле с одинаковым именем (id) в разных таблицах — разные куски
+ pieces = [
+ {"id": self._piece_id(slug, f"{t.name}.{c.name}"), "text": c.name}
+ for t in self.tables
+ for c in t.columns
+ ]
+ pieces += [
+ {"id": self._piece_id(slug, d), "text": d.strip(), "distractor": True}
+ for d in self.distractors
+ ]
+ data["pieces"] = self._shuffle(slug, pieces)
return {"type": "constructor", "data": data}
def answer_block(self, slug: str) -> dict[str, Any]:
- """Эталон: шаги в правильном порядке с вложенностью."""
+ """Эталон: шаги в правильном порядке с вложенностью или схема с внешними ключами."""
+ if self.kind == "schema":
+ schema = [
+ {
+ "name": t.name,
+ "fields": [
+ {"name": c.name, **({"ref": c.ref} if c.ref else {})} for c in t.columns
+ ],
+ }
+ for t in self.tables
+ ]
+ return {"type": "constructor", "data": {"kind": "schema", "schema": schema}}
solution = [
{"id": self._piece_id(slug, s.text), "text": s.text.strip(), "indent": s.indent}
for s in self.steps
diff --git a/app/services/ai_review.py b/app/services/ai_review.py
index d08baf7..8518ab4 100644
--- a/app/services/ai_review.py
+++ b/app/services/ai_review.py
@@ -154,9 +154,9 @@ def blocks_to_text(blocks: list[dict[str, Any]] | None, limit: int) -> str:
def _constructor_text(data: dict[str, Any]) -> str:
- """Задание-конструктор в промпте: алгоритм кандидат собирает из блоков, его балл считается без ИИ.
+ """Задание-конструктор в промпте: решение кандидат собирает из блоков, его балл считается без ИИ.
- В вопросе — что объяснить словами, в эталоне — правильный порядок шагов как ориентир.
+ В вопросе — что объяснить словами, в эталоне — шаги или схема как ориентир.
"""
if data.get("solution"):
steps = "\n".join(
@@ -164,9 +164,21 @@ def _constructor_text(data: dict[str, Any]) -> str:
for i, s in enumerate(data["solution"], 1)
)
return f"Reference algorithm steps (graded separately):\n{steps}"
+ if data.get("schema"):
+ tables = "; ".join(
+ f"{t.get('name', '')}("
+ + ", ".join(
+ f"{f.get('name', '')} -> {f['ref']}" if f.get("ref") else str(f.get("name", ""))
+ for f in t.get("fields") or []
+ )
+ + ")"
+ for t in data["schema"]
+ )
+ return f"Reference schema (graded separately): {tables}"
if data.get("mode") == "with_text" and data.get("text_prompt"):
+ what = "database schema" if data.get("kind") == "schema" else "algorithm"
return (
- "[The candidate assembles the algorithm from blocks; that part is graded separately "
+ f"[The candidate assembles the {what} from blocks; that part is graded separately "
"without you. Grade ONLY the written answer to this task:] " + str(data["text_prompt"])
)
return ""
diff --git a/app/validators.py b/app/validators.py
index 8e39e6a..ff4344b 100644
--- a/app/validators.py
+++ b/app/validators.py
@@ -52,12 +52,15 @@ def validate_content_structure(contents: list[dict[str, Any]]) -> list[dict[str,
return contents
-CONSTRUCTOR_KINDS = ("sequence",)
+CONSTRUCTOR_KINDS = ("sequence", "schema")
CONSTRUCTOR_MODES = ("replace", "with_text")
def _validate_constructor(data: Any) -> None:
- """Блок конструктора: в вопросе — перемешанные куски (pieces), в ответе — эталон (solution)."""
+ """Блок конструктора: в вопросе — перемешанные куски (pieces), в ответе — эталон.
+
+ Эталон sequence — шаги (solution), эталон schema — таблицы с полями (schema).
+ """
if not isinstance(data, dict) or data.get("kind") not in CONSTRUCTOR_KINDS:
raise ValueError(f"Constructor-блок: data.kind должен быть одним из {CONSTRUCTOR_KINDS}")
mode = data.get("mode", "replace")
@@ -65,6 +68,17 @@ def _validate_constructor(data: Any) -> None:
raise ValueError(f"Constructor-блок: data.mode должен быть одним из {CONSTRUCTOR_MODES}")
if mode == "with_text" and not str(data.get("text_prompt", "")).strip():
raise ValueError("Constructor-блок with_text должен содержать data.text_prompt")
+ if "pieces" not in data and data["kind"] == "schema":
+ _validate_schema(data.get("schema"))
+ return
+ if "pieces" in data and data["kind"] == "schema":
+ tables = data.get("tables")
+ if (
+ not isinstance(tables, list)
+ or not tables
+ or not all(isinstance(t, str) and t.strip() for t in tables)
+ ):
+ raise ValueError("Constructor-блок schema должен содержать непустой data.tables")
items = data.get("pieces") if "pieces" in data else data.get("solution")
if not isinstance(items, list) or not items:
raise ValueError("Constructor-блок должен содержать непустой data.pieces или data.solution")
@@ -79,3 +93,21 @@ def _validate_constructor(data: Any) -> None:
ids.append(item["id"])
if len(set(ids)) != len(ids):
raise ValueError("id кусков конструктора должны быть уникальны")
+
+
+def _validate_schema(schema: Any) -> None:
+ """Эталонная схема: таблицы с непустыми полями, ref — на таблицу из этой же схемы."""
+ if not isinstance(schema, list) or not schema:
+ raise ValueError("Constructor-блок schema должен содержать непустой data.schema")
+ names = [t.get("name") if isinstance(t, dict) else None for t in schema]
+ if not all(isinstance(n, str) and n.strip() for n in names) or len(set(names)) != len(names):
+ raise ValueError("Таблицы схемы должны иметь уникальные непустые имена")
+ for table in schema:
+ fields = table.get("fields")
+ if not isinstance(fields, list) or not fields:
+ raise ValueError(f"Таблица {table['name']}: нужны поля")
+ for f in fields:
+ if not isinstance(f, dict) or not str(f.get("name", "")).strip():
+ raise ValueError(f"Таблица {table['name']}: у поля нет имени")
+ if f.get("ref") is not None and f["ref"] not in names:
+ raise ValueError(f"Таблица {table['name']}: ссылка на неизвестную таблицу")
diff --git a/content/questions/databases/db-normalization-1nf-3nf.yaml b/content/questions/databases/db-normalization-1nf-3nf.yaml
index 7e482d3..3b42c60 100644
--- a/content/questions/databases/db-normalization-1nf-3nf.yaml
+++ b/content/questions/databases/db-normalization-1nf-3nf.yaml
@@ -82,6 +82,26 @@ answer:
- info: "Короткий ориентир для собеседования: «каждый неключевой атрибут зависит от ключа, от всего ключа и ни от чего, кроме ключа». Дальше идёт **BCNF**: в любой нетривиальной функциональной зависимости X → Y левая часть X — суперключ (3NF допускает исключение, когда Y входит в какой-то потенциальный ключ). На практике обычно останавливаются на 3NF или BCNF."
- warning: "Не всякое «повторение» нарушает 3NF. Цена в `order_items` на момент покупки — это отдельный исторический факт, а не копия `products.price`: если товар подорожает, старые заказы не должны измениться. И наоборот, нормализация не бесплатна: больше `JOIN`, поэтому для отчётов и горячих чтений сознательно денормализуют (материализованные представления, счётчики), но с механизмом синхронизации."
- info: "Что могут спросить дальше: чем BCNF строже 3NF; приведите пример денормализации, которая оправдана; нарушает ли 1NF столбец `jsonb` или массив (формально да, если по элементам нужно искать, связывать или ставить ограничения; если значение читается целиком как документ — допустимо)."
+build:
+ kind: schema
+ mode: with_text
+ prompt: "Разложите поля плоской таблицы заказов по четырём таблицам в 3NF и отметьте внешние ключи. Поля, которые нарушают нормальные формы, оставьте в стороне."
+ text_prompt: "Объясните, чем отличаются 1NF, 2NF и 3NF и какую аномалию убирает каждый шаг на этом примере."
+ tables:
+ - name: customers
+ fields: [id, name, city]
+ - name: orders
+ fields:
+ - id
+ - {name: customer_id, ref: customers}
+ - name: order_items
+ fields:
+ - {name: order_id, ref: orders}
+ - {name: product_id, ref: products}
+ - qty
+ - name: products
+ fields: [id, title]
+ distractors: [items, customer_city, product_title]
sources:
- https://en.wikipedia.org/wiki/Database_normalization
- https://learn.microsoft.com/en-us/office/troubleshoot/access/database-normalization-description
diff --git a/docs/content.md b/docs/content.md
index a0aa8c7..5261b49 100644
--- a/docs/content.md
+++ b/docs/content.md
@@ -120,7 +120,7 @@ LeetCode и тексты статей не копируем, а пересказ
```yaml
build:
- kind: sequence # пока только алгоритм из шагов
+ kind: sequence # алгоритм из шагов; схема БД — kind: schema, см. ниже
prompt: 'Соберите алгоритм из блоков: порядок и вложенность. Лишние блоки оставьте.'
steps: # 3–12 шагов
- text: 'Завести пустой стек'
@@ -148,7 +148,31 @@ build:
Тексты шагов и отвлекающих блоков не повторяются, каждый шаг — одно действие до 200 символов. Балл
считает браузер: 10 × (наибольшая общая подпоследовательность с эталоном) / число шагов, минус 1 за
неверную вложенность и минус 2 за каждый взятый отвлекающий блок. Вопрос с `build` должен быть
-привязан к компании, иначе в режиме собеседования его не увидят.
+привязан к компании или стоять в шаге роадмапа, иначе в режиме собеседования его не увидят.
+
+`kind: schema` — схема БД: таблицы заданы, кандидат раскладывает по ним поля и отмечает, на какую
+таблицу ссылается внешний ключ. В вопрос уходят имена таблиц и перемешанные поля (одноимённые `id`
+разных таблиц взаимозаменяемы), в эталон — схема со ссылками.
+
+```yaml
+build:
+ kind: schema
+ mode: with_text # или replace
+ prompt: 'Разложите поля по таблицам в 3NF и отметьте внешние ключи'
+ text_prompt: 'Объясните, какую аномалию убирает каждый шаг'
+ tables: # 2–6 таблиц, в каждой 1–8 полей
+ - name: customers
+ fields: [id, name, city]
+ - name: orders
+ fields:
+ - id
+ - {name: customer_id, ref: customers} # внешний ключ: ref — имя таблицы из этого списка
+ distractors: [customer_city] # до 4 полей, которых в схеме быть не должно
+```
+
+Имена таблиц и полей — `a-z`, `0-9`, `_`. Балл: 10 × (поля в своей таблице + верные ссылки) /
+(поля эталона + ссылки эталона), минус 2 за каждое взятое отвлекающее поле и минус 1 за ссылку, которой
+нет в эталоне (лишнюю или не на ту таблицу).
### Сложность
diff --git a/frontend/src/components/ContentRenderer.tsx b/frontend/src/components/ContentRenderer.tsx
index ac62da6..8e3ceef 100644
--- a/frontend/src/components/ContentRenderer.tsx
+++ b/frontend/src/components/ContentRenderer.tsx
@@ -102,9 +102,40 @@ const extractData = (block: ContentBlock): BlockData => {
const ConstructorBlockView = ({ block }: { block: ContentBlock }) => {
const { c } = useTokens();
const solution = block.data?.solution;
+ const schema = block.data?.schema;
const pieces = block.data?.pieces;
+ const tables = block.data?.tables;
const rowSx = { fontFamily: fonts.mono, fontSize: '0.8125rem', lineHeight: 1.5, color: c.text, overflowWrap: 'anywhere' } as const;
+ if (schema?.length) {
+ return (
+
+
+ Эталонная схема
+
+
+ {schema.map((table) => (
+
+ {table.name}
+
+ {table.fields.map((f) => (
+
+ {f.name}
+ {f.ref && (
+
+ {' '}→ {f.ref}
+
+ )}
+
+ ))}
+
+
+ ))}
+
+
+ );
+ }
+
if (solution?.length) {
return (
@@ -134,13 +165,30 @@ const ConstructorBlockView = ({ block }: { block: ContentBlock }) => {
{block.data.prompt}
)}
-
- {pieces.map((p) => (
-
- {p.text}
-
- ))}
-
+ {tables?.length ? (
+ <>
+
+ Таблицы:{' '}
+
+ {tables.join(', ')}
+
+
+
+ Поля:{' '}
+
+ {pieces.map((p) => p.text).join(', ')}
+
+
+ >
+ ) : (
+
+ {pieces.map((p) => (
+
+ {p.text}
+
+ ))}
+
+ )}
{block.data?.text_prompt && (
@@ -150,7 +198,9 @@ const ConstructorBlockView = ({ block }: { block: ContentBlock }) => {
)}
- Собрать решение из этих блоков можно в режиме собеседования: порядок и вложенность проверятся автоматически.
+ {tables?.length
+ ? 'Разложить поля по таблицам можно в режиме собеседования: места полей и внешние ключи проверятся автоматически.'
+ : 'Собрать решение из этих блоков можно в режиме собеседования: порядок и вложенность проверятся автоматически.'}
);
diff --git a/frontend/src/components/interview/GradeScale.tsx b/frontend/src/components/interview/GradeScale.tsx
index 4596222..78f1767 100644
--- a/frontend/src/components/interview/GradeScale.tsx
+++ b/frontend/src/components/interview/GradeScale.tsx
@@ -2,7 +2,7 @@ import { Box, Stack, Typography } from '@mui/material';
import { MasteryIcon } from '../ui/Mastery';
import { MASTERY_LABEL, MASTERY_LEVELS, useMasteryColor } from '../ui/masteryLevels';
import { radius, useTokens } from '../../theme/tokens';
-import type { ConstructorMode, MasteryLevel } from '../../types';
+import type { ConstructorKind, ConstructorMode, MasteryLevel } from '../../types';
import { SELF_TO_LEVEL, type QuestionResult, scoreOf, textScoreOf } from './session';
/** Что стоит за каждым уровнем: диапазон оценки ИИ и как его заработать. */
@@ -14,25 +14,31 @@ const SCALE: Record = {
const HOW_TO = ['Суть в одной фразе', 'Как это устроено', 'Пример из практики', 'Подводные камни'];
+/** Как называть собранную часть: схема БД или сборка алгоритма. */
+const buildNoun = (result: QuestionResult) => (result.build?.fields ? 'схема' : 'сборка');
+
/** Откуда уровень: для сборки с текстом — итог и обе части. */
const withTextSource = (result: QuestionResult) => {
const final = scoreOf(result);
const build = result.build?.score;
const text = textScoreOf(result);
+ const noun = buildNoun(result);
if (result.revealed && final === undefined) return 'Подсмотрен эталон';
- if (final !== undefined) return `Итог: ${final}/10 (сборка ${build}, объяснение ${text})`;
- if (build !== undefined) return `Сборка: ${build}/10, объяснение ещё не оценено`;
- if (text !== undefined) return `Объяснение: ${text}/10, сборка не сдана`;
+ if (final !== undefined) return `Итог: ${final}/10 (${noun} ${build}, объяснение ${text})`;
+ if (build !== undefined) return `${capitalize(noun)}: ${build}/10, объяснение ещё не оценено`;
+ if (text !== undefined) return `Объяснение: ${text}/10, ${noun} не сдана`;
return null;
};
+const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
+
const sourceOf = (result: QuestionResult | undefined) =>
result?.withText
? withTextSource(result)
: result?.review
? `Оценка ИИ: ${result.review.score}/10`
: result?.build?.score !== undefined
- ? `Сборка: ${result.build.score}/10`
+ ? `${capitalize(buildNoun(result))}: ${result.build.score}/10`
: result?.revealed
? 'Подсмотрен эталон'
: result?.self
@@ -48,6 +54,15 @@ const BUILD_SCALE: Record = {
const BUILD_HOW_TO = ['Что нужно до цикла', 'Заголовок цикла или условия', 'Тело — с отступом вправо', 'Лишние блоки не брать'];
+/** Схема БД: за баллом — поля по таблицам и внешние ключи. */
+const SCHEMA_SCALE: Record = {
+ passed: 'Поля и ключи на местах, максимум одна ошибка',
+ partial: 'Таблицы разобраны, но ключи или пара полей мимо',
+ failed: 'Много ошибок, лишние поля или подсмотренный эталон',
+};
+
+const SCHEMA_HOW_TO = ['Каждый факт — в одной таблице', 'Ключ — на стороне «много»', 'Отметить, на что ссылается ключ', 'Лишние поля не брать'];
+
/** Сборка с текстом: уровень по среднему двух частей. */
const WITH_TEXT_SCALE: Record = {
passed: 'В среднем 8+: и сборка, и объяснение сильные',
@@ -56,6 +71,7 @@ const WITH_TEXT_SCALE: Record = {
};
const WITH_TEXT_HOW_TO = ['Собрать алгоритм из блоков', 'Сдать сборку', 'Объяснить словами, что спрошено', 'Итог — среднее двух баллов'];
+const SCHEMA_WITH_TEXT_HOW_TO = ['Разложить поля по таблицам', 'Сдать схему', 'Объяснить словами, что спрошено', 'Итог — среднее двух баллов'];
/**
* Шкала собеседования сбоку от вопроса: какие уровни можно получить и за что.
@@ -65,13 +81,18 @@ export const GradeScale = ({
result,
aiAvailable,
build = false,
+ kind = 'sequence',
}: {
result: QuestionResult | undefined;
aiAvailable: boolean;
/** Задание-конструктор: replace — только сборка, with_text — сборка и объяснение. */
build?: false | ConstructorMode;
+ /** Вид конструктора: алгоритм из шагов или схема БД. */
+ kind?: ConstructorKind;
}) => {
const withText = build === 'with_text';
+ const schema = kind === 'schema';
+ const howTo = withText ? (schema ? SCHEMA_WITH_TEXT_HOW_TO : WITH_TEXT_HOW_TO) : build ? (schema ? SCHEMA_HOW_TO : BUILD_HOW_TO) : HOW_TO;
const { c } = useTokens();
const color = useMasteryColor();
const current = result?.self ? SELF_TO_LEVEL[result.self] : null;
@@ -103,7 +124,7 @@ export const GradeScale = ({
{MASTERY_LABEL[level]}
{SCALE[level].range}
- {withText ? WITH_TEXT_SCALE[level] : build ? BUILD_SCALE[level] : SCALE[level].hint}
+ {withText ? WITH_TEXT_SCALE[level] : build ? (schema ? SCHEMA_SCALE : BUILD_SCALE)[level] : SCALE[level].hint}
);
@@ -112,9 +133,9 @@ export const GradeScale = ({
{source ??
(withText
- ? 'Сборку оценит эталон, объяснение — ИИ; итог — среднее.'
+ ? `${schema ? 'Схему' : 'Сборку'} оценит эталон, объяснение — ИИ; итог — среднее.`
: build
- ? 'Балл посчитается по эталону сразу после сдачи сборки.'
+ ? `Балл посчитается по эталону сразу после сдачи ${schema ? 'схемы' : 'сборки'}.`
: aiAvailable
? 'Оценку поставит ИИ, когда сдадите ответ.'
: 'ИИ недоступен — оцените ответ сами под полем ответа.')}
@@ -123,10 +144,10 @@ export const GradeScale = ({
- {build === 'replace' ? 'Как собирать' : 'Как отвечать'}
+ {build === 'replace' ? (schema ? 'Как раскладывать' : 'Как собирать') : 'Как отвечать'}
- {(withText ? WITH_TEXT_HOW_TO : build ? BUILD_HOW_TO : HOW_TO).map((step) => (
+ {howTo.map((step) => (
: { tone: 'fire', text: `${score}/10. Не расстраивайся: открой эталон и попробуй ещё раз своими словами.` };
/** Вопрос-конструктор: объявляем формат вместо обычной подсказки по сложности. */
-export const buildQuestionLine = (index: number, total: number, revisit: boolean, withText = false): Line => {
+export const buildQuestionLine = (index: number, total: number, revisit: boolean, withText = false, kind: ConstructorKind = 'sequence'): Line => {
const head = `Вопрос ${index + 1} из ${total}.`;
- if (revisit) return { tone: 'calm', text: `${head} Возвращаемся к сборке.` };
+ if (revisit) return { tone: 'calm', text: `${head} Возвращаемся к ${kind === 'schema' ? 'схеме' : 'сборке'}.` };
+ if (kind === 'schema') {
+ return {
+ tone: 'focus',
+ text: `${head} ${
+ withText
+ ? 'Две части: разложи поля по таблицам и отметь внешние ключи, потом объясни словами. Итог — среднее.'
+ : pickLine('schema:start', [
+ 'Тут схема БД: разложи поля по таблицам и отметь внешние ключи. Лишние поля не бери.',
+ 'Задание-схема. Каждый факт — в одной таблице, ключ — на стороне «много».',
+ ])
+ }`,
+ };
+ }
if (withText) {
return {
tone: 'focus',
@@ -83,9 +96,23 @@ export const BUILD_SILENCE_LINES = [
'Не всё в блоках нужно: пара шагов там для отвода глаз.',
];
+export const SCHEMA_SILENCE_LINES = [
+ 'Спроси себя про каждое поле: от чего оно зависит? Туда его и клади.',
+ 'Внешний ключ живёт на стороне «много»: у заказа есть клиент, а не наоборот.',
+ 'Не всё из списка нужно: пара полей нарушает нормальные формы.',
+];
+
/** Сборка проверена по эталону. */
-export const buildLine = (score: number): Line =>
- score >= 9
+export const buildLine = (score: number, kind: ConstructorKind = 'sequence'): Line =>
+ kind === 'schema'
+ ? score >= 9
+ ? { tone: 'cheer', text: `${score}/10! Схема как из учебника.` }
+ : score >= STRONG_SCORE
+ ? { tone: 'cheer', text: `${score}/10 — почти идеально. Посмотри, какое поле подвело.` }
+ : score >= 5
+ ? { tone: 'focus', text: `${score}/10. Таблицы угаданы, но поля или ключи хромают — смотри пометки.` }
+ : { tone: 'fire', text: `${score}/10. Открой эталон и пройди по зависимостям полей, потом соберём ещё раз.` }
+ : score >= 9
? { tone: 'cheer', text: `${score}/10! Алгоритм собран как по учебнику.` }
: score >= STRONG_SCORE
? { tone: 'cheer', text: `${score}/10 — почти идеально. Посмотри, какая строка подвела.` }
@@ -94,8 +121,8 @@ export const buildLine = (score: number): Line =>
: { tone: 'fire', text: `${score}/10. Открой эталон и пройди алгоритм по шагам, потом соберём ещё раз.` };
/** Обе части задания с текстом оценены: итог — среднее. */
-export const combinedLine = (score: number, build: number, text: number): Line => {
- const parts = `Сборка ${build}, объяснение ${text}`;
+export const combinedLine = (score: number, build: number, text: number, kind: ConstructorKind = 'sequence'): Line => {
+ const parts = `${kind === 'schema' ? 'Схема' : 'Сборка'} ${build}, объяснение ${text}`;
return score >= STRONG_SCORE
? { tone: 'cheer', text: `Итог ${score}/10. ${parts} — так и отвечают на собеседовании.` }
: score >= 5
diff --git a/frontend/src/components/interview/constructor/BuildPanel.test.tsx b/frontend/src/components/interview/constructor/BuildPanel.test.tsx
index a68f5cb..da55918 100644
--- a/frontend/src/components/interview/constructor/BuildPanel.test.tsx
+++ b/frontend/src/components/interview/constructor/BuildPanel.test.tsx
@@ -8,7 +8,7 @@ import type { AIReview, AIReviewStatus, ContentBlock } from '../../../types';
import { GradeScale } from '../GradeScale';
import type { QuestionResult } from '../session';
import { BuildPanel } from './BuildPanel';
-import type { SequenceTask } from './sequence';
+import type { ConstructorTask } from './task';
const setMastery = vi.fn();
const reviewMutate = vi.fn();
@@ -19,7 +19,8 @@ vi.mock('../../../queries/interview', () => ({
}));
const STEPS = ['Завести стек', 'Для каждого символа', 'Положить в стек'];
-const task: SequenceTask = {
+const task: ConstructorTask = {
+ kind: 'sequence',
prompt: 'Соберите алгоритм',
// куски вперемешку, плюс отвлекающий
pieces: [
@@ -30,7 +31,7 @@ const task: SequenceTask = {
],
mode: 'replace',
};
-const withTextTask: SequenceTask = { ...task, mode: 'with_text', textPrompt: 'Объясните сложность' };
+const withTextTask: ConstructorTask = { ...task, mode: 'with_text', textPrompt: 'Объясните сложность' };
const aiOn = { enabled: true, daily_limit: 30, used_today: 0 } as AIReviewStatus;
const aiOff = { enabled: false, daily_limit: 0, used_today: 0 } as AIReviewStatus;
const answer: ContentBlock[] = [
@@ -49,7 +50,7 @@ const answer: ContentBlock[] = [
];
let latest: QuestionResult | undefined;
-const Harness = ({ initial, t = task, ai }: { initial?: QuestionResult; t?: SequenceTask; ai?: AIReviewStatus }) => {
+const Harness = ({ initial, t = task, ai, blocks = answer }: { initial?: QuestionResult; t?: ConstructorTask; ai?: AIReviewStatus; blocks?: ContentBlock[] }) => {
const [result, setResult] = useState(initial);
return (
<>
@@ -63,21 +64,21 @@ const Harness = ({ initial, t = task, ai }: { initial?: QuestionResult; t?: Sequ
return latest;
})
}
- answerBlocks={answer}
+ answerBlocks={blocks}
answersLoading={false}
answersFailed={false}
ai={ai}
/>
-
+
>
);
};
-const renderPanel = (initial?: QuestionResult, t?: SequenceTask, ai?: AIReviewStatus) =>
+const renderPanel = (initial?: QuestionResult, t?: ConstructorTask, ai?: AIReviewStatus, blocks?: ContentBlock[]) =>
render(
-
+
,
);
@@ -234,3 +235,101 @@ describe('BuildPanel with_text', () => {
await waitFor(() => expect(screen.getByRole('button', { name: 'Сдать ответ' })).toBeDisabled());
});
});
+
+const schemaTask: ConstructorTask = {
+ kind: 'schema',
+ prompt: 'Разложите поля по таблицам',
+ tables: ['users', 'posts'],
+ pieces: [
+ { id: 'uid', text: 'user_id' },
+ { id: 'u1', text: 'id' },
+ { id: 'x', text: 'user_email' },
+ { id: 'e', text: 'email' },
+ { id: 'p1', text: 'id' },
+ ],
+ mode: 'replace',
+};
+const schemaAnswer: ContentBlock[] = [
+ { type: 'paragraph', data: { text: 'Суть' } },
+ {
+ type: 'constructor',
+ data: {
+ kind: 'schema',
+ schema: [
+ { name: 'users', fields: [{ name: 'id' }, { name: 'email' }] },
+ { name: 'posts', fields: [{ name: 'id' }, { name: 'user_id', ref: 'users' }] },
+ ],
+ },
+ },
+];
+
+/** Поле из списка — в таблицу через меню (как тап на телефоне). */
+const put = (text: string, table: string) => {
+ fireEvent.click(screen.getAllByRole('button', { name: `Поле ${text}: выбрать таблицу` })[0]);
+ fireEvent.click(screen.getByRole('menuitem', { name: table }));
+};
+const tableFields = (table: string) => within(screen.getByRole('group', { name: `Таблица ${table}` })).queryAllByRole('listitem');
+
+describe('BuildPanel schema', () => {
+ beforeEach(() => {
+ setMastery.mockReset();
+ latest = undefined;
+ });
+
+ it('lays out fields by tables, marks the foreign key and grades the schema without AI', () => {
+ renderPanel(undefined, schemaTask, undefined, schemaAnswer);
+ expect(screen.getByText('Балл посчитается по эталону сразу после сдачи схемы.')).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Как раскладывать' })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Сдать схему' })).toBeDisabled();
+
+ put('id', 'users');
+ put('email', 'users');
+ put('id', 'posts');
+ put('user_id', 'posts');
+ expect(tableFields('users')).toHaveLength(2);
+ expect(tableFields('posts')).toHaveLength(2);
+ expect(screen.getByText('Поле «user_id» — в таблице posts')).toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText('Внешний ключ поля user_id'), { target: { value: 'users' } });
+ expect(latest?.build?.fields).toContainEqual({ id: 'uid', table: 'posts', ref: 'users' });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Сдать схему' }));
+ expect(latest?.build?.score).toBe(10);
+ expect(latest?.self).toBe('knew');
+ expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'passed' });
+ expect(screen.getByText('Поля на месте 4 из 4 · ключи 1 из 1')).toBeInTheDocument();
+ expect(screen.getByText('Схема: 10/10')).toBeInTheDocument();
+ // после сдачи схема только для чтения
+ expect(screen.queryByLabelText('Внешний ключ поля user_id')).not.toBeInTheDocument();
+ });
+
+ it('marks a misplaced field, a distractor and a missing key', () => {
+ renderPanel(undefined, schemaTask, undefined, schemaAnswer);
+ put('id', 'users');
+ put('id', 'posts');
+ put('user_id', 'posts');
+ put('email', 'posts');
+ put('user_email', 'users');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Сдать схему' }));
+ // поля: 3 из 4 + ключи 0 из 1 → 6, минус 2 за лишнее поле
+ expect(latest?.build?.score).toBe(4);
+ expect(latest?.build?.missing).toEqual(['users.email']);
+ expect(setMastery).toHaveBeenCalledWith({ id: 'q1', level: 'failed' });
+ expect(screen.getByText('не в той таблице')).toBeInTheDocument();
+ expect(screen.getByText('лишнее поле')).toBeInTheDocument();
+ expect(screen.getByText('не отмечен внешний ключ')).toBeInTheDocument();
+ });
+
+ it('moves a field to another table and back to the pool with Delete', () => {
+ renderPanel(undefined, schemaTask, undefined, schemaAnswer);
+ put('email', 'posts');
+ fireEvent.click(screen.getByRole('button', { name: 'Перенести в другую таблицу' }));
+ fireEvent.click(screen.getByRole('menuitem', { name: 'users' }));
+ expect(latest?.build?.fields).toEqual([{ id: 'e', table: 'users' }]);
+
+ fireEvent.keyDown(screen.getByLabelText('email'), { key: 'Delete' });
+ expect(latest?.build?.fields).toEqual([]);
+ expect(screen.getByRole('button', { name: 'Поле email: выбрать таблицу' })).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/interview/constructor/BuildPanel.tsx b/frontend/src/components/interview/constructor/BuildPanel.tsx
index 4d923f7..b49f4ad 100644
--- a/frontend/src/components/interview/constructor/BuildPanel.tsx
+++ b/frontend/src/components/interview/constructor/BuildPanel.tsx
@@ -11,18 +11,21 @@ import { ConfirmDialog } from '../../ui/ConfirmDialog';
import { bitSay } from '../../ui/bitVoice';
import { levelFromScore } from '../../ui/masteryLevels';
import { radius, useTokens } from '../../../theme/tokens';
-import type { AIReviewStatus, ContentBlock } from '../../../types';
+import type { AIReviewStatus, ContentBlock, SchemaTableRef } from '../../../types';
import { AnswerPanel, ReferenceAnswer, RevealedAlert } from '../AnswerPanel';
import { buildLine, combinedLine, revealLine } from '../bitInterview';
import { ScoreBadge } from '../ScoreBadge';
import { scoreLabel } from '../score';
-import { LEVEL_TO_SELF, type QuestionResult, scoreOf, textScoreOf } from '../session';
+import { type BuildResult, LEVEL_TO_SELF, type QuestionResult, scoreOf, textScoreOf } from '../session';
+import { SchemaBuilder } from './SchemaBuilder';
import { SequenceBuilder } from './SequenceBuilder';
-import { findSequenceSolution, scoreSequence, type PlacedStep, type SequenceTask } from './sequence';
+import { findSchemaSolution, scoreSchema, type PlacedField } from './schema';
+import { findSequenceSolution, scoreSequence, type PlacedStep } from './sequence';
+import type { ConstructorTask } from './task';
interface BuildPanelProps {
questionId: string;
- task: SequenceTask;
+ task: ConstructorTask;
result: QuestionResult | undefined;
onChange: (patch: Partial) => void;
answerBlocks: ContentBlock[] | undefined;
@@ -48,7 +51,8 @@ const PartHeading = ({ n, title, children }: { n: number; title: string; childre
};
/**
- * Ответ-конструктор: кандидат собирает алгоритм из блоков, балл считается по эталону без ИИ.
+ * Ответ-конструктор: кандидат собирает алгоритм из блоков или схему БД из полей,
+ * балл считается по эталону без ИИ.
* Первая сдача фиксирует оценку; эталон до сдачи, как и в текстовом ответе, — «Не прошёл».
* В режиме with_text рядом со сборкой — текстовый ответ на ИИ-проверке, итог — среднее двух баллов.
*/
@@ -61,13 +65,16 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
const withText = task.mode === 'with_text';
const build = result?.build;
const order = build?.order ?? [];
+ const fields = build?.fields ?? [];
const submitted = build?.score !== undefined;
const revealed = Boolean(result?.revealed);
- const solution = findSequenceSolution(answerBlocks);
+ const sequenceSolution = task.kind === 'sequence' ? findSequenceSolution(answerBlocks) : null;
+ const schemaSolution = task.kind === 'schema' ? findSchemaSolution(answerBlocks) : null;
+ const solution = sequenceSolution ?? schemaSolution;
const final = withText ? scoreOf({ answer: '', ...result, withText: true }) : build?.score;
// с текстом эталон без штрафа — только когда оценены обе части: иначе он подскажет объяснение
const referenceFree = final !== undefined || revealed;
- const canSubmit = !submitted && !revealed && order.length > 0 && Boolean(solution);
+ const canSubmit = !submitted && !revealed && (task.kind === 'schema' ? fields.length : order.length) > 0 && Boolean(solution);
/** Правка результата; для with_text итоговый уровень пересчитывается, когда оценены обе части. */
const update = (patch: Partial) => {
@@ -84,7 +91,7 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
onChange({ withText: true, ...patch, self: LEVEL_TO_SELF[level] });
if (after !== before) {
setMastery.mutate({ id: questionId, level });
- const line = combinedLine(after, next.build!.score!, textScoreOf(next)!);
+ const line = combinedLine(after, next.build!.score!, textScoreOf(next)!, task.kind);
bitSay(line.text, line.tone);
}
} else if (before !== undefined) {
@@ -97,18 +104,33 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
};
const setOrder = (next: PlacedStep[]) => update({ build: { order: next } });
+ const setFields = (next: PlacedField[]) => update({ build: { order: [], fields: next } });
+
+ /** Сдача: балл по эталону; у схемы пометки полей, у алгоритма — строк. */
+ const grade = (): BuildResult | null => {
+ if (sequenceSolution) {
+ const { score, marks, missing } = scoreSequence(sequenceSolution, order);
+ return { order, score, marks, missing };
+ }
+ if (schemaSolution) {
+ const { score, marks, missing } = scoreSchema(schemaSolution, task.pieces, fields);
+ return { order: [], fields, score, fieldMarks: marks, missing };
+ }
+ return null;
+ };
const submit = () => {
- if (!solution) return;
- const { score, marks, missing } = scoreSequence(solution, order);
- const line = buildLine(score);
+ const graded = grade();
+ if (!graded) return;
+ const score = graded.score!;
+ const line = buildLine(score, task.kind);
bitSay(line.text, line.tone);
if (withText) {
- update({ build: { order, score, marks, missing } });
+ update({ build: graded });
return;
}
const level = levelFromScore(score);
- onChange({ build: { order, score, marks, missing }, self: LEVEL_TO_SELF[level] });
+ onChange({ build: graded, self: LEVEL_TO_SELF[level] });
setMastery.mutate({ id: questionId, level });
};
@@ -128,11 +150,8 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
update('self' in patch ? { ...rest, textSelf: self } : rest);
};
- const placedCount = build?.marks?.filter((m) => m === 'ok').length ?? 0;
- const extraCount = build?.marks?.filter((m) => m === 'extra').length ?? 0;
- const buildSummary = `На месте ${placedCount} из ${solution?.length ?? order.length}${extraCount ? ` · лишних блоков: ${extraCount}` : ''}${
- build?.missing?.length ? ` · пропущено: ${build.missing.length}` : ''
- }`;
+ const buildSummary = schemaSolution ? schemaSummary(build, schemaSolution) : sequenceSummary(build, sequenceSolution?.length ?? order.length);
+ const noun = task.kind === 'schema' ? 'схему' : 'сборку';
const textScore = textScoreOf(result);
const referenceButton = (
@@ -151,7 +170,7 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
return (
{withText ? (
-
+
{task.prompt}
) : (
@@ -160,14 +179,26 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
)}
-
+ {task.kind === 'schema' ? (
+
+ ) : (
+
+ )}
{!submitted && (
@@ -178,7 +209,7 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
startIcon={}
sx={{ bgcolor: c.accent, color: c.onAccent, '&:hover': { bgcolor: c.accentHover } }}
>
- Сдать сборку
+ Сдать {noun}
)}
{!withText && referenceButton}
@@ -188,7 +219,7 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
)}
{withText && submitted && build?.score !== undefined && (
-
+
{buildSummary}
@@ -199,7 +230,7 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
{!solution && !answersLoading && (
- {answersFailed ? 'Не удалось загрузить эталон для проверки. Обновите страницу.' : 'У задания нет эталона — сдать сборку нельзя.'}
+ {answersFailed ? 'Не удалось загрузить эталон для проверки. Обновите страницу.' : `У задания нет эталона — сдать ${noun} нельзя.`}
)}
@@ -263,7 +294,7 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
Итог: {scoreLabel(final).toLowerCase()}
- Сборка {build?.score}/10 · объяснение {textScore}/10
+ {task.kind === 'schema' ? 'Схема' : 'Сборка'} {build?.score}/10 · объяснение {textScore}/10
{result?.review ? '' : ' (своя оценка)'} · итог — среднее с округлением вниз
@@ -278,8 +309,8 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
title="Подсмотреть эталон?"
description={
withText
- ? 'Вопрос сразу засчитается как «Не прошёл»: сдать сборку и проверить объяснение будет нельзя. На настоящем собеседовании подсказки не будет.'
- : 'Вопрос сразу засчитается как «Не прошёл», а сдать сборку будет нельзя. На настоящем собеседовании подсказки не будет.'
+ ? `Вопрос сразу засчитается как «Не прошёл»: сдать ${noun} и проверить объяснение будет нельзя. На настоящем собеседовании подсказки не будет.`
+ : `Вопрос сразу засчитается как «Не прошёл», а сдать ${noun} будет нельзя. На настоящем собеседовании подсказки не будет.`
}
confirmText="Подсмотреть"
cancelText="Ещё подумаю"
@@ -290,3 +321,20 @@ export const BuildPanel = ({ questionId, task, result, onChange, answerBlocks, a
);
};
+
+const sequenceSummary = (build: BuildResult | undefined, total: number) => {
+ const placed = build?.marks?.filter((m) => m === 'ok').length ?? 0;
+ const extra = build?.marks?.filter((m) => m === 'extra').length ?? 0;
+ return `На месте ${placed} из ${total}${extra ? ` · лишних блоков: ${extra}` : ''}${build?.missing?.length ? ` · пропущено: ${build.missing.length}` : ''}`;
+};
+
+const schemaSummary = (build: BuildResult | undefined, schema: SchemaTableRef[]) => {
+ const marks = build?.fieldMarks ?? [];
+ const fields = schema.reduce((n, t) => n + t.fields.length, 0);
+ const refs = schema.reduce((n, t) => n + t.fields.filter((f) => f.ref).length, 0);
+ const placed = marks.filter((m) => m.place === 'ok').length;
+ const linked = marks.filter((m) => m.ref === 'ok').length;
+ const extra = marks.filter((m) => m.place === 'extra').length;
+ const wrong = marks.filter((m) => m.ref === 'wrong').length;
+ return `Поля на месте ${placed} из ${fields} · ключи ${linked} из ${refs}${extra ? ` · лишних полей: ${extra}` : ''}${wrong ? ` · неверных ссылок: ${wrong}` : ''}`;
+};
diff --git a/frontend/src/components/interview/constructor/SchemaBuilder.tsx b/frontend/src/components/interview/constructor/SchemaBuilder.tsx
new file mode 100644
index 0000000..1ffa84d
--- /dev/null
+++ b/frontend/src/components/interview/constructor/SchemaBuilder.tsx
@@ -0,0 +1,429 @@
+import { type KeyboardEvent, type ReactNode, useEffect, useMemo, useRef, useState } from 'react';
+import { Box, IconButton, ListSubheader, Menu, MenuItem, Tooltip, Typography } from '@mui/material';
+import {
+ AddRounded as AddIcon,
+ CheckCircleOutlineRounded as OkIcon,
+ CloseRounded as RemoveIcon,
+ DragIndicatorRounded as DragIcon,
+ HighlightOffRounded as ExtraIcon,
+ SwapHorizRounded as MoveIcon,
+ TableChartOutlined as TableIcon,
+ WarningAmberRounded as WarnIcon,
+} from '@mui/icons-material';
+import {
+ type Announcements,
+ DndContext,
+ type DragEndEvent,
+ DragOverlay,
+ type DragStartEvent,
+ MouseSensor,
+ TouchSensor,
+ pointerWithin,
+ rectIntersection,
+ type CollisionDetection,
+ useDraggable,
+ useDroppable,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import { fonts, radius, useTokens } from '../../../theme/tokens';
+import type { ConstructorPiece } from '../../../types';
+import { type FieldMark, type FieldPlace, type PlacedField, type RefMark, placeField, setFieldRef, unplaceField } from './schema';
+
+const POOL_ZONE = 'zone:pool';
+const tid = (name: string) => `t:${name}`;
+const pid = (id: string) => `p:${id}`;
+const fid = (id: string) => `f:${id}`;
+const pieceOf = (dndId: string | number) => String(dndId).slice(2);
+
+const PLACE_LABEL: Record = { ok: 'на месте', table: 'не в той таблице', extra: 'лишнее поле' };
+const REF_LABEL: Record = { ok: 'ссылка верна', wrong: 'ссылка не та', missing: 'не отмечен внешний ключ' };
+
+/** Сначала то, что под указателем, иначе — что пересекается: карточки таблиц разного размера. */
+const collision: CollisionDetection = (args) => {
+ const hits = pointerWithin(args);
+ return hits.length ? hits : rectIntersection(args);
+};
+
+interface SchemaBuilderProps {
+ tables: string[];
+ pieces: ConstructorPiece[];
+ placed: PlacedField[];
+ onChange: (placed: PlacedField[]) => void;
+ /** Пометки после сдачи: схема становится только для чтения. */
+ marks?: FieldMark[];
+ missing?: string[];
+ disabled?: boolean;
+}
+
+/**
+ * Сборка схемы БД: поля раскладываются по заданным таблицам (перетаскиванием или через меню),
+ * у внешнего ключа выбирается таблица, на которую он ссылается. Delete на поле убирает его из схемы.
+ */
+export const SchemaBuilder = ({ tables, pieces, placed, onChange, marks, missing, disabled }: SchemaBuilderProps) => {
+ const { c } = useTokens();
+ const locked = Boolean(marks) || Boolean(disabled);
+ const byId = useMemo(() => new Map(pieces.map((p) => [p.id, p])), [pieces]);
+ const placedIds = new Set(placed.map((p) => p.id));
+ const pool = pieces.filter((p) => !placedIds.has(p.id));
+ const [status, setStatus] = useState('');
+ const [dragging, setDragging] = useState(null);
+ const [menu, setMenu] = useState<{ anchor: HTMLElement; id: string } | null>(null);
+ const [focusId, setFocusId] = useState(null);
+
+ const textOf = (id: string) => byId.get(id)?.text ?? '';
+ const quote = (id: string) => `«${textOf(id)}»`;
+
+ const sensors = useSensors(
+ useSensor(MouseSensor, { activationConstraint: { distance: 6 } }),
+ useSensor(TouchSensor, { activationConstraint: { delay: 150, tolerance: 6 } }),
+ );
+
+ const commit = (next: PlacedField[], message: string, focus?: string) => {
+ onChange(next);
+ setStatus(message);
+ if (focus) setFocusId(focus);
+ };
+ const put = (id: string, table: string) => {
+ const next = placeField(placed, id, table);
+ if (next !== placed) commit(next, `Поле ${quote(id)} — в таблице ${table}`, id);
+ };
+ const remove = (id: string) => commit(unplaceField(placed, id), `Поле ${quote(id)} убрано из схемы`);
+ const link = (id: string, ref: string | undefined) =>
+ commit(setFieldRef(placed, id, ref), ref ? `Поле ${quote(id)} ссылается на ${ref}` : `Поле ${quote(id)} — не внешний ключ`);
+
+ const onDragStart = (e: DragStartEvent) => setDragging(String(e.active.id));
+ const onDragEnd = ({ active, over }: DragEndEvent) => {
+ setDragging(null);
+ if (!over) return;
+ const id = pieceOf(active.id);
+ const overId = String(over.id);
+ if (overId.startsWith('t:')) put(id, overId.slice(2));
+ else if (overId === POOL_ZONE && String(active.id).startsWith('f:')) remove(id);
+ };
+
+ const announcements: Announcements = {
+ onDragStart: ({ active }) => `Взято поле ${quote(pieceOf(active.id))}`,
+ onDragOver: ({ over }) => (over ? (String(over.id).startsWith('t:') ? `Над таблицей ${pieceOf(over.id)}` : 'Над списком полей') : 'Вне таблиц'),
+ onDragEnd: ({ active, over }) => (over ? `Поле ${quote(pieceOf(active.id))} отпущено` : 'Перетаскивание отменено'),
+ onDragCancel: () => 'Перетаскивание отменено',
+ };
+
+ const menuField = menu ? placed.find((p) => p.id === menu.id) : undefined;
+
+ return (
+ setDragging(null)}
+ accessibility={{
+ announcements,
+ screenReaderInstructions: {
+ draggable: 'Нажмите на поле, чтобы выбрать таблицу. В таблице: список «ссылка» отмечает внешний ключ, Delete убирает поле из схемы.',
+ },
+ }}
+ >
+ {!locked && setMenu({ anchor, id })} />}
+
+
+ {tables.map((table) => {
+ const rows = placed.map((p, i) => ({ p, mark: marks?.[i] })).filter(({ p }) => p.table === table);
+ return (
+
+ {rows.map(({ p, mark }) => (
+ setFocusId(null)}
+ onRef={(ref) => link(p.id, ref)}
+ onMove={(anchor) => setMenu({ anchor, id: p.id })}
+ onRemove={() => remove(p.id)}
+ />
+ ))}
+
+ );
+ })}
+
+
+ {marks && missing && missing.length > 0 && (
+
+ Не на своём месте полей эталона: {missing.length}. Какие — видно в эталоне.
+
+ )}
+
+
+
+
+ {status}
+
+
+
+ {dragging ? (
+
+ {textOf(pieceOf(dragging))}
+
+ ) : null}
+
+
+ );
+};
+
+const Pool = ({ pieces, dragging, onPick }: { pieces: ConstructorPiece[]; dragging: string | null; onPick: (anchor: HTMLElement, id: string) => void }) => {
+ const { c } = useTokens();
+ const { setNodeRef, isOver } = useDroppable({ id: POOL_ZONE });
+ return (
+
+
+ Поля · {pieces.length}
+
+
+ {pieces.map((p) => (
+ onPick(anchor, p.id)} />
+ ))}
+
+ {pieces.length === 0 && (
+
+ Все поля разложены. Лишнее можно перетащить обратно.
+
+ )}
+
+ );
+};
+
+const PoolChip = ({ piece, onPick }: { piece: ConstructorPiece; onPick: (anchor: HTMLElement) => void }) => {
+ const { c } = useTokens();
+ const { setNodeRef, listeners, attributes, isDragging } = useDraggable({ id: pid(piece.id) });
+ // с клавиатуры поле кладётся через меню таблиц (Enter/пробел), без перетаскивания
+ const pointerListeners = Object.fromEntries(Object.entries(listeners ?? {}).filter(([name]) => name !== 'onKeyDown'));
+ return (
+
+ onPick(e.currentTarget)}
+ sx={{
+ all: 'unset', boxSizing: 'border-box', display: 'inline-flex', alignItems: 'center', gap: 0.5,
+ pl: 0.75, pr: 1.25, minHeight: 36, borderRadius: `${radius.md}px`, border: `1px solid ${c.border}`, bgcolor: c.surface,
+ fontFamily: fonts.mono, fontSize: '.8125rem', color: c.text, cursor: 'grab', touchAction: 'manipulation',
+ transition: 'border-color .15s, background-color .15s',
+ '&:hover': { borderColor: c.accentBorder, bgcolor: c.surfaceHover },
+ '&:focus-visible': { outline: `2px solid ${c.accent}`, outlineOffset: 2 },
+ }}
+ >
+
+ {piece.text}
+
+
+ );
+};
+
+const TableCard = ({ name, count, locked, dragging, children }: { name: string; count: number; locked: boolean; dragging: string | null; children: ReactNode }) => {
+ const { c } = useTokens();
+ const { setNodeRef, isOver } = useDroppable({ id: tid(name), disabled: locked });
+ return (
+
+
+
+
+ {name}
+
+
+ {count}
+
+
+
+ {children}
+ {count === 0 && !locked && (
+
+ Перетащите сюда поля
+
+ )}
+
+
+ );
+};
+
+interface FieldRowProps {
+ field: PlacedField;
+ text: string;
+ tables: string[];
+ mark?: FieldMark;
+ locked: boolean;
+ autoFocus: boolean;
+ onFocused: () => void;
+ onRef: (ref: string | undefined) => void;
+ onMove: (anchor: HTMLElement) => void;
+ onRemove: () => void;
+}
+
+const FieldRow = ({ field, text, tables, mark, locked, autoFocus, onFocused, onRef, onMove, onRemove }: FieldRowProps) => {
+ const { c } = useTokens();
+ const rowRef = useRef(null);
+ // после переноса из меню фокус переходит на поле в новой таблице
+ useEffect(() => {
+ if (!autoFocus) return;
+ const el = rowRef.current;
+ if (el && !el.contains(document.activeElement)) el.focus();
+ onFocused();
+ }, [autoFocus, onFocused]);
+ const { setNodeRef, setActivatorNodeRef, listeners, attributes, isDragging } = useDraggable({ id: fid(field.id), disabled: locked });
+
+ const placeColor = mark ? { ok: c.success, table: c.warning, extra: c.danger }[mark.place] : null;
+ const placeBg = mark ? { ok: c.successSoft, table: c.warningSoft, extra: c.dangerSoft }[mark.place] : null;
+ const refColor = mark?.ref ? { ok: c.success, wrong: c.danger, missing: c.warning }[mark.ref] : c.textMuted;
+ const issue = mark && mark.place === 'ok' && mark.ref && mark.ref !== 'ok' ? mark.ref : null;
+ const color = issue ? (issue === 'wrong' ? c.danger : c.warning) : placeColor;
+ const MarkIcon = mark ? (mark.place === 'ok' && !issue ? OkIcon : mark.place === 'extra' || issue === 'wrong' ? ExtraIcon : WarnIcon) : null;
+ const notes = mark ? [mark.place !== 'ok' && PLACE_LABEL[mark.place], mark.ref && mark.ref !== 'ok' && REF_LABEL[mark.ref]].filter(Boolean) : [];
+ const label = `${text}${field.ref ? `, ссылается на ${field.ref}` : ''}${mark ? `, ${[PLACE_LABEL[mark.place], mark.ref && REF_LABEL[mark.ref]].filter(Boolean).join(', ')}` : ''}`;
+
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (locked || e.target !== e.currentTarget) return;
+ if (e.key === 'Delete' || e.key === 'Backspace') {
+ e.preventDefault();
+ onRemove();
+ }
+ };
+
+ return (
+
+
+ {locked ? (
+ MarkIcon &&
+ ) : (
+
+
+
+ )}
+
+
+ {text}
+ {locked && field.ref && (
+
+ → {field.ref}
+
+ )}
+
+ {notes.length > 0 && (
+
+ {notes.join(' · ')}
+
+ )}
+
+ {!locked && (
+
+ onRef(e.target.value || undefined)}
+ aria-label={`Внешний ключ поля ${text}`}
+ sx={{
+ flexShrink: 0, maxWidth: { xs: 112, sm: 128 }, height: 30, px: 0.75, borderRadius: `${radius.sm}px`,
+ border: `1px solid ${field.ref ? c.accentBorder : c.border}`, bgcolor: field.ref ? c.accentSoft : c.surface,
+ color: field.ref ? c.accent : c.textMuted, fontFamily: fonts.mono, fontSize: '.75rem', cursor: 'pointer',
+ '&:focus-visible': { outline: `2px solid ${c.accent}`, outlineOffset: 1 },
+ }}
+ >
+
+ {tables.map((t) => (
+
+ ))}
+
+ onMove(e.currentTarget)} icon={} />
+ } />
+
+ )}
+
+
+ );
+};
+
+const FieldAction = ({ title, onClick, icon }: { title: string; onClick: (e: React.MouseEvent) => void; icon: ReactNode }) => (
+
+
+ {icon}
+
+
+);
diff --git a/frontend/src/components/interview/constructor/schema.test.ts b/frontend/src/components/interview/constructor/schema.test.ts
new file mode 100644
index 0000000..0a69b81
--- /dev/null
+++ b/frontend/src/components/interview/constructor/schema.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from 'vitest';
+import type { ContentBlock, ConstructorPiece, SchemaTableRef } from '../../../types';
+import { findSchemaSolution, findSchemaTask, placeField, scoreSchema, setFieldRef, unplaceField, type PlacedField } from './schema';
+import { findConstructorTask } from './task';
+
+/** customers(id, city) · orders(id, customer_id → customers): 4 поля и 1 ключ, всего 5 баллов-единиц. */
+const schema: SchemaTableRef[] = [
+ { name: 'customers', fields: [{ name: 'id' }, { name: 'city' }] },
+ { name: 'orders', fields: [{ name: 'id' }, { name: 'customer_id', ref: 'customers' }] },
+];
+const pieces: ConstructorPiece[] = [
+ { id: 'c1', text: 'id' },
+ { id: 'o1', text: 'id' },
+ { id: 'ct', text: 'city' },
+ { id: 'fk', text: 'customer_id' },
+ { id: 'x', text: 'customer_city' },
+];
+const exact: PlacedField[] = [
+ { id: 'c1', table: 'customers' },
+ { id: 'ct', table: 'customers' },
+ { id: 'o1', table: 'orders' },
+ { id: 'fk', table: 'orders', ref: 'customers' },
+];
+
+describe('scoreSchema', () => {
+ it('gives 10 for the reference schema, same-named pieces are interchangeable', () => {
+ const r = scoreSchema(schema, pieces, exact);
+ expect(r.score).toBe(10);
+ expect(r.marks.map((m) => m.place)).toEqual(['ok', 'ok', 'ok', 'ok']);
+ expect(r.marks[3].ref).toBe('ok');
+ // id из customers в orders и наоборот — то же самое
+ const swapped = exact.map((f) => (f.id === 'c1' ? { ...f, table: 'orders' } : f.id === 'o1' ? { ...f, table: 'customers' } : f));
+ expect(scoreSchema(schema, pieces, swapped).score).toBe(10);
+ });
+
+ it('a missing foreign key costs its share, a wrong one also a point', () => {
+ const noRef = setFieldRef(exact, 'fk', undefined);
+ const r = scoreSchema(schema, pieces, noRef);
+ expect(r.score).toBe(8); // 4 из 5
+ expect(r.marks[3]).toEqual({ place: 'ok', ref: 'missing' });
+
+ const wrongTarget = setFieldRef(exact, 'fk', 'orders');
+ expect(scoreSchema(schema, pieces, wrongTarget).score).toBe(7); // 4 из 5 и минус 1
+ const extraRef = setFieldRef(exact, 'ct', 'orders');
+ expect(scoreSchema(schema, pieces, extraRef).marks[1]).toEqual({ place: 'ok', ref: 'wrong' });
+ expect(scoreSchema(schema, pieces, extraRef).score).toBe(9);
+ });
+
+ it('a field in the wrong table is not counted, a distractor costs two points', () => {
+ const misplaced = placeField(exact, 'ct', 'orders');
+ const r = scoreSchema(schema, pieces, misplaced);
+ expect(r.score).toBe(8); // 4 из 5
+ expect(r.missing).toEqual(['customers.city']);
+ expect(r.marks.find((_, i) => misplaced[i].id === 'ct')?.place).toBe('table');
+
+ const withExtra = placeField(exact, 'x', 'orders');
+ const e = scoreSchema(schema, pieces, withExtra);
+ expect(e.score).toBe(8);
+ expect(e.marks[4]).toEqual({ place: 'extra' });
+ });
+
+ it('two same-named fields in one table count once; empty attempt scores zero', () => {
+ const doubled = placeField(exact, 'o1', 'customers');
+ const r = scoreSchema(schema, pieces, doubled);
+ expect(r.marks.filter((m) => m.place === 'table')).toHaveLength(1);
+ expect(r.missing).toEqual(['orders.id']);
+ expect(scoreSchema(schema, pieces, []).score).toBe(0);
+ expect(scoreSchema(schema, pieces, [{ id: 'x', table: 'orders' }]).score).toBe(0);
+ });
+});
+
+describe('editing helpers', () => {
+ it('moves a field between tables and drops its key only when the table changes', () => {
+ expect(placeField(exact, 'fk', 'orders')).toBe(exact);
+ expect(placeField(exact, 'fk', 'customers').at(-1)).toEqual({ id: 'fk', table: 'customers' });
+ expect(unplaceField(exact, 'fk')).toHaveLength(3);
+ expect(setFieldRef(exact, 'fk', undefined)[3]).toEqual({ id: 'fk', table: 'orders' });
+ });
+});
+
+describe('content blocks', () => {
+ const question: ContentBlock[] = [
+ { type: 'paragraph', data: { text: 'Условие' } },
+ { type: 'constructor', data: { kind: 'schema', mode: 'with_text', text_prompt: 'Объясните', prompt: 'Разложите', tables: ['customers', 'orders'], pieces } },
+ ];
+
+ it('finds the schema task and the reference schema', () => {
+ expect(findSchemaTask(question)).toEqual({ prompt: 'Разложите', tables: ['customers', 'orders'], pieces, mode: 'with_text', textPrompt: 'Объясните' });
+ expect(findConstructorTask(question)?.kind).toBe('schema');
+ expect(findSchemaTask([{ type: 'constructor', data: { kind: 'schema', pieces } }])).toBeNull();
+ expect(findSchemaSolution([{ type: 'constructor', data: { kind: 'schema', schema } }])).toBe(schema);
+ expect(findSchemaSolution(question)).toBeNull();
+ });
+});
diff --git a/frontend/src/components/interview/constructor/schema.ts b/frontend/src/components/interview/constructor/schema.ts
new file mode 100644
index 0000000..57b087e
--- /dev/null
+++ b/frontend/src/components/interview/constructor/schema.ts
@@ -0,0 +1,129 @@
+import type { ContentBlock, ConstructorMode, ConstructorPiece, SchemaTableRef } from '../../../types';
+
+/** Задание-конструктор вида «схема БД»: таблицы заданы, поля и внешние ключи раскладывает кандидат. */
+export interface SchemaTask {
+ prompt: string;
+ tables: string[];
+ pieces: ConstructorPiece[];
+ mode: ConstructorMode;
+ /** with_text: что объяснить словами рядом со сборкой. */
+ textPrompt?: string;
+}
+
+/** Поле в собранной схеме: какой кусок, в какой таблице и на какую таблицу ссылается. */
+export interface PlacedField {
+ id: string;
+ table: string;
+ ref?: string;
+}
+
+/** Пометка поля после сдачи: в своей таблице / не в той таблице / лишнее поле. */
+export type FieldPlace = 'ok' | 'table' | 'extra';
+/** Пометка ссылки у поля на своём месте: верная / не та или лишняя / не отмечена. */
+export type RefMark = 'ok' | 'wrong' | 'missing';
+
+export interface FieldMark {
+ place: FieldPlace;
+ ref?: RefMark;
+}
+
+export interface SchemaScore {
+ /** 0..10, как у оценки ИИ: 8–10 «Прошёл», 5–7 «Частично», 0–4 «Не прошёл». */
+ score: number;
+ /** Пометки в порядке `placed`. */
+ marks: FieldMark[];
+ /** Поля эталона, которых нет в своей таблице, вида `orders.customer_id`. */
+ missing: string[];
+ fields: { ok: number; total: number };
+ refs: { ok: number; total: number };
+}
+
+const schemaBlock = (b: ContentBlock | undefined) => b?.type === 'constructor' && b.data?.kind === 'schema';
+
+/** Задание «схема БД» в блоках вопроса, если оно есть. */
+export const findSchemaTask = (blocks: ContentBlock[] | undefined): SchemaTask | null => {
+ const block = blocks?.find((b) => schemaBlock(b) && Boolean(b.data?.pieces?.length) && Boolean(b.data?.tables?.length));
+ if (!block) return null;
+ const textPrompt = block.data?.text_prompt?.trim();
+ return {
+ prompt: block.data?.prompt ?? 'Разложите поля по таблицам',
+ tables: block.data!.tables!,
+ pieces: block.data!.pieces!,
+ // with_text без формулировки текстовой части превращается в обычную сборку
+ mode: block.data?.mode === 'with_text' && textPrompt ? 'with_text' : 'replace',
+ ...(textPrompt ? { textPrompt } : {}),
+ };
+};
+
+/** Эталонная схема в блоках ответа. */
+export const findSchemaSolution = (blocks: ContentBlock[] | undefined): SchemaTableRef[] | null => {
+ const block = blocks?.find((b) => schemaBlock(b) && Boolean(b.data?.schema?.length));
+ return block ? block.data!.schema! : null;
+};
+
+/**
+ * Балл схемы: 10 × (поля в своей таблице + верные ссылки) / (поля эталона + ссылки эталона),
+ * с округлением вниз; минус 2 за каждое лишнее поле и минус 1 за ссылку, которой нет в эталоне.
+ * Поля сравниваются по имени: одноимённые куски (id разных таблиц) взаимозаменяемы.
+ */
+export const scoreSchema = (schema: SchemaTableRef[], pieces: ConstructorPiece[], placed: PlacedField[]): SchemaScore => {
+ const textOf = new Map(pieces.map((p) => [p.id, p.text]));
+ const expected = new Map(schema.map((t) => [t.name, new Map(t.fields.map((f) => [f.name, f.ref]))]));
+ const known = new Set(schema.flatMap((t) => t.fields.map((f) => f.name)));
+ const filled = new Set();
+
+ let fieldsOk = 0;
+ let refsOk = 0;
+ let extra = 0;
+ let wrongRefs = 0;
+ const marks = placed.map((p): FieldMark => {
+ const name = textOf.get(p.id) ?? '';
+ if (!known.has(name)) {
+ extra++;
+ return { place: 'extra' };
+ }
+ const table = expected.get(p.table);
+ const key = `${p.table}.${name}`;
+ // второе одноимённое поле в той же таблице на место не встаёт
+ if (!table?.has(name) || filled.has(key)) return { place: 'table' };
+ filled.add(key);
+ fieldsOk++;
+ const want = table.get(name);
+ if (p.ref && p.ref !== want) {
+ wrongRefs++;
+ return { place: 'ok', ref: 'wrong' };
+ }
+ if (!want) return { place: 'ok' };
+ if (p.ref) {
+ refsOk++;
+ return { place: 'ok', ref: 'ok' };
+ }
+ return { place: 'ok', ref: 'missing' };
+ });
+
+ const all = schema.flatMap((t) => t.fields.map((f) => ({ key: `${t.name}.${f.name}`, ref: f.ref })));
+ const totalRefs = all.filter((f) => f.ref).length;
+ const total = all.length + totalRefs;
+ const base = total ? Math.floor((10 * (fieldsOk + refsOk)) / total) : 0;
+ return {
+ score: Math.max(0, Math.min(10, base - 2 * extra - wrongRefs)),
+ marks,
+ missing: all.filter((f) => !filled.has(f.key)).map((f) => f.key),
+ fields: { ok: fieldsOk, total: all.length },
+ refs: { ok: refsOk, total: totalRefs },
+ };
+};
+
+/** Положить поле в таблицу (или перенести): ссылка сохраняется, только если таблица та же. */
+export const placeField = (placed: PlacedField[], id: string, table: string): PlacedField[] => {
+ const current = placed.find((p) => p.id === id);
+ if (current?.table === table) return placed;
+ return [...placed.filter((p) => p.id !== id), { id, table }];
+};
+
+/** Убрать поле из схемы обратно к остальным. */
+export const unplaceField = (placed: PlacedField[], id: string): PlacedField[] => placed.filter((p) => p.id !== id);
+
+/** Отметить, на какую таблицу ссылается поле (undefined — не внешний ключ). */
+export const setFieldRef = (placed: PlacedField[], id: string, ref: string | undefined): PlacedField[] =>
+ placed.map((p) => (p.id !== id ? p : ref ? { ...p, ref } : { id: p.id, table: p.table }));
diff --git a/frontend/src/components/interview/constructor/task.ts b/frontend/src/components/interview/constructor/task.ts
new file mode 100644
index 0000000..b7135b5
--- /dev/null
+++ b/frontend/src/components/interview/constructor/task.ts
@@ -0,0 +1,13 @@
+import type { ContentBlock } from '../../../types';
+import { findSchemaTask, type SchemaTask } from './schema';
+import { findSequenceTask, type SequenceTask } from './sequence';
+
+/** Задание-конструктор любого вида: алгоритм из шагов или схема БД. */
+export type ConstructorTask = ({ kind: 'sequence' } & SequenceTask) | ({ kind: 'schema' } & SchemaTask);
+
+export const findConstructorTask = (blocks: ContentBlock[] | undefined): ConstructorTask | null => {
+ const sequence = findSequenceTask(blocks);
+ if (sequence) return { kind: 'sequence', ...sequence };
+ const schema = findSchemaTask(blocks);
+ return schema ? { kind: 'schema', ...schema } : null;
+};
diff --git a/frontend/src/components/interview/session.ts b/frontend/src/components/interview/session.ts
index 2237bbd..85da38e 100644
--- a/frontend/src/components/interview/session.ts
+++ b/frontend/src/components/interview/session.ts
@@ -1,4 +1,5 @@
import type { AIReview, MasteryLevel, Question } from '../../types';
+import type { FieldMark, PlacedField } from './constructor/schema';
import type { PlacedStep, StepMark } from './constructor/sequence';
/** Уровень по вопросу: ставит ИИ, сам кандидат — только если ИИ недоступен. */
@@ -25,10 +26,14 @@ export interface QuestionResult {
}
export interface BuildResult {
+ /** Алгоритм из шагов: собранный порядок (у схемы пустой). */
order: PlacedStep[];
+ /** Схема БД: поля по таблицам с внешними ключами. */
+ fields?: PlacedField[];
/** Балл 0..10 фиксируется первой сдачей: перебором порядок не подобрать. */
score?: number;
marks?: StepMark[];
+ fieldMarks?: FieldMark[];
missing?: string[];
}
@@ -54,7 +59,7 @@ export const scoreOf = (result: QuestionResult | undefined): number | undefined
/** На вопрос ответили: есть текст, оценка или начатая сборка. */
export const isAnswered = (result: QuestionResult | undefined) =>
- Boolean(result?.answer?.trim() || result?.self || result?.build?.order.length);
+ Boolean(result?.answer?.trim() || result?.self || result?.build?.order.length || result?.build?.fields?.length);
export interface InterviewOptions {
/** 0 — все подходящие вопросы. */
diff --git a/frontend/src/pages/InterviewModePage.tsx b/frontend/src/pages/InterviewModePage.tsx
index 8954668..a6cf74f 100644
--- a/frontend/src/pages/InterviewModePage.tsx
+++ b/frontend/src/pages/InterviewModePage.tsx
@@ -13,6 +13,7 @@ import { BitHost } from '../components/ui/BitHost';
import { bitSay, pickLine } from '../components/ui/bitVoice';
import {
BUILD_SILENCE_LINES,
+ SCHEMA_SILENCE_LINES,
buildQuestionLine,
INTERVIEW_ROLE,
markedLine,
@@ -25,7 +26,8 @@ import {
import { ContentRenderer } from '../components/ContentRenderer';
import { AnswerPanel } from '../components/interview/AnswerPanel';
import { BuildPanel } from '../components/interview/constructor/BuildPanel';
-import { findSequenceTask, withoutConstructor } from '../components/interview/constructor/sequence';
+import { withoutConstructor } from '../components/interview/constructor/sequence';
+import { findConstructorTask } from '../components/interview/constructor/task';
import { InterviewResults } from '../components/interview/InterviewResults';
import { InterviewSetup } from '../components/interview/InterviewSetup';
import { GradeScale } from '../components/interview/GradeScale';
@@ -98,14 +100,14 @@ const QuestionView = ({ question, result, onChange }: QuestionViewProps) => {
const card = useInterviewCard(question.id);
const ai = useAIReviewStatus();
const hasAnswer = isAnswered(result);
- const task = useMemo(() => findSequenceTask(question.content), [question.content]);
+ const task = useMemo(() => findConstructorTask(question.content), [question.content]);
const blocks = useMemo(() => withoutConstructor(question.content ?? []), [question.content]);
// Молчание на вопросе: Бит один раз мягко подталкивает начать
useEffect(() => {
if (hasAnswer) return;
const timer = window.setTimeout(
- () => (task ? bitSay(pickLine('silence:build', BUILD_SILENCE_LINES), 'focus', { move: 'nod' }) : bitSay(pickLine('silence', SILENCE_LINES), 'focus', { move: 'nod' })),
+ () => (task ? bitSay(task.kind === 'schema' ? pickLine('silence:schema', SCHEMA_SILENCE_LINES) : pickLine('silence:build', BUILD_SILENCE_LINES), 'focus', { move: 'nod' }) : bitSay(pickLine('silence', SILENCE_LINES), 'focus', { move: 'nod' })),
SILENCE_MS,
);
return () => window.clearTimeout(timer);
@@ -118,7 +120,7 @@ const QuestionView = ({ question, result, onChange }: QuestionViewProps) => {
{question.category?.name && }
{task && }
{result?.review && }
- {result?.build?.score !== undefined && }
+ {result?.build?.score !== undefined && }
@@ -255,9 +257,9 @@ export const InterviewFlow = ({
useEffect(() => {
if (!currentQuestion) return;
const revisit = isAnswered(session?.results[currentQuestion.id]);
- const task = findSequenceTask(currentQuestion.content);
+ const task = findConstructorTask(currentQuestion.content);
const line = task
- ? buildQuestionLine(currentIndex, plan.length, revisit, task.mode === 'with_text')
+ ? buildQuestionLine(currentIndex, plan.length, revisit, task.mode === 'with_text', task.kind)
: questionLine(currentIndex, plan.length, currentQuestion, revisit);
if (startedRef.current && currentIndex === 0) {
bitSay(`${startLine(startedRef.current).text} ${line.text}`, 'cheer');
@@ -366,6 +368,7 @@ export const InterviewFlow = ({
const isLast = currentIndex === plan.length - 1;
const currentResult = session?.results[currentQuestion.id];
+ const currentTask = findConstructorTask(currentQuestion.content);
const aiAvailable = Boolean(ai.data?.enabled) && ai.data!.used_today < ai.data!.daily_limit;
@@ -416,7 +419,7 @@ export const InterviewFlow = ({
-
+
diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts
index 371de12..0e6c972 100644
--- a/frontend/src/types/index.ts
+++ b/frontend/src/types/index.ts
@@ -238,20 +238,37 @@ export interface ConstructorStep extends ConstructorPiece {
/** replace — конструктор вместо текстового ответа, with_text — сборка плюс объяснение словами. */
export type ConstructorMode = 'replace' | 'with_text';
+/** sequence — алгоритм из шагов, schema — схема БД из полей и внешних ключей. */
+export type ConstructorKind = 'sequence' | 'schema';
+
+/** Поле эталонной схемы: ref — таблица, на которую ссылается внешний ключ. */
+export interface SchemaFieldRef {
+ name: string;
+ ref?: string;
+}
+
+export interface SchemaTableRef {
+ name: string;
+ fields: SchemaFieldRef[];
+}
+
/**
- * Задание-конструктор: кандидат собирает алгоритм из блоков.
- * В вопросе лежат перемешанные куски (pieces), в эталонном ответе — решение (solution).
+ * Задание-конструктор: кандидат собирает решение из блоков.
+ * В вопросе лежат перемешанные куски (pieces; для схемы ещё имена таблиц — tables),
+ * в эталонном ответе — решение (solution) или схема (schema).
*/
export interface ConstructorBlock extends BlockBase {
type: 'constructor';
data?: {
- kind: 'sequence';
+ kind: ConstructorKind;
mode?: ConstructorMode;
prompt?: string;
/** with_text: что объяснить словами — эту часть оценивает ИИ. */
text_prompt?: string;
pieces?: ConstructorPiece[];
+ tables?: string[];
solution?: ConstructorStep[];
+ schema?: SchemaTableRef[];
};
}
@@ -265,12 +282,14 @@ export interface ContentBlock {
url?: string;
alt?: string;
caption?: string;
- kind?: 'sequence';
+ kind?: ConstructorKind;
mode?: ConstructorMode;
prompt?: string;
text_prompt?: string;
pieces?: ConstructorPiece[];
+ tables?: string[];
solution?: ConstructorStep[];
+ schema?: SchemaTableRef[];
};
order?: number;
}
diff --git a/tests/test_ai_review.py b/tests/test_ai_review.py
index dfa91fb..37441b4 100644
--- a/tests/test_ai_review.py
+++ b/tests/test_ai_review.py
@@ -264,3 +264,29 @@ def test_blocks_to_text_scopes_constructor_with_text_to_the_written_part():
[{"type": "constructor", "data": {"kind": "sequence", "solution": solution}}], 10_000
)
assert "1. Шаг A" in reference and "2. Шаг B" in reference
+
+
+def test_blocks_to_text_renders_constructor_schema():
+ question = [
+ {
+ "type": "constructor",
+ "data": {
+ "kind": "schema",
+ "mode": "with_text",
+ "prompt": "Разложите",
+ "text_prompt": "Объясните 3NF",
+ "tables": ["users", "posts"],
+ "pieces": [{"id": "a", "text": "user_id"}],
+ },
+ }
+ ]
+ out = blocks_to_text(question, 10_000)
+ assert "database schema" in out and "Объясните 3NF" in out and "user_id" not in out
+ schema = [
+ {"name": "users", "fields": [{"name": "id"}]},
+ {"name": "posts", "fields": [{"name": "id"}, {"name": "user_id", "ref": "users"}]},
+ ]
+ reference = blocks_to_text(
+ [{"type": "constructor", "data": {"kind": "schema", "schema": schema}}], 10_000
+ )
+ assert "users(id); posts(id, user_id -> users)" in reference
diff --git a/tests/test_content_constructor.py b/tests/test_content_constructor.py
index 0a1e34e..2519c55 100644
--- a/tests/test_content_constructor.py
+++ b/tests/test_content_constructor.py
@@ -138,6 +138,18 @@ def test_text_prompt_is_required_exactly_for_with_text(tmp_path, body):
{"kind": "sequence", "pieces": []},
{"kind": "sequence", "solution": [{"id": "a", "text": " "}]},
{"kind": "sequence", "pieces": [{"id": "a", "text": "x"}, {"id": "a", "text": "y"}]},
+ {"kind": "schema", "pieces": [{"id": "a", "text": "x"}]},
+ {"kind": "schema", "tables": [], "pieces": [{"id": "a", "text": "x"}]},
+ {"kind": "schema", "schema": []},
+ {"kind": "schema", "schema": [{"name": "a", "fields": []}]},
+ {
+ "kind": "schema",
+ "schema": [
+ {"name": "a", "fields": [{"name": "x"}]},
+ {"name": "a", "fields": [{"name": "y"}]},
+ ],
+ },
+ {"kind": "schema", "schema": [{"name": "a", "fields": [{"name": "x", "ref": "b"}]}]},
],
)
def test_validator_rejects_malformed_constructor_block(data):
@@ -149,8 +161,10 @@ def test_real_catalog_has_constructor_questions():
content = load_content()
with_build = [q.slug for q in content.questions if q.build]
assert "algo-valid-parentheses" in with_build
- # задание видно в режиме собеседования только у вопросов с компаниями
- assert all(q.companies for q in content.questions if q.build)
+ assert "db-normalization-1nf-3nf" in with_build
+ # задание видно в режиме собеседования у вопросов компании или шага роадмапа
+ in_roadmaps = {slug for r in content.roadmaps for step in r.steps for slug in step.questions}
+ assert all(q.companies or q.slug in in_roadmaps for q in content.questions if q.build)
async def test_import_stores_constructor_in_question_and_answer(engine, session, tmp_path):
@@ -162,3 +176,81 @@ async def test_import_stores_constructor_in_question_and_answer(engine, session,
answer = await session.scalar(select(Answer).where(Answer.question_id == question.id))
assert answer.content[1]["type"] == "constructor"
assert len(answer.content[1]["data"]["solution"]) == 5
+
+
+SCHEMA = """\
+build:
+ kind: schema
+ prompt: Разложите поля по таблицам
+ tables:
+ - name: users
+ fields: [id, email]
+ - name: posts
+ fields:
+ - id
+ - {name: user_id, ref: users}
+ - title
+ distractors: [user_email]
+"""
+
+
+def test_schema_goes_to_question_as_tables_and_fields_and_to_answer_as_schema(tmp_path):
+ root = make_catalog(tmp_path)
+ add_build(root, SCHEMA)
+ content = load_content(root)
+ assert content.errors == []
+ q = gil(content)
+
+ data = build_question_blocks(q)[-1]["data"]
+ assert data["kind"] == "schema" and data["tables"] == ["users", "posts"]
+ # куски — имена полей без таблиц и ссылок; одноимённые id разных таблиц — разные куски
+ assert sorted(p["text"] for p in data["pieces"]) == sorted(
+ ["id", "email", "id", "user_id", "title", "user_email"]
+ )
+ assert len({p["id"] for p in data["pieces"]}) == 6
+ assert all(set(p) == {"id", "text"} for p in data["pieces"])
+ validate_content_structure([build_question_blocks(q)[-1]])
+
+ answer = build_answer_blocks(q, content.company_names())
+ assert answer[0]["type"] == "paragraph"
+ assert answer[1]["data"] == {
+ "kind": "schema",
+ "schema": [
+ {"name": "users", "fields": [{"name": "id"}, {"name": "email"}]},
+ {
+ "name": "posts",
+ "fields": [{"name": "id"}, {"name": "user_id", "ref": "users"}, {"name": "title"}],
+ },
+ ],
+ }
+
+
+@pytest.mark.parametrize(
+ ("body", "needle"),
+ [
+ (
+ SCHEMA.replace("{name: user_id, ref: users}", "{name: user_id, ref: accounts}"),
+ "accounts",
+ ),
+ (SCHEMA.replace("[id, email]", "[id, id]"), "поля повторяются"),
+ (SCHEMA.replace("name: posts", "name: users"), "имена таблиц"),
+ (SCHEMA.replace("[user_email]", "[email]"), "совпадает с настоящим"),
+ (SCHEMA.replace("[id, email]", "[id, E-mail]"), "E-mail"),
+ (SCHEMA.replace(" distractors", " steps:\n - text: шаг\n distractors"), "steps"),
+ (
+ "build:\n kind: schema\n prompt: Разложите\n tables:\n - {name: a, fields: [x]}\n",
+ "от 2 до 6",
+ ),
+ (
+ BUILD.replace(
+ " distractors", " tables:\n - {name: a, fields: [x]}\n distractors"
+ ),
+ "tables",
+ ),
+ ],
+)
+def test_loader_rejects_broken_schema(tmp_path, body, needle):
+ root = make_catalog(tmp_path)
+ add_build(root, body)
+ errors = load_content(root).errors
+ assert any("gil.yaml" in e and needle in e for e in errors), errors