Complete durable private Education review preparation and recovery
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-11 08:21:56 +02:00
parent bbc3c1c9bc
commit 6805b606a1
14 changed files with 1092 additions and 49 deletions
@@ -0,0 +1,174 @@
<?php
namespace Tests\Feature;
use App\Models\Course;
use App\Models\LabourDemand;
use App\Models\Occupation;
use App\Models\Project;
use App\Models\Skill;
use App\Models\TrainingCapacity;
use App\Models\TrainingProvider;
use App\Models\User;
use App\Services\EducationReviews;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tests\TestCase;
final class EducationReviewPreparationTest extends TestCase
{
use DatabaseTransactions;
private User $reviewer;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
config(['education.enabled' => true]);
$identity = DB::selectOne('select current_database() as name,inet_server_port() as port');
$this->assertSame('simulator_fiscal_delta_20261021_test', $identity->name);
$this->assertSame(55441, (int) $identity->port);
$this->reviewer = $this->manager();
}
private function manager(): User
{
$u = User::factory()->create();
config(['portal.managers' => [...config('portal.managers', []), $u->email]]);
$this->actingAs($u);
return $u;
}
private function record(string $kind): LabourDemand|TrainingCapacity
{
$place = (string) Str::uuid();
DB::table('geo_locations')->insert(['id' => $place, 'name' => 'SYNTHETIC province', 'code' => $place, 'location_type' => 'province']);
$data = ['occupation_id' => Occupation::create(['code' => (string) Str::uuid(), 'name' => 'SYNTHETIC occupation'])->id, 'skill_id' => Skill::create(['code' => (string) Str::uuid(), 'name' => 'SYNTHETIC skill'])->id,
'geo_location_id' => $place, 'qualification' => 'SYNTHETIC qualification', 'quantity' => 20, 'period_start' => today()->addMonth()->toDateString(), 'period_end' => today()->addMonths(2)->toDateString(),
'source' => 'SYNTHETIC documentary source', 'reference_date' => today()->toDateString(), 'valid_until' => today()->addYear()->toDateString(), 'submitted_by' => User::factory()->create()->id, 'status' => 'submitted', 'version_no' => 1];
if ($kind === 'demands') {
return LabourDemand::create([...$data, 'project_id' => Project::create(['code' => (string) Str::uuid(), 'name' => 'SYNTHETIC project', 'status' => 'draft'])->id, 'employer' => 'SYNTHETIC employer']);
}
$provider = TrainingProvider::create(['name' => 'SYNTHETIC provider', 'status' => 'candidate']);
$course = Course::create(['provider_id' => $provider->id, 'code' => (string) Str::uuid(), 'title' => 'SYNTHETIC course', 'status' => 'draft']);
return TrainingCapacity::create([...$data, 'course_id' => $course->id]);
}
private function state(LabourDemand|TrainingCapacity $record): array
{
$base = ['version_no' => 1, 'qualification' => 'SYNTHETIC qualification', 'quantity' => 20, 'status' => 'submitted', 'period_start' => $record->getRawOriginal('period_start'), 'period_end' => $record->getRawOriginal('period_end'),
'valid_until' => $record->getRawOriginal('valid_until'), 'source' => 'SYNTHETIC documentary source', 'reference_date' => today()->toDateString(), 'employer' => '', 'references' => []];
return ['values' => ['version_no' => 1, 'status' => 'reviewed', 'review_reason' => ' SENSITIVE SYNTHETIC PRIVATE REVIEW NOTE '], 'generation' => ['status' => 0, 'review_reason' => 1], 'base' => $base, 'pending' => null];
}
private function url(string $kind, LabourDemand|TrainingCapacity $r): string
{
return '/management/education/'.$kind.'/'.$r->id.'/review-preparation';
}
public function test_private_preparation_is_encrypted_actor_scoped_idempotent_and_preserves_the_declaration(): void
{
foreach (['demands', 'capacities'] as $kind) {
$record = $this->record($kind);
$before = $record->fresh()->getAttributes();
$url = $this->url($kind, $record);
$body = ['actor_id' => $this->reviewer->id, 'version' => 0, 'operation_key' => (string) Str::uuid(), 'snapshot' => $this->state($record)];
$response = $this->postJson($url, $body)->assertOk()->assertHeader('Cache-Control', 'no-store, private')->assertJsonPath('version', 1);
$this->assertStringContainsString('"references":{}', $response->getContent());
$saved = $response->json();
$this->assertSame($body['snapshot'], $saved['snapshot']);
$this->postJson($url, $body)->assertOk()->assertJsonPath('version', 1);
$query = DB::table('audit_events')->where('source_system', 'portal-education-review')->where('entity_id', $record->id)->where('action', 'review_preparation_saved');
$this->assertSame(1, $query->count());
$this->assertStringNotContainsString('SENSITIVE SYNTHETIC PRIVATE REVIEW NOTE', $query->value('after_data'));
$this->getJson($url)->assertOk()->assertJsonPath('snapshot.values.review_reason', $body['snapshot']['values']['review_reason']);
$this->assertSame($before, $record->fresh()->getAttributes());
$this->assertSame(0, DB::table('audit_events')->where('entity_id', $record->id)->where('action', 'review_committed')->count());
$this->get('/management/education/'.$kind.'/'.$record->id)->assertOk()->assertInertia(fn ($page) => $page->where('preparation.version', 1)->where('history.total', 0));
$this->manager();
$this->getJson($url)->assertOk()->assertJsonPath('version', 0)->assertJsonPath('snapshot', null);
$this->actingAs($this->reviewer);
$this->postJson($url, [...$body, 'snapshot' => [...$body['snapshot'], 'values' => [...$body['snapshot']['values'], 'review_reason' => 'DIFFERENT NOTE USING THE SAME KEY']]])->assertConflict();
}
}
public function test_private_preparation_optimistic_version_and_late_replay_never_replace_newer_notes(): void
{
$r = $this->record('demands');
$url = $this->url('demands', $r);
$first = ['actor_id' => $this->reviewer->id, 'version' => 0, 'operation_key' => (string) Str::uuid(), 'snapshot' => $this->state($r)];
$this->postJson($url, $first)->assertOk();
$second = [...$first, 'version' => 1, 'operation_key' => (string) Str::uuid()];
$second['snapshot']['values']['review_reason'] = 'SYNTHETIC deliberate newer note from a second window.';
$this->postJson($url, $second)->assertOk()->assertJsonPath('version', 2);
$this->postJson($url, $first)->assertOk()->assertJsonPath('version', 2)->assertJsonPath('snapshot.values.review_reason', $second['snapshot']['values']['review_reason']);
$this->postJson($url, [...$first, 'operation_key' => (string) Str::uuid()])->assertConflict();
$this->assertSame(2, DB::table('audit_events')->where('entity_id', $r->id)->where('action', 'review_preparation_saved')->count());
$other = $this->manager();
$this->postJson($url, $first)->assertConflict();
$this->getJson($url.'?actor_id='.$this->reviewer->id)->assertConflict();
$this->getJson($url)->assertOk()->assertJsonPath('snapshot', null)->assertJsonPath('actor_id', $other->id);
}
public function test_uncertain_review_is_recovered_from_its_private_intent_and_same_native_command_once(): void
{
$r = $this->record('demands');
$state = $this->state($r);
$key = (string) Str::uuid();
$state['pending'] = ['values' => [...$state['values'], 'client_key' => $key], 'reasonGeneration' => 1, 'statusGeneration' => 0, 'base' => $state['base']];
$state['values']['review_reason'] = 'SYNTHETIC later edit retained after an uncertain response.';
$state['generation']['review_reason'] = 2;
$url = $this->url('demands', $r);
$this->postJson($url, ['actor_id' => $this->reviewer->id, 'version' => 0, 'operation_key' => (string) Str::uuid(), 'snapshot' => $state])->assertOk();
$native = '/management/education/demands/'.$r->id.'/review';
$this->post($native, $state['pending']['values'])->assertRedirect();
$recovered = $this->getJson($url)->assertOk()->json('snapshot');
$this->assertSame($state, $recovered);
$this->post($native, $recovered['pending']['values'])->assertRedirect();
$this->assertSame(2, $r->fresh()->version_no);
$this->assertSame(1, DB::table('audit_events')->where('entity_id', $r->id)->where('action', 'review_committed')->count());
$context = app(EducationReviews::class)->context($this->reviewer, $r->fresh());
$this->assertSame($key, $context['commands'][0]['key']);
$page = $this->get('/management/education/demands/'.$r->id)->assertOk()->viewData('page')['props'];
$directory = base_path('outputs/education-review-preparation-20261111');
if (! is_dir($directory)) {
mkdir($directory, 0700, true);
}
file_put_contents($directory.'/recovered-page.json', json_encode(['synthetic' => true, 'transactional_QA' => true, 'props' => array_intersect_key($page, array_flip(['declaration', 'kind', 'actorId', 'today', 'references', 'preparation', 'history', 'backUrl']))], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
public function test_unreadable_private_preparation_and_unauthorised_access_preserve_previous_bytes(): void
{
$r = $this->record('demands');
$url = $this->url('demands', $r);
$bytes = json_encode(['education_preparation' => ['actor_id' => $this->reviewer->id, 'version' => 1, 'operation_key' => (string) Str::uuid(), 'hash' => str_repeat('a', 64), 'snapshot' => 'SYNTHETIC unreadable original encrypted bytes']], JSON_THROW_ON_ERROR);
DB::table('audit_events')->insert(['source_system' => 'portal-education-review', 'actor_user_id' => $this->reviewer->id, 'entity_type' => 'labour_demands', 'entity_id' => $r->id, 'action' => 'review_preparation_saved', 'data_classification' => 'restricted', 'after_data' => $bytes]);
$stored = DB::table('audit_events')->where('entity_id', $r->id)->where('action', 'review_preparation_saved')->value('after_data');
$this->getJson($url)->assertOk()->assertJsonPath('unavailable', true)->assertJsonPath('snapshot', null);
$this->postJson($url, ['actor_id' => $this->reviewer->id, 'version' => 1, 'operation_key' => (string) Str::uuid(), 'snapshot' => $this->state($r)])->assertConflict();
$this->assertSame($stored, DB::table('audit_events')->where('entity_id', $r->id)->where('action', 'review_preparation_saved')->value('after_data'));
$this->actingAs(User::factory()->create());
$this->getJson($url)->assertForbidden();
$this->postJson($url, [])->assertForbidden();
}
public function test_invalid_decrypted_snapshots_are_unavailable_without_losing_the_encrypted_original(): void
{
foreach (['{', json_encode(['unexpected' => 'SYNTHETIC invalid snapshot'], JSON_THROW_ON_ERROR)] as $plain) {
$r = $this->record('demands');
$cipher = Crypt::encryptString($plain);
DB::table('audit_events')->insert(['source_system' => 'portal-education-review', 'actor_user_id' => $this->reviewer->id, 'entity_type' => 'labour_demands', 'entity_id' => $r->id, 'action' => 'review_preparation_saved', 'data_classification' => 'restricted',
'after_data' => json_encode(['education_preparation' => ['version' => 1, 'operation_key' => (string) Str::uuid(), 'hash' => str_repeat('a', 64), 'snapshot' => $cipher]], JSON_THROW_ON_ERROR)]);
$this->getJson($this->url('demands', $r))->assertOk()->assertJsonPath('unavailable', true)->assertJsonPath('snapshot', null);
$actual = json_decode(DB::table('audit_events')->where('entity_id', $r->id)->value('after_data'), true);
$this->assertSame($cipher, $actual['education_preparation']['snapshot']);
}
}
}
@@ -0,0 +1,300 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { harness, props, text } from './helpers/education-review.mjs';
const initial = {
actor_id: 1,
kind: 'demands',
record_id: props().declaration.id,
version: 0,
operation_key: null,
snapshot: null,
unavailable: false,
};
const reason = 'Justificação e evidência da revisão';
const receipt = (request) => ({
actor_id: request.data.actor_id,
kind: request.url.split('/')[3],
record_id: request.url.split('/')[4],
version: request.data.version + 1,
operation_key: request.data.operation_key,
snapshot: request.data.snapshot,
unavailable: false,
});
test('private review preparation is recovered after remount and never decides on save or restore', async () => {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC deliberate reviewer note for later recovery.',
);
h.click('Guardar preparação da revisão');
assert.equal(h.sent.length, 0);
const request = h.preparations[0];
await h.preparationResponse(receipt(request));
const reopened = harness(props({ preparation: receipt(request) }));
assert.equal(reopened.field('education-review', reason).props.value, '');
reopened.click('Recuperar preparação guardada');
await reopened.preparationResponse(receipt(request));
assert.equal(
reopened.field('education-review', reason).props.value,
request.data.snapshot.values.review_reason,
);
assert.equal(reopened.sent.length, 0);
});
test('review waits for a durable intent; a lost preparation response retries exactly before one native decision', async () => {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC proof of durable intent before native decision.',
);
h.submit('education-review');
assert.equal(h.sent.length, 0);
const request = h.preparations[0];
assert.ok(request.data.snapshot.pending.values.client_key);
await h.preparationFailure(
new Error('SYNTHETIC lost persistence response'),
);
assert.equal(h.sent.length, 0);
h.submit('education-review');
assert.deepEqual(h.preparations[1].data, request.data);
await h.preparationResponse(receipt(request));
assert.equal(h.sent.length, 1);
assert.equal(
h.sent[0].data.client_key,
request.data.snapshot.pending.values.client_key,
);
h.fail(h.sent[0]);
const fresh = harness(props({ preparation: receipt(request) }));
fresh.click('Recuperar preparação guardada');
await fresh.preparationResponse(receipt(request));
fresh.submit('education-review');
const resumed = fresh.preparations.at(-1);
await fresh.preparationResponse(receipt(resumed));
assert.deepEqual(fresh.sent[0].data, h.sent[0].data);
});
test('restoring an older declaration requires comparison and preserves deliberate edits during loading', async () => {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC stored reasoning against the first version.',
);
h.click('Guardar preparação da revisão');
const saved = receipt(h.preparations[0]);
await h.preparationResponse(saved);
const fresh = harness(
props({
preparation: saved,
declaration: {
...h.props.declaration,
version_no: 2,
quantity: 40,
},
}),
);
fresh.click('Recuperar preparação guardada');
await fresh.preparationResponse(saved);
assert.match(text(fresh.tree), /A declaração mudou/);
fresh.submit('education-review');
assert.equal(fresh.sent.length, 0);
const loading = harness(props({ preparation: saved }));
loading.click('Recuperar preparação guardada');
loading.change(
'education-review',
reason,
'SYNTHETIC later edit while recovery response is pending.',
);
await loading.preparationResponse(saved);
assert.match(
loading.field('education-review', reason).props.value,
/later edit/,
);
assert.match(text(loading.tree), /não as substituiu/);
});
test('late private preparation responses cannot populate a different actor', async () => {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC private content for the original reviewer only.',
);
h.click('Guardar preparação da revisão');
const request = h.preparations[0];
h.render({
...h.props,
actorId: 3,
declaration: {
...h.props.declaration,
review_context: { actor_id: 3, commands: [] },
},
preparation: initial,
});
await h.preparationResponse(receipt(request));
assert.equal(h.field('education-review', reason).props.value, '');
assert.equal(h.sent.length, 0);
});
test('a newer saved preparation in another window never causes the older intent to be submitted', async () => {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC first window prepares a review.',
);
h.submit('education-review');
const request = h.preparations[0];
await h.preparationResponse({
...receipt(request),
version: 4,
operation_key: 'another-window',
});
assert.equal(h.sent.length, 0);
assert.match(text(h.tree), /noutra janela/);
h.submit('education-review');
assert.deepEqual(
h.preparations.at(-1).data,
request.data,
'A newer server version must not be adopted silently',
);
});
test('restoring a committed uncertain attempt acknowledges the native receipt and retains edits after sending', async () => {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC original submitted reason.',
);
h.submit('education-review');
const request = h.preparations[0];
await h.preparationResponse(receipt(request));
h.fail(h.sent[0]);
h.change(
'education-review',
reason,
'SYNTHETIC later deliberate note after lost native response.',
);
h.click('Guardar preparação da revisão');
const saved = receipt(h.preparations.at(-1));
await h.preparationResponse(saved);
const command = request.data.snapshot.pending.values.client_key;
const fresh = harness(
props({
preparation: saved,
declaration: {
...h.props.declaration,
version_no: 2,
status: 'reviewed',
review_context: {
actor_id: 1,
commands: [{ key: command, version: 2 }],
},
},
}),
);
fresh.click('Recuperar preparação guardada');
await fresh.preparationResponse(saved);
assert.equal(fresh.sent.length, 0);
assert.match(
fresh.field('education-review', reason).props.value,
/later deliberate note/,
);
assert.match(text(fresh.tree), /Revisão registada/);
});
test('a private preparation response for another account or declaration never unlocks a review', async () => {
for (const patch of [
{ actor_id: 2 },
{ record_id: 'another-record' },
{ kind: 'capacities' },
]) {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC note belongs to this reviewer and declaration only.',
);
h.submit('education-review');
const request = h.preparations[0];
await h.preparationResponse({ ...receipt(request), ...patch });
assert.equal(h.sent.length, 0);
assert.match(text(h.tree), /não pôde ser conferida/);
}
});
test('an unreadable persistence receipt cannot release the business decision', async () => {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC intent must remain recoverable before deciding.',
);
h.submit('education-review');
await h.preparationResponse({
...receipt(h.preparations[0]),
snapshot: null,
unavailable: true,
});
assert.equal(h.sent.length, 0);
assert.match(text(h.tree), /não pôde ser recuperada/);
});
test('edits made while a native decision is in flight can be saved without a second decision', async () => {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC original native decision reason.',
);
h.submit('education-review');
const first = h.preparations[0];
await h.preparationResponse(receipt(first));
assert.equal(h.sent[0].form.processing, true);
h.change(
'education-review',
reason,
'SYNTHETIC later note while native response is pending.',
);
h.click('Guardar preparação da revisão');
const during = h.preparations.at(-1);
assert.equal(
during.data.snapshot.pending.values.client_key,
h.sent[0].data.client_key,
);
assert.match(during.data.snapshot.values.review_reason, /later note/);
await h.preparationResponse(receipt(during));
assert.equal(h.sent.length, 1);
});
test('a receipt observed during recovery acknowledges the current declaration instead of a captured old page', async () => {
const h = harness(props({ preparation: initial }));
h.change(
'education-review',
reason,
'SYNTHETIC a review whose response was uncertain.',
);
h.submit('education-review');
const request = h.preparations[0];
await h.preparationResponse(receipt(request));
const fresh = harness(props({ preparation: receipt(request) }));
fresh.click('Recuperar preparação guardada');
fresh.render({
...fresh.props,
declaration: {
...fresh.props.declaration,
version_no: 2,
status: 'reviewed',
review_context: {
actor_id: 1,
commands: [
{
key: request.data.snapshot.pending.values.client_key,
version: 2,
},
],
},
},
});
await fresh.preparationResponse(receipt(request));
assert.equal(fresh.sent.length, 0);
assert.match(text(fresh.tree), /Revisão registada/);
});
@@ -61,6 +61,7 @@ export function harness(initial = props()) {
const frames = new Map(),
sent = [],
reloads = [],
preparations = [],
before = new Set(),
unload = new Set();
let active,
@@ -234,6 +235,18 @@ export function harness(initial = props()) {
taskStates: { open: 'Aberta', done: 'Conclu?da' },
},
};
mocks['./profile-json'] = {
profileJson: (url, data = {}, method = 'POST') =>
new Promise((resolve, reject) =>
preparations.push({
url,
data: clone(data),
method,
resolve,
reject,
}),
),
};
const operation = {
createOperationKey: () =>
`00000000-0000-4000-8000-${String(++sequence).padStart(12, '0')}`,
@@ -366,6 +379,23 @@ export function harness(initial = props()) {
render();
return {
sent,
preparations,
async preparationResponse(value, request = preparations.at(-1)) {
const previousWindow = globalThis.window;
globalThis.window = windowMock;
try {
request.resolve(clone(value));
await new Promise((resolve) => setImmediate(resolve));
render();
} finally {
globalThis.window = previousWindow;
}
},
async preparationFailure(error, request = preparations.at(-1)) {
request.reject(error);
await new Promise((resolve) => setImmediate(resolve));
render();
},
reloads,
render,
get props() {