From 930064269e48fbc0d1a814a6dacbcdbfc5d211d3 Mon Sep 17 00:00:00 2001
From: nala
Date: Fri, 27 Nov 2026 18:11:02 +0200
Subject: [PATCH] commit compras2 2711
---
.../Controllers/CapitalRegisterController.php | 58 +
app/Http/Controllers/EquipmentController.php | 2 +
.../ImportBankSupportController.php | 76 ++
.../Controllers/ImportDossierController.php | 5 +-
.../Controllers/ImportLegalController.php | 62 +
.../Controllers/ImportReadinessController.php | 24 +
.../Controllers/RequisitionController.php | 2 +
app/Models/InventoryLotAllocation.php | 6 +-
app/Services/CapitalAssignments.php | 115 ++
app/Services/CapitalRegister.php | 129 ++
app/Services/CapitalTrace.php | 54 +
app/Services/ImportBankSupport.php | 242 ++++
app/Services/ImportCostDocumentHealth.php | 14 +-
app/Services/ImportEstimates.php | 28 +-
app/Services/ImportEvidence.php | 5 +-
app/Services/ImportLegalAmounts.php | 113 ++
app/Services/ImportLegalEstimates.php | 76 ++
app/Services/ImportLegalRules.php | 256 ++++
app/Services/ImportReadiness.php | 144 ++
app/Services/ImportTariffCodes.php | 27 +-
app/Services/OrderPartsWorkflow.php | 5 +-
app/Services/PurchaseWorkflow.php | 2 +
config/capital-register.php | 3 +
config/import-bank-support.php | 3 +
config/import-legal.php | 3 +
config/import-readiness.php | 3 +
docs/desenvolvimento.md | 10 +
docs/matriz-sgc-reconciliada.md | 10 +
docs/orientacoes-continuidade.md | 10 +
docs/plano-entregas-sgc.md | 2 +
docs/proofs/capital-register-qa.json | 47 +
docs/proofs/import-bank-support-qa.json | 89 ++
docs/proofs/import-legal-amounts-qa.json | 140 ++
docs/proofs/import-legal-readiness-qa.json | 131 ++
.../components/capital-assignment-summary.tsx | 54 +
.../js/components/import-legal-charges.tsx | 252 ++++
.../js/components/import-tariff-summary.tsx | 22 +
resources/js/lib/journey-help.ts | 55 +
.../js/pages/equipment/capital-register.tsx | 412 ++++++
resources/js/pages/equipment/index.tsx | 7 +
resources/js/pages/purchases/show.tsx | 4 +
.../requisitions/capital-assignments.tsx | 306 +++++
resources/js/pages/requisitions/show.tsx | 11 +
.../js/pages/supply/import-bank-support.tsx | 820 ++++++++++++
resources/js/pages/supply/import-dossier.tsx | 20 +
resources/js/pages/supply/import-estimate.tsx | 266 ++++
resources/js/pages/supply/import-legal.tsx | 1155 +++++++++++++++++
.../js/pages/supply/import-readiness.tsx | 73 ++
resources/js/pages/supply/import-tariffs.tsx | 16 +
resources/js/types/purchase.ts | 2 +
resources/views/purchases/print.blade.php | 13 +
routes/web.php | 16 +
scripts/quotation-exchange-pg-check.php | 77 +-
.../budget-distribution-recovery-worker.php | 103 +-
tests/Concurrency/import-dossier-worker.php | 77 +-
.../import-legal-corpus-worker.php | 79 ++
.../Concurrency/import-legal-http-worker.php | 216 +++
tests/Feature/CapitalRegisterTest.php | 135 ++
tests/Feature/ImportBankSupportTest.php | 144 ++
tests/Feature/ImportEstimatesTest.php | 55 +
tests/Feature/ImportLegalEstimatesTest.php | 84 ++
tests/Feature/ImportLegalRulesTest.php | 183 +++
tests/Feature/ImportReadinessTest.php | 140 ++
tests/Feature/PurchaseAwardOrderTest.php | 63 +
tests/Support/ImportBankQaFixture.php | 35 +
tests/Support/ImportLegalQaFixture.php | 42 +
tests/Support/LandedQaReceipts.php | 34 +-
tests/Support/import-legal-http-router.php | 38 +
tests/Unit/LandedQaReceiptsTest.php | 92 ++
tests/frontend/capital-register.test.tsx | 89 ++
tests/frontend/import-bank-support.test.tsx | 143 ++
tests/frontend/import-legal-plan.test.tsx | 113 ++
tests/frontend/import-legal.test.tsx | 116 ++
tests/frontend/import-readiness.test.tsx | 88 ++
74 files changed, 7506 insertions(+), 40 deletions(-)
create mode 100644 app/Http/Controllers/CapitalRegisterController.php
create mode 100644 app/Http/Controllers/ImportBankSupportController.php
create mode 100644 app/Http/Controllers/ImportLegalController.php
create mode 100644 app/Http/Controllers/ImportReadinessController.php
create mode 100644 app/Services/CapitalAssignments.php
create mode 100644 app/Services/CapitalRegister.php
create mode 100644 app/Services/CapitalTrace.php
create mode 100644 app/Services/ImportBankSupport.php
create mode 100644 app/Services/ImportLegalAmounts.php
create mode 100644 app/Services/ImportLegalEstimates.php
create mode 100644 app/Services/ImportLegalRules.php
create mode 100644 app/Services/ImportReadiness.php
create mode 100644 config/capital-register.php
create mode 100644 config/import-bank-support.php
create mode 100644 config/import-legal.php
create mode 100644 config/import-readiness.php
create mode 100644 docs/proofs/capital-register-qa.json
create mode 100644 docs/proofs/import-bank-support-qa.json
create mode 100644 docs/proofs/import-legal-amounts-qa.json
create mode 100644 docs/proofs/import-legal-readiness-qa.json
create mode 100644 resources/js/components/capital-assignment-summary.tsx
create mode 100644 resources/js/components/import-legal-charges.tsx
create mode 100644 resources/js/pages/equipment/capital-register.tsx
create mode 100644 resources/js/pages/requisitions/capital-assignments.tsx
create mode 100644 resources/js/pages/supply/import-bank-support.tsx
create mode 100644 resources/js/pages/supply/import-legal.tsx
create mode 100644 resources/js/pages/supply/import-readiness.tsx
create mode 100644 tests/Concurrency/import-legal-corpus-worker.php
create mode 100644 tests/Concurrency/import-legal-http-worker.php
create mode 100644 tests/Feature/CapitalRegisterTest.php
create mode 100644 tests/Feature/ImportBankSupportTest.php
create mode 100644 tests/Feature/ImportLegalEstimatesTest.php
create mode 100644 tests/Feature/ImportLegalRulesTest.php
create mode 100644 tests/Feature/ImportReadinessTest.php
create mode 100644 tests/Support/ImportBankQaFixture.php
create mode 100644 tests/Support/ImportLegalQaFixture.php
create mode 100644 tests/Support/import-legal-http-router.php
create mode 100644 tests/frontend/capital-register.test.tsx
create mode 100644 tests/frontend/import-bank-support.test.tsx
create mode 100644 tests/frontend/import-legal-plan.test.tsx
create mode 100644 tests/frontend/import-legal.test.tsx
create mode 100644 tests/frontend/import-readiness.test.tsx
diff --git a/app/Http/Controllers/CapitalRegisterController.php b/app/Http/Controllers/CapitalRegisterController.php
new file mode 100644
index 0000000..e0a6dcf
--- /dev/null
+++ b/app/Http/Controllers/CapitalRegisterController.php
@@ -0,0 +1,58 @@
+user('web');
+ abort_unless($actor instanceof User, 403);
+ $filters = $request->validate(['page' => 'nullable|integer|min:1|max:1000000', 'history' => 'nullable|uuid', 'history_page' => 'nullable|integer|min:1|max:1000000',
+ 'origins_page' => 'nullable|integer|min:1|max:1000000', 'receipts_page' => 'nullable|integer|min:1|max:1000000']);
+ $props = $service->workspace($actor, $filters['history'] ?? null);
+ Inertia::encryptHistory();
+ $response = Inertia::render('equipment/capital-register', $props)->toResponse($request);
+ $response->headers->set('Cache-Control', 'private, no-store, max-age=0');
+
+ return $response;
+ }
+
+ public function store(Request $request, CapitalRegister $service): Response
+ {
+ $actor = $request->user('web');
+ abort_unless($actor instanceof User, 403);
+ $service->save($actor, $request->all());
+
+ return back()->with('success', 'Versão do cadastro preservada.');
+ }
+
+ public function assignments(Request $request, Requisition $requisition, CapitalAssignments $service): Response
+ {
+ $actor = $request->user('web');
+ abort_unless($actor instanceof User, 403);
+ $request->validate(['choices_page' => 'nullable|integer|min:1|max:1000000', 'history_page' => 'nullable|integer|min:1|max:1000000']);
+ Inertia::encryptHistory();
+ $response = Inertia::render('requisitions/capital-assignments', $service->workspace($actor, $requisition))->toResponse($request);
+ $response->headers->set('Cache-Control', 'private, no-store, max-age=0');
+
+ return $response;
+ }
+
+ public function assign(Request $request, Requisition $requisition, CapitalAssignments $service): Response
+ {
+ $actor = $request->user('web');
+ abort_unless($actor instanceof User, 403);
+ $service->save($actor, $requisition, $request->all());
+
+ return back()->with('success', 'Ligação documental preservada.');
+ }
+}
diff --git a/app/Http/Controllers/EquipmentController.php b/app/Http/Controllers/EquipmentController.php
index bb5d5b3..b45de8c 100644
--- a/app/Http/Controllers/EquipmentController.php
+++ b/app/Http/Controllers/EquipmentController.php
@@ -14,6 +14,7 @@ use App\Models\StockMovement;
use App\Models\StockOperation;
use App\Models\User;
use App\Services\AdministrativeGeography;
+use App\Services\CapitalRegister;
use App\Services\ConflictGuard;
use App\Services\CurrentActor;
use App\Services\EquipmentWarehouseRequests;
@@ -117,6 +118,7 @@ class EquipmentController extends Controller
'departments' => $departments->orderBy('name')->get(['id', 'name']),
'history' => StockOperation::query()->whereNotNull('equipment_id')->whereIn('equipment_id', $equipment->pluck('id'))->latest('id')->paginate(15),
'canManage' => $this->actor($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement]),
+ 'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
'canConfigure' => $this->actor($request)->hasFunctions([PurchasingRole::Admin]),
]);
}
diff --git a/app/Http/Controllers/ImportBankSupportController.php b/app/Http/Controllers/ImportBankSupportController.php
new file mode 100644
index 0000000..65b300f
--- /dev/null
+++ b/app/Http/Controllers/ImportBankSupportController.php
@@ -0,0 +1,76 @@
+user('web');
+ abort_unless($actor instanceof User, 403);
+ $request->validate(['bank_current_page' => 'nullable|integer|min:1|max:1000000', 'bank_history_page' => 'nullable|integer|min:1|max:1000000',
+ 'bank_documents_page' => 'nullable|integer|min:1|max:1000000']);
+ Inertia::encryptHistory();
+ $response = Inertia::render('supply/import-bank-support', $service->workspace($actor, $import))->toResponse($request);
+ $response->headers->set('Cache-Control', 'private, no-store, max-age=0');
+
+ return $response;
+ }
+
+ public function store(Request $request, SupplyRecord $import, ImportBankSupport $service): RedirectResponse
+ {
+ $actor = $request->user('web');
+ abort_unless($actor instanceof User, 403);
+ $service->save($actor, $import, $request->all());
+
+ return back()->with('success', 'Acompanhamento documental bancário versionado.');
+ }
+
+ public function export(Request $request, SupplyRecord $import, ImportBankSupport $service): Response
+ {
+ $actor = $request->user('web');
+ abort_unless($actor instanceof User, 403);
+ $service->assertReadable($actor, $import);
+
+ return response()->streamDownload(function () use ($actor, $import, $service) {
+ $output = fopen('php://output', 'w');
+ if ($output === false) {
+ throw new \RuntimeException('Não foi possível exportar o acompanhamento bancário.');
+ }
+ $text = fn ($value) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', (string) $value) ? "'".$value : $value;
+ fwrite($output, "\xEF\xBB\xBF");
+ fputcsv($output, ['Acompanhamento documental bancário', 'Gerado em', now()->toIso8601String(), 'Não certifica cumprimento nem executa transferências ou submissões JUE'], ';', '"', '');
+ fputcsv($output, ['Termo', 'Versão', 'Situação registada', 'Documento único / declaração', 'Requisitos conhecidos', 'Tipos e quantidades pedidos', 'Fonte dos requisitos',
+ 'Suportes seleccionados', 'Comprovativo de entrega', 'Data efectiva da entrega documentada', 'Fundamento da entrega', 'Prazo documental', 'Fonte do prazo', 'Alertas actuais', 'Motivo'], ';', '"', '');
+ $service->report($actor, $import, function (SupplyRecord $record, array $issues) use ($output, $text) {
+ $documents = [];
+ foreach ($record->snapshot['documents'] as $document) {
+ $documents[$document['id']] = $document;
+ }
+ $reference = fn ($id) => $id === null ? 'Por associar' : ($documents[$id]['reference'] ?? 'Indeterminado');
+ $requirements = [];
+ foreach ($record->data['required_support_counts'] as $type => $count) {
+ $requirements[] = ImportDossier::TYPES[$type].': '.$count;
+ }
+ $state = match ($record->state) {
+ 'ready' => 'Documentos reunidos; entrega por documentar', 'documented' => 'Comprovativo de entrega associado', default => 'Documentação incompleta'
+ };
+ fputcsv($output, array_map($text, [$reference($record->data['commitment_document_id']), $record->version, $state,
+ $reference($record->data['declaration_document_id']), $record->data['requirements_known'] ? 'Sim' : 'Desconhecidos',
+ $record->data['requirements_known'] ? (implode(' | ', $requirements) ?: 'Nenhum tipo exigido segundo a fonte registada') : 'Desconhecidos', $record->data['requirements_basis'],
+ implode(' | ', array_map($reference, $record->data['support_document_ids'])), $reference($record->data['submission_document_id']), $record->data['submitted_on'] ?? 'Desconhecida', $record->data['submission_basis'] ?? 'Por indicar',
+ $record->data['due_on'] ?? 'Desconhecido', $record->data['deadline_basis'] ?? 'Não indicado', implode(' | ', $issues), $record->reason]), ';', '"', '');
+ });
+ fclose($output);
+ }, 'suporte-bancario-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
+ }
+}
diff --git a/app/Http/Controllers/ImportDossierController.php b/app/Http/Controllers/ImportDossierController.php
index 394ea83..a22583e 100644
--- a/app/Http/Controllers/ImportDossierController.php
+++ b/app/Http/Controllers/ImportDossierController.php
@@ -4,9 +4,11 @@ namespace App\Http\Controllers;
use App\Models\SupplyRecord;
use App\Models\User;
+use App\Services\ImportBankSupport;
use App\Services\ImportDossier;
use App\Services\ImportEvidence;
use App\Services\ImportParties;
+use App\Services\ImportReadiness;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Inertia\Inertia;
@@ -28,7 +30,8 @@ final class ImportDossierController extends Controller
Inertia::encryptHistory();
$actor = $this->actor($request);
$response = Inertia::render('supply/import-dossier', [...$service->workspace($actor, $import),
- 'parties' => app(ImportParties::class)->workspace($actor, $import, $search)])->toResponse($request);
+ 'parties' => app(ImportParties::class)->workspace($actor, $import, $search),
+ 'bankSupportReady' => app(ImportBankSupport::class)->ready(), 'readinessReady' => app(ImportReadiness::class)->ready()])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
diff --git a/app/Http/Controllers/ImportLegalController.php b/app/Http/Controllers/ImportLegalController.php
new file mode 100644
index 0000000..4b08205
--- /dev/null
+++ b/app/Http/Controllers/ImportLegalController.php
@@ -0,0 +1,62 @@
+user('web');
+ abort_unless($actor instanceof User, 403);
+ $filters = $request->validate(['rules_page' => 'nullable|integer|min:1|max:1000000', 'legal_history_page' => 'nullable|integer|min:1|max:1000000', 'legal_sources_page' => 'nullable|integer|min:1|max:1000000', 'legal_estimates_page' => 'nullable|integer|min:1|max:1000000',
+ 'code' => 'nullable|string|max:40', 'origin' => 'nullable|string|max:120', 'sector' => 'nullable|string|max:160', 'date' => 'nullable|date_format:Y-m-d']);
+ $workspace = $service->workspace($actor, $requisition);
+ $date = $filters['date'] ?? today()->toDateString();
+ $suggestions = empty($filters['code']) ? [] : $service->suggestions($actor, $requisition, $filters['code'], $filters['origin'] ?? '', $filters['sector'] ?? '', $date);
+ Inertia::encryptHistory();
+
+ $response = Inertia::render('supply/import-legal', [...$workspace, 'filters' => [...$filters, 'date' => $date], 'suggestions' => $suggestions])->toResponse($request);
+ $response->headers->set('Cache-Control', 'private, no-store, max-age=0');
+
+ return $response;
+ }
+
+ public function store(Request $request, Requisition $requisition, ImportLegalRules $service): Response
+ {
+ $actor = $request->user('web');
+ abort_unless($actor instanceof User, 403);
+ $service->workspace($actor, $requisition);
+ $service->save($actor, $request->except('file'), $request->file('file'));
+
+ return back()->with('success', 'Versão da base legal registada.');
+ }
+
+ public function source(Request $request, Requisition $requisition, int $source, ImportLegalRules $service): Response
+ {
+ $actor = $request->user('web');
+ abort_unless($actor instanceof User, 403);
+ $record = $service->source($actor, $requisition, $source);
+ $bytes = app(ImportEvidence::class)->bytes($record);
+
+ return response($bytes, 200, ['Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename="fonte-legal-'.$record->id.'.'.pathinfo($record->snapshot['evidence']['path'], PATHINFO_EXTENSION).'"',
+ 'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
+ }
+
+ public function estimate(Request $request, Requisition $requisition, ImportLegalEstimates $service): Response
+ {
+ $actor = $request->user('web');
+ abort_unless($actor instanceof User, 403);
+ $service->save($actor, $requisition, $request->all());
+
+ return back()->with('success', 'Estimativa documentada; sem efeitos financeiros ou pagamentos.');
+ }
+}
diff --git a/app/Http/Controllers/ImportReadinessController.php b/app/Http/Controllers/ImportReadinessController.php
new file mode 100644
index 0000000..df9f351
--- /dev/null
+++ b/app/Http/Controllers/ImportReadinessController.php
@@ -0,0 +1,24 @@
+user('web');
+ abort_unless($actor instanceof User, 403);
+ Inertia::encryptHistory();
+ $response = Inertia::render('supply/import-readiness', $service->workspace($actor, $import))->toResponse($request);
+ $response->headers->set('Cache-Control', 'private, no-store, max-age=0');
+
+ return $response;
+ }
+}
diff --git a/app/Http/Controllers/RequisitionController.php b/app/Http/Controllers/RequisitionController.php
index 7fbc73a..404755d 100644
--- a/app/Http/Controllers/RequisitionController.php
+++ b/app/Http/Controllers/RequisitionController.php
@@ -13,6 +13,7 @@ use App\Models\TechnicalReview;
use App\Models\Tenant;
use App\Models\User;
use App\Services\ApprovalRouting;
+use App\Services\CapitalRegister;
use App\Services\ComparisonPolicy;
use App\Services\ConflictGuard;
use App\Services\EquipmentWorkflow;
@@ -125,6 +126,7 @@ class RequisitionController extends Controller
'canEdit' => app(OrganizationAccess::class)->canRequest($this->actor($request)) && $requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft',
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
'importEstimatesReady' => app(ImportEstimates::class)->ready(),
+ 'capitalRegisterReady' => app(CapitalRegister::class)->ready(),
'canDecide' => $requisition->canDecide($this->actor($request)),
'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft'
&& $requisition->requester_id === $this->actor($request)->id && app(OrganizationAccess::class)->canRequest($this->actor($request)),
diff --git a/app/Models/InventoryLotAllocation.php b/app/Models/InventoryLotAllocation.php
index eb02103..479db9d 100644
--- a/app/Models/InventoryLotAllocation.php
+++ b/app/Models/InventoryLotAllocation.php
@@ -5,7 +5,11 @@ namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
-/** @property int $lot_id */
+/**
+ * @property int $lot_id
+ * @property int $stock_item_id
+ * @property int $warehouse_id
+ */
class InventoryLotAllocation extends Model
{
use BelongsToTenant;
diff --git a/app/Services/CapitalAssignments.php b/app/Services/CapitalAssignments.php
new file mode 100644
index 0000000..6f6cf29
--- /dev/null
+++ b/app/Services/CapitalAssignments.php
@@ -0,0 +1,115 @@
+ready(), 503);
+ app(ConflictGuard::class)->lockCompany($actor);
+ $actor = app(CurrentActor::class)->lock($actor);
+ abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
+ $request = Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id);
+
+ return [$actor, $request];
+ }
+
+ /** @return array */
+ public function workspace(User $actor, Requisition $request): array
+ {
+ return DB::transaction(function () use ($actor, $request) {
+ [$actor, $request] = $this->context($actor, $request);
+
+ return ['requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description']),
+ 'current' => app(SupplyPlanning::class)->latest('capital_assignment')->where('data->requisition_id', $request->id)->get(),
+ 'choices' => app(SupplyPlanning::class)->latest('capital_register')->where('state', 'active')->where('data->department_id', $request->department_id)
+ ->orderBy('data->code')->paginate(15, ['id', 'version', 'data'], 'choices_page')->withQueryString(),
+ 'history' => SupplyRecord::query()->where('kind', 'capital_assignment')->where('data->requisition_id', $request->id)
+ ->latest('id')->paginate(15, ['*'], 'history_page')->withQueryString(),
+ 'canWrite' => $request->status === 'draft' && $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor)
+ && ! app(ConflictGuard::class)->participationBlocked($actor, $request),
+ 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
+ });
+ }
+
+ /** @param array $input */
+ public function save(User $actor, Requisition $request, array $input): SupplyRecord
+ {
+ $data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
+ 'item_id' => 'required|integer|min:1', 'capital_id' => 'present|nullable|integer|min:1', 'reason' => 'required|string|min:10|max:4000'])->validate();
+ $data['operation_key'] = strtolower($data['operation_key']);
+ $hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
+
+ return DB::transaction(function () use ($actor, $request, $data, $hash) {
+ [$actor, $request] = $this->context($actor, $request);
+ abort_unless($request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor), 403);
+ app(ConflictGuard::class)->assertParticipation($actor, $request);
+ $retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
+ if ($retry !== null) {
+ abort_unless($retry->kind === 'capital_assignment' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
+
+ return $retry;
+ }
+ abort_unless($request->status === 'draft', 403);
+ $item = $request->items()->whereKey($data['item_id'])->firstOrFail();
+ $old = app(SupplyPlanning::class)->latest('capital_assignment')->where('data->requisition_item_id', $item->id)->first();
+ abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A ligação mudou. Reveja a versão actual.');
+ $source = $data['capital_id'] === null ? null : app(SupplyPlanning::class)->latest('capital_register')->where('state', 'active')
+ ->where('data->department_id', $request->department_id)->whereKey($data['capital_id'])->firstOrFail();
+ $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'capital_assignment',
+ 'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
+ 'state' => $source === null ? 'cleared' : 'linked', 'created_by' => $actor->id,
+ 'data' => ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'capital_id' => $source?->id],
+ 'snapshot' => ['item' => $this->item($item), 'source' => $source?->only(['id', 'record_key', 'version', 'state', 'data', 'snapshot']), 'financial_effects' => false],
+ 'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
+ app(RequisitionWorkflow::class)->audit($actor, 'capital.assignment_recorded', $request, $old?->toArray(), ['record' => $record->toArray()]);
+
+ return $record;
+ });
+ }
+
+ /** @return array */
+ private function item(RequisitionItem $item): array
+ {
+ return $item->only(['id', 'description', 'unit', 'quantity', 'purchase_type', 'equipment_id', 'category_context']);
+ }
+
+ /** Preserve accepted choices even after a later rename/archive. New choices require a current active source.
+ * @param list $itemIds
+ * @return array>
+ */
+ public function freezeForItems(User $actor, array $itemIds): array
+ {
+ abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
+ if (! Schema::hasTable('supply_records')) {
+ return [];
+ }
+ $records = app(SupplyPlanning::class)->latest('capital_assignment')->whereIn('data->requisition_item_id', $itemIds)->where('state', 'linked')->get();
+ if ($records->isEmpty()) {
+ return [];
+ }
+ abort_unless(app(CapitalRegister::class)->ready(), 503, 'Preserve a capacidade das ligações a projectos e imobilizado antes de emitir a ordem.');
+ $result = [];
+ foreach ($records as $record) {
+ $item = RequisitionItem::query()->whereKey($record->data['requisition_item_id'])->firstOrFail();
+ Requisition::query()->visibleTo($actor)->whereKey($item->requisition_id)->firstOrFail();
+ abort_unless($record->snapshot['item'] === $this->item($item), 409, 'O artigo mudou. Reveja a ligação ao projecto ou imobilizado.');
+ $result[$item->id] = $record->only(['id', 'version', 'data', 'snapshot', 'reason']);
+ }
+ ksort($result, SORT_NUMERIC);
+
+ return $result;
+ }
+}
diff --git a/app/Services/CapitalRegister.php b/app/Services/CapitalRegister.php
new file mode 100644
index 0000000..5a69456
--- /dev/null
+++ b/app/Services/CapitalRegister.php
@@ -0,0 +1,129 @@
+environment('testing')
+ && (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
+ || ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
+ && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
+ }
+
+ private function actor(User $actor, bool $write = false): User
+ {
+ abort_unless($this->ready(), 503);
+ app(ConflictGuard::class)->lockCompany($actor);
+ $actor = app(CurrentActor::class)->lock($actor);
+ abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
+ // Reuse the native equipment register's capabilities and departmental scope.
+ abort_unless($actor->hasFunctions($write ? ['admin', 'warehouse', 'procurement']
+ : ['admin', 'warehouse', 'procurement', 'finance', 'department_head']), 403);
+
+ return $actor;
+ }
+
+ /** @return Builder */
+ private function visible(User $actor): Builder
+ {
+ return app(SupplyPlanning::class)->latest('capital_register')
+ ->when($actor->departmentScoped(), fn ($q) => $q->where('data->department_id', $actor->department_id));
+ }
+
+ /** @return array */
+ public function workspace(User $actor, ?string $historyKey = null): array
+ {
+ return DB::transaction(function () use ($actor, $historyKey) {
+ $actor = $this->actor($actor);
+ if ($historyKey !== null) {
+ $this->visible($actor)->where('record_key', $historyKey)->firstOrFail();
+ }
+ $departments = Department::query()->when($actor->departmentScoped(), fn ($q) => $q->whereKey($actor->department_id));
+ $equipment = Equipment::query()->when($actor->departmentScoped(), fn ($q) => $q->where('department_id', $actor->department_id));
+
+ return ['records' => $this->visible($actor)->orderBy('data->code')->paginate(15)->withQueryString(),
+ 'history' => $historyKey === null ? null : SupplyRecord::query()->where('kind', 'capital_register')->where('record_key', $historyKey)
+ ->orderByDesc('version')->paginate(15, ['*'], 'history_page')->withQueryString(),
+ 'trace' => $historyKey === null ? null : app(CapitalTrace::class)->workspace($actor, $historyKey),
+ 'departments' => $departments->orderBy('name')->get(['id', 'name']),
+ 'equipment' => $equipment->orderBy('code')->get(['id', 'code', 'description', 'department_id']),
+ 'canManage' => $actor->hasFunctions(['admin', 'warehouse', 'procurement']),
+ 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
+ });
+ }
+
+ /** @param array $input */
+ public function save(User $actor, array $input): SupplyRecord
+ {
+ $input = array_map(fn ($v) => is_string($v) ? trim($v) : $v, $input);
+ $input['code'] = is_string($input['code'] ?? null) ? Str::upper($input['code']) : ($input['code'] ?? null);
+ $data = Validator::make(['record_key' => null, 'equipment_id' => null, ...$input], [
+ 'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
+ 'type' => 'required|in:project,asset', 'code' => ['required', 'string', 'regex:/^[A-Z0-9][A-Z0-9._-]{0,39}$/D'],
+ 'name' => 'required|string|min:3|max:200', 'department_id' => 'required|integer|min:1',
+ 'equipment_id' => 'nullable|integer|min:1', 'reference' => 'required|string|min:3|max:1000',
+ 'state' => 'required|in:active,archived', 'reason' => 'required|string|min:10|max:4000',
+ ])->validate();
+ $data['operation_key'] = strtolower($data['operation_key']);
+ $hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
+
+ return DB::transaction(function () use ($actor, $data, $hash) {
+ $actor = $this->actor($actor, true);
+ $retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
+ if ($retry !== null) {
+ abort_unless($retry->kind === 'capital_register' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
+
+ return $retry;
+ }
+ $old = $data['record_key'] === null ? null : $this->visible($actor)->where('record_key', $data['record_key'])->firstOrFail();
+ abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'O cadastro mudou. Reveja a versão actual.');
+ $department = Department::query()->when($actor->departmentScoped(), fn ($q) => $q->whereKey($actor->department_id))->whereKey($data['department_id'])->firstOrFail();
+ if ($old !== null && ($old->data['type'] !== $data['type'] || $old->data['code'] !== $data['code'])) {
+ throw ValidationException::withMessages(['code' => 'Preserve o tipo e o código da identidade já registada.']);
+ }
+ if ($old === null && SupplyRecord::query()->where('kind', 'capital_register')->where('data->type', $data['type'])->where('data->code', $data['code'])->exists()) {
+ throw ValidationException::withMessages(['code' => 'Este código já existe, incluindo no histórico arquivado.']);
+ }
+ $equipment = null;
+ if ($data['equipment_id'] !== null) {
+ abort_unless($data['type'] === 'asset', 422);
+ $equipment = Equipment::query()->where('department_id', $department->id)->whereKey($data['equipment_id'])->firstOrFail();
+ if (SupplyRecord::query()->where('kind', 'capital_register')->where('data->equipment_id', $equipment->id)
+ ->when($old !== null, fn ($q) => $q->where('record_key', '!=', $old->record_key))->exists()) {
+ throw ValidationException::withMessages(['equipment_id' => 'Este equipamento já está identificado noutra referência de imobilizado.']);
+ }
+ if ($old !== null && ($old->data['equipment_id'] ?? null) !== null && (int) $data['equipment_id'] !== $old->data['equipment_id']) {
+ throw ValidationException::withMessages(['equipment_id' => 'Preserve a ligação ao equipamento já identificado.']);
+ }
+ } elseif (($old?->data['equipment_id'] ?? null) !== null) {
+ throw ValidationException::withMessages(['equipment_id' => 'Preserve a ligação ao equipamento já identificado.']);
+ }
+ $canonical = ['type' => $data['type'], 'code' => $data['code'], 'name' => $data['name'], 'department_id' => $department->id,
+ 'equipment_id' => $equipment?->id, 'reference' => $data['reference']];
+ $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'capital_register',
+ 'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
+ 'state' => $data['state'], 'created_by' => $actor->id, 'data' => $canonical,
+ 'snapshot' => ['department' => $department->only(['id', 'name']), 'equipment' => $equipment?->only(['id', 'code', 'description', 'version']),
+ 'accounting_effects' => false, 'source_system' => 'compras'],
+ 'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
+ app(RequisitionWorkflow::class)->audit($actor, 'capital.register_recorded', null, $old?->toArray(), ['record' => $record->toArray()]);
+
+ return $record;
+ });
+ }
+}
diff --git a/app/Services/CapitalTrace.php b/app/Services/CapitalTrace.php
new file mode 100644
index 0000000..a4cda0b
--- /dev/null
+++ b/app/Services/CapitalTrace.php
@@ -0,0 +1,54 @@
+join('purchase_orders as document', 'document.id', '=', 'line.purchase_order_id')
+ ->where('line.tenant_id', $actor->tenant_id)->where('document.tenant_id', $actor->tenant_id)
+ ->whereIn('document.id', PurchaseOrder::query()->visibleTo($actor)->select('id'));
+ if (DB::getDriverName() === 'pgsql') {
+ $query->whereRaw("document.snapshot::jsonb -> 'capital_assignments' -> line.requisition_item_id::text -> 'snapshot' -> 'source' ->> 'record_key' = ?", [$key]);
+ } elseif (DB::getDriverName() === 'sqlite') {
+ $query->whereRaw("json_extract(document.snapshot, '$.capital_assignments.' || line.requisition_item_id || '.snapshot.source.record_key') = ?", [$key]);
+ } else {
+ abort(503, 'A consulta de origens requer um motor verificado.');
+ }
+ return $query;
+ }
+
+ /** The caller has already checked the current register identity's visibility.
+ * @return array
+ */
+ public function workspace(User $actor, string $key): array
+ {
+ abort_unless(app(CapitalRegister::class)->ready() && auth()->id() === $actor->id && DB::transactionLevel() > 0, 403);
+ $lines = $this->lines($actor, $key);
+ $orders = (clone $lines)->orderBy('line.id')->paginate(15,
+ ['line.id', 'line.description', 'line.quantity', 'line.unit', 'document.id as order_id', 'document.number as order_number'], 'origins_page')->withQueryString();
+ $receipts = GoodsReceiptItem::query()->whereIn('purchase_order_item_id', (clone $lines)->select('line.id'))
+ ->orderBy('id')->paginate(15, ['id', 'goods_receipt_id', 'purchase_order_item_id', 'snapshot', 'accepted_milli', 'quality_status'], 'receipts_page')->withQueryString();
+ $documents = GoodsReceipt::query()->whereIn('id', $receipts->getCollection()->pluck('goods_receipt_id'))->get()->keyBy('id');
+ $receipts->through(function (GoodsReceiptItem $item) use ($documents) {
+ $document = $documents->get($item->goods_receipt_id);
+ return ['id' => $item->id, 'description' => $item->snapshot['order_item']['description'] ?? null, 'unit' => $item->snapshot['order_item']['unit'] ?? null,
+ 'receipt_id' => $item->goods_receipt_id, 'order_id' => $document?->purchase_order_id,
+ 'received_on' => $document?->received_on->toDateString(), 'quality_status' => $item->quality_status,
+ 'accepted_quantity' => (string) BigDecimal::of($item->accepted_milli)->dividedBy(1000, 3),
+ 'reversed' => app(InventoryReversals::class)->receiptReversed($item->id),
+ 'returned_quantity' => (string) BigDecimal::of(app(InventoryDispositions::class)->returnedForReceipt($item->id))->dividedBy(1000, 3)];
+ });
+ return ['orders' => $orders, 'receipts' => $receipts];
+ }
+}
diff --git a/app/Services/ImportBankSupport.php b/app/Services/ImportBankSupport.php
new file mode 100644
index 0000000..797d943
--- /dev/null
+++ b/app/Services/ImportBankSupport.php
@@ -0,0 +1,242 @@
+ready();
+ }
+
+ public function assertReadable(User $actor, SupplyRecord $import): void
+ {
+ abort_unless($this->ready(), 503);
+ DB::transaction(fn () => app(ImportDossier::class)->context($actor, $import));
+ }
+
+ /** @param \Closure(SupplyRecord,list):void $consume */
+ public function report(User $actor, SupplyRecord $import, \Closure $consume): void
+ {
+ abort_unless($this->ready(), 503);
+ DB::transaction(function () use ($actor, $import, $consume) {
+ [, $current, $order] = app(ImportDossier::class)->context($actor, $import);
+ $records = app(SupplyPlanning::class)->latest('import_bank_support')->where('purchase_order_id', $order->id)->where('snapshot->import_key', $current->record_key);
+ foreach ($records->lazyById(100) as $record) {
+ $consume($record, $this->issues($record));
+ }
+ });
+ }
+
+ /** @return array */
+ public function workspace(User $actor, SupplyRecord $import): array
+ {
+ abort_unless($this->ready(), 503);
+
+ return DB::transaction(function () use ($actor, $import) {
+ [$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import);
+ $base = SupplyRecord::query()->where('kind', 'import_bank_support')->where('purchase_order_id', $order->id)->where('snapshot->import_key', $current->record_key);
+ $latest = (clone $base)->whereIn('id', app(SupplyPlanning::class)->latest('import_bank_support')->select('id'))->latest('id')
+ ->paginate(10, ['*'], 'bank_current_page')->withQueryString();
+ $latest->through(fn ($record) => [...$record->toArray(), 'issues' => $this->issues($record)]);
+
+ return ['importRecord' => $current->only(['id', 'record_key', 'version']), 'order' => $order->only(['id', 'number']),
+ 'current' => $latest, 'history' => (clone $base)->latest('id')->paginate(10, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason', 'created_at'], 'bank_history_page')->withQueryString(),
+ 'documents' => app(SupplyPlanning::class)->latest('import_document')->where('purchase_order_id', $order->id)->where('snapshot->import_key', $current->record_key)
+ ->latest('id')->paginate(20, ['id', 'record_key', 'version', 'data'], 'bank_documents_page')->withQueryString(),
+ 'types' => ImportDossier::TYPES, 'canWrite' => $actor->hasFunctions(['import_prepare']),
+ 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id, 'today' => today()->toDateString()];
+ });
+ }
+
+ /** @param array $input */
+ public function save(User $actor, SupplyRecord $import, array $input): SupplyRecord
+ {
+ abort_unless($this->ready(), 503);
+ foreach (['requirements_basis', 'deadline_basis', 'submission_basis', 'reason'] as $field) {
+ if (isset($input[$field]) && is_string($input[$field])) {
+ $input[$field] = trim($input[$field]);
+ }
+ }
+ $types = array_diff(array_keys(ImportDossier::TYPES), ['bank_commitment']);
+ $data = Validator::make(['record_key' => null, ...$input], [
+ 'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
+ 'commitment_document_id' => 'required|integer|min:1', 'declaration_document_id' => 'present|nullable|integer|min:1',
+ 'submission_document_id' => 'present|nullable|integer|min:1', 'submission_basis' => 'present|nullable|string|min:3|max:1000',
+ 'submitted_on' => 'present|nullable|date_format:Y-m-d|before_or_equal:today',
+ 'support_document_ids' => 'present|array|list|max:100', 'support_document_ids.*' => 'required|integer|min:1|distinct',
+ 'requirements_known' => 'required|boolean', 'required_support_types' => 'present|array|list|max:14',
+ 'required_support_types.*' => ['required', 'distinct', Rule::in($types)], 'requirements_basis' => 'required|string|min:3|max:1000',
+ 'required_support_counts' => 'present|array|max:14', 'required_support_counts.*' => 'required|integer|min:1|max:100',
+ 'due_on' => 'present|nullable|date_format:Y-m-d', 'deadline_basis' => 'present|nullable|string|min:3|max:1000',
+ 'reason' => 'required|string|min:10|max:4000',
+ ])->validate();
+ $data['version'] = (int) $data['version'];
+ $data['commitment_document_id'] = (int) $data['commitment_document_id'];
+ $data['declaration_document_id'] = $data['declaration_document_id'] === null ? null : (int) $data['declaration_document_id'];
+ $data['submission_document_id'] = $data['submission_document_id'] === null ? null : (int) $data['submission_document_id'];
+ $data['support_document_ids'] = array_map('intval', $data['support_document_ids']);
+ $data['requirements_known'] = (bool) $data['requirements_known'];
+ sort($data['support_document_ids'], SORT_NUMERIC);
+ sort($data['required_support_types'], SORT_STRING);
+ $data['required_support_counts'] = array_map('intval', $data['required_support_counts']);
+ ksort($data['required_support_counts']);
+ abort_unless(array_keys($data['required_support_counts']) === $data['required_support_types'] && array_sum($data['required_support_counts']) <= 100, 422,
+ 'Indique a quantidade explícita de cada tipo de documento solicitado pelo banco.');
+ abort_unless($data['requirements_known'] || $data['required_support_types'] === [], 422, 'Requisitos desconhecidos não podem ser apresentados como uma lista confirmada.');
+ abort_if($data['due_on'] !== null && (! is_string($data['deadline_basis']) || mb_strlen($data['deadline_basis']) < 3), 422, 'Indique a fonte do prazo documental, sem aplicar um prazo genérico.');
+ abort_if($data['submission_document_id'] !== null && (! is_string($data['submission_basis']) || mb_strlen($data['submission_basis']) < 3), 422, 'Identifique o fundamento do comprovativo de entrega documental.');
+ abort_unless(($data['submission_document_id'] === null) === ($data['submitted_on'] === null), 422,
+ 'Associe o comprovativo e a data efectiva da entrega documental; não presuma a data pelo carregamento do ficheiro.');
+ $hash = hash('sha256', json_encode([$import->record_key, $data], JSON_THROW_ON_ERROR));
+
+ return DB::transaction(function () use ($actor, $import, $data, $hash) {
+ [$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import, true);
+ $retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
+ if ($retry !== null) {
+ abort_unless($retry->kind === 'import_bank_support' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
+
+ return $retry;
+ }
+ $old = $data['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_bank_support')->where('record_key', $data['record_key'])->latest('version')->firstOrFail();
+ abort_unless($data['version'] === ($old->version ?? 0), 409, 'O acompanhamento bancário mudou. Consulte a versão actual.');
+ if ($old !== null) {
+ abort_unless($old->purchase_order_id === $order->id && $old->snapshot['import_key'] === $current->record_key, 404);
+ }
+ $documents = [];
+ $commitment = $this->document($current, $data['commitment_document_id']);
+ abort_unless($commitment->data['type'] === 'bank_commitment', 422, 'Seleccione um termo de compromisso tipificado.');
+ $documents[$commitment->id] = $this->freeze($commitment);
+ if ($data['declaration_document_id'] !== null) {
+ $declaration = $this->document($current, $data['declaration_document_id']);
+ abort_unless($declaration->data['type'] === 'customs_declaration', 422, 'Seleccione o documento único ou a declaração aduaneira.');
+ $documents[$declaration->id] = $this->freeze($declaration);
+ }
+ foreach ($data['support_document_ids'] as $id) {
+ $document = $this->document($current, $id);
+ abort_unless($document->data['type'] !== 'bank_commitment', 422);
+ $documents[$document->id] = $this->freeze($document);
+ }
+ if ($data['submission_document_id'] !== null) {
+ $submission = $this->document($current, $data['submission_document_id']);
+ abort_unless($submission->data['type'] === 'bank_support', 422, 'Seleccione o comprovativo documental de entrega ao banco.');
+ $documents[$submission->id] = $this->freeze($submission);
+ }
+ if ($old === null) {
+ abort_if(app(SupplyPlanning::class)->latest('import_bank_support')->where('purchase_order_id', $order->id)
+ ->where('data->commitment_key', $commitment->record_key)->exists(), 409, 'O termo já tem acompanhamento. Versione o registo existente.');
+ } else {
+ abort_unless($old->data['commitment_key'] === $commitment->record_key, 409, 'Uma correcção conserva a identidade do termo de compromisso.');
+ }
+ $payload = array_diff_key($data, array_flip(['operation_key', 'record_key', 'version', 'reason']));
+ $payload['commitment_key'] = $commitment->record_key;
+ $snapshot = ['import_key' => $current->record_key, 'documents' => array_values($documents), 'supersedes' => $old?->id,
+ 'bank_transfer_executed' => false, 'jue_submission_executed' => false, 'bank_compliance_certified' => false];
+ $complete = $data['requirements_known'] && $data['declaration_document_id'] !== null
+ && $this->missingRequirements($data, array_values($documents)) === [];
+ $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_bank_support',
+ 'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
+ 'state' => $complete ? ($data['submission_document_id'] !== null ? 'documented' : 'ready') : 'tracking', 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
+ 'data' => $payload, 'snapshot' => $snapshot, 'reason' => $data['reason'], 'operation_key' => $data['operation_key'],
+ 'input_hash' => $hash, 'created_at' => now()]);
+ foreach (app(OrderPartsAccess::class)->origins($order) as $id) {
+ app(RequisitionWorkflow::class)->audit($actor, 'import.bank_support_recorded', Requisition::query()->whereKey($id)->firstOrFail(), null,
+ ['record_id' => $record->id, 'version' => $record->version, 'state' => $record->state, 'bank_transfer_executed' => false, 'jue_submission_executed' => false]);
+ }
+
+ return $record;
+ });
+ }
+
+ private function document(SupplyRecord $import, int $id): SupplyRecord
+ {
+ $document = SupplyRecord::query()->where('kind', 'import_document')->where('purchase_order_id', $import->purchase_order_id)
+ ->where('snapshot->import_key', $import->record_key)->findOrFail($id);
+ abort_unless(SupplyRecord::query()->where('kind', 'import_document')->where('record_key', $document->record_key)->latest('version')->value('id') === $document->id, 409,
+ 'Seleccione a versão actual do documento, conservando o original anterior.');
+ app(ImportEvidence::class)->bytes($document);
+
+ return $document;
+ }
+
+ /** @return array */
+ private function freeze(SupplyRecord $document): array
+ {
+ return ['id' => $document->id, 'record_key' => $document->record_key, 'version' => $document->version,
+ 'type' => $document->data['type'], 'reference' => $document->data['reference'], 'issuer_reference' => $document->data['issuer_reference'],
+ 'sha256' => $document->snapshot['evidence']['sha256']];
+ }
+
+ /** @return list */
+ public function issues(SupplyRecord $record): array
+ {
+ $issues = [];
+ if (! $record->data['requirements_known']) {
+ $issues[] = 'Requisitos de suporte ainda desconhecidos.';
+ }
+ if ($record->data['declaration_document_id'] === null) {
+ $issues[] = 'Falta associar o documento único ou a declaração aduaneira.';
+ }
+ if ($record->data['submission_document_id'] === null) {
+ $issues[] = 'Falta associar o comprovativo de entrega documental ao banco; reunir documentos não demonstra a entrega.';
+ }
+ $issues = [...$issues, ...$this->missingRequirements($record->data, $record->snapshot['documents'])];
+ $import = SupplyRecord::query()->where('kind', 'import')->where('record_key', $record->snapshot['import_key'])->latest('version')->firstOrFail();
+ foreach ($record->snapshot['documents'] as $frozen) {
+ try {
+ $document = $this->document($import, $frozen['id']);
+ if ($this->freeze($document) !== $frozen) {
+ $issues[] = 'O original '.$frozen['reference'].' divergiu da versão preservada.';
+ }
+ } catch (HttpExceptionInterface|ModelNotFoundException $error) {
+ $issues[] = 'O original '.$frozen['reference'].' está em falta, alterado ou foi corrigido; reveja a associação.';
+ }
+ }
+ $pending = $issues !== [];
+ if ($record->data['due_on'] === null) {
+ $issues[] = 'Prazo documental ainda por indicar; não foi presumido um prazo legal.';
+ } else {
+ if ($record->data['submitted_on'] !== null && $record->data['submitted_on'] > $record->data['due_on']) {
+ $issues[] = 'Entrega documentada após o prazo indicado.';
+ }
+ if ($pending && $record->data['due_on'] < today()->toDateString()) {
+ $issues[] = 'Prazo documental ultrapassado.';
+ } elseif ($pending && $record->data['due_on'] === today()->toDateString()) {
+ $issues[] = 'O prazo documental termina hoje.';
+ }
+ }
+
+ return array_values(array_unique($issues));
+ }
+
+ /** @param array $data
+ * @param list> $documents
+ * @return list
+ */
+ private function missingRequirements(array $data, array $documents): array
+ {
+ $support = array_filter($documents, fn ($document) => in_array($document['id'], $data['support_document_ids'], true)
+ || $document['id'] === $data['declaration_document_id']);
+ $counts = array_count_values(array_column($support, 'type'));
+ $issues = [];
+ foreach ($data['required_support_counts'] as $type => $required) {
+ $missing = $required - ($counts[$type] ?? 0);
+ if ($missing > 0) {
+ $issues[] = 'Documento em falta: '.ImportDossier::TYPES[$type].' ('.$missing.').';
+ }
+ }
+
+ return $issues;
+ }
+}
diff --git a/app/Services/ImportCostDocumentHealth.php b/app/Services/ImportCostDocumentHealth.php
index 7bd3765..33d5a4e 100644
--- a/app/Services/ImportCostDocumentHealth.php
+++ b/app/Services/ImportCostDocumentHealth.php
@@ -25,22 +25,24 @@ final class ImportCostDocumentHealth
'documents_checked' => 0, 'files_checked' => 0, 'missing' => 0, 'altered' => 0,
'invalid_reference' => 0, 'unreferenced' => 0, 'reasons' => []];
$disk = Storage::disk('local');
- $records = DB::table('supply_records')->whereIn('kind', ['import_cost_doc', 'import_document'])->orderBy('id')->limit($limit + 1)->get();
+ $records = DB::table('supply_records')->whereIn('kind', ['import_cost_doc', 'import_document', 'import_legal_source'])->orderBy('id')->limit($limit + 1)->get();
$limited = $records->count() > $limit;
$root = realpath($disk->path(''));
foreach ($records->take($limit) as $record) {
$result['documents_checked']++;
$snapshot = json_decode($record->snapshot, true, 64, JSON_THROW_ON_ERROR);
$evidence = $snapshot['evidence'] ?? [];
- $directory = $record->kind === 'import_cost_doc' ? 'import-costs' : 'import-dossier';
- $prefix = $directory.'/'.$record->tenant_id.'/'.$record->purchase_order_id.'/';
+ $directory = match ($record->kind) {
+ 'import_cost_doc' => 'import-costs', 'import_legal_source' => 'import-legal', default => 'import-dossier'
+ };
+ $prefix = $directory.'/'.$record->tenant_id.'/'.($record->kind === 'import_legal_source' ? '' : $record->purchase_order_id.'/');
$path = $evidence['path'] ?? null;
if (($evidence['disk'] ?? null) !== 'local' || ! is_string($path)
|| ! preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
|| ! preg_match('/^'.preg_quote($prefix.$record->record_key.'-'.$record->version, '/').'\.(pdf|jpg|jpeg|png)$/D', $path)
- || ! is_int($evidence['size'] ?? null) || $evidence['size'] < 1 || $evidence['size'] > 2097152
+ || ! is_int($evidence['size'] ?? null) || $evidence['size'] < 1 || $evidence['size'] > ($record->kind === 'import_legal_source' ? 67108864 : 2097152)
|| ! is_string($evidence['sha256'] ?? null) || ! preg_match('/^[a-f0-9]{64}$/D', $evidence['sha256'])
- || ! DB::table('purchase_orders')->where('tenant_id', $record->tenant_id)->where('id', $record->purchase_order_id)->exists()) {
+ || ($record->kind !== 'import_legal_source' && ! DB::table('purchase_orders')->where('tenant_id', $record->tenant_id)->where('id', $record->purchase_order_id)->exists())) {
$result['invalid_reference']++;
continue;
@@ -69,7 +71,7 @@ final class ImportCostDocumentHealth
$result['altered']++;
}
}
- foreach (['import-costs' => 'import_cost_doc', 'import-dossier' => 'import_document'] as $directory => $kind) {
+ foreach (['import-costs' => 'import_cost_doc', 'import-dossier' => 'import_document', 'import-legal' => 'import_legal_source'] as $directory => $kind) {
foreach ($disk->getDriver()->listContents($directory, true) as $entry) {
if (! $entry->isFile()) {
continue;
diff --git a/app/Services/ImportEstimates.php b/app/Services/ImportEstimates.php
index 7cd12a1..1a97690 100644
--- a/app/Services/ImportEstimates.php
+++ b/app/Services/ImportEstimates.php
@@ -48,6 +48,7 @@ final class ImportEstimates
$latest = $this->current($request);
return ['requisition' => $request->only(['id', 'number', 'status', 'subtotal_minor', 'tax_minor', 'total_minor']),
+ 'legalAmounts' => app(ImportLegalRules::class)->ready() ? app(SupplyPlanning::class)->latest('import_legal_amount')->where('data->requisition_id', $request->id)->get() : [],
'latest' => $latest, 'nativeChanged' => $latest !== null && $latest->snapshot['native'] !== $this->native($request),
'history' => SupplyRecord::query()->where('kind', 'import_estimate')->where('data->requisition_id', $request->id)
->latest('version')->paginate(10, ['id', 'version', 'state', 'reason', 'data', 'snapshot', 'created_at'], 'estimate_page')->withQueryString(),
@@ -74,6 +75,9 @@ final class ImportEstimates
abort_unless($this->ready(), 503, 'Preserve a capacidade de estimativa de importação antes de submeter.');
abort_unless($record->snapshot['native'] === $this->native($request), 409, 'A requisição mudou. Reveja e versione a estimativa antes de submeter.');
abort_unless($record->snapshot['plan']['complete'] === true, 422, 'Existem custos de importação desconhecidos. Complete os pressupostos antes da aprovação e reserva.');
+ foreach ($record->snapshot['legal_sources'] ?? [] as $source) {
+ app(ImportLegalEstimates::class)->forPlan($request, $source['estimate_id']);
+ }
$budget = Budget::query()->whereKey($record->data['budget_id'])->firstOrFail();
abort_unless($budget->approved_by !== null && $budget->only(['id', 'cost_center_id', 'year', 'kind', 'includes_tax']) === $record->snapshot['budget'], 409,
'O orçamento da estimativa mudou. Reveja a preparação.');
@@ -199,6 +203,8 @@ final class ImportEstimates
abort_unless($this->ready(), 503);
$data = Validator::make($input, [
'operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'budget_id' => 'required|integer|min:1',
+ 'legal_sources' => 'sometimes|array|max:100', 'legal_sources.*' => 'required|array:estimate_id,charge_key',
+ 'legal_sources.*.estimate_id' => 'required|integer|min:1', 'legal_sources.*.charge_key' => 'required|string|max:100',
'components' => 'required|array|list|min:6|max:100', 'components.*' => 'required|array:key,kind,status,basis,subtotal_minor,tax_minor,total_minor',
'components.*.key' => 'required|string|max:100', 'components.*.kind' => 'required|string',
'components.*.status' => 'required|in:known,unknown,not_applicable', 'components.*.basis' => 'required|string|min:3|max:4000',
@@ -237,12 +243,32 @@ final class ImportEstimates
->where('kind', $request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating')
->where('year', now()->year)->whereNotNull('approved_by')->firstOrFail();
$native = $this->native($request);
+ $legalSources = [];
+ $usedLegalLines = [];
+ foreach ($data['legal_sources'] ?? [] as $componentKey => $source) {
+ $estimate = app(ImportLegalEstimates::class)->forPlan($request, (int) $source['estimate_id']);
+ $lines = array_values(array_filter($estimate->snapshot['result']['lines'], fn ($line) => $line['key'] === $source['charge_key']));
+ $components = array_values(array_filter($data['components'], fn ($component) => $component['key'] === $componentKey));
+ $identity = $estimate->id.':'.$source['charge_key'];
+ abort_unless(count($lines) === 1 && count($components) === 1 && ! isset($usedLegalLines[$identity]), 422, 'Seleccione uma componente e use cada imposição calculada uma única vez.');
+ $line = $lines[0];
+ $component = $components[0];
+ abort_unless($component['kind'] === $line['kind'], 422, 'A família do encargo deve corresponder à imposição seleccionada.');
+ $amount = $line['amount_minor'];
+ abort_unless($amount === null ? $component['status'] === 'unknown'
+ : ($component['status'] === 'known' && $component['total_minor'] === $amount)
+ || ($line['method'] === 'not_applicable' && $component['status'] === 'not_applicable' && $amount === 0), 422,
+ 'O total ou a situação diverge da estimativa legal. Retire explicitamente a ligação para preparar um pressuposto manual.');
+ $usedLegalLines[$identity] = true;
+ $legalSources[$componentKey] = ['estimate_id' => $estimate->id, 'estimate_version' => $estimate->version, 'charge_key' => $line['key'],
+ 'amount_minor' => $amount, 'legal_rule' => $estimate->snapshot['legal_rule']];
+ }
$plan = app(CommonBudget::class)->execute(fn () => BudgetImportEstimate::reconcile($native, $data['components'], (bool) $budget->includes_tax));
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_estimate',
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
'state' => $plan['complete'] ? 'prepared' : 'incomplete', 'created_by' => $actor->id,
'data' => ['requisition_id' => $request->id, 'budget_id' => $budget->id, 'components' => $data['components']],
- 'snapshot' => ['native' => $native, 'plan' => $plan, 'budget' => $budget->only(['id', 'cost_center_id', 'year', 'kind', 'includes_tax'])],
+ 'snapshot' => ['native' => $native, 'plan' => $plan, 'budget' => $budget->only(['id', 'cost_center_id', 'year', 'kind', 'includes_tax']), 'legal_sources' => $legalSources],
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'import.estimate_prepared', $request, null,
['record_id' => $record->id, 'version' => $record->version, 'complete' => $plan['complete'], 'financial_effects' => false]);
diff --git a/app/Services/ImportEvidence.php b/app/Services/ImportEvidence.php
index bd7dc53..05b4001 100644
--- a/app/Services/ImportEvidence.php
+++ b/app/Services/ImportEvidence.php
@@ -15,14 +15,15 @@ final class ImportEvidence
$prefix = match ($record->kind) {
'import_cost_doc' => 'import-costs',
'import_document' => 'import-dossier',
+ 'import_legal_source' => 'import-legal',
default => null,
};
$path = $evidence['path'] ?? null;
- $expected = $prefix.'/'.$record->tenant_id.'/'.$record->purchase_order_id.'/'.$record->record_key.'-'.$record->version;
+ $expected = $prefix.'/'.$record->tenant_id.'/'.($record->kind === 'import_legal_source' ? '' : $record->purchase_order_id.'/').$record->record_key.'-'.$record->version;
abort_unless($prefix !== null && preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
&& ($evidence['disk'] ?? null) === 'local' && is_string($path)
&& preg_match('/^'.preg_quote($expected, '/').'\.(pdf|jpg|jpeg|png)$/D', $path)
- && is_int($evidence['size'] ?? null) && $evidence['size'] > 0 && $evidence['size'] <= 2097152
+ && is_int($evidence['size'] ?? null) && $evidence['size'] > 0 && $evidence['size'] <= ($record->kind === 'import_legal_source' ? 67108864 : 2097152)
&& is_string($evidence['sha256'] ?? null) && preg_match('/^[a-f0-9]{64}$/D', $evidence['sha256']), 409,
'A referência do original privado está incompleta.');
$disk = Storage::disk('local');
diff --git a/app/Services/ImportLegalAmounts.php b/app/Services/ImportLegalAmounts.php
new file mode 100644
index 0000000..1333c3e
--- /dev/null
+++ b/app/Services/ImportLegalAmounts.php
@@ -0,0 +1,113 @@
+ $definitions
+ * @return list>
+ */
+ public function definitions(array $definitions): array
+ {
+ $data = Validator::make(['charges' => $definitions], [
+ 'charges' => 'present|array|list|max:20',
+ 'charges.*' => 'required|array:key,kind,label,method,rate_percent,specific_minor,quantity_unit,basis_reference',
+ 'charges.*.key' => 'required|string|max:100|distinct', 'charges.*.label' => 'required|string|min:2|max:120',
+ 'charges.*.kind' => 'required|in:duty,ice,vat,other',
+ 'charges.*.method' => 'required|in:unknown,not_applicable,ad_valorem,specific,maximum',
+ 'charges.*.rate_percent' => ['present', 'nullable', 'regex:/^\d{1,4}(\.\d{1,6})?$/', 'numeric', 'min:0', 'max:10000'],
+ 'charges.*.specific_minor' => 'present|nullable|integer|min:0|max:100000000000000',
+ 'charges.*.quantity_unit' => 'present|nullable|string|max:40',
+ 'charges.*.basis_reference' => 'required|string|min:3|max:4000',
+ ])->validate();
+ $result = [];
+ foreach ($data['charges'] as $index => $charge) {
+ $percent = in_array($charge['method'], ['ad_valorem', 'maximum'], true);
+ $specific = in_array($charge['method'], ['specific', 'maximum'], true);
+ if (($charge['rate_percent'] !== null) !== $percent || ($charge['specific_minor'] !== null) !== $specific
+ || ($specific && trim($charge['quantity_unit'] ?? '') === '')) {
+ throw ValidationException::withMessages(['charges.'.$index => 'Indique exactamente as taxas e a unidade do método documentado; desconhecido ou não aplicável não presume uma taxa.']);
+ }
+ $result[] = [...$charge, 'rate_percent' => $percent ? (string) BigDecimal::of($charge['rate_percent'])->toScale(6) : null,
+ 'specific_minor' => $specific ? (int) $charge['specific_minor'] : null];
+ }
+
+ return $result;
+ }
+
+ /** @param list> $definitions
+ * @param array> $bases
+ * @return array
+ */
+ public function calculate(array $definitions, array $bases): array
+ {
+ $definitions = $this->definitions($definitions);
+ $bases = $this->bases($bases);
+ if (array_diff(array_keys($bases), array_column($definitions, 'key')) !== []) {
+ throw ValidationException::withMessages(['bases' => 'As bases devem corresponder às imposições da versão seleccionada.']);
+ }
+ $lines = [];
+ $known = 0;
+ $complete = $definitions !== [];
+ foreach ($definitions as $charge) {
+ $base = $bases[$charge['key']] ?? null;
+ $value = $base['value_minor'] ?? null;
+ $quantity = $base['quantity'] ?? null;
+ if (($value !== null || $quantity !== null) && mb_strlen(trim($base['source'] ?? '')) < 3) {
+ throw ValidationException::withMessages(['bases.'.$charge['key'].'.source' => 'Indique a origem do valor ou da quantidade efectivamente usados.']);
+ }
+ $percent = in_array($charge['method'], ['ad_valorem', 'maximum'], true);
+ $specific = in_array($charge['method'], ['specific', 'maximum'], true);
+ if ($specific && $quantity !== null && ($base['quantity_unit'] ?? null) !== $charge['quantity_unit']) {
+ throw ValidationException::withMessages(['bases.'.$charge['key'] => 'A unidade da quantidade deve coincidir com a taxa específica; não foi presumida uma conversão.']);
+ }
+ $amount = null;
+ if ($charge['method'] === 'not_applicable') {
+ $amount = mb_strlen(trim($base['source'] ?? '')) >= 3 ? 0 : null;
+ } elseif ($charge['method'] !== 'unknown' && (! $percent || $value !== null) && (! $specific || $quantity !== null)) {
+ $adValorem = $percent ? BigDecimal::of($value)->multipliedBy($charge['rate_percent'])->dividedBy(100, 8, RoundingMode::Unnecessary) : BigDecimal::zero();
+ $perUnit = $specific ? BigDecimal::of($quantity)->multipliedBy($charge['specific_minor']) : BigDecimal::zero();
+ $calculated = ($charge['method'] === 'specific' || ($charge['method'] === 'maximum' && $perUnit->isGreaterThan($adValorem))) ? $perUnit : $adValorem;
+ $rounded = $calculated->toScale(0, RoundingMode::HalfUp);
+ if ($rounded->isGreaterThan(100000000000000) || $rounded->plus($known)->isGreaterThan(100000000000000)) {
+ throw ValidationException::withMessages(['bases' => 'A estimativa excede o limite monetário suportado. Reveja as bases e as unidades.']);
+ }
+ $amount = $rounded->toInt();
+ }
+ $complete = $complete && $amount !== null;
+ $known += $amount ?? 0;
+ $lines[] = ['key' => $charge['key'], 'kind' => $charge['kind'], 'label' => $charge['label'], 'method' => $charge['method'],
+ 'amount_minor' => $amount, 'basis_reference' => $charge['basis_reference'], 'input' => $base];
+ }
+
+ return ['currency' => 'MZN', 'lines' => $lines, 'complete' => $complete, 'known_subtotal_minor' => $known,
+ 'total_minor' => $complete ? $known : null, 'financial_effects' => false, 'rounding' => 'HALF_UP_PER_CHARGE'];
+ }
+
+ /** @param array> $bases
+ * @return array>
+ */
+ public function bases(array $bases): array
+ {
+ Validator::make(['bases' => $bases], ['bases' => 'present|array|max:20',
+ 'bases.*' => 'required|array:value_minor,quantity,quantity_unit,source',
+ 'bases.*.value_minor' => 'present|nullable|integer|min:0|max:100000000000000',
+ 'bases.*.quantity' => ['present', 'nullable', 'string', 'regex:/^\d{1,12}(\.\d{1,6})?$/'],
+ 'bases.*.quantity_unit' => 'present|nullable|string|max:40', 'bases.*.source' => 'nullable|string|min:3|max:1000'])->validate();
+ foreach ($bases as &$base) {
+ $base['value_minor'] = $base['value_minor'] === null ? null : (int) $base['value_minor'];
+ foreach (['quantity_unit', 'source'] as $field) {
+ $base[$field] = trim($base[$field] ?? '') === '' ? null : trim($base[$field]);
+ }
+ }
+ unset($base);
+
+ return $bases;
+ }
+}
diff --git a/app/Services/ImportLegalEstimates.php b/app/Services/ImportLegalEstimates.php
new file mode 100644
index 0000000..81a29d7
--- /dev/null
+++ b/app/Services/ImportLegalEstimates.php
@@ -0,0 +1,76 @@
+ready(), 503, 'Preserve a consulta das fontes usadas na estimativa.');
+ $record = SupplyRecord::query()->where('kind', 'import_legal_amount')->where('data->requisition_id', $request->id)->findOrFail($id);
+ $item = $request->items()->whereKey($record->data['requisition_item_id'])->firstOrFail();
+ abort_unless($record->snapshot['item'] === $item->only(['id', 'description', 'unit', 'quantity']), 409,
+ 'O artigo mudou. Reveja a fonte antes de usar os montantes.');
+ $rule = $record->snapshot['legal_rule'];
+ app(ImportLegalRules::class)->freeze($rule['id'], $rule['context']['code'], $rule['context']['origin_country'], $rule['context']['sector'], $rule['context']['date']);
+ abort_unless(app(ImportLegalAmounts::class)->calculate($rule['data']['charges'] ?? [], $record->data['bases']) === $record->snapshot['result'], 409,
+ 'A estimativa diverge das bases e taxas preservadas.');
+
+ return $record;
+ }
+
+ /** @param array $input */
+ public function save(User $actor, Requisition $request, array $input): SupplyRecord
+ {
+ abort_unless(app(ImportLegalRules::class)->ready(), 503);
+ $data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
+ 'requisition_item_id' => 'required|integer|min:1', 'rule_id' => 'required|integer|min:1',
+ 'match_code' => 'required|string|max:40', 'origin' => 'nullable|string|max:120', 'sector' => 'nullable|string|max:160',
+ 'date' => 'required|date_format:Y-m-d', 'bases' => 'present|array|max:20', 'reason' => 'required|string|min:10|max:4000'])->validate();
+ $data['operation_key'] = strtolower($data['operation_key']);
+ foreach (['version', 'rule_id', 'requisition_item_id'] as $field) {
+ $data[$field] = (int) $data[$field];
+ }
+ $data['bases'] = app(ImportLegalAmounts::class)->bases($data['bases']);
+ $hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
+
+ return DB::transaction(function () use ($actor, $request, $data, $hash) {
+ app(ConflictGuard::class)->lockCompany($actor);
+ $actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
+ abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
+ $request = Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id);
+ app(ConflictGuard::class)->assertParticipation($actor, $request);
+ $item = $request->items()->whereKey($data['requisition_item_id'])->firstOrFail();
+ $retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
+ if ($retry !== null) {
+ abort_unless($retry->kind === 'import_legal_amount' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
+
+ return $retry;
+ }
+ $old = app(SupplyPlanning::class)->latest('import_legal_amount')->where('data->requisition_id', $request->id)
+ ->where('data->requisition_item_id', $item->id)->first();
+ abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A estimativa do artigo mudou. Consulte a versão actual e preserve as suas bases.');
+ $rule = app(ImportLegalRules::class)->freeze((int) $data['rule_id'], $data['match_code'], $data['origin'] ?? '', $data['sector'] ?? '', $data['date']);
+ $result = app(ImportLegalAmounts::class)->calculate($rule['data']['charges'] ?? [], $data['bases']);
+ $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_legal_amount',
+ 'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
+ 'state' => $result['complete'] ? 'calculated' : 'indeterminate', 'created_by' => $actor->id,
+ 'data' => ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'bases' => $data['bases']],
+ 'snapshot' => ['item' => $item->only(['id', 'description', 'unit', 'quantity']), 'legal_rule' => $rule, 'result' => $result, 'supersedes' => $old?->id],
+ 'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
+ app(RequisitionWorkflow::class)->audit($actor, 'import.legal_estimate_recorded', $request, null,
+ ['record_id' => $record->id, 'version' => $record->version, 'state' => $record->state, 'financial_effects' => false]);
+
+ return $record;
+ });
+ }
+}
diff --git a/app/Services/ImportLegalRules.php b/app/Services/ImportLegalRules.php
new file mode 100644
index 0000000..c2ac57d
--- /dev/null
+++ b/app/Services/ImportLegalRules.php
@@ -0,0 +1,256 @@
+ready();
+ }
+
+ private function actor(User $actor): User
+ {
+ abort_unless($this->ready(), 503);
+ app(ConflictGuard::class)->lockCompany($actor);
+ $actor = app(CurrentActor::class)->lock($actor);
+ abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
+ abort_unless($actor->hasFunctions(['import_read', 'import_prepare', 'import_customs', PurchasingRole::Procurement]), 403);
+
+ return $actor;
+ }
+
+ /** @return array */
+ public function workspace(User $actor, Requisition $request): array
+ {
+ return DB::transaction(function () use ($actor, $request) {
+ $actor = $this->actor($actor);
+ $request = Requisition::query()->visibleTo($actor)->findOrFail($request->id);
+ $rules = app(SupplyPlanning::class)->latest('import_legal_rule')->latest('id')
+ ->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason'], 'rules_page')->withQueryString();
+ $rules->through(fn ($rule) => [...$rule->toArray(), 'source_url' => '/requisicoes/'.$request->id.'/base-legal/fontes/'.$rule->snapshot['source_id']]);
+
+ return ['requisition' => $request->only(['id', 'number']), 'rules' => $rules,
+ 'sources' => SupplyRecord::query()->where('kind', 'import_legal_source')->latest('id')
+ ->paginate(15, ['id', 'data', 'created_at'], 'legal_sources_page')->withQueryString(),
+ 'items' => $request->items()->orderBy('id')->get(['id', 'description']),
+ 'classifications' => app(SupplyPlanning::class)->latest('import_tariff')->where('data->requisition_id', $request->id)->get(['version', 'data']),
+ 'canPropose' => $actor->hasFunctions([PurchasingRole::Procurement]),
+ 'estimates' => app(SupplyPlanning::class)->latest('import_legal_amount')->where('data->requisition_id', $request->id)->get(),
+ 'estimateHistory' => SupplyRecord::query()->where('kind', 'import_legal_amount')->where('data->requisition_id', $request->id)->latest('id')
+ ->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'snapshot', 'reason'], 'legal_estimates_page')->withQueryString(),
+ 'history' => SupplyRecord::query()->where('kind', 'import_legal_rule')->latest('id')
+ ->paginate(15, ['id', 'record_key', 'version', 'state', 'data', 'reason', 'created_at'], 'legal_history_page')->withQueryString(),
+ 'canManage' => $actor->hasFunctions(['import_customs']), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id,
+ 'types' => ImportDossier::TYPES];
+ });
+ }
+
+ /** @param array $input */
+ public function save(User $actor, array $input, ?UploadedFile $file = null): SupplyRecord
+ {
+ $input = array_map(fn ($value) => is_string($value) ? trim($value) : $value, $input);
+ $input['official_url'] = ($input['official_url'] ?? '') === '' ? null : $input['official_url'];
+ $data = Validator::make(['record_key' => null, 'document_types' => [], 'charges' => [], ...$input, 'file' => $file], [
+ 'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
+ 'action' => 'required|in:source,save,publish,withdraw', 'reason' => 'required|string|min:10|max:4000',
+ 'source_id' => 'nullable|integer|min:1',
+ 'title' => 'required_if:action,save|nullable|string|min:3|max:200',
+ 'official_reference' => 'required_if:action,save,source|nullable|string|min:3|max:1000',
+ 'official_url' => 'nullable|url:http,https|max:2000',
+ 'citation' => 'required_if:action,save|nullable|string|min:3|max:4000',
+ 'valid_from' => 'required_if:action,save|nullable|date_format:Y-m-d',
+ 'valid_until' => 'nullable|date_format:Y-m-d|after_or_equal:valid_from',
+ 'match_code' => 'required_if:action,save|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/',
+ 'suggested_code' => 'required_if:action,save|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/',
+ 'origin_country' => 'nullable|string|max:120', 'sector' => 'nullable|string|max:160',
+ 'obligations' => 'required_if:action,save|nullable|string|min:3|max:4000',
+ 'document_types' => 'present|array|list|max:14',
+ 'document_types.*' => ['required', 'distinct', Rule::in(array_keys(ImportDossier::TYPES))],
+ 'charges' => 'present|array|list|max:20',
+ 'file' => 'nullable|file|mimes:pdf,jpg,jpeg,png|extensions:pdf,jpg,jpeg,png|max:65536',
+ ])->validate();
+ unset($data['file']);
+ $data['charges'] = app(ImportLegalAmounts::class)->definitions($data['charges']);
+ $data['operation_key'] = strtolower($data['operation_key']);
+ $checksum = $file === null ? null : hash_file('sha256', $file->getPathname());
+ $hash = hash('sha256', json_encode([$data, $checksum], JSON_THROW_ON_ERROR));
+ $newPath = '';
+ try {
+ return DB::transaction(function () use ($actor, $data, $hash, $file, &$newPath) {
+ $actor = $this->actor($actor);
+ abort_unless($actor->hasFunctions(['import_customs']), 403);
+ $retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
+ if ($retry !== null) {
+ abort_unless($retry->kind === ($data['action'] === 'source' ? 'import_legal_source' : 'import_legal_rule') && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
+
+ return $retry;
+ }
+ if ($data['action'] === 'source') {
+ abort_unless($file !== null && $data['record_key'] === null && (int) $data['version'] === 0 && empty($data['source_id']), 422);
+ $source = $this->storeSource($actor, $data, $file, $hash, $data['operation_key'], $newPath);
+ app(RequisitionWorkflow::class)->audit($actor, 'import.legal_source_recorded', null, null, ['source_id' => $source->id, 'calculations_activated' => false]);
+
+ return $source;
+ }
+ $old = $data['record_key'] === null ? null : app(SupplyPlanning::class)->latest('import_legal_rule')->where('record_key', $data['record_key'])->firstOrFail();
+ abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A regra mudou. Consulte a versão actual e preserve a preparação.');
+ $sourceId = $data['source_id'] ?? $old?->snapshot['source_id'] ?? null;
+ if ($data['action'] === 'save') {
+ abort_unless($file !== null || $sourceId !== null, 422, 'Conserve o exemplar oficial antes da publicação.');
+ if ($file === null) {
+ $existingSource = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($sourceId)->firstOrFail();
+ abort_unless($data['official_reference'] === $existingSource->data['official_reference'] && ($data['official_url'] ?? null) === ($existingSource->data['official_url'] ?? null), 422,
+ 'Uma fonte diferente exige o respectivo exemplar; pode alterar a citação dentro do mesmo exemplar.');
+ }
+ if ($file !== null) {
+ abort_if(! empty($data['source_id']), 422, 'Seleccione um exemplar existente ou carregue um novo.');
+ $source = $this->storeSource($actor, $data, $file, $hash, (string) Str::uuid(), $newPath);
+ $sourceId = $source->id;
+ }
+ $payload = array_diff_key($data, array_flip(['operation_key', 'record_key', 'version', 'action', 'reason']));
+ $state = 'draft';
+ } else {
+ abort_unless($old !== null && ($data['action'] === 'publish' ? $old->state === 'draft' : $old->state !== 'withdrawn'), 409);
+ abort_unless($file === null && empty($data['source_id']), 422, 'A decisão conserva o exemplar da preparação; altere a fonte numa nova preparação.');
+ $payload = $old->data;
+ $state = $data['action'] === 'publish' ? 'published' : 'withdrawn';
+ }
+ $source = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($sourceId)->firstOrFail();
+ app(ImportEvidence::class)->bytes($source);
+ $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_legal_rule',
+ 'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
+ 'state' => $state, 'created_by' => $actor->id, 'data' => $payload,
+ 'snapshot' => ['source_id' => $source->id, 'source_sha256' => $source->snapshot['evidence']['sha256'],
+ 'supersedes' => $old?->id, 'calculations_activated' => false, 'reviewed_by' => $state === 'published' ? $actor->id : null],
+ 'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
+ app(RequisitionWorkflow::class)->audit($actor, 'import.legal_'.$data['action'], null, null,
+ ['record_id' => $record->id, 'version' => $record->version, 'state' => $state, 'source_id' => $source->id, 'calculations_activated' => false]);
+
+ return $record;
+ });
+ } catch (\Throwable $error) {
+ if ($newPath !== '' && ! SupplyRecord::query()->where('snapshot->evidence->path', $newPath)->exists()) {
+ Storage::disk('local')->delete($newPath);
+ }
+ throw $error;
+ }
+ }
+
+ /** @param array $data */
+ private function storeSource(User $actor, array $data, UploadedFile $file, string $hash, string $operation, string &$newPath): SupplyRecord
+ {
+ $key = (string) Str::uuid();
+ $stored = $file->storeAs('import-legal/'.$actor->tenant_id, $key.'-1.'.$file->extension(), 'local');
+ abort_unless(is_string($stored) && $file->getSize() > 0, 503);
+ $newPath = $stored;
+ $checksum = hash_file('sha256', $file->getPathname());
+ abort_unless(is_string($checksum), 503);
+ $source = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_legal_source',
+ 'record_key' => $key, 'version' => 1, 'state' => 'recorded', 'created_by' => $actor->id,
+ 'data' => ['official_reference' => $data['official_reference'], 'official_url' => $data['official_url'] ?? null],
+ 'snapshot' => ['evidence' => ['disk' => 'local', 'path' => $newPath, 'sha256' => $checksum,
+ 'size' => $file->getSize(), 'mime_type' => $file->getMimeType()]],
+ 'reason' => $data['reason'], 'operation_key' => $operation, 'input_hash' => $hash, 'created_at' => now()]);
+ app(ImportEvidence::class)->bytes($source);
+
+ return $source;
+ }
+
+ /** @return Builder */
+ private function published(?string $date = null)
+ {
+ $date ??= today()->toDateString();
+
+ return SupplyRecord::query()->where('kind', 'import_legal_rule')->whereIn('id', SupplyRecord::query()
+ ->where('kind', 'import_legal_rule')->whereIn('state', ['published', 'withdrawn'])
+ ->where(fn ($query) => $query->where('state', 'withdrawn')->orWhere('data->valid_from', '<=', $date))
+ ->selectRaw('MAX(id)')->groupBy('record_key'))
+ ->where('state', 'published');
+ }
+
+ /** @return list> */
+ public function suggestions(User $actor, Requisition $request, string $code, string $origin, string $sector, string $date): array
+ {
+ return DB::transaction(function () use ($actor, $request, $code, $origin, $sector, $date) {
+ $actor = $this->actor($actor);
+ Requisition::query()->visibleTo($actor)->findOrFail($request->id);
+ Validator::make(['date' => $date], ['date' => 'required|date_format:Y-m-d'])->validate();
+
+ return array_values($this->published($date)->where('data->match_code', $code)->orderBy('id')->get()->filter(fn ($rule) => $this->applies($rule, $origin, $sector, $date))
+ ->map(fn ($rule) => ['id' => $rule->id, 'version' => $rule->version, 'data' => $rule->data,
+ 'source_sha256' => $rule->snapshot['source_sha256']])->all());
+ });
+ }
+
+ private function applies(SupplyRecord $rule, string $origin, string $sector, string $date): bool
+ {
+ return $rule->data['valid_from'] <= $date && (($rule->data['valid_until'] ?? null) === null || $rule->data['valid_until'] >= $date)
+ && (empty($rule->data['origin_country']) || mb_strtolower($rule->data['origin_country']) === mb_strtolower(trim($origin)))
+ && (empty($rule->data['sector']) || mb_strtolower($rule->data['sector']) === mb_strtolower(trim($sector)));
+ }
+
+ /** @return array */
+ public function freeze(int $id, string $code, string $origin, string $sector, string $date): array
+ {
+ abort_unless($this->ready(), 503);
+ $rule = SupplyRecord::query()->where('kind', 'import_legal_rule')->findOrFail($id);
+ abort_unless($this->published($date)->whereKey($id)->exists(), 409,
+ 'A regra foi substituída, retirada ou ainda não foi publicada para este período. Consulte as fontes preservadas e prepare a versão aplicável.');
+ abort_unless($rule->data['match_code'] === $code && $this->applies($rule, $origin, $sector, $date), 409, 'A regra não corresponde ao contexto ou ao período indicado.');
+ $source = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($rule->snapshot['source_id'])->firstOrFail();
+ app(ImportEvidence::class)->bytes($source);
+
+ return ['id' => $rule->id, 'record_key' => $rule->record_key, 'version' => $rule->version, 'data' => $rule->data,
+ 'source_id' => $source->id, 'source_sha256' => $source->snapshot['evidence']['sha256'],
+ 'context' => ['code' => $code, 'origin_country' => $origin, 'sector' => $sector, 'date' => $date]];
+ }
+
+ /** @param array $frozen */
+ public function changed(array $frozen): bool
+ {
+ if (! $this->ready()) {
+ return true;
+ }
+ $rule = $this->published()->where('record_key', $frozen['record_key'])->first();
+
+ if ($rule === null || $rule->id !== $frozen['id'] || ! $this->applies($rule, $frozen['context']['origin_country'], $frozen['context']['sector'], today()->toDateString())) {
+ return true;
+ }
+ try {
+ $source = SupplyRecord::query()->where('kind', 'import_legal_source')->whereKey($rule->snapshot['source_id'])->firstOrFail();
+ app(ImportEvidence::class)->bytes($source);
+ } catch (HttpExceptionInterface|ModelNotFoundException) {
+ return true;
+ }
+
+ return false;
+ }
+
+ public function source(User $actor, Requisition $request, int $id): SupplyRecord
+ {
+ return DB::transaction(function () use ($actor, $request, $id) {
+ $actor = $this->actor($actor);
+ Requisition::query()->visibleTo($actor)->findOrFail($request->id);
+ $source = SupplyRecord::query()->where('kind', 'import_legal_source')->findOrFail($id);
+ app(ImportEvidence::class)->bytes($source);
+
+ return $source;
+ });
+ }
+}
diff --git a/app/Services/ImportReadiness.php b/app/Services/ImportReadiness.php
new file mode 100644
index 0000000..ee89c1e
--- /dev/null
+++ b/app/Services/ImportReadiness.php
@@ -0,0 +1,144 @@
+ready();
+ }
+
+ /** @return array */
+ public function workspace(User $actor, SupplyRecord $import): array
+ {
+ abort_unless($this->ready(), 503);
+
+ return DB::transaction(function () use ($actor, $import) {
+ [$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import);
+ $base = '/compras/importacoes/'.$current->id;
+ $alerts = [];
+ $add = function (string $key, string $category, string $text, string $href) use (&$alerts) {
+ $alerts[] = ['key' => $key, 'category' => $category, 'text' => $text, 'href' => $href];
+ };
+ $expected = $current->data['expected_usable_on'] ?? null;
+ $receipts = app(ReceiptWorkflow::class)->progress($order);
+ if ($expected === null) {
+ $add('expected-unknown', 'Por determinar', 'Data de recepção utilizável prevista ainda por indicar.', '/compras/fornecimento/import');
+ } elseif ($receipts['state'] !== 'complete' && $expected <= today()->toDateString()) {
+ $add('expected-due', 'Logística', $expected < today()->toDateString()
+ ? 'A previsão de recepção utilizável foi ultrapassada; confira os marcos logísticos.'
+ : 'A recepção utilizável está prevista para hoje; confira os marcos logísticos.', '/compras/fornecimento/import');
+ }
+ if (in_array($current->state, ['arrived', 'held'], true)) {
+ $add('customs-pending', 'Logística', 'A mercadoria ainda não tem libertação aduaneira registada; a chegada não demonstra stock utilizável.', '/compras/fornecimento/import');
+ }
+ $linkedLots = InventoryLotAllocation::query()->whereIn('stock_movement_id', StockMovement::query()->select('id')
+ ->whereIn('goods_receipt_item_id', GoodsReceiptItem::query()->select('id')->whereIn('purchase_order_item_id', $order->items()->select('id'))))->pluck('lot_id');
+ $lotLocations = InventoryLotAllocation::query()->whereIn('lot_id', $linkedLots)->get(['lot_id', 'stock_item_id', 'warehouse_id'])
+ ->groupBy(fn ($row) => $row->stock_item_id.':'.$row->warehouse_id);
+ $lotsComplete = true;
+ foreach ($lotLocations as $locations) {
+ $first = $locations->firstOrFail();
+ $context = app(InventoryLots::class)->context($first->stock_item_id, $first->warehouse_id);
+ if ($context === null || ! $context['reconciled']) {
+ $lotsComplete = false;
+ $add('stock-unverified-'.$first->stock_item_id.'-'.$first->warehouse_id, 'Verificação incompleta', 'A disponibilidade por lotes ligados à recepção requer conferência no armazém.', '/ordens/'.$order->id);
+ } else {
+ foreach ($context['lots'] as $lot) {
+ if ($locations->contains('lot_id', $lot['id']) && $lot['quantity_milli'] > 0 && $lot['usable_milli'] === 0) {
+ $add('stock-held-'.$lot['id'].'-'.$first->warehouse_id, 'Disponibilidade', 'Há saldo não utilizável num lote ligado às recepções desta ordem; confira a identificação, validade e libertação de qualidade no armazém.', '/ordens/'.$order->id);
+ }
+ }
+ }
+ }
+ $documents = app(SupplyPlanning::class)->latest('import_document')->where('purchase_order_id', $order->id)
+ ->where('snapshot->import_key', $current->record_key)->orderBy('id')->limit(201)->get();
+ $documentsComplete = $documents->count() <= 200;
+ $complete = $documentsComplete && $lotsComplete;
+ $validTypes = [];
+ foreach ($documents->take(200) as $document) {
+ try {
+ app(ImportEvidence::class)->bytes($document);
+ $validTypes[] = $document->data['type'];
+ } catch (HttpExceptionInterface) {
+ $add('document-'.$document->id, 'Documentos', 'Original indisponível ou alterado: '.$document->data['reference'].'.', $base.'/documentos');
+ }
+ }
+ if (! $documentsComplete) {
+ $add('documents-incomplete', 'Verificação incompleta', 'O acompanhamento verificou os primeiros 200 originais actuais. Consulte o dossiê completo antes de concluir a conferência.', $base.'/documentos');
+ }
+ $requirements = [];
+ $classifications = $order->snapshot['import_tariffs'] ?? [];
+ foreach ($classifications as $classification) {
+ $requestId = $classification['data']['requisition_id'] ?? $order->requisition_id;
+ $legal = $classification['legal_rule'] ?? null;
+ if ($legal === null) {
+ $add('legal-unknown-'.$classification['record_id'], 'Por determinar', 'Requisitos legais ainda por associar ao artigo '.$classification['item']['description'].'.', '/requisicoes/'.$requestId.'/base-legal');
+
+ continue;
+ }
+ if (app(ImportLegalRules::class)->changed($legal)) {
+ $add('legal-changed-'.$classification['record_id'], 'Fonte legal', 'A regra aplicada ao artigo '.$classification['item']['description'].' mudou, terminou ou ficou indisponível. A decisão preservada requer revisão.', '/requisicoes/'.$requestId.'/classificacao-pautal');
+ }
+ $requirements = [...$requirements, ...$legal['data']['document_types']];
+ }
+ if ($classifications === []) {
+ $add('classification-unknown', 'Por determinar', 'Não há classificação pautal preservada nesta ordem. Consulte as origens antes de determinar os requisitos aplicáveis.', '/ordens/'.$order->id);
+ }
+ foreach (array_unique($requirements) as $type) {
+ if (! in_array($type, $validTypes, true)) {
+ $add('required-'.$type, 'Documentos', 'Documento indicado na fonte aplicada ainda não disponível: '.ImportDossier::TYPES[$type].'.', $base.'/documentos');
+ }
+ }
+ $parties = app(ImportParties::class)->workspace($actor, $current)['current'];
+ if ($parties->isEmpty()) {
+ $add('parties-unknown', 'Por determinar', 'Despachante ou transitário e respectivas instruções ainda por associar; não foram presumidos intervenientes.', $base.'/documentos');
+ }
+ foreach ($parties as $party) {
+ foreach ($party['issues'] as $index => $issue) {
+ $add('party-'.$party['id'].'-'.$index, 'Intervenientes', $issue, $base.'/documentos');
+ }
+ }
+ if (app(ImportBankSupport::class)->ready()) {
+ $terms = 0;
+ app(ImportBankSupport::class)->report($actor, $current, function ($record, $issues) use (&$terms, $add, $base) {
+ $terms++;
+ foreach ($issues as $index => $issue) {
+ $add('bank-'.$record->id.'-'.$index, 'Suporte bancário', $issue, $base.'/suporte-bancario');
+ }
+ });
+ if ($terms === 0) {
+ $add('bank-unknown', 'Por determinar', 'Aplicabilidade e acompanhamento do termo bancário ainda por registar; não foi presumido um prazo.', $base.'/suporte-bancario');
+ }
+ } else {
+ $complete = false;
+ $add('bank-unavailable', 'Verificação incompleta', 'A consulta do acompanhamento bancário está indisponível neste ambiente.', $base.'/documentos');
+ }
+ if ($actor->hasFunctions(['finance'])) {
+ $plans = app(SupplyPlanning::class)->latest('import_cost_plan')->where('purchase_order_id', $order->id)->get(['id', 'state']);
+ if ($plans->isEmpty()) {
+ $add('cost-unknown', 'Por determinar', 'Custos efectivos ainda sem preparação neste âmbito; a ausência de valores não significa custo zero.', $base.'/custos');
+ }
+ foreach ($plans as $plan) {
+ if (in_array($plan->state, ['draft', 'returned'], true)) {
+ $add('cost-'.$plan->id, 'Conferência financeira', 'A preparação dos custos efectivos aguarda conferência ou correcção no percurso financeiro.', $base.'/custos');
+ }
+ }
+ }
+
+ return ['importRecord' => $current->only(['id', 'record_key', 'version', 'state']), 'order' => $order->only(['id', 'number']),
+ 'expectedUsableOn' => $expected, 'checkedAt' => now()->toIso8601String(), 'complete' => $complete,
+ 'alerts' => $alerts, 'financialEffects' => false, 'automaticNotifications' => false];
+ });
+ }
+}
diff --git a/app/Services/ImportTariffCodes.php b/app/Services/ImportTariffCodes.php
index c81da16..62f53c5 100644
--- a/app/Services/ImportTariffCodes.php
+++ b/app/Services/ImportTariffCodes.php
@@ -39,7 +39,8 @@ final class ImportTariffCodes
'Confirme a classificação pautal actual de cada artigo importado antes de emitir a ordem.');
$result[$item->id] = ['record_id' => $record->id, 'version' => $record->version,
'requisition_item_id' => $item->id, 'item' => $record->snapshot['item'], 'data' => $record->data,
- 'source' => $record->snapshot['master'] ?? null, 'confirmed_by' => $record->snapshot['confirmed_by'], 'reason' => $record->reason];
+ 'source' => $record->snapshot['master'] ?? null, 'legal_rule' => $record->snapshot['legal_rule'] ?? null,
+ 'confirmed_by' => $record->snapshot['confirmed_by'], 'reason' => $record->reason];
}
ksort($result, SORT_NUMERIC);
@@ -72,7 +73,11 @@ final class ImportTariffCodes
$stockItems->through(fn ($item) => [...$item->only(['id', 'code', 'name', 'unit']),
'tariff' => app(SupplyPlanning::class)->latest('stock_tariff')->where('stock_item_id', $item->id)->first(['id', 'version', 'data'])]);
- return ['requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity']),
+ $latest->each(function ($record) {
+ $record->setAttribute('legal_changed', isset($record->snapshot['legal_rule']) && app(ImportLegalRules::class)->changed($record->snapshot['legal_rule']));
+ });
+
+ return ['legalReady' => app(ImportLegalRules::class)->ready(), 'requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity']),
'latest' => $latest, 'history' => $history, 'stockItems' => $stockItems, 'canPropose' => ($actor->id === $request->requester_id && app(OrganizationAccess::class)->canRequest($actor)) || $actor->hasFunctions([PurchasingRole::Procurement]),
'canConfirm' => $actor->hasFunctions([PurchasingRole::Procurement]),
'masters' => app(SupplyPlanning::class)->latest('stock_tariff')->when(! $materialsVisible, fn ($q) => $q->whereRaw('1 = 0'))->whereIn('stock_item_id', StockItem::query()->select('id'))
@@ -89,7 +94,10 @@ final class ImportTariffCodes
'version' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000',
'stock_item_id' => 'required_if:action,master|nullable|integer|min:1', 'requisition_item_id' => 'required_unless:action,master|nullable|integer|min:1',
'master_id' => 'nullable|integer|min:1', 'code' => 'required_unless:action,propose|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/',
- 'source_reference' => 'required_unless:action,propose|nullable|string|max:2000'])->validate();
+ 'source_reference' => 'required_unless:action,propose|nullable|string|max:2000',
+ 'legal_rule_id' => 'nullable|integer|min:1', 'legal_match_code' => 'required_with:legal_rule_id|nullable|string|max:40',
+ 'legal_origin' => 'nullable|string|max:120', 'legal_sector' => 'nullable|string|max:160',
+ 'legal_date' => 'required_with:legal_rule_id|nullable|date_format:Y-m-d'])->validate();
$data['operation_key'] = strtolower($data['operation_key']);
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
@@ -133,10 +141,23 @@ final class ImportTariffCodes
abort_unless($code === $master->data['code'] && $source === $master->data['source_reference'], 409, 'Aplique explicitamente o código e a fonte do cadastro ou conserve uma proposta manual.');
$snapshot['master'] = ['id' => $master->id, 'version' => $master->version, 'item' => $master->snapshot['item']];
}
+ if (! empty($data['legal_rule_id'])) {
+ abort_unless($buyer && empty($data['master_id']), 403);
+ $legal = app(ImportLegalRules::class)->freeze((int) $data['legal_rule_id'], $data['legal_match_code'],
+ $data['legal_origin'] ?? '', $data['legal_sector'] ?? '', $data['legal_date']);
+ abort_unless($code === $legal['data']['suggested_code'] && $source === $legal['data']['official_reference'].' — '.$legal['data']['citation'], 409,
+ 'Aplique explicitamente o código e a citação da regra seleccionada.');
+ $snapshot['legal_rule'] = $legal;
+ }
$state = 'proposed';
} else {
abort_unless($old !== null && $old->state === 'proposed' && empty($data['master_id']) && $code !== '' && $source !== '', 409, 'Seleccione uma proposta actual e indique código e fonte da confirmação.');
abort_unless($old->snapshot['item'] === $snapshot['item'], 409, 'O artigo mudou. Prepare uma proposta actual.');
+ if (isset($old->snapshot['legal_rule'])) {
+ $legal = $old->snapshot['legal_rule'];
+ app(ImportLegalRules::class)->freeze($legal['id'], $legal['context']['code'], $legal['context']['origin_country'],
+ $legal['context']['sector'], $legal['context']['date']);
+ }
$payload = [...$old->data, 'confirmed_code' => $code, 'confirmation_source' => $source,
'deviation' => $code !== $old->data['proposed_code'], 'confirmed_by' => $actor->id];
$snapshot = [...$old->snapshot, 'confirmed_by' => ['id' => $actor->id, 'name' => $actor->name]];
diff --git a/app/Services/OrderPartsWorkflow.php b/app/Services/OrderPartsWorkflow.php
index ea69404..1cff781 100644
--- a/app/Services/OrderPartsWorkflow.php
+++ b/app/Services/OrderPartsWorkflow.php
@@ -195,7 +195,7 @@ final class OrderPartsWorkflow
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.');
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
- $frames = $requests = $lines = $catalogue = $tariffs = [];
+ $frames = $requests = $lines = $catalogue = $tariffs = $capital = [];
$firstQuote = null;
foreach ($prepared['sources'] as $source) {
$request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
@@ -208,6 +208,7 @@ final class OrderPartsWorkflow
'Preserve os intervenientes e as referências de cada origem.');
$requested = $request->items()->get()->keyBy('id');
$tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
+ $capital += app(CapitalAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
foreach ($source['items'] as $item) {
$native = $requested->get($item['requisition_item_id']);
abort_unless($native !== null, 409);
@@ -240,7 +241,7 @@ final class OrderPartsWorkflow
$exchange = $foreign ? ['exchange_basis' => null,
'exchange_sources' => array_map(fn ($s) => ['requisition_id' => $s['requisition_id'], 'exchange_basis' => $s['exchange_basis']], $prepared['sources']),
'reference_amounts' => app(OrderPartsExchange::class)->sum(array_column($prepared['sources'], 'reference_amounts'))] : [];
- $snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
+ $snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), ...($capital === [] ? [] : ['capital_assignments' => $capital]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true,
diff --git a/app/Services/PurchaseWorkflow.php b/app/Services/PurchaseWorkflow.php
index bb1de6e..e4cc534 100644
--- a/app/Services/PurchaseWorkflow.php
+++ b/app/Services/PurchaseWorkflow.php
@@ -170,7 +170,9 @@ class PurchaseWorkflow
}
}
$tariffs = app(ImportTariffCodes::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
+ $capital = app(CapitalAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
$snapshot = [
+ ...($capital === [] ? [] : ['capital_assignments' => $capital]),
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
diff --git a/config/capital-register.php b/config/capital-register.php
new file mode 100644
index 0000000..a626b62
--- /dev/null
+++ b/config/capital-register.php
@@ -0,0 +1,3 @@
+ false];
diff --git a/config/import-bank-support.php b/config/import-bank-support.php
new file mode 100644
index 0000000..a626b62
--- /dev/null
+++ b/config/import-bank-support.php
@@ -0,0 +1,3 @@
+ false];
diff --git a/config/import-legal.php b/config/import-legal.php
new file mode 100644
index 0000000..a626b62
--- /dev/null
+++ b/config/import-legal.php
@@ -0,0 +1,3 @@
+ false];
diff --git a/config/import-readiness.php b/config/import-readiness.php
new file mode 100644
index 0000000..a626b62
--- /dev/null
+++ b/config/import-readiness.php
@@ -0,0 +1,3 @@
+ false];
diff --git a/docs/desenvolvimento.md b/docs/desenvolvimento.md
index e538d03..9668fce 100644
--- a/docs/desenvolvimento.md
+++ b/docs/desenvolvimento.md
@@ -1,7 +1,17 @@
# Desenvolvimento do SGC
+Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
+
+Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
+
## Continuação integral — 27/11/2026
+Estimativa documentada de imposições e adopção no plano nativo também implementadas em QA (`proofs/import-legal-amounts-qa.json`): aritmética decimal exacta, taxas/bases/unidades e condições explícitas, desconhecido indeterminado, fonte/versão preservadas, escolha humana e divisão base/imposto sem pressupor recuperabilidade. Uma imposição não pode ser repetida em duas parcelas ligadas à mesma origem. Publicação futura conserva o período anterior aplicável; fonte retirada exige revisão antes da aprovação. PostgreSQL57/919, concorrência e restauro com cálculo750cêntimos/plano10750cêntimos sintéticos e11originais aprovados, bases removidas; frontend180/180, tipos/PHPStan/check/build privado aprovados. HTTP nativo carregou/descarregou15509234bytes do BR real partilhado com mesmoSHA, login/CSRF/repetição/401/403, sem publicar regras ou efeitos financeiros; servidor/base/raiz privados removidos. PHP global conserva limites anteriores; ensaio privado usou64M/70M. Corrigido identificador interno longo detectado pelo PostgreSQL, com regressão nativa. Não declarar conclusão integral nem parar por este incremento; continuar os requisitos e a revisão visual. O host de navegador está indisponível, mas o Edge nativo foi lançado com êxito; revisão ainda não executada. Piloto e fontes reais preservados.
+
+Base legal documental e acompanhamento contextual de importação implementados em QA (`proofs/import-legal-readiness-qa.json`). Fontes independentes das regras; exemplares até64MB, citação/vigência, preparação/publicação/retirada pela competência aduaneira existente, sugestão explícita e confirmação/desvio pelo comprador, fonte congelada na requisição/ordem/impressão e alerta de alteração sem reescrever decisões. Acompanhamento reutiliza originais, intervenientes, relatório bancário e recepção efectiva; desconhecido/incompleto explícitos, sem notificações automáticas ou novos efeitos financeiros. PostgreSQL integrado36/337 e delta final da base legalSQLite7/54; protocolo8/38; frontend177/177, tipos/PHPStan/check e build privado aprovados. Concorrência legal e recuperação de11originais/versão publicada/contexto do comprador aprovadas; bases removidas. Legislação já partilhada localizada: inventário8109ficheiros (inclui ocultos); quatro exemplares oficiais reais conferidos em empresaQA sintética, sem publicar regras nem alterar originais. Continuar cálculo documentado de imposições, demais regras/alertas e lacunas transversais; não encerrar a aplicação por este incremento. Navegador novamente indisponível na API actual, sem navegador nativo enumerado; revisão visual permanece pendente. Piloto conserva manifesto1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e, sem instalação/activação.
+
+Suporte documental bancário concluído em QA: termo ligado ao DU/declaração, tipos e quantidades explícitos, fonte do prazo, data efectiva/comprovativo da entrega, versões, alertas e CSV integral. Desconhecido permanece por indicar; sem activação de regras legais, transferências ou submissões JUE. Prova `proofs/import-bank-support-qa.json`: PostgreSQL39/324, concorrência200/200 e200/409 com um efeito/uma auditoria, recuperação de duas versões bancárias e dez originais privados, bases removidas; frontend172/172, tipos/PHPStan/Pint/check e build privado aprovados. Este delta substitui apenas a pendência de acompanhamento bancário abaixo. Sugestões legais versionadas, revisão visual/móvel/impressão e preparação operacional continuam abertas; não instalar/activar por inferência. Preservar as provas, sem repetir suites aprovadas sem delta.
+
Estimativas: `ImportEstimates`/formulário nativo/ajuda conservam pressupostos por versão antes dos documentos. `BudgetImportEstimate` e capacidade comum opcional reservam apenas extras no diário existente; o percurso nativo usa o custo integral para todos os níveis, sem alterar os bens. Rejeição liberta ambas as reservas na mesma transacção. `reconcileImportEstimate` e formulário de Finanças fazem a libertação parcial e a aplicação documental atomicamente, incluindo várias origens/mesmo plano e planos só de facturas nativas. Guardas preservam identidade, orçamento, revisões e consumo, rejeitam duplicação por outra chave e ignoram paginação na autoridade. A fonte prévia v2 foi congelada apenas num directório QA privado para provar a recusa de downgrade. Prova `proofs/import-estimates-qa.json`: nativoPG6/70, contrato22/156, aprovações32/737, importação40/286, concorrência/recuperação, frontend169/169, tipos/PHPStan/build privado aprovados. Corrigidas as inconsistências do próprio ensaio: identidades de operação distintas, orçamento sintético criado/aprovado por Finanças, agregados PostgreSQL e ajuda contextual em falta. Sem alterações operacionais.
Delta: `ImportParties` e formulário nativo seleccionam despachante/transitário elegível, com versão do fornecedor e instrução escrita, comprador independente, conflitos, histórico e revalidação logística. Prova `proofs/import-parties-qa.json`: PostgreSQL40/286, concorrência e recuperação de seis originais/duas selecções aprovadas. Correcção do auxiliar CLI preserva os utilizadores sem modificar autenticação real. Despesa por confirmação implementada em `ProcurementPaymentInsights`, leitura auditada através de `SupplierPayables`, painel e CSV próprios; origem externa única, período da confirmação e moedas independentes. Prova `proofs/confirmed-payment-insights-qa.json`: regressãoPG24/515, delta final5/84, frontend2, tipos/PHPStan/build privado aprovados. Sem disponibilização operacional; revisão visual e requisitos restantes continuam abertos.
diff --git a/docs/matriz-sgc-reconciliada.md b/docs/matriz-sgc-reconciliada.md
index 77300fb..0b60b03 100644
--- a/docs/matriz-sgc-reconciliada.md
+++ b/docs/matriz-sgc-reconciliada.md
@@ -1,7 +1,17 @@
# Matriz reconciliada do SGC — 03/11/2026
+Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
+
+Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
+
## Continuação integral — 27/11/2026
+Estimativa documentada de imposições e adopção no plano nativo também implementadas em QA (`proofs/import-legal-amounts-qa.json`): aritmética decimal exacta, taxas/bases/unidades e condições explícitas, desconhecido indeterminado, fonte/versão preservadas, escolha humana e divisão base/imposto sem pressupor recuperabilidade. Uma imposição não pode ser repetida em duas parcelas ligadas à mesma origem. Publicação futura conserva o período anterior aplicável; fonte retirada exige revisão antes da aprovação. PostgreSQL57/919, concorrência e restauro com cálculo750cêntimos/plano10750cêntimos sintéticos e11originais aprovados, bases removidas; frontend180/180, tipos/PHPStan/check/build privado aprovados. HTTP nativo carregou/descarregou15509234bytes do BR real partilhado com mesmoSHA, login/CSRF/repetição/401/403, sem publicar regras ou efeitos financeiros; servidor/base/raiz privados removidos. PHP global conserva limites anteriores; ensaio privado usou64M/70M. Corrigido identificador interno longo detectado pelo PostgreSQL, com regressão nativa. Não declarar conclusão integral nem parar por este incremento; continuar os requisitos e a revisão visual. O host de navegador está indisponível, mas o Edge nativo foi lançado com êxito; revisão ainda não executada. Piloto e fontes reais preservados.
+
+Base legal documental e acompanhamento contextual de importação implementados em QA (`proofs/import-legal-readiness-qa.json`). Fontes independentes das regras; exemplares até64MB, citação/vigência, preparação/publicação/retirada pela competência aduaneira existente, sugestão explícita e confirmação/desvio pelo comprador, fonte congelada na requisição/ordem/impressão e alerta de alteração sem reescrever decisões. Acompanhamento reutiliza originais, intervenientes, relatório bancário e recepção efectiva; desconhecido/incompleto explícitos, sem notificações automáticas ou novos efeitos financeiros. PostgreSQL integrado36/337 e delta final da base legalSQLite7/54; protocolo8/38; frontend177/177, tipos/PHPStan/check e build privado aprovados. Concorrência legal e recuperação de11originais/versão publicada/contexto do comprador aprovadas; bases removidas. Legislação já partilhada localizada: inventário8109ficheiros (inclui ocultos); quatro exemplares oficiais reais conferidos em empresaQA sintética, sem publicar regras nem alterar originais. Continuar cálculo documentado de imposições, demais regras/alertas e lacunas transversais; não encerrar a aplicação por este incremento. Navegador novamente indisponível na API actual, sem navegador nativo enumerado; revisão visual permanece pendente. Piloto conserva manifesto1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e, sem instalação/activação.
+
+Suporte documental bancário concluído em QA: termo ligado ao DU/declaração, tipos e quantidades explícitos, fonte do prazo, data efectiva/comprovativo da entrega, versões, alertas e CSV integral. Desconhecido permanece por indicar; sem activação de regras legais, transferências ou submissões JUE. Prova `proofs/import-bank-support-qa.json`: PostgreSQL39/324, concorrência200/200 e200/409 com um efeito/uma auditoria, recuperação de duas versões bancárias e dez originais privados, bases removidas; frontend172/172, tipos/PHPStan/Pint/check e build privado aprovados. Este delta substitui apenas a pendência de acompanhamento bancário abaixo. Sugestões legais versionadas, revisão visual/móvel/impressão e preparação operacional continuam abertas; não instalar/activar por inferência. Preservar as provas, sem repetir suites aprovadas sem delta.
+
Estimativa pré-documental integrada em QA: pressupostos versionados, desconhecido distinto de não aplicável, bens nativos preservados, aprovação pelo custo integral, reserva apenas dos encargos e libertação na rejeição. Finanças reconcilia parcelas explícitas com documentos efectivamente conferidos, conservando saldos de outras ordens e sem novo principal de factura. Várias origens podem reconciliar-se no mesmo plano sem repetir o custo efectivo; a paginação não altera a autoridade financeira. PostgreSQL nativo6/70, contrato22/156, regressão de aprovações32/737 e importação/dossiê/logística/saúde40/286 aprovados em bases separadas removidas; contagens não se somam. Concorrência de reserva/reconciliação, recusa dos três motores anteriores e recuperação integral aprovadas, incluindo saldo estimado remanescente e seis originais privados. Frontend169/169, tipos/PHPStan/check/build privado aprovados. Prova `proofs/import-estimates-qa.json`. Fonte canónica e adaptação apenas; sem instalação/activação. Continuam abertos suporte bancário/prazos, sugestões legais versionadas, revisão visual e demais requisitos do produto.
Despesa por período implementada em QA segundo a escolha «pagamentos confirmados»: originais auditados, data de confirmação no fuso da aplicação, moedas separadas, soma exacta, cobertura indeterminada explícita e CSV próprio. O filtro temporal deste indicador não exclui requisições criadas antes da confirmação. As cópias importadas não são somadas de novo; pendentes/rejeitados/preparações não contam. PostgreSQL regressão24/515 e deltaHTTP/CSV5/84 aprovados, bases removidas; dois testes frontend, tipos/PHPStan/check/build privado aprovados. Prova `proofs/confirmed-payment-insights-qa.json`. Não certifica execução bancária nem encerra a análise avançada restante.
diff --git a/docs/orientacoes-continuidade.md b/docs/orientacoes-continuidade.md
index 30db3fa..94f9c13 100644
--- a/docs/orientacoes-continuidade.md
+++ b/docs/orientacoes-continuidade.md
@@ -1,7 +1,17 @@
# Continuidade do desenvolvimento do SGC
+Decisão expressa nesta continuação: projectos e imobilizado terão cadastro próprio em Compras, independente do SGF. Implementação em curso, apenas QA, sem efeitos contabilísticos nem instalação no piloto. Reutilizar as fichas físicas de equipamento existentes; não criar dependência SGF. Revisão bancária nativa posterior gravou versão 2 com comprovativo/data/fundamento sintéticos, conservou versão 1 e retirou os avisos de entrega pendente/prazo de hoje. Ambiente privado encerrado e removido.
+
+Revisão nativa posterior em Edge: base legal observada a 390/823px sem transbordo horizontal; reutilização explícita da base sintética de 100 MZN gravou versão 2 de 7,50 MZN. Plano anterior conservou a origem escolhida #5 e total 107,50 MZN. Acompanhamento apresentou desconhecidos e pendências bancárias esperados. Servidor/raiz/base QA removidos, separadores do utilizador preservados. Prova ampliada em `proofs/import-legal-amounts-qa.json`. Esta revisão substitui apenas a indicação de revisão ainda não iniciada; impressão e aceitação visual transversal continuam por verificar.
+
## Continuação integral — 27/11/2026
+Estimativa documentada de imposições e adopção no plano nativo também implementadas em QA (`proofs/import-legal-amounts-qa.json`): aritmética decimal exacta, taxas/bases/unidades e condições explícitas, desconhecido indeterminado, fonte/versão preservadas, escolha humana e divisão base/imposto sem pressupor recuperabilidade. Uma imposição não pode ser repetida em duas parcelas ligadas à mesma origem. Publicação futura conserva o período anterior aplicável; fonte retirada exige revisão antes da aprovação. PostgreSQL57/919, concorrência e restauro com cálculo750cêntimos/plano10750cêntimos sintéticos e11originais aprovados, bases removidas; frontend180/180, tipos/PHPStan/check/build privado aprovados. HTTP nativo carregou/descarregou15509234bytes do BR real partilhado com mesmoSHA, login/CSRF/repetição/401/403, sem publicar regras ou efeitos financeiros; servidor/base/raiz privados removidos. PHP global conserva limites anteriores; ensaio privado usou64M/70M. Corrigido identificador interno longo detectado pelo PostgreSQL, com regressão nativa. Não declarar conclusão integral nem parar por este incremento; continuar os requisitos e a revisão visual. O host de navegador está indisponível, mas o Edge nativo foi lançado com êxito; revisão ainda não executada. Piloto e fontes reais preservados.
+
+Base legal documental e acompanhamento contextual de importação implementados em QA (`proofs/import-legal-readiness-qa.json`). Fontes independentes das regras; exemplares até64MB, citação/vigência, preparação/publicação/retirada pela competência aduaneira existente, sugestão explícita e confirmação/desvio pelo comprador, fonte congelada na requisição/ordem/impressão e alerta de alteração sem reescrever decisões. Acompanhamento reutiliza originais, intervenientes, relatório bancário e recepção efectiva; desconhecido/incompleto explícitos, sem notificações automáticas ou novos efeitos financeiros. PostgreSQL integrado36/337 e delta final da base legalSQLite7/54; protocolo8/38; frontend177/177, tipos/PHPStan/check e build privado aprovados. Concorrência legal e recuperação de11originais/versão publicada/contexto do comprador aprovadas; bases removidas. Legislação já partilhada localizada: inventário8109ficheiros (inclui ocultos); quatro exemplares oficiais reais conferidos em empresaQA sintética, sem publicar regras nem alterar originais. Continuar cálculo documentado de imposições, demais regras/alertas e lacunas transversais; não encerrar a aplicação por este incremento. Navegador novamente indisponível na API actual, sem navegador nativo enumerado; revisão visual permanece pendente. Piloto conserva manifesto1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e, sem instalação/activação.
+
+Suporte documental bancário concluído em QA: termo ligado ao DU/declaração, tipos e quantidades explícitos, fonte do prazo, data efectiva/comprovativo da entrega, versões, alertas e CSV integral. Desconhecido permanece por indicar; sem activação de regras legais, transferências ou submissões JUE. Prova `proofs/import-bank-support-qa.json`: PostgreSQL39/324, concorrência200/200 e200/409 com um efeito/uma auditoria, recuperação de duas versões bancárias e dez originais privados, bases removidas; frontend172/172, tipos/PHPStan/Pint/check e build privado aprovados. Este delta substitui apenas a pendência de acompanhamento bancário abaixo. Sugestões legais versionadas, revisão visual/móvel/impressão e preparação operacional continuam abertas; não instalar/activar por inferência. Preservar as provas, sem repetir suites aprovadas sem delta.
+
Estimativa pré-documental e reconciliação com custos efectivos também concluídas em QA (`proofs/import-estimates-qa.json`). Preservar a capacidade opcional, o saldo estimado por origem, o custo integral nas aprovações e o escritor comum. Não repetir suites aprovadas sem delta: nativoPG6/70, contrato22/156, aprovações32/737, importação40/286, frontend169/169, concorrência e recuperação integral. Fonte e formulário bancário/prazos são a próxima frente; secção10.4 do Word especifica termo de compromisso ligado ao DU/JUE e suporte bancário, mas os seus resumos/prazos não activam regras legais ou execução bancária. O Word mantém o hash aprovado; não foi editado. Rever fontes oficiais e a configuração existente conforme o requisito afectado, sem inventar prazos ou destinatários.
Implementados em QA desde a decisão: selecção de intervenientes/instruções escritas (`proofs/import-parties-qa.json`) e indicador/CSV de pagamentos confirmados por data de confirmação (`proofs/confirmed-payment-insights-qa.json`). Preservar estes deltas e os testes aceites; não repetir a escolha da base da despesa. A próxima frente funcional é a estimativa pré-documental e sua integração com aprovação/reserva no núcleo financeiro comum autorizado. A análise avançada restante e a revisão visual não estão concluídas; não instalar/activar por inferência.
diff --git a/docs/plano-entregas-sgc.md b/docs/plano-entregas-sgc.md
index 7f50fa0..b01dac1 100644
--- a/docs/plano-entregas-sgc.md
+++ b/docs/plano-entregas-sgc.md
@@ -1,5 +1,7 @@
# Entregas por blocos funcionais do SGC
+Base legal documental e acompanhamento contextual de importação implementados em QA (`proofs/import-legal-readiness-qa.json`). Fontes independentes das regras; exemplares até64MB, citação/vigência, preparação/publicação/retirada pela competência aduaneira existente, sugestão explícita e confirmação/desvio pelo comprador, fonte congelada na requisição/ordem/impressão e alerta de alteração sem reescrever decisões. Acompanhamento reutiliza originais, intervenientes, relatório bancário e recepção efectiva; desconhecido/incompleto explícitos, sem notificações automáticas ou novos efeitos financeiros. PostgreSQL integrado36/337 e delta final da base legalSQLite7/54; protocolo8/38; frontend177/177, tipos/PHPStan/check e build privado aprovados. Concorrência legal e recuperação de11originais/versão publicada/contexto do comprador aprovadas; bases removidas. Legislação já partilhada localizada: inventário8109ficheiros (inclui ocultos); quatro exemplares oficiais reais conferidos em empresaQA sintética, sem publicar regras nem alterar originais. Continuar cálculo documentado de imposições, demais regras/alertas e lacunas transversais; não encerrar a aplicação por este incremento. Navegador novamente indisponível na API actual, sem navegador nativo enumerado; revisão visual permanece pendente. Piloto conserva manifesto1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e, sem instalação/activação.
+
## Estado reconciliado mais recente - 22/11/2026
Ordens parciais/consolidadas em MZN: emissão nativa, origens, recepção, factura com validação independente e cancelamento C2 por Finanças implementados em QA. PostgreSQL 56 testes/498 verificações; delta HTTP final 1/25. A revisão nativa observou uma ordem sintética de 100 MZN, parcelas de 40/60 MZN e apresentação a 390/1000 px. A ferramenta interrompeu o controlo antes da paginação de impressão; restante percurso visual continua pendente. Servidor, base e configuração privados removidos. Prova: `proofs/rq01-multi-order-native-qa.json`. Câmbio por origem, reafectação de Finanças e disponibilização operacional continuam por concluir.
diff --git a/docs/proofs/capital-register-qa.json b/docs/proofs/capital-register-qa.json
new file mode 100644
index 0000000..7e1c1bc
--- /dev/null
+++ b/docs/proofs/capital-register-qa.json
@@ -0,0 +1,47 @@
+{
+ "date": "2026-11-27",
+ "status": "development_in_isolated_qa_not_installed_not_product_completion",
+ "owner_decision": "Cadastro próprio em Compras, independente do SGF",
+ "implementation": [
+ "Versioned project and asset documentary references owned by Compras",
+ "Existing equipment identities reused without creating duplicate physical records",
+ "Existing equipment register capabilities and department scope reused; no grants",
+ "Immutable codes, archive/history, operation replay and stale-version conflicts",
+ "Explicit draft requisition line assignment by its requester",
+ "Frozen origin in ordinary and partial/consolidated native order snapshots and print",
+ "Later register rename/archive does not rewrite accepted choices or issued orders"
+ ],
+ "sqlite_register_and_assignments": {"tests": 7, "assertions": 89, "passed": true},
+ "postgresql_directed_native_integration": {"tests": 11, "assertions": 181, "passed": true, "database_removed": true},
+ "frontend_directed": {"tests": 2, "passed": true},
+ "checks": {"types": "passed", "phpstan": "passed", "scoped_format_lint": "passed", "scoped_pint": "passed", "diff_whitespace": "passed"},
+ "concurrency": {
+ "same_operation": [200, 200], "same_version": [200, 409], "blocked_writers_observed": 2,
+ "new_versions_per_scenario": 1, "audits_per_scenario": 1, "new_files": 0, "database_removed": true,
+ "receipt_protocol_regression": {"tests": 10, "assertions": 46, "passed": true}
+ },
+ "native_edge_review": {
+ "synthetic_project_created_through_native_form": true,
+ "synthetic_line_assignment_saved_through_native_form": true,
+ "assignment_version": 1,
+ "source_version": 1,
+ "history_visible": true,
+ "viewports_observed_px": [390, 823],
+ "private_server_stopped": true, "private_root_removed": true, "database_removed": true,
+ "user_tabs_preserved": true,
+ "layout_follow_up": "Align page padding with native equipment/requisition pages; mobile overflow was not observed."
+ },
+ "private_build": {
+ "path": "storage/framework/testing/sgc-capital-register-qa-20261127",
+ "manifest_sha256": "baaf8095659bb678e449133dfdd07d1862bb89870f8fbcf44fd2d079474faed1",
+ "passed": true
+ },
+ "preserved": {"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e", "pilot_activated": false, "migration_created": false, "new_financial_or_stock_writer": false, "sgf_dependency": false},
+ "remaining": [
+ "Native receipt-to-asset entry lineage and current correction/return visibility",
+ "Full assignment/account applicability across RQ-01 categories",
+ "Backup/recovery proof for new register and assignments",
+ "Final visual/mobile/print review after remaining implementation",
+ "Other existing matrix gaps and separately scoped operational preparation"
+ ]
+}
diff --git a/docs/proofs/import-bank-support-qa.json b/docs/proofs/import-bank-support-qa.json
new file mode 100644
index 0000000..d1a8bff
--- /dev/null
+++ b/docs/proofs/import-bank-support-qa.json
@@ -0,0 +1,89 @@
+{
+ "date": "2026-11-27",
+ "status": "implemented_in_isolated_qa_not_installed",
+ "scope": "Documentary bank follow-up: existing commitment, DU/customs declaration, requested counts, explicit deadline source, dated delivery evidence, history, alerts and full-scope CSV",
+ "data": "Synthetic fixtures; unknown requirements/dates remain unknown; no presumed legal deadline",
+ "effects": {
+ "bank_transfer": false,
+ "jue_submission": false,
+ "compliance_certification": false,
+ "new_financial_or_stock_writer": false
+ },
+ "sqlite_directed": {
+ "tests": 10,
+ "assertions": 105,
+ "passed": true,
+ "includes_protocol_unit": true
+ },
+ "postgresql_integration": {
+ "tests": 39,
+ "assertions": 324,
+ "passed": true,
+ "database_removed": true
+ },
+ "concurrency": {
+ "same_operation": [
+ 200,
+ 200
+ ],
+ "conflicting_version": [
+ 200,
+ 409
+ ],
+ "blocked_writers_per_scenario": 2,
+ "new_versions_per_scenario": 1,
+ "audits_per_scenario": 1,
+ "new_files_per_scenario": 0,
+ "originals_verified": true,
+ "database_removed": true
+ },
+ "recovery": {
+ "bank_support_versions_restored": 2,
+ "relationships_restored": true,
+ "replay_without_effect": true,
+ "private_original_versions_restored": 10,
+ "typed_dossier_versions_restored": 8,
+ "selected_party_versions_restored": 2,
+ "previous_tables_preserved": 115,
+ "optional_tables": 2,
+ "post_restore_all_sql_equal": true,
+ "pre_extension_restore_passed": true,
+ "separate_private_root_restored": true,
+ "native_authorized_access_verified": true,
+ "databases_removed": true
+ },
+ "frontend": {
+ "files": 40,
+ "tests": 172,
+ "passed": true,
+ "includes_bank_tests": 3
+ },
+ "checks": {
+ "types": "passed",
+ "phpstan": "passed",
+ "scoped_pint": "passed",
+ "scoped_format_and_lint": "passed",
+ "diff_whitespace": "passed"
+ },
+ "private_build": {
+ "directory": "storage/framework/testing/sgc-import-bank-support-qa-20261127",
+ "exit_code": 0,
+ "manifest_sha256": "55f1cd3adf5382bde4fda5ecca99231cbdd1fdd8b07d46dd166d5c2fb4025a72"
+ },
+ "commands": [
+ "php vendor/bin/pest tests/Feature/ImportBankSupportTest.php tests/Unit/LandedQaReceiptsTest.php",
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --bank-support-focused",
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --bank-support-concurrency",
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --bank-support-recovery",
+ "npx.cmd vitest run",
+ "npm.cmd run types:check",
+ "php vendor/bin/phpstan analyse --no-progress",
+ "npm.cmd run build -- --outDir storage/framework/testing/sgc-import-bank-support-qa-20261127"
+ ],
+ "limitations": [
+ "Visual/mobile/print review pending; earlier missing-runtime blocker not retried",
+ "No pilot/operational SGF installation, activation, migration, real data or permission changes",
+ "Versioned legal suggestions and remaining product requirements remain open"
+ ],
+ "execution_note": "PowerShell blocked ps1 npm/npx wrappers; cmd launchers passed without policy changes. Overlapping test counts must not be added."
+}
diff --git a/docs/proofs/import-legal-amounts-qa.json b/docs/proofs/import-legal-amounts-qa.json
new file mode 100644
index 0000000..b27c7e2
--- /dev/null
+++ b/docs/proofs/import-legal-amounts-qa.json
@@ -0,0 +1,140 @@
+{
+ "date": "2026-11-27",
+ "status": "implemented_in_isolated_qa_not_installed_not_product_completion",
+ "scope": [
+ "Explicit versioned charge definitions and MZN bases",
+ "Exact decimal ad-valorem, specific and maximum-of-both estimation",
+ "Unknown rates/bases and unproven non-application remain indeterminate",
+ "Immutable source-linked estimates and deliberate adoption into native import cost preparation",
+ "Explicit budget subtotal/tax split and single-use charge protection",
+ "Future legal periods preserve the earlier applicable publication",
+ "Native lot-availability warnings remain distinct from physical receipt acceptance"
+ ],
+ "data": "Calculation tests use synthetic rates, bases and organizations. Real shared official originals were separately consulted and upload-tested; no real rate rules activated.",
+ "postgresql_money_integration": {
+ "tests": 57,
+ "assertions": 919,
+ "passed": true,
+ "database_removed": true
+ },
+ "sqlite_readiness_delta": {
+ "tests": 5,
+ "assertions": 42,
+ "passed": true
+ },
+ "protocol_unit": {
+ "tests": 9,
+ "assertions": 43,
+ "passed": true
+ },
+ "frontend": {
+ "files": 43,
+ "tests": 180,
+ "passed": true
+ },
+ "checks": {
+ "types": "passed",
+ "phpstan": "passed",
+ "scoped_format_lint": "passed",
+ "scoped_pint": "passed",
+ "diff_whitespace": "passed"
+ },
+ "concurrency": {
+ "same_operation": [
+ 200,
+ 200
+ ],
+ "same_version": [
+ 200,
+ 409
+ ],
+ "blocked_writers": 2,
+ "amount_versions_per_scenario": 1,
+ "audits_per_scenario": 1,
+ "new_files": 0,
+ "originals_verified": true,
+ "database_removed": true
+ },
+ "recovery": {
+ "calculated_amount_minor": 750,
+ "native_goods_minor": 10000,
+ "native_cost_plan_total_minor": 10750,
+ "source_provenance_restored": true,
+ "amount_and_native_plan_replay_without_effects": true,
+ "private_originals": 11,
+ "previous_tables_preserved": 115,
+ "optional_tables": 2,
+ "all_sql_equal": true,
+ "pre_extension_recovery": true,
+ "databases_removed": true
+ },
+ "native_http": {
+ "native_fortify_login": true,
+ "csrf_required": true,
+ "real_shared_pdf_bytes": 15509234,
+ "source_sha256": "8bcb278f77d365804d70a51074400af8ad2cdf6c620e5668c8bbd9b31e0d3fd2",
+ "exact_download_and_original_unchanged": true,
+ "one_source_one_audit_after_replay": true,
+ "guest_status": 401,
+ "revoked_status": 403,
+ "rules_published": 0,
+ "financial_stock_unchanged": true,
+ "private_upload_limit": "64M",
+ "private_post_limit": "70M",
+ "global_php_unchanged": true,
+ "server_stopped": true,
+ "private_root_and_database_removed": true
+ },
+ "private_build": {
+ "directory": "storage/framework/testing/sgc-import-legal-amounts-qa-20261127",
+ "manifest_sha256": "76ce989c99f800d50a877f5eff7b7d22f8ed1bfb7de04dc1b73cba614cfa4984",
+ "passed": true
+ },
+ "corrections": [
+ "PostgreSQL caught a 21-character internal kind exceeding the existing 20-character schema; changed to import_legal_amount without a migration. Native HTTP, source queries and recovery now cover it.",
+ "Non-application needs article-specific documentary grounding rather than becoming zero automatically.",
+ "A future publication no longer suppresses an earlier applicable period; no expired replacement fallback.",
+ "Native HTTP test now follows the actual Inertia bootstrap asset version instead of treating a reload response as JSON."
+ ],
+ "limitations": [
+ "Real exemptions, rates and procedures must remain tied to their actual scope, sources and periods; no blanket claim of complete source parametrization",
+ "The operational PHP upload/post limits still require scoped installation preparation; only private QA limits were exercised",
+ "Browser host remains unavailable, but native Edge was successfully launched for a separate visual review that has not yet been completed",
+ "Other matrix requirements, operational installation and enterprise acceptance remain open"
+ ],
+ "commands": [
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-amounts-focused",
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-amount-concurrency",
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-amount-recovery",
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-http --legal-corpus-root= --legal-http-candidate= --legal-http-manifest="
+ ],
+ "native_visual_delta": {
+ "browser": "Native Microsoft Edge",
+ "viewports_observed_px": [
+ 390,
+ 823
+ ],
+ "legal_page_no_horizontal_overflow_observed": true,
+ "explicit_reuse_preserved_base_minor": 10000,
+ "native_form_saved_new_amount_version": 2,
+ "native_form_calculated_minor": 750,
+ "existing_plan_preserved_selected_estimate_id": 5,
+ "existing_plan_total_minor": 10750,
+ "readiness_expected_unknown_and_bank_deadline_pending_visible": true,
+ "scope_limit": "Not a complete visual acceptance: bank editing, print pagination and remaining product flows remain unverified. Empty required reason was blocked by native form validation; server error rendering was not demonstrated.",
+ "private_server_stopped": true,
+ "private_root_removed": true,
+ "isolated_database_removed": true,
+ "user_tabs_preserved": true
+ },
+ "native_bank_visual_delta": {
+ "native_form_saved_version": 2,
+ "state": "documented",
+ "effective_delivery_on": "2026-11-27",
+ "dated_original_and_basis_preserved": true,
+ "previous_version_preserved": true,
+ "pending_delivery_and_due_today_alerts_removed": true,
+ "isolated_environment_removed": true,
+ "bank_execution": false
+ }
+}
diff --git a/docs/proofs/import-legal-readiness-qa.json b/docs/proofs/import-legal-readiness-qa.json
new file mode 100644
index 0000000..d48013d
--- /dev/null
+++ b/docs/proofs/import-legal-readiness-qa.json
@@ -0,0 +1,131 @@
+{
+ "date": "2026-11-27",
+ "status": "documentary_legal_rules_and_contextual_followup_implemented_in_qa_not_product_completion",
+ "authorization": "Owner requested uninterrupted development to functional completion, preserving separate operational authorization; legislation already shared, located and used",
+ "scope": [
+ "Independent private official-source consultation",
+ "Versioned draft/publication/withdrawal using existing import_customs authority",
+ "Explicit code/origin/sector/date suggestions and native buyer confirmation/deviation",
+ "Frozen source in requisition/new order/print; changed, expired or missing-source warning",
+ "Live logistics, required-document, party, bank and Finance follow-up without notifications"
+ ],
+ "postgresql_integration": {
+ "tests": 36,
+ "assertions": 337,
+ "passed": true,
+ "database_removed": true
+ },
+ "final_legal_sqlite_delta": {
+ "tests": 7,
+ "assertions": 54,
+ "passed": true
+ },
+ "protocol_unit": {
+ "tests": 8,
+ "assertions": 38,
+ "passed": true
+ },
+ "concurrency": {
+ "same_operation": [
+ 200,
+ 200
+ ],
+ "same_version": [
+ 200,
+ 409
+ ],
+ "blocked_writers": 2,
+ "rule_versions_per_scenario": 1,
+ "originals_per_scenario": 1,
+ "audits_per_scenario": 1,
+ "originals_verified": true,
+ "database_removed": true
+ },
+ "recovery": {
+ "legal_source_restored": true,
+ "published_version_restored": true,
+ "buyer_context_restored": true,
+ "replay_without_effect": true,
+ "private_original_versions_restored": 11,
+ "typed_dossier_versions_restored": 8,
+ "previous_tables_preserved": 115,
+ "optional_tables": 2,
+ "all_sql_equal": true,
+ "pre_extension_restore": true,
+ "databases_removed": true
+ },
+ "real_sources": {
+ "corpus_root": "C:/Mac/Home/Documents/TEMPO/Portal Tempo/Legislacao",
+ "files_inventoried_including_hidden": 8109,
+ "inventory_metadata_sha256": "446df82acf6918a1ca792e54baeae2703842a1c6d8922be8d2a4f94598393e9c",
+ "sources": [
+ {
+ "reference": "BR251 29/12/2022, Leis17/2022 e19/2022 integral",
+ "bytes": 15509234,
+ "sha256": "8bcb278f77d365804d70a51074400af8ad2cdf6c620e5668c8bbd9b31e0d3fd2"
+ },
+ {
+ "reference": "BR248 suplemento29/12/2025, Leis7/2025 a12/2025",
+ "bytes": 1002011,
+ "sha256": "a0110696253715567af39c159a21bacfebc32f944fa43a4efd18070d36959e50"
+ },
+ {
+ "reference": "Lei28/2022 Lei Cambial",
+ "bytes": 596387,
+ "sha256": "0dba2775dbede3701b8c1f476e1497c0dc2a481d59e7898013aa992d0a3db896"
+ },
+ {
+ "reference": "BR57 20/03/2024 Aviso3/GBM/2024",
+ "bytes": 758167,
+ "sha256": "e170d541bf2f21f4070a97d8b1b12a35ec8f5d59a28eb17c50597c5d17656db5"
+ }
+ ],
+ "native_read_and_original_hashes_verified": true,
+ "financial_stock_unchanged": true,
+ "rules_published": 0,
+ "synthetic_qa_organization_only": true,
+ "database_removed": true
+ },
+ "frontend": {
+ "files": 42,
+ "tests": 177,
+ "passed": true
+ },
+ "checks": {
+ "types": "passed",
+ "phpstan": "passed",
+ "scoped_format_lint": "passed",
+ "scoped_pint": "passed",
+ "diff_whitespace": "passed"
+ },
+ "private_build": {
+ "directory": "storage/framework/testing/sgc-import-legal-readiness-qa-20261127",
+ "manifest_sha256": "36613eecf708866996ab2febe661ed00b3cd1e1508f97998f3779b56c7834b31",
+ "passed": true
+ },
+ "pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
+ "corrections": [
+ "Replaced transactional2MB limit for official sources with64MB and regression for full legal publications",
+ "Separated source availability from rule publication to avoid artificial classification/rate data",
+ "Publication cannot replace the prepared original; regression rejects a source swap",
+ "Expected receipt warning follows native effective acceptance rather than customs release alone"
+ ],
+ "visual": {
+ "browser_host": "unavailable",
+ "native_browser_inventory": "empty",
+ "review_completed": false,
+ "pdf_source_review": "pypdf extraction and pypdfium2 rendered 2025 amendment pages2-4; page3/4 images inspected; no source modifications"
+ },
+ "limitations": [
+ "Tax estimate calculations and complete source-specific rule parametrization remain open",
+ "Automatic recipients and organizational deadlines are not inferred",
+ "Visual/mobile/print review and other reconciled matrix gaps remain open",
+ "No operational installation/activation, migration or real permissions changed"
+ ],
+ "commands": [
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-focused",
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-concurrency",
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-recovery",
+ "php scripts/quotation-exchange-pg-check.php --import-landed-costs-only --legal-corpus --legal-corpus-root="
+ ]
+}
diff --git a/resources/js/components/capital-assignment-summary.tsx b/resources/js/components/capital-assignment-summary.tsx
new file mode 100644
index 0000000..2b2d86a
--- /dev/null
+++ b/resources/js/components/capital-assignment-summary.tsx
@@ -0,0 +1,54 @@
+import { Panel } from '@/components/procurement';
+
+export type FrozenCapitalAssignment = {
+ id: number;
+ version: number;
+ reason: string;
+ snapshot: {
+ item: { description: string };
+ source: {
+ version: number;
+ data: {
+ type: string;
+ code: string;
+ name: string;
+ reference: string;
+ };
+ };
+ };
+};
+export default function CapitalAssignmentSummary({
+ records,
+}: {
+ records?: Record;
+}) {
+ const rows = Object.values(records ?? {});
+ if (!rows.length) return null;
+ return (
+
+ {rows.map((row) => (
+
+
+ {row.snapshot.item.description}
+
+
+ {row.snapshot.source.data.type === 'project'
+ ? 'Projecto'
+ : 'Imobilizado'}{' '}
+ · {row.snapshot.source.data.code} ·{' '}
+ {row.snapshot.source.data.name} · versão{' '}
+ {row.snapshot.source.version}
+
+ {row.snapshot.source.data.reference}
+ {row.reason}
+
+ ))}
+
+ );
+}
diff --git a/resources/js/components/import-legal-charges.tsx b/resources/js/components/import-legal-charges.tsx
new file mode 100644
index 0000000..615ae1e
--- /dev/null
+++ b/resources/js/components/import-legal-charges.tsx
@@ -0,0 +1,252 @@
+import { controlClass } from '@/components/procurement';
+import { Button } from '@/components/ui/button';
+import { estimateMoney } from '@/lib/import-estimate-money';
+import { money } from '@/types/procurement';
+
+export type LegalCharge = {
+ key: string;
+ kind: string;
+ label: string;
+ method: string;
+ rate_percent: string | null;
+ specific_minor: number | null;
+ quantity_unit: string | null;
+ basis_reference: string;
+};
+export type LegalChargeDraft = {
+ key: string;
+ kind: string;
+ label: string;
+ method: string;
+ rate_percent: string;
+ specific_amount: string;
+ quantity_unit: string;
+ basis_reference: string;
+};
+export const chargeDrafts = (charges: LegalCharge[]) =>
+ charges.map((charge): LegalChargeDraft => ({
+ key: charge.key,
+ kind: charge.kind,
+ label: charge.label,
+ method: charge.method,
+ rate_percent: charge.rate_percent ?? '',
+ specific_amount: estimateMoney(charge.specific_minor),
+ quantity_unit: charge.quantity_unit ?? '',
+ basis_reference: charge.basis_reference,
+ }));
+export function LegalChargeSummary({ charges }: { charges: LegalCharge[] }) {
+ const methods: Record = {
+ unknown: 'Por determinar',
+ not_applicable: 'Não aplicável segundo a fonte',
+ ad_valorem: 'Percentagem sobre base em MZN',
+ specific: 'Montante por unidade',
+ maximum: 'Maior valor entre percentagem e montante por unidade',
+ };
+ if (charges.length === 0)
+ return Imposições ainda por parametrizar nesta regra.
;
+ return (
+
+ {charges.map((charge) => (
+
+ {charge.label}
+ {methods[charge.method]}
+ {charge.rate_percent !== null && (
+ Taxa: {charge.rate_percent}%
+ )}
+ {charge.specific_minor !== null && (
+
+ Taxa específica: {money(charge.specific_minor)} por{' '}
+ {charge.quantity_unit}
+
+ )}
+ Base e condições
+ {charge.basis_reference}
+
+ ))}
+
+ );
+}
+export default function LegalChargeFields({
+ charges,
+ onChange,
+}: {
+ charges: LegalChargeDraft[];
+ onChange: (charges: LegalChargeDraft[]) => void;
+}) {
+ const change = (index: number, values: Partial) =>
+ onChange(
+ charges.map((charge, at) =>
+ at === index ? { ...charge, ...values } : charge,
+ ),
+ );
+ return (
+
+ Imposições documentadas para estimativa
+
+ Sem taxas parametrizadas, os montantes permanecem por
+ determinar. Registe a base legal de cada método; não aplique
+ isenções sem os seus requisitos.
+
+ {charges.map((charge, index) => (
+
+
+ Imposição
+
+ change(index, { kind: e.target.value })
+ }
+ >
+ Direitos aduaneiros
+ ICE
+ IVA da importação
+ Outro encargo
+
+
+
+ Designação
+
+ change(index, { label: e.target.value })
+ }
+ />
+
+
+ Método previsto na fonte
+
+ change(index, {
+ method: e.target.value,
+ rate_percent: '',
+ specific_amount: '',
+ quantity_unit: '',
+ })
+ }
+ >
+ Por determinar
+
+ Não aplicável segundo a fonte
+
+
+ Percentagem sobre base expressa em MZN
+
+
+ Montante em MZN por unidade
+
+
+ Maior valor entre percentagem e taxa por unidade
+
+
+
+ {['ad_valorem', 'maximum'].includes(charge.method) && (
+
+ Taxa percentual
+
+ change(index, {
+ rate_percent: e.target.value,
+ })
+ }
+ />
+
+ )}
+ {['specific', 'maximum'].includes(charge.method) && (
+ <>
+
+ Taxa específica em MZN por unidade
+
+ change(index, {
+ specific_amount: e.target.value,
+ })
+ }
+ />
+
+
+ Unidade da taxa específica
+
+ change(index, {
+ quantity_unit: e.target.value,
+ })
+ }
+ />
+
+ >
+ )}
+
+ Artigo e condições da base de incidência ou da não
+ aplicação
+
+
+ onChange(charges.filter((_, at) => at !== index))
+ }
+ >
+ Retirar desta preparação
+
+
+ ))}
+ = 20}
+ onClick={() =>
+ onChange([
+ ...charges,
+ {
+ key: crypto.randomUUID(),
+ kind: 'duty',
+ label: '',
+ method: 'unknown',
+ rate_percent: '',
+ specific_amount: '',
+ quantity_unit: '',
+ basis_reference: '',
+ },
+ ])
+ }
+ >
+ Acrescentar imposição documentada
+
+
+ );
+}
diff --git a/resources/js/components/import-tariff-summary.tsx b/resources/js/components/import-tariff-summary.tsx
index 8803899..db4442c 100644
--- a/resources/js/components/import-tariff-summary.tsx
+++ b/resources/js/components/import-tariff-summary.tsx
@@ -13,6 +13,16 @@ export type FrozenImportTariff = {
};
confirmed_by: { name: string };
reason: string;
+ legal_rule?: {
+ version: number;
+ data: {
+ official_reference: string;
+ citation: string;
+ obligations: string;
+ document_types: string[];
+ };
+ context: { date: string; origin_country: string; sector: string };
+ } | null;
};
export default function ImportTariffSummary({
records,
@@ -42,6 +52,18 @@ export default function ImportTariffSummary({
Fonte da confirmação
{record.data.confirmation_source}
+ {record.legal_rule && (
+ <>
+ Regra legal aplicada
+
+ {record.legal_rule.data.official_reference}{' '}
+ · {record.legal_rule.data.citation} · versão{' '}
+ {record.legal_rule.version}
+
+ Condições preservadas
+ {record.legal_rule.data.obligations}
+ >
+ )}
{record.data.deviation
? 'Justificação do desvio'
diff --git a/resources/js/lib/journey-help.ts b/resources/js/lib/journey-help.ts
index 33665bd..2f7958e 100644
--- a/resources/js/lib/journey-help.ts
+++ b/resources/js/lib/journey-help.ts
@@ -37,6 +37,61 @@ function topic(
}
export const journeyHelp: JourneyHelp[] = [
+ topic(
+ 'import-readiness',
+ 'Acompanhar pendências da importação',
+ ['supply/import-readiness'],
+ 'Reunir os alertas factuais da ordem e abrir o percurso que permite resolver cada pendência.',
+ [
+ 'Confira a previsão de recepção utilizável com os marcos logísticos e as quantidades efectivamente aceites.',
+ 'Consulte originais em falta ou alterados e os documentos indicados nas fontes legais preservadas.',
+ 'Reveja alterações de fontes, intervenientes, instruções e suporte bancário nos respectivos percursos.',
+ 'Finanças consulta as preparações de custo pendentes no circuito financeiro existente.',
+ ],
+ [
+ 'Informação desconhecida permanece por determinar e verificações indisponíveis são identificadas.',
+ 'A consulta não concede competências, não envia notificações e não certifica cumprimento ou pagamentos.',
+ ],
+ 'Se a importação mudou, abra a versão actual e volte a conferir as pendências; os originais e decisões anteriores permanecem preservados.',
+ 'Abra o percurso relacionado com a pendência e regresse para consultar a situação actualizada.',
+ ),
+ topic(
+ 'import-legal',
+ 'Consultar e manter a base legal de importação',
+ ['supply/import-legal'],
+ 'Consultar fontes aplicáveis ao código, origem, sector e período e preparar a classificação do artigo.',
+ [
+ 'Indique o contexto e a data. Sem correspondência publicada, a regra permanece por determinar.',
+ 'Seleccione o artigo e prepare uma proposta com a fonte escolhida; confirme ou justifique o desvio na classificação pautal.',
+ 'A área aduaneira conserva exemplar, diploma, citação e vigência antes de validar e publicar a preparação.',
+ 'Uma revisão conserva a publicação anterior até nova validação. A retirada impede novas sugestões.',
+ ],
+ [
+ 'Publicar uma fonte não activa cálculos, isenções, pagamentos ou submissões JUE.',
+ 'Uma mudança da regra sinaliza a decisão anterior, conservando a fonte e o histórico aplicados.',
+ ],
+ 'Se a regra mudou ou o exemplar divergiu, preserve a preparação e seleccione uma fonte actual antes da confirmação.',
+ 'Regresse à classificação pautal para confirmar a proposta ou justificar o desvio.',
+ ),
+ topic(
+ 'import-bank-support',
+ 'Acompanhar o suporte documental bancário',
+ ['supply/import-bank-support'],
+ 'Associar o termo de compromisso ao documento único, reunir os suportes solicitados e conservar o comprovativo de entrega ao banco.',
+ [
+ 'Seleccione os originais já registados no dossiê; não reintroduza referências ou entidades emitentes.',
+ 'Identifique os tipos e quantidades pedidos pelo banco, com a fonte dos requisitos.',
+ 'Indique apenas um prazo documentado e a sua fonte; informação desconhecida permanece por indicar.',
+ 'Reunir documentos não demonstra entrega. Seleccione o comprovativo de entrega quando estiver disponível.',
+ 'Corrija por nova versão e consulte os alertas, o histórico e o CSV do âmbito completo.',
+ ],
+ [
+ 'A correcção ou perda de um original reabre o alerta; o registo anterior não é apagado.',
+ 'O acompanhamento não executa transferências ou submissões na JUE e não certifica cumprimento bancário.',
+ ],
+ 'Conserve a preparação se a versão mudou. Seleccione explicitamente os novos originais e explique a correcção.',
+ 'Consulte os prazos e documentos em falta e prossiga no percurso próprio da importação.',
+ ),
topic(
'import-estimate',
'Preparar o custo estimado da importação',
diff --git a/resources/js/pages/equipment/capital-register.tsx b/resources/js/pages/equipment/capital-register.tsx
new file mode 100644
index 0000000..37112b2
--- /dev/null
+++ b/resources/js/pages/equipment/capital-register.tsx
@@ -0,0 +1,412 @@
+import { Head, Link, useForm } from '@inertiajs/react';
+import { useEffect, useRef } from 'react';
+import {
+ FormErrors,
+ PageTitle,
+ Panel,
+ controlClass,
+} from '@/components/procurement';
+import { Button } from '@/components/ui/button';
+
+type Data = {
+ type: string;
+ code: string;
+ name: string;
+ department_id: number;
+ equipment_id: number | null;
+ reference: string;
+};
+type Record = {
+ id: number;
+ record_key: string;
+ version: number;
+ state: string;
+ data: Data;
+ reason: string;
+};
+type Props = {
+ trace?: {
+ orders: { data: { id: number; description: string; quantity: string; unit: string; order_id: number; order_number: string }[]; prev_page_url: string | null; next_page_url: string | null };
+ receipts: { data: { id: number; description: string | null; unit: string | null; receipt_id: number; order_id: number | null; received_on: string | null; quality_status: string; accepted_quantity: string; reversed: boolean; returned_quantity: string }[]; prev_page_url: string | null; next_page_url: string | null };
+ } | null;
+ history: {
+ data: Record[];
+ prev_page_url: string | null;
+ next_page_url: string | null;
+ } | null;
+ records: {
+ data: Record[];
+ prev_page_url: string | null;
+ next_page_url: string | null;
+ };
+ departments: { id: number; name: string }[];
+ equipment: {
+ id: number;
+ code: string;
+ description: string;
+ department_id: number;
+ }[];
+ canManage: boolean;
+ actorId: number;
+ tenantId: number;
+};
+export default function CapitalRegister(props: Props) {
+ const url = '/projectos-imobilizado';
+ const form = useForm(
+ `capital-register:${props.tenantId}:${props.actorId}`,
+ {
+ operation_key: '',
+ record_key: null as string | null,
+ version: 0,
+ type: 'project',
+ code: '',
+ name: '',
+ department_id: '',
+ equipment_id: '',
+ reference: '',
+ state: 'active',
+ reason: '',
+ },
+ );
+ const ref = useRef(null);
+ useEffect(() => {
+ const node = ref.current;
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: node, dirty: form.isDirty },
+ }),
+ );
+ return () => {
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: node, dirty: false },
+ }),
+ );
+ };
+ }, [form.isDirty]);
+ const edit = (record: Record) =>
+ form.setData({
+ ...record.data,
+ operation_key: '',
+ record_key: record.record_key,
+ version: record.version,
+ department_id: String(record.data.department_id),
+ equipment_id:
+ record.data.equipment_id === null
+ ? ''
+ : String(record.data.equipment_id),
+ state: record.state,
+ reason: '',
+ });
+ return (
+
+
+
+
+ Consultar equipamentos e peças
+
+
+ {props.records.data.length === 0 && (
+ Ainda não há registos neste âmbito.
+ )}
+ {props.records.data.map((record) => (
+
+
+ {record.data.code} · {record.data.name}
+
+
+ {record.data.type === 'project'
+ ? 'Projecto'
+ : 'Imobilizado'}{' '}
+ ·{' '}
+ {record.state === 'active' ? 'Activo' : 'Arquivado'}{' '}
+ · versão {record.version}
+
+ {record.data.reference}
+ {record.reason}
+
+ Consultar versões e origens
+
+ {props.canManage && (
+ edit(record)}
+ >
+ Preparar nova versão
+
+ )}
+
+ ))}
+
+ {props.records.prev_page_url && (
+
+ Anterior
+
+ )}
+ {props.records.next_page_url && (
+
+ Seguinte
+
+ )}
+
+
+ {props.history && (
+
+ {props.history.data.map((record) => (
+
+
+ {record.data.code} · versão {record.version}
+
+
+ {record.data.name} ·{' '}
+ {record.state === 'active'
+ ? 'Activo'
+ : 'Arquivado'}
+
+ {record.data.reference}
+ {record.reason}
+
+ ))}
+
+ {props.history.prev_page_url && (
+
+ Anterior
+
+ )}
+ {props.history.next_page_url && (
+
+ Seguinte
+
+ )}
+
+
+ )}
+ {props.trace &&
+ {props.trace.orders.data.length === 0 && Ainda não há ordens visíveis com esta referência preservada.
}
+ {props.trace.orders.data.map(line => {line.order_number}{line.description} · {line.quantity} {line.unit}
)}
+ {props.trace.orders.prev_page_url && Anterior}{props.trace.orders.next_page_url && Seguinte}
+ }
+ {props.trace &&
+ {props.trace.receipts.data.length === 0 && Ainda não há recepções visíveis nestas origens.
}
+ {props.trace.receipts.data.map(receipt => Recepção #{receipt.receipt_id} · {receipt.description || 'Descrição por conferir'} Data: {receipt.received_on || 'Por conferir'} · Aceite no original: {receipt.accepted_quantity} {receipt.unit || ''}
Qualidade registada: {receipt.quality_status === 'compliant' ? 'Conforme' : receipt.quality_status === 'quarantined' ? 'Em quarentena' : 'Com divergência'}
{receipt.reversed && Recepção estornada; o original permanece no histórico.
}{receipt.returned_quantity !== '0.000' && Devolução ao fornecedor: {receipt.returned_quantity} {receipt.unit || ''}
}{receipt.order_id && Conferir documentos e movimentos da ordem} )}
+ {props.trace.receipts.prev_page_url && Anterior}{props.trace.receipts.next_page_url && Seguinte}
+ }
+ {props.canManage && (
+
+
+
+ )}
+
+ );
+}
diff --git a/resources/js/pages/equipment/index.tsx b/resources/js/pages/equipment/index.tsx
index 3ef7f28..6e293f4 100644
--- a/resources/js/pages/equipment/index.tsx
+++ b/resources/js/pages/equipment/index.tsx
@@ -64,6 +64,7 @@ type History = {
};
};
type Props = {
+ capitalRegisterReady?: boolean;
geographyEnabled?: boolean;
equipmentGeography?: Record;
geographyFilter?: GeographyDescription;
@@ -107,6 +108,7 @@ export default function EquipmentPage({
history,
canManage,
canConfigure,
+ capitalRegisterReady = false,
demo = false,
geographyEnabled = false,
equipmentGeography = {},
@@ -157,6 +159,11 @@ export default function EquipmentPage({
description="Cadastro, peças compatíveis, mínimos explícitos e rastreabilidade das saídas."
/>
+ {capitalRegisterReady && (
+
+ Projectos e imobilizado
+
+ )}
{geographyEnabled && !demo && (
)}
+
{snapshot.investment_rules && (
diff --git a/resources/js/pages/requisitions/capital-assignments.tsx b/resources/js/pages/requisitions/capital-assignments.tsx
new file mode 100644
index 0000000..86f0139
--- /dev/null
+++ b/resources/js/pages/requisitions/capital-assignments.tsx
@@ -0,0 +1,306 @@
+import { Head, Link, useForm } from '@inertiajs/react';
+import { useEffect, useRef } from 'react';
+import {
+ FormErrors,
+ PageTitle,
+ Panel,
+ controlClass,
+} from '@/components/procurement';
+import { Button } from '@/components/ui/button';
+
+type Source = {
+ id: number;
+ version: number;
+ data: { code: string; name: string; type: string; reference: string };
+};
+type Assignment = {
+ id: number;
+ version: number;
+ state: string;
+ reason: string;
+ data: { requisition_item_id: number };
+ snapshot: { item: { description: string }; source: Source | null };
+};
+type Page = {
+ data: T[];
+ prev_page_url: string | null;
+ next_page_url: string | null;
+};
+type Props = {
+ requisition: { id: number; number: string; status: string };
+ items: { id: number; description: string }[];
+ current: Assignment[];
+ history: Page;
+ choices: Page;
+ canWrite: boolean;
+ actorId: number;
+ tenantId: number;
+};
+export default function CapitalAssignments(props: Props) {
+ const url = `/requisicoes/${props.requisition.id}/projectos-imobilizado`;
+ const form = useForm(
+ `capital-assignment:${props.tenantId}:${props.actorId}:${props.requisition.id}`,
+ {
+ operation_key: '',
+ item_id: '',
+ version: 0,
+ capital_id: '',
+ capital_label: '',
+ reason: '',
+ },
+ );
+ const ref = useRef(null);
+ useEffect(() => {
+ const node = ref.current;
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: node, dirty: form.isDirty },
+ }),
+ );
+ return () => {
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: node, dirty: false },
+ }),
+ );
+ };
+ }, [form.isDirty]);
+ const chooseItem = (id: string) => {
+ const old = props.current.find(
+ (row) => String(row.data.requisition_item_id) === id,
+ );
+ const source = old?.snapshot.source;
+ form.setData({
+ operation_key: '',
+ item_id: id,
+ version: old?.version ?? 0,
+ capital_id: source ? String(source.id) : '',
+ capital_label: source
+ ? `${source.data.code} · ${source.data.name} · v${source.version}`
+ : '',
+ reason: '',
+ });
+ };
+ return (
+
+
+
+
+ Voltar à requisição
+
+
+ {props.current.length === 0 && (
+
+ Ainda não há ligações registadas. As origens anteriores
+ permanecem preservadas.
+
+ )}
+ {props.current.map((row) => (
+
+
+ {row.snapshot.item.description} · versão{' '}
+ {row.version}
+
+
+ {row.state === 'cleared'
+ ? 'Ligação retirada explicitamente'
+ : `${row.snapshot.source?.data.code} · ${row.snapshot.source?.data.name} · versão ${row.snapshot.source?.version}`}
+
+ {row.reason}
+
+ ))}
+
+ {props.canWrite && (
+
+ {
+ event.preventDefault();
+ const operation =
+ form.data.operation_key || crypto.randomUUID();
+ form.setData('operation_key', operation);
+ form.transform((data) => ({
+ operation_key: operation,
+ item_id: data.item_id,
+ version: data.version,
+ capital_id: data.capital_id || null,
+ reason: data.reason,
+ }));
+ form.post(url, {
+ preserveScroll: true,
+ onSuccess: () => {
+ form.reset();
+ form.clearErrors();
+ },
+ });
+ }}
+ >
+
+
+ Artigo
+
+ chooseItem(event.target.value)
+ }
+ >
+ Seleccione
+ {props.items.map((item) => (
+
+ {item.description}
+
+ ))}
+
+
+
+ Referência seleccionada:{' '}
+ {form.data.capital_label || 'Sem ligação'} · versão
+ da preparação {form.data.version}
+
+
+ Reveja o artigo actual antes de guardar. Uma
+ referência arquivada conserva-se no histórico e nas
+ escolhas já aceites; para uma nova ligação, escolha
+ uma versão activa.
+
+ {props.choices.data.map((source) => (
+
+
+ {source.data.type === 'project'
+ ? 'Projecto'
+ : 'Imobilizado'}{' '}
+ · {source.data.code} · {source.data.name} ·
+ versão {source.version}
+
+ {source.data.reference}
+
+ form.setData((data) => ({
+ ...data,
+ capital_id: String(source.id),
+ capital_label: `${source.data.code} · ${source.data.name} · v${source.version}`,
+ operation_key: '',
+ }))
+ }
+ >
+ Escolher {source.data.code}
+
+
+ ))}
+ {props.choices.data.length === 0 && (
+
+ Não há referências activas no departamento desta
+ requisição.
+
+ )}
+
+ {props.choices.prev_page_url && (
+
+ Anterior
+
+ )}
+ {props.choices.next_page_url && (
+
+ Seguinte
+
+ )}
+
+
+ form.setData((data) => ({
+ ...data,
+ capital_id: '',
+ capital_label: '',
+ operation_key: '',
+ }))
+ }
+ >
+ Retirar ligação desta preparação
+
+
+ Motivo
+
+ form.setData('reason', e.target.value)
+ }
+ />
+
+
+ Guardar ligação
+
+
+
+ )}
+
+ {props.history.data.map((row) => (
+
+
+ {row.snapshot.item.description} · versão{' '}
+ {row.version} ·{' '}
+ {row.snapshot.source
+ ? `${row.snapshot.source.data.code} · v${row.snapshot.source.version}`
+ : 'Sem ligação'}
+
+ {row.reason}
+
+ ))}
+
+ {props.history.prev_page_url && (
+
+ Anterior
+
+ )}
+ {props.history.next_page_url && (
+
+ Seguinte
+
+ )}
+
+
+
+ );
+}
diff --git a/resources/js/pages/requisitions/show.tsx b/resources/js/pages/requisitions/show.tsx
index 2ada9c2..3a9eac0 100644
--- a/resources/js/pages/requisitions/show.tsx
+++ b/resources/js/pages/requisitions/show.tsx
@@ -55,8 +55,10 @@ export default function Show({
canPrepareDistributions = false,
importTariffsReady = false,
importEstimatesReady = false,
+ capitalRegisterReady = false,
}: {
importEstimatesReady?: boolean;
+ capitalRegisterReady?: boolean;
importTariffsReady?: boolean;
canPrepareDistributions?: boolean;
requisition: Requisition;
@@ -165,6 +167,15 @@ export default function Show({
}
/>
+ {capitalRegisterReady && (
+
+
+ Ligar artigos a projecto ou imobilizado
+
+
+ )}
{importEstimatesReady && (
;
+ requirements_basis: string;
+ due_on: string | null;
+ deadline_basis: string | null;
+ };
+};
+type Page = {
+ data: T[];
+ prev_page_url: string | null;
+ next_page_url: string | null;
+};
+type Props = {
+ importRecord: { id: number; record_key: string; version: number };
+ order: { id: number; number: string };
+ current: Page;
+ history: Page;
+ documents: Page;
+ types: Record;
+ canWrite: boolean;
+ actorId: number;
+ tenantId: number;
+ today?: string;
+};
+const stateLabels: Record = {
+ tracking: 'Documentação incompleta',
+ ready: 'Documentos reunidos; entrega por documentar',
+ documented: 'Comprovativo de entrega associado',
+};
+function Pages({ page }: { page: Page }) {
+ return (
+
+ {page.prev_page_url && (
+
+ Anterior
+
+ )}
+ {page.next_page_url && (
+
+ Seguinte
+
+ )}
+
+ );
+}
+export default function ImportBankSupport(props: Props) {
+ const url = `/compras/importacoes/${props.importRecord.id}/suporte-bancario`;
+ const form = useForm(
+ `import-bank:${props.tenantId}:${props.actorId}:${props.importRecord.record_key}:${props.importRecord.version}`,
+ {
+ operation_key: '',
+ record_key: null as string | null,
+ version: 0,
+ commitment_document_id: '',
+ commitment_label: '',
+ declaration_document_id: '',
+ declaration_label: '',
+ support: [] as { id: number; reference: string }[],
+ submission_document_id: '',
+ submission_label: '',
+ submission_basis: '',
+ submitted_on: '',
+ requirements_known: false,
+ counts: {} as Record,
+ requirements_basis: '',
+ due_on: '',
+ deadline_basis: '',
+ reason: '',
+ },
+ );
+ const ref = useRef(null);
+ useEffect(() => {
+ const node = ref.current;
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: node, dirty: form.isDirty },
+ }),
+ );
+ return () => {
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: node, dirty: false },
+ }),
+ );
+ };
+ }, [form.isDirty]);
+ const edit = (record: BankRecord) => {
+ const label = (id: number | null) =>
+ record.snapshot.documents.find((doc) => doc.id === id)?.reference ??
+ '';
+ form.setData({
+ operation_key: '',
+ record_key: record.record_key,
+ version: record.version,
+ commitment_document_id: String(record.data.commitment_document_id),
+ commitment_label: label(record.data.commitment_document_id),
+ declaration_document_id:
+ record.data.declaration_document_id === null
+ ? ''
+ : String(record.data.declaration_document_id),
+ declaration_label: label(record.data.declaration_document_id),
+ support: record.data.support_document_ids.map((id) => ({
+ id,
+ reference: label(id),
+ })),
+ submission_document_id:
+ record.data.submission_document_id === null
+ ? ''
+ : String(record.data.submission_document_id),
+ submission_label: label(record.data.submission_document_id),
+ submission_basis: record.data.submission_basis ?? '',
+ submitted_on: record.data.submitted_on ?? '',
+ requirements_known: record.data.requirements_known,
+ counts: Object.fromEntries(
+ Object.entries(record.data.required_support_counts).map(
+ ([type, count]) => [type, String(count)],
+ ),
+ ),
+ requirements_basis: record.data.requirements_basis,
+ due_on: record.data.due_on ?? '',
+ deadline_basis: record.data.deadline_basis ?? '',
+ reason: '',
+ });
+ form.clearErrors();
+ };
+ return (
+ <>
+
+
+
+
+
+ {props.current.data.length === 0 && (
+ Ainda não há termos acompanhados neste âmbito.
+ )}
+ {props.current.data.map((record) => (
+
+
+ {
+ record.snapshot.documents.find(
+ (doc) =>
+ doc.id ===
+ record.data.commitment_document_id,
+ )?.reference
+ }{' '}
+ · versão {record.version}
+
+ {stateLabels[record.state] ?? record.state}
+
+ Prazo:{' '}
+ {record.data.due_on
+ ? date(record.data.due_on)
+ : 'Por indicar'}{' '}
+ ·{' '}
+ {record.data.deadline_basis ??
+ 'Sem prazo presumido'}
+
+ {(record.issues ?? []).map((issue) => (
+
+ {issue}
+
+ ))}
+
+ Entrega documentada:{' '}
+ {record.data.submitted_on
+ ? date(record.data.submitted_on)
+ : 'Por indicar'}{' '}
+ · {record.data.submission_basis}
+
+ {record.reason}
+ {props.canWrite && (
+ edit(record)}
+ >
+ Preparar nova versão
+
+ )}
+
+ ))}
+
+
+ {props.canWrite && (
+
+ {
+ event.preventDefault();
+ const operation =
+ form.data.operation_key ||
+ crypto.randomUUID();
+ form.setData('operation_key', operation);
+ form.transform((data) => ({
+ operation_key: operation,
+ record_key: data.record_key,
+ version: data.version,
+ commitment_document_id:
+ data.commitment_document_id,
+ declaration_document_id:
+ data.declaration_document_id || null,
+ support_document_ids: data.support.map(
+ (doc) => doc.id,
+ ),
+ submission_document_id:
+ data.submission_document_id || null,
+ submission_basis:
+ data.submission_basis || null,
+ submitted_on: data.submission_document_id
+ ? data.submitted_on || null
+ : null,
+ requirements_known: data.requirements_known,
+ required_support_types:
+ data.requirements_known
+ ? Object.keys(data.counts)
+ : [],
+ required_support_counts:
+ data.requirements_known
+ ? data.counts
+ : {},
+ requirements_basis: data.requirements_basis,
+ due_on: data.due_on || null,
+ deadline_basis: data.deadline_basis || null,
+ reason: data.reason,
+ }));
+ form.post(url, {
+ preserveScroll: true,
+ onSuccess: () => {
+ form.reset();
+ router.visit(url, {
+ preserveState: false,
+ preserveScroll: true,
+ });
+ },
+ });
+ }}
+ >
+
+
+
+ Termo de compromisso
+ {
+ const doc =
+ props.documents.data.find(
+ (d) =>
+ String(d.id) ===
+ e.target.value,
+ );
+ form.setData((data) => ({
+ ...data,
+ commitment_document_id:
+ e.target.value,
+ commitment_label:
+ doc?.data.reference ?? '',
+ }));
+ }}
+ >
+ Seleccione
+ {form.data.commitment_document_id &&
+ !props.documents.data.some(
+ (doc) =>
+ String(doc.id) ===
+ form.data
+ .commitment_document_id,
+ ) && (
+
+ {form.data.commitment_label}{' '}
+ · seleccionado noutra página
+
+ )}
+ {props.documents.data
+ .filter(
+ (doc) =>
+ doc.data.type ===
+ 'bank_commitment',
+ )
+ .map((doc) => (
+
+ {doc.data.reference} · v
+ {doc.version}
+
+ ))}
+
+
+
+ Documento único / declaração
+ {
+ const doc =
+ props.documents.data.find(
+ (d) =>
+ String(d.id) ===
+ e.target.value,
+ );
+ form.setData((data) => ({
+ ...data,
+ declaration_document_id:
+ e.target.value,
+ declaration_label:
+ doc?.data.reference ?? '',
+ }));
+ }}
+ >
+
+ Ainda por associar
+
+ {form.data.declaration_document_id &&
+ !props.documents.data.some(
+ (doc) =>
+ String(doc.id) ===
+ form.data
+ .declaration_document_id,
+ ) && (
+
+ {
+ form.data
+ .declaration_label
+ }{' '}
+ · seleccionado noutra página
+
+ )}
+ {props.documents.data
+ .filter(
+ (doc) =>
+ doc.data.type ===
+ 'customs_declaration',
+ )
+ .map((doc) => (
+
+ {doc.data.reference} · v
+ {doc.version}
+
+ ))}
+
+
+
+ Comprovativo de entrega ao banco
+ {
+ const doc =
+ props.documents.data.find(
+ (d) =>
+ String(d.id) ===
+ e.target.value,
+ );
+ form.setData((data) => ({
+ ...data,
+ submission_document_id:
+ e.target.value,
+ submission_label:
+ doc?.data.reference ?? '',
+ }));
+ }}
+ >
+
+ Ainda por associar
+
+ {form.data.submission_document_id &&
+ !props.documents.data.some(
+ (doc) =>
+ String(doc.id) ===
+ form.data
+ .submission_document_id,
+ ) && (
+
+ {form.data.submission_label}{' '}
+ · seleccionado noutra página
+
+ )}
+ {props.documents.data
+ .filter(
+ (doc) =>
+ doc.data.type ===
+ 'bank_support',
+ )
+ .map((doc) => (
+
+ {doc.data.reference} · v
+ {doc.version}
+
+ ))}
+
+
+
+ {form.data.submission_document_id && (
+
+ Fundamento do comprovativo de entrega
+
+ form.setData(
+ 'submission_basis',
+ e.target.value,
+ )
+ }
+ />
+
+ )}
+ {form.data.submission_document_id && (
+
+ Data efectiva da entrega documentada
+
+ form.setData(
+ 'submitted_on',
+ event.target.value,
+ )
+ }
+ />
+
+ )}
+
+
+ Documentos de suporte seleccionados
+
+ {form.data.support.map((doc) => (
+
+ {doc.reference}
+
+ form.setData(
+ 'support',
+ form.data.support.filter(
+ (d) => d.id !== doc.id,
+ ),
+ )
+ }
+ >
+ Retirar da preparação
+
+
+ ))}
+ {props.documents.data
+ .filter(
+ (doc) =>
+ doc.data.type !== 'bank_commitment',
+ )
+ .map((doc) => (
+
+
+ selected.id === doc.id,
+ )}
+ onChange={(e) =>
+ form.setData(
+ 'support',
+ e.target.checked
+ ? [
+ ...form.data
+ .support,
+ {
+ id: doc.id,
+ reference:
+ doc
+ .data
+ .reference,
+ },
+ ]
+ : form.data.support.filter(
+ (d) =>
+ d.id !==
+ doc.id,
+ ),
+ )
+ }
+ />
+
+ {props.types[doc.data.type]} ·{' '}
+ {doc.data.reference} · v
+ {doc.version}
+
+
+ ))}
+
+
+
+
+ form.setData(
+ 'requirements_known',
+ e.target.checked,
+ )
+ }
+ />
+ Os requisitos documentais pedidos pelo banco
+ estão identificados
+
+ {form.data.requirements_known && (
+
+
+ Tipos e quantidades pedidos pelo banco
+
+ {Object.entries(props.types)
+ .filter(
+ ([type]) =>
+ type !== 'bank_commitment',
+ )
+ .map(([type, label]) => (
+
+
+ {
+ const counts = {
+ ...form.data
+ .counts,
+ };
+ if (
+ e.target.checked
+ )
+ counts[type] =
+ '';
+ else
+ delete counts[
+ type
+ ];
+ form.setData(
+ 'counts',
+ counts,
+ );
+ }}
+ />
+ {label}
+
+ {Object.hasOwn(
+ form.data.counts,
+ type,
+ ) && (
+
+ Quantidade solicitada
+
+ form.setData(
+ 'counts',
+ {
+ ...form
+ .data
+ .counts,
+ [type]: e
+ .target
+ .value,
+ },
+ )
+ }
+ />
+
+ )}
+
+ ))}
+
+ )}
+
+ Fonte dos requisitos ou informação ainda em
+ falta
+
+ form.setData(
+ 'requirements_basis',
+ e.target.value,
+ )
+ }
+ />
+
+
+
+ Prazo documental indicado
+
+ form.setData(
+ 'due_on',
+ e.target.value,
+ )
+ }
+ />
+
+
+ Fonte do prazo
+
+ form.setData(
+ 'deadline_basis',
+ e.target.value,
+ )
+ }
+ />
+
+
+
+ Motivo desta versão
+
+ form.setData('reason', e.target.value)
+ }
+ />
+
+
+ Guardar acompanhamento documental
+
+
+
+ )}
+
+ {props.history.data.map((record) => (
+
+
+ Versão {record.version} ·{' '}
+ {stateLabels[record.state] ?? record.state}
+
+ {record.reason}
+
+ Requisitos:{' '}
+ {record.data.requirements_known
+ ? record.data.required_support_types
+ .map(
+ (type) =>
+ `${props.types[type]}: ${record.data.required_support_counts[type]}`,
+ )
+ .join('; ') ||
+ 'Nenhum tipo exigido segundo a fonte registada'
+ : 'Ainda desconhecidos'}{' '}
+ · {record.data.requirements_basis}
+
+
+ Entrega documentada:{' '}
+ {record.data.submitted_on
+ ? date(record.data.submitted_on)
+ : 'Por indicar'}{' '}
+ · {record.data.submission_basis}
+
+
+ Prazo:{' '}
+ {record.data.due_on
+ ? date(record.data.due_on)
+ : 'Desconhecido'}{' '}
+ · {record.data.deadline_basis}
+
+ {record.snapshot.documents.map((doc) => (
+
+
+ {props.types[doc.type]} ·{' '}
+ {doc.reference} · v{doc.version}
+
+
+ ))}
+
+ ))}
+
+
+
+ >
+ );
+}
diff --git a/resources/js/pages/supply/import-dossier.tsx b/resources/js/pages/supply/import-dossier.tsx
index 33a2551..b72f201 100644
--- a/resources/js/pages/supply/import-dossier.tsx
+++ b/resources/js/pages/supply/import-dossier.tsx
@@ -38,6 +38,8 @@ type Props = {
actorId: number;
tenantId: number;
parties?: ImportPartyWorkspace;
+ bankSupportReady?: boolean;
+ readinessReady?: boolean;
};
export default function Dossier({
@@ -49,6 +51,8 @@ export default function Dossier({
actorId,
tenantId,
parties,
+ bankSupportReady = false,
+ readinessReady = false,
}: Props) {
const form = useForm(
`import-dossier:${tenantId}:${actorId}:${importRecord.record_key}:${importRecord.version}`,
@@ -116,6 +120,22 @@ export default function Dossier({
Consultar a ordem e as suas origens
+ {readinessReady && (
+
+ Consultar alertas e próximos passos
+
+ )}
+ {bankSupportReady && (
+
+ Acompanhar termo e suporte bancário
+
+ )}
{parties && (
;
plan: {
complete: boolean;
budget_amount_minor: number | null;
@@ -47,6 +55,23 @@ type Page = {
next_page_url: string | null;
};
type Props = {
+ legalAmounts?: {
+ id: number;
+ version: number;
+ snapshot: {
+ item: { description: string };
+ legal_rule: { data: { official_reference: string } };
+ result: {
+ lines: {
+ key: string;
+ kind: string;
+ label: string;
+ method: string;
+ amount_minor: number | null;
+ }[];
+ };
+ };
+ }[];
requisition: {
id: number;
number: string;
@@ -105,6 +130,12 @@ export default function ImportEstimate(props: Props) {
subtotal: estimateMoney(row.subtotal_minor),
tax: estimateMoney(row.tax_minor),
total: estimateMoney(row.total_minor),
+ legal_estimate_id:
+ latest?.snapshot.legal_sources?.[row.key]?.estimate_id ??
+ (null as number | null),
+ legal_charge_key:
+ latest?.snapshot.legal_sources?.[row.key]?.charge_key ??
+ (null as string | null),
})),
},
);
@@ -185,6 +216,25 @@ export default function ImportEstimate(props: Props) {
form.setData('operation_key', operation);
form.transform((data) => ({
...data,
+ legal_sources: Object.fromEntries(
+ data.components
+ .filter(
+ (row) =>
+ row.legal_estimate_id !==
+ null &&
+ row.legal_charge_key !==
+ null,
+ )
+ .map((row) => [
+ row.key,
+ {
+ estimate_id:
+ row.legal_estimate_id,
+ charge_key:
+ row.legal_charge_key,
+ },
+ ]),
+ ),
operation_key: operation,
components: data.components.map((row) => ({
key: row.key,
@@ -260,6 +310,174 @@ export default function ImportEstimate(props: Props) {
{labels[row.kind] ?? row.kind}
+ {((props.legalAmounts?.length ?? 0) > 0 ||
+ row.legal_estimate_id !== null) && (
+
+ Reutilizar uma imposição calculada
+ {
+ const candidates = (
+ props.legalAmounts ?? []
+ ).flatMap((estimate) =>
+ estimate.snapshot.result.lines
+ .filter(
+ (line) =>
+ line.kind ===
+ row.kind,
+ )
+ .map((line) => ({
+ estimate,
+ line,
+ value: `${estimate.id}:${line.key}`,
+ })),
+ );
+ const selected =
+ candidates.find(
+ (candidate) =>
+ candidate.value ===
+ event.target
+ .value,
+ );
+ form.setData(
+ 'components',
+ form.data.components.map(
+ (component, at) =>
+ at !== index
+ ? component
+ : selected
+ ? {
+ ...component,
+ legal_estimate_id:
+ selected
+ .estimate
+ .id,
+ legal_charge_key:
+ selected
+ .line
+ .key,
+ status:
+ selected
+ .line
+ .amount_minor ===
+ null
+ ? 'unknown'
+ : selected
+ .line
+ .method ===
+ 'not_applicable'
+ ? 'not_applicable'
+ : 'known',
+ basis: `Estimativa legal #${selected.estimate.id}, versão ${selected.estimate.version}; ${selected.line.label}. Fonte: ${selected.estimate.snapshot.legal_rule.data.official_reference}.`,
+ total: estimateMoney(
+ selected
+ .line
+ .amount_minor,
+ ),
+ subtotal:
+ selected
+ .line
+ .amount_minor ===
+ 0
+ ? '0.00'
+ : '',
+ tax:
+ selected
+ .line
+ .amount_minor ===
+ 0
+ ? '0.00'
+ : '',
+ }
+ : {
+ ...component,
+ legal_estimate_id:
+ null,
+ legal_charge_key:
+ null,
+ },
+ ),
+ );
+ }}
+ >
+
+ Pressuposto manual / retirar
+ ligação e conservar os
+ valores
+
+ {row.legal_estimate_id !==
+ null &&
+ !(
+ props.legalAmounts ?? []
+ ).some(
+ (estimate) =>
+ estimate.id ===
+ row.legal_estimate_id,
+ ) && (
+
+ Versão preservada da
+ estimativa #
+ {
+ row.legal_estimate_id
+ }
+
+ )}
+ {(
+ props.legalAmounts ?? []
+ ).flatMap((estimate) =>
+ estimate.snapshot.result.lines
+ .filter(
+ (line) =>
+ line.kind ===
+ row.kind,
+ )
+ .map((line) => (
+
+ {
+ estimate
+ .snapshot
+ .item
+ .description
+ }{' '}
+ · {line.label} ·
+ estimativa #
+ {estimate.id} v
+ {
+ estimate.version
+ }{' '}
+ ·{' '}
+ {line.amount_minor ===
+ null
+ ? 'Por determinar'
+ : `${estimateMoney(line.amount_minor)} MZN`}
+
+ )),
+ )}
+
+ {row.legal_estimate_id !== null && (
+
+ O total conserva a fonte
+ seleccionada. Indique
+ explicitamente a divisão
+ entre base e imposto segundo
+ o orçamento. Para alterar o
+ montante, retire primeiro a
+ ligação.
+
+ )}
+
+ )}
Situação
+
+ =
+ 100
+ }
+ onClick={() =>
+ form.setData('components', [
+ ...form.data.components,
+ {
+ key: crypto.randomUUID(),
+ kind: row.kind,
+ status: 'unknown',
+ basis: '',
+ subtotal: '',
+ tax: '',
+ total: '',
+ legal_estimate_id: null,
+ legal_charge_key: null,
+ },
+ ])
+ }
+ >
+ Acrescentar parcela desta família
+
+ {form.data.components.filter(
+ (component) =>
+ component.kind === row.kind,
+ ).length > 1 && (
+
+ form.setData(
+ 'components',
+ form.data.components.filter(
+ (_, at) =>
+ at !== index,
+ ),
+ )
+ }
+ >
+ Retirar parcela da preparação
+
+ )}
+
))}
diff --git a/resources/js/pages/supply/import-legal.tsx b/resources/js/pages/supply/import-legal.tsx
new file mode 100644
index 0000000..09ac406
--- /dev/null
+++ b/resources/js/pages/supply/import-legal.tsx
@@ -0,0 +1,1155 @@
+import { Head, Link, useForm } from '@inertiajs/react';
+import { useEffect, useRef } from 'react';
+import {
+ FormErrors,
+ PageTitle,
+ Panel,
+ controlClass,
+} from '@/components/procurement';
+import { Button } from '@/components/ui/button';
+import LegalChargeFields, {
+ LegalChargeSummary,
+ chargeDrafts,
+ type LegalCharge,
+ type LegalChargeDraft,
+} from '@/components/import-legal-charges';
+import { estimateMinor, estimateMoney } from '@/lib/import-estimate-money';
+import { date, money } from '@/types/procurement';
+
+type LegalData = {
+ title: string;
+ official_reference: string;
+ official_url: string | null;
+ citation: string;
+ valid_from: string;
+ valid_until: string | null;
+ match_code: string;
+ suggested_code: string;
+ origin_country: string | null;
+ sector: string | null;
+ obligations: string;
+ document_types: string[];
+ charges?: LegalCharge[];
+};
+type LegalRule = {
+ id: number;
+ record_key: string;
+ version: number;
+ state: string;
+ data: LegalData;
+ reason: string;
+ source_url: string;
+};
+type Page = {
+ data: T[];
+ prev_page_url: string | null;
+ next_page_url: string | null;
+};
+type Props = {
+ sources?: Page<{
+ id: number;
+ data: { official_reference: string; official_url: string | null };
+ }>;
+ requisition: { id: number; number: string };
+ rules: Page;
+ history: Page;
+ suggestions: {
+ id: number;
+ version: number;
+ data: LegalData;
+ source_sha256: string;
+ }[];
+ items: { id: number; description: string }[];
+ classifications: {
+ version: number;
+ data: { requisition_item_id: number };
+ }[];
+ canManage: boolean;
+ estimates?: {
+ id: number;
+ version: number;
+ state: string;
+ data: {
+ requisition_item_id: number;
+ bases: Record<
+ string,
+ {
+ value_minor: number | null;
+ quantity: string | null;
+ source: string | null;
+ }
+ >;
+ };
+ snapshot: {
+ legal_rule: {
+ id: number;
+ context: {
+ code: string;
+ origin_country: string;
+ sector: string;
+ date: string;
+ };
+ };
+ item: { description: string };
+ result: {
+ total_minor: number | null;
+ known_subtotal_minor: number;
+ lines: {
+ key: string;
+ label: string;
+ amount_minor: number | null;
+ }[];
+ };
+ };
+ }[];
+ estimateHistory?: Page<{
+ id: number;
+ version: number;
+ state: string;
+ reason: string;
+ }>;
+ canPropose: boolean;
+ actorId: number;
+ tenantId: number;
+ types: Record;
+ filters: { code?: string; origin?: string; sector?: string; date: string };
+};
+const states: Record = {
+ draft: 'Em preparação',
+ published: 'Publicada pela área aduaneira',
+ withdrawn: 'Retirada de novas sugestões',
+};
+function useDirtyForm(dirty: boolean) {
+ const ref = useRef(null);
+ useEffect(() => {
+ const form = ref.current;
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', { detail: { form, dirty } }),
+ );
+ return () => {
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form, dirty: false },
+ }),
+ );
+ };
+ }, [dirty]);
+ return ref;
+}
+function Pages({ page }: { page: Page }) {
+ return (
+
+ {page.prev_page_url && (
+
+ Anterior
+
+ )}
+ {page.next_page_url && (
+
+ Seguinte
+
+ )}
+
+ );
+}
+function Proposal({
+ rule,
+ props,
+}: {
+ rule: Props['suggestions'][number];
+ props: Props;
+}) {
+ const form = useForm(
+ `legal-proposal:${props.tenantId}:${props.actorId}:${props.requisition.id}:${rule.id}:${JSON.stringify(props.filters)}`,
+ { operation_key: '', requisition_item_id: '', reason: '', version: 0 },
+ );
+ const ref = useDirtyForm(form.isDirty);
+ return (
+ {
+ event.preventDefault();
+ const operation =
+ form.data.operation_key || crypto.randomUUID();
+ form.setData('operation_key', operation);
+ form.transform((data) => ({
+ ...data,
+ operation_key: operation,
+ action: 'propose',
+ code: rule.data.suggested_code,
+ source_reference: `${rule.data.official_reference} — ${rule.data.citation}`,
+ legal_rule_id: rule.id,
+ legal_match_code: props.filters.code,
+ legal_origin: props.filters.origin ?? '',
+ legal_sector: props.filters.sector ?? '',
+ legal_date: props.filters.date,
+ }));
+ form.post(
+ `/requisicoes/${props.requisition.id}/classificacao-pautal`,
+ { onSuccess: () => form.reset() },
+ );
+ }}
+ >
+
+
+ Artigo a classificar
+
+ form.setData((data) => ({
+ ...data,
+ requisition_item_id: e.target.value,
+ version:
+ props.classifications.find(
+ (row) =>
+ String(row.data.requisition_item_id) ===
+ e.target.value,
+ )?.version ?? 0,
+ }))
+ }
+ >
+ Seleccione
+ {props.items.map((item) => (
+
+ {item.description}
+
+ ))}
+
+
+
+ Motivo da proposta ou da substituição
+ form.setData('reason', e.target.value)}
+ />
+
+
+ Preparar proposta com esta fonte
+
+
+ A proposta conserva a fonte e o contexto. Confirme ou justifique
+ o desvio no percurso de classificação pautal.
+
+
+ );
+}
+function ChargeEstimate({
+ rule,
+ props,
+}: {
+ rule: Props['suggestions'][number];
+ props: Props;
+}) {
+ const form = useForm(
+ `legal-amounts:${props.tenantId}:${props.actorId}:${props.requisition.id}:${rule.id}:${JSON.stringify(props.filters)}`,
+ {
+ operation_key: '',
+ requisition_item_id: '',
+ version: 0,
+ reason: '',
+ bases: Object.fromEntries(
+ (rule.data.charges ?? []).map((charge) => [
+ charge.key,
+ { value: '', quantity: '', source: '' },
+ ]),
+ ),
+ },
+ );
+ const ref = useDirtyForm(form.isDirty);
+ const previous = props.estimates?.find(
+ (estimate) =>
+ String(estimate.data.requisition_item_id) ===
+ form.data.requisition_item_id &&
+ estimate.snapshot.legal_rule.id === rule.id &&
+ estimate.snapshot.legal_rule.context.code === props.filters.code &&
+ estimate.snapshot.legal_rule.context.origin_country ===
+ (props.filters.origin ?? '') &&
+ estimate.snapshot.legal_rule.context.sector ===
+ (props.filters.sector ?? '') &&
+ estimate.snapshot.legal_rule.context.date === props.filters.date,
+ );
+ return (
+ {
+ event.preventDefault();
+ const operation =
+ form.data.operation_key || crypto.randomUUID();
+ form.setData('operation_key', operation);
+ form.transform((data) => ({
+ operation_key: operation,
+ requisition_item_id: data.requisition_item_id,
+ version: data.version,
+ reason: data.reason,
+ rule_id: rule.id,
+ match_code: props.filters.code,
+ origin: props.filters.origin ?? '',
+ sector: props.filters.sector ?? '',
+ date: props.filters.date,
+ bases: Object.fromEntries(
+ (rule.data.charges ?? []).map((charge) => {
+ const base = data.bases[charge.key];
+ return [
+ charge.key,
+ {
+ value_minor:
+ base.value === ''
+ ? null
+ : estimateMinor(base.value),
+ quantity: base.quantity || null,
+ quantity_unit: charge.quantity_unit,
+ source: base.source || null,
+ },
+ ];
+ }),
+ ),
+ }));
+ form.post(
+ `/requisicoes/${props.requisition.id}/base-legal/estimativas`,
+ { onSuccess: () => form.reset() },
+ );
+ }}
+ >
+ Estimar as imposições desta regra
+ {previous && (
+
+
+ Há bases preservadas na estimativa #{previous.id},
+ versão {previous.version}, para este contexto. Pode
+ reutilizá-las e revê-las antes de calcular.
+
+
+ form.setData(
+ 'bases',
+ Object.fromEntries(
+ (rule.data.charges ?? []).map((charge) => {
+ const base =
+ previous.data.bases[charge.key];
+ return [
+ charge.key,
+ {
+ value: estimateMoney(
+ base?.value_minor ?? null,
+ ),
+ quantity: base?.quantity ?? '',
+ source: base?.source ?? '',
+ },
+ ];
+ }),
+ ),
+ )
+ }
+ >
+ Reutilizar bases preservadas
+
+
+ )}
+
+
+ Artigo
+
+ form.setData((data) => ({
+ ...data,
+ requisition_item_id: e.target.value,
+ version:
+ props.estimates?.find(
+ (row) =>
+ String(row.data.requisition_item_id) ===
+ e.target.value,
+ )?.version ?? 0,
+ }))
+ }
+ >
+ Seleccione
+ {props.items.map((item) => (
+
+ {item.description}
+
+ ))}
+
+
+ {(rule.data.charges ?? []).map((charge) => (
+
+ {charge.label}
+ {charge.basis_reference}
+ {['ad_valorem', 'maximum'].includes(charge.method) && (
+
+ Base de incidência em MZN · taxa{' '}
+ {charge.rate_percent}%
+
+ form.setData('bases', {
+ ...form.data.bases,
+ [charge.key]: {
+ ...form.data.bases[charge.key],
+ value: e.target.value,
+ },
+ })
+ }
+ />
+
+ )}
+ {['specific', 'maximum'].includes(charge.method) && (
+
+ Quantidade em {charge.quantity_unit} · taxa{' '}
+ {money(charge.specific_minor)} por unidade
+
+ form.setData('bases', {
+ ...form.data.bases,
+ [charge.key]: {
+ ...form.data.bases[charge.key],
+ quantity: e.target.value,
+ },
+ })
+ }
+ />
+
+ )}
+ {[
+ 'ad_valorem',
+ 'specific',
+ 'maximum',
+ 'not_applicable',
+ ].includes(charge.method) ? (
+
+ {charge.method === 'not_applicable'
+ ? 'Fundamento documental de que a não aplicação e os seus requisitos se verificam neste artigo'
+ : 'Origem do valor ou da quantidade'}
+
+ form.setData('bases', {
+ ...form.data.bases,
+ [charge.key]: {
+ ...form.data.bases[charge.key],
+ source: e.target.value,
+ },
+ })
+ }
+ />
+
+ ) : (
+ Imposição por determinar.
+ )}
+
+ ))}
+
+ Deixe por indicar as bases desconhecidas. O subtotal conhecido
+ não representa o custo integral da importação.
+
+
+ Motivo e pressupostos
+ form.setData('reason', e.target.value)}
+ />
+
+
+ Calcular e preservar estimativa
+
+
+ );
+}
+function SourceForm({ url, scope }: { url: string; scope: string }) {
+ const form = useForm(`legal-source:${scope}`, {
+ operation_key: '',
+ action: 'source',
+ record_key: null,
+ version: 0,
+ official_reference: '',
+ official_url: '',
+ reason: '',
+ file: null as File | null,
+ });
+ const ref = useDirtyForm(form.isDirty);
+ return (
+ {
+ event.preventDefault();
+ const operation =
+ form.data.operation_key || crypto.randomUUID();
+ form.setData('operation_key', operation);
+ form.transform((data) => ({
+ ...data,
+ operation_key: operation,
+ }));
+ form.post(url, {
+ forceFormData: true,
+ onSuccess: () => form.reset(),
+ });
+ }}
+ >
+
+
+ Diploma e edição do exemplar
+
+ form.setData('official_reference', e.target.value)
+ }
+ />
+
+
+ Ligação oficial, quando disponível
+
+ form.setData('official_url', e.target.value)
+ }
+ />
+
+
+ Exemplar integral (PDF ou imagem, até 64 MB)
+
+ form.setData('file', e.target.files?.[0] ?? null)
+ }
+ />
+
+
+ Motivo do registo
+ form.setData('reason', e.target.value)}
+ />
+
+
+ Conservar fonte para consulta
+
+
+ );
+}
+export default function ImportLegal(props: Props) {
+ const url = `/requisicoes/${props.requisition.id}/base-legal`;
+ const form = useForm(
+ `legal-rule:${props.tenantId}:${props.actorId}:${props.requisition.id}`,
+ {
+ operation_key: '',
+ record_key: null as string | null,
+ version: 0,
+ action: 'save',
+ title: '',
+ official_reference: '',
+ official_url: '',
+ citation: '',
+ valid_from: '',
+ valid_until: '',
+ match_code: '',
+ suggested_code: '',
+ origin_country: '',
+ sector: '',
+ obligations: '',
+ document_types: [] as string[],
+ reason: '',
+ file: null as File | null,
+ source_id: '',
+ charges: [] as LegalChargeDraft[],
+ },
+ );
+ const action = useForm(
+ `legal-action:${props.tenantId}:${props.actorId}:${props.requisition.id}`,
+ {
+ operation_key: '',
+ record_key: '',
+ version: 0,
+ action: '',
+ reason: '',
+ },
+ );
+ const actionRef = useDirtyForm(action.isDirty);
+ const ref = useRef(null);
+ useEffect(() => {
+ const node = ref.current;
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: node, dirty: form.isDirty },
+ }),
+ );
+ return () => {
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: node, dirty: false },
+ }),
+ );
+ };
+ }, [form.isDirty]);
+ const edit = (rule: LegalRule) => {
+ form.setData({
+ ...form.data,
+ ...rule.data,
+ official_url: rule.data.official_url ?? '',
+ valid_until: rule.data.valid_until ?? '',
+ origin_country: rule.data.origin_country ?? '',
+ sector: rule.data.sector ?? '',
+ operation_key: '',
+ action: 'save',
+ record_key: rule.record_key,
+ version: rule.version,
+ file: null,
+ source_id: '',
+ charges: chargeDrafts(rule.data.charges ?? []),
+ reason: '',
+ });
+ form.clearErrors();
+ };
+ const fields = [
+ ['title', 'Título da regra'],
+ ['official_reference', 'Diploma e edição oficial'],
+ ['official_url', 'Ligação da fonte oficial'],
+ ['citation', 'Artigo, página e citação aplicável'],
+ ['valid_from', 'Início da vigência'],
+ ['valid_until', 'Fim da vigência conhecido (opcional)'],
+ ['match_code', 'Código a consultar'],
+ ['suggested_code', 'Código sugerido'],
+ [
+ 'origin_country',
+ 'País de origem específico (vazio: todas as origens)',
+ ],
+ ['sector', 'Sector específico (vazio: todos os sectores)'],
+ ] as const;
+ return (
+
+
+
+
+ Voltar à classificação pautal
+
+
+
+ {(['code', 'origin', 'sector', 'date'] as const).map(
+ (key) => (
+
+ {
+ {
+ code: 'Código previsto',
+ origin: 'País de origem',
+ sector: 'Sector',
+ date: 'Data de aplicação',
+ }[key]
+ }
+
+
+ ),
+ )}
+ Consultar fontes aplicáveis
+
+ {props.filters.code && props.suggestions.length === 0 && (
+
+ Sem regra publicada correspondente a este contexto e
+ período. Não foram presumidos código, taxa ou isenção.
+
+ )}
+ {props.suggestions.map((rule) => (
+
+
+ {rule.data.title} · versão {rule.version}
+
+ Código sugerido: {rule.data.suggested_code}
+
+ {rule.data.official_reference} ·{' '}
+ {rule.data.citation}
+
+ {rule.data.obligations}
+
+ Documentos indicados:{' '}
+ {rule.data.document_types
+ .map((type) => props.types[type])
+ .join(', ') ||
+ 'Nenhum segundo a fonte registada'}
+
+
+ {props.canPropose && (
+
+ )}
+ {props.canPropose && (
+
+ )}
+
+ ))}
+
+
+ {props.rules.data.length === 0 && (
+ Ainda não existem fontes neste âmbito.
+ )}
+ {props.rules.data.map((rule) => (
+
+
+ {rule.data.title} · versão {rule.version}
+
+ {states[rule.state]}
+
+ {rule.data.official_reference} ·{' '}
+ {rule.data.citation}
+
+
+ {date(rule.data.valid_from)} até{' '}
+ {rule.data.valid_until
+ ? date(rule.data.valid_until)
+ : 'sem termo final indicado'}
+
+
+
+ Descarregar exemplar preservado
+
+ {props.canManage && (
+
+ edit(rule)}
+ >
+ Preparar nova versão
+
+ {rule.state === 'draft' && (
+
+ action.setData({
+ operation_key: '',
+ record_key: rule.record_key,
+ version: rule.version,
+ action: 'publish',
+ reason: '',
+ })
+ }
+ >
+ Preparar publicação
+
+ )}
+ {rule.state !== 'withdrawn' && (
+
+ action.setData({
+ operation_key: '',
+ record_key: rule.record_key,
+ version: rule.version,
+ action: 'withdraw',
+ reason: '',
+ })
+ }
+ >
+ Preparar retirada
+
+ )}
+
+ )}
+
+ ))}
+
+
+ {props.canManage && action.data.record_key && (
+
+ {
+ e.preventDefault();
+ const operation =
+ action.data.operation_key ||
+ crypto.randomUUID();
+ action.setData('operation_key', operation);
+ action.transform((data) => ({
+ ...data,
+ operation_key: operation,
+ }));
+ action.post(url, {
+ onSuccess: () => action.reset(),
+ });
+ }}
+ >
+
+
+ Motivo da decisão
+
+ action.setData('reason', e.target.value)
+ }
+ />
+
+
+ Registar decisão da área aduaneira
+
+
+
+ )}
+ {props.canManage && (
+
+ {
+ e.preventDefault();
+ const operation =
+ form.data.operation_key || crypto.randomUUID();
+ form.setData('operation_key', operation);
+ form.transform((data) => ({
+ ...data,
+ operation_key: operation,
+ valid_until: data.valid_until || null,
+ source_id: data.source_id || null,
+ origin_country: data.origin_country || null,
+ sector: data.sector || null,
+ charges: data.charges.map((charge) => ({
+ key: charge.key,
+ kind: charge.kind,
+ label: charge.label,
+ method: charge.method,
+ rate_percent: charge.rate_percent || null,
+ specific_minor:
+ charge.specific_amount === ''
+ ? null
+ : estimateMinor(
+ charge.specific_amount,
+ ),
+ quantity_unit: charge.quantity_unit || null,
+ basis_reference: charge.basis_reference,
+ })),
+ }));
+ form.post(url, {
+ forceFormData: true,
+ onSuccess: () => form.reset(),
+ });
+ }}
+ >
+
+
+ Reutilizar exemplar preservado
+ {
+ const source = props.sources?.data.find(
+ (row) =>
+ String(row.id) === e.target.value,
+ );
+ form.setData((data) => ({
+ ...data,
+ source_id: e.target.value,
+ ...(source
+ ? {
+ official_reference:
+ source.data
+ .official_reference,
+ official_url:
+ source.data
+ .official_url ?? '',
+ file: null,
+ }
+ : {}),
+ }));
+ }}
+ >
+
+ {form.data.record_key
+ ? 'Conservar exemplar anterior ou carregar um novo'
+ : 'Carregar um novo exemplar'}
+
+ {props.sources?.data.map((source) => (
+
+ {source.data.official_reference}
+
+ ))}
+
+
+
+ {fields.map(([key, label]) => (
+
+ {label}
+
+ form.setData(key, e.target.value)
+ }
+ />
+
+ ))}
+
+
+ Imposições, condições, isenções e procedimentos
+ documentados
+
+ form.setData('obligations', e.target.value)
+ }
+ />
+
+
+ Documentos exigidos na fonte
+ {Object.entries(props.types).map(
+ ([type, label]) => (
+
+
+ form.setData(
+ 'document_types',
+ e.target.checked
+ ? [
+ ...form.data
+ .document_types,
+ type,
+ ]
+ : form.data.document_types.filter(
+ (value) =>
+ value !==
+ type,
+ ),
+ )
+ }
+ />
+ {label}
+
+ ),
+ )}
+
+
+ form.setData('charges', charges)
+ }
+ />
+
+ Exemplar oficial (PDF ou imagem, até 64 MB)
+
+ form.setData(
+ 'file',
+ e.target.files?.[0] ?? null,
+ )
+ }
+ />
+
+
+ Motivo da preparação
+
+ form.setData('reason', e.target.value)
+ }
+ />
+
+
+ Guardar preparação para validação aduaneira
+
+ {form.data.record_key && (
+ form.reset()}
+ >
+ Preparar outra regra
+
+ )}
+
+
+ )}
+
+ {props.sources?.data.map((source) => (
+
+
+ {source.data.official_reference}
+
+
+ ))}
+ {props.sources && }
+ {props.canManage && (
+
+ )}
+
+
+ {props.estimates?.map((estimate) => (
+
+
+ {estimate.snapshot.item.description} · versão{' '}
+ {estimate.version}
+
+
+ Total das imposições parametrizadas:{' '}
+ {estimate.snapshot.result.total_minor === null
+ ? 'Por determinar'
+ : money(estimate.snapshot.result.total_minor)}
+
+
+ Subtotal conhecido:{' '}
+ {money(
+ estimate.snapshot.result.known_subtotal_minor,
+ )}
+
+ {estimate.snapshot.result.lines.map((line) => (
+
+ {line.label}:{' '}
+ {line.amount_minor === null
+ ? 'Por determinar'
+ : money(line.amount_minor)}
+
+ ))}
+
+ ))}
+
+ Abrir plano de custo da importação
+
+ {props.estimateHistory?.data.map((estimate) => (
+
+ Estimativa #{estimate.id} · versão {estimate.version} ·{' '}
+ {estimate.reason}
+
+ ))}
+ {props.estimateHistory && (
+
+ )}
+
+
+ {props.history.data.map((rule) => (
+
+ {rule.data.title} · v{rule.version} ·{' '}
+ {states[rule.state]} · {rule.reason}
+
+ ))}
+
+
+
+ );
+}
diff --git a/resources/js/pages/supply/import-readiness.tsx b/resources/js/pages/supply/import-readiness.tsx
new file mode 100644
index 0000000..989fc4c
--- /dev/null
+++ b/resources/js/pages/supply/import-readiness.tsx
@@ -0,0 +1,73 @@
+import { Head, Link } from '@inertiajs/react';
+import { PageTitle, Panel } from '@/components/procurement';
+import { date } from '@/types/procurement';
+
+type Props = {
+ importRecord: { id: number; version: number; state: string };
+ order: { id: number; number: string };
+ expectedUsableOn: string | null;
+ checkedAt: string;
+ complete: boolean;
+ alerts: { key: string; category: string; text: string; href: string }[];
+};
+export default function ImportReadiness(props: Props) {
+ return (
+
+
+
+
+
+ Abrir dossiê
+
+
+ Voltar às importações
+
+
+
+
+ Versão logística: {props.importRecord.version} · previsão de
+ recepção utilizável:{' '}
+ {props.expectedUsableOn
+ ? date(props.expectedUsableOn)
+ : 'Por indicar'}
+
+ {!props.complete && (
+
+ Verificação incompleta: consulte as limitações abaixo
+ antes de concluir a conferência.
+
+ )}
+ {props.alerts.length === 0 && (
+
+ Sem alertas identificados no âmbito verificado. Conserve
+ a conferência humana dos requisitos aplicáveis.
+
+ )}
+
+ {props.alerts.map((alert) => (
+
+ {alert.category}
+ {alert.text}
+
+ Abrir percurso relacionado
+
+
+ ))}
+
+
+
+ );
+}
diff --git a/resources/js/pages/supply/import-tariffs.tsx b/resources/js/pages/supply/import-tariffs.tsx
index 7712e00..7ec7280 100644
--- a/resources/js/pages/supply/import-tariffs.tsx
+++ b/resources/js/pages/supply/import-tariffs.tsx
@@ -9,6 +9,7 @@ import {
} from '@/components/procurement';
type RecordVersion = {
+ legal_changed?: boolean;
id: number;
version: number;
state: string;
@@ -38,6 +39,7 @@ type Page = {
next_page_url: string | null;
};
type Props = {
+ legalReady?: boolean;
requisition: { id: number; number: string };
items: {
id: number;
@@ -142,6 +144,12 @@ function ItemForm({
? `Confirmado: ${latest.data.confirmed_code} · ${latest.snapshot.confirmed_by?.name ?? 'Comprador registado'}`
: 'Código pautal por confirmar pelo comprador.'}
+ {latest?.legal_changed && (
+
+ A fonte legal aplicada foi substituída ou retirada. Reveja a
+ classificação; a decisão anterior permanece no histórico.
+
+ )}
{latest?.snapshot.master && (
Proposta reutilizada de {latest.snapshot.master.item.code} ·{' '}
@@ -368,6 +376,14 @@ export default function ImportTariffs(props: Props) {
percurso.
+ {props.legalReady && (
+
+ Consultar base legal e sugestões
+
+ )}
;
import_tariffs?: Record;
budget_checked?: boolean;
agreement_bindings?: Record;
diff --git a/resources/views/purchases/print.blade.php b/resources/views/purchases/print.blade.php
index 531784c..6ccc94f 100644
--- a/resources/views/purchases/print.blade.php
+++ b/resources/views/purchases/print.blade.php
@@ -85,10 +85,23 @@
limite por ordem: {{ $binding['max_order_quantity_milli'] === null ? 'Não definido' : str_replace('.', ',', (string)\Brick\Math\BigDecimal::of($binding['max_order_quantity_milli'])->dividedBy(1000, 3)) . ' ' . $binding['unit'] }}.
@endforeach
@endif
+ @if(!empty($snapshot['capital_assignments']))
+ Projectos e imobilizado
+ @foreach($snapshot['capital_assignments'] as $assignment)
+ {{ $assignment['snapshot']['item']['description'] }}
+ {{ $assignment['snapshot']['source']['data']['type'] === 'project' ? 'Projecto' : 'Imobilizado' }}:
+ {{ $assignment['snapshot']['source']['data']['code'] }} · {{ $assignment['snapshot']['source']['data']['name'] }}
+ · versão {{ $assignment['snapshot']['source']['version'] }}
+ {{ $assignment['snapshot']['source']['data']['reference'] }} {{ $assignment['reason'] }}
+ @endforeach
+ @endif
@if(!empty($snapshot['import_tariffs']))
Classificação pautal preservada na emissão
@foreach($snapshot['import_tariffs'] as $classification)
{{ $classification['item']['description'] }} Código confirmado: {{ $classification['data']['confirmed_code'] }} · versão {{ $classification['version'] }} · {{ $classification['confirmed_by']['name'] }} Proposta: {{ $classification['data']['proposed_code'] ?? 'Não indicada' }} · Fonte: {{ $classification['data']['source_reference'] ?? 'Por completar' }} Fonte da confirmação: {{ $classification['data']['confirmation_source'] }} {{ $classification['data']['deviation'] ? 'Justificação do desvio' : 'Motivo' }}: {{ $classification['reason'] }}
+ @if(!empty($classification['legal_rule']))
+ Regra legal aplicada: {{ $classification['legal_rule']['data']['official_reference'] }} · {{ $classification['legal_rule']['data']['citation'] }} · versão {{ $classification['legal_rule']['version'] }} Condições preservadas: {{ $classification['legal_rule']['data']['obligations'] }}
+ @endif
@endforeach
@endif
Justificação da adjudicação {{ $snapshot['award']['justification'] }}
diff --git a/routes/web.php b/routes/web.php
index a2cd920..14c9a13 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -7,6 +7,7 @@ use App\Http\Controllers\AutomaticPurchaseController;
use App\Http\Controllers\BudgetController;
use App\Http\Controllers\BudgetReinforcementController;
use App\Http\Controllers\CandidatePortalController;
+use App\Http\Controllers\CapitalRegisterController;
use App\Http\Controllers\CommonStockReadController;
use App\Http\Controllers\CompanyController;
use App\Http\Controllers\ConflictDeclarationController;
@@ -17,9 +18,12 @@ use App\Http\Controllers\FormalAdmissionController;
use App\Http\Controllers\FormalRecommendationController;
use App\Http\Controllers\GeneralLedgerController;
use App\Http\Controllers\GoodsReceiptController;
+use App\Http\Controllers\ImportBankSupportController;
use App\Http\Controllers\ImportDossierController;
use App\Http\Controllers\ImportEstimateController;
use App\Http\Controllers\ImportLandedCostController;
+use App\Http\Controllers\ImportLegalController;
+use App\Http\Controllers\ImportReadinessController;
use App\Http\Controllers\ImportTariffController;
use App\Http\Controllers\InventoryDispositionController;
use App\Http\Controllers\InventoryLotController;
@@ -139,6 +143,10 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('compras/importacoes/{import}/intervenientes', [ImportDossierController::class, 'selectParty'])->whereNumber('import');
Route::get('compras/importacoes/{import}/documentos/{document}', [ImportDossierController::class, 'evidence'])->whereNumber('import')->whereNumber('document');
Route::get('requisicoes/{requisition}/classificacao-pautal', [ImportTariffController::class, 'index'])->whereNumber('requisition');
+ Route::get('requisicoes/{requisition}/base-legal', [ImportLegalController::class, 'index'])->whereNumber('requisition');
+ Route::post('requisicoes/{requisition}/base-legal', [ImportLegalController::class, 'store'])->whereNumber('requisition');
+ Route::post('requisicoes/{requisition}/base-legal/estimativas', [ImportLegalController::class, 'estimate'])->whereNumber('requisition');
+ Route::get('requisicoes/{requisition}/base-legal/fontes/{source}', [ImportLegalController::class, 'source'])->whereNumber('requisition')->whereNumber('source');
Route::get('requisicoes/{requisition}/estimativa-importacao', [ImportEstimateController::class, 'index'])->whereNumber('requisition');
Route::post('requisicoes/{requisition}/estimativa-importacao', [ImportEstimateController::class, 'store'])->whereNumber('requisition');
Route::post('requisicoes/{requisition}/classificacao-pautal', [ImportTariffController::class, 'store'])->whereNumber('requisition');
@@ -146,6 +154,10 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('compras/importacoes/{import}/custos/documentos', [ImportLandedCostController::class, 'document'])->whereNumber('import');
Route::post('compras/importacoes/{import}/custos/preparacao', [ImportLandedCostController::class, 'save'])->whereNumber('import');
Route::post('compras/importacoes/{import}/custos/{plan}/orcamento', [ImportLandedCostController::class, 'financial'])->whereNumber('import')->whereNumber('plan');
+ Route::get('compras/importacoes/{import}/suporte-bancario', [ImportBankSupportController::class, 'index'])->whereNumber('import');
+ Route::get('compras/importacoes/{import}/acompanhamento', [ImportReadinessController::class, 'index'])->whereNumber('import');
+ Route::get('compras/importacoes/{import}/suporte-bancario.csv', [ImportBankSupportController::class, 'export'])->whereNumber('import');
+ Route::post('compras/importacoes/{import}/suporte-bancario', [ImportBankSupportController::class, 'store'])->whereNumber('import');
Route::get('compras/importacoes/{import}/custos/documentos/{document}', [ImportLandedCostController::class, 'evidence'])->whereNumber('import')->whereNumber('document');
Route::get('compras/pesquisa', [ProcurementSearchController::class, 'index'])->name('procurement.search');
Route::post('compras/pesquisas-guardadas', [SavedProcurementSearchController::class, 'store'])->name('procurement.saved-searches.store');
@@ -290,6 +302,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('orcamentos', [BudgetController::class, 'store'])->name('budgets.store');
Route::post('orcamentos/{budget}/aprovar', [BudgetController::class, 'approve'])->name('budgets.approve');
Route::get('equipamentos', [EquipmentController::class, 'index'])->name('equipment.index');
+ Route::get('projectos-imobilizado', [CapitalRegisterController::class, 'index'])->name('capital-register.index');
+ Route::post('projectos-imobilizado', [CapitalRegisterController::class, 'store'])->name('capital-register.store');
Route::get('ordens/cancelamentos', [OrderCancellationController::class, 'index']);
Route::post('ordens/{order}/cancelamento', [OrderCancellationController::class, 'request'])->whereNumber('order');
Route::post('ordens/cancelamentos/{cancellation}/decidir', [OrderCancellationController::class, 'decide'])->whereNumber('cancellation');
@@ -354,6 +368,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::put('requisicoes/{requisition}', [RequisitionController::class, 'update'])->name('requisitions.update');
Route::post('requisicoes/{requisition}/submeter', [RequisitionController::class, 'submit'])->name('requisitions.submit');
Route::get('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'distributions'])->name('requisitions.distributions');
+ Route::get('requisicoes/{requisition}/projectos-imobilizado', [CapitalRegisterController::class, 'assignments'])->name('requisitions.capital');
+ Route::post('requisicoes/{requisition}/projectos-imobilizado', [CapitalRegisterController::class, 'assign'])->name('requisitions.capital.assign');
Route::post('requisicoes/{requisition}/distribuicoes', [RequisitionController::class, 'prepareDistributions'])->name('requisitions.distributions.prepare');
Route::post('requisicoes/{requisition}/decidir', [RequisitionController::class, 'decide'])->name('requisitions.decide');
});
diff --git a/scripts/quotation-exchange-pg-check.php b/scripts/quotation-exchange-pg-check.php
index a310095..f1d0f4f 100644
--- a/scripts/quotation-exchange-pg-check.php
+++ b/scripts/quotation-exchange-pg-check.php
@@ -83,6 +83,68 @@ try {
if (in_array('--dossier-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportDossierTest.php', 'tests/Feature/ImportLandedCostsTest.php', 'tests/Feature/OperationalHealthTest.php', 'tests/Feature/SupplyPlanningTest.php']];
}
+ if (in_array('--bank-support-focused', $argv, true)) {
+ $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportBankSupportTest.php', 'tests/Feature/ImportDossierTest.php', 'tests/Feature/ImportLandedCostsTest.php', 'tests/Feature/SupplyPlanningTest.php']];
+ }
+ if (in_array('--legal-focused', $argv, true)) {
+ $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalRulesTest.php', 'tests/Feature/ImportTariffCodesTest.php',
+ 'tests/Feature/ImportReadinessTest.php', 'tests/Feature/ImportBankSupportTest.php', 'tests/Feature/OperationalHealthTest.php', 'tests/Feature/ImportDossierTest.php']];
+ }
+ if (in_array('--legal-amounts-focused', $argv, true)) {
+ $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLegalEstimatesTest.php', 'tests/Feature/ImportLegalRulesTest.php',
+ 'tests/Feature/ImportEstimatesTest.php', 'tests/Feature/ImportEstimatePlanTest.php', 'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionApprovalLevelsTest.php']];
+ }
+ if (in_array('--capital-focused', $argv, true)) {
+ $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/CapitalRegisterTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
+ '--filter=capital|register|line destination|submitted requisitions|confirmed import classifications|partial native order retains']];
+ }
+ if (in_array('--capital-concurrency', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-capital']];
+ }
+ if (in_array('--legal-concurrency', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-legal']];
+ }
+ if (in_array('--legal-amount-concurrency', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-legal-amount']];
+ }
+ if (in_array('--legal-recovery', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'import-legal']];
+ }
+ if (in_array('--legal-amount-recovery', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'import-legal-amount']];
+ }
+ if (in_array('--legal-corpus', $argv, true)) {
+ $corpusArguments = array_values(array_filter($argv, fn ($value) => str_starts_with($value, '--legal-corpus-root=')));
+ if (count($corpusArguments) !== 1) {
+ throw new InvalidArgumentException('Indique exactamente uma pasta de legislação partilhada.');
+ }
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/import-legal-corpus-worker.php', $database, 'corpus', substr($corpusArguments[0], strlen('--legal-corpus-root='))]];
+ }
+ if (in_array('--legal-http', $argv, true) || in_array('--legal-native-review', $argv, true)) {
+ $values = [];
+ foreach (['--legal-corpus-root=', '--legal-http-candidate=', '--legal-http-manifest='] as $prefix) {
+ $matches = array_values(array_filter($argv, fn ($value) => str_starts_with($value, $prefix)));
+ if (count($matches) !== 1) {
+ throw new InvalidArgumentException('Indique uma pasta de fontes e uma candidata privada com o seu manifesto validado.');
+ }
+ $values[] = substr($matches[0], strlen($prefix));
+ }
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/import-legal-http-worker.php', $database, in_array('--legal-native-review', $argv, true) ? 'legal-review' : 'legal-http', ...$values]];
+ }
+ if (in_array('--bank-support-native-only', $argv, true)) {
+ $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportBankSupportTest.php']];
+ }
+ if (in_array('--bank-support-concurrency', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-bank']];
+ }
if (in_array('--dossier-concurrency', $argv, true)) {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-dossier']];
@@ -118,6 +180,10 @@ try {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'import-estimates']];
}
+ if (in_array('--bank-support-recovery', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'import-bank-support']];
+ }
}
if ($orderPartsMode) {
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
@@ -218,9 +284,14 @@ try {
throw new LogicException('Each Pest kernel must use its own disposable PostgreSQL database.');
}
foreach ($commands as $command) {
- $process = new Process($command, dirname(__DIR__), $environment, timeout: 180);
- $process->run();
- echo $process->getOutput();
+ $nativeReview = ($command[3] ?? '') === 'legal-review';
+ $process = new Process($command, dirname(__DIR__), $environment, timeout: $nativeReview ? 3660 : 180);
+ $process->run($nativeReview ? function ($type, $buffer) {
+ echo $buffer;
+ } : null);
+ if (! $nativeReview) {
+ echo $process->getOutput();
+ }
if (! $process->isSuccessful()) {
echo $process->getErrorOutput();
throw new RuntimeException('Validação PostgreSQL não aprovada.');
diff --git a/tests/Concurrency/budget-distribution-recovery-worker.php b/tests/Concurrency/budget-distribution-recovery-worker.php
index 2fecba6..775f341 100644
--- a/tests/Concurrency/budget-distribution-recovery-worker.php
+++ b/tests/Concurrency/budget-distribution-recovery-worker.php
@@ -2,14 +2,20 @@
use App\Enums\PurchasingRole;
use App\Models\PurchaseOrder;
+use App\Models\Requisition;
use App\Models\Supplier;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CommonBudget;
+use App\Services\ImportBankSupport;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportDossier;
+use App\Services\ImportEstimates;
use App\Services\ImportLandedCosts;
+use App\Services\ImportLegalEstimates;
+use App\Services\ImportLegalRules;
use App\Services\ImportParties;
+use App\Services\ImportTariffCodes;
use App\Services\SupplyPlanning;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
@@ -34,10 +40,15 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
+require_once __DIR__.'/../Support/ImportBankQaFixture.php';
+require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
-$importEstimates = ($argv[2] ?? '') === 'import-estimates';
+$legalAmounts = ($argv[2] ?? '') === 'import-legal-amount';
+$legalRules = $legalAmounts || ($argv[2] ?? '') === 'import-legal';
+$bankSupport = $legalRules || ($argv[2] ?? '') === 'import-bank-support';
+$importEstimates = $bankSupport || ($argv[2] ?? '') === 'import-estimates';
$landedCosts = $importEstimates || ($argv[2] ?? '') === 'landed-costs';
$f = receiptFixture();
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
@@ -192,6 +203,51 @@ if ($landedCosts) {
app(ImportParties::class)->select($partyBuyer, $nativeImport, [...$partyInput, 'operation_key' => (string) Str::uuid(),
'version' => 1, 'instruction_document_id' => $instructionsCorrection->id]);
$nativeEvidenceRecords = [$nativeDoc, $correction, $typedFirst, $typedCorrection, $instructions, $instructionsCorrection];
+ if ($bankSupport) {
+ config(['import-bank-support.qa_enabled' => true]);
+ $bankFixture = importBankQaFixture($partyBuyer, $nativeImport);
+ $bankFirst = app(ImportBankSupport::class)->save($partyBuyer, $nativeImport, $bankFixture['input']);
+ $bankFinalInput = [...$bankFixture['input'], 'operation_key' => (string) Str::uuid(), 'record_key' => $bankFirst->record_key, 'version' => 1,
+ 'submission_document_id' => $bankFixture['documents']['delivery']->id, 'submitted_on' => today()->toDateString(),
+ 'submission_basis' => 'Synthetic bank delivery receipt recorded on the explicit due date'];
+ $bankFinal = app(ImportBankSupport::class)->save($partyBuyer, $nativeImport, $bankFinalInput);
+ $nativeEvidenceRecords = [...$nativeEvidenceRecords, ...array_values($bankFixture['documents'])];
+ }
+ if ($legalRules) {
+ config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
+ supplyGrant($partyBuyer, ['procurement', 'import_prepare', 'import_customs']);
+ $legalService = app(ImportLegalRules::class);
+ $legalDraft = $legalService->save($partyBuyer, importLegalQaInput($legalAmounts ? ['charges' => [importLegalQaCharge()]] : []), importLegalQaFile());
+ $legalPublishInput = ['operation_key' => (string) Str::uuid(), 'record_key' => $legalDraft->record_key, 'version' => 1,
+ 'action' => 'publish', 'reason' => 'Synthetic customs publication for the native recovery fixture'];
+ $legalPublished = $legalService->save($partyBuyer, $legalPublishInput);
+ $legalProposal = app(ImportTariffCodes::class)->save($partyBuyer, $f['r'], ['operation_key' => (string) Str::uuid(), 'version' => 0,
+ 'action' => 'propose', 'requisition_item_id' => $f['r']->items()->sole()->id,
+ 'code' => '1234.56', 'source_reference' => $legalPublished->data['official_reference'].' — '.$legalPublished->data['citation'],
+ 'legal_rule_id' => $legalPublished->id, 'legal_match_code' => '1234', 'legal_origin' => 'Synthetic A', 'legal_sector' => 'Synthetic sector',
+ 'legal_date' => '2026-11-27', 'reason' => 'Synthetic documentary suggestion preserved for recovery']);
+ $nativeEvidenceRecords[] = $legalService->source($partyBuyer, $f['r'], $legalPublished->snapshot['source_id']);
+ if ($legalAmounts) {
+ config(['import-estimates.qa_enabled' => true]);
+ $legalPlanRequest = $f['r']->replicate();
+ $legalPlanRequest->fill(['number' => 'LEGAL-RECOVERY-'.Str::random(10), 'status' => 'draft']);
+ $legalPlanRequest->save();
+ $legalPlanItem = $f['r']->items()->sole()->replicate();
+ $legalPlanItem->requisition_id = $legalPlanRequest->id;
+ $legalPlanItem->save();
+ $legalAmountInput = importLegalQaAmountInput($legalPlanItem->id, $legalPublished->id);
+ $legalAmountInput['bases']['synthetic-duty']['value_minor'] = 10000;
+ $legalAmount = app(ImportLegalEstimates::class)->save($partyBuyer, $legalPlanRequest, $legalAmountInput);
+ $legalNativeInput = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $budget,
+ 'reason' => 'Synthetic native import preparation; only the documented duty applies in this isolated scenario',
+ 'legal_sources' => ['duty' => ['estimate_id' => $legalAmount->id, 'charge_key' => 'synthetic-duty']],
+ 'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable',
+ 'basis' => 'Explicit synthetic recovery assumptions, not a real import or legal exemption',
+ 'subtotal_minor' => $kind === 'duty' ? 750 : null, 'tax_minor' => $kind === 'duty' ? 0 : null,
+ 'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)];
+ $legalNativePlan = app(ImportEstimates::class)->save($partyBuyer, $legalPlanRequest, $legalNativeInput);
+ }
+ }
$evidenceManifest = [];
foreach ($nativeEvidenceRecords as $record) {
$evidence = $record->snapshot['evidence'];
@@ -294,11 +350,54 @@ try {
if ($restoredParty->data['instruction_document_id'] !== $instructionsCorrection->id) {
throw new RuntimeException('Restored instruction identity differs: '.get_debug_type($restoredParty->data['instruction_document_id']).'/'.get_debug_type($instructionsCorrection->id));
}
+ if ($bankSupport) {
+ $bankService = app(ImportBankSupport::class);
+ $bankWorkspace = $bankService->workspace($restoredBuyer, $nativeImport);
+ $bankReplay = $bankService->save($restoredBuyer, $nativeImport, $bankFinalInput);
+ $restoredBank = $bankWorkspace['current']->items()[0];
+ if ($restoredBank['version'] !== 2 || $restoredBank['state'] !== 'documented' || $restoredBank['issues'] !== [] || $bankReplay->id !== $bankFinal->id
+ || $restoredBank['data']['commitment_document_id'] !== $bankFixture['documents']['term']->id
+ || $restoredBank['data']['declaration_document_id'] !== $bankFixture['documents']['declaration']->id
+ || $restoredBank['data']['submission_document_id'] !== $bankFixture['documents']['delivery']->id) {
+ throw new RuntimeException('Bank support relationships, documentary status or original operation replay differ after restore.');
+ }
+ echo json_encode(['bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true,
+ 'bank_support_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
+ }
+ if ($legalRules) {
+ $legalService = app(ImportLegalRules::class);
+ $legalSource = $legalService->source($restoredBuyer, $f['r'], $legalPublished->snapshot['source_id']);
+ $restoredProposal = SupplyRecord::query()->findOrFail($legalProposal->id);
+ $legalReplay = $legalService->save($restoredBuyer, $legalPublishInput);
+ $restoredFrozen = $legalService->freeze($legalPublished->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
+ if ($legalReplay->id !== $legalPublished->id || $restoredProposal->snapshot['legal_rule'] !== $restoredFrozen
+ || $legalSource->snapshot['evidence']['sha256'] !== $restoredFrozen['source_sha256']) {
+ throw new RuntimeException('Legal source, publication replay or frozen buyer context differs after restore.');
+ }
+ echo json_encode(['legal_source_restored' => true, 'legal_published_version_restored' => true,
+ 'legal_buyer_context_restored' => true, 'legal_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
+ if ($legalAmounts) {
+ $restoredRequest = Requisition::query()->findOrFail($legalPlanRequest->id);
+ $amountService = app(ImportLegalEstimates::class);
+ $restoredAmount = $amountService->forPlan($restoredRequest, $legalAmount->id);
+ $amountReplay = $amountService->save($restoredBuyer, $restoredRequest, $legalAmountInput);
+ $nativePlanReplay = app(ImportEstimates::class)->save($restoredBuyer, $restoredRequest, $legalNativeInput);
+ $nativeApproval = app(ImportEstimates::class)->approval($restoredRequest);
+ if ($restoredAmount->snapshot['result']['total_minor'] !== 750 || $amountReplay->id !== $legalAmount->id
+ || $nativePlanReplay->id !== $legalNativePlan->id || $nativeApproval['plan']['budget_amount_minor'] !== 10750
+ || $nativePlanReplay->snapshot['legal_sources']['duty']['estimate_id'] !== $legalAmount->id) {
+ throw new RuntimeException('Calculated legal amount, native cost plan, source provenance or replay differs after restore.');
+ }
+ echo json_encode(['legal_amount_minor_restored' => 750, 'legal_amount_replay_without_effects' => true,
+ 'native_legal_plan_total_minor' => 10750, 'native_legal_plan_source_restored' => true,
+ 'native_legal_plan_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
+ }
+ }
$readFingerprint = $fingerprint($restored, $afterColumns);
if ($readFingerprint !== $after) {
throw new RuntimeException('Native restored read changed tables: '.implode(',', array_keys(array_diff_assoc($readFingerprint, $after))));
}
- echo json_encode(['private_original_versions_restored' => count($nativeEvidenceRecords), 'typed_dossier_versions_restored' => 4,
+ echo json_encode(['private_original_versions_restored' => count($nativeEvidenceRecords), 'typed_dossier_versions_restored' => count(array_filter($nativeEvidenceRecords, fn ($record) => $record->kind === 'import_document')),
'selected_party_versions_restored' => 2, 'source_loss_detected' => true,
'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true,
'evidence_manifest_sha256' => hash('sha256', json_encode($evidenceManifest, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR).PHP_EOL;
diff --git a/tests/Concurrency/import-dossier-worker.php b/tests/Concurrency/import-dossier-worker.php
index 5eb5ef4..9f9b1c2 100644
--- a/tests/Concurrency/import-dossier-worker.php
+++ b/tests/Concurrency/import-dossier-worker.php
@@ -1,11 +1,16 @@
environment('testing') || DB::getDriverName() !== 'pgsql' || DB::con
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
throw new LogicException('Dossier contention requires disposable local PostgreSQL QA.');
}
-config(['import-dossier.qa_enabled' => true]);
+config(['capital-register.qa_enabled' => true, 'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-tariffs.qa_enabled' => true, 'import-legal.qa_enabled' => true]);
Storage::set('local', Storage::build(['driver' => 'local', 'root' => storage_path('framework/testing/dossier-contention-'.$database), 'throw' => true]));
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
+require_once __DIR__.'/../Support/ImportBankQaFixture.php';
+require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
$file = static fn () => UploadedFile::fake()->createWithContent('packing.pdf', "%PDF-1.4\nSynthetic concurrent packing list\n%%EOF");
$partyMode = in_array($argv[2] ?? '', ['prepare-party', 'write-party', 'race-party'], true);
-$recordKind = $partyMode ? 'import_party' : 'import_document';
-$auditAction = $partyMode ? 'import.party_selected' : 'import.document_recorded';
-if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
+$bankMode = in_array($argv[2] ?? '', ['prepare-bank', 'write-bank', 'race-bank'], true);
+$legalMode = in_array($argv[2] ?? '', ['prepare-legal', 'write-legal', 'race-legal'], true);
+$amountMode = in_array($argv[2] ?? '', ['prepare-amount', 'write-amount', 'race-legal-amount'], true);
+$capitalMode = in_array($argv[2] ?? '', ['prepare-capital', 'write-capital', 'race-capital'], true);
+$recordKind = $amountMode ? 'import_legal_amount' : ($legalMode ? 'import_legal_rule' : ($bankMode ? 'import_bank_support' : ($partyMode ? 'import_party' : 'import_document')));
+$auditAction = $amountMode ? 'import.legal_estimate_recorded' : ($legalMode ? 'import.legal_save' : ($bankMode ? 'import.bank_support_recorded' : ($partyMode ? 'import.party_selected' : 'import.document_recorded')));
+if ($capitalMode) {
+ $recordKind = 'capital_register';
+ $auditAction = 'capital.register_recorded';
+}
+if (in_array($argv[2] ?? '', ['prepare', 'prepare-party', 'prepare-bank', 'prepare-legal', 'prepare-amount', 'prepare-capital'], true)) {
$f = receiptFixture();
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
auth()->guard()->setUser($f['issuer']);
@@ -42,7 +57,38 @@ if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
$data = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-PARALLEL',
'issuer_reference' => 'Synthetic supplier', 'reason' => 'Synthetic concurrent original document registration.'];
$actor = $f['issuer'];
- if ($partyMode) {
+ if ($capitalMode) {
+ $data = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project', 'code' => 'CONCURRENT-QA',
+ 'name' => 'Projecto sintético concorrente', 'department_id' => $f['department']->id, 'equipment_id' => null,
+ 'reference' => 'Documento sintético de concorrência', 'state' => 'active', 'reason' => 'Cadastro independente em concorrência real de testes'];
+ if (($argv[3] ?? '') === 'same_version') {
+ $old = app(CapitalRegister::class)->save($actor, $data);
+ $data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1];
+ }
+ } elseif ($amountMode) {
+ supplyGrant($actor, ['procurement', 'import_prepare', 'import_customs']);
+ $draft = app(ImportLegalRules::class)->save($actor, importLegalQaInput(['charges' => [importLegalQaCharge()]]), importLegalQaFile());
+ $rule = app(ImportLegalRules::class)->save($actor, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
+ 'version' => 1, 'action' => 'publish', 'reason' => 'Synthetic reviewed tax definition for concurrent estimates']);
+ $data = importLegalQaAmountInput($f['r']->items()->sole()->id, $rule->id);
+ if (($argv[3] ?? '') === 'same_version') {
+ app(ImportLegalEstimates::class)->save($actor, $f['r'], $data);
+ $data = [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1];
+ }
+ } elseif ($legalMode) {
+ supplyGrant($actor, ['procurement', 'import_prepare', 'import_customs']);
+ $data = importLegalQaInput();
+ if (($argv[3] ?? '') === 'same_version') {
+ $old = app(ImportLegalRules::class)->save($actor, $data, importLegalQaFile());
+ $data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1];
+ }
+ } elseif ($bankMode) {
+ $data = importBankQaFixture($actor, $import)['input'];
+ if (($argv[3] ?? '') === 'same_version') {
+ $old = app(ImportBankSupport::class)->save($actor, $import, $data);
+ $data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1];
+ }
+ } elseif ($partyMode) {
$actor = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
supplyGrant($actor, ['procurement', 'import_prepare']);
auth()->guard()->setUser($actor);
@@ -63,32 +109,35 @@ if (in_array($argv[2] ?? '', ['prepare', 'prepare-party'], true)) {
$data = [...$data, 'operation_key' => (string) Str::uuid(), 'record_key' => $old->record_key, 'version' => 1,
'reference' => 'PACK-CORRECTED'];
}
- echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $actor->id, 'import' => $import->id, 'data' => $data,
+ echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $actor->id, 'import' => $import->id, 'request' => $f['r']->id, 'data' => $data,
'records_before' => SupplyRecord::query()->where('kind', $recordKind)->count(),
'audits_before' => DB::table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', $auditAction)->count(),
'files_before' => count(Storage::disk('local')->allFiles())], JSON_THROW_ON_ERROR);
exit;
}
-if (in_array($argv[2] ?? '', ['write', 'write-party'], true)) {
+if (in_array($argv[2] ?? '', ['write', 'write-party', 'write-bank', 'write-legal', 'write-amount', 'write-capital'], true)) {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_dossier_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
$import = SupplyRecord::query()->findOrFail($input['import']);
- $record = $partyMode ? app(ImportParties::class)->select($actor, $import, $input['data'])
- : app(ImportDossier::class)->record($actor, $import, $input['data'], $file());
+ $record = $capitalMode ? app(CapitalRegister::class)->save($actor, $input['data']) : ($amountMode ? app(ImportLegalEstimates::class)->save($actor, Requisition::query()->findOrFail($input['request']), $input['data']) : ($legalMode ? app(ImportLegalRules::class)->save($actor, $input['data'], importLegalQaFile()) : ($bankMode ? app(ImportBankSupport::class)->save($actor, $import, $input['data'])
+ : ($partyMode ? app(ImportParties::class)->select($actor, $import, $input['data'])
+ : app(ImportDossier::class)->record($actor, $import, $input['data'], $file())))));
echo json_encode(['status' => 200, 'id' => $record->id], JSON_THROW_ON_ERROR);
} catch (HttpExceptionInterface $error) {
echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR);
}
exit;
}
-if (! in_array($argv[2] ?? '', ['race-dossier', 'race-party'], true)) {
+if (! in_array($argv[2] ?? '', ['race-dossier', 'race-party', 'race-bank', 'race-legal', 'race-legal-amount', 'race-capital'], true)) {
throw new InvalidArgumentException('Unknown dossier worker mode.');
}
foreach (['same_operation', 'same_version'] as $scenario) {
- $prepare = new Process([PHP_BINARY, __FILE__, $database, $partyMode ? 'prepare-party' : 'prepare', $scenario], dirname(__DIR__, 2), timeout: 30);
+ $prepareMode = $capitalMode ? 'prepare-capital' : ($amountMode ? 'prepare-amount' : ($legalMode ? 'prepare-legal' : ($bankMode ? 'prepare-bank' : ($partyMode ? 'prepare-party' : 'prepare'))));
+ $writeMode = $capitalMode ? 'write-capital' : ($amountMode ? 'write-amount' : ($legalMode ? 'write-legal' : ($bankMode ? 'write-bank' : ($partyMode ? 'write-party' : 'write'))));
+ $prepare = new Process([PHP_BINARY, __FILE__, $database, $prepareMode, $scenario], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$db = DB::connection();
@@ -101,7 +150,7 @@ foreach (['same_operation', 'same_version'] as $scenario) {
if ($scenario === 'same_version' && $index === 1) {
$workerInput['data']['operation_key'] = (string) Str::uuid();
}
- $worker = new Process([PHP_BINARY, __FILE__, $database, $partyMode ? 'write-party' : 'write', json_encode($workerInput, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
+ $worker = new Process([PHP_BINARY, __FILE__, $database, $writeMode, json_encode($workerInput, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$workers[] = $worker;
$worker->start();
}
@@ -131,11 +180,11 @@ foreach (['same_operation', 'same_version'] as $scenario) {
$records = DB::table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', $recordKind)->count() - $input['records_before'];
$audits = DB::table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', $auditAction)->count() - $input['audits_before'];
$files = count(Storage::disk('local')->allFiles()) - $input['files_before'];
- if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $files !== ($partyMode ? 0 : 1)) {
+ if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $files !== ($capitalMode || $partyMode || $bankMode || $amountMode ? 0 : 1)) {
throw new RuntimeException('Dossier contention must preserve one document version, one original and one audit.');
}
auth()->guard()->setUser(User::query()->findOrFail($input['actor']));
- foreach (SupplyRecord::query()->where('kind', 'import_document')->get() as $record) {
+ foreach (SupplyRecord::query()->whereIn('kind', ['import_document', 'import_legal_source'])->get() as $record) {
app(ImportEvidence::class)->bytes($record);
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
diff --git a/tests/Concurrency/import-legal-corpus-worker.php b/tests/Concurrency/import-legal-corpus-worker.php
new file mode 100644
index 0000000..70b5d12
--- /dev/null
+++ b/tests/Concurrency/import-legal-corpus-worker.php
@@ -0,0 +1,79 @@
+make(Kernel::class)->bootstrap();
+$database = $argv[1] ?? '';
+$root = realpath($argv[3] ?? '');
+if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
+ || DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
+ || $root === false || ! is_dir($root)) {
+ throw new LogicException('Real-source preparation requires a supplied corpus and disposable local PostgreSQL QA.');
+}
+require_once __DIR__.'/../Support/ReceiptFixture.php';
+require_once __DIR__.'/../Support/SupplyFixture.php';
+config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
+$directory = storage_path('framework/testing/legal-corpus-'.$database);
+Storage::set('local', Storage::build(['driver' => 'local', 'root' => $directory, 'throw' => true]));
+$inventory = [];
+foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)) as $entry) {
+ if ($entry->isFile()) {
+ $inventory[] = ['path' => str_replace('\\', '/', substr($entry->getPathname(), strlen($root) + 1)), 'bytes' => $entry->getSize()];
+ }
+}
+usort($inventory, fn ($a, $b) => strcmp($a['path'], $b['path']));
+$patterns = [
+ 'Legislacao/2022/12 Dezembro/series-i/br-series-i-29-12-2022-*.pdf' => 'BR I Série 251, 29/12/2022 — Leis 17/2022 e 19/2022, exemplar integral',
+ 'novas/BR_248_I_SERIE_SUPLEMENTO_2025.pdf' => 'BR I Série 248, suplemento de 29/12/2025 — Leis 7/2025 a 12/2025',
+ 'lei-nr-28-2022-de-29-de-dezembro-lei-cambial.pdf' => 'BR I Série 251, suplemento de 29/12/2022 — Lei 28/2022, Lei Cambial',
+ 'Legislacao/2024/03 */series-i/br-series-i-20-03-2024-*.pdf' => 'BR I Série 57, 20/03/2024 — Aviso 3/GBM/2024, normas e procedimentos cambiais',
+];
+$f = receiptFixture();
+supplyGrant($f['issuer'], ['procurement', 'import_customs']);
+auth()->guard()->setUser($f['issuer']);
+$fingerprint = fn () => [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
+$before = $fingerprint();
+$sources = [];
+try {
+ foreach ($patterns as $pattern => $reference) {
+ $matches = glob(str_replace('\\', '/', $root).'/'.$pattern);
+ if ($matches === false || count($matches) !== 1) {
+ throw new RuntimeException('The selected corpus reference is missing or ambiguous: '.$reference);
+ }
+ $path = $matches[0];
+ $checksum = hash_file('sha256', $path);
+ $input = ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => 0,
+ 'official_reference' => $reference, 'reason' => 'Fonte oficial real partilhada pelo proprietário; preparação exclusivamente em empresa e base QA sintéticas, sem publicar regras'];
+ $file = new UploadedFile($path, basename($path), 'application/pdf', UPLOAD_ERR_OK, true);
+ $record = app(ImportLegalRules::class)->save($f['issuer'], $input, $file);
+ $resolved = app(ImportLegalRules::class)->source($f['issuer'], $f['r'], $record->id);
+ if (hash('sha256', app(ImportEvidence::class)->bytes($resolved)) !== $checksum || hash_file('sha256', $path) !== $checksum
+ || app(ImportLegalRules::class)->save($f['issuer'], $input, $file)->id !== $record->id) {
+ throw new RuntimeException('The original, private source or idempotent replay differs.');
+ }
+ $sources[] = ['reference' => $reference, 'relative_path' => str_replace('\\', '/', substr($path, strlen($root) + 1)),
+ 'bytes' => filesize($path), 'sha256' => $checksum, 'native_authorized_download_verified' => true];
+ }
+ if ($fingerprint() !== $before || SupplyRecord::query()->where('kind', 'import_legal_rule')->exists()) {
+ throw new RuntimeException('Registering sources must not publish rules or create financial/stock effects.');
+ }
+ echo json_encode(['shared_corpus_files_inventoried' => count($inventory), 'inventory_metadata_sha256' => hash('sha256', json_encode($inventory, JSON_THROW_ON_ERROR)),
+ 'real_official_sources_prepared' => $sources, 'rules_published' => 0, 'originals_unchanged' => true,
+ 'financial_and_stock_unchanged' => true, 'synthetic_qa_organization_only' => true], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
+} finally {
+ $resolved = realpath($directory);
+ $boundary = realpath(storage_path('framework/testing'));
+ if ($resolved !== false && $boundary !== false && str_starts_with(str_replace('\\', '/', $resolved), str_replace('\\', '/', $boundary).'/legal-corpus-compras_receipts_test_')) {
+ File::deleteDirectory($resolved);
+ }
+}
diff --git a/tests/Concurrency/import-legal-http-worker.php b/tests/Concurrency/import-legal-http-worker.php
new file mode 100644
index 0000000..7233d87
--- /dev/null
+++ b/tests/Concurrency/import-legal-http-worker.php
@@ -0,0 +1,216 @@
+make(Kernel::class)->bootstrap();
+$database = $argv[1] ?? '';
+$corpus = realpath($argv[3] ?? '');
+$candidateRelative = $argv[4] ?? '';
+$candidateHash = $argv[5] ?? '';
+$reviewMode = ($argv[2] ?? '') === 'legal-review';
+if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
+ || DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
+ || $corpus === false || ! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative)
+ || ! preg_match('/^[a-f0-9]{64}$/D', $candidateHash) || hash_file('sha256', base_path($candidateRelative.'/manifest.json')) !== $candidateHash) {
+ throw new LogicException('HTTP source review requires a supplied corpus, validated private candidate and disposable PostgreSQL.');
+}
+require_once __DIR__.'/../Support/ReceiptFixture.php';
+require_once __DIR__.'/../Support/SupplyFixture.php';
+require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
+require_once __DIR__.'/../Support/ImportBankQaFixture.php';
+$files = glob(str_replace('\\', '/', $corpus).'/Legislacao/2022/12 Dezembro/series-i/br-series-i-29-12-2022-*.pdf');
+if ($files === false || count($files) !== 1 || filesize($files[0]) <= 2097152) {
+ throw new LogicException('Select the complete shared official journal, not a small extracted example.');
+}
+$path = $files[0];
+$originalHash = hash_file('sha256', $path);
+$f = receiptFixture();
+supplyGrant($f['issuer'], ['procurement', 'import_customs']);
+auth()->guard()->setUser($f['issuer']);
+$password = Str::random(48);
+$f['issuer']->forceFill(['password' => Hash::make($password)])->save();
+$fingerprint = fn () => [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
+$before = $fingerprint();
+$directory = storage_path('framework/testing/legal-http-'.$database);
+foreach (['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private'] as $relative) {
+ File::ensureDirectoryExists($directory.'/'.$relative);
+}
+File::copyDirectory(base_path($candidateRelative), $directory.'/public/build');
+$socket = stream_socket_server('tcp://127.0.0.1:0', $errorCode, $error);
+if ($socket === false) {
+ throw new RuntimeException('Unable to reserve a loopback QA port.');
+}
+$address = stream_socket_get_name($socket, false);
+fclose($socket);
+$port = substr($address, strrpos($address, ':') + 1);
+$url = 'http://'.($reviewMode ? 'localhost' : '127.0.0.1').':'.$port;
+$server = new Process([PHP_BINARY, '-d', 'upload_max_filesize=64M', '-d', 'post_max_size=70M', '-S', '127.0.0.1:'.$port,
+ 'tests/Support/import-legal-http-router.php'], base_path(), ['APP_ENV' => 'testing', 'APP_DEBUG' => 'false',
+ 'APP_URL' => $url, 'ASSET_URL' => $url, 'SGC_LEGAL_HTTP_QA_ROOT' => $directory, 'SGC_LEGAL_HTTP_QA_PORT' => $port,
+ 'SESSION_COOKIE' => 'sgc_legal_http_'.substr($database, -12), 'SESSION_DRIVER' => 'file'], timeout: null);
+$client = new Client(['base_uri' => $url, 'cookies' => $cookies = new CookieJar, 'http_errors' => false, 'allow_redirects' => false,
+ 'timeout' => 20, 'expect' => false]);
+$result = null;
+try {
+ $server->start();
+ $ready = false;
+ $deadline = microtime(true) + 10;
+ do {
+ try {
+ $ready = $client->get('/up')->getStatusCode() === 200;
+ } catch (ConnectException) {
+ usleep(50000);
+ }
+ } while (! $ready && $server->isRunning() && microtime(true) < $deadline);
+ if (! $ready || $client->get('/login')->getStatusCode() !== 200) {
+ throw new RuntimeException('Private native HTTP login page unavailable.');
+ }
+ $token = fn () => rawurldecode($cookies->getCookieByName('XSRF-TOKEN')?->getValue() ?? '');
+ if ($token() === '') {
+ throw new RuntimeException('Native session did not issue a CSRF cookie.');
+ }
+ $login = $client->post('/login', ['headers' => ['Accept' => 'application/json', 'X-XSRF-TOKEN' => $token()],
+ 'form_params' => ['email' => $f['issuer']->email, 'password' => $password]]);
+ if (! in_array($login->getStatusCode(), [200, 302, 303], true)) {
+ throw new RuntimeException('Native synthetic Fortify login failed: '.$login->getStatusCode());
+ }
+ $route = '/requisicoes/'.$f['r']->id.'/base-legal';
+ $headers = ['Accept' => 'application/json', 'X-XSRF-TOKEN' => $token(), 'Referer' => $url.$route];
+ $negative = $client->post($route, ['headers' => ['Accept' => 'application/json'], 'json' => ['action' => 'source']]);
+ if ($negative->getStatusCode() !== 419) {
+ throw new RuntimeException('Native HTTP source requests must require CSRF: '.$negative->getStatusCode());
+ }
+ $input = ['operation_key' => (string) Str::uuid(), 'action' => 'source', 'version' => '0',
+ 'official_reference' => 'BR I Série 251 de 29/12/2022 — exemplar integral real partilhado',
+ 'reason' => 'Ensaio HTTP estritamente QA com exemplar oficial real, empresa e conta sintéticas; sem publicar regras'];
+ foreach ([1, 2] as $attempt) {
+ $multipart = array_map(fn ($name) => ['name' => $name, 'contents' => $input[$name]], array_keys($input));
+ $multipart[] = ['name' => 'file', 'contents' => fopen($path, 'rb'), 'filename' => basename($path), 'headers' => ['Content-Type' => 'application/pdf']];
+ $response = $client->post($route, ['headers' => $headers, 'multipart' => $multipart]);
+ if (! in_array($response->getStatusCode(), [302, 303], true)) {
+ throw new RuntimeException('Native large-source multipart upload failed: '.$response->getStatusCode());
+ }
+ }
+ $initial = $client->get($route);
+ if ($initial->getStatusCode() !== 200 || ! preg_match('~~s', (string) $initial->getBody(), $initialData)) {
+ throw new RuntimeException('Native source page bootstrap unavailable: '.$initial->getStatusCode());
+ }
+ $initialPage = json_decode($initialData[1], true, 64, JSON_THROW_ON_ERROR);
+ $page = $client->get($route, ['headers' => ['X-Inertia' => 'true', 'X-Inertia-Version' => $initialPage['version'], 'Accept' => 'text/html, application/xhtml+xml']]);
+ if ($page->getStatusCode() !== 200 || ! str_contains($page->getHeaderLine('Content-Type'), 'application/json')) {
+ throw new RuntimeException('Native Inertia page did not accept its bootstrap version: '.$page->getStatusCode());
+ }
+ $props = json_decode((string) $page->getBody(), true, 64, JSON_THROW_ON_ERROR)['props'] ?? [];
+ $source = SupplyRecord::query()->where('kind', 'import_legal_source')->sole();
+ $download = $client->get($route.'/fontes/'.$source->id);
+ $guest = new Client(['base_uri' => $url, 'http_errors' => false, 'allow_redirects' => false, 'timeout' => 10]);
+ $anonymous = $guest->get($route.'/fontes/'.$source->id, ['headers' => ['Accept' => 'application/json']]);
+ if ($page->getStatusCode() !== 200 || ($props['sources']['total'] ?? null) !== 1 || ($props['rules']['total'] ?? null) !== 0
+ || $download->getStatusCode() !== 200 || hash('sha256', (string) $download->getBody()) !== $originalHash
+ || hash_file('sha256', $path) !== $originalHash || $anonymous->getStatusCode() !== 401
+ || DB::table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', 'import.legal_source_recorded')->count() !== 1
+ || $fingerprint() !== $before) {
+ throw new RuntimeException('Native source scope, large bytes, idempotence, authentication or financial preservation not demonstrated.');
+ }
+ DB::table('organization_memberships')->where('user_id', $f['issuer']->id)->delete();
+ $revoked = $client->get($route.'/fontes/'.$source->id, ['headers' => ['Accept' => 'application/json']]);
+ if ($revoked->getStatusCode() !== 403) {
+ throw new RuntimeException('Native download did not revalidate revoked QA authority.');
+ }
+ $result = ['native_legal_http_login' => true, 'csrf_required' => true, 'large_multipart_upload_bytes' => filesize($path),
+ 'original_sha256' => $originalHash, 'original_unchanged' => true, 'exact_native_download' => true, 'one_source_one_audit_after_replay' => true,
+ 'guest_status' => 401, 'revoked_status' => 403, 'rules_published' => 0, 'financial_stock_unchanged' => true,
+ 'private_upload_limit' => '64M', 'private_post_limit' => '70M', 'global_php_config_unchanged' => true];
+ if ($reviewMode) {
+ // Existing factory password is confined to guarded, disposable synthetic QA identities.
+ $reviewer = $f['otherReceiver'];
+ supplyGrant($reviewer, ['procurement', 'requester', 'import_read', 'import_prepare', 'import_customs']);
+ config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true, 'import-estimates.qa_enabled' => true,
+ 'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-readiness.qa_enabled' => true]);
+ Storage::set('local', Storage::build(['driver' => 'local', 'root' => $directory.'/storage/app/private', 'throw' => true]));
+ $author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
+ $approver = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
+ supplyGrant($author, ['finance']);
+ supplyGrant($approver, ['finance']);
+ auth()->guard()->setUser($author);
+ $budget = app(CommonBudget::class)->for($author)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
+ 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 1000000, 'reason' => 'Dotação estritamente sintética da revisão nativa']);
+ auth()->guard()->setUser($approver);
+ app(CommonBudget::class)->for($approver)->approve($budget);
+ auth()->guard()->setUser($reviewer);
+ $draftRequest = $f['r']->replicate();
+ $draftRequest->fill(['number' => 'VISUAL-LEGAL-'.Str::random(8), 'requester_id' => $reviewer->id, 'status' => 'draft']);
+ $draftRequest->save();
+ $draftItem = $f['r']->items()->sole()->replicate();
+ $draftItem->requisition_id = $draftRequest->id;
+ $draftItem->save();
+ $legalDraft = app(ImportLegalRules::class)->save($reviewer, importLegalQaInput(['title' => 'Regra de ensaio — dados fictícios', 'charges' => [importLegalQaCharge()]]), importLegalQaFile());
+ $legalRule = app(ImportLegalRules::class)->save($reviewer, ['operation_key' => (string) Str::uuid(), 'record_key' => $legalDraft->record_key,
+ 'version' => 1, 'action' => 'publish', 'reason' => 'Publicação de dados estritamente fictícios para revisão nativa isolada']);
+ $amountInput = importLegalQaAmountInput($draftItem->id, $legalRule->id);
+ $amountInput['bases']['synthetic-duty']['value_minor'] = 10000;
+ $amount = app(ImportLegalEstimates::class)->save($reviewer, $draftRequest, $amountInput);
+ app(ImportEstimates::class)->save($reviewer, $draftRequest, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $budget,
+ 'reason' => 'Plano fictício apenas com direitos neste cenário; sem reserva ou submissão', 'legal_sources' => ['duty' => ['estimate_id' => $amount->id, 'charge_key' => 'synthetic-duty']],
+ 'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => $kind === 'duty' ? 'known' : 'not_applicable',
+ 'basis' => 'Pressuposto estritamente sintético desta revisão, não isenção real', 'subtotal_minor' => $kind === 'duty' ? 750 : null,
+ 'tax_minor' => $kind === 'duty' ? 0 : null, 'total_minor' => $kind === 'duty' ? 750 : null], BudgetImportEstimate::KINDS)]);
+ $import = app(SupplyPlanning::class)->save($reviewer, 'import', supplyInput(['purchase_order_id' => $f['order']->id, 'purpose' => 'internal',
+ 'jurisdiction' => 'Âmbito fictício QA', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Regime fictício QA']));
+ $bank = importBankQaFixture($reviewer, $import);
+ app(ImportBankSupport::class)->save($reviewer, $import, $bank['input']);
+ $stopFile = $directory.'/stop';
+ echo json_encode(['private_review_running' => true, 'url' => $url, 'stop_file' => $stopFile,
+ 'synthetic_user' => $reviewer->email, 'draft_request' => $draftRequest->id, 'import' => $import->id,
+ 'legal_url' => $url.'/requisicoes/'.$draftRequest->id.'/base-legal?'.http_build_query(['code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27']),
+ 'private_candidate_manifest' => $candidateHash, 'pilot_assets_changed' => false], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
+ $deadline = microtime(true) + 3600;
+ while (! is_file($stopFile) && microtime(true) < $deadline) {
+ if (! $server->isRunning()) {
+ throw new RuntimeException('Private native review server stopped unexpectedly.');
+ }
+ $server->getIncrementalOutput();
+ $server->getIncrementalErrorOutput();
+ usleep(100000);
+ }
+ $result['private_native_review_stopped'] = true;
+ }
+} catch (Throwable $error) {
+ $summary = 'No native exception log.';
+ $log = $directory.'/storage/logs/laravel.log';
+ if (is_file($log) && preg_match_all('/testing\.ERROR: ([^\r\n]+)/', file_get_contents($log), $matches) && $matches[1] !== []) {
+ $summary = substr(str_replace($password, '[synthetic credential redacted]', end($matches[1])), 0, 300);
+ }
+ throw new RuntimeException($error->getMessage().' Native diagnostic: '.$summary);
+} finally {
+ $server->stop();
+ $resolved = realpath($directory);
+ $boundary = realpath(storage_path('framework/testing'));
+ if ($resolved !== false && $boundary !== false && str_replace('\\', '/', $resolved) === str_replace('\\', '/', $boundary).'/legal-http-'.$database) {
+ File::deleteDirectory($resolved);
+ }
+ if ($result !== null) {
+ echo json_encode([...$result, 'private_http_server_stopped' => true, 'private_http_root_removed' => ! is_dir($directory)], JSON_THROW_ON_ERROR).PHP_EOL;
+ }
+}
diff --git a/tests/Feature/CapitalRegisterTest.php b/tests/Feature/CapitalRegisterTest.php
new file mode 100644
index 0000000..14d89b9
--- /dev/null
+++ b/tests/Feature/CapitalRegisterTest.php
@@ -0,0 +1,135 @@
+ true]);
+ $this->withoutVite();
+ $this->f = receiptFixture();
+ $this->actingAs($this->f['issuer']);
+ $this->input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
+ 'type' => 'project', 'code' => 'PRJ-QA', 'name' => 'Projecto estritamente sintético',
+ 'department_id' => $this->f['department']->id, 'equipment_id' => null,
+ 'reference' => 'Documento fictício para cadastro independente de Compras', 'state' => 'active',
+ 'reason' => 'Preparação de referência sintética para testes de compras'];
+});
+
+test('own project register versions preserves identity and replay without financial or stock effects', function () {
+ $service = app(CapitalRegister::class);
+ $before = [];
+ foreach (['budget_entries', 'stock_movements', 'invoices', 'purchase_orders'] as $table) {
+ $before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
+ }
+ $first = $service->save($this->f['issuer'], $this->input);
+ expect($first->version)->toBe(1)->and($first->snapshot['source_system'])->toBe('compras');
+ expect($service->save($this->f['issuer'], $this->input)->id)->toBe($first->id);
+ $archive = [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1, 'state' => 'archived'];
+ $second = $service->save($this->f['issuer'], $archive);
+ expect($second->version)->toBe(2)->and($second->state)->toBe('archived')
+ ->and($first->fresh()->state)->toBe('active')->and(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(2);
+ foreach ($before as $table => $rows) {
+ expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
+ }
+ expect(fn () => $service->save($this->f['issuer'], [...$archive, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
+ expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(ValidationException::class);
+});
+
+test('register rejects reused operation content and renaming a permanent code', function () {
+ $service = app(CapitalRegister::class);
+ $first = $service->save($this->f['issuer'], $this->input);
+ expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'name' => 'Conteúdo diferente']))->toThrow(HttpException::class);
+ expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $first->record_key, 'version' => 1, 'code' => 'OUTRO']))->toThrow(ValidationException::class);
+ expect(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(1);
+});
+
+test('asset references reuse a physical equipment identity and reject duplicate or removed links', function () {
+ $level = CriticalityLevel::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'created_at' => now(), 'code' => 'QA', 'name' => 'Ensaio', 'criteria' => 'Só fixture sintética', 'is_critical' => false]);
+ $equipment = Equipment::query()->create(['tenant_id' => $this->f['tenant']->id, 'created_by' => $this->f['issuer']->id, 'code' => 'EQ-QA', 'description' => 'Equipamento físico sintético',
+ 'area' => 'Área sintética', 'status' => 'active', 'department_id' => $this->f['department']->id, 'criticality_level_id' => $level->id]);
+ $input = [...$this->input, 'type' => 'asset', 'code' => 'ASSET-QA', 'equipment_id' => $equipment->id];
+ $service = app(CapitalRegister::class);
+ $first = $service->save($this->f['issuer'], $input);
+ expect($first->snapshot['equipment']['id'])->toBe($equipment->id)->and(Equipment::query()->count())->toBe(1);
+ expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => 'OTHER-QA']))->toThrow(ValidationException::class);
+ expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1, 'equipment_id' => null]))->toThrow(ValidationException::class);
+ $this->get('/projectos-imobilizado?history='.$first->record_key)->assertOk()->assertInertia(fn (Assert $page) => $page->has('history.data', 1));
+ expect(fn () => $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'code' => ['invalid']]))->toThrow(ValidationException::class);
+});
+
+test('native register page is encrypted private paginated and gated off outside QA', function () {
+ app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
+ $this->get('/projectos-imobilizado')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
+ ->assertViewHas('page', fn (array $page) => $page['encryptHistory'] === true)
+ ->assertInertia(fn (Assert $page) => $page->component('equipment/capital-register')
+ ->has('records.data', 1)->where('records.data.0.data.code', 'PRJ-QA')->where('canManage', true));
+ config(['capital-register.qa_enabled' => false]);
+ $this->get('/projectos-imobilizado')->assertStatus(503);
+});
+
+test('native register revalidates operator and hides foreign department identity without creating versions', function () {
+ $service = app(CapitalRegister::class);
+ $first = $service->save($this->f['issuer'], $this->input);
+ $this->actingAs($this->f['receiver']);
+ expect(fn () => $service->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
+ $this->actingAs($this->f['issuer']);
+ $other = receiptFixture();
+ $this->actingAs($other['issuer']);
+ $this->get('/projectos-imobilizado')->assertOk()->assertInertia(fn (Assert $page) => $page->has('records.data', 0));
+ $this->post('/projectos-imobilizado', [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1])->assertNotFound();
+ $this->actingAs($this->f['issuer']);
+ expect(SupplyRecord::query()->where('kind', 'capital_register')->count())->toBe(1);
+});
+
+test('line destination freezes the chosen project version and preserves it after archival without financial effects', function () {
+ $register = app(CapitalRegister::class);
+ $source = $register->save($this->f['issuer'], $this->input);
+ $this->f['r']->update(['status' => 'draft']);
+ $item = $this->f['r']->items()->firstOrFail();
+ $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id,
+ 'capital_id' => $source->id, 'reason' => 'Escolha de destino sintético da linha da requisição'];
+ $service = app(CapitalAssignments::class);
+ $first = $service->save($this->f['issuer'], $this->f['r'], $input);
+ expect($first->state)->toBe('linked')->and($service->save($this->f['issuer'], $this->f['r'], $input)->id)->toBe($first->id);
+ $register->save($this->f['issuer'], [...$this->input, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $source->record_key, 'version' => 1, 'state' => 'archived', 'name' => 'Designação posterior sintética']);
+ $frozen = $service->freezeForItems($this->f['issuer'], [$item->id]);
+ expect($frozen[$item->id]['snapshot']['source']['version'])->toBe(1)
+ ->and($frozen[$item->id]['snapshot']['source']['data']['name'])->toBe($this->input['name']);
+ $this->get('/requisicoes/'.$this->f['r']->id.'/projectos-imobilizado')->assertOk()
+ ->assertInertia(fn (Assert $page) => $page->component('requisitions/capital-assignments')->where('canWrite', true)->has('choices.data', 0)->has('current', 1));
+ expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(ModelNotFoundException::class);
+ expect(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('stock_movements')->count())->toBe(0);
+ $item->update(['description' => 'Artigo alterado após a escolha']);
+ expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
+ $cleared = $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'capital_id' => null]);
+ expect($cleared->state)->toBe('cleared')->and($service->freezeForItems($this->f['issuer'], [$item->id]))->toBe([])
+ ->and($first->fresh()->state)->toBe('linked');
+});
+
+test('submitted requisitions reject new line destinations and stale versions do not replace choices', function () {
+ $source = app(CapitalRegister::class)->save($this->f['issuer'], $this->input);
+ $item = $this->f['r']->items()->firstOrFail();
+ $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $item->id, 'capital_id' => $source->id,
+ 'reason' => 'Escolha documental sintética preservando decisões anteriores'];
+ $service = app(CapitalAssignments::class);
+ expect(fn () => $service->save($this->f['issuer'], $this->f['r'], $input))->toThrow(HttpException::class);
+ $this->f['r']->update(['status' => 'draft']);
+ $service->save($this->f['issuer'], $this->f['r'], $input);
+ expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'capital_id' => null]))->toThrow(HttpException::class);
+ config(['capital-register.qa_enabled' => false]);
+ expect(fn () => $service->freezeForItems($this->f['issuer'], [$item->id]))->toThrow(HttpException::class);
+ expect(SupplyRecord::query()->where('kind', 'capital_assignment')->count())->toBe(1);
+});
diff --git a/tests/Feature/ImportBankSupportTest.php b/tests/Feature/ImportBankSupportTest.php
new file mode 100644
index 0000000..c353dc7
--- /dev/null
+++ b/tests/Feature/ImportBankSupportTest.php
@@ -0,0 +1,144 @@
+record($test->f['issuer'], $test->import, ['operation_key' => (string) Str::uuid(), 'type' => $type,
+ 'record_key' => $previous?->record_key, 'version' => $previous?->version ?? 0, 'reference' => $reference,
+ 'issuer_reference' => 'Synthetic issuing entity', 'issued_on' => today()->toDateString(), 'notes' => 'Synthetic bank-support evidence only.',
+ 'reason' => 'Preservar original sintético para o acompanhamento bancário'],
+ UploadedFile::fake()->createWithContent('bank-support.pdf', "%PDF-1.4\nSynthetic original ".$reference."\n%%EOF"));
+}
+
+beforeEach(function () {
+ config(['import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true]);
+ Storage::fake('local');
+ $this->withoutVite();
+ $this->f = receiptFixture();
+ supplyGrant($this->f['issuer'], ['procurement', 'import_prepare']);
+ $this->actingAs($this->f['issuer']);
+ $this->import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
+ 'purchase_order_id' => $this->f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic bank-support jurisdiction',
+ 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime']));
+ $this->term = bankSupportOriginal($this, 'bank_commitment', 'BANK-TERM-QA');
+ $this->declaration = bankSupportOriginal($this, 'customs_declaration', 'DU-QA');
+ $this->invoice = bankSupportOriginal($this, 'commercial_invoice', 'INVOICE-QA-1');
+ $this->input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
+ 'commitment_document_id' => $this->term->id, 'declaration_document_id' => $this->declaration->id,
+ 'support_document_ids' => [$this->invoice->id], 'requirements_known' => true,
+ 'required_support_types' => ['commercial_invoice'], 'required_support_counts' => ['commercial_invoice' => 2],
+ 'requirements_basis' => 'Synthetic bank request explicitly asks for two commercial invoices',
+ 'submission_document_id' => null, 'submission_basis' => null, 'submitted_on' => null,
+ 'due_on' => today()->subDay()->toDateString(), 'deadline_basis' => 'Explicit synthetic bank letter deadline, not a legal default',
+ 'reason' => 'Acompanhamento estritamente documental e sintético'];
+});
+
+test('bank support preserves exact requested counts versions and original delivery evidence without payment or JUE effects', function () {
+ $service = app(ImportBankSupport::class);
+ $before = [DB::table('stock_movements')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), $this->import->fresh()->getAttributes()];
+ $first = $service->save($this->f['issuer'], $this->import, $this->input);
+ expect($first->state)->toBe('tracking')->and($service->save($this->f['issuer'], $this->import, $this->input)->id)->toBe($first->id)
+ ->and(implode(' ', $service->issues($first)))->toContain('Factura comercial (1)', 'Prazo documental ultrapassado', 'não demonstra a entrega');
+ expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
+ $invoice = bankSupportOriginal($this, 'commercial_invoice', 'INVOICE-QA-2');
+ $secondInput = [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1,
+ 'support_document_ids' => [$this->invoice->id, $invoice->id]];
+ $ready = $service->save($this->f['issuer'], $this->import, $secondInput);
+ expect($ready->state)->toBe('ready')->and(implode(' ', $service->issues($ready)))->toContain('Prazo documental ultrapassado');
+ $delivery = bankSupportOriginal($this, 'bank_support', 'BANK-DELIVERY-QA-1');
+ $thirdInput = [...$secondInput, 'operation_key' => (string) Str::uuid(), 'version' => 2,
+ 'submission_document_id' => $delivery->id, 'submission_basis' => 'Synthetic documentary delivery receipt; no live bank action', 'submitted_on' => today()->toDateString()];
+ $documented = $service->save($this->f['issuer'], $this->import, $thirdInput);
+ expect($documented->state)->toBe('documented')->and($service->issues($documented))->toBe(['Entrega documentada após o prazo indicado.'])
+ ->and($documented->snapshot['bank_transfer_executed'])->toBeFalse()->and($documented->snapshot['jue_submission_executed'])->toBeFalse()
+ ->and($documented->snapshot['bank_compliance_certified'])->toBeFalse();
+ $correction = bankSupportOriginal($this, 'bank_support', 'BANK-DELIVERY-QA-2', $delivery);
+ expect(implode(' ', $service->issues($documented)))->toContain('foi corrigido', 'Prazo documental ultrapassado');
+ $fourth = $service->save($this->f['issuer'], $this->import, [...$thirdInput, 'operation_key' => (string) Str::uuid(), 'version' => 3, 'submission_document_id' => $correction->id]);
+ expect($fourth->version)->toBe(4)->and($service->issues($fourth))->toBe(['Entrega documentada após o prazo indicado.'])->and($first->fresh()->state)->toBe('tracking')
+ ->and([DB::table('stock_movements')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), $this->import->fresh()->getAttributes()])->toBe($before);
+});
+
+test('unknown bank requirements and deadlines stay unknown and cannot silently become a completed or zero-day obligation', function () {
+ $record = app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input,
+ 'requirements_known' => false, 'required_support_types' => [], 'required_support_counts' => [], 'declaration_document_id' => null,
+ 'due_on' => null, 'deadline_basis' => null]);
+ expect($record->state)->toBe('tracking')->and($record->data['due_on'])->toBeNull()
+ ->and(implode(' ', app(ImportBankSupport::class)->issues($record)))->toContain('desconhecidos', 'Prazo documental ainda por indicar');
+ expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input, 'deadline_basis' => ' ']))->toThrow(HttpException::class);
+ expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input, 'required_support_counts' => []]))->toThrow(HttpException::class);
+ $delivery = bankSupportOriginal($this, 'bank_support', 'DELIVERY-UNKNOWN-DATE');
+ expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input,
+ 'submission_document_id' => $delivery->id, 'submission_basis' => 'Synthetic delivery evidence with no event date']))->toThrow(HttpException::class);
+ expect(fn () => app(ImportBankSupport::class)->save($this->f['issuer'], $this->import, [...$this->input,
+ 'submission_document_id' => $delivery->id, 'submission_basis' => 'Synthetic delivery cannot be recorded as already occurred tomorrow',
+ 'submitted_on' => today()->addDay()->toDateString()]))->toThrow(ValidationException::class);
+});
+
+test('bank follow-up rejects foreign documents wrong types stale versions and withdrawn write authority', function () {
+ $service = app(ImportBankSupport::class);
+ expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'commitment_document_id' => $this->invoice->id]))->toThrow(HttpException::class);
+ $record = $service->save($this->f['issuer'], $this->import, $this->input);
+ expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'record_key' => $record->record_key, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
+ $other = receiptFixture();
+ supplyGrant($other['issuer'], ['procurement', 'import_prepare']);
+ $this->actingAs($other['issuer']);
+ $otherImport = app(SupplyPlanning::class)->save($other['issuer'], 'import', supplyInput([
+ 'purchase_order_id' => $other['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Other synthetic jurisdiction',
+ 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime']));
+ $otherDocument = bankSupportOriginal((object) ['f' => $other, 'import' => $otherImport], 'bank_commitment', 'OTHER-BANK-TERM');
+ expect(fn () => $service->save($other['issuer'], $this->import, $this->input))->toThrow(ModelNotFoundException::class);
+ $this->actingAs($this->f['issuer']);
+ expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
+ 'commitment_document_id' => $otherDocument->id]))->toThrow(ModelNotFoundException::class);
+ DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
+ expect(fn () => $service->save($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
+});
+
+test('native bank entry consultation and full-scope CSV share source data permissions and formula-safe references', function () {
+ $term = bankSupportOriginal($this, 'bank_commitment', '=SYNTHETIC-REFERENCE');
+ $input = [...$this->input, 'commitment_document_id' => $term->id];
+ $url = '/compras/importacoes/'.$this->import->id.'/suporte-bancario';
+ $this->post($url, $input)->assertRedirect();
+ $record = SupplyRecord::query()->where('kind', 'import_bank_support')->where('operation_key', $input['operation_key'])->firstOrFail();
+ $this->post($url, $input)->assertRedirect();
+ expect(SupplyRecord::query()->where('kind', 'import_bank_support')->count())->toBe(1);
+ $tables = ['users', 'supply_records', 'audit_logs', 'budget_entries', 'invoices', 'stock_movements'];
+ $before = [];
+ foreach ($tables as $table) {
+ $before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
+ }
+ $this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
+ ->assertInertia(fn (AssertableInertia $page) => $page->component('supply/import-bank-support')
+ ->where('canWrite', true)->where('current.data.0.id', $record->id)->where('current.data.0.data.required_support_counts.commercial_invoice', 2)
+ ->missing('current.data.0.snapshot.documents.0.path'));
+ $csv = $this->get($url.'.csv?bank_current_page=999999')->assertOk()->assertDownload();
+ expect($csv->streamedContent())->toContain("'=SYNTHETIC-REFERENCE", 'Factura comercial: 2', 'Prazo documental ultrapassado')
+ ->not->toContain('import-dossier/', 'account_identifier');
+ foreach ($tables as $table) {
+ expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($before[$table]);
+ }
+ $viewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
+ supplyGrant($viewer, ['finance']);
+ $this->actingAs($viewer)->get($url)->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('canWrite', false));
+ $this->post($url, [...$input, 'operation_key' => (string) Str::uuid()])->assertForbidden();
+ config(['import-bank-support.qa_enabled' => false]);
+ $this->get($url)->assertStatus(503);
+});
diff --git a/tests/Feature/ImportEstimatesTest.php b/tests/Feature/ImportEstimatesTest.php
index f5b1c43..06bc544 100644
--- a/tests/Feature/ImportEstimatesTest.php
+++ b/tests/Feature/ImportEstimatesTest.php
@@ -9,6 +9,8 @@ use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ImportEstimates;
use App\Services\ImportLandedCosts;
+use App\Services\ImportLegalEstimates;
+use App\Services\ImportLegalRules;
use App\Services\ImportTariffCodes;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
@@ -24,6 +26,7 @@ use Tempo\Finance\Budget\BudgetImportEstimate;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
+require_once __DIR__.'/../Support/ImportLegalQaFixture.php';
beforeEach(function () {
if (! class_exists(BudgetImportEstimate::class)) {
@@ -54,6 +57,58 @@ beforeEach(function () {
'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS)];
});
+test('native import cost assumptions reuse exact legal charges once with explicit tax split and immutable source provenance', function () {
+ config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
+ Storage::fake('local');
+ supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
+ $rules = app(ImportLegalRules::class);
+ $draft = $rules->save($this->f['issuer'], importLegalQaInput(['charges' => [[
+ 'key' => 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem', 'rate_percent' => '7.5',
+ 'specific_minor' => null, 'quantity_unit' => null, 'basis_reference' => 'Synthetic explicit customs-value basis',
+ ]]]), importLegalQaFile());
+ $rule = $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
+ 'version' => 1, 'action' => 'publish', 'reason' => 'Synthetic rate publication for native estimate integration']);
+ $legal = app(ImportLegalEstimates::class)->save($this->f['issuer'], $this->draft, ['operation_key' => (string) Str::uuid(), 'version' => 0,
+ 'requisition_item_id' => $this->draft->items()->sole()->id, 'rule_id' => $rule->id, 'match_code' => '1234', 'origin' => 'Synthetic A',
+ 'sector' => 'Synthetic sector', 'date' => '2026-11-27', 'bases' => ['synthetic-duty' => ['value_minor' => 10000,
+ 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic declared customs valuation']], 'reason' => 'Synthetic exact charge adoption fixture']);
+ $input = $this->input;
+ foreach ($input['components'] as &$component) {
+ $component['status'] = $component['kind'] === 'duty' ? 'known' : 'not_applicable';
+ $component['basis'] = 'Explicit synthetic assumptions; other costs do not apply in this test';
+ if ($component['kind'] === 'duty') {
+ $component['subtotal_minor'] = 750;
+ $component['tax_minor'] = 0;
+ $component['total_minor'] = 750;
+ }
+ }
+ unset($component);
+ $input['legal_sources'] = ['duty' => ['estimate_id' => $legal->id, 'charge_key' => 'synthetic-duty']];
+ $native = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
+ expect($native->snapshot['plan']['budget_amount_minor'])->toBe(10750)
+ ->and($native->snapshot['legal_sources']['duty']['estimate_id'])->toBe($legal->id)
+ ->and($native->snapshot['legal_sources']['duty']['legal_rule']['id'])->toBe($rule->id)
+ ->and(DB::table('budget_entries')->count())->toBe(0);
+ $changed = [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1];
+ foreach ($changed['components'] as &$component) {
+ if ($component['kind'] === 'duty') {
+ $component['subtotal_minor'] = 751;
+ $component['total_minor'] = 751;
+ }
+ }
+ unset($component);
+ expect(fn () => app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $changed))->toThrow(HttpException::class);
+ $duplicate = [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1];
+ $duty = array_values(array_filter($duplicate['components'], fn ($component) => $component['kind'] === 'duty'))[0];
+ $duplicate['components'][] = [...$duty, 'key' => 'duty-again'];
+ $duplicate['legal_sources']['duty-again'] = $duplicate['legal_sources']['duty'];
+ expect(fn () => app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $duplicate))->toThrow(HttpException::class);
+ $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $rule->record_key,
+ 'version' => 2, 'action' => 'withdraw', 'reason' => 'Synthetic withdrawal before native approval requires explicit review']);
+ expect(fn () => app(ImportEstimates::class)->approval($this->draft))->toThrow(HttpException::class);
+ expect(DB::table('budget_entries')->count())->toBe(0)->and($native->fresh()->snapshot['plan']['budget_amount_minor'])->toBe(10750);
+});
+
test('native draft assumptions preserve unknowns originals and versions without financial or stock effects', function () {
$service = app(ImportEstimates::class);
$before = $this->draft->fresh()->getAttributes();
diff --git a/tests/Feature/ImportLegalEstimatesTest.php b/tests/Feature/ImportLegalEstimatesTest.php
new file mode 100644
index 0000000..f54166f
--- /dev/null
+++ b/tests/Feature/ImportLegalEstimatesTest.php
@@ -0,0 +1,84 @@
+ 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem',
+ 'rate_percent' => '7.5', 'specific_minor' => null, 'quantity_unit' => null,
+ 'basis_reference' => 'Synthetic customs-value basis; not an approved real legal rule'], ...$overrides];
+}
+
+beforeEach(function () {
+ config(['import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
+ Storage::fake('local');
+ $this->withoutVite();
+ $this->f = receiptFixture();
+ supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
+ $this->actingAs($this->f['issuer']);
+});
+
+test('ad valorem specific and the greater-value method use exact decimals and documented units', function () {
+ $amounts = app(ImportLegalAmounts::class);
+ $base = ['value_minor' => 10001, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic explicit customs valuation'];
+ $result = $amounts->calculate([legalCharge()], ['synthetic-duty' => $base]);
+ expect($result['total_minor'])->toBe(750)->and($result['financial_effects'])->toBeFalse();
+ $specific = legalCharge(['method' => 'specific', 'rate_percent' => null, 'specific_minor' => 125, 'quantity_unit' => 'KG']);
+ expect($amounts->calculate([$specific], ['synthetic-duty' => [...$base, 'value_minor' => null, 'quantity' => '1.500', 'quantity_unit' => 'KG']])['total_minor'])->toBe(188);
+ $maximum = legalCharge(['method' => 'maximum', 'specific_minor' => 1000, 'quantity_unit' => 'KG']);
+ expect($amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'quantity' => '1.500', 'quantity_unit' => 'KG']])['total_minor'])->toBe(1500);
+ expect($amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'quantity' => '0.100', 'quantity_unit' => 'KG']])['total_minor'])->toBe(750);
+ expect(fn () => $amounts->calculate([$maximum], ['synthetic-duty' => [...$base, 'quantity' => '1.5', 'quantity_unit' => 'BOX']]))->toThrow(ValidationException::class);
+});
+
+test('unknown rates and missing bases never become zero while explicit non-application and zero rates remain distinct', function () {
+ $amounts = app(ImportLegalAmounts::class);
+ $unknown = legalCharge(['key' => 'unknown', 'method' => 'unknown', 'rate_percent' => null]);
+ $zero = legalCharge(['key' => 'zero', 'rate_percent' => '0']);
+ $notApplicable = legalCharge(['key' => 'not-applicable', 'method' => 'not_applicable', 'rate_percent' => null]);
+ $result = $amounts->calculate([$unknown, $zero, $notApplicable], ['zero' => ['value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic declared base'],
+ 'not-applicable' => ['value_minor' => null, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic documentary proof that all non-application prerequisites are met']]);
+ expect($result['complete'])->toBeFalse()->and($result['total_minor'])->toBeNull()->and($result['known_subtotal_minor'])->toBe(0)
+ ->and(array_column($result['lines'], 'amount_minor'))->toBe([null, 0, 0]);
+ expect($amounts->calculate([], [])['total_minor'])->toBeNull();
+ expect($amounts->calculate([$notApplicable], [])['total_minor'])->toBeNull();
+ expect($amounts->calculate([legalCharge()], [])['total_minor'])->toBeNull();
+ expect(fn () => $amounts->definitions([legalCharge(['method' => 'unknown'])]))->toThrow(ValidationException::class);
+ expect(fn () => $amounts->calculate([legalCharge()], ['synthetic-duty' => ['value_minor' => 10000, 'quantity' => null, 'quantity_unit' => null, 'source' => null]]))->toThrow(ValidationException::class);
+ expect(fn () => $amounts->calculate([legalCharge(['rate_percent' => '10000'])], ['synthetic-duty' => ['value_minor' => 100000000000000, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic overflow boundary']]))->toThrow(ValidationException::class);
+});
+
+test('native estimates freeze source bases and calculated results without reserving funds and reject stale versions', function () {
+ $rules = app(ImportLegalRules::class);
+ $draft = $rules->save($this->f['issuer'], importLegalQaInput(['charges' => [legalCharge()]]), importLegalQaFile());
+ $rule = $rules->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
+ 'action' => 'publish', 'reason' => 'Synthetic explicit customs rate review for estimates']);
+ $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'requisition_item_id' => $this->f['r']->items()->sole()->id,
+ 'rule_id' => $rule->id, 'match_code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27',
+ 'bases' => ['synthetic-duty' => ['value_minor' => 10001, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic exact customs valuation']],
+ 'reason' => 'Synthetic estimate with explicit source and no financial effects'];
+ $before = [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
+ $url = '/requisicoes/'.$this->f['r']->id.'/base-legal/estimativas';
+ $this->post($url, $input)->assertRedirect();
+ $service = app(ImportLegalEstimates::class);
+ $record = $service->save($this->f['issuer'], $this->f['r'], $input);
+ expect($record->snapshot['result']['total_minor'])->toBe(750)->and($record->snapshot['legal_rule']['id'])->toBe($rule->id)
+ ->and($service->save($this->f['issuer'], $this->f['r'], $input)->id)->toBe($record->id);
+ expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
+ $second = $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'bases' => []]);
+ expect($second->state)->toBe('indeterminate')->and($second->snapshot['result']['total_minor'])->toBeNull()
+ ->and($record->fresh()->snapshot['result']['total_minor'])->toBe(750)
+ ->and($service->forPlan($this->f['r'], $record->id)->id)->toBe($record->id)
+ ->and([DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()])->toBe($before);
+});
diff --git a/tests/Feature/ImportLegalRulesTest.php b/tests/Feature/ImportLegalRulesTest.php
new file mode 100644
index 0000000..da2d8c6
--- /dev/null
+++ b/tests/Feature/ImportLegalRulesTest.php
@@ -0,0 +1,183 @@
+ (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
+ 'title' => 'Synthetic tariff rule', 'official_reference' => 'Synthetic official edition QA only',
+ 'official_url' => 'https://example.test/official-qa.pdf', 'citation' => 'Synthetic article 1, page 2',
+ 'valid_from' => '2026-01-01', 'valid_until' => '2026-12-31', 'match_code' => '1234', 'suggested_code' => '1234.56',
+ 'origin_country' => 'Synthetic A', 'sector' => 'Synthetic sector', 'obligations' => 'Synthetic duty conditions; no real tax activated',
+ 'document_types' => ['licence'], 'reason' => 'Synthetic legal configuration; not an approved real legal rule'], ...$overrides];
+}
+
+function legalRuleFile(): UploadedFile
+{
+ return UploadedFile::fake()->createWithContent('source.pdf', "%PDF-1.4\nSynthetic official source for QA only\n%%EOF");
+}
+
+function publishLegalRule(User $actor, SupplyRecord $draft): SupplyRecord
+{
+ return app(ImportLegalRules::class)->save($actor, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
+ 'version' => $draft->version, 'action' => 'publish', 'reason' => 'Synthetic customs review and publication of the prepared rule']);
+}
+
+beforeEach(function () {
+ config(['import-tariffs.qa_enabled' => true, 'import-legal.qa_enabled' => true]);
+ Storage::fake('local');
+ $this->withoutVite();
+ $this->f = receiptFixture();
+ supplyGrant($this->f['issuer'], ['procurement', 'import_customs']);
+ $this->actingAs($this->f['issuer']);
+});
+
+test('legal publication preserves sources versions periods scope and previous publication during a draft revision', function () {
+ $service = app(ImportLegalRules::class);
+ $before = [DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()];
+ $input = legalRuleInput();
+ $file = legalRuleFile();
+ $draft = $service->save($this->f['issuer'], $input, $file);
+ expect($service->save($this->f['issuer'], $input, $file)->id)->toBe($draft->id);
+ $find = fn ($origin = 'Synthetic A', $sector = 'Synthetic sector', $date = '2026-11-27') => $service->suggestions($this->f['issuer'], $this->f['r'], '1234', $origin, $sector, $date);
+ expect($find())->toBe([]);
+ $published = publishLegalRule($this->f['issuer'], $draft);
+ expect($find()[0]['id'])->toBe($published->id)->and($find(''))->toBe([])->and($find('Synthetic A', ''))->toBe([])
+ ->and($find('Synthetic A', 'Synthetic sector', '2027-01-01'))->toBe([])
+ ->and($find('Synthetic A', 'Synthetic sector', '2026-01-01'))->toHaveCount(1)
+ ->and($find('Synthetic A', 'Synthetic sector', '2026-12-31'))->toHaveCount(1);
+ $frozen = $service->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
+ $next = $service->save($this->f['issuer'], legalRuleInput(['record_key' => $published->record_key, 'version' => 2, 'suggested_code' => '1234.57']));
+ expect($find()[0]['id'])->toBe($published->id)->and($service->changed($frozen))->toBeFalse();
+ $new = publishLegalRule($this->f['issuer'], $next);
+ expect($service->changed($frozen))->toBeTrue()->and($frozen['data']['suggested_code'])->toBe('1234.56')
+ ->and($published->fresh()->data['suggested_code'])->toBe('1234.56');
+ $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $new->record_key, 'version' => 4,
+ 'action' => 'withdraw', 'reason' => 'Synthetic withdrawal without deleting original sources or applied decisions']);
+ expect($find())->toBe([])->and(Storage::disk('local')->allFiles())->toHaveCount(1)
+ ->and([DB::table('budget_entries')->get()->toJson(), DB::table('invoices')->get()->toJson(), DB::table('stock_movements')->get()->toJson()])->toBe($before);
+});
+
+test('buyer proposal freezes legal context and confirmation permits a reasoned deviation while changes require a current source', function () {
+ $service = app(ImportLegalRules::class);
+ $published = publishLegalRule($this->f['issuer'], $service->save($this->f['issuer'], legalRuleInput(), legalRuleFile()));
+ $tariffs = app(ImportTariffCodes::class);
+ $input = ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0, 'requisition_item_id' => $this->f['r']->items()->sole()->id,
+ 'code' => '1234.56', 'source_reference' => $published->data['official_reference'].' — '.$published->data['citation'], 'legal_rule_id' => $published->id,
+ 'legal_match_code' => '1234', 'legal_origin' => 'Synthetic A', 'legal_sector' => 'Synthetic sector', 'legal_date' => '2026-11-27',
+ 'reason' => 'Synthetic buyer selection of a documented suggestion'];
+ $proposal = $tariffs->save($this->f['issuer'], $this->f['r'], $input);
+ $confirmed = $tariffs->save($this->f['issuer'], $this->f['r'], ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => 1,
+ 'requisition_item_id' => $input['requisition_item_id'], 'code' => '1234.59', 'source_reference' => 'Synthetic technical classification reference',
+ 'reason' => 'Synthetic buyer explains the documented deviation from the suggested code']);
+ expect($confirmed->data['deviation'])->toBeTrue()->and($confirmed->snapshot['legal_rule']['id'])->toBe($published->id)
+ ->and($confirmed->snapshot['calculations_activated'])->toBeFalse()->and($proposal->fresh()->state)->toBe('proposed');
+ expect($tariffs->freezeForItems($this->f['issuer'], [$input['requisition_item_id']])[$input['requisition_item_id']]['legal_rule'])->toBe($confirmed->snapshot['legal_rule']);
+ $tariffs->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid(), 'version' => 2]);
+ $draft = $service->save($this->f['issuer'], legalRuleInput(['record_key' => $published->record_key, 'version' => 2]));
+ publishLegalRule($this->f['issuer'], $draft);
+ expect(fn () => $tariffs->save($this->f['issuer'], $this->f['r'], ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => 3,
+ 'requisition_item_id' => $input['requisition_item_id'], 'code' => '1234.56', 'source_reference' => 'Synthetic source', 'reason' => 'Synthetic obsolete-source confirmation must fail']))->toThrow(HttpException::class);
+ expect($tariffs->workspace($this->f['issuer'], $this->f['r'])['latest']->first()->legal_changed)->toBeTrue();
+});
+
+test('legal management rejects stale operations foreign access revoked permissions and missing or altered original bytes', function () {
+ $service = app(ImportLegalRules::class);
+ $input = legalRuleInput();
+ $draft = $service->save($this->f['issuer'], $input, legalRuleFile());
+ expect(fn () => $service->save($this->f['issuer'], [...$input, 'title' => 'Changed title'], legalRuleFile()))->toThrow(HttpException::class);
+ expect(fn () => $service->save($this->f['issuer'], legalRuleInput(['record_key' => $draft->record_key])))->toThrow(HttpException::class);
+ $viewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Procurement]);
+ supplyGrant($viewer, ['procurement']);
+ $this->actingAs($viewer);
+ expect(fn () => publishLegalRule($viewer, $draft))->toThrow(HttpException::class);
+ $foreign = receiptFixture();
+ supplyGrant($foreign['issuer'], ['procurement', 'import_customs']);
+ $this->actingAs($foreign['issuer']);
+ expect(fn () => $service->source($foreign['issuer'], $foreign['r'], $draft->snapshot['source_id']))->toThrow(ModelNotFoundException::class);
+ $this->actingAs($this->f['issuer']);
+ $source = $service->source($this->f['issuer'], $this->f['r'], $draft->snapshot['source_id']);
+ Storage::disk('local')->put($source->snapshot['evidence']['path'], 'altered');
+ expect(fn () => publishLegalRule($this->f['issuer'], $draft))->toThrow(HttpException::class);
+ DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
+ expect(fn () => $service->workspace($this->f['issuer'], $this->f['r']))->toThrow(HttpException::class);
+});
+
+test('native legal forms keep sources private and allow source download and explicit human publication only', function () {
+ $url = '/requisicoes/'.$this->f['r']->id.'/base-legal';
+ $this->post($url, [...legalRuleInput(), 'file' => legalRuleFile()])->assertRedirect();
+ $draft = SupplyRecord::query()->where('kind', 'import_legal_rule')->sole();
+ $this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private');
+ $source = app(ImportLegalRules::class)->source($this->f['issuer'], $this->f['r'], $draft->snapshot['source_id']);
+ $download = $this->get($url.'/fontes/'.$source->id)->assertOk()->assertHeader('X-Content-Type-Options', 'nosniff');
+ expect($download->getContent())->toBe(app(ImportEvidence::class)->bytes($source));
+ $this->getJson($url.'?rules_page=0')->assertUnprocessable();
+ config(['import-legal.qa_enabled' => false]);
+ $this->get($url)->assertStatus(503);
+});
+
+test('missing source alerts an already applied rule and changed source metadata requires a new original', function () {
+ $service = app(ImportLegalRules::class);
+ $draft = $service->save($this->f['issuer'], legalRuleInput(), legalRuleFile());
+ $published = publishLegalRule($this->f['issuer'], $draft);
+ $frozen = $service->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
+ expect(fn () => $service->save($this->f['issuer'], legalRuleInput(['record_key' => $published->record_key, 'version' => 2,
+ 'official_reference' => 'Different synthetic source without its original'])))->toThrow(HttpException::class);
+ $source = $service->source($this->f['issuer'], $this->f['r'], $frozen['source_id']);
+ Storage::disk('local')->delete($source->snapshot['evidence']['path']);
+ expect($service->changed($frozen))->toBeTrue();
+ expect(fn () => $service->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27'))->toThrow(HttpException::class);
+});
+
+test('an official source larger than a transactional attachment remains consultable without truncation', function () {
+ $bytes = "%PDF-1.4\n".str_repeat('Synthetic legal publication page bytes ', 70000)."\n%%EOF";
+ $service = app(ImportLegalRules::class);
+ $draft = $service->save($this->f['issuer'], legalRuleInput(), UploadedFile::fake()->createWithContent('large-source.pdf', $bytes));
+ $source = $service->source($this->f['issuer'], $this->f['r'], $draft->snapshot['source_id']);
+ expect(strlen($bytes))->toBeGreaterThan(2097152)->and(app(ImportEvidence::class)->bytes($source))->toBe($bytes);
+ expect(publishLegalRule($this->f['issuer'], $draft)->snapshot['source_sha256'])->toBe(hash('sha256', $bytes));
+});
+
+test('a shared official source is independently consultable and reused without inventing a code or publishing a rule', function () {
+ $service = app(ImportLegalRules::class);
+ $input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'action' => 'source',
+ 'official_reference' => 'Synthetic complete official journal; no rule or inferred rate',
+ 'reason' => 'Retain the synthetic official publication independently of its later use'];
+ $source = $service->save($this->f['issuer'], $input, legalRuleFile());
+ expect($service->save($this->f['issuer'], $input, legalRuleFile())->id)->toBe($source->id)
+ ->and($source->kind)->toBe('import_legal_source')->and($source->data['official_url'])->toBeNull()
+ ->and(SupplyRecord::query()->where('kind', 'import_legal_rule')->count())->toBe(0);
+ $rule = $service->save($this->f['issuer'], legalRuleInput(['source_id' => $source->id,
+ 'official_reference' => $source->data['official_reference'], 'official_url' => null]));
+ expect($rule->snapshot['source_id'])->toBe($source->id)->and(Storage::disk('local')->allFiles())->toHaveCount(1)
+ ->and($service->workspace($this->f['issuer'], $this->f['r'])['sources']->total())->toBe(1);
+ $other = $service->save($this->f['issuer'], [...$input, 'operation_key' => (string) Str::uuid(), 'official_reference' => 'Another synthetic official source'], legalRuleFile());
+ expect(fn () => $service->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $rule->record_key, 'version' => 1,
+ 'action' => 'publish', 'source_id' => $other->id, 'reason' => 'A publication decision cannot silently replace the prepared original']))->toThrow(HttpException::class);
+ expect(publishLegalRule($this->f['issuer'], $rule)->snapshot['source_id'])->toBe($source->id);
+});
+
+test('publishing a future period preserves the earlier applicable period without resurrecting an expired replacement', function () {
+ $service = app(ImportLegalRules::class);
+ $first = publishLegalRule($this->f['issuer'], $service->save($this->f['issuer'], legalRuleInput(), legalRuleFile()));
+ $future = publishLegalRule($this->f['issuer'], $service->save($this->f['issuer'], legalRuleInput(['record_key' => $first->record_key, 'version' => 2,
+ 'valid_from' => '2027-01-01', 'valid_until' => '2027-06-30', 'suggested_code' => '1234.57'])));
+ $find = fn ($date) => $service->suggestions($this->f['issuer'], $this->f['r'], '1234', 'Synthetic A', 'Synthetic sector', $date);
+ expect($find('2026-11-27')[0]['id'])->toBe($first->id)->and($find('2027-01-01')[0]['id'])->toBe($future->id)
+ ->and($find('2027-07-01'))->toBe([])
+ ->and($service->freeze($first->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27')['id'])->toBe($first->id);
+});
diff --git a/tests/Feature/ImportReadinessTest.php b/tests/Feature/ImportReadinessTest.php
new file mode 100644
index 0000000..6861208
--- /dev/null
+++ b/tests/Feature/ImportReadinessTest.php
@@ -0,0 +1,140 @@
+ true, 'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true,
+ 'import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true]);
+ Storage::fake('local');
+ $this->withoutVite();
+ $this->f = receiptFixture();
+ supplyGrant($this->f['issuer'], ['procurement', 'import_prepare', 'import_customs']);
+ $this->actingAs($this->f['issuer']);
+ $this->import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
+ 'purchase_order_id' => $this->f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic readiness jurisdiction',
+ 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic regime',
+ 'expected_usable_on' => today()->subDay()->toDateString()]));
+});
+
+test('current import alerts distinguish unknown requirements and the expected receipt from customs release without side effects', function () {
+ $service = app(ImportReadiness::class);
+ $before = [];
+ foreach (['supply_records', 'audit_logs', 'budget_entries', 'stock_movements', 'invoices', 'workflow_notices'] as $table) {
+ $before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
+ }
+ $workspace = $service->workspace($this->f['issuer'], $this->import);
+ expect(array_column($workspace['alerts'], 'key'))->toContain('expected-due', 'classification-unknown', 'parties-unknown', 'bank-unknown')
+ ->and($workspace['complete'])->toBeTrue()->and($workspace['financialEffects'])->toBeFalse()->and($workspace['automaticNotifications'])->toBeFalse();
+ foreach ($before as $table => $rows) {
+ expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
+ }
+ $planning = app(SupplyPlanning::class);
+ $transit = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic transit', 'event_date' => today()->toDateString()], 'transit', $this->import));
+ $arrived = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic arrival', 'event_date' => today()->toDateString()], 'arrive', $transit));
+ expect(array_column($service->workspace($this->f['issuer'], $arrived)['alerts'], 'key'))->toContain('customs-pending');
+ supplyGrant($this->f['receiver'], ['warehouse', 'import_customs', 'import_read']);
+ $this->actingAs($this->f['receiver']);
+ $released = $planning->save($this->f['receiver'], 'import', supplyInput(['evidence' => 'Synthetic independent release', 'event_date' => today()->toDateString()], 'release', $arrived));
+ $this->actingAs($this->f['issuer']);
+ expect(array_column($service->workspace($this->f['issuer'], $released)['alerts'], 'key'))->toContain('expected-due')->not->toContain('customs-pending');
+ $this->actingAs($this->f['receiver']);
+ app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
+ $this->actingAs($this->f['issuer']);
+ expect(array_column($service->workspace($this->f['issuer'], $released)['alerts'], 'key'))->not->toContain('expected-due');
+});
+
+test('document requirements come from the frozen rule and missing or altered evidence reopens the live alert', function () {
+ $legal = app(ImportLegalRules::class);
+ $draft = $legal->save($this->f['issuer'], importLegalQaInput(), importLegalQaFile());
+ $published = $legal->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
+ 'action' => 'publish', 'reason' => 'Synthetic customs source publication for current alerts']);
+ $frozen = $legal->freeze($published->id, '1234', 'Synthetic A', 'Synthetic sector', '2026-11-27');
+ // Construct an issued-order fixture; no production order is rewritten.
+ DB::table('purchase_orders')->where('id', $this->f['order']->id)->update(['snapshot' => json_encode([...$this->f['order']->snapshot,
+ 'import_tariffs' => [['record_id' => 999, 'item' => ['description' => 'Synthetic classified item'],
+ 'data' => ['requisition_id' => $this->f['r']->id], 'legal_rule' => $frozen]]], JSON_THROW_ON_ERROR)]);
+ $service = app(ImportReadiness::class);
+ expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->toContain('required-licence');
+ $document = app(ImportDossier::class)->record($this->f['issuer'], $this->import, ['operation_key' => (string) Str::uuid(), 'type' => 'licence',
+ 'reference' => 'LICENCE-QA', 'issuer_reference' => 'Synthetic issuer', 'reason' => 'Synthetic licence for documentary readiness'],
+ UploadedFile::fake()->createWithContent('licence.pdf', "%PDF-1.4\nSynthetic licence\n%%EOF"));
+ expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->not->toContain('required-licence');
+ Storage::disk('local')->put($document->snapshot['evidence']['path'], 'altered');
+ expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->toContain('required-licence', 'document-'.$document->id);
+ $legal->save($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'record_key' => $published->record_key, 'version' => 2,
+ 'action' => 'withdraw', 'reason' => 'Synthetic withdrawal alerts the existing decision without deleting it']);
+ expect(array_column($service->workspace($this->f['issuer'], $this->import)['alerts'], 'key'))->toContain('legal-changed-999');
+});
+
+test('bank pending alerts reuse the native report and disappear after dated documentary delivery', function () {
+ $fixture = importBankQaFixture($this->f['issuer'], $this->import);
+ $bank = app(ImportBankSupport::class);
+ $first = $bank->save($this->f['issuer'], $this->import, $fixture['input']);
+ $service = app(ImportReadiness::class);
+ $bankAlerts = fn () => array_values(array_filter($service->workspace($this->f['issuer'], $this->import)['alerts'], fn ($alert) => $alert['category'] === 'Suporte bancário'));
+ expect($bankAlerts())->not->toBeEmpty();
+ $bank->save($this->f['issuer'], $this->import, [...$fixture['input'], 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $first->record_key, 'version' => 1, 'submission_document_id' => $fixture['documents']['delivery']->id,
+ 'submitted_on' => today()->toDateString(), 'submission_basis' => 'Synthetic documentary delivery evidence']);
+ expect($bankAlerts())->toBe([]);
+ config(['import-bank-support.qa_enabled' => false]);
+ $workspace = $service->workspace($this->f['issuer'], $this->import);
+ expect($workspace['complete'])->toBeFalse()->and(array_column($workspace['alerts'], 'key'))->toContain('bank-unavailable');
+});
+
+test('native follow-up revalidates current identity company context versions and private response headers', function () {
+ $url = '/compras/importacoes/'.$this->import->id.'/acompanhamento';
+ $this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
+ ->assertInertia(fn (Assert $page) => $page->component('supply/import-readiness')->where('automaticNotifications', false));
+ $foreign = receiptFixture();
+ supplyGrant($foreign['issuer'], ['procurement', 'import_read']);
+ $this->actingAs($foreign['issuer'])->get($url)->assertNotFound();
+ $this->actingAs($this->f['issuer']);
+ DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
+ expect(fn () => app(ImportReadiness::class)->workspace($this->f['issuer'], $this->import))->toThrow(HttpException::class);
+});
+
+test('accepted receipt in quarantine remains an availability alert until native independent quality release', function () {
+ $planning = app(SupplyPlanning::class);
+ $transit = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic transit', 'event_date' => today()->toDateString()], 'transit', $this->import));
+ $arrived = $planning->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic arrival', 'event_date' => today()->toDateString()], 'arrive', $transit));
+ supplyGrant($this->f['issuer'], ['inventory_lot_prepare']);
+ $lots = app(InventoryLots::class);
+ $setup = $lots->save($this->f['issuer'], supplyInput(['stock_item_id' => $this->f['stock']->id, 'warehouse_id' => $this->f['warehouse']->id,
+ 'requires_expiry' => false, 'minimum_remaining_days' => 0, 'lots' => [], 'quarantine_on_receipt' => true], 'prepare'));
+ supplyGrant($this->f['receiver'], ['warehouse', 'import_customs', 'inventory_lot_review']);
+ $this->actingAs($this->f['receiver']);
+ $lots->save($this->f['receiver'], supplyInput([], 'activate', $setup));
+ $released = $planning->save($this->f['receiver'], 'import', supplyInput(['evidence' => 'Synthetic independent release', 'event_date' => today()->toDateString()], 'release', $arrived));
+ $input = receiptPayload($this->f, '1.000');
+ $input['items'][0]['lots'] = [['code' => 'QA-LOT', 'no_expiry' => true]];
+ app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], $input);
+ $lot = $lots->context($this->f['stock']->id, $this->f['warehouse']->id)['lots'][0];
+ $this->actingAs($this->f['issuer']);
+ $alerts = app(ImportReadiness::class)->workspace($this->f['issuer'], $released)['alerts'];
+ expect(array_column($alerts, 'key'))->toContain('stock-held-'.$lot['id'].'-'.$this->f['warehouse']->id);
+ supplyGrant($this->f['otherReceiver'], ['warehouse', 'inventory_lot_release']);
+ $this->actingAs($this->f['otherReceiver']);
+ $lots->save($this->f['otherReceiver'], supplyInput(['lot_id' => $lot['id'], 'warehouse_id' => $this->f['warehouse']->id,
+ 'state_version' => $lot['state_version']], 'release', SupplyRecord::query()->findOrFail($lot['metadata_id'])));
+ $this->actingAs($this->f['issuer']);
+ expect(array_column(app(ImportReadiness::class)->workspace($this->f['issuer'], $released)['alerts'], 'key'))->not->toContain('stock-held-'.$lot['id'].'-'.$this->f['warehouse']->id);
+});
diff --git a/tests/Feature/PurchaseAwardOrderTest.php b/tests/Feature/PurchaseAwardOrderTest.php
index f7af465..4e12b63 100644
--- a/tests/Feature/PurchaseAwardOrderTest.php
+++ b/tests/Feature/PurchaseAwardOrderTest.php
@@ -31,6 +31,8 @@ use App\Models\User;
use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
use App\Services\BudgetWorkflow;
+use App\Services\CapitalAssignments;
+use App\Services\CapitalRegister;
use App\Services\CommonBudget;
use App\Services\ComparisonPolicy;
use App\Services\ConflictGuard;
@@ -71,6 +73,67 @@ require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
+function nativeCapitalAssignment(object $test): array
+{
+ config(['capital-register.qa_enabled' => true]);
+ $test->actingAs($test->buyer);
+ $input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project',
+ 'code' => 'PRJ-NATIVE-QA', 'name' => 'Projecto sintético da ordem', 'department_id' => $test->department->id,
+ 'equipment_id' => null, 'reference' => 'Documento sintético de investimento', 'state' => 'active', 'reason' => 'Cadastro estritamente sintético da ligação à ordem'];
+ $source = app(CapitalRegister::class)->save($test->buyer, $input);
+ // Extend the pre-approved synthetic fixture with a choice made while it was a draft.
+ $test->r->update(['status' => 'draft']);
+ $test->actingAs($test->owner);
+ $assignment = app(CapitalAssignments::class)->save($test->owner, $test->r, ['operation_key' => (string) Str::uuid(),
+ 'version' => 0, 'item_id' => $test->item->id, 'capital_id' => $source->id, 'reason' => 'Destino documental escolhido pelo requisitante sintético']);
+ $test->r->update(['status' => 'approved']);
+ $test->actingAs($test->buyer);
+
+ return [$source, $assignment, $input];
+}
+
+test('native order preserves the capital destination and print after the independent register is archived', function () {
+ [$source, $assignment, $input] = nativeCapitalAssignment($this);
+ $award = selectPurchaseAward($this);
+ $order = issuePurchaseOrder($this, $award);
+ expect($order->snapshot['capital_assignments'][$this->item->id]['id'])->toBe($assignment->id)
+ ->and($order->total_minor)->toBe($award->total_minor);
+ app(CapitalRegister::class)->save($this->buyer, [...$input, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $source->record_key, 'version' => 1, 'name' => 'Nome posterior ao documento', 'state' => 'archived']);
+ $this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('PRJ-NATIVE-QA')->assertSee('Projecto sintético da ordem')->assertDontSee('Nome posterior ao documento');
+ expect($order->fresh()->snapshot['capital_assignments'][$this->item->id]['snapshot']['source']['version'])->toBe(1);
+ $this->withoutVite();
+ $this->get('/projectos-imobilizado?history='.$source->record_key)->assertOk()
+ ->assertInertia(fn (Assert $page) => $page->has('trace.orders.data', 1)->where('trace.orders.data.0.order_number', $order->number)->has('trace.receipts.data', 0));
+ $receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
+ $this->actingAs($receiver);
+ $warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CAPITAL-QA', 'name' => 'Armazém sintético']);
+ $stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CAPITAL-QA', 'name' => 'Artigo sintético', 'unit' => 'un']);
+ $receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'CAPITAL-NATIVE-RECEIPT',
+ 'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
+ 'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '1.000', 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]);
+ $this->actingAs($this->buyer);
+ $before = DB::table('stock_movements')->get()->toJson();
+ $this->get('/projectos-imobilizado?history='.$source->record_key)->assertOk()
+ ->assertInertia(fn (Assert $page) => $page->has('trace.receipts.data', 1)->where('trace.receipts.data.0.receipt_id', $receipt->id)
+ ->where('trace.receipts.data.0.accepted_quantity', '1.000')->where('trace.receipts.data.0.returned_quantity', '0.000')->where('trace.receipts.data.0.reversed', false));
+ expect(DB::table('stock_movements')->get()->toJson())->toBe($before);
+});
+
+test('native partial order freezes the same explicit capital origin without changing its financial allocation', function () {
+ if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
+ $this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
+ }
+ [, $assignment] = nativeCapitalAssignment($this);
+ $award = nativeOrderPartsAward($this);
+ $input = nativeOrderPartsInput($this, $award, '0.400', 0);
+ $this->actingAs($this->buyer);
+ $order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
+ expect($order->snapshot['capital_assignments'][$this->item->id]['id'])->toBe($assignment->id)
+ ->and($order->total_minor)->toBe(4000)->and(DB::table('budget_order_commands')->count())->toBe(1);
+ $this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('PRJ-NATIVE-QA');
+});
+
test('confirmed import classifications freeze in a newly issued native order and survive later proposals', function () {
config(['import-tariffs.qa_enabled' => true]);
$tariffs = app(ImportTariffCodes::class);
diff --git a/tests/Support/ImportBankQaFixture.php b/tests/Support/ImportBankQaFixture.php
new file mode 100644
index 0000000..8b6783e
--- /dev/null
+++ b/tests/Support/ImportBankQaFixture.php
@@ -0,0 +1,35 @@
+,input:array}
+ */
+function importBankQaFixture(User $actor, SupplyRecord $import): array
+{
+ $db = DB::connection();
+ if (! app()->environment('testing') || ! (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
+ || ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))) {
+ throw new LogicException('Bank evidence fixtures require isolated QA.');
+ }
+ $documents = [];
+ foreach (['term' => 'bank_commitment', 'declaration' => 'customs_declaration', 'invoice' => 'commercial_invoice', 'delivery' => 'bank_support'] as $key => $type) {
+ $reference = 'BANK-QA-'.$key.'-'.Str::random(8);
+ $documents[$key] = app(ImportDossier::class)->record($actor, $import, ['operation_key' => (string) Str::uuid(), 'type' => $type,
+ 'reference' => $reference, 'issuer_reference' => 'Synthetic bank evidence issuer', 'issued_on' => today()->toDateString(),
+ 'reason' => 'Original estritamente sintético de suporte documental bancário'],
+ UploadedFile::fake()->createWithContent('bank-'.$key.'.pdf', "%PDF-1.4\nSynthetic evidence ".$reference."\n%%EOF"));
+ }
+
+ return ['documents' => $documents, 'input' => ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
+ 'commitment_document_id' => $documents['term']->id, 'declaration_document_id' => $documents['declaration']->id,
+ 'support_document_ids' => [$documents['invoice']->id], 'requirements_known' => true, 'required_support_types' => ['commercial_invoice'],
+ 'required_support_counts' => ['commercial_invoice' => 1], 'requirements_basis' => 'Explicit synthetic bank letter requests one invoice',
+ 'submission_document_id' => null, 'submission_basis' => null, 'submitted_on' => null,
+ 'due_on' => today()->toDateString(), 'deadline_basis' => 'Explicit synthetic bank letter deadline', 'reason' => 'Acompanhamento bancário exclusivamente sintético']];
+}
diff --git a/tests/Support/ImportLegalQaFixture.php b/tests/Support/ImportLegalQaFixture.php
new file mode 100644
index 0000000..716031a
--- /dev/null
+++ b/tests/Support/ImportLegalQaFixture.php
@@ -0,0 +1,42 @@
+environment('testing') || ! (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
+ || ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))) {
+ throw new LogicException('Legal fixtures require isolated QA.');
+ }
+
+ return [...['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
+ 'title' => 'Synthetic tariff rule', 'official_reference' => 'Synthetic official edition QA only',
+ 'official_url' => 'https://example.test/official-qa.pdf', 'citation' => 'Synthetic article 1, page 2',
+ 'valid_from' => '2026-01-01', 'valid_until' => '2026-12-31', 'match_code' => '1234', 'suggested_code' => '1234.56',
+ 'origin_country' => 'Synthetic A', 'sector' => 'Synthetic sector', 'obligations' => 'Synthetic conditions only; no real tax activated',
+ 'document_types' => ['licence'], 'reason' => 'Synthetic legal configuration; not an approved real legal rule'], ...$overrides];
+}
+
+function importLegalQaFile(): UploadedFile
+{
+ return UploadedFile::fake()->createWithContent('source.pdf', "%PDF-1.4\nSynthetic official source for QA only\n%%EOF");
+}
+
+function importLegalQaCharge(): array
+{
+ return ['key' => 'synthetic-duty', 'kind' => 'duty', 'label' => 'Synthetic duty', 'method' => 'ad_valorem',
+ 'rate_percent' => '7.5', 'specific_minor' => null, 'quantity_unit' => null,
+ 'basis_reference' => 'Synthetic explicit customs valuation; no real rate configured'];
+}
+
+function importLegalQaAmountInput(int $itemId, int $ruleId): array
+{
+ return ['operation_key' => (string) Str::uuid(), 'version' => 0, 'requisition_item_id' => $itemId, 'rule_id' => $ruleId,
+ 'match_code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27',
+ 'bases' => ['synthetic-duty' => ['value_minor' => 10001, 'quantity' => null, 'quantity_unit' => null, 'source' => 'Synthetic exact declared valuation']],
+ 'reason' => 'Synthetic legal charge estimate without financial or stock effects'];
+}
diff --git a/tests/Support/LandedQaReceipts.php b/tests/Support/LandedQaReceipts.php
index 9c1ece9..fe278c7 100644
--- a/tests/Support/LandedQaReceipts.php
+++ b/tests/Support/LandedQaReceipts.php
@@ -43,12 +43,12 @@ function landedQaReceiptsVerified(array $command, string $output): bool
&& (! in_array($mode, ['race-estimate', 'race-estimate-reconcile'], true) || $contains(fn ($row) => ($row['old_estimate_runtime_rejected'] ?? false) === true
&& ($row['runtime_landed_version'] ?? null) === 'COMMON-BUDGET-LANDED-COST-QA-v2' && ($row['status'] ?? null) === 503));
}
- if (in_array($mode, ['race-dossier', 'race-party'], true)) {
+ if (in_array($mode, ['race-dossier', 'race-party', 'race-bank', 'race-legal', 'race-legal-amount', 'race-capital'], true)) {
foreach (['same_operation', 'same_version'] as $scenario) {
$matches = array_values(array_filter($records, fn ($row) => ($row['scenario'] ?? null) === $scenario));
if (count($matches) !== 1 || ($matches[0]['blocked_writers_observed'] ?? 0) < 2
|| ($matches[0]['documents_created'] ?? 0) !== 1 || ($matches[0]['audits'] ?? 0) !== 1
- || ($matches[0]['files_created'] ?? -1) !== ($mode === 'race-party' ? 0 : 1) || ($matches[0]['all_originals_verified'] ?? false) !== true
+ || ($matches[0]['files_created'] ?? -1) !== (in_array($mode, ['race-party', 'race-bank', 'race-legal-amount', 'race-capital'], true) ? 0 : 1) || ($matches[0]['all_originals_verified'] ?? false) !== true
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
return false;
}
@@ -56,17 +56,41 @@ function landedQaReceiptsVerified(array $command, string $output): bool
return true;
}
- if (in_array($mode, ['landed-costs', 'import-estimates'], true)) {
- return ($mode !== 'import-estimates' || $contains(fn ($row) => ($row['estimate_source_remainder_restored'] ?? null) === 1000 && ($row['estimate_original_replay_without_effects'] ?? false) === true))
+ if (in_array($mode, ['landed-costs', 'import-estimates', 'import-bank-support', 'import-legal', 'import-legal-amount'], true)) {
+ return ($mode === 'landed-costs' || $contains(fn ($row) => ($row['estimate_source_remainder_restored'] ?? null) === 1000 && ($row['estimate_original_replay_without_effects'] ?? false) === true))
+ && ($mode !== 'import-legal-amount' || $contains(fn ($row) => ($row['legal_amount_minor_restored'] ?? null) === 750 && ($row['legal_amount_replay_without_effects'] ?? false) === true
+ && ($row['native_legal_plan_total_minor'] ?? null) === 10750 && ($row['native_legal_plan_source_restored'] ?? false) === true && ($row['native_legal_plan_replay_without_effects'] ?? false) === true))
+ && (! in_array($mode, ['import-legal', 'import-legal-amount'], true) || $contains(fn ($row) => ($row['legal_source_restored'] ?? false) === true && ($row['legal_published_version_restored'] ?? false) === true
+ && ($row['legal_buyer_context_restored'] ?? false) === true && ($row['legal_replay_without_effects'] ?? false) === true))
+ && (! in_array($mode, ['import-bank-support', 'import-legal', 'import-legal-amount'], true) || $contains(fn ($row) => ($row['bank_support_versions_restored'] ?? null) === 2
+ && ($row['bank_support_relationships_restored'] ?? false) === true && ($row['bank_support_replay_without_effects'] ?? false) === true))
&& $contains(fn ($row) => ($row['post_extension_restore_all_tables_equal'] ?? false) === true
&& ($row['recovered_operation_replay_no_effects'] ?? false) === true && ($row['pre_extension_schema_data_balance_restored'] ?? false) === true)
- && $contains(fn ($row) => ($row['private_original_versions_restored'] ?? 0) === 6 && ($row['typed_dossier_versions_restored'] ?? 0) === 4
+ && $contains(fn ($row) => ($row['private_original_versions_restored'] ?? 0) === (in_array($mode, ['import-legal', 'import-legal-amount'], true) ? 11 : ($mode === 'import-bank-support' ? 10 : 6)) && ($row['typed_dossier_versions_restored'] ?? 0) === (in_array($mode, ['import-bank-support', 'import-legal', 'import-legal-amount'], true) ? 8 : 4)
&& ($row['selected_party_versions_restored'] ?? 0) === 2
&& ($row['source_loss_detected'] ?? false) === true
&& ($row['separate_private_root_restored'] ?? false) === true && ($row['native_authorized_evidence_resolved'] ?? false) === true)
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
}
+ if (in_array($mode, ['legal-http', 'legal-review'], true)) {
+ return $contains(fn ($row) => ($row['native_legal_http_login'] ?? false) === true && ($row['csrf_required'] ?? false) === true
+ && ($row['large_multipart_upload_bytes'] ?? 0) > 2097152 && ($row['original_unchanged'] ?? false) === true
+ && ($row['exact_native_download'] ?? false) === true && ($row['one_source_one_audit_after_replay'] ?? false) === true
+ && ($row['guest_status'] ?? null) === 401 && ($row['revoked_status'] ?? null) === 403 && ($row['rules_published'] ?? null) === 0
+ && ($row['financial_stock_unchanged'] ?? false) === true && ($row['global_php_config_unchanged'] ?? false) === true
+ && ($row['private_http_server_stopped'] ?? false) === true && ($row['private_http_root_removed'] ?? false) === true);
+ }
+ if ($mode === 'corpus') {
+ return $contains(fn ($row) => ($row['shared_corpus_files_inventoried'] ?? 0) > 0 && count($row['real_official_sources_prepared'] ?? []) === 4
+ && is_string($row['inventory_metadata_sha256'] ?? null) && preg_match('/^[a-f0-9]{64}$/D', $row['inventory_metadata_sha256']) === 1
+ && count(array_filter($row['real_official_sources_prepared'], fn ($source) => is_string($source['sha256'] ?? null)
+ && preg_match('/^[a-f0-9]{64}$/D', $source['sha256']) === 1 && ($source['bytes'] ?? 0) > 0
+ && ($source['native_authorized_download_verified'] ?? false) === true)) === 4
+ && ($row['rules_published'] ?? null) === 0 && ($row['originals_unchanged'] ?? false) === true
+ && ($row['financial_and_stock_unchanged'] ?? false) === true && ($row['synthetic_qa_organization_only'] ?? false) === true);
+ }
+
return $mode === 'pest' && $contains(fn ($row) => ($row['tool'] ?? null) === 'pest' && ($row['result'] ?? null) === 'passed'
&& ($row['tests'] ?? 0) > 0 && ($row['passed'] ?? 0) === $row['tests']);
}
diff --git a/tests/Support/import-legal-http-router.php b/tests/Support/import-legal-http-router.php
new file mode 100644
index 0000000..d5d4769
--- /dev/null
+++ b/tests/Support/import-legal-http-router.php
@@ -0,0 +1,38 @@
+ 'text/javascript', 'css' => 'text/css', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2'];
+if ($asset !== false && is_file($asset) && str_starts_with(str_replace('\\', '/', $asset), str_replace('\\', '/', $public).'/')
+ && isset($types[pathinfo($asset, PATHINFO_EXTENSION)])) {
+ header('Content-Type: '.$types[pathinfo($asset, PATHINFO_EXTENSION)]);
+ readfile($asset);
+ exit;
+}
+$app = require __DIR__.'/../../bootstrap/app.php';
+$app->useStoragePath($root.'/storage');
+$app->usePublicPath($root.'/public');
+$app->booted(function () use ($root, $database) {
+ if (config('database.default') !== 'pgsql' || config('database.connections.pgsql.database') !== $database) {
+ abort(503);
+ }
+ config(['capital-register.qa_enabled' => true, 'import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true,
+ 'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-readiness.qa_enabled' => true, 'import-estimates.qa_enabled' => true,
+ 'session.driver' => 'file', 'session.files' => $root.'/storage/framework/sessions', 'session.domain' => null,
+ 'session.secure' => false, 'cache.default' => 'array']);
+});
+$app->handleRequest(Request::capture());
diff --git a/tests/Unit/LandedQaReceiptsTest.php b/tests/Unit/LandedQaReceiptsTest.php
index bfc9dbd..11e5581 100644
--- a/tests/Unit/LandedQaReceiptsTest.php
+++ b/tests/Unit/LandedQaReceiptsTest.php
@@ -1,5 +1,19 @@
[200, 200], 'same_version' => [200, 409]] as $scenario => $statuses) {
+ $rows[] = ['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => 2, 'documents_created' => 1,
+ 'audits' => 1, 'files_created' => 0, 'all_originals_verified' => true];
+ }
+ $output = implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows));
+ expect(landedQaReceiptsVerified($command, $output))->toBeTrue();
+ expect(landedQaReceiptsVerified($command, json_encode($rows[0], JSON_THROW_ON_ERROR)))->toBeFalse();
+ $rows[1]['documents_created'] = 2;
+ expect(landedQaReceiptsVerified($command, implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows))))->toBeFalse();
+});
+
require_once __DIR__.'/../Support/LandedQaReceipts.php';
test('estimate contention receipts require all native uniqueness races and explicit estimate effects', function () {
@@ -74,6 +88,15 @@ test('restore completion requires the restored replay original snapshot and data
expect(landedQaReceiptsVerified($estimateCommand, $existingRecovery."\n".json_encode([
'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
], JSON_THROW_ON_ERROR)))->toBeTrue();
+ $bankCommand = [...array_slice($command, 0, 3), 'import-bank-support'];
+ $bankPrivate = [...$privateFiles, 'private_original_versions_restored' => 10, 'typed_dossier_versions_restored' => 8];
+ $bankOutput = $databaseOnly."\n".json_encode($bankPrivate, JSON_THROW_ON_ERROR)."\n".json_encode([
+ 'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
+ ], JSON_THROW_ON_ERROR);
+ expect(landedQaReceiptsVerified($bankCommand, $bankOutput))->toBeFalse();
+ expect(landedQaReceiptsVerified($bankCommand, $bankOutput."\n".json_encode([
+ 'bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true, 'bank_support_replay_without_effects' => true,
+ ], JSON_THROW_ON_ERROR)))->toBeTrue();
$missingTyped = $privateFiles;
unset($missingTyped['typed_dossier_versions_restored']);
expect(landedQaReceiptsVerified($command, $databaseOnly."\n".json_encode($missingTyped, JSON_THROW_ON_ERROR)))->toBeFalse();
@@ -101,6 +124,75 @@ test('dossier contention requires both races one original and verified bytes', f
}
unset($row);
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeTrue();
+ $bankCommand = [...array_slice($partyCommand, 0, 3), 'race-bank'];
+ expect(landedQaReceiptsVerified($bankCommand, $encode($rows)))->toBeTrue();
$rows[1]['files_created'] = 1;
expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeFalse();
+ expect(landedQaReceiptsVerified($bankCommand, $encode($rows)))->toBeFalse();
+});
+
+test('legal contention and recovery require original source publication and frozen buyer context receipts', function () {
+ $command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-legal'];
+ $rows = [];
+ foreach (['same_operation', 'same_version'] as $scenario) {
+ $rows[] = ['scenario' => $scenario, 'statuses' => $scenario === 'same_operation' ? [200, 200] : [200, 409],
+ 'blocked_writers_observed' => 2, 'documents_created' => 1, 'audits' => 1, 'files_created' => 1, 'all_originals_verified' => true];
+ }
+ $encode = fn ($records) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $records));
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
+ $rows[1]['files_created'] = 0;
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
+ $command[3] = 'import-legal';
+ $rows = [['post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true,
+ 'pre_extension_schema_data_balance_restored' => true, 'isolated_restore_removed' => true,
+ 'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
+ 'bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true, 'bank_support_replay_without_effects' => true,
+ 'private_original_versions_restored' => 11, 'typed_dossier_versions_restored' => 8, 'selected_party_versions_restored' => 2,
+ 'source_loss_detected' => true, 'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true]];
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
+ $rows[] = ['legal_source_restored' => true, 'legal_published_version_restored' => true, 'legal_buyer_context_restored' => true, 'legal_replay_without_effects' => true];
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
+ unset($rows[1]['legal_buyer_context_restored']);
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
+});
+
+test('real corpus receipts require hashes verified native originals and no rule publication', function () {
+ $command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'corpus'];
+ $row = ['shared_corpus_files_inventoried' => 4, 'inventory_metadata_sha256' => str_repeat('a', 64),
+ 'real_official_sources_prepared' => array_fill(0, 4, ['sha256' => str_repeat('b', 64), 'bytes' => 100, 'native_authorized_download_verified' => true]),
+ 'rules_published' => 0, 'originals_unchanged' => true, 'financial_and_stock_unchanged' => true, 'synthetic_qa_organization_only' => true];
+ $encode = fn ($value) => json_encode($value, JSON_THROW_ON_ERROR);
+ expect(landedQaReceiptsVerified($command, $encode($row)))->toBeTrue();
+ $row['real_official_sources_prepared'][0]['native_authorized_download_verified'] = false;
+ expect(landedQaReceiptsVerified($command, $encode($row)))->toBeFalse();
+ $row['real_official_sources_prepared'][0]['native_authorized_download_verified'] = true;
+ $row['rules_published'] = 1;
+ expect(landedQaReceiptsVerified($command, $encode($row)))->toBeFalse();
+});
+
+test('legal amount receipts require both contention cases and recovery of the exact native source-linked cost total', function () {
+ $command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-legal-amount'];
+ $rows = [];
+ foreach (['same_operation', 'same_version'] as $scenario) {
+ $rows[] = ['scenario' => $scenario, 'statuses' => $scenario === 'same_operation' ? [200, 200] : [200, 409],
+ 'blocked_writers_observed' => 2, 'documents_created' => 1, 'audits' => 1, 'files_created' => 0, 'all_originals_verified' => true];
+ }
+ $encode = fn ($records) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $records));
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
+ $rows[0]['files_created'] = 1;
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
+ $command[3] = 'import-legal-amount';
+ $rows = [['post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true,
+ 'pre_extension_schema_data_balance_restored' => true, 'isolated_restore_removed' => true,
+ 'estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true,
+ 'bank_support_versions_restored' => 2, 'bank_support_relationships_restored' => true, 'bank_support_replay_without_effects' => true,
+ 'private_original_versions_restored' => 11, 'typed_dossier_versions_restored' => 8, 'selected_party_versions_restored' => 2,
+ 'source_loss_detected' => true, 'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true,
+ 'legal_source_restored' => true, 'legal_published_version_restored' => true, 'legal_buyer_context_restored' => true, 'legal_replay_without_effects' => true]];
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
+ $rows[] = ['legal_amount_minor_restored' => 750, 'legal_amount_replay_without_effects' => true,
+ 'native_legal_plan_total_minor' => 10750, 'native_legal_plan_source_restored' => true, 'native_legal_plan_replay_without_effects' => true];
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
+ $rows[1]['native_legal_plan_total_minor'] = 10751;
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
});
diff --git a/tests/frontend/capital-register.test.tsx b/tests/frontend/capital-register.test.tsx
new file mode 100644
index 0000000..57b2752
--- /dev/null
+++ b/tests/frontend/capital-register.test.tsx
@@ -0,0 +1,89 @@
+import { App } from '@inertiajs/react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { expect, test } from 'vitest';
+import CapitalRegister from '../../resources/js/pages/equipment/capital-register';
+import CapitalAssignments from '../../resources/js/pages/requisitions/capital-assignments';
+import CapitalAssignmentSummary from '../../resources/js/components/capital-assignment-summary';
+
+const source = {
+ id: 2,
+ version: 3,
+ record_key: 'source',
+ state: 'archived',
+ reason: 'Synthetic archive reason',
+ data: {
+ type: 'project',
+ code: 'PRJ-QA',
+ name: '',
+ reference: 'Frozen documentary reference',
+ department_id: 1,
+ equipment_id: null,
+ },
+};
+const page = (data: T[]) => ({
+ data,
+ prev_page_url: null,
+ next_page_url: null,
+});
+const assignment = {
+ id: 5,
+ version: 1,
+ state: 'linked',
+ reason: 'Synthetic deliberate assignment',
+ data: { requisition_item_id: 1 },
+ snapshot: { item: { description: 'Synthetic item' }, source },
+};
+function render(
+ component: typeof CapitalRegister | typeof CapitalAssignments,
+ props: object,
+) {
+ return renderToStaticMarkup(
+ ,
+ );
+}
+test('read-only capital register preserves archived identity and history without management forms', () => {
+ const html = render(CapitalRegister, {
+ records: page([source]),
+ history: page([source]),
+ departments: [],
+ equipment: [],
+ canManage: false,
+ actorId: 1,
+ tenantId: 1,
+ });
+ expect(html).toContain('Arquivado');
+ expect(html).toContain('Histórico do registo');
+ expect(html).toContain('<script>QA</script>');
+ expect(html).not.toContain(' {
+ const html = render(CapitalAssignments, {
+ requisition: { id: 1, number: 'REQ-QA', status: 'approved' },
+ items: [],
+ current: [assignment],
+ choices: page([]),
+ history: page([assignment]),
+ canWrite: false,
+ actorId: 1,
+ tenantId: 1,
+ });
+ expect(html).toContain('PRJ-QA');
+ expect(html).toContain('versão 3');
+ expect(html).not.toContain(' ,
+ );
+ expect(frozen).toContain('Frozen documentary reference');
+ expect(frozen).toContain('<script>QA</script>');
+ expect(renderToStaticMarkup( )).toBe('');
+});
diff --git a/tests/frontend/import-bank-support.test.tsx b/tests/frontend/import-bank-support.test.tsx
new file mode 100644
index 0000000..d9fe53d
--- /dev/null
+++ b/tests/frontend/import-bank-support.test.tsx
@@ -0,0 +1,143 @@
+import { App } from '@inertiajs/react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { expect, test } from 'vitest';
+import BankSupport from '@/pages/supply/import-bank-support';
+
+function renderBankSupport(canWrite: boolean, dated = false) {
+ const record = {
+ id: 2,
+ record_key: 'synthetic-bank-key',
+ version: 1,
+ state: dated ? 'documented' : 'ready',
+ reason: 'Synthetic bank evidence',
+ data: {
+ commitment_document_id: 1,
+ declaration_document_id: 3,
+ support_document_ids: [4, 5],
+ submission_document_id: dated ? 6 : null,
+ submission_basis: dated
+ ? 'Explicit synthetic delivery evidence'
+ : null,
+ submitted_on: dated ? '2026-11-26' : null,
+ requirements_known: true,
+ required_support_types: ['commercial_invoice'],
+ required_support_counts: { commercial_invoice: 2 },
+ requirements_basis: 'Explicit synthetic bank request',
+ due_on: dated ? '2026-11-27' : null,
+ deadline_basis: dated
+ ? 'Explicit synthetic bank request deadline'
+ : null,
+ },
+ snapshot: {
+ documents: [
+ {
+ id: 1,
+ version: 1,
+ type: 'bank_commitment',
+ reference: '',
+ issuer_reference: 'Synthetic bank',
+ },
+ {
+ id: 3,
+ version: 1,
+ type: 'customs_declaration',
+ reference: 'DU-QA',
+ issuer_reference: 'Synthetic issuer',
+ },
+ {
+ id: 4,
+ version: 1,
+ type: 'commercial_invoice',
+ reference: 'INVOICE-QA-1',
+ issuer_reference: 'Synthetic supplier',
+ },
+ {
+ id: 5,
+ version: 1,
+ type: 'commercial_invoice',
+ reference: 'INVOICE-QA-2',
+ issuer_reference: 'Synthetic supplier',
+ },
+ ...(dated
+ ? [
+ {
+ id: 6,
+ version: 1,
+ type: 'bank_support',
+ reference: 'DELIVERY-QA',
+ issuer_reference: 'Synthetic bank',
+ },
+ ]
+ : []),
+ ],
+ },
+ issues: dated
+ ? []
+ : [
+ 'Falta o comprovativo de entrega ao banco.',
+ 'Prazo documental ainda por indicar.',
+ ],
+ };
+ const page = { data: [record], prev_page_url: null, next_page_url: null };
+ return renderToStaticMarkup(
+ ,
+ );
+}
+
+test('bank consultation and report links preserve unknown deadlines requested counts and the delivery distinction', () => {
+ const html = renderBankSupport(false);
+ expect(html).toContain('Documentos reunidos; entrega por documentar');
+ expect(html).toContain('Factura comercial: 2');
+ expect(html).toContain('Prazo: Por indicar');
+ expect(html).toContain('suporte-bancario.csv');
+ expect(html).toContain('<script>private term</script>');
+ expect(html).not.toContain(' {
+ const html = renderBankSupport(false, true);
+ expect(html).toContain('Prazo: 27/11/2026');
+ expect(html).toContain('Entrega documentada: 26/11/2026');
+ expect(html).toContain('Comprovativo de entrega associado');
+ expect(html).not.toContain('entrega por documentar');
+});
+
+test('bank preparation reuses existing originals and does not apply a generic legal deadline', () => {
+ const html = renderBankSupport(true);
+ expect(html).toContain('Seleccione os originais já registados');
+ expect(html).toContain('Fonte dos requisitos ou informação ainda em falta');
+ expect(html).not.toContain('30 dias');
+});
diff --git a/tests/frontend/import-legal-plan.test.tsx b/tests/frontend/import-legal-plan.test.tsx
new file mode 100644
index 0000000..49af2b9
--- /dev/null
+++ b/tests/frontend/import-legal-plan.test.tsx
@@ -0,0 +1,113 @@
+import { App } from '@inertiajs/react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { expect, test } from 'vitest';
+import ImportEstimate from '@/pages/supply/import-estimate';
+
+function renderPlan(linked = false) {
+ const page = { data: [], prev_page_url: null, next_page_url: null };
+ const source = {
+ id: 4,
+ version: 2,
+ snapshot: {
+ item: { description: 'Synthetic valued item' },
+ legal_rule: {
+ data: { official_reference: 'Preserved official source' },
+ },
+ result: {
+ lines: [
+ {
+ key: 'duty-line',
+ kind: 'duty',
+ label: 'Synthetic documented duty',
+ method: 'ad_valorem',
+ amount_minor: 750,
+ },
+ ],
+ },
+ },
+ };
+ return renderToStaticMarkup(
+ ,
+ );
+}
+
+test('native import preparation offers legal source reuse and additional parcels without silently selecting a value', () => {
+ const html = renderPlan();
+ expect(html).toContain('Reutilizar uma imposição calculada');
+ expect(html).toContain('Synthetic valued item');
+ expect(html).toContain('7.50 MZN');
+ expect(html).toContain('Acrescentar parcela desta família');
+ expect(html).not.toContain('O total conserva a fonte seleccionada');
+});
+
+test('a preserved legal amount retains explicit budget tax treatment and a deliberate manual-detach action', () => {
+ const html = renderPlan(true);
+ expect(html).toContain('O total conserva a fonte seleccionada');
+ expect(html).toContain('divisão entre base e imposto');
+ expect(html).toContain('retirar ligação e conservar os valores');
+ expect(html.match(/]*value="4:duty-line"[^>]*>/)?.[0]).toContain(
+ 'selected=""',
+ );
+});
diff --git a/tests/frontend/import-legal.test.tsx b/tests/frontend/import-legal.test.tsx
new file mode 100644
index 0000000..b5146a3
--- /dev/null
+++ b/tests/frontend/import-legal.test.tsx
@@ -0,0 +1,116 @@
+import { App } from '@inertiajs/react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { expect, test } from 'vitest';
+import Legal from '../../resources/js/pages/supply/import-legal';
+
+function renderLegal(canManage: boolean, withRule = true, withCharges = false) {
+ const data = {
+ title: '',
+ official_reference: 'Synthetic official edition',
+ official_url: 'https://example.test/source.pdf',
+ citation: 'Article QA',
+ valid_from: '2026-01-01',
+ valid_until: null,
+ match_code: '1234',
+ suggested_code: '1234.56',
+ origin_country: null,
+ sector: null,
+ obligations: 'Synthetic conditions only',
+ document_types: ['licence'],
+ charges: withCharges
+ ? [
+ {
+ key: 'synthetic-duty',
+ kind: 'duty',
+ label: 'Synthetic duty',
+ method: 'maximum',
+ rate_percent: '7.500000',
+ specific_minor: 125,
+ quantity_unit: 'KG',
+ basis_reference:
+ 'Synthetic explicit valuation and quantity basis',
+ },
+ ]
+ : [],
+ };
+ const rule = {
+ id: 1,
+ record_key: 'qa',
+ version: 2,
+ state: 'published',
+ data,
+ reason: 'Synthetic publication',
+ source_url: '/requisicoes/1/base-legal/fontes/1',
+ };
+ const page = {
+ data: withRule ? [rule] : [],
+ prev_page_url: null,
+ next_page_url: null,
+ };
+ return renderToStaticMarkup(
+ ,
+ );
+}
+
+test('legal consultation escapes titles preserves periods and offers verified-source downloads without management controls', () => {
+ const html = renderLegal(false);
+ expect(html).toContain('<script>synthetic rule</script>');
+ expect(html).toContain('01/01/2026');
+ expect(html).toContain('sem termo final indicado');
+ expect(html).toContain('/base-legal/fontes/1');
+ expect(html).not.toContain('Guardar preparação para validação aduaneira');
+ expect(html).not.toContain('Preparar proposta com esta fonte');
+});
+
+test('legal preparation makes documentary scope and human publication explicit', () => {
+ const html = renderLegal(true);
+ expect(html).toContain('Preparar proposta com esta fonte');
+ expect(html).toContain('Preparar nova versão');
+ expect(html).toContain('Guardar preparação para validação aduaneira');
+ expect(html).toContain('Exemplar oficial');
+ expect(html).toContain('Licença ou autorização');
+});
+
+test('no matching rule never becomes an assumed zero tax or exemption', () => {
+ const html = renderLegal(false, false);
+ expect(html).toContain('Sem regra publicada correspondente');
+ expect(html).toContain('Não foram presumidos código, taxa ou isenção');
+});
+
+test('documented charges expose their methods rates units and input provenance before estimating', () => {
+ const html = renderLegal(true, true, true);
+ expect(html).toContain(
+ 'Maior valor entre percentagem e montante por unidade',
+ );
+ expect(html).toContain('7.500000%');
+ expect(html).toContain('Taxa específica:');
+ expect(html).toContain('Quantidade em KG');
+ expect(html).toContain('Origem do valor ou da quantidade');
+ expect(html).toContain('Calcular e preservar estimativa');
+});
diff --git a/tests/frontend/import-readiness.test.tsx b/tests/frontend/import-readiness.test.tsx
new file mode 100644
index 0000000..7c6e2bc
--- /dev/null
+++ b/tests/frontend/import-readiness.test.tsx
@@ -0,0 +1,88 @@
+import { App } from '@inertiajs/react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { expect, test } from 'vitest';
+import Readiness from '../../resources/js/pages/supply/import-readiness';
+import ImportTariffSummary from '../../resources/js/components/import-tariff-summary';
+
+test('import follow-up preserves incomplete checks actionable links and unknown dates without rendering financial operations', () => {
+ const html = renderToStaticMarkup(
+ Missing synthetic licence',
+ href: '/compras/importacoes/1/documentos',
+ },
+ ],
+ },
+ }}
+ />,
+ );
+ expect(html).toContain('Verificação incompleta');
+ expect(html).toContain('Por indicar');
+ expect(html).toContain(
+ '<script>Missing synthetic licence</script>',
+ );
+ expect(html).toContain('/compras/importacoes/1/documentos');
+ expect(html).not.toContain(' {
+ const html = renderToStaticMarkup(
+ ,
+ );
+ expect(html).toContain('Preserved official edition');
+ expect(html).toContain('Article QA');
+ expect(html).toContain('versão 5');
+ expect(html).toContain('Preserved documentary conditions');
+});