From f40d6f47d5e1b20134c92854c73651db0211d165 Mon Sep 17 00:00:00 2001 From: Andrei Mihai Visalon <54636077+Prekzursil@users.noreply.github.com> Date: Wed, 18 Nov 2026 15:49:11 +0200 Subject: [PATCH 1/2] feat(authoring): testcase generator DSL, variant families, Polygon legacy import, statement attachments [wave F items 122/126/127/128] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - item 122: problems/generator_dsl.py — declarative int/str variable declarations + print template; parse errors pinpoint the line; generate() is deterministic per (script, seed); POST /problems/{id}/generate-tests/ renders real TestCase rows (inputs first; expected outputs flow through the existing expected-output tool / reference solution) - item 126: Problem.variant_parent/variant_note — children point at the family ROOT (grandchildren flatten to the root); spawn copies statement + samples into a DRAFT child; GET /problems/{id}/variants/list/ tree; /author/tools UI - item 127: the package importer now also accepts the legacy Polygon extensionless tests/ + tests/.a layout (Kattis .in/.ans stays primary; seen-set dedup when both forms exist) - item 128: StatementAttachment — base64 upload onto media storage with a 2MB/10-file cap and sanitized names, inline/download kinds; GET/POST /problems/{id}/attachments/ - classroom effort-board test made wall-clock independent on this branch - BACKLOG statuses for 122/126/127/128 --- backend/classroom/test_wave_e_reports.py | 17 +- backend/problems/authoring_ops.py | 308 +++++++++++ backend/problems/generator_dsl.py | 70 +++ ...nt_note_problem_variant_parent_and_more.py | 94 ++++ backend/problems/models.py | 61 ++ backend/problems/test_authoring_ops.py | 357 ++++++++++++ backend/problems/tooling.py | 24 + backend/problems/urls.py | 22 + docs/BACKLOG.md | 2 +- e2e/mock-api/server.mjs | 65 +++ e2e/wave-f-tools.spec.ts | 42 ++ public/locales/ar.json | 20 +- public/locales/bg.json | 20 +- public/locales/ca.json | 20 +- public/locales/de.json | 20 +- public/locales/el.json | 20 +- public/locales/en.json | 20 +- public/locales/es.json | 20 +- public/locales/fa.json | 20 +- public/locales/fr.json | 20 +- public/locales/hi.json | 20 +- public/locales/hr.json | 20 +- public/locales/hu.json | 20 +- public/locales/id.json | 20 +- public/locales/it.json | 20 +- public/locales/ja.json | 20 +- public/locales/kk.json | 20 +- public/locales/ko.json | 20 +- public/locales/lt.json | 20 +- public/locales/nl.json | 20 +- public/locales/pl.json | 20 +- public/locales/pt.json | 20 +- public/locales/ro.json | 20 +- public/locales/ru.json | 20 +- public/locales/sr-Latn.json | 20 +- public/locales/th.json | 20 +- public/locales/tr.json | 20 +- public/locales/uk.json | 20 +- public/locales/vi.json | 20 +- public/locales/zh-Hans.json | 20 +- public/locales/zh-Hant.json | 20 +- scripts/add-wave-f8-keys.py | 522 ++++++++++++++++++ src/app/author/tools/ToolsPage.test.tsx | 119 ++++ src/app/author/tools/page.tsx | 238 ++++++++ src/components/layout/Navbar.tsx | 5 + src/locales/ar.json | 20 +- src/locales/bg.json | 20 +- src/locales/ca.json | 20 +- src/locales/de.json | 20 +- src/locales/el.json | 20 +- src/locales/en.json | 20 +- src/locales/es.json | 20 +- src/locales/fa.json | 20 +- src/locales/fr.json | 20 +- src/locales/hi.json | 20 +- src/locales/hr.json | 20 +- src/locales/hu.json | 20 +- src/locales/id.json | 20 +- src/locales/it.json | 20 +- src/locales/ja.json | 20 +- src/locales/kk.json | 20 +- src/locales/ko.json | 20 +- src/locales/lt.json | 20 +- src/locales/nl.json | 20 +- src/locales/pl.json | 20 +- src/locales/pt.json | 20 +- src/locales/ro.json | 20 +- src/locales/ru.json | 20 +- src/locales/sr-Latn.json | 20 +- src/locales/th.json | 20 +- src/locales/tr.json | 20 +- src/locales/uk.json | 20 +- src/locales/vi.json | 20 +- src/locales/zh-Hans.json | 20 +- src/locales/zh-Hant.json | 20 +- src/services/ApiService.ts | 26 + src/types/api.ts | 17 + 77 files changed, 3122 insertions(+), 67 deletions(-) create mode 100644 backend/problems/authoring_ops.py create mode 100644 backend/problems/generator_dsl.py create mode 100644 backend/problems/migrations/0024_problem_variant_note_problem_variant_parent_and_more.py create mode 100644 backend/problems/test_authoring_ops.py create mode 100644 e2e/wave-f-tools.spec.ts create mode 100644 scripts/add-wave-f8-keys.py create mode 100644 src/app/author/tools/ToolsPage.test.tsx create mode 100644 src/app/author/tools/page.tsx diff --git a/backend/classroom/test_wave_e_reports.py b/backend/classroom/test_wave_e_reports.py index ca59ef97..364574b1 100644 --- a/backend/classroom/test_wave_e_reports.py +++ b/backend/classroom/test_wave_e_reports.py @@ -95,11 +95,15 @@ class EffortAndHeatmapTest(ReportsBase): """Items 43/44: the analytics derivations.""" def test_effort_board_ranks_grinders(self): - # st attempts 3 times (2 active days); lz a single AC. - # The two "old day" submissions are pinned to fixed clock times on - # explicit dates (10:00 and 10:30 two days ago, 10:00 yesterday): - # minutes_ago offsets straddle midnight depending on the wall clock - # at run time, which made active_days flake (3 dates at night runs). + # st attempts 4 times (2 active days); lz a single AC. Every + # submission sits on a pinned instant (10:00/10:30 two days ago, + # 10:00/10:30 yesterday) and the window is widened to 3 days so + # the pins always fall inside — fully wall-clock independent. + Assignment.objects.filter(pk=self.assignment.pk).update( + available_from=timezone.now() - timedelta(days=3), + due_at=timezone.now() + timedelta(days=3), + ) + def pinned(days_ago: int, minute: int = 0): moment = timezone.now() - timedelta(days=days_ago) return moment.replace(hour=10, minute=minute, second=0, microsecond=0) @@ -107,10 +111,11 @@ def pinned(days_ago: int, minute: int = 0): self._submit_at(self.student, WA, 10, pinned(2, 0)) self._submit_at(self.student, WA, 20, pinned(2, 30)) self._submit_at(self.student, WA, 30, pinned(1, 0)) + self._submit_at(self.student, WA, 40, pinned(1, 30)) self._submit(self.lazy, AC, 100) board = effort_board(self.classroom) rows = {r["username"]: r for r in board["results"]} - self.assertEqual(rows["st"]["attempts"], 3) + self.assertEqual(rows["st"]["attempts"], 4) self.assertEqual(rows["st"]["active_days"], 2) self.assertEqual(rows["st"]["problems_solved"], 0) self.assertEqual(rows["lz"]["problems_solved"], 1) diff --git a/backend/problems/authoring_ops.py b/backend/problems/authoring_ops.py new file mode 100644 index 00000000..3ecc294b --- /dev/null +++ b/backend/problems/authoring_ops.py @@ -0,0 +1,308 @@ +"""Wave F authoring-ops API (items 122/126/127/128). + +- ``POST /problems/{id}/generate-tests/`` render the DSL into TestCases +- ``POST /problems/{id}/variants/`` spawn a variant child +- ``GET /problems/{id}/variants/`` the family tree +- ``POST /problems/{id}/attachments/`` upload a statement attachment +- ``GET /problems/{id}/attachments/`` list them +- ``POST /problems/tools/import-package/`` (existing) now also accepts the + legacy Polygon ``tests/`` + ``tests/.a`` layout. +""" + +from __future__ import annotations + +import base64 +import binascii +import re + +from django.core.files.storage import default_storage +from django.db import models as dj_models +from django.utils import timezone +from rest_framework import permissions, serializers, status +from rest_framework.response import Response +from rest_framework.views import APIView + +from users.models import User + +from .models import Problem, TestCase +from .generator_dsl import generate, parse_dsl + +MAX_ATTACHMENT_BYTES = 2 * 1024 * 1024 +ATTACHMENT_NAME_RE = re.compile(r"^[\w\-. ]+$") +MAX_ATTACHMENTS = 10 + + +def _authoring_gate(user) -> bool: + return bool( + user + and user.is_authenticated + and ( + user.is_superuser + or user.is_staff + or getattr(user, "role", "") + in ( + User.Roles.ADMIN, + User.Roles.PROBLEM_VERIFIER, + User.Roles.PROBLEM_CREATOR, + User.Roles.TEACHER, + ) + ) + ) + + +class GenerateTestsSerializer(serializers.Serializer): + dsl = serializers.CharField(max_length=20_000) + count = serializers.IntegerField(min_value=1, max_value=50, default=5) + seed = serializers.IntegerField(min_value=0, default=0) + is_sample = serializers.BooleanField(default=False) + + +class GenerateTestsView(APIView): + """Item 122 — render the generator DSL into real TestCase rows.""" + + permission_classes = [permissions.IsAuthenticated] + + def post(self, request, problem_id): + problem = Problem.objects.filter(pk=problem_id).first() + if problem is None: + return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND) + if not _authoring_gate(request.user): + return Response( + {"detail": "Authors and verifiers only."}, + status=status.HTTP_403_FORBIDDEN, + ) + payload = GenerateTestsSerializer(data=request.data) + payload.is_valid(raise_exception=True) + data = payload.validated_data + try: + parse_dsl(data["dsl"]) + except ValueError as exc: + return Response({"dsl": str(exc)}, status=status.HTTP_400_BAD_REQUEST) + base_order = problem.test_cases.count() + created = 0 + for offset in range(data["count"]): + rendered = generate(data["dsl"], data["seed"] + offset) + TestCase.objects.create( + problem=problem, + input_data=rendered, + expected_output_data="", + is_sample=data["is_sample"], + points=10, + order=base_order + offset, + ) + created += 1 + return Response( + { + "created": created, + "first": generate(data["dsl"], data["seed"]), + "note": "Inputs generated; fill expected outputs via the " + "expected-output tool or a reference solution.", + }, + status=status.HTTP_201_CREATED, + ) + + +class VariantSerializer(serializers.Serializer): + note = serializers.CharField(max_length=200, required=False, allow_blank=True) + + +class VariantSpawnView(APIView): + """Item 126 — spawn a variant child from a family parent.""" + + permission_classes = [permissions.IsAuthenticated] + + def post(self, request, problem_id): + parent = Problem.objects.filter(pk=problem_id).first() + if parent is None: + return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND) + if not _authoring_gate(request.user): + return Response( + {"detail": "Authors and verifiers only."}, + status=status.HTTP_403_FORBIDDEN, + ) + payload = VariantSerializer(data=request.data) + payload.is_valid(raise_exception=True) + note = payload.validated_data.get("note", "") + base_title = ( + parent.title_i18n.get("en", f"Problem {parent.id}") + if isinstance(parent.title_i18n, dict) + else f"Problem {parent.id}" + ) + root = parent.variant_root + child_count = Problem.objects.filter(variant_parent=root).count() + child = Problem.objects.create( + title_i18n={ + "en": f"{base_title} — variant {child_count + 1}", + "ro": f"{base_title} — varianta {child_count + 1}", + }, + statement_i18n=dict(parent.statement_i18n), + status=Problem.ProblemStatus.DRAFT, + author=request.user, + difficulty=parent.difficulty, + default_time_limit_ms=parent.default_time_limit_ms, + default_memory_limit_kb=parent.default_memory_limit_kb, + variant_parent=root, + variant_note=note, + ) + # Copy the samples so the variant starts from the parent's worked + # examples; hidden tests stay per-variant by design. + for sample in parent.test_cases.filter(is_sample=True): + TestCase.objects.create( + problem=child, + input_data=sample.input_data, + expected_output_data=sample.expected_output_data, + is_sample=True, + points=sample.points, + order=sample.order, + ) + return Response( + { + "variant_id": child.id, + "root_id": root.id, + "title": child.title_i18n["en"], + }, + status=status.HTTP_201_CREATED, + ) + + +class VariantListView(APIView): + """Item 126 — the family tree for one problem (root + siblings).""" + + permission_classes = [permissions.AllowAny] + + def get(self, request, problem_id): + problem = Problem.objects.filter(pk=problem_id).first() + if problem is None: + return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND) + root = problem.variant_root + family = Problem.objects.filter( + dj_models.Q(pk=root.pk) | dj_models.Q(variant_parent=root) + ).order_by("id") + return Response( + { + "root": root.id, + "count": family.count(), + "variants": [ + { + "id": row.id, + "title": ( + row.title_i18n.get("en", f"Problem {row.id}") + if isinstance(row.title_i18n, dict) + else f"Problem {row.id}" + ), + "note": row.variant_note, + "status": row.status, + } + for row in family + ], + } + ) + + +class AttachmentSerializer(serializers.Serializer): + name = serializers.CharField(max_length=120) + content_base64 = serializers.CharField() + kind = serializers.ChoiceField(choices=["inline", "download"], default="inline") + + +class AttachmentView(APIView): + """Items 128 — statement attachments stored on the media storage.""" + + permission_classes = [permissions.IsAuthenticated] + + def _problem_or_none(self, problem_id): + return Problem.objects.filter(pk=problem_id).first() + + def get(self, request, problem_id): + problem = self._problem_or_none(problem_id) + if problem is None: + return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND) + if not _authoring_gate(request.user): + return Response( + {"detail": "Authors and verifiers only."}, + status=status.HTTP_403_FORBIDDEN, + ) + from .models import StatementAttachment + + rows = StatementAttachment.objects.filter(problem=problem).order_by("id") + return Response( + { + "count": rows.count(), + "results": [ + { + "id": row.id, + "name": row.name, + "kind": row.kind, + "size_bytes": row.size_bytes, + "url": row.file.url if row.file else "", + "uploaded_at": row.uploaded_at, + } + for row in rows + ], + } + ) + + def post(self, request, problem_id): + problem = self._problem_or_none(problem_id) + if problem is None: + return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND) + if not _authoring_gate(request.user): + return Response( + {"detail": "Authors and verifiers only."}, + status=status.HTTP_403_FORBIDDEN, + ) + from .models import StatementAttachment + + if ( + StatementAttachment.objects.filter(problem=problem).count() + >= MAX_ATTACHMENTS + ): + return Response( + { + "detail": f"A statement may carry at most {MAX_ATTACHMENTS} attachments." + }, + status=status.HTTP_400_BAD_REQUEST, + ) + payload = AttachmentSerializer(data=request.data) + payload.is_valid(raise_exception=True) + data = payload.validated_data + if not ATTACHMENT_NAME_RE.match(data["name"]): + return Response( + {"name": "Letters, digits, dash, underscore, dot and space only."}, + status=status.HTTP_400_BAD_REQUEST, + ) + try: + raw = base64.b64decode(data["content_base64"], validate=True) + except (binascii.Error, ValueError): + return Response( + {"content_base64": "Invalid base64 payload."}, + status=status.HTTP_400_BAD_REQUEST, + ) + if len(raw) > MAX_ATTACHMENT_BYTES: + return Response( + {"content_base64": "Attachments are capped at 2 MB."}, + status=status.HTTP_400_BAD_REQUEST, + ) + safe_name = f"attachments/p{problem.id}/{timezone.now().strftime('%Y%m%d%H%M%S')}-{data['name']}" + from django.core.files.base import ContentFile + + saved = default_storage.save(safe_name, ContentFile(raw, name=data["name"])) + row = StatementAttachment.objects.create( + problem=problem, + name=data["name"], + kind=data["kind"], + file=saved, + size_bytes=len(raw), + uploaded_by=request.user, + ) + return Response( + { + "id": row.id, + "name": row.name, + "kind": row.kind, + "size_bytes": row.size_bytes, + "url": row.file.url if row.file else "", + "uploaded_at": row.uploaded_at, + }, + status=status.HTTP_201_CREATED, + ) diff --git a/backend/problems/generator_dsl.py b/backend/problems/generator_dsl.py new file mode 100644 index 00000000..87a07376 --- /dev/null +++ b/backend/problems/generator_dsl.py @@ -0,0 +1,70 @@ +"""Testcase generator DSL + variant families + statement attachments +(wave F items 122/126/128) and Polygon legacy-layout import (item 127). + +- ``generator_dsl`` — a tiny declarative language for reproducible test + data: lines of ``name = int(lo, hi)`` / ``name = str(lo, hi)`` variable + declarations plus a ``print`` template referencing ``{name}`` fields. + ``generate(dsl, seed)`` is deterministic per (script, seed). +- ``variants`` — a variant family groups problems sharing a skeleton; + spawning a child copies the parent with per-variant parameter notes. +- Polygon legacy layout (item 127) is accepted by extending the package + importer's test walker to extensionless ``tests/`` + + ``tests/.a`` pairs. +""" + +from __future__ import annotations + +import random +import re + +_LINE_RE = re.compile( + r"^\s*(\w+)\s*=\s*(int|str)\s*\(\s*(-?\d+)\s*,\s*(-?\d+)\s*\)\s*$" +) +_PRINT_RE = re.compile(r"^\s*print\s+(.+)$") + + +def parse_dsl(script: str) -> dict: + """Parse a generator script: {vars: {name: (kind, lo, hi)}, template: str}. + + Raises ``ValueError`` with a precise message on malformed lines. + """ + variables: dict[str, tuple[str, int, int]] = {} + template = "" + for lineno, line in enumerate(script.splitlines(), start=1): + if not line.strip() or line.strip().startswith("#"): + continue + match = _LINE_RE.match(line) + if match: + name, kind, lo, hi = match.groups() + lo, hi = int(lo), int(hi) + if lo > hi: + raise ValueError(f"line {lineno}: range low > high for '{name}'") + variables[name] = (kind, lo, hi) + continue + match = _PRINT_RE.match(line) + if match: + template = match.group(1).strip() + continue + raise ValueError(f"line {lineno}: cannot parse '{line.strip()}'") + if not template: + raise ValueError("the script needs a print template line") + # every placeholder must be declared + for field in re.findall(r"\{(\w+)\}", template): + if field not in variables: + raise ValueError(f"template references undeclared field '{field}'") + return {"vars": variables, "template": template} + + +def generate(dsl: str, seed: int) -> str: + """Render one deterministic test input for the script + seed.""" + parsed = parse_dsl(dsl) + rng = random.Random(f"{seed}") # deterministic across platforms/runs + values: dict[str, str] = {} + for name, (kind, lo, hi) in parsed["vars"].items(): + if kind == "int": + values[name] = str(rng.randint(lo, hi)) + else: + length = rng.randint(lo, hi) + alphabet = "abcdefghijklmnopqrstuvwxyz" + values[name] = "".join(rng.choice(alphabet) for _ in range(length)) + return parsed["template"].format(**values) diff --git a/backend/problems/migrations/0024_problem_variant_note_problem_variant_parent_and_more.py b/backend/problems/migrations/0024_problem_variant_note_problem_variant_parent_and_more.py new file mode 100644 index 00000000..28f2014d --- /dev/null +++ b/backend/problems/migrations/0024_problem_variant_note_problem_variant_parent_and_more.py @@ -0,0 +1,94 @@ +# Generated by Django 5.2.17 on 2026-11-18 10:45 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("problems", "0023_problem_reference_language_and_more"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name="problem", + name="variant_note", + field=models.CharField( + blank=True, max_length=200, verbose_name="variant note" + ), + ), + migrations.AddField( + model_name="problem", + name="variant_parent", + field=models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="variant_children", + to="problems.problem", + verbose_name="variant parent (family root)", + ), + ), + migrations.CreateModel( + name="StatementAttachment", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("name", models.CharField(max_length=120, verbose_name="name")), + ( + "kind", + models.CharField( + choices=[ + ("inline", "Inline (rendered in the statement)"), + ("download", "Download"), + ], + default="inline", + max_length=10, + verbose_name="kind", + ), + ), + ( + "file", + models.FileField(max_length=300, upload_to="", verbose_name="file"), + ), + ( + "size_bytes", + models.PositiveIntegerField(default=0, verbose_name="size (bytes)"), + ), + ("uploaded_at", models.DateTimeField(auto_now_add=True)), + ( + "problem", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="attachments", + to="problems.problem", + verbose_name="problem", + ), + ), + ( + "uploaded_by", + models.ForeignKey( + blank=True, + null=True, + on_delete=django.db.models.deletion.SET_NULL, + related_name="uploaded_attachments", + to=settings.AUTH_USER_MODEL, + ), + ), + ], + options={ + "verbose_name": "statement attachment", + "verbose_name_plural": "statement attachments", + "ordering": ["problem", "id"], + }, + ), + ] diff --git a/backend/problems/models.py b/backend/problems/models.py index c3e51fec..d622d1c5 100644 --- a/backend/problems/models.py +++ b/backend/problems/models.py @@ -451,6 +451,18 @@ class ComparisonMode(models.TextChoices): blank=True, help_text=_("Registry language of the reference solution."), ) + # Variant families (item 126): children point at the family ROOT; the + # root itself points at nothing. variant_note records the per-variant + # parameter tweak ("bounds doubled", "queries offline", …). + variant_parent = models.ForeignKey( + "self", + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="variant_children", + verbose_name=_("variant parent (family root)"), + ) + variant_note = models.CharField(_("variant note"), max_length=200, blank=True) verifier_feedback = models.TextField( _("verifier feedback"), blank=True, @@ -467,6 +479,16 @@ def __str__(self): ) return f"Problem {self.id}" + @property + def variant_root(self): + """The family root: the problem itself when it has no parent.""" + current = self + seen = set() + while current.variant_parent_id is not None and current.id not in seen: + seen.add(current.id) + current = current.variant_parent + return current + class Meta: verbose_name = _("problem") verbose_name_plural = _("problems") @@ -1017,3 +1039,42 @@ def __str__(self): self.position, self.problem_id, ) + + +class StatementAttachment(models.Model): + """Item 128 — a file attached to a problem statement (figure, PDF, + dataset sketch). Stored on the media storage; the statement embeds it + by URL. Author/verifier-visible in the authoring flow.""" + + class Kind(models.TextChoices): + INLINE = "inline", _("Inline (rendered in the statement)") + DOWNLOAD = "download", _("Download") + + problem = models.ForeignKey( + Problem, + on_delete=models.CASCADE, + related_name="attachments", + verbose_name=_("problem"), + ) + name = models.CharField(_("name"), max_length=120) + kind = models.CharField( + _("kind"), max_length=10, choices=Kind.choices, default=Kind.INLINE + ) + file = models.FileField(_("file"), max_length=300) + size_bytes = models.PositiveIntegerField(_("size (bytes)"), default=0) + uploaded_by = models.ForeignKey( + settings.AUTH_USER_MODEL, + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="uploaded_attachments", + ) + uploaded_at = models.DateTimeField(auto_now_add=True) + + class Meta: + verbose_name = _("statement attachment") + verbose_name_plural = _("statement attachments") + ordering = ["problem", "id"] + + def __str__(self): + return f"attachment {self.name} (problem {self.problem_id})" diff --git a/backend/problems/test_authoring_ops.py b/backend/problems/test_authoring_ops.py new file mode 100644 index 00000000..888e2f6a --- /dev/null +++ b/backend/problems/test_authoring_ops.py @@ -0,0 +1,357 @@ +"""Wave F — authoring-ops tests (items 122/126/127/128). + +The generator DSL (parse + deterministic generation + endpoint), variant +families (spawn + tree), statement attachments and the legacy Polygon +``tests/`` import layout. +""" + +import base64 +import io +import zipfile + +from django.test import TestCase, override_settings +from rest_framework import status +from rest_framework.test import APIClient + +from problems.generator_dsl import generate, parse_dsl +from problems.models import Problem, StatementAttachment +from problems.models import TestCase as ProblemTestCase +from users.models import User + + +DSL = """\n# sizes +n = int(1, 100) +q = int(1, 20) +s = str(3, 8) +print {n} {q} {s} +""" + + +class AuthoringOpsBase(TestCase): + def setUp(self): + self.author = User.objects.create_user( + username="author", password="pw", role=User.Roles.PROBLEM_CREATOR + ) + self.verifier = User.objects.create_user( + username="verifier", password="pw", role=User.Roles.PROBLEM_VERIFIER + ) + self.basic = User.objects.create_user(username="basic", password="pw") + self.client = APIClient() + self.problem = Problem.objects.create( + title_i18n={"en": "Sum", "ro": "Suma"}, + statement_i18n={"en": "Input. Output. Constraints. Example.", "ro": "x"}, + status=Problem.ProblemStatus.DRAFT, + author=self.author, + ) + + def mk_zip(self, files: dict) -> str: + buffer = io.BytesIO() + with zipfile.ZipFile(buffer, "w") as zf: + for name, content in files.items(): + zf.writestr(name, content) + return base64.b64encode(buffer.getvalue()).decode() + + +class GeneratorDslTests(AuthoringOpsBase): + def test_parse_and_determinism(self): + parsed = parse_dsl(DSL) + self.assertEqual(set(parsed["vars"]), {"n", "q", "s"}) + first = generate(DSL, 42) + self.assertEqual(first, generate(DSL, 42)) + self.assertNotEqual(generate(DSL, 1), generate(DSL, 2)) + + def test_parse_errors(self): + with self.assertRaises(ValueError): + parse_dsl("n = int(10, 1)\nprint {n}") # lo > hi + with self.assertRaises(ValueError): + parse_dsl("n = int(1, 10)") # no print + with self.assertRaises(ValueError): + parse_dsl("print {ghost}") # undeclared field + with self.assertRaises(ValueError): + parse_dsl("nonsense line") + + def test_generate_endpoint(self): + self.client.force_authenticate(self.author) + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/generate-tests/", + {"dsl": DSL, "count": 3, "seed": 5}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data) + self.assertEqual(response.data["created"], 3) + self.assertEqual(self.problem.test_cases.count(), 3) + # Bad DSL rejected. + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/generate-tests/", + {"dsl": "print {ghost}", "count": 1}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + + def test_endpoint_gates(self): + self.client.force_authenticate(self.basic) + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/generate-tests/", + {"dsl": DSL, "count": 1}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + self.client.force_authenticate(self.author) + response = self.client.post( + "/api/v1/problems/problems/999999/generate-tests/", + {"dsl": DSL, "count": 1}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + +class VariantTests(AuthoringOpsBase): + def test_spawn_and_tree(self): + child_body = {"note": "bounds doubled"} + self.client.force_authenticate(self.verifier) + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/variants/", + child_body, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data) + child_id = response.data["variant_id"] + self.assertEqual(response.data["root_id"], self.problem.id) + # Grandchildren attach to the ROOT, not the child. + response = self.client.post( + f"/api/v1/problems/problems/{child_id}/variants/", + {"note": "offline queries"}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + self.assertEqual(response.data["root_id"], self.problem.id) + # Family tree from the child's perspective includes everyone. + response = self.client.get( + f"/api/v1/problems/problems/{child_id}/variants/list/" + ) + self.assertEqual(response.status_code, 200, response.data) + self.assertEqual(response.data["count"], 3) + notes = {row["note"] for row in response.data["variants"]} + self.assertIn("bounds doubled", notes) + self.assertIn("offline queries", notes) + + def test_spawn_copies_samples(self): + ProblemTestCase.objects.create( + problem=self.problem, + input_data="1", + expected_output_data="2", + is_sample=True, + points=10, + order=0, + ) + self.client.force_authenticate(self.author) + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/variants/", {}, format="json" + ) + child = Problem.objects.get(pk=response.data["variant_id"]) + self.assertEqual(child.test_cases.filter(is_sample=True).count(), 1) + + def test_variant_anon_gate_and_list_404(self): + # Anonymous spawn hits the auth gate (401) before the view body. + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/variants/", {}, format="json" + ) + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + + def test_variant_gates_and_404(self): + self.client.force_authenticate(self.basic) + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/variants/", {}, format="json" + ) + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + self.client.force_authenticate(self.author) + response = self.client.post( + "/api/v1/problems/problems/999999/variants/", {}, format="json" + ) + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + response = self.client.get("/api/v1/problems/problems/999999/variants/list/") + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + +class AttachmentTests(AuthoringOpsBase): + def _upload(self, name="fig.png", content=b"pngbytes", kind="inline"): + payload = base64.b64encode(content).decode() + return self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/attachments/", + {"name": name, "content_base64": payload, "kind": kind}, + format="json", + ) + + @override_settings() + def test_upload_and_list(self): + self.client.force_authenticate(self.author) + response = self._upload() + self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data) + self.assertEqual(response.data["kind"], "inline") + self.assertIn("url", response.data) + listing = self.client.get( + f"/api/v1/problems/problems/{self.problem.id}/attachments/" + ) + self.assertEqual(listing.data["count"], 1) + self.assertTrue( + StatementAttachment.objects.filter(problem=self.problem).exists() + ) + + def test_upload_validation(self): + self.client.force_authenticate(self.author) + response = self._upload(name="../evil") + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/attachments/", + {"name": "x.png", "content_base64": "not!valid!base64!!"}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + response = self._upload(content=b"a" * (2 * 1024 * 1024 + 1)) + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + + def test_upload_cap_and_gates(self): + self.client.force_authenticate(self.basic) + response = self._upload() + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + self.client.force_authenticate(self.author) + for i in range(10): + response = self._upload(name=f"f{i}.png") + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + response = self._upload(name="over.png") + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + self.client.force_authenticate(self.verifier) + listing = self.client.get( + f"/api/v1/problems/problems/{self.problem.id}/attachments/" + ) + self.assertEqual(listing.data["count"], 10) + response = self.client.get("/api/v1/problems/problems/999999/attachments/") + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + def test_attachment_get_and_post_gates(self): + # Authors can list; basic users are refused on GET and POST. + self.client.force_authenticate(self.basic) + response = self.client.get( + f"/api/v1/problems/problems/{self.problem.id}/attachments/" + ) + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/attachments/", + {"name": "x.png", "content_base64": base64.b64encode(b"x").decode()}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) + + def test_attachment_anonymous_oversize_and_404(self): + # Anonymous upload (401), the oversize guard, and unknown problems. + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/attachments/", + {"name": "x.png", "content_base64": base64.b64encode(b"x").decode()}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) + self.client.force_authenticate(self.author) + from unittest import mock + + from problems import authoring_ops as ops + + with mock.patch.object(ops, "MAX_ATTACHMENT_BYTES", 4): + big = base64.b64encode(b"toolongpayload").decode() + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/attachments/", + {"name": "big.bin", "content_base64": big}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + big = base64.b64encode(b"a" * (2 * 1024 * 1024 + 1)).decode() + response = self.client.post( + f"/api/v1/problems/problems/{self.problem.id}/attachments/", + {"name": "big.bin", "content_base64": big}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + response = self.client.post( + "/api/v1/problems/problems/999999/attachments/", + {"name": "x.png", "content_base64": base64.b64encode(b"x").decode()}, + format="json", + ) + self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + def test_str_method(self): + self.client.force_authenticate(self.author) + response = self._upload() + row = StatementAttachment.objects.get(pk=response.data["id"]) + self.assertIn("attachment", str(row)) + + +class PolygonLegacyImportTests(AuthoringOpsBase): + def _import(self, files): + self.client.force_authenticate(self.verifier) + return self.client.post( + "/api/v1/problems/tools/import-package/", + { + "package_base64": self.mk_zip(files), + "declare_own_content": True, + }, + format="json", + ) + + def test_legacy_tests_layout(self): + response = self._import( + { + "tests/1": "5\n1 2 3 4 5", + "tests/1.a": "15", + "tests/2": "3\n1 2 3", + "tests/2.ans": "6", + "tests/3": "orphan", + } + ) + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(response.data["tests_imported"], 2) + created = Problem.objects.get(pk=response.data["problem_id"]) + inputs = list( + created.test_cases.order_by("order").values_list("input_data", flat=True) + ) + self.assertEqual(inputs[0].strip(), "5\n1 2 3 4 5") + self.assertEqual(inputs[1].strip(), "3\n1 2 3") + + def test_legacy_mixed_with_kattis(self): + response = self._import( + { + "data/sample/a.in": "1", + "data/sample/a.ans": "2", + "tests/9": "7", + "tests/9.a": "8", + } + ) + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(response.data["tests_imported"], 2) + self.assertEqual(response.data["samples"], 1) + + +class PolygonDedupTests(AuthoringOpsBase): + def test_extensionless_skipped_when_kattis_pair_exists(self): + # tests/1.in pairs Kattis-style; the extensionless tests/1 is then + # already covered (seen) and the legacy loop must skip it. + self.client.force_authenticate(self.verifier) + response = self.client.post( + "/api/v1/problems/tools/import-package/", + { + "package_base64": self.mk_zip( + { + "tests/1.in": "5", + "tests/1.ans": "6", + "tests/1": "5", + "tests/1.a": "6", + "tests/2": "7", + "tests/2.a": "8", + } + ), + "declare_own_content": True, + }, + format="json", + ) + self.assertEqual(response.status_code, 201, response.data) + self.assertEqual(response.data["tests_imported"], 2) + created = Problem.objects.get(pk=response.data["problem_id"]) + self.assertEqual(created.test_cases.count(), 2) diff --git a/backend/problems/tooling.py b/backend/problems/tooling.py index 5f32a692..19b22c9d 100644 --- a/backend/problems/tooling.py +++ b/backend/problems/tooling.py @@ -808,6 +808,30 @@ def _tests_from_zip(package: zipfile.ZipFile) -> list[tuple[str, str, str, bool] input_text = package.read(name).decode("utf-8", errors="replace") is_sample = any(part.lower() == "sample" for part in parts) pairs.append((stem, input_text, answer, is_sample)) + # Legacy Polygon layout (item 127): extensionless ``tests/`` input + # files paired with ``tests/.a`` answers (or .ans/.out siblings). + seen = {pair[0] for pair in pairs} + for name in names: + if not _safe_member_name(name) or name.endswith("/"): + continue + parts = re.split(r"[/\\]", name) + if parts[0].lower() != "tests" or len(parts) != 2: + continue + if "." in parts[1]: + continue # answers and other files carry extensions + stem = name + if stem in seen: + continue + answer = None + for ext in _ANSWER_SUFFIXES: + candidate = stem + ext + if candidate in names: + answer = package.read(candidate).decode("utf-8", errors="replace") + break + if answer is None: + continue + input_text = package.read(name).decode("utf-8", errors="replace") + pairs.append((stem, input_text, answer, False)) return pairs diff --git a/backend/problems/urls.py b/backend/problems/urls.py index 8424fa58..96fdda3c 100644 --- a/backend/problems/urls.py +++ b/backend/problems/urls.py @@ -25,6 +25,7 @@ ) from .presubmit import PreSubmitLintView, PreSubmitSamplesView from .strength import TestStrengthView +from . import authoring_ops from .random_problem import RandomProblemView app_name = "problems" @@ -117,4 +118,25 @@ # the "random" path can never collide with the /{pk}/ detail route. path("random/", RandomProblemView.as_view(), name="problem-random"), path("", include(router.urls)), + # Wave F items 122/126/128 — generator DSL, variants, attachments. + path( + "problems//generate-tests/", + authoring_ops.GenerateTestsView.as_view(), + name="generate_tests", + ), + path( + "problems//variants/", + authoring_ops.VariantSpawnView.as_view(), + name="variant_spawn", + ), + path( + "problems//variants/list/", + authoring_ops.VariantListView.as_view(), + name="variant_list", + ), + path( + "problems//attachments/", + authoring_ops.AttachmentView.as_view(), + name="statement_attachments", + ), ] diff --git a/docs/BACKLOG.md b/docs/BACKLOG.md index 67033572..395423cf 100644 --- a/docs/BACKLOG.md +++ b/docs/BACKLOG.md @@ -27,7 +27,7 @@ Item-level tracker of record. Statuses: `shipped (PR #N)` · `in-flight (wave X) 113. Plagiarism detection (MOSS/JPlag) · (vote trust-weighting shipped Wave C — RAT-10) 114. Boilerplate detection · 115. Multi-account heuristics · 116. AI-solution labeling/policy · 117. Abuse queue + SLA · 118. Moderation appeals + audit trail · 119. Bug bounty page · 120. Verifiable participation certificates — shipped (Wave D, certifications/attestats: leaderboard-derived atestats — rated-contest participation, rating milestones, solve milestones — public UUID verification, print/PDF sheet, revocation ledger; contest medals were the first increment, Wave C CON-11) ## I. Authoring & content ops — wave F -121. Visual authoring wizard · 122. Testcase generator DSL · 123. Statement linter · 124. EN+translation sidecar authoring · 125. Problem versioning/changelog · (statement revision history shipped Wave C — UXP-4) · 126. Variant families · 127. Polygon-format import · 128. Statement attachments · 129. Advanced search w/ saved queries · 130. Source attribution + licensing field (UGC CC BY-SA + school DPA + ImportSource permission ledger + provenance fields shipped Wave C) · 131. Scheduled content drops · 132. Author analytics · 133. Testcase bounties · 134. Readability scoring +121. Visual authoring wizard · 122. Testcase generator DSL — shipped (Wave F: problems/generator_dsl.py — declarative int/str var declarations + print template, deterministic per (script, seed); POST /problems/{id}/generate-tests/ renders real TestCase rows; /author/tools UI) · 123. Statement linter · 124. EN+translation sidecar authoring · 125. Problem versioning/changelog · (statement revision history shipped Wave C — UXP-4) · 126. Variant families — shipped (Wave F: Problem.variant_parent/variant_note — children point at the family root (grandchildren flatten); spawn copies the statement + samples into a DRAFT child with per-variant note; GET /problems/{id}/variants/list/ family tree + tools UI) · 127. Polygon-format import — shipped complete (Wave C: Kattis/Polygon-compatible .in/.ans packages via tools/import-package with the CNT-2 ledger gate; Wave F: the legacy extensionless Polygon tests/ + tests/.a layout accepted and tested) · 128. Statement attachments — shipped (Wave F: StatementAttachment — base64 upload (2MB cap, 10-file cap, sanitized names) onto media storage, inline/download kinds; GET/POST /problems/{id}/attachments/ + tools UI list) · 129. Advanced search w/ saved queries · 130. Source attribution + licensing field (UGC CC BY-SA + school DPA + ImportSource permission ledger + provenance fields shipped Wave C) · 131. Scheduled content drops · 132. Author analytics · 133. Testcase bounties · 134. Readability scoring ## J. Ops, performance, reliability — wave G 135. Judge queue transparency page · 136. Autoscaling workers · 137. Contest priority lanes · 138. Load-test harness · 139. Status page · 140. Blue-green deploy · 141. Nightly prod-like e2e · 142. Restore drills · 143. Cost dashboard · 144. Edge protection · 145. Error tracking productized diff --git a/e2e/mock-api/server.mjs b/e2e/mock-api/server.mjs index ddeeb33d..cdc714a8 100644 --- a/e2e/mock-api/server.mjs +++ b/e2e/mock-api/server.mjs @@ -316,6 +316,17 @@ const messagingState = { const virtualStarted = new Set(); +// Wave F authoring-ops fixtures (item 128). +const MOCK_ATTACHMENTS = [ + { + id: 1, + name: 'figure.png', + kind: 'inline', + size_bytes: 512, + url: '/media/mock-figure.png', + }, +]; + // Wave F recognition fixtures (items 67-69). const MOCK_AWARDS = [ { @@ -1818,6 +1829,60 @@ const server = createServer((req, res) => { return; } + // ---- Wave F authoring ops (items 122/126/128) ---- + const generateTests = path.match(/^\/api\/v1\/problems\/problems\/(\d+)\/generate-tests\/$/); + if (req.method === 'POST' && generateTests) { + readBody(req, (body) => { + json(res, 201, { + created: body.count ?? 5, + first: '42 7', + note: 'Inputs generated', + }); + }); + return; + } + const variantSpawn = path.match(/^\/api\/v1\/problems\/problems\/(\d+)\/variants\/$/); + if (req.method === 'POST' && variantSpawn) { + json(res, 201, { + variant_id: 12, + root_id: Number(variantSpawn[1]), + title: 'Two Sum — variant 1', + }); + return; + } + const variantList = path.match(/^\/api\/v1\/problems\/problems\/(\d+)\/variants\/list\/$/); + if (req.method === 'GET' && variantList) { + json(res, 200, { + root: Number(variantList[1]), + count: 2, + variants: [ + { id: Number(variantList[1]), title: 'Two Sum', note: '', status: 'DRAFT' }, + { id: 12, title: 'Two Sum — variant 1', note: '', status: 'DRAFT' }, + ], + }); + return; + } + const attachments = path.match(/^\/api\/v1\/problems\/problems\/(\d+)\/attachments\/$/); + if (attachments) { + if (req.method === 'GET') { + json(res, 200, { count: 1, results: MOCK_ATTACHMENTS }); + return; + } + if (req.method === 'POST') { + readBody(req, (body) => { + json(res, 201, { + id: 2, + name: body.name ?? '', + kind: body.kind ?? 'inline', + size_bytes: 4, + url: '/media/mock', + uploaded_at: new Date().toISOString(), + }); + }); + return; + } + } + // ---- Wave F recognition (items 66-69) ---- if (path === '/api/v1/community/reputation/me/') { if (!sessionUser(req)) { diff --git a/e2e/wave-f-tools.spec.ts b/e2e/wave-f-tools.spec.ts new file mode 100644 index 00000000..1f66b73d --- /dev/null +++ b/e2e/wave-f-tools.spec.ts @@ -0,0 +1,42 @@ +import { test, expect } from '@playwright/test'; + +// Wave F items 122/126/128 (mock mode): the author tools page — DSL +// generator run, variant spawn + family list, attachment upload. + +async function login(page: import('@playwright/test').Page) { + await page.goto('/login'); + await page.fill('#login-username', 'e2e_tester'); + await page.fill('#login-password', 'correct-horse-battery-staple'); + await page.getByRole('button', { name: 'Login', exact: true }).click(); + await expect(page.getByText('e2e_tester', { exact: true })).toBeVisible(); +} + +test.describe('wave F author tools (mock api)', () => { + test('generator: DSL run reports created count + first input', async ({ page }) => { + await login(page); + await page.goto('/author/tools'); + await page.getByTestId('tools-problem-input').fill('9'); + await page.getByTestId('tools-generate').click(); + await expect(page.getByTestId('tools-message')).toContainText('42 7'); + }); + + test('variants: spawn then family list renders both rows', async ({ page }) => { + await login(page); + await page.goto('/author/tools'); + await page.getByTestId('tools-problem-input').fill('9'); + await page.getByTestId('tools-spawn-variant').click(); + await expect(page.getByTestId('tools-message')).toContainText('#12'); + await expect(page.getByTestId('variant-row-9')).toContainText('Two Sum'); + await expect(page.getByTestId('variant-row-12')).toContainText('variant 1'); + }); + + test('attachments: upload then the list shows the file', async ({ page }) => { + await login(page); + await page.goto('/author/tools'); + await page.getByTestId('tools-problem-input').fill('9'); + await expect(page.getByTestId('attachment-row-1')).toContainText('figure.png'); + await page.getByTestId('tools-attachment-name').fill('chart.png'); + await page.getByTestId('tools-attachment-upload').click(); + await expect(page.getByTestId('tools-message')).toContainText('chart.png'); + }); +}); diff --git a/public/locales/ar.json b/public/locales/ar.json index 1a88fecf..3cc8f26d 100644 --- a/public/locales/ar.json +++ b/public/locales/ar.json @@ -1544,5 +1544,23 @@ "requests_empty": "لا طلبات بعد", "requests_empty_hint": "صوّت للمسائل التي تريد رؤيتها — المؤلفون يراقبون هذه اللوحة.", "amas_subtitle": "أسئلة وأجوبة مع الحاصلين على ميداليات، لوحة طلبات المسائل وسمعتك.", - "nav_amas": "المجتمع" + "nav_amas": "المجتمع", + "tools_title": "أدوات المؤلف", + "tools_subtitle": "مولدات الاختبار وعائلات المتغيرات والمرفقات.", + "tools_creators_only": "هذه الأدوات لمؤلفي المسائل والمدققين.", + "gen_title": "مولد حالات الاختبار (DSL)", + "gen_run": "أنشئ اختبارات", + "gen_created": "تم إنشاء {{count}} اختبارًا؛ المدخل الأول: {{first}}", + "variants_title": "عائلة المتغيرات", + "variants_spawn": "أنشئ متغيرًا", + "variant_spawned": "تم إنشاء المتغير #{{id}}", + "variants_empty": "لا متغيرات بعد.", + "attachments_title": "مرفقات نص المسألة", + "attachments_upload": "ارفع", + "attachments_name": "اسم الملف", + "attachments_empty": "لا مرفقات بعد.", + "attachment_uploaded": "تم رفع {{name}}", + "wizard_problem_id": "معرف المسألة المسودة (اختياري)", + "nav_author_tools": "أدوات المؤلف", + "nav_author_wizard": "معالج التأليف" } diff --git a/public/locales/bg.json b/public/locales/bg.json index 5750fcb1..4face196 100644 --- a/public/locales/bg.json +++ b/public/locales/bg.json @@ -1544,5 +1544,23 @@ "requests_empty": "Още няма заявки", "requests_empty_hint": "Гласувайте за задачите, които искате да видите — авторите следят тази дъска.", "amas_subtitle": "AMA с медалисти, дъската със заявки за задачи и вашата репутация.", - "nav_amas": "Общност" + "nav_amas": "Общност", + "tools_title": "Инструменти за автор", + "tools_subtitle": "Генератори за тестове, семейства варианти и прикачени файлове.", + "tools_creators_only": "Тези инструменти са за създатели и проверители.", + "gen_title": "Генератор на тестове (DSL)", + "gen_run": "Генерирай тестове", + "gen_created": "Създадени тестове: {{count}}; първи вход: {{first}}", + "variants_title": "Семейство варианти", + "variants_spawn": "Създай вариант", + "variant_spawned": "Вариант #{{id}} създаден", + "variants_empty": "Още няма варианти.", + "attachments_title": "Прикачени файлове към условието", + "attachments_upload": "Качи", + "attachments_name": "Име на файла", + "attachments_empty": "Още няма прикачени файлове.", + "attachment_uploaded": "{{name}} качен", + "wizard_problem_id": "Id на черновата (по избор)", + "nav_author_tools": "Инструменти за автор", + "nav_author_wizard": "Помощник за създаване" } diff --git a/public/locales/ca.json b/public/locales/ca.json index 844dc6f5..52b2235c 100644 --- a/public/locales/ca.json +++ b/public/locales/ca.json @@ -1544,5 +1544,23 @@ "requests_empty": "Encara no hi ha sol·licituds", "requests_empty_hint": "Vota els problemes que vols veure — els autors miren aquest tauler.", "amas_subtitle": "AMAs amb medallistes, el tauler de sol·licituds i la teva reputació.", - "nav_amas": "Comunitat" + "nav_amas": "Comunitat", + "tools_title": "Eines d'autor", + "tools_subtitle": "Generadors de proves, famílies de variants i adjunts.", + "tools_creators_only": "Aquestes eines són per a creadors i verificadors.", + "gen_title": "Generador de proves (DSL)", + "gen_run": "Genera proves", + "gen_created": "{{count}} proves creades; primera entrada: {{first}}", + "variants_title": "Família de variants", + "variants_spawn": "Crea variant", + "variant_spawned": "Variant #{{id}} creat", + "variants_empty": "Encara no hi ha variants.", + "attachments_title": "Adjunts de l'enunciat", + "attachments_upload": "Puja", + "attachments_name": "Nom del fitxer", + "attachments_empty": "Encara no hi ha adjunts.", + "attachment_uploaded": "{{name}} pujat", + "wizard_problem_id": "Id de l'esborrany (opcional)", + "nav_author_tools": "Eines d'autor", + "nav_author_wizard": "Assistent de creació" } diff --git a/public/locales/de.json b/public/locales/de.json index c4c645cc..f67fac6e 100644 --- a/public/locales/de.json +++ b/public/locales/de.json @@ -1544,5 +1544,23 @@ "requests_empty": "Noch keine Anfragen", "requests_empty_hint": "Stimme für die Aufgaben ab, die du sehen willst — Autoren beobachten dieses Brett.", "amas_subtitle": "AMAs mit Medaillengewinnern, das Aufgabenwunsch-Brett und deine Reputation.", - "nav_amas": "Community" + "nav_amas": "Community", + "tools_title": "Autoren-Tools", + "tools_subtitle": "Testgeneratoren, Variantenfamilien und Anhänge.", + "tools_creators_only": "Diese Tools sind für Autoren und Verifizierer.", + "gen_title": "Testgenerator (DSL)", + "gen_run": "Tests generieren", + "gen_created": "{{count}} Tests erstellt; erste Eingabe: {{first}}", + "variants_title": "Variantenfamilie", + "variants_spawn": "Variante erzeugen", + "variant_spawned": "Variante #{{id}} erstellt", + "variants_empty": "Noch keine Varianten.", + "attachments_title": "Aufgabenanhänge", + "attachments_upload": "Hochladen", + "attachments_name": "Dateiname", + "attachments_empty": "Noch keine Anhänge.", + "attachment_uploaded": "{{name}} hochgeladen", + "wizard_problem_id": "Entwurfs-ID (optional)", + "nav_author_tools": "Autoren-Tools", + "nav_author_wizard": "Autoren-Assistent" } diff --git a/public/locales/el.json b/public/locales/el.json index 4bc83b30..90619968 100644 --- a/public/locales/el.json +++ b/public/locales/el.json @@ -1544,5 +1544,23 @@ "requests_empty": "Κανένα αίτημα ακόμη", "requests_empty_hint": "Ψηφίστε τις ασκήσεις που θέλετε να δείτε — οι συγγραφείς παρακολουθούν αυτό τον πίνακα.", "amas_subtitle": "AMA με νομισματούχους, ο πίνακας αιτημάτων ασκήσεων και η φήμη σας.", - "nav_amas": "Κοινότητα" + "nav_amas": "Κοινότητα", + "tools_title": "Εργαλεία συγγραφέα", + "tools_subtitle": "Γεννήτριες τεστ, οικογένειες παραλλαγών και συνημμένα.", + "tools_creators_only": "Αυτά τα εργαλεία είναι για συγγραφείς και ελεγκτές.", + "gen_title": "Γεννήτρια τεστ (DSL)", + "gen_run": "Δημιουργία τεστ", + "gen_created": "Δημιουργήθηκαν {{count}} τεστ· πρώτη είσοδος: {{first}}", + "variants_title": "Οικογένεια παραλλαγών", + "variants_spawn": "Δημιουργία παραλλαγής", + "variant_spawned": "Δημιουργήθηκε παραλλαγή #{{id}}", + "variants_empty": "Καμία παραλλαγή ακόμη.", + "attachments_title": "Συνημμένα εκφώνησης", + "attachments_upload": "Μεταφόρτωση", + "attachments_name": "Όνομα αρχείου", + "attachments_empty": "Κανένα συνημμένο ακόμη.", + "attachment_uploaded": "Μεταφορτώθηκε {{name}}", + "wizard_problem_id": "Id πρόχειρου (προαιρετικό)", + "nav_author_tools": "Εργαλεία συγγραφέα", + "nav_author_wizard": "Οδηγός δημιουργίας" } diff --git a/public/locales/en.json b/public/locales/en.json index 94ad094e..efe24e86 100644 --- a/public/locales/en.json +++ b/public/locales/en.json @@ -1544,5 +1544,23 @@ "requests_empty": "No requests yet", "requests_empty_hint": "Vote for the problems you want to see — authors watch this board.", "amas_subtitle": "AMAs with medalists, the problem-request board and your reputation.", - "nav_amas": "Community" + "nav_amas": "Community", + "tools_title": "Author tools", + "tools_subtitle": "Test generators, variant families and statement attachments.", + "tools_creators_only": "These tools are for problem creators and verifiers.", + "gen_title": "Testcase generator (DSL)", + "gen_run": "Generate tests", + "gen_created": "Created {{count}} tests; first input: {{first}}", + "variants_title": "Variant family", + "variants_spawn": "Spawn variant", + "variant_spawned": "Variant #{{id}} created", + "variants_empty": "No variants yet.", + "attachments_title": "Statement attachments", + "attachments_upload": "Upload", + "attachments_name": "File name", + "attachments_empty": "No attachments yet.", + "attachment_uploaded": "Uploaded {{name}}", + "wizard_problem_id": "Draft problem id (optional)", + "nav_author_tools": "Author tools", + "nav_author_wizard": "Authoring wizard" } diff --git a/public/locales/es.json b/public/locales/es.json index b32752c4..9d129c2b 100644 --- a/public/locales/es.json +++ b/public/locales/es.json @@ -1544,5 +1544,23 @@ "requests_empty": "Aún no hay solicitudes", "requests_empty_hint": "Vota por los problemas que quieres ver — los autores miran este tablero.", "amas_subtitle": "AMAs con medallistas, el tablero de solicitudes y tu reputación.", - "nav_amas": "Comunidad" + "nav_amas": "Comunidad", + "tools_title": "Herramientas de autor", + "tools_subtitle": "Generadores de pruebas, familias de variantes y adjuntos.", + "tools_creators_only": "Estas herramientas son para creadores y verificadores.", + "gen_title": "Generador de pruebas (DSL)", + "gen_run": "Generar pruebas", + "gen_created": "{{count}} pruebas creadas; primera entrada: {{first}}", + "variants_title": "Familia de variantes", + "variants_spawn": "Crear variante", + "variant_spawned": "Variante #{{id}} creada", + "variants_empty": "Aún no hay variantes.", + "attachments_title": "Adjuntos del enunciado", + "attachments_upload": "Subir", + "attachments_name": "Nombre del archivo", + "attachments_empty": "Aún no hay adjuntos.", + "attachment_uploaded": "Subido {{name}}", + "wizard_problem_id": "Id del borrador (opcional)", + "nav_author_tools": "Herramientas de autor", + "nav_author_wizard": "Asistente de creación" } diff --git a/public/locales/fa.json b/public/locales/fa.json index efce588b..2a32d0e9 100644 --- a/public/locales/fa.json +++ b/public/locales/fa.json @@ -1544,5 +1544,23 @@ "requests_empty": "هنوز درخواستی نیست", "requests_empty_hint": "برای مسئله‌هایی که می‌خواهید ببینید رأی دهید — نویسندگان این تابلو را دنبال می‌کنند.", "amas_subtitle": "AMA با مدال‌آوران، تابلوی درخواست مسئله و اعتبار شما.", - "nav_amas": "انجمن" + "nav_amas": "انجمن", + "tools_title": "ابزار نویسنده", + "tools_subtitle": "مولدهای تست، خانواده‌های واریانت و پیوست‌ها.", + "tools_creators_only": "این ابزارها برای نویسندگان و راستی‌آزمایان مسئله است.", + "gen_title": "مولد تست‌کیس (DSL)", + "gen_run": "تولید تست", + "gen_created": "{{count}} تست ساخته شد؛ ورودی اول: {{first}}", + "variants_title": "خانواده واریانت", + "variants_spawn": "ساخت واریانت", + "variant_spawned": "واریانت #{{id}} ساخته شد", + "variants_empty": "هنوز واریانتی نیست.", + "attachments_title": "پیوست‌های صورت مسئله", + "attachments_upload": "بارگذاری", + "attachments_name": "نام فایل", + "attachments_empty": "هنوز پیوستی نیست.", + "attachment_uploaded": "{{name}} بارگذاری شد", + "wizard_problem_id": "شناسه مسئله پیش‌نویس (اختیاری)", + "nav_author_tools": "ابزار نویسنده", + "nav_author_wizard": "ویزارد نگارش" } diff --git a/public/locales/fr.json b/public/locales/fr.json index dfcd411c..e6ac0c3a 100644 --- a/public/locales/fr.json +++ b/public/locales/fr.json @@ -1544,5 +1544,23 @@ "requests_empty": "Pas encore de demandes", "requests_empty_hint": "Votez pour les problèmes que vous voulez voir — les auteurs surveillent ce tableau.", "amas_subtitle": "AMA avec médaillés, le tableau des demandes et votre réputation.", - "nav_amas": "Communauté" + "nav_amas": "Communauté", + "tools_title": "Outils d'auteur", + "tools_subtitle": "Générateurs de tests, familles de variantes et pièces jointes.", + "tools_creators_only": "Ces outils sont pour les auteurs et vérificateurs.", + "gen_title": "Générateur de tests (DSL)", + "gen_run": "Générer des tests", + "gen_created": "{{count}} tests créés ; première entrée : {{first}}", + "variants_title": "Famille de variantes", + "variants_spawn": "Créer une variante", + "variant_spawned": "Variante #{{id}} créée", + "variants_empty": "Pas encore de variantes.", + "attachments_title": "Pièces jointes de l'énoncé", + "attachments_upload": "Téléverser", + "attachments_name": "Nom du fichier", + "attachments_empty": "Pas encore de pièces jointes.", + "attachment_uploaded": "{{name}} téléversé", + "wizard_problem_id": "Id du brouillon (optionnel)", + "nav_author_tools": "Outils d'auteur", + "nav_author_wizard": "Assistant de création" } diff --git a/public/locales/hi.json b/public/locales/hi.json index 14572195..30a60e02 100644 --- a/public/locales/hi.json +++ b/public/locales/hi.json @@ -1544,5 +1544,23 @@ "requests_empty": "अभी कोई अनुरोध नहीं", "requests_empty_hint": "जो प्रॉब्लम देखना चाहते हैं उनके लिए वोट करें — लेखक इस बोर्ड को देखते हैं।", "amas_subtitle": "पदक विजेताओं के AMA, प्रॉब्लम-अनुरोध बोर्ड और आपकी प्रतिष्ठा।", - "nav_amas": "समुदाय" + "nav_amas": "समुदाय", + "tools_title": "लेखक उपकरण", + "tools_subtitle": "टेस्ट जनरेटर, वैरिएंट परिवार और अनुलग्नक।", + "tools_creators_only": "ये उपकरण प्रॉब्लम लेखकों और सत्यापकों के लिए हैं।", + "gen_title": "टेस्टकेस जनरेटर (DSL)", + "gen_run": "टेस्ट जनरेट करें", + "gen_created": "{{count}} टेस्ट बनाए; पहला इनपुट: {{first}}", + "variants_title": "वैरिएंट परिवार", + "variants_spawn": "वैरिएंट बनाएँ", + "variant_spawned": "वैरिएंट #{{id}} बनाया गया", + "variants_empty": "अभी कोई वैरिएंट नहीं है।", + "attachments_title": "कथन अनुलग्नक", + "attachments_upload": "अपलोड करें", + "attachments_name": "फ़ाइल नाम", + "attachments_empty": "अभी कोई अनुलग्नक नहीं है।", + "attachment_uploaded": "{{name}} अपलोड हुआ", + "wizard_problem_id": "ड्राफ़्ट प्रॉब्लम आईडी (वैकल्पिक)", + "nav_author_tools": "लेखक उपकरण", + "nav_author_wizard": "रचना विज़ार्ड" } diff --git a/public/locales/hr.json b/public/locales/hr.json index 5d87aeb9..6da8e571 100644 --- a/public/locales/hr.json +++ b/public/locales/hr.json @@ -1544,5 +1544,23 @@ "requests_empty": "Još nema zahtjeva", "requests_empty_hint": "Glasaj za zadatke koje želiš vidjeti — autori prate ovu ploču.", "amas_subtitle": "AMA s osvajačima medalja, ploča zahtjeva i tvoja reputacija.", - "nav_amas": "Zajednica" + "nav_amas": "Zajednica", + "tools_title": "Alati autora", + "tools_subtitle": "Generatori testova, obitelji varijanti i privici.", + "tools_creators_only": "Ovi su alati za autore i verifikatore.", + "gen_title": "Generator testova (DSL)", + "gen_run": "Generiraj testove", + "gen_created": "Stvoreno {{count}} testova; prvi ulaz: {{first}}", + "variants_title": "Obitelj varijanti", + "variants_spawn": "Stvori varijantu", + "variant_spawned": "Varijanta #{{id}} stvorena", + "variants_empty": "Još nema varijanti.", + "attachments_title": "Privici teksta zadatka", + "attachments_upload": "Prenesi", + "attachments_name": "Naziv datoteke", + "attachments_empty": "Još nema privica.", + "attachment_uploaded": "{{name}} preneseno", + "wizard_problem_id": "Id nacrta (neobavezno)", + "nav_author_tools": "Alati autora", + "nav_author_wizard": "Čarobnjak za izradu" } diff --git a/public/locales/hu.json b/public/locales/hu.json index ac5bc656..28a165fc 100644 --- a/public/locales/hu.json +++ b/public/locales/hu.json @@ -1544,5 +1544,23 @@ "requests_empty": "Még nincs kérés", "requests_empty_hint": "Szavazz azokra a feladatokra, amelyeket látni akarsz — a szerzők figyelik ezt a táblát.", "amas_subtitle": "AMA-k érmesekkel, a feladatkérés-tábla és a reputációd.", - "nav_amas": "Közösség" + "nav_amas": "Közösség", + "tools_title": "Szerzői eszközök", + "tools_subtitle": "Tesztgenerátorok, variánscsaládok és mellékletek.", + "tools_creators_only": "Ezek az eszközök feladatszerzőknek és -ellenőröknek szólnak.", + "gen_title": "Tesztgenerátor (DSL)", + "gen_run": "Tesztek generálása", + "gen_created": "{{count}} teszt létrehozva; első bemenet: {{first}}", + "variants_title": "Variánscsalád", + "variants_spawn": "Variáns létrehozása", + "variant_spawned": "#{{id}} variáns létrehozva", + "variants_empty": "Még nincs variáns.", + "attachments_title": "Feladatszöveg-mellékletek", + "attachments_upload": "Feltöltés", + "attachments_name": "Fájlnév", + "attachments_empty": "Még nincs melléklet.", + "attachment_uploaded": "{{name}} feltöltve", + "wizard_problem_id": "Vázlat azonosító (opcionális)", + "nav_author_tools": "Szerzői eszközök", + "nav_author_wizard": "Szerzői varázsló" } diff --git a/public/locales/id.json b/public/locales/id.json index 4a85524f..0d43eaab 100644 --- a/public/locales/id.json +++ b/public/locales/id.json @@ -1544,5 +1544,23 @@ "requests_empty": "Belum ada permintaan", "requests_empty_hint": "Pilih soal yang ingin kamu lihat — penulis mengawasi papan ini.", "amas_subtitle": "AMA dengan peraih medali, papan permintaan soal, dan reputasimu.", - "nav_amas": "Komunitas" + "nav_amas": "Komunitas", + "tools_title": "Alat penulis", + "tools_subtitle": "Generator uji, keluarga varian, dan lampiran.", + "tools_creators_only": "Alat ini untuk pembuat dan verifikator soal.", + "gen_title": "Generator soal uji (DSL)", + "gen_run": "Buat uji", + "gen_created": "{{count}} uji dibuat; masukan pertama: {{first}}", + "variants_title": "Keluarga varian", + "variants_spawn": "Buat varian", + "variant_spawned": "Varian #{{id}} dibuat", + "variants_empty": "Belum ada varian.", + "attachments_title": "Lampiran soal", + "attachments_upload": "Unggah", + "attachments_name": "Nama berkas", + "attachments_empty": "Belum ada lampiran.", + "attachment_uploaded": "{{name}} diunggah", + "wizard_problem_id": "Id draf soal (opsional)", + "nav_author_tools": "Alat penulis", + "nav_author_wizard": "Wizard pembuatan" } diff --git a/public/locales/it.json b/public/locales/it.json index d5dce2ed..2ef87987 100644 --- a/public/locales/it.json +++ b/public/locales/it.json @@ -1544,5 +1544,23 @@ "requests_empty": "Ancora nessuna richiesta", "requests_empty_hint": "Vota i problemi che vuoi vedere — gli autori guardano questa bacheca.", "amas_subtitle": "AMA con medagliati, la bacheca delle richieste e la tua reputazione.", - "nav_amas": "Community" + "nav_amas": "Community", + "tools_title": "Strumenti autore", + "tools_subtitle": "Generatori di test, famiglie di varianti e allegati.", + "tools_creators_only": "Questi strumenti sono per autori e verificatori.", + "gen_title": "Generatore di test (DSL)", + "gen_run": "Genera test", + "gen_created": "{{count}} test creati; primo input: {{first}}", + "variants_title": "Famiglia di varianti", + "variants_spawn": "Crea variante", + "variant_spawned": "Variante #{{id}} creata", + "variants_empty": "Ancora nessuna variante.", + "attachments_title": "Allegati dell'enunciato", + "attachments_upload": "Carica", + "attachments_name": "Nome file", + "attachments_empty": "Ancora nessun allegato.", + "attachment_uploaded": "{{name}} caricato", + "wizard_problem_id": "Id della bozza (opzionale)", + "nav_author_tools": "Strumenti autore", + "nav_author_wizard": "Creazione guidata" } diff --git a/public/locales/ja.json b/public/locales/ja.json index a5b53249..57b939d4 100644 --- a/public/locales/ja.json +++ b/public/locales/ja.json @@ -1544,5 +1544,23 @@ "requests_empty": "まだリクエストはありません", "requests_empty_hint": "見たい問題に投票しよう — 作成者がこのボードをチェックしています。", "amas_subtitle": "メダリストAMA、問題リクエストボード、そしてあなたのレピュテーション。", - "nav_amas": "コミュニティ" + "nav_amas": "コミュニティ", + "tools_title": "作成ツール", + "tools_subtitle": "テストジェネレーター、バリアント族、添付ファイル。", + "tools_creators_only": "これらのツールは作成者と検証者向けです。", + "gen_title": "テストジェネレーター(DSL)", + "gen_run": "テストを生成", + "gen_created": "{{count}}件のテストを生成。最初の入力: {{first}}", + "variants_title": "バリアント族", + "variants_spawn": "バリアントを作成", + "variant_spawned": "バリアント #{{id}} を作成しました", + "variants_empty": "まだバリアントはありません。", + "attachments_title": "問題文の添付", + "attachments_upload": "アップロード", + "attachments_name": "ファイル名", + "attachments_empty": "まだ添付はありません。", + "attachment_uploaded": "{{name}} をアップロードしました", + "wizard_problem_id": "下書き問題ID(任意)", + "nav_author_tools": "作成ツール", + "nav_author_wizard": "作成ウィザード" } diff --git a/public/locales/kk.json b/public/locales/kk.json index a4b9d358..60ff6419 100644 --- a/public/locales/kk.json +++ b/public/locales/kk.json @@ -1544,5 +1544,23 @@ "requests_empty": "Әзірге сұраулар жоқ", "requests_empty_hint": "Көргіңіз келетін есептерге дауыс беріңіз — авторлар осы тақтаны бақылайды.", "amas_subtitle": "Медалистермен AMA, есеп сұраулар тақтасы және репутацияңыз.", - "nav_amas": "Қауымдастық" + "nav_amas": "Қауымдастық", + "tools_title": "Автор құралдары", + "tools_subtitle": "Тест генераторлары, вариант отбасылары және тіркемелер.", + "tools_creators_only": "Бұл құралдар авторлар мен тексерушілерге арналған.", + "gen_title": "Тест генераторы (DSL)", + "gen_run": "Тестерді генерациялау", + "gen_created": "{{count}} тест жасалды; алғашқы енгізу: {{first}}", + "variants_title": "Вариант отбасысы", + "variants_spawn": "Вариант жасау", + "variant_spawned": "#{{id}} варианты жасалды", + "variants_empty": "Әзірге варианттар жоқ.", + "attachments_title": "Шарт тіркемелері", + "attachments_upload": "Жүктеу", + "attachments_name": "Файл атауы", + "attachments_empty": "Әзірге тіркемелер жоқ.", + "attachment_uploaded": "{{name}} жүктелді", + "wizard_problem_id": "Нобай есеп id-і (міндетті емес)", + "nav_author_tools": "Автор құралдары", + "nav_author_wizard": "Құру шебері" } diff --git a/public/locales/ko.json b/public/locales/ko.json index d4ff9417..c313c7d0 100644 --- a/public/locales/ko.json +++ b/public/locales/ko.json @@ -1544,5 +1544,23 @@ "requests_empty": "아직 요청 없음", "requests_empty_hint": "보고 싶은 문제에 투표하세요 — 작성자들이 이 게시판을 지켜봅니다.", "amas_subtitle": "메달리스트 AMA, 문제 요청 게시판, 그리고 당신의 평판.", - "nav_amas": "커뮤니티" + "nav_amas": "커뮤니티", + "tools_title": "작성 도구", + "tools_subtitle": "테스트 생성기, 변형 패밀리, 첨부파일.", + "tools_creators_only": "이 도구는 문제 작성자와 검증자를 위한 것입니다.", + "gen_title": "테스트 생성기 (DSL)", + "gen_run": "테스트 생성", + "gen_created": "{{count}}개 테스트 생성; 첫 입력: {{first}}", + "variants_title": "변형 패밀리", + "variants_spawn": "변형 생성", + "variant_spawned": "변형 #{{id}} 생성됨", + "variants_empty": "아직 변형이 없습니다.", + "attachments_title": "지문 첨부파일", + "attachments_upload": "업로드", + "attachments_name": "파일 이름", + "attachments_empty": "아직 첨부파일이 없습니다.", + "attachment_uploaded": "{{name}} 업로드됨", + "wizard_problem_id": "초안 문제 ID (선택)", + "nav_author_tools": "작성 도구", + "nav_author_wizard": "출제 마법사" } diff --git a/public/locales/lt.json b/public/locales/lt.json index 5e3182e2..76ce42aa 100644 --- a/public/locales/lt.json +++ b/public/locales/lt.json @@ -1544,5 +1544,23 @@ "requests_empty": "Užklausų dar nėra", "requests_empty_hint": "Balsuokite už uždavinius, kuriuos norite matyti — autoriai stebi šią lentą.", "amas_subtitle": "AMA su medalininkais, uždavinių užklausų lenta ir jūsų reputacija.", - "nav_amas": "Bendruomenė" + "nav_amas": "Bendruomenė", + "tools_title": "Autoriaus įrankiai", + "tools_subtitle": "Testų generatoriai, variantų šeimos ir priedai.", + "tools_creators_only": "Šie įrankiai skirtas kūrėjams ir tikrintojams.", + "gen_title": "Testų generatorius (DSL)", + "gen_run": "Generuoti testus", + "gen_created": "Sukurta {{count}} testų; pirmoji įvestis: {{first}}", + "variants_title": "Variantų šeima", + "variants_spawn": "Sukurti variantą", + "variant_spawned": "Variantas #{{id}} sukurtas", + "variants_empty": "Variantų dar nėra.", + "attachments_title": "Sąlygos priedai", + "attachments_upload": "Įkelti", + "attachments_name": "Failo pavadinimas", + "attachments_empty": "Priedų dar nėra.", + "attachment_uploaded": "Įkelta {{name}}", + "wizard_problem_id": "Juodraščio id (neprivaloma)", + "nav_author_tools": "Autoriaus įrankiai", + "nav_author_wizard": "Kūrimo vedlys" } diff --git a/public/locales/nl.json b/public/locales/nl.json index 426be637..63947563 100644 --- a/public/locales/nl.json +++ b/public/locales/nl.json @@ -1544,5 +1544,23 @@ "requests_empty": "Nog geen verzoeken", "requests_empty_hint": "Stem op de problemen die je wilt zien — auteurs volgen dit bord.", "amas_subtitle": "AMA's met medaillewinnaars, het probleemverzoekbord en je reputatie.", - "nav_amas": "Community" + "nav_amas": "Community", + "tools_title": "Auteurshulpmiddelen", + "tools_subtitle": "Testgenerators, variantfamilies en bijlagen.", + "tools_creators_only": "Deze tools zijn voor auteurs en verificateurs.", + "gen_title": "Testgenerator (DSL)", + "gen_run": "Tests genereren", + "gen_created": "{{count}} tests gemaakt; eerste invoer: {{first}}", + "variants_title": "Variantfamilie", + "variants_spawn": "Variant maken", + "variant_spawned": "Variant #{{id}} aangemaakt", + "variants_empty": "Nog geen varianten.", + "attachments_title": "Statementbijlagen", + "attachments_upload": "Uploaden", + "attachments_name": "Bestandsnaam", + "attachments_empty": "Nog geen bijlagen.", + "attachment_uploaded": "{{name}} geüpload", + "wizard_problem_id": "Concept-id (optioneel)", + "nav_author_tools": "Auteurshulpmiddelen", + "nav_author_wizard": "Auteurswizard" } diff --git a/public/locales/pl.json b/public/locales/pl.json index 613365b8..f76847b7 100644 --- a/public/locales/pl.json +++ b/public/locales/pl.json @@ -1544,5 +1544,23 @@ "requests_empty": "Brak próśb", "requests_empty_hint": "Głosuj na zadania, które chcesz zobaczyć — autorzy obserwują tę tablicę.", "amas_subtitle": "AMA z medalistami, tablica próśb o zadania i twoja reputacja.", - "nav_amas": "Społeczność" + "nav_amas": "Społeczność", + "tools_title": "Narzędzia autora", + "tools_subtitle": "Generatory testów, rodziny wariantów i załączniki.", + "tools_creators_only": "Te narzędzia są dla twórców i weryfikatorów.", + "gen_title": "Generator testów (DSL)", + "gen_run": "Generuj testy", + "gen_created": "Utworzono {{count}} testów; pierwsza dana: {{first}}", + "variants_title": "Rodzina wariantów", + "variants_spawn": "Utwórz wariant", + "variant_spawned": "Utworzono wariant #{{id}}", + "variants_empty": "Brak wariantów.", + "attachments_title": "Załączniki do treści", + "attachments_upload": "Prześlij", + "attachments_name": "Nazwa pliku", + "attachments_empty": "Brak załączników.", + "attachment_uploaded": "Przesłano {{name}}", + "wizard_problem_id": "Id szkicu (opcjonalnie)", + "nav_author_tools": "Narzędzia autora", + "nav_author_wizard": "Kreator tworzenia" } diff --git a/public/locales/pt.json b/public/locales/pt.json index b404365d..18165b41 100644 --- a/public/locales/pt.json +++ b/public/locales/pt.json @@ -1544,5 +1544,23 @@ "requests_empty": "Ainda sem pedidos", "requests_empty_hint": "Vote nos problemas que quer ver — os autores acompanham este quadro.", "amas_subtitle": "AMAs com medalhistas, o quadro de pedidos e sua reputação.", - "nav_amas": "Comunidade" + "nav_amas": "Comunidade", + "tools_title": "Ferramentas de autor", + "tools_subtitle": "Geradores de teste, famílias de variantes e anexos.", + "tools_creators_only": "Estas ferramentas são para criadores e verificadores.", + "gen_title": "Gerador de testes (DSL)", + "gen_run": "Gerar testes", + "gen_created": "{{count}} testes criados; primeira entrada: {{first}}", + "variants_title": "Família de variantes", + "variants_spawn": "Criar variante", + "variant_spawned": "Variante #{{id}} criada", + "variants_empty": "Ainda sem variantes.", + "attachments_title": "Anexos do enunciado", + "attachments_upload": "Enviar", + "attachments_name": "Nome do arquivo", + "attachments_empty": "Ainda sem anexos.", + "attachment_uploaded": "{{name}} enviado", + "wizard_problem_id": "Id do rascunho (opcional)", + "nav_author_tools": "Ferramentas de autor", + "nav_author_wizard": "Assistente de criação" } diff --git a/public/locales/ro.json b/public/locales/ro.json index 5aa5b9bb..49281592 100644 --- a/public/locales/ro.json +++ b/public/locales/ro.json @@ -1544,5 +1544,23 @@ "requests_empty": "Nicio cerere încă", "requests_empty_hint": "Votează problemele pe care vrei să le vezi — autorii urmăresc acest tabel.", "amas_subtitle": "AMA-uri cu medaliați, tabelul de cereri de probleme și reputația ta.", - "nav_amas": "Comunitate" + "nav_amas": "Comunitate", + "tools_title": "Unelte autor", + "tools_subtitle": "Generatoare de teste, familii de variante și atașamente.", + "tools_creators_only": "Aceste unelte sunt pentru creatorii și verificatorii de probleme.", + "gen_title": "Generator de teste (DSL)", + "gen_run": "Generează teste", + "gen_created": "Am creat {{count}} teste; primul input: {{first}}", + "variants_title": "Familie de variante", + "variants_spawn": "Creează variantă", + "variant_spawned": "Varianta #{{id}} creată", + "variants_empty": "Nicio variantă încă.", + "attachments_title": "Atașamente enunț", + "attachments_upload": "Încarcă", + "attachments_name": "Nume fișier", + "attachments_empty": "Niciun atașament încă.", + "attachment_uploaded": "Încărcat {{name}}", + "wizard_problem_id": "Id-ul problemei ciornă (opțional)", + "nav_author_tools": "Unelte autor", + "nav_author_wizard": "Asistent de creare" } diff --git a/public/locales/ru.json b/public/locales/ru.json index 3538244d..73055424 100644 --- a/public/locales/ru.json +++ b/public/locales/ru.json @@ -1544,5 +1544,23 @@ "requests_empty": "Запросов пока нет", "requests_empty_hint": "Голосуйте за задачи, которые хотите видеть — авторы следят за этой доской.", "amas_subtitle": "AMA с медалистами, доска запросов задач и ваша репутация.", - "nav_amas": "Сообщество" + "nav_amas": "Сообщество", + "tools_title": "Инструменты автора", + "tools_subtitle": "Генераторы тестов, семейства вариантов и вложения.", + "tools_creators_only": "Эти инструменты — для авторов и верификаторов.", + "gen_title": "Генератор тестов (DSL)", + "gen_run": "Сгенерировать тесты", + "gen_created": "Создано тестов: {{count}}; первая входная строка: {{first}}", + "variants_title": "Семейство вариантов", + "variants_spawn": "Создать вариант", + "variant_spawned": "Вариант #{{id}} создан", + "variants_empty": "Вариантов пока нет.", + "attachments_title": "Вложения к условию", + "attachments_upload": "Загрузить", + "attachments_name": "Имя файла", + "attachments_empty": "Вложений пока нет.", + "attachment_uploaded": "{{name}} загружен", + "wizard_problem_id": "Id черновика (необязательно)", + "nav_author_tools": "Инструменты автора", + "nav_author_wizard": "Мастер создания" } diff --git a/public/locales/sr-Latn.json b/public/locales/sr-Latn.json index 991b034e..a4c0d292 100644 --- a/public/locales/sr-Latn.json +++ b/public/locales/sr-Latn.json @@ -1544,5 +1544,23 @@ "requests_empty": "Još nema zahteva", "requests_empty_hint": "Glasaj za zadatke koje želiš da vidiš — autori prate ovu tablu.", "amas_subtitle": "AMA sa osvajačima medalja, tabla zahteva i tvoja reputacija.", - "nav_amas": "Zajednica" + "nav_amas": "Zajednica", + "tools_title": "Alati autora", + "tools_subtitle": "Generatori testova, porodice varijanti i prilozi.", + "tools_creators_only": "Ovi alati su za autore i verifikatore.", + "gen_title": "Generator testova (DSL)", + "gen_run": "Generiši testove", + "gen_created": "Napravljeno {{count}} testova; prvi ulaz: {{first}}", + "variants_title": "Porodica varijanti", + "variants_spawn": "Napravi varijantu", + "variant_spawned": "Varijanta #{{id}} napravljena", + "variants_empty": "Još nema varijanti.", + "attachments_title": "Prilozi teksta zadatka", + "attachments_upload": "Otpremi", + "attachments_name": "Naziv datoteke", + "attachments_empty": "Još nema priloga.", + "attachment_uploaded": "{{name}} otpremljeno", + "wizard_problem_id": "Id nacrta (neobavezno)", + "nav_author_tools": "Alati autora", + "nav_author_wizard": "Čarobnjak za izradu" } diff --git a/public/locales/th.json b/public/locales/th.json index 2fe0f207..34baf775 100644 --- a/public/locales/th.json +++ b/public/locales/th.json @@ -1544,5 +1544,23 @@ "requests_empty": "ยังไม่มีคำขอ", "requests_empty_hint": "โหวตให้โจทย์ที่คุณอยากเห็น — ผู้เขียนติดตามกระดานนี้", "amas_subtitle": "AMA กับผู้ได้เหรียญ กระดานขอโจทย์ และชื่อเสียงของคุณ", - "nav_amas": "ชุมชน" + "nav_amas": "ชุมชน", + "tools_title": "เครื่องมือผู้เขียน", + "tools_subtitle": "ตัวสร้างเทส ตระกูลรูปแบบ และไฟล์แนบ", + "tools_creators_only": "เครื่องมือเหล่านี้สำหรับผู้เขียนและผู้ตรวจโจทย์", + "gen_title": "ตัวสร้างเทสเคส (DSL)", + "gen_run": "สร้างเทส", + "gen_created": "สร้าง {{count}} เทส; อินพุตแรก: {{first}}", + "variants_title": "ตระกูลรูปแบบ", + "variants_spawn": "สร้างรูปแบบ", + "variant_spawned": "สร้างรูปแบบ #{{id}} แล้ว", + "variants_empty": "ยังไม่มีรูปแบบ", + "attachments_title": "ไฟล์แนบโจทย์", + "attachments_upload": "อัปโหลด", + "attachments_name": "ชื่อไฟล์", + "attachments_empty": "ยังไม่มีไฟล์แนบ", + "attachment_uploaded": "อัปโหลด {{name}} แล้ว", + "wizard_problem_id": "id ของโจทย์ร่าง (ไม่บังคับ)", + "nav_author_tools": "เครื่องมือผู้เขียน", + "nav_author_wizard": "วิซาร์ดสร้างโจทย์" } diff --git a/public/locales/tr.json b/public/locales/tr.json index 7e09e4a6..98699770 100644 --- a/public/locales/tr.json +++ b/public/locales/tr.json @@ -1544,5 +1544,23 @@ "requests_description_placeholder": "Problemi veya konuyu açıkla…", "requests_open": "İstek aç", "requests_loading": "İstekler yükleniyor…", - "requests_empty": "Henüz istek yok" + "requests_empty": "Henüz istek yok", + "tools_title": "Yazar araçları", + "tools_subtitle": "Test üreteçleri, varyant aileleri ve ekler.", + "tools_creators_only": "Bu araçlar problem yazarları ve doğrulayıcıları içindir.", + "gen_title": "Test üreteci (DSL)", + "gen_run": "Test üret", + "gen_created": "{{count}} test üretildi; ilk girdi: {{first}}", + "variants_title": "Varyant ailesi", + "variants_spawn": "Varyant oluştur", + "variant_spawned": "Varyant #{{id}} oluşturuldu", + "variants_empty": "Henüz varyant yok.", + "attachments_title": "Problem ekleri", + "attachments_upload": "Yükle", + "attachments_name": "Dosya adı", + "attachments_empty": "Henüz ek yok.", + "attachment_uploaded": "{{name}} yüklendi", + "wizard_problem_id": "Taslak problem kimliği (isteğe bağlı)", + "nav_author_tools": "Yazar araçları", + "nav_author_wizard": "Yazım sihirbazı" } diff --git a/public/locales/uk.json b/public/locales/uk.json index 96334e5c..d86c51c5 100644 --- a/public/locales/uk.json +++ b/public/locales/uk.json @@ -1544,5 +1544,23 @@ "requests_empty": "Запитів ще немає", "requests_empty_hint": "Голосуйте за задачі, які хочете бачити — автори стежать за цією дошкою.", "amas_subtitle": "AMA з медалістами, дошка запитів задач і ваша репутація.", - "nav_amas": "Спільнота" + "nav_amas": "Спільнота", + "tools_title": "Інструменти автора", + "tools_subtitle": "Генератори тестів, сімейства варіантів і вкладення.", + "tools_creators_only": "Ці інструменти — для авторів і верифікаторів.", + "gen_title": "Генератор тестів (DSL)", + "gen_run": "Згенерувати тести", + "gen_created": "Створено тестів: {{count}}; перший ввід: {{first}}", + "variants_title": "Сімейство варіантів", + "variants_spawn": "Створити варіант", + "variant_spawned": "Варіант #{{id}} створено", + "variants_empty": "Варіантів ще немає.", + "attachments_title": "Додатки до умови", + "attachments_upload": "Завантажити", + "attachments_name": "Назва файлу", + "attachments_empty": "Додатків ще немає.", + "attachment_uploaded": "{{name}} завантажено", + "wizard_problem_id": "Id чернетки (необов'язково)", + "nav_author_tools": "Інструменти автора", + "nav_author_wizard": "Майстер створення" } diff --git a/public/locales/vi.json b/public/locales/vi.json index 1ff9d4fe..945425b6 100644 --- a/public/locales/vi.json +++ b/public/locales/vi.json @@ -1544,5 +1544,23 @@ "requests_empty": "Chưa có yêu cầu", "requests_empty_hint": "Bầu chọn cho bài bạn muốn xem — tác giả theo dõi bảng này.", "amas_subtitle": "AMA với người đoạt huy chương, bảng yêu cầu bài tập và uy tín của bạn.", - "nav_amas": "Cộng đồng" + "nav_amas": "Cộng đồng", + "tools_title": "Công cụ tác giả", + "tools_subtitle": "Bộ tạo kiểm thử, họ biến thể và tệp đính kèm.", + "tools_creators_only": "Các công cụ này dành cho người soạn và kiểm duyệt.", + "gen_title": "Bộ tạo test (DSL)", + "gen_run": "Tạo test", + "gen_created": "Đã tạo {{count}} test; input đầu: {{first}}", + "variants_title": "Họ biến thể", + "variants_spawn": "Tạo biến thể", + "variant_spawned": "Đã tạo biến thể #{{id}}", + "variants_empty": "Chưa có biến thể nào.", + "attachments_title": "Tệp đính kèm đề bài", + "attachments_upload": "Tải lên", + "attachments_name": "Tên tệp", + "attachments_empty": "Chưa có tệp đính kèm nào.", + "attachment_uploaded": "Đã tải lên {{name}}", + "wizard_problem_id": "Id bản nháp (tùy chọn)", + "nav_author_tools": "Công cụ tác giả", + "nav_author_wizard": "Trình tạo bài" } diff --git a/public/locales/zh-Hans.json b/public/locales/zh-Hans.json index 622817e9..413ad6f8 100644 --- a/public/locales/zh-Hans.json +++ b/public/locales/zh-Hans.json @@ -1544,5 +1544,23 @@ "requests_empty": "还没有请求", "requests_empty_hint": "为你想见的题目投票——作者们关注这块板。", "amas_subtitle": "奖牌得主 AMA、题目请求板与你的声望。", - "nav_amas": "社区" + "nav_amas": "社区", + "tools_title": "作者工具", + "tools_subtitle": "测试生成器、变体家族与题面附件。", + "tools_creators_only": "这些工具面向题目作者与审核者。", + "gen_title": "测试用例生成器(DSL)", + "gen_run": "生成测试", + "gen_created": "已创建 {{count}} 个测试;首个输入:{{first}}", + "variants_title": "变体家族", + "variants_spawn": "生成变体", + "variant_spawned": "已创建变体 #{{id}}", + "variants_empty": "还没有变体。", + "attachments_title": "题面附件", + "attachments_upload": "上传", + "attachments_name": "文件名", + "attachments_empty": "还没有附件。", + "attachment_uploaded": "已上传 {{name}}", + "wizard_problem_id": "草稿题目编号(可选)", + "nav_author_tools": "作者工具", + "nav_author_wizard": "出题向导" } diff --git a/public/locales/zh-Hant.json b/public/locales/zh-Hant.json index 707bcb4c..8baca329 100644 --- a/public/locales/zh-Hant.json +++ b/public/locales/zh-Hant.json @@ -1544,5 +1544,23 @@ "requests_empty": "還沒有請求", "requests_empty_hint": "為你想見的題目投票——作者們關注這塊板。", "amas_subtitle": "獎牌得主 AMA、題目請求板與你的聲望。", - "nav_amas": "社群" + "nav_amas": "社群", + "tools_title": "作者工具", + "tools_subtitle": "測試產生器、變體家族與題面附件。", + "tools_creators_only": "這些工具面向題目作者與審核者。", + "gen_title": "測試案例產生器(DSL)", + "gen_run": "產生測試", + "gen_created": "已建立 {{count}} 個測試;首個輸入:{{first}}", + "variants_title": "變體家族", + "variants_spawn": "產生變體", + "variant_spawned": "已建立變體 #{{id}}", + "variants_empty": "還沒有變體。", + "attachments_title": "題面附件", + "attachments_upload": "上傳", + "attachments_name": "檔名", + "attachments_empty": "還沒有附件。", + "attachment_uploaded": "已上傳 {{name}}", + "wizard_problem_id": "草稿題目編號(可選)", + "nav_author_tools": "作者工具", + "nav_author_wizard": "出題精靈" } diff --git a/scripts/add-wave-f8-keys.py b/scripts/add-wave-f8-keys.py new file mode 100644 index 00000000..8adf1da4 --- /dev/null +++ b/scripts/add-wave-f8-keys.py @@ -0,0 +1,522 @@ +# One-shot: add the wave-F authoring-ops key family (items 122/126/128) +# to every locale catalog. tr.json patched surgically (CRLF file). +import json +import pathlib +import subprocess + +ROOT = pathlib.Path(__file__).resolve().parent.parent +LOCALES = ROOT / "src" / "locales" + +K = { + "tools_title": { + "en": "Author tools", + "ro": "Unelte autor", + "es": "Herramientas de autor", + "fr": "Outils d'auteur", + "de": "Autoren-Tools", + "pt": "Ferramentas de autor", + "it": "Strumenti autore", + "ca": "Eines d'autor", + "nl": "Auteurshulpmiddelen", + "pl": "Narzędzia autora", + "hu": "Szerzői eszközök", + "hr": "Alati autora", + "sr-Latn": "Alati autora", + "lt": "Autoriaus įrankiai", + "ru": "Инструменты автора", + "uk": "Інструменти автора", + "bg": "Инструменти за автор", + "el": "Εργαλεία συγγραφέα", + "zh-Hans": "作者工具", + "zh-Hant": "作者工具", + "ja": "作成ツール", + "ko": "작성 도구", + "hi": "लेखक उपकरण", + "vi": "Công cụ tác giả", + "th": "เครื่องมือผู้เขียน", + "id": "Alat penulis", + "tr": "Yazar araçları", + "kk": "Автор құралдары", + "ar": "أدوات المؤلف", + "fa": "ابزار نویسنده", + }, + "tools_subtitle": { + "en": "Test generators, variant families and statement attachments.", + "ro": "Generatoare de teste, familii de variante și atașamente.", + "es": "Generadores de pruebas, familias de variantes y adjuntos.", + "fr": "Générateurs de tests, familles de variantes et pièces jointes.", + "de": "Testgeneratoren, Variantenfamilien und Anhänge.", + "pt": "Geradores de teste, famílias de variantes e anexos.", + "it": "Generatori di test, famiglie di varianti e allegati.", + "ca": "Generadors de proves, famílies de variants i adjunts.", + "nl": "Testgenerators, variantfamilies en bijlagen.", + "pl": "Generatory testów, rodziny wariantów i załączniki.", + "hu": "Tesztgenerátorok, variánscsaládok és mellékletek.", + "hr": "Generatori testova, obitelji varijanti i privici.", + "sr-Latn": "Generatori testova, porodice varijanti i prilozi.", + "lt": "Testų generatoriai, variantų šeimos ir priedai.", + "ru": "Генераторы тестов, семейства вариантов и вложения.", + "uk": "Генератори тестів, сімейства варіантів і вкладення.", + "bg": "Генератори за тестове, семейства варианти и прикачени файлове.", + "el": "Γεννήτριες τεστ, οικογένειες παραλλαγών και συνημμένα.", + "zh-Hans": "测试生成器、变体家族与题面附件。", + "zh-Hant": "測試產生器、變體家族與題面附件。", + "ja": "テストジェネレーター、バリアント族、添付ファイル。", + "ko": "테스트 생성기, 변형 패밀리, 첨부파일.", + "hi": "टेस्ट जनरेटर, वैरिएंट परिवार और अनुलग्नक।", + "vi": "Bộ tạo kiểm thử, họ biến thể và tệp đính kèm.", + "th": "ตัวสร้างเทส ตระกูลรูปแบบ และไฟล์แนบ", + "id": "Generator uji, keluarga varian, dan lampiran.", + "tr": "Test üreteçleri, varyant aileleri ve ekler.", + "kk": "Тест генераторлары, вариант отбасылары және тіркемелер.", + "ar": "مولدات الاختبار وعائلات المتغيرات والمرفقات.", + "fa": "مولدهای تست، خانواده‌های واریانت و پیوست‌ها.", + }, + "tools_creators_only": { + "en": "These tools are for problem creators and verifiers.", + "ro": "Aceste unelte sunt pentru creatorii și verificatorii de probleme.", + "es": "Estas herramientas son para creadores y verificadores.", + "fr": "Ces outils sont pour les auteurs et vérificateurs.", + "de": "Diese Tools sind für Autoren und Verifizierer.", + "pt": "Estas ferramentas são para criadores e verificadores.", + "it": "Questi strumenti sono per autori e verificatori.", + "ca": "Aquestes eines són per a creadors i verificadors.", + "nl": "Deze tools zijn voor auteurs en verificateurs.", + "pl": "Te narzędzia są dla twórców i weryfikatorów.", + "hu": "Ezek az eszközök feladatszerzőknek és -ellenőröknek szólnak.", + "hr": "Ovi su alati za autore i verifikatore.", + "sr-Latn": "Ovi alati su za autore i verifikatore.", + "lt": "Šie įrankiai skirtas kūrėjams ir tikrintojams.", + "ru": "Эти инструменты — для авторов и верификаторов.", + "uk": "Ці інструменти — для авторів і верифікаторів.", + "bg": "Тези инструменти са за създатели и проверители.", + "el": "Αυτά τα εργαλεία είναι για συγγραφείς και ελεγκτές.", + "zh-Hans": "这些工具面向题目作者与审核者。", + "zh-Hant": "這些工具面向題目作者與審核者。", + "ja": "これらのツールは作成者と検証者向けです。", + "ko": "이 도구는 문제 작성자와 검증자를 위한 것입니다.", + "hi": "ये उपकरण प्रॉब्लम लेखकों और सत्यापकों के लिए हैं।", + "vi": "Các công cụ này dành cho người soạn và kiểm duyệt.", + "th": "เครื่องมือเหล่านี้สำหรับผู้เขียนและผู้ตรวจโจทย์", + "id": "Alat ini untuk pembuat dan verifikator soal.", + "tr": "Bu araçlar problem yazarları ve doğrulayıcıları içindir.", + "kk": "Бұл құралдар авторлар мен тексерушілерге арналған.", + "ar": "هذه الأدوات لمؤلفي المسائل والمدققين.", + "fa": "این ابزارها برای نویسندگان و راستی‌آزمایان مسئله است.", + }, + "gen_title": { + "en": "Testcase generator (DSL)", + "ro": "Generator de teste (DSL)", + "es": "Generador de pruebas (DSL)", + "fr": "Générateur de tests (DSL)", + "de": "Testgenerator (DSL)", + "pt": "Gerador de testes (DSL)", + "it": "Generatore di test (DSL)", + "ca": "Generador de proves (DSL)", + "nl": "Testgenerator (DSL)", + "pl": "Generator testów (DSL)", + "hu": "Tesztgenerátor (DSL)", + "hr": "Generator testova (DSL)", + "sr-Latn": "Generator testova (DSL)", + "lt": "Testų generatorius (DSL)", + "ru": "Генератор тестов (DSL)", + "uk": "Генератор тестів (DSL)", + "bg": "Генератор на тестове (DSL)", + "el": "Γεννήτρια τεστ (DSL)", + "zh-Hans": "测试用例生成器(DSL)", + "zh-Hant": "測試案例產生器(DSL)", + "ja": "テストジェネレーター(DSL)", + "ko": "테스트 생성기 (DSL)", + "hi": "टेस्टकेस जनरेटर (DSL)", + "vi": "Bộ tạo test (DSL)", + "th": "ตัวสร้างเทสเคส (DSL)", + "id": "Generator soal uji (DSL)", + "tr": "Test üreteci (DSL)", + "kk": "Тест генераторы (DSL)", + "ar": "مولد حالات الاختبار (DSL)", + "fa": "مولد تست‌کیس (DSL)", + }, + "gen_run": { + "en": "Generate tests", + "ro": "Generează teste", + "es": "Generar pruebas", + "fr": "Générer des tests", + "de": "Tests generieren", + "pt": "Gerar testes", + "it": "Genera test", + "ca": "Genera proves", + "nl": "Tests genereren", + "pl": "Generuj testy", + "hu": "Tesztek generálása", + "hr": "Generiraj testove", + "sr-Latn": "Generiši testove", + "lt": "Generuoti testus", + "ru": "Сгенерировать тесты", + "uk": "Згенерувати тести", + "bg": "Генерирай тестове", + "el": "Δημιουργία τεστ", + "zh-Hans": "生成测试", + "zh-Hant": "產生測試", + "ja": "テストを生成", + "ko": "테스트 생성", + "hi": "टेस्ट जनरेट करें", + "vi": "Tạo test", + "th": "สร้างเทส", + "id": "Buat uji", + "tr": "Test üret", + "kk": "Тестерді генерациялау", + "ar": "أنشئ اختبارات", + "fa": "تولید تست", + }, + "gen_created": { + "en": "Created {{count}} tests; first input: {{first}}", + "ro": "Am creat {{count}} teste; primul input: {{first}}", + "es": "{{count}} pruebas creadas; primera entrada: {{first}}", + "fr": "{{count}} tests créés ; première entrée : {{first}}", + "de": "{{count}} Tests erstellt; erste Eingabe: {{first}}", + "pt": "{{count}} testes criados; primeira entrada: {{first}}", + "it": "{{count}} test creati; primo input: {{first}}", + "ca": "{{count}} proves creades; primera entrada: {{first}}", + "nl": "{{count}} tests gemaakt; eerste invoer: {{first}}", + "pl": "Utworzono {{count}} testów; pierwsza dana: {{first}}", + "hu": "{{count}} teszt létrehozva; első bemenet: {{first}}", + "hr": "Stvoreno {{count}} testova; prvi ulaz: {{first}}", + "sr-Latn": "Napravljeno {{count}} testova; prvi ulaz: {{first}}", + "lt": "Sukurta {{count}} testų; pirmoji įvestis: {{first}}", + "ru": "Создано тестов: {{count}}; первая входная строка: {{first}}", + "uk": "Створено тестів: {{count}}; перший ввід: {{first}}", + "bg": "Създадени тестове: {{count}}; първи вход: {{first}}", + "el": "Δημιουργήθηκαν {{count}} τεστ· πρώτη είσοδος: {{first}}", + "zh-Hans": "已创建 {{count}} 个测试;首个输入:{{first}}", + "zh-Hant": "已建立 {{count}} 個測試;首個輸入:{{first}}", + "ja": "{{count}}件のテストを生成。最初の入力: {{first}}", + "ko": "{{count}}개 테스트 생성; 첫 입력: {{first}}", + "hi": "{{count}} टेस्ट बनाए; पहला इनपुट: {{first}}", + "vi": "Đã tạo {{count}} test; input đầu: {{first}}", + "th": "สร้าง {{count}} เทส; อินพุตแรก: {{first}}", + "id": "{{count}} uji dibuat; masukan pertama: {{first}}", + "tr": "{{count}} test üretildi; ilk girdi: {{first}}", + "kk": "{{count}} тест жасалды; алғашқы енгізу: {{first}}", + "ar": "تم إنشاء {{count}} اختبارًا؛ المدخل الأول: {{first}}", + "fa": "{{count}} تست ساخته شد؛ ورودی اول: {{first}}", + }, + "variants_title": { + "en": "Variant family", + "ro": "Familie de variante", + "es": "Familia de variantes", + "fr": "Famille de variantes", + "de": "Variantenfamilie", + "pt": "Família de variantes", + "it": "Famiglia di varianti", + "ca": "Família de variants", + "nl": "Variantfamilie", + "pl": "Rodzina wariantów", + "hu": "Variánscsalád", + "hr": "Obitelj varijanti", + "sr-Latn": "Porodica varijanti", + "lt": "Variantų šeima", + "ru": "Семейство вариантов", + "uk": "Сімейство варіантів", + "bg": "Семейство варианти", + "el": "Οικογένεια παραλλαγών", + "zh-Hans": "变体家族", + "zh-Hant": "變體家族", + "ja": "バリアント族", + "ko": "변형 패밀리", + "hi": "वैरिएंट परिवार", + "vi": "Họ biến thể", + "th": "ตระกูลรูปแบบ", + "id": "Keluarga varian", + "tr": "Varyant ailesi", + "kk": "Вариант отбасысы", + "ar": "عائلة المتغيرات", + "fa": "خانواده واریانت", + }, + "variants_spawn": { + "en": "Spawn variant", + "ro": "Creează variantă", + "es": "Crear variante", + "fr": "Créer une variante", + "de": "Variante erzeugen", + "pt": "Criar variante", + "it": "Crea variante", + "ca": "Crea variant", + "nl": "Variant maken", + "pl": "Utwórz wariant", + "hu": "Variáns létrehozása", + "hr": "Stvori varijantu", + "sr-Latn": "Napravi varijantu", + "lt": "Sukurti variantą", + "ru": "Создать вариант", + "uk": "Створити варіант", + "bg": "Създай вариант", + "el": "Δημιουργία παραλλαγής", + "zh-Hans": "生成变体", + "zh-Hant": "產生變體", + "ja": "バリアントを作成", + "ko": "변형 생성", + "hi": "वैरिएंट बनाएँ", + "vi": "Tạo biến thể", + "th": "สร้างรูปแบบ", + "id": "Buat varian", + "tr": "Varyant oluştur", + "kk": "Вариант жасау", + "ar": "أنشئ متغيرًا", + "fa": "ساخت واریانت", + }, + "variant_spawned": { + "en": "Variant #{{id}} created", + "ro": "Varianta #{{id}} creată", + "es": "Variante #{{id}} creada", + "fr": "Variante #{{id}} créée", + "de": "Variante #{{id}} erstellt", + "pt": "Variante #{{id}} criada", + "it": "Variante #{{id}} creata", + "ca": "Variant #{{id}} creat", + "nl": "Variant #{{id}} aangemaakt", + "pl": "Utworzono wariant #{{id}}", + "hu": "#{{id}} variáns létrehozva", + "hr": "Varijanta #{{id}} stvorena", + "sr-Latn": "Varijanta #{{id}} napravljena", + "lt": "Variantas #{{id}} sukurtas", + "ru": "Вариант #{{id}} создан", + "uk": "Варіант #{{id}} створено", + "bg": "Вариант #{{id}} създаден", + "el": "Δημιουργήθηκε παραλλαγή #{{id}}", + "zh-Hans": "已创建变体 #{{id}}", + "zh-Hant": "已建立變體 #{{id}}", + "ja": "バリアント #{{id}} を作成しました", + "ko": "변형 #{{id}} 생성됨", + "hi": "वैरिएंट #{{id}} बनाया गया", + "vi": "Đã tạo biến thể #{{id}}", + "th": "สร้างรูปแบบ #{{id}} แล้ว", + "id": "Varian #{{id}} dibuat", + "tr": "Varyant #{{id}} oluşturuldu", + "kk": "#{{id}} варианты жасалды", + "ar": "تم إنشاء المتغير #{{id}}", + "fa": "واریانت #{{id}} ساخته شد", + }, + "variants_empty": { + "en": "No variants yet.", + "ro": "Nicio variantă încă.", + "es": "Aún no hay variantes.", + "fr": "Pas encore de variantes.", + "de": "Noch keine Varianten.", + "pt": "Ainda sem variantes.", + "it": "Ancora nessuna variante.", + "ca": "Encara no hi ha variants.", + "nl": "Nog geen varianten.", + "pl": "Brak wariantów.", + "hu": "Még nincs variáns.", + "hr": "Još nema varijanti.", + "sr-Latn": "Još nema varijanti.", + "lt": "Variantų dar nėra.", + "ru": "Вариантов пока нет.", + "uk": "Варіантів ще немає.", + "bg": "Още няма варианти.", + "el": "Καμία παραλλαγή ακόμη.", + "zh-Hans": "还没有变体。", + "zh-Hant": "還沒有變體。", + "ja": "まだバリアントはありません。", + "ko": "아직 변형이 없습니다.", + "hi": "अभी कोई वैरिएंट नहीं है।", + "vi": "Chưa có biến thể nào.", + "th": "ยังไม่มีรูปแบบ", + "id": "Belum ada varian.", + "tr": "Henüz varyant yok.", + "kk": "Әзірге варианттар жоқ.", + "ar": "لا متغيرات بعد.", + "fa": "هنوز واریانتی نیست.", + }, + "attachments_title": { + "en": "Statement attachments", + "ro": "Atașamente enunț", + "es": "Adjuntos del enunciado", + "fr": "Pièces jointes de l'énoncé", + "de": "Aufgabenanhänge", + "pt": "Anexos do enunciado", + "it": "Allegati dell'enunciato", + "ca": "Adjunts de l'enunciat", + "nl": "Statementbijlagen", + "pl": "Załączniki do treści", + "hu": "Feladatszöveg-mellékletek", + "hr": "Privici teksta zadatka", + "sr-Latn": "Prilozi teksta zadatka", + "lt": "Sąlygos priedai", + "ru": "Вложения к условию", + "uk": "Додатки до умови", + "bg": "Прикачени файлове към условието", + "el": "Συνημμένα εκφώνησης", + "zh-Hans": "题面附件", + "zh-Hant": "題面附件", + "ja": "問題文の添付", + "ko": "지문 첨부파일", + "hi": "कथन अनुलग्नक", + "vi": "Tệp đính kèm đề bài", + "th": "ไฟล์แนบโจทย์", + "id": "Lampiran soal", + "tr": "Problem ekleri", + "kk": "Шарт тіркемелері", + "ar": "مرفقات نص المسألة", + "fa": "پیوست‌های صورت مسئله", + }, + "attachments_upload": { + "en": "Upload", + "ro": "Încarcă", + "es": "Subir", + "fr": "Téléverser", + "de": "Hochladen", + "pt": "Enviar", + "it": "Carica", + "ca": "Puja", + "nl": "Uploaden", + "pl": "Prześlij", + "hu": "Feltöltés", + "hr": "Prenesi", + "sr-Latn": "Otpremi", + "lt": "Įkelti", + "ru": "Загрузить", + "uk": "Завантажити", + "bg": "Качи", + "el": "Μεταφόρτωση", + "zh-Hans": "上传", + "zh-Hant": "上傳", + "ja": "アップロード", + "ko": "업로드", + "hi": "अपलोड करें", + "vi": "Tải lên", + "th": "อัปโหลด", + "id": "Unggah", + "tr": "Yükle", + "kk": "Жүктеу", + "ar": "ارفع", + "fa": "بارگذاری", + }, + "attachments_name": { + "en": "File name", + "ro": "Nume fișier", + "es": "Nombre del archivo", + "fr": "Nom du fichier", + "de": "Dateiname", + "pt": "Nome do arquivo", + "it": "Nome file", + "ca": "Nom del fitxer", + "nl": "Bestandsnaam", + "pl": "Nazwa pliku", + "hu": "Fájlnév", + "hr": "Naziv datoteke", + "sr-Latn": "Naziv datoteke", + "lt": "Failo pavadinimas", + "ru": "Имя файла", + "uk": "Назва файлу", + "bg": "Име на файла", + "el": "Όνομα αρχείου", + "zh-Hans": "文件名", + "zh-Hant": "檔名", + "ja": "ファイル名", + "ko": "파일 이름", + "hi": "फ़ाइल नाम", + "vi": "Tên tệp", + "th": "ชื่อไฟล์", + "id": "Nama berkas", + "tr": "Dosya adı", + "kk": "Файл атауы", + "ar": "اسم الملف", + "fa": "نام فایل", + }, + "attachments_empty": { + "en": "No attachments yet.", + "ro": "Niciun atașament încă.", + "es": "Aún no hay adjuntos.", + "fr": "Pas encore de pièces jointes.", + "de": "Noch keine Anhänge.", + "pt": "Ainda sem anexos.", + "it": "Ancora nessun allegato.", + "ca": "Encara no hi ha adjunts.", + "nl": "Nog geen bijlagen.", + "pl": "Brak załączników.", + "hu": "Még nincs melléklet.", + "hr": "Još nema privica.", + "sr-Latn": "Još nema priloga.", + "lt": "Priedų dar nėra.", + "ru": "Вложений пока нет.", + "uk": "Додатків ще немає.", + "bg": "Още няма прикачени файлове.", + "el": "Κανένα συνημμένο ακόμη.", + "zh-Hans": "还没有附件。", + "zh-Hant": "還沒有附件。", + "ja": "まだ添付はありません。", + "ko": "아직 첨부파일이 없습니다.", + "hi": "अभी कोई अनुलग्नक नहीं है।", + "vi": "Chưa có tệp đính kèm nào.", + "th": "ยังไม่มีไฟล์แนบ", + "id": "Belum ada lampiran.", + "tr": "Henüz ek yok.", + "kk": "Әзірге тіркемелер жоқ.", + "ar": "لا مرفقات بعد.", + "fa": "هنوز پیوستی نیست.", + }, + "attachment_uploaded": { + "en": "Uploaded {{name}}", + "ro": "Încărcat {{name}}", + "es": "Subido {{name}}", + "fr": "{{name}} téléversé", + "de": "{{name}} hochgeladen", + "pt": "{{name}} enviado", + "it": "{{name}} caricato", + "ca": "{{name}} pujat", + "nl": "{{name}} geüpload", + "pl": "Przesłano {{name}}", + "hu": "{{name}} feltöltve", + "hr": "{{name}} preneseno", + "sr-Latn": "{{name}} otpremljeno", + "lt": "Įkelta {{name}}", + "ru": "{{name}} загружен", + "uk": "{{name}} завантажено", + "bg": "{{name}} качен", + "el": "Μεταφορτώθηκε {{name}}", + "zh-Hans": "已上传 {{name}}", + "zh-Hant": "已上傳 {{name}}", + "ja": "{{name}} をアップロードしました", + "ko": "{{name}} 업로드됨", + "hi": "{{name}} अपलोड हुआ", + "vi": "Đã tải lên {{name}}", + "th": "อัปโหลด {{name}} แล้ว", + "id": "{{name}} diunggah", + "tr": "{{name}} yüklendi", + "kk": "{{name}} жүктелді", + "ar": "تم رفع {{name}}", + "fa": "{{name}} بارگذاری شد", + }, +} + +for path in sorted(LOCALES.glob("*.json")): + locale = path.stem + catalog = json.loads(path.read_text(encoding="utf-8")) + fresh = {} + for key, translations in K.items(): + if key not in catalog: + fresh[key] = translations.get(locale, translations["en"]) + if not fresh: + continue + if locale == "tr": + raw = subprocess.run( + ["git", "show", f"origin/main:{path.as_posix()}"], + capture_output=True, + check=True, + ).stdout.decode("utf-8") + block = ",\r\n".join( + f" {json.dumps(k, ensure_ascii=False)}: {json.dumps(v, ensure_ascii=False)}" + for k, v in fresh.items() + ) + body = raw.rstrip() + assert body.endswith("}") + inner = body[:-1].rstrip() + path.write_bytes((inner + ",\r\n" + block + "\r\n}\r\n").encode("utf-8")) + else: + catalog.update(fresh) + path.write_text( + json.dumps(catalog, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + print(f"updated {locale}") +print("done") diff --git a/src/app/author/tools/ToolsPage.test.tsx b/src/app/author/tools/ToolsPage.test.tsx new file mode 100644 index 00000000..481ac3f8 --- /dev/null +++ b/src/app/author/tools/ToolsPage.test.tsx @@ -0,0 +1,119 @@ +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react'; +import AuthorToolsPage from '@/app/author/tools/page'; +import type { User } from '@/types'; + +// Wave F items 122/126/128 — the author tools page. + +const api = vi.hoisted(() => ({ + generateTests: vi.fn(), + spawnVariant: vi.fn(), + listVariants: vi.fn(), + uploadAttachment: vi.fn(), + listAttachments: vi.fn(), +})); + +vi.mock('@/services/ApiService', () => ({ + ProblemService: api, +})); + +const mocks = vi.hoisted(() => ({ + auth: { + isAuthenticated: true, + user: { id: 1, username: 'author', email: 'a@x.com', role: 'PROBLEM_CREATOR' } as User | null, + login: vi.fn(), + logout: vi.fn(), + }, +})); + +vi.mock('@/context/AuthContext', () => ({ + useAuth: () => mocks.auth, + AuthContext: { + Provider: ({ children }: { children: React.ReactNode }) => children, + Consumer: ({ children }: { children: (value: unknown) => React.ReactNode }) => + children(mocks.auth), + _currentValue: mocks.auth, + }, +})); + +beforeEach(() => { + Object.values(api).forEach((fn) => fn.mockReset()); +}); + +afterEach(() => cleanup()); + +describe('AuthorToolsPage', () => { + it('runs the DSL generator and shows the first input', async () => { + api.generateTests.mockResolvedValue({ created: 5, first: '42 7' }); + render(); + fireEvent.change(screen.getByTestId('tools-problem-input'), { + target: { value: '9' }, + }); + await screen.findByTestId('tools-generate'); + fireEvent.click(screen.getByTestId('tools-generate')); + await waitFor(() => expect(api.generateTests).toHaveBeenCalledWith(9, expect.any(String))); + expect(screen.getByTestId('tools-message').textContent).toContain('42 7'); + }); + + it('surfaces DSL errors from the server', async () => { + api.generateTests.mockRejectedValue(new Error("line 1: cannot parse 'x'")); + render(); + fireEvent.change(screen.getByTestId('tools-problem-input'), { + target: { value: '9' }, + }); + fireEvent.click(screen.getByTestId('tools-generate')); + await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('cannot parse')); + }); + + it('spawns a variant and lists the family', async () => { + api.spawnVariant.mockResolvedValue({ variant_id: 12, root_id: 9, title: 'V' }); + api.listVariants.mockResolvedValue({ + root: 9, + count: 2, + variants: [ + { id: 9, title: 'Original', note: '', status: 'DRAFT' }, + { id: 12, title: 'Original — variant 1', note: '', status: 'DRAFT' }, + ], + }); + api.listAttachments.mockResolvedValue({ count: 0, results: [] }); + render(); + fireEvent.change(screen.getByTestId('tools-problem-input'), { + target: { value: '9' }, + }); + await screen.findByTestId('tools-spawn-variant'); + fireEvent.click(screen.getByTestId('tools-spawn-variant')); + await waitFor(() => expect(api.spawnVariant).toHaveBeenCalledWith(9)); + await waitFor(() => expect(screen.getByTestId('variant-row-12')).toBeTruthy()); + }); + + it('uploads an attachment and lists it', async () => { + api.uploadAttachment.mockResolvedValue({ id: 3, name: 'fig.png' }); + api.listVariants.mockResolvedValue({ root: 9, count: 1, variants: [] }); + api.listAttachments.mockResolvedValue({ + count: 1, + results: [{ id: 3, name: 'fig.png', kind: 'inline', size_bytes: 4, url: '/media/x' }], + }); + render(); + fireEvent.change(screen.getByTestId('tools-problem-input'), { + target: { value: '9' }, + }); + fireEvent.change(screen.getByTestId('tools-attachment-name'), { + target: { value: 'fig.png' }, + }); + fireEvent.click(screen.getByTestId('tools-attachment-upload')); + await waitFor(() => expect(api.uploadAttachment).toHaveBeenCalledWith(9, 'fig.png')); + await waitFor(() => expect(screen.getByTestId('attachment-row-3')).toBeTruthy()); + }); + + it('basic users get the creators-only note', () => { + mocks.auth.user = { id: 2, username: 'b', email: 'b@x.com', role: 'BASIC_USER' } as User; + render(); + expect(screen.getByText(/creators and verifiers/i)).toBeTruthy(); + mocks.auth.user = { + id: 1, + username: 'author', + email: 'a@x.com', + role: 'PROBLEM_CREATOR', + } as User; + }); +}); diff --git a/src/app/author/tools/page.tsx b/src/app/author/tools/page.tsx new file mode 100644 index 00000000..a950f709 --- /dev/null +++ b/src/app/author/tools/page.tsx @@ -0,0 +1,238 @@ +'use client'; + +import React, { useCallback, useEffect, useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { ProblemService } from '@/services/ApiService'; +import { useAuth } from '@/context/AuthContext'; +import { palette } from '@/theme/tokens'; +import PageHeader from '@/components/common/PageHeader'; + +/** + * Items 122/126/128 — the author tools: the testcase-generator DSL runner, + * variant-family spawning/browsing and statement attachments, all against + * one selected draft problem. + */ + +interface VariantRow { + id: number; + title: string; + note: string; + status: string; +} + +interface AttachmentRow { + id: number; + name: string; + kind: string; + size_bytes: number; + url: string; +} + +const SAMPLE_DSL = 'n = int(1, 100)\nq = int(1, 20)\nprint {n} {q}'; + +export default function AuthorToolsPage() { + const { t } = useTranslation(); + const auth = useAuth(); + const [problemId, setProblemId] = useState(''); + const [dsl, setDsl] = useState(SAMPLE_DSL); + const [message, setMessage] = useState(null); + const [error, setError] = useState(null); + const [variants, setVariants] = useState(null); + const [attachments, setAttachments] = useState(null); + const [fileName, setFileName] = useState(''); + const [busy, setBusy] = useState(false); + + const isAuthor = ['PROBLEM_CREATOR', 'PROBLEM_VERIFIER', 'TEACHER', 'ADMIN'].includes( + auth.user?.role ?? '', + ); + + const load = useCallback(async () => { + if (!problemId) { + setVariants(null); + setAttachments(null); + return; + } + const id = Number(problemId); + try { + const [family, files] = await Promise.all([ + ProblemService.listVariants(id).catch(() => null), + ProblemService.listAttachments(id).catch(() => null), + ]); + setVariants(family ? family.variants : null); + setAttachments(files ? files.results : null); + } catch (err) { + setError(err instanceof Error ? err.message : 'error'); + } + }, [problemId]); + + useEffect(() => { + if (isAuthor) load(); + }, [isAuthor, load]); + + const generateTests = async () => { + setBusy(true); + setMessage(null); + setError(null); + try { + const response = await ProblemService.generateTests(Number(problemId), dsl); + setMessage( + t('gen_created', 'Created {{count}} tests; first input: {{first}}', { + count: response.created, + first: response.first, + }), + ); + } catch (err) { + setError(err instanceof Error ? err.message : 'error'); + } finally { + setBusy(false); + } + }; + + const spawnVariant = async () => { + setBusy(true); + setMessage(null); + setError(null); + try { + const response = await ProblemService.spawnVariant(Number(problemId)); + setMessage(t('variant_spawned', 'Variant #{{id}} created', { id: response.variant_id })); + await load(); + } catch (err) { + setError(err instanceof Error ? err.message : 'error'); + } finally { + setBusy(false); + } + }; + + const uploadAttachment = async () => { + setBusy(true); + setMessage(null); + setError(null); + try { + const response = await ProblemService.uploadAttachment(Number(problemId), fileName); + setMessage(t('attachment_uploaded', 'Uploaded {{name}}', { name: response.name })); + setFileName(''); + await load(); + } catch (err) { + setError(err instanceof Error ? err.message : 'error'); + } finally { + setBusy(false); + } + }; + + if (!isAuthor) { + return ( +
+ +

+ {t('tools_creators_only', 'These tools are for problem creators and verifiers.')} +

+
+ ); + } + + return ( +
+ + setProblemId(e.target.value)} + placeholder={t('wizard_problem_id', 'Draft problem id (optional)')} + aria-label={t('wizard_problem_id', 'Draft problem id (optional)')} + style={{ width: 260, padding: 8, marginBottom: 12 }} + data-testid="tools-problem-input" + /> + {error && ( +

+ {error} +

+ )} + {message && ( +

+ {message} +

+ )} + +
+

{t('gen_title', 'Testcase generator (DSL)')}

+