Complete durable private Education review preparation and recovery
tests / ci (push) Canceled after 0s
tests / ci (push) Canceled after 0s
This commit is contained in:
@@ -21,11 +21,13 @@ use App\Services\EducationWorkQueue;
|
||||
use App\Services\InvestmentGeography;
|
||||
use App\Services\PortalAudit;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Inertia\Response;
|
||||
|
||||
@@ -166,6 +168,7 @@ class EducationController extends Controller
|
||||
Inertia::encryptHistory();
|
||||
|
||||
return tap(Inertia::render('education/declaration', ['declaration' => $row, 'kind' => $kind, 'actorId' => $request->user()->id, 'today' => now()->toDateString(),
|
||||
'preparation' => app(EducationReviews::class)->preparation($request->user(), $record),
|
||||
'history' => app(EducationReviews::class)->history($request->user(), $record),
|
||||
'backUrl' => route('management.education.index', $filters, false), 'references' => $references])->toResponse($request), static fn (\Symfony\Component\HttpFoundation\Response $response) => $response->headers->set('Cache-Control', 'private, no-store'));
|
||||
}
|
||||
@@ -203,6 +206,29 @@ class EducationController extends Controller
|
||||
return back()->with('success', 'Declaração registada para revisão independente.');
|
||||
}
|
||||
|
||||
public function reviewPreparation(Request $request, string $kind, string $id): JsonResponse
|
||||
{
|
||||
$service = app(EducationReviews::class);
|
||||
app(EducationAccess::class)->authorize($request->user());
|
||||
if ($request->isMethod('POST')) {
|
||||
// Like CRM preparations, retain partial text before business validation.
|
||||
$input = json_decode($request->getContent(), true);
|
||||
if (! is_array($input)) {
|
||||
throw ValidationException::withMessages(['snapshot' => 'A preparação deve ser enviada em JSON.']);
|
||||
}
|
||||
$view = $service->savePreparation($request->user(), $kind, $id, $input);
|
||||
} else {
|
||||
$expected = $request->validate(['actor_id' => 'sometimes|required|integer|min:1']);
|
||||
abort_if(isset($expected['actor_id']) && (int) $expected['actor_id'] !== $request->user()->id, 409, 'A conta mudou. Actualize a entrada antes de recuperar.');
|
||||
$record = match ($kind) {
|
||||
'demands' => LabourDemand::findOrFail($id), 'capacities' => TrainingCapacity::findOrFail($id), default => abort(404)
|
||||
};
|
||||
$view = $service->preparation($request->user(), $record);
|
||||
}
|
||||
|
||||
return response()->json($view)->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function review(Request $request, string $kind, string $id): RedirectResponse
|
||||
{
|
||||
$result = app(EducationReviews::class)->decide($request->user(), $kind, $id, $request->all());
|
||||
|
||||
@@ -6,10 +6,13 @@ use App\Models\LabourDemand;
|
||||
use App\Models\TrainingCapacity;
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Encryption\DecryptException;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use JsonException;
|
||||
|
||||
final class EducationReviews
|
||||
{
|
||||
@@ -55,6 +58,134 @@ final class EducationReviews
|
||||
});
|
||||
}
|
||||
|
||||
/** Private preparation only; never a decision or an authority grant.
|
||||
* @return array<string,mixed> */
|
||||
public function preparation(User $actor, LabourDemand|TrainingCapacity $record): array
|
||||
{
|
||||
app(EducationAccess::class)->authorize($actor);
|
||||
$event = $this->preparations($actor, $record)->orderByRaw("CASE WHEN (after_data->'education_preparation'->>'version') ~ '^[0-9]{1,10}$' THEN (after_data->'education_preparation'->>'version')::bigint END DESC NULLS LAST")->orderByDesc('occurred_at')->orderByDesc('id')->first(['after_data']);
|
||||
$value = $event ? json_decode($event->after_data, true, 512, JSON_THROW_ON_ERROR)['education_preparation'] : null;
|
||||
$snapshot = null;
|
||||
$unavailable = false;
|
||||
if ($value) {
|
||||
try {
|
||||
$decoded = json_decode(Crypt::decryptString($value['snapshot']), true, 512, JSON_THROW_ON_ERROR);
|
||||
$snapshot = Validator::make(['snapshot' => $decoded], $this->preparationRules($decoded))->validate()['snapshot'];
|
||||
} catch (DecryptException|JsonException|ValidationException) {
|
||||
$unavailable = true;
|
||||
}
|
||||
}
|
||||
// Empty reference maps remain JSON objects in the browser, like the declaration props.
|
||||
if (is_array($snapshot)) {
|
||||
if ($snapshot['base']['references'] === []) {
|
||||
$snapshot['base']['references'] = (object) [];
|
||||
}
|
||||
if (is_array($snapshot['pending']) && $snapshot['pending']['base']['references'] === []) {
|
||||
$snapshot['pending']['base']['references'] = (object) [];
|
||||
}
|
||||
}
|
||||
|
||||
return ['actor_id' => $actor->id, 'kind' => $record instanceof LabourDemand ? 'demands' : 'capacities', 'record_id' => $record->id, 'version' => (int) ($value['version'] ?? 0), 'operation_key' => $value['operation_key'] ?? null,
|
||||
'snapshot' => $snapshot, 'unavailable' => $unavailable];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed> */
|
||||
public function savePreparation(User $actor, string $kind, string $id, array $input): array
|
||||
{
|
||||
app(EducationAccess::class)->authorize($actor);
|
||||
$model = match ($kind) {
|
||||
'demands' => LabourDemand::class, 'capacities' => TrainingCapacity::class, default => abort(404)
|
||||
};
|
||||
$data = Validator::make($input, [...$this->preparationRules($input['snapshot'] ?? null),
|
||||
'actor_id' => 'required|integer|min:1', 'version' => 'required|integer|min:0', 'operation_key' => 'required|uuid'])->validate();
|
||||
abort_unless((int) $data['actor_id'] === $actor->id, 409, 'A conta mudou. Actualize a entrada antes de guardar a preparação.');
|
||||
$key = strtolower($data['operation_key']);
|
||||
$snapshot = $data['snapshot'];
|
||||
foreach (['values', 'base'] as $field) {
|
||||
$snapshot[$field]['version_no'] = (int) $snapshot[$field]['version_no'];
|
||||
}
|
||||
$snapshot['base']['quantity'] = (int) $snapshot['base']['quantity'];
|
||||
foreach (['status', 'review_reason'] as $field) {
|
||||
$snapshot['generation'][$field] = (int) $snapshot['generation'][$field];
|
||||
}
|
||||
if ($snapshot['pending'] !== null) {
|
||||
$snapshot['pending']['values']['version_no'] = (int) $snapshot['pending']['values']['version_no'];
|
||||
$snapshot['pending']['base']['version_no'] = (int) $snapshot['pending']['base']['version_no'];
|
||||
$snapshot['pending']['base']['quantity'] = (int) $snapshot['pending']['base']['quantity'];
|
||||
$snapshot['pending']['values']['client_key'] = strtolower($snapshot['pending']['values']['client_key']);
|
||||
foreach (['reasonGeneration', 'statusGeneration'] as $field) {
|
||||
$snapshot['pending'][$field] = (int) $snapshot['pending'][$field];
|
||||
}
|
||||
abort_unless($snapshot['pending']['values']['version_no'] === $snapshot['pending']['base']['version_no'], 422);
|
||||
abort_unless($snapshot['pending']['reasonGeneration'] <= $snapshot['generation']['review_reason'] && $snapshot['pending']['statusGeneration'] <= $snapshot['generation']['status'], 422);
|
||||
}
|
||||
abort_unless($snapshot['values']['version_no'] === $snapshot['base']['version_no'], 422);
|
||||
$hash = hash('sha256', json_encode(Arr::sortRecursive(['actor' => $actor->id, 'kind' => $kind, 'id' => $id,
|
||||
'version' => (int) $data['version'], 'snapshot' => $snapshot]), JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $model, $id, $data, $snapshot, $key, $hash): array {
|
||||
$record = $model::lockForUpdate()->findOrFail($id);
|
||||
$previous = $this->preparations($actor, $record)->whereRaw("after_data->'education_preparation'->>'operation_key' = ?", [$key])->first(['after_data']);
|
||||
if ($previous) {
|
||||
$receipt = json_decode($previous->after_data, true, 512, JSON_THROW_ON_ERROR)['education_preparation'];
|
||||
abort_unless(hash_equals($receipt['hash'], $hash), 409, 'Esta tentativa de guardar já foi usada com outros dados.');
|
||||
|
||||
return $this->preparation($actor, $record);
|
||||
}
|
||||
$current = $this->preparation($actor, $record);
|
||||
abort_unless($current['version'] === (int) $data['version'], 409, 'A preparação mudou noutra janela. Compare antes de substituir.');
|
||||
abort_if($current['unavailable'], 409, 'A preparação anterior não pôde ser recuperada e foi preservada.');
|
||||
abort_if($snapshot['base']['version_no'] > (int) $record->getAttribute('version_no'), 422, 'A versão analisada não existe nesta declaração.');
|
||||
DB::table('audit_events')->insert(['source_system' => self::SOURCE, 'actor_user_id' => $actor->id,
|
||||
'entity_type' => $record->getTable(), 'entity_id' => $id, 'action' => 'review_preparation_saved', 'data_classification' => 'restricted',
|
||||
'after_data' => json_encode(['education_preparation' => ['version' => $current['version'] + 1, 'operation_key' => $key, 'hash' => $hash,
|
||||
'snapshot' => Crypt::encryptString(json_encode($snapshot, JSON_THROW_ON_ERROR))]], JSON_THROW_ON_ERROR)]);
|
||||
|
||||
return $this->preparation($actor, $record);
|
||||
});
|
||||
}
|
||||
|
||||
private function preparations(User $actor, LabourDemand|TrainingCapacity $record): Builder
|
||||
{
|
||||
return DB::table('audit_events')->where('source_system', self::SOURCE)->where('actor_user_id', $actor->id)
|
||||
->where('entity_type', $record->getTable())->where('entity_id', $record->id)->where('action', 'review_preparation_saved');
|
||||
}
|
||||
|
||||
/** @return array<string,string> */
|
||||
private function preparationRules(mixed $snapshot): array
|
||||
{
|
||||
$rules = ['snapshot' => 'required|array:values,generation,base,pending', 'snapshot.values' => 'required|array:version_no,status,review_reason',
|
||||
'snapshot.generation' => 'required|array:status,review_reason', 'snapshot.pending' => 'present|nullable|array:values,reasonGeneration,statusGeneration,base'];
|
||||
$roots = ['snapshot'];
|
||||
if (is_array($snapshot) && is_array($snapshot['pending'] ?? null)) {
|
||||
$roots[] = 'snapshot.pending';
|
||||
$rules['snapshot.pending.values'] = 'required|array:version_no,status,review_reason,client_key';
|
||||
$rules['snapshot.pending.values.client_key'] = 'required|uuid';
|
||||
foreach (['reasonGeneration', 'statusGeneration'] as $field) {
|
||||
$rules['snapshot.pending.'.$field] = 'required|integer|min:0|max:1000000000';
|
||||
}
|
||||
}
|
||||
foreach (['status', 'review_reason'] as $field) {
|
||||
$rules['snapshot.generation.'.$field] = 'required|integer|min:0|max:1000000000';
|
||||
}
|
||||
foreach ($roots as $root) {
|
||||
$rules[$root.'.values.version_no'] = 'required|integer|min:1';
|
||||
$rules[$root.'.values.status'] = 'required|in:reviewed,rejected';
|
||||
$rules[$root.'.values.review_reason'] = 'present|string|max:3000';
|
||||
$rules[$root.'.base'] = 'required|array:version_no,qualification,quantity,status,period_start,period_end,valid_until,source,reference_date,employer,references';
|
||||
$rules[$root.'.base.version_no'] = 'required|integer|min:1';
|
||||
$rules[$root.'.base.quantity'] = 'required|integer|min:0';
|
||||
foreach (['qualification' => 250, 'status' => 40, 'period_start' => 40, 'period_end' => 40, 'valid_until' => 40, 'source' => 5000, 'reference_date' => 40, 'employer' => 1000] as $field => $max) {
|
||||
$rules[$root.'.base.'.$field] = 'present|string|max:'.$max;
|
||||
}
|
||||
$rules[$root.'.base.references'] = 'present|array:occupation,skill,project,course,location';
|
||||
$rules[$root.'.base.references.*'] = 'nullable|string|max:1000';
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
/** @return array{actor_id:int,commands:list<array{key:string,version:int}>} */
|
||||
public function context(User $actor, LabourDemand|TrainingCapacity $record): array
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user