Unit Content Validation on Word Import — Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Validate the structural correctness of every unidade (topics, objetiva, V/F, escrita) parsed from a discipline’s Word file before it is persisted, blocking the whole file’s processing and surfacing per-unidade errors on /disciplinas when anything is malformed.
Architecture: A pure, dependency-free validator class inspects the raw parser output (before it’s mapped into Value Objects, which is where missing markers get silently masked into false/zero defaults) and returns a flat list of formatted error strings. unit_create_service::execute() — the one place that actually persists unit_content from a Word import — runs this validator first, before its persist loop, and reuses its existing catch (Throwable) block (which already sets the discipline to Failed and writes error_message, both already surfaced on /disciplinas) by throwing when errors are found. The validation outcome is also recorded on the pre-existing but previously unwired file_word_validation entity.
Tech Stack: PHP 8.x, Moodle plugin (local_helico), PHPUnit (Moodle advanced_testcase for DB-backed tests, plain PHPUnit\Framework\TestCase for pure-logic tests).
Spec: docs/superpowers/specs/2026-08-27-unit-content-validation-design.md
Global Constraints
- Namespace mirrors file path per ADR-23 (
docs/plataforma/adrs/adr-23_convencao-file-layout-dominio.md) — new files go in the existingservice/kind dir of their subdomain. - Code identifiers, PHPDocs, and exception/log messages: English. User-facing validation error text (ends up in
error_message, shown on/disciplinas): pt-BR. - No inline comments except to explain a non-obvious WHY — this codebase’s default is not to comment.
- Pure-logic tests extend
PHPUnit\Framework\TestCasewith#[CoversClass(...)], no Moodle bootstrap. Tests touching items/DB extendadvanced_testcase, call$this->resetAfterTest(true)insetUp(), and carry#[Group('local_helico')]. - Test command:
../../vendor/bin/phpunit -c phpunit.xml --filter <TestClass>(run from the plugin root,moodle-local_helico/). - Git is read-only in this repo per project CLAUDE.md. Before running the
git commitin any task’s last step, stop and get the user’s explicit go-ahead (branchfeat/unit-content-validationalready exists with the design spec committed — reuse it, don’t create a new one). Do not batch multiple tasks’ commits without asking each time.
Task 1: unit_content_validator — structural validation rules
Files:
- Create:
classes/extensions/content/base/unit/unit_content/service/unit_content_validator.php - Test:
tests/extensions/content/base/unit/unit_content/service/unit_content_validator_test.php
Interfaces:
-
Produces:
unit_content_validator::validate_unidades(array $unidades): array— static method. Input is the raw parser output keyed by hour label (same shapeunit_json_engine::process_phpword()builds andfile_word_service::get_json_unidade_in_array()returns after the JSON round-trip): each entry has keystopic_content(list of{title, subtitle, summary, jurisprudence, notes}),question_truefalse({video, questions: list of {id, statement, comment, category, correctAnswer: ?bool}}),question_multichoice({video, questions: list of {id, statement, alternatives: list<string>, correctAnswer: string, category, comment}}),question_essay(list of{id, type, statement, correctionMirror, video, correctionParams: list of {title, autoAnswer, grade}}). Returnsarray<int, string>of messages formatted"Unidade {label}: {problema}"; empty array means everything passed. -
Step 1: Write the failing test
<?php
declare(strict_types=1);
/**
* HÉLICO Local
*
* @package local_helico
*
* @author Michael Meneses <michael@middag.com.br>
* @author Gabriel Sousa <gabriel.sousa@middag.com.br>
* @copyright 2026 MIDDAG (https://www.middag.com.br)
* @license commercial
*/
namespace local_helico\extensions\content\base\unit\unit_content\service;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;
defined('MOODLE_INTERNAL') || exit;
/**
* @internal
*/
#[CoversClass(unit_content_validator::class)]
final class unit_content_validator_test extends TestCase
{
public function test_valid_unidade_produces_no_errors(): void
{
$errors = unit_content_validator::validate_unidades([
'UNIDADE 1' => $this->valid_unidade(),
]);
$this->assertSame([], $errors);
}
public function test_topic_without_title_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['topic_content'][0]['title'] = '';
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Tópico sem título', $errors);
}
public function test_topic_without_summary_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['topic_content'][0]['summary'] = '<p></p>';
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Tópico sem conteúdo', $errors);
}
public function test_multichoice_without_statement_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['question_multichoice']['questions'][0]['statement'] = '';
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Questão objetiva sem enunciado', $errors);
}
public function test_multichoice_with_less_than_two_alternatives_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['question_multichoice']['questions'][0]['alternatives'] = ['Única opção'];
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Questão objetiva com menos de 2 alternativas', $errors);
}
public function test_multichoice_without_marked_answer_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['question_multichoice']['questions'][0]['correctAnswer'] = '';
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Questão objetiva sem resposta correta marcada', $errors);
}
public function test_multichoice_answer_out_of_range_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['question_multichoice']['questions'][0]['alternatives'] = ['A', 'B'];
$unidade['question_multichoice']['questions'][0]['correctAnswer'] = '5';
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains(
'Unidade UNIDADE 1: Questão objetiva com resposta apontando para alternativa inexistente',
$errors
);
}
public function test_truefalse_without_statement_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['question_truefalse']['questions'][0]['statement'] = '';
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Questão V/F sem enunciado', $errors);
}
public function test_truefalse_without_marked_answer_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['question_truefalse']['questions'][0]['correctAnswer'] = null;
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Questão V/F sem gabarito marcado', $errors);
}
public function test_essay_without_statement_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['question_essay'][0]['statement'] = '';
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Questão escrita sem enunciado', $errors);
}
public function test_essay_without_correction_params_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['question_essay'][0]['correctionParams'] = [];
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Questão escrita sem parâmetros de correção', $errors);
}
public function test_essay_with_unknown_type_is_flagged(): void
{
$unidade = $this->valid_unidade();
$unidade['question_essay'][0]['type'] = 'redacao_livre';
$errors = unit_content_validator::validate_unidades(['UNIDADE 1' => $unidade]);
$this->assertContains('Unidade UNIDADE 1: Questão escrita com tipo inválido', $errors);
}
public function test_errors_are_prefixed_with_the_hour_label_that_produced_them(): void
{
$broken = $this->valid_unidade();
$broken['topic_content'][0]['title'] = '';
$errors = unit_content_validator::validate_unidades([
'UNIDADE 1' => $this->valid_unidade(),
'UNIDADE 2' => $broken,
]);
$this->assertSame(['Unidade UNIDADE 2: Tópico sem título'], $errors);
}
/**
* @return array{
* topic_content: array<int, array{title: string, subtitle: string, summary: string, jurisprudence: string, notes: string}>,
* question_truefalse: array{video: string, questions: array<int, array{id: string, statement: string, comment: string, category: string, correctAnswer: bool}>},
* question_multichoice: array{video: string, questions: array<int, array{id: string, statement: string, alternatives: array<int, string>, correctAnswer: string, category: string, comment: string}>},
* question_essay: array<int, array{id: string, type: string, statement: string, correctionMirror: string, video: string, correctionParams: array<int, array{title: string, autoAnswer: string, grade: string}>}>,
* }
*/
private function valid_unidade(): array
{
return [
'topic_content' => [
[
'title' => 'Introdução',
'subtitle' => '',
'summary' => '<p>Conteúdo do tópico.</p>',
'jurisprudence' => '',
'notes' => '',
],
],
'question_truefalse' => [
'video' => '',
'questions' => [
[
'id' => 'U1_VF_Q1',
'statement' => '<p>Afirmação a julgar.</p>',
'comment' => '',
'category' => 'lei',
'correctAnswer' => true,
],
],
],
'question_multichoice' => [
'video' => '',
'questions' => [
[
'id' => 'U1_OBJ_Q1',
'statement' => '<p>Enunciado da questão.</p>',
'alternatives' => ['Opção A', 'Opção B', 'Opção C'],
'correctAnswer' => '1',
'category' => 'lei',
'comment' => '',
],
],
],
'question_essay' => [
[
'id' => 'U1_DISSERT_Q1',
'type' => 'dissertativa',
'statement' => '<p>Enunciado dissertativo.</p>',
'correctionMirror' => '',
'video' => '',
'correctionParams' => [
['title' => 'Critério 1', 'autoAnswer' => 'Resposta esperada', 'grade' => '2.0'],
],
],
],
];
}
}- Step 2: Run test to verify it fails
Run: ../../vendor/bin/phpunit -c phpunit.xml --filter unit_content_validator_test
Expected: FAIL/ERROR — Class "local_helico\extensions\content\base\unit\unit_content\service\unit_content_validator" not found
- Step 3: Write minimal implementation
<?php
declare(strict_types=1);
/**
* HÉLICO Local
*
* @package local_helico
*
* @author Michael Meneses <michael@middag.com.br>
* @author Gabriel Sousa <gabriel.sousa@middag.com.br>
* @copyright 2026 MIDDAG (https://www.middag.com.br)
* @license commercial
*/
namespace local_helico\extensions\content\base\unit\unit_content\service;
/**
* Validates the raw parser output of every unidade in a Word file before it
* is persisted as unit_content. Runs on the parser's raw arrays (not the
* mapped Value Objects) because a missing answer marker in the Word doc gets
* silently coerced by the VOs into a falsy default (0/false/'dissertative')
* rather than surfacing as an error — by the time a VO exists, the "it was
* missing" signal is already gone.
*/
final class unit_content_validator
{
private const WRITTEN_FORMATS = ['discursiva', 'dissertativa', 'discursive', 'peca_pratica'];
/**
* @param array<int|string, array{
* topic_content: array<int, array{title?: string, summary?: string}>,
* question_truefalse: array{questions: array<int, array{statement?: string, correctAnswer?: ?bool}>},
* question_multichoice: array{questions: array<int, array{statement?: string, alternatives?: array<int, string>, correctAnswer?: string}>},
* question_essay: array<int, array{statement?: string, correctionParams?: array, type?: string}>,
* }> $unidades
*
* @return array<int, string>
*/
public static function validate_unidades(array $unidades): array
{
$errors = [];
foreach ($unidades as $label => $unidade) {
foreach (self::validate_unidade((array) $unidade) as $message) {
$errors[] = sprintf('Unidade %s: %s', (string) $label, $message);
}
}
return $errors;
}
/**
* @return array<int, string>
*/
private static function validate_unidade(array $unidade): array
{
$errors = [];
foreach ($unidade['topic_content'] ?? [] as $topic) {
array_push($errors, ...self::validate_topic((array) $topic));
}
foreach ($unidade['question_truefalse']['questions'] ?? [] as $question) {
array_push($errors, ...self::validate_truefalse((array) $question));
}
foreach ($unidade['question_multichoice']['questions'] ?? [] as $question) {
array_push($errors, ...self::validate_multichoice((array) $question));
}
foreach ($unidade['question_essay'] ?? [] as $question) {
array_push($errors, ...self::validate_essay((array) $question));
}
return $errors;
}
/**
* @return array<int, string>
*/
private static function validate_topic(array $topic): array
{
$errors = [];
if (trim((string) ($topic['title'] ?? '')) === '') {
$errors[] = 'Tópico sem título';
}
if (trim(strip_tags((string) ($topic['summary'] ?? ''))) === '') {
$errors[] = 'Tópico sem conteúdo';
}
return $errors;
}
/**
* @return array<int, string>
*/
private static function validate_truefalse(array $question): array
{
$errors = [];
if (trim(strip_tags((string) ($question['statement'] ?? ''))) === '') {
$errors[] = 'Questão V/F sem enunciado';
}
if (($question['correctAnswer'] ?? null) === null) {
$errors[] = 'Questão V/F sem gabarito marcado';
}
return $errors;
}
/**
* @return array<int, string>
*/
private static function validate_multichoice(array $question): array
{
$errors = [];
if (trim(strip_tags((string) ($question['statement'] ?? ''))) === '') {
$errors[] = 'Questão objetiva sem enunciado';
}
$alternatives = $question['alternatives'] ?? [];
if (count($alternatives) < 2) {
$errors[] = 'Questão objetiva com menos de 2 alternativas';
}
$correct_answer = (string) ($question['correctAnswer'] ?? '');
if ($correct_answer === '') {
$errors[] = 'Questão objetiva sem resposta correta marcada';
} elseif ((int) $correct_answer >= count($alternatives)) {
$errors[] = 'Questão objetiva com resposta apontando para alternativa inexistente';
}
return $errors;
}
/**
* @return array<int, string>
*/
private static function validate_essay(array $question): array
{
$errors = [];
if (trim(strip_tags((string) ($question['statement'] ?? ''))) === '') {
$errors[] = 'Questão escrita sem enunciado';
}
if (($question['correctionParams'] ?? []) === []) {
$errors[] = 'Questão escrita sem parâmetros de correção';
}
$type = mb_strtolower((string) ($question['type'] ?? ''), 'UTF-8');
if ($type !== '' && !in_array($type, self::WRITTEN_FORMATS, true)) {
$errors[] = 'Questão escrita com tipo inválido';
}
return $errors;
}
}- Step 4: Run test to verify it passes
Run: ../../vendor/bin/phpunit -c phpunit.xml --filter unit_content_validator_test
Expected: PASS — 13 tests, 0 failures
- Step 5: Commit
Ask the user for explicit go-ahead first (project CLAUDE.md: git is read-only unless explicitly requested). On approval:
git add classes/extensions/content/base/unit/unit_content/service/unit_content_validator.php tests/extensions/content/base/unit/unit_content/service/unit_content_validator_test.php
git commit -m "feat: validate unidade content structure before persisting from Word import"Task 2: Wire validation into unit_create_service::execute()
Files:
- Modify:
classes/extensions/content/base/unit/service/unit_create_service.php:56-104(theexecute()method) - Test:
tests/extensions/content/base/unit/unit_create_service_test.php
Interfaces:
-
Consumes:
unit_content_validator::validate_unidades(array $unidades): arrayfrom Task 1. -
Consumes:
file_word_validation_service_interface::create(ItemDtoInterface $dto): ItemInterface(existing,classes/extensions/content/management/file_word/contract/file_word_validation_service_interface.php),file_word_validationmetadata fieldsfile_word_id,validation_status,errors,validated_at(existing,classes/extensions/content/management/file_word/entity/file_word_validation.php:27-32). -
Produces:
unit_create_service::execute()now throws (and is caught by its own existingcatch (Throwable)block) before persisting anything whenunit_content_validator::validate_unidades()returns a non-empty array. No new public interface — behavior change only. -
Step 1: Write the failing test
<?php
declare(strict_types=1);
/**
* HÉLICO Local
*
* @package local_helico
*
* @author Michael Meneses <michael@middag.com.br>
* @author Gabriel Sousa <gabriel.sousa@middag.com.br>
* @copyright 2026 MIDDAG (https://www.middag.com.br)
* @license commercial
*/
namespace local_helico\extensions\content\base\unit;
use local_middag\base\domain\item\item_dto;
defined('MOODLE_INTERNAL') || exit;
use advanced_testcase;
use local_helico\extensions\content\base\discipline\service\discipline_service;
use local_helico\extensions\content\base\unit\service\unit_create_service;
use local_helico\extensions\content\management\file_word\entity\file_word_validation;
use local_helico\extensions\content\management\file_word\service\file_word_service;
use local_middag\base\facade\query_executor;
use local_middag\middag;
use Middag\Core\Persistence\QueryEngine\MiddagItemQueryBuilder;
use Middag\Core\Shared\Enum\ItemStatus;
use Middag\Framework\Shared\Enum\Operator;
use PHPUnit\Framework\Attributes\Group;
#[Group('local_helico')]
final class unit_create_service_test extends advanced_testcase
{
private discipline_service $disciplina_service;
private file_word_service $file_service;
protected function setUp(): void
{
parent::setUp();
$this->resetAfterTest(true);
$this->disciplina_service = middag::get(discipline_service::class);
$this->file_service = middag::get(file_word_service::class);
}
public function test_execute_blocks_whole_file_and_reports_every_broken_unidade(): void
{
$discipline = $this->create_disciplina('SC_VAL_001', 'Validação');
$file = $this->create_disciplina_file($discipline);
$this->file_service->save_disciplina_json_file($file, json_encode([
'UNIDADE 1' => $this->valid_unidade(),
'UNIDADE 2' => $this->unidade_missing_multichoice_answer(),
], JSON_THROW_ON_ERROR));
$discipline = $this->disciplina_service->find_by_id((int) $discipline->getId());
unit_create_service::execute($discipline);
$refreshed = $this->disciplina_service->find_by_id((int) $discipline->getId());
$this->assertSame(ItemStatus::Failed->value, $refreshed->getStatus());
$this->assertStringContainsString(
'Unidade UNIDADE 2: Questão objetiva sem resposta correta marcada',
(string) $refreshed->getMeta('error_message')
);
$validations = $this->find_validations_for_file((int) $file->getId());
$this->assertCount(1, $validations);
$this->assertSame('invalid', $validations[0]->get_validation_status());
$this->assertStringContainsString(
'Unidade UNIDADE 2: Questão objetiva sem resposta correta marcada',
(string) $validations[0]->get_errors()
);
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
private function create_disciplina(string $idnumber, string $fullname): \Middag\Core\Domain\Item\Contract\ItemInterface
{
$dto = new item_dto(
fullname: $fullname,
idnumber: $idnumber,
metadata: [
'categoryname' => $fullname,
],
);
return $this->disciplina_service->create($dto);
}
private function create_disciplina_file(\Middag\Core\Domain\Item\Contract\ItemInterface $disciplina): \Middag\Core\Domain\Item\Contract\ItemInterface
{
$dto = item_dto::fromArray([
'fullname' => '[SC_VAL_001] Validação.docx',
'parent' => $disciplina->getId(),
'version' => '1',
'metadata' => [
'filetimecreated' => time(),
'filetimemodified' => time(),
],
]);
return $this->file_service->create($dto);
}
/**
* @return array<int, file_word_validation>
*/
private function find_validations_for_file(int $file_word_id): array
{
$query = MiddagItemQueryBuilder::make()
->where('type', Operator::Eq, file_word_validation::TYPE)
->withMetadata(file_word_validation::METADATA_FIELDS)
->domain(file_word_validation::class);
$result = query_executor::execute($query);
$validations = [];
foreach ($result->items() as $item) {
if ($item instanceof file_word_validation && $item->get_file_word_id() === $file_word_id) {
$validations[] = $item;
}
}
return $validations;
}
/**
* @return array<string, mixed>
*/
private function valid_unidade(): array
{
return [
'topic_content' => [
[
'title' => 'Introdução',
'subtitle' => '',
'summary' => '<p>Conteúdo do tópico.</p>',
'jurisprudence' => '',
'notes' => '',
],
],
'question_truefalse' => [
'video' => '',
'questions' => [
[
'id' => 'U1_VF_Q1',
'statement' => '<p>Afirmação a julgar.</p>',
'comment' => '',
'category' => 'lei',
'correctAnswer' => true,
],
],
],
'question_multichoice' => [
'video' => '',
'questions' => [
[
'id' => 'U1_OBJ_Q1',
'statement' => '<p>Enunciado da questão.</p>',
'alternatives' => ['Opção A', 'Opção B', 'Opção C'],
'correctAnswer' => '1',
'category' => 'lei',
'comment' => '',
],
],
],
'question_essay' => [
[
'id' => 'U1_DISSERT_Q1',
'type' => 'dissertativa',
'statement' => '<p>Enunciado dissertativo.</p>',
'correctionMirror' => '',
'video' => '',
'correctionParams' => [
['title' => 'Critério 1', 'autoAnswer' => 'Resposta esperada', 'grade' => '2.0'],
],
],
],
];
}
/**
* @return array<string, mixed>
*/
private function unidade_missing_multichoice_answer(): array
{
$unidade = $this->valid_unidade();
$unidade['question_multichoice']['questions'][0]['correctAnswer'] = '';
return $unidade;
}
}- Step 2: Run test to verify it fails
Run: ../../vendor/bin/phpunit -c phpunit.xml --filter unit_create_service_test
Expected: FAIL — discipline status is completed, not failed (validation isn’t wired in yet), and/or no file_word_validation record is found.
- Step 3: Wire the validator into
execute()
Add two use statements near the top of classes/extensions/content/base/unit/service/unit_create_service.php (after the existing use local_helico\extensions\content\base\unit\unit_content\contract\unit_content_service_interface; at line 30):
use local_helico\extensions\content\base\unit\unit_content\service\unit_content_validator;
use local_helico\extensions\content\management\file_word\contract\file_word_validation_service_interface;Replace the body of execute() (lines 56-104) with:
public static function execute(discipline|ItemInterface $helico_disciplina): array
{
$unidades = middag::get(file_word_service_interface::class)->get_json_unidade_in_array($helico_disciplina);
$helico_discipline_file = middag::get(file_word_service_interface::class)->get_last_helico_disciplina_file_version($helico_disciplina);
$changes = [];
$file_word_id = $helico_discipline_file instanceof file_word ? (int) $helico_discipline_file->getId() : null;
try {
$validation_errors = unit_content_validator::validate_unidades($unidades);
self::persist_validation_result($file_word_id, $validation_errors);
if ($validation_errors !== []) {
throw new Exception(implode("\n", $validation_errors));
}
$totals = self::total_unidade_content($unidades);
foreach ($unidades as $hour_label => $unidade) {
$result = self::persist($helico_disciplina, $hour_label, $unidade, $helico_discipline_file);
if (!is_array($result)) {
continue;
}
if ($result['unit'] instanceof unit) {
middag::get(unit_service_interface::class)->set_total_unidade_content($result['unit'], $totals);
}
if ($result['change'] !== null) {
$changes[] = $result['change'];
}
}
$helico_disciplina = middag::get(discipline_service_interface::class)->set_status($helico_disciplina, ItemStatus::Completed->value);
if ($helico_discipline_file instanceof file_word) {
$helico_discipline_file = middag::get(file_word_service_interface::class)->set_unidade_process_status($helico_discipline_file, ItemStatus::Completed->value);
$helico_discipline_file = middag::get(file_word_service_interface::class)->set_status($helico_discipline_file, ItemStatus::Completed->value);
}
$helico_disciplina = middag::get(discipline_service_interface::class)->set_lastprocessfile($helico_disciplina, time());
middag::get(discipline_service_interface::class)->set_error_message($helico_disciplina, '');
} catch (Throwable $throwable) {
$helico_disciplina = middag::get(discipline_service_interface::class)->set_status($helico_disciplina, ItemStatus::Failed->value);
middag::get(file_word_service_interface::class)->set_unidade_process_status($helico_discipline_file, ItemStatus::Failed->value);
middag::get(discipline_service_interface::class)->set_error_message($helico_disciplina, $throwable->getMessage());
sentry_service::debug($throwable, [
'message' => 'Error on persist unidades',
'idnumber' => $helico_disciplina->getIdnumber(),
]);
}
return [
'file_word_id' => $file_word_id,
'changes' => $changes,
];
}
/**
* Records the outcome of the pre-persist structural validation on the
* (previously unwired) file_word_validation entity, so failures are
* auditable even though the aggregated message already reaches the
* discipline's error_message.
*
* @param array<int, string> $errors
*/
private static function persist_validation_result(?int $file_word_id, array $errors): void
{
if ($file_word_id === null) {
return;
}
middag::get(file_word_validation_service_interface::class)->create(ItemDto::fromArray([
'fullname' => 'Validação de conteúdo #' . $file_word_id,
'metadata' => [
'file_word_id' => $file_word_id,
'validation_status' => $errors === [] ? 'valid' : 'invalid',
'errors' => json_encode($errors, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
'validated_at' => date(DATE_ATOM),
],
]));
}(Only execute()’s body and the new persist_validation_result() private method are added/changed — get_category_or_create(), create_unidade_content(), persist(), and everything below stay as-is.)
- Step 4: Run test to verify it passes
Run: ../../vendor/bin/phpunit -c phpunit.xml --filter unit_create_service_test
Expected: PASS
- Step 5: Run the full suite to check for regressions
Run: ../../vendor/bin/phpunit -c phpunit.xml
Expected: PASS (no pre-existing test exercises unit_create_service::execute()’s success path today, so none should be newly broken by this change; confirm no failures elsewhere in tests/extensions/content/).
- Step 6: Commit
Ask the user for explicit go-ahead first (project CLAUDE.md: git is read-only unless explicitly requested). On approval:
git add classes/extensions/content/base/unit/service/unit_create_service.php tests/extensions/content/base/unit/unit_create_service_test.php
git commit -m "feat: block Word import persistence when unidade content fails validation"Manual QA (after both tasks land)
- Take (or make) a Word file that follows
docs/operacao/tutoriais/importar-unidades-docx.md’s template, deliberately break one rule (e.g. delete aRESPOSTA:_Xmarker on one objetiva question). - Trigger the normal disciplina file upload + process flow (
register_start_process). - Confirm on
/disciplinas: the discipline showsFalhou/Failedstatus with the sublabel listingUnidade <label>: Questão objetiva sem resposta correta marcada. - Fix the Word file, re-upload, confirm the discipline reaches
Completedand the unit content is created normally.