From e709d900d19cd62fc6a3080fc782ea623be3dd6f Mon Sep 17 00:00:00 2001
From: nala
Date: Fri, 27 Nov 2026 13:49:31 +0200
Subject: [PATCH] commit compras 2711
---
.../Controllers/ImportDossierController.php | 63 +++
.../Controllers/ImportEstimateController.php | 35 ++
.../ImportLandedCostController.php | 9 +-
app/Http/Controllers/OrderPartsController.php | 4 +-
.../ProcurementReportController.php | 39 +-
app/Http/Controllers/PurchaseController.php | 22 +
.../Controllers/RequisitionController.php | 2 +
.../Controllers/SupplyPlanningController.php | 2 +
app/Services/CommonBudget.php | 12 +-
app/Services/ConflictGuard.php | 2 +-
app/Services/ImportCostDocumentHealth.php | 31 +-
app/Services/ImportDossier.php | 147 ++++++
app/Services/ImportEstimates.php | 253 +++++++++++
app/Services/ImportEvidence.php | 40 ++
app/Services/ImportLandedCosts.php | 24 +-
app/Services/ImportParties.php | 149 +++++++
app/Services/InternalRequisitionPort.php | 18 +-
app/Services/InvoiceWorkflow.php | 3 +-
app/Services/OrderCancellationWorkflow.php | 8 +
app/Services/OrderPartsAmendments.php | 78 ++++
app/Services/OrderPartsExchange.php | 111 +++++
app/Services/OrderPartsInvoices.php | 13 +-
app/Services/OrderPartsPreparation.php | 20 +
app/Services/OrderPartsReference.php | 21 +
app/Services/OrderPartsWorkflow.php | 57 ++-
app/Services/ProcurementPaymentInsights.php | 74 ++++
app/Services/QuotationExchange.php | 9 +
app/Services/RequisitionApprovalLevels.php | 4 +-
app/Services/SupplierPayables.php | 13 +
app/Services/SupplyPlanning.php | 3 +
config/import-dossier.php | 6 +
config/import-estimates.php | 3 +
docs/desenvolvimento.md | 14 +
docs/matriz-sgc-reconciliada.md | 18 +
docs/orientacoes-continuidade.md | 14 +
.../proofs/confirmed-payment-insights-qa.json | 16 +
docs/proofs/import-dossier-qa.json | 34 ++
docs/proofs/import-estimates-qa.json | 29 ++
docs/proofs/import-parties-qa.json | 13 +
docs/proofs/rq01-origin-exchange-qa.json | 56 +++
.../purchasing/src/InternalRequisitions.php | 6 +-
.../import-estimate-reconciliation.tsx | 182 ++++++++
.../js/components/import-party-selection.tsx | 386 ++++++++++++++++
.../js/components/order-parts-summary.tsx | 33 ++
.../procurement-payment-insights.tsx | 59 +++
resources/js/lib/import-estimate-money.ts | 10 +
resources/js/lib/journey-help.ts | 57 +++
.../pages/purchases/order-parts-amendment.tsx | 263 +++++++++++
resources/js/pages/purchases/parts.tsx | 126 +++++-
resources/js/pages/purchases/show.tsx | 10 +
resources/js/pages/reports/procurement.tsx | 12 +
resources/js/pages/requisitions/show.tsx | 11 +
resources/js/pages/supply/import-costs.tsx | 30 +-
resources/js/pages/supply/import-dossier.tsx | 351 +++++++++++++++
resources/js/pages/supply/import-estimate.tsx | 418 ++++++++++++++++++
resources/js/pages/supply/index.tsx | 9 +
resources/views/purchases/print.blade.php | 3 +
routes/web.php | 9 +
scripts/quotation-exchange-pg-check.php | 44 ++
.../budget-distribution-recovery-worker.php | 114 ++++-
.../Concurrency/budget-landed-cost-worker.php | 68 ++-
.../Concurrency/budget-order-parts-worker.php | 50 ++-
tests/Concurrency/import-dossier-worker.php | 153 +++++++
.../Feature/BudgetLandedCostsContractTest.php | 70 +++
.../Feature/BudgetOrderPartsContractTest.php | 127 ++++++
tests/Feature/ImportDossierTest.php | 239 ++++++++++
tests/Feature/ImportEstimatePlanTest.php | 51 +++
tests/Feature/ImportEstimatesTest.php | 230 ++++++++++
.../ProcurementPayableInsightsTest.php | 40 ++
tests/Feature/PurchaseAwardOrderTest.php | 242 +++++++++-
tests/Support/ImportQaIdentity.php | 18 +
tests/Support/LandedQaReceipts.php | 32 +-
tests/Unit/LandedQaReceiptsTest.php | 63 ++-
tests/Unit/OrderPartsReferenceTest.php | 32 ++
tests/frontend/import-dossier.test.tsx | 87 ++++
.../import-estimate-reconciliation.test.tsx | 45 ++
tests/frontend/import-estimate.test.tsx | 72 +++
.../frontend/import-party-selection.test.tsx | 91 ++++
tests/frontend/order-parts.test.tsx | 85 ++++
.../procurement-payment-insights.test.tsx | 51 +++
tools/phpstan/optional-packages.stub | 11 +
81 files changed, 5352 insertions(+), 107 deletions(-)
create mode 100644 app/Http/Controllers/ImportDossierController.php
create mode 100644 app/Http/Controllers/ImportEstimateController.php
create mode 100644 app/Services/ImportDossier.php
create mode 100644 app/Services/ImportEstimates.php
create mode 100644 app/Services/ImportEvidence.php
create mode 100644 app/Services/ImportParties.php
create mode 100644 app/Services/OrderPartsAmendments.php
create mode 100644 app/Services/OrderPartsExchange.php
create mode 100644 app/Services/OrderPartsReference.php
create mode 100644 app/Services/ProcurementPaymentInsights.php
create mode 100644 config/import-dossier.php
create mode 100644 config/import-estimates.php
create mode 100644 docs/proofs/confirmed-payment-insights-qa.json
create mode 100644 docs/proofs/import-dossier-qa.json
create mode 100644 docs/proofs/import-estimates-qa.json
create mode 100644 docs/proofs/import-parties-qa.json
create mode 100644 docs/proofs/rq01-origin-exchange-qa.json
create mode 100644 resources/js/components/import-estimate-reconciliation.tsx
create mode 100644 resources/js/components/import-party-selection.tsx
create mode 100644 resources/js/components/procurement-payment-insights.tsx
create mode 100644 resources/js/lib/import-estimate-money.ts
create mode 100644 resources/js/pages/purchases/order-parts-amendment.tsx
create mode 100644 resources/js/pages/supply/import-dossier.tsx
create mode 100644 resources/js/pages/supply/import-estimate.tsx
create mode 100644 tests/Concurrency/import-dossier-worker.php
create mode 100644 tests/Feature/ImportDossierTest.php
create mode 100644 tests/Feature/ImportEstimatePlanTest.php
create mode 100644 tests/Feature/ImportEstimatesTest.php
create mode 100644 tests/Support/ImportQaIdentity.php
create mode 100644 tests/Unit/OrderPartsReferenceTest.php
create mode 100644 tests/frontend/import-dossier.test.tsx
create mode 100644 tests/frontend/import-estimate-reconciliation.test.tsx
create mode 100644 tests/frontend/import-estimate.test.tsx
create mode 100644 tests/frontend/import-party-selection.test.tsx
create mode 100644 tests/frontend/procurement-payment-insights.test.tsx
diff --git a/app/Http/Controllers/ImportDossierController.php b/app/Http/Controllers/ImportDossierController.php
new file mode 100644
index 0000000..394ea83
--- /dev/null
+++ b/app/Http/Controllers/ImportDossierController.php
@@ -0,0 +1,63 @@
+user('web');
+ abort_unless($actor instanceof User, 403);
+
+ return $actor;
+ }
+
+ public function index(Request $request, SupplyRecord $import, ImportDossier $service): Response
+ {
+ $search = $request->validate(['party_search' => 'nullable|string|max:100'])['party_search'] ?? '';
+ 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);
+ $response->headers->set('Cache-Control', 'private, no-store, max-age=0');
+
+ return $response;
+ }
+
+ public function store(Request $request, SupplyRecord $import, ImportDossier $service): Response
+ {
+ $request->validate(['file' => 'required|file']);
+ $file = $request->file('file');
+ abort_unless($file instanceof UploadedFile, 422);
+ $service->record($this->actor($request), $import, $request->except('file'), $file);
+
+ return to_route('imports.dossier', $import);
+ }
+
+ public function evidence(Request $request, SupplyRecord $import, int $document, ImportDossier $service): Response
+ {
+ $source = $service->evidence($this->actor($request), $import, $document);
+ $extension = pathinfo($source->snapshot['evidence']['path'], PATHINFO_EXTENSION);
+
+ return response(app(ImportEvidence::class)->bytes($source), 200, ['Content-Type' => 'application/octet-stream',
+ 'Content-Disposition' => 'attachment; filename="documento-importacao-'.$source->id.'.'.$extension.'"',
+ 'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
+ }
+
+ public function selectParty(Request $request, SupplyRecord $import, ImportParties $service): Response
+ {
+ $service->select($this->actor($request), $import, $request->all());
+
+ return to_route('imports.dossier', $import);
+ }
+}
diff --git a/app/Http/Controllers/ImportEstimateController.php b/app/Http/Controllers/ImportEstimateController.php
new file mode 100644
index 0000000..07961b2
--- /dev/null
+++ b/app/Http/Controllers/ImportEstimateController.php
@@ -0,0 +1,35 @@
+user('web');
+ abort_unless($actor instanceof User, 403);
+ $request->validate(['estimate_page' => 'nullable|integer|min:1|max:1000000', 'budgets_page' => 'nullable|integer|min:1|max:1000000']);
+ Inertia::encryptHistory();
+ $response = Inertia::render('supply/import-estimate', $service->workspace($actor, $requisition))->toResponse($request);
+ $response->headers->set('Cache-Control', 'private, no-store, max-age=0');
+
+ return $response;
+ }
+
+ public function store(Request $request, Requisition $requisition, ImportEstimates $service): RedirectResponse
+ {
+ $actor = $request->user('web');
+ abort_unless($actor instanceof User, 403);
+ $service->save($actor, $requisition, $request->all());
+
+ return back()->with('success', 'Estimativa versionada. A reserva ocorre apenas na submissão da requisição completa.');
+ }
+}
diff --git a/app/Http/Controllers/ImportLandedCostController.php b/app/Http/Controllers/ImportLandedCostController.php
index 4c95a93..24d750e 100644
--- a/app/Http/Controllers/ImportLandedCostController.php
+++ b/app/Http/Controllers/ImportLandedCostController.php
@@ -4,11 +4,11 @@ namespace App\Http\Controllers;
use App\Models\SupplyRecord;
use App\Models\User;
+use App\Services\ImportEvidence;
use App\Services\ImportLandedCosts;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
-use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
@@ -35,7 +35,7 @@ class ImportLandedCostController extends Controller
/** @param array|null $preview */
private function page(Request $request, SupplyRecord $import, ImportLandedCosts $service, ?array $preview = null): Response
{
- $search = $request->validate(['invoice_search' => 'nullable|string|max:100'])['invoice_search'] ?? '';
+ $search = $request->validate(['invoice_search' => 'nullable|string|max:100', 'estimates_page' => 'nullable|integer|min:1|max:1000000'])['invoice_search'] ?? '';
Inertia::encryptHistory();
$response = Inertia::render('supply/import-costs', [...$service->workspace($this->actor($request), $import, $search), 'preview' => $preview])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
@@ -72,7 +72,8 @@ class ImportLandedCostController extends Controller
$source = $service->evidence($this->actor($request), $import, $document);
$evidence = $source->snapshot['evidence'];
- return Storage::disk('local')->download($evidence['path'], 'documento-importacao-'.$source->id.'.'.pathinfo($evidence['path'], PATHINFO_EXTENSION),
- ['Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
+ return response(app(ImportEvidence::class)->bytes($source), 200, [
+ 'Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename="documento-importacao-'.$source->id.'.'.pathinfo($evidence['path'], PATHINFO_EXTENSION).'"',
+ 'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
}
}
diff --git a/app/Http/Controllers/OrderPartsController.php b/app/Http/Controllers/OrderPartsController.php
index 4f1054e..2707ab9 100644
--- a/app/Http/Controllers/OrderPartsController.php
+++ b/app/Http/Controllers/OrderPartsController.php
@@ -80,8 +80,8 @@ class OrderPartsController extends Controller
public function adopt(Request $request, PurchaseAward $award, OrderPartsWorkflow $workflow): RedirectResponse
{
- $data = $request->validate(['operation_key' => 'required|uuid']);
- $workflow->adopt($this->actor($request), $award, $data['operation_key']);
+ $data = $request->validate(['operation_key' => 'required|uuid', 'reference_lines' => 'sometimes|array|list|max:500']);
+ $workflow->adopt($this->actor($request), $award, $data['operation_key'], $data['reference_lines'] ?? []);
return to_route('orders.parts');
}
diff --git a/app/Http/Controllers/ProcurementReportController.php b/app/Http/Controllers/ProcurementReportController.php
index 8973046..2d88a52 100644
--- a/app/Http/Controllers/ProcurementReportController.php
+++ b/app/Http/Controllers/ProcurementReportController.php
@@ -11,6 +11,7 @@ use App\Models\User;
use App\Services\OrganizationAccess;
use App\Services\ProcurementOperationalInsights;
use App\Services\ProcurementPayableInsights;
+use App\Services\ProcurementPaymentInsights;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
@@ -152,7 +153,10 @@ class ProcurementReportController extends Controller
$insights = app(ProcurementOperationalInsights::class)->build($this->records(clone $query, $actor), $instant);
return ['records' => $records, 'counts' => $counts, 'filters' => $filters, 'departments' => $departments, 'generatedAt' => $instant->toIso8601String(), 'insights' => $insights,
- 'payableInsights' => app(ProcurementPayableInsights::class)->build($actor, clone $query)];
+ 'payableInsights' => app(ProcurementPayableInsights::class)->build($actor, clone $query),
+ 'paymentInsights' => app(ProcurementPaymentInsights::class)->build($actor,
+ $this->query($actor, array_diff_key($filters, array_flip(['from', 'to'])), $instant->toDateString()),
+ $filters['from'] ?? null, $filters['to'] ?? null)];
});
Inertia::encryptHistory();
@@ -193,6 +197,39 @@ class ProcurementReportController extends Controller
}, 'posicao-obrigacoes-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
}
+ public function exportPayments(Request $request): Response
+ {
+ $data = $this->snapshot(function () use ($request): array {
+ $instant = CarbonImmutable::now(config('app.timezone'));
+ $filters = $this->filters($request);
+ $actor = $this->actor($request);
+ $payments = app(ProcurementPaymentInsights::class)->build($actor,
+ $this->query($actor, array_diff_key($filters, array_flip(['from', 'to'])), $instant->toDateString()),
+ $filters['from'] ?? null, $filters['to'] ?? null);
+ abort_unless($payments !== null, 403);
+
+ return ['payments' => $payments, 'generated_at' => $instant->toIso8601String()];
+ });
+
+ return response()->streamDownload(function () use ($data) {
+ $output = fopen('php://output', 'w');
+ if ($output === false) {
+ throw new \RuntimeException('Não foi possível exportar a despesa.');
+ }
+ fwrite($output, "\xEF\xBB\xBF");
+ $payments = $data['payments'];
+ fputcsv($output, ['Pagamentos externos confirmados pela data de confirmação', 'Gerado em', $data['generated_at']], ';', '"', '');
+ fputcsv($output, ['Confirmação desde', $payments['from'] ?? '', 'Até (inclusive)', $payments['to'] ?? ''], ';', '"', '');
+ fputcsv($output, ['Facturas no âmbito', 'Históricos indeterminados excluídos', 'Pagamentos confirmados determinados'], ';', '"', '');
+ fputcsv($output, array_values($payments['coverage']), ';', '"', '');
+ fputcsv($output, ['Moeda', 'Pagamentos', 'Despesa (centavos)'], ';', '"', '');
+ foreach ($payments['currencies'] as $row) {
+ fputcsv($output, [$row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
+ }
+ fclose($output);
+ }, 'despesa-confirmada-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
+ }
+
public function export(Request $request): Response
{
$this->filters($request);
diff --git a/app/Http/Controllers/PurchaseController.php b/app/Http/Controllers/PurchaseController.php
index b38d70e..02a5dcd 100644
--- a/app/Http/Controllers/PurchaseController.php
+++ b/app/Http/Controllers/PurchaseController.php
@@ -15,6 +15,7 @@ use App\Services\AgreementOrderLimits;
use App\Services\FormalRecommendation;
use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsAccess;
+use App\Services\OrderPartsAmendments;
use App\Services\OrderPartsWorkflow;
use App\Services\OrganizationAccess;
use App\Services\ProposalComparison;
@@ -98,6 +99,19 @@ class PurchaseController extends Controller
public function distributionAmendment(Request $request, PurchaseOrder $order): Response
{
+ if (OrderPartsAccess::applies($order)) {
+ $actor = $this->access($request);
+ $sources = app(OrderPartsAmendments::class)->sources($actor, $order);
+ Inertia::encryptHistory();
+
+ return Inertia::render('purchases/order-parts-amendment', ['order' => $order->only(['id', 'number', 'currency']), 'sources' => $sources,
+ 'history' => DB::table('budget_order_commands')->where('tenant_id', $actor->tenant_id)
+ ->where('kind', 'amend')->where('document_key', 'like', $order->getAttribute('order_key').'-%')
+ ->orderBy('id')->get(['id', 'created_at', 'created_by', 'snapshot', 'result'])->map(fn ($event) => [
+ 'id' => $event->id, 'created_at' => $event->created_at, 'created_by' => $event->created_by,
+ 'sources' => json_decode($event->snapshot, true, 64, JSON_THROW_ON_ERROR),
+ 'reason' => json_decode($event->result, true, 64, JSON_THROW_ON_ERROR)['reason'] ?? null])]);
+ }
$host = app(RequisitionBudgetDistributions::class);
abort_unless($host->ready(), 503);
$actor = $this->access($request);
@@ -128,6 +142,11 @@ class PurchaseController extends Controller
public function amendDistribution(Request $request, PurchaseOrder $order): RedirectResponse
{
+ if (OrderPartsAccess::applies($order)) {
+ app(OrderPartsAmendments::class)->amend($this->access($request), $order, $request->all());
+
+ return to_route('orders.show', $order);
+ }
app(RequisitionBudgetDistributions::class)->amend($this->access($request), $order, $request->all());
return to_route('orders.show', $order);
@@ -176,6 +195,9 @@ class PurchaseController extends Controller
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
'order' => $order->load('items'),
'orderPartsSources' => $order->snapshot['order_parts']['frames'] ?? [],
+ 'canAmendOrderParts' => OrderPartsAccess::applies($order) && app(OrderPartsWorkflow::class)->ready()
+ && $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)
+ && app(OrderCancellationWorkflow::class)->state($order) === 'issued',
'orderCancellation' => ['enabled' => (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
'state' => app(OrderCancellationWorkflow::class)->state($order),
'canRequest' => app(OrderCancellationWorkflow::class)->canRequest($actor, $order)],
diff --git a/app/Http/Controllers/RequisitionController.php b/app/Http/Controllers/RequisitionController.php
index 87ebf29..7fbc73a 100644
--- a/app/Http/Controllers/RequisitionController.php
+++ b/app/Http/Controllers/RequisitionController.php
@@ -16,6 +16,7 @@ use App\Services\ApprovalRouting;
use App\Services\ComparisonPolicy;
use App\Services\ConflictGuard;
use App\Services\EquipmentWorkflow;
+use App\Services\ImportEstimates;
use App\Services\ImportTariffCodes;
use App\Services\InternalSupplyTrace;
use App\Services\OrganizationAccess;
@@ -123,6 +124,7 @@ class RequisitionController extends Controller
'comparisonPolicy' => app(ComparisonPolicy::class)->forRequest($requisition),
'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(),
'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/Http/Controllers/SupplyPlanningController.php b/app/Http/Controllers/SupplyPlanningController.php
index 449c3dd..f4bbfd5 100644
--- a/app/Http/Controllers/SupplyPlanningController.php
+++ b/app/Http/Controllers/SupplyPlanningController.php
@@ -15,6 +15,7 @@ use App\Models\SupplyRecord;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
+use App\Services\ImportDossier;
use App\Services\ImportLandedCosts;
use App\Services\InventoryReversals;
use App\Services\OrganizationAccess;
@@ -112,6 +113,7 @@ class SupplyPlanningController extends Controller
? $this->approvedOptions($planning, 'contract', $records->pluck('data.contract_key')->push($contractFilters['selected_contract_key'] ?? null), ['agreement_search' => $contractFilters['contract_search'] ?? ''])->map(fn ($r) => $r->only(['record_key', 'version', 'data', 'snapshot'])) : [],
'orderLimitsReady' => app(AgreementOrderLimits::class)->ready(),
'importCostsReady' => $import && $actor->hasFunctions([PurchasingRole::Finance]) && app(ImportLandedCosts::class)->ready(),
+ 'importDossierReady' => $import && $actor->hasFunctions(['import_read', 'import_prepare', 'finance']) && app(ImportDossier::class)->ready(),
'linkedAgreementKey' => $kind === 'policy' ? $request->query('linked_agreement_key') : null,
'linkedContractKey' => $kind === 'agreement' ? $request->query('linked_contract_key') : null,
'agreementSearch' => $agreementFilters['agreement_search'] ?? '', 'agreementFormKey' => $agreementFilters['agreement_form_key'] ?? null,
diff --git a/app/Services/CommonBudget.php b/app/Services/CommonBudget.php
index b34a792..48ded9c 100644
--- a/app/Services/CommonBudget.php
+++ b/app/Services/CommonBudget.php
@@ -17,10 +17,12 @@ final class CommonBudget
{
public const DISTRIBUTIONS_CONTRACT = 'COMMON-BUDGET-DISTRIBUTION-QA-v1';
- public const ORDER_PARTS_CONTRACT = 'COMMON-BUDGET-ORDER-PARTS-QA-v1';
+ public const ORDER_PARTS_CONTRACT = 'COMMON-BUDGET-ORDER-PARTS-QA-v2';
public const LANDED_COSTS_CONTRACT = 'COMMON-BUDGET-LANDED-COST-QA-v2';
+ public const IMPORT_ESTIMATE_CONTRACT = 'COMMON-BUDGET-IMPORT-ESTIMATE-QA-v1';
+
public function for(User $user): BudgetControl
{
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
@@ -28,6 +30,12 @@ final class CommonBudget
$landedTables = ['budget_landed_commands', 'budget_landed_entries'];
$landedPresent = array_values(array_filter($landedTables, fn ($table) => Schema::hasTable($table)));
abort_if(count($landedPresent) !== 0 && count($landedPresent) !== count($landedTables), 503, 'Estrutura de aterragem incompleta; saldo não presumido.');
+ if (in_array('budget_landed_entries', $landedPresent, true)
+ && (! $runtime->hasConstant('IMPORT_ESTIMATE_VERSION') || $runtime->getConstant('IMPORT_ESTIMATE_VERSION') !== self::IMPORT_ESTIMATE_CONTRACT
+ || ! $runtime->hasMethod('reserveImportEstimate'))) {
+ abort_if(DB::table('budget_landed_entries')->where('tenant_id', $user->tenant_id)->where('source_kind', 'import_estimate')->exists(), 503,
+ 'Existem estimativas reservadas. Preserve o motor compatível; pressupostos não podem ser tratados como documentos efectivos.');
+ }
if (! $runtime->hasConstant('LANDED_COSTS_VERSION') || $runtime->getConstant('LANDED_COSTS_VERSION') !== self::LANDED_COSTS_CONTRACT
|| ! $runtime->hasMethod('reserveLandedCosts') || ! $runtime->hasMethod('transitionLandedCosts')) {
foreach ($landedPresent as $table) {
@@ -64,7 +72,7 @@ final class CommonBudget
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Moeda da organização incompatível com esta entrega.');
$roles = in_array($action, ['create', 'approve', 'reinforcement.propose', 'reinforcement.review', 'view'], true)
? [PurchasingRole::Admin, PurchasingRole::Finance]
- : (in_array($action, ['consume', 'consume.preview', 'distribution.amend', 'orders.cancel', 'landed.reserve', 'landed.commit', 'landed.consume', 'landed.cancel', 'landed.amend'], true) ? [PurchasingRole::Finance]
+ : (in_array($action, ['consume', 'consume.preview', 'distribution.amend', 'orders.cancel', 'orders.amend', 'landed.reserve', 'landed.commit', 'landed.consume', 'landed.cancel', 'landed.amend'], true) ? [PurchasingRole::Finance]
: (in_array($action, ['orders.commit', 'orders.adopt'], true) ? [PurchasingRole::Procurement] : null));
app(CurrentActor::class)->lock($user, $roles);
},
diff --git a/app/Services/ConflictGuard.php b/app/Services/ConflictGuard.php
index d5aece3..a23296f 100644
--- a/app/Services/ConflictGuard.php
+++ b/app/Services/ConflictGuard.php
@@ -83,7 +83,7 @@ class ConflictGuard
->merge(AuditLog::query()->where('requisition_id', $requisition->id)->whereIn('action', [
'requisition.created', 'requisition.updated', 'requisition.submitted',
'approval.approved', 'approval.rejected', 'quotation.created', 'quotation.evaluated',
- 'award.created', 'award.approved', 'award.rejected', 'purchase_order.issued',
+ 'award.created', 'award.approved', 'award.rejected', 'purchase_order.issued', 'import.party_selected',
'opening.recorded',
'qualification.defined', 'qualification.assessed',
'admission.adopted', 'admission.proposed', 'admission.reviewed',
diff --git a/app/Services/ImportCostDocumentHealth.php b/app/Services/ImportCostDocumentHealth.php
index 436d2af..7bd3765 100644
--- a/app/Services/ImportCostDocumentHealth.php
+++ b/app/Services/ImportCostDocumentHealth.php
@@ -25,14 +25,15 @@ 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')->where('kind', 'import_cost_doc')->orderBy('id')->limit($limit + 1)->get();
+ $records = DB::table('supply_records')->whereIn('kind', ['import_cost_doc', 'import_document'])->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'] ?? [];
- $prefix = 'import-costs/'.$record->tenant_id.'/'.$record->purchase_order_id.'/';
+ $directory = $record->kind === 'import_cost_doc' ? 'import-costs' : 'import-dossier';
+ $prefix = $directory.'/'.$record->tenant_id.'/'.$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)
@@ -51,7 +52,7 @@ final class ImportCostDocumentHealth
continue;
}
$absolute = str_replace('\\', '/', $resolved);
- $boundary = $root === false ? null : str_replace('\\', '/', $root).'/import-costs/';
+ $boundary = $root === false ? null : str_replace('\\', '/', $root).'/'.$directory.'/';
if ($boundary === null || ! (PHP_OS_FAMILY === 'Windows'
? str_starts_with(strtolower($absolute), strtolower($boundary)) : str_starts_with($absolute, $boundary))) {
$result['invalid_reference']++;
@@ -68,17 +69,19 @@ final class ImportCostDocumentHealth
$result['altered']++;
}
}
- foreach ($disk->getDriver()->listContents('import-costs', true) as $entry) {
- if (! $entry->isFile()) {
- continue;
- }
- if ($result['files_checked'] >= $limit) {
- $limited = true;
- break;
- }
- $result['files_checked']++;
- if (! DB::table('supply_records')->where('kind', 'import_cost_doc')->where('snapshot->evidence->path', $entry->path())->exists()) {
- $result['unreferenced']++;
+ foreach (['import-costs' => 'import_cost_doc', 'import-dossier' => 'import_document'] as $directory => $kind) {
+ foreach ($disk->getDriver()->listContents($directory, true) as $entry) {
+ if (! $entry->isFile()) {
+ continue;
+ }
+ if ($result['files_checked'] >= $limit) {
+ $limited = true;
+ break;
+ }
+ $result['files_checked']++;
+ if (! DB::table('supply_records')->where('kind', $kind)->where('snapshot->evidence->path', $entry->path())->exists()) {
+ $result['unreferenced']++;
+ }
}
}
foreach (['missing', 'altered', 'invalid_reference', 'unreferenced'] as $reason) {
diff --git a/app/Services/ImportDossier.php b/app/Services/ImportDossier.php
new file mode 100644
index 0000000..d07ae92
--- /dev/null
+++ b/app/Services/ImportDossier.php
@@ -0,0 +1,147 @@
+ 'Factura comercial', 'packing_list' => 'Lista de embalagem',
+ 'transport_document' => 'Documento de transporte', 'insurance' => 'Seguro',
+ 'origin_certificate' => 'Certificado de origem', 'licence' => 'Licença ou autorização',
+ 'customs_declaration' => 'Declaração aduaneira ou documento único', 'customs_assessment' => 'Liquidação aduaneira',
+ 'payment_evidence' => 'Comprovativo documental de pagamento', 'customs_release' => 'Documento de libertação',
+ 'bank_commitment' => 'Termo de compromisso bancário', 'bank_support' => 'Documento de suporte bancário',
+ 'written_instructions' => 'Instruções escritas', 'other' => 'Outro documento',
+ ];
+
+ public function ready(): bool
+ {
+ $db = DB::connection();
+
+ return config('import-dossier.qa_enabled') === true && app()->environment('testing')
+ && (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
+ || ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
+ }
+
+ /** @return array{User,SupplyRecord,PurchaseOrder} */
+ public function context(User $actor, SupplyRecord $import, bool $write = false): array
+ {
+ abort_unless($this->ready(), 503);
+ app(ConflictGuard::class)->lockCompany($actor);
+ $actor = app(CurrentActor::class)->lock($actor);
+ abort_unless($actor->hasFunctions($write ? ['import_prepare'] : ['import_read', 'import_prepare', 'finance']), 403);
+ abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
+ $current = SupplyRecord::query()->where('kind', 'import')->where('record_key', $import->record_key)->latest('version')->lockForUpdate()->firstOrFail();
+ abort_unless($current->id === $import->id, 409, 'A importação mudou. Consulte a versão actual.');
+ $order = PurchaseOrder::query()->visibleTo($actor)->whereKey($current->purchase_order_id)->lockForUpdate()->firstOrFail();
+ app(OrderPartsAccess::class)->assertProcess($actor, $order);
+
+ return [$actor, $current, $order];
+ }
+
+ /** @return array */
+ public function workspace(User $actor, SupplyRecord $import): array
+ {
+ return DB::transaction(function () use ($actor, $import): array {
+ [$actor, $current, $order] = $this->context($actor, $import);
+ $documents = SupplyRecord::query()->where('kind', 'import_document')->where('purchase_order_id', $order->id)
+ ->where('snapshot->import_key', $current->record_key)->latest('id')
+ ->paginate(20, ['id', 'record_key', 'version', 'state', 'created_by', 'created_at', 'data', 'reason', 'snapshot'])->withQueryString();
+ $latestIds = app(SupplyPlanning::class)->latest('import_document')->where('purchase_order_id', $order->id)->pluck('id')->all();
+ $documents->through(fn ($record) => [...$record->only(['id', 'record_key', 'version', 'state', 'created_by', 'created_at', 'data', 'reason']),
+ 'current' => in_array($record->id, $latestIds, true), 'supersedes' => $record->snapshot['supersedes'], 'sha256' => $record->snapshot['evidence']['sha256']]);
+
+ return ['importRecord' => $current->only(['id', 'record_key', 'version']), 'order' => $order->only(['id', 'number']),
+ 'documents' => $documents, 'types' => self::TYPES, 'canWrite' => $actor->hasFunctions(['import_prepare']),
+ 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
+ });
+ }
+
+ /** @param array $input */
+ public function record(User $actor, SupplyRecord $import, array $input, UploadedFile $file): SupplyRecord
+ {
+ abort_unless($this->ready(), 503);
+ $data = Validator::make(['record_key' => null, 'version' => 0, ...$input, 'file' => $file], [
+ 'operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
+ 'type' => 'required|in:'.implode(',', array_keys(self::TYPES)), 'reference' => 'required|string|min:1|max:180',
+ 'issued_on' => 'nullable|date_format:Y-m-d', 'issuer_reference' => 'required|string|min:1|max:180',
+ 'notes' => 'nullable|string|max:4000', 'reason' => 'required|string|min:10|max:4000',
+ 'file' => 'required|file|mimes:pdf,jpg,jpeg,png|extensions:pdf,jpg,jpeg,png|max:2048',
+ ])->validate();
+ unset($data['file']);
+ $data['operation_key'] = strtolower($data['operation_key']);
+ $data['reference'] = trim($data['reference']);
+ $data['issuer_reference'] = trim($data['issuer_reference']);
+ abort_unless($data['reference'] !== '' && $data['issuer_reference'] !== '', 422);
+ $sha = hash_file('sha256', $file->getPathname());
+ abort_unless(is_string($sha) && $file->getSize() > 0, 422);
+ $hash = hash('sha256', json_encode([$import->record_key, $data, $sha], JSON_THROW_ON_ERROR));
+ $newPath = null;
+ try {
+ return DB::transaction(function () use ($actor, $import, $data, $file, $sha, $hash, &$newPath): SupplyRecord {
+ [$actor, $current, $order] = $this->context($actor, $import, true);
+ $replay = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
+ if ($replay !== null) {
+ abort_unless($replay->kind === 'import_document' && $replay->created_by === $actor->id && hash_equals($replay->input_hash, $hash), 409);
+
+ return $replay;
+ }
+ $previous = $data['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_document')
+ ->where('record_key', $data['record_key'])->latest('version')->lockForUpdate()->firstOrFail();
+ abort_unless((int) $data['version'] === ($previous->version ?? 0), 409, 'O documento mudou. Consulte a versão actual.');
+ if ($previous !== null) {
+ abort_unless($previous->purchase_order_id === $order->id && $previous->snapshot['import_key'] === $current->record_key
+ && $previous->data['type'] === $data['type'], 409, 'Uma correcção conserva a importação e o tipo documental.');
+ }
+ abort_if(SupplyRecord::query()->where('kind', 'import_document')->where('purchase_order_id', $order->id)
+ ->when($previous !== null, fn ($q) => $q->where('record_key', '!=', $previous->record_key))
+ ->where('data->type', $data['type'])->where('data->reference', $data['reference'])
+ ->where('data->issuer_reference', $data['issuer_reference'])->exists(), 409, 'Documento já registado. Consulte ou corrija a versão existente.');
+ $key = $previous->record_key ?? (string) Str::uuid();
+ $version = ($previous->version ?? 0) + 1;
+ $newPath = $file->storeAs('import-dossier/'.$actor->tenant_id.'/'.$order->id, $key.'-'.$version.'.'.$file->extension(), 'local');
+ abort_unless(is_string($newPath), 503, 'Não foi possível conservar o original privado.');
+ $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_document', 'record_key' => $key,
+ 'version' => $version, 'state' => 'recorded', 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
+ 'data' => array_diff_key($data, array_flip(['operation_key', 'record_key', 'version', 'reason'])),
+ 'snapshot' => ['import_key' => $current->record_key, 'import_version' => $current->version, 'supersedes' => $previous->id ?? null,
+ 'evidence' => ['disk' => 'local', 'path' => $newPath, 'sha256' => $sha, 'size' => $file->getSize(), 'mime_type' => $file->getMimeType()],
+ 'financial_effects' => false, 'external_submission' => false],
+ 'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
+ app(ImportEvidence::class)->bytes($record);
+ app(RequisitionWorkflow::class)->audit($actor, 'import.document_recorded', Requisition::query()->whereKey($order->requisition_id)->firstOrFail(), null,
+ ['record_id' => $record->id, 'record_key' => $record->record_key, 'version' => $version, 'type' => $data['type'], 'sha256' => $sha, 'financial_effects' => false]);
+
+ return $record;
+ });
+ } catch (\Throwable $error) {
+ if (is_string($newPath) && ! DB::table('supply_records')->where('tenant_id', $actor->tenant_id)->where('snapshot->evidence->path', $newPath)->exists()) {
+ Storage::disk('local')->delete($newPath);
+ }
+ throw $error;
+ }
+ }
+
+ public function evidence(User $actor, SupplyRecord $import, int $id): SupplyRecord
+ {
+ return DB::transaction(function () use ($actor, $import, $id): SupplyRecord {
+ [, $current, $order] = $this->context($actor, $import);
+ $document = SupplyRecord::query()->where('kind', 'import_document')->where('purchase_order_id', $order->id)
+ ->where('snapshot->import_key', $current->record_key)->whereKey($id)->firstOrFail();
+ app(ImportEvidence::class)->bytes($document);
+
+ return $document;
+ });
+ }
+}
diff --git a/app/Services/ImportEstimates.php b/app/Services/ImportEstimates.php
new file mode 100644
index 0000000..7cd12a1
--- /dev/null
+++ b/app/Services/ImportEstimates.php
@@ -0,0 +1,253 @@
+environment('testing')
+ && class_exists(BudgetImportEstimate::class) && Schema::hasTable('supply_records')
+ && (($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())));
+ }
+
+ public function current(Requisition $request): ?SupplyRecord
+ {
+ if (! Schema::hasTable('supply_records')) {
+ return null;
+ }
+
+ return SupplyRecord::query()->where('kind', 'import_estimate')->where('data->requisition_id', $request->id)->latest('version')->first();
+ }
+
+ /** @return array */
+ public function workspace(User $actor, Requisition $request): array
+ {
+ abort_unless($this->ready(), 503);
+ abort_unless(auth()->id() === $actor->id, 403);
+ $actor = User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
+ abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
+ $request = Requisition::query()->visibleTo($actor)->findOrFail($request->id);
+ $latest = $this->current($request);
+
+ return ['requisition' => $request->only(['id', 'number', 'status', 'subtotal_minor', 'tax_minor', 'total_minor']),
+ '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(),
+ 'budgets' => Budget::query()->where('cost_center_id', $request->cost_center_id)->where('year', now()->year)->whereNotNull('approved_by')
+ ->where('kind', $request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating')
+ ->orderBy('id')->paginate(20, ['id', 'includes_tax'], 'budgets_page')->withQueryString(),
+ 'canPrepare' => $request->status === 'draft' && $request->draft_input === null
+ && (($actor->id === $request->requester_id && app(OrganizationAccess::class)->canRequest($actor)) || $actor->hasFunctions([PurchasingRole::Procurement])),
+ 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
+ }
+
+ /** @return array|null */
+ public function approval(Requisition $request): ?array
+ {
+ $record = $this->current($request);
+ if ($record === null) {
+ if ($this->ready()) {
+ abort_if(SupplyRecord::query()->where('kind', 'import_tariff')->where('data->requisition_id', $request->id)->exists(), 422,
+ 'Prepare a estimativa dos artigos importados antes de submeter.');
+ }
+
+ return null;
+ }
+ 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.');
+ $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.');
+
+ return ['record_id' => $record->id, 'record_key' => $record->record_key, 'version' => $record->version,
+ 'budget_id' => $budget->id, 'plan' => $record->snapshot['plan']];
+ }
+
+ public function reserve(User $actor, Requisition $request): void
+ {
+ $estimate = $this->approval($request);
+ if ($estimate === null) {
+ return;
+ }
+ $record = $this->current($request);
+ abort_unless($record !== null, 409);
+ $adapter = app(CommonBudget::class);
+ $engine = $adapter->for($actor);
+ abort_unless(in_array('reserveImportEstimate', get_class_methods($engine), true), 503, 'Motor sem reserva pré-documental.');
+ $adapter->execute(fn () => (new \ReflectionMethod($engine, 'reserveImportEstimate'))->invoke($engine, $record->record_key, $record->version, $record->data['budget_id'],
+ $request->id, $record->snapshot['plan']['goods'], $record->data['components'], $record->operation_key));
+ }
+
+ public function release(User $actor, Requisition $request): void
+ {
+ $policy = $request->getAttribute('approval_snapshot');
+ $estimate = is_array($policy) ? ($policy['import_estimate'] ?? null) : null;
+ if ($estimate === null) {
+ return;
+ }
+ abort_unless($this->ready(), 503, 'Preserve o motor das estimativas reservadas.');
+ $adapter = app(CommonBudget::class);
+ $engine = $adapter->for($actor);
+ abort_unless(in_array('releaseImportEstimate', get_class_methods($engine), true), 503);
+ $adapter->execute(fn () => (new \ReflectionMethod($engine, 'releaseImportEstimate'))->invoke($engine, $estimate['record_key'], $estimate['version'],
+ $estimate['plan']['fingerprint'], (string) Str::uuid()));
+ }
+
+ public function reconciliationSource(PurchaseOrder $order, int $id): SupplyRecord
+ {
+ abort_unless($this->ready(), 503);
+ $source = SupplyRecord::query()->where('kind', 'import_estimate')->findOrFail($id);
+ abort_unless(in_array($source->data['requisition_id'], app(OrderPartsAccess::class)->origins($order), true), 404);
+ $request = Requisition::query()->whereKey($source->data['requisition_id'])->firstOrFail();
+ $policy = $request->getAttribute('approval_snapshot');
+ abort_unless(is_array($policy) && ($policy['import_estimate']['record_id'] ?? null) === $source->id, 409,
+ 'Seleccione a estimativa efectivamente incluída na aprovação da origem.');
+
+ return $source;
+ }
+
+ /** @return array */
+ public function reconciliationWorkspace(User $actor, PurchaseOrder $order): array
+ {
+ if (! $this->ready()) {
+ abort_if($this->approvedSourceIds($order) !== [], 503, 'Preserve a capacidade das estimativas aprovadas desta ordem.');
+
+ return ['data' => [], 'prev_page_url' => null, 'next_page_url' => null];
+ }
+ $ids = $this->approvedSourceIds($order);
+ $engine = app(CommonBudget::class)->for($actor);
+ $page = SupplyRecord::query()->where('kind', 'import_estimate')->whereIn('id', $ids)->orderBy('id')->paginate(20, ['*'], 'estimates_page')->withQueryString();
+ $page->through(function ($record) use ($engine) {
+ $state = (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $record->record_key);
+
+ return ['id' => $record->id, 'version' => $record->version, 'requisition_id' => $record->data['requisition_id'],
+ 'budget_id' => $record->data['budget_id'], 'revision' => $state['result']['revision'] ?? null,
+ 'reserved_minor' => $state['result']['reserved_minor'] ?? null, 'committed_minor' => $state['result']['committed_minor'] ?? null];
+ });
+
+ return $page->toArray();
+ }
+
+ public function hasOutstanding(User $actor, PurchaseOrder $order): bool
+ {
+ if (! $this->ready()) {
+ abort_if($this->approvedSourceIds($order) !== [], 503, 'Preserve a capacidade das estimativas aprovadas desta ordem.');
+
+ return false;
+ }
+ $engine = app(CommonBudget::class)->for($actor);
+ $ids = $this->approvedSourceIds($order);
+ $records = SupplyRecord::query()->where('kind', 'import_estimate')->whereIn('id', $ids);
+ abort_unless((clone $records)->count() === count($ids), 503, 'Uma estimativa aprovada está em falta.');
+ foreach ($records->lazyById() as $record) {
+ $state = (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $record->record_key);
+ if (! is_array($state)) {
+ abort(503, 'A estimativa aprovada não tem a posição financeira esperada.');
+ }
+ if ($state['result']['reserved_minor'] + $state['result']['committed_minor'] > 0) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /** @return list */
+ private function approvedSourceIds(PurchaseOrder $order): array
+ {
+ $ids = [];
+ foreach (Requisition::query()->whereIn('id', app(OrderPartsAccess::class)->origins($order))->get() as $request) {
+ $policy = $request->getAttribute('approval_snapshot');
+ if (is_array($policy) && isset($policy['import_estimate']['record_id'])) {
+ $ids[] = $policy['import_estimate']['record_id'];
+ }
+ }
+
+ return $ids;
+ }
+
+ /** @return array */
+ public function native(Requisition $request): array
+ {
+ return ['requisition_id' => $request->id, 'cost_center_id' => $request->cost_center_id,
+ 'subtotal_minor' => $request->subtotal_minor, 'tax_minor' => $request->tax_minor, 'total_minor' => $request->total_minor,
+ 'items' => $request->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity', 'subtotal_minor', 'tax_minor', 'total_minor'])->toArray()];
+ }
+
+ /** @param array $input */
+ public function save(User $actor, Requisition $request, array $input): SupplyRecord
+ {
+ abort_unless($this->ready(), 503);
+ $data = Validator::make($input, [
+ 'operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'budget_id' => 'required|integer|min:1',
+ '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',
+ 'components.*.subtotal_minor' => 'present|nullable|integer|min:0|max:100000000000000',
+ 'components.*.tax_minor' => 'present|nullable|integer|min:0|max:100000000000000',
+ 'components.*.total_minor' => 'present|nullable|integer|min:0|max:100000000000000', 'reason' => 'required|string|min:10|max:4000',
+ ])->validate();
+ $data['version'] = (int) $data['version'];
+ $data['budget_id'] = (int) $data['budget_id'];
+ foreach ($data['components'] as &$component) {
+ foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
+ $component[$field] = $component[$field] === null ? null : (int) $component[$field];
+ }
+ }
+ unset($component);
+ $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);
+ abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
+ $request = Requisition::query()->visibleTo($actor)->findOrFail($request->id);
+ abort_unless(($actor->id === $request->requester_id && app(OrganizationAccess::class)->canRequest($actor))
+ || $actor->hasFunctions([PurchasingRole::Procurement]), 403);
+ app(ConflictGuard::class)->assertParticipation($actor, $request);
+ $retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
+ if ($retry !== null) {
+ abort_unless($retry->kind === 'import_estimate' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
+
+ return $retry;
+ }
+ abort_unless($request->status === 'draft' && $request->draft_input === null, 409, 'Prepare a estimativa no rascunho completo, antes de submeter.');
+ $old = $this->current($request);
+ abort_unless($data['version'] === ($old->version ?? 0), 409, 'A estimativa mudou. Preserve os seus pressupostos e consulte a versão actual.');
+ $budget = Budget::query()->whereKey($data['budget_id'])->where('cost_center_id', $request->cost_center_id)
+ ->where('kind', $request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating')
+ ->where('year', now()->year)->whereNotNull('approved_by')->firstOrFail();
+ $native = $this->native($request);
+ $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'])],
+ '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]);
+
+ return $record;
+ });
+ }
+}
diff --git a/app/Services/ImportEvidence.php b/app/Services/ImportEvidence.php
new file mode 100644
index 0000000..bd7dc53
--- /dev/null
+++ b/app/Services/ImportEvidence.php
@@ -0,0 +1,40 @@
+snapshot['evidence'] ?? [];
+ $prefix = match ($record->kind) {
+ 'import_cost_doc' => 'import-costs',
+ 'import_document' => 'import-dossier',
+ default => null,
+ };
+ $path = $evidence['path'] ?? null;
+ $expected = $prefix.'/'.$record->tenant_id.'/'.$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_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');
+ try {
+ abort_unless($disk->exists($path) && $disk->size($path) === $evidence['size'], 409, 'O original está indisponível ou alterado.');
+ $bytes = $disk->get($path);
+ } catch (FilesystemException) {
+ abort(409, 'O original está indisponível ou alterado.');
+ }
+ abort_unless(is_string($bytes) && strlen($bytes) === $evidence['size'] && hash_equals($evidence['sha256'], hash('sha256', $bytes)), 409,
+ 'O original está indisponível ou alterado.');
+
+ return $bytes;
+ }
+}
diff --git a/app/Services/ImportLandedCosts.php b/app/Services/ImportLandedCosts.php
index 3647876..5b4174a 100644
--- a/app/Services/ImportLandedCosts.php
+++ b/app/Services/ImportLandedCosts.php
@@ -84,6 +84,7 @@ final class ImportLandedCosts
'order_id' => $order->id, 'order_number' => $order->number, 'context' => array_intersect_key($current->data, array_flip(['purpose', 'jurisdiction', 'origin_country', 'dispatch_country', 'incoterm', 'regime'])),
'context_changed' => $latest !== null && $this->preparationImportRevision($latest->snapshot['plan']) !== $this->importRevision($current)],
'importTariffs' => $order->snapshot['import_tariffs'] ?? [],
+ 'estimateSources' => $this->financialReady() ? app(ImportEstimates::class)->reconciliationWorkspace($actor, $order) : ['data' => [], 'prev_page_url' => null, 'next_page_url' => null],
'invoices' => $invoices, 'documents' => $documents, 'budgets' => $budgets,
'history' => $history, 'latest' => $latest, 'financialReady' => $this->financialReady(), 'financialState' => $financial, 'financialEvents' => $financialEvents,
'orderItems' => $order->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity']),
@@ -99,8 +100,7 @@ final class ImportLandedCosts
[, $current, $order] = $this->context($actor, $import);
$document = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)->findOrFail($documentId);
abort_unless($document->snapshot['import_key'] === $current->record_key, 404);
- $evidence = $document->snapshot['evidence'];
- abort_unless(Storage::disk('local')->exists($evidence['path']) && hash_equals($evidence['sha256'], hash('sha256', Storage::disk('local')->get($evidence['path']))), 409, 'A evidência documental está indisponível ou alterada.');
+ app(ImportEvidence::class)->bytes($document);
return $document;
});
@@ -329,7 +329,11 @@ final class ImportLandedCosts
public function financial(User $actor, SupplyRecord $import, SupplyRecord $plan, array $input): SupplyRecord
{
abort_unless($this->financialReady(), 503, 'A estrutura financeira adicional só está preparada em QA.');
- $data = Validator::make($input, ['operation_key' => 'required|uuid', 'action' => 'required|in:reserve,commit,consume,amend,cancel',
+ $data = Validator::make($input, ['operation_key' => 'required|uuid', 'action' => 'required|in:reserve,commit,consume,amend,cancel,reconcile_estimate',
+ 'estimate_id' => 'required_if:action,reconcile_estimate|prohibited_unless:action,reconcile_estimate|integer|min:1',
+ 'estimate_revision' => 'required_if:action,reconcile_estimate|prohibited_unless:action,reconcile_estimate|integer|min:1',
+ 'estimate_release_minor' => 'required_if:action,reconcile_estimate|prohibited_unless:action,reconcile_estimate|integer|min:1|max:100000000000000',
+ 'actual_operation_key' => 'required_if:action,reconcile_estimate|prohibited_unless:action,reconcile_estimate|uuid|different:operation_key',
'financial_revision' => 'required|integer|min:0', 'sources' => 'sometimes|array|max:100',
'sources.*' => 'required|string|max:120|distinct|regex:/^[A-Za-z0-9:_-]+$/D',
'reason' => 'required|string|min:10|max:4000'])->validate();
@@ -359,9 +363,21 @@ final class ImportLandedCosts
$state = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $plan->record_key));
abort_unless($data['financial_revision'] === (is_array($state) ? $state['result']['revision'] : 0), 409, 'A posição orçamental mudou; conserve a preparação e actualize antes de continuar.');
abort_unless(! in_array($data['action'], ['reserve', 'amend'], true) || $data['sources'] === [], 422, 'A reserva e a reafectação usam a preparação conferida completa.');
+ if ($data['action'] === 'reserve') {
+ abort_if(app(ImportEstimates::class)->hasOutstanding($actor, $order), 409,
+ 'Existe uma estimativa reservada. Reconcilie explicitamente a parcela correspondente em vez de reservar o mesmo custo outra vez.');
+ }
$args = [$plan->record_key, $plan->version, $plan->snapshot['plan']['budget_id'], $plan->data['components'], $plan->snapshot['plan']['documents'], $data['operation_key']];
$method = 'reserveLandedCosts';
- if ($data['action'] !== 'reserve') {
+ if ($data['action'] === 'reconcile_estimate') {
+ abort_unless($data['sources'] === [], 422);
+ $estimate = app(ImportEstimates::class)->reconciliationSource($order, (int) $data['estimate_id']);
+ abort_unless(in_array('reconcileImportEstimate', get_class_methods($engine), true), 503);
+ $method = 'reconcileImportEstimate';
+ $args = [$estimate->record_key, $estimate->version, $estimate->snapshot['plan']['fingerprint'], (int) $data['estimate_revision'],
+ (int) $data['estimate_release_minor'], $plan->record_key, $plan->version, $plan->snapshot['plan']['budget_id'],
+ $plan->data['components'], $plan->snapshot['plan']['documents'], $data['operation_key'], strtolower($data['actual_operation_key'])];
+ } elseif ($data['action'] !== 'reserve') {
abort_unless(is_array($state), 409, 'Registe primeiro a reserva adicional.');
if ($data['action'] === 'amend') {
abort_unless($state['result']['budget_id'] === $plan->snapshot['plan']['budget_id'], 409, 'A reafectação desta versão conserva a dotação e a sua base de imposto.');
diff --git a/app/Services/ImportParties.php b/app/Services/ImportParties.php
new file mode 100644
index 0000000..ea0057b
--- /dev/null
+++ b/app/Services/ImportParties.php
@@ -0,0 +1,149 @@
+ 'Despachante aduaneiro', 'forwarder' => 'Transitário'];
+
+ public function canSelect(User $actor, PurchaseOrder $order): bool
+ {
+ if (! $actor->hasFunctions(['procurement']) || ! $actor->hasFunctions(['import_prepare'])
+ || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
+ return false;
+ }
+
+ return ! Requisition::query()->whereIn('id', app(OrderPartsAccess::class)->origins($order))->where('requester_id', $actor->id)->exists();
+ }
+
+ /** @return array */
+ public function workspace(User $actor, SupplyRecord $import, string $search = ''): array
+ {
+ return DB::transaction(function () use ($actor, $import, $search): array {
+ [$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import);
+ $canSelect = $this->canSelect($actor, $order);
+ $parties = SupplyRecord::query()->where('kind', 'import_party')->where('purchase_order_id', $order->id)
+ ->where('snapshot->import_key', $current->record_key)->latest('id')
+ ->paginate(10, ['id', 'record_key', 'version', 'data', 'snapshot', 'reason', 'created_at', 'created_by'], 'parties_page')->withQueryString();
+ $currentParties = app(SupplyPlanning::class)->latest('import_party')->where('purchase_order_id', $order->id)
+ ->where('snapshot->import_key', $current->record_key)->get();
+ $currentParties = $currentParties->map(fn ($record) => [...$record->only(['id', 'record_key', 'version', 'data', 'snapshot', 'reason']),
+ 'issues' => $this->issues($actor, $order, $record)]);
+ $suppliers = Supplier::query()->when(! $canSelect, fn ($q) => $q->whereRaw('1=0'))->where('status', 'active')->where('blocked', false)
+ ->where('next_review', '>=', today())->when($search !== '', fn ($q) => $q->where(fn ($match) => $match
+ ->whereRaw('LOWER(name) LIKE ?', ['%'.addcslashes(mb_strtolower($search), '%_\\').'%'])
+ ->orWhereRaw('LOWER(nuit) LIKE ?', ['%'.addcslashes(mb_strtolower($search), '%_\\').'%'])))
+ ->orderBy('name')->orderBy('id')->paginate(20, ['id', 'name', 'nuit', 'version'], 'party_suppliers_page')->withQueryString();
+ $instructions = app(SupplyPlanning::class)->latest('import_document')->where('purchase_order_id', $order->id)
+ ->where('snapshot->import_key', $current->record_key)->where('data->type', 'written_instructions')
+ ->latest('id')->paginate(20, ['id', 'record_key', 'version', 'data'], 'instructions_page')->withQueryString();
+
+ return ['roles' => self::ROLES, 'canSelect' => $canSelect, 'search' => $search, 'suppliers' => $suppliers,
+ 'instructions' => $instructions, 'current' => $currentParties, 'history' => $parties];
+ });
+ }
+
+ /** @return list */
+ private function issues(User $actor, PurchaseOrder $order, SupplyRecord $record): array
+ {
+ $issues = [];
+ $supplier = Supplier::query()->whereKey($record->data['supplier_id'])->first();
+ if ($supplier === null || ! $supplier->eligible() || $supplier->only(['id', 'name', 'nuit', 'version']) !== $record->snapshot['supplier']) {
+ $issues[] = 'O cadastro ou a elegibilidade da entidade mudou; confira a selecção.';
+ }
+ foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
+ $request = Requisition::query()->whereKey($origin)->firstOrFail();
+ if (app(ConflictGuard::class)->processBlocked($request, $record->data['supplier_id'], $actor)) {
+ $issues[] = 'Existe um conflito de interesses activo com a entidade seleccionada.';
+ break;
+ }
+ }
+ $latest = app(SupplyPlanning::class)->latest('import_document')->where('record_key', $record->snapshot['instructions']['record_key'])->first();
+ if ($latest === null || $latest->id !== $record->data['instruction_document_id']) {
+ $issues[] = 'As instruções escritas têm uma versão diferente; confira a selecção.';
+ } else {
+ try {
+ app(ImportEvidence::class)->bytes($latest);
+ } catch (HttpExceptionInterface) {
+ $issues[] = 'O original das instruções está indisponível ou alterado.';
+ }
+ }
+
+ return $issues;
+ }
+
+ /** @param array $input */
+ public function select(User $actor, SupplyRecord $import, array $input): SupplyRecord
+ {
+ $data = Validator::make($input, ['operation_key' => 'required|uuid', 'role' => 'required|in:broker,forwarder',
+ 'version' => 'required|integer|min:0', 'supplier_id' => 'required|integer|min:1', 'supplier_version' => 'required|integer|min:1',
+ 'instruction_document_id' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:4000', 'no_conflict' => 'required|accepted'])->validate();
+ $data['operation_key'] = strtolower($data['operation_key']);
+ $hash = hash('sha256', json_encode([$import->record_key, $data], JSON_THROW_ON_ERROR));
+
+ return DB::transaction(function () use ($actor, $import, $data, $hash): SupplyRecord {
+ [$actor, $current, $order] = app(ImportDossier::class)->context($actor, $import, true);
+ abort_unless($this->canSelect($actor, $order), 403, 'A selecção cabe ao comprador, distinto dos requisitantes das origens.');
+ $replay = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
+ if ($replay !== null) {
+ abort_unless($replay->kind === 'import_party' && $replay->created_by === $actor->id && hash_equals($replay->input_hash, $hash), 409);
+
+ return $replay;
+ }
+ $previous = SupplyRecord::query()->where('kind', 'import_party')->where('purchase_order_id', $order->id)
+ ->where('snapshot->import_key', $current->record_key)->where('data->role', $data['role'])->latest('version')->lockForUpdate()->first();
+ abort_unless((int) $data['version'] === ($previous->version ?? 0), 409, 'A selecção mudou. Consulte a versão actual.');
+ $supplier = Supplier::query()->whereKey($data['supplier_id'])->lockForUpdate()->firstOrFail();
+ abort_unless($supplier->version === (int) $data['supplier_version'], 409, 'O cadastro da entidade mudou. Consulte a versão actual antes de seleccionar.');
+ abort_unless($supplier->eligible(), 422, 'Seleccione uma entidade activa e elegível no cadastro.');
+ foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
+ $request = Requisition::query()->whereKey($origin)->firstOrFail();
+ app(ConflictGuard::class)->assertProcess($request, $supplier->id, $actor);
+ }
+ $instructions = app(ImportDossier::class)->evidence($actor, $current, (int) $data['instruction_document_id']);
+ abort_unless($instructions->data['type'] === 'written_instructions'
+ && app(SupplyPlanning::class)->latest('import_document')->where('record_key', $instructions->record_key)->value('id') === $instructions->id, 409,
+ 'Seleccione a versão actual das instruções escritas desta importação.');
+ $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_party',
+ 'record_key' => $previous->record_key ?? (string) Str::uuid(), 'version' => ($previous->version ?? 0) + 1,
+ 'state' => 'selected', 'purchase_order_id' => $order->id, 'supplier_id' => $supplier->id, 'created_by' => $actor->id,
+ 'data' => ['role' => $data['role'], 'supplier_id' => $supplier->id, 'instruction_document_id' => $instructions->id],
+ 'snapshot' => ['import_key' => $current->record_key, 'import_version' => $current->version, 'supersedes' => $previous->id ?? null,
+ 'supplier' => $supplier->only(['id', 'name', 'nuit', 'version']),
+ 'instructions' => $instructions->only(['id', 'record_key', 'version', 'data']),
+ 'financial_effects' => false, 'no_conflict' => true],
+ 'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
+ foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
+ app(RequisitionWorkflow::class)->audit($actor, 'import.party_selected', Requisition::query()->whereKey($origin)->firstOrFail(), null,
+ ['record_id' => $record->id, 'role' => $data['role'], 'supplier_id' => $supplier->id, 'version' => $record->version, 'no_conflict' => true]);
+ }
+
+ return $record;
+ });
+ }
+
+ public function assertCurrent(User $actor, PurchaseOrder $order, string $importKey): void
+ {
+ $parties = app(SupplyPlanning::class)->latest('import_party')->where('purchase_order_id', $order->id)->where('snapshot->import_key', $importKey)->get();
+ if ($parties->isEmpty()) {
+ return; // Historic imports without a selected party retain their existing workflow.
+ }
+ abort_unless(app(ImportDossier::class)->ready(), 503, 'Preserve a capacidade de consulta dos intervenientes seleccionados.');
+ foreach ($parties as $record) {
+ abort_unless($this->issues($actor, $order, $record) === [], 409, 'Confira a entidade seleccionada, os conflitos e a versão das instruções antes de continuar.');
+ $instructions = SupplyRecord::query()->whereKey($record->data['instruction_document_id'])->firstOrFail();
+ app(ImportEvidence::class)->bytes($instructions);
+ }
+ }
+}
diff --git a/app/Services/InternalRequisitionPort.php b/app/Services/InternalRequisitionPort.php
index ee7d9bf..2584f27 100644
--- a/app/Services/InternalRequisitionPort.php
+++ b/app/Services/InternalRequisitionPort.php
@@ -123,12 +123,22 @@ final class InternalRequisitionPort implements RequisitionPort
throw ValidationException::withMessages(['submission' => 'Actualize a data de entrega antes de submeter.']);
}
- return [...Tenant::query()->findOrFail($this->actor->tenant_id)->only(['first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional']), ...app(RequisitionApprovalLevels::class)->policy($r)];
+ $base = Tenant::query()->findOrFail($this->actor->tenant_id)->only(['first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional']);
+ $estimate = app(ImportEstimates::class)->approval($r);
+ $basis = $estimate['plan']['reference_totals'] ?? null;
+ $amount = $basis === null ? null : $basis[$base['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor'];
+
+ return [...$base, ...app(RequisitionApprovalLevels::class)->policy($r, $amount),
+ ...($estimate === null ? [] : ['import_estimate' => $estimate, 'approval_basis' => $basis])];
}
public function reserve(array $record): ?array
{
- return app(BudgetWorkflow::class)->record($this->actor, $this->model($record['id']), 'reserve', $record['total_minor'], $record['subtotal_minor']);
+ $request = $this->model($record['id']);
+ $result = app(BudgetWorkflow::class)->record($this->actor, $request, 'reserve', $record['total_minor'], $record['subtotal_minor']);
+ app(ImportEstimates::class)->reserve($this->actor, $request);
+
+ return $result;
}
public function submitted(array $record, array $policy, array $roles): array
@@ -170,7 +180,9 @@ final class InternalRequisitionPort implements RequisitionPort
public function release(array $record): void
{
- app(BudgetWorkflow::class)->record($this->actor, $this->model($record['id']), 'release');
+ $request = $this->model($record['id']);
+ app(BudgetWorkflow::class)->record($this->actor, $request, 'release');
+ app(ImportEstimates::class)->release($this->actor, $request);
}
public function replay(string $key, string $hash): ?array
diff --git a/app/Services/InvoiceWorkflow.php b/app/Services/InvoiceWorkflow.php
index ea4de45..b8406fd 100644
--- a/app/Services/InvoiceWorkflow.php
+++ b/app/Services/InvoiceWorkflow.php
@@ -125,7 +125,8 @@ class InvoiceWorkflow
}
}
$invoice = new Invoice(['tenant_id' => $user->tenant_id, 'purchase_order_id' => $order->id, 'supplier_id' => $order->supplier_id, 'created_by' => $user->id, 'number' => $number, 'issued_on' => $data['issued_on'], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'snapshot' => ['supplier' => $order->snapshot['supplier'], 'order_number' => $order->number, 'author' => $user->only(['id', 'name']), 'currency' => $order->currency,
- ...($order->currency === 'MZN' ? [] : ['exchange_basis' => $order->snapshot['exchange_basis']]),
+ ...($order->currency === 'MZN' ? [] : ['exchange_basis' => $order->snapshot['exchange_basis'],
+ ...(OrderPartsAccess::applies($order) ? ['exchange_sources' => $order->snapshot['exchange_sources']] : [])]),
'development_only' => true, 'matching_tolerance' => 'zero', 'rounding' => 'cumulative_half_up']]);
if (app(RequisitionBudgetDistributions::class)->applies($request)) {
$distribution = app(InvoiceBudgetDistributions::class)->prepare($user, $invoice, $order, $data, $lines);
diff --git a/app/Services/OrderCancellationWorkflow.php b/app/Services/OrderCancellationWorkflow.php
index ae1e793..43b2648 100644
--- a/app/Services/OrderCancellationWorkflow.php
+++ b/app/Services/OrderCancellationWorkflow.php
@@ -225,6 +225,14 @@ class OrderCancellationWorkflow
abort_unless($distribution !== null, 503, 'Preserve a origem do compromisso.');
$source['version'] = DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count();
$source['plan_hash'] = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR)['plan_hash'];
+ foreach ($source['allocations'] as &$row) {
+ $current = DB::table('budget_order_allocations')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)
+ ->where('order_key', $order->getAttribute('order_key'))->where('allocation_key', $row['allocation_key'])->whereIn('kind', ['commit', 'amend']);
+ foreach (['subtotal_minor', 'total_minor'] as $field) {
+ $row[$field] = (int) (clone $current)->sum($field);
+ }
+ }
+ unset($row);
}
unset($source);
$adapter = app(CommonBudget::class);
diff --git a/app/Services/OrderPartsAmendments.php b/app/Services/OrderPartsAmendments.php
new file mode 100644
index 0000000..180f280
--- /dev/null
+++ b/app/Services/OrderPartsAmendments.php
@@ -0,0 +1,78 @@
+> */
+ public function sources(User $actor, PurchaseOrder $order): array
+ {
+ abort_unless(app(OrderPartsWorkflow::class)->ready() && OrderPartsAccess::applies($order), 503);
+ abort_unless(auth()->id() === $actor->id && $actor->hasFunctions([PurchasingRole::Finance])
+ && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
+ app(OrderPartsAccess::class)->assertProcess($actor, $order);
+ app(OrderCancellationWorkflow::class)->assertOperational($order);
+ $sources = [];
+ foreach ($order->snapshot['order_parts']['budget_sources'] as $original) {
+ $origin = $original['origin'];
+ $distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $origin)->first();
+ abort_unless($distribution !== null && $distribution->phase === 'orders', 409);
+ $snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
+ $frozen = array_column($snapshot['allocations'], null, 'allocation_key');
+ $rows = [];
+ foreach ($original['allocations'] as $row) {
+ $allocation = $frozen[$row['allocation_key']] ?? null;
+ abort_unless($allocation !== null, 503, 'Preserve as atribuições originais.');
+ $current = DB::table('budget_order_allocations')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)
+ ->where('order_key', $order->getAttribute('order_key'))->where('allocation_key', $row['allocation_key'])->whereIn('kind', ['commit', 'amend']);
+ $rows[] = ['allocation_key' => $row['allocation_key'], 'line_id' => $allocation['line_id'], 'centre_id' => $allocation['centre_id'],
+ 'subtotal' => (string) BigDecimal::of((int) (clone $current)->sum('subtotal_minor'))->dividedBy(100, 2),
+ 'total' => (string) BigDecimal::of((int) (clone $current)->sum('total_minor'))->dividedBy(100, 2)];
+ }
+ $sources[] = ['origin' => $origin, 'version' => DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count(),
+ 'plan_hash' => $snapshot['plan_hash'], 'allocations' => $rows];
+ }
+
+ return $sources;
+ }
+
+ /** @param array $input */
+ public function amend(User $actor, PurchaseOrder $order, array $input): void
+ {
+ DB::transaction(function () use ($actor, $order, $input): void {
+ app(ConflictGuard::class)->lockCompany($actor);
+ $actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Finance]);
+ $order = PurchaseOrder::query()->whereKey($order->id)->lockForUpdate()->firstOrFail();
+ $this->sources($actor, $order);
+ app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
+ $data = Validator::make($input, [
+ 'operation_key' => 'required|uuid', 'reason' => 'required|string|min:10|max:4000',
+ 'sources' => 'required|array|list|min:1|max:100',
+ 'sources.*' => 'required|array:origin,version,plan_hash,allocations',
+ 'sources.*.origin' => 'required|integer|min:1|distinct', 'sources.*.version' => 'required|integer|min:0',
+ 'sources.*.plan_hash' => 'required|regex:/^[a-f0-9]{64}$/D',
+ 'sources.*.allocations' => 'required|array|list|min:1|max:500',
+ 'sources.*.allocations.*' => 'required|array:allocation_key,subtotal,total',
+ 'sources.*.allocations.*.allocation_key' => 'required|string|max:120',
+ 'sources.*.allocations.*.subtotal' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/D'],
+ 'sources.*.allocations.*.total' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/D'],
+ ])->validate();
+ $sources = array_map(fn ($source) => ['origin' => BigDecimal::of($source['origin'])->toInt(), 'version' => BigDecimal::of($source['version'])->toInt(),
+ 'plan_hash' => $source['plan_hash'], 'allocations' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'],
+ 'subtotal_minor' => BigDecimal::of($row['subtotal'])->multipliedBy(100)->toInt(),
+ 'total_minor' => BigDecimal::of($row['total'])->multipliedBy(100)->toInt()], $source['allocations'])], $data['sources']);
+ $adapter = app(CommonBudget::class);
+ $engine = $adapter->for($actor);
+ $adapter->execute(fn () => (new \ReflectionMethod($engine, 'amendOrderParts'))->invoke($engine,
+ $order->getAttribute('order_key'), $sources, $data['reason'], strtolower($data['operation_key'])));
+ });
+ }
+}
diff --git a/app/Services/OrderPartsExchange.php b/app/Services/OrderPartsExchange.php
new file mode 100644
index 0000000..31a9298
--- /dev/null
+++ b/app/Services/OrderPartsExchange.php
@@ -0,0 +1,111 @@
+> */
+ public function sources(PurchaseOrder $order): array
+ {
+ abort_unless(app(OrderPartsWorkflow::class)->ready(), 503);
+ app(OrderPartsAccess::class)->origins($order);
+ $sources = $order->snapshot['order_parts']['sources'];
+ foreach ($sources as $source) {
+ $request = Requisition::query()->where('tenant_id', $order->tenant_id)->whereKey($source['requisition_id'])->firstOrFail();
+ abort_unless($source['currency'] === $order->currency && $source['exchange_basis'] === app(QuotationExchange::class)->basis($request, $order->currency), 409,
+ 'Preserve a taxa congelada de cada origem.');
+ $offset = $source['reference_offset'];
+ $expected = OrderPartsReference::portion($offset['subtotal_minor'], $offset['tax_minor'],
+ array_sum(array_column($source['items'], 'subtotal_minor')), array_sum(array_column($source['items'], 'tax_minor')),
+ $source['exchange_basis']['rate']);
+ abort_unless($expected === $source['reference_amounts'], 409, 'Referência cambial da parcela inconsistente.');
+ }
+
+ return array_column($sources, null, 'requisition_id');
+ }
+
+ /** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
+ public function orderAmounts(PurchaseOrder $order): array
+ {
+ $sources = $this->sources($order);
+ $amounts = $this->sum(array_column($sources, 'reference_amounts'));
+ abort_unless($amounts === ($order->snapshot['reference_amounts'] ?? null)
+ && $order->subtotal_minor === array_sum(array_map(fn ($s) => array_sum(array_column($s['items'], 'subtotal_minor')), $sources))
+ && $order->tax_minor === array_sum(array_map(fn ($s) => array_sum(array_column($s['items'], 'tax_minor')), $sources))
+ && $order->total_minor === $order->subtotal_minor + $order->tax_minor, 409,
+ 'A ordem diverge dos valores documentais das suas origens.');
+
+ return $amounts;
+ }
+
+ /** @param list> $lines
+ * @return array
+ */
+ public function invoiceSources(PurchaseOrder $order, array $lines, ?int $invoiceId = null): array
+ {
+ $this->orderAmounts($order);
+ $sources = $this->sources($order);
+ $lineOrigins = [];
+ foreach ($sources as $origin => $source) {
+ foreach ($source['items'] as $line) {
+ $lineOrigins[$line['requisition_item_id']] = $origin;
+ }
+ }
+ $orderLines = $order->items()->get()->keyBy('id');
+ $current = $previous = [];
+ foreach ($lines as $line) {
+ $native = $orderLines->get($line['purchase_order_item_id']);
+ abort_unless($native !== null && isset($lineOrigins[$native->requisition_item_id]), 409);
+ $origin = $lineOrigins[$native->requisition_item_id];
+ $current[$origin] ??= ['subtotal_minor' => 0, 'tax_minor' => 0];
+ $current[$origin]['subtotal_minor'] += $line['subtotal_minor'];
+ $current[$origin]['tax_minor'] += $line['tax_minor'];
+ }
+ $old = DB::table('invoice_items')->join('invoices', 'invoices.id', '=', 'invoice_items.invoice_id')
+ ->where('invoices.tenant_id', $order->tenant_id)->where('invoices.purchase_order_id', $order->id)
+ ->where('invoices.status', 'validated')->when($invoiceId !== null, fn ($q) => $q->where('invoices.id', '!=', $invoiceId))
+ ->select('invoice_items.purchase_order_item_id', 'invoice_items.subtotal_minor', 'invoice_items.tax_minor')->get();
+ foreach ($old as $line) {
+ $native = $orderLines->get($line->purchase_order_item_id);
+ abort_unless($native !== null && isset($lineOrigins[$native->requisition_item_id]), 409);
+ $origin = $lineOrigins[$native->requisition_item_id];
+ $previous[$origin] ??= ['subtotal_minor' => 0, 'tax_minor' => 0];
+ $previous[$origin]['subtotal_minor'] += $line->subtotal_minor;
+ $previous[$origin]['tax_minor'] += $line->tax_minor;
+ }
+ $result = [];
+ foreach ($current as $origin => $amount) {
+ $source = $sources[$origin];
+ $offset = $source['reference_offset'];
+ $result[$origin] = OrderPartsReference::portion(
+ $offset['subtotal_minor'] + ($previous[$origin]['subtotal_minor'] ?? 0),
+ $offset['tax_minor'] + ($previous[$origin]['tax_minor'] ?? 0),
+ $amount['subtotal_minor'], $amount['tax_minor'], $source['exchange_basis']['rate']);
+ }
+
+ return $result;
+ }
+
+ /** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
+ public function invoiceAmounts(PurchaseOrder $order, Invoice $invoice): array
+ {
+ $lines = $invoice->items()->get()->map(fn ($line) => $line->only(['purchase_order_item_id', 'subtotal_minor', 'tax_minor']))->values()->all();
+
+ return $this->sum($this->invoiceSources($order, array_values($lines), $invoice->id));
+ }
+
+ /** @param array $rows
+ * @return array{subtotal_minor:int,tax_minor:int,total_minor:int}
+ */
+ public function sum(array $rows): array
+ {
+ return ['subtotal_minor' => array_sum(array_column($rows, 'subtotal_minor')),
+ 'tax_minor' => array_sum(array_column($rows, 'tax_minor')), 'total_minor' => array_sum(array_column($rows, 'total_minor'))];
+ }
+}
diff --git a/app/Services/OrderPartsInvoices.php b/app/Services/OrderPartsInvoices.php
index cff1ded..49d9069 100644
--- a/app/Services/OrderPartsInvoices.php
+++ b/app/Services/OrderPartsInvoices.php
@@ -65,7 +65,6 @@ final class OrderPartsInvoices
abort_unless(auth()->id() === $actor->id && $actor->hasFunctions([PurchasingRole::Finance])
&& $invoice->tenant_id === $actor->tenant_id && $order->tenant_id === $actor->tenant_id && $invoice->purchase_order_id === $order->id, 403);
app(OrderPartsAccess::class)->assertProcess($actor, $order);
- abort_unless($order->currency === 'MZN', 503, 'A imputação multimoeda por origem ainda está em preparação.');
$data = Validator::make($input, $this->rules())->validate();
$rows = [];
$seen = [];
@@ -116,6 +115,7 @@ final class OrderPartsInvoices
'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['subtotal_minor'] + $line['tax_minor']];
}
$sources = $sums = [];
+ $reference = $order->currency === 'MZN' ? null : app(OrderPartsExchange::class)->invoiceSources($order, $nativeLines);
foreach ($rows as $row) {
if (! in_array($row['origin'], $origins, true)) {
throw ValidationException::withMessages(['order_part_allocations' => 'Origem fora desta ordem.']);
@@ -139,10 +139,19 @@ final class OrderPartsInvoices
'subtotal_minor' => $row['subtotal_minor'], 'total_minor' => $row['total_minor']];
}
foreach ($expected as $id => $line) {
- if (($sums[$id] ?? null) !== ['subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]) {
+ if ($order->currency === 'MZN' && ($sums[$id] ?? null) !== ['subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]) {
throw ValidationException::withMessages(['order_part_allocations' => 'As imputações devem coincidir exactamente com cada linha nativa da factura.']);
}
}
+ if ($reference !== null) {
+ foreach ($reference as $origin => $amount) {
+ $allocated = $sources[$origin]['allocations'] ?? [];
+ if (array_sum(array_column($allocated, 'subtotal_minor')) !== $amount['subtotal_minor']
+ || array_sum(array_column($allocated, 'total_minor')) !== $amount['total_minor']) {
+ throw ValidationException::withMessages(['order_part_allocations' => 'As imputações em MZN devem coincidir exactamente com a referência de cada origem facturada.']);
+ }
+ }
+ }
foreach ($sources as &$source) {
unset($source['frozen']);
}
diff --git a/app/Services/OrderPartsPreparation.php b/app/Services/OrderPartsPreparation.php
index 9e5f09b..1baadd3 100644
--- a/app/Services/OrderPartsPreparation.php
+++ b/app/Services/OrderPartsPreparation.php
@@ -8,6 +8,7 @@ use App\Models\PurchaseOrderItem;
use App\Models\Requisition;
use App\Models\User;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use Tempo\Finance\Budget\BudgetControl;
@@ -110,6 +111,25 @@ final class OrderPartsPreparation
'award_terms' => array_intersect_key($award->attributesToArray(), array_flip(['delivery_date', 'delivery_location', 'justification'])),
'approval_snapshot' => $award->approval_snapshot,
'approval_fingerprint' => $award->comparison_hash];
+ if ($quote->currency !== 'MZN') {
+ $beforeNet = $beforeTax = 0;
+ $issuedSources = Schema::hasTable('purchase_order_sources') ? DB::table('purchase_order_sources')->where('tenant_id', $actor->tenant_id)
+ ->where('requisition_id', $award->requisition_id)->orderBy('purchase_order_id')->lockForUpdate()->get() : [];
+ foreach ($issuedSources as $issued) {
+ $frame = json_decode($issued->snapshot, true, 64, JSON_THROW_ON_ERROR);
+ $previous = $frame['native_preparation'] ?? null;
+ abort_unless(is_array($previous) && $previous['quotation_id'] === $quote->id
+ && $previous['exchange_basis'] === $quote->exchange_basis, 409,
+ 'Preserve a proposta e a taxa de cada parcela anterior.');
+ $beforeNet += array_sum(array_column($previous['items'], 'subtotal_minor'));
+ $beforeTax += array_sum(array_column($previous['items'], 'tax_minor'));
+ }
+ $last = array_key_last($result);
+ $result[$last]['reference_offset'] = ['subtotal_minor' => $beforeNet, 'tax_minor' => $beforeTax];
+ $result[$last]['reference_amounts'] = OrderPartsReference::portion($beforeNet, $beforeTax,
+ array_sum(array_column($prepared, 'subtotal_minor')), array_sum(array_column($prepared, 'tax_minor')),
+ $quote->exchange_basis['rate']);
+ }
}
$subtotal = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'subtotal_minor')), $result));
$tax = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'tax_minor')), $result));
diff --git a/app/Services/OrderPartsReference.php b/app/Services/OrderPartsReference.php
new file mode 100644
index 0000000..fd7cb40
--- /dev/null
+++ b/app/Services/OrderPartsReference.php
@@ -0,0 +1,21 @@
+ PHP_INT_MAX - $net || $beforeTax > PHP_INT_MAX - $tax) {
+ throw new \InvalidArgumentException('Base cambial cumulativa inválida.');
+ }
+ $exchange = new QuotationExchange;
+ $subtotal = $exchange->convert($beforeNet + $net, $rate) - $exchange->convert($beforeNet, $rate);
+ $vat = $exchange->convert($beforeTax + $tax, $rate) - $exchange->convert($beforeTax, $rate);
+
+ return ['subtotal_minor' => $subtotal, 'tax_minor' => $vat, 'total_minor' => $subtotal + $vat];
+ }
+}
diff --git a/app/Services/OrderPartsWorkflow.php b/app/Services/OrderPartsWorkflow.php
index ee1d5ae..ea69404 100644
--- a/app/Services/OrderPartsWorkflow.php
+++ b/app/Services/OrderPartsWorkflow.php
@@ -33,7 +33,11 @@ final class OrderPartsWorkflow
foreach ($prepared['sources'] as $source) {
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first();
if ($distribution === null) {
- $financial[] = ['origin' => $source['requisition_id'], 'award_id' => $source['award_id'], 'requires_adoption' => true, 'allocations' => []];
+ $adoptionLines = Quotation::query()->whereKey($source['quotation_id'])->firstOrFail()->items()->orderBy('id')->get()
+ ->map(fn ($line) => ['line_id' => $line->requisition_item_id, 'description' => $line->description,
+ 'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor])->all();
+ $financial[] = ['origin' => $source['requisition_id'], 'award_id' => $source['award_id'], 'requires_adoption' => true,
+ 'adoption_lines' => $adoptionLines, 'approved_reference' => $source['approved_reference'], 'allocations' => []];
continue;
}
@@ -55,20 +59,44 @@ final class OrderPartsWorkflow
}
return ['selection' => $selection, 'prepared' => $prepared, 'financial' => $financial,
- 'can_issue' => $prepared['currency'] === 'MZN' && ! in_array(true, array_column($financial, 'requires_adoption'), true)];
+ 'can_issue' => ! in_array(true, array_column($financial, 'requires_adoption'), true)];
});
}
- public function adopt(User $actor, PurchaseAward $award, string $operation): void
+ /** @param list> $referenceLines */
+ public function adopt(User $actor, PurchaseAward $award, string $operation, array $referenceLines = []): void
{
abort_unless($this->ready(), 503);
Validator::make(['operation_key' => $operation], ['operation_key' => 'required|uuid'])->validate();
- DB::transaction(function () use ($actor, $award, $operation): void {
+ DB::transaction(function () use ($actor, $award, $operation, $referenceLines): void {
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
$quote = app(PurchaseWorkflow::class)->approvedSource($actor, $award);
$request = Requisition::query()->whereKey($quote->requisition_id)->firstOrFail();
- abort_unless($quote->currency === 'MZN', 503, 'A adopção multimoeda ainda está em preparação.');
+ $explicit = [];
+ if ($quote->currency !== 'MZN') {
+ $data = Validator::make(['reference_lines' => $referenceLines], [
+ 'reference_lines' => 'required|array|list|min:1|max:500',
+ 'reference_lines.*' => 'required|array:line_id,subtotal,total',
+ 'reference_lines.*.line_id' => 'required|integer|min:1|distinct',
+ 'reference_lines.*.subtotal' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/D'],
+ 'reference_lines.*.total' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/D'],
+ ])->validate();
+ $explicit = array_column(array_map(fn ($row) => ['line_id' => BigDecimal::of($row['line_id'])->toInt(),
+ 'subtotal_minor' => BigDecimal::of($row['subtotal'])->multipliedBy(100)->toInt(),
+ 'total_minor' => BigDecimal::of($row['total'])->multipliedBy(100)->toInt()], $data['reference_lines']), null, 'line_id');
+ $ids = $quote->items()->pluck('requisition_item_id')->all();
+ $provided = array_keys($explicit);
+ sort($ids, SORT_NUMERIC);
+ sort($provided, SORT_NUMERIC);
+ $reference = app(QuotationExchange::class)->amounts($quote);
+ if ($ids !== $provided || array_sum(array_column($explicit, 'subtotal_minor')) !== $reference['subtotal_minor']
+ || array_sum(array_column($explicit, 'total_minor')) !== $reference['total_minor']) {
+ throw ValidationException::withMessages(['reference_lines' => 'Confira todos os artigos e os totais em MZN da proposta aprovada.']);
+ }
+ } else {
+ abort_unless($referenceLines === [], 422, 'As linhas em MZN conservam os valores nativos.');
+ }
$adopted = DB::table('budget_order_commands')->where('tenant_id', $actor->tenant_id)->where('kind', 'adopt')
->where('document_key', 'origin-'.$request->id)->where('operation_key', strtolower($operation))->exists();
abort_if(! $adopted && PurchaseOrderItem::query()->whereIn('requisition_item_id', $request->items()->select('id'))->exists(), 409,
@@ -76,9 +104,10 @@ final class OrderPartsWorkflow
$kind = $request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating';
$lines = $allocations = [];
foreach ($quote->items()->orderBy('id')->get() as $line) {
- $lines[$line->requisition_item_id] = ['subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor, 'required_kind' => $kind];
+ $amounts = $explicit[$line->requisition_item_id] ?? ['subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor];
+ $lines[$line->requisition_item_id] = [...array_intersect_key($amounts, array_flip(['subtotal_minor', 'total_minor'])), 'required_kind' => $kind];
$allocations[] = ['allocation_key' => 'legacy-line-'.$line->requisition_item_id, 'line_id' => $line->requisition_item_id,
- 'centre_id' => $request->cost_center_id, 'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor];
+ 'centre_id' => $request->cost_center_id, 'subtotal_minor' => $amounts['subtotal_minor'], 'total_minor' => $amounts['total_minor']];
}
$revision = hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR));
$adapter = app(CommonBudget::class);
@@ -165,8 +194,6 @@ 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.');
- // Foreign references require the full per-origin invoice conversion bridge, never an averaged rate.
- abort_unless($prepared['currency'] === 'MZN', 503, 'O percurso de emissão multimoeda por origem ainda está em preparação.');
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
$frames = $requests = $lines = $catalogue = $tariffs = [];
$firstQuote = null;
@@ -209,7 +236,11 @@ final class OrderPartsWorkflow
$engine = $adapter->for($actor);
$commit = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'commitOrderParts'))->invoke($engine,
$orderKey, $budgetSources, strtolower($data['operation_key'])));
- $snapshot = [...$frames[0], ...$limits, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
+ $foreign = $prepared['currency'] !== 'MZN';
+ $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']),
'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,
@@ -279,10 +310,14 @@ final class OrderPartsWorkflow
throw ValidationException::withMessages(['budget_sources' => 'Não inclua artigos que não pertencem a esta parcela.']);
}
foreach ($selected as $id => $line) {
- if (($amounts[$id] ?? null) !== array_intersect_key($line, array_flip(['subtotal_minor', 'total_minor']))) {
+ if ($source['currency'] === 'MZN' && ($amounts[$id] ?? null) !== array_intersect_key($line, array_flip(['subtotal_minor', 'total_minor']))) {
throw ValidationException::withMessages(['budget_sources' => 'As atribuições devem reconciliar exactamente com cada linha nativa emitida.']);
}
}
+ if ($source['currency'] !== 'MZN' && (array_sum(array_column($amounts, 'subtotal_minor')) !== $source['reference_amounts']['subtotal_minor']
+ || array_sum(array_column($amounts, 'total_minor')) !== $source['reference_amounts']['total_minor'])) {
+ throw ValidationException::withMessages(['budget_sources' => 'As imputações em MZN devem coincidir exactamente com a referência cambial desta origem.']);
+ }
}
}
}
diff --git a/app/Services/ProcurementPaymentInsights.php b/app/Services/ProcurementPaymentInsights.php
new file mode 100644
index 0000000..060bfd7
--- /dev/null
+++ b/app/Services/ProcurementPaymentInsights.php
@@ -0,0 +1,74 @@
+ $requests
+ * @return array|null
+ */
+ public function build(User $actor, Builder $requests, ?string $from, ?string $to): ?array
+ {
+ $adapter = app(SupplierPayables::class);
+ if (! $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) || ! $adapter->can($actor, 'view')) {
+ return null;
+ }
+ $adapter->readContext($actor);
+ $start = $from === null ? null : CarbonImmutable::parse($from, config('app.timezone'))->startOfDay();
+ $end = $to === null ? null : CarbonImmutable::parse($to, config('app.timezone'))->addDay()->startOfDay();
+ $orders = PurchaseOrder::query()->visibleTo($actor)->whereIn('requisition_id', (clone $requests)->reorder()->select('id'));
+ $invoices = Invoice::query()->where('tenant_id', $actor->tenant_id)->whereIn('purchase_order_id', $orders->select('id'));
+ $coverage = ['invoices' => 0, 'indeterminate' => 0, 'confirmed_payments' => 0];
+ $currencies = [];
+ foreach ($invoices->select('id')->lazyById(200) as $invoice) {
+ $coverage['invoices']++;
+ $rows = [];
+ try {
+ foreach ($adapter->readPaymentHistory($actor, $invoice->id) as $payment) {
+ if ($payment['status'] !== 'confirmed') {
+ continue;
+ }
+ if (! is_int($payment['amount_minor']) || $payment['amount_minor'] < 1
+ || ! is_string($payment['currency']) || ! preg_match('/^[A-Z]{3}$/D', $payment['currency'])
+ || ! is_string($payment['reviewed_at']) || trim($payment['reviewed_at']) === '') {
+ throw new \DomainException('Confirmação incompleta.');
+ }
+ try {
+ $date = CarbonImmutable::parse($payment['reviewed_at'], config('app.timezone'));
+ } catch (\Exception $error) {
+ throw new \DomainException('Data de confirmação indeterminada.', 0, $error);
+ }
+ if (($start !== null && $date < $start) || ($end !== null && $date >= $end)) {
+ continue;
+ }
+ $rows[] = $payment;
+ }
+ } catch (\DomainException) {
+ $coverage['indeterminate']++;
+
+ continue;
+ }
+ foreach ($rows as $payment) {
+ $currency = $payment['currency'];
+ $currencies[$currency] ??= ['currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
+ $currencies[$currency]['count']++;
+ $currencies[$currency]['amount_minor'] = (string) BigInteger::of($currencies[$currency]['amount_minor'])->plus($payment['amount_minor']);
+ $coverage['confirmed_payments']++;
+ }
+ }
+ ksort($currencies);
+
+ return ['method' => 'audited_original_confirmed_payments_v1', 'from' => $from, 'to' => $to,
+ 'coverage' => $coverage, 'currencies' => array_values($currencies)];
+ }
+}
diff --git a/app/Services/QuotationExchange.php b/app/Services/QuotationExchange.php
index 26c5db7..59bdcca 100644
--- a/app/Services/QuotationExchange.php
+++ b/app/Services/QuotationExchange.php
@@ -142,6 +142,12 @@ class QuotationExchange
public function orderAmounts(PurchaseOrder $order, int $subtotal, int $tax): array
{
abort_unless($subtotal >= 0 && $tax >= 0, 409);
+ if ($order->currency !== 'MZN' && OrderPartsAccess::applies($order)) {
+ abort_unless($subtotal === $order->subtotal_minor && $tax === $order->tax_minor, 409,
+ 'A conversão parcial exige a identificação das origens facturadas.');
+
+ return app(OrderPartsExchange::class)->orderAmounts($order);
+ }
if ($order->currency === 'MZN') {
abort_unless(($order->snapshot['exchange_basis'] ?? null) === null, 409, 'Base cambial incompatível com ordem em MZN.');
@@ -166,6 +172,9 @@ class QuotationExchange
*/
public function invoiceAmounts(PurchaseOrder $order, Invoice $invoice): array
{
+ if ($order->currency !== 'MZN' && OrderPartsAccess::applies($order)) {
+ return app(OrderPartsExchange::class)->invoiceAmounts($order, $invoice);
+ }
if ($order->currency === 'MZN') {
return ['subtotal_minor' => $invoice->subtotal_minor, 'tax_minor' => $invoice->tax_minor, 'total_minor' => $invoice->total_minor];
}
diff --git a/app/Services/RequisitionApprovalLevels.php b/app/Services/RequisitionApprovalLevels.php
index 3e64d2d..7e187a1 100644
--- a/app/Services/RequisitionApprovalLevels.php
+++ b/app/Services/RequisitionApprovalLevels.php
@@ -89,7 +89,7 @@ class RequisitionApprovalLevels
}
/** @return array */
- public function policy(Requisition $request): array
+ public function policy(Requisition $request, ?int $amountOverride = null): array
{
$company = Tenant::query()->findOrFail($request->tenant_id);
$plan = $company->requisition_approval_policy;
@@ -97,7 +97,7 @@ class RequisitionApprovalLevels
return [];
}
abort_unless($this->ready(), 503, 'O plano de aprovação exige a composição compatível; não é permitido ignorar os níveis configurados.');
- $amount = $company->approval_includes_tax ? $request->total_minor : $request->subtotal_minor;
+ $amount = $amountOverride ?? ($company->approval_includes_tax ? $request->total_minor : $request->subtotal_minor);
if ($amount === null) {
throw ValidationException::withMessages(['submission' => 'Complete os montantes antes de determinar os níveis de aprovação.']);
}
diff --git a/app/Services/SupplierPayables.php b/app/Services/SupplierPayables.php
index ad7df9d..e6e97ed 100644
--- a/app/Services/SupplierPayables.php
+++ b/app/Services/SupplierPayables.php
@@ -5,6 +5,7 @@ namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\Invoice;
use App\Models\InvoiceItem;
+use App\Models\PurchaseOrder;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
@@ -82,6 +83,18 @@ final class SupplierPayables
return $result;
}
+ /** Audited originals, once per payment; imported copies are never added.
+ * @return list>
+ */
+ public function readPaymentHistory(User $user, int $invoiceId): array
+ {
+ $this->readContext($user);
+ abort_unless(Invoice::query()->where('tenant_id', $user->tenant_id)->whereKey($invoiceId)
+ ->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($user)->select('id'))->exists(), 404);
+
+ return $this->paymentHistory($user, $invoiceId);
+ }
+
/** @return array */
public static function paymentFacts(\stdClass $payment, ?\stdClass $registration, ?\stdClass $decision): array
{
diff --git a/app/Services/SupplyPlanning.php b/app/Services/SupplyPlanning.php
index 44d8504..254474f 100644
--- a/app/Services/SupplyPlanning.php
+++ b/app/Services/SupplyPlanning.php
@@ -170,6 +170,9 @@ class SupplyPlanning
$order = isset($data['purchase_order_id']) ? PurchaseOrder::query()->whereKey($data['purchase_order_id'])->firstOrFail() : null;
if ($order !== null) {
app(OrderCancellationWorkflow::class)->assertOperational($order);
+ if ($kind === 'import' && in_array($action, ['transit', 'release'], true)) {
+ app(ImportParties::class)->assertCurrent($actor, $order, $old->record_key);
+ }
}
if (in_array($kind, ['agreement', 'contract'], true) && $state === 'approved') {
$this->check($supplier !== null && $supplier->eligible(), 'supplier_id', 'O fornecedor deve estar activo e com revisão documental vigente.');
diff --git a/config/import-dossier.php b/config/import-dossier.php
new file mode 100644
index 0000000..6088732
--- /dev/null
+++ b/config/import-dossier.php
@@ -0,0 +1,6 @@
+ env('SGC_IMPORT_DOSSIER_QA_ENABLED', false),
+];
diff --git a/config/import-estimates.php b/config/import-estimates.php
new file mode 100644
index 0000000..a626b62
--- /dev/null
+++ b/config/import-estimates.php
@@ -0,0 +1,3 @@
+ false];
diff --git a/docs/desenvolvimento.md b/docs/desenvolvimento.md
index dc11b44..e538d03 100644
--- a/docs/desenvolvimento.md
+++ b/docs/desenvolvimento.md
@@ -1,5 +1,19 @@
# Desenvolvimento do SGC
+## Continuação integral — 27/11/2026
+
+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.
+
+Dossiê tipificado: `ImportDossier`, formulário nativo e rotas ligam originais privados à importação/ordem, com tipo, emitente, referência, data disponível, notas, motivo, versões/correcções e auditoria. `ImportEvidence` partilha a verificação delimitada; a descarga financeira e a documental devolvem os bytes verificados, sem reabrir um ficheiro após a verificação. Inspecção agregada existente cobre ambos os directórios, sem reparar/apagar. Registar comprovativo não confirma pagamento, JUE ou libertação. Nova flag QA desligada por defeito; sem migração, dados reais ou activação. Prova `proofs/import-dossier-qa.json`: PostgreSQL28/192, concorrência200/200 e200/409 com dois escritores bloqueados/uma versão/um original/uma auditoria; restauro115tabelas anteriores/quatro originais em raiz separada/replay/recuperação pré-extensão aprovados, bases removidas. Frontend35ficheiros/162testes, protocolo5/17, tipos/PHPStan/check/build privado passaram. Manifesto63f58b44aef3aacbe9761004b4542c98dfe1ee3937be48e037295dd6c7ad05f8. Corrigido protocolo de ensaio para exigir também as duas versões tipificadas, com regressão; primeira corrida com recibo antigo não foi aprovada. Ainda faltam intervenientes, estimativa, base legal/alertas, suporte bancário, revisão visual e preparação operacional, além dos restantes requisitos do produto.
+
+Delta de fecho funcional de ordens: `OrderPartsAmendments` e formulário nativo permitem a Finanças reafectar os centros previstos com motivo, versão, histórico, recuperação e isolamento existentes. Fonte canónica `sgf-tempo/packages/budget-control` evoluiu para `COMMON-BUDGET-ORDER-PARTS-QA-v2` no âmbito QA já autorizado; efeitos assinados append-only, totais por artigo/origem preservados, piso consumido, reserva não emitida intacta, consumo/cancelamento sobre o compromisso revisto. Adopção legada estrangeira exige todos os artigos e referências MZN exactas, conservando a reserva/histórico anteriores. Não se inventam taxas ou compensações. PostgreSQL final65/659; concorrência real200/200 e200/409, um comando/uma auditoria; restauro115tabelas anteriores/oito opcionais e replay da reafectação aprovados, bases removidas. Tipos/PHPStan zero,17frontend antes do delta de adopção e10frontend de parcelas no delta final, build privado de manifesto4342fb2de9b565a197e6ddb7bfcfbb4485ba4b3bf0c97c35415e5d98710c3e76. Contagens sobrepostas; ver prova. Navegador/nativo falharam por módulos ausentes, não por erro funcional comprovado; não alegar revisão visual. Servidor/base/configuração QA visual removidos. Próxima frente: estimativa pré-documental e restantes requisitos de importação; sem instalação/activação no piloto ou SGF.
+
+Implementada ponte cambial por origem nas ordens parciais/consolidadas, reutilizando `QuotationExchange::convert` e o escritor comum existente. Cada origem conserva taxa/data/fonte, montantes documentais e deslocamento cumulativo; facturas parciais preservam cêntimos e requerem imputações MZN explícitas, conferidas novamente na validação independente. Preparação, ficha e impressão mostram as taxas separadas. Sem taxa média, compensação, nova migração ou activação operacional.
+
+Prova `proofs/rq01-origin-exchange-qa.json`: nove unitários/15, dois casos nativos SQLite/59 antes do delta adicional consolidado1/37; PostgreSQL integrado59/581 inclui histórico imutável, financeiro75/428, recuperação115tabelas anteriores/oito opcionais/restauro pré e pós/repetição sem efeito, bases removidas. Nove frontend, TypeScript e PHPStan zero erros. Contagens sobrepostas. Build privado em curso. Reafectação multiordem, adopção legada multimoeda, visual/móvel/impressão e restantes requisitos ainda por concluir; esta entrega não encerra a aplicaçã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/matriz-sgc-reconciliada.md b/docs/matriz-sgc-reconciliada.md
index d8a0a79..77300fb 100644
--- a/docs/matriz-sgc-reconciliada.md
+++ b/docs/matriz-sgc-reconciliada.md
@@ -1,5 +1,23 @@
# Matriz reconciliada do SGC — 03/11/2026
+## Continuação integral — 27/11/2026
+
+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.
+
+Selecção de despachante/transitário concluída em QA: fornecedor elegível versionado, instruções escritas originais, comprador independente, declaração de ausência de conflito, correcções/histórico e revalidação antes do trânsito/libertação. PostgreSQL dirigido40/286; concorrência200/200 e200/409, um efeito/uma auditoria, sem novos ficheiros; restauro de seis originais e duas versões da selecção, SQL e acesso nativo preservados, bases removidas. Frontend164/164, tipos/PHPStan/build privado aprovados. Corrigido o auxiliar CLI de recuperação que rodava o remember token ao terminar sessão; regressão compara os utilizadores integrais. Prova `proofs/import-parties-qa.json`. Este delta substitui apenas a pendência de selecção referida abaixo; estimativa, demais requisitos e revisão visual permanecem abertos.
+
+Decisão expressa do proprietário nesta continuação: o indicador «Despesa por período» usa **pagamentos confirmados**, pela data da confirmação. Não confundir essa base com facturas conferidas, ordens, compromissos ou pagamentos apenas preparados. A implementação deve reutilizar a autoridade financeira existente e separar moedas, sem duplicar o histórico importado.
+
+Dossiê de importação tipificado implementado em QA, sem migração: originais privados e correcções por versão, metadados, permissões/contexto, preparação recuperável, descarga dos bytes efectivamente verificados e inspecção agregada. PostgreSQL28/192; concorrência200/200 e200/409 com uma versão/um ficheiro/uma auditoria; restauro de quatro originais (dois custos e dois dossiê), SQL e acessos conferidos, bases removidas. Frontend integral162/162, tipos/PHPStan/build privado aprovados. `proofs/import-dossier-qa.json`. Não substitui selecção de despachante/transitário, estimativa antes dos documentos, base legal, prazos bancários, revisão visual ou disponibilização operacional, ainda pendentes.
+
+Delta posterior: reafectação explícita por Finanças e adopção legada multimoeda também implementadas em QA. Contrato comum opcional v2, sem novo schema, escritor ou alteração de artefacto instalado. Consumo/cancelamento usam os compromissos revistos, mantendo artigos/origens/consumos e reserva não emitida. PostgreSQL final65/659; concorrência real200/200 e200/409 com um efeito/uma auditoria; recuperação da reafectação aprovada, bases removidas. Tipos/PHPStan e build privado passaram. A revisão visual está impedida pelos módulos ausentes `@oai/cua/tinyskyAlt` e `@oai/sky`; ambiente visual privado encerrado/removido. Não declarar móvel/impressão visual ou aceitação concluídos. Próxima frente funcional: estimativa pré-documental de importação e restantes requisitos da secção10; disponibilização operacional mantém autorização específica.
+
+O proprietário mandou prosseguir até à conclusão final, verificando os passos seguintes e interrompendo apenas perante autorização específica necessária. A conclusão de um incremento não encerra o produto. Autorizações de instalação/activação e decisões empresariais mantêm os seus âmbitos.
+
+Ordens por origem: emissão multimoeda, facturas parciais/consolidadas e conversão cumulativa por taxa congelada integradas em QA, sem média cambial ou outro motor financeiro. PostgreSQL integrado 59/581, regressão financeira 75/428, recuperação pré/pós e repetição sem efeito aprovadas; bases removidas. Nove casos unitários/15 verificações, nove frontend, tipos e PHPStan aprovados. Prova `proofs/rq01-origin-exchange-qa.json`; contagens sobrepostas não se somam. Restam reafectação explícita de Finanças neste contrato, adopção legada multimoeda, revisão visual e preparação operacional; o restante produto continua aberto. Piloto e SGF operacional preservados.
+
## 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/orientacoes-continuidade.md b/docs/orientacoes-continuidade.md
index 07fb8fe..30db3fa 100644
--- a/docs/orientacoes-continuidade.md
+++ b/docs/orientacoes-continuidade.md
@@ -1,5 +1,19 @@
# Continuidade do desenvolvimento do SGC
+## Continuação integral — 27/11/2026
+
+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.
+
+O proprietário escolheu expressamente «pagamentos confirmados» para a base da despesa por período. A decisão anterior em falta está resolvida; implementar pela data da confirmação, reutilizando o registo financeiro canónico, sem somar novamente históricos já importados e com moedas separadas. Não voltar a pedir esta escolha.
+
+Delta documental: `proofs/import-dossier-qa.json` demonstra dossiê tipificado em QA, originais/correcções/imputação à importação existentes, integridade e acessos; sem efeitos financeiros/JUE/banca/stock. PostgreSQL28/192, concorrência com dois escritores e um original por operação, restauro de quatro originais, frontend integral162/162, tipos/PHPStan/build privado aprovados. A revisão nativa continua impedida pelos módulos ausentes já diagnosticados; não repetir tentativas sem mudança. Próximos requisitos: despachante/transitário com conflitos e instruções, estimativa pré-documental, regras/alertas e suporte bancário. Não instalar/activar por inferência.
+
+Estado posterior: `proofs/rq01-origin-exchange-qa.json` inclui agora reafectação Finance por ordem, adopção legada multimoeda e contrato opcional comum v2. PostgreSQL65/659, concorrência de reafectação real com dois escritores bloqueados/um efeito, restauro pré/pós e repetição aprovados. Tipos/PHPStan/build privado passaram. Não repetir as antigas pendências funcionais de reafectação/adopção. Revisão visual não executável: ambos os módulos de controlo ausentes; duas tentativas sem progresso nessa frente, não insistir sem mudança do ambiente. Servidor/base/configuração visual privada removidos. Continuar estimativas/importações e restantes requisitos independentes; piloto e SGF operacional preservados.
+
+Directiva actual: continuar até à conclusão funcional final, conferir os passos seguintes e não encerrar por incremento. A emissão multimoeda por origem e a conferência de facturas parciais/consolidadas já estão integradas em QA; ver `proofs/rq01-origin-exchange-qa.json`. PostgreSQL nativo 59/581 e financeiro 75/428 aprovados; recuperação pré/pós e repetição aprovadas, bases removidas. Tipos, PHPStan, nove unitários e nove frontend passaram. Não repetir estes resultados sem delta. Próximos passos: completar a reafectação explícita no contrato comum autorizado, adopção legada multimoeda e revisão nativa/móvel/impressão, depois continuar os requisitos restantes. Build privado ainda em curso; nada instalado/activado no piloto ou SGF.
+
## 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/confirmed-payment-insights-qa.json b/docs/proofs/confirmed-payment-insights-qa.json
new file mode 100644
index 0000000..90d4529
--- /dev/null
+++ b/docs/proofs/confirmed-payment-insights-qa.json
@@ -0,0 +1,16 @@
+{
+ "date": "2026-11-27",
+ "status": "implemented_in_isolated_qa_not_installed",
+ "owner_decision": "pagamentos confirmados",
+ "basis": "Original audited external payments, confirmation reviewed_at timestamp, inclusive local-date period and separate exact currency totals",
+ "deduplication": "Read authoritative originals once; never add pa imported copies or allocations as another payment",
+ "coverage": "Visible requisitions and invoices in the actor company; creation-date bounds do not exclude payments confirmed in the requested period; missing audit or confirmation metadata excludes the invoice as indeterminate, never zero",
+ "postgresql_regression": {"tests": 24, "assertions": 515, "passed": true, "database_removed": true},
+ "postgresql_final_http_csv_delta": {"tests": 5, "assertions": 84, "passed": true, "database_removed": true},
+ "sqlite_before_final_csv_delta": {"tests": 5, "assertions": 78, "passed": true},
+ "frontend_targeted": {"tests": 2, "passed": true},
+ "checks": {"types": "passed", "phpstan": "passed", "scoped_format_lint": "passed", "diff_whitespace": "passed"},
+ "private_build": {"directory": "storage/framework/testing/sgc-payment-insights-qa-final-20261127", "exit_code": 0, "manifest_sha256": "3545a8cbf60ed54515957c119bf378b9146dd39d8831b1fae5fb0267d0078408"},
+ "build_note": "The first build emitted output but PowerShell treated native timing stderr as an error. Final private build used native redirection and exited 0; installed public build was not changed.",
+ "limitations": ["Read-only original externally registered payment coverage, not proof of bank execution", "Experimental settlement proposals are not counted as external payments", "Visual review still unavailable", "No operational activation or real data changes"]
+}
diff --git a/docs/proofs/import-dossier-qa.json b/docs/proofs/import-dossier-qa.json
new file mode 100644
index 0000000..d72dc82
--- /dev/null
+++ b/docs/proofs/import-dossier-qa.json
@@ -0,0 +1,34 @@
+{
+ "date": "2026-11-27",
+ "status": "typed_documentary_dossier_verified_in_isolated_qa_not_operationally_installed",
+ "functional_source": "rq01-import-reconciliation.json sections 10.2, 10.3 and 10.4",
+ "source_sha256_rechecked": "9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408",
+ "implemented": [
+ "Typed private originals, references, issuers, optional dates, notes and versioned corrections linked to the native import/order",
+ "Current authority, company and all-origin process checks, encrypted recoverable form and native contextual guide",
+ "Shared bounded evidence verification; downloads return exactly the verified bytes",
+ "Existing aggregate operational inspection also detects missing altered or unreferenced typed originals",
+ "No new schema, payable, stock movement, customs release, bank or JUE execution"
+ ],
+ "verification": {
+ "sqlite_dossier_and_receipt_protocol_before_final_protocol_case": {"passed": 10, "assertions": 58},
+ "postgresql_dossier_costs_health": {"passed": 28, "assertions": 192, "database_removed": true},
+ "concurrency": {"blocked_writers_each_case": 2, "same_operation": [200, 200], "same_previous_version": [200, 409], "new_document_versions_each_case": 1, "new_original_files_each_case": 1, "audits_each_case": 1, "all_originals_verified": true, "database_removed": true},
+ "recovery": {"previous_tables_preserved": 115, "cost_document_original_versions_restored": 2, "typed_document_original_versions_restored": 2, "source_loss_demonstrated": true, "separate_private_root_restored": true, "native_authorized_evidence_resolved": true, "sql_restored_equal": true, "replay_no_new_effects": true, "pre_extension_restored": true, "databases_removed": true},
+ "frontend_integrated": {"files": 35, "passed": 162, "log": "storage/logs/frontend-integrated-20261127.txt"},
+ "receipt_protocol_final": {"passed": 5, "assertions": 17},
+ "typescript": "passed",
+ "phpstan": "passed_zero_errors",
+ "scoped_format_lint": "passed",
+ "private_build": {"path": "storage/framework/testing/sgc-import-dossier-qa-20261127", "manifest_sha256": "63f58b44aef3aacbe9761004b4542c98dfe1ee3937be48e037295dd6c7ad05f8"},
+ "counts_overlap_do_not_sum": true
+ },
+ "own_verification_corrections": [
+ "Recovery now requires four private originals including both typed dossier versions; protocol regression rejects a receipt missing typed recovery",
+ "Invalid original tests assert the HTTP 422 behaviour rather than one internal exception class"
+ ],
+ "remaining": ["Broker/forwarder selection and conflict integration", "Pre-document landed-cost estimate and approval/budget integration", "Versioned legal rules and remaining import alerts/bank-support workflow", "Native visual/mobile/print review", "Operational preparation and specific target authorization", "Remaining application requirements"],
+ "qa_flag_default": false,
+ "pilot_or_sgf_installation_activation": false,
+ "published_assets_changed": false
+}
diff --git a/docs/proofs/import-estimates-qa.json b/docs/proofs/import-estimates-qa.json
new file mode 100644
index 0000000..f04ee97
--- /dev/null
+++ b/docs/proofs/import-estimates-qa.json
@@ -0,0 +1,29 @@
+{
+ "date": "2026-11-27",
+ "status": "implemented_in_isolated_qa_not_installed",
+ "authorization": "import-landed-cost-contract-authorization.json",
+ "scope": "Versioned pre-document import assumptions, full native approval basis, additional-only reservation, native rejection release and explicit Finance partial reconciliation into independently reviewed actual origins",
+ "money": "Explicit exact MZN assumptions; original goods unchanged; unknown costs leave totals indeterminate; no legal-rate, exemption or recoverability default",
+ "authority": "Existing canonical budget journal; original invoices retain their own principal and budget effects; no new financial or stock writer",
+ "native_postgresql_final": {"tests": 6, "assertions": 70, "passed": true, "database_removed": true},
+ "canonical_postgresql": {"tests": 22, "assertions": 156, "passed": true, "database_removed": true},
+ "approval_regression_postgresql": {"tests": 32, "assertions": 737, "passed": true, "database_removed": true},
+ "import_dossier_logistics_health_regression_postgresql": {"tests": 40, "assertions": 286, "passed": true, "database_removed": true},
+ "reservation_concurrency": {"same_operation": [200, 200], "conflicting_version": [200, 409], "same_requisition_different_plan": [200, 409], "blocked_writers": 2, "commands_per_scenario": 1, "reservation_audits": 1, "reserved_minor": 2000, "database_removed": true},
+ "reconciliation_concurrency": {"same_operation": [200, 200], "conflicting_version": [200, 409], "different_actual_plan_same_source": [200, 409], "blocked_writers": 2, "total_commands": 3, "reconciliation_audits": 1, "combined_reserved_minor": 3000, "database_removed": true},
+ "downgrade": {"installed_v1_refused": 503, "earlier_landed_v1_refused": 503, "earlier_per_origin_landed_v2_refused": 503, "private_prior_runtime_budget_control_sha256": "d81f8fb172683727c221395224cecf9acb8285ab94e71e914141d41cf9e79efa"},
+ "recovery": {"previous_tables_preserved": 115, "optional_tables": 2, "post_restore_all_sql_equal": true, "estimate_remainder_restored_minor": 1000, "original_estimate_replay_without_effect": true, "actual_cost_replay_without_effect": true, "private_original_versions_restored": 6, "typed_dossier_versions_restored": 4, "selected_party_versions_restored": 2, "native_authorized_access_verified": true, "pre_extension_restore_passed": true, "databases_removed": true},
+ "frontend": {"files": 39, "tests": 169, "passed": true},
+ "protocol_unit": {"tests": 6, "assertions": 26, "passed": true},
+ "checks": {"types": "passed", "phpstan": "passed", "scoped_format_and_lint": "passed", "diff_whitespace": "passed"},
+ "private_build": {"directory": "storage/framework/testing/sgc-import-estimates-qa-20261127", "exit_code": 0, "manifest_sha256": "b31742bcd6f6b68c3e7544bff24e50a21f711d65cb4e9abdbba7d68557054ea4"},
+ "corrections": [
+ "PostgreSQL SUM returns decimal text; assertions now compare exact integer values consistently, without changing calculated values",
+ "Separate disposable suites replaced one aggregate execution that timed out; that execution is not counted as passing",
+ "Recovery fixture now uses distinct source and actual operation identities; conflicting identity regression preserves the original reservation",
+ "Native budget fixture now uses Finance creation and independent Finance approval through the common engine",
+ "Added the missing contextual guide after the global frontend coverage test identified it",
+ "Financial duplicate-reservation protection reads all approved source identities, never a paginated display subset; regression covers an out-of-range page"
+ ],
+ "limitations": ["Visual review remains unavailable because native computer-use runtime modules are missing", "No pilot/SGF operational installation, activation, migration, real data or permission changes", "Bank support commitments/deadlines, versioned legal suggestions and other product requirements remain open"]
+}
diff --git a/docs/proofs/import-parties-qa.json b/docs/proofs/import-parties-qa.json
new file mode 100644
index 0000000..9533667
--- /dev/null
+++ b/docs/proofs/import-parties-qa.json
@@ -0,0 +1,13 @@
+{
+ "date": "2026-11-27",
+ "status": "implemented_in_isolated_qa_not_installed",
+ "scope": "Versioned broker/forwarder selection linked to immutable written instructions, existing supplier eligibility and independent buyer authority",
+ "postgresql_focused": {"tests": 40, "assertions": 286, "result": "passed", "database_removed": true},
+ "concurrency": {"same_operation": [200, 200], "same_previous_version": [200, 409], "blocked_sessions": 2, "new_selection": 1, "new_audit": 1, "new_files": 0, "database_removed": true},
+ "recovery": {"private_original_versions_restored": 6, "typed_dossier_versions_restored": 4, "selected_party_versions_restored": 2, "sql_fingerprint_preserved_after_native_reads": true, "authorised_original_access_verified": true, "replay_without_effect": true, "pre_extension_restore": true, "databases_removed": true},
+ "harness_correction": "CLI identity reset now forgets guards under isolated-test/sessionless checks. SessionGuard logout rotated a synthetic user's remember token; production authentication was not changed. Regression verifies all user rows remain unchanged.",
+ "frontend": {"tests": 164, "files": 36, "result": "passed"},
+ "checks": {"types": "passed", "phpstan": "passed", "scoped_format_and_lint": "passed"},
+ "private_build": {"directory": "storage/framework/testing/sgc-import-parties-qa-20261127", "manifest_sha256": "63c1bb750a6390d0ed3ca45f534f337486e02d7d1b0a007e59e95924596bbe6c"},
+ "limitations": ["Visual review unavailable because native computer-use runtime modules are missing", "No operational installation, permission change, migration, bank execution or customs release", "Pre-document estimate and other import requirements remain open"]
+}
diff --git a/docs/proofs/rq01-origin-exchange-qa.json b/docs/proofs/rq01-origin-exchange-qa.json
new file mode 100644
index 0000000..89664f8
--- /dev/null
+++ b/docs/proofs/rq01-origin-exchange-qa.json
@@ -0,0 +1,56 @@
+{
+ "date": "2026-11-27",
+ "status": "development_in_progress_not_operationally_installed",
+ "authorization": "rq01-multi-order-contract-authorization.json",
+ "implemented": [
+ "Cumulative reference conversion through the existing frozen-rate calculator",
+ "Foreign partial and consolidated issuance preserving separate origin rates",
+ "Origin-specific explicit MZN invoice imputations, independent validation and native consumption",
+ "Origin rate, source and reference visible in preparation, detail and print",
+ "Explicit Finance order amendments with immutable signed effects and preserved per-line/origin totals",
+ "Revised consumption/cancellation capacity, consumed floors and unchanged unissued reservations",
+ "Foreign legacy adoption requires explicit exact MZN references for all approved quotation lines"
+ ],
+ "verification": {
+ "unit_reference": {"passed": 9, "assertions": 15},
+ "sqlite_foreign_native": {"passed": 2, "assertions": 59, "note": "Before additional consolidated receipt/invoice assertions"},
+ "sqlite_consolidated_full_delta": {"passed": 1, "assertions": 37},
+ "postgresql_native_integrated": {"passed": 65, "assertions": 659, "database_removed": true},
+ "postgresql_financial_regression": {"passed": 75, "assertions": 428, "database_removed": true},
+ "postgresql_recovery": {"previous_tables_preserved": 115, "optional_tables": 8, "post_extension_restore_equal": true, "recovered_replay_no_effects": true, "pre_extension_restored": true, "databases_removed": true},
+ "sqlite_contract_and_native_before_final_adoption": {"passed": 38, "skipped_postgresql_only": 2, "assertions": 452},
+ "sqlite_foreign_adoption_delta": {"passed": 1, "assertions": 29},
+ "frontend_order_parts": {"passed": 10},
+ "frontend_help_before_adoption_delta": {"passed": 8},
+ "amendment_concurrency": {"blocked_writers_observed_each_case": 2, "same_operation": [200, 200], "different_payload": [200, 409], "commands_each_case": 1, "audits_each_case": 1, "old_runtime_refused": 503, "database_removed": true},
+ "amendment_recovery": {"previous_tables_preserved": 115, "optional_tables": 8, "restored_all_tables_equal": true, "restored_amendment_replay_no_effects": true, "pre_extension_restored": true, "databases_removed": true},
+ "typescript": "passed",
+ "phpstan": "passed_zero_errors",
+ "counts_overlap_do_not_sum": true
+ },
+ "remaining": [
+ "Native mobile and print-dialog review",
+ "Operational preparation and specific target installation approval",
+ "Remaining application requirements and final integrated verification"
+ ],
+ "pilot_or_sgf_installation_activation": false,
+ "real_business_operations": false,
+ "common_source": {
+ "capability": "COMMON-BUDGET-ORDER-PARTS-QA-v2",
+ "BudgetControl.php_sha256": "702b9def4c3dd25cffb8122a9df8e70d8c7af7cd472d97e31a571b32a405f9f4",
+ "BudgetOrderParts.php_sha256": "b3b9ea06d908c990e63ba9438b68098a62f6e2e607b43c3be64753adcbd300b5"
+ },
+ "private_build": {
+ "path": "storage/framework/testing/sgc-order-adoption-qa-20261127",
+ "manifest_sha256": "4342fb2de9b565a197e6ddb7bfcfbb4485ba4b3bf0c97c35415e5d98710c3e76",
+ "published_assets_changed": false
+ },
+ "visual_impediment": {
+ "browser_tool": "Module not found: @oai/cua/tinyskyAlt",
+ "native_tool": "Module not found: @oai/sky",
+ "private_review_server_stopped": true,
+ "private_review_database_removed": true,
+ "private_review_settings_removed": true,
+ "visual_acceptance_claimed": false
+ }
+}
diff --git a/packages/purchasing/src/InternalRequisitions.php b/packages/purchasing/src/InternalRequisitions.php
index b12b666..b0534af 100644
--- a/packages/purchasing/src/InternalRequisitions.php
+++ b/packages/purchasing/src/InternalRequisitions.php
@@ -54,7 +54,11 @@ final class InternalRequisitions
*/
public static function roles(array $record, array $policy): array
{
- $amount = $policy['approval_includes_tax'] ? $record['total_minor'] : $record['subtotal_minor'];
+ $basis = $policy['approval_basis'] ?? $record;
+ $amount = $policy['approval_includes_tax'] ? ($basis['total_minor'] ?? null) : ($basis['subtotal_minor'] ?? null);
+ if (! is_int($amount) || $amount < 0) {
+ throw new RequisitionFailure('A base de aprovação deve ser explícita e determinada.', 422);
+ }
$roles = ['department_head'];
if ($amount > $policy['first_limit_minor']) {
$roles[] = 'procurement';
diff --git a/resources/js/components/import-estimate-reconciliation.tsx b/resources/js/components/import-estimate-reconciliation.tsx
new file mode 100644
index 0000000..9d93908
--- /dev/null
+++ b/resources/js/components/import-estimate-reconciliation.tsx
@@ -0,0 +1,182 @@
+import { Link, useForm } from '@inertiajs/react';
+import { useEffect, useRef } from 'react';
+import { FormErrors, Panel, controlClass } from '@/components/procurement';
+import { Button } from '@/components/ui/button';
+import { estimateMinor, estimateMoney } from '@/lib/import-estimate-money';
+
+export type EstimateSources = {
+ data: {
+ id: number;
+ version: number;
+ requisition_id: number;
+ budget_id: number;
+ revision: number | null;
+ reserved_minor: number | null;
+ committed_minor: number | null;
+ }[];
+ prev_page_url: string | null;
+ next_page_url: string | null;
+};
+export default function EstimateReconciliation({
+ sources,
+ planId,
+ url,
+ historyKey,
+ financialRevision,
+}: {
+ sources: EstimateSources;
+ planId: number;
+ url: string;
+ historyKey: string;
+ financialRevision: number;
+}) {
+ const form = useForm(
+ `${historyKey}:estimate-reconciliation:${planId}:${financialRevision}`,
+ {
+ operation_key: '',
+ actual_operation_key: '',
+ estimate_id: '',
+ amount: '',
+ 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]);
+ if (
+ sources.data.length === 0 &&
+ !sources.prev_page_url &&
+ !sources.next_page_url
+ )
+ return null;
+ const selected = sources.data.find(
+ (source) => String(source.id) === form.data.estimate_id,
+ );
+ return (
+
+
+
+ {sources.prev_page_url && (
+
+ Anterior
+
+ )}
+ {sources.next_page_url && (
+
+ Seguinte
+
+ )}
+
+
+ );
+}
diff --git a/resources/js/components/import-party-selection.tsx b/resources/js/components/import-party-selection.tsx
new file mode 100644
index 0000000..0681ec6
--- /dev/null
+++ b/resources/js/components/import-party-selection.tsx
@@ -0,0 +1,386 @@
+import { Link, useForm } from '@inertiajs/react';
+import { useEffect, useRef } from 'react';
+import { FormErrors, Panel } from '@/components/procurement';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+
+type Selection = {
+ id: number;
+ version: number;
+ data: {
+ role: string;
+ supplier_id: number;
+ instruction_document_id: number;
+ };
+ snapshot: {
+ supplier: { name: string; nuit: string; version: number };
+ instructions: { data: { reference: string } };
+ };
+ reason: string;
+ issues?: string[];
+};
+type Page = {
+ data: T[];
+ prev_page_url: string | null;
+ next_page_url: string | null;
+};
+export type ImportPartyWorkspace = {
+ roles: Record;
+ canSelect: boolean;
+ search: string;
+ suppliers: Page<{
+ id: number;
+ name: string;
+ nuit: string;
+ version: number;
+ }>;
+ instructions: Page<{
+ id: number;
+ version: number;
+ data: { reference: string; issuer_reference: string };
+ }>;
+ current: Selection[];
+ history: Page;
+};
+
+function Pages({
+ page,
+}: {
+ page: { prev_page_url: string | null; next_page_url: string | null };
+}) {
+ return (
+
+ {page.prev_page_url && (
+
+ Anterior
+
+ )}
+ {page.next_page_url && (
+
+ Seguinte
+
+ )}
+
+ );
+}
+
+export default function ImportPartySelection({
+ workspace,
+ importId,
+ importKey,
+ actorId,
+ tenantId,
+}: {
+ workspace: ImportPartyWorkspace;
+ importId: number;
+ importKey: string;
+ actorId: number;
+ tenantId: number;
+}) {
+ const current = workspace.current.find((s) => s.data.role === 'broker');
+ const form = useForm(`import-parties:${tenantId}:${actorId}:${importKey}`, {
+ operation_key: crypto.randomUUID(),
+ role: 'broker',
+ version: current?.version ?? 0,
+ supplier_id: current ? String(current.data.supplier_id) : '',
+ supplier_version: current?.snapshot.supplier.version ?? 0,
+ supplier_label: current?.snapshot.supplier.name ?? '',
+ instruction_document_id: current
+ ? String(current.data.instruction_document_id)
+ : '',
+ instruction_label: current?.snapshot.instructions.data.reference ?? '',
+ reason: '',
+ no_conflict: false,
+ });
+ 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 loadRole = (role: string) => {
+ const selected = workspace.current.find((s) => s.data.role === role);
+ form.setData({
+ operation_key: crypto.randomUUID(),
+ role,
+ version: selected?.version ?? 0,
+ supplier_id: selected ? String(selected.data.supplier_id) : '',
+ supplier_version: selected?.snapshot.supplier.version ?? 0,
+ supplier_label: selected?.snapshot.supplier.name ?? '',
+ instruction_document_id: selected
+ ? String(selected.data.instruction_document_id)
+ : '',
+ instruction_label:
+ selected?.snapshot.instructions.data.reference ?? '',
+ reason: '',
+ no_conflict: false,
+ });
+ };
+ return (
+
+
+ A escolha reutiliza uma entidade elegível do cadastro e as
+ instruções escritas deste dossiê. O comprador deve ser distinto
+ dos requisitantes; os conflitos são novamente conferidos antes
+ de continuar o trânsito ou a libertação.
+
+
+ {workspace.current.length === 0 ? (
+
Sem selecção registada.
+ ) : (
+ workspace.current.map((selection) => (
+
+
+ {workspace.roles[selection.data.role]} ·{' '}
+ {selection.snapshot.supplier.name}
+
+
+ Versão {selection.version} · Instruções:{' '}
+ {selection.snapshot.instructions.data.reference}
+
+ {selection.issues?.map((issue) => (
+
+ {issue}
+
+ ))}
+
+ ))
+ )}
+
+ {workspace.canSelect && (
+
+
{
+ event.preventDefault();
+ form.transform(
+ ({
+ supplier_label: _supplierLabel,
+ instruction_label: _instructionLabel,
+ ...data
+ }) => data,
+ );
+ form.post(
+ `/compras/importacoes/${importId}/intervenientes`,
+ );
+ }}
+ >
+
+
+ Função
+
+ loadRole(event.target.value)
+ }
+ >
+ {Object.entries(workspace.roles).map(
+ ([key, label]) => (
+
+ {label}
+
+ ),
+ )}
+
+
+
+ Entidade seleccionada:{' '}
+ {form.data.supplier_label || 'Por seleccionar'}
+
+
+ Instruções seleccionadas:{' '}
+ {form.data.instruction_label || 'Por seleccionar'}
+
+
+ Versão da selecção em conferência:{' '}
+ {form.data.version}
+
+ loadRole(form.data.role)}
+ >
+ Rever a selecção actual
+
+
+ Motivo da selecção ou substituição
+
+ form.setData('reason', event.target.value)
+ }
+ />
+
+
+
+ form.setData(
+ 'no_conflict',
+ event.target.checked,
+ )
+ }
+ />
+ Confirmo a ausência de conflito de interesses com
+ esta entidade nesta selecção.
+
+
+ Confirmar entidade e instruções
+
+
+
+
+ Escolher a entidade do cadastro
+
+
+
+
+ Pesquisar entidades
+
+
+ {workspace.suppliers.data.map((supplier) => (
+
+
+ {supplier.name} · {supplier.nuit}
+
+
{
+ form.setData(
+ 'supplier_id',
+ String(supplier.id),
+ );
+ form.setData(
+ 'supplier_label',
+ supplier.name,
+ );
+ form.setData(
+ 'supplier_version',
+ supplier.version,
+ );
+ form.setData('no_conflict', false);
+ }}
+ >
+ Escolher entidade
+
+
+ ))}
+
+
+
+
+ Escolher instruções escritas
+
+ {workspace.instructions.data.length === 0 ? (
+
+ Registe primeiro as instruções escritas no
+ dossiê documental.
+
+ ) : (
+ workspace.instructions.data.map((instruction) => (
+
+
+ {instruction.data.reference} ·{' '}
+ {instruction.data.issuer_reference} ·
+ Versão {instruction.version}
+
+
{
+ form.setData(
+ 'instruction_document_id',
+ String(instruction.id),
+ );
+ form.setData(
+ 'instruction_label',
+ instruction.data.reference,
+ );
+ }}
+ >
+ Escolher instruções
+
+
+ ))
+ )}
+
+
+
+ )}
+ {workspace.history.data.length > 0 && (
+
+ Histórico de selecções e substituições
+ {workspace.history.data.map((selection) => (
+
+ ))}
+
+
+ )}
+
+ );
+}
diff --git a/resources/js/components/order-parts-summary.tsx b/resources/js/components/order-parts-summary.tsx
index a5ccca3..678e552 100644
--- a/resources/js/components/order-parts-summary.tsx
+++ b/resources/js/components/order-parts-summary.tsx
@@ -13,6 +13,12 @@ export type OrderPartFrame = {
justification?: string;
};
native_preparation: {
+ exchange_basis?: {
+ rate: string;
+ quoted_on: string;
+ source: string;
+ } | null;
+ reference_amounts?: { total_minor: number };
approved_reference?: { subtotal_minor: number; total_minor: number };
items: {
quotation_item_id: number;
@@ -97,6 +103,33 @@ export function OrderPartsSummary({ sources }: { sources: OrderPartFrame[] }) {
Fundamento: {source.award.justification}
)}
+ {source.native_preparation.exchange_basis &&
+ source.native_preparation.reference_amounts && (
+
+ Taxa desta origem:{' '}
+ {
+ source.native_preparation.exchange_basis
+ .rate
+ }{' '}
+ MZN
+ {' · '}
+ {
+ source.native_preparation.exchange_basis
+ .quoted_on
+ }
+ {' · '}
+ {
+ source.native_preparation.exchange_basis
+ .source
+ }
+ {' · '}Referência da parcela:{' '}
+ {money(
+ source.native_preparation
+ .reference_amounts.total_minor,
+ 'MZN',
+ )}
+
+ )}
+
+ {data.from ?? 'Desde o início'} —{' '}
+ {data.to ?? 'Até à data actual'}.{' '}
+ {data.coverage.confirmed_payments} pagamentos confirmados.
+
+ {data.coverage.indeterminate > 0 && (
+
+ {data.coverage.indeterminate} facturas com histórico
+ indeterminado excluídas dos totais. Os valores apresentados
+ são parciais.
+
+ )}
+ {data.currencies.map((row) => {
+ const digits = row.amount_minor.padStart(3, '0');
+ return (
+
+ {digits.slice(0, -2)},{digits.slice(-2)} {row.currency}{' '}
+ · {row.count} pagamentos
+
+ );
+ })}
+ {data.currencies.length === 0 && (
+
+ Nenhum pagamento confirmado determinado neste período.
+
+ )}
+ {exportHref && (
+
+ Exportar despesa CSV
+
+ )}
+
+ );
+}
diff --git a/resources/js/lib/import-estimate-money.ts b/resources/js/lib/import-estimate-money.ts
new file mode 100644
index 0000000..81ab03f
--- /dev/null
+++ b/resources/js/lib/import-estimate-money.ts
@@ -0,0 +1,10 @@
+export const estimateMoney = (value: number | null) => {
+ if (value === null) return '';
+ const digits = String(value).padStart(3, '0');
+ return `${digits.slice(0, -2)}.${digits.slice(-2)}`;
+};
+export const estimateMinor = (value: string): number | string => {
+ if (!/^\d{1,13}(?:[.,]\d{1,2})?$/.test(value)) return value;
+ const [whole, fraction = ''] = value.replace(',', '.').split('.');
+ return Number(BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0')));
+};
diff --git a/resources/js/lib/journey-help.ts b/resources/js/lib/journey-help.ts
index b28543e..33665bd 100644
--- a/resources/js/lib/journey-help.ts
+++ b/resources/js/lib/journey-help.ts
@@ -37,6 +37,43 @@ function topic(
}
export const journeyHelp: JourneyHelp[] = [
+ topic(
+ 'import-estimate',
+ 'Preparar o custo estimado da importação',
+ ['supply/import-estimate'],
+ 'Preparar os encargos adicionais antes dos documentos efectivos, conservando os bens da requisição e os pressupostos de cada versão.',
+ [
+ 'Escolha o orçamento aprovado dos encargos e indique cada família de custo.',
+ 'Distinga valores conhecidos, informação desconhecida e não aplicabilidade fundamentada.',
+ 'Guarde a estimativa; a submissão da requisição completa determina as aprovações pelo custo integral e reserva os encargos adicionais.',
+ 'Com documentos conferidos, Finanças reconcilia a parcela correspondente a cada ordem e preserva o saldo das restantes.',
+ ],
+ [
+ 'Não repita encargos já incluídos nos bens nem substitua um desconhecido por zero.',
+ 'Os montantes são pressupostos explícitos em MZN; não são calculadas taxas legais ou isenções automaticamente.',
+ 'Uma estimativa não é uma factura, um consumo orçamental ou um pagamento.',
+ ],
+ 'Se a requisição mudou, reveja os pressupostos e guarde uma nova versão. Se o saldo for insuficiente, a submissão não deixa uma reserva parcial.',
+ 'Retome a requisição para submissão ou consulte a reconciliação nos custos efectivos da importação.',
+ ),
+ topic(
+ 'import-dossier',
+ 'Conservar os documentos da importação',
+ ['supply/import-dossier'],
+ 'Reunir os originais por tipo, conservar versões e seleccionar despachante ou transitário com instruções escritas.',
+ [
+ 'Escolha o tipo e identifique a referência e a entidade emitente.',
+ 'Seleccione o original privado e explique o registo.',
+ 'Para corrigir, escolha a versão actual e guarde uma nova versão; o original anterior permanece disponível.',
+ ],
+ [
+ 'A descarga verifica tamanho e integridade do original.',
+ 'Registar um comprovativo não confirma pagamento, submissão na JUE ou libertação de mercadoria.',
+ 'O acesso ao dossiê respeita as competências e todas as origens da ordem.',
+ ],
+ 'Se a importação ou a versão mudou, conserve os dados e consulte a versão actual. Após recarregar, volte a seleccionar o ficheiro.',
+ 'Retome a conferência documental e os marcos de desembaraço no percurso próprio.',
+ ),
topic(
'import-tariffs',
'Classificar os artigos importados',
@@ -64,6 +101,7 @@ export const journeyHelp: JourneyHelp[] = [
'Seleccione as facturas já validadas e os documentos adicionais.',
'Identifique cada componente e indique os valores documentais e as referências em MZN.',
'Guarde a preparação para conferência independente de Finanças.',
+ 'Se existir uma estimativa reservada, reconcilie explicitamente a parcela desta ordem com os documentos conferidos; não crie uma segunda reserva do mesmo custo.',
'Depois da conferência, reserve, comprometa e consuma as origens elegíveis; pode seleccionar uma parte das origens.',
'Para custos tardios, prepare uma nova versão e aplique a alteração conferida. O consumo anterior não se repete.',
],
@@ -85,6 +123,7 @@ export const journeyHelp: JourneyHelp[] = [
'Escolha as origens e as quantidades ainda por emitir.',
'Clique em Conferir para obter os valores nativos e as distribuições.',
'Confira as imputações em MZN; se houver vários centros, indique explicitamente cada parcela.',
+ 'Em moeda estrangeira, confira a taxa, a data, a fonte e a referência de cada origem; as taxas não são substituídas por uma média.',
'Emita a ordem e acompanhe as recepções e a factura no percurso normal.',
],
[
@@ -95,6 +134,24 @@ export const journeyHelp: JourneyHelp[] = [
'Se a quantidade ou a versão tiver mudado, conserve a preparação e volte a conferir. Consulte o histórico antes de repetir uma emissão incerta.',
'Conferir a ordem emitida e as suas origens; depois registar a recepção e a factura com a validação independente de Finanças.',
),
+ topic(
+ 'order-parts-amendment',
+ 'Reafectar as imputações de uma ordem',
+ ['purchases/order-parts-amendment'],
+ 'Finanças pode redistribuir explicitamente os montantes pelos centros já previstos, conservando cada artigo e origem.',
+ [
+ 'Confira os valores actuais em MZN e a versão de todas as origens.',
+ 'Indique as novas parcelas sem IVA e com IVA.',
+ 'Registe o motivo e confirme por Finanças.',
+ ],
+ [
+ 'Não reduza valores já consumidos.',
+ 'A reserva da quantidade ainda não emitida e os documentos originais são preservados.',
+ 'A confirmação não valida facturas nem executa pagamentos.',
+ ],
+ 'Se outra operação mudou a versão, volte a consultar a ordem e confira novamente as imputações.',
+ 'Consulte a versão registada e retome a conferência da factura por uma pessoa independente.',
+ ),
topic(
'budget-distributions',
'Distribuir um pedido por centros de custo',
diff --git a/resources/js/pages/purchases/order-parts-amendment.tsx b/resources/js/pages/purchases/order-parts-amendment.tsx
new file mode 100644
index 0000000..eda125a
--- /dev/null
+++ b/resources/js/pages/purchases/order-parts-amendment.tsx
@@ -0,0 +1,263 @@
+import { Head, Link, useForm, usePage } from '@inertiajs/react';
+import { useEffect, useRef } from 'react';
+import { FormErrors, PageTitle, Panel } from '@/components/procurement';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { money } from '@/types/procurement';
+
+type Source = {
+ origin: number;
+ version: number;
+ plan_hash: string;
+ allocations: {
+ allocation_key: string;
+ line_id: number;
+ centre_id: number;
+ subtotal: string;
+ total: string;
+ }[];
+};
+
+export default function Amendment({
+ order,
+ sources,
+ history,
+}: {
+ order: { id: number; number: string; currency: string };
+ sources: Source[];
+ history: {
+ id: number;
+ created_at: string;
+ created_by: number;
+ reason: string | null;
+ sources: {
+ origin: number;
+ allocations: {
+ allocation_key: string;
+ subtotal_minor: number;
+ total_minor: number;
+ }[];
+ }[];
+ }[];
+}) {
+ const actor = usePage().props.auth?.user;
+ const form = useForm(
+ `order-parts-amendment:${actor?.tenant_id}:${actor?.id}:${order.id}:${sources.map((s) => `${s.origin}:${s.version}:${s.plan_hash}`).join(',')}`,
+ {
+ operation_key: crypto.randomUUID(),
+ reason: '',
+ sources: sources.map((source) => ({
+ origin: source.origin,
+ version: source.version,
+ plan_hash: source.plan_hash,
+ allocations: source.allocations.map(
+ ({ allocation_key, subtotal, total }) => ({
+ allocation_key,
+ subtotal,
+ total,
+ }),
+ ),
+ })),
+ },
+ );
+ const ref = useRef(null);
+ useEffect(() => {
+ const current = ref.current;
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: current, dirty: form.isDirty },
+ }),
+ );
+ return () => {
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: current, dirty: false },
+ }),
+ );
+ };
+ }, [form.isDirty]);
+ const update = (
+ origin: number,
+ allocation: number,
+ field: 'subtotal' | 'total',
+ value: string,
+ ) => {
+ form.setData(
+ 'sources',
+ form.data.sources.map((source, i) =>
+ i !== origin
+ ? source
+ : {
+ ...source,
+ allocations: source.allocations.map((row, j) =>
+ j !== allocation
+ ? row
+ : { ...row, [field]: value },
+ ),
+ },
+ ),
+ );
+ };
+ return (
+ <>
+
+
+
+
+ Conserve os montantes de cada artigo e origem. Apenas os
+ centros já previstos podem ser reafectados. Valores
+ consumidos, reservas não emitidas e documentos originais são
+ preservados.
+
+ {
+ event.preventDefault();
+ form.post(`/ordens/${order.id}/reafectacao`);
+ }}
+ >
+
+ {sources.map((source, i) => (
+
+
+ Origem #{source.origin} · Versão{' '}
+ {source.version}
+
+ {source.allocations.map((allocation, j) => (
+
+ ))}
+
+ ))}
+
+ Motivo
+
+ form.setData('reason', e.target.value)
+ }
+ />
+
+
+ Confirmar reafectação por Finanças
+
+
+ Voltar à ordem
+
+
+
+
+ {history.length === 0 ? (
+ Sem reafectações registadas.
+ ) : (
+ history.map((event) => (
+
+
+ Reafectação #{event.id} · {event.created_at} ·
+ Interveniente #{event.created_by}
+
+ {event.reason && (
+
+ {event.reason}
+
+ )}
+
+
+ Consultar imputações conservadas
+
+ {event.sources.map((source) => (
+
+
Origem #{source.origin}
+ {source.allocations.map((row) => (
+
+ Centro #
+ {
+ sources
+ .find(
+ (s) =>
+ s.origin ===
+ source.origin,
+ )
+ ?.allocations.find(
+ (a) =>
+ a.allocation_key ===
+ row.allocation_key,
+ )?.centre_id
+ }{' '}
+ ·{' '}
+ {money(
+ row.subtotal_minor,
+ 'MZN',
+ )}{' '}
+ sem IVA ·{' '}
+ {money(row.total_minor, 'MZN')}{' '}
+ com IVA
+
+ ))}
+
+ ))}
+
+
+ ))
+ )}
+
+ >
+ );
+}
diff --git a/resources/js/pages/purchases/parts.tsx b/resources/js/pages/purchases/parts.tsx
index f245a02..c9f2dc3 100644
--- a/resources/js/pages/purchases/parts.tsx
+++ b/resources/js/pages/purchases/parts.tsx
@@ -22,6 +22,13 @@ type Financial = {
origin: number;
award_id: number;
requires_adoption: boolean;
+ approved_reference?: { subtotal_minor: number; total_minor: number };
+ adoption_lines?: {
+ line_id: number;
+ description: string;
+ subtotal_minor: number;
+ total_minor: number;
+ }[];
version?: number;
plan_hash?: string;
allocations: {
@@ -47,6 +54,12 @@ type Preview = {
requisition_number?: string | null;
award_id: number;
currency: string;
+ reference_amounts?: { subtotal_minor: number; total_minor: number };
+ exchange_basis?: {
+ rate: string;
+ quoted_on: string;
+ source: string;
+ } | null;
items: {
description: string;
quotation_item_id: number;
@@ -82,8 +95,28 @@ function useGuard(ref: RefObject, dirty: boolean) {
}, [dirty, ref]);
}
-function Adoption({ award }: { award: number }) {
- const form = useForm({ operation_key: crypto.randomUUID() });
+function Adoption({
+ source,
+ currency,
+}: {
+ source: Financial;
+ currency: string;
+}) {
+ const foreign = currency !== 'MZN';
+ const form = useForm({
+ operation_key: crypto.randomUUID(),
+ ...(foreign
+ ? {
+ reference_lines: (source.adoption_lines ?? []).map(
+ (line) => ({
+ line_id: line.line_id,
+ subtotal: '',
+ total: '',
+ }),
+ ),
+ }
+ : {}),
+ });
return (
@@ -96,11 +129,73 @@ function Adoption({ award }: { award: number }) {
da origem. A adopção não cria dotação nem saldo.
+ {foreign && (
+ <>
+
+ Confira a referência integral aprovada em MZN antes de
+ transferir a reserva:{' '}
+ {source.approved_reference
+ ? money(
+ source.approved_reference.total_minor,
+ 'MZN',
+ )
+ : 'Referência por conferir'}
+ . Indique todos os artigos da proposta, mesmo os que não
+ serão emitidos nesta parcela.
+
+ {(source.adoption_lines ?? []).map((line, index) => (
+
+
+ {line.description} ·{' '}
+ {money(line.total_minor, currency)}
+
+ {(['subtotal', 'total'] as const).map((field) => (
+
+ {field === 'subtotal'
+ ? 'Sem IVA (MZN)'
+ : 'Com IVA (MZN)'}
+
+ form.setData(
+ 'reference_lines',
+ (
+ form.data.reference_lines ??
+ []
+ ).map((row, i) =>
+ i === index
+ ? {
+ ...row,
+ [field]:
+ event.target
+ .value,
+ }
+ : row,
+ ),
+ )
+ }
+ />
+
+ ))}
+
+ ))}
+ >
+ )}
- form.post(`/adjudicacoes/${award}/parcelas/adoptar`)
+ form.post(
+ `/adjudicacoes/${source.award_id}/parcelas/adoptar`,
+ )
}
>
Adoptar a reserva existente
@@ -219,8 +314,28 @@ function Prepared({
{money(line.total_minor, source.currency)}
))}
+ {source.reference_amounts &&
+ source.exchange_basis && (
+
+ Referência desta origem:{' '}
+ {money(
+ source.reference_amounts
+ .total_minor,
+ 'MZN',
+ )}
+ {' · '}Taxa:{' '}
+ {source.exchange_basis.rate}
+ {' · '}
+ {source.exchange_basis.quoted_on}
+ {' · '}
+ {source.exchange_basis.source}
+
+ )}
{preview.financial[index].requires_adoption ? (
-
+
) : (
<>
@@ -354,8 +469,7 @@ function Prepared({
{!preview.can_issue && (
Complete a distribuição de todas as origens antes de
- emitir. A emissão multimoeda por parcelas ainda não
- está disponível.
+ emitir.
)}
diff --git a/resources/js/pages/purchases/show.tsx b/resources/js/pages/purchases/show.tsx
index 0405874..ed972dc 100644
--- a/resources/js/pages/purchases/show.tsx
+++ b/resources/js/pages/purchases/show.tsx
@@ -35,12 +35,14 @@ export default function OrderShow({
orderCancellation,
snapshotComplete = true,
orderPartsSources = [],
+ canAmendOrderParts = false,
}: {
order: PurchaseOrder;
history: History[];
orderCancellation?: OrderCancellationState;
snapshotComplete?: boolean;
orderPartsSources?: OrderPartFrame[];
+ canAmendOrderParts?: boolean;
}) {
const snapshot = order.snapshot;
if (!snapshotComplete) {
@@ -160,6 +162,14 @@ export default function OrderShow({
' Regras de aprovação provisórias.'}
+ {canAmendOrderParts && (
+
+ Conferir ou reafectar imputações por Finanças
+
+ )}
{snapshot.investment_rules && (
diff --git a/resources/js/pages/reports/procurement.tsx b/resources/js/pages/reports/procurement.tsx
index 8f81cd6..b780078 100644
--- a/resources/js/pages/reports/procurement.tsx
+++ b/resources/js/pages/reports/procurement.tsx
@@ -1,4 +1,8 @@
import { Head, Link, useForm } from '@inertiajs/react';
+import {
+ ProcurementPaymentInsights,
+ type PaymentInsights,
+} from '@/components/procurement-payment-insights';
import { Download } from 'lucide-react';
import {
PageTitle,
@@ -48,6 +52,7 @@ export default function ProcurementReports({
generatedAt,
insights,
payableInsights,
+ paymentInsights,
}: {
records: {
data: Row[];
@@ -63,6 +68,7 @@ export default function ProcurementReports({
generatedAt: string;
insights?: ProcurementInsights;
payableInsights?: PayableInsights | null;
+ paymentInsights?: PaymentInsights | null;
}) {
const form = useForm({
search: filters.search ?? '',
@@ -113,6 +119,12 @@ export default function ProcurementReports({
exportHref={`/relatorios/obrigacoes.csv?${params}`}
/>
)}
+ {paymentInsights && (
+
+ )}
+ {importEstimatesReady && (
+
+
+ Estimativa de importação
+
+
+ )}
{importTariffsReady && (
;
financialReady: boolean;
+ estimateSources?: EstimateSources;
financialState: {
revision: number;
native_plan_id: number | null;
@@ -1036,6 +1040,7 @@ function FinancialStage({
financialReady,
url,
historyKey,
+ estimateSources,
}: Props & { url: string; historyKey: string }) {
const form = useForm(`${historyKey}:financial`, {
operation_key: crypto.randomUUID(),
@@ -1061,7 +1066,15 @@ function FinancialStage({
const eligible = (phase: string) =>
selected.some((origin) => origin.phase === phase);
if (current && !importRecord.context_changed) {
- if (!state) {
+ if (
+ !state &&
+ !estimateSources?.data.some(
+ (source) =>
+ (source.reserved_minor ?? 0) +
+ (source.committed_minor ?? 0) >
+ 0,
+ )
+ ) {
if (
Object.values(latest.snapshot.plan.document_details).some(
(document) =>
@@ -1471,6 +1484,21 @@ export default function ImportCosts(props: Props) {
url={url}
historyKey={key}
/>
+ {props.estimateSources &&
+ props.financialReady &&
+ latest?.state === 'approved' &&
+ !props.importRecord.context_changed && (
+
+ )}
{props.financialEvents.data.length > 0 && (
{props.financialEvents.data.map((event) => (
diff --git a/resources/js/pages/supply/import-dossier.tsx b/resources/js/pages/supply/import-dossier.tsx
new file mode 100644
index 0000000..33a2551
--- /dev/null
+++ b/resources/js/pages/supply/import-dossier.tsx
@@ -0,0 +1,351 @@
+import { Head, Link, useForm } from '@inertiajs/react';
+import { useEffect, useRef } from 'react';
+import { FormErrors, PageTitle, Panel } from '@/components/procurement';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import ImportPartySelection, {
+ type ImportPartyWorkspace,
+} from '@/components/import-party-selection';
+
+type Document = {
+ id: number;
+ record_key: string;
+ version: number;
+ created_at: string;
+ created_by: number;
+ current: boolean;
+ supersedes: number | null;
+ sha256: string;
+ reason: string;
+ data: {
+ type: string;
+ reference: string;
+ issuer_reference: string;
+ issued_on: string | null;
+ notes: string | null;
+ };
+};
+type Props = {
+ importRecord: { id: number; version: number; record_key: string };
+ order: { id: number; number: string };
+ documents: {
+ data: Document[];
+ prev_page_url: string | null;
+ next_page_url: string | null;
+ };
+ types: Record;
+ canWrite: boolean;
+ actorId: number;
+ tenantId: number;
+ parties?: ImportPartyWorkspace;
+};
+
+export default function Dossier({
+ importRecord,
+ order,
+ documents,
+ types,
+ canWrite,
+ actorId,
+ tenantId,
+ parties,
+}: Props) {
+ const form = useForm(
+ `import-dossier:${tenantId}:${actorId}:${importRecord.record_key}:${importRecord.version}`,
+ {
+ operation_key: crypto.randomUUID(),
+ record_key: null as string | null,
+ version: 0,
+ type: '',
+ reference: '',
+ issuer_reference: '',
+ issued_on: '',
+ notes: '',
+ reason: '',
+ file: null as File | null,
+ },
+ );
+ const ref = useRef(null);
+ const fileRef = useRef(null);
+ useEffect(() => {
+ const current = ref.current;
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: current, dirty: form.isDirty },
+ }),
+ );
+ return () => {
+ window.dispatchEvent(
+ new CustomEvent('sgc:context-dirty', {
+ detail: { form: current, dirty: false },
+ }),
+ );
+ };
+ }, [form.isDirty]);
+ const correction = (document: Document) => {
+ form.setData({
+ operation_key: crypto.randomUUID(),
+ record_key: document.record_key,
+ version: document.version,
+ type: document.data.type,
+ reference: document.data.reference,
+ issuer_reference: document.data.issuer_reference,
+ issued_on: document.data.issued_on ?? '',
+ notes: document.data.notes ?? '',
+ reason: '',
+ file: null,
+ });
+ if (fileRef.current) fileRef.current.value = '';
+ ref.current?.scrollIntoView({ block: 'start' });
+ };
+ return (
+ <>
+
+
+
+
+ Registar um documento conserva a evidência. Não submete
+ declarações na JUE, não confirma pagamentos nem liberta
+ mercadoria. Esses factos mantêm os seus percursos e
+ competências próprios.
+
+
+ Consultar a ordem e as suas origens
+
+ {parties && (
+
+ )}
+ {canWrite && (
+
+ {
+ event.preventDefault();
+ form.post(
+ `/compras/importacoes/${importRecord.id}/documentos`,
+ {
+ forceFormData: true,
+ onSuccess: () => {
+ form.reset();
+ if (fileRef.current)
+ fileRef.current.value = '';
+ },
+ },
+ );
+ }}
+ >
+
+
+ Tipo de documento
+
+ form.setData('type', e.target.value)
+ }
+ >
+ Seleccione
+ {Object.entries(types).map(
+ ([key, label]) => (
+
+ {label}
+
+ ),
+ )}
+
+
+
+ Referência
+
+ form.setData(
+ 'reference',
+ e.target.value,
+ )
+ }
+ />
+
+
+ Entidade emitente
+
+ form.setData(
+ 'issuer_reference',
+ e.target.value,
+ )
+ }
+ />
+
+
+ Data do documento, quando disponível
+
+ form.setData(
+ 'issued_on',
+ e.target.value,
+ )
+ }
+ />
+
+
+ Notas
+
+ form.setData('notes', e.target.value)
+ }
+ />
+
+
+ Motivo do registo ou da correcção
+
+ form.setData('reason', e.target.value)
+ }
+ />
+
+
+ Original privado (PDF, JPG ou PNG, até 2 MB)
+
+ form.setData(
+ 'file',
+ e.target.files?.[0] ?? null,
+ )
+ }
+ />
+
+
+ Após recarregar a página, volte a seleccionar o
+ ficheiro. A correcção cria uma nova versão e
+ conserva o original anterior.
+
+
+ Guardar documento privado
+
+
+
+ )}
+
+ {documents.data.length === 0 ? (
+ Ainda não há documentos neste dossiê.
+ ) : (
+ documents.data.map((document) => (
+
+
+ {types[document.data.type]} ·{' '}
+ {document.data.reference}
+
+
+ {document.data.issuer_reference} · Versão{' '}
+ {document.version}
+ {document.current
+ ? ' · Actual'
+ : ' · Histórica'}
+
+ {document.data.issued_on && (
+
+ Data do documento:{' '}
+ {document.data.issued_on}
+
+ )}
+ {document.data.notes && (
+
+ {document.data.notes}
+
+ )}
+
+ {document.reason}
+
+
+ Descarregar esta versão
+
+ {canWrite && document.current && (
+ correction(document)}
+ >
+ Preparar correcção
+
+ )}
+
+ Rastreabilidade
+
+ Registo: {document.created_at} ·
+ Interveniente #{document.created_by}
+
+
+ SHA-256: {document.sha256}
+
+
+
+ ))
+ )}
+
+ {documents.prev_page_url && (
+
+ Anterior
+
+ )}
+ {documents.next_page_url && (
+
+ Seguinte
+
+ )}
+
+
+
+ >
+ );
+}
diff --git a/resources/js/pages/supply/import-estimate.tsx b/resources/js/pages/supply/import-estimate.tsx
new file mode 100644
index 0000000..4834d82
--- /dev/null
+++ b/resources/js/pages/supply/import-estimate.tsx
@@ -0,0 +1,418 @@
+import { Head, Link, router, useForm } from '@inertiajs/react';
+import { useEffect, useRef } from 'react';
+import {
+ FormErrors,
+ PageTitle,
+ Panel,
+ controlClass,
+} from '@/components/procurement';
+import { Button } from '@/components/ui/button';
+import { estimateMinor, estimateMoney } from '@/lib/import-estimate-money';
+
+const labels: Record = {
+ freight: 'Frete',
+ insurance: 'Seguro',
+ duty: 'Direitos aduaneiros',
+ ice: 'ICE',
+ vat: 'IVA da importação',
+ other: 'Outros encargos',
+};
+type Component = {
+ key: string;
+ kind: string;
+ status: string;
+ basis: string;
+ subtotal_minor: number | null;
+ tax_minor: number | null;
+ total_minor: number | null;
+};
+type Version = {
+ id: number;
+ version: number;
+ state: string;
+ reason: string;
+ data: { budget_id: number; components: Component[] };
+ snapshot: {
+ plan: {
+ complete: boolean;
+ budget_amount_minor: number | null;
+ known_total_minor: number;
+ unknown: string[];
+ };
+ };
+};
+type Page = {
+ data: T[];
+ prev_page_url: string | null;
+ next_page_url: string | null;
+};
+type Props = {
+ requisition: {
+ id: number;
+ number: string;
+ status: string;
+ total_minor: number | null;
+ };
+ latest: Version | null;
+ nativeChanged: boolean;
+ history: Page;
+ budgets: Page<{ id: number; includes_tax: boolean }>;
+ canPrepare: boolean;
+ actorId: number;
+ tenantId: number;
+};
+function Pages({ page }: { page: Page }) {
+ return (
+
+ {page.prev_page_url && (
+
+ Anterior
+
+ )}
+ {page.next_page_url && (
+
+ Seguinte
+
+ )}
+
+ );
+}
+export default function ImportEstimate(props: Props) {
+ const { requisition, latest, canPrepare } = props;
+ const components =
+ latest?.data.components ??
+ Object.keys(labels).map((kind) => ({
+ key: kind,
+ kind,
+ status: 'unknown',
+ basis: '',
+ subtotal_minor: null,
+ tax_minor: null,
+ total_minor: null,
+ }));
+ const form = useForm(
+ `import-estimate:${props.tenantId}:${props.actorId}:${requisition.id}:${latest?.version ?? 0}`,
+ {
+ operation_key: '',
+ version: latest?.version ?? 0,
+ budget_id: latest ? String(latest.data.budget_id) : '',
+ reason: '',
+ components: components.map((row) => ({
+ key: row.key,
+ kind: row.kind,
+ status: row.status,
+ basis: row.basis,
+ subtotal: estimateMoney(row.subtotal_minor),
+ tax: estimateMoney(row.tax_minor),
+ total: estimateMoney(row.total_minor),
+ })),
+ },
+ );
+ 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]);
+ return (
+ <>
+
+
+
+
+ Voltar à requisição
+
+
+
+ Bens:{' '}
+ {requisition.total_minor === null
+ ? 'Por completar'
+ : `${estimateMoney(requisition.total_minor)} MZN`}
+ .
+
+
+ Guardar conserva os pressupostos; a submissão usa a
+ estimativa completa para determinar as aprovações e
+ reservar os custos adicionais.
+
+ {props.nativeChanged && (
+
+ A requisição mudou. Reveja os pressupostos e guarde
+ uma nova versão antes de submeter.
+
+ )}
+ {latest && (
+
+ {latest.snapshot.plan.complete
+ ? `Estimativa completa: ${estimateMoney(latest.snapshot.plan.budget_amount_minor)} MZN, segundo a base do orçamento escolhido.`
+ : `Estimativa incompleta. Parcela conhecida: ${estimateMoney(latest.snapshot.plan.known_total_minor)} MZN; o total permanece indeterminado.`}
+
+ )}
+
+ {canPrepare && (
+
+ {
+ event.preventDefault();
+ const operation =
+ form.data.operation_key ||
+ crypto.randomUUID();
+ form.setData('operation_key', operation);
+ form.transform((data) => ({
+ ...data,
+ operation_key: operation,
+ components: data.components.map((row) => ({
+ key: row.key,
+ kind: row.kind,
+ status: row.status,
+ basis: row.basis,
+ subtotal_minor:
+ row.status === 'known'
+ ? estimateMinor(row.subtotal)
+ : null,
+ tax_minor:
+ row.status === 'known'
+ ? estimateMinor(row.tax)
+ : null,
+ total_minor:
+ row.status === 'known'
+ ? estimateMinor(row.total)
+ : null,
+ })),
+ }));
+ form.post(
+ `/requisicoes/${requisition.id}/estimativa-importacao`,
+ {
+ preserveScroll: true,
+ onSuccess: () => {
+ form.reset();
+ router.visit(
+ `/requisicoes/${requisition.id}/estimativa-importacao`,
+ {
+ preserveState: false,
+ preserveScroll: true,
+ },
+ );
+ },
+ },
+ );
+ }}
+ >
+
+
+ Orçamento aprovado dos encargos
+
+ form.setData(
+ 'budget_id',
+ e.target.value,
+ )
+ }
+ >
+ Seleccione
+ {props.budgets.data.map((budget) => (
+
+ Orçamento {budget.id} ·{' '}
+ {budget.includes_tax
+ ? 'Inclui imposto'
+ : 'Sem imposto'}
+
+ ))}
+
+
+
+ {form.data.components.map((row, index) => (
+
+
+ {labels[row.kind] ?? row.kind}
+
+
+ Situação
+
+ form.setData(
+ 'components',
+ form.data.components.map(
+ (r, i) =>
+ i === index
+ ? {
+ ...r,
+ status: e
+ .target
+ .value,
+ }
+ : r,
+ ),
+ )
+ }
+ >
+
+ Ainda desconhecido
+
+
+ Valor conhecido
+
+
+ Não aplicável
+
+
+
+ {row.status === 'known' && (
+
+ {(
+ [
+ 'subtotal',
+ 'tax',
+ 'total',
+ ] as const
+ ).map((field) => (
+
+ {field === 'subtotal'
+ ? 'Base'
+ : field === 'tax'
+ ? 'Imposto'
+ : 'Total'}{' '}
+ (MZN)
+
+ form.setData(
+ 'components',
+ form.data.components.map(
+ (r, i) =>
+ i ===
+ index
+ ? {
+ ...r,
+ [field]:
+ e
+ .target
+ .value,
+ }
+ : r,
+ ),
+ )
+ }
+ />
+
+ ))}
+
+ )}
+
+ Fonte ou fundamento
+
+ form.setData(
+ 'components',
+ form.data.components.map(
+ (r, i) =>
+ i === index
+ ? {
+ ...r,
+ basis: e
+ .target
+ .value,
+ }
+ : r,
+ ),
+ )
+ }
+ />
+
+
+ ))}
+
+ Motivo desta versão
+
+ form.setData('reason', e.target.value)
+ }
+ />
+
+
+ Guardar estimativa
+
+
+
+ )}
+
+ {props.history.data.map((record) => (
+
+
+ Versão {record.version} ·{' '}
+ {record.snapshot.plan.complete
+ ? 'Completa'
+ : 'Incompleta'}
+
+ {record.reason}
+ {record.data.components.map((row) => (
+
+ {labels[row.kind]}:{' '}
+ {row.status === 'known'
+ ? `${estimateMoney(row.total_minor)} MZN`
+ : row.status === 'unknown'
+ ? 'Desconhecido'
+ : 'Não aplicável'}{' '}
+ · {row.basis}
+
+ ))}
+
+ ))}
+
+
+
+ >
+ );
+}
diff --git a/resources/js/pages/supply/index.tsx b/resources/js/pages/supply/index.tsx
index 19f0f75..d23eef5 100644
--- a/resources/js/pages/supply/index.tsx
+++ b/resources/js/pages/supply/index.tsx
@@ -76,6 +76,7 @@ type Projection = {
};
type Props = {
importCostsReady?: boolean;
+ importDossierReady?: boolean;
orderLimitsReady?: boolean;
linkedAgreementKey?: string | null;
linkedContractKey?: string | null;
@@ -1535,6 +1536,14 @@ export default function SupplyIndex(props: Props) {
Preparar e conferir o custo de aterragem
)}
+ {props.importDossierReady && (
+
+ Consultar o dossiê documental da importação
+
+ )}
Dados preservados desta versão
diff --git a/resources/views/purchases/print.blade.php b/resources/views/purchases/print.blade.php
index d538522..531784c 100644
--- a/resources/views/purchases/print.blade.php
+++ b/resources/views/purchases/print.blade.php
@@ -48,6 +48,9 @@
Cada origem conserva as condições e aprovações registadas. Os valores das parcelas usam o arredondamento cumulativo da origem.
@foreach($snapshot['order_parts']['frames'] as $frame)
{{ $frame['requisition']['number'] }} {{ $frame['department']['name'] }} · {{ $frame['cost_center']['code'] }} · {{ $frame['cost_center']['name'] }} Proposta {{ $frame['quotation']['reference'] }} · Pagamento: {{ $frame['quotation']['payment_terms'] }} Entrega: {{ $frame['award']['delivery_date'] }} · {{ $frame['award']['delivery_location'] }}
+ @if(!empty($frame['native_preparation']['exchange_basis']))
+ @include('purchases.exchange-basis', ['basis' => $frame['native_preparation']['exchange_basis'], 'reference' => $frame['requisition']['number'], 'referenceAmounts' => $frame['native_preparation']['reference_amounts']])
+ @endif
@endforeach
@endif
Artigos e valores
diff --git a/routes/web.php b/routes/web.php
index e65963c..a2cd920 100644
--- a/routes/web.php
+++ b/routes/web.php
@@ -17,6 +17,8 @@ use App\Http\Controllers\FormalAdmissionController;
use App\Http\Controllers\FormalRecommendationController;
use App\Http\Controllers\GeneralLedgerController;
use App\Http\Controllers\GoodsReceiptController;
+use App\Http\Controllers\ImportDossierController;
+use App\Http\Controllers\ImportEstimateController;
use App\Http\Controllers\ImportLandedCostController;
use App\Http\Controllers\ImportTariffController;
use App\Http\Controllers\InventoryDispositionController;
@@ -132,7 +134,13 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('api/stock-returns/{id}/reject', [WarehouseReturnController::class, 'reject'])->whereNumber('id');
Route::get('compras/fornecimento', [SupplyPlanningController::class, 'index'])->name('supply.index');
Route::get('compras/importacoes/{import}/custos', [ImportLandedCostController::class, 'index'])->whereNumber('import')->name('imports.costs');
+ Route::get('compras/importacoes/{import}/documentos', [ImportDossierController::class, 'index'])->whereNumber('import')->name('imports.dossier');
+ Route::post('compras/importacoes/{import}/documentos', [ImportDossierController::class, 'store'])->whereNumber('import');
+ 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}/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');
Route::post('compras/importacoes/{import}/custos', [ImportLandedCostController::class, 'preview'])->whereNumber('import');
Route::post('compras/importacoes/{import}/custos/documentos', [ImportLandedCostController::class, 'document'])->whereNumber('import');
@@ -244,6 +252,7 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::get('relatorios', [ProcurementReportController::class, 'index'])->name('reports.index');
Route::get('relatorios/compras.csv', [ProcurementReportController::class, 'export'])->name('reports.export');
Route::get('relatorios/obrigacoes.csv', [ProcurementReportController::class, 'exportPositions'])->name('reports.positions');
+ Route::get('relatorios/despesa.csv', [ProcurementReportController::class, 'exportPayments'])->name('reports.payments');
Route::get('requisicoes/{requisition}/qualificacao', [DocumentaryQualificationController::class, 'show'])->name('qualifications.show');
Route::post('requisicoes/{requisition}/qualificacao', [DocumentaryQualificationController::class, 'define']);
Route::post('qualificacoes/{set}/analises', [DocumentaryQualificationController::class, 'assess']);
diff --git a/scripts/quotation-exchange-pg-check.php b/scripts/quotation-exchange-pg-check.php
index 1d56005..a310095 100644
--- a/scripts/quotation-exchange-pg-check.php
+++ b/scripts/quotation-exchange-pg-check.php
@@ -59,6 +59,38 @@ try {
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostPlanTest.php', 'tests/Feature/ImportLandedCostsTest.php', 'tests/Feature/BudgetLandedCostsContractTest.php',
'tests/Feature/SupplyPlanningTest.php', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetOrderPartsContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php', 'tests/Feature/InvoiceTest.php', 'tests/Feature/OperationalHealthTest.php']];
+ if (in_array('--estimate-focused', $argv, true)) {
+ $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportEstimatePlanTest.php', 'tests/Feature/ImportEstimatesTest.php',
+ 'tests/Feature/BudgetLandedCostsContractTest.php', 'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionApprovalLevelsTest.php']];
+ }
+ if (in_array('--estimate-concurrency', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/budget-landed-cost-worker.php', $database, 'race-estimate']];
+ }
+ if (in_array('--estimate-reconciliation-concurrency', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/budget-landed-cost-worker.php', $database, 'race-estimate-reconcile']];
+ }
+ if (in_array('--estimate-native-only', $argv, true)) {
+ $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportEstimatesTest.php']];
+ }
+ if (in_array('--estimate-contract-only', $argv, true)) {
+ $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportEstimatePlanTest.php', 'tests/Feature/BudgetLandedCostsContractTest.php']];
+ }
+ if (in_array('--estimate-regression-only', $argv, true)) {
+ $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/RequisitionApprovalLevelsTest.php']];
+ }
+ 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('--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']];
+ }
+ if (in_array('--party-concurrency', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/import-dossier-worker.php', $database, 'race-party']];
+ }
if (in_array('--native-financial-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostsTest.php', '--filter=native independently reviewed cost plan']];
}
@@ -82,6 +114,10 @@ try {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'landed-costs']];
}
+ if (in_array('--estimate-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-estimates']];
+ }
}
if ($orderPartsMode) {
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
@@ -99,6 +135,14 @@ try {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/budget-order-parts-worker.php', $database, 'race']];
}
+ if (in_array('--order-parts-amendment-concurrency', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/budget-order-parts-worker.php', $database, 'race-amend']];
+ }
+ if (in_array('--order-parts-amendment-recovery', $argv, true)) {
+ $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
+ [PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'order-parts-amendment']];
+ }
}
if ($categoryApprovalsMode) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionApprovalLevelsTest.php', 'tests/Feature/RequisitionCategoriesTest.php']];
diff --git a/tests/Concurrency/budget-distribution-recovery-worker.php b/tests/Concurrency/budget-distribution-recovery-worker.php
index e6841ed..2fecba6 100644
--- a/tests/Concurrency/budget-distribution-recovery-worker.php
+++ b/tests/Concurrency/budget-distribution-recovery-worker.php
@@ -1,10 +1,15 @@
environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
-$orderParts = ($argv[2] ?? '') === 'order-parts';
-$landedCosts = ($argv[2] ?? '') === 'landed-costs';
+$orderPartsAmendment = ($argv[2] ?? '') === 'order-parts-amendment';
+$orderParts = $orderPartsAmendment || ($argv[2] ?? '') === 'order-parts';
+$importEstimates = ($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]);
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
@@ -86,16 +96,31 @@ $unexpectedEffects = $landedCosts
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore || $unexpectedEffects) {
throw new RuntimeException('Optional schema changed pre-existing data or native balances.');
}
-$prepare = new Process([PHP_BINARY, __DIR__.($landedCosts ? '/budget-landed-cost-worker.php' : ($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php')), $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
+$prepare = new Process([PHP_BINARY, __DIR__.($landedCosts ? '/budget-landed-cost-worker.php' : ($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php')), $database, $importEstimates ? 'prepare-estimate' : ($orderPartsAmendment ? 'prepare-amend' : 'prepare')], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
$engine = app(CommonBudget::class)->for($actor);
+if ($importEstimates) {
+ $estimateInput = $input;
+ $estimateComponents = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic recovery assumption',
+ 'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
+ $estimateComponents[0] = [...$estimateComponents[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
+ $estimateApply = static fn ($engine) => $engine->reserveImportEstimate($estimateInput['plan'], 1, $estimateInput['budget'], $estimateInput['requisition'],
+ ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $estimateComponents, $estimateInput['operation']);
+ $estimated = $estimateApply($engine);
+ $input['plan'] = (string) Str::uuid();
+ $input['operation'] = (string) Str::uuid();
+ $engine->reconcileImportEstimate($estimateInput['plan'], 1, $estimated['plan_hash'], 1, 1000, $input['plan'], 1, $input['budget'],
+ $input['components'], $input['documents'], (string) Str::uuid(), $input['operation']);
+}
$apply = static fn ($engine) => $landedCosts
- ? $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation'])
- : ($orderParts ? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation'])
- : $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']));
+ ? ($importEstimates ? $engine->landedCostState($input['plan'])['result']
+ : $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']))
+ : ($orderPartsAmendment ? $engine->amendOrderParts($input['order'], $input['sources'], 'Explicit synthetic amendment preserved in backup.', $input['operation'])
+ : ($orderParts ? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation'])
+ : $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation'])));
$applied = $apply($engine);
if ($landedCosts) {
foreach (['commit', 'consume'] as $kind) {
@@ -119,7 +144,7 @@ if ($landedCosts) {
$privateRestore = $directory.'/private-restored';
File::ensureDirectoryExists($privateLive);
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateLive, 'throw' => true]));
- config(['import-landed-costs.qa_enabled' => true]);
+ config(['import-landed-costs.qa_enabled' => true, 'import-dossier.qa_enabled' => true]);
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
supplyGrant($author, ['finance']);
auth()->guard()->setUser($f['issuer']);
@@ -138,8 +163,37 @@ if ($landedCosts) {
$correction = $costs->recordDocument($author, $nativeImport, [...$nativeData, 'operation_key' => (string) Str::uuid(),
'record_key' => $nativeDoc->record_key, 'version' => 1, 'subtotal_minor' => 2100, 'total_minor' => 2100],
UploadedFile::fake()->createWithContent('recovery-correction.pdf', "%PDF-1.4\nSynthetic corrected QA bytes\n%%EOF"));
+ auth()->guard()->setUser($f['issuer']);
+ $dossier = app(ImportDossier::class);
+ $typedInput = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-RECOVERY-QA',
+ 'issuer_reference' => 'Synthetic packing list issuer', 'reason' => 'Retain a synthetic private packing list for recovery.'];
+ $typedFirst = $dossier->record($f['issuer'], $nativeImport, $typedInput,
+ UploadedFile::fake()->createWithContent('packing.pdf', "%PDF-1.4\nSynthetic packing original\n%%EOF"));
+ $typedCorrection = $dossier->record($f['issuer'], $nativeImport, [...$typedInput, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $typedFirst->record_key, 'version' => 1],
+ UploadedFile::fake()->createWithContent('packing-correction.pdf', "%PDF-1.4\nSynthetic packing correction\n%%EOF"));
+ $partyBuyer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
+ supplyGrant($partyBuyer, ['procurement', 'import_prepare']);
+ auth()->guard()->setUser($partyBuyer);
+ $partySupplier = Supplier::query()->whereKey($f['order']->supplier_id)->firstOrFail()->replicate();
+ $partySupplier->name = 'Synthetic recovery broker';
+ $partySupplier->nuit = '987654321';
+ $partySupplier->save();
+ $instructionsInput = [...$typedInput, 'operation_key' => (string) Str::uuid(), 'type' => 'written_instructions', 'reference' => 'INSTRUCTIONS-RECOVERY-QA'];
+ $instructions = $dossier->record($partyBuyer, $nativeImport, $instructionsInput,
+ UploadedFile::fake()->createWithContent('instructions.pdf', "%PDF-1.4\nSynthetic recovery instructions\n%%EOF"));
+ $partyInput = ['operation_key' => (string) Str::uuid(), 'role' => 'broker', 'version' => 0, 'supplier_id' => $partySupplier->id,
+ 'supplier_version' => $partySupplier->version, 'instruction_document_id' => $instructions->id, 'no_conflict' => true,
+ 'reason' => 'Explicit synthetic broker and instructions for recovery.'];
+ $party = app(ImportParties::class)->select($partyBuyer, $nativeImport, $partyInput);
+ $instructionsCorrection = $dossier->record($partyBuyer, $nativeImport, [...$instructionsInput, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $instructions->record_key, 'version' => 1],
+ UploadedFile::fake()->createWithContent('instructions-correction.pdf', "%PDF-1.4\nSynthetic revised recovery instructions\n%%EOF"));
+ 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];
$evidenceManifest = [];
- foreach ([$nativeDoc, $correction] as $record) {
+ foreach ($nativeEvidenceRecords as $record) {
$evidence = $record->snapshot['evidence'];
$evidenceManifest[$evidence['path']] = $evidence['sha256'];
}
@@ -152,9 +206,9 @@ if ($landedCosts) {
}
Storage::disk('local')->delete($path);
}
- auth()->guard()->logout();
- if (app(ImportCostDocumentHealth::class)->inspect()['missing'] !== 2) {
- throw new RuntimeException('The recovery test must demonstrate actual loss of its two synthetic original files.');
+ clearImportQaIdentity();
+ if (app(ImportCostDocumentHealth::class)->inspect()['missing'] !== count($nativeEvidenceRecords)) {
+ throw new RuntimeException('The recovery test must demonstrate actual loss of its synthetic original files.');
}
}
auth()->guard()->setUser($author);
@@ -197,13 +251,22 @@ try {
if ($position['result']['consumed_minor'] !== 2000 || $position['result']['reserved_minor'] !== 500 || $position['result']['phase'] !== 'mixed') {
throw new RuntimeException('Restored per-origin positions do not match the preserved journal.');
}
+ if ($importEstimates) {
+ $restoredEngine = app(CommonBudget::class)->for($restoredActor);
+ $estimateState = $restoredEngine->landedCostState($estimateInput['plan']);
+ $estimateReplay = $estimateApply($restoredEngine);
+ if ($estimateState['result']['reserved_minor'] !== 1000 || ! $estimateReplay['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
+ throw new RuntimeException('The restored estimate remainder, original replay or complete SQL fingerprint differs.');
+ }
+ echo json_encode(['estimate_source_remainder_restored' => 1000, 'estimate_original_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
+ }
if (! File::copyDirectory($privateBackup, $privateRestore)) {
throw new RuntimeException('Unable to restore private evidence into the separate QA root.');
}
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateRestore, 'throw' => true]));
- auth()->guard()->logout();
+ clearImportQaIdentity();
$health = app(ImportCostDocumentHealth::class)->inspect();
- if (! $health['ok'] || ! $health['complete'] || $health['documents_checked'] !== 2 || $health['files_checked'] !== 2) {
+ if (! $health['ok'] || ! $health['complete'] || $health['documents_checked'] !== count($nativeEvidenceRecords) || $health['files_checked'] !== count($nativeEvidenceRecords)) {
throw new RuntimeException('Restored native evidence did not match the restored SQL metadata.');
}
auth()->guard()->setUser(User::query()->findOrFail($author->id));
@@ -213,7 +276,30 @@ try {
throw new RuntimeException('Private native download no longer resolves the preserved original version.');
}
}
- echo json_encode(['private_original_versions_restored' => 2, 'source_loss_detected' => true,
+ auth()->guard()->setUser(User::query()->findOrFail($f['issuer']->id));
+ foreach ([$typedFirst, $typedCorrection, $instructions, $instructionsCorrection] as $record) {
+ $recovered = $dossier->evidence(auth()->user(), $nativeImport, $record->id);
+ if ($recovered->snapshot['evidence']['sha256'] !== $evidenceManifest[$recovered->snapshot['evidence']['path']]) {
+ throw new RuntimeException('Restored typed dossier version lost its original evidence.');
+ }
+ }
+ $restoredBuyer = User::query()->findOrFail($partyBuyer->id);
+ auth()->guard()->setUser($restoredBuyer);
+ $restoredOrder = PurchaseOrder::query()->whereKey($f['order']->id)->firstOrFail();
+ app(ImportParties::class)->assertCurrent($restoredBuyer, $restoredOrder, $nativeImport->record_key);
+ $restoredParty = SupplyRecord::query()->where('kind', 'import_party')->where('record_key', $party->record_key)->latest('version')->firstOrFail();
+ if ($restoredParty->version !== 2) {
+ throw new RuntimeException('Restored broker version differs: '.get_debug_type($restoredParty->version).' '.json_encode($restoredParty->version));
+ }
+ 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));
+ }
+ $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,
+ '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/budget-landed-cost-worker.php b/tests/Concurrency/budget-landed-cost-worker.php
index 483b5bf..ddbb63c 100644
--- a/tests/Concurrency/budget-landed-cost-worker.php
+++ b/tests/Concurrency/budget-landed-cost-worker.php
@@ -10,6 +10,7 @@ use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Process\Process;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
+use Tempo\Finance\Budget\BudgetImportEstimate;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
@@ -21,22 +22,24 @@ if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::con
throw new LogicException('Landed-cost contention requires the approved common source and isolated local QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
-if (($argv[2] ?? '') === 'legacy') {
+if (in_array($argv[2] ?? '', ['legacy', 'legacy-estimate'], true)) {
+ $legacyEstimate = ($argv[2] ?? '') === 'legacy-estimate';
$actor = User::query()->findOrFail((int) ($argv[3] ?? 0));
auth()->guard()->setUser($actor);
try {
app(CommonBudget::class)->for($actor);
throw new RuntimeException('The old runtime must refuse balances with landed-cost effects.');
} catch (HttpExceptionInterface $error) {
- if ($error->getStatusCode() !== 503 || (defined(BudgetControl::class.'::LANDED_COSTS_VERSION') && BudgetControl::LANDED_COSTS_VERSION === CommonBudget::LANDED_COSTS_CONTRACT)) {
+ if ($error->getStatusCode() !== 503 || ($legacyEstimate ? defined(BudgetControl::class.'::IMPORT_ESTIMATE_VERSION')
+ : (defined(BudgetControl::class.'::LANDED_COSTS_VERSION') && BudgetControl::LANDED_COSTS_VERSION === CommonBudget::LANDED_COSTS_CONTRACT))) {
throw $error;
}
- echo json_encode(['old_runtime_rejected_before_balance' => true, 'status' => 503,
+ echo json_encode(['old_runtime_rejected_before_balance' => true, 'old_estimate_runtime_rejected' => $legacyEstimate, 'status' => 503,
'runtime_landed_version' => defined(BudgetControl::class.'::LANDED_COSTS_VERSION') ? BudgetControl::LANDED_COSTS_VERSION : null], JSON_THROW_ON_ERROR).PHP_EOL;
}
exit;
}
-if (($argv[2] ?? '') === 'prepare') {
+if (in_array($argv[2] ?? '', ['prepare', 'prepare-estimate', 'prepare-reconcile'], true)) {
$f = receiptFixture();
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
@@ -48,11 +51,22 @@ if (($argv[2] ?? '') === 'prepare') {
$money = ['subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000,
'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000];
// Contract fixture, not a native document upload or statutory customs action.
- echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $finance->id, 'budget' => $budget, 'plan' => (string) Str::uuid(),
+ $prepared = ['tenant' => $f['tenant']->id, 'actor' => $finance->id, 'budget' => $budget, 'plan' => (string) Str::uuid(),
+ 'estimate' => in_array($argv[2] ?? '', ['prepare-estimate', 'prepare-reconcile'], true), 'reconciliation' => ($argv[2] ?? '') === 'prepare-reconcile', 'requisition' => $f['r']->id,
'version' => 1, 'operation' => (string) Str::uuid(),
'documents' => ['customs' => ['kind' => 'customs_assessment', 'id' => 1, 'source_key' => (string) Str::uuid(), 'source_version' => 1,
'creditor_key' => 'synthetic-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Synthetic customs source'), ...$money]],
- 'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', ...$money]]], JSON_THROW_ON_ERROR);
+ 'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', ...$money]]];
+ if ($prepared['reconciliation']) {
+ $components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic contention assumption',
+ 'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
+ $components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
+ auth()->guard()->setUser($finance);
+ $estimate = app(CommonBudget::class)->for($finance)->reserveImportEstimate($prepared['plan'], 1, $budget, $f['r']->id,
+ ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, (string) Str::uuid());
+ $prepared += ['estimate_hash' => $estimate['plan_hash'], 'actual_plan' => (string) Str::uuid(), 'actual_operation' => (string) Str::uuid()];
+ }
+ echo json_encode($prepared, JSON_THROW_ON_ERROR);
exit;
}
if (($argv[2] ?? '') === 'write') {
@@ -61,7 +75,19 @@ if (($argv[2] ?? '') === 'write') {
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
- $result = app(CommonBudget::class)->for($actor)->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']);
+ $engine = app(CommonBudget::class)->for($actor);
+ if ($input['reconciliation'] ?? false) {
+ $result = $engine->reconcileImportEstimate($input['plan'], $input['version'], $input['estimate_hash'], 1, 1000,
+ $input['actual_plan'], 1, $input['budget'], $input['components'], $input['documents'], $input['operation'], $input['actual_operation']);
+ } elseif ($input['estimate'] ?? false) {
+ $components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Synthetic contention assumption',
+ 'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
+ $components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000];
+ $result = $engine->reserveImportEstimate($input['plan'], $input['version'], $input['budget'], $input['requisition'],
+ ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, $input['operation']);
+ } else {
+ $result = $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']);
+ }
echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
} catch (BudgetFailure $error) {
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
@@ -70,12 +96,15 @@ if (($argv[2] ?? '') === 'write') {
}
exit;
}
-if (($argv[2] ?? '') !== 'race') {
+if (! in_array($argv[2] ?? '', ['race', 'race-estimate', 'race-estimate-reconcile'], true)) {
throw new InvalidArgumentException('Invalid landed-cost worker mode.');
}
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] as $scenario) {
- $prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
+ $prepareMode = match ($argv[2] ?? '') {
+ 'race-estimate-reconcile' => 'prepare-reconcile', 'race-estimate' => 'prepare-estimate', default => 'prepare'
+ };
+ $prepare = new Process([PHP_BINARY, __FILE__, $database, $prepareMode], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
@@ -88,7 +117,7 @@ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_p
if ($index === 1 && $scenario !== 'same_operation') {
$contender['operation'] = (string) Str::uuid();
if ($scenario === 'same_source_different_plan') {
- $contender['plan'] = (string) Str::uuid();
+ $contender[($input['reconciliation'] ?? false) ? 'actual_plan' : 'plan'] = (string) Str::uuid();
} else {
$contender['version'] = 2;
}
@@ -121,13 +150,13 @@ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_p
$statuses = array_column($results, 'status');
sort($statuses);
$commands = $db->table('budget_landed_commands')->where('tenant_id', $input['tenant'])->count();
- $audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.landed_reserve')->count();
+ $audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', ($input['reconciliation'] ?? false) ? 'budget.landed_estimate_reconcile' : (($input['estimate'] ?? false) ? 'budget.landed_estimate_reserve' : 'budget.landed_reserve'))->count();
$reserved = (int) $db->table('budget_landed_entries')->where('tenant_id', $input['tenant'])->sum('reserved_minor');
- if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1 || $reserved !== 2000
+ if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== (($input['reconciliation'] ?? false) ? 3 : 1) || $audits !== 1 || $reserved !== (($input['reconciliation'] ?? false) ? 3000 : 2000)
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
throw new RuntimeException('Contention must retain exactly one source, budget effect and audit.');
}
- echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
+ echo json_encode(['scenario' => $scenario, 'estimate' => $input['estimate'] ?? false, 'reconciliation' => $input['reconciliation'] ?? false, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved], JSON_THROW_ON_ERROR).PHP_EOL;
if ($scenario === 'same_operation') {
$artifact = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
@@ -149,6 +178,19 @@ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_p
throw new RuntimeException('The earlier whole-command runtime must refuse the new per-origin data.');
}
echo $whole->getOutput();
+ if ($input['estimate'] ?? false) {
+ $prior = base_path('storage/framework/testing/budget-import-estimate-prior-qa-20261127');
+ if (hash_file('sha256', $prior.'/src/BudgetControl.php') !== 'd81f8fb172683727c221395224cecf9acb8285ab94e71e914141d41cf9e79efa') {
+ throw new RuntimeException('Preserve the private prior runtime used for estimate downgrade verification.');
+ }
+ $oldEstimate = new Process([PHP_BINARY, __FILE__, $database, 'legacy-estimate', (string) $input['actor']], dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => $prior], timeout: 30);
+ $oldEstimate->mustRun();
+ $receipt = json_decode($oldEstimate->getOutput(), true, 32, JSON_THROW_ON_ERROR);
+ if (($receipt['old_estimate_runtime_rejected'] ?? false) !== true || ($receipt['runtime_landed_version'] ?? null) !== CommonBudget::LANDED_COSTS_CONTRACT) {
+ throw new RuntimeException('The prior per-origin runtime must refuse estimate effects before balance access.');
+ }
+ echo $oldEstimate->getOutput();
+ }
}
} finally {
if ($db->transactionLevel() > 0) {
diff --git a/tests/Concurrency/budget-order-parts-worker.php b/tests/Concurrency/budget-order-parts-worker.php
index 03ad979..419eaf5 100644
--- a/tests/Concurrency/budget-order-parts-worker.php
+++ b/tests/Concurrency/budget-order-parts-worker.php
@@ -23,6 +23,7 @@ if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::con
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
require_once __DIR__.'/../Support/BudgetOrderPartsFixture.php';
+$amendmentMode = in_array($argv[2] ?? '', ['prepare-amend', 'write-amend', 'race-amend'], true);
if (($argv[2] ?? '') === 'legacy') {
$actor = User::query()->findOrFail((int) ($argv[3] ?? 0));
auth()->guard()->setUser($actor);
@@ -37,7 +38,7 @@ if (($argv[2] ?? '') === 'legacy') {
}
exit;
}
-if (($argv[2] ?? '') === 'prepare') {
+if (in_array($argv[2] ?? '', ['prepare', 'prepare-amend'], true)) {
$f = receiptFixture();
$source = unissuedOrderPartsSource($f, 10000);
$line = $source->items()->sole();
@@ -52,20 +53,36 @@ if (($argv[2] ?? '') === 'prepare') {
$engine = app(CommonBudget::class)->for($f['issuer']);
$lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
$plan = [['allocation_key' => 'synthetic', 'line_id' => $line->id, 'centre_id' => $f['r']->cost_center_id, 'subtotal_minor' => 10000, 'total_minor' => 10000]];
+ if ($amendmentMode) {
+ $plan = [[...$plan[0], 'allocation_key' => 'a', 'subtotal_minor' => 5000, 'total_minor' => 5000],
+ [...$plan[0], 'allocation_key' => 'b', 'subtotal_minor' => 5000, 'total_minor' => 5000]];
+ }
$engine->recordDistribution($source->id, 'reserve', $plan, $lines, str_repeat('a', 64), (string) Str::uuid());
$award = $engine->recordDistribution($source->id, 'award', $plan, $lines, str_repeat('b', 64), (string) Str::uuid());
- echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'budget' => $budget, 'source' => $award['distribution_id'],
+ $input = ['tenant' => $f['tenant']->id, 'actor' => $f['issuer']->id, 'budget' => $budget, 'source' => $award['distribution_id'],
'order' => (string) Str::uuid(), 'operation' => (string) Str::uuid(), 'sources' => [['origin' => $source->id, 'version' => 0,
- 'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => 'synthetic', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]]], JSON_THROW_ON_ERROR);
+ 'plan_hash' => $award['plan_hash'], 'allocations' => [['allocation_key' => 'synthetic', 'subtotal_minor' => 4000, 'total_minor' => 4000]]]]];
+ if ($amendmentMode) {
+ $input['sources'][0]['allocations'] = [['allocation_key' => 'a', 'subtotal_minor' => 2000, 'total_minor' => 2000],
+ ['allocation_key' => 'b', 'subtotal_minor' => 2000, 'total_minor' => 2000]];
+ $engine->commitOrderParts($input['order'], $input['sources'], (string) Str::uuid());
+ $input['actor'] = $finance->id;
+ $input['sources'][0]['version'] = 1;
+ $input['sources'][0]['allocations'][0]['subtotal_minor'] = $input['sources'][0]['allocations'][0]['total_minor'] = 1000;
+ $input['sources'][0]['allocations'][1]['subtotal_minor'] = $input['sources'][0]['allocations'][1]['total_minor'] = 3000;
+ }
+ echo json_encode($input, JSON_THROW_ON_ERROR);
exit;
}
-if (($argv[2] ?? '') === 'write') {
+if (in_array($argv[2] ?? '', ['write', 'write-amend'], true)) {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_order_parts_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
- $result = app(CommonBudget::class)->for($actor)->commitOrderParts($input['order'], $input['sources'], $input['operation']);
+ $engine = app(CommonBudget::class)->for($actor);
+ $result = $amendmentMode ? $engine->amendOrderParts($input['order'], $input['sources'], 'Explicit synthetic concurrent Finance amendment.', $input['operation'])
+ : $engine->commitOrderParts($input['order'], $input['sources'], $input['operation']);
echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
} catch (BudgetFailure $error) {
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
@@ -74,13 +91,13 @@ if (($argv[2] ?? '') === 'write') {
}
exit;
}
-if (($argv[2] ?? '') !== 'race') {
+if (! in_array($argv[2] ?? '', ['race', 'race-amend'], true)) {
throw new InvalidArgumentException('Invalid order-part worker mode.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
foreach (['same_operation', 'conflicting_version'] as $scenario) {
- $prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
+ $prepare = new Process([PHP_BINARY, __FILE__, $database, $amendmentMode ? 'prepare-amend' : 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
@@ -91,11 +108,16 @@ foreach (['same_operation', 'conflicting_version'] as $scenario) {
for ($index = 0; $index < 2; $index++) {
if ($index === 1 && $scenario === 'conflicting_version') {
$input['operation'] = (string) Str::uuid();
- $input['order'] = (string) Str::uuid();
- $input['sources'][0]['allocations'][0]['subtotal_minor'] = 6000;
- $input['sources'][0]['allocations'][0]['total_minor'] = 6000;
+ if ($amendmentMode) {
+ $input['sources'][0]['allocations'][0]['subtotal_minor'] = $input['sources'][0]['allocations'][0]['total_minor'] = 1500;
+ $input['sources'][0]['allocations'][1]['subtotal_minor'] = $input['sources'][0]['allocations'][1]['total_minor'] = 2500;
+ } else {
+ $input['order'] = (string) Str::uuid();
+ $input['sources'][0]['allocations'][0]['subtotal_minor'] = 6000;
+ $input['sources'][0]['allocations'][0]['total_minor'] = 6000;
+ }
}
- $worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
+ $worker = new Process([PHP_BINARY, __FILE__, $database, $amendmentMode ? 'write-amend' : 'write', json_encode($input, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$workers[] = $worker;
$worker->start();
}
@@ -125,14 +147,14 @@ foreach (['same_operation', 'conflicting_version'] as $scenario) {
$entries = $db->table('budget_distribution_entries')->where('distribution_id', $input['source']);
$reserved = (int) (clone $entries)->sum('reserved_minor');
$committed = (int) (clone $entries)->sum('committed_minor');
- $commands = $db->table('budget_order_commands')->where('tenant_id', $input['tenant'])->count();
- $audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.orders_committed')->count();
+ $commands = $db->table('budget_order_commands')->where('tenant_id', $input['tenant'])->where('kind', $amendmentMode ? 'amend' : 'commit')->count();
+ $audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', $amendmentMode ? 'budget.order_parts_amended' : 'budget.orders_committed')->count();
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1
|| $reserved + $committed !== 10000 || ! in_array($committed, [4000, 6000], true)
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
throw new RuntimeException('Contention did not preserve one command, one audit and the exact original budget.');
}
- echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
+ echo json_encode(['scenario' => $scenario, 'amendment' => $amendmentMode, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved, 'committed_minor' => $committed], JSON_THROW_ON_ERROR).PHP_EOL;
if ($scenario === 'same_operation') {
$proof = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
diff --git a/tests/Concurrency/import-dossier-worker.php b/tests/Concurrency/import-dossier-worker.php
new file mode 100644
index 0000000..5eb5ef4
--- /dev/null
+++ b/tests/Concurrency/import-dossier-worker.php
@@ -0,0 +1,153 @@
+make(Kernel::class)->bootstrap();
+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)) {
+ throw new LogicException('Dossier contention requires disposable local PostgreSQL QA.');
+}
+config(['import-dossier.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';
+$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)) {
+ $f = receiptFixture();
+ supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
+ auth()->guard()->setUser($f['issuer']);
+ $import = app(SupplyPlanning::class)->save($f['issuer'], 'import', supplyInput(['purchase_order_id' => $f['order']->id,
+ 'purpose' => 'internal', 'jurisdiction' => 'Synthetic contention jurisdiction', 'origin_country' => 'Synthetic A',
+ 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime']));
+ $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) {
+ $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);
+ $instructions = app(ImportDossier::class)->record($actor, $import, [...$data, 'type' => 'written_instructions'], $file());
+ $supplier = Supplier::query()->whereKey($f['order']->supplier_id)->firstOrFail()->replicate();
+ $supplier->name = 'Synthetic concurrent broker';
+ $supplier->nuit = '987654321';
+ $supplier->save();
+ $data = ['operation_key' => (string) Str::uuid(), 'role' => 'broker', 'version' => 0, 'supplier_id' => $supplier->id,
+ 'supplier_version' => $supplier->version, 'instruction_document_id' => $instructions->id, 'no_conflict' => true,
+ 'reason' => 'Explicit synthetic concurrent independent buyer selection.'];
+ if (($argv[3] ?? '') === 'same_version') {
+ app(ImportParties::class)->select($actor, $import, $data);
+ $data = [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1, 'role' => 'broker'];
+ }
+ } elseif (($argv[3] ?? '') === 'same_version') {
+ $old = app(ImportDossier::class)->record($f['issuer'], $import, $data, $file());
+ $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,
+ '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)) {
+ $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());
+ 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)) {
+ 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);
+ $prepare->mustRun();
+ $input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
+ $db = DB::connection();
+ $workers = [];
+ $db->beginTransaction();
+ try {
+ $db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
+ for ($index = 0; $index < 2; $index++) {
+ $workerInput = $input;
+ 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);
+ $workers[] = $worker;
+ $worker->start();
+ }
+ $deadline = microtime(true) + 10;
+ do {
+ $db->select('select pg_stat_clear_snapshot()');
+ $blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_dossier_write_%' and wait_event_type='Lock'", [$database])->n;
+ if ($blocked >= 2) {
+ break;
+ }
+ usleep(50000);
+ } while (microtime(true) < $deadline);
+ if ($blocked < 2) {
+ throw new RuntimeException('Both dossier writers must demonstrably wait on the company lock.');
+ }
+ $db->commit();
+ $results = [];
+ foreach ($workers as $worker) {
+ $worker->wait();
+ if (! $worker->isSuccessful()) {
+ throw new RuntimeException($worker->getErrorOutput());
+ }
+ $results[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR);
+ }
+ $statuses = array_column($results, 'status');
+ sort($statuses);
+ $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)) {
+ 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) {
+ app(ImportEvidence::class)->bytes($record);
+ }
+ echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
+ 'documents_created' => $records, 'audits' => $audits, 'files_created' => $files, 'all_originals_verified' => true], JSON_THROW_ON_ERROR).PHP_EOL;
+ } finally {
+ if ($db->transactionLevel() > 0) {
+ $db->rollBack();
+ }
+ foreach ($workers as $worker) {
+ if ($worker->isRunning()) {
+ $worker->stop();
+ }
+ }
+ }
+}
diff --git a/tests/Feature/BudgetLandedCostsContractTest.php b/tests/Feature/BudgetLandedCostsContractTest.php
index 8b8c11c..fcd7c42 100644
--- a/tests/Feature/BudgetLandedCostsContractTest.php
+++ b/tests/Feature/BudgetLandedCostsContractTest.php
@@ -10,6 +10,7 @@ use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
+use Tempo\Finance\Budget\BudgetImportEstimate;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -58,6 +59,75 @@ test('landed reserve commit and consume affect only the additional native origin
->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
});
+test('pre-document assumptions reserve only extras and reconcile atomically into actual origins without an invented principal', function () {
+ $components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Pressuposto sintético explícito',
+ 'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
+ $components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 160, 'total_minor' => 1160];
+ $goods = ['subtotal_minor' => 10000, 'tax_minor' => 1600, 'total_minor' => 11600];
+ $operation = (string) Str::uuid();
+ $beforePrincipal = DB::table('invoices')->count();
+ $reserved = $this->engine->reserveImportEstimate($this->key, 1, $this->budget, $this->f['r']->id, $goods, $components, $operation);
+ expect($reserved['additional_amount_minor'])->toBe(1160)->and($reserved['total_reference_minor'])->toBe(12760)
+ ->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(1160)
+ ->and($this->engine->reserveImportEstimate($this->key, 1, $this->budget, $this->f['r']->id, $goods, $components, $operation)['replayed'])->toBeTrue();
+ expect(fn () => $this->engine->reserveImportEstimate((string) Str::uuid(), 1, $this->budget, $this->f['r']->id, $goods, $components, (string) Str::uuid()))->toThrow(BudgetFailure::class);
+ expect(fn () => $this->engine->reconcileImportEstimate($this->key, 1, $reserved['plan_hash'], 1, 1000,
+ (string) Str::uuid(), 1, $this->budget, $this->components, $this->documents, (string) Str::uuid(), $operation))->toThrow(BudgetFailure::class);
+ expect($this->engine->balance($this->budget)['reserved_minor'])->toBe(1160);
+ $this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'commit', (string) Str::uuid());
+ expect(fn () => $this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'consume', (string) Str::uuid()))->toThrow(BudgetFailure::class);
+ $actual = $this->engine->amendLandedCosts($this->key, 1, $reserved['plan_hash'], 2, $this->components, $this->documents, (string) Str::uuid());
+ expect($actual['additional_amount_minor'])->toBe(2000)->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(2000)
+ ->and($this->engine->balance($this->budget)['committed_minor'])->toBe(0)
+ ->and(DB::table('invoices')->count())->toBe($beforePrincipal);
+});
+
+test('partial estimate reconciliation preserves its unallocated remainder and actual costs once with atomic failure', function () {
+ $components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Pressuposto sintético explícito',
+ 'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
+ $components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 3000, 'tax_minor' => 0, 'total_minor' => 3000];
+ $reserved = $this->engine->reserveImportEstimate($this->key, 1, $this->budget, $this->f['r']->id,
+ ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000], $components, (string) Str::uuid());
+ $actualKey = (string) Str::uuid();
+ $operation = (string) Str::uuid();
+ $actualOperation = (string) Str::uuid();
+ $apply = fn () => $this->engine->reconcileImportEstimate($this->key, 1, $reserved['plan_hash'], 1, 1000,
+ $actualKey, 1, $this->budget, $this->components, $this->documents, $operation, $actualOperation);
+ $result = $apply();
+ expect($result['additional_amount_minor'])->toBe(2000)->and($result['estimate_reconciliation']['reserved_minor'])->toBe(2000)
+ ->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(4000)
+ ->and($apply()['replayed'])->toBeTrue()->and(DB::table('budget_landed_commands')->count())->toBe(3);
+ $before = DB::table('budget_landed_entries')->orderBy('id')->get()->toJson();
+ expect(fn () => $this->engine->reconcileImportEstimate($this->key, 1, $reserved['plan_hash'], 2, 1000,
+ (string) Str::uuid(), 1, $this->budget, $this->components, $this->documents, (string) Str::uuid(), (string) Str::uuid()))->toThrow(BudgetFailure::class);
+ expect(DB::table('budget_landed_entries')->orderBy('id')->get()->toJson())->toBe($before)
+ ->and(DB::table('budget_landed_commands')->count())->toBe(3);
+});
+
+test('multiple approved-origin estimates reconcile to the same native invoice plan without another principal or repeated actual cost', function () {
+ $components = array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Pressuposto sintético explícito',
+ 'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
+ $components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 3000, 'tax_minor' => 0, 'total_minor' => 3000];
+ $goods = ['subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000];
+ $first = $this->engine->reserveImportEstimate($this->key, 1, $this->budget, $this->f['r']->id, $goods, $components, (string) Str::uuid());
+ $request = $this->f['r']->replicate();
+ $request->number = 'SECOND-ESTIMATE-'.Str::random(10);
+ $request->save();
+ $secondKey = (string) Str::uuid();
+ $second = $this->engine->reserveImportEstimate($secondKey, 1, $this->budget, $request->id, $goods, $components, (string) Str::uuid());
+ $documents = array_diff_key($this->documents, ['source-2' => true]);
+ $actualComponents = array_values(array_filter($this->components, fn ($row) => $row['kind'] !== 'duty'));
+ $actualKey = (string) Str::uuid();
+ $this->engine->reconcileImportEstimate($this->key, 1, $first['plan_hash'], 1, 1000, $actualKey, 1, $this->budget,
+ $actualComponents, $documents, (string) Str::uuid(), (string) Str::uuid());
+ $result = $this->engine->reconcileImportEstimate($secondKey, 1, $second['plan_hash'], 1, 2000, $actualKey, 1, $this->budget,
+ $actualComponents, $documents, (string) Str::uuid(), (string) Str::uuid());
+ expect($result['additional_amount_minor'])->toBe(0)->and($result['origins'])->toBe([])
+ ->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(3000)
+ ->and($this->engine->landedCostState($actualKey)['result']['revision'])->toBe(2)
+ ->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
+});
+
test('landed operation mismatch stale versions and repeated transition fail without changing the balance', function () {
$operation = (string) Str::uuid();
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, $operation);
diff --git a/tests/Feature/BudgetOrderPartsContractTest.php b/tests/Feature/BudgetOrderPartsContractTest.php
index 5e95b21..5bda4fd 100644
--- a/tests/Feature/BudgetOrderPartsContractTest.php
+++ b/tests/Feature/BudgetOrderPartsContractTest.php
@@ -1,6 +1,7 @@
create(['tenant_id' => $test->finance->tenant_id, 'department_id' => $test->f['department']->id,
+ 'code' => 'PART-AMEND-'.Str::random(8), 'name' => 'Synthetic amendment centre']);
+ $test->actingAs($test->finance);
+ $test->secondBudget = app(CommonBudget::class)->for($test->finance)->create(['cost_center_id' => $centre->id,
+ 'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000,
+ 'reason' => 'Synthetic second-centre amendment capacity.']);
+ $test->actingAs($test->reviewer);
+ app(CommonBudget::class)->for($test->reviewer)->approve($test->secondBudget);
+ $test->actingAs($test->f['issuer']);
+ $request = unissuedOrderPartsSource($test->f, 10000);
+ $line = $request->items()->sole();
+ $lines = [$line->id => ['subtotal_minor' => 10000, 'total_minor' => 10000, 'required_kind' => 'operating']];
+ $allocations = [
+ ['allocation_key' => 'a', 'line_id' => $line->id, 'centre_id' => $request->cost_center_id, 'subtotal_minor' => 5000, 'total_minor' => 5000],
+ ['allocation_key' => 'b', 'line_id' => $line->id, 'centre_id' => $centre->id, 'subtotal_minor' => 5000, 'total_minor' => 5000],
+ ];
+ $engine = app(CommonBudget::class)->for($test->f['issuer']);
+ $engine->recordDistribution($request->id, 'reserve', $allocations, $lines, str_repeat('a', 64), (string) Str::uuid());
+ $result = $engine->recordDistribution($request->id, 'award', $allocations, $lines, str_repeat('b', 64), (string) Str::uuid());
+
+ return ['origin' => $request->id, 'version' => 0, 'plan_hash' => $result['plan_hash'],
+ 'allocations' => [['allocation_key' => 'a', 'subtotal_minor' => 2000, 'total_minor' => 2000],
+ ['allocation_key' => 'b', 'subtotal_minor' => 2000, 'total_minor' => 2000]]];
+}
+
+test('explicit Finance order amendment preserves unissued reserve original documents and replay', function () {
+ $source = amendableOrderPartsSource($this);
+ $order = (string) Str::uuid();
+ app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$source], (string) Str::uuid());
+ $this->actingAs($this->finance);
+ $engine = app(CommonBudget::class)->for($this->finance);
+ $original = DB::table('budget_order_commands')->where('kind', 'commit')->first()->snapshot;
+ $source['version'] = 1;
+ $source['allocations'][0]['subtotal_minor'] = $source['allocations'][0]['total_minor'] = 1000;
+ $source['allocations'][1]['subtotal_minor'] = $source['allocations'][1]['total_minor'] = 3000;
+ $operation = (string) Str::uuid();
+ expect($engine->amendOrderParts($order, [$source], 'Explicit synthetic Finance reallocation.', $operation)['replayed'])->toBeFalse()
+ ->and($engine->amendOrderParts($order, [$source], 'Explicit synthetic Finance reallocation.', $operation)['replayed'])->toBeTrue()
+ ->and(DB::table('budget_order_commands')->where('kind', 'commit')->first()->snapshot)->toBe($original)
+ ->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
+ ->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000)
+ ->and($engine->balance($this->budget)['committed_minor'])->toBe(1000)
+ ->and($engine->balance($this->secondBudget)['committed_minor'])->toBe(3000);
+ expect(fn () => $engine->amendOrderParts($order, [$source], 'Stale independent synthetic amendment.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
+ $distribution = DB::table('budget_distributions')->where('requisition_id', $source['origin'])->first();
+ $source['version'] = 2;
+ $source['plan_hash'] = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR)['plan_hash'];
+ $engine->cancelOrderParts($order, [$source], (string) Str::uuid());
+ expect((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
+ ->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000);
+});
+
+test('Finance amendment respects consumed floors authorisation atomicity and revised invoice capacity', function () {
+ $source = amendableOrderPartsSource($this);
+ $order = (string) Str::uuid();
+ $issuer = app(CommonBudget::class)->for($this->f['issuer']);
+ $issuer->commitOrderParts($order, [$source], (string) Str::uuid());
+ $source['version'] = 1;
+ $amended = $source;
+ $amended['allocations'][0]['subtotal_minor'] = $amended['allocations'][0]['total_minor'] = 1000;
+ $amended['allocations'][1]['subtotal_minor'] = $amended['allocations'][1]['total_minor'] = 3000;
+ expect(fn () => $issuer->amendOrderParts($order, [$amended], 'Procurement cannot amend Finance allocations.', (string) Str::uuid()))->toThrow(HttpException::class);
+ $this->actingAs($this->finance);
+ $engine = app(CommonBudget::class)->for($this->finance);
+ $invoice = orderPartsInvoice($this, 1500);
+ $consumption = $source;
+ $consumption['allocations'] = [['order_key' => $order, 'allocation_key' => 'a', 'subtotal_minor' => 1500, 'total_minor' => 1500]];
+ $engine->consumeOrderParts($invoice->id, [$consumption], (string) Str::uuid());
+ $amended['version'] = 2;
+ $before = [DB::table('budget_distribution_entries')->get()->toArray(), DB::table('budget_order_commands')->count()];
+ expect(fn () => $engine->amendOrderParts($order, [$amended], 'Cannot reduce the amount already consumed.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
+ expect([DB::table('budget_distribution_entries')->get()->toArray(), DB::table('budget_order_commands')->count()])->toEqual($before);
+ $amended['allocations'][0]['subtotal_minor'] = $amended['allocations'][0]['total_minor'] = 1500;
+ $amended['allocations'][1]['subtotal_minor'] = $amended['allocations'][1]['total_minor'] = 2500;
+ $engine->amendOrderParts($order, [$amended], 'Explicit amendment preserves the consumed floor.', (string) Str::uuid());
+ $distribution = DB::table('budget_distributions')->where('requisition_id', $source['origin'])->first();
+ $consumption = ['origin' => $source['origin'], 'version' => 3,
+ 'plan_hash' => json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR)['plan_hash'],
+ 'allocations' => [['order_key' => $order, 'allocation_key' => 'b', 'subtotal_minor' => 2500, 'total_minor' => 2500]]];
+ $engine->consumeOrderParts(orderPartsInvoice($this, 2500)->id, [$consumption], (string) Str::uuid());
+ expect((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(4000)
+ ->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
+ ->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000);
+});
+
+test('one invalid origin rejects an entire consolidated Finance amendment without partial effects', function () {
+ $a = amendableOrderPartsSource($this);
+ $b = amendableOrderPartsSource($this);
+ $order = (string) Str::uuid();
+ app(CommonBudget::class)->for($this->f['issuer'])->commitOrderParts($order, [$a, $b], (string) Str::uuid());
+ $this->actingAs($this->finance);
+ $a['version'] = $b['version'] = 1;
+ $a['allocations'][0]['subtotal_minor'] = $a['allocations'][0]['total_minor'] = 1000;
+ $a['allocations'][1]['subtotal_minor'] = $a['allocations'][1]['total_minor'] = 3000;
+ $b['allocations'][1]['subtotal_minor'] = $b['allocations'][1]['total_minor'] = 3000;
+ $before = [DB::table('budget_distributions')->get()->toArray(), DB::table('budget_order_allocations')->get()->toArray(),
+ DB::table('budget_order_commands')->count(), DB::table('budget_distribution_entries')->get()->toArray()];
+ expect(fn () => app(CommonBudget::class)->for($this->finance)->amendOrderParts($order, [$a, $b],
+ 'Second origin cannot change its original line totals.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
+ expect([DB::table('budget_distributions')->get()->toArray(), DB::table('budget_order_allocations')->get()->toArray(),
+ DB::table('budget_order_commands')->count(), DB::table('budget_distribution_entries')->get()->toArray()])->toEqual($before);
+});
+
+test('Finance amendment cannot transfer commitment into a centre with no available budget', function () {
+ $source = amendableOrderPartsSource($this);
+ $centre = DB::table('budgets')->where('id', $this->secondBudget)->value('cost_center_id');
+ $other = unissuedOrderPartsSource($this->f, 95000);
+ $line = $other->items()->sole();
+ $engine = app(CommonBudget::class)->for($this->f['issuer']);
+ $engine->recordDistribution($other->id, 'reserve', [['allocation_key' => 'other', 'line_id' => $line->id, 'centre_id' => $centre,
+ 'subtotal_minor' => 95000, 'total_minor' => 95000]], [$line->id => ['subtotal_minor' => 95000, 'total_minor' => 95000, 'required_kind' => 'operating']],
+ str_repeat('c', 64), (string) Str::uuid());
+ $order = (string) Str::uuid();
+ $engine->commitOrderParts($order, [$source], (string) Str::uuid());
+ $this->actingAs($this->finance);
+ $source['version'] = 1;
+ $source['allocations'][0]['subtotal_minor'] = $source['allocations'][0]['total_minor'] = 1000;
+ $source['allocations'][1]['subtotal_minor'] = $source['allocations'][1]['total_minor'] = 3000;
+ expect(fn () => app(CommonBudget::class)->for($this->finance)->amendOrderParts($order, [$source],
+ 'Insufficient destination capacity must reject this amendment.', (string) Str::uuid()))->toThrow(BudgetFailure::class);
+ expect(DB::table('budget_order_commands')->where('kind', 'amend')->count())->toBe(0)
+ ->and((int) DB::table('budget_distribution_entries')->where('kind', 'like', 'order-amend-%')->count())->toBe(0);
+});
+
test('one approved synthetic source commits forty then sixty without committing the unissued portion', function () {
$source = orderPartsSource($this, 10000);
$order = (string) Str::uuid();
diff --git a/tests/Feature/ImportDossierTest.php b/tests/Feature/ImportDossierTest.php
new file mode 100644
index 0000000..23f421a
--- /dev/null
+++ b/tests/Feature/ImportDossierTest.php
@@ -0,0 +1,239 @@
+ true]);
+ Storage::fake('local');
+ $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 dossier jurisdiction',
+ 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary regime',
+ ]));
+ $this->input = ['operation_key' => (string) Str::uuid(), 'type' => 'packing_list', 'reference' => 'PACK-QA-1',
+ 'issuer_reference' => 'Synthetic supplier', 'issued_on' => today()->toDateString(), 'notes' => 'Synthetic private original.',
+ 'reason' => 'Retain the original synthetic packing list.'];
+ $this->bytes = "%PDF-1.4\nSynthetic packing list only\n%%EOF";
+ $this->file = UploadedFile::fake()->createWithContent('packing.pdf', $this->bytes);
+});
+
+test('typed import dossier retains originals corrections and replay without financial stock or customs effects', function () {
+ $service = app(ImportDossier::class);
+ $before = [DB::table('stock_movements')->count(), DB::table('invoices')->count(), DB::table('budget_entries')->get()->toArray(), $this->import->toArray()];
+ $first = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
+ expect($service->record($this->f['issuer'], $this->import, $this->input, $this->file)->id)->toBe($first->id)
+ ->and($first->version)->toBe(1)->and($first->snapshot['financial_effects'])->toBeFalse()
+ ->and($first->snapshot['external_submission'])->toBeFalse();
+ $correction = $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $first->record_key, 'version' => 1, 'reference' => 'PACK-QA-1-CORRECTED'],
+ UploadedFile::fake()->createWithContent('corrected.pdf', "%PDF-1.4\nSynthetic corrected packing list\n%%EOF"));
+ expect($correction->version)->toBe(2)->and($correction->snapshot['supersedes'])->toBe($first->id)
+ ->and(app(ImportEvidence::class)->bytes($first))->toBe($this->bytes)
+ ->and($service->record($this->f['issuer'], $this->import, $this->input, $this->file)->id)->toBe($first->id)
+ ->and([DB::table('stock_movements')->count(), DB::table('invoices')->count(), DB::table('budget_entries')->get()->toArray(), $this->import->fresh()->toArray()])->toEqual($before);
+ $workspace = $service->workspace($this->f['issuer'], $this->import);
+ expect($workspace['documents']->items()[0]['current'])->toBeTrue()
+ ->and($workspace['documents']->items()[1]['current'])->toBeFalse()
+ ->and(json_encode($workspace, JSON_THROW_ON_ERROR))->not->toContain('import-dossier/'.$first->tenant_id.'/');
+ expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $first->record_key, 'version' => 1], $this->file))->toThrow(HttpException::class);
+ expect(fn () => DB::transaction(fn () => DB::table('supply_records')->where('id', $first->id)->update(['state' => 'approved'])))->toThrow(QueryException::class);
+});
+
+test('typed dossier refuses duplicate identities type changes and storage changes', function () {
+ $service = app(ImportDossier::class);
+ $record = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
+ expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()], $this->file))->toThrow(HttpException::class);
+ expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $record->record_key, 'version' => 1, 'type' => 'payment_evidence'], $this->file))->toThrow(HttpException::class);
+ $this->withoutVite();
+ $response = $this->get('/compras/importacoes/'.$this->import->id.'/documentos/'.$record->id)->assertOk()
+ ->assertHeader('X-Content-Type-Options', 'nosniff');
+ expect($response->getContent())->toBe($this->bytes);
+ Storage::disk('local')->put($record->snapshot['evidence']['path'], str_repeat('X', strlen($this->bytes)));
+ expect($response->getContent())->toBe($this->bytes);
+ $this->get('/compras/importacoes/'.$this->import->id.'/documentos/'.$record->id)->assertConflict();
+ expect(SupplyRecord::query()->where('kind', 'import_document')->count())->toBe(1);
+});
+
+test('dossier read and write use current roles tenant isolation and the disabled capability guard', function () {
+ $service = app(ImportDossier::class);
+ $record = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
+ $finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
+ supplyGrant($finance, ['finance']);
+ $this->actingAs($finance);
+ expect($service->workspace($finance, $this->import)['canWrite'])->toBeFalse();
+ expect(fn () => $service->record($finance, $this->import, [...$this->input, 'operation_key' => (string) Str::uuid()], $this->file))->toThrow(HttpException::class);
+ $this->withoutVite();
+ $url = '/compras/importacoes/'.$this->import->id.'/documentos';
+ $this->get($url)->assertOk()->assertViewHas('page', fn ($page) => $page['component'] === 'supply/import-dossier' && $page['encryptHistory'] === true && $page['props']['canWrite'] === false);
+ $other = receiptFixture();
+ supplyGrant($other['issuer'], ['procurement', 'import_prepare']);
+ $this->actingAs($other['issuer'])->get($url.'/'.$record->id)->assertNotFound();
+ $this->actingAs($this->f['issuer']);
+ DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->update(['maintenance' => true, 'expires_at' => now()->addHour()]);
+ $this->get($url)->assertForbidden();
+ config(['import-dossier.qa_enabled' => false]);
+ expect($service->ready())->toBeFalse();
+ $this->get($url)->assertServiceUnavailable();
+});
+
+test('failed dossier audit removes only the new unconfirmed private file and preserves existing versions', function () {
+ $service = app(ImportDossier::class);
+ $record = $service->record($this->f['issuer'], $this->import, $this->input, $this->file);
+ $before = Storage::disk('local')->allFiles();
+ $this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('Synthetic audit failure'));
+ expect(fn () => $service->record($this->f['issuer'], $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $record->record_key, 'version' => 1], UploadedFile::fake()->createWithContent('next.pdf', "%PDF-1.4\nUnconfirmed QA version\n%%EOF")))->toThrow(RuntimeException::class);
+ expect(Storage::disk('local')->allFiles())->toEqual($before)
+ ->and(app(ImportEvidence::class)->bytes($record))->toBe($this->bytes)
+ ->and(SupplyRecord::query()->where('kind', 'import_document')->count())->toBe(1);
+});
+
+test('aggregate import inspection includes typed dossier originals without exposing or repairing them', function () {
+ $record = app(ImportDossier::class)->record($this->f['issuer'], $this->import, $this->input, $this->file);
+ $path = $record->snapshot['evidence']['path'];
+ auth()->logout();
+ $health = app(ImportCostDocumentHealth::class);
+ expect($health->inspect()['ok'])->toBeTrue();
+ Storage::disk('local')->put($path, str_repeat('Y', strlen($this->bytes)));
+ Storage::disk('local')->put('import-dossier/orphan.pdf', 'Synthetic unreferenced file.');
+ $result = $health->inspect();
+ expect($result['altered'])->toBe(1)->and($result['unreferenced'])->toBe(1)
+ ->and(json_encode($result, JSON_THROW_ON_ERROR))->not->toContain($path, $this->input['reference']);
+ Storage::disk('local')->assertExists($path);
+});
+
+test('dossier rejects unsupported empty or oversized originals before storing any record', function () {
+ foreach ([UploadedFile::fake()->createWithContent('script.txt', 'Not an accepted original.'),
+ UploadedFile::fake()->create('oversized.pdf', 2049, 'application/pdf'),
+ UploadedFile::fake()->createWithContent('empty.pdf', '')] as $file) {
+ $this->postJson('/compras/importacoes/'.$this->import->id.'/documentos', [...$this->input, 'file' => $file])->assertUnprocessable();
+ }
+ expect(SupplyRecord::query()->where('kind', 'import_document')->count())->toBe(0)
+ ->and(Storage::disk('local')->allFiles())->toBe([]);
+});
+
+function importDossierPartyFixture(object $test): array
+{
+ $buyer = User::factory()->create(['tenant_id' => $test->f['tenant']->id, 'department_id' => $test->f['department']->id,
+ 'purchasing_role' => PurchasingRole::Procurement]);
+ supplyGrant($buyer, ['procurement', 'import_prepare']);
+ $test->actingAs($buyer);
+ $supplier = Supplier::query()->whereKey($test->f['order']->supplier_id)->firstOrFail()->replicate();
+ $supplier->name = 'Despachante exclusivamente sintético';
+ $supplier->nuit = '987654321';
+ $supplier->save();
+ $instructions = app(ImportDossier::class)->record($buyer, $test->import, [...$test->input, 'operation_key' => (string) Str::uuid(),
+ 'type' => 'written_instructions', 'reference' => 'INSTRUCTIONS-QA'], $test->file);
+ $data = ['operation_key' => (string) Str::uuid(), 'role' => 'broker', 'version' => 0, 'supplier_id' => $supplier->id,
+ 'supplier_version' => $supplier->version, 'instruction_document_id' => $instructions->id,
+ 'reason' => 'Explicit synthetic independent buyer selection.', 'no_conflict' => true];
+
+ return [$buyer, $supplier, $instructions, $data];
+}
+
+test('broker selection reuses eligible entity and current written instructions preserving history and requester segregation', function () {
+ [$buyer, $supplier, $instructions, $data] = importDossierPartyFixture($this);
+ $service = app(ImportParties::class);
+ $this->actingAs($this->f['issuer']);
+ expect($service->canSelect($this->f['issuer'], $this->f['order']))->toBeFalse();
+ expect(fn () => $service->select($this->f['issuer'], $this->import, $data))->toThrow(HttpException::class);
+ $this->actingAs($buyer);
+ expect($service->workspace($buyer, $this->import, 'despachante')['suppliers']->pluck('id')->all())->toContain($supplier->id);
+ $record = $service->select($buyer, $this->import, $data);
+ expect($record->snapshot['supplier']['id'])->toBe($supplier->id)
+ ->and($record->data['instruction_document_id'])->toBe($instructions->id)
+ ->and($record->snapshot['no_conflict'])->toBeTrue()
+ ->and($service->select($buyer, $this->import, $data)->id)->toBe($record->id);
+ $this->withoutVite();
+ $this->get('/compras/importacoes/'.$this->import->id.'/documentos')->assertOk()
+ ->assertViewHas('page', fn ($page) => $page['props']['parties']['canSelect'] === true);
+ $this->post('/compras/importacoes/'.$this->import->id.'/intervenientes', $data)
+ ->assertRedirect('/compras/importacoes/'.$this->import->id.'/documentos');
+ $correction = app(ImportDossier::class)->record($buyer, $this->import, [...$this->input, 'operation_key' => (string) Str::uuid(),
+ 'record_key' => $instructions->record_key, 'version' => 1, 'type' => 'written_instructions', 'reference' => 'INSTRUCTIONS-QA-2'],
+ UploadedFile::fake()->createWithContent('instructions.pdf', "%PDF-1.4\nNew synthetic instructions\n%%EOF"));
+ $transit = supplyInput(['event_date' => today()->toDateString(), 'evidence' => 'Synthetic transit evidence.'], 'transit', $this->import);
+ expect(fn () => app(SupplyPlanning::class)->save($buyer, 'import', $transit))->toThrow(HttpException::class);
+ $next = $service->select($buyer, $this->import, [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1,
+ 'instruction_document_id' => $correction->id]);
+ expect($next->version)->toBe(2)->and($next->snapshot['supersedes'])->toBe($record->id)
+ ->and(app(SupplyPlanning::class)->save($buyer, 'import', $transit)->state)->toBe('transit')
+ ->and(SupplyRecord::query()->where('kind', 'import_party')->count())->toBe(2)
+ ->and(DB::table('stock_movements')->count())->toBe(0);
+});
+
+test('broker selection refuses stale entity versions missing declarations and conflicts of earlier selectors', function () {
+ [$buyer, $supplier, $instructions, $data] = importDossierPartyFixture($this);
+ $service = app(ImportParties::class);
+ expect(fn () => $service->select($buyer, $this->import, [...$data, 'supplier_version' => $supplier->version + 1]))->toThrow(HttpException::class);
+ expect(fn () => $service->select($buyer, $this->import, [...$data, 'no_conflict' => false]))->toThrow(ValidationException::class);
+ $record = $service->select($buyer, $this->import, $data);
+ ConflictDeclaration::query()->create(['tenant_id' => $buyer->tenant_id, 'user_id' => $buyer->id, 'supplier_id' => $supplier->id,
+ 'has_conflict' => true, 'known_since' => today(), 'declared_at' => now(), 'reason' => 'Synthetic declared broker relationship.']);
+ $other = User::factory()->create(['tenant_id' => $buyer->tenant_id, 'department_id' => $buyer->department_id, 'purchasing_role' => PurchasingRole::Procurement]);
+ supplyGrant($other, ['procurement', 'import_prepare']);
+ $this->actingAs($other);
+ expect(fn () => $service->select($other, $this->import, [...$data, 'operation_key' => (string) Str::uuid(), 'version' => 1]))->toThrow(ValidationException::class);
+ expect(fn () => app(SupplyPlanning::class)->save($other, 'import', supplyInput(['event_date' => today()->toDateString(),
+ 'evidence' => 'Synthetic transit evidence.'], 'transit', $this->import)))->toThrow(HttpException::class);
+ $workspace = $service->workspace($other, $this->import);
+ expect($workspace['current'][0]['issues'])->not->toBeEmpty()
+ ->and(SupplyRecord::query()->where('kind', 'import_party')->count())->toBe(1)
+ ->and($record->fresh()->snapshot['supplier']['id'])->toBe($supplier->id);
+});
+
+test('a private original lost between metadata and byte reading is refused as a recoverable conflict', function () {
+ $record = app(ImportDossier::class)->record($this->f['issuer'], $this->import, $this->input, $this->file);
+ $disk = Mockery::mock(FilesystemAdapter::class);
+ $disk->shouldReceive('exists')->once()->andReturnTrue();
+ $disk->shouldReceive('size')->once()->andReturn(strlen($this->bytes));
+ $disk->shouldReceive('get')->once()->andReturnNull();
+ Storage::shouldReceive('disk')->with('local')->andReturn($disk);
+ try {
+ app(ImportEvidence::class)->bytes($record);
+ $this->fail('Missing private bytes must not be returned.');
+ } catch (HttpException $error) {
+ expect($error->getStatusCode())->toBe(409);
+ }
+});
+
+test('documentary date is preserved without inferring current validity or forbidding a future original date', function () {
+ $date = today()->addMonth()->toDateString();
+ $record = app(ImportDossier::class)->record($this->f['issuer'], $this->import, [...$this->input, 'issued_on' => $date], $this->file);
+ expect($record->data['issued_on'])->toBe($date)->and($record->state)->toBe('recorded')
+ ->and($record->snapshot['external_submission'])->toBeFalse()->and($record->snapshot['financial_effects'])->toBeFalse();
+});
+
+test('sessionless QA actor reset permits inspection without changing any restored user fields', function () {
+ app(ImportDossier::class)->record($this->f['issuer'], $this->import, $this->input, $this->file);
+ $before = hash('sha256', DB::table('users')->orderBy('id')->get()->toJson());
+ clearImportQaIdentity();
+ expect(auth()->check())->toBeFalse()->and(app(ImportCostDocumentHealth::class)->inspect()['ok'])->toBeTrue()
+ ->and(hash('sha256', DB::table('users')->orderBy('id')->get()->toJson()))->toBe($before);
+});
diff --git a/tests/Feature/ImportEstimatePlanTest.php b/tests/Feature/ImportEstimatePlanTest.php
new file mode 100644
index 0000000..4f54389
--- /dev/null
+++ b/tests/Feature/ImportEstimatePlanTest.php
@@ -0,0 +1,51 @@
+markTestSkipped('Select the authorised unpublished common source for isolated QA.');
+ }
+});
+
+/** Synthetic assumptions only; no legal rate, exemption or real transaction. */
+function importEstimateExample(): array
+{
+ return array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'not_applicable', 'basis' => 'Hipótese sintética explícita',
+ 'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS);
+}
+
+test('pre-document cost uses exact known assumptions and native goods without manufacturing documentary origins', function () {
+ $components = importEstimateExample();
+ $components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 160, 'total_minor' => 1160];
+ $goods = ['subtotal_minor' => 10000, 'tax_minor' => 1600, 'total_minor' => 11600];
+ $gross = BudgetImportEstimate::reconcile($goods, $components, true);
+ $net = BudgetImportEstimate::reconcile($goods, $components, false);
+ expect($gross['budget_amount_minor'])->toBe(12760)->and($net['budget_amount_minor'])->toBe(11000)
+ ->and($gross['additional_budget_minor'])->toBe(1160)->and($gross['goods'])->toBe($goods)
+ ->and($gross['financial_effects'])->toBeFalse()->and($gross['complete'])->toBeTrue()
+ ->and(BudgetImportEstimate::reconcile($goods, array_reverse($components), true)['fingerprint'])->toBe($gross['fingerprint']);
+ expect(BudgetImportEstimate::reconcile(array_reverse($goods, true), $components, true)['fingerprint'])->toBe($gross['fingerprint']);
+});
+
+test('unknown costs retain a partial known subtotal but prevent a determinate approval or reservation basis', function () {
+ $components = importEstimateExample();
+ $components[2]['status'] = 'unknown';
+ $plan = BudgetImportEstimate::reconcile(['subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100], $components, true);
+ expect($plan['complete'])->toBeFalse()->and($plan['budget_amount_minor'])->toBeNull()
+ ->and($plan['additional_budget_minor'])->toBeNull()->and($plan['reference_totals'])->toBeNull()
+ ->and($plan['known_total_minor'])->toBe(100)->and($plan['unknown'])->toBe(['duty']);
+});
+
+test('missing families duplicate assumptions absent money and arbitrary balancing are rejected', function (string $error) {
+ $components = importEstimateExample();
+ match ($error) {
+ 'missing' => array_pop($components),
+ 'duplicate' => $components[] = $components[0],
+ 'zero_unknown' => $components[0]['subtotal_minor'] = 0,
+ 'unbalanced' => $components[0] = [...$components[0], 'status' => 'known', 'subtotal_minor' => 100, 'tax_minor' => 2, 'total_minor' => 101],
+ 'missing_tax' => $components[0] = array_diff_key([...$components[0], 'status' => 'known', 'subtotal_minor' => 100, 'total_minor' => 100], ['tax_minor' => true]),
+ };
+ expect(fn () => BudgetImportEstimate::reconcile(['subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100], $components, true))->toThrow(BudgetFailure::class);
+})->with(['missing', 'duplicate', 'zero_unknown', 'unbalanced', 'missing_tax']);
diff --git a/tests/Feature/ImportEstimatesTest.php b/tests/Feature/ImportEstimatesTest.php
new file mode 100644
index 0000000..f5b1c43
--- /dev/null
+++ b/tests/Feature/ImportEstimatesTest.php
@@ -0,0 +1,230 @@
+markTestSkipped('Select the authorised unpublished common source for isolated QA.');
+ }
+ config(['import-estimates.qa_enabled' => true]);
+ $this->withoutVite();
+ $this->f = receiptFixture();
+ $this->actingAs($this->f['issuer']);
+ $this->draft = $this->f['r']->replicate();
+ $this->draft->fill(['number' => 'ESTIMATE-'.Str::random(12), 'status' => 'draft']);
+ $this->draft->save();
+ $item = $this->f['r']->items()->sole()->replicate();
+ $item->requisition_id = $this->draft->id;
+ $item->save();
+ $budgetAuthor = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
+ $budgetReviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
+ $this->actingAs($budgetAuthor);
+ $budgetId = app(CommonBudget::class)->for($budgetAuthor)->create(['cost_center_id' => $this->draft->cost_center_id,
+ 'year' => (int) now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true, 'reason' => 'Orçamento estritamente sintético']);
+ $this->actingAs($budgetReviewer);
+ app(CommonBudget::class)->for($budgetReviewer)->approve($budgetId);
+ $this->budget = Budget::query()->findOrFail($budgetId);
+ $this->actingAs($this->f['issuer']);
+ $this->input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'budget_id' => $this->budget->id,
+ 'reason' => 'Preparação de pressupostos estritamente sintéticos',
+ 'components' => array_map(fn ($kind) => ['key' => $kind, 'kind' => $kind, 'status' => 'unknown', 'basis' => 'Valor ainda não disponível',
+ 'subtotal_minor' => null, 'tax_minor' => null, 'total_minor' => null], BudgetImportEstimate::KINDS)];
+});
+
+test('native draft assumptions preserve unknowns originals and versions without financial or stock effects', function () {
+ $service = app(ImportEstimates::class);
+ $before = $this->draft->fresh()->getAttributes();
+ $record = $service->save($this->f['issuer'], $this->draft, $this->input);
+ expect($record->state)->toBe('incomplete')->and($record->snapshot['plan']['budget_amount_minor'])->toBeNull()
+ ->and($service->save($this->f['issuer'], $this->draft, $this->input)->id)->toBe($record->id)
+ ->and($this->draft->fresh()->getAttributes())->toBe($before)->and(DB::table('budget_entries')->count())->toBe(0);
+ $next = [...$this->input, 'operation_key' => (string) Str::uuid(), 'version' => 1];
+ foreach ($next['components'] as &$component) {
+ $component['status'] = 'not_applicable';
+ $component['basis'] = 'Hipótese sintética sem esta componente';
+ }
+ unset($component);
+ $corrected = $service->save($this->f['issuer'], $this->draft, $next);
+ expect($corrected->version)->toBe(2)->and($corrected->state)->toBe('prepared')
+ ->and($corrected->snapshot['plan']['budget_amount_minor'])->toBe(10000)
+ ->and($record->fresh()->state)->toBe('incomplete');
+ $this->get('/requisicoes/'.$this->draft->id.'/estimativa-importacao')->assertOk()
+ ->assertInertia(fn (AssertableInertia $page) => $page->component('supply/import-estimate')
+ ->where('latest.version', 2)->where('canPrepare', true)->where('nativeChanged', false));
+ expect(fn () => $service->save($this->f['issuer'], $this->draft, [...$next, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
+});
+
+test('assumptions cannot rewrite a submitted request or bypass actor and feature isolation', function () {
+ $service = app(ImportEstimates::class);
+ expect(fn () => $service->save($this->f['issuer'], $this->f['r'], $this->input))->toThrow(HttpException::class);
+ $this->actingAs($this->f['receiver']);
+ expect(fn () => $service->save($this->f['receiver'], $this->draft, $this->input))->toThrow(ModelNotFoundException::class);
+ $this->actingAs($this->f['issuer']);
+ config(['import-estimates.qa_enabled' => false]);
+ expect(fn () => $service->save($this->f['issuer'], $this->draft, $this->input))->toThrow(HttpException::class);
+});
+
+test('native submission approves the full estimate reserves goods and extras once and rejection releases both', function () {
+ (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
+ $this->f['tenant']->update(['first_limit_minor' => 10500, 'second_limit_minor' => 10800]);
+ $input = $this->input;
+ foreach ($input['components'] as &$component) {
+ $component['status'] = 'not_applicable';
+ }
+ unset($component);
+ $input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 1000, 'tax_minor' => 0, 'total_minor' => 1000];
+ $estimate = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
+ $workflow = app(RequisitionWorkflow::class);
+ $workflow->submit($this->f['issuer'], $this->draft);
+ $submitted = $this->draft->fresh();
+ expect($submitted->status)->toBe('pending')->and($submitted->total_minor)->toBe(10000)
+ ->and($submitted->approval_snapshot['approval_basis']['total_minor'])->toBe(11000)
+ ->and($submitted->steps()->orderBy('position')->pluck('role')->all())->toBe(['department_head', 'procurement', 'finance']);
+ $this->actingAs($this->f['issuer']);
+ $engine = app(CommonBudget::class)->for($this->f['issuer']);
+ expect((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(10000)
+ ->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(1000)
+ ->and($estimate->fresh()->state)->toBe('prepared');
+ $head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->draft->department_id,
+ 'purchasing_role' => PurchasingRole::DepartmentHead]);
+ $this->actingAs($head);
+ $workflow->decide($head, $submitted, 'rejected', 'Rejeição sintética para conferir a libertação');
+ expect($this->draft->fresh()->status)->toBe('rejected')->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(0)
+ ->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(0);
+});
+
+test('unknown or stale estimate prevents native submission without partial reservations or approval steps', function () {
+ app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $this->input);
+ try {
+ app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft);
+ $this->fail('Unknown costs cannot be submitted as zero.');
+ } catch (HttpException $error) {
+ expect($error->getStatusCode())->toBe(422);
+ }
+ expect($this->draft->fresh()->status)->toBe('draft')->and($this->draft->steps()->count())->toBe(0)
+ ->and(DB::table('budget_entries')->count())->toBe(0);
+ $this->draft->items()->firstOrFail()->update(['description' => 'Edição deliberada posterior']);
+ expect(fn () => app(ImportEstimates::class)->approval($this->draft->fresh()))->toThrow(HttpException::class);
+});
+
+test('identified imported articles require an estimate and insufficient extras roll back the native goods reservation', function () {
+ config(['import-tariffs.qa_enabled' => true]);
+ app(ImportTariffCodes::class)->save($this->f['issuer'], $this->draft, [
+ 'operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0,
+ 'requisition_item_id' => $this->draft->items()->sole()->id, 'reason' => 'Identificação sintética do artigo importado']);
+ expect(fn () => app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft))->toThrow(HttpException::class);
+ (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
+ $input = $this->input;
+ foreach ($input['components'] as &$component) {
+ $component['status'] = 'not_applicable';
+ }
+ unset($component);
+ $input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 200000, 'tax_minor' => 0, 'total_minor' => 200000];
+ app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
+ expect(fn () => app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft))->toThrow(ValidationException::class);
+ expect($this->draft->fresh()->status)->toBe('draft')->and($this->draft->steps()->count())->toBe(0)
+ ->and(DB::table('budget_entries')->count())->toBe(0)->and(DB::table('budget_landed_entries')->count())->toBe(0);
+});
+
+test('native independently reviewed documents reconcile an approved estimate portion and preserve the remaining orders capacity', function () {
+ config(['import-landed-costs.qa_enabled' => true]);
+ Storage::fake('local');
+ (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
+ $input = $this->input;
+ foreach ($input['components'] as &$component) {
+ $component['status'] = 'not_applicable';
+ }
+ unset($component);
+ $input['components'][0] = [...$input['components'][0], 'status' => 'known', 'subtotal_minor' => 3000, 'tax_minor' => 0, 'total_minor' => 3000];
+ $estimate = app(ImportEstimates::class)->save($this->f['issuer'], $this->draft, $input);
+ app(RequisitionWorkflow::class)->submit($this->f['issuer'], $this->draft);
+ $head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->draft->department_id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
+ $this->actingAs($head);
+ app(RequisitionWorkflow::class)->decide($head, $this->draft->fresh(), 'approved', 'Aprovação sintética do custo integral');
+ // Synthetic issued-order fixture, after actual native approval of this new source.
+ $award = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id)->replicate();
+ $quote = Quotation::query()->findOrFail($award->quotation_id)->replicate();
+ $quote->fill(['requisition_id' => $this->draft->id, 'reference' => 'ESTIMATE-QUOTE-'.Str::random(10)]);
+ $quote->save();
+ $award->fill(['requisition_id' => $this->draft->id, 'quotation_id' => $quote->id]);
+ $award->save();
+ $order = $this->f['order']->replicate();
+ $order->fill(['number' => 'ESTIMATE-ORDER-'.Str::random(10), 'requisition_id' => $this->draft->id, 'purchase_award_id' => $award->id]);
+ $order->save();
+ $line = $this->f['line']->replicate();
+ $line->purchase_order_id = $order->id;
+ $line->save();
+ supplyGrant($this->f['issuer'], ['procurement', 'import_prepare', 'requester']);
+ $this->actingAs($this->f['issuer']);
+ $import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
+ 'purchase_order_id' => $order->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic QA jurisdiction',
+ 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Explicit synthetic regime']));
+ $finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
+ $reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
+ supplyGrant($finance, ['finance']);
+ supplyGrant($reviewer, ['finance']);
+ $this->actingAs($finance);
+ $service = app(ImportLandedCosts::class);
+ $document = $service->recordDocument($finance, $import, ['operation_key' => (string) Str::uuid(), 'kind' => 'customs_assessment',
+ 'reference' => 'SYNTHETIC-ESTIMATE-ACTUAL', 'issued_on' => today()->toDateString(), 'creditor_reference' => 'Synthetic authority', 'currency' => 'MZN',
+ 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000, 'exchange_basis' => null, 'reason' => 'Documento sintético, sem execução aduaneira'],
+ UploadedFile::fake()->createWithContent('estimate-actual.pdf', "%PDF-1.4\nSynthetic QA only\n%%EOF"));
+ $selection = ['budget_id' => $this->budget->id, 'documents' => [['origin' => 'customs', 'kind' => 'customs_assessment', 'id' => $document->id]],
+ 'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', 'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000,
+ 'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000]]];
+ $prepared = $service->save($finance, $import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
+ 'action' => 'save', 'reason' => 'Preparação documental sintética', 'data' => $selection]);
+ $this->actingAs($reviewer);
+ $approved = $service->save($reviewer, $import, ['operation_key' => (string) Str::uuid(), 'record_key' => $prepared->record_key, 'version' => 1,
+ 'action' => 'approve', 'reason' => 'Conferência independente dos documentos sintéticos', 'data' => []]);
+ $this->actingAs($finance);
+ expect(fn () => $service->financial($finance, $import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve',
+ 'financial_revision' => 0, 'reason' => 'Não duplicar a reserva estimada']))->toThrow(HttpException::class);
+ $this->post('/compras/importacoes/'.$import->id.'/custos/'.$approved->id.'/orcamento?estimates_page=999999',
+ ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0, 'reason' => 'A paginação não altera a protecção financeira'])->assertStatus(409);
+ $command = ['operation_key' => (string) Str::uuid(), 'actual_operation_key' => (string) Str::uuid(), 'action' => 'reconcile_estimate',
+ 'financial_revision' => 0, 'estimate_id' => $estimate->id, 'estimate_revision' => 1, 'estimate_release_minor' => 1000,
+ 'reason' => 'Parcela sintética correspondente a esta ordem; diferença documentada de 1000 MZN centavos'];
+ $this->post('/compras/importacoes/'.$import->id.'/custos/'.$approved->id.'/orcamento', $command)->assertRedirect();
+ $result = SupplyRecord::query()->where('kind', 'import_cost_event')->where('operation_key', $command['operation_key'])->firstOrFail();
+ expect($result->snapshot['common_result']['estimate_reconciliation']['reserved_minor'])->toBe(2000)
+ ->and($result->snapshot['common_result']['additional_amount_minor'])->toBe(2000)
+ ->and($service->financial($finance, $import, $approved, $command)->id)->toBe($result->id)
+ ->and((int) DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(4000)
+ ->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('stock_movements')->count())->toBe(0);
+ $this->get('/compras/importacoes/'.$import->id.'/custos')->assertOk()->assertInertia(fn (AssertableInertia $page) => $page
+ ->where('estimateSources.data.0.reserved_minor', 2000)->where('estimateSources.data.0.revision', 2));
+ expect(fn () => $service->financial($finance, $import, $approved, [...$command, 'operation_key' => (string) Str::uuid(),
+ 'actual_operation_key' => (string) Str::uuid(), 'financial_revision' => 1]))->toThrow(HttpException::class);
+ config(['import-estimates.qa_enabled' => false]);
+ try {
+ $service->financial($finance, $import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve',
+ 'financial_revision' => 1, 'reason' => 'A capacidade desligada não permite ignorar a reserva anterior']);
+ $this->fail('The reserved estimate capability must remain available.');
+ } catch (HttpException $error) {
+ expect($error->getStatusCode())->toBe(503);
+ }
+});
diff --git a/tests/Feature/ProcurementPayableInsightsTest.php b/tests/Feature/ProcurementPayableInsightsTest.php
index 4600236..a410f57 100644
--- a/tests/Feature/ProcurementPayableInsightsTest.php
+++ b/tests/Feature/ProcurementPayableInsightsTest.php
@@ -3,6 +3,7 @@
use App\Models\Requisition;
use App\Services\ExternalPaymentWorkflow;
use App\Services\ProcurementPayableInsights;
+use App\Services\ProcurementPaymentInsights;
use App\Services\SupplierPayables;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -99,6 +100,45 @@ test('native imported history is counted once and pending payments do not reduce
expect($result['coverage']['recognised'])->toBe(1)->and($result['currencies'][0]['principal_minor'])->toBe('6000')
->and($result['currencies'][0]['confirmed_payments_minor'])->toBe('3000')->and($result['currencies'][0]['allocated_payments_minor'])->toBe('0')
->and($result['currencies'][0]['balance_minor'])->toBe('3000');
+ $confirmed = app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->visibleTo($f['validator']), today()->format('Y-m-d'), today()->format('Y-m-d'));
+ expect($confirmed['coverage']['confirmed_payments'])->toBe(1)
+ ->and($confirmed['currencies'])->toBe([['currency' => 'MZN', 'count' => 1, 'amount_minor' => '3000']]);
+ $outside = app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->visibleTo($f['validator']), today()->subDay()->format('Y-m-d'), today()->subDay()->format('Y-m-d'));
+ expect($outside['currencies'])->toBe([]);
+});
+
+test('payment period follows confirmation instead of the original payment or requisition date and reports broken evidence', function () {
+ $f = paymentFixture();
+ foreach (['view', 'prepare', 'validate'] as $action) {
+ DB::table('pa_access')->insert(['tenant_id' => $f['validator']->tenant_id, 'company_id' => 0, 'unit_id' => 0,
+ 'user_id' => $f['validator']->id, 'person' => 'period-person', 'action' => $action]);
+ }
+ $this->actingAs($f['author']);
+ $payment = app(ExternalPaymentWorkflow::class)->register($f['author'], $f['invoice'], $f['payment_data']);
+ $this->travel(1)->days();
+ $this->actingAs($f['validator']);
+ app(ExternalPaymentWorkflow::class)->review($f['validator'], $payment, 'confirmed', 'Conferência sintética independente');
+ $query = Requisition::query()->visibleTo($f['validator']);
+ $service = app(ProcurementPaymentInsights::class);
+ expect($service->build($f['validator'], clone $query, today()->format('Y-m-d'), today()->format('Y-m-d'))['currencies'][0]['amount_minor'])->toBe('4000')
+ ->and($service->build($f['validator'], clone $query, today()->subDay()->format('Y-m-d'), today()->subDay()->format('Y-m-d'))['currencies'])->toBe([]);
+ if (DB::getDriverName() === 'pgsql') {
+ if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
+ throw new LogicException('Commit only the disposable report test fixture.');
+ }
+ DB::commit();
+ $this->committedInsightsFixture = true;
+ }
+ $this->get('/relatorios?from='.today()->format('Y-m-d').'&to='.today()->format('Y-m-d'))->assertOk()
+ ->assertInertia(fn (Assert $page) => $page->where('records.total', 0)
+ ->where('paymentInsights.coverage.confirmed_payments', 1)->where('paymentInsights.currencies.0.amount_minor', '4000'));
+ $csv = $this->get('/relatorios/despesa.csv?from='.today()->format('Y-m-d').'&to='.today()->format('Y-m-d'))->assertOk()->assertDownload();
+ expect($csv->streamedContent())->toContain('MZN;1;4000')->not->toContain('bank_snapshot')->not->toContain('account_identifier');
+ $this->actingAs($f['issuer'])->get('/relatorios/despesa.csv')->assertForbidden();
+ $this->actingAs($f['validator']);
+ DB::table('external_payments')->where('id', $payment->id)->update(['reviewed_at' => null]);
+ $broken = $service->build($f['validator'], clone $query, null, null);
+ expect($broken['coverage']['indeterminate'])->toBe(1)->and($broken['currencies'])->toBe([]);
});
test('read composition rejects commands and revalidates withdrawn native financial access', function () {
diff --git a/tests/Feature/PurchaseAwardOrderTest.php b/tests/Feature/PurchaseAwardOrderTest.php
index 3382e99..f7af465 100644
--- a/tests/Feature/PurchaseAwardOrderTest.php
+++ b/tests/Feature/PurchaseAwardOrderTest.php
@@ -41,6 +41,7 @@ use App\Services\ImportTariffCodes;
use App\Services\InvoiceWorkflow;
use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow;
+use App\Services\OrderPartsAmendments;
use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementReviewCsv;
@@ -1490,7 +1491,7 @@ test('optional partial-order preparation consolidates two independently approved
});
/** Native adjudication/approval fixture; requisition approval itself is the existing synthetic source. */
-function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quotation $quote = null): PurchaseAward
+function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quotation $quote = null, ?int $secondCentre = null): PurchaseAward
{
$request ??= $test->r;
$quote ??= $test->quotes[0];
@@ -1508,15 +1509,30 @@ function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quot
app(CommonBudget::class)->for($test->admin)->approve($id);
}
$host = app(RequisitionBudgetDistributions::class);
- $allocations = $quote->items()->get()->map(fn ($line) => ['allocation_key' => (string) Str::uuid(),
- 'line_id' => $line->requisition_item_id, 'centre_id' => $request->cost_center_id,
+ $allocations = $request->items()->get()->map(fn ($line) => ['allocation_key' => (string) Str::uuid(),
+ 'line_id' => $line->id, 'centre_id' => $request->cost_center_id,
'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor])->all();
+ if ($secondCentre !== null) {
+ if (count($allocations) !== 1 || $allocations[0]['subtotal_minor'] !== 10000 || $allocations[0]['total_minor'] !== 10000) {
+ throw new LogicException('Explicit two-centre fixture requires a single synthetic 100 MZN line.');
+ }
+ $allocations[0]['subtotal_minor'] = $allocations[0]['total_minor'] = 5000;
+ $allocations[] = [...$allocations[0], 'allocation_key' => (string) Str::uuid(), 'centre_id' => $secondCentre];
+ }
$request->forceFill(['budget_distribution_preparation' => ['allocations' => $allocations,
'source_revision' => $host->revision($request, $host->requestLines($request)), 'prepared_by' => $test->owner->id,
'reason' => 'Explicit synthetic source allocation.']])->save();
$test->actingAs($test->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($test->finance, $request, 'reserve', $request->total_minor, $request->subtotal_minor));
$test->actingAs($test->buyer);
+ if ($quote->currency !== 'MZN') {
+ if (count($allocations) !== 1) {
+ throw new LogicException('Foreign synthetic fixture requires explicit single-line allocation.');
+ }
+ $reference = app(QuotationExchange::class)->amounts($quote);
+ $allocations[0]['subtotal_minor'] = $reference['subtotal_minor'];
+ $allocations[0]['total_minor'] = $reference['total_minor'];
+ }
$data = [...$test->selection, 'quotation_id' => $quote->id, 'reason' => 'Explicit native award distribution.',
'budget_distribution_preparation' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'],
'subtotal' => (string) BigDecimal::of($row['subtotal_minor'])->dividedBy(100, 2),
@@ -1535,13 +1551,186 @@ function nativeOrderPartsInput(object $test, PurchaseAward $award, string $quant
$prepared = app(OrderPartsPreparation::class)->prepare($test->buyer, $input);
$distribution = DB::table('budget_distributions')->where('requisition_id', $award->requisition_id)->first();
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
- $line = $prepared['sources'][0]['items'][0];
+ $line = $prepared['sources'][0]['reference_amounts'] ?? $prepared['sources'][0]['items'][0];
return [...$input, 'order_key' => (string) Str::uuid(), 'operation_key' => (string) Str::uuid(), 'fingerprint' => $prepared['fingerprint'],
'budget_sources' => [['origin' => $award->requisition_id, 'version' => $version, 'plan_hash' => $snapshot['plan_hash'],
'allocations' => [['allocation_key' => $snapshot['allocations'][0]['allocation_key'], 'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]]]]];
}
+test('native partial-order foreign receipts and invoices preserve origin rates and cumulative remainders', function () {
+ if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
+ $this->markTestSkipped('Explicit unpublished common source required.');
+ }
+ $this->actingAs($this->finance);
+ $exchange = app(QuotationExchange::class);
+ $exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '1.5',
+ 'quoted_on' => today()->toDateString(), 'source' => 'Synthetic origin-specific FX, not a market rate.']);
+ $quote = $this->quotes[0];
+ $quote->items()->update(['unit_price_minor' => 223, 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223]);
+ $quote->update(['currency' => 'USD', 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223,
+ 'exchange_basis' => $exchange->basis($this->r, 'USD')]);
+ $award = nativeOrderPartsAward($this);
+ $flow = app(OrderPartsWorkflow::class);
+ $input = nativeOrderPartsInput($this, $award, '0.400', 0);
+ $first = $flow->issue($this->buyer, $input);
+ expect($first->currency)->toBe('USD')->and($first->total_minor)->toBe(89)
+ ->and($exchange->orderAmounts($first, 89, 0)['total_minor'])->toBe(134)
+ ->and($flow->issue($this->buyer, $input)->id)->toBe($first->id);
+ $this->withoutVite();
+ $this->get('/ordens/'.$first->id.'/imprimir')->assertOk()->assertSee('1.5000000000')->assertSee('Synthetic origin-specific FX');
+ $second = $flow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 1));
+ expect($second->total_minor)->toBe(134)->and($exchange->orderAmounts($second, 134, 0)['total_minor'])->toBe(201)
+ ->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(335);
+ $receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
+ $reviewer = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
+ $this->actingAs($receiver);
+ $warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-PART', 'name' => 'Synthetic warehouse']);
+ $stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-PART', 'name' => 'Synthetic material', 'unit' => 'un']);
+ $line = $first->items()->sole();
+ app(ReceiptWorkflow::class)->confirm($receiver, $first, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'FX-PART',
+ 'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
+ 'items' => [['purchase_order_item_id' => $line->id, 'received_quantity' => '0.400', 'accepted_quantity' => '0.400',
+ 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]]);
+ $key = $input['budget_sources'][0]['allocations'][0]['allocation_key'];
+ foreach ([['0.45', '0.68'], ['0.44', '0.66']] as $index => [$documentary, $reference]) {
+ $this->actingAs($this->finance);
+ $data = ['number' => 'FX-PART-'.$index, 'issued_on' => today()->toDateString(), 'subtotal' => $documentary,
+ 'tax' => '0.00', 'total' => $documentary, 'items' => [['purchase_order_item_id' => $line->id, 'quantity' => '0.200']],
+ 'reason' => 'Explicit Finance reference for a synthetic foreign partial invoice.',
+ 'order_part_allocations' => [['origin' => $this->r->id, 'allocation_key' => $key, 'subtotal' => $reference, 'total' => $reference]]];
+ $bad = $data;
+ $bad['order_part_allocations'][0]['subtotal'] = $documentary;
+ $bad['order_part_allocations'][0]['total'] = $documentary;
+ expect(fn () => app(InvoiceWorkflow::class)->register($this->finance, $first, $bad))->toThrow(ValidationException::class);
+ $invoice = app(InvoiceWorkflow::class)->register($this->finance, $first, $data);
+ $this->actingAs($reviewer);
+ app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
+ app(InvoiceWorkflow::class)->validate($reviewer, $invoice->fresh());
+ }
+ expect(Invoice::query()->count())->toBe(2)->and(StockMovement::query()->count())->toBe(1)
+ ->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(134)
+ ->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(201)
+ ->and($quote->fresh()->exchange_basis['rate'])->toBe('1.5000000000');
+});
+
+test('native consolidated order preserves two different foreign origin rates in the document and reference', function () {
+ if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
+ $this->markTestSkipped('Explicit unpublished common source required.');
+ }
+ [$request, $quotes] = secondNativeOrderPartsOrigin($this);
+ foreach ([[$this->r, $this->quotes[0], '1.5'], [$request, $quotes[0], '2']] as [$origin, $quote, $rate]) {
+ $this->actingAs($this->finance);
+ $exchange = app(QuotationExchange::class);
+ $exchange->record($this->finance, $origin, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => $rate,
+ 'quoted_on' => today()->toDateString(), 'source' => 'Synthetic separate origin rate '.$rate]);
+ $quote->items()->update(['unit_price_minor' => 100, 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100]);
+ $quote->update(['currency' => 'USD', 'subtotal_minor' => 100, 'tax_minor' => 0, 'total_minor' => 100,
+ 'exchange_basis' => $exchange->basis($origin, 'USD')]);
+ }
+ $first = nativeOrderPartsAward($this);
+ $second = nativeOrderPartsAward($this, $request, $quotes[0]);
+ $a = nativeOrderPartsInput($this, $first, '1.000', 0);
+ $b = nativeOrderPartsInput($this, $second, '1.000', 0);
+ $sources = [...$a['sources'], ...$b['sources']];
+ $flow = app(OrderPartsWorkflow::class);
+ $preview = $flow->preview($this->buyer, ['sources' => $sources]);
+ expect($preview['can_issue'])->toBeTrue();
+ $order = $flow->issue($this->buyer, [...$a, 'sources' => $sources, 'fingerprint' => $preview['prepared']['fingerprint'],
+ 'budget_sources' => [...$a['budget_sources'], ...$b['budget_sources']]]);
+ expect($order->total_minor)->toBe(200)->and($order->snapshot['exchange_basis'])->toBeNull()
+ ->and($exchange->orderAmounts($order, 200, 0)['total_minor'])->toBe(350)
+ ->and(array_column(array_column($order->snapshot['exchange_sources'], 'exchange_basis'), 'rate'))->toBe(['1.5000000000', '2.0000000000']);
+ $this->withoutVite();
+ $this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1.5000000000')->assertSee('2.0000000000');
+ expect(fn () => $exchange->orderAmounts($order, 100, 0))->toThrow(HttpException::class);
+ $receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
+ $reviewer = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
+ $this->actingAs($receiver);
+ $warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-CONSOL', 'name' => 'Synthetic warehouse']);
+ $stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'FX-CONSOL', 'name' => 'Synthetic material', 'unit' => 'un']);
+ $lines = $order->items()->orderBy('id')->get();
+ app(ReceiptWorkflow::class)->confirm($receiver, $order, ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'FX-CONSOL',
+ 'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
+ 'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'received_quantity' => '1.000',
+ 'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id])->all()]);
+ $this->actingAs($this->finance);
+ $invoice = app(InvoiceWorkflow::class)->register($this->finance, $order, ['number' => 'FX-CONSOL', 'issued_on' => today()->toDateString(),
+ 'subtotal' => '2.00', 'tax' => '0.00', 'total' => '2.00', 'reason' => 'Explicit Finance allocation preserving both source rates.',
+ 'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'quantity' => '1.000'])->all(),
+ 'order_part_allocations' => [
+ ['origin' => $first->requisition_id, 'allocation_key' => $a['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '1.50', 'total' => '1.50'],
+ ['origin' => $second->requisition_id, 'allocation_key' => $b['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '2.00', 'total' => '2.00']]]);
+ $this->actingAs($reviewer);
+ app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
+ app(InvoiceWorkflow::class)->validate($reviewer, $invoice->fresh());
+ expect($invoice->fresh()->status)->toBe('validated')->and($invoice->fresh()->total_minor)->toBe(200)
+ ->and(Invoice::query()->count())->toBe(1)->and(StockMovement::query()->count())->toBe(2)
+ ->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(350)
+ ->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0);
+});
+
+test('native partial-order postgres history refuses source line and header rewriting after issuance', function () {
+ if (DB::getDriverName() !== 'pgsql' || ! method_exists(BudgetControl::class, 'commitOrderParts')) {
+ $this->markTestSkipped('PostgreSQL isolated optional contract required.');
+ }
+ $award = nativeOrderPartsAward($this);
+ $order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
+ $before = [$order->toArray(), $order->items()->get()->toArray(), DB::table('purchase_order_sources')->get()->toArray()];
+ foreach ([
+ fn () => DB::table('purchase_orders')->where('id', $order->id)->update(['total_minor' => 1]),
+ fn () => DB::table('purchase_order_items')->where('purchase_order_id', $order->id)->update(['quantity_offset_milli' => 1]),
+ fn () => DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->update(['snapshot' => '{}']),
+ fn () => DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->delete(),
+ ] as $mutation) {
+ expect(fn () => DB::transaction($mutation))->toThrow(QueryException::class);
+ }
+ expect([$order->fresh()->toArray(), $order->items()->get()->toArray(), DB::table('purchase_order_sources')->get()->toArray()])->toEqual($before);
+});
+
+test('native partial-order Finance amendment exposes a recoverable form and preserves original order and unissued reserve', function () {
+ if (! method_exists(BudgetControl::class, 'amendOrderParts')) {
+ $this->markTestSkipped('Explicit unpublished common source required.');
+ }
+ $centre = CostCenter::query()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id,
+ 'code' => 'NATIVE-AMEND', 'name' => 'Synthetic second centre']);
+ $this->actingAs($this->finance);
+ $budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $centre->id, 'year' => (int) now()->year,
+ 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Synthetic native amendment capacity.']);
+ $this->actingAs($this->admin);
+ app(CommonBudget::class)->for($this->admin)->approve($budget);
+ $award = nativeOrderPartsAward($this, secondCentre: $centre->id);
+ $input = nativeOrderPartsInput($this, $award, '0.400', 0);
+ $distribution = DB::table('budget_distributions')->where('requisition_id', $this->r->id)->first();
+ $plan = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
+ $input['budget_sources'][0]['allocations'] = array_map(fn ($row) => ['allocation_key' => $row['allocation_key'],
+ 'subtotal_minor' => 2000, 'total_minor' => 2000], $plan['allocations']);
+ $order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
+ $original = $order->toArray();
+ $this->withoutVite();
+ $this->get('/ordens/'.$order->id.'/reafectacao')->assertForbidden();
+ $this->actingAs($this->finance);
+ $this->get('/ordens/'.$order->id)->assertOk()->assertViewHas('page', fn ($page) => $page['props']['canAmendOrderParts'] === true);
+ $this->get('/ordens/'.$order->id.'/reafectacao')->assertOk()->assertViewHas('page', fn ($page) => $page['component'] === 'purchases/order-parts-amendment' && $page['encryptHistory'] === true);
+ $service = app(OrderPartsAmendments::class);
+ $sources = $service->sources($this->finance, $order);
+ $data = ['operation_key' => (string) Str::uuid(), 'reason' => 'Explicit native independent Finance allocation.',
+ 'sources' => array_map(fn ($source) => [...$source, 'allocations' => array_map(fn ($row, $index) => [
+ 'allocation_key' => $row['allocation_key'], 'subtotal' => $index === 0 ? '10.00' : '30.00',
+ 'total' => $index === 0 ? '10.00' : '30.00'], $source['allocations'], array_keys($source['allocations']))], $sources)];
+ $this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertRedirect('/ordens/'.$order->id);
+ $this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertRedirect('/ordens/'.$order->id);
+ expect($order->fresh()->toArray())->toEqual($original)
+ ->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
+ ->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000)
+ ->and(DB::table('budget_order_commands')->where('kind', 'amend')->count())->toBe(1)
+ ->and(array_column($service->sources($this->finance, $order)[0]['allocations'], 'total'))->toBe(['10.00', '30.00']);
+ $this->get('/ordens/'.$order->id.'/reafectacao')->assertOk()->assertViewHas('page', fn ($page) => count($page['props']['history']) === 1);
+ $data['operation_key'] = (string) Str::uuid();
+ $data['reason'] = 'A different amendment cannot reuse a stale source version.';
+ $this->post('/ordens/'.$order->id.'/reafectacao', $data)->assertConflict();
+});
+
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
@@ -1812,3 +2001,48 @@ test('native explicit adoption keeps the old reserve unchanged and supports repl
expect(DB::table('budget_order_commands')->where('kind', 'adopt')->count())->toBe(1)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000);
});
+
+test('native explicit adoption of a foreign legacy award requires exact reference lines and preserves its original reserve history', function () {
+ if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
+ $this->markTestSkipped('Explicit unpublished common source required.');
+ }
+ budgetDistributionFixtureSchema();
+ (require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
+ (require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
+ config(['order-parts.qa_enabled' => true, 'budget-distributions.qa_enabled' => true]);
+ $this->actingAs($this->finance);
+ $id = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->r->cost_center_id, 'year' => (int) now()->year,
+ 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Synthetic foreign legacy reserve.']);
+ $this->actingAs($this->admin);
+ app(CommonBudget::class)->for($this->admin)->approve($id);
+ $this->actingAs($this->finance);
+ DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
+ $exchange = app(QuotationExchange::class);
+ $exchange->record($this->finance, $this->r, ['operation_id' => (string) Str::uuid(), 'currency' => 'USD', 'rate' => '1.5',
+ 'quoted_on' => today()->toDateString(), 'source' => 'Synthetic explicit legacy origin rate.']);
+ $quote = $this->quotes[0];
+ $quote->items()->update(['unit_price_minor' => 223, 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223]);
+ $quote->update(['currency' => 'USD', 'subtotal_minor' => 223, 'tax_minor' => 0, 'total_minor' => 223,
+ 'exchange_basis' => $exchange->basis($this->r, 'USD')]);
+ $award = selectPurchaseAward($this);
+ approvePurchaseAward($this, $award);
+ $old = DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->get()->toArray();
+ $this->actingAs($this->buyer);
+ $this->withoutVite();
+ $operation = (string) Str::uuid();
+ $url = '/adjudicacoes/'.$award->id.'/parcelas/adoptar';
+ $this->post($url, ['operation_key' => $operation])->assertSessionHasErrors('reference_lines');
+ $data = ['operation_key' => $operation, 'reference_lines' => [['line_id' => $this->item->id, 'subtotal' => '3.35', 'total' => '3.35']]];
+ $bad = $data;
+ $bad['reference_lines'][0]['total'] = '3.34';
+ $this->post($url, $bad)->assertSessionHasErrors('reference_lines');
+ expect(DB::table('budget_order_commands')->count())->toBe(0);
+ $this->post($url, $data)->assertRedirect('/ordens/preparar');
+ $order = app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
+ $this->post($url, $data)->assertRedirect('/ordens/preparar');
+ expect(DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->limit(count($old))->get()->toArray())->toEqual($old)
+ ->and($order->total_minor)->toBe(89)->and($order->snapshot['reference_amounts']['total_minor'])->toBe(134)
+ ->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(201)
+ ->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(134)
+ ->and(DB::table('budget_order_commands')->where('kind', 'adopt')->count())->toBe(1);
+});
diff --git a/tests/Support/ImportQaIdentity.php b/tests/Support/ImportQaIdentity.php
new file mode 100644
index 0000000..188b70a
--- /dev/null
+++ b/tests/Support/ImportQaIdentity.php
@@ -0,0 +1,18 @@
+getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
+ || ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
+ if (! app()->environment('testing') || ! app()->runningInConsole() || ! $isolated || request()->hasSession()) {
+ throw new LogicException('Only a sessionless disposable CLI fixture actor may be cleared this way.');
+ }
+ auth()->forgetGuards();
+ if (auth()->check()) {
+ throw new LogicException('The synthetic inspection still has an authenticated actor.');
+ }
+}
diff --git a/tests/Support/LandedQaReceipts.php b/tests/Support/LandedQaReceipts.php
index 5f597a5..9c1ece9 100644
--- a/tests/Support/LandedQaReceipts.php
+++ b/tests/Support/LandedQaReceipts.php
@@ -27,22 +27,42 @@ function landedQaReceiptsVerified(array $command, string $output): bool
if ($mode === 'migrate') {
return $contains(fn ($row) => ($row['isolated_schema_prepared'] ?? false) === true);
}
- if ($mode === 'race') {
+ if (in_array($mode, ['race', 'race-estimate', 'race-estimate-reconcile'], true)) {
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] 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]['commands'] ?? 0) !== 1 || ($matches[0]['audits'] ?? 0) !== 1
+ || ($matches[0]['commands'] ?? 0) !== ($mode === 'race-estimate-reconcile' ? 3 : 1) || ($matches[0]['audits'] ?? 0) !== 1
+ || ($mode === 'race-estimate' && (($matches[0]['estimate'] ?? false) !== true || ($matches[0]['reserved_minor'] ?? null) !== 2000))
+ || ($mode === 'race-estimate-reconcile' && (($matches[0]['reconciliation'] ?? false) !== true || ($matches[0]['reserved_minor'] ?? null) !== 3000))
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
return false;
}
}
- return $contains(fn ($row) => ($row['old_runtime_rejected_before_balance'] ?? false) === true && ($row['status'] ?? 0) === 503);
+ return $contains(fn ($row) => ($row['old_runtime_rejected_before_balance'] ?? false) === true && ($row['status'] ?? 0) === 503)
+ && (! 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 ($mode === 'landed-costs') {
- return $contains(fn ($row) => ($row['post_extension_restore_all_tables_equal'] ?? false) === true
+ if (in_array($mode, ['race-dossier', 'race-party'], 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]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
+ return false;
+ }
+ }
+
+ 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))
+ && $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) === 2 && ($row['source_loss_detected'] ?? false) === true
+ && $contains(fn ($row) => ($row['private_original_versions_restored'] ?? 0) === 6 && ($row['typed_dossier_versions_restored'] ?? 0) === 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);
}
diff --git a/tests/Unit/LandedQaReceiptsTest.php b/tests/Unit/LandedQaReceiptsTest.php
index 5c70b96..bfc9dbd 100644
--- a/tests/Unit/LandedQaReceiptsTest.php
+++ b/tests/Unit/LandedQaReceiptsTest.php
@@ -2,6 +2,33 @@
require_once __DIR__.'/../Support/LandedQaReceipts.php';
+test('estimate contention receipts require all native uniqueness races and explicit estimate effects', function () {
+ $command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-estimate'];
+ $rows = [['old_runtime_rejected_before_balance' => true, 'old_estimate_runtime_rejected' => true,
+ 'runtime_landed_version' => 'COMMON-BUDGET-LANDED-COST-QA-v2', 'status' => 503]];
+ foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] as $scenario) {
+ $rows[] = ['scenario' => $scenario, 'estimate' => true, 'statuses' => $scenario === 'same_operation' ? [200, 200] : [200, 409],
+ 'blocked_writers_observed' => 2, 'commands' => 1, 'audits' => 1, 'reserved_minor' => 2000];
+ }
+ $encode = fn ($records) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $records));
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeTrue();
+ $reconciliation = $rows;
+ foreach ($reconciliation as &$row) {
+ if (isset($row['scenario'])) {
+ $row['reconciliation'] = true;
+ $row['commands'] = 3;
+ $row['reserved_minor'] = 3000;
+ }
+ }
+ unset($row);
+ $reconcileCommand = [...array_slice($command, 0, 3), 'race-estimate-reconcile'];
+ expect(landedQaReceiptsVerified($reconcileCommand, $encode($reconciliation)))->toBeTrue();
+ $reconciliation[1]['reserved_minor'] = 2000;
+ expect(landedQaReceiptsVerified($reconcileCommand, $encode($reconciliation)))->toBeFalse();
+ unset($rows[2]['estimate']);
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
+});
+
test('separate Pest kernels cannot reuse one disposable database with persistent migration functions', function () {
$pest = ['php', 'vendor/bin/pest', 'tests/Feature/ImportTariffCodesTest.php'];
expect(landedQaCommandIsolationVerified([$pest]))->toBeTrue();
@@ -38,8 +65,42 @@ test('restore completion requires the restored replay original snapshot and data
expect(landedQaReceiptsVerified($command, $proof))->toBeFalse();
$databaseOnly = $proof."\n".json_encode(['isolated_restore_removed' => true], JSON_THROW_ON_ERROR);
expect(landedQaReceiptsVerified($command, $databaseOnly))->toBeFalse();
- $privateFiles = ['private_original_versions_restored' => 2, 'source_loss_detected' => true,
+ $privateFiles = ['private_original_versions_restored' => 6, 'typed_dossier_versions_restored' => 4, 'selected_party_versions_restored' => 2, 'source_loss_detected' => true,
'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true];
expect(landedQaReceiptsVerified($command, $databaseOnly."\n".json_encode($privateFiles, JSON_THROW_ON_ERROR)))->toBeTrue();
+ $estimateCommand = [...array_slice($command, 0, 3), 'import-estimates'];
+ $existingRecovery = $databaseOnly."\n".json_encode($privateFiles, JSON_THROW_ON_ERROR);
+ expect(landedQaReceiptsVerified($estimateCommand, $existingRecovery))->toBeFalse();
+ expect(landedQaReceiptsVerified($estimateCommand, $existingRecovery."\n".json_encode([
+ 'estimate_source_remainder_restored' => 1000, 'estimate_original_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();
+ $missingParty = $privateFiles;
+ unset($missingParty['selected_party_versions_restored']);
+ expect(landedQaReceiptsVerified($command, $databaseOnly."\n".json_encode($missingParty, JSON_THROW_ON_ERROR)))->toBeFalse();
expect(landedQaReceiptsVerified(['php', 'vendor/bin/pest', '--compact'], '{"tool":"pest","result":"passed","tests":1,"passed":0,"skipped":1}'))->toBeFalse();
});
+
+test('dossier contention requires both races one original and verified bytes', function () {
+ $command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-dossier'];
+ $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();
+ expect(landedQaReceiptsVerified($command, $encode([$rows[0]])))->toBeFalse();
+ $rows[1]['files_created'] = 2;
+ expect(landedQaReceiptsVerified($command, $encode($rows)))->toBeFalse();
+ $partyCommand = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-party'];
+ foreach ($rows as &$row) {
+ $row['files_created'] = 0;
+ }
+ unset($row);
+ expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeTrue();
+ $rows[1]['files_created'] = 1;
+ expect(landedQaReceiptsVerified($partyCommand, $encode($rows)))->toBeFalse();
+});
diff --git a/tests/Unit/OrderPartsReferenceTest.php b/tests/Unit/OrderPartsReferenceTest.php
new file mode 100644
index 0000000..29504d3
--- /dev/null
+++ b/tests/Unit/OrderPartsReferenceTest.php
@@ -0,0 +1,32 @@
+toBe(['subtotal_minor' => 2, 'tax_minor' => 2, 'total_minor' => 4])
+ ->and($second)->toBe(['subtotal_minor' => 1, 'tax_minor' => 1, 'total_minor' => 2])
+ ->and($first['total_minor'] + $second['total_minor'])->toBe(6);
+});
+
+test('consolidation preserves separate origin rates instead of averaging them', function () {
+ $a = OrderPartsReference::portion(0, 0, 100, 16, '63.25');
+ $b = OrderPartsReference::portion(0, 0, 200, 32, '64.75');
+ expect($a)->toBe(['subtotal_minor' => 6325, 'tax_minor' => 1012, 'total_minor' => 7337])
+ ->and($b)->toBe(['subtotal_minor' => 12950, 'tax_minor' => 2072, 'total_minor' => 15022])
+ ->and($a['total_minor'] + $b['total_minor'])->toBe(22359);
+});
+
+test('partial invoices within a partial order preserve the source offset', function () {
+ $order = OrderPartsReference::portion(1, 1, 3, 2, '1.5');
+ $first = OrderPartsReference::portion(1, 1, 1, 1, '1.5');
+ $second = OrderPartsReference::portion(2, 2, 2, 1, '1.5');
+ foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
+ expect($first[$field] + $second[$field])->toBe($order[$field]);
+ }
+});
+
+test('invalid reference bases are refused before arithmetic', function (int $before, int $net, string $rate) {
+ expect(fn () => OrderPartsReference::portion($before, 0, $net, 0, $rate))->toThrow(InvalidArgumentException::class);
+})->with([[-1, 1, '1'], [0, -1, '1'], [PHP_INT_MAX, 1, '1'], [0, 1, '0'], [0, 1, '-1'], [0, 100000000000000, '2']]);
diff --git a/tests/frontend/import-dossier.test.tsx b/tests/frontend/import-dossier.test.tsx
new file mode 100644
index 0000000..5dfb49b
--- /dev/null
+++ b/tests/frontend/import-dossier.test.tsx
@@ -0,0 +1,87 @@
+import { App } from '@inertiajs/react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { expect, test } from 'vitest';
+import Dossier from '@/pages/supply/import-dossier';
+
+function renderDossier(canWrite: boolean) {
+ const original = {
+ id: 1,
+ record_key: 'synthetic-key',
+ version: 1,
+ created_at: '2026-11-27',
+ created_by: 3,
+ current: false,
+ supersedes: null,
+ sha256: 'a'.repeat(64),
+ reason: 'Original synthetic document.',
+ data: {
+ type: 'packing_list',
+ reference: '',
+ issuer_reference: 'Synthetic issuer',
+ issued_on: null,
+ notes: null,
+ },
+ };
+ return renderToStaticMarkup(
+ ,
+ );
+}
+
+test('dossier reader retains version downloads and context without advertising write authority', () => {
+ const html = renderDossier(false);
+ expect(html).toContain('Dossiê de importação');
+ expect(html).toContain('/compras/importacoes/4/documentos/1');
+ expect(html).toContain('/compras/importacoes/4/documentos/2');
+ expect(html).toContain('Histórica');
+ expect(html).not.toContain(
+ 'Guardar documento privado',
+ 'Preparar correcção',
+ );
+ expect(html).toContain('<script>private reference</script>');
+ expect(html).not.toContain('',
+ nuit: '123456789',
+ version: 1,
+ },
+ instructions: { data: { reference: 'INSTRUCTIONS-QA' } },
+ },
+ reason: 'Explicit synthetic selection.',
+ issues: [
+ 'As instruções escritas têm uma versão diferente; confira a selecção.',
+ ],
+ };
+ const workspace: ImportPartyWorkspace = {
+ roles: { broker: 'Despachante aduaneiro', forwarder: 'Transitário' },
+ canSelect,
+ search: '',
+ current: [selected],
+ history: { data: [selected], prev_page_url: null, next_page_url: null },
+ suppliers: {
+ data: [{ id: 3, name: 'Broker QA', nuit: '123456789', version: 1 }],
+ prev_page_url: null,
+ next_page_url: null,
+ },
+ instructions: {
+ data: [
+ {
+ id: 4,
+ version: 1,
+ data: {
+ reference: 'INSTRUCTIONS-QA',
+ issuer_reference: 'QA buyer',
+ },
+ },
+ ],
+ prev_page_url: null,
+ next_page_url: null,
+ },
+ };
+ return renderToStaticMarkup(
+ ,
+ );
+}
+
+test('party reader sees preserved selection instructions and pending issues without selection commands', () => {
+ const html = renderParties(false);
+ expect(html).toContain('INSTRUCTIONS-QA');
+ expect(html).toContain('uma versão diferente');
+ expect(html).toContain('/compras/importacoes/5/documentos/4');
+ expect(html).not.toContain('Confirmar entidade e instruções');
+ expect(html).toContain('<script>Broker QA</script>');
+ expect(html).not.toContain('