Skip to content

Desempenho — Filtros Cruzados Implementation Plan

Desempenho — Filtros Cruzados 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: Habilitar os filtros cruzados (Módulo, Disciplina/Matéria, Fonte, Tipo de Simulado) em “Desempenho por Simulado”, “Desempenho por Tipo de Fonte” e “Desempenho por Disciplina”, e separar o Simulado Escrito em Discursiva/Dissertação/Peça Prática (hoje um balde único que atribui tudo a “Discursiva”).

Architecture: Backend (moodle-local_helico) ganha um novo campo breakdown[] (tabela de fatos plana, uma linha por combinação módulo×disciplina×tipo×fonte) no payload de GET /platform/study/{enrolment_id}/performance, calculado por um novo breakdown_calculator_service. by_module_calculator_service passa a separar o Simulado Escrito em subtipos. discipline_performance_calculator_service ganha module_id por linha. Frontend (app-helico) consome esses campos novos localmente em cada componente (sem generalizar um “filter engine” — YAGNI), mantendo a view padrão sem filtro exatamente como está hoje.

Tech Stack: PHP 8.3 (Moodle plugin, Symfony-style DI autowired por interface, PHPUnit), TypeScript/React (Next.js, Vitest + Testing Library).

Spec: docs/_archive/specs/2026-08-28-desempenho-filtros-cruzados-design.md

Global Constraints

  • Mudança aditiva no contrato de /performance — nenhum campo existente é removido ou renomeado.
  • Vocabulário de subtipo do Simulado Escrito: discursiva | dissertacao | peca_pratica (ADR-60/LinkML aprovado), lido de slot.context (ctx_subtype), default discursiva quando ausente.
  • Combinações de breakdown[] sem dado são omitidas — nunca score: null.
  • source ausente nas linhas de Simulado Escrito (exam_type começando com exam_written).
  • Nenhum commit deve ser feito além dos exigidos por cada step do plano (branches já criadas: feat/desempenho-filtros-cruzados em moodle-local_helico, feature/correction já ativa em app-helico — não criar branch nova lá).
  • Repos: /private/var/www/middag-work/moodle-local_helico (backend) e /private/var/www/app-helico (frontend).

File Structure

Backend (moodle-local_helico):

  • Modify: classes/extensions/metrics/consolidation/service/discipline_performance_calculator_service.php — ganha module_id por linha.
  • Modify: tests/extensions/metrics/consolidation/service/discipline_performance_calculator_service_test.php
  • Modify: classes/extensions/metrics/consolidation/service/by_module_calculator_service.php — separa Simulado Escrito em subtipos no by_exam_type[] aninhado.
  • Modify: tests/extensions/metrics/consolidation/service/by_module_calculator_service_test.php
  • Create: classes/extensions/metrics/consolidation/contract/breakdown_calculator_service_interface.php
  • Create: classes/extensions/metrics/consolidation/service/breakdown_calculator_service.php — novo calculator, tabela de fatos.
  • Create: tests/extensions/metrics/consolidation/service/breakdown_calculator_service_test.php
  • Modify: classes/extensions/metrics/consolidation/dto/consolidated_dashboard_dto.php — campo breakdown.
  • Modify: classes/extensions/metrics/consolidation/service/consolidation_engine_service.php — injeta e chama o novo calculator.

Frontend (app-helico):

  • Modify: lib/moodle.ts — tipos novos.
  • Modify: lib/helico/platform-adapters.ts — corrige EXAM_TYPE_BY_PLATFORM_TYPE, exporta clampPercent, mapPerformanceToDisciplines ganha moduleId.
  • Modify: tests/unit/lib/helico/platform-adapters.test.ts
  • Modify: types/helico/area-do-aluno/type.ts — ExamType ganha 'escrito'.
  • Modify: components/helico/performance-section/ExamPerformanceFilters.tsx
  • Modify: tests/unit/components/performance-section/exam-performance-filters.test.tsx
  • Modify: components/helico/performance-section/ExamPerformanceSection.tsx
  • Modify: tests/unit/components/performance-section/exam-performance-section.test.tsx
  • Modify: components/helico/performance-section/PerformanceEfficiencySection.tsx
  • Modify: tests/unit/components/performance-section/performance-efficiency-section.test.tsx
  • Modify: components/helico/performance-section/DisciplinePerformanceSection.tsx
  • Create: tests/unit/components/performance-section/discipline-performance-section.test.tsx

Verificação + docs (sem código):

  • Verificação de dados, matrícula 225.
  • docs/plataforma/api-integracoes/contratos/performance.md, docs/operacao/uc-007-desempenho.md, app-helico/docs/api-gaps-platform.md, spec (Status: Implementado).

Task 1: discipline_performance_calculator_service — module_id por linha

Files:

  • Modify: classes/extensions/metrics/consolidation/service/discipline_performance_calculator_service.php
  • Test: tests/extensions/metrics/consolidation/service/discipline_performance_calculator_service_test.php

Interfaces:

  • Produces: cada linha de by_discipline[] ganha a chave module_id: int (é module_number da topologia). Uma linha por (disciplina, módulo), não mais uma por disciplina agregando todos os módulos.

  • Step 1: Atualizar o helper de teste topo() pra aceitar módulo variável

Em tests/extensions/metrics/consolidation/service/discipline_performance_calculator_service_test.php, trocar:

    private function topo(int $discipline_id, string $discipline_name): array
    {
        return [
            'discipline_id' => $discipline_id,
            'discipline_name' => $discipline_name,
            'module_number' => 1,
            'module_name' => 'Módulo 1',
        ];
    }

por:

    private function topo(int $discipline_id, string $discipline_name, int $module_number = 1): array
    {
        return [
            'discipline_id' => $discipline_id,
            'discipline_name' => $discipline_name,
            'module_number' => $module_number,
            'module_name' => 'Módulo ' . $module_number,
        ];
    }

(Compatível com as 4 chamadas existentes, que não passam o 3º argumento.)

  • Step 2: Escrever o teste que falha

Adicionar em discipline_performance_calculator_service_test.php, e também adicionar $this->assertSame(1, $out[0]['module_id']); ao final de testNamesComeFromTopologyNotUnitParent():

    public function testSameDisciplineAcrossTwoModulesProducesTwoRows(): void
    {
        $topology = $this->createMock(plan_topology_resolver_service_interface::class);
        $topology->method('resolve_by_unit')->willReturn([
            11 => $this->topo(100, 'Civil', 1),
            12 => $this->topo(100, 'Civil', 2),
        ]);

        $classification_service = $this->createMock(classification_service_interface::class);
        $classification_service->method('get_all_by_student_plan')->willReturn([
            [$this->make_classification(11, 60.0)],
            [$this->make_classification(12, 90.0)],
        ]);

        $out = new discipline_performance_calculator_service($classification_service, $topology)->compute(1, 10, 100);

        $this->assertCount(2, $out);
        $module_ids = array_column($out, 'module_id');
        sort($module_ids);
        $this->assertSame([1, 2], $module_ids);
        foreach ($out as $row) {
            $this->assertSame(100, $row['discipline_id']);
            $this->assertSame(1, $row['units_studied']);
        }
    }
  • Step 3: Rodar o teste e confirmar que falha

Run: docker exec helico-moodle bash -lc "cd /var/www/html/moodle/local/helico && /var/www/html/vendor/bin/phpunit --bootstrap /var/www/html/moodle/lib/phpunit/bootstrap.php tests/extensions/metrics/consolidation/service/discipline_performance_calculator_service_test.php" Expected: FAIL — testSameDisciplineAcrossTwoModulesProducesTwoRows retorna 1 linha em vez de 2 (comportamento atual agrega por disciplina só); testNamesComeFromTopologyNotUnitParent falha por chave module_id inexistente.

  • Step 4: Implementar — agrupar por (disciplina, módulo)

Substituir o corpo de compute() e units_total_by_discipline() em classes/extensions/metrics/consolidation/service/discipline_performance_calculator_service.php:

    public function compute(int $enrolment_id, int $student_plan_id, int $user_id): array
    {
        $topology = $this->topology_resolver->resolve_by_unit($student_plan_id);
        if ($topology === []) {
            return [];
        }

        $totals = $this->units_total_by_discipline_and_module($topology);

        $by_unit = $this->classification_service->get_all_by_student_plan($student_plan_id);

        $by_discipline = [];
        foreach ($by_unit as $entries) {
            if ($entries === []) {
                continue;
            }
            $latest = $entries[0];
            if (!$latest instanceof classification) {
                continue;
            }
            $unit_id = $latest->get_unit_id();
            if (!isset($topology[$unit_id])) {
                continue;
            }

            $entry = $topology[$unit_id];
            $did = $entry['discipline_id'];
            $module_id = $entry['module_number'];
            $key = $did . ':' . $module_id;
            $by_discipline[$key] ??= [
                'discipline_id' => $did,
                'module_id' => $module_id,
                'name' => $entry['discipline_name'],
                'scores' => [],
            ];
            $by_discipline[$key]['scores'][] = $latest->get_score();
        }

        $output = [];
        foreach ($by_discipline as $key => $row) {
            $scores = $row['scores'];
            $score = $scores === [] ? 0.0 : array_sum($scores) / count($scores);
            $output[] = [
                'discipline_id' => $row['discipline_id'],
                'module_id' => $row['module_id'],
                'name' => $row['name'],
                'score' => round($score, 1),
                'trend' => 'stable',
                'units_studied' => count($scores),
                'units_total' => $totals[$key] ?? count($scores),
            ];
        }

        return $output;
    }

    /**
     * Total de Unidades por (Disciplina, Módulo) presentes na topologia.
     *
     * @param array<int, array{discipline_id: int, discipline_name: string, module_number: int, module_name: string}> $topology
     *
     * @return array<string, int> "discipline_id:module_id" → unit count
     */
    private function units_total_by_discipline_and_module(array $topology): array
    {
        $totals = [];
        foreach ($topology as $entry) {
            $key = $entry['discipline_id'] . ':' . $entry['module_number'];
            $totals[$key] = ($totals[$key] ?? 0) + 1;
        }

        return $totals;
    }

Atualizar o docblock da classe (linha de comentário logo acima de final readonly class) acrescentando: “Uma linha por (disciplina, módulo) — não uma por disciplina agregando todos os módulos. O frontend agrega ele mesmo (groupBy(discipline_id)) quando nenhum filtro de Módulo estiver ativo.”

  • Step 5: Rodar os testes e confirmar que passam

Run: mesmo comando do Step 3. Expected: PASS — todos os testes do arquivo, incluindo os 3 pré-existentes (que continuam batendo porque todos usam módulo 1 implícito).

  • Step 6: Commit
cd /private/var/www/middag-work/moodle-local_helico
git add classes/extensions/metrics/consolidation/service/discipline_performance_calculator_service.php tests/extensions/metrics/consolidation/service/discipline_performance_calculator_service_test.php
git commit -m "feat(desempenho): by_discipline ganha module_id por linha"

Task 2: by_module_calculator_service — separar Simulado Escrito em subtipos

Files:

  • Modify: classes/extensions/metrics/consolidation/service/by_module_calculator_service.php
  • Test: tests/extensions/metrics/consolidation/service/by_module_calculator_service_test.php

Interfaces:

  • Consumes: slot_context_factory::from_metadata(string $slot_type, array $metadata): ?slot_context_interface (namespace local_helico\extensions\engine\algorithm\vo\context); slot_context_exam_written->subtype: string (valores discursiva|dissertacao|peca_pratica, default discursiva).

  • Produces: by_exam_type[] de cada módulo ganha até 3 linhas extras (exam_written_discursiva, exam_written_dissertacao, exam_written_peca_pratica), cada uma só quando count > 0. exam_written continua existindo como agregado (Geral).

  • Step 1: Atualizar o helper slot() do teste pra aceitar contexto

Em tests/extensions/metrics/consolidation/service/by_module_calculator_service_test.php, trocar:

    private function slot(string $flowref): slot
    {
        $mock = $this->createMock(slot::class);
        $mock->method('get_flowref')->willReturn($flowref);

        return $mock;
    }

por:

    private function slot(string $flowref, ?string $context = null): slot
    {
        $mock = $this->createMock(slot::class);
        $mock->method('get_flowref')->willReturn($flowref);
        $mock->method('get_context')->willReturn($context);

        return $mock;
    }

(Compatível com as chamadas existentes, que não passam o 2º argumento — get_context() não é usado nesses casos porque nenhum é exam_written.)

  • Step 2: Escrever os testes que falham

Adicionar em by_module_calculator_service_test.php:

    public function testExamWrittenSplitsIntoSubtypeAndGeneralAggregate(): void
    {
        $topology = $this->createMock(plan_topology_resolver_service_interface::class);
        $topology->method('resolve_by_unit')->willReturn([11 => $this->topo(100, 'Civil', 1)]);

        $results = [
            $this->exam_result('exam_written', slot_id: 900, nota: 60.0),
            $this->exam_result('exam_written', slot_id: 901, nota: 40.0),
        ];
        $slots = [
            900 => $this->slot('module_1', json_encode(['ctx_subtype' => 'peca_pratica'])),
            901 => $this->slot('module_1', json_encode(['ctx_subtype' => 'dissertacao'])),
        ];

        $service = $this->make_service(
            $topology,
            [[$this->classification(11, 100.0)]],
            $results,
            $slots,
            [$this->flow('module_1', 1)],
        );

        $out = $service->compute(1, 10, 100);

        $geral = $this->exam_row($out[0]['by_exam_type'], 'exam_written');
        $this->assertSame(50.0, $geral['score'], 'Geral = média das 2 provas (60+40)/2');
        $this->assertSame(2, $geral['count']);

        $peca = $this->exam_row($out[0]['by_exam_type'], 'exam_written_peca_pratica');
        $this->assertSame(60.0, $peca['score']);
        $this->assertSame(1, $peca['count']);
        $this->assertSame('Peça Prática', $peca['label']);

        $dissertacao = $this->exam_row($out[0]['by_exam_type'], 'exam_written_dissertacao');
        $this->assertSame(40.0, $dissertacao['score']);
        $this->assertSame('Dissertação', $dissertacao['label']);

        $types = array_column($out[0]['by_exam_type'], 'type');
        $this->assertNotContains('exam_written_discursiva', $types, 'sem dado, não emite linha');
    }

    public function testExamWrittenWithoutCtxSubtypeDefaultsToDiscursiva(): void
    {
        $topology = $this->createMock(plan_topology_resolver_service_interface::class);
        $topology->method('resolve_by_unit')->willReturn([11 => $this->topo(100, 'Civil', 1)]);

        $results = [$this->exam_result('exam_written', slot_id: 900, nota: 70.0)];
        $slots = [900 => $this->slot('module_1', json_encode([]))];

        $service = $this->make_service(
            $topology,
            [[$this->classification(11, 100.0)]],
            $results,
            $slots,
            [$this->flow('module_1', 1)],
        );

        $out = $service->compute(1, 10, 100);

        $discursiva = $this->exam_row($out[0]['by_exam_type'], 'exam_written_discursiva');
        $this->assertSame(70.0, $discursiva['score']);
        $this->assertSame('Discursiva', $discursiva['label']);
    }
  • Step 3: Rodar os testes e confirmar que falham

Run: docker exec helico-moodle bash -lc "cd /var/www/html/moodle/local/helico && /var/www/html/vendor/bin/phpunit --bootstrap /var/www/html/moodle/lib/phpunit/bootstrap.php tests/extensions/metrics/consolidation/service/by_module_calculator_service_test.php" Expected: FAIL — exam_row() chama self::fail() porque exam_written_peca_pratica/exam_written_dissertacao/exam_written_discursiva não existem no output atual.

  • Step 4: Implementar

Em classes/extensions/metrics/consolidation/service/by_module_calculator_service.php:

Adicionar imports:

use local_helico\extensions\engine\algorithm\vo\context\slot_context_exam_written;
use local_helico\extensions\engine\algorithm\vo\context\slot_context_factory;
use local_helico\extensions\engine\enum\slot_type;

Adicionar constante logo após EXAM_TYPES:

    private const array WRITTEN_SUBTYPE_LABELS = [
        'discursiva' => ['type' => 'exam_written_discursiva', 'label' => 'Discursiva'],
        'dissertacao' => ['type' => 'exam_written_dissertacao', 'label' => 'Dissertação'],
        'peca_pratica' => ['type' => 'exam_written_peca_pratica', 'label' => 'Peça Prática'],
    ];

Substituir exam_scores_by_module() por:

    private function exam_scores_by_module(int $student_plan_id): array
    {
        $flowref_to_module = $this->flowref_to_module($student_plan_id);
        $source_to_display = $this->source_to_display();

        $out = [];
        foreach ($this->result_service->find_by_student_plan($student_plan_id) as $r) {
            if (!$r instanceof result) {
                continue;
            }
            $slot_type = $r->get_slot_type();
            $display_type = $source_to_display[$slot_type] ?? null;
            if ($display_type === null) {
                continue;
            }
            $nota = $r->get_score_breakdown()->nota_real;
            if ($nota === null) {
                continue;
            }
            $slot = $this->slot_service->find_by_id($r->get_slot_id());
            if (!$slot instanceof slot) {
                continue;
            }
            $module_number = $flowref_to_module[$slot->get_flowref()] ?? null;
            if ($module_number === null) {
                continue;
            }

            $out[$module_number][$display_type][] = $nota;

            if ($slot_type === slot_type::EXAM_WRITTEN->value) {
                $subtype_key = $this->written_subtype_display_key($slot);
                if ($subtype_key !== null) {
                    $out[$module_number][$subtype_key][] = $nota;
                }
            }
        }

        return $out;
    }

    /**
     * Resolve a chave de exibição do subtipo de Simulado Escrito
     * (`exam_written_discursiva`/`_dissertacao`/`_peca_pratica`) a partir do
     * `context` persistido no slot. Retorna `null` se o slot não tiver
     * contexto decodificável — resultado só entra no bucket agregado
     * `exam_written` (Geral), nunca num subtipo.
     */
    private function written_subtype_display_key(slot $slot): ?string
    {
        $context = json_decode($slot->get_context() ?? '{}', true);
        if (!is_array($context)) {
            $context = [];
        }
        $vo = slot_context_factory::from_metadata(slot_type::EXAM_WRITTEN->value, $context);
        if (!$vo instanceof slot_context_exam_written) {
            return null;
        }

        return self::WRITTEN_SUBTYPE_LABELS[$vo->subtype]['type'] ?? null;
    }

Substituir build_exam_types() por:

    private function build_exam_types(array $scores_by_type): array
    {
        $out = [];
        foreach (self::EXAM_TYPES as $type => $def) {
            $scores = $scores_by_type[$type] ?? [];
            $out[] = [
                'type' => $type,
                'label' => $def['label'],
                'score' => $scores === [] ? null : round($this->mean($scores), 1),
                'count' => count($scores),
            ];
        }

        foreach (self::WRITTEN_SUBTYPE_LABELS as $def) {
            $scores = $scores_by_type[$def['type']] ?? [];
            if ($scores === []) {
                continue;
            }
            $out[] = [
                'type' => $def['type'],
                'label' => $def['label'],
                'score' => round($this->mean($scores), 1),
                'count' => count($scores),
            ];
        }

        return $out;
    }
  • Step 5: Rodar os testes e confirmar que passam

Run: mesmo comando do Step 3. Expected: PASS — os 2 novos testes e todos os pré-existentes (o teste testByExamTypeAlwaysEmitsThreePlaceholdersWhenNoExamResults continua batendo porque, sem resultado de exam_written, nenhum subtipo é emitido).

  • Step 6: Commit
cd /private/var/www/middag-work/moodle-local_helico
git add classes/extensions/metrics/consolidation/service/by_module_calculator_service.php tests/extensions/metrics/consolidation/service/by_module_calculator_service_test.php
git commit -m "feat(desempenho): separa Simulado Escrito em subtipos no by_module.by_exam_type"

Task 3: breakdown_calculator_service — interface + linhas de V/F e Objetivo

Files:

  • Create: classes/extensions/metrics/consolidation/contract/breakdown_calculator_service_interface.php
  • Create: classes/extensions/metrics/consolidation/service/breakdown_calculator_service.php
  • Create: tests/extensions/metrics/consolidation/service/breakdown_calculator_service_test.php

Interfaces:

  • Consumes: result_service_interface::find_by_student_plan(int): result[]; response_service_interface::find_by_session_ids(int[]): array<int, list<response>>; plan_topology_resolver_service_interface::resolve_by_unit(int): array<int, array{discipline_id:int, discipline_name:string, module_number:int, module_name:string}>; question_category::from_storage(?string): ?question_category.
  • Produces: breakdown_calculator_service::compute() retorna array<int, array{module_id:int, discipline_id:int, exam_type:string, source?:string, score:float, count:int}>. dimension_key() retorna 'breakdown'.

Este task cobre só a parte de V/F/Objetivo/DI/SVD (granularidade response). A parte de Simulado Escrito entra no Task 4, no mesmo arquivo.

  • Step 1: Criar a interface

classes/extensions/metrics/consolidation/contract/breakdown_calculator_service_interface.php:

<?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\metrics\consolidation\contract;

defined('MOODLE_INTERNAL') || exit;

interface breakdown_calculator_service_interface extends dimension_calculator_interface {}
  • Step 2: Escrever o teste que falha (V/F e Objetivo)

tests/extensions/metrics/consolidation/service/breakdown_calculator_service_test.php:

<?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\metrics\consolidation\service;

use local_helico\extensions\activity\response\contract\response_service_interface;
use local_helico\extensions\activity\response\entity\response;
use local_helico\extensions\activity\result\contract\result_service_interface;
use local_helico\extensions\activity\result\entity\result;
use local_helico\extensions\activity\result\vo\score_breakdown;
use local_helico\extensions\engine\algorithm\contract\slot_scope_service_interface;
use local_helico\extensions\engine\algorithm\contract\slot_service_interface;
use local_helico\extensions\engine\algorithm\entity\slot;
use local_helico\extensions\engine\algorithm\vo\slot_scope_ref;
use local_helico\extensions\engine\plan\contract\plan_topology_resolver_service_interface;
use local_helico\extensions\engine\plan\contract\study_flow_service_interface;
use local_helico\extensions\engine\plan\entity\study_flow;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\TestCase;

defined('MOODLE_INTERNAL') || exit;

/**
 * @internal
 */
#[CoversClass(breakdown_calculator_service::class)]
final class breakdown_calculator_service_test extends TestCase
{
    public function testReturnsEmptyWithoutResults(): void
    {
        $service = $this->make_service(results: []);

        $this->assertSame([], $service->compute(1, 10, 100));
    }

    public function testClosedQuestionRowCrossesModuleDisciplineTypeAndSource(): void
    {
        $topology = [11 => $this->topo(100, 1)];
        $results = [$this->exam_result('exam_truefalse', session_id: 500)];
        $responses = [500 => [
            $this->make_response(unit_id: 11, category: 'legislation', correct: 1, notsure: 0),
            $this->make_response(unit_id: 11, category: 'legislation', correct: 0, notsure: 0),
        ]];

        $out = $this->make_service($results, $responses, $topology)->compute(1, 10, 100);

        $this->assertCount(1, $out);
        $this->assertSame([
            'module_id' => 1,
            'discipline_id' => 100,
            'exam_type' => 'exam_truefalse',
            'source' => 'legislation',
            'score' => 50.0,
            'count' => 2,
        ], $out[0]);
    }

    public function testResponsesWithoutUnitOrCategoryAreExcluded(): void
    {
        $topology = [11 => $this->topo(100, 1)];
        $results = [$this->exam_result('exam_objective', session_id: 500)];
        $responses = [500 => [
            $this->make_response(unit_id: null, category: 'legislation', correct: 1, notsure: 0),
            $this->make_response(unit_id: 11, category: null, correct: 1, notsure: 0),
            $this->make_response(unit_id: 99, category: 'legislation', correct: 1, notsure: 0), // fora da topologia
        ]];

        $out = $this->make_service($results, $responses, $topology)->compute(1, 10, 100);

        $this->assertSame([], $out);
    }

    public function testDifferentDisciplinesInSameSessionProduceSeparateRows(): void
    {
        $topology = [11 => $this->topo(100, 1), 12 => $this->topo(200, 1)];
        $results = [$this->exam_result('exam_objective', session_id: 500)];
        $responses = [500 => [
            $this->make_response(unit_id: 11, category: 'legislation', correct: 1, notsure: 0),
            $this->make_response(unit_id: 12, category: 'doctrine', correct: 1, notsure: 0),
        ]];

        $out = $this->make_service($results, $responses, $topology)->compute(1, 10, 100);

        $this->assertCount(2, $out);
        $disciplines = array_column($out, 'discipline_id');
        sort($disciplines);
        $this->assertSame([100, 200], $disciplines);
    }

    public function testNotSureCountsAsIncorrectButCountsTotal(): void
    {
        $topology = [11 => $this->topo(100, 1)];
        $results = [$this->exam_result('exam_truefalse', session_id: 500)];
        $responses = [500 => [
            $this->make_response(unit_id: 11, category: 'legislation', correct: 1, notsure: 1),
        ]];

        $out = $this->make_service($results, $responses, $topology)->compute(1, 10, 100);

        $this->assertSame(0.0, $out[0]['score']);
        $this->assertSame(1, $out[0]['count']);
    }

    /**
     * @param list<result>                           $results
     * @param array<int, list<response>>              $responses_by_session
     * @param array<int, array{discipline_id:int, discipline_name:string, module_number:int, module_name:string}> $topology
     */
    private function make_service(
        array $results,
        array $responses_by_session = [],
        array $topology = [],
        array $slots = [],
        array $flows = [],
    ): breakdown_calculator_service {
        $result_service = $this->createMock(result_service_interface::class);
        $result_service->method('find_by_student_plan')->willReturn($results);

        $response_service = $this->createMock(response_service_interface::class);
        $response_service->method('find_by_session_ids')->willReturn($responses_by_session);

        $slot_service = $this->createMock(slot_service_interface::class);
        $slot_service->method('find_by_id')->willReturnCallback(
            static fn (int $id): ?slot => $slots[$id] ?? null,
        );

        $slot_scope_service = $this->createMock(slot_scope_service_interface::class);
        $slot_scope_service->method('find_by_slot')->willReturn([]);

        $topology_resolver = $this->createMock(plan_topology_resolver_service_interface::class);
        $topology_resolver->method('resolve_by_unit')->willReturn($topology);

        $flow_service = $this->createMock(study_flow_service_interface::class);
        $flow_service->method('find_by_student_plan')->willReturn($flows);

        return new breakdown_calculator_service(
            $result_service,
            $response_service,
            $slot_service,
            $slot_scope_service,
            $topology_resolver,
            $flow_service,
        );
    }

    /**
     * @return array{discipline_id:int, discipline_name:string, module_number:int, module_name:string}
     */
    private function topo(int $discipline_id, int $module_number): array
    {
        return [
            'discipline_id' => $discipline_id,
            'discipline_name' => 'Disciplina ' . $discipline_id,
            'module_number' => $module_number,
            'module_name' => 'Módulo ' . $module_number,
        ];
    }

    private function exam_result(string $slot_type, int $session_id, int $slot_id = 0, float $nota = 0.0): result
    {
        $bd = new score_breakdown(
            nota_real: $nota,
            nota_bruta: null,
            nota_ajustada: null,
            bonus_relevancia: 0.0,
            total_questions: 0,
            correct_count: 0,
            incorrect_count: 0,
            unanswered_count: 0,
            time_total_ms: 0,
        );
        $mock = $this->createMock(result::class);
        $mock->method('get_slot_type')->willReturn($slot_type);
        $mock->method('get_session_id')->willReturn($session_id);
        $mock->method('get_slot_id')->willReturn($slot_id);
        $mock->method('get_score_breakdown')->willReturn($bd);

        return $mock;
    }

    private function make_response(?int $unit_id, ?string $category, int $correct, int $notsure): response
    {
        $mock = $this->createMock(response::class);
        $mock->method('get_unit_id')->willReturn($unit_id);
        $mock->method('get_category')->willReturn($category);
        $mock->method('get_correct')->willReturn($correct);
        $mock->method('get_notsure')->willReturn($notsure);

        return $mock;
    }
}
  • Step 3: Rodar o teste e confirmar que falha

Run: docker exec helico-moodle bash -lc "cd /var/www/html/moodle/local/helico && /var/www/html/vendor/bin/phpunit --bootstrap /var/www/html/moodle/lib/phpunit/bootstrap.php tests/extensions/metrics/consolidation/service/breakdown_calculator_service_test.php" Expected: FAIL — classe breakdown_calculator_service não existe.

  • Step 4: Implementar breakdown_calculator_service.php (parte fechada)

classes/extensions/metrics/consolidation/service/breakdown_calculator_service.php:

<?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\metrics\consolidation\service;

use local_helico\extensions\activity\assessment\question_category\enums\question_category;
use local_helico\extensions\activity\response\contract\response_service_interface;
use local_helico\extensions\activity\response\entity\response;
use local_helico\extensions\activity\result\contract\result_service_interface;
use local_helico\extensions\activity\result\entity\result;
use local_helico\extensions\engine\algorithm\contract\slot_scope_service_interface;
use local_helico\extensions\engine\algorithm\contract\slot_service_interface;
use local_helico\extensions\engine\plan\contract\plan_topology_resolver_service_interface;
use local_helico\extensions\engine\plan\contract\study_flow_service_interface;
use local_helico\extensions\metrics\consolidation\contract\breakdown_calculator_service_interface;

defined('MOODLE_INTERNAL') || exit;

/**
 * Desempenho — tabela de fatos pra filtros cruzados (Módulo × Disciplina ×
 * Tipo de Simulado × Fonte).
 *
 * V/F, Objetivo, DI, SVD: granularidade de `response` — `module_id`/
 * `discipline_id` vêm de `response.unit_id` via `plan_topology_resolver`
 * (mesmo mecanismo do `discipline_performance_calculator_service`), `source`
 * vem de `response.category`, `exam_type` vem do `slot_type` do `result` dono
 * da sessão.
 *
 * Simulado Escrito (Geral + subtipos): sem `response` por questão (correção
 * holística) — ver {@see add_written_exam_rows}.
 *
 * @see docs/_archive/specs/2026-08-28-desempenho-filtros-cruzados-design.md
 */
final readonly class breakdown_calculator_service implements breakdown_calculator_service_interface
{
    private const array CLOSED_EXAM_TYPES = [
        'diagnostic_initial',
        'diagnostic_verify',
        'exam_objective',
        'exam_truefalse',
    ];

    public function __construct(
        private result_service_interface $result_service,
        private response_service_interface $response_service,
        private slot_service_interface $slot_service,
        private slot_scope_service_interface $slot_scope_service,
        private plan_topology_resolver_service_interface $topology_resolver,
        private study_flow_service_interface $study_flow_service,
    ) {}

    public function dimension_key(): string
    {
        return 'breakdown';
    }

    public function compute(int $enrolment_id, int $student_plan_id, int $user_id): array
    {
        $results = $this->result_service->find_by_student_plan($student_plan_id);
        $topology = $this->topology_resolver->resolve_by_unit($student_plan_id);

        $buckets = [];
        $this->add_closed_question_rows($results, $topology, $buckets);

        return $this->flatten($buckets);
    }

    /**
     * @param result[] $results
     * @param array<int, array{discipline_id:int, discipline_name:string, module_number:int, module_name:string}> $topology
     * @param array<string, array{module_id:int, discipline_id:int, exam_type:string, source:?string, scores:float[]}> $buckets
     */
    private function add_closed_question_rows(array $results, array $topology, array &$buckets): void
    {
        $exam_type_by_session = [];
        $session_ids = [];
        foreach ($results as $r) {
            if (!$r instanceof result) {
                continue;
            }
            if (!in_array($r->get_slot_type(), self::CLOSED_EXAM_TYPES, true)) {
                continue;
            }
            $sid = $r->get_session_id();
            if ($sid <= 0) {
                continue;
            }
            $exam_type_by_session[$sid] = $r->get_slot_type();
            $session_ids[$sid] = true;
        }

        if ($session_ids === []) {
            return;
        }

        $by_session = $this->response_service->find_by_session_ids(array_keys($session_ids));

        foreach ($by_session as $session_id => $responses) {
            $exam_type = $exam_type_by_session[$session_id] ?? null;
            if ($exam_type === null) {
                continue;
            }

            foreach ($responses as $resp) {
                if (!$resp instanceof response) {
                    continue;
                }
                $unit_id = $resp->get_unit_id();
                if ($unit_id === null || !isset($topology[$unit_id])) {
                    continue;
                }
                $category = question_category::from_storage($resp->get_category());
                if (!$category instanceof question_category) {
                    continue;
                }

                $entry = $topology[$unit_id];
                $key = implode(':', [$entry['module_number'], $entry['discipline_id'], $exam_type, $category->value]);
                $buckets[$key] ??= [
                    'module_id' => $entry['module_number'],
                    'discipline_id' => $entry['discipline_id'],
                    'exam_type' => $exam_type,
                    'source' => $category->value,
                    'scores' => [],
                ];
                $buckets[$key]['scores'][] = $this->is_correct($resp) ? 100.0 : 0.0;
            }
        }
    }

    private function is_correct(response $resp): bool
    {
        if ($resp->get_notsure() === 1) {
            return false;
        }

        return $resp->get_correct() === 1;
    }

    /**
     * @param array<string, array{module_id:int, discipline_id:int, exam_type:string, source:?string, scores:float[]}> $buckets
     *
     * @return array<int, array{module_id:int, discipline_id:int, exam_type:string, source?:string, score:float, count:int}>
     */
    private function flatten(array $buckets): array
    {
        $out = [];
        foreach ($buckets as $row) {
            $scores = $row['scores'];
            if ($scores === []) {
                continue;
            }
            $entry = [
                'module_id' => $row['module_id'],
                'discipline_id' => $row['discipline_id'],
                'exam_type' => $row['exam_type'],
                'score' => round(array_sum($scores) / count($scores), 1),
                'count' => count($scores),
            ];
            if ($row['source'] !== null) {
                $entry['source'] = $row['source'];
            }
            $out[] = $entry;
        }

        return $out;
    }
}

slot_scope_service_interface e study_flow_service_interface são injetados aqui já pra fechar a assinatura do construtor que o Task 4 usa (evita mudar a assinatura de novo) — ainda sem uso nesta parte do arquivo.

  • Step 5: Rodar os testes e confirmar que passam

Run: mesmo comando do Step 3. Expected: PASS — todos os 5 testes.

  • Step 6: Commit
cd /private/var/www/middag-work/moodle-local_helico
git add classes/extensions/metrics/consolidation/contract/breakdown_calculator_service_interface.php classes/extensions/metrics/consolidation/service/breakdown_calculator_service.php tests/extensions/metrics/consolidation/service/breakdown_calculator_service_test.php
git commit -m "feat(desempenho): breakdown_calculator_service — linhas de V/F, Objetivo, DI, SVD"

Task 4: breakdown_calculator_service — linhas de Simulado Escrito

Files:

  • Modify: classes/extensions/metrics/consolidation/service/breakdown_calculator_service.php
  • Modify: tests/extensions/metrics/consolidation/service/breakdown_calculator_service_test.php

Interfaces:

  • Consumes: slot_scope_service_interface::find_by_slot(int $slot_id): slot_scope_ref[]; slot_scope_ref->kind: string, ->ref_id: int; slot::getId(): int (herdado de item); slot_context_factory::from_metadata() (mesmo uso do Task 2).

  • Produces: linhas com exam_type em exam_written|exam_written_discursiva|exam_written_dissertacao|exam_written_peca_pratica, sem source. Uma linha por disciplina no scope do slot (fan-out) — a nota inteira da prova conta pra cada uma.

  • Step 1: Escrever os testes que falham

Adicionar em breakdown_calculator_service_test.php:

    public function testWrittenExamProducesGeneralAndSubtypeRowsPerDiscipline(): void
    {
        $results = [$this->exam_result('exam_written', session_id: 0, slot_id: 900, nota: 61.0)];
        $slot = $this->written_slot('module_1', json_encode(['ctx_subtype' => 'peca_pratica']));
        $slots = [900 => $slot];
        $scopes = [$slot->getId() => [
            new slot_scope_ref(kind: 'discipline', ref_id: 3, name: 'Civil'),
        ]];
        $flows = [$this->flow('module_1', 2)];

        $out = $this->make_service($results, [], [], $slots, $flows, $scopes)->compute(1, 10, 100);

        $rows_by_type = array_column($out, null, 'exam_type');
        $this->assertSame(['module_id' => 2, 'discipline_id' => 3, 'exam_type' => 'exam_written', 'score' => 61.0, 'count' => 1], $rows_by_type['exam_written']);
        $this->assertSame(['module_id' => 2, 'discipline_id' => 3, 'exam_type' => 'exam_written_peca_pratica', 'score' => 61.0, 'count' => 1], $rows_by_type['exam_written_peca_pratica']);
        $this->assertArrayNotHasKey('source', $rows_by_type['exam_written']);
    }

    public function testWrittenExamWithMultiDisciplineScopeFansOutToEachDiscipline(): void
    {
        $results = [$this->exam_result('exam_written', session_id: 0, slot_id: 900, nota: 55.0)];
        $slot = $this->written_slot('module_1', json_encode(['ctx_subtype' => 'discursiva']));
        $slots = [900 => $slot];
        $scopes = [$slot->getId() => [
            new slot_scope_ref(kind: 'discipline', ref_id: 3, name: 'Civil'),
            new slot_scope_ref(kind: 'discipline', ref_id: 7, name: 'Penal'),
        ]];
        $flows = [$this->flow('module_1', 1)];

        $out = $this->make_service($results, [], [], $slots, $flows, $scopes)->compute(1, 10, 100);

        $written_rows = array_filter($out, static fn (array $r): bool => $r['exam_type'] === 'exam_written');
        $disciplines = array_column($written_rows, 'discipline_id');
        sort($disciplines);
        $this->assertSame([3, 7], $disciplines);
        foreach ($written_rows as $row) {
            $this->assertSame(55.0, $row['score']);
        }
    }

    public function testWrittenExamWithoutDisciplineScopeIsExcluded(): void
    {
        $results = [$this->exam_result('exam_written', session_id: 0, slot_id: 900, nota: 55.0)];
        $slot = $this->written_slot('module_1', json_encode(['ctx_subtype' => 'discursiva']));
        $slots = [900 => $slot];
        $flows = [$this->flow('module_1', 1)];

        // $scopes vazio ($slot_scope_service->find_by_slot() retorna []) — sem escopo, sem linha.
        $out = $this->make_service($results, [], [], $slots, $flows, [])->compute(1, 10, 100);

        $this->assertSame([], $out);
    }

Atualizar make_service() (a assinatura ganha $scopes e written_slot()/os mocks de slot_scope_service passam a usar um callback em vez de willReturn([]) fixo):

    /**
     * @param list<result>                           $results
     * @param array<int, list<response>>              $responses_by_session
     * @param array<int, array{discipline_id:int, discipline_name:string, module_number:int, module_name:string}> $topology
     * @param array<int, slot>                        $slots
     * @param list<study_flow>                        $flows
     * @param array<int, slot_scope_ref[]>             $scopes slot_id → refs
     */
    private function make_service(
        array $results,
        array $responses_by_session = [],
        array $topology = [],
        array $slots = [],
        array $flows = [],
        array $scopes = [],
    ): breakdown_calculator_service {
        $result_service = $this->createMock(result_service_interface::class);
        $result_service->method('find_by_student_plan')->willReturn($results);

        $response_service = $this->createMock(response_service_interface::class);
        $response_service->method('find_by_session_ids')->willReturn($responses_by_session);

        $slot_service = $this->createMock(slot_service_interface::class);
        $slot_service->method('find_by_id')->willReturnCallback(
            static fn (int $id): ?slot => $slots[$id] ?? null,
        );

        $slot_scope_service = $this->createMock(slot_scope_service_interface::class);
        $slot_scope_service->method('find_by_slot')->willReturnCallback(
            static fn (int $slot_id): array => $scopes[$slot_id] ?? [],
        );

        $topology_resolver = $this->createMock(plan_topology_resolver_service_interface::class);
        $topology_resolver->method('resolve_by_unit')->willReturn($topology);

        $flow_service = $this->createMock(study_flow_service_interface::class);
        $flow_service->method('find_by_student_plan')->willReturn($flows);

        return new breakdown_calculator_service(
            $result_service,
            $response_service,
            $slot_service,
            $slot_scope_service,
            $topology_resolver,
            $flow_service,
        );
    }

    private function written_slot(string $flowref, ?string $context): slot
    {
        static $next_id = 900;
        $id = $next_id++;
        $mock = $this->createMock(slot::class);
        $mock->method('getId')->willReturn($id);
        $mock->method('get_flowref')->willReturn($flowref);
        $mock->method('get_context')->willReturn($context);

        return $mock;
    }

    private function flow(string $flowref, ?int $module_number): study_flow
    {
        $mock = $this->createMock(study_flow::class);
        $mock->method('get_flowref')->willReturn($flowref);
        $mock->method('get_module_number')->willReturn($module_number);

        return $mock;
    }

Ajustar exam_result() pra aceitar slot_id nomeado (já usado nos novos testes: $this->exam_result('exam_written', session_id: 0, slot_id: 900, nota: 61.0)) — a assinatura já criada no Task 3 (exam_result(string $slot_type, int $session_id, int $slot_id = 0, float $nota = 0.0)) já cobre isso, sem mudança.

  • Step 2: Rodar os testes e confirmar que falham

Run: docker exec helico-moodle bash -lc "cd /var/www/html/moodle/local/helico && /var/www/html/vendor/bin/phpunit --bootstrap /var/www/html/moodle/lib/phpunit/bootstrap.php tests/extensions/metrics/consolidation/service/breakdown_calculator_service_test.php" Expected: FAIL — os 3 novos testes retornam [] (Simulado Escrito ainda não processado).

  • Step 3: Implementar

Em classes/extensions/metrics/consolidation/service/breakdown_calculator_service.php, adicionar imports:

use local_helico\extensions\engine\algorithm\entity\slot;
use local_helico\extensions\engine\algorithm\vo\context\slot_context_exam_written;
use local_helico\extensions\engine\algorithm\vo\context\slot_context_factory;
use local_helico\extensions\engine\algorithm\vo\slot_scope_ref;
use local_helico\extensions\engine\enum\slot_type;
use local_helico\extensions\engine\plan\entity\study_flow;

Adicionar constante:

    private const array WRITTEN_SUBTYPE_TO_EXAM_TYPE = [
        'discursiva' => 'exam_written_discursiva',
        'dissertacao' => 'exam_written_dissertacao',
        'peca_pratica' => 'exam_written_peca_pratica',
    ];

Atualizar compute():

    public function compute(int $enrolment_id, int $student_plan_id, int $user_id): array
    {
        $results = $this->result_service->find_by_student_plan($student_plan_id);
        $topology = $this->topology_resolver->resolve_by_unit($student_plan_id);

        $buckets = [];
        $this->add_closed_question_rows($results, $topology, $buckets);
        $this->add_written_exam_rows($results, $student_plan_id, $buckets);

        return $this->flatten($buckets);
    }

Adicionar os métodos novos (após add_closed_question_rows):

    /**
     * Simulado Escrito (Geral + subtipos) — granularidade de `result`, não gera
     * `response` por questão (correção holística, ver `exam_written_handler_service`).
     * `module_id` vem de `slot.flowref`; `discipline_id`(s) vêm de `slot.scope`
     * (fan-out — uma linha por disciplina no escopo, a nota inteira conta pra
     * cada uma); subtipo vem de `slot.context`. Sem `source`.
     *
     * @param result[] $results
     * @param array<string, array{module_id:int, discipline_id:int, exam_type:string, source:?string, scores:float[]}> $buckets
     */
    private function add_written_exam_rows(array $results, int $student_plan_id, array &$buckets): void
    {
        $written_results = array_filter(
            $results,
            static fn ($r): bool => $r instanceof result && $r->get_slot_type() === slot_type::EXAM_WRITTEN->value,
        );
        if ($written_results === []) {
            return;
        }

        $flowref_to_module = $this->flowref_to_module($student_plan_id);

        foreach ($written_results as $r) {
            $nota = $r->get_score_breakdown()->nota_real;
            if ($nota === null) {
                continue;
            }
            $slot = $this->slot_service->find_by_id($r->get_slot_id());
            if (!$slot instanceof slot) {
                continue;
            }
            $module_id = $flowref_to_module[$slot->get_flowref()] ?? null;
            if ($module_id === null) {
                continue;
            }

            $discipline_ids = $this->written_discipline_ids((int) $slot->getId());
            if ($discipline_ids === []) {
                continue;
            }

            $exam_types = ['exam_written'];
            $subtype_type = $this->written_subtype_exam_type($slot);
            if ($subtype_type !== null) {
                $exam_types[] = $subtype_type;
            }

            foreach ($discipline_ids as $discipline_id) {
                foreach ($exam_types as $exam_type) {
                    $key = implode(':', [$module_id, $discipline_id, $exam_type, 'none']);
                    $buckets[$key] ??= [
                        'module_id' => $module_id,
                        'discipline_id' => $discipline_id,
                        'exam_type' => $exam_type,
                        'source' => null,
                        'scores' => [],
                    ];
                    $buckets[$key]['scores'][] = $nota;
                }
            }
        }
    }

    /** @return int[] */
    private function written_discipline_ids(int $slot_id): array
    {
        $refs = $this->slot_scope_service->find_by_slot($slot_id);

        return array_values(array_map(
            static fn (slot_scope_ref $ref): int => $ref->ref_id,
            array_filter($refs, static fn (slot_scope_ref $ref): bool => $ref->kind === 'discipline'),
        ));
    }

    private function written_subtype_exam_type(slot $slot): ?string
    {
        $context = json_decode($slot->get_context() ?? '{}', true);
        if (!is_array($context)) {
            $context = [];
        }
        $vo = slot_context_factory::from_metadata(slot_type::EXAM_WRITTEN->value, $context);
        if (!$vo instanceof slot_context_exam_written) {
            return null;
        }

        return self::WRITTEN_SUBTYPE_TO_EXAM_TYPE[$vo->subtype] ?? null;
    }

    /** @return array<string, int> flowref → module_number */
    private function flowref_to_module(int $student_plan_id): array
    {
        $map = [];
        foreach ($this->study_flow_service->find_by_student_plan($student_plan_id) as $flow) {
            if (!$flow instanceof study_flow) {
                continue;
            }
            $module_number = $flow->get_module_number();
            if ($module_number !== null) {
                $map[(string) $flow->get_flowref()] = $module_number;
            }
        }

        return $map;
    }
  • Step 4: Rodar os testes e confirmar que passam

Run: mesmo comando do Step 2. Expected: PASS — todos os testes do arquivo (8 no total, 5 do Task 3 + 3 novos).

  • Step 5: Commit
cd /private/var/www/middag-work/moodle-local_helico
git add classes/extensions/metrics/consolidation/service/breakdown_calculator_service.php tests/extensions/metrics/consolidation/service/breakdown_calculator_service_test.php
git commit -m "feat(desempenho): breakdown_calculator_service — linhas de Simulado Escrito (Geral + subtipos)"

Task 5: Ligar breakdown[] no consolidated_dashboard_dto e no consolidation_engine_service

Files:

  • Modify: classes/extensions/metrics/consolidation/dto/consolidated_dashboard_dto.php
  • Modify: classes/extensions/metrics/consolidation/service/consolidation_engine_service.php

Interfaces:

  • Consumes: breakdown_calculator_service_interface::compute(...) (Task 3+4).
  • Produces: consolidated_dashboard_dto->breakdown: array, presente em to_array(), empty() e na decodificação do cache.

Sem PHPUnit próprio pra este task — a smoke coverage vem do teste de regressão de rotas (Step 3) e da verificação da matrícula 225 (Task 11). O dimension_calculator_interface é resolvido por autowire (Symfony, um binding por interface) — não há arquivo de configuração de DI pra editar neste repo.

  • Step 1: Adicionar breakdown ao DTO

Em classes/extensions/metrics/consolidation/dto/consolidated_dashboard_dto.php, mudar o construtor:

    public function __construct(
        public array $overall,
        public array $by_discipline,
        public array $by_module,
        public array $by_exam_type,
        public array $by_source,
        public array $flashcard_practice,
        public array $progress,
        public array $weekly = [],
        public array $periods = [],
        public array $breakdown = [],
    ) {}

to_array():

    public function to_array(): array
    {
        return [
            'overall' => $this->overall,
            'by_discipline' => $this->by_discipline,
            'by_module' => $this->by_module,
            'by_exam_type' => $this->by_exam_type,
            'by_source' => $this->by_source,
            'flashcard_practice' => $this->flashcard_practice,
            'progress' => $this->progress,
            'weekly' => $this->weekly,
            'periods' => $this->periods,
            'breakdown' => $this->breakdown,
        ];
    }

empty() ganha breakdown: [] no final da lista de argumentos nomeados.

  • Step 2: Injetar e chamar o novo calculator no engine

Em classes/extensions/metrics/consolidation/service/consolidation_engine_service.php:

Adicionar import:

use local_helico\extensions\metrics\consolidation\contract\breakdown_calculator_service_interface;

Adicionar ao construtor (após $period_calculator):

        private period_trends_calculator_service_interface $period_calculator,
        private breakdown_calculator_service_interface $breakdown_calculator,

Em recompute_now(), adicionar após $periods = ...:

        $breakdown = $this->breakdown_calculator->compute($enrolment_id, $student_plan_id, $user_id);

E no construtor de $dashboard:

        $dashboard = new consolidated_dashboard_dto(
            overall: $overall,
            by_discipline: $by_discipline,
            by_module: $by_module,
            by_exam_type: $by_exam_type,
            by_source: $by_source,
            flashcard_practice: $flashcards,
            progress: $this->normalize_progress($progress),
            weekly: $weekly,
            periods: $periods,
            breakdown: $breakdown,
        );

Em decode_cache(), adicionar ao new consolidated_dashboard_dto(...):

            breakdown: (array) ($decoded['breakdown'] ?? []),
  • Step 3: Rodar a suíte de regressão da Platform API

Run: docker exec helico-moodle bash -lc "cd /var/www/html/moodle/local/helico && /var/www/html/vendor/bin/phpunit --bootstrap /var/www/html/moodle/lib/phpunit/bootstrap.php tests/regression/platform_routes_test.php tests/extensions/metrics/consolidation/service/" Expected: PASS — nenhuma rota quebrou, todos os calculators (incluindo os 3 tasks anteriores) continuam verdes. Se o autowire do Symfony falhar em resolver breakdown_calculator_service_interface (erro Cannot autowire service ... argument $breakdown_calculator), é sinal de que este container exige registro explícito — nesse caso, procurar por onde by_exam_type_calculator_service_interface é registrado (grep by_exam_type_calculator_service_interface fora de contract//service/) e replicar o mesmo padrão pra breakdown_calculator_service_interface.

  • Step 4: Commit
cd /private/var/www/middag-work/moodle-local_helico
git add classes/extensions/metrics/consolidation/dto/consolidated_dashboard_dto.php classes/extensions/metrics/consolidation/service/consolidation_engine_service.php
git commit -m "feat(desempenho): liga breakdown_calculator_service no engine de consolidação"

Task 6: Frontend — tipos e adapter

Files:

  • Modify: lib/moodle.ts
  • Modify: lib/helico/platform-adapters.ts
  • Test: tests/unit/lib/helico/platform-adapters.test.ts

Interfaces:

  • Produces: PlatformPerformanceExamTypeBreakdownRow (novo type); PlatformPerformanceResponse.breakdown: PlatformPerformanceExamTypeBreakdownRow[]; PlatformPerformanceDiscipline.module_id: number; EXAM_TYPE_BY_PLATFORM_TYPE corrigido; mapPerformanceToDisciplines() retorna moduleId também; clampPercent exportado (usado nos Tasks 8/9).

  • Step 1: Escrever os testes que falham

Em tests/unit/lib/helico/platform-adapters.test.ts, localizar o describe de mapPerformanceToDisciplines (já existe — usar como base) e adicionar:

it('inclui o module_id de cada linha de disciplina', () => {
  const performance = criarPerformanceBase({
    by_discipline: [
      { discipline_id: 10, name: 'Civil', score: 80, trend: 'stable', units_studied: 2, units_total: 2, module_id: 1 },
    ],
  });

  const result = mapPerformanceToDisciplines(performance);

  expect(result[0]).toMatchObject({ moduleId: 1 });
});

(Ajustar o nome do helper de fixture criarPerformanceBase pro que já existir no arquivo — reaproveitar EMPTY_WEEK/EMPTY_WEEKLY/EMPTY_FC/EMPTY_PROGRESS e os demais campos obrigatórios de PlatformPerformanceResponse já usados nos testes vizinhos de mapPerformanceToDisciplines, incluindo agora breakdown: [].)

E no describe de exam entries/adapters de tipo, adicionar:

it('mapeia os 3 subtipos de escrita e o Geral pros ExamType corretos', () => {
  const performance = criarPerformanceBase({
    by_module: [
      {
        module_id: 1,
        module_name: 'Módulo 1',
        score: 0,
        units_studied: 0,
        by_discipline: [],
        by_exam_type: [
          { type: 'exam_written', label: 'Simulado Escrito', score: 58, count: 3 },
          { type: 'exam_written_discursiva', label: 'Discursiva', score: 60, count: 1 },
          { type: 'exam_written_dissertacao', label: 'Dissertação', score: 55, count: 1 },
          { type: 'exam_written_peca_pratica', label: 'Peça Prática', score: 59, count: 1 },
        ],
      },
    ],
  });

  const entries = mapPerformanceToExamEntries(performance);
  const types = entries.map((e) => e.type).sort();

  expect(types).toEqual(['discursivo', 'dissertativa', 'escrito', 'peca-pratica']);
});
  • Step 2: Rodar os testes e confirmar que falham

Run: cd /private/var/www/app-helico && npx vitest run tests/unit/lib/helico/platform-adapters.test.ts Expected: FAIL — moduleId undefined; exam_written_dissertacao/exam_written_peca_pratica não mapeados (o EXAM_TYPE_BY_PLATFORM_TYPE atual só conhece exam_written→'discursivo'), tipo PlatformPerformanceExamType não aceita os literais novos (erro de compilação TS).

  • Step 3: Implementar — lib/moodle.ts

Trocar a união PlatformPerformanceExamType (linha ~1096):

export type PlatformPerformanceExamType =
  | 'diagnostic_initial'
  | 'diagnostic_verify'
  | 'exam_objective'
  | 'exam_truefalse'
  | 'exam_written'
  | 'exam_written_discursiva'
  | 'exam_written_dissertacao'
  | 'exam_written_peca_pratica'
  | 'general_review';

Adicionar module_id em PlatformPerformanceDiscipline (linha ~1065):

export interface PlatformPerformanceDiscipline {
  discipline_id: number;
  name: string;
  score: number;
  trend: PlatformTrend;
  units_studied: number;
  units_total: number;
  module_id: number;
}

Adicionar o novo type (logo após PlatformPerformanceBySource):

export interface PlatformPerformanceExamTypeBreakdownRow {
  module_id: number;
  discipline_id: number;
  exam_type: PlatformPerformanceExamType;
  source?: PlatformPerformanceSource;
  score: number;
  count: number;
}

Adicionar breakdown em PlatformPerformanceResponse:

export interface PlatformPerformanceResponse {
  enrolment_id: number;
  overall: PlatformPerformanceOverall;
  by_discipline: PlatformPerformanceDiscipline[];
  by_module: PlatformPerformanceModule[];
  by_exam_type: PlatformPerformanceByExamType[];
  by_source: PlatformPerformanceBySource[];
  flashcard_practice: PlatformPerformanceFlashcardPractice;
  progress: PlatformPerformanceProgress;
  weekly: PlatformPerformanceWeekly;
  periods?: PlatformPerformancePeriods;
  breakdown: PlatformPerformanceExamTypeBreakdownRow[];
}
  • Step 4: Implementar — lib/helico/platform-adapters.ts

Trocar EXAM_TYPE_BY_PLATFORM_TYPE:

const EXAM_TYPE_BY_PLATFORM_TYPE: Record<string, ExamType> = {
  exam_objective: 'objetivo',
  exam_truefalse: 'vf',
  exam_written: 'escrito',
  exam_written_discursiva: 'discursivo',
  exam_written_dissertacao: 'dissertativa',
  exam_written_peca_pratica: 'peca-pratica',
};

Trocar mapPerformanceToDisciplines:

export function mapPerformanceToDisciplines(
  performance: PlatformPerformanceResponse,
) {
  return performance.by_discipline.map((item) => ({
    id: String(item.discipline_id),
    discipline: item.name,
    percentage: clampPercent(item.score),
    moduleId: item.module_id,
  }));
}

Exportar clampPercent (trocar function clampPercent por export function clampPercent, mantendo toNumber como está).

  • Step 5: Rodar os testes e confirmar que passam

Run: mesmo comando do Step 2. Expected: PASS.

  • Step 6: Commit
cd /private/var/www/app-helico
git add lib/moodle.ts lib/helico/platform-adapters.ts tests/unit/lib/helico/platform-adapters.test.ts
git commit -m "feat(desempenho): tipos e adapter pro breakdown e subtipos de Simulado Escrito"

Task 7: ExamType ganha “Simulado Escrito Geral” + filtros por tipo

Files:

  • Modify: types/helico/area-do-aluno/type.ts
  • Modify: components/helico/performance-section/ExamPerformanceFilters.tsx
  • Test: tests/unit/components/performance-section/exam-performance-filters.test.tsx

Interfaces:

  • Produces: ExamType ganha 'escrito'. FILTERS_BY_TYPE['escrito'] = [MATERIA] (sem Fonte). TYPE_LABELS['escrito'] = 'Simulado Escrito'.

  • Step 1: Escrever o teste que falha

Adicionar em tests/unit/components/performance-section/exam-performance-filters.test.tsx:

it('dá só matéria ao Simulado Escrito Geral, sem fonte', () => {
  montar('escrito');

  expect(secundarias()).toEqual(['Matéria']);
  expect(screen.getByText('Simulado Escrito')).toBeInTheDocument();
});
  • Step 2: Rodar o teste e confirmar que falha

Run: cd /private/var/www/app-helico && npx vitest run tests/unit/components/performance-section/exam-performance-filters.test.tsx Expected: FAIL — TS não compila ('escrito' não é ExamType) e/ou Record<ExamType, ...> incompleto barra o build.

  • Step 3: Implementar

Em types/helico/area-do-aluno/type.ts (linha ~100):

export type ExamType =
  | 'vf'
  | 'objetivo'
  | 'escrito'
  | 'discursivo'
  | 'dissertativa'
  | 'peca-pratica';

Em components/helico/performance-section/ExamPerformanceFilters.tsx, TYPE_LABELS:

const TYPE_LABELS: Record<ExamType, string> = {
  vf: 'Verdadeiro e Falso',
  objetivo: 'Objetivo',
  escrito: 'Simulado Escrito',
  discursivo: 'Discursiva',
  dissertativa: 'Dissertativa',
  'peca-pratica': 'Peça Prática',
};

FILTERS_BY_TYPE:

const FILTERS_BY_TYPE: Record<ExamType, SecondaryFilter[]> = {
  vf: [DISCIPLINA, FONTE],
  objetivo: [DISCIPLINA, FONTE],
  escrito: [MATERIA],
  discursivo: [MATERIA],
  dissertativa: [MATERIA],
  'peca-pratica': [MATERIA],
};
  • Step 4: Rodar os testes e confirmar que passam

Run: mesmo comando do Step 2. Expected: PASS — inclusive 'não tem mais filtro de módulo', que não é afetado.

  • Step 5: Commit
cd /private/var/www/app-helico
git add types/helico/area-do-aluno/type.ts components/helico/performance-section/ExamPerformanceFilters.tsx tests/unit/components/performance-section/exam-performance-filters.test.tsx
git commit -m "feat(desempenho): pílula 'Simulado Escrito' (Geral) nos filtros de tipo"

Task 8: ExamPerformanceSection — cruzar Disciplina/Matéria/Fonte com o tipo

Files:

  • Modify: components/helico/performance-section/ExamPerformanceSection.tsx
  • Test: tests/unit/components/performance-section/exam-performance-section.test.tsx

Interfaces:

  • Consumes: usePlatformPerformance({enrolmentId, courseId, enabled}): {data: PlatformPerformanceResponse} (hook já existente); clampPercent (Task 6).
  • Produces: componente passa a aceitar seleção de Disciplina/Matéria/Fonte, filtrando performance.breakdown e recalculando as barras por módulo.

Nota de design: a view padrão (sem filtro secundário) continua vindo de usePerformance()/by_module.by_exam_type (nota_real por resultado inteiro) — comportamento idêntico ao de hoje. Só quando Disciplina/Matéria/Fonte está ativo o componente troca pra performance.breakdown (granularidade de resposta pra V/F/Objetivo, de resultado pra escritas) — os dois números podem divergir ligeiramente porque são unidades estatísticas diferentes (média de notas de prova vs. % de acerto por resposta); isso é esperado e documentado na spec.

  • Step 1: Escrever os testes que falham

Adicionar em tests/unit/components/performance-section/exam-performance-section.test.tsx, um mock de usePlatformPerformance e useActivePlatformParams (o componente vai precisar dos dois hooks agora, junto com usePerformance):

vi.mock('@/hooks/useActivePlatformParams', () => ({
  useActivePlatformParams: () => ({
    enrolmentId: 1,
    courseId: 1,
    hasContext: true,
    isLoading: false,
  }),
}));

const BREAKDOWN = [
  { module_id: 1, discipline_id: 10, exam_type: 'exam_truefalse', source: 'legislation', score: 90, count: 2 },
  { module_id: 1, discipline_id: 10, exam_type: 'exam_truefalse', source: 'doctrine', score: 30, count: 2 },
  { module_id: 2, discipline_id: 10, exam_type: 'exam_truefalse', source: 'legislation', score: 40, count: 1 },
];

vi.mock('@/hooks/usePlatformPerformance', () => ({
  usePlatformPerformance: () => ({
    data: {
      by_discipline: [{ discipline_id: 10, name: 'Civil', module_id: 1 }],
      by_module: [
        { module_id: 1, module_name: 'Módulo 1' },
        { module_id: 2, module_name: 'Módulo 2' },
      ],
      breakdown: BREAKDOWN,
    },
    isLoading: false,
  }),
}));

E os testes:

it('cruza o tipo escolhido com a fonte selecionada', async () => {
  const ExamPerformanceSection = await importarSecao();

  render(<ExamPerformanceSection />);

  await userEvent.click(screen.getByRole('combobox', { name: 'Fonte' }));
  await userEvent.click(screen.getByRole('option', { name: 'Lei' }));

  expect(screen.getByText('Módulo 1: 90')).toBeInTheDocument();
  expect(screen.getByText('Módulo 2: 40')).toBeInTheDocument();
  expect(screen.queryByText('Módulo 1: 60')).not.toBeInTheDocument();
});

it('volta pro dado padrão quando a fonte é limpa', async () => {
  const ExamPerformanceSection = await importarSecao();

  render(<ExamPerformanceSection />);

  await userEvent.click(screen.getByRole('combobox', { name: 'Fonte' }));
  await userEvent.click(screen.getByRole('option', { name: 'Lei' }));
  // Trocar de tipo reseta o filtro secundário — evita herdar Fonte pra um tipo sem Fonte.
  await escolherTipo('Objetivo');

  expect(
    screen.queryByRole('combobox', { name: 'Fonte' }),
  ).not.toBeInTheDocument();
});
  • Step 2: Rodar os testes e confirmar que falham

Run: cd /private/var/www/app-helico && npx vitest run tests/unit/components/performance-section/exam-performance-section.test.tsx Expected: FAIL — pílulas de Disciplina/Fonte continuam disabled/sem opções, sem efeito nas barras.

  • Step 3: Implementar

Em components/helico/performance-section/ExamPerformanceSection.tsx, reescrever o componente:

//components/helico/performance-section/ExamPerformanceSection.tsx
'use client';

import { useMemo, useState } from 'react';
import {
  ExamModulePerformance,
  ExamPerformanceEntry,
  ExamType,
} from '@/types/helico/area-do-aluno/type';
import {
  PlatformPerformanceExamType,
  PlatformPerformanceExamTypeBreakdownRow,
  PlatformPerformanceSource,
} from '@/lib/moodle';
import { clampPercent } from '@/lib/helico/platform-adapters';
import { usePerformance } from '@/hooks/usePerformance';
import { useActivePlatformParams } from '@/hooks/useActivePlatformParams';
import { usePlatformPerformance } from '@/hooks/usePlatformPerformance';
import { Performance } from '@/components/helico/icons/Performance';
import { ExamPerformanceChart } from '@/components/helico/performance-section/ExamPerformanceChart';
import { ExamPerformanceFilters } from '@/components/helico/performance-section/ExamPerformanceFilters';
import { ExamPerformanceFilterSkeleton } from '@/components/helico/skeleton/ExamPerformanceFilterSkeleton';
import { ExamPerformanceSkeleton } from '@/components/helico/skeleton/ExamPerformanceSkeleton';
import { Skeleton } from '@/components/helico/skeleton/Skeleton';

const EMPTY_NO_DATA = 'Você ainda não iniciou a sua trilha';

const EMPTY_BY_TYPE: Record<ExamType, string> = {
  vf: 'Nenhum simulado de verdadeiro e falso respondido ainda',
  objetivo: 'Nenhum simulado objetivo respondido ainda',
  escrito: 'Nenhum simulado escrito respondido ainda',
  discursivo: 'Nenhuma prova discursiva respondida ainda',
  dissertativa: 'Nenhuma dissertativa respondida ainda',
  'peca-pratica': 'Nenhuma peça prática respondida ainda',
};

/** exam_type bruto (payload) que cada pílula de tipo representa. */
const PLATFORM_TYPES_BY_EXAM_TYPE: Record<ExamType, PlatformPerformanceExamType[]> = {
  vf: ['diagnostic_initial', 'diagnostic_verify', 'exam_truefalse'],
  objetivo: ['exam_objective'],
  escrito: ['exam_written'],
  discursivo: ['exam_written_discursiva'],
  dissertativa: ['exam_written_dissertacao'],
  'peca-pratica': ['exam_written_peca_pratica'],
};

function buildModuleView(
  entries: ExamPerformanceEntry[],
  type: ExamType,
): ExamModulePerformance[] {
  return entries
    .filter((entry) => entry.moduleId !== null && entry.type === type)
    .map((entry) => ({ module: entry.moduleName, value: entry.value }));
}

/** Recorta o breakdown pelo tipo + disciplina/matéria + fonte escolhidos, e
 * agrega por módulo com média ponderada por `count`. */
function buildModuleViewFromBreakdown(
  breakdown: PlatformPerformanceExamTypeBreakdownRow[],
  moduleNames: Map<number, string>,
  type: ExamType,
  disciplineId: number | null,
  source: PlatformPerformanceSource | null,
): ExamModulePerformance[] {
  const platformTypes = PLATFORM_TYPES_BY_EXAM_TYPE[type];
  const rows = breakdown.filter((row) => {
    if (!platformTypes.includes(row.exam_type)) return false;
    if (disciplineId !== null && row.discipline_id !== disciplineId) return false;
    if (source !== null && row.source !== source) return false;
    return true;
  });

  const byModule = new Map<number, { total: number; count: number }>();
  rows.forEach((row) => {
    const acc = byModule.get(row.module_id) ?? { total: 0, count: 0 };
    acc.total += row.score * row.count;
    acc.count += row.count;
    byModule.set(row.module_id, acc);
  });

  return Array.from(byModule.entries()).map(([moduleId, acc]) => ({
    module: moduleNames.get(moduleId) ?? `Módulo ${moduleId}`,
    value: clampPercent(acc.total / acc.count),
  }));
}

export function ExamPerformanceSection() {
  const [type, setType] = useState<ExamType>('vf');
  const [disciplineId, setDisciplineId] = useState<number | null>(null);
  const [source, setSource] = useState<PlatformPerformanceSource | null>(null);
  const { data, isError, isLoading } = usePerformance();
  const { enrolmentId, courseId, hasContext } = useActivePlatformParams();
  const { data: performance } = usePlatformPerformance({
    enrolmentId,
    courseId,
    enabled: hasContext,
  });

  const entries = useMemo(
    () => (data && !isError ? data : []),
    [data, isError],
  );

  const disciplineOptions = useMemo(
    () =>
      (performance?.by_discipline ?? [])
        .filter((d, index, all) => all.findIndex((x) => x.discipline_id === d.discipline_id) === index)
        .map((d) => ({ value: String(d.discipline_id), label: d.name })),
    [performance],
  );

  const moduleNames = useMemo(() => {
    const map = new Map<number, string>();
    (performance?.by_module ?? []).forEach((m) => map.set(m.module_id, m.module_name));
    return map;
  }, [performance]);

  const hasSecondaryFilter = disciplineId !== null || source !== null;

  const chartData: ExamModulePerformance[] = useMemo(() => {
    if (hasSecondaryFilter && performance) {
      return buildModuleViewFromBreakdown(
        performance.breakdown,
        moduleNames,
        type,
        disciplineId,
        source,
      );
    }
    return buildModuleView(entries, type);
  }, [entries, type, performance, moduleNames, disciplineId, source, hasSecondaryFilter]);

  const emptyMessage = useMemo(
    () => (entries.length === 0 ? EMPTY_NO_DATA : EMPTY_BY_TYPE[type]),
    [entries, type],
  );

  function handleTypeChange(nextType: ExamType) {
    setType(nextType);
    // Reseta os filtros secundários — evita herdar Fonte pra um tipo escrito
    // (que nunca tem Fonte) ou Matéria de um tipo que não a suporta.
    setDisciplineId(null);
    setSource(null);
  }

  return (
    <section className="flex w-full items-start gap-6 p-[16_16_8_16] rounded-2xl bg-[linear-gradient(49deg,rgba(255,255,255,1)_70%,rgba(232,242,255,1)_100%)]">
      <div className="p-0 flex flex-col items-start gap-2 justify-center flex-1 grow">
        <div className="flex flex-col items-start gap-2.5 self-stretch w-full">
          <div className="flex items-center justify-between self-stretch w-full gap-3">
            {!isLoading ? (
              <div className="flex items-center gap-3">
                <div className="flex w-8 h-8 justify-center gap-2 p-1 bg-blue-60 rounded-xl aspect-square shadow-[0px_2.4px_2.4px_#e1edfc] items-center">
                  <Performance className="w-6 h-6 text-white" />
                </div>

                <h4 className="font-semibold text-dark-blue text-base whitespace-nowrap leading-[22.5px]">
                  Desempenho por Simulado
                </h4>
              </div>
            ) : (
              <div className="flex items-center gap-3">
                <Skeleton style={{ height: 30, width: 30 }} />
                <Skeleton style={{ height: 18, width: 300 }} />
              </div>
            )}

            {!isLoading ? (
              <ExamPerformanceFilters
                type={type}
                onTypeChangeAction={handleTypeChange}
                disciplineId={disciplineId}
                onDisciplineChangeAction={setDisciplineId}
                disciplineOptions={disciplineOptions}
                source={source}
                onSourceChangeAction={setSource}
              />
            ) : (
              <ExamPerformanceFilterSkeleton />
            )}
          </div>
        </div>

        {!isLoading ? (
          <ExamPerformanceChart data={chartData} emptyMessage={emptyMessage} />
        ) : (
          <ExamPerformanceSkeleton />
        )}
      </div>
    </section>
  );
}

ExamPerformanceFilters precisa das novas props (disciplineId, onDisciplineChangeAction, disciplineOptions, source, onSourceChangeAction) — atualizar a assinatura e desabilitar só quando não houver opções:

type Props = {
  type: ExamType;
  onTypeChangeAction: (value: ExamType) => void;
  disciplineId: number | null;
  onDisciplineChangeAction: (value: number | null) => void;
  disciplineOptions: FilterOption[];
  source: PlatformPerformanceSource | null;
  onSourceChangeAction: (value: PlatformPerformanceSource | null) => void;
};

const SOURCE_OPTIONS: FilterOption[] = [
  { value: 'legislation', label: 'Lei' },
  { value: 'doctrine', label: 'Doutrina' },
  { value: 'jurisprudence', label: 'Jurisprudência' },
];

export function ExamPerformanceFilters({
  type,
  onTypeChangeAction,
  disciplineId,
  onDisciplineChangeAction,
  disciplineOptions,
  source,
  onSourceChangeAction,
}: Props) {
  const secondary = FILTERS_BY_TYPE[type];

  return (
    <div className="flex flex-wrap items-center justify-end gap-2">
      <ExamPerformanceFilterPill
        value={type}
        options={TYPE_OPTIONS}
        onChangeAction={(value) => onTypeChangeAction(value as ExamType)}
        ariaLabel="Tipo de simulado"
      />

      {secondary.includes(DISCIPLINA) || secondary.includes(MATERIA) ? (
        <ExamPerformanceFilterPill
          value={disciplineId === null ? '' : String(disciplineId)}
          options={disciplineOptions}
          onChangeAction={(value) => onDisciplineChangeAction(value === '' ? null : Number(value))}
          ariaLabel={secondary.includes(MATERIA) ? 'Matéria' : 'Disciplina'}
          placeholder={secondary.includes(MATERIA) ? 'Matéria' : 'Disciplina'}
        />
      ) : null}

      {secondary.includes(FONTE) ? (
        <ExamPerformanceFilterPill
          value={source ?? ''}
          options={SOURCE_OPTIONS}
          onChangeAction={(value) => onSourceChangeAction(value === '' ? null : (value as PlatformPerformanceSource))}
          ariaLabel="Fonte"
          placeholder="Fonte"
        />
      ) : null}
    </div>
  );
}

(Import PlatformPerformanceSource de @/lib/moodle no topo de ExamPerformanceFilters.tsx; DISCIPLINA/MATERIA/FONTE continuam sendo os objetos-constante já existentes, agora usados pra decidir QUAL pílula secundária mostrar em vez de renderizar todas desabilitadas — remover o array FILTERS_BY_TYPE[type].map(...) antigo de pílulas placeholder.)

  • Step 4: Rodar os testes e confirmar que passam

Run: mesmo comando do Step 2, e também npx vitest run tests/unit/components/performance-section/exam-performance-filters.test.tsx (garantir que a mudança de assinatura de ExamPerformanceFilters não quebrou o Task 7 — ajustar a chamada montar() desse arquivo pra passar as novas props obrigatórias com valores neutros: disciplineId={null} onDisciplineChangeAction={vi.fn()} disciplineOptions={[]} source={null} onSourceChangeAction={vi.fn()}). Expected: PASS em ambos os arquivos.

  • Step 5: Commit
cd /private/var/www/app-helico
git add components/helico/performance-section/ExamPerformanceSection.tsx components/helico/performance-section/ExamPerformanceFilters.tsx tests/unit/components/performance-section/exam-performance-section.test.tsx tests/unit/components/performance-section/exam-performance-filters.test.tsx
git commit -m "feat(desempenho): cruza Disciplina/Matéria/Fonte com o tipo em Desempenho por Simulado"

Task 9: PerformanceEfficiencySection — Disciplina + Módulo + Tipo de Simulado

Files:

  • Modify: components/helico/performance-section/PerformanceEfficiencySection.tsx
  • Test: tests/unit/components/performance-section/performance-efficiency-section.test.tsx

Interfaces:

  • Consumes: performance.breakdown (Task 6), clampPercent.

  • Produces: componente ganha 3 pílulas reais (Disciplina, Módulo, Tipo de Simulado limitado a V/F|Objetivo) cruzando com by_source[]/breakdown[]; sem filtro, comportamento idêntico ao atual (mapPerformanceToSources).

  • Step 1: Escrever os testes que falham

Reescrever tests/unit/components/performance-section/performance-efficiency-section.test.tsx:

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeAll, describe, expect, it, vi } from 'vitest';

beforeAll(() => {
  Element.prototype.hasPointerCapture = vi.fn(() => false);
  Element.prototype.setPointerCapture = vi.fn();
  Element.prototype.releasePointerCapture = vi.fn();
  Element.prototype.scrollIntoView = vi.fn();
});

vi.mock('@/hooks/useActivePlatformParams', () => ({
  useActivePlatformParams: () => ({
    enrolmentId: 1,
    courseId: 1,
    hasContext: true,
    isLoading: false,
  }),
}));

const BREAKDOWN = [
  { module_id: 1, discipline_id: 10, exam_type: 'exam_truefalse', source: 'legislation', score: 90, count: 2 },
  { module_id: 2, discipline_id: 10, exam_type: 'exam_objective', source: 'legislation', score: 30, count: 2 },
];

vi.mock('@/hooks/usePlatformPerformance', () => ({
  usePlatformPerformance: () => ({
    data: {
      by_source: [
        { source: 'legislation', total: 10, correct: 6, score: 60 },
        { source: 'doctrine', total: 10, correct: 3, score: 30 },
      ],
      by_discipline: [{ discipline_id: 10, name: 'Civil', module_id: 1 }],
      by_module: [
        { module_id: 1, module_name: 'Módulo 1' },
        { module_id: 2, module_name: 'Módulo 2' },
      ],
      breakdown: BREAKDOWN,
    },
    isLoading: false,
  }),
}));

async function importarSecao() {
  const mod = await import(
    '@/components/helico/performance-section/PerformanceEfficiencySection'
  );

  return mod.PerformanceEfficiencySection;
}

describe('PerformanceEfficiencySection', () => {
  it('segue desenhando as barras por fonte sem filtro', async () => {
    const PerformanceEfficiencySection = await importarSecao();

    render(<PerformanceEfficiencySection />);

    expect(screen.getByText('Lei')).toBeInTheDocument();
    expect(screen.getByText('Doutrina')).toBeInTheDocument();
  });

  it('mostra as pílulas de Disciplina, Módulo e Tipo de Simulado habilitadas', async () => {
    const PerformanceEfficiencySection = await importarSecao();

    render(<PerformanceEfficiencySection />);

    expect(screen.getByRole('combobox', { name: 'Disciplina' })).not.toBeDisabled();
    expect(screen.getByRole('combobox', { name: 'Módulo' })).not.toBeDisabled();
    expect(screen.getByRole('combobox', { name: 'Tipo de simulado' })).not.toBeDisabled();
  });

  it('cruza módulo e tipo de simulado ao filtrar', async () => {
    const PerformanceEfficiencySection = await importarSecao();

    render(<PerformanceEfficiencySection />);

    await userEvent.click(screen.getByRole('combobox', { name: 'Tipo de simulado' }));
    await userEvent.click(screen.getByRole('option', { name: 'Objetivo' }));

    // Só a linha de módulo 2 / exam_objective (score 30) deve aparecer.
    expect(screen.getByText('Lei')).toBeInTheDocument();
    expect(screen.queryByText('Doutrina')).not.toBeInTheDocument();
  });
});
  • Step 2: Rodar os testes e confirmar que falham

Run: cd /private/var/www/app-helico && npx vitest run tests/unit/components/performance-section/performance-efficiency-section.test.tsx Expected: FAIL — pílula “Disciplina” continua fixa/desabilitada, “Módulo” e “Tipo de simulado” não existem.

  • Step 3: Implementar
//components/helico/performance-section/PerformanceEfficiencySection.tsx
'use client';

import { useMemo, useState } from 'react';
import { mapPerformanceToSources, PerformanceSourceItem } from '@/lib/helico/platform-adapters';
import { useActivePlatformParams } from '@/hooks/useActivePlatformParams';
import { usePlatformPerformance } from '@/hooks/usePlatformPerformance';
import { getPerformanceColorHex } from '@/lib/helico/performance-level';
import { Card, CardContent } from '@/components/ui/card';
import { BookGlasses } from '@/components/helico/icons/BookGlasses';
import { BarChart } from '@/components/helico/performance-section/BarChart';
import { ExamPerformanceFilterPill } from '@/components/helico/performance-section/ExamPerformanceFilterPill';
import { BarPerformanceSectionSkeleton } from '@/components/helico/skeleton/BarPerformanceSectionSkeleton';

type Props = {
  barStyle?: React.CSSProperties;
};

/** Módulo/Disciplina/Fonte só existem em breakdown[]; Tipo de simulado aqui
 * é sempre um destes dois — Fonte não faz sentido em Escrita. */
type SourceExamType = 'exam_truefalse' | 'exam_objective';

const ALL = '';

const SOURCE_LABELS: Record<string, string> = {
  legislation: 'Lei',
  doctrine: 'Doutrina',
  jurisprudence: 'Jurisprudência',
};

export function PerformanceEfficiencySection({ barStyle }: Props) {
  const {
    enrolmentId,
    courseId,
    hasContext,
    isLoading: isContextLoading,
  } = useActivePlatformParams();
  const { data: performance, isLoading } = usePlatformPerformance({
    enrolmentId,
    courseId,
    enabled: hasContext,
  });

  const [moduleId, setModuleId] = useState<string>(ALL);
  const [disciplineId, setDisciplineId] = useState<string>(ALL);
  const [examType, setExamType] = useState<string>(ALL);

  const disciplineOptions = useMemo(
    () =>
      (performance?.by_discipline ?? [])
        .filter((d, index, all) => all.findIndex((x) => x.discipline_id === d.discipline_id) === index)
        .map((d) => ({ value: String(d.discipline_id), label: d.name })),
    [performance],
  );
  const moduleOptions = useMemo(
    () => (performance?.by_module ?? []).map((m) => ({ value: String(m.module_id), label: m.module_name })),
    [performance],
  );
  const examTypeOptions = [
    { value: 'exam_truefalse', label: 'Verdadeiro e Falso' },
    { value: 'exam_objective', label: 'Objetivo' },
  ];

  const hasFilter = moduleId !== ALL || disciplineId !== ALL || examType !== ALL;

  const data: PerformanceSourceItem[] = useMemo(() => {
    if (!performance) return [];
    if (!hasFilter) return mapPerformanceToSources(performance);

    const rows = performance.breakdown.filter((row) => {
      if (row.source === undefined) return false;
      if (moduleId !== ALL && String(row.module_id) !== moduleId) return false;
      if (disciplineId !== ALL && String(row.discipline_id) !== disciplineId) return false;
      if (examType !== ALL && row.exam_type !== (examType as SourceExamType)) return false;
      return true;
    });

    const bySource = new Map<string, { total: number; count: number }>();
    rows.forEach((row) => {
      const acc = bySource.get(row.source as string) ?? { total: 0, count: 0 };
      acc.total += row.score * row.count;
      acc.count += row.count;
      bySource.set(row.source as string, acc);
    });

    return Array.from(bySource.entries()).map(([source, acc], index) => {
      const percentage = Math.round(acc.total / acc.count);
      return {
        id: index + 1,
        caption: SOURCE_LABELS[source] ?? source,
        percentage,
        color: getPerformanceColorHex(percentage),
      };
    });
  }, [performance, hasFilter, moduleId, disciplineId, examType]);

  const sectionIsLoading = isContextLoading || isLoading;

  return (
    <section className="flex flex-col items-start gap-6 self-stretch w-full">
      {!sectionIsLoading ? (
        <Card className="flex flex-wrap items-start content-start justify-center gap-6 p-[16_16_8_16] self-stretch w-full rounded-2xl bg-[linear-gradient(75deg,#FFF_13.6%,#E8F2FF_88.67%)]">
          <CardContent className="p-0 w-full flex flex-col items-start gap-4 justify-center flex-1 grow">
            <div className="flex flex-wrap items-center justify-between gap-3 self-stretch w-full">
              <div className="flex h-12 items-center gap-3">
                <div className="flex w-8 h-8 justify-center content-center gap-2 p-1 bg-blue-60 rounded-xl aspect-square shadow-[0px_2.4px_2.4px_#e1edfc] items-center">
                  <BookGlasses className="w-6 h-6 text-white" />
                </div>

                <h4 className="font-semibold text-dark-blue text-base whitespace-nowrap leading-[22.5px]">
                  Desempenho por Tipo de Fonte
                </h4>
              </div>

              <div className="flex flex-wrap items-center gap-2">
                <ExamPerformanceFilterPill
                  value={moduleId}
                  options={moduleOptions}
                  onChangeAction={setModuleId}
                  ariaLabel="Módulo"
                  placeholder="Módulo"
                />
                <ExamPerformanceFilterPill
                  value={disciplineId}
                  options={disciplineOptions}
                  onChangeAction={setDisciplineId}
                  ariaLabel="Disciplina"
                  placeholder="Disciplina"
                />
                <ExamPerformanceFilterPill
                  value={examType}
                  options={examTypeOptions}
                  onChangeAction={setExamType}
                  ariaLabel="Tipo de simulado"
                  placeholder="Tipo de simulado"
                />
              </div>
            </div>

            <div className="w-full overflow-x-auto overflow-y-hidden">
              <BarChart data={data} />
            </div>
          </CardContent>
        </Card>
      ) : (
        <BarPerformanceSectionSkeleton />
      )}
    </section>
  );
}

(getPerformanceColorHex vem de @/lib/helico/performance-level — platform-adapters.ts só o importa de lá pra usar dentro de mapPerformanceToSources, não o reexporta.)

  • Step 4: Rodar os testes e confirmar que passam

Run: mesmo comando do Step 2. Expected: PASS.

  • Step 5: Commit
cd /private/var/www/app-helico
git add components/helico/performance-section/PerformanceEfficiencySection.tsx tests/unit/components/performance-section/performance-efficiency-section.test.tsx
git commit -m "feat(desempenho): filtros de Módulo, Disciplina e Tipo de Simulado em Desempenho por Tipo de Fonte"

Task 10: DisciplinePerformanceSection — filtro de Módulo

Files:

  • Modify: components/helico/performance-section/DisciplinePerformanceSection.tsx
  • Create: tests/unit/components/performance-section/discipline-performance-section.test.tsx

Interfaces:

  • Consumes: mapPerformanceToDisciplines() (Task 6, já retorna moduleId).

  • Produces: pílula “Módulo” nova, seguindo o padrão de ModulePerformanceSection (ALL_MODULES = 'todos').

  • Step 1: Escrever o teste que falha

tests/unit/components/performance-section/discipline-performance-section.test.tsx:

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { beforeAll, describe, expect, it, vi } from 'vitest';

beforeAll(() => {
  Element.prototype.hasPointerCapture = vi.fn(() => false);
  Element.prototype.setPointerCapture = vi.fn();
  Element.prototype.releasePointerCapture = vi.fn();
  Element.prototype.scrollIntoView = vi.fn();
});

vi.mock('@/hooks/useActivePlatformParams', () => ({
  useActivePlatformParams: () => ({
    enrolmentId: 1,
    courseId: 1,
    hasContext: true,
    isLoading: false,
  }),
}));

vi.mock('@/hooks/usePlatformPerformance', () => ({
  usePlatformPerformance: () => ({
    data: {
      by_discipline: [
        { discipline_id: 10, name: 'Civil', score: 80, module_id: 1 },
        { discipline_id: 10, name: 'Civil', score: 60, module_id: 2 },
        { discipline_id: 20, name: 'Penal', score: 90, module_id: 1 },
      ],
      by_module: [
        { module_id: 1, module_name: 'Módulo 1' },
        { module_id: 2, module_name: 'Módulo 2' },
      ],
    },
    isLoading: false,
  }),
}));

async function importarSecao() {
  const mod = await import(
    '@/components/helico/performance-section/DisciplinePerformanceSection'
  );

  return mod.DisciplinePerformanceSection;
}

describe('DisciplinePerformanceSection', () => {
  it('agrega por disciplina quando nenhum módulo está selecionado', async () => {
    const DisciplinePerformanceSection = await importarSecao();

    render(<DisciplinePerformanceSection />);

    expect(screen.getByText('Civil')).toBeInTheDocument();
    expect(screen.getByText('Penal')).toBeInTheDocument();
  });

  it('recorta por módulo quando escolhido', async () => {
    const DisciplinePerformanceSection = await importarSecao();

    render(<DisciplinePerformanceSection />);

    await userEvent.click(screen.getByRole('combobox', { name: 'Módulo' }));
    await userEvent.click(screen.getByRole('option', { name: 'Módulo 2' }));

    expect(screen.getByText('Civil')).toBeInTheDocument();
    expect(screen.queryByText('Penal')).not.toBeInTheDocument();
  });
});
  • Step 2: Rodar o teste e confirmar que falha

Run: cd /private/var/www/app-helico && npx vitest run tests/unit/components/performance-section/discipline-performance-section.test.tsx Expected: FAIL — não existe pílula “Módulo” no componente atual.

  • Step 3: Implementar
//components/helico/performance-section/DisciplinePerformanceSection.tsx
'use client';

import React, { useMemo, useState } from 'react';
import { mapPerformanceToDisciplines } from '@/lib/helico/platform-adapters';
import { useActivePlatformParams } from '@/hooks/useActivePlatformParams';
import { usePlatformPerformance } from '@/hooks/usePlatformPerformance';
import { Card, CardContent } from '@/components/ui/card';
import { BookMortarboard } from '@/components/helico/icons/BookMortarboard';
import { DisciplineCharCard } from '@/components/helico/performance-section/DisciplineCharCard';
import { ExamPerformanceFilterPill } from '@/components/helico/performance-section/ExamPerformanceFilterPill';
import { DisciplinePerformanceSectionSkeleton } from '@/components/helico/skeleton/DisciplinePerformanceSectionSkeleton';

/** Valor do filtro quando nenhum módulo específico está escolhido. */
const ALL_MODULES = 'todos';

export function DisciplinePerformanceSection() {
  const {
    enrolmentId,
    courseId,
    hasContext,
    isLoading: isContextLoading,
  } = useActivePlatformParams();
  const { data: performance, isLoading } = usePlatformPerformance({
    enrolmentId,
    courseId,
    enabled: hasContext,
  });
  const [moduleValue, setModuleValue] = useState<string>(ALL_MODULES);

  const rows = useMemo(
    () => (performance ? mapPerformanceToDisciplines(performance) : []),
    [performance],
  );

  const moduleOptions = useMemo(
    () => [
      { value: ALL_MODULES, label: 'Todos os módulos' },
      ...(performance?.by_module ?? []).map((m) => ({
        value: String(m.module_id),
        label: m.module_name,
      })),
    ],
    [performance],
  );

  const data = useMemo(() => {
    const filtered =
      moduleValue === ALL_MODULES
        ? rows
        : rows.filter((item) => String(item.moduleId) === moduleValue);

    if (moduleValue !== ALL_MODULES) {
      return filtered;
    }

    // Sem filtro: agrega por disciplina (média ponderada por módulo).
    const byDiscipline = new Map<string, { discipline: string; total: number; count: number }>();
    filtered.forEach((item) => {
      const acc = byDiscipline.get(item.id) ?? { discipline: item.discipline, total: 0, count: 0 };
      acc.total += item.percentage;
      acc.count += 1;
      byDiscipline.set(item.id, acc);
    });

    return Array.from(byDiscipline.entries()).map(([id, acc]) => ({
      id,
      discipline: acc.discipline,
      percentage: Math.round(acc.total / acc.count),
    }));
  }, [rows, moduleValue]);

  const sectionIsLoading = isContextLoading || isLoading;

  return (
    <section className="flex flex-col items-start gap-6 self-stretch w-full">
      {!sectionIsLoading ? (
        <Card className="flex flex-wrap items-start content-start justify-center gap-6 p-[16_16_8_16] self-stretch w-full rounded-2xl bg-[linear-gradient(75deg,#FFF_13.6%,#E8F2FF_88.67%)]">
          <CardContent className="p-0 w-full flex flex-col items-start gap-4 justify-center flex-1 grow">
            <div className="flex justify-between items-center gap-2 self-stretch w-full">
              <div className="flex h-12 items-center gap-3 self-stretch w-full">
                <div className="flex w-8 h-8 justify-center content-center gap-2 p-1 bg-blue-60 rounded-xl aspect-square shadow-[0px_2.4px_2.4px_#e1edfc] items-center">
                  <BookMortarboard className="w-6 h-6 text-white" />
                </div>

                <h4 className="font-semibold text-dark-blue text-base whitespace-nowrap leading-[22.5px]">
                  Desempenho por Disciplina
                </h4>
              </div>

              <ExamPerformanceFilterPill
                value={moduleValue}
                options={moduleOptions}
                onChangeAction={setModuleValue}
                ariaLabel="Módulo"
              />
            </div>

            <div className="w-full overflow-x-auto overflow-y-hidden">
              <div className="flex flex-nowrap gap-5 p-3">
                {data.map((item) => (
                  <div key={item.id} className="shrink-0">
                    <DisciplineCharCard
                      discipline={item.discipline}
                      percentage={item.percentage}
                    />
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      ) : (
        <DisciplinePerformanceSectionSkeleton />
      )}
    </section>
  );
}

(justify-beetween — typo pré-existente no arquivo original — corrigido pra justify-between de passagem, já que a linha está sendo tocada mesmo.)

  • Step 4: Rodar o teste e confirmar que passa

Run: mesmo comando do Step 2. Expected: PASS.

  • Step 5: Commit
cd /private/var/www/app-helico
git add components/helico/performance-section/DisciplinePerformanceSection.tsx tests/unit/components/performance-section/discipline-performance-section.test.tsx
git commit -m "feat(desempenho): filtro de Módulo em Desempenho por Disciplina"

Task 11: Verificação de dados — matrícula 225

Sem código — investigação manual no ambiente local, depois de todos os tasks anteriores mergeados/rodando.

  • Step 1: Resolver o student_plan_id da matrícula 225
docker exec helico-postgres psql -U helico -d helico -c "
SELECT itemid, meta_key, meta_value FROM mdl_helico_itemmeta
WHERE meta_key = 'enrolment_id' AND meta_value = '225';
"

Isso dá o itemid do item type='student_plan' cujo enrolment_id é 225 — esse itemid é o student_plan_id usado no restante da investigação.

  • Step 2: Listar os result de Simulado Escrito dessa matrícula
docker exec helico-postgres psql -U helico -d helico -c "
SELECT i.id AS result_id, m_slot.meta_value AS slot_id, m_nota.meta_value AS nota_real
FROM mdl_helico_items i
JOIN mdl_helico_itemmeta m_plan ON m_plan.itemid = i.id AND m_plan.meta_key = 'student_plan_id'
JOIN mdl_helico_itemmeta m_type ON m_type.itemid = i.id AND m_type.meta_key = 'slot_type' AND m_type.meta_value = 'exam_written'
LEFT JOIN mdl_helico_itemmeta m_slot ON m_slot.itemid = i.id AND m_slot.meta_key = 'slot_id'
LEFT JOIN mdl_helico_itemmeta m_nota ON m_nota.itemid = i.id AND m_nota.meta_key = 'nota_real'
WHERE i.type = 'activity_result' AND m_plan.meta_value = '<student_plan_id do Step 1>';
"
  • Step 3: Pra cada slot_id encontrado, ler o ctx_subtype
docker exec helico-postgres psql -U helico -d helico -c "
SELECT meta_value FROM mdl_helico_itemmeta WHERE itemid = <slot_id> AND meta_key = 'context';
"

Decodificar o JSON manualmente e conferir o campo ctx_subtype. Se a chave não existir no JSON, o subtipo efetivo é discursiva (default do slot_context_exam_written::from_metadata).

  • Step 4: Confirmar contra a API

Com o backend rodando local (feat/desempenho-filtros-cruzados já com todos os tasks anteriores), chamar:

curl -s -H "Authorization: Bearer <wstoken de teste>" \
  "http://helico.moodle.localhost/local/helico/ajax.php/api/v1/platform/study/225/performance" | \
  python3 -c "import json,sys; d=json.load(sys.stdin); print(json.dumps([r for r in d['breakdown'] if r['exam_type'].startswith('exam_written')], indent=2))"

Conferir: (a) cada result_id do Step 2 aparece refletido em pelo menos uma linha com o exam_type correto (exam_written_<subtipo do Step 3>); (b) nenhuma prova de Peça Prática ou Dissertação está contribuindo pro bucket exam_written_discursiva — esse era o bug documentado em app-helico/docs/api-gaps-platform.md §8; (c) o tamanho de breakdown retornado é razoável (dezenas de linhas, não centenas) — se for desproporcional, anotar isso como um achado pra reavaliar o recorte por querystring mencionado na spec §3.1.

  • Step 5: Registrar o resultado

Anexar as 3 conferências do Step 4 (com valores reais encontrados) na seção de verificação do Task 12 (atualização de documentação) antes de marcar a spec como implementada — se algum problema for encontrado, ele vira um novo bug a corrigir antes de fechar, não uma nota de rodapé.


Task 12: Atualizar documentação

Files:

  • Modify: docs/plataforma/api-integracoes/contratos/performance.md

  • Modify: docs/operacao/uc-007-desempenho.md

  • Modify: docs/_archive/specs/2026-08-28-desempenho-filtros-cruzados-design.md

  • Modify: /private/var/www/app-helico/docs/api-gaps-platform.md

  • Step 1: performance.md — documentar breakdown[]

Adicionar ao JSON de exemplo (após by_source):

  "breakdown": [
    { "module_id": 3, "discipline_id": 10, "exam_type": "exam_truefalse", "source": "legislation", "score": 57.6, "count": 12 },
    { "module_id": 2, "discipline_id": 7, "exam_type": "exam_written_peca_pratica", "score": 55.0, "count": 1 }
  ]

Adicionar uma seção ### breakdown[] — cruzamento de dimensões (copiar a tabela de campos de docs/_archive/specs/2026-08-28-desempenho-filtros-cruzados-design.md §3.1). Atualizar a tabela de by_exam_type[].type (linha ~156) e a de by_module[].by_exam_type[].type (linha ~145) incluindo os 4 novos valores possíveis (exam_written_discursiva, exam_written_dissertacao, exam_written_peca_pratica, mais o exam_written Geral que já existia). Adicionar module_id à tabela de by_discipline[] (linha ~119-126). Atualizar a lista de Calculators: na seção de Referências incluindo breakdown.

  • Step 2: uc-007-desempenho.md — atualizar exemplo de resposta

Adicionar breakdown ao JSON de exemplo (mesmo shape do Step 1) e uma linha na tabela de “Mapeamento de terms” referenciando breakdown[] como a fonte dos cruzamentos de “Desempenho por Simulado”/“Desempenho por Tipo de Fonte” quando um filtro secundário está ativo.

  • Step 3: Marcar a spec como implementada

Em docs/_archive/specs/2026-08-28-desempenho-filtros-cruzados-design.md, trocar Status: rascunho para revisão por Status: Implementado, e no final da seção “7. Verificação de dados — matrícula 225” colar os 3 achados reais do Task 11 Step 4/5.

  • Step 4: app-helico/docs/api-gaps-platform.md — marcar §8 como resolvido

No início da seção ## 8. /performance — cruzamento de dimensões (matéria e fonte), adicionar uma nota:

> **Resolvido em 2026-08-28** — implementado via `breakdown[]` (tabela de fatos), não o aninhamento originalmente esboçado nesta seção. Ver `moodle-local_helico/docs/_archive/specs/2026-08-28-desempenho-filtros-cruzados-design.md`.

E na tabela ## Prioridade sugerida, marcar os itens 4 e 5 (breakdown[] e separação de exam_type) como concluídos.

  • Step 5: Commit (2 repos)
cd /private/var/www/middag-work/moodle-local_helico
git add docs/plataforma/api-integracoes/contratos/performance.md docs/operacao/uc-007-desempenho.md docs/_archive/specs/2026-08-28-desempenho-filtros-cruzados-design.md
git commit -m "docs(desempenho): documenta breakdown[] e subtipos de Simulado Escrito"
cd /private/var/www/app-helico
git add docs/api-gaps-platform.md
git commit -m "docs: marca gap de cruzamento de desempenho (§8) como resolvido"

Self-Review

Cobertura da spec:

  • §2.1 (contrato breakdown[]) → Tasks 3, 4, 5.
  • §2.2 (vocabulário de subtipo, default discursiva) → Tasks 2, 4 (testes ...WithoutCtxSubtypeDefaultsToDiscursiva).
  • §2.3 (Geral cruza com Matéria) → Task 4 (exam_written sempre emitido junto do subtipo).
  • §2.4 (3 componentes, Disciplina fica fora do breakdown) → Tasks 1 (Disciplina), 3+4+9+8 (breakdown, Simulado e Fonte), 10 (Disciplina no front).
  • §3.1-3.4 (formato exato dos campos) → Tasks 3, 4, 5, 6.
  • §4 (serviços tocados) → Tasks 1, 2, 3, 4, 5 cobrem exatamente a tabela da spec.
  • §5 (frontend) → Tasks 6, 7, 8, 9, 10.
  • §6 (testes) → cada task de backend tem seu próprio Step de teste.
  • §7 (matrícula 225) → Task 11.
  • §8 (docs) → Task 12.

Scan de placeholder: nenhum “TBD”/“implementar depois” — todo step tem código completo ou comando exato.

Consistência de tipos: exam_written_discursiva/_dissertacao/_peca_pratica usados de forma idêntica em by_module_calculator_service.php (Task 2), breakdown_calculator_service.php (Task 4), lib/moodle.ts (Task 6) e nos componentes (Tasks 8/9). PlatformPerformanceExamTypeBreakdownRow definido uma vez (Task 6) e consumido sem redefinição nos Tasks 8/9.


Plano completo e salvo em docs/_archive/plans/2026-08-28-desempenho-filtros-cruzados.md. Duas opções de execução:

1. Subagent-Driven (recomendado) — um subagente fresco por task, revisão entre tasks, iteração rápida.

2. Inline Execution — execução em lote nesta sessão via executing-plans, com checkpoints de revisão.

Qual abordagem?

Navigation

Type to search…

↑↓ navigate↵ selectEsc close