@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use App\Services\ImportDossier;
|
||||
use App\Services\ImportEvidence;
|
||||
use App\Services\ImportParties;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class ImportDossierController extends Controller
|
||||
{
|
||||
private function actor(Request $request): User
|
||||
{
|
||||
$actor = $request->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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\ImportEstimates;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class ImportEstimateController extends Controller
|
||||
{
|
||||
public function index(Request $request, Requisition $requisition, ImportEstimates $service): Response
|
||||
{
|
||||
$actor = $request->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.');
|
||||
}
|
||||
}
|
||||
@@ -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<string,mixed>|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']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)],
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
},
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
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\Storage;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/** Versioned documentary originals. No customs submission, payment or legal conclusion. */
|
||||
final class ImportDossier
|
||||
{
|
||||
public const TYPES = [
|
||||
'commercial_invoice' => '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<string,mixed> */
|
||||
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<string,mixed> $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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Budget;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Tempo\Finance\Budget\BudgetImportEstimate;
|
||||
|
||||
/** Native, versioned assumptions before supplier/customs documents exist. */
|
||||
final class ImportEstimates
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
|
||||
return config('import-estimates.qa_enabled') === true && app()->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<string,mixed> */
|
||||
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<string,mixed>|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<string,mixed> */
|
||||
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<int> */
|
||||
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<string,mixed> */
|
||||
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<string,mixed> $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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SupplyRecord;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use League\Flysystem\FilesystemException;
|
||||
|
||||
/** Read the bounded private original once and return exactly the bytes that were verified. */
|
||||
final class ImportEvidence
|
||||
{
|
||||
public function bytes(SupplyRecord $record): string
|
||||
{
|
||||
$evidence = $record->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;
|
||||
}
|
||||
}
|
||||
@@ -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.');
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Explicit native broker/forwarder selection with retained written instructions. */
|
||||
final class ImportParties
|
||||
{
|
||||
public const ROLES = ['broker' => '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<string,mixed> */
|
||||
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<string> */
|
||||
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<string,mixed> $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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
|
||||
/** Native Finance authority and projection; the common writer alone reallocates commitments. */
|
||||
final class OrderPartsAmendments
|
||||
{
|
||||
/** @return list<array<string,mixed>> */
|
||||
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<string,mixed> $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'])));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/** Per-origin FX bridge. Documentary amounts remain in the supplier's currency. */
|
||||
final class OrderPartsExchange
|
||||
{
|
||||
/** @return array<int,array<string,mixed>> */
|
||||
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<array<string,mixed>> $lines
|
||||
* @return array<int,array{subtotal_minor:int,tax_minor:int,total_minor:int}>
|
||||
*/
|
||||
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<array{subtotal_minor:int,tax_minor:int,total_minor:int}> $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'))];
|
||||
}
|
||||
}
|
||||
@@ -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']);
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
/** Converts cumulative documentary amounts with the frozen rate of one origin. */
|
||||
final class OrderPartsReference
|
||||
{
|
||||
/** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
|
||||
public static function portion(int $beforeNet, int $beforeTax, int $net, int $tax, string $rate): array
|
||||
{
|
||||
if (min($beforeNet, $beforeTax, $net, $tax) < 0
|
||||
|| $beforeNet > 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];
|
||||
}
|
||||
}
|
||||
@@ -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<array<string,mixed>> $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.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigInteger;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
/** Read confirmed original payments, never sum imported financial copies. */
|
||||
class ProcurementPaymentInsights
|
||||
{
|
||||
/** @param Builder<Requisition> $requests
|
||||
* @return array<string,mixed>|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)];
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
|
||||
@@ -89,7 +89,7 @@ class RequisitionApprovalLevels
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
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.']);
|
||||
}
|
||||
|
||||
@@ -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<array<string,mixed>>
|
||||
*/
|
||||
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<string,mixed> */
|
||||
public static function paymentFacts(\stdClass $payment, ?\stdClass $registration, ?\stdClass $decision): array
|
||||
{
|
||||
|
||||
@@ -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.');
|
||||
|
||||
Reference in New Issue
Block a user