commit melhorias compras6
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-23 06:37:16 +02:00
parent db1615fac1
commit dc73540558
73 changed files with 7539 additions and 175 deletions
+473
View File
@@ -0,0 +1,473 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\SupplyRecord;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetLandedCostPlan;
/** Versioned documentary cost preparation. Financial effects remain in the common writer. */
final class ImportLandedCosts
{
public function ready(): bool
{
$db = DB::connection();
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
return config('import-landed-costs.qa_enabled') === true && app()->environment('testing') && $isolated
&& class_exists(BudgetLandedCostPlan::class);
}
public function financialReady(): bool
{
$runtime = new \ReflectionClass(BudgetControl::class);
return $this->ready() && Schema::hasTable('budget_landed_commands') && Schema::hasTable('budget_landed_entries')
&& Schema::hasColumn('budget_landed_entries', 'source_snapshot')
&& $runtime->hasConstant('LANDED_COSTS_VERSION') && $runtime->getConstant('LANDED_COSTS_VERSION') === CommonBudget::LANDED_COSTS_CONTRACT
&& $runtime->hasMethod('reserveLandedCosts') && $runtime->hasMethod('transitionLandedCosts') && $runtime->hasMethod('amendLandedCosts');
}
/** @return array<string,mixed> */
public function workspace(User $actor, SupplyRecord $import, string $search = ''): array
{
abort_unless($this->ready(), 503);
return DB::transaction(function () use ($actor, $import, $search): array {
[$actor, $current, $order] = $this->context($actor, $import);
$invoices = Invoice::query()->where('status', 'validated')->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))
->when($search !== '', fn ($query) => $query->where('number', 'like', '%'.addcslashes($search, '%_\\').'%'))
->latest('id')->paginate(20, ['id', 'number', 'supplier_id', 'purchase_order_id', 'subtotal_minor', 'tax_minor', 'total_minor'], 'invoices_page')->withQueryString();
$invoices->through(fn (Invoice $invoice) => [...$invoice->only(['id', 'number', 'purchase_order_id', 'total_minor']),
'currency' => PurchaseOrder::query()->whereKey($invoice->purchase_order_id)->value('currency')]);
$documents = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)
->whereIn('id', SupplyRecord::query()->selectRaw('MAX(id)')->where('kind', 'import_cost_doc')->groupBy('record_key'))->latest('id')
->paginate(20, ['id', 'record_key', 'version', 'data', 'created_at'], 'documents_page')->withQueryString();
$budgets = DB::table('budgets')->where('tenant_id', $actor->tenant_id)->whereNotNull('approved_by')->where('year', now()->year)
->orderBy('id')->paginate(20, ['id', 'cost_center_id', 'kind', 'includes_tax'], 'budgets_page')->withQueryString();
$history = SupplyRecord::query()->where('kind', 'import_cost_plan')->where('purchase_order_id', $order->id)->latest('version')
->paginate(10, ['id', 'record_key', 'version', 'state', 'reason', 'created_by', 'created_at', 'data', 'snapshot'], 'history_page')->withQueryString();
$latest = SupplyRecord::query()->where('kind', 'import_cost_plan')->where('purchase_order_id', $order->id)->latest('version')->first();
$financialEvents = SupplyRecord::query()->where('kind', 'import_cost_event')->where('purchase_order_id', $order->id)->latest('version')
->paginate(10, ['id', 'version', 'state', 'reason', 'created_by', 'created_at', 'data', 'snapshot'], 'financial_events_page')->withQueryString();
$financial = null;
if ($latest !== null && $this->financialReady()) {
$engine = app(CommonBudget::class)->for($actor);
$state = app(CommonBudget::class)->execute(fn () => (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $latest->record_key));
$financial = is_array($state) ? $state['result'] : null;
if ($financial !== null) {
$financial['native_plan_id'] = SupplyRecord::query()->where('kind', 'import_cost_plan')->where('record_key', $latest->record_key)
->where('version', $financial['version'])->where('state', 'approved')->value('id');
foreach ($financial['origins'] as &$origin) {
$source = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)->whereKey($origin['id'])->firstOrFail();
abort_unless($source->version === $origin['source_version'], 503, 'Preserve a versão documental associada ao efeito financeiro.');
$origin['reference'] = $source->data['reference'];
$origin['evidence_url'] = '/compras/importacoes/'.$current->id.'/custos/documentos/'.$source->id;
}
unset($origin);
}
}
return ['importRecord' => ['id' => $current->id, 'record_key' => $current->record_key, 'version' => $current->version,
'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'] ?? [],
'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']),
'invoiceSearch' => $search, 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
});
}
public function evidence(User $actor, SupplyRecord $import, int $documentId): SupplyRecord
{
abort_unless($this->ready(), 503);
return DB::transaction(function () use ($actor, $import, $documentId): SupplyRecord {
[, $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.');
return $document;
});
}
/** Native documentary source, not a supplier invoice or a payable.
* @param array<string,mixed> $input
*/
public function recordDocument(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', 'kind' => 'required|in:customs_assessment,other_charge',
'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
'reference' => 'required|string|min:3|max:180', 'issued_on' => 'required|date_format:Y-m-d|before_or_equal:today',
'creditor_reference' => 'required|string|min:3|max:180', 'currency' => 'required|regex:/^[A-Z]{3}$/D',
'subtotal_minor' => 'required|integer|min:0|max:100000000000000', 'tax_minor' => 'required|integer|min:0|max:100000000000000',
'total_minor' => 'required|integer|min:0|max:100000000000000', 'exchange_basis' => 'present|nullable|array:rate,quoted_on,source',
'exchange_basis.rate' => ['required_unless:currency,MZN', 'regex:/^\d{1,8}(?:\.\d{1,10})?$/D'],
'exchange_basis.quoted_on' => 'required_unless:currency,MZN|date_format:Y-m-d|before_or_equal:today',
'exchange_basis.source' => 'required_unless:currency,MZN|string|min:3|max:1000',
'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']);
// Multipart form fields arrive as strings; normalise only validated exact cent integers.
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
abort_unless(is_int($data[$field]) || (is_string($data[$field]) && preg_match('/^\d{1,15}$/D', $data[$field])), 422, 'Indique centavos inteiros, sem arredondamentos.');
$data[$field] = (int) $data[$field];
}
$data['operation_key'] = strtolower($data['operation_key']);
$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);
$old = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
if ($old !== null) {
abort_unless($old->kind === 'import_cost_doc' && $old->created_by === $actor->id && hash_equals($old->input_hash, $hash), 409);
return $old;
}
$previous = $data['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_cost_doc')
->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 antes de corrigir.');
if ($previous !== null) {
abort_unless($previous->purchase_order_id === $order->id && $previous->snapshot['import_key'] === $current->record_key && $previous->data['kind'] === $data['kind'], 409, 'A correcção deve conservar a origem e o tipo documental.');
abort_unless($previous->data['currency'] === $data['currency'] && $previous->data['exchange_basis'] === $data['exchange_basis'], 409, 'A correcção conserva a moeda e a taxa de Finanças já congeladas nesta origem.');
}
abort_if(SupplyRecord::query()->where('kind', 'import_cost_doc')
->when($previous !== null, fn ($query) => $query->where('record_key', '!=', $previous->record_key))
->where('data->kind', $data['kind'])->where('data->creditor_reference', $data['creditor_reference'])
->where('data->reference', $data['reference'])->exists(), 409, 'A origem documental já foi registada. Preserve a referência existente.');
$reference = $this->reference($data);
$recordKey = $previous->record_key ?? (string) Str::uuid();
$version = ($previous->version ?? 0) + 1;
$newPath = $file->storeAs('import-costs/'.$actor->tenant_id.'/'.$order->id, $recordKey.'-'.$version.'.'.$file->extension(), 'local');
abort_unless(is_string($newPath), 503, 'Não foi possível conservar o documento privado.');
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_cost_doc', 'record_key' => $recordKey,
'version' => $version, 'state' => 'recorded', 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
'data' => array_diff_key($data, array_flip(['operation_key', 'reason', 'record_key', 'version'])),
'snapshot' => ['import_key' => $current->record_key, 'import_version' => $current->version, 'reference_amounts' => $reference,
'exchange_basis_recorded_by' => $previous->snapshot['exchange_basis_recorded_by'] ?? $actor->id,
'supersedes' => $previous->id ?? null, 'contributors' => array_values(array_unique([...($previous?->snapshot['contributors'] ?? []), $actor->id])),
'evidence' => ['disk' => 'local', 'path' => $newPath, 'sha256' => $sha, 'size' => $file->getSize(), 'mime_type' => $file->getMimeType()],
'financial_effects' => false, 'legal_rate_verified' => false],
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'import.cost_document_recorded', Requisition::query()->findOrFail($order->requisition_id), null,
['record_id' => $record->id, 'import_key' => $current->record_key, 'sha256' => $sha, 'financial_effects' => false]);
return $record;
});
} catch (\Throwable $error) {
if (is_string($newPath) && ! SupplyRecord::query()->where('kind', 'import_cost_doc')->where('snapshot->evidence->path', $newPath)->exists()) {
Storage::disk('local')->delete($newPath);
}
throw $error;
}
}
/** @param array<string,mixed> $input
* @return array<string,mixed>
*/
public function preview(User $actor, SupplyRecord $import, array $input): array
{
abort_unless($this->ready(), 503);
$data = Validator::make($input, ['documents' => 'required|array|min:1|max:100', 'documents.*' => 'required|array:origin,kind,id',
'documents.*.origin' => 'required|string|regex:/^[A-Za-z0-9:_-]{1,120}$/D|distinct',
'documents.*.kind' => 'required|in:supplier_invoice,carrier_invoice,insurer_invoice,customs_assessment,other_charge',
'documents.*.id' => 'required|integer|min:1', 'components' => 'required|array|min:1|max:500', 'budget_id' => 'required|integer|min:1',
'item_references' => 'sometimes|array|list|max:500',
'item_references.*' => 'required|array:component_key,purchase_order_item_ids',
'item_references.*.component_key' => 'required|string|max:120|distinct',
'item_references.*.purchase_order_item_ids' => 'required|array|list|min:1|max:100',
'item_references.*.purchase_order_item_ids.*' => 'required|integer|min:1'])->validate();
return DB::transaction(function () use ($actor, $import, $data): array {
[$actor, $current, $order] = $this->context($actor, $import);
$budget = DB::table('budgets')->where('tenant_id', $actor->tenant_id)->where('id', $data['budget_id'])->lockForUpdate()->first();
abort_unless($budget !== null && $budget->approved_by !== null && (int) $budget->year === (int) now()->year, 422, 'Seleccione uma dotação aprovada do exercício.');
$documents = $details = [];
foreach ($data['documents'] as $selection) {
if (in_array($selection['kind'], ['supplier_invoice', 'carrier_invoice', 'insurer_invoice'], true)) {
$invoice = Invoice::query()->whereKey($selection['id'])->lockForUpdate()->firstOrFail();
abort_unless($invoice->status === 'validated', 409, 'A factura de origem ainda não foi validada.');
$sourceOrder = PurchaseOrder::query()->visibleTo($actor)->findOrFail($invoice->purchase_order_id);
app(OrderPartsAccess::class)->assertProcess($actor, $sourceOrder);
abort_if($selection['kind'] === 'supplier_invoice' && $sourceOrder->id !== $order->id, 422, 'A mercadoria deve pertencer à ordem da importação.');
$native = ['currency' => $sourceOrder->currency, 'subtotal_minor' => $invoice->subtotal_minor, 'tax_minor' => $invoice->tax_minor,
'total_minor' => $invoice->total_minor, 'exchange_basis' => $invoice->snapshot['exchange_basis'] ?? null];
$reference = $this->reference($native);
$revision = hash('sha256', json_encode($invoice->getAttributes(), JSON_THROW_ON_ERROR));
$creditor = 'supplier:'.$invoice->supplier_id;
$sourceKey = 'invoice:'.$invoice->id;
$sourceVersion = 1;
$details[$selection['origin']] = ['reference' => $invoice->number, 'creditor' => $invoice->snapshot['supplier']['name'],
'currency' => $native['currency'], 'exchange_basis' => $native['exchange_basis'], 'financial_authority' => 'native_invoice'];
} else {
$document = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)->whereKey($selection['id'])->firstOrFail();
abort_unless($document->data['kind'] === $selection['kind'] && $document->snapshot['import_key'] === $current->record_key, 409);
abort_unless(SupplyRecord::query()->where('kind', 'import_cost_doc')->where('record_key', $document->record_key)->latest('version')->value('id') === $document->id, 409, 'O documento foi corrigido. Seleccione a nova versão, preservando a preparação anterior.');
$native = $document->data;
$reference = $document->snapshot['reference_amounts'];
$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.');
$revision = $document->input_hash;
$creditor = 'authority:'.hash('sha256', $native['creditor_reference']);
$sourceKey = $document->record_key;
$sourceVersion = $document->version;
$details[$selection['origin']] = ['reference' => $native['reference'], 'creditor' => $native['creditor_reference'],
'currency' => $native['currency'], 'exchange_basis' => $native['exchange_basis'], 'financial_authority' => 'documentary_source_only'];
}
$documents[$selection['origin']] = ['kind' => $selection['kind'], 'id' => (int) $selection['id'], 'creditor_key' => $creditor,
'source_key' => $sourceKey, 'source_version' => $sourceVersion,
'currency' => $native['currency'], 'revision' => $revision, 'subtotal_minor' => $native['subtotal_minor'], 'tax_minor' => $native['tax_minor'], 'total_minor' => $native['total_minor'],
'reference_subtotal_minor' => $reference['subtotal_minor'], 'reference_tax_minor' => $reference['tax_minor'], 'reference_total_minor' => $reference['total_minor']];
}
$plan = app(CommonBudget::class)->execute(fn () => BudgetLandedCostPlan::reconcile($data['components'], $documents, (bool) $budget->includes_tax));
$items = $order->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity'])->keyBy('id');
$references = [];
foreach ($data['item_references'] ?? [] as $selection) {
abort_unless(in_array($selection['component_key'], array_column($plan['components'], 'component_key'), true), 422, 'A referência exige um componente da preparação.');
$ids = array_map(intval(...), $selection['purchase_order_item_ids']);
abort_unless(count(array_unique($ids)) === count($ids), 422, 'Não repita o mesmo artigo no componente.');
sort($ids, SORT_NUMERIC);
foreach ($ids as $id) {
abort_unless($items->has($id), 422, 'Seleccione apenas artigos da ordem desta importação.');
$references[$selection['component_key']][] = $items->get($id)->only(['id', 'description', 'unit', 'quantity']);
}
}
ksort($references);
return [...$plan, 'budget_id' => $budget->id, 'import_key' => $current->record_key, 'import_version' => $current->version,
'import_revision' => $this->importRevision($current),
'item_references' => $references,
'purchase_order_id' => $order->id, 'document_details' => $details, 'native_principals_preserved' => true];
});
}
/** Persist a recoverable preparation; independent review does not execute budget effects.
* @param array<string,mixed> $input
*/
public function save(User $actor, SupplyRecord $import, array $input): SupplyRecord
{
abort_unless($this->ready(), 503);
$envelope = Validator::make($input, ['operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid',
'version' => 'required|integer|min:0', 'action' => 'required|in:save,approve,return',
'reason' => 'required|string|min:10|max:4000', 'data' => 'present|array'])->validate();
$envelope['operation_key'] = strtolower($envelope['operation_key']);
$hash = hash('sha256', json_encode([$import->record_key, $import->version, $envelope], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $import, $envelope, $hash): SupplyRecord {
[$actor, $current, $order] = $this->context($actor, $import);
$replay = SupplyRecord::query()->where('operation_key', $envelope['operation_key'])->first();
if ($replay !== null) {
abort_unless($replay->kind === 'import_cost_plan' && $replay->created_by === $actor->id && hash_equals($replay->input_hash, $hash), 409);
return $replay;
}
$old = $envelope['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_cost_plan')
->where('record_key', $envelope['record_key'])->latest('version')->lockForUpdate()->firstOrFail();
abort_unless((int) $envelope['version'] === ($old->version ?? 0), 409, 'A preparação mudou. Conserve os seus valores e consulte a versão actual.');
if ($old !== null) {
abort_unless($old->purchase_order_id === $order->id && $old->snapshot['import_key'] === $current->record_key, 409);
} else {
abort_if(SupplyRecord::query()->where('kind', 'import_cost_plan')->where('purchase_order_id', $order->id)->exists(), 409, 'A importação já tem uma preparação. Continue a versão existente.');
}
$action = $envelope['action'];
if ($action === 'save') {
$selection = $envelope['data'];
$plan = $this->preview($actor, $current, $selection);
$contributors = array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id]));
foreach ($selection['documents'] as $document) {
if (in_array($document['kind'], ['customs_assessment', 'other_charge'], true)) {
$source = SupplyRecord::query()->where('kind', 'import_cost_doc')->whereKey($document['id'])->sole();
$contributors = [...$contributors, ...$source->snapshot['contributors']];
}
}
$contributors = array_values(array_unique($contributors));
$state = 'draft';
} else {
abort_unless($old !== null && $old->state === 'draft' && $envelope['data'] === [], 409, 'A conferência exige uma preparação actual sem alterar o seu conteúdo.');
$contributors = $old->snapshot['contributors'];
abort_if(in_array($actor->id, $contributors, true), 403, 'A conferência exige Finanças independente da preparação e dos documentos adicionais.');
$selection = $old->data;
$plan = $action === 'return' ? $old->snapshot['plan'] : $this->preview($actor, $current, $selection);
abort_unless($action === 'return' || $this->equivalentPreparation($plan, $old->snapshot['plan']), 409, 'As origens ou a dotação mudaram. Devolva e actualize a preparação.');
$state = $action === 'approve' ? 'approved' : 'returned';
}
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_cost_plan',
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
'state' => $state, 'purchase_order_id' => $order->id, 'created_by' => $actor->id, 'data' => $selection,
'snapshot' => ['import_key' => $current->record_key, 'contributors' => $contributors, 'plan' => $plan, 'financial_effects' => false],
'reason' => $envelope['reason'], 'operation_key' => $envelope['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'import.cost_plan_'.$action, Requisition::query()->findOrFail($order->requisition_id), null,
['record_id' => $record->id, 'record_key' => $record->record_key, 'version' => $record->version, 'state' => $state, 'fingerprint' => $plan['fingerprint'], 'financial_effects' => false]);
return $record;
});
}
/** One native receipt around one common financial command.
* @param array<string,mixed> $input
*/
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',
'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();
$data['operation_key'] = strtolower($data['operation_key']);
$data['financial_revision'] = (int) $data['financial_revision'];
$data['sources'] ??= [];
sort($data['sources'], SORT_STRING);
$hash = hash('sha256', json_encode([$import->record_key, $plan->id, $data], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $import, $plan, $data, $hash): SupplyRecord {
[$actor, $current, $order] = $this->context($actor, $import);
$plan = SupplyRecord::query()->where('kind', 'import_cost_plan')->whereKey($plan->id)->lockForUpdate()->firstOrFail();
abort_unless($plan->purchase_order_id === $order->id && $plan->snapshot['import_key'] === $current->record_key, 404);
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
if ($retry !== null) {
abort_unless($retry->kind === 'import_cost_event' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
return $retry;
}
abort_unless($plan->state === 'approved', 409, 'A aplicação financeira exige conferência independente da preparação.');
if ($data['action'] !== 'cancel') {
abort_unless(SupplyRecord::query()->where('kind', 'import_cost_plan')->where('record_key', $plan->record_key)->latest('version')->value('id') === $plan->id, 409, 'Existe uma nova preparação; conclua a sua revisão antes de movimentar.');
abort_unless($this->equivalentPreparation($this->preview($actor, $current, $plan->data), $plan->snapshot['plan']), 409, 'As origens documentais mudaram. Prepare e confira uma nova versão.');
}
$adapter = app(CommonBudget::class);
$engine = $adapter->for($actor);
$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.');
$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') {
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.');
$method = 'amendLandedCosts';
$args = [$plan->record_key, $state['result']['version'], $state['result']['plan_hash'], $plan->version,
$plan->data['components'], $plan->snapshot['plan']['documents'], $data['operation_key'], $data['financial_revision']];
} else {
abort_unless($data['action'] === 'cancel' || ($state['result']['version'] === $plan->version && $state['result']['plan_hash'] === $plan->snapshot['plan']['fingerprint']), 409, 'Aplique a alteração documental aprovada antes de continuar.');
$method = 'transitionLandedCosts';
$args = [$plan->record_key, $state['result']['version'], $state['result']['plan_hash'], $data['action'], $data['operation_key'], $data['sources'], $data['financial_revision']];
}
}
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, $method))->invoke($engine, ...$args));
abort_unless(is_array($result), 503, 'Recibo financeiro incompatível; operação não concluída.');
$version = (int) SupplyRecord::query()->where('kind', 'import_cost_event')->where('record_key', $plan->record_key)->max('version') + 1;
$event = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_cost_event', 'record_key' => $plan->record_key,
'version' => $version, 'state' => $result['phase'], 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
'data' => ['action' => $data['action'], 'approved_preparation_id' => $plan->id, 'financial_plan_version' => $result['version']],
'snapshot' => ['import_key' => $current->record_key, 'common_result' => $result, 'actor' => $actor->only(['id', 'name'])],
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
return $event;
});
}
/** @return array{User,SupplyRecord,PurchaseOrder} */
private function context(User $actor, SupplyRecord $import): array
{
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Finance]);
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, 'O processo de importação mudou. Consulte a versão actual.');
$order = PurchaseOrder::query()->visibleTo($actor)->lockForUpdate()->findOrFail($current->purchase_order_id);
app(OrderPartsAccess::class)->assertProcess($actor, $order);
return [$actor, $current, $order];
}
private function importRevision(SupplyRecord $import): string
{
$context = ['purchase_order_id' => $import->purchase_order_id];
foreach (['purpose', 'jurisdiction', 'origin_country', 'dispatch_country', 'incoterm', 'regime'] as $field) {
$context[$field] = $import->data[$field] ?? null;
}
return hash('sha256', json_encode($context, JSON_THROW_ON_ERROR));
}
/** Logistics events do not revoke accepted financial sources.
* @param array<string,mixed> $fresh
* @param array<string,mixed> $frozen
*/
private function equivalentPreparation(array $fresh, array $frozen): bool
{
$frozen['import_revision'] = $this->preparationImportRevision($frozen);
$frozen['item_references'] ??= [];
if ($frozen['import_revision'] === null) {
return false;
}
unset($fresh['import_version'], $frozen['import_version']);
// Key order is presentation, not a financial source change.
ksort($fresh);
ksort($frozen);
return $fresh === $frozen;
}
/** @param array<string,mixed> $plan */
private function preparationImportRevision(array $plan): ?string
{
if (isset($plan['import_revision'])) {
return $plan['import_revision'];
}
$historical = SupplyRecord::query()->where('kind', 'import')->where('record_key', $plan['import_key'])
->where('version', $plan['import_version'])->first();
return $historical === null ? null : $this->importRevision($historical);
}
/** @param array<string,mixed> $document
* @return array{subtotal_minor:int,tax_minor:int,total_minor:int}
*/
private function reference(array $document): array
{
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
abort_unless(is_int($document[$field]) && $document[$field] >= 0 && $document[$field] <= 100000000000000, 422, 'Indique montantes documentais inteiros em centavos.');
}
abort_unless($document['subtotal_minor'] <= $document['total_minor'] && $document['tax_minor'] === $document['total_minor'] - $document['subtotal_minor'], 422, 'Os valores documentais não reconciliam.');
$basis = $document['exchange_basis'];
if ($document['currency'] === 'MZN') {
abort_unless($basis === null, 422, 'Documentos MZN conservam os valores nativos.');
return array_intersect_key($document, array_flip(['subtotal_minor', 'tax_minor', 'total_minor']));
}
abort_unless(is_array($basis) && is_string($basis['rate'] ?? null) && is_string($basis['quoted_on'] ?? null)
&& is_string($basis['source'] ?? null) && trim($basis['source']) !== '', 422, 'Conserve a taxa, data e fonte explícitas de Finanças.');
try {
$subtotal = app(QuotationExchange::class)->convert($document['subtotal_minor'], $basis['rate']);
$tax = app(QuotationExchange::class)->convert($document['tax_minor'], $basis['rate']);
} catch (\InvalidArgumentException) {
abort(422, 'Montante ou taxa de câmbio não representável.');
}
abort_if($subtotal > 100000000000000 - $tax, 422, 'Total convertido não representável.');
return ['subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax];
}
}