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

This commit is contained in:
2026-11-23 06:37:16 +02:00
parent db1615fac1
commit dc73540558
73 changed files with 7539 additions and 175 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ class OperationsCheck extends Command
$this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)); $this->line(json_encode($result, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
} else { } else {
$this->line($result['ok'] ? 'Operação: verificações concluídas sem divergências observadas.' : 'Operação: verificações requerem atenção.'); $this->line($result['ok'] ? 'Operação: verificações concluídas sem divergências observadas.' : 'Operação: verificações requerem atenção.');
$labels = ['replenishment' => 'Reposição', 'receipt_documents' => 'Documentos da recepção']; $labels = ['replenishment' => 'Reposição', 'receipt_documents' => 'Documentos da recepção', 'import_cost_documents' => 'Documentos dos custos de importação'];
$states = ['passed' => 'sem divergências observadas', 'attention' => 'requer atenção', 'incomplete' => 'verificação incompleta', 'unavailable' => 'consulta indisponível']; $states = ['passed' => 'sem divergências observadas', 'attention' => 'requer atenção', 'incomplete' => 'verificação incompleta', 'unavailable' => 'consulta indisponível'];
foreach ($result['checks'] as $key => $check) { foreach ($result['checks'] as $key => $check) {
$this->line($labels[$key].': '.$states[$check['status']].'.'); $this->line($labels[$key].': '.$states[$check['status']].'.');
@@ -0,0 +1,78 @@
<?php
namespace App\Http\Controllers;
use App\Models\SupplyRecord;
use App\Models\User;
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;
class ImportLandedCostController 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, ImportLandedCosts $service): Response
{
return $this->page($request, $import, $service);
}
public function preview(Request $request, SupplyRecord $import, ImportLandedCosts $service): Response
{
return $this->page($request, $import, $service, $service->preview($this->actor($request), $import, $request->all()));
}
/** @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'] ?? '';
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');
return $response;
}
public function document(Request $request, SupplyRecord $import, ImportLandedCosts $service): RedirectResponse
{
$request->validate(['file' => 'required|file']);
$file = $request->file('file');
abort_unless($file instanceof UploadedFile, 422);
$service->recordDocument($this->actor($request), $import, $request->except('file'), $file);
return to_route('imports.costs', $import);
}
public function save(Request $request, SupplyRecord $import, ImportLandedCosts $service): RedirectResponse
{
$service->save($this->actor($request), $import, $request->all());
return to_route('imports.costs', $import);
}
public function financial(Request $request, SupplyRecord $import, SupplyRecord $plan, ImportLandedCosts $service): RedirectResponse
{
$service->financial($this->actor($request), $import, $plan, $request->all());
return to_route('imports.costs', $import);
}
public function evidence(Request $request, SupplyRecord $import, int $document, ImportLandedCosts $service): Response
{
$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']);
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Http\Controllers;
use App\Models\Requisition;
use App\Models\User;
use App\Services\ImportTariffCodes;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
final class ImportTariffController extends Controller
{
public function index(Request $request, Requisition $requisition, ImportTariffCodes $service): Response
{
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
$data = $request->validate(['search' => 'nullable|string|max:100', 'tariff_history_page' => 'nullable|integer|min:1|max:1000000',
'stock_page' => 'nullable|integer|min:1|max:1000000', 'masters_page' => 'nullable|integer|min:1|max:1000000']);
Inertia::encryptHistory();
$response = Inertia::render('supply/import-tariffs', $service->workspace($actor, $requisition, $data['search'] ?? ''))->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
}
public function store(Request $request, Requisition $requisition, ImportTariffCodes $service): RedirectResponse
{
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
$service->save($actor, $requisition, $request->all());
return back()->with('success', 'Classificação documental registada.');
}
}
+8 -2
View File
@@ -10,6 +10,8 @@ use App\Models\User;
use App\Services\InventoryDispositions; use App\Services\InventoryDispositions;
use App\Services\InventoryReversals; use App\Services\InventoryReversals;
use App\Services\InvoiceWorkflow; use App\Services\InvoiceWorkflow;
use App\Services\OrderPartsAccess;
use App\Services\OrderPartsInvoices;
use App\Services\OrganizationAccess; use App\Services\OrganizationAccess;
use App\Services\RequisitionBudgetDistributions; use App\Services\RequisitionBudgetDistributions;
use App\Services\SupplierPayables; use App\Services\SupplierPayables;
@@ -36,7 +38,9 @@ class InvoiceController extends Controller
'invoices' => Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->when($focus !== null, fn ($q) => $q->whereKey($focus))->when($focusOrder !== null, fn ($q) => $q->where('purchase_order_id', $focusOrder))->with('items')->latest('id')->paginate(15)->withQueryString() 'invoices' => Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->when($focus !== null, fn ($q) => $q->whereKey($focus))->when($focusOrder !== null, fn ($q) => $q->where('purchase_order_id', $focusOrder))->with('items')->latest('id')->paginate(15)->withQueryString()
->through(fn (Invoice $invoice) => [...$invoice->toArray(), 'canValidate' => app(InvoiceWorkflow::class)->reviewerEligible($actor, $invoice)]), ->through(fn (Invoice $invoice) => [...$invoice->toArray(), 'canValidate' => app(InvoiceWorkflow::class)->reviewerEligible($actor, $invoice)]),
'orders' => PurchaseOrder::query()->visibleTo($actor)->operational()->with('items')->latest('id')->get()->map(fn ($order) => ['id' => $order->id, 'number' => $order->number, 'currency' => $order->currency, 'supplier' => $order->snapshot['supplier']['name'], 'items' => $order->items, 'orders' => PurchaseOrder::query()->visibleTo($actor)->operational()->with('items')->latest('id')->get()->map(fn ($order) => ['id' => $order->id, 'number' => $order->number, 'currency' => $order->currency, 'supplier' => $order->snapshot['supplier']['name'], 'items' => $order->items,
'budgetDistributionOptions' => app(RequisitionBudgetDistributions::class)->options($actor, Requisition::query()->findOrFail($order->requisition_id))]), 'orderParts' => OrderPartsAccess::applies($order),
'orderPartsBudgetOptions' => OrderPartsAccess::applies($order) ? app(OrderPartsInvoices::class)->options($actor, $order) : null,
'budgetDistributionOptions' => OrderPartsAccess::applies($order) ? null : app(RequisitionBudgetDistributions::class)->options($actor, Requisition::query()->findOrFail($order->requisition_id))]),
'sgfDispatchAvailable' => config('sgf_invoice.workspace_enabled') === true && $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 'sgfDispatchAvailable' => config('sgf_invoice.workspace_enabled') === true && $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor),
'payablesAvailable' => SupplierPayables::enabled() && app(SupplierPayables::class)->can($actor, 'view'), 'canManage' => $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)])->toResponse($request); 'payablesAvailable' => SupplierPayables::enabled() && app(SupplierPayables::class)->can($actor, 'view'), 'canManage' => $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0'); $response->headers->set('Cache-Control', 'private, no-store, max-age=0');
@@ -50,7 +54,9 @@ class InvoiceController extends Controller
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Finance]), 403); abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Finance]), 403);
$decimal = ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/']; $decimal = ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'];
$data = $request->validate(['number' => 'required|string|max:100', 'issued_on' => 'required|date_format:Y-m-d', 'subtotal' => $decimal, 'tax' => $decimal, 'total' => $decimal, 'items' => 'required|array|min:1|max:50', 'items.*.purchase_order_item_id' => 'required|integer|distinct', 'items.*.quantity' => ['required', 'regex:/^\d{1,9}(\.\d{1,3})?$/'], 'items.*.unit' => 'sometimes|required|string|max:30', 'items.*.unit_price' => ['sometimes', ...$decimal], 'items.*.tax_rate' => ['sometimes', 'required', 'regex:/^\d{1,3}(\.\d{1,2})?$/']]); $data = $request->validate(['number' => 'required|string|max:100', 'issued_on' => 'required|date_format:Y-m-d', 'subtotal' => $decimal, 'tax' => $decimal, 'total' => $decimal, 'items' => 'required|array|min:1|max:50', 'items.*.purchase_order_item_id' => 'required|integer|distinct', 'items.*.quantity' => ['required', 'regex:/^\d{1,9}(\.\d{1,3})?$/'], 'items.*.unit' => 'sometimes|required|string|max:30', 'items.*.unit_price' => ['sometimes', ...$decimal], 'items.*.tax_rate' => ['sometimes', 'required', 'regex:/^\d{1,3}(\.\d{1,2})?$/']]);
if (app(RequisitionBudgetDistributions::class)->applies(Requisition::query()->findOrFail($order->requisition_id))) { if (OrderPartsAccess::applies($order)) {
$data += $request->validate(app(OrderPartsInvoices::class)->rules());
} elseif (app(RequisitionBudgetDistributions::class)->applies(Requisition::query()->findOrFail($order->requisition_id))) {
$data += $request->validate(app(RequisitionBudgetDistributions::class)->rules(Requisition::query()->findOrFail($order->requisition_id))); $data += $request->validate(app(RequisitionBudgetDistributions::class)->rules(Requisition::query()->findOrFail($order->requisition_id)));
} }
$workflow->register($actor, $order, $data); $workflow->register($actor, $order, $data);
@@ -0,0 +1,88 @@
<?php
namespace App\Http\Controllers;
use App\Enums\PurchasingRole;
use App\Models\PurchaseAward;
use App\Models\PurchaseOrderItem;
use App\Models\Quotation;
use App\Models\Requisition;
use App\Models\User;
use App\Services\OrderPartsWorkflow;
use App\Services\OrganizationAccess;
use App\Services\ReceiptWorkflow;
use Brick\Math\BigDecimal;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class OrderPartsController extends Controller
{
private function actor(Request $request): User
{
$actor = $request->user('web');
abort_unless($actor instanceof User && $actor->hasFunctions([PurchasingRole::Procurement])
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
abort_unless(app(OrderPartsWorkflow::class)->ready(), 503);
return $actor;
}
public function index(Request $request): Response
{
return $this->page($this->actor($request));
}
public function preview(Request $request, OrderPartsWorkflow $workflow): Response
{
$actor = $this->actor($request);
return $this->page($actor, $workflow->preview($actor, $request->all()));
}
/** @param array<string,mixed>|null $preview */
private function page(User $actor, ?array $preview = null): Response
{
$candidates = PurchaseAward::query()->where('status', 'approved')
->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id'))
->whereExists(fn ($lines) => $lines->selectRaw('1')->from('quotation_items as qi')
->whereColumn('qi.quotation_id', 'purchase_awards.quotation_id')->whereColumn('qi.tenant_id', 'purchase_awards.tenant_id')
->whereRaw('ROUND(qi.quantity * 1000) > (select COALESCE(SUM(ROUND(oi.quantity * 1000)), 0) from purchase_order_items oi where oi.requisition_item_id = qi.requisition_item_id and oi.tenant_id = qi.tenant_id)'))
->latest('id')->paginate(20)
->through(function (PurchaseAward $award): array {
$quote = Quotation::query()->with(['items', 'supplier'])->whereKey($award->quotation_id)->firstOrFail();
$request = Requisition::query()->whereKey($award->requisition_id)->firstOrFail();
$items = [];
foreach ($quote->items as $line) {
$before = 0;
foreach (PurchaseOrderItem::query()->where('requisition_item_id', $line->requisition_item_id)->get(['quantity']) as $old) {
$before += ReceiptWorkflow::milli($old->quantity);
}
$remaining = max(0, ReceiptWorkflow::milli($line->quantity) - $before);
$items[] = ['id' => $line->id, 'description' => $line->description, 'remaining' => (string) BigDecimal::of($remaining)->dividedBy(1000, 3)];
}
return ['id' => $award->id, 'requisition_id' => $request->id, 'number' => $request->number,
'supplier' => $quote->supplier?->name, 'currency' => $quote->currency, 'items' => $items];
});
Inertia::encryptHistory();
return Inertia::render('purchases/parts', ['candidates' => $candidates, 'preview' => $preview]);
}
public function issue(Request $request, OrderPartsWorkflow $workflow): RedirectResponse
{
$order = $workflow->issue($this->actor($request), $request->all());
return to_route('orders.show', $order);
}
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']);
return to_route('orders.parts');
}
}
+7 -1
View File
@@ -14,6 +14,8 @@ use App\Models\User;
use App\Services\AgreementOrderLimits; use App\Services\AgreementOrderLimits;
use App\Services\FormalRecommendation; use App\Services\FormalRecommendation;
use App\Services\OrderCancellationWorkflow; use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsAccess;
use App\Services\OrderPartsWorkflow;
use App\Services\OrganizationAccess; use App\Services\OrganizationAccess;
use App\Services\ProposalComparison; use App\Services\ProposalComparison;
use App\Services\PurchaseWorkflow; use App\Services\PurchaseWorkflow;
@@ -158,6 +160,7 @@ class PurchaseController extends Controller
$actor = $this->access($request); $actor = $this->access($request);
return Inertia::render('purchases/index', [ return Inertia::render('purchases/index', [
'partsAvailable' => $actor->hasFunctions([PurchasingRole::Procurement]) && app(OrderPartsWorkflow::class)->ready(),
'orders' => PurchaseOrder::query()->visibleTo($actor)->latest('id')->paginate(15), 'orders' => PurchaseOrder::query()->visibleTo($actor)->latest('id')->paginate(15),
'awards' => PurchaseAward::query()->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id'))->latest()->paginate(15, ['*'], 'awards_page'), 'awards' => PurchaseAward::query()->whereIn('requisition_id', Requisition::query()->visibleTo($actor)->select('id'))->latest()->paginate(15, ['*'], 'awards_page'),
]); ]);
@@ -167,14 +170,16 @@ class PurchaseController extends Controller
{ {
$actor = $this->access($request); $actor = $this->access($request);
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id); PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
$origins = app(OrderPartsAccess::class)->origins($order);
return Inertia::render('purchases/show', [ return Inertia::render('purchases/show', [
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(), 'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
'order' => $order->load('items'), 'order' => $order->load('items'),
'orderPartsSources' => $order->snapshot['order_parts']['frames'] ?? [],
'orderCancellation' => ['enabled' => (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'), 'orderCancellation' => ['enabled' => (bool) config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'),
'state' => app(OrderCancellationWorkflow::class)->state($order), 'state' => app(OrderCancellationWorkflow::class)->state($order),
'canRequest' => app(OrderCancellationWorkflow::class)->canRequest($actor, $order)], 'canRequest' => app(OrderCancellationWorkflow::class)->canRequest($actor, $order)],
'history' => AuditLog::query()->where('requisition_id', $order->requisition_id)->whereIn('action', ['award.created', 'award.approved', 'award.rejected', 'purchase_order.issued'])->orderBy('id')->get(['id', 'user_id', 'action', 'created_at']), 'history' => AuditLog::query()->whereIn('requisition_id', $origins)->whereIn('action', ['award.created', 'award.approved', 'award.rejected', 'purchase_order.issued'])->orderBy('id')->get(['id', 'requisition_id', 'user_id', 'action', 'created_at']),
]); ]);
} }
@@ -182,6 +187,7 @@ class PurchaseController extends Controller
{ {
$actor = $this->access($request); $actor = $this->access($request);
PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id); PurchaseOrder::query()->visibleTo($actor)->findOrFail($order->id);
app(OrderPartsAccess::class)->origins($order);
return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot, return view('purchases.print', ['order' => $order->load('items'), 'snapshot' => $order->snapshot,
'snapshotComplete' => $order->hasCompleteDocumentSnapshot(), 'snapshotComplete' => $order->hasCompleteDocumentSnapshot(),
@@ -16,6 +16,7 @@ use App\Services\ApprovalRouting;
use App\Services\ComparisonPolicy; use App\Services\ComparisonPolicy;
use App\Services\ConflictGuard; use App\Services\ConflictGuard;
use App\Services\EquipmentWorkflow; use App\Services\EquipmentWorkflow;
use App\Services\ImportTariffCodes;
use App\Services\InternalSupplyTrace; use App\Services\InternalSupplyTrace;
use App\Services\OrganizationAccess; use App\Services\OrganizationAccess;
use App\Services\RequisitionAuditTrail; use App\Services\RequisitionAuditTrail;
@@ -121,6 +122,7 @@ class RequisitionController extends Controller
'automaticSource' => app(InternalSupplyTrace::class)->purchaseOrigin($this->actor($request), $requisition), 'automaticSource' => app(InternalSupplyTrace::class)->purchaseOrigin($this->actor($request), $requisition),
'comparisonPolicy' => app(ComparisonPolicy::class)->forRequest($requisition), 'comparisonPolicy' => app(ComparisonPolicy::class)->forRequest($requisition),
'canEdit' => app(OrganizationAccess::class)->canRequest($this->actor($request)) && $requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft', 'canEdit' => app(OrganizationAccess::class)->canRequest($this->actor($request)) && $requisition->requester_id === $this->actor($request)->id && $requisition->status === 'draft',
'importTariffsReady' => app(ImportTariffCodes::class)->ready(),
'canDecide' => $requisition->canDecide($this->actor($request)), 'canDecide' => $requisition->canDecide($this->actor($request)),
'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft' 'canPrepareDistributions' => app(RequisitionBudgetDistributions::class)->ready() && $requisition->status === 'draft'
&& $requisition->requester_id === $this->actor($request)->id && app(OrganizationAccess::class)->canRequest($this->actor($request)), && $requisition->requester_id === $this->actor($request)->id && app(OrganizationAccess::class)->canRequest($this->actor($request)),
@@ -2,6 +2,7 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Enums\PurchasingRole;
use App\Models\CostCenter; use App\Models\CostCenter;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem; use App\Models\PurchaseOrderItem;
@@ -14,6 +15,7 @@ use App\Models\SupplyRecord;
use App\Models\User; use App\Models\User;
use App\Models\Warehouse; use App\Models\Warehouse;
use App\Services\AgreementOrderLimits; use App\Services\AgreementOrderLimits;
use App\Services\ImportLandedCosts;
use App\Services\InventoryReversals; use App\Services\InventoryReversals;
use App\Services\OrganizationAccess; use App\Services\OrganizationAccess;
use App\Services\ReceiptWorkflow; use App\Services\ReceiptWorkflow;
@@ -109,6 +111,7 @@ class SupplyPlanningController extends Controller
'contracts' => $ready && $prepare && $kind === 'agreement' && app(AgreementOrderLimits::class)->ready() 'contracts' => $ready && $prepare && $kind === 'agreement' && app(AgreementOrderLimits::class)->ready()
? $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'])) : [], ? $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(), 'orderLimitsReady' => app(AgreementOrderLimits::class)->ready(),
'importCostsReady' => $import && $actor->hasFunctions([PurchasingRole::Finance]) && app(ImportLandedCosts::class)->ready(),
'linkedAgreementKey' => $kind === 'policy' ? $request->query('linked_agreement_key') : null, 'linkedAgreementKey' => $kind === 'policy' ? $request->query('linked_agreement_key') : null,
'linkedContractKey' => $kind === 'agreement' ? $request->query('linked_contract_key') : null, 'linkedContractKey' => $kind === 'agreement' ? $request->query('linked_contract_key') : null,
'agreementSearch' => $agreementFilters['agreement_search'] ?? '', 'agreementFormKey' => $agreementFilters['agreement_form_key'] ?? null, 'agreementSearch' => $agreementFilters['agreement_search'] ?? '', 'agreementFormKey' => $agreementFilters['agreement_form_key'] ?? null,
+16
View File
@@ -51,6 +51,22 @@ class PurchaseOrder extends Model
public function scopeVisibleTo(Builder $query, User $user): void public function scopeVisibleTo(Builder $query, User $user): void
{ {
$query->whereIn('requisition_id', Requisition::query()->visibleTo($user)->select('id')); $query->whereIn('requisition_id', Requisition::query()->visibleTo($user)->select('id'));
if (Schema::hasColumn('purchase_orders', 'order_key')) {
if (! Schema::hasTable('purchase_order_sources')) {
$query->whereNull('order_key');
} else {
$query->where(function ($orders) use ($user) {
$orders->whereNull('order_key')->orWhere(function ($parts) use ($user) {
$parts->whereExists(fn ($sources) => $sources->selectRaw('1')->from('purchase_order_sources as os')
->whereColumn('os.purchase_order_id', 'purchase_orders.id')->whereColumn('os.tenant_id', 'purchase_orders.tenant_id'))
->whereRaw('(select count(*) from purchase_order_sources os where os.purchase_order_id = purchase_orders.id and os.tenant_id = purchase_orders.tenant_id) = purchase_orders.order_source_count')
->whereNotExists(fn ($sources) => $sources->selectRaw('1')->from('purchase_order_sources as os')
->whereColumn('os.purchase_order_id', 'purchase_orders.id')->whereColumn('os.tenant_id', 'purchase_orders.tenant_id')
->whereNotIn('os.requisition_id', Requisition::query()->visibleTo($user)->select('id')));
});
});
}
}
} }
/** @param Builder<PurchaseOrder> $query */ /** @param Builder<PurchaseOrder> $query */
+13 -1
View File
@@ -7,6 +7,7 @@ use App\Models\GoodsReceipt;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\Requisition; use App\Models\Requisition;
use App\Models\User; use App\Models\User;
use App\Services\OrderPartsAccess;
class GoodsReceiptPolicy class GoodsReceiptPolicy
{ {
@@ -17,6 +18,16 @@ class GoodsReceiptPolicy
public function viewOrder(User $user, PurchaseOrder $order): bool public function viewOrder(User $user, PurchaseOrder $order): bool
{ {
if (OrderPartsAccess::applies($order)) {
if (! $this->viewAny($user) || $user->tenant_id !== $order->tenant_id) {
return false;
}
$origins = app(OrderPartsAccess::class)->origins($order);
return Requisition::query()->whereIn('id', $origins)->count() === count($origins)
&& (! $user->departmentScoped() || ! Requisition::query()->whereIn('id', $origins)->where('department_id', '!=', $user->department_id)->exists());
}
return $this->viewAny($user) && $user->tenant_id === $order->tenant_id && return $this->viewAny($user) && $user->tenant_id === $order->tenant_id &&
(! $user->departmentScoped() || Requisition::query()->whereKey($order->requisition_id)->where('department_id', $user->department_id)->exists()); (! $user->departmentScoped() || Requisition::query()->whereKey($order->requisition_id)->where('department_id', $user->department_id)->exists());
} }
@@ -30,6 +41,7 @@ class GoodsReceiptPolicy
public function create(User $user, PurchaseOrder $order): bool public function create(User $user, PurchaseOrder $order): bool
{ {
return $user->tenant_id === $order->tenant_id && $user->hasFunctions([PurchasingRole::Warehouse]) && $user->id !== $order->issued_by; return $user->tenant_id === $order->tenant_id && $user->hasFunctions([PurchasingRole::Warehouse]) && $user->id !== $order->issued_by
&& (! OrderPartsAccess::applies($order) || $this->viewOrder($user, $order));
} }
} }
+7 -1
View File
@@ -109,9 +109,10 @@ final class AgreementOrderLimits
/** @param list<array<string,mixed>> $lines /** @param list<array<string,mixed>> $lines
* @param list<array<string,mixed>> $bindings * @param list<array<string,mixed>> $bindings
* @param list<Requisition> $additionalRequests
* @return array<string,mixed> * @return array<string,mixed>
*/ */
public function freeze(User $actor, Quotation $quote, Requisition $request, array $lines, array $bindings): array public function freeze(User $actor, Quotation $quote, Requisition $request, array $lines, array $bindings, array $additionalRequests = []): array
{ {
if ($bindings === []) { if ($bindings === []) {
return []; return [];
@@ -120,6 +121,11 @@ final class AgreementOrderLimits
abort_unless($this->canRead($actor), 403); abort_unless($this->canRead($actor), 403);
$bindings = $this->canonical($bindings); $bindings = $this->canonical($bindings);
$sources = $request->items()->get()->keyBy('id'); $sources = $request->items()->get()->keyBy('id');
foreach ($additionalRequests as $additional) {
abort_unless($additional->tenant_id === $actor->tenant_id
&& Requisition::query()->visibleTo($actor)->whereKey($additional->id)->exists(), 403);
$sources = $sources->concat($additional->items()->get())->keyBy('id');
}
$frozen = []; $frozen = [];
$groups = []; $groups = [];
foreach ($bindings as $binding) { foreach ($bindings as $binding) {
+13 -2
View File
@@ -19,10 +19,21 @@ final class CommonBudget
public const ORDER_PARTS_CONTRACT = 'COMMON-BUDGET-ORDER-PARTS-QA-v1'; public const ORDER_PARTS_CONTRACT = 'COMMON-BUDGET-ORDER-PARTS-QA-v1';
public const LANDED_COSTS_CONTRACT = 'COMMON-BUDGET-LANDED-COST-QA-v2';
public function for(User $user): BudgetControl public function for(User $user): BudgetControl
{ {
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403); abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
$runtime = new \ReflectionClass(BudgetControl::class); $runtime = new \ReflectionClass(BudgetControl::class);
$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 (! $runtime->hasConstant('LANDED_COSTS_VERSION') || $runtime->getConstant('LANDED_COSTS_VERSION') !== self::LANDED_COSTS_CONTRACT
|| ! $runtime->hasMethod('reserveLandedCosts') || ! $runtime->hasMethod('transitionLandedCosts')) {
foreach ($landedPresent as $table) {
abort_if(DB::table($table)->where('tenant_id', $user->tenant_id)->exists(), 503, 'Existem efeitos de aterragem; preserve o motor compatível antes de consultar saldos.');
}
}
$orderTables = ['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions']; $orderTables = ['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions'];
$orderPresent = array_values(array_filter($orderTables, fn ($table) => Schema::hasTable($table))); $orderPresent = array_values(array_filter($orderTables, fn ($table) => Schema::hasTable($table)));
abort_if(count($orderPresent) !== 0 && count($orderPresent) !== count($orderTables), 503, abort_if(count($orderPresent) !== 0 && count($orderPresent) !== count($orderTables), 503,
@@ -53,8 +64,8 @@ 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.'); 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) $roles = in_array($action, ['create', 'approve', 'reinforcement.propose', 'reinforcement.review', 'view'], true)
? [PurchasingRole::Admin, PurchasingRole::Finance] ? [PurchasingRole::Admin, PurchasingRole::Finance]
: (in_array($action, ['consume', 'consume.preview', 'distribution.amend'], true) ? [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, ['orders.commit', 'orders.cancel', 'orders.adopt'], true) ? [PurchasingRole::Procurement] : null)); : (in_array($action, ['orders.commit', 'orders.adopt'], true) ? [PurchasingRole::Procurement] : null));
app(CurrentActor::class)->lock($user, $roles); app(CurrentActor::class)->lock($user, $roles);
}, },
function (string $action, array $data, ?int $origin) use ($user): void { function (string $action, array $data, ?int $origin) use ($user): void {
+98
View File
@@ -0,0 +1,98 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use LogicException;
/** Aggregate, bounded technical inspection; never repairs, discloses or removes evidence. */
final class ImportCostDocumentHealth
{
/** @return array<string,mixed> */
public function inspect(int $limit = 1000): array
{
abort_unless(app()->runningInConsole() && ! auth()->check() && ! request()->hasSession(), 403);
if ($limit < 1 || $limit > 10000) {
throw new LogicException('Limite fora do intervalo permitido.');
}
return DB::transaction(function () use ($limit): array {
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
}
$result = ['checked_at' => now()->toIso8601String(), 'ok' => false, 'complete' => false,
'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();
$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.'/';
$path = $evidence['path'] ?? null;
if (($evidence['disk'] ?? null) !== 'local' || ! is_string($path)
|| ! preg_match('/^[a-f0-9-]{36}$/D', $record->record_key)
|| ! preg_match('/^'.preg_quote($prefix.$record->record_key.'-'.$record->version, '/').'\.(pdf|jpg|jpeg|png)$/D', $path)
|| ! is_int($evidence['size'] ?? null) || $evidence['size'] < 1 || $evidence['size'] > 2097152
|| ! is_string($evidence['sha256'] ?? null) || ! preg_match('/^[a-f0-9]{64}$/D', $evidence['sha256'])
|| ! DB::table('purchase_orders')->where('tenant_id', $record->tenant_id)->where('id', $record->purchase_order_id)->exists()) {
$result['invalid_reference']++;
continue;
}
$resolved = realpath($disk->path($path));
if ($resolved === false || ! is_file($resolved)) {
$result['missing']++;
continue;
}
$absolute = str_replace('\\', '/', $resolved);
$boundary = $root === false ? null : str_replace('\\', '/', $root).'/import-costs/';
if ($boundary === null || ! (PHP_OS_FAMILY === 'Windows'
? str_starts_with(strtolower($absolute), strtolower($boundary)) : str_starts_with($absolute, $boundary))) {
$result['invalid_reference']++;
continue;
}
if (filesize($resolved) !== $evidence['size']) {
$result['altered']++;
continue;
}
$checksum = hash_file('sha256', $resolved);
if (! is_string($checksum) || ! hash_equals($evidence['sha256'], $checksum)) {
$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 (['missing', 'altered', 'invalid_reference', 'unreferenced'] as $reason) {
if ($result[$reason] > 0) {
$result['reasons'][] = $reason;
}
}
if ($limited) {
$result['reasons'][] = 'limit_reached';
}
$result['complete'] = ! $limited;
$result['ok'] = $result['reasons'] === [];
return $result;
});
}
}
+473
View File
@@ -0,0 +1,473 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\SupplyRecord;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetLandedCostPlan;
/** Versioned documentary cost preparation. Financial effects remain in the common writer. */
final class ImportLandedCosts
{
public function ready(): bool
{
$db = DB::connection();
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
return config('import-landed-costs.qa_enabled') === true && app()->environment('testing') && $isolated
&& class_exists(BudgetLandedCostPlan::class);
}
public function financialReady(): bool
{
$runtime = new \ReflectionClass(BudgetControl::class);
return $this->ready() && Schema::hasTable('budget_landed_commands') && Schema::hasTable('budget_landed_entries')
&& Schema::hasColumn('budget_landed_entries', 'source_snapshot')
&& $runtime->hasConstant('LANDED_COSTS_VERSION') && $runtime->getConstant('LANDED_COSTS_VERSION') === CommonBudget::LANDED_COSTS_CONTRACT
&& $runtime->hasMethod('reserveLandedCosts') && $runtime->hasMethod('transitionLandedCosts') && $runtime->hasMethod('amendLandedCosts');
}
/** @return array<string,mixed> */
public function workspace(User $actor, SupplyRecord $import, string $search = ''): array
{
abort_unless($this->ready(), 503);
return DB::transaction(function () use ($actor, $import, $search): array {
[$actor, $current, $order] = $this->context($actor, $import);
$invoices = Invoice::query()->where('status', 'validated')->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))
->when($search !== '', fn ($query) => $query->where('number', 'like', '%'.addcslashes($search, '%_\\').'%'))
->latest('id')->paginate(20, ['id', 'number', 'supplier_id', 'purchase_order_id', 'subtotal_minor', 'tax_minor', 'total_minor'], 'invoices_page')->withQueryString();
$invoices->through(fn (Invoice $invoice) => [...$invoice->only(['id', 'number', 'purchase_order_id', 'total_minor']),
'currency' => PurchaseOrder::query()->whereKey($invoice->purchase_order_id)->value('currency')]);
$documents = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)
->whereIn('id', SupplyRecord::query()->selectRaw('MAX(id)')->where('kind', 'import_cost_doc')->groupBy('record_key'))->latest('id')
->paginate(20, ['id', 'record_key', 'version', 'data', 'created_at'], 'documents_page')->withQueryString();
$budgets = DB::table('budgets')->where('tenant_id', $actor->tenant_id)->whereNotNull('approved_by')->where('year', now()->year)
->orderBy('id')->paginate(20, ['id', 'cost_center_id', 'kind', 'includes_tax'], 'budgets_page')->withQueryString();
$history = SupplyRecord::query()->where('kind', 'import_cost_plan')->where('purchase_order_id', $order->id)->latest('version')
->paginate(10, ['id', 'record_key', 'version', 'state', 'reason', 'created_by', 'created_at', 'data', 'snapshot'], 'history_page')->withQueryString();
$latest = SupplyRecord::query()->where('kind', 'import_cost_plan')->where('purchase_order_id', $order->id)->latest('version')->first();
$financialEvents = SupplyRecord::query()->where('kind', 'import_cost_event')->where('purchase_order_id', $order->id)->latest('version')
->paginate(10, ['id', 'version', 'state', 'reason', 'created_by', 'created_at', 'data', 'snapshot'], 'financial_events_page')->withQueryString();
$financial = null;
if ($latest !== null && $this->financialReady()) {
$engine = app(CommonBudget::class)->for($actor);
$state = app(CommonBudget::class)->execute(fn () => (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $latest->record_key));
$financial = is_array($state) ? $state['result'] : null;
if ($financial !== null) {
$financial['native_plan_id'] = SupplyRecord::query()->where('kind', 'import_cost_plan')->where('record_key', $latest->record_key)
->where('version', $financial['version'])->where('state', 'approved')->value('id');
foreach ($financial['origins'] as &$origin) {
$source = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)->whereKey($origin['id'])->firstOrFail();
abort_unless($source->version === $origin['source_version'], 503, 'Preserve a versão documental associada ao efeito financeiro.');
$origin['reference'] = $source->data['reference'];
$origin['evidence_url'] = '/compras/importacoes/'.$current->id.'/custos/documentos/'.$source->id;
}
unset($origin);
}
}
return ['importRecord' => ['id' => $current->id, 'record_key' => $current->record_key, 'version' => $current->version,
'order_id' => $order->id, 'order_number' => $order->number, 'context' => array_intersect_key($current->data, array_flip(['purpose', 'jurisdiction', 'origin_country', 'dispatch_country', 'incoterm', 'regime'])),
'context_changed' => $latest !== null && $this->preparationImportRevision($latest->snapshot['plan']) !== $this->importRevision($current)],
'importTariffs' => $order->snapshot['import_tariffs'] ?? [],
'invoices' => $invoices, 'documents' => $documents, 'budgets' => $budgets,
'history' => $history, 'latest' => $latest, 'financialReady' => $this->financialReady(), 'financialState' => $financial, 'financialEvents' => $financialEvents,
'orderItems' => $order->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity']),
'invoiceSearch' => $search, 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
});
}
public function evidence(User $actor, SupplyRecord $import, int $documentId): SupplyRecord
{
abort_unless($this->ready(), 503);
return DB::transaction(function () use ($actor, $import, $documentId): SupplyRecord {
[, $current, $order] = $this->context($actor, $import);
$document = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)->findOrFail($documentId);
abort_unless($document->snapshot['import_key'] === $current->record_key, 404);
$evidence = $document->snapshot['evidence'];
abort_unless(Storage::disk('local')->exists($evidence['path']) && hash_equals($evidence['sha256'], hash('sha256', Storage::disk('local')->get($evidence['path']))), 409, 'A evidência documental está indisponível ou alterada.');
return $document;
});
}
/** Native documentary source, not a supplier invoice or a payable.
* @param array<string,mixed> $input
*/
public function recordDocument(User $actor, SupplyRecord $import, array $input, UploadedFile $file): SupplyRecord
{
abort_unless($this->ready(), 503);
$data = Validator::make(['record_key' => null, 'version' => 0, ...$input, 'file' => $file], [
'operation_key' => 'required|uuid', 'kind' => 'required|in:customs_assessment,other_charge',
'record_key' => 'present|nullable|uuid', 'version' => 'required|integer|min:0',
'reference' => 'required|string|min:3|max:180', 'issued_on' => 'required|date_format:Y-m-d|before_or_equal:today',
'creditor_reference' => 'required|string|min:3|max:180', 'currency' => 'required|regex:/^[A-Z]{3}$/D',
'subtotal_minor' => 'required|integer|min:0|max:100000000000000', 'tax_minor' => 'required|integer|min:0|max:100000000000000',
'total_minor' => 'required|integer|min:0|max:100000000000000', 'exchange_basis' => 'present|nullable|array:rate,quoted_on,source',
'exchange_basis.rate' => ['required_unless:currency,MZN', 'regex:/^\d{1,8}(?:\.\d{1,10})?$/D'],
'exchange_basis.quoted_on' => 'required_unless:currency,MZN|date_format:Y-m-d|before_or_equal:today',
'exchange_basis.source' => 'required_unless:currency,MZN|string|min:3|max:1000',
'reason' => 'required|string|min:10|max:4000', 'file' => 'required|file|mimes:pdf,jpg,jpeg,png|extensions:pdf,jpg,jpeg,png|max:2048',
])->validate();
unset($data['file']);
// Multipart form fields arrive as strings; normalise only validated exact cent integers.
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
abort_unless(is_int($data[$field]) || (is_string($data[$field]) && preg_match('/^\d{1,15}$/D', $data[$field])), 422, 'Indique centavos inteiros, sem arredondamentos.');
$data[$field] = (int) $data[$field];
}
$data['operation_key'] = strtolower($data['operation_key']);
$sha = hash_file('sha256', $file->getPathname());
abort_unless(is_string($sha) && $file->getSize() > 0, 422);
$hash = hash('sha256', json_encode([$import->record_key, $data, $sha], JSON_THROW_ON_ERROR));
$newPath = null;
try {
return DB::transaction(function () use ($actor, $import, $data, $file, $sha, $hash, &$newPath): SupplyRecord {
[$actor, $current, $order] = $this->context($actor, $import);
$old = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
if ($old !== null) {
abort_unless($old->kind === 'import_cost_doc' && $old->created_by === $actor->id && hash_equals($old->input_hash, $hash), 409);
return $old;
}
$previous = $data['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_cost_doc')
->where('record_key', $data['record_key'])->latest('version')->lockForUpdate()->firstOrFail();
abort_unless((int) $data['version'] === ($previous->version ?? 0), 409, 'O documento mudou. Consulte a versão actual antes de corrigir.');
if ($previous !== null) {
abort_unless($previous->purchase_order_id === $order->id && $previous->snapshot['import_key'] === $current->record_key && $previous->data['kind'] === $data['kind'], 409, 'A correcção deve conservar a origem e o tipo documental.');
abort_unless($previous->data['currency'] === $data['currency'] && $previous->data['exchange_basis'] === $data['exchange_basis'], 409, 'A correcção conserva a moeda e a taxa de Finanças já congeladas nesta origem.');
}
abort_if(SupplyRecord::query()->where('kind', 'import_cost_doc')
->when($previous !== null, fn ($query) => $query->where('record_key', '!=', $previous->record_key))
->where('data->kind', $data['kind'])->where('data->creditor_reference', $data['creditor_reference'])
->where('data->reference', $data['reference'])->exists(), 409, 'A origem documental já foi registada. Preserve a referência existente.');
$reference = $this->reference($data);
$recordKey = $previous->record_key ?? (string) Str::uuid();
$version = ($previous->version ?? 0) + 1;
$newPath = $file->storeAs('import-costs/'.$actor->tenant_id.'/'.$order->id, $recordKey.'-'.$version.'.'.$file->extension(), 'local');
abort_unless(is_string($newPath), 503, 'Não foi possível conservar o documento privado.');
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_cost_doc', 'record_key' => $recordKey,
'version' => $version, 'state' => 'recorded', 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
'data' => array_diff_key($data, array_flip(['operation_key', 'reason', 'record_key', 'version'])),
'snapshot' => ['import_key' => $current->record_key, 'import_version' => $current->version, 'reference_amounts' => $reference,
'exchange_basis_recorded_by' => $previous->snapshot['exchange_basis_recorded_by'] ?? $actor->id,
'supersedes' => $previous->id ?? null, 'contributors' => array_values(array_unique([...($previous?->snapshot['contributors'] ?? []), $actor->id])),
'evidence' => ['disk' => 'local', 'path' => $newPath, 'sha256' => $sha, 'size' => $file->getSize(), 'mime_type' => $file->getMimeType()],
'financial_effects' => false, 'legal_rate_verified' => false],
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'import.cost_document_recorded', Requisition::query()->findOrFail($order->requisition_id), null,
['record_id' => $record->id, 'import_key' => $current->record_key, 'sha256' => $sha, 'financial_effects' => false]);
return $record;
});
} catch (\Throwable $error) {
if (is_string($newPath) && ! SupplyRecord::query()->where('kind', 'import_cost_doc')->where('snapshot->evidence->path', $newPath)->exists()) {
Storage::disk('local')->delete($newPath);
}
throw $error;
}
}
/** @param array<string,mixed> $input
* @return array<string,mixed>
*/
public function preview(User $actor, SupplyRecord $import, array $input): array
{
abort_unless($this->ready(), 503);
$data = Validator::make($input, ['documents' => 'required|array|min:1|max:100', 'documents.*' => 'required|array:origin,kind,id',
'documents.*.origin' => 'required|string|regex:/^[A-Za-z0-9:_-]{1,120}$/D|distinct',
'documents.*.kind' => 'required|in:supplier_invoice,carrier_invoice,insurer_invoice,customs_assessment,other_charge',
'documents.*.id' => 'required|integer|min:1', 'components' => 'required|array|min:1|max:500', 'budget_id' => 'required|integer|min:1',
'item_references' => 'sometimes|array|list|max:500',
'item_references.*' => 'required|array:component_key,purchase_order_item_ids',
'item_references.*.component_key' => 'required|string|max:120|distinct',
'item_references.*.purchase_order_item_ids' => 'required|array|list|min:1|max:100',
'item_references.*.purchase_order_item_ids.*' => 'required|integer|min:1'])->validate();
return DB::transaction(function () use ($actor, $import, $data): array {
[$actor, $current, $order] = $this->context($actor, $import);
$budget = DB::table('budgets')->where('tenant_id', $actor->tenant_id)->where('id', $data['budget_id'])->lockForUpdate()->first();
abort_unless($budget !== null && $budget->approved_by !== null && (int) $budget->year === (int) now()->year, 422, 'Seleccione uma dotação aprovada do exercício.');
$documents = $details = [];
foreach ($data['documents'] as $selection) {
if (in_array($selection['kind'], ['supplier_invoice', 'carrier_invoice', 'insurer_invoice'], true)) {
$invoice = Invoice::query()->whereKey($selection['id'])->lockForUpdate()->firstOrFail();
abort_unless($invoice->status === 'validated', 409, 'A factura de origem ainda não foi validada.');
$sourceOrder = PurchaseOrder::query()->visibleTo($actor)->findOrFail($invoice->purchase_order_id);
app(OrderPartsAccess::class)->assertProcess($actor, $sourceOrder);
abort_if($selection['kind'] === 'supplier_invoice' && $sourceOrder->id !== $order->id, 422, 'A mercadoria deve pertencer à ordem da importação.');
$native = ['currency' => $sourceOrder->currency, 'subtotal_minor' => $invoice->subtotal_minor, 'tax_minor' => $invoice->tax_minor,
'total_minor' => $invoice->total_minor, 'exchange_basis' => $invoice->snapshot['exchange_basis'] ?? null];
$reference = $this->reference($native);
$revision = hash('sha256', json_encode($invoice->getAttributes(), JSON_THROW_ON_ERROR));
$creditor = 'supplier:'.$invoice->supplier_id;
$sourceKey = 'invoice:'.$invoice->id;
$sourceVersion = 1;
$details[$selection['origin']] = ['reference' => $invoice->number, 'creditor' => $invoice->snapshot['supplier']['name'],
'currency' => $native['currency'], 'exchange_basis' => $native['exchange_basis'], 'financial_authority' => 'native_invoice'];
} else {
$document = SupplyRecord::query()->where('kind', 'import_cost_doc')->where('purchase_order_id', $order->id)->whereKey($selection['id'])->firstOrFail();
abort_unless($document->data['kind'] === $selection['kind'] && $document->snapshot['import_key'] === $current->record_key, 409);
abort_unless(SupplyRecord::query()->where('kind', 'import_cost_doc')->where('record_key', $document->record_key)->latest('version')->value('id') === $document->id, 409, 'O documento foi corrigido. Seleccione a nova versão, preservando a preparação anterior.');
$native = $document->data;
$reference = $document->snapshot['reference_amounts'];
$evidence = $document->snapshot['evidence'];
abort_unless(Storage::disk('local')->exists($evidence['path']) && hash_equals($evidence['sha256'], hash('sha256', Storage::disk('local')->get($evidence['path']))), 409, 'A evidência documental está indisponível ou alterada.');
$revision = $document->input_hash;
$creditor = 'authority:'.hash('sha256', $native['creditor_reference']);
$sourceKey = $document->record_key;
$sourceVersion = $document->version;
$details[$selection['origin']] = ['reference' => $native['reference'], 'creditor' => $native['creditor_reference'],
'currency' => $native['currency'], 'exchange_basis' => $native['exchange_basis'], 'financial_authority' => 'documentary_source_only'];
}
$documents[$selection['origin']] = ['kind' => $selection['kind'], 'id' => (int) $selection['id'], 'creditor_key' => $creditor,
'source_key' => $sourceKey, 'source_version' => $sourceVersion,
'currency' => $native['currency'], 'revision' => $revision, 'subtotal_minor' => $native['subtotal_minor'], 'tax_minor' => $native['tax_minor'], 'total_minor' => $native['total_minor'],
'reference_subtotal_minor' => $reference['subtotal_minor'], 'reference_tax_minor' => $reference['tax_minor'], 'reference_total_minor' => $reference['total_minor']];
}
$plan = app(CommonBudget::class)->execute(fn () => BudgetLandedCostPlan::reconcile($data['components'], $documents, (bool) $budget->includes_tax));
$items = $order->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity'])->keyBy('id');
$references = [];
foreach ($data['item_references'] ?? [] as $selection) {
abort_unless(in_array($selection['component_key'], array_column($plan['components'], 'component_key'), true), 422, 'A referência exige um componente da preparação.');
$ids = array_map(intval(...), $selection['purchase_order_item_ids']);
abort_unless(count(array_unique($ids)) === count($ids), 422, 'Não repita o mesmo artigo no componente.');
sort($ids, SORT_NUMERIC);
foreach ($ids as $id) {
abort_unless($items->has($id), 422, 'Seleccione apenas artigos da ordem desta importação.');
$references[$selection['component_key']][] = $items->get($id)->only(['id', 'description', 'unit', 'quantity']);
}
}
ksort($references);
return [...$plan, 'budget_id' => $budget->id, 'import_key' => $current->record_key, 'import_version' => $current->version,
'import_revision' => $this->importRevision($current),
'item_references' => $references,
'purchase_order_id' => $order->id, 'document_details' => $details, 'native_principals_preserved' => true];
});
}
/** Persist a recoverable preparation; independent review does not execute budget effects.
* @param array<string,mixed> $input
*/
public function save(User $actor, SupplyRecord $import, array $input): SupplyRecord
{
abort_unless($this->ready(), 503);
$envelope = Validator::make($input, ['operation_key' => 'required|uuid', 'record_key' => 'present|nullable|uuid',
'version' => 'required|integer|min:0', 'action' => 'required|in:save,approve,return',
'reason' => 'required|string|min:10|max:4000', 'data' => 'present|array'])->validate();
$envelope['operation_key'] = strtolower($envelope['operation_key']);
$hash = hash('sha256', json_encode([$import->record_key, $import->version, $envelope], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $import, $envelope, $hash): SupplyRecord {
[$actor, $current, $order] = $this->context($actor, $import);
$replay = SupplyRecord::query()->where('operation_key', $envelope['operation_key'])->first();
if ($replay !== null) {
abort_unless($replay->kind === 'import_cost_plan' && $replay->created_by === $actor->id && hash_equals($replay->input_hash, $hash), 409);
return $replay;
}
$old = $envelope['record_key'] === null ? null : SupplyRecord::query()->where('kind', 'import_cost_plan')
->where('record_key', $envelope['record_key'])->latest('version')->lockForUpdate()->firstOrFail();
abort_unless((int) $envelope['version'] === ($old->version ?? 0), 409, 'A preparação mudou. Conserve os seus valores e consulte a versão actual.');
if ($old !== null) {
abort_unless($old->purchase_order_id === $order->id && $old->snapshot['import_key'] === $current->record_key, 409);
} else {
abort_if(SupplyRecord::query()->where('kind', 'import_cost_plan')->where('purchase_order_id', $order->id)->exists(), 409, 'A importação já tem uma preparação. Continue a versão existente.');
}
$action = $envelope['action'];
if ($action === 'save') {
$selection = $envelope['data'];
$plan = $this->preview($actor, $current, $selection);
$contributors = array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id]));
foreach ($selection['documents'] as $document) {
if (in_array($document['kind'], ['customs_assessment', 'other_charge'], true)) {
$source = SupplyRecord::query()->where('kind', 'import_cost_doc')->whereKey($document['id'])->sole();
$contributors = [...$contributors, ...$source->snapshot['contributors']];
}
}
$contributors = array_values(array_unique($contributors));
$state = 'draft';
} else {
abort_unless($old !== null && $old->state === 'draft' && $envelope['data'] === [], 409, 'A conferência exige uma preparação actual sem alterar o seu conteúdo.');
$contributors = $old->snapshot['contributors'];
abort_if(in_array($actor->id, $contributors, true), 403, 'A conferência exige Finanças independente da preparação e dos documentos adicionais.');
$selection = $old->data;
$plan = $action === 'return' ? $old->snapshot['plan'] : $this->preview($actor, $current, $selection);
abort_unless($action === 'return' || $this->equivalentPreparation($plan, $old->snapshot['plan']), 409, 'As origens ou a dotação mudaram. Devolva e actualize a preparação.');
$state = $action === 'approve' ? 'approved' : 'returned';
}
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_cost_plan',
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
'state' => $state, 'purchase_order_id' => $order->id, 'created_by' => $actor->id, 'data' => $selection,
'snapshot' => ['import_key' => $current->record_key, 'contributors' => $contributors, 'plan' => $plan, 'financial_effects' => false],
'reason' => $envelope['reason'], 'operation_key' => $envelope['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'import.cost_plan_'.$action, Requisition::query()->findOrFail($order->requisition_id), null,
['record_id' => $record->id, 'record_key' => $record->record_key, 'version' => $record->version, 'state' => $state, 'fingerprint' => $plan['fingerprint'], 'financial_effects' => false]);
return $record;
});
}
/** One native receipt around one common financial command.
* @param array<string,mixed> $input
*/
public function financial(User $actor, SupplyRecord $import, SupplyRecord $plan, array $input): SupplyRecord
{
abort_unless($this->financialReady(), 503, 'A estrutura financeira adicional só está preparada em QA.');
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'action' => 'required|in:reserve,commit,consume,amend,cancel',
'financial_revision' => 'required|integer|min:0', 'sources' => 'sometimes|array|max:100',
'sources.*' => 'required|string|max:120|distinct|regex:/^[A-Za-z0-9:_-]+$/D',
'reason' => 'required|string|min:10|max:4000'])->validate();
$data['operation_key'] = strtolower($data['operation_key']);
$data['financial_revision'] = (int) $data['financial_revision'];
$data['sources'] ??= [];
sort($data['sources'], SORT_STRING);
$hash = hash('sha256', json_encode([$import->record_key, $plan->id, $data], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $import, $plan, $data, $hash): SupplyRecord {
[$actor, $current, $order] = $this->context($actor, $import);
$plan = SupplyRecord::query()->where('kind', 'import_cost_plan')->whereKey($plan->id)->lockForUpdate()->firstOrFail();
abort_unless($plan->purchase_order_id === $order->id && $plan->snapshot['import_key'] === $current->record_key, 404);
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
if ($retry !== null) {
abort_unless($retry->kind === 'import_cost_event' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
return $retry;
}
abort_unless($plan->state === 'approved', 409, 'A aplicação financeira exige conferência independente da preparação.');
if ($data['action'] !== 'cancel') {
abort_unless(SupplyRecord::query()->where('kind', 'import_cost_plan')->where('record_key', $plan->record_key)->latest('version')->value('id') === $plan->id, 409, 'Existe uma nova preparação; conclua a sua revisão antes de movimentar.');
abort_unless($this->equivalentPreparation($this->preview($actor, $current, $plan->data), $plan->snapshot['plan']), 409, 'As origens documentais mudaram. Prepare e confira uma nova versão.');
}
$adapter = app(CommonBudget::class);
$engine = $adapter->for($actor);
$state = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'landedCostState'))->invoke($engine, $plan->record_key));
abort_unless($data['financial_revision'] === (is_array($state) ? $state['result']['revision'] : 0), 409, 'A posição orçamental mudou; conserve a preparação e actualize antes de continuar.');
abort_unless(! in_array($data['action'], ['reserve', 'amend'], true) || $data['sources'] === [], 422, 'A reserva e a reafectação usam a preparação conferida completa.');
$args = [$plan->record_key, $plan->version, $plan->snapshot['plan']['budget_id'], $plan->data['components'], $plan->snapshot['plan']['documents'], $data['operation_key']];
$method = 'reserveLandedCosts';
if ($data['action'] !== 'reserve') {
abort_unless(is_array($state), 409, 'Registe primeiro a reserva adicional.');
if ($data['action'] === 'amend') {
abort_unless($state['result']['budget_id'] === $plan->snapshot['plan']['budget_id'], 409, 'A reafectação desta versão conserva a dotação e a sua base de imposto.');
$method = 'amendLandedCosts';
$args = [$plan->record_key, $state['result']['version'], $state['result']['plan_hash'], $plan->version,
$plan->data['components'], $plan->snapshot['plan']['documents'], $data['operation_key'], $data['financial_revision']];
} else {
abort_unless($data['action'] === 'cancel' || ($state['result']['version'] === $plan->version && $state['result']['plan_hash'] === $plan->snapshot['plan']['fingerprint']), 409, 'Aplique a alteração documental aprovada antes de continuar.');
$method = 'transitionLandedCosts';
$args = [$plan->record_key, $state['result']['version'], $state['result']['plan_hash'], $data['action'], $data['operation_key'], $data['sources'], $data['financial_revision']];
}
}
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, $method))->invoke($engine, ...$args));
abort_unless(is_array($result), 503, 'Recibo financeiro incompatível; operação não concluída.');
$version = (int) SupplyRecord::query()->where('kind', 'import_cost_event')->where('record_key', $plan->record_key)->max('version') + 1;
$event = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_cost_event', 'record_key' => $plan->record_key,
'version' => $version, 'state' => $result['phase'], 'purchase_order_id' => $order->id, 'created_by' => $actor->id,
'data' => ['action' => $data['action'], 'approved_preparation_id' => $plan->id, 'financial_plan_version' => $result['version']],
'snapshot' => ['import_key' => $current->record_key, 'common_result' => $result, 'actor' => $actor->only(['id', 'name'])],
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
return $event;
});
}
/** @return array{User,SupplyRecord,PurchaseOrder} */
private function context(User $actor, SupplyRecord $import): array
{
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Finance]);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
$current = SupplyRecord::query()->where('kind', 'import')->where('record_key', $import->record_key)->latest('version')->lockForUpdate()->firstOrFail();
abort_unless($current->id === $import->id, 409, 'O processo de importação mudou. Consulte a versão actual.');
$order = PurchaseOrder::query()->visibleTo($actor)->lockForUpdate()->findOrFail($current->purchase_order_id);
app(OrderPartsAccess::class)->assertProcess($actor, $order);
return [$actor, $current, $order];
}
private function importRevision(SupplyRecord $import): string
{
$context = ['purchase_order_id' => $import->purchase_order_id];
foreach (['purpose', 'jurisdiction', 'origin_country', 'dispatch_country', 'incoterm', 'regime'] as $field) {
$context[$field] = $import->data[$field] ?? null;
}
return hash('sha256', json_encode($context, JSON_THROW_ON_ERROR));
}
/** Logistics events do not revoke accepted financial sources.
* @param array<string,mixed> $fresh
* @param array<string,mixed> $frozen
*/
private function equivalentPreparation(array $fresh, array $frozen): bool
{
$frozen['import_revision'] = $this->preparationImportRevision($frozen);
$frozen['item_references'] ??= [];
if ($frozen['import_revision'] === null) {
return false;
}
unset($fresh['import_version'], $frozen['import_version']);
// Key order is presentation, not a financial source change.
ksort($fresh);
ksort($frozen);
return $fresh === $frozen;
}
/** @param array<string,mixed> $plan */
private function preparationImportRevision(array $plan): ?string
{
if (isset($plan['import_revision'])) {
return $plan['import_revision'];
}
$historical = SupplyRecord::query()->where('kind', 'import')->where('record_key', $plan['import_key'])
->where('version', $plan['import_version'])->first();
return $historical === null ? null : $this->importRevision($historical);
}
/** @param array<string,mixed> $document
* @return array{subtotal_minor:int,tax_minor:int,total_minor:int}
*/
private function reference(array $document): array
{
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
abort_unless(is_int($document[$field]) && $document[$field] >= 0 && $document[$field] <= 100000000000000, 422, 'Indique montantes documentais inteiros em centavos.');
}
abort_unless($document['subtotal_minor'] <= $document['total_minor'] && $document['tax_minor'] === $document['total_minor'] - $document['subtotal_minor'], 422, 'Os valores documentais não reconciliam.');
$basis = $document['exchange_basis'];
if ($document['currency'] === 'MZN') {
abort_unless($basis === null, 422, 'Documentos MZN conservam os valores nativos.');
return array_intersect_key($document, array_flip(['subtotal_minor', 'tax_minor', 'total_minor']));
}
abort_unless(is_array($basis) && is_string($basis['rate'] ?? null) && is_string($basis['quoted_on'] ?? null)
&& is_string($basis['source'] ?? null) && trim($basis['source']) !== '', 422, 'Conserve a taxa, data e fonte explícitas de Finanças.');
try {
$subtotal = app(QuotationExchange::class)->convert($document['subtotal_minor'], $basis['rate']);
$tax = app(QuotationExchange::class)->convert($document['tax_minor'], $basis['rate']);
} catch (\InvalidArgumentException) {
abort(422, 'Montante ou taxa de câmbio não representável.');
}
abort_if($subtotal > 100000000000000 - $tax, 422, 'Total convertido não representável.');
return ['subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax];
}
}
+171
View File
@@ -0,0 +1,171 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\Requisition;
use App\Models\RequisitionItem;
use App\Models\StockItem;
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;
/** Documentary classification only. No tariff, exemption or financial calculation is activated. */
final class ImportTariffCodes
{
/** Freeze classifications only for explicitly marked imported lines; never rewrite an existing order.
* @param list<int> $itemIds
* @return array<int,array<string,mixed>>
*/
public function freezeForItems(User $actor, array $itemIds): array
{
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
if (! Schema::hasTable('supply_records')) {
return [];
}
$records = app(SupplyPlanning::class)->latest('import_tariff')->whereIn('data->requisition_item_id', $itemIds)->get();
if ($records->isEmpty()) {
return [];
}
abort_unless($this->ready(), 503, 'Preserve a capacidade de classificação dos artigos importados antes de emitir uma nova ordem.');
$result = [];
foreach ($records as $record) {
$item = RequisitionItem::query()->whereKey($record->data['requisition_item_id'])->firstOrFail();
Requisition::query()->visibleTo($actor)->whereKey($item->requisition_id)->firstOrFail();
abort_unless($record->state === 'confirmed' && $record->snapshot['item'] === $item->only(['id', 'description', 'unit', 'quantity']), 409,
'Confirme a classificação pautal actual de cada artigo importado antes de emitir a ordem.');
$result[$item->id] = ['record_id' => $record->id, 'version' => $record->version,
'requisition_item_id' => $item->id, 'item' => $record->snapshot['item'], 'data' => $record->data,
'source' => $record->snapshot['master'] ?? null, 'confirmed_by' => $record->snapshot['confirmed_by'], 'reason' => $record->reason];
}
ksort($result, SORT_NUMERIC);
return $result;
}
public function ready(): bool
{
$db = DB::connection();
return config('import-tariffs.qa_enabled') === true && app()->environment('testing')
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
}
/** @return array<string,mixed> */
public function workspace(User $actor, Requisition $request, string $search = ''): array
{
return DB::transaction(function () use ($actor, $request, $search): array {
[$actor, $request] = $this->context($actor, $request);
$materialsVisible = $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance]);
$history = SupplyRecord::query()->where('kind', 'import_tariff')->where('data->requisition_id', $request->id)
->latest('id')->paginate(20, ['id', 'version', 'state', 'reason', 'data', 'snapshot', 'created_at'], 'tariff_history_page')->withQueryString();
$latest = app(SupplyPlanning::class)->latest('import_tariff')->where('data->requisition_id', $request->id)
->get(['id', 'record_key', 'version', 'state', 'reason', 'data', 'snapshot']);
$stockItems = StockItem::query()->when(! $materialsVisible, fn ($q) => $q->whereRaw('1 = 0'))->when($search !== '', fn ($q) => $q->where(fn ($match) => $match
->where('code', 'like', '%'.addcslashes($search, '%_\\').'%')->orWhere('name', 'like', '%'.addcslashes($search, '%_\\').'%')))
->orderBy('id')->paginate(20, ['id', 'code', 'name', 'unit'], 'stock_page')->withQueryString();
$stockItems->through(fn ($item) => [...$item->only(['id', 'code', 'name', 'unit']),
'tariff' => app(SupplyPlanning::class)->latest('stock_tariff')->where('stock_item_id', $item->id)->first(['id', 'version', 'data'])]);
return ['requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description', 'unit', 'quantity']),
'latest' => $latest, 'history' => $history, 'stockItems' => $stockItems, 'canPropose' => ($actor->id === $request->requester_id && app(OrganizationAccess::class)->canRequest($actor)) || $actor->hasFunctions([PurchasingRole::Procurement]),
'canConfirm' => $actor->hasFunctions([PurchasingRole::Procurement]),
'masters' => app(SupplyPlanning::class)->latest('stock_tariff')->when(! $materialsVisible, fn ($q) => $q->whereRaw('1 = 0'))->whereIn('stock_item_id', StockItem::query()->select('id'))
->when($search !== '', fn ($q) => $q->whereRaw("LOWER(data->>'code') LIKE ? ESCAPE '!'", ['%'.str_replace(['!', '%', '_'], ['!!', '!%', '!_'], mb_strtolower($search)).'%']))
->latest('id')->paginate(20, ['id', 'version', 'stock_item_id', 'data', 'snapshot'], 'masters_page')->withQueryString(),
'masterSearch' => $search, 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
});
}
/** @param array<string,mixed> $input */
public function save(User $actor, Requisition $request, array $input): SupplyRecord
{
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'action' => 'required|in:master,propose,confirm',
'version' => 'required|integer|min:0', 'reason' => 'required|string|min:10|max:4000',
'stock_item_id' => 'required_if:action,master|nullable|integer|min:1', 'requisition_item_id' => 'required_unless:action,master|nullable|integer|min:1',
'master_id' => 'nullable|integer|min:1', 'code' => 'required_unless:action,propose|nullable|string|max:40|not_regex:/[\x00-\x1F\x7F]/',
'source_reference' => 'required_unless:action,propose|nullable|string|max:2000'])->validate();
$data['operation_key'] = strtolower($data['operation_key']);
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $request, $data, $hash): SupplyRecord {
[$actor, $request] = $this->context($actor, $request);
$buyer = $actor->hasFunctions([PurchasingRole::Procurement]);
abort_unless($buyer || ($data['action'] === 'propose' && $actor->id === $request->requester_id && app(OrganizationAccess::class)->canRequest($actor)), 403);
app(ConflictGuard::class)->assertParticipation($actor, $request);
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
if ($retry !== null) {
abort_unless($retry->created_by === $actor->id && in_array($retry->kind, ['stock_tariff', 'import_tariff'], true) && hash_equals($retry->input_hash, $hash), 409);
return $retry;
}
$code = trim($data['code'] ?? '');
$source = trim($data['source_reference'] ?? '');
$snapshot = ['calculations_activated' => false, 'legal_validity_certified' => false];
if ($data['action'] === 'master') {
abort_unless($code !== '' && $source !== '' && empty($data['requisition_item_id']) && empty($data['master_id']), 422, 'Indique código e fonte do cadastro do material.');
$item = StockItem::query()->whereKey($data['stock_item_id'] ?? null)->firstOrFail();
$kind = 'stock_tariff';
$old = app(SupplyPlanning::class)->latest($kind)->where('stock_item_id', $item->id)->first();
$payload = ['code' => $code, 'source_reference' => $source];
$snapshot['item'] = $item->only(['id', 'code', 'name', 'unit']);
$state = 'recorded';
} else {
abort_if(! empty($data['stock_item_id']), 422);
$item = $request->items()->whereKey($data['requisition_item_id'] ?? null)->firstOrFail();
$kind = 'import_tariff';
$old = app(SupplyPlanning::class)->latest($kind)->where('data->requisition_item_id', $item->id)->first();
$snapshot['item'] = $item->only(['id', 'description', 'unit', 'quantity']);
if ($data['action'] === 'propose') {
$payload = ['requisition_id' => $request->id, 'requisition_item_id' => $item->id,
'proposed_code' => $code === '' ? null : $code, 'source_reference' => $source === '' ? null : $source];
if (! empty($data['master_id'])) {
abort_unless($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance]), 403);
$master = SupplyRecord::query()->where('kind', 'stock_tariff')->whereKey($data['master_id'])->firstOrFail();
$currentMaster = app(SupplyPlanning::class)->latest('stock_tariff')->where('stock_item_id', $master->stock_item_id)->firstOrFail();
$material = StockItem::query()->whereKey($master->stock_item_id)->firstOrFail();
abort_unless($currentMaster->id === $master->id && $material->only(['id', 'code', 'name', 'unit']) === $master->snapshot['item'], 409, 'O cadastro do material mudou. Seleccione a versão actual.');
abort_unless($code === $master->data['code'] && $source === $master->data['source_reference'], 409, 'Aplique explicitamente o código e a fonte do cadastro ou conserve uma proposta manual.');
$snapshot['master'] = ['id' => $master->id, 'version' => $master->version, 'item' => $master->snapshot['item']];
}
$state = 'proposed';
} else {
abort_unless($old !== null && $old->state === 'proposed' && empty($data['master_id']) && $code !== '' && $source !== '', 409, 'Seleccione uma proposta actual e indique código e fonte da confirmação.');
abort_unless($old->snapshot['item'] === $snapshot['item'], 409, 'O artigo mudou. Prepare uma proposta actual.');
$payload = [...$old->data, 'confirmed_code' => $code, 'confirmation_source' => $source,
'deviation' => $code !== $old->data['proposed_code'], 'confirmed_by' => $actor->id];
$snapshot = [...$old->snapshot, 'confirmed_by' => ['id' => $actor->id, 'name' => $actor->name]];
$state = 'confirmed';
}
}
abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A classificação mudou. Preserve os seus valores e consulte a versão actual.');
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => $kind,
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
'stock_item_id' => $kind === 'stock_tariff' ? $item->id : null, 'state' => $state,
'created_by' => $actor->id, 'data' => $payload, 'snapshot' => $snapshot,
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'import.tariff_'.$data['action'], $kind === 'stock_tariff' ? null : $request, null,
['record_id' => $record->id, 'version' => $record->version, 'state' => $state, 'calculations_activated' => false]);
return $record;
});
}
/** @return array{User,Requisition} */
private function context(User $actor, Requisition $request): array
{
abort_unless($this->ready(), 503);
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
abort_unless(app(OrganizationAccess::class)->permissions($actor) !== [], 403);
$request = Requisition::query()->visibleTo($actor)->findOrFail($request->id);
return [$actor, $request];
}
}
@@ -22,6 +22,9 @@ class InvoiceBudgetDistributions
*/ */
public function prepare(User $actor, Invoice $invoice, PurchaseOrder $order, array $input, array $nativeLines): array public function prepare(User $actor, Invoice $invoice, PurchaseOrder $order, array $input, array $nativeLines): array
{ {
if (OrderPartsAccess::applies($order)) {
return app(OrderPartsInvoices::class)->prepare($actor, $invoice, $order, $input, $nativeLines);
}
$host = app(RequisitionBudgetDistributions::class); $host = app(RequisitionBudgetDistributions::class);
abort_unless($host->ready() && DB::transactionLevel() > 0, 503); abort_unless($host->ready() && DB::transactionLevel() > 0, 503);
abort_unless(auth()->id() === $actor->id && $actor->hasFunctions([PurchasingRole::Finance]) abort_unless(auth()->id() === $actor->id && $actor->hasFunctions([PurchasingRole::Finance])
@@ -84,6 +87,9 @@ class InvoiceBudgetDistributions
*/ */
public function consume(User $actor, Invoice $invoice, PurchaseOrder $order, array $reference): array public function consume(User $actor, Invoice $invoice, PurchaseOrder $order, array $reference): array
{ {
if (OrderPartsAccess::applies($order)) {
return app(OrderPartsInvoices::class)->consume($actor, $invoice, $order);
}
abort_unless(app(RequisitionBudgetDistributions::class)->ready() && DB::transactionLevel() > 0, 503); abort_unless(app(RequisitionBudgetDistributions::class)->ready() && DB::transactionLevel() > 0, 503);
$plan = $invoice->snapshot['budget_distribution'] ?? null; $plan = $invoice->snapshot['budget_distribution'] ?? null;
if (! is_array($plan) || $plan['revision'] !== $this->revision($invoice, $order) || $plan['reference'] !== $reference) { if (! is_array($plan) || $plan['revision'] !== $this->revision($invoice, $order) || $plan['reference'] !== $reference) {
+11 -3
View File
@@ -33,7 +33,7 @@ class InvoiceWorkflow
if ($invoice->status !== 'pending' || ! $this->reviewerBaseEligible($user, $invoice)) { if ($invoice->status !== 'pending' || ! $this->reviewerBaseEligible($user, $invoice)) {
return false; return false;
} }
$order = PurchaseOrder::query()->whereKey($invoice->purchase_order_id)->first(); $order = PurchaseOrder::query()->visibleTo($user)->whereKey($invoice->purchase_order_id)->first();
if ($order === null) { if ($order === null) {
return false; return false;
} }
@@ -76,10 +76,12 @@ class InvoiceWorkflow
$this->invalid('Preço, unidade e IVA devem coincidir exactamente com a ordem. Não há tolerância ou excepção configurada.'); $this->invalid('Preço, unidade e IVA devem coincidir exactamente com a ordem. Não há tolerância ou excepção configurada.');
} }
// Cumulative rounding ensures partial invoices sum exactly to the frozen order. // Cumulative rounding ensures partial invoices sum exactly to the frozen order.
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, (int) $previous, $quantity); $offset = $source->getAttribute('quantity_offset_milli') ?? 0;
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, $offset + (int) $previous, $quantity);
$lines[] = ['tenant_id' => $order->tenant_id, 'purchase_order_item_id' => $source->id, 'quantity_milli' => $quantity, $lines[] = ['tenant_id' => $order->tenant_id, 'purchase_order_item_id' => $source->id, 'quantity_milli' => $quantity,
'subtotal_minor' => $amounts['subtotal_minor'], 'tax_minor' => $amounts['tax_minor'], 'subtotal_minor' => $amounts['subtotal_minor'], 'tax_minor' => $amounts['tax_minor'],
'snapshot' => $source->only(['description', 'unit', 'unit_price_minor', 'tax_rate'])]; 'snapshot' => [...$source->only(['description', 'unit', 'unit_price_minor', 'tax_rate']),
...($source->getAttribute('quantity_offset_milli') === null ? [] : ['quantity_offset_milli' => $offset])]];
} }
if ($lines === []) { if ($lines === []) {
$this->invalid('Indique pelo menos uma linha.'); $this->invalid('Indique pelo menos uma linha.');
@@ -99,6 +101,9 @@ class InvoiceWorkflow
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Finance]); $user = app(CurrentActor::class)->lock($user, [PurchasingRole::Finance]);
$this->access($user); $this->access($user);
$order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id); $order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id);
if (OrderPartsAccess::applies($order)) {
app(OrderPartsAccess::class)->assertProcess($user, $order);
}
app(OrderCancellationWorkflow::class)->assertOperational($order); app(OrderCancellationWorkflow::class)->assertOperational($order);
$request = Requisition::query()->findOrFail($order->requisition_id); $request = Requisition::query()->findOrFail($order->requisition_id);
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user); app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user);
@@ -147,6 +152,9 @@ class InvoiceWorkflow
return; return;
} }
$order = PurchaseOrder::query()->lockForUpdate()->findOrFail($invoice->purchase_order_id); $order = PurchaseOrder::query()->lockForUpdate()->findOrFail($invoice->purchase_order_id);
if (OrderPartsAccess::applies($order)) {
app(OrderPartsAccess::class)->assertProcess($user, $order);
}
$request = Requisition::query()->findOrFail($order->requisition_id); $request = Requisition::query()->findOrFail($order->requisition_id);
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user); app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user);
if (substr((string) $invoice->issued_on, 0, 4) !== now()->format('Y')) { if (substr((string) $invoice->issued_on, 0, 4) !== now()->format('Y')) {
+1
View File
@@ -18,6 +18,7 @@ class OperationalHealth
$checks = []; $checks = [];
$startedAt = now()->toIso8601String(); $startedAt = now()->toIso8601String();
foreach (['replenishment' => fn () => app(ReplenishmentQueue::class)->health(), foreach (['replenishment' => fn () => app(ReplenishmentQueue::class)->health(),
'import_cost_documents' => fn () => app(ImportCostDocumentHealth::class)->inspect($documentLimit),
'receipt_documents' => fn () => app(ReceiptDocumentHealth::class)->inspect($documentLimit)] as $key => $read) { 'receipt_documents' => fn () => app(ReceiptDocumentHealth::class)->inspect($documentLimit)] as $key => $read) {
try { try {
$result = $read(); $result = $read();
+78 -13
View File
@@ -27,7 +27,8 @@ class OrderCancellationWorkflow
} }
$order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id); $order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id);
return $order && Requisition::query()->whereKey($order->requisition_id)->where('requester_id', $actor->id)->where('department_id', $actor->department_id)->exists(); return $order && ! OrderPartsAccess::applies($order)
&& Requisition::query()->whereKey($order->requisition_id)->where('requester_id', $actor->id)->where('department_id', $actor->department_id)->exists();
} }
public function canRequest(User $actor, PurchaseOrder $order): bool public function canRequest(User $actor, PurchaseOrder $order): bool
@@ -38,6 +39,17 @@ class OrderCancellationWorkflow
} }
$request = Requisition::query()->visibleTo($actor)->find($order->requisition_id); $request = Requisition::query()->visibleTo($actor)->find($order->requisition_id);
$policy = app(OrderCancellationPolicyWorkflow::class)->current(); $policy = app(OrderCancellationPolicyWorkflow::class)->current();
if (OrderPartsAccess::applies($order)) {
if (! PurchaseOrder::query()->visibleTo($actor)->whereKey($order->id)->exists()) {
return false;
}
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
$source = Requisition::query()->whereKey($origin)->first();
if (! $source || $source->requester_id === $actor->id || app(ConflictGuard::class)->processBlocked($source, $order->supplier_id, $actor)) {
return false;
}
}
}
return $request && $request->requester_id !== $actor->id && $policy && $policy->enabled && $policy->mode === 'issued_order' return $request && $request->requester_id !== $actor->id && $policy && $policy->enabled && $policy->mode === 'issued_order'
&& $policy->valid_until >= today()->format('Y-m-d') && $policy->valid_until >= today()->format('Y-m-d')
@@ -53,6 +65,16 @@ class OrderCancellationWorkflow
$order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id); $order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id);
$request = $order ? Requisition::query()->find($order->requisition_id) : null; $request = $order ? Requisition::query()->find($order->requisition_id) : null;
$award = $order ? PurchaseAward::query()->find($order->purchase_award_id) : null; $award = $order ? PurchaseAward::query()->find($order->purchase_award_id) : null;
if ($order && OrderPartsAccess::applies($order)) {
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
$source = Requisition::query()->whereKey($origin)->first();
$sourceAward = PurchaseAward::query()->where('requisition_id', $origin)->first();
if (! $source || ! $sourceAward || in_array($actor->id, [$source->requester_id, $sourceAward->created_by], true)
|| app(ConflictGuard::class)->processBlocked($source, $order->supplier_id, $actor)) {
return false;
}
}
}
return $order && $request && $award && ! in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true); return $order && $request && $award && ! in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true);
} }
@@ -92,6 +114,8 @@ class OrderCancellationWorkflow
private function basis(PurchaseOrder $order): string private function basis(PurchaseOrder $order): string
{ {
return hash('sha256', json_encode(['order' => $order->getAttributes(), 'items' => $order->items()->orderBy('id')->get()->toArray(), return hash('sha256', json_encode(['order' => $order->getAttributes(), 'items' => $order->items()->orderBy('id')->get()->toArray(),
...(OrderPartsAccess::applies($order) ? ['order_parts_financial' => DB::table('budget_order_allocations')->where('tenant_id', $order->tenant_id)
->where('order_key', $order->getAttribute('order_key'))->orderBy('id')->get()->toArray()] : []),
'budget' => DB::table('budget_entries')->where('tenant_id', $order->tenant_id)->where('requisition_id', $order->requisition_id)->orderBy('id')->get()->toArray()], JSON_THROW_ON_ERROR)); 'budget' => DB::table('budget_entries')->where('tenant_id', $order->tenant_id)->where('requisition_id', $order->requisition_id)->orderBy('id')->get()->toArray()], JSON_THROW_ON_ERROR));
} }
@@ -111,6 +135,10 @@ class OrderCancellationWorkflow
$request = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id); $request = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
abort_if($actor->id === $request->requester_id, 403); abort_if($actor->id === $request->requester_id, 403);
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor); app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
if (OrderPartsAccess::applies($order)) {
app(OrderPartsAccess::class)->assertProcess($actor, $order);
abort_if(Requisition::query()->whereIn('id', app(OrderPartsAccess::class)->origins($order))->where('requester_id', $actor->id)->exists(), 403);
}
$old = OrderCancellation::query()->where('created_by', $actor->id)->where('operation_key', $data['operation_key'])->first(); $old = OrderCancellation::query()->where('created_by', $actor->id)->where('operation_key', $data['operation_key'])->first();
if ($old) { if ($old) {
abort_unless($old->input_hash === $hash, 422, 'Chave utilizada com outro conteúdo.'); abort_unless($old->input_hash === $hash, 422, 'Chave utilizada com outro conteúdo.');
@@ -143,36 +171,72 @@ class OrderCancellationWorkflow
$award = PurchaseAward::query()->findOrFail($order->purchase_award_id); $award = PurchaseAward::query()->findOrFail($order->purchase_award_id);
abort_if(in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true), 403); abort_if(in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true), 403);
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor); app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
if (OrderPartsAccess::applies($order)) {
app(OrderPartsAccess::class)->assertProcess($actor, $order);
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
$source = Requisition::query()->whereKey($origin)->firstOrFail();
$sourceAward = PurchaseAward::query()->where('requisition_id', $origin)->firstOrFail();
abort_if(in_array($actor->id, [$source->requester_id, $sourceAward->created_by], true), 403);
}
}
if ($record->status !== 'pending') { if ($record->status !== 'pending') {
abort_unless($record->status === $decision && $record->review_reason === $reason && $record->reviewed_by === $actor->id, 409, 'Decisão imutável.'); abort_unless($record->status === $decision && $record->review_reason === $reason && $record->reviewed_by === $actor->id, 409, 'Decisão imutável.');
return; return;
} }
$entry = null; $entry = null;
$partReversal = null;
if ($decision === 'approved') { if ($decision === 'approved') {
$this->source($order); $this->source($order);
abort_unless($record->basis_hash === $this->basis($order), 409, 'A base da ordem ou do compromisso mudou.'); abort_unless($record->basis_hash === $this->basis($order), 409, 'A base da ordem ou do compromisso mudou.');
$policy = app(OrderCancellationPolicyWorkflow::class)->requireCurrent(); $policy = app(OrderCancellationPolicyWorkflow::class)->requireCurrent();
abort_unless($policy->id === $record->policy_id, 409, 'Política alterada; rejeite o pedido para retomar o circuito.'); abort_unless($policy->id === $record->policy_id, 409, 'Política alterada; rejeite o pedido para retomar o circuito.');
abort_unless(DB::table('tenants')->where('id', $actor->tenant_id)->value('currency') === 'MZN', 422); abort_unless(DB::table('tenants')->where('id', $actor->tenant_id)->value('currency') === 'MZN', 422);
if (! empty($order->snapshot['budget_control']) && ! DB::table('budget_entries')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->exists()) { if (OrderPartsAccess::applies($order)) {
throw ValidationException::withMessages(['budget' => 'A ordem indica controlo orçamental, mas o compromisso não está disponível.']); $partReversal = $this->reverseParts($actor, $order, $record);
} else {
if (! empty($order->snapshot['budget_control']) && ! DB::table('budget_entries')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->exists()) {
throw ValidationException::withMessages(['budget' => 'A ordem indica controlo orçamental, mas o compromisso não está disponível.']);
}
$path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
require_once $path;
try {
$entry = (new CommitmentReversal)->reverse(DB::connection(), new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN'), $request->id, $order->id);
} catch (\LogicException $error) {
throw ValidationException::withMessages(['budget' => 'O compromisso não está integralmente disponível para reversão ou a sua base é inconsistente. Reveja o controlo orçamental.']);
}
$request->update(['status' => 'cancelled']);
} }
$path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
require_once $path;
try {
$entry = (new CommitmentReversal)->reverse(DB::connection(), new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN'), $request->id, $order->id);
} catch (\LogicException $error) {
throw ValidationException::withMessages(['budget' => 'O compromisso não está integralmente disponível para reversão ou a sua base é inconsistente. Reveja o controlo orçamental.']);
}
$request->update(['status' => 'cancelled']);
} }
$record->update(['status' => $decision, 'reviewed_by' => $actor->id, 'review_reason' => $reason, 'reviewed_at' => now()]); $record->update(['status' => $decision, 'reviewed_by' => $actor->id, 'review_reason' => $reason, 'reviewed_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'order_cancellation.'.$decision, $request, null, ['cancellation_id' => $record->id, 'order_id' => $order->id, 'budget_reversal_entry_id' => $entry]); app(RequisitionWorkflow::class)->audit($actor, 'order_cancellation.'.$decision, $request, null, ['cancellation_id' => $record->id, 'order_id' => $order->id, 'budget_reversal_entry_id' => $entry,
...($partReversal === null ? [] : ['order_parts_reversal' => $partReversal])]);
}); });
} }
/** @return array<string,mixed> */
private function reverseParts(User $actor, PurchaseOrder $order, OrderCancellation $record): array
{
abort_unless(app(OrderPartsWorkflow::class)->ready(), 503);
$sources = $order->snapshot['order_parts']['budget_sources'];
foreach ($sources as &$source) {
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['origin'])->lockForUpdate()->first();
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'];
}
unset($source);
$adapter = app(CommonBudget::class);
$engine = $adapter->for($actor);
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'cancelOrderParts'))->invoke($engine, $order->getAttribute('order_key'), $sources, $record->operation_key));
if (! is_array($result)) {
throw new \LogicException('Resposta incompatível da reversão por parcelas.');
}
return $result;
}
public function revise(User $actor, OrderCancellation $record, string $neededBy, string $reason): Requisition public function revise(User $actor, OrderCancellation $record, string $neededBy, string $reason): Requisition
{ {
$this->enabled(); $this->enabled();
@@ -184,6 +248,7 @@ class OrderCancellationWorkflow
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403); abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
$record = OrderCancellation::query()->lockForUpdate()->findOrFail($record->id); $record = OrderCancellation::query()->lockForUpdate()->findOrFail($record->id);
$order = PurchaseOrder::query()->findOrFail($record->purchase_order_id); $order = PurchaseOrder::query()->findOrFail($record->purchase_order_id);
abort_if(OrderPartsAccess::applies($order), 422, 'Cancelar uma parcela não encerra a requisição nem autoriza uma nova requisição por arrasto.');
$source = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id); $source = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
abort_unless($actor->id === $source->requester_id && $actor->department_id === $source->department_id && $record->status === 'approved', 403); abort_unless($actor->id === $source->requester_id && $actor->department_id === $source->department_id && $record->status === 'approved', 403);
if ($record->revised_requisition_id) { if ($record->revised_requisition_id) {
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Services;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\Requisition;
use App\Models\RequisitionItem;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/** All-or-nothing access to consolidated documents, preserving each native origin. */
final class OrderPartsAccess
{
public static function applies(PurchaseOrder $order): bool
{
return $order->getAttribute('order_key') !== null || isset($order->snapshot['order_parts']);
}
/** @return list<int> */
public function origins(PurchaseOrder $order): array
{
if (! self::applies($order)) {
return [$order->requisition_id];
}
abort_unless(Schema::hasTable('purchase_order_sources'), 503, 'Preserve as origens da ordem antes de a utilizar.');
$ids = DB::table('purchase_order_sources')->where('tenant_id', $order->tenant_id)->where('purchase_order_id', $order->id)
->orderBy('requisition_id')->pluck('requisition_id')->all();
$expected = array_column($order->snapshot['order_parts']['sources'] ?? [], 'requisition_id');
sort($expected, SORT_NUMERIC);
abort_unless($ids !== [] && $ids === $expected, 503, 'As origens documentais da ordem estão incompletas.');
return $ids;
}
/** Validates every source before a native writer operates on the shared document. */
public function assertProcess(User $actor, PurchaseOrder $order, bool $participation = false, bool $receipt = false): void
{
abort_unless(auth()->id() === $actor->id && $actor->tenant_id === $order->tenant_id, 403);
foreach ($this->origins($order) as $id) {
$query = Requisition::query()->whereKey($id);
if (! $receipt) {
$query->visibleTo($actor);
} elseif ($actor->departmentScoped()) {
$query->where('department_id', $actor->department_id);
}
$request = $query->firstOrFail();
if ($participation) {
app(ConflictGuard::class)->assertParticipation($actor, $request);
}
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
}
}
public function requestForLine(PurchaseOrder $order, PurchaseOrderItem $line): Requisition
{
abort_unless($line->purchase_order_id === $order->id && $line->tenant_id === $order->tenant_id, 409);
$id = RequisitionItem::query()->whereKey($line->requisition_item_id)->value('requisition_id');
abort_unless(in_array($id, $this->origins($order), true), 503, 'Linha sem origem documental preservada.');
return Requisition::query()->whereKey($id)->firstOrFail();
}
}
+189
View File
@@ -0,0 +1,189 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\User;
use Brick\Math\BigDecimal;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
/** Finance's explicit native invoice imputations, with one common consumption command. */
final class OrderPartsInvoices
{
/** @return list<array<string,mixed>>|null */
public function options(User $actor, PurchaseOrder $order): ?array
{
if (! app(OrderPartsWorkflow::class)->ready() || ! $actor->hasFunctions([PurchasingRole::Finance])
|| app(OrganizationAccess::class)->maintenanceOnly($actor)) {
return null;
}
app(OrderPartsAccess::class)->assertProcess($actor, $order);
$rows = [];
foreach ($order->snapshot['order_parts']['sources'] as $source) {
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->first();
abort_unless($distribution !== null, 503);
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$nativeLines = array_column($source['items'], null, 'requisition_item_id');
foreach ($snapshot['allocations'] as $allocation) {
if (! isset($nativeLines[$allocation['line_id']]) || ! DB::table('budget_order_allocations')->where('tenant_id', $actor->tenant_id)
->where('order_key', $order->getAttribute('order_key'))->where('distribution_id', $distribution->id)->where('allocation_key', $allocation['allocation_key'])->where('kind', 'commit')->exists()) {
continue;
}
$rows[] = ['origin' => $source['requisition_id'], 'allocation_key' => $allocation['allocation_key'], 'line_id' => $allocation['line_id'],
'centre_id' => $allocation['centre_id'], 'description' => $nativeLines[$allocation['line_id']]['description']];
}
}
return $rows;
}
/** @return array<string,mixed> */
public function rules(): array
{
$money = ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/D'];
return ['order_part_allocations' => 'required|array|min:1|max:500',
'order_part_allocations.*' => 'required|array:origin,allocation_key,subtotal,total',
'order_part_allocations.*.origin' => 'required|integer|min:1',
'order_part_allocations.*.allocation_key' => 'required|string|max:120',
'order_part_allocations.*.subtotal' => $money, 'order_part_allocations.*.total' => $money,
'reason' => 'required|string|min:10|max:4000'];
}
/** @param array<string,mixed> $input
* @param list<array<string,mixed>> $nativeLines
* @return array<string,mixed>
*/
public function prepare(User $actor, Invoice $invoice, PurchaseOrder $order, array $input, array $nativeLines): array
{
abort_unless(app(OrderPartsWorkflow::class)->ready() && DB::transactionLevel() > 0 && OrderPartsAccess::applies($order), 503);
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 = [];
foreach ($data['order_part_allocations'] as $row) {
$origin = BigDecimal::of($row['origin'])->toInt();
$key = $origin.':'.$row['allocation_key'];
if (isset($seen[$key])) {
throw ValidationException::withMessages(['order_part_allocations' => 'Cada atribuição é indicada uma única vez por origem.']);
}
$seen[$key] = true;
$rows[] = ['origin' => $origin, 'allocation_key' => $row['allocation_key'],
'subtotal_minor' => BigDecimal::of($row['subtotal'])->multipliedBy(100)->toInt(),
'total_minor' => BigDecimal::of($row['total'])->multipliedBy(100)->toInt()];
}
usort($rows, fn ($a, $b) => [$a['origin'], $a['allocation_key']] <=> [$b['origin'], $b['allocation_key']]);
$sources = $this->bindings($actor, $order, $rows, $nativeLines);
$adapter = app(CommonBudget::class);
$engine = $adapter->for($actor);
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'checkOrderPartsConsumption'))->invoke($engine, $sources));
return ['allocations' => $rows, 'source_versions_at_preparation' => array_column($sources, 'version', 'origin'),
'revision' => $this->revision($invoice, $order, $nativeLines), 'operation_key' => (string) Str::uuid(),
'prepared_by' => $actor->id, 'reason' => trim($data['reason'])];
}
/** @param list<array<string,mixed>> $rows
* @param list<array<string,mixed>> $nativeLines
* @return list<array<string,mixed>>
*/
private function bindings(User $actor, PurchaseOrder $order, array $rows, array $nativeLines): array
{
$orderKey = $order->getAttribute('order_key');
abort_unless(is_string($orderKey) && $orderKey === ($order->snapshot['order_parts']['order_key'] ?? null), 503,
'Preserve o identificador nativo da ordem por parcelas.');
$origins = app(OrderPartsAccess::class)->origins($order);
$orderLines = $order->items()->get()->keyBy('id');
$lineOrigins = [];
foreach ($order->snapshot['order_parts']['sources'] as $source) {
foreach ($source['items'] as $line) {
$lineOrigins[$line['requisition_item_id']] = $source['requisition_id'];
}
}
$expected = [];
foreach ($nativeLines as $line) {
$native = $orderLines->get($line['purchase_order_item_id']);
abort_unless($native !== null && isset($lineOrigins[$native->requisition_item_id]), 409);
$expected[$native->requisition_item_id] = ['origin' => $lineOrigins[$native->requisition_item_id],
'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['subtotal_minor'] + $line['tax_minor']];
}
$sources = $sums = [];
foreach ($rows as $row) {
if (! in_array($row['origin'], $origins, true)) {
throw ValidationException::withMessages(['order_part_allocations' => 'Origem fora desta ordem.']);
}
if (! isset($sources[$row['origin']])) {
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $row['origin'])->lockForUpdate()->first();
abort_unless($distribution !== null, 503, 'Preserve a distribuição da origem.');
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$sources[$row['origin']] = ['origin' => $row['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' => [], 'frozen' => array_column($snapshot['allocations'], null, 'allocation_key')];
}
$binding = $sources[$row['origin']]['frozen'][$row['allocation_key']] ?? null;
$id = $binding['line_id'] ?? null;
if ($id === null || ! isset($expected[$id]) || $expected[$id]['origin'] !== $row['origin']) {
throw ValidationException::withMessages(['order_part_allocations' => 'Distribua apenas as linhas e origens efectivamente facturadas.']);
}
$sums[$id] ??= ['subtotal_minor' => 0, 'total_minor' => 0];
$sums[$id]['subtotal_minor'] += $row['subtotal_minor'];
$sums[$id]['total_minor'] += $row['total_minor'];
$sources[$row['origin']]['allocations'][] = ['order_key' => $orderKey, 'allocation_key' => $row['allocation_key'],
'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']]) {
throw ValidationException::withMessages(['order_part_allocations' => 'As imputações devem coincidir exactamente com cada linha nativa da factura.']);
}
}
foreach ($sources as &$source) {
unset($source['frozen']);
}
unset($source);
ksort($sources, SORT_NUMERIC);
return array_values($sources);
}
/** @param list<array<string,mixed>> $lines */
private function revision(Invoice $invoice, PurchaseOrder $order, array $lines): string
{
$items = array_map(fn ($line) => array_intersect_key($line, array_flip(['purchase_order_item_id', 'quantity_milli', 'subtotal_minor', 'tax_minor'])), $lines);
usort($items, fn ($a, $b) => $a['purchase_order_item_id'] <=> $b['purchase_order_item_id']);
foreach ($items as &$item) {
ksort($item);
}
unset($item);
return hash('sha256', json_encode([$invoice->only(['tenant_id', 'purchase_order_id', 'number', 'subtotal_minor', 'tax_minor', 'total_minor']),
$order->only(['id', 'order_key', 'currency', 'snapshot']), $items], JSON_THROW_ON_ERROR));
}
/** @return array<string,mixed> */
public function consume(User $actor, Invoice $invoice, PurchaseOrder $order): array
{
abort_unless(app(OrderPartsWorkflow::class)->ready() && DB::transactionLevel() > 0, 503);
app(OrderPartsAccess::class)->assertProcess($actor, $order);
$plan = $invoice->snapshot['budget_distribution'] ?? null;
$lines = array_values($invoice->items()->orderBy('purchase_order_item_id')->get()->map(fn ($item) => $item->only(['purchase_order_item_id', 'quantity_milli', 'subtotal_minor', 'tax_minor']))->all());
if (! is_array($plan) || ($plan['revision'] ?? null) !== $this->revision($invoice, $order, $lines)) {
throw ValidationException::withMessages(['order_part_allocations' => 'Preserve a imputação nativa confirmada para esta factura.']);
}
$sources = $this->bindings($actor, $order, $plan['allocations'], $lines);
$adapter = app(CommonBudget::class);
$engine = $adapter->for($actor);
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'consumeOrderParts'))->invoke($engine, $invoice->id, $sources, $plan['operation_key']));
if (! is_array($result)) {
throw new \LogicException('Resposta incompatível do consumo por origem.');
}
return $result;
}
}
+74 -57
View File
@@ -5,6 +5,7 @@ namespace App\Services;
use App\Enums\PurchasingRole; use App\Enums\PurchasingRole;
use App\Models\PurchaseAward; use App\Models\PurchaseAward;
use App\Models\PurchaseOrderItem; use App\Models\PurchaseOrderItem;
use App\Models\Requisition;
use App\Models\User; use App\Models\User;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Validator;
@@ -32,7 +33,19 @@ final class OrderPartsPreparation
public function prepare(User $actor, array $input): array public function prepare(User $actor, array $input): array
{ {
abort_unless($this->ready(), 503); abort_unless($this->ready(), 503);
$data = Validator::make($input, [ $data = $this->selection($input);
return DB::transaction(function () use ($actor, $data): array {
return $this->prepareSelected($actor, $data);
});
}
/** @param array<string,mixed> $input
* @return array<string,mixed>
*/
public function selection(array $input): array
{
return Validator::make($input, [
'sources' => 'required|array|min:1|max:100', 'sources' => 'required|array|min:1|max:100',
'sources.*' => 'required|array:award_id,items', 'sources.*' => 'required|array:award_id,items',
'sources.*.award_id' => 'required|integer|min:1|distinct', 'sources.*.award_id' => 'required|integer|min:1|distinct',
@@ -41,64 +54,68 @@ final class OrderPartsPreparation
'sources.*.items.*.quotation_item_id' => 'required|integer|min:1|distinct', 'sources.*.items.*.quotation_item_id' => 'required|integer|min:1|distinct',
'sources.*.items.*.quantity' => ['required', 'string', 'regex:/^\d{1,10}(?:\.\d{1,3})?$/D'], 'sources.*.items.*.quantity' => ['required', 'string', 'regex:/^\d{1,10}(?:\.\d{1,3})?$/D'],
])->validate(); ])->validate();
}
return DB::transaction(function () use ($actor, $data): array { /** @param array<string,mixed> $data
app(ConflictGuard::class)->lockCompany($actor); * @return array<string,mixed>
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]); */
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403); private function prepareSelected(User $actor, array $data): array
$sources = $data['sources']; {
usort($sources, fn ($a, $b) => $a['award_id'] <=> $b['award_id']); app(ConflictGuard::class)->lockCompany($actor);
$result = []; $actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
$compatibility = null; abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
foreach ($sources as $selection) { $sources = $data['sources'];
$award = PurchaseAward::query()->where('id', $selection['award_id'])->firstOrFail(); usort($sources, fn ($a, $b) => $a['award_id'] <=> $b['award_id']);
$quote = app(PurchaseWorkflow::class)->approvedSource($actor, $award); $result = [];
$key = [$quote->tenant_id, $quote->supplier_id, $quote->currency]; $compatibility = null;
if ($compatibility !== null && $key !== $compatibility) { foreach ($sources as $selection) {
throw ValidationException::withMessages(['sources' => 'Consolide apenas adjudicações da mesma empresa, fornecedor e moeda documental.']); $award = PurchaseAward::query()->where('id', $selection['award_id'])->firstOrFail();
} $quote = app(PurchaseWorkflow::class)->approvedSource($actor, $award);
$compatibility = $key; $key = [$quote->tenant_id, $quote->supplier_id, $quote->currency];
$lines = $quote->items()->orderBy('id')->lockForUpdate()->get()->keyBy('id'); if ($compatibility !== null && $key !== $compatibility) {
$prepared = []; throw ValidationException::withMessages(['sources' => 'Consolide apenas adjudicações da mesma empresa, fornecedor e moeda documental.']);
foreach ($selection['items'] as $item) {
$source = $lines->get($item['quotation_item_id']);
abort_unless($source !== null, 422, 'Linha fora da proposta aprovada.');
$ordered = PurchaseOrderItem::query()->where('requisition_item_id', $source->requisition_item_id)->orderBy('id')->lockForUpdate()->get();
$before = 0;
foreach ($ordered as $old) {
// Cancelled lines remain used; cancellation never authorizes automatic reissue.
$before += ReceiptWorkflow::milli($old->quantity);
}
$quantity = ReceiptWorkflow::milli($item['quantity']);
$full = ReceiptWorkflow::milli($source->quantity);
if ($quantity < 1 || $before > $full || $quantity > $full - $before) {
throw ValidationException::withMessages(['sources' => 'A parcela ultrapassa a quantidade aprovada ainda não emitida.']);
}
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, $before, $quantity);
$native = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, 0, $full);
if ($native['subtotal_minor'] !== $source->subtotal_minor || $native['tax_minor'] !== $source->tax_minor || $native['total_minor'] !== $source->total_minor) {
throw ValidationException::withMessages(['sources' => 'A base nativa da linha aprovada está inconsistente.']);
}
$prepared[] = ['quotation_item_id' => $source->id, 'requisition_item_id' => $source->requisition_item_id,
'description' => $source->description, 'quantity_milli' => $quantity, 'quantity_offset_milli' => $before,
'unit_price_minor' => $source->unit_price_minor, 'tax_rate' => (string) $source->tax_rate, ...$amounts];
}
usort($prepared, fn ($a, $b) => $a['quotation_item_id'] <=> $b['quotation_item_id']);
$result[] = ['requisition_id' => $award->requisition_id, 'award_id' => $award->id, 'quotation_id' => $quote->id,
'supplier_id' => $quote->supplier_id, 'currency' => $quote->currency, 'items' => $prepared,
'exchange_basis' => $quote->exchange_basis, 'approved_reference' => app(QuotationExchange::class)->amounts($quote),
'explicit_reference_allocation_required' => $quote->currency !== 'MZN',
'quotation_terms' => $quote->only(['reference', 'valid_until', 'payment_terms', 'delivery_days']),
'award_terms' => $award->only(['delivery_date', 'delivery_location', 'justification']),
'approval_snapshot' => $award->approval_snapshot,
'approval_fingerprint' => $award->comparison_hash];
} }
$subtotal = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'subtotal_minor')), $result)); $compatibility = $key;
$tax = array_sum(array_map(fn ($source) => array_sum(array_column($source['items'], 'tax_minor')), $result)); $lines = $quote->items()->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$prepared = [];
foreach ($selection['items'] as $item) {
$source = $lines->get($item['quotation_item_id']);
abort_unless($source !== null, 422, 'Linha fora da proposta aprovada.');
$ordered = PurchaseOrderItem::query()->where('requisition_item_id', $source->requisition_item_id)->orderBy('id')->lockForUpdate()->get();
$before = 0;
foreach ($ordered as $old) {
// Cancelled lines remain used; cancellation never authorizes automatic reissue.
$before += ReceiptWorkflow::milli($old->quantity);
}
$quantity = ReceiptWorkflow::milli($item['quantity']);
$full = ReceiptWorkflow::milli($source->quantity);
if ($quantity < 1 || $before > $full || $quantity > $full - $before) {
throw ValidationException::withMessages(['sources' => 'A parcela ultrapassa a quantidade aprovada ainda não emitida.']);
}
$amounts = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, $before, $quantity);
$native = PurchaseLineAmounts::portion($source->unit_price_minor, (string) $source->tax_rate, 0, $full);
if ($native['subtotal_minor'] !== $source->subtotal_minor || $native['tax_minor'] !== $source->tax_minor || $native['total_minor'] !== $source->total_minor) {
throw ValidationException::withMessages(['sources' => 'A base nativa da linha aprovada está inconsistente.']);
}
$prepared[] = ['quotation_item_id' => $source->id, 'requisition_item_id' => $source->requisition_item_id, 'approved_quantity_milli' => $full,
'description' => $source->description, 'quantity_milli' => $quantity, 'quantity_offset_milli' => $before,
'unit_price_minor' => $source->unit_price_minor, 'tax_rate' => (string) $source->tax_rate, ...$amounts];
}
usort($prepared, fn ($a, $b) => $a['quotation_item_id'] <=> $b['quotation_item_id']);
$result[] = ['requisition_id' => $award->requisition_id, 'requisition_number' => Requisition::query()->whereKey($award->requisition_id)->value('number'), 'award_id' => $award->id, 'quotation_id' => $quote->id,
'supplier_id' => $quote->supplier_id, 'currency' => $quote->currency, 'items' => $prepared,
'exchange_basis' => $quote->exchange_basis, 'approved_reference' => app(QuotationExchange::class)->amounts($quote),
'explicit_reference_allocation_required' => $quote->currency !== 'MZN',
'quotation_terms' => array_intersect_key($quote->attributesToArray(), array_flip(['reference', 'valid_until', 'payment_terms', 'delivery_days'])),
'award_terms' => array_intersect_key($award->attributesToArray(), array_flip(['delivery_date', 'delivery_location', 'justification'])),
'approval_snapshot' => $award->approval_snapshot,
'approval_fingerprint' => $award->comparison_hash];
}
$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));
return ['sources' => $result, 'currency' => $compatibility[2], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax, return ['sources' => $result, 'currency' => $compatibility[2], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax,
'total_minor' => $subtotal + $tax, 'fingerprint' => hash('sha256', json_encode($result, JSON_THROW_ON_ERROR)), 'total_minor' => $subtotal + $tax, 'fingerprint' => hash('sha256', json_encode($result, JSON_THROW_ON_ERROR)),
'issued' => false, 'budget_effects' => false]; 'issued' => false, 'budget_effects' => false];
});
} }
} }
+288
View File
@@ -0,0 +1,288 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\PurchaseAward;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\Quotation;
use App\Models\Requisition;
use App\Models\Tenant;
use App\Models\User;
use Brick\Math\BigDecimal;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
/** Optional native issuance. Every document and common budget effect shares one transaction. */
final class OrderPartsWorkflow
{
/** @param array<string,mixed> $input
* @return array<string,mixed>
*/
public function preview(User $actor, array $input): array
{
abort_unless($this->ready(), 503);
return DB::transaction(function () use ($actor, $input): array {
$selection = app(OrderPartsPreparation::class)->selection($input);
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
$financial = [];
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' => []];
continue;
}
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$selected = array_column($source['items'], null, 'requisition_item_id');
$rows = [];
foreach ($snapshot['allocations'] as $row) {
if (! isset($selected[$row['line_id']])) {
continue;
}
$line = $selected[$row['line_id']];
$count = count(array_filter($snapshot['allocations'], fn ($part) => $part['line_id'] === $row['line_id']));
$rows[] = ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'],
'description' => $line['description'], 'subtotal' => $count === 1 && $source['currency'] === 'MZN' ? (string) BigDecimal::of($line['subtotal_minor'])->dividedBy(100, 2) : '',
'total' => $count === 1 && $source['currency'] === 'MZN' ? (string) BigDecimal::of($line['total_minor'])->dividedBy(100, 2) : ''];
}
$financial[] = ['origin' => $source['requisition_id'], 'award_id' => $source['award_id'], 'requires_adoption' => false,
'plan_hash' => $snapshot['plan_hash'], 'version' => DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count(), 'allocations' => $rows];
}
return ['selection' => $selection, 'prepared' => $prepared, 'financial' => $financial,
'can_issue' => $prepared['currency'] === 'MZN' && ! in_array(true, array_column($financial, 'requires_adoption'), true)];
});
}
public function adopt(User $actor, PurchaseAward $award, string $operation): void
{
abort_unless($this->ready(), 503);
Validator::make(['operation_key' => $operation], ['operation_key' => 'required|uuid'])->validate();
DB::transaction(function () use ($actor, $award, $operation): 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.');
$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,
'Uma ordem já emitida não pode ser dividida retroactivamente.');
$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];
$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];
}
$revision = hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR));
$adapter = app(CommonBudget::class);
$engine = $adapter->for($actor);
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'adoptOrderSource'))->invoke($engine, $request->id,
$allocations, $lines, $revision, strtolower($operation)));
});
}
public function ready(): bool
{
foreach (['budget_order_commands', 'budget_order_bindings', 'budget_order_allocations', 'budget_order_consumptions', 'purchase_order_sources'] as $table) {
if (! Schema::hasTable($table)) {
return false;
}
}
return app(OrderPartsPreparation::class)->ready() && app(RequisitionBudgetDistributions::class)->ready()
&& Schema::hasTable('budget_order_commands') && Schema::hasTable('purchase_order_sources')
&& Schema::hasColumn('purchase_orders', 'order_key') && Schema::hasColumn('purchase_orders', 'order_source_count')
&& Schema::hasColumn('purchase_order_items', 'quantity_offset_milli');
}
/** @param array<string,mixed> $input */
public function issue(User $actor, array $input): PurchaseOrder
{
abort_unless($this->ready(), 503, 'Emissão por parcelas indisponível nesta composição.');
$selection = app(OrderPartsPreparation::class)->selection($input);
$data = Validator::make($input, [
'operation_key' => 'required|uuid', 'order_key' => 'required|uuid', 'fingerprint' => 'required|regex:/^[a-f0-9]{64}$/D',
'budget_sources' => 'required|array|min:1|max:100',
'budget_sources.*' => 'required|array:origin,version,plan_hash,allocations',
'budget_sources.*.origin' => 'required|integer|min:1|distinct', 'budget_sources.*.version' => 'required|integer|min:0',
'budget_sources.*.plan_hash' => 'required|regex:/^[a-f0-9]{64}$/D',
'budget_sources.*.allocations' => 'required|array|min:1|max:500',
'budget_sources.*.allocations.*' => 'required|array:allocation_key,subtotal_minor,total_minor',
'budget_sources.*.allocations.*.allocation_key' => 'required|string|max:120',
'budget_sources.*.allocations.*.subtotal_minor' => 'required|integer|min:0|max:100000000000000',
'budget_sources.*.allocations.*.total_minor' => 'required|integer|min:0|max:100000000000000',
'agreement_bindings' => 'sometimes|array|max:100',
'tenant_id' => 'prohibited', 'snapshot' => 'prohibited', 'status' => 'prohibited', 'issued_by' => 'prohibited',
])->validate();
foreach ($selection['sources'] as &$source) {
$source['award_id'] = BigDecimal::of($source['award_id'])->toInt();
foreach ($source['items'] as &$line) {
$line['quotation_item_id'] = BigDecimal::of($line['quotation_item_id'])->toInt();
$line['quantity'] = (string) BigDecimal::of($line['quantity'])->toScale(3);
}
unset($line);
usort($source['items'], fn ($a, $b) => $a['quotation_item_id'] <=> $b['quotation_item_id']);
}
unset($source);
usort($selection['sources'], fn ($a, $b) => $a['award_id'] <=> $b['award_id']);
$budgetSources = $data['budget_sources'];
foreach ($budgetSources as &$source) {
$source['origin'] = BigDecimal::of($source['origin'])->toInt();
$source['version'] = BigDecimal::of($source['version'])->toInt();
foreach ($source['allocations'] as &$row) {
$row['subtotal_minor'] = BigDecimal::of($row['subtotal_minor'])->toInt();
$row['total_minor'] = BigDecimal::of($row['total_minor'])->toInt();
ksort($row);
}
unset($row);
usort($source['allocations'], fn ($a, $b) => $a['allocation_key'] <=> $b['allocation_key']);
ksort($source);
}
unset($source);
usort($budgetSources, fn ($a, $b) => $a['origin'] <=> $b['origin']);
$orderKey = strtolower($data['order_key']);
$hash = hash('sha256', json_encode([$selection, $budgetSources, $data['fingerprint'], $data['agreement_bindings'] ?? []], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $selection, $data, $budgetSources, $orderKey, $hash): PurchaseOrder {
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Procurement]);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
$existing = PurchaseOrder::query()->where('order_key', $orderKey)->lockForUpdate()->first();
if ($existing !== null) {
abort_unless(hash_equals($existing->getAttribute('order_payload_hash'), $hash), 409, 'A ordem já foi emitida com outra preparação.');
PurchaseOrder::query()->visibleTo($actor)->whereKey($existing->id)->firstOrFail();
app(OrderPartsAccess::class)->assertProcess($actor, $existing, true);
app(OrderCancellationWorkflow::class)->assertOperational($existing);
return $existing;
}
$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;
foreach ($prepared['sources'] as $source) {
$request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
$award = PurchaseAward::query()->whereKey($source['award_id'])->firstOrFail();
$quote = Quotation::query()->whereKey($source['quotation_id'])->firstOrFail();
$firstQuote ??= $quote;
$requests[] = $request;
$request->load(['department', 'costCenter', 'requester']);
abort_unless($request->department !== null && $request->costCenter !== null && $quote->supplier !== null, 409,
'Preserve os intervenientes e as referências de cada origem.');
$requested = $request->items()->get()->keyBy('id');
$tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
foreach ($source['items'] as $item) {
$native = $requested->get($item['requisition_item_id']);
abort_unless($native !== null, 409);
$lines[] = ['tenant_id' => $actor->tenant_id,
...array_intersect_key($item, array_flip(['quotation_item_id', 'requisition_item_id', 'description', 'quantity_offset_milli', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor'])),
'quantity' => (string) BigDecimal::of($item['quantity_milli'])->dividedBy(1000, 3),
...$native->only(['unit', 'category', 'purchase_type', 'equipment_id', 'spare_part_id'])];
if ($native->catalogue_snapshot !== null) {
$catalogue[$native->id] = $native->catalogue_snapshot;
}
}
$frames[] = ['requisition' => $request->only(['id', 'number', 'justification']),
'department' => $request->department->only(['id', 'name']), 'cost_center' => $request->costCenter->only(['id', 'code', 'name']),
'requester' => $request->requester?->only(['id', 'name']),
'quotation' => [...$source['quotation_terms'], 'id' => $quote->id, 'currency' => $quote->currency],
'award' => [...$source['award_terms'], 'id' => $award->id], 'approval_rules' => $award->approval_snapshot,
'investment_rules' => $award->investment_snapshot, 'admission' => $award->admission_snapshot, 'recommendation' => $award->recommendation_snapshot,
'estimate_approvals' => $request->steps()->get()->toArray(), 'final_approvals' => $award->approvals()->get()->toArray(),
'decision_matrix' => $award->decision_matrix, 'comparison_policy' => app(ComparisonPolicy::class)->forRequest($request),
'native_preparation' => $source];
}
$first = $prepared['sources'][0];
$limits = app(AgreementOrderLimits::class)->freeze($actor, $firstQuote, $requests[0], $lines,
$data['agreement_bindings'] ?? [], array_slice($requests, 1));
$adapter = app(CommonBudget::class);
$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']),
'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,
'order_parts' => ['version' => 1, 'order_key' => $orderKey, 'preparation_fingerprint' => $prepared['fingerprint'],
'sources' => $prepared['sources'], 'frames' => $frames, 'budget_sources' => $budgetSources]];
$order = new PurchaseOrder(['tenant_id' => $actor->tenant_id, 'requisition_id' => $first['requisition_id'],
'purchase_award_id' => $first['award_id'], 'supplier_id' => $first['supplier_id'], 'issued_by' => $actor->id,
'currency' => $prepared['currency'],
'subtotal_minor' => $prepared['subtotal_minor'], 'tax_minor' => $prepared['tax_minor'], 'total_minor' => $prepared['total_minor'],
'snapshot' => $snapshot, 'issued_at' => now()]);
// Trusted metadata must survive an ORM column cache warmed before the optional QA schema.
$order->setAttribute('order_key', $orderKey);
$order->setAttribute('order_payload_hash', $hash);
$order->setAttribute('order_source_count', count($prepared['sources']));
$order->save();
DB::table('purchase_orders')->where('id', $order->id)->update(['number' => sprintf('OC-%s-%06d', now()->format('Y'), $order->id)]);
$order->refresh();
foreach ($lines as $line) {
$record = new PurchaseOrderItem(array_diff_key($line, array_flip(['quotation_item_id', 'quantity_offset_milli'])));
$record->setAttribute('quotation_item_id', $line['quotation_item_id']);
$record->setAttribute('quantity_offset_milli', $line['quantity_offset_milli']);
$order->items()->save($record);
}
foreach ($prepared['sources'] as $index => $source) {
DB::table('purchase_order_sources')->insert(['tenant_id' => $actor->tenant_id, 'purchase_order_id' => $order->id,
'requisition_id' => $source['requisition_id'], 'purchase_award_id' => $source['award_id'], 'quotation_id' => $source['quotation_id'],
'snapshot' => json_encode($frames[$index], JSON_THROW_ON_ERROR)]);
app(RequisitionWorkflow::class)->audit($actor, 'purchase_order.issued', $requests[$index], null,
['order_id' => $order->id, 'number' => $order->number, 'order_key' => $orderKey, 'source' => $source, 'budget_control' => $commit]);
}
return $order;
});
}
/** @param list<array<string,mixed>> $sources
* @param list<array<string,mixed>> $financial
*/
private function checkAllocations(User $actor, array $sources, array $financial): void
{
$expected = array_column($sources, 'requisition_id');
$actual = array_column($financial, 'origin');
sort($expected, SORT_NUMERIC);
sort($actual, SORT_NUMERIC);
if ($expected !== $actual) {
throw ValidationException::withMessages(['budget_sources' => 'Distribua exactamente as origens seleccionadas.']);
}
$byOrigin = array_column($financial, null, 'origin');
foreach ($sources as $source) {
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first();
abort_unless($distribution !== null, 422, 'Prepare a distribuição ou a adopção explícita da reserva antes de emitir parcelas.');
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$frozen = array_column($snapshot['allocations'], null, 'allocation_key');
$amounts = [];
foreach ($byOrigin[$source['requisition_id']]['allocations'] as $row) {
$binding = $frozen[$row['allocation_key']] ?? null;
if ($binding === null) {
throw ValidationException::withMessages(['budget_sources' => 'Atribuição fora da origem seleccionada.']);
}
$id = $binding['line_id'];
$amounts[$id] ??= ['subtotal_minor' => 0, 'total_minor' => 0];
$amounts[$id]['subtotal_minor'] += $row['subtotal_minor'];
$amounts[$id]['total_minor'] += $row['total_minor'];
}
$selected = array_column($source['items'], null, 'requisition_item_id');
if (array_diff(array_keys($amounts), array_keys($selected)) !== []) {
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']))) {
throw ValidationException::withMessages(['budget_sources' => 'As atribuições devem reconciliar exactamente com cada linha nativa emitida.']);
}
}
}
}
}
+3
View File
@@ -129,6 +129,7 @@ class PurchaseWorkflow
// An already committed issue is returned, never re-created or re-snapshotted. // An already committed issue is returned, never re-created or re-snapshotted.
$existing = PurchaseOrder::query()->where('requisition_id', $requisition->id)->first(); $existing = PurchaseOrder::query()->where('requisition_id', $requisition->id)->first();
if ($existing) { if ($existing) {
abort_if(OrderPartsAccess::applies($existing), 409, 'Esta adjudicação utiliza parcelas. Consulte as ordens emitidas ou prepare a parcela restante.');
app(OrderCancellationWorkflow::class)->assertOperational($existing); app(OrderCancellationWorkflow::class)->assertOperational($existing);
app(AgreementOrderLimits::class)->assertReplay($existing, $agreementBindings); app(AgreementOrderLimits::class)->assertReplay($existing, $agreementBindings);
@@ -168,7 +169,9 @@ class PurchaseWorkflow
$catalogueSources[$sourceLine->id] = $sourceLine->catalogue_snapshot; $catalogueSources[$sourceLine->id] = $sourceLine->catalogue_snapshot;
} }
} }
$tariffs = app(ImportTariffCodes::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
$snapshot = [ $snapshot = [
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings), ...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]), ...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
...($catalogueSources === [] ? [] : ['catalogue_sources' => $catalogueSources]), ...($catalogueSources === [] ? [] : ['catalogue_sources' => $catalogueSources]),
+9 -2
View File
@@ -79,6 +79,9 @@ class ReceiptWorkflow
$order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id); $order = PurchaseOrder::query()->lockForUpdate()->findOrFail($order->id);
app(OrderCancellationWorkflow::class)->assertOperational($order); app(OrderCancellationWorkflow::class)->assertOperational($order);
Gate::forUser($user)->authorize('create', [GoodsReceipt::class, $order]); Gate::forUser($user)->authorize('create', [GoodsReceipt::class, $order]);
if (OrderPartsAccess::applies($order)) {
app(OrderPartsAccess::class)->assertProcess($user, $order, true, true);
}
$deliveryNote = Str::squish(Str::upper($data['delivery_note'])); $deliveryNote = Str::squish(Str::upper($data['delivery_note']));
if ($deliveryNote === '') { if ($deliveryNote === '') {
throw ValidationException::withMessages(['delivery_note' => 'Indique a guia de remessa do fornecedor.']); throw ValidationException::withMessages(['delivery_note' => 'Indique a guia de remessa do fornecedor.']);
@@ -157,9 +160,11 @@ class ReceiptWorkflow
if (GoodsReceipt::query()->where('purchase_order_id', $order->id)->where('delivery_note', $deliveryNote)->exists()) { if (GoodsReceipt::query()->where('purchase_order_id', $order->id)->where('delivery_note', $deliveryNote)->exists()) {
throw ValidationException::withMessages(['delivery_note' => 'Esta guia já foi confirmada nesta ordem. Consulte o histórico em vez de repetir a recepção.']); throw ValidationException::withMessages(['delivery_note' => 'Esta guia já foi confirmada nesta ordem. Consulte o histórico em vez de repetir a recepção.']);
} }
$classifiedImport = ! empty($order->snapshot['import_tariffs']);
abort_if($classifiedImport && ! Schema::hasTable('supply_records'), 503, 'Preserve o processo de importação antes da recepção.');
if (Schema::hasTable('supply_records')) { if (Schema::hasTable('supply_records')) {
$import = app(SupplyPlanning::class)->latest('import')->where('purchase_order_id', $order->id)->first(); $import = app(SupplyPlanning::class)->latest('import')->where('purchase_order_id', $order->id)->first();
if ($import !== null && $import->state !== 'released') { if (($classifiedImport && $import === null) || ($import !== null && $import->state !== 'released')) {
throw ValidationException::withMessages(['items' => 'A importação ainda não tem libertação aduaneira comprovada. A chegada ou o pagamento não autorizam entrada utilizável.']); throw ValidationException::withMessages(['items' => 'A importação ainda não tem libertação aduaneira comprovada. A chegada ou o pagamento não autorizam entrada utilizável.']);
} }
} }
@@ -202,7 +207,8 @@ class ReceiptWorkflow
if (! $source->spare_part_id || ! $source->equipment_id) { if (! $source->spare_part_id || ! $source->equipment_id) {
throw ValidationException::withMessages(['items' => 'Peça sem associação autorizada na ordem. A recepção está bloqueada.']); throw ValidationException::withMessages(['items' => 'Peça sem associação autorizada na ordem. A recepção está bloqueada.']);
} }
$part = app(EquipmentWorkflow::class)->linkedPart((int) $source->spare_part_id, (int) $source->equipment_id, $requisition->department_id); $lineRequest = OrderPartsAccess::applies($order) ? app(OrderPartsAccess::class)->requestForLine($order, $source) : $requisition;
$part = app(EquipmentWorkflow::class)->linkedPart((int) $source->spare_part_id, (int) $source->equipment_id, $lineRequest->department_id);
if ($accepted > 0 && $stockItem?->id !== $part->stock_item_id) { if ($accepted > 0 && $stockItem?->id !== $part->stock_item_id) {
throw ValidationException::withMessages(['items' => 'A peça recebida deve usar o artigo de stock autorizado na ordem.']); throw ValidationException::withMessages(['items' => 'A peça recebida deve usar o artigo de stock autorizado na ordem.']);
} }
@@ -225,6 +231,7 @@ class ReceiptWorkflow
'rejected_milli' => $received - $accepted, 'quality_status' => $input['quality_status'], 'notes' => $input['notes'], 'rejected_milli' => $received - $accepted, 'quality_status' => $input['quality_status'], 'notes' => $input['notes'],
'snapshot' => [ 'snapshot' => [
'order_item' => $source->only(['id', 'description', 'unit', 'purchase_type', 'quantity']), 'order_item' => $source->only(['id', 'description', 'unit', 'purchase_type', 'quantity']),
...(OrderPartsAccess::applies($order) ? ['source_line' => $source->only(['requisition_item_id', 'quotation_item_id', 'quantity_offset_milli'])] : []),
'stock_item' => $stockItem?->only(['id', 'code', 'name', 'unit']), 'stock_item' => $stockItem?->only(['id', 'code', 'name', 'unit']),
'warehouse' => $warehouse?->only(['id', 'code', 'name']), 'warehouse' => $warehouse?->only(['id', 'code', 'name']),
'physical' => $physical, 'physical' => $physical,
+6
View File
@@ -204,6 +204,12 @@ class SupplyPlanning
$this->check(! $this->latest('import')->where('purchase_order_id', $order->id)->exists(), 'purchase_order_id', 'A ordem já tem processo de importação. Consulte-o sem duplicar a compra.'); $this->check(! $this->latest('import')->where('purchase_order_id', $order->id)->exists(), 'purchase_order_id', 'A ordem já tem processo de importação. Consulte-o sem duplicar a compra.');
$this->check(! GoodsReceipt::query()->where('purchase_order_id', $order->id)->exists(), 'purchase_order_id', 'Registe a importação antes da primeira recepção da ordem.'); $this->check(! GoodsReceipt::query()->where('purchase_order_id', $order->id)->exists(), 'purchase_order_id', 'Registe a importação antes da primeira recepção da ordem.');
} }
if ($kind === 'import' && $old !== null && $old->purchase_order_id !== $order->id) {
$this->check(! $this->latest('import')->where('purchase_order_id', $order->id)->where('record_key', '!=', $old->record_key)->exists(),
'purchase_order_id', 'A ordem de destino já tem um processo de importação.');
$this->check(! SupplyRecord::query()->whereIn('kind', ['import_cost_doc', 'import_cost_plan', 'import_cost_event'])
->where('snapshot->import_key', $old->record_key)->exists(), 'purchase_order_id', 'A importação já conserva documentos ou custos financeiros. Preserve a ligação à ordem de origem.');
}
$snapshot = $action === 'save' ? ['prepared_by' => $actor->id, 'contributors' => array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id])), 'item' => $item?->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse?->only(['id', 'code', 'name']), $snapshot = $action === 'save' ? ['prepared_by' => $actor->id, 'contributors' => array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id])), 'item' => $item?->only(['id', 'code', 'name', 'unit']), 'warehouse' => $warehouse?->only(['id', 'code', 'name']),
'supplier' => $supplier?->only(['id', 'name', 'version']), 'order' => $order?->only(['id', 'number', 'currency', 'supplier_id', 'total_minor'])] : $old->snapshot; 'supplier' => $supplier?->only(['id', 'name', 'version']), 'order' => $order?->only(['id', 'number', 'currency', 'supplier_id', 'total_minor'])] : $old->snapshot;
if ($action === 'save' && $kind === 'agreement' && ! empty($data['contract_key'])) { if ($action === 'save' && $kind === 'agreement' && ! empty($data['contract_key'])) {
+6
View File
@@ -0,0 +1,6 @@
<?php
return [
// Development/QA only; operational activation is outside the approved scope.
'qa_enabled' => env('SGC_IMPORT_LANDED_COSTS_QA_ENABLED', false),
];
+3
View File
@@ -0,0 +1,3 @@
<?php
return ['qa_enabled' => false];
+1 -1
View File
@@ -2,5 +2,5 @@
return [ return [
// No operational activation path is included in this authorization. // No operational activation path is included in this authorization.
'qa_enabled' => false, 'qa_enabled' => env('SGC_ORDER_PARTS_QA_ENABLED', false),
]; ];
@@ -0,0 +1,72 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
// Approved multi-order host adaptation, exclusively on disposable QA.
return new class extends Migration
{
public function up(): void
{
$db = DB::connection();
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
if (! app()->environment('testing') || ! $isolated) {
throw new LogicException('Order-source schema requires disposable QA.');
}
$schema = $db->getSchemaBuilder();
if ($schema->hasTable('purchase_order_sources') || $schema->hasColumn('purchase_orders', 'order_key') || ! $schema->hasTable('budget_order_commands')) {
throw new LogicException('Install the optional financial schema first; do not reinstall or repair a partial host schema automatically.');
}
$db->transaction(function () use ($db, $schema): void {
$schema->table('purchase_orders', function (Blueprint $table): void {
$table->dropUnique(['requisition_id']);
$table->dropUnique(['purchase_award_id']);
$table->uuid('order_key')->nullable();
$table->string('order_payload_hash', 64)->nullable();
$table->unsignedInteger('order_source_count')->nullable();
$table->unique(['tenant_id', 'order_key']);
});
$schema->table('purchase_order_items', function (Blueprint $table): void {
$table->foreignId('quotation_item_id')->nullable()->constrained()->restrictOnDelete();
$table->unsignedBigInteger('quantity_offset_milli')->nullable();
});
$schema->create('purchase_order_sources', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->foreignId('purchase_order_id')->constrained()->restrictOnDelete();
$table->foreignId('requisition_id')->constrained()->restrictOnDelete();
$table->foreignId('purchase_award_id')->constrained()->restrictOnDelete();
$table->foreignId('quotation_id')->constrained()->restrictOnDelete();
$table->json('snapshot');
$table->unique(['purchase_order_id', 'requisition_id']);
});
if ($db->getDriverName() === 'pgsql') {
$db->statement('CREATE TRIGGER distribution_history_guard BEFORE UPDATE OR DELETE ON purchase_order_sources FOR EACH ROW EXECUTE FUNCTION sgc_distribution_history_guard()');
$db->unprepared(<<<'SQL'
CREATE FUNCTION sgc_order_parts_header_guard() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF OLD.order_key IS NOT NULL THEN
IF TG_OP = 'DELETE' THEN RAISE EXCEPTION 'Preserve partial order history'; END IF;
IF (to_jsonb(NEW) - 'number' - 'status') IS DISTINCT FROM (to_jsonb(OLD) - 'number' - 'status') THEN
RAISE EXCEPTION 'Preserve the frozen partial order';
END IF;
ELSIF TG_OP = 'UPDATE' AND NEW.order_key IS NOT NULL THEN
RAISE EXCEPTION 'Do not relabel an issued legacy order';
END IF;
IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
RETURN NEW;
END $$;
CREATE TRIGGER order_parts_header_guard BEFORE UPDATE OR DELETE ON purchase_orders FOR EACH ROW EXECUTE FUNCTION sgc_order_parts_header_guard();
CREATE TRIGGER order_parts_line_guard BEFORE UPDATE OR DELETE ON purchase_order_items FOR EACH ROW WHEN (OLD.quotation_item_id IS NOT NULL) EXECUTE FUNCTION sgc_distribution_history_guard();
SQL);
}
});
}
public function down(): void
{
throw new LogicException('Use verified recovery; never discard order lineage or restore single-order uniqueness over issued documents.');
}
};
@@ -0,0 +1,72 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
// Explicit isolated QA only; not a default or deployment migration.
return new class extends Migration
{
public function up(): void
{
$db = DB::connection();
$isolated = ($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|| ($db->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName()));
if (! app()->environment('testing') || ! $isolated) {
throw new LogicException('Landed cost effects require a guarded disposable QA database.');
}
$schema = $db->getSchemaBuilder();
$tables = ['budget_landed_commands', 'budget_landed_entries'];
if ($schema->hasTable($tables[0]) || $schema->hasTable($tables[1])) {
throw new LogicException('Never reinstall or repair landed-cost financial history implicitly.');
}
$db->transaction(function () use ($schema, $db, $tables): void {
$schema->create('budget_landed_commands', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->foreignId('created_by')->constrained('users')->restrictOnDelete();
$table->uuid('operation_key');
$table->uuid('plan_key');
$table->unsignedInteger('plan_version');
$table->string('plan_hash', 64);
$table->string('kind', 20);
$table->string('payload_hash', 64);
$table->json('snapshot');
$table->timestamp('created_at');
$table->unique(['tenant_id', 'operation_key']);
$table->index(['tenant_id', 'plan_key', 'id']);
});
$schema->create('budget_landed_entries', function (Blueprint $table): void {
$table->id();
$table->foreignId('tenant_id')->constrained()->restrictOnDelete();
$table->foreignId('command_id')->constrained('budget_landed_commands')->restrictOnDelete();
$table->foreignId('budget_id')->constrained('budgets')->restrictOnDelete();
$table->string('source_key', 120);
$table->string('source_kind', 30);
$table->unsignedBigInteger('source_id');
$table->unsignedInteger('source_version');
$table->string('source_revision', 64);
$table->json('source_snapshot');
$table->bigInteger('reserved_minor');
$table->bigInteger('committed_minor');
$table->bigInteger('consumed_minor');
$table->unique(['command_id', 'source_key']);
$table->index(['tenant_id', 'source_key']);
});
foreach ($tables as $table) {
if ($db->getDriverName() === 'pgsql') {
$db->unprepared('CREATE FUNCTION preserve_'.$table.'() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION \'Preserve landed cost history\'; END $$;');
$db->statement('CREATE TRIGGER immutable_landed_history BEFORE UPDATE OR DELETE ON '.$table.' FOR EACH ROW EXECUTE FUNCTION preserve_'.$table.'()');
} else {
$db->unprepared('CREATE TRIGGER '.$table.'_update BEFORE UPDATE ON '.$table." BEGIN SELECT RAISE(ABORT, 'Preserve landed cost history'); END;");
$db->unprepared('CREATE TRIGGER '.$table.'_delete BEFORE DELETE ON '.$table." BEGIN SELECT RAISE(ABORT, 'Preserve landed cost history'); END;");
}
}
});
}
public function down(): void
{
throw new LogicException('Recover from a verified pre-extension backup; never delete financial history.');
}
};
+10
View File
@@ -1,5 +1,15 @@
# Desenvolvimento do SGC # Desenvolvimento do SGC
## Estado reconciliado mais recente - 22/11/2026
Ordens parciais/consolidadas em MZN: emissão nativa, origens, recepção, factura com validação independente e cancelamento C2 por Finanças implementados em QA. PostgreSQL 56 testes/498 verificações; delta HTTP final 1/25. A revisão nativa observou uma ordem sintética de 100 MZN, parcelas de 40/60 MZN e apresentação a 390/1000 px. A ferramenta interrompeu o controlo antes da paginação de impressão; restante percurso visual continua pendente. Servidor, base e configuração privados removidos. Prova: `proofs/rq01-multi-order-native-qa.json`. Câmbio por origem, reafectação de Finanças e disponibilização operacional continuam por concluir.
Custo de aterragem: extensão QA autorizada em `proofs/import-landed-cost-contract-authorization.json`. Reserva, compromisso, consumo, alteração e cancelamento por origem documental implementados no motor comum, com revisão financeira explícita, saldos mistos e preservação do consumo anterior. Facturas nativas conservam o seu principal e autoridade; encargos adicionais não criam facturas fictícias. Fontes privadas/correcções, revisão independente, formulários recuperáveis e referências opcionais aos artigos estão integrados, sem novo writer de stock. Inspecção operacional detecta evidência em falta, alterada ou sem referência, com saída agregada. SQLite nativo/operacional 22/146; PostgreSQL alargado 147/846; concorrência real e restauro pré/pós-extensão aprovados, bases removidas. Runtime instalado V1 e QA financeiro v1 recusam saldos v2 (503). Tipos, análise estática e build privado aprovados. Permanecem a estimativa anterior aos documentos efectivos, restantes requisitos de importação, revisão visual/móvel/impressão e preparação operacional. O restauro adicional recuperou duas versões privadas após perda simulada, com hashes e acesso nativo conferidos; SQL anterior/posterior e bases descartáveis preservados/removidas conforme a prova. Testes dirigidos finais nativos, saúde e protocolo: 25/157. Prova: `proofs/import-landed-cost-qa.json`.
Classificação pautal documental: cadastro do material versionado, proposta por artigo da requisição, selecção explícita do material e confirmação/desvio pelo comprador implementados em QA. Código desconhecido conserva-se por completar. Mudanças no cadastro não reescrevem confirmações ou ordens anteriores. Isolamento e permissões actuais, histórico, formulários recuperáveis e ajuda integrados. SQLite 5/53; PostgreSQL com catálogo nativo 9/112, base removida; tipos, PHPStan, oito testes de ajuda e build privado aprovados. Emissão normal/parcial conserva a confirmação na ordem, ficha, impressão e custo de importação; propostas pendentes recusam nova emissão. A recepção exige processo de importação e libertção aduaneira, com um único movimento. PostgreSQL dirigido: ligação de ordens 8/212 e regressão multimoeda/documentos anteriores 8/157. Regressão de recepção/stock: 44/45 passaram; comparação do agregado SQL corrigida e validada num delta isolado 1/30, sem declarar aprovada uma reexecução integral. Ainda faltam sugestões legais versionadas, estimativas, dossiê tipificado, demais ligações e revisão visual. Sem novas taxas, migração ou activação operacional. Prova: `proofs/import-tariffs-qa.json`.
Piloto preservado: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; nenhuma nova instalação, activação, concessão ou operação real. O SGC integral e os novos requisitos de importação continuam em desenvolvimento; as secções anteriores são históricas quando divergirem deste estado.
## Importação directa na especificação actualizada - 22/11/2026 ## Importação directa na especificação actualizada - 22/11/2026
O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9. O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9.
+10
View File
@@ -1,5 +1,15 @@
# Matriz reconciliada do SGC — 03/11/2026 # Matriz reconciliada do SGC — 03/11/2026
## Estado reconciliado mais recente - 22/11/2026
Ordens parciais/consolidadas em MZN: emissão nativa, origens, recepção, factura com validação independente e cancelamento C2 por Finanças implementados em QA. PostgreSQL 56 testes/498 verificações; delta HTTP final 1/25. A revisão nativa observou uma ordem sintética de 100 MZN, parcelas de 40/60 MZN e apresentação a 390/1000 px. A ferramenta interrompeu o controlo antes da paginação de impressão; restante percurso visual continua pendente. Servidor, base e configuração privados removidos. Prova: `proofs/rq01-multi-order-native-qa.json`. Câmbio por origem, reafectação de Finanças e disponibilização operacional continuam por concluir.
Custo de aterragem: extensão QA autorizada em `proofs/import-landed-cost-contract-authorization.json`. Reserva, compromisso, consumo, alteração e cancelamento por origem documental implementados no motor comum, com revisão financeira explícita, saldos mistos e preservação do consumo anterior. Facturas nativas conservam o seu principal e autoridade; encargos adicionais não criam facturas fictícias. Fontes privadas/correcções, revisão independente, formulários recuperáveis e referências opcionais aos artigos estão integrados, sem novo writer de stock. Inspecção operacional detecta evidência em falta, alterada ou sem referência, com saída agregada. SQLite nativo/operacional 22/146; PostgreSQL alargado 147/846; concorrência real e restauro pré/pós-extensão aprovados, bases removidas. Runtime instalado V1 e QA financeiro v1 recusam saldos v2 (503). Tipos, análise estática e build privado aprovados. Permanecem a estimativa anterior aos documentos efectivos, restantes requisitos de importação, revisão visual/móvel/impressão e preparação operacional. O restauro adicional recuperou duas versões privadas após perda simulada, com hashes e acesso nativo conferidos; SQL anterior/posterior e bases descartáveis preservados/removidas conforme a prova. Testes dirigidos finais nativos, saúde e protocolo: 25/157. Prova: `proofs/import-landed-cost-qa.json`.
Classificação pautal documental: cadastro do material versionado, proposta por artigo da requisição, selecção explícita do material e confirmação/desvio pelo comprador implementados em QA. Código desconhecido conserva-se por completar. Mudanças no cadastro não reescrevem confirmações ou ordens anteriores. Isolamento e permissões actuais, histórico, formulários recuperáveis e ajuda integrados. SQLite 5/53; PostgreSQL com catálogo nativo 9/112, base removida; tipos, PHPStan, oito testes de ajuda e build privado aprovados. Emissão normal/parcial conserva a confirmação na ordem, ficha, impressão e custo de importação; propostas pendentes recusam nova emissão. A recepção exige processo de importação e libertção aduaneira, com um único movimento. PostgreSQL dirigido: ligação de ordens 8/212 e regressão multimoeda/documentos anteriores 8/157. Regressão de recepção/stock: 44/45 passaram; comparação do agregado SQL corrigida e validada num delta isolado 1/30, sem declarar aprovada uma reexecução integral. Ainda faltam sugestões legais versionadas, estimativas, dossiê tipificado, demais ligações e revisão visual. Sem novas taxas, migração ou activação operacional. Prova: `proofs/import-tariffs-qa.json`.
Piloto preservado: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; nenhuma nova instalação, activação, concessão ou operação real. O SGC integral e os novos requisitos de importação continuam em desenvolvimento; as secções anteriores são históricas quando divergirem deste estado.
## Importação directa na especificação actualizada - 22/11/2026 ## Importação directa na especificação actualizada - 22/11/2026
O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9. O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9.
+6 -2
View File
@@ -1,6 +1,6 @@
# O2 — diagnóstico operacional integrado # O2 — diagnóstico operacional integrado
03/11/2026. O comando `php artisan sgc:operations-check --json` reúne as verificações existentes de reposição durável e integridade documental da recepção. Não instala serviços nem executa recuperação, compras, aprovações ou reparações. Os comandos individuais continuam disponíveis. Actualização de 22/11/2026. O comando `php artisan sgc:operations-check --json` reúne as verificações de reposição durável, documentos da recepção e evidências privadas dos custos de importação. Não instala serviços nem executa recuperação, compras, aprovações ou reparações. Os comandos individuais existentes continuam disponíveis.
`--document-limit=1000` limita a verificação documental de 1 a 10000 registos/ficheiros, segundo o verificador nativo. Limites inválidos devolvem código 2 antes de inspeccionar. O comando só pode executar em consola, sem identidade autenticada ou sessão interactiva, pois agrega observações de várias empresas. `--document-limit=1000` limita a verificação documental de 1 a 10000 registos/ficheiros, segundo o verificador nativo. Limites inválidos devolvem código 2 antes de inspeccionar. O comando só pode executar em consola, sem identidade autenticada ou sessão interactiva, pois agrega observações de várias empresas.
@@ -13,7 +13,11 @@ Estados por verificação:
- `incomplete`: a verificação não cobriu todo o âmbito, por exemplo limite documental atingido ou estrutura indisponível. - `incomplete`: a verificação não cobriu todo o âmbito, por exemplo limite documental atingido ou estrutura indisponível.
- `unavailable`: erro na execução; o outro verificador continua e o resultado apresenta apenas motivo genérico. - `unavailable`: erro na execução; o outro verificador continua e o resultado apresenta apenas motivo genérico.
`ok` só é verdadeiro se ambas passarem. `complete` indica apenas que ambas as consultas terminaram com cobertura completa; pode ser verdadeiro com `ok=false`. Código de saída 0 indica ausência de divergências observadas e 1 indica atenção/incompletude/indisponibilidade. Não certifica prontidão comercial, cópias de segurança, restauro, capacidade, serviço instalado ou aprovação humana. `ok` só é verdadeiro se todas passarem. `complete` indica apenas que todas as consultas terminaram com cobertura completa; pode ser verdadeiro com `ok=false`. Código de saída 0 indica ausência de divergências observadas e 1 indica atenção/incompletude/indisponibilidade. Não certifica prontidão comercial, cópias de segurança, restauro, capacidade, serviço instalado ou aprovação humana.
`import_cost_documents` confere todas as versões conservadas de `import_cost_doc`, o vínculo empresa/ordem, o caminho privado esperado, tamanho até 2 MB e SHA-256. Só calcula o hash quando o tamanho coincide. A listagem de ficheiros sem referência limita-se a `import-costs` no disco privado `local`; documentos e ficheiros têm limites independentes. A inspecção não depende da activação do formulário e continua a detectar perdas quando a funcionalidade está desligada. Não publica caminhos, nomes ou conteúdo; não elimina ficheiros sem referência.
A recuperação QA de importação inclui cópia dos bytes de duas versões sintéticas, detecção da sua perda e restauro num directório privado separado, em conjunto com metadados SQL restaurados. Os hashes e o acesso nativo às duas versões são conferidos. Os ficheiros de teste não representam documentos aduaneiros reais nem uma revisão visual de PDF. Esta prova não instala um serviço de backup: a instalação deve incluir o directório privado `import-costs` e todos os históricos referenciados no plano de cópia/restauro, preservando a configuração, sem publicar esse directório. Provas e limites em `proofs/import-landed-cost-qa.json`.
O comando não inclui nomes, identificadores de empresas, caminhos privados ou credenciais no resultado. Excepções conservam o registo técnico existente; a saída não inclui a mensagem privada. Não agenda tarefas, publica notificações nem grava telemetria. Quem monitoriza pode integrar o código de saída e o JSON conforme a instalação autorizada. O comando não inclui nomes, identificadores de empresas, caminhos privados ou credenciais no resultado. Excepções conservam o registo técnico existente; a saída não inclui a mensagem privada. Não agenda tarefas, publica notificações nem grava telemetria. Quem monitoriza pode integrar o código de saída e o JSON conforme a instalação autorizada.
+10
View File
@@ -1,5 +1,15 @@
# Continuidade do desenvolvimento do SGC # Continuidade do desenvolvimento do SGC
## Estado reconciliado mais recente - 22/11/2026
Ordens parciais/consolidadas em MZN: emissão nativa, origens, recepção, factura com validação independente e cancelamento C2 por Finanças implementados em QA. PostgreSQL 56 testes/498 verificações; delta HTTP final 1/25. A revisão nativa observou uma ordem sintética de 100 MZN, parcelas de 40/60 MZN e apresentação a 390/1000 px. A ferramenta interrompeu o controlo antes da paginação de impressão; restante percurso visual continua pendente. Servidor, base e configuração privados removidos. Prova: `proofs/rq01-multi-order-native-qa.json`. Câmbio por origem, reafectação de Finanças e disponibilização operacional continuam por concluir.
Custo de aterragem: extensão QA autorizada em `proofs/import-landed-cost-contract-authorization.json`. Reserva, compromisso, consumo, alteração e cancelamento por origem documental implementados no motor comum, com revisão financeira explícita, saldos mistos e preservação do consumo anterior. Facturas nativas conservam o seu principal e autoridade; encargos adicionais não criam facturas fictícias. Fontes privadas/correcções, revisão independente, formulários recuperáveis e referências opcionais aos artigos estão integrados, sem novo writer de stock. Inspecção operacional detecta evidência em falta, alterada ou sem referência, com saída agregada. SQLite nativo/operacional 22/146; PostgreSQL alargado 147/846; concorrência real e restauro pré/pós-extensão aprovados, bases removidas. Runtime instalado V1 e QA financeiro v1 recusam saldos v2 (503). Tipos, análise estática e build privado aprovados. Permanecem a estimativa anterior aos documentos efectivos, restantes requisitos de importação, revisão visual/móvel/impressão e preparação operacional. O restauro adicional recuperou duas versões privadas após perda simulada, com hashes e acesso nativo conferidos; SQL anterior/posterior e bases descartáveis preservados/removidas conforme a prova. Testes dirigidos finais nativos, saúde e protocolo: 25/157. Prova: `proofs/import-landed-cost-qa.json`.
Classificação pautal documental: cadastro do material versionado, proposta por artigo da requisição, selecção explícita do material e confirmação/desvio pelo comprador implementados em QA. Código desconhecido conserva-se por completar. Mudanças no cadastro não reescrevem confirmações ou ordens anteriores. Isolamento e permissões actuais, histórico, formulários recuperáveis e ajuda integrados. SQLite 5/53; PostgreSQL com catálogo nativo 9/112, base removida; tipos, PHPStan, oito testes de ajuda e build privado aprovados. Emissão normal/parcial conserva a confirmação na ordem, ficha, impressão e custo de importação; propostas pendentes recusam nova emissão. A recepção exige processo de importação e libertção aduaneira, com um único movimento. PostgreSQL dirigido: ligação de ordens 8/212 e regressão multimoeda/documentos anteriores 8/157. Regressão de recepção/stock: 44/45 passaram; comparação do agregado SQL corrigida e validada num delta isolado 1/30, sem declarar aprovada uma reexecução integral. Ainda faltam sugestões legais versionadas, estimativas, dossiê tipificado, demais ligações e revisão visual. Sem novas taxas, migração ou activação operacional. Prova: `proofs/import-tariffs-qa.json`.
Piloto preservado: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; nenhuma nova instalação, activação, concessão ou operação real. O SGC integral e os novos requisitos de importação continuam em desenvolvimento; as secções anteriores são históricas quando divergirem deste estado.
## Importação directa na especificação actualizada - 22/11/2026 ## Importação directa na especificação actualizada - 22/11/2026
O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9. O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9.
+10
View File
@@ -1,5 +1,15 @@
# Entregas por blocos funcionais do SGC # Entregas por blocos funcionais do SGC
## Estado reconciliado mais recente - 22/11/2026
Ordens parciais/consolidadas em MZN: emissão nativa, origens, recepção, factura com validação independente e cancelamento C2 por Finanças implementados em QA. PostgreSQL 56 testes/498 verificações; delta HTTP final 1/25. A revisão nativa observou uma ordem sintética de 100 MZN, parcelas de 40/60 MZN e apresentação a 390/1000 px. A ferramenta interrompeu o controlo antes da paginação de impressão; restante percurso visual continua pendente. Servidor, base e configuração privados removidos. Prova: `proofs/rq01-multi-order-native-qa.json`. Câmbio por origem, reafectação de Finanças e disponibilização operacional continuam por concluir.
Custo de aterragem: extensão QA autorizada em `proofs/import-landed-cost-contract-authorization.json`. Reserva, compromisso, consumo, alteração e cancelamento por origem documental implementados no motor comum, com revisão financeira explícita, saldos mistos e preservação do consumo anterior. Facturas nativas conservam o seu principal e autoridade; encargos adicionais não criam facturas fictícias. Fontes privadas/correcções, revisão independente, formulários recuperáveis e referências opcionais aos artigos estão integrados, sem novo writer de stock. Inspecção operacional detecta evidência em falta, alterada ou sem referência, com saída agregada. SQLite nativo/operacional 22/146; PostgreSQL alargado 147/846; concorrência real e restauro pré/pós-extensão aprovados, bases removidas. Runtime instalado V1 e QA financeiro v1 recusam saldos v2 (503). Tipos, análise estática e build privado aprovados. Permanecem a estimativa anterior aos documentos efectivos, restantes requisitos de importação, revisão visual/móvel/impressão e preparação operacional. O restauro adicional recuperou duas versões privadas após perda simulada, com hashes e acesso nativo conferidos; SQL anterior/posterior e bases descartáveis preservados/removidas conforme a prova. Testes dirigidos finais nativos, saúde e protocolo: 25/157. Prova: `proofs/import-landed-cost-qa.json`.
Classificação pautal documental: cadastro do material versionado, proposta por artigo da requisição, selecção explícita do material e confirmação/desvio pelo comprador implementados em QA. Código desconhecido conserva-se por completar. Mudanças no cadastro não reescrevem confirmações ou ordens anteriores. Isolamento e permissões actuais, histórico, formulários recuperáveis e ajuda integrados. SQLite 5/53; PostgreSQL com catálogo nativo 9/112, base removida; tipos, PHPStan, oito testes de ajuda e build privado aprovados. Emissão normal/parcial conserva a confirmação na ordem, ficha, impressão e custo de importação; propostas pendentes recusam nova emissão. A recepção exige processo de importação e libertção aduaneira, com um único movimento. PostgreSQL dirigido: ligação de ordens 8/212 e regressão multimoeda/documentos anteriores 8/157. Regressão de recepção/stock: 44/45 passaram; comparação do agregado SQL corrigida e validada num delta isolado 1/30, sem declarar aprovada uma reexecução integral. Ainda faltam sugestões legais versionadas, estimativas, dossiê tipificado, demais ligações e revisão visual. Sem novas taxas, migração ou activação operacional. Prova: `proofs/import-tariffs-qa.json`.
Piloto preservado: manifesto `1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e`; nenhuma nova instalação, activação, concessão ou operação real. O SGC integral e os novos requisitos de importação continuam em desenvolvimento; as secções anteriores são históricas quando divergirem deste estado.
## Importação directa na especificação actualizada - 22/11/2026 ## Importação directa na especificação actualizada - 22/11/2026
O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9. O proprietário forneceu uma nova versão de `A requisção de insumos de produção.docx`: SHA256 `9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408`, 567 parágrafos, sem documentos incorporados. A leitura partilhada preservou o original aberto. O exemplar anterior e a sua autorização mantêm-se como histórico; a secção 10 acrescenta requisitos de importação, além dos controlos de conflito da secção 9.
@@ -0,0 +1,15 @@
{
"date": "2026-11-22",
"status": "approved_for_development_and_isolated_qa_only",
"owner_response": "Autorizar a extensão em QA",
"proposal": "import-landed-cost-contract-proposal.json",
"proposal_sha256": "7f62d7d3ef9c88f667a57ad5d9351eadccd16a2506ce5c4095ecbfcef9814dd5",
"scope": "Common financial contract canonical source and SGC adaptation for explicit landed-cost components and separate native documentary origins as proposed",
"excluded": [
"Published/installed artifacts",
"Pilot or SGF migration, installation or activation",
"Real data or permission changes",
"Bank/JUE execution, customs payment, legal-rate activation",
"Inventory stock/valuation contract changes and accounting postings"
]
}
@@ -0,0 +1,72 @@
{
"date": "2026-11-22",
"status": "prepared_awaiting_specific_qa_financial_contract_authorization",
"source_requirements": "rq01-import-reconciliation.json",
"source_sha256": "9646630ac9b7e08cf84f3e93efc6cf1a90657cdc3e59d680621b74238d3a7408",
"functional_source_sections": [
"10.1",
"10.4",
"10.6",
"10.8"
],
"problem": "The existing common budget source and native invoice principal cover the supplier goods purchase. Landed cost also includes carrier/insurer/customs components with different native documentary origins; adding them to a supplier invoice would fabricate a debt or duplicate another principal. The order-parts authorization does not establish those new financial origins.",
"current_common_source_sha256": "6c4d043fb505622649e03cca510f7027cdb511e713c43c9a6ac4447661c3f9ee",
"requested_scope": [
"Extend only the canonical common budget source and SGC adapter in isolated development/QA for explicitly identified landed-cost components",
"Keep one budget authority and preserve existing V1/order-part capabilities and installed pilot artifact",
"Maintain separate versioned goods, freight, insurance, duties, ICE, VAT and other documented customs components, each with actual native origin identity, original currency and explicitly frozen Finance rate when relevant",
"Apply the existing budget subtotal/total basis to explicit component values; do not infer VAT recoverability, tax applicability, exemption or legal rate",
"Reconcile estimate/reservation/commitment and explicit reviewed actual-cost changes against native approvals and available funds; keep previous versions",
"Use the actual authorized document type for each consumption; do not create a fictional supplier invoice for customs duties or aggregate different creditors into the goods invoice",
"Preserve independent supplier-invoice principals, cumulative limits, operation identities and per-origin cancellation/recovery",
"Only preserve cost-to-item allocation references for inventory integration at this stage; do not create a second stock/valuation writer or change the installed inventory contract"
],
"illustrative_synthetic_acceptance": {
"not_a_legal_rate_or_real_import": true,
"components": [
{
"native_origin": "supplier_invoice",
"subtotal_minor": 10000,
"tax_minor": 1600,
"total_minor": 11600
},
{
"native_origin": "carrier_invoice",
"subtotal_minor": 1000,
"tax_minor": 160,
"total_minor": 1160
},
{
"native_origin": "customs_assessment",
"subtotal_minor": 2000,
"tax_minor": 0,
"total_minor": 2000,
"tax_note": "Explicitly known zero in this synthetic fixture, not a fallback or a legal exemption"
}
],
"budget_reference": {
"subtotal_minor": 13000,
"total_minor": 14760
},
"assertions": [
"One reservation/commitment reconciled to 13000 or 14760 according to the existing explicit budget tax basis",
"Supplier principal remains 11600; carrier principal remains 1160; customs source remains separate at 2000",
"A missing duty, tax rule or conversion rate remains indeterminate; no zero default, automatic compensation or operational activation",
"A source replay produces no duplicate budget consumption or creditor principal"
]
},
"required_verification": [
"Focused native and common financial regression, exact sums and unknown-value failures",
"Company and role isolation, independent Finance review, stale versions and atomic rollback",
"Real disposable PostgreSQL concurrency and same-role pre/post-extension recovery",
"Legacy artifact compatibility and fail-closed downgrade with new data"
],
"excluded": [
"Published or installed packages",
"Pilot or SGF installation, migration or activation",
"Real company data or permissions",
"Bank/JUE submission, customs payment, tax declaration or legal-rate activation",
"Inventory valuation/stock-contract changes, accounting postings and production deployment"
],
"remaining_work_not_blocked_by_this_decision": "Native order-parts forms, read/print/mobile review and other already authorized QA development continue independently"
}
+143
View File
@@ -0,0 +1,143 @@
{
"date": "2026-11-22",
"status": "native_documentary_and_per_origin_financial_commands_verified_in_isolated_QA_remaining_import_requirements_in_progress",
"authorization": "import-landed-cost-contract-authorization.json",
"source_specification": "rq01-import-reconciliation.json",
"implemented": [
"Common exact per-document/per-creditor reconciliation with frozen MZN references",
"Native private customs/additional-charge evidence with hash checking and immutable corrective versions",
"Finance-only isolated-QA recording, source scope/conflict checks and native invoice resolution",
"Recoverable preparations, operation replay protection, stale-source checks and independent review",
"Authenticated forms, private evidence download, specific help and paginated sources/history",
"Existing validated invoice principals and budget effects are preserved; no fictional supplier invoice",
"Common reserve/commit/consume/amend/cancel with per-source positions, consumed floors, explicit financial revision and one audit/effect per operation",
"Native financial receipts atomic with common effects; a failing receipt insert rolls back commands, entries and audit",
"Mixed consumed/reserved states and reviewed late costs; only the incremental amount is encumbered",
"Logistics-only versions retain financial review and recoverable forms; cost context and documentary changes require a new independent review",
"Optional cost-to-native-item references frozen with item descriptions and quantities; no monetary allocation or stock writer",
"Bounded console inspection of historical private import evidence, hashes, missing/altered/orphan files and aggregate non-identifying output"
],
"verification": {
"SQLite_native_and_operational_health": {
"tests": 22,
"assertions": 146,
"log": "storage/logs/import-landed-cost-health-tests.txt"
},
"PostgreSQL_native_common_logistics_financial_operational_regression": {
"tests": 147,
"passed": 147,
"assertions": 846,
"database": "compras_receipts_test_626672ea66d6",
"database_removed": true,
"log": "storage/logs/import-landed-cost-final-pg.txt"
},
"real_PostgreSQL_concurrency": {
"log": "storage/logs/import-landed-cost-v2-concurrency.txt",
"database": "compras_receipts_test_a9f806b6f779",
"database_removed": true,
"scenarios": [
"same_operation: [200,200], one command/audit",
"conflicting_plan_version: [200,409], one command/audit",
"same_source_different_plan: [200,409], one command/audit"
],
"blocked_writers_observed_per_scenario": 2,
"older_installed_V1_and_whole_source_QA_v1_rejected_before_balance": 503
},
"same_role_PostgreSQL_recovery": {
"log": "storage/logs/import-landed-cost-v2-recovery.txt",
"previous_tables_preserved": 115,
"optional_tables": 2,
"post_restore_all_tables_equal": true,
"mixed_consumed_2000_reserved_500_replay_no_new_effect": true,
"pre_extension_schema_data_balance_restored": true,
"source_database_removed": true,
"restore_database_removed": true,
"before_dump_sha256": "6686cc91265dc9a438489d863f5ebd9adc74004ff269aa3a9c4e753ab9862e6d",
"after_dump_sha256": "9a77a7106b98a47bea71d9ea0ebdc561ec1162c77fe51f40ddc2f7c5a365fbff"
},
"frontend_parser_and_help": {
"tests": 17,
"log": "storage/logs/import-landed-cost-v2-ui-tests.txt"
},
"native_visual": "pending; prior Computer Use URL-confidence interruption preserved; no bypass/retry claimed",
"phpstan": "passed_zero_errors",
"typescript": "passed",
"scoped_format_and_lint": "passed",
"private_build": {
"exit_code": 0,
"manifest_sha256": "51df871f351e8781a1e657651e5924f799da26fe2fad0e096a6d7836aef9556b",
"log": "storage/logs/import-landed-cost-final-build.txt"
},
"private_evidence_SQL_recovery": {
"log": "storage/logs/import-landed-cost-evidence-recovery.txt",
"original_versions_restored": 2,
"actual_synthetic_source_loss_detected": true,
"separate_private_root_restored": true,
"native_authorized_evidence_resolved": true,
"evidence_manifest_sha256": "a3600e017e1b2c69787d0edd4917929b11d76a9ee2cf0d63d9eb5f5a5fe4eba6",
"post_extension_all_SQL_tables_equal": true,
"pre_extension_schema_data_balance_restored": true,
"source_database": "compras_receipts_test_e92f309b1085",
"restore_database": "compras_receipts_test_86a38a1f959d",
"both_databases_removed": true,
"not_a_rendered_PDF_or_commercial_backup_service_proof": true
},
"SQLite_final_native_health_protocol_delta": {
"tests": 25,
"assertions": 157,
"log": "storage/logs/import-landed-cost-evidence-final-tests.txt"
},
"latest_shared_private_build": {
"manifest_sha256": "f3bbf5518a88e3af4646f933856c95e2e9f51d246e357ffd31211bba88a01e5f",
"log": "storage/logs/import-tariffs-links-private-build.txt",
"exit_code": 0
}
},
"own_corrections": [
"Multipart monetary strings are validated and normalised as exact cent integers, with an authenticated-route regression",
"Older documentary values and bytes remain immutable after correction; stale preparations reject superseded sources",
"Mandatory concurrency/recovery receipts prevent Laravel CLI exit-zero failures from being accepted as proofs",
"Multipart money and financial revision normalized without floating arithmetic; stale financial revision rejects the action",
"Legacy invoice roles cannot acquire another financial source identity; same document version cannot change amounts",
"Operational text output updated for the additional inspection and covered by native CLI regression"
],
"remaining_authorized_work": [
"Landed-cost estimates before actual documentary sources, consumed-cost credit/refund handling if required by reconciled native contract",
"Further import requirements: tariff codes, broker/forwarder conflicts, typed dossier/JUE manual evidence, bank documentary support and versioned legal sources/alerts",
"Full native visual/mobile/print review, operational proposal and business acceptance",
"Operational backup/service configuration and capacity in the actual authorized destination; QA private-file recovery is proven separately"
],
"preserved": {
"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
"operational_flag_default": false,
"real_data_or_permissions_changed": false,
"bank_JUE_tax_activation_or_stock_valuation_changed": false,
"operational_migration_or_activation": false
},
"source_sha256": {
"bootstrap.php": "2ca32e23f75107c24e716d5935ed95b2e45a1b7bb4706adbd6d67a518f117984",
"src/BudgetControl.php": "d81f8fb172683727c221395224cecf9acb8285ab94e71e914141d41cf9e79efa",
"src/BudgetDistributions.php": "fb353e47c335728798a0e653653d4fdecd5cdce7659eefcaa74c028daafbb35f",
"src/BudgetOrderParts.php": "f639248062c43e4292a09473b9e722607fd5fc7f2a5e31173ee604913406be58",
"src/BudgetLandedCostPlan.php": "5a9f26b3d50abcb0bdc20c5571012da37b1f6403587ca68ea9573f08891f8c7a",
"src/BudgetLandedCosts.php": "59b4847040d4aaab42e8ec2e8a528dca92d14cb3272ff242981de93e36cf54c1"
},
"host_sha256": {
"app/Services/ImportLandedCosts.php": "b66aa5cc35157606d87af70389fed40465dabadbc43d95a9b4e32d085ca5852e",
"app/Services/ImportCostDocumentHealth.php": "282a1cab2c6f3e14d93efbde280c699d12a284828a6e19cdb894e3bf46a3b923",
"app/Services/OperationalHealth.php": "b19f8a366c9f05848e8e4b4173ef0c9cac19fdcd36eff4c0d5e21dd21083f5f3",
"app/Console/Commands/OperationsCheck.php": "1787d325f4eebd4b0196eb7685514c61ba9b1cd67a7a38d55ceb6cf03eba80fe",
"app/Http/Controllers/ImportLandedCostController.php": "914951bf60c67fb2b348f95332938cb32a287172fec8e05d34de91e28939b03f",
"resources/js/pages/supply/import-costs.tsx": "554e467262a4de71457521d9f14b1d052547b39bf43d95ceae4c287815beb702",
"config/import-landed-costs.php": "926005d192572657858bfe6194e2ce2ba34707e4a1fb128229e81c97d7acc55b",
"database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php": "c2b0a799157eab74da91c0c508887c7c1e80f171273f14190602ef7dbdb59828"
},
"financial_contract": "COMMON-BUDGET-LANDED-COST-QA-v2",
"qa_schema": {
"path": "database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php",
"outside_default_migrations": true,
"source_snapshot_required": true,
"applied_only_to_disposable_test_databases": true,
"operationally_applied": false
}
}
+145
View File
@@ -0,0 +1,145 @@
{
"date": "2026-11-22",
"status": "native_tariff_master_proposals_buyer_confirmation_order_freezing_and_customs_receipt_link_verified_in_isolated_QA",
"source_requirements": "rq01-import-reconciliation.json",
"source_sections": [
"10.1",
"10.2",
"10.6"
],
"implemented": [
"Versioned material-master tariff code and documentary source, preserving native stock facts",
"Explicit material selection or manual per-requisition-item proposal; unknown code stays null",
"Current Procurement confirmation retains proposed/final code, source, actor and deviation reason",
"Immutable historical versions, stale-master/version refusal, actor-bound operation replay and transactional audit",
"Company/request/item scope, current membership revalidation and existing material-catalog visibility",
"Private encrypted-history forms, remembered data, departure protection, pagination and contextual help",
"New native normal/partial/consolidated orders freeze confirmed imported-item classifications; unconfirmed marked items reject before budget effects",
"Order screen, native Blade print and landed-cost workspace reuse the frozen order classification, preserving existing documents",
"Classified imported orders require a native import process and independent customs release before usable receipt; arrival alone remains insufficient; replay preserves one physical movement"
],
"verification": {
"SQLite": {
"tests": 5,
"assertions": 49,
"log": "storage/logs/import-tariffs-final-native.txt",
"uses_default_installed_common_runtime_without_landed_financial_dependency": true
},
"PostgreSQL_with_native_requisition_catalogue": {
"tests": 9,
"assertions": 112,
"log": "storage/logs/import-tariffs-catalogue-current-pg.txt",
"database": "compras_receipts_test_30a47ee88442",
"database_removed": true
},
"frontend_help": {
"tests": 8,
"log": "storage/logs/import-tariffs-help-tests.txt"
},
"phpstan": "passed_zero_errors",
"typescript": "passed",
"scoped_format_lint": "passed",
"private_build": {
"exit_code": 0,
"manifest_sha256": "f3bbf5518a88e3af4646f933856c95e2e9f51d246e357ffd31211bba88a01e5f",
"log": "storage/logs/import-tariffs-links-private-build.txt"
},
"native_visual_mobile_print": "pending; no new browser proof claimed",
"PostgreSQL_native_order_connection": {
"tests": 8,
"assertions": 212,
"log": "storage/logs/import-tariffs-orders-isolated-pg.txt",
"database": "compras_receipts_test_8fca1b135f98",
"database_removed": true
},
"PostgreSQL_foreign_legacy_approval_regression": {
"tests": 8,
"assertions": 157,
"log": "storage/logs/import-tariffs-order-regression-pg.txt",
"database": "compras_receipts_test_d59f03cc3ae3",
"database_removed": true
},
"SQLite_latest_validation_delta": {
"tests": 5,
"assertions": 53,
"log": "storage/logs/import-tariffs-link-validation-tests.txt"
},
"SQLite_cost_classification_connection": {
"tests": 22,
"assertions": 163,
"log": "storage/logs/import-tariffs-links-native-tests.txt"
},
"SQLite_customs_receipt_connection": {
"tests": 1,
"assertions": 25,
"log": "storage/logs/import-tariffs-receipt-tests.txt"
},
"PostgreSQL_receipt_stock_regression": {
"tests": 45,
"passed": 44,
"assertions": 531,
"result": "one_test_only_aggregate_type_mismatch_then_corrected_in_focused_delta",
"log": "storage/logs/import-tariffs-receipt-pg.txt",
"database": "compras_receipts_test_d467be2a92ad",
"database_removed": true,
"focused_corrected_case_log": "storage/logs/import-tariffs-catalogue-receipt-delta-pg.txt",
"complete_suite_rerun_claimed": false,
"focused_corrected_case": {
"tests": 1,
"assertions": 30,
"database": "compras_receipts_test_721d1ad1998c",
"database_removed": true
}
},
"harness_isolation_regression": {
"tests": 4,
"assertions": 13,
"log": "storage/logs/import-tariffs-isolation-tests.txt",
"separate_Pest_kernels_cannot_reuse_one_database": true
},
"failed_diagnostic_attempts": [
{
"log": "storage/logs/import-tariffs-issuance-pg.txt",
"cause": "Full 87-declaration purchase-order suite exceeded the existing 180-second process limit; no pass claimed; disposable database removed"
},
{
"log": "storage/logs/import-tariffs-issuance-partitioned-pg.txt",
"cause": "Own harness reused a PostgreSQL database across Pest kernels; migration functions persisted. Corrected to separate disposable databases and guarded by regression tests; failed database removed"
}
],
"phpstan_final_log": "storage/logs/import-tariffs-complete-phpstan.txt"
},
"preserved": {
"operational_flag_default": false,
"operational_installation_activation": false,
"new_schema_migration": false,
"existing_orders_approvals_stock_or_financial_facts_changed": false,
"legal_rates_exemptions_licences_bank_or_JUE_activated": false,
"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e"
},
"remaining_authorized_work": [
"Official versioned tariff/legal suggestions, applicability and supporting-document rules; no active legal calculation is inferred from the Word summary",
"Native visual/mobile/print and operational readiness; product acceptance remains pending",
"Typed shipment/customs dossier, broker/forwarder conflicts and bank documentary tracking; whole-order import scope remains as the existing logistics model",
"Complete official-rule and import-estimate reconciliation plus remaining global SGC requirements"
],
"source_sha256": {
"app/Services/ImportTariffCodes.php": "cc0a7f9a2f5fd17612585ee8a2921bd9774c94cb7b17e01e51f93ef14e3725c6",
"app/Http/Controllers/ImportTariffController.php": "1ca9e66f793f429ea73da5271efd41fad6778fea0616bd63bd0ebd4181531bda",
"config/import-tariffs.php": "2153ea384c8396493f8b559265be4c4a27d2e12fb0184c6670da9bab5887b2af",
"resources/js/pages/supply/import-tariffs.tsx": "7fba4d5ad408697247e0f17be29b1aae3396cd8307a799cdb7599f9a6a5a693b",
"tests/Feature/ImportTariffCodesTest.php": "4c4bf70dc1792e88c5fe9742227f210d17d0035253ad2ac0365a78084ee010ea",
"app/Services/PurchaseWorkflow.php": "10d94902b74b7d8963b147e50e595fec9b954e1252e33fdbe6c77ebcd25e46f6",
"app/Services/OrderPartsWorkflow.php": "8b22d222e08639697c6c9ac730f4209f901bb890bc7f21c552724615bf2dbc41",
"app/Services/ReceiptWorkflow.php": "d5dd38f74ae29b327db712369a80287111d19f9a817b5a25bb599533be34b5ae",
"app/Services/ImportLandedCosts.php": "b66aa5cc35157606d87af70389fed40465dabadbc43d95a9b4e32d085ca5852e",
"resources/js/components/import-tariff-summary.tsx": "940095b110cdb281b0c1e2f83f313187798e0455f8a41cc1b4f19da54f49608d",
"resources/js/pages/supply/import-costs.tsx": "554e467262a4de71457521d9f14b1d052547b39bf43d95ceae4c287815beb702",
"resources/views/purchases/print.blade.php": "cd36077156a670995b8b6b8c38d6a6d843cb9e5d079ad0664885cfac5d4e5bdb"
},
"own_corrections": [
"Each Pest kernel now has its own disposable PostgreSQL database; mandatory proof helper is loaded before command isolation checks",
"Raw catalogue receipt SUM comparison normalised as an exact string for SQLite/PostgreSQL; expected 1000 remains unchanged",
"Receipt linkage corrected so a newly classified import cannot enter usable stock without a native import record and customs release"
]
}
+3 -3
View File
@@ -28,12 +28,12 @@
{ {
"section": "10.1-10.2", "section": "10.1-10.2",
"requirement": "Tariff code per imported item in material master/requisition, proposed classification, buyer confirmation or justified deviation", "requirement": "Tariff code per imported item in material master/requisition, proposed classification, buyer confirmation or justified deviation",
"state": "not covered by existing import metadata" "state": "Documentary material master, per-item proposal, buyer confirmation/deviation and frozen projection to new orders/screen/print/cost workspace verified in isolated QA. New classified imports require a native logistics process and independent customs release before usable receipts. Official legal suggestions and remaining import requirements remain pending; see import-tariffs-qa.json."
}, },
{ {
"section": "10.1,10.4", "section": "10.1,10.4",
"requirement": "Versioned landed-cost estimate with goods, freight, insurance, duties, taxes and customs expenses; native budget/approval basis and explicit actual-cost changes", "requirement": "Versioned landed-cost estimate with goods, freight, insurance, duties, taxes and customs expenses; native budget/approval basis and explicit actual-cost changes",
"state": "requires economic/budget reconciliation; no new financial authority implemented" "state": "Native actual-document landed-cost preparation and common per-source reserve/commit/consume/amend/cancel verified in isolated QA; native principals and consumed floors preserved. Pre-document estimates, operational readiness and visual acceptance remain pending. See import-landed-cost-qa.json."
}, },
{ {
"section": "10.2-10.3", "section": "10.2-10.3",
@@ -68,7 +68,7 @@
{ {
"section": "10.4", "section": "10.4",
"requirement": "Preserve customs originals, versions and audit evidence", "requirement": "Preserve customs originals, versions and audit evidence",
"state": "existing owner decision of integral preservation without automatic deletion remains in force" "state": "Private originals, immutable corrective versions, hash-checked download and bounded inspection implemented in isolated QA. Combined SQL/private-file recovery demonstrated source loss and restoration of two versions into a separate private root with native authorized evidence access. No automatic deletion; operational service installation and visual acceptance remain pending."
} }
], ],
"preserved": [ "preserved": [
@@ -0,0 +1,66 @@
{
"date": "2026-11-22",
"status": "native_MZN_journey_verified_in_isolated_QA_visual_review_partial",
"authorization": "rq01-multi-order-contract-authorization.json",
"implemented": [
"Native partial and consolidated MZN order issuance with approval and source revalidation",
"Explicit per-origin centre allocations and atomic budget commitment",
"All-origin visibility, conflict checks, immutable quantity offsets and source snapshots",
"Native receipt and independent invoice validation; one existing stock writer and one invoice principal",
"Existing C2 independent Finance cancellation, without cancelling the unissued requisition or restoring issuance capacity",
"Authenticated encrypted forms, saved preparations, specific help, source-aware detail and print reproduction"
],
"verification": {
"postgresql": {
"tests": 56,
"assertions": 498,
"log": "storage/logs/order-parts-native-pg.txt",
"database_removed": true
},
"final_HTTP_delta": {
"tests": 1,
"assertions": 25,
"log": "storage/logs/order-parts-native-final-http.txt"
},
"frontend_parser_and_help": {
"tests": 17,
"log": "storage/logs/import-landed-cost-ui-tests.txt"
},
"phpstan": "passed_zero_errors"
},
"visual": {
"private_database": "compras_receipts_test_01724507cff8",
"private_candidate_sha256": "9e9450b0ec4bbaf8241e46623e3598df2b06ecc2911cb0c59d7decdff876bc9c",
"synthetic_only": true,
"observed": [
"Recovered 0.400 and 0.600 source quantities after reload",
"Specific order-parts help and focus on preview",
"Explicit net/gross allocations of 20/20 and 30/30 across two centres",
"One native consolidated order OC-2026-000003, 100 MZN",
"Source approvals and original terms on 390px and 1000px views",
"Print reproduction retains both requisition origins and 40/60 MZN lines"
],
"not_verified": [
"Print-dialog pagination",
"Native visual receipt and invoice journey"
],
"interruption": "Computer Use stopped because it could not determine the current Windows browser URL with sufficient confidence; no bypass attempted",
"private_server_stopped": true,
"private_database_removed": true,
"private_settings_removed": true,
"cleanup_log": "storage/logs/order-parts-native-visual-server.txt"
},
"own_corrections": [
"Explicit server-derived metadata assignment avoids stale Eloquent guardable-column caches after optional QA DDL; regression warms the old model metadata",
"Cancellation follows the existing C2 Finance authority, correcting the prototype Procurement role",
"Display metadata no longer resets remembered financial imputations; native quantity or offset changes do"
],
"remaining": [
"Full per-origin foreign-currency issuance and explicit Finance amendments",
"Negative native document/source immutability and post-host-schema recovery delta",
"Remaining mobile/print/full-role visual review",
"Operational proposal and specific installation/activation approval"
],
"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e",
"published_or_installed_artifacts_changed": false
}
@@ -0,0 +1,58 @@
import { Panel } from '@/components/procurement';
export type FrozenImportTariff = {
record_id: number;
version: number;
item: { description: string; quantity: string; unit: string };
data: {
proposed_code: string | null;
confirmed_code: string;
source_reference: string | null;
confirmation_source: string;
deviation: boolean;
};
confirmed_by: { name: string };
reason: string;
};
export default function ImportTariffSummary({
records,
}: {
records?: Record<number, FrozenImportTariff>;
}) {
if (!records || !Object.keys(records).length) return null;
return (
<Panel title="Classificação pautal preservada na emissão">
<div className="grid gap-4">
{Object.values(records).map((record) => (
<dl
key={record.record_id}
className="rounded border p-3 text-sm"
>
<dt className="font-medium">
{record.item.description}
</dt>
<dd>
Código confirmado: {record.data.confirmed_code} ·
versão {record.version} · {record.confirmed_by.name}
</dd>
<dt>Proposta e fonte</dt>
<dd>
{record.data.proposed_code ?? 'Não indicada'} ·{' '}
{record.data.source_reference ?? 'Por completar'}
</dd>
<dt>Fonte da confirmação</dt>
<dd>{record.data.confirmation_source}</dd>
<dt>
{record.data.deviation
? 'Justificação do desvio'
: 'Motivo'}
</dt>
<dd className="break-words whitespace-pre-wrap">
{record.reason}
</dd>
</dl>
))}
</div>
</Panel>
);
}
@@ -0,0 +1,142 @@
import { Link } from '@inertiajs/react';
import { Panel } from '@/components/procurement';
import { money, roleLabels } from '@/types/procurement';
export type OrderPartFrame = {
requisition: { id: number; number: string };
department: { name: string };
cost_center: { code: string; name: string };
quotation: { reference: string; currency: string; payment_terms: string };
award: {
delivery_date: string;
delivery_location: string;
justification?: string;
};
native_preparation: {
approved_reference?: { subtotal_minor: number; total_minor: number };
items: {
quotation_item_id: number;
description: string;
quantity_milli: number;
approved_quantity_milli?: number;
total_minor: number;
}[];
};
approval_rules?: { approval_includes_tax: boolean };
final_approvals?: {
id: number;
role: string;
approver_id: number | null;
decision: string;
}[];
};
export function OrderPartsSummary({ sources }: { sources: OrderPartFrame[] }) {
if (sources.length === 0) return null;
return (
<Panel
title={
sources.length === 1
? 'Origem da parcela emitida'
: 'Origens preservadas na ordem'
}
>
<p className="mb-4">
Cada linha conserva a adjudicação original. Quantidades e IVA
usam os arredondamentos cumulativos da origem; o documento
mostra apenas as parcelas emitidas nesta ordem.
</p>
<div className="grid min-w-0 gap-4">
{sources.map((source) => (
<section
key={source.requisition.id}
className="grid min-w-0 gap-2 rounded-lg border p-4"
>
<h3 className="font-semibold">
<Link
href={`/requisicoes/${source.requisition.id}`}
className="underline"
>
{source.requisition.number}
</Link>
</h3>
<p className="break-words">
{source.department.name} · {source.cost_center.code}{' '}
· {source.cost_center.name}
</p>
<p className="break-words">
Proposta {source.quotation.reference} · Pagamento:{' '}
{source.quotation.payment_terms}
</p>
<p className="break-words">
Entrega: {source.award.delivery_date} ·{' '}
{source.award.delivery_location}
</p>
{source.native_preparation.approved_reference && (
<p>
Base aprovada da origem:{' '}
{money(
source.approval_rules
?.approval_includes_tax === false
? source.native_preparation
.approved_reference.subtotal_minor
: source.native_preparation
.approved_reference.total_minor,
'MZN',
)}{' '}
(
{source.approval_rules
?.approval_includes_tax === false
? 'sem IVA'
: 'com IVA'}
).
</p>
)}
{source.award.justification && (
<p className="break-words whitespace-pre-wrap">
Fundamento: {source.award.justification}
</p>
)}
<Link
href={`/requisicoes/${source.requisition.id}/adjudicacao`}
className="underline"
>
Consultar a adjudicação desta origem
</Link>
{(source.final_approvals ?? []).map((step) => (
<p key={step.id} className="text-sm">
{Object.entries(roleLabels).find(
([role]) => role === step.role,
)?.[1] ?? step.role}{' '}
·{' '}
{step.decision === 'approved'
? 'Aprovado'
: step.decision === 'rejected'
? 'Rejeitado'
: 'Pendente'}{' '}
· Interveniente #{step.approver_id}
</p>
))}
{source.native_preparation.items.map((line) => (
<p
key={line.quotation_item_id}
className="break-words"
>
{line.description}: emitido{' '}
{line.quantity_milli / 1000}
{line.approved_quantity_milli === undefined
? ''
: ` de ${line.approved_quantity_milli / 1000} aprovado(s)`}{' '}
·{' '}
{money(
line.total_minor,
source.quotation.currency,
)}
</p>
))}
</section>
))}
</div>
</Panel>
);
}
+58
View File
@@ -37,6 +37,64 @@ function topic(
} }
export const journeyHelp: JourneyHelp[] = [ export const journeyHelp: JourneyHelp[] = [
topic(
'import-tariffs',
'Classificar os artigos importados',
['supply/import-tariffs'],
'Conservar o código proposto, a fonte e a confirmação do comprador por artigo.',
[
'Seleccione explicitamente o cadastro do material ou escreva uma proposta manual.',
'Guarde uma proposta mesmo quando o código ainda for desconhecido.',
'O comprador confirma o código e a fonte, justificando qualquer desvio.',
],
[
'Uma nova versão do cadastro não altera confirmações anteriores.',
'A classificação documental não activa imposições, licenças ou submissões JUE.',
],
'Se a origem ou a versão mudou, conserve os seus valores e seleccione o cadastro actual antes de voltar a guardar.',
'Conclua a conferência documental e os restantes requisitos aplicáveis à importação.',
),
topic(
'import-costs',
'Conferir o custo de aterragem',
['supply/import-costs'],
'Reunir os custos da importação conservando cada documento, moeda e credor.',
[
'Registe as imposições documentadas e conserve a evidência privada.',
'Seleccione as facturas já validadas e os documentos adicionais.',
'Identifique cada componente e indique os valores documentais e as referências em MZN.',
'Guarde a preparação para conferência independente de Finanças.',
'Depois da conferência, reserve, comprometa e consuma as origens elegíveis; pode seleccionar uma parte das origens.',
'Para custos tardios, prepare uma nova versão e aplique a alteração conferida. O consumo anterior não se repete.',
],
[
'Não inclua a mesma factura com dois papéis.',
'Não some novamente um encargo já incluído no preço de uma factura; conserve o documento como evidência de consulta.',
'Uma taxa desconhecida não equivale a zero; conserve a taxa, data e fonte explícitas.',
'A conferência documental não cria dívida. A etapa orçamental, após revisão independente, movimenta apenas os custos adicionais e conserva os efeitos nativos das facturas.',
],
'Se uma origem mudou, devolva a preparação e corrija numa nova versão. Os documentos e versões anteriores ficam preservados.',
'Consultar os saldos e o histórico por origem; uma libertação afecta apenas o montante ainda não consumido.',
),
topic(
'order-parts',
'Dividir ou consolidar ordens de compra',
['purchases/parts'],
'Emitir apenas as quantidades necessárias ou reunir origens aprovadas do mesmo fornecedor e moeda, conservando a identidade de cada linha.',
[
'Escolha as origens e as quantidades ainda por emitir.',
'Clique em Conferir para obter os valores nativos e as distribuições.',
'Confira as imputações em MZN; se houver vários centros, indique explicitamente cada parcela.',
'Emita a ordem e acompanhe as recepções e a factura no percurso normal.',
],
[
'As aprovações da origem continuam obrigatórias e são novamente verificadas.',
'A adopção apenas transfere uma reserva adjudicada existente, sem criar saldo ou alterar ordens anteriores.',
'Cancelar uma parcela não autoriza a sua repetição nem encerra a requisição inteira.',
],
'Se a quantidade ou a versão tiver mudado, conserve a preparação e volte a conferir. Consulte o histórico antes de repetir uma emissão incerta.',
'Conferir a ordem emitida e as suas origens; depois registar a recepção e a factura com a validação independente de Finanças.',
),
topic( topic(
'budget-distributions', 'budget-distributions',
'Distribuir um pedido por centros de custo', 'Distribuir um pedido por centros de custo',
+36
View File
@@ -0,0 +1,36 @@
/** Exact transport of explicit monetary input; no price, VAT or exchange calculation. */
export function orderPartMinor(value: string): number | null {
if (!/^\d{1,13}(?:\.\d{1,2})?$/.test(value)) return null;
const [whole, fraction = ''] = value.split('.');
const result = BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
return result <= 100000000000000n ? Number(result) : null;
}
/** Display-only metadata must not change the identity of a remembered quantity preparation. */
export function orderPartDraftKey(
sources: {
requisition_id: number;
award_id: number;
items: {
quotation_item_id: number;
quantity_milli: number;
quantity_offset_milli: number;
}[];
}[],
): string {
return JSON.stringify(
sources
.map((source): [number, number, [number, number, number][]] => [
source.requisition_id,
source.award_id,
source.items
.map((line): [number, number, number] => [
line.quotation_item_id,
line.quantity_milli,
line.quantity_offset_milli,
])
.sort((a, b) => a[0] - b[0]),
])
.sort((a, b) => a[0] - b[0]),
);
}
+225 -13
View File
@@ -39,6 +39,19 @@ type Line = {
unit_price: string; unit_price: string;
tax_rate: string; tax_rate: string;
}; };
type OrderPartOption = {
origin: number;
allocation_key: string;
line_id: number;
centre_id: number;
description: string;
};
type OrderPartInput = {
origin: number;
allocation_key: string;
subtotal: string;
total: string;
};
type Invoice = { type Invoice = {
id: number; id: number;
number: string; number: string;
@@ -81,6 +94,8 @@ export default function Invoices({
supplier: string; supplier: string;
items: Source[]; items: Source[];
budgetDistributionOptions?: BudgetDistributionOption[] | null; budgetDistributionOptions?: BudgetDistributionOption[] | null;
orderParts?: boolean;
orderPartsBudgetOptions?: OrderPartOption[] | null;
}[]; }[];
canManage: boolean; canManage: boolean;
focusInvoiceId?: number | null; focusInvoiceId?: number | null;
@@ -139,8 +154,22 @@ export default function Invoices({
})) ?? []) as Line[], })) ?? []) as Line[],
}; };
const form = useForm(historyKey, initialData); const form = useForm(historyKey, initialData);
const [partAllocations, setPartAllocations] = useRemember<OrderPartInput[]>(
(
orders.find((source) => source.id === focusOrderId)
?.orderPartsBudgetOptions ?? []
).map((row) => ({
origin: row.origin,
allocation_key: row.allocation_key,
subtotal: '',
total: '',
})),
`${historyKey}:part-allocations`,
);
const formElement = useRef<HTMLFormElement>(null); const formElement = useRef<HTMLFormElement>(null);
const dirty = hasPreparationChanges(initialData, form.data); const dirty =
hasPreparationChanges(initialData, form.data) ||
partAllocations.some((row) => row.subtotal !== '' || row.total !== '');
useEffect(() => { useEffect(() => {
window.dispatchEvent( window.dispatchEvent(
new CustomEvent('sgc:context-dirty', { new CustomEvent('sgc:context-dirty', {
@@ -157,9 +186,38 @@ export default function Invoices({
(source) => source.id === line.purchase_order_item_id, (source) => source.id === line.purchase_order_item_id,
)?.requisition_item_id, )?.requisition_item_id,
); );
const activeAllocations = form.data.budget_distribution_preparation.filter( const activeAllocations = (
(row) => activeLineIds.includes(row.line_id), form.data.budget_distribution_preparation ?? []
); ).filter((row) => activeLineIds.includes(row.line_id));
const updatePartAmount = (
option: OrderPartOption,
field: 'subtotal' | 'total',
value: string,
) => {
setPartAllocations((rows) =>
rows.some(
(row) =>
row.origin === option.origin &&
row.allocation_key === option.allocation_key,
)
? rows.map((row) =>
row.origin !== option.origin ||
row.allocation_key !== option.allocation_key
? row
: { ...row, [field]: value },
)
: [
...rows,
{
origin: option.origin,
allocation_key: option.allocation_key,
subtotal: '',
total: '',
[field]: value,
},
],
);
};
return ( return (
<> <>
<Head title="Facturas" /> <Head title="Facturas" />
@@ -245,13 +303,29 @@ export default function Invoices({
e.preventDefault(); e.preventDefault();
form.transform((d) => ({ form.transform((d) => ({
...d, ...d,
budget_distribution_preparation: ...(order?.orderParts
d.budget_distribution_preparation.filter( ? {
(row) => order_part_allocations:
activeLineIds.includes( partAllocations.filter(
row.line_id, (row) =>
), order.orderPartsBudgetOptions?.some(
), (option) =>
option.origin ===
row.origin &&
option.allocation_key ===
row.allocation_key &&
activeLineIds.includes(
option.line_id,
),
),
),
}
: {}),
budget_distribution_preparation: (
d.budget_distribution_preparation ?? []
).filter((row) =>
activeLineIds.includes(row.line_id),
),
items: d.items items: d.items
.filter((l) => l.quantity !== '') .filter((l) => l.quantity !== '')
.map( .map(
@@ -281,6 +355,21 @@ export default function Invoices({
value={orderId} value={orderId}
onChange={(e) => { onChange={(e) => {
setOrderId(e.target.value); setOrderId(e.target.value);
setPartAllocations(
(
orders.find(
(source) =>
String(source.id) ===
e.target.value,
)?.orderPartsBudgetOptions ?? []
).map((row) => ({
origin: row.origin,
allocation_key:
row.allocation_key,
subtotal: '',
total: '',
})),
);
form.setData('reason', ''); form.setData('reason', '');
form.setData( form.setData(
'budget_distribution_preparation', 'budget_distribution_preparation',
@@ -475,7 +564,11 @@ export default function Invoices({
onChange={(rows) => onChange={(rows) =>
form.setData( form.setData(
'budget_distribution_preparation', 'budget_distribution_preparation',
form.data.budget_distribution_preparation.map( (
form.data
.budget_distribution_preparation ??
[]
).map(
(row) => (row) =>
rows.find( rows.find(
(changed) => (changed) =>
@@ -488,7 +581,126 @@ export default function Invoices({
/> />
</div> </div>
)} )}
<Button disabled={!orderId || form.processing}> {order?.orderParts && (
<fieldset className="grid min-w-0 gap-3 rounded-lg border p-4">
<legend className="px-2 font-semibold">
Imputação pelas origens da ordem
</legend>
<p>
Indique em MZN a parcela de cada linha
efectivamente facturada. A ordem e a
factura mantêm um único documento; o
consumo fica separado pelas origens
aprovadas.
</p>
{order.orderPartsBudgetOptions == null && (
<p role="status">
A preparação de novas facturas desta
ordem está temporariamente
indisponível. Os documentos
anteriores continuam em consulta.
</p>
)}
{(order.orderPartsBudgetOptions ?? [])
.filter((option) =>
activeLineIds.includes(
option.line_id,
),
)
.map((option) => {
const index =
partAllocations.findIndex(
(row) =>
row.origin ===
option.origin &&
row.allocation_key ===
option.allocation_key,
);
const row = partAllocations[index];
return (
<div
key={`${option.origin}:${option.allocation_key}`}
className="grid min-w-0 gap-3 rounded border p-3 sm:grid-cols-2"
>
<p className="break-words sm:col-span-2">
Origem #{option.origin}{' '}
· {option.description} ·
Centro #
{option.centre_id}
</p>
<label className="grid gap-1">
Sem IVA (MZN)
<Input
required
inputMode="decimal"
value={
row?.subtotal ??
''
}
onChange={(event) =>
updatePartAmount(
option,
'subtotal',
event.target
.value,
)
}
/>
</label>
<label className="grid gap-1">
Com IVA (MZN)
<Input
required
inputMode="decimal"
value={
row?.total ?? ''
}
onChange={(event) =>
updatePartAmount(
option,
'total',
event.target
.value,
)
}
/>
</label>
</div>
);
})}
<label className="grid gap-1">
Fundamento da imputação
<textarea
className="rounded-md border p-2"
required
minLength={10}
maxLength={4000}
value={form.data.reason}
onChange={(event) =>
form.setData(
'reason',
event.target.value,
)
}
/>
</label>
<p className="text-sm text-muted-foreground">
Os montantes têm de coincidir com as
linhas nativas e com o compromisso ainda
disponível. Não há compensação
automática. A validação exige outra
pessoa de Finanças.
</p>
</fieldset>
)}
<Button
disabled={
!orderId ||
form.processing ||
(order?.orderParts === true &&
order.orderPartsBudgetOptions == null)
}
>
Registar para conferência independente Registar para conferência independente
</Button> </Button>
</form> </form>
+10
View File
@@ -11,9 +11,11 @@ type Page<T> = {
export default function Orders({ export default function Orders({
orders, orders,
awards, awards,
partsAvailable = false,
}: { }: {
orders: Page<PurchaseOrder>; orders: Page<PurchaseOrder>;
awards: Page<PurchaseAward>; awards: Page<PurchaseAward>;
partsAvailable?: boolean;
}) { }) {
return ( return (
<> <>
@@ -25,6 +27,14 @@ export default function Orders({
description="Acompanhe as aprovações dos valores finais e os documentos emitidos para revisão." description="Acompanhe as aprovações dos valores finais e os documentos emitidos para revisão."
/> />
<Panel title="Ordens emitidas"> <Panel title="Ordens emitidas">
{partsAvailable && (
<Link
href="/ordens/preparar"
className="mb-4 inline-block underline"
>
Preparar ordens por parcelas ou consolidar origens
</Link>
)}
<div className="overflow-x-auto"> <div className="overflow-x-auto">
<table className="w-full text-left text-sm"> <table className="w-full text-left text-sm">
<thead className="border-b text-muted-foreground"> <thead className="border-b text-muted-foreground">
+627
View File
@@ -0,0 +1,627 @@
import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { useEffect, useRef, type RefObject } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { FormErrors, PageTitle, Panel } from '@/components/procurement';
import { orderPartDraftKey, orderPartMinor } from '@/lib/order-parts';
import { money } from '@/types/procurement';
type Selection = {
award_id: number;
items: { quotation_item_id: number; quantity: string }[];
};
type Candidate = {
id: number;
requisition_id: number;
number: string;
supplier: string;
currency: string;
items: { id: number; description: string; remaining: string }[];
};
type Financial = {
origin: number;
award_id: number;
requires_adoption: boolean;
version?: number;
plan_hash?: string;
allocations: {
allocation_key: string;
line_id: number;
centre_id: number;
description: string;
subtotal: string;
total: string;
}[];
};
type Preview = {
selection: { sources: Selection[] };
can_issue: boolean;
financial: Financial[];
prepared: {
fingerprint: string;
currency: string;
subtotal_minor: number;
total_minor: number;
sources: {
requisition_id: number;
requisition_number?: string | null;
award_id: number;
currency: string;
items: {
description: string;
quotation_item_id: number;
quantity_offset_milli: number;
quantity_milli: number;
total_minor: number;
}[];
}[];
};
};
type Props = {
candidates: {
data: Candidate[];
prev_page_url: string | null;
next_page_url: string | null;
};
preview: Preview | null;
};
function useGuard(ref: RefObject<HTMLFormElement | null>, dirty: boolean) {
useEffect(() => {
const form = ref.current;
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', { detail: { form, dirty } }),
);
return () => {
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form, dirty: false },
}),
);
};
}, [dirty, ref]);
}
function Adoption({ award }: { award: number }) {
const form = useForm({ operation_key: crypto.randomUUID() });
return (
<div className="grid gap-3 rounded-lg border p-4">
<p>
Esta origem ainda não tem distribuição para parcelas. Pode
adoptar a reserva já adjudicada, conservando o centro, os
valores e o histórico. Uma ordem anterior não é alterada.
</p>
<p className="text-sm text-muted-foreground">
Se não existir reserva, complete primeiro o controlo orçamental
da origem. A adopção não cria dotação nem saldo.
</p>
<FormErrors errors={form.errors} />
<Button
type="button"
disabled={form.processing}
onClick={() =>
form.post(`/adjudicacoes/${award}/parcelas/adoptar`)
}
>
Adoptar a reserva existente
</Button>
</div>
);
}
function Prepared({
preview,
historyKey,
}: {
preview: Preview;
historyKey: string;
}) {
const initial = {
order_key: crypto.randomUUID(),
operation_key: crypto.randomUUID(),
budget_sources: preview.financial.map((source) => ({
origin: source.origin,
version: source.version ?? 0,
plan_hash: source.plan_hash ?? '',
allocations: source.allocations.map((row) => ({
allocation_key: row.allocation_key,
subtotal: row.subtotal,
total: row.total,
})),
})),
};
const form = useForm(historyKey, initial);
const ref = useRef<HTMLFormElement>(null);
const changed = form.data.budget_sources.some((source, i) =>
source.allocations.some(
(row, j) =>
row.subtotal !==
initial.budget_sources[i]?.allocations[j]?.subtotal ||
row.total !== initial.budget_sources[i]?.allocations[j]?.total,
),
);
useGuard(ref, changed);
return (
<div id="order-parts-review" tabIndex={-1} className="scroll-mt-24">
<Panel title="Conferir e emitir a ordem">
<p className="mb-4">
As origens mantêm as suas aprovações. Só as quantidades
indicadas são emitidas; a reserva restante fica disponível
para as próximas parcelas. Cancelar uma parcela não autoriza
a sua repetição.
</p>
<form
ref={ref}
className="grid min-w-0 gap-5"
onSubmit={(event) => {
event.preventDefault();
const invalid = form.data.budget_sources.some(
(source) =>
source.allocations.some(
(row) =>
orderPartMinor(row.subtotal) === null ||
orderPartMinor(row.total) === null,
),
);
if (invalid) {
form.setError(
'budget_sources',
'Indique montantes válidos, com até duas casas decimais.',
);
return;
}
form.transform((data) => ({
order_key: data.order_key,
operation_key: data.operation_key,
sources: preview.selection.sources,
fingerprint: preview.prepared.fingerprint,
budget_sources: data.budget_sources.map(
(source) => ({
origin: source.origin,
version: source.version,
plan_hash: source.plan_hash,
allocations: source.allocations.map(
(row) => ({
allocation_key: row.allocation_key,
subtotal_minor: orderPartMinor(
row.subtotal,
),
total_minor: orderPartMinor(
row.total,
),
}),
),
}),
),
}));
form.post('/ordens/parcelas/emitir');
}}
>
<FormErrors errors={form.errors} />
{preview.prepared.sources.map((source, index) => (
<fieldset
key={source.requisition_id}
className="grid min-w-0 gap-3 rounded-lg border p-4"
>
<legend className="px-2 font-semibold">
<Link
href={`/requisicoes/${source.requisition_id}/adjudicacao`}
className="underline"
>
{source.requisition_number ??
`Origem #${source.requisition_id}`}
</Link>
</legend>
{source.items.map((line, i) => (
<p key={i} className="break-words">
{line.description}:{' '}
{line.quantity_milli / 1000} —{' '}
{money(line.total_minor, source.currency)}
</p>
))}
{preview.financial[index].requires_adoption ? (
<Adoption award={source.award_id} />
) : (
<>
<p className="text-sm text-muted-foreground">
Confira a imputação em MZN por centro.
Quando há vários centros, indique
explicitamente os montantes; o sistema
não distribui diferenças
automaticamente.
</p>
{preview.financial[index].allocations.map(
(row, position) => (
<div
key={row.allocation_key}
className="grid min-w-0 gap-3 rounded border p-3 sm:grid-cols-2"
>
<p className="break-words sm:col-span-2">
{row.description} · Centro #
{row.centre_id}
</p>
<label className="grid gap-1">
Sem IVA (MZN)
<Input
inputMode="decimal"
required
value={
form.data
.budget_sources[
index
].allocations[
position
].subtotal
}
onChange={(event) => {
form.setData(
'budget_sources',
form.data.budget_sources.map(
(
entry,
i,
) =>
i !==
index
? entry
: {
...entry,
allocations:
entry.allocations.map(
(
part,
j,
) =>
j !==
position
? part
: {
...part,
subtotal:
event
.target
.value,
},
),
},
),
);
}}
/>
</label>
<label className="grid gap-1">
Com IVA (MZN)
<Input
inputMode="decimal"
required
value={
form.data
.budget_sources[
index
].allocations[
position
].total
}
onChange={(event) => {
form.setData(
'budget_sources',
form.data.budget_sources.map(
(
entry,
i,
) =>
i !==
index
? entry
: {
...entry,
allocations:
entry.allocations.map(
(
part,
j,
) =>
j !==
position
? part
: {
...part,
total: event
.target
.value,
},
),
},
),
);
}}
/>
</label>
</div>
),
)}
</>
)}
</fieldset>
))}
<p className="font-semibold">
Total documental:{' '}
{money(
preview.prepared.total_minor,
preview.prepared.currency,
)}
</p>
{!preview.can_issue && (
<p role="status">
Complete a distribuição de todas as origens antes de
emitir. A emissão multimoeda por parcelas ainda não
está disponível.
</p>
)}
<p className="text-sm text-muted-foreground">
Na emissão voltam a ser verificadas aprovações,
quantidades, versões e orçamento. Se a origem tiver
mudado, conserve os valores e volte a conferir.
</p>
<Button
type="submit"
disabled={form.processing || !preview.can_issue}
>
Emitir uma ordem com estas parcelas
</Button>
</form>
</Panel>
</div>
);
}
export default function Parts({ candidates, preview }: Props) {
const actor = usePage().props.auth?.user;
const historyKey = `order-parts:${actor?.tenant_id}:${actor?.id}`;
const form = useForm<{ sources: Selection[] }>(`${historyKey}:selection`, {
sources: [],
});
const ref = useRef<HTMLFormElement>(null);
useGuard(ref, form.data.sources.length > 0);
useEffect(() => {
if (preview) {
const review = document.getElementById('order-parts-review');
review?.scrollIntoView({ block: 'start' });
review?.focus({ preventScroll: true });
}
}, [preview]);
const draftKey = preview ? orderPartDraftKey(preview.prepared.sources) : '';
return (
<>
<Head title="Preparar ordens por parcelas" />
<div className="mx-auto grid w-full max-w-5xl min-w-0 gap-6 p-5 lg:p-8">
<PageTitle
eyebrow="Compras"
title="Preparar ordens por parcelas"
description="Divida uma adjudicação ou reúna origens aprovadas da mesma empresa, fornecedor e moeda. Cada origem conserva a sua identidade."
/>
<Link href="/ordens" className="underline">
Voltar às adjudicações e ordens
</Link>
<Panel title="Escolher origens e quantidades">
<form
ref={ref}
className="grid min-w-0 gap-4"
onSubmit={(event) => {
event.preventDefault();
form.post('/ordens/preparar', {
preserveState: true,
preserveScroll: true,
});
}}
>
<p>
Escolha apenas as linhas a emitir agora. O saldo de
quantidade já inclui as parcelas anteriores, mesmo
canceladas. As aprovações e os prazos serão
novamente conferidos.
</p>
<p className="text-sm text-muted-foreground">
As escolhas ficam conservadas neste navegador para o
seu utilizador e empresa. Depois de actualizar a
página, volte a conferir para recuperar a preparação
actual.
</p>
<FormErrors errors={form.errors} />
{candidates.data.map((candidate) => {
const selected = form.data.sources.find(
(source) => source.award_id === candidate.id,
);
return (
<fieldset
key={candidate.id}
className="grid min-w-0 gap-3 rounded-lg border p-4"
>
<legend className="px-2 font-semibold break-words">
{candidate.number} ·{' '}
{candidate.supplier} ·{' '}
{candidate.currency}
</legend>
{candidate.items.map((line) => {
const value = selected?.items.find(
(item) =>
item.quotation_item_id ===
line.id,
);
return (
<div
key={line.id}
className="grid gap-2"
>
<label className="flex items-start gap-3 break-words">
<input
type="checkbox"
checked={
value !== undefined
}
disabled={
!value &&
Number(
line.remaining,
) <= 0
}
onChange={(event) => {
const items = event
.target.checked
? [
...(selected?.items ??
[]),
{
quotation_item_id:
line.id,
quantity:
line.remaining,
},
]
: (
selected?.items ??
[]
).filter(
(item) =>
item.quotation_item_id !==
line.id,
);
form.setData(
'sources',
[
...form.data.sources.filter(
(
source,
) =>
source.award_id !==
candidate.id,
),
...(items.length ===
0
? []
: [
{
award_id:
candidate.id,
items,
},
]),
],
);
}}
/>
{line.description} · Por
emitir: {line.remaining}
</label>
{value && (
<label className="grid gap-1">
Quantidade desta parcela
<Input
inputMode="decimal"
required
value={
value.quantity
}
onChange={(event) =>
form.setData(
'sources',
form.data.sources.map(
(
source,
) =>
source.award_id !==
candidate.id
? source
: {
...source,
items: source.items.map(
(
item,
) =>
item.quotation_item_id !==
line.id
? item
: {
...item,
quantity:
event
.target
.value,
},
),
},
),
)
}
/>
</label>
)}
</div>
);
})}
<Link
href={`/requisicoes/${candidate.requisition_id}/adjudicacao`}
className="underline"
>
Consultar a adjudicação
</Link>
</fieldset>
);
})}
{candidates.data.length === 0 && (
<p>
Não há adjudicações aprovadas disponíveis nesta
página.
</p>
)}
<p>
{form.data.sources.length}{' '}
{form.data.sources.length === 1
? 'origem seleccionada'
: 'origens seleccionadas'}
, incluindo escolhas de outras páginas.
</p>
<Button
disabled={
form.processing ||
form.data.sources.length === 0
}
>
Conferir as parcelas seleccionadas
</Button>
</form>
<nav
aria-label="Páginas de adjudicações"
className="mt-4 flex flex-wrap gap-4"
>
{candidates.prev_page_url && (
<Link
preserveState
href={candidates.prev_page_url}
className="underline"
>
Anterior
</Link>
)}
{candidates.next_page_url && (
<Link
preserveState
href={candidates.next_page_url}
className="underline"
>
Seguinte
</Link>
)}
</nav>
</Panel>
{preview && (
<Prepared
key={`${draftKey}:${preview.financial.map((source) => `${source.plan_hash}:${source.version}`).join(':')}`}
preview={preview}
historyKey={`${historyKey}:issue:${draftKey}:${preview.financial.map((source) => source.version).join(':')}`}
/>
)}
</div>
</>
);
}
+34 -5
View File
@@ -8,9 +8,14 @@ import { Button } from '@/components/ui/button';
import { date, money, roleLabels } from '@/types/procurement'; import { date, money, roleLabels } from '@/types/procurement';
import { ExchangeSummary } from '@/components/quotation-exchange-panel'; import { ExchangeSummary } from '@/components/quotation-exchange-panel';
import type { PurchaseOrder } from '@/types/purchase'; import type { PurchaseOrder } from '@/types/purchase';
import ImportTariffSummary from '@/components/import-tariff-summary';
import OrderCancellationRequest, { import OrderCancellationRequest, {
type OrderCancellationState, type OrderCancellationState,
} from '@/components/order-cancellation-request'; } from '@/components/order-cancellation-request';
import {
OrderPartsSummary,
type OrderPartFrame,
} from '@/components/order-parts-summary';
type History = { type History = {
id: number; id: number;
@@ -29,11 +34,13 @@ export default function OrderShow({
history, history,
orderCancellation, orderCancellation,
snapshotComplete = true, snapshotComplete = true,
orderPartsSources = [],
}: { }: {
order: PurchaseOrder; order: PurchaseOrder;
history: History[]; history: History[];
orderCancellation?: OrderCancellationState; orderCancellation?: OrderCancellationState;
snapshotComplete?: boolean; snapshotComplete?: boolean;
orderPartsSources?: OrderPartFrame[];
}) { }) {
const snapshot = order.snapshot; const snapshot = order.snapshot;
if (!snapshotComplete) { if (!snapshotComplete) {
@@ -145,11 +152,15 @@ export default function OrderShow({
Documento de desenvolvimento. Não autoriza compras Documento de desenvolvimento. Não autoriza compras
reais. reais.
</strong>{' '} </strong>{' '}
Orçamento não verificado. Os dados apresentados foram {snapshot.budget_checked === true
congelados na emissão. ? 'Controlo orçamental confirmado para as parcelas emitidas. '
: 'Orçamento não verificado. '}{' '}
Os dados apresentados foram congelados na emissão.
{snapshot.approval_rules.rules_provisional && {snapshot.approval_rules.rules_provisional &&
' Regras de aprovação provisórias.'} ' Regras de aprovação provisórias.'}
</div> </div>
<OrderPartsSummary sources={orderPartsSources} />
<ImportTariffSummary records={snapshot.import_tariffs} />
<div className="grid gap-6 md:grid-cols-2"> <div className="grid gap-6 md:grid-cols-2">
{snapshot.investment_rules && ( {snapshot.investment_rules && (
<Panel title="Regra de investimento congelada"> <Panel title="Regra de investimento congelada">
@@ -315,7 +326,13 @@ export default function OrderShow({
<AgreementOrderLimitSummary <AgreementOrderLimitSummary
bindings={snapshot.agreement_bindings} bindings={snapshot.agreement_bindings}
/> />
<Panel title="Fundamento e matriz congelada"> <Panel
title={
orderPartsSources.length > 1
? 'Fundamento e matriz da referência principal'
: 'Fundamento e matriz congelada'
}
>
{snapshot.comparison_policy && ( {snapshot.comparison_policy && (
<ComparisonPolicySummary <ComparisonPolicySummary
policy={snapshot.comparison_policy} policy={snapshot.comparison_policy}
@@ -359,7 +376,13 @@ export default function OrderShow({
))} ))}
</div> </div>
</Panel> </Panel>
<Panel title="Aprovações do valor final"> <Panel
title={
orderPartsSources.length > 1
? 'Aprovações da referência principal'
: 'Aprovações do valor final'
}
>
<ol className="space-y-3"> <ol className="space-y-3">
{snapshot.final_approvals.map((step) => ( {snapshot.final_approvals.map((step) => (
<li key={step.id} className="text-sm"> <li key={step.id} className="text-sm">
@@ -382,7 +405,13 @@ export default function OrderShow({
separadamente. separadamente.
</p> </p>
</Panel> </Panel>
<Panel title="Histórico do processo"> <Panel
title={
orderPartsSources.length > 1
? 'Histórico das origens'
: 'Histórico do processo'
}
>
<ol className="space-y-3"> <ol className="space-y-3">
{history.map((event) => ( {history.map((event) => (
<li key={event.id} className="text-sm"> <li key={event.id} className="text-sm">
+11
View File
@@ -53,7 +53,9 @@ export default function Show({
approvalRouting, approvalRouting,
canRefreshRouting = false, canRefreshRouting = false,
canPrepareDistributions = false, canPrepareDistributions = false,
importTariffsReady = false,
}: { }: {
importTariffsReady?: boolean;
canPrepareDistributions?: boolean; canPrepareDistributions?: boolean;
requisition: Requisition; requisition: Requisition;
canRefreshRouting?: boolean; canRefreshRouting?: boolean;
@@ -161,6 +163,15 @@ export default function Show({
} }
/> />
<FormErrors errors={submission.errors} /> <FormErrors errors={submission.errors} />
{importTariffsReady && (
<Button asChild variant="outline">
<Link
href={`/requisicoes/${r.id}/classificacao-pautal`}
>
Classificação pautal dos artigos importados
</Link>
</Button>
)}
{canPrepareDistributions && ( {canPrepareDistributions && (
<Button asChild variant="outline"> <Button asChild variant="outline">
<Link href={`/requisicoes/${r.id}/distribuicoes`}> <Link href={`/requisicoes/${r.id}/distribuicoes`}>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,461 @@
import { Head, Link, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import { Button } from '@/components/ui/button';
import {
FormErrors,
PageTitle,
Panel,
controlClass,
} from '@/components/procurement';
type RecordVersion = {
id: number;
version: number;
state: string;
reason: string;
data: {
code?: string;
proposed_code?: string | null;
confirmed_code?: string;
source_reference?: string | null;
confirmation_source?: string;
deviation?: boolean;
requisition_item_id?: number;
};
snapshot: {
item?: { name?: string; description?: string };
confirmed_by?: { name: string };
master?: {
id: number;
version: number;
item: { code: string; name: string };
};
};
};
type Page<T> = {
data: T[];
prev_page_url: string | null;
next_page_url: string | null;
};
type Props = {
requisition: { id: number; number: string };
items: {
id: number;
description: string;
quantity: string;
unit: string;
}[];
latest: Record<string, RecordVersion> | RecordVersion[];
history: Page<RecordVersion>;
masters: Page<RecordVersion>;
stockItems: Page<{
id: number;
code: string;
name: string;
unit: string;
tariff: RecordVersion | null;
}>;
canPropose: boolean;
canConfirm: boolean;
masterSearch: string;
actorId: number;
tenantId: number;
};
function useGuard(dirty: boolean) {
const ref = useRef<HTMLFormElement>(null);
useEffect(() => {
const form = ref.current;
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', { detail: { form, dirty } }),
);
return () => {
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form, dirty: false },
}),
);
};
}, [dirty]);
return ref;
}
function Pagination({ page }: { page: Page<unknown> }) {
return (
<nav className="my-3 flex flex-wrap gap-4" aria-label="Páginas">
{page.prev_page_url && (
<Link preserveState href={page.prev_page_url}>
Anterior
</Link>
)}
{page.next_page_url && (
<Link preserveState href={page.next_page_url}>
Seguinte
</Link>
)}
</nav>
);
}
function ItemForm({
item,
latest,
props,
scope,
url,
}: {
item: Props['items'][number];
latest?: RecordVersion;
props: Props;
scope: string;
url: string;
}) {
const form = useForm(`${scope}:item:${item.id}:${latest?.version ?? 0}`, {
operation_key: crypto.randomUUID(),
action: 'propose',
version: latest?.version ?? 0,
requisition_item_id: item.id,
master_id: '',
code: latest?.data.confirmed_code ?? latest?.data.proposed_code ?? '',
source_reference:
latest?.data.confirmation_source ??
latest?.data.source_reference ??
'',
reason: '',
});
const ref = useGuard(form.isDirty);
const submit = (action: string) => {
form.transform((data) => ({
...data,
action,
master_id: action === 'confirm' ? null : data.master_id || null,
}));
form.post(url, {
preserveScroll: true,
onSuccess: () => {
form.reset();
},
});
};
return (
<Panel title={`${item.description} · ${item.quantity} ${item.unit}`}>
<p className="mb-3">
{latest?.state === 'confirmed'
? `Confirmado: ${latest.data.confirmed_code} · ${latest.snapshot.confirmed_by?.name ?? 'Comprador registado'}`
: 'Código pautal por confirmar pelo comprador.'}
</p>
{latest?.snapshot.master && (
<p>
Proposta reutilizada de {latest.snapshot.master.item.code} ·{' '}
{latest.snapshot.master.item.name}, versão{' '}
{latest.snapshot.master.version}.
</p>
)}
{(props.canPropose || props.canConfirm) && (
<form
ref={ref}
className="grid gap-3"
onSubmit={(e) => {
e.preventDefault();
submit('propose');
}}
>
<FormErrors errors={form.errors} />
{props.canPropose && (
<label>
Reutilizar cadastro do material (opcional)
<select
className={controlClass}
value={form.data.master_id}
onChange={(e) => {
const selected = props.masters.data.find(
(row) =>
String(row.id) === e.target.value,
);
form.setData((old) => ({
...old,
master_id: e.target.value,
...(selected
? {
code:
selected.data.code ?? '',
source_reference:
selected.data
.source_reference ??
'',
}
: {}),
}));
}}
>
<option value="">
Proposta manual / conservar os valores
escritos
</option>
{props.masters.data.map((row) => (
<option key={row.id} value={row.id}>
{row.snapshot.item?.name} ·{' '}
{row.data.code} · v{row.version}
</option>
))}
</select>
</label>
)}
<label>
Código proposto ou a confirmar
<input
className={controlClass}
maxLength={40}
value={form.data.code}
onChange={(e) =>
form.setData('code', e.target.value)
}
/>
</label>
<label>
Fonte e versão documental
<textarea
className={controlClass}
maxLength={2000}
value={form.data.source_reference}
onChange={(e) =>
form.setData('source_reference', e.target.value)
}
/>
</label>
<label>
Motivo / justificação do desvio
<textarea
required
minLength={10}
maxLength={4000}
className={controlClass}
value={form.data.reason}
onChange={(e) =>
form.setData('reason', e.target.value)
}
/>
</label>
<div className="flex flex-wrap gap-3">
{props.canPropose && (
<Button disabled={form.processing}>
Guardar proposta
</Button>
)}
{props.canConfirm && latest?.state === 'proposed' && (
<Button
type="button"
disabled={form.processing}
onClick={() => submit('confirm')}
>
Confirmar como comprador
</Button>
)}
</div>
<p className="text-sm text-muted-foreground">
Pode guardar uma proposta sem código conhecido; a
confirmação exige código, fonte e motivo. Se alterar a
proposta confirmada, será criada uma nova versão por
confirmar. Não são calculadas imposições nem submetida
uma declaração.
</p>
</form>
)}
</Panel>
);
}
function MasterForm({
item,
scope,
url,
}: {
item: Props['stockItems']['data'][number];
scope: string;
url: string;
}) {
const form = useForm(
`${scope}:master:${item.id}:${item.tariff?.version ?? 0}`,
{
operation_key: crypto.randomUUID(),
action: 'master',
version: item.tariff?.version ?? 0,
stock_item_id: item.id,
code: item.tariff?.data.code ?? '',
source_reference: item.tariff?.data.source_reference ?? '',
reason: '',
},
);
const ref = useGuard(form.isDirty);
return (
<details className="rounded border p-3">
<summary>
{item.code} · {item.name} ·{' '}
{item.tariff?.data.code ?? 'Sem código pautal'}
</summary>
<form
ref={ref}
className="mt-3 grid gap-3"
onSubmit={(e) => {
e.preventDefault();
form.post(url, { preserveScroll: true });
}}
>
<FormErrors errors={form.errors} />
<label>
Código pautal do material
<input
required
maxLength={40}
className={controlClass}
value={form.data.code}
onChange={(e) => form.setData('code', e.target.value)}
/>
</label>
<label>
Fonte e versão documental
<textarea
required
maxLength={2000}
className={controlClass}
value={form.data.source_reference}
onChange={(e) =>
form.setData('source_reference', e.target.value)
}
/>
</label>
<label>
Motivo da actualização
<textarea
required
minLength={10}
maxLength={4000}
className={controlClass}
value={form.data.reason}
onChange={(e) => form.setData('reason', e.target.value)}
/>
</label>
<Button disabled={form.processing}>
Guardar versão do cadastro
</Button>
</form>
</details>
);
}
export default function ImportTariffs(props: Props) {
const url = `/requisicoes/${props.requisition.id}/classificacao-pautal`;
const scope = `import-tariffs:${props.tenantId}:${props.actorId}:${props.requisition.id}`;
return (
<div className="space-y-5">
<Head title="Classificação pautal" />
<PageTitle
eyebrow="Importação directa"
description="Proposta por artigo, cadastro do material e confirmação do comprador."
title={`Classificação pautal · ${props.requisition.number}`}
/>
<Link href={`/requisicoes/${props.requisition.id}`}>
Voltar à requisição
</Link>
<Panel title="Código por artigo e confirmação do comprador">
<p>
Associe explicitamente cada artigo importado ao cadastro do
material ou prepare a sua classificação manual. A
confirmação conserva a proposta e identifica o comprador e o
motivo; alterações futuras do cadastro não reescrevem
decisões anteriores.
</p>
<p className="mt-2">
O cadastro documental não certifica vigência legal, activa
taxas ou substitui a conferência das fontes aplicáveis.
Licenças e documentos aduaneiros continuam no respectivo
percurso.
</p>
</Panel>
<Panel title="Localizar material ou código">
<form
method="get"
action={url}
className="flex flex-wrap gap-3"
>
<label>
Pesquisa
<input
name="search"
maxLength={100}
defaultValue={props.masterSearch}
className={controlClass}
/>
</label>
<Button>Pesquisar</Button>
</form>
<Pagination page={props.masters} />
</Panel>
{props.items.map((item) => {
const latest = Object.values(props.latest).find(
(row) => row.data.requisition_item_id === item.id,
);
return (
<ItemForm
key={`${scope}:${item.id}:${latest?.version ?? 0}`}
item={item}
latest={latest}
props={props}
scope={scope}
url={url}
/>
);
})}
{props.canConfirm && (
<Panel title="Cadastro pautal dos materiais">
<p className="mb-3">
A actualização beneficia novas propostas. Para associar
um material, seleccione-o explicitamente no artigo da
requisição.
</p>
<div className="grid gap-3">
{props.stockItems.data.map((item) => (
<MasterForm
key={`${scope}:${item.id}:${item.tariff?.version ?? 0}`}
item={item}
scope={scope}
url={url}
/>
))}
</div>
<Pagination page={props.stockItems} />
</Panel>
)}
<Panel title="Histórico preservado">
{props.history.data.map((row) => (
<details key={row.id} className="my-3 rounded border p-3">
<summary>
{row.snapshot.item?.description} · v{row.version} ·{' '}
{row.state === 'confirmed'
? 'Confirmado'
: 'Proposto'}
</summary>
<p>
Proposta:{' '}
{row.data.proposed_code ?? 'Por completar'}
</p>
<p>
Fonte:{' '}
{row.data.source_reference ?? 'Por completar'}
</p>
{row.data.confirmed_code && (
<p>
Confirmado: {row.data.confirmed_code} ·{' '}
{row.snapshot.confirmed_by?.name} · Fonte:{' '}
{row.data.confirmation_source}
</p>
)}
<p>
{row.data.deviation
? 'Desvio justificado: '
: 'Motivo: '}
{row.reason}
</p>
</details>
))}
<Pagination page={props.history} />
</Panel>
</div>
);
}
+9
View File
@@ -75,6 +75,7 @@ type Projection = {
series?: { date: string; balance_milli: number }[]; series?: { date: string; balance_milli: number }[];
}; };
type Props = { type Props = {
importCostsReady?: boolean;
orderLimitsReady?: boolean; orderLimitsReady?: boolean;
linkedAgreementKey?: string | null; linkedAgreementKey?: string | null;
linkedContractKey?: string | null; linkedContractKey?: string | null;
@@ -1526,6 +1527,14 @@ export default function SupplyIndex(props: Props) {
/> />
)} )}
<RecordActions record={record} props={props} /> <RecordActions record={record} props={props} />
{props.importCostsReady && (
<Link
className="mt-4 inline-block underline"
href={`/compras/importacoes/${record.id}/custos`}
>
Preparar e conferir o custo de aterragem
</Link>
)}
<details className="mt-4"> <details className="mt-4">
<summary className="cursor-pointer text-sm"> <summary className="cursor-pointer text-sm">
Dados preservados desta versão Dados preservados desta versão
+3
View File
@@ -1,6 +1,7 @@
import type { CommercialTerms } from '@/components/quotation-commercial-terms'; import type { CommercialTerms } from '@/components/quotation-commercial-terms';
import type { ComparisonPolicy } from '@/components/comparison-policy-summary'; import type { ComparisonPolicy } from '@/components/comparison-policy-summary';
import type { ExchangeBasis } from '@/components/quotation-exchange-panel'; import type { ExchangeBasis } from '@/components/quotation-exchange-panel';
import type { FrozenImportTariff } from '@/components/import-tariff-summary';
export type MatrixRow = { export type MatrixRow = {
currency?: string; currency?: string;
@@ -98,6 +99,8 @@ export type PurchaseOrder = {
total_minor: number; total_minor: number;
items: OrderItem[]; items: OrderItem[];
snapshot: { snapshot: {
import_tariffs?: Record<number, FrozenImportTariff>;
budget_checked?: boolean;
agreement_bindings?: Record<string, FrozenOrderAgreement>; agreement_bindings?: Record<string, FrozenOrderAgreement>;
exchange_basis?: ExchangeBasis; exchange_basis?: ExchangeBasis;
reference_amounts?: { reference_amounts?: {
+16 -3
View File
@@ -38,20 +38,27 @@
<p>Subtotal sem IVA: {{ $money($order->subtotal_minor) }}<br>IVA: {{ $money($order->tax_minor) }}<br>Total com IVA: {{ $money($order->total_minor) }}</p> <p>Subtotal sem IVA: {{ $money($order->subtotal_minor) }}<br>IVA: {{ $money($order->tax_minor) }}<br>Total com IVA: {{ $money($order->total_minor) }}</p>
@else @else
<p>{{ $snapshot['company']['name'] }} · {{ $snapshot['requisition']['number'] }}</p> <p>{{ $snapshot['company']['name'] }} · {{ $snapshot['requisition']['number'] }}</p>
<div class="notice"><strong>Documento de desenvolvimento. Não autoriza compras reais.</strong><br>Orçamento não verificado. @if($snapshot['approval_rules']['rules_provisional']) Regras de aprovação provisórias. @endif</div> <div class="notice"><strong>Documento de desenvolvimento. Não autoriza compras reais.</strong><br>@if(($snapshot['budget_checked'] ?? false) === true) Controlo orçamental confirmado para as parcelas emitidas. @else Orçamento não verificado. @endif @if($snapshot['approval_rules']['rules_provisional']) Regras de aprovação provisórias. @endif</div>
<div class="columns"> <div class="columns">
<div><h2>Fornecedor</h2><strong>{{ $snapshot['supplier']['name'] }}</strong><br>NUIT {{ $snapshot['supplier']['nuit'] }}<br><span class="pre">{{ $snapshot['supplier']['address'] }}</span><br>{{ $snapshot['supplier']['contact'] }}<br>{{ $snapshot['supplier']['phone'] }} · {{ $snapshot['supplier']['email'] }}</div> <div><h2>Fornecedor</h2><strong>{{ $snapshot['supplier']['name'] }}</strong><br>NUIT {{ $snapshot['supplier']['nuit'] }}<br><span class="pre">{{ $snapshot['supplier']['address'] }}</span><br>{{ $snapshot['supplier']['contact'] }}<br>{{ $snapshot['supplier']['phone'] }} · {{ $snapshot['supplier']['email'] }}</div>
<div><h2>Condições</h2>Entrega: {{ $snapshot['award']['delivery_date'] }}<br><span class="pre">{{ $snapshot['award']['delivery_location'] }}</span><br>Pagamento: {{ $snapshot['quotation']['payment_terms'] }}<br>Proposta: {{ $snapshot['quotation']['reference'] }}<br>{{ $snapshot['department']['name'] }} · {{ $snapshot['cost_center']['code'] }}<br>Emitente: {{ $snapshot['issuer']['name'] }}<br>Emissão: {{ $order->issued_at->format('Y-m-d H:i:s') }}</div> <div><h2>Condições</h2>Entrega: {{ $snapshot['award']['delivery_date'] }}<br><span class="pre">{{ $snapshot['award']['delivery_location'] }}</span><br>Pagamento: {{ $snapshot['quotation']['payment_terms'] }}<br>Proposta: {{ $snapshot['quotation']['reference'] }}<br>{{ $snapshot['department']['name'] }} · {{ $snapshot['cost_center']['code'] }}<br>Emitente: {{ $snapshot['issuer']['name'] }}<br>Emissão: {{ $order->issued_at->format('Y-m-d H:i:s') }}</div>
</div> </div>
@if(!empty($snapshot['order_parts']['frames']))
<h2>Origens desta ordem</h2>
<p>Cada origem conserva as condições e aprovações registadas. Os valores das parcelas usam o arredondamento cumulativo da origem.</p>
@foreach($snapshot['order_parts']['frames'] as $frame)
<section><h3>{{ $frame['requisition']['number'] }}</h3><p>{{ $frame['department']['name'] }} · {{ $frame['cost_center']['code'] }} · {{ $frame['cost_center']['name'] }}<br>Proposta {{ $frame['quotation']['reference'] }} · Pagamento: {{ $frame['quotation']['payment_terms'] }}<br>Entrega: {{ $frame['award']['delivery_date'] }} · <span class="pre">{{ $frame['award']['delivery_location'] }}</span></p></section>
@endforeach
@endif
<h2>Artigos e valores</h2> <h2>Artigos e valores</h2>
@if(!empty($snapshot['investment_rules'])) @if(!empty($snapshot['investment_rules']))
<h2>Regra de investimento congelada</h2> <h2>Regra de investimento congelada</h2>
<p>Versão {{ $snapshot['investment_rules']['revision'] }} · Tecto {{ $money($snapshot['investment_rules']['ceiling_minor'], 'MZN') }} · {{ $snapshot['investment_rules']['includes_tax'] ? 'com IVA' : 'sem IVA' }} · Vigência {{ $snapshot['investment_rules']['valid_from'] }} a {{ $snapshot['investment_rules']['valid_until'] }}.</p> <p>Versão {{ $snapshot['investment_rules']['revision'] }} · Tecto {{ $money($snapshot['investment_rules']['ceiling_minor'], 'MZN') }} · {{ $snapshot['investment_rules']['includes_tax'] ? 'com IVA' : 'sem IVA' }} · Vigência {{ $snapshot['investment_rules']['valid_from'] }} a {{ $snapshot['investment_rules']['valid_until'] }}.</p>
@foreach($snapshot['equipment_requests'] ?? [] as $context)<p class="pre">{{ $context['description'] }} · Área: {{ $context['production_area'] }}</p>@endforeach @foreach($snapshot['equipment_requests'] ?? [] as $context)<p class="pre">{{ $context['description'] }} · Área: {{ $context['production_area'] }}</p>@endforeach
@endif @endif
<table><thead><tr><th>Descrição</th><th>Quantidade</th><th>Preço sem IVA</th><th>IVA</th><th>Total com IVA</th></tr></thead><tbody> <table><thead><tr>@if(!empty($snapshot['order_parts']['frames']))<th>Origem</th>@endif<th>Descrição</th><th>Quantidade</th><th>Preço sem IVA</th><th>IVA</th><th>Total com IVA</th></tr></thead><tbody>
@foreach($order->items as $item) @foreach($order->items as $item)
<tr><td class="pre">{{ $item->description }}</td><td>{{ $item->quantity }} {{ $item->unit }}</td><td>{{ $money($item->unit_price_minor) }}</td><td>{{ $item->tax_rate }}%</td><td>{{ $money($item->total_minor) }}</td></tr> <tr>@if(!empty($snapshot['order_parts']['frames']))@php($originFrame = collect($snapshot['order_parts']['frames'])->first(fn ($frame) => in_array($item->requisition_item_id, array_column($frame['native_preparation']['items'], 'requisition_item_id'), true)))<td>{{ $originFrame['requisition']['number'] ?? 'Origem indisponível' }}</td>@endif<td class="pre">{{ $item->description }}</td><td>{{ $item->quantity }} {{ $item->unit }}</td><td>{{ $money($item->unit_price_minor) }}</td><td>{{ $item->tax_rate }}%</td><td>{{ $money($item->total_minor) }}</td></tr>
@endforeach @endforeach
</tbody></table> </tbody></table>
@foreach($snapshot['decision_matrix'] as $row) @foreach($snapshot['decision_matrix'] as $row)
@@ -75,6 +82,12 @@
limite por ordem: {{ $binding['max_order_quantity_milli'] === null ? 'Não definido' : str_replace('.', ',', (string)\Brick\Math\BigDecimal::of($binding['max_order_quantity_milli'])->dividedBy(1000, 3)) . ' ' . $binding['unit'] }}.</p> limite por ordem: {{ $binding['max_order_quantity_milli'] === null ? 'Não definido' : str_replace('.', ',', (string)\Brick\Math\BigDecimal::of($binding['max_order_quantity_milli'])->dividedBy(1000, 3)) . ' ' . $binding['unit'] }}.</p>
@endforeach @endforeach
@endif @endif
@if(!empty($snapshot['import_tariffs']))
<h2>Classificação pautal preservada na emissão</h2>
@foreach($snapshot['import_tariffs'] as $classification)
<p class="pre"><strong>{{ $classification['item']['description'] }}</strong><br>Código confirmado: {{ $classification['data']['confirmed_code'] }} · versão {{ $classification['version'] }} · {{ $classification['confirmed_by']['name'] }}<br>Proposta: {{ $classification['data']['proposed_code'] ?? 'Não indicada' }} · Fonte: {{ $classification['data']['source_reference'] ?? 'Por completar' }}<br>Fonte da confirmação: {{ $classification['data']['confirmation_source'] }}<br>{{ $classification['data']['deviation'] ? 'Justificação do desvio' : 'Motivo' }}: {{ $classification['reason'] }}</p>
@endforeach
@endif
<h2>Justificação da adjudicação</h2><p class="pre">{{ $snapshot['award']['justification'] }}</p> <h2>Justificação da adjudicação</h2><p class="pre">{{ $snapshot['award']['justification'] }}</p>
<h2>Matriz de avaliação congelada</h2> <h2>Matriz de avaliação congelada</h2>
@if(!empty($snapshot['comparison_policy'])) @if(!empty($snapshot['comparison_policy']))
+28 -10
View File
@@ -17,18 +17,22 @@ use App\Http\Controllers\FormalAdmissionController;
use App\Http\Controllers\FormalRecommendationController; use App\Http\Controllers\FormalRecommendationController;
use App\Http\Controllers\GeneralLedgerController; use App\Http\Controllers\GeneralLedgerController;
use App\Http\Controllers\GoodsReceiptController; use App\Http\Controllers\GoodsReceiptController;
use App\Http\Controllers\ImportLandedCostController;
use App\Http\Controllers\ImportTariffController;
use App\Http\Controllers\InventoryDispositionController; use App\Http\Controllers\InventoryDispositionController;
use App\Http\Controllers\InventoryLotController; use App\Http\Controllers\InventoryLotController;
use App\Http\Controllers\InventoryReversalController; use App\Http\Controllers\InventoryReversalController;
use App\Http\Controllers\InvestmentPolicyController; use App\Http\Controllers\InvestmentPolicyController;
use App\Http\Controllers\InvoiceController; use App\Http\Controllers\InvoiceController;
use App\Http\Controllers\OrderCancellationController; use App\Http\Controllers\OrderCancellationController;
use App\Http\Controllers\OrderPartsController;
use App\Http\Controllers\OrganizationConfigurationController; use App\Http\Controllers\OrganizationConfigurationController;
use App\Http\Controllers\PeopleHiringController; use App\Http\Controllers\PeopleHiringController;
use App\Http\Controllers\PeopleRegistryController; use App\Http\Controllers\PeopleRegistryController;
use App\Http\Controllers\PeopleReportController; use App\Http\Controllers\PeopleReportController;
use App\Http\Controllers\ProcurementReportController; use App\Http\Controllers\ProcurementReportController;
use App\Http\Controllers\ProcurementReviewReportController; use App\Http\Controllers\ProcurementReviewReportController;
use App\Http\Controllers\ProcurementSearchController;
use App\Http\Controllers\ProposalOpeningController; use App\Http\Controllers\ProposalOpeningController;
use App\Http\Controllers\PurchaseControlController; use App\Http\Controllers\PurchaseControlController;
use App\Http\Controllers\PurchaseController; use App\Http\Controllers\PurchaseController;
@@ -39,6 +43,8 @@ use App\Http\Controllers\ReceiptDocumentController;
use App\Http\Controllers\RequisitionAuditController; use App\Http\Controllers\RequisitionAuditController;
use App\Http\Controllers\RequisitionCatalogueController; use App\Http\Controllers\RequisitionCatalogueController;
use App\Http\Controllers\RequisitionController; use App\Http\Controllers\RequisitionController;
use App\Http\Controllers\SavedProcurementSearchController;
use App\Http\Controllers\SgfInvoiceDispatchController;
use App\Http\Controllers\StockController; use App\Http\Controllers\StockController;
use App\Http\Controllers\StockOperationController; use App\Http\Controllers\StockOperationController;
use App\Http\Controllers\SubmissionFormsController; use App\Http\Controllers\SubmissionFormsController;
@@ -106,11 +112,11 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('empresa/iniciar', [CompanyController::class, 'store'])->name('company.store'); Route::post('empresa/iniciar', [CompanyController::class, 'store'])->name('company.store');
Route::middleware([EnsureCompanyIsConfigured::class, EnsureWorkContext::class])->group(function () { Route::middleware([EnsureCompanyIsConfigured::class, EnsureWorkContext::class])->group(function () {
Route::get('facturas/envio-sgf', [\App\Http\Controllers\SgfInvoiceDispatchController::class,'index']); Route::get('facturas/envio-sgf', [SgfInvoiceDispatchController::class, 'index']);
Route::post('facturas/envio-sgf', [\App\Http\Controllers\SgfInvoiceDispatchController::class,'create']); Route::post('facturas/envio-sgf', [SgfInvoiceDispatchController::class, 'create']);
Route::get('facturas/envio-sgf/{id}', [\App\Http\Controllers\SgfInvoiceDispatchController::class,'show'])->whereNumber('id'); Route::get('facturas/envio-sgf/{id}', [SgfInvoiceDispatchController::class, 'show'])->whereNumber('id');
Route::post('facturas/envio-sgf/{id}/rever', [\App\Http\Controllers\SgfInvoiceDispatchController::class,'revise'])->whereNumber('id'); Route::post('facturas/envio-sgf/{id}/rever', [SgfInvoiceDispatchController::class, 'revise'])->whereNumber('id');
Route::post('facturas/envio-sgf/{id}/operar', [\App\Http\Controllers\SgfInvoiceDispatchController::class,'dispatch'])->whereNumber('id'); Route::post('facturas/envio-sgf/{id}/operar', [SgfInvoiceDispatchController::class, 'dispatch'])->whereNumber('id');
Route::get('administracao/divisao-administrativa', [AdministrativeGeographyController::class, 'review']); Route::get('administracao/divisao-administrativa', [AdministrativeGeographyController::class, 'review']);
Route::get('administracao/divisao-administrativa.csv', [AdministrativeGeographyController::class, 'exportReview']); Route::get('administracao/divisao-administrativa.csv', [AdministrativeGeographyController::class, 'exportReview']);
Route::post('stock/armazens/{warehouse}/localizacao', [StockController::class, 'warehouseGeography'])->whereNumber('warehouse'); Route::post('stock/armazens/{warehouse}/localizacao', [StockController::class, 'warehouseGeography'])->whereNumber('warehouse');
@@ -125,11 +131,19 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('api/stock-returns/{id}/withdraw', [WarehouseReturnController::class, 'withdraw'])->whereNumber('id'); Route::post('api/stock-returns/{id}/withdraw', [WarehouseReturnController::class, 'withdraw'])->whereNumber('id');
Route::post('api/stock-returns/{id}/reject', [WarehouseReturnController::class, 'reject'])->whereNumber('id'); Route::post('api/stock-returns/{id}/reject', [WarehouseReturnController::class, 'reject'])->whereNumber('id');
Route::get('compras/fornecimento', [SupplyPlanningController::class, 'index'])->name('supply.index'); Route::get('compras/fornecimento', [SupplyPlanningController::class, 'index'])->name('supply.index');
Route::get('compras/pesquisa', [\App\Http\Controllers\ProcurementSearchController::class, 'index'])->name('procurement.search'); Route::get('compras/importacoes/{import}/custos', [ImportLandedCostController::class, 'index'])->whereNumber('import')->name('imports.costs');
Route::post('compras/pesquisas-guardadas', [\App\Http\Controllers\SavedProcurementSearchController::class, 'store'])->name('procurement.saved-searches.store'); Route::get('requisicoes/{requisition}/classificacao-pautal', [ImportTariffController::class, 'index'])->whereNumber('requisition');
Route::put('compras/pesquisas-guardadas/{search}', [\App\Http\Controllers\SavedProcurementSearchController::class, 'update'])->whereNumber('search')->name('procurement.saved-searches.update'); Route::post('requisicoes/{requisition}/classificacao-pautal', [ImportTariffController::class, 'store'])->whereNumber('requisition');
Route::post('compras/pesquisas-guardadas/{search}/arquivar', [\App\Http\Controllers\SavedProcurementSearchController::class, 'archive'])->whereNumber('search')->name('procurement.saved-searches.archive'); Route::post('compras/importacoes/{import}/custos', [ImportLandedCostController::class, 'preview'])->whereNumber('import');
Route::post('compras/pesquisas-guardadas/{search}/restaurar', [\App\Http\Controllers\SavedProcurementSearchController::class, 'restore'])->whereNumber('search')->name('procurement.saved-searches.restore'); Route::post('compras/importacoes/{import}/custos/documentos', [ImportLandedCostController::class, 'document'])->whereNumber('import');
Route::post('compras/importacoes/{import}/custos/preparacao', [ImportLandedCostController::class, 'save'])->whereNumber('import');
Route::post('compras/importacoes/{import}/custos/{plan}/orcamento', [ImportLandedCostController::class, 'financial'])->whereNumber('import')->whereNumber('plan');
Route::get('compras/importacoes/{import}/custos/documentos/{document}', [ImportLandedCostController::class, 'evidence'])->whereNumber('import')->whereNumber('document');
Route::get('compras/pesquisa', [ProcurementSearchController::class, 'index'])->name('procurement.search');
Route::post('compras/pesquisas-guardadas', [SavedProcurementSearchController::class, 'store'])->name('procurement.saved-searches.store');
Route::put('compras/pesquisas-guardadas/{search}', [SavedProcurementSearchController::class, 'update'])->whereNumber('search')->name('procurement.saved-searches.update');
Route::post('compras/pesquisas-guardadas/{search}/arquivar', [SavedProcurementSearchController::class, 'archive'])->whereNumber('search')->name('procurement.saved-searches.archive');
Route::post('compras/pesquisas-guardadas/{search}/restaurar', [SavedProcurementSearchController::class, 'restore'])->whereNumber('search')->name('procurement.saved-searches.restore');
Route::get('compras/acordos/vigencia', [AgreementFollowupController::class, 'index'])->name('supply.agreements.followup'); Route::get('compras/acordos/vigencia', [AgreementFollowupController::class, 'index'])->name('supply.agreements.followup');
Route::get('compras/acordos/vigencia.csv', [AgreementFollowupController::class, 'csv'])->name('supply.agreements.followup.csv'); Route::get('compras/acordos/vigencia.csv', [AgreementFollowupController::class, 'csv'])->name('supply.agreements.followup.csv');
Route::get('compras/fornecimento.csv', [SupplyCoordinationReportController::class, 'csv'])->name('supply.coordination.csv'); Route::get('compras/fornecimento.csv', [SupplyCoordinationReportController::class, 'csv'])->name('supply.coordination.csv');
@@ -295,6 +309,10 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('adjudicacoes/{award}/decidir', [PurchaseController::class, 'decide'])->name('purchases.decide'); Route::post('adjudicacoes/{award}/decidir', [PurchaseController::class, 'decide'])->name('purchases.decide');
Route::post('adjudicacoes/{award}/emitir', [PurchaseController::class, 'issue'])->name('purchases.issue'); Route::post('adjudicacoes/{award}/emitir', [PurchaseController::class, 'issue'])->name('purchases.issue');
Route::get('ordens', [PurchaseController::class, 'index'])->name('orders.index'); Route::get('ordens', [PurchaseController::class, 'index'])->name('orders.index');
Route::get('ordens/preparar', [OrderPartsController::class, 'index'])->name('orders.parts');
Route::post('ordens/preparar', [OrderPartsController::class, 'preview'])->name('orders.parts.preview');
Route::post('ordens/parcelas/emitir', [OrderPartsController::class, 'issue'])->name('orders.parts.issue');
Route::post('adjudicacoes/{award}/parcelas/adoptar', [OrderPartsController::class, 'adopt'])->name('orders.parts.adopt');
Route::get('ordens/{order}', [PurchaseController::class, 'show'])->name('orders.show'); Route::get('ordens/{order}', [PurchaseController::class, 'show'])->name('orders.show');
Route::get('ordens/{order}/imprimir', [PurchaseController::class, 'print'])->name('orders.print'); Route::get('ordens/{order}/imprimir', [PurchaseController::class, 'print'])->name('orders.print');
Route::get('ordens/{order}/reafectacao', [PurchaseController::class, 'distributionAmendment'])->name('orders.distributions'); Route::get('ordens/{order}/reafectacao', [PurchaseController::class, 'distributionAmendment'])->name('orders.distributions');
+3
View File
@@ -92,6 +92,9 @@ $environment = ['APP_ENV' => 'testing', 'APP_DEBUG' => 'false', 'APP_KEY' => con
'MAIL_MAILER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'BROADCAST_CONNECTION' => 'null', 'BCRYPT_ROUNDS' => '4', 'MAIL_MAILER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'BROADCAST_CONNECTION' => 'null', 'BCRYPT_ROUNDS' => '4',
'COMMON_BUDGET_PATH' => 'C:/laragon/www/sgf-tempo/packages/budget-control', 'SGC_BUDGET_DISTRIBUTIONS_QA_ENABLED' => 'true', 'COMMON_BUDGET_PATH' => 'C:/laragon/www/sgf-tempo/packages/budget-control', 'SGC_BUDGET_DISTRIBUTIONS_QA_ENABLED' => 'true',
'SGC_DISTRIBUTION_QA_PUBLIC' => $private.'/public']; 'SGC_DISTRIBUTION_QA_PUBLIC' => $private.'/public'];
if (in_array('--order-parts', $argv, true)) {
$environment['SGC_ORDER_PARTS_QA_ENABLED'] = 'true';
}
file_put_contents($private.'/settings.json', json_encode($environment, JSON_THROW_ON_ERROR)); file_put_contents($private.'/settings.json', json_encode($environment, JSON_THROW_ON_ERROR));
config(['database.connections.distribution_visual_admin' => [...$config, 'database' => 'postgres', 'url' => null]]); config(['database.connections.distribution_visual_admin' => [...$config, 'database' => 'postgres', 'url' => null]]);
$admin = DB::connection('distribution_visual_admin'); $admin = DB::connection('distribution_visual_admin');
+49 -2
View File
@@ -6,6 +6,7 @@ use Illuminate\Support\Str;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
require dirname(__DIR__).'/vendor/autoload.php'; require dirname(__DIR__).'/vendor/autoload.php';
require_once __DIR__.'/../tests/Support/LandedQaReceipts.php';
$app = require dirname(__DIR__).'/bootstrap/app.php'; $app = require dirname(__DIR__).'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap(); $app->make(Kernel::class)->bootstrap();
$config = DB::connection('pgsql')->getConfig(); $config = DB::connection('pgsql')->getConfig();
@@ -20,6 +21,7 @@ if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database) || $datab
config(['database.connections.quotation_fx_admin' => [...$config, 'database' => 'postgres', 'url' => null]]); config(['database.connections.quotation_fx_admin' => [...$config, 'database' => 'postgres', 'url' => null]]);
$admin = DB::connection('quotation_fx_admin'); $admin = DB::connection('quotation_fx_admin');
$admin->statement('CREATE DATABASE "'.$database.'"'); $admin->statement('CREATE DATABASE "'.$database.'"');
$qaVerificationFailed = false;
try { try {
$environment = ['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_HOST' => $config['host'], $environment = ['APP_ENV' => 'testing', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'DB_HOST' => $config['host'],
'DB_PORT' => (string) $config['port'], 'DB_DATABASE' => $database, 'DB_USERNAME' => $config['username'], 'DB_PORT' => (string) $config['port'], 'DB_DATABASE' => $database, 'DB_USERNAME' => $config['username'],
@@ -52,13 +54,42 @@ try {
$savedSearchesMode = in_array('--saved-searches-only', $argv, true); $savedSearchesMode = in_array('--saved-searches-only', $argv, true);
$categoryApprovalsMode = in_array('--category-approvals-only', $argv, true); $categoryApprovalsMode = in_array('--category-approvals-only', $argv, true);
$orderPartsMode = in_array('--budget-order-parts-only', $argv, true); $orderPartsMode = in_array('--budget-order-parts-only', $argv, true);
$landedCostsMode = in_array('--import-landed-costs-only', $argv, true);
if ($landedCostsMode) {
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostPlanTest.php', 'tests/Feature/ImportLandedCostsTest.php', 'tests/Feature/BudgetLandedCostsContractTest.php',
'tests/Feature/SupplyPlanningTest.php', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetOrderPartsContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php', 'tests/Feature/InvoiceTest.php', 'tests/Feature/OperationalHealthTest.php']];
if (in_array('--native-financial-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportLandedCostsTest.php', '--filter=native independently reviewed cost plan']];
}
if (in_array('--tariffs-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportTariffCodesTest.php', 'tests/Feature/RequisitionCatalogueTest.php']];
}
if (in_array('--tariff-orders-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/SupplyPlanningTest.php', 'tests/Feature/ReceiptStockTest.php', '--filter=confirmed import classifications|imported item classification|native partial-order|native consolidated order|import tracking|receipt|stock']];
if (in_array('--catalogue-receipt-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=catalogue origin survives order issue']];
}
}
if (in_array('--tariff-order-regression', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', '--filter=foreign|discount evidence|admission basis changes|expired after approval|older synthetic']];
}
if (in_array('--landed-concurrency', $argv, true)) {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/budget-landed-cost-worker.php', $database, 'race']];
}
if (in_array('--landed-recovery', $argv, true)) {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'landed-costs']];
}
}
if ($orderPartsMode) { if ($orderPartsMode) {
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control'; $environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php']]; $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php']];
if (in_array('--order-parts-native', $argv, true)) { if (in_array('--order-parts-native', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php', $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php',
'tests/Feature/InvoiceTest.php', 'tests/Unit/PurchaseLineAmountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/InvoiceTest.php', 'tests/Unit/PurchaseLineAmountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
'--filter=BudgetOrderPartsContractTest|InvoiceTest|PurchaseLineAmountsTest|optional partial-order']]; '--filter=BudgetOrderPartsContractTest|InvoiceTest|PurchaseLineAmountsTest|optional partial-order|native partial-order|native consolidated order|native explicit adoption']];
} }
if (in_array('--order-parts-recovery', $argv, true)) { if (in_array('--order-parts-recovery', $argv, true)) {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'], $commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
@@ -139,6 +170,9 @@ try {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SupplierBankAccountsTest.php', 'tests/Feature/SupplierBankTest.php', $commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SupplierBankAccountsTest.php', 'tests/Feature/SupplierBankTest.php',
'tests/Feature/ExternalPaymentTest.php', 'tests/Feature/PaymentIntegrationTest.php', 'tests/Feature/QuotationExchangeFinanceTest.php']]; 'tests/Feature/ExternalPaymentTest.php', 'tests/Feature/PaymentIntegrationTest.php', 'tests/Feature/QuotationExchangeFinanceTest.php']];
} }
if ($landedCostsMode && ! landedQaCommandIsolationVerified($commands)) {
throw new LogicException('Each Pest kernel must use its own disposable PostgreSQL database.');
}
foreach ($commands as $command) { foreach ($commands as $command) {
$process = new Process($command, dirname(__DIR__), $environment, timeout: 180); $process = new Process($command, dirname(__DIR__), $environment, timeout: 180);
$process->run(); $process->run();
@@ -147,8 +181,15 @@ try {
echo $process->getErrorOutput(); echo $process->getErrorOutput();
throw new RuntimeException('Validação PostgreSQL não aprovada.'); throw new RuntimeException('Validação PostgreSQL não aprovada.');
} }
if ($landedCostsMode) {
$verified = landedQaReceiptsVerified($command, $process->getOutput());
if (! $verified) {
echo $process->getErrorOutput();
throw new RuntimeException('O processo terminou sem os recibos obrigatórios de verificação QA.');
}
}
} }
if ($conversionMode || $agreementMode || $orderLimitMode || $upgradeMode || $benchmarkMode || $draftMode || $searchMode || $productionMode || $configuredLevelsMode || $orderDocumentMode || $payableInsightsMode || $budgetDistributionMode || $categoriesMode || $savedSearchesMode || $categoryApprovalsMode || $orderPartsMode) { if ($conversionMode || $agreementMode || $orderLimitMode || $upgradeMode || $benchmarkMode || $draftMode || $searchMode || $productionMode || $configuredLevelsMode || $orderDocumentMode || $payableInsightsMode || $budgetDistributionMode || $categoriesMode || $savedSearchesMode || $categoryApprovalsMode || $orderPartsMode || $landedCostsMode) {
return; return;
} }
config(['database.connections.quotation_fx_proof' => [...$config, 'database' => $database, 'url' => null]]); config(['database.connections.quotation_fx_proof' => [...$config, 'database' => $database, 'url' => null]]);
@@ -239,7 +280,13 @@ try {
} }
} }
} }
} catch (Throwable $error) {
$qaVerificationFailed = true;
echo json_encode(['qa_verification_failed' => true, 'message' => $error->getMessage()], JSON_THROW_ON_ERROR).PHP_EOL;
} finally { } finally {
$admin->statement('DROP DATABASE "'.$database.'" WITH (FORCE)'); $admin->statement('DROP DATABASE "'.$database.'" WITH (FORCE)');
echo json_encode(['database' => $database, 'isolated_database_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL; echo json_encode(['database' => $database, 'isolated_database_removed' => true], JSON_THROW_ON_ERROR).PHP_EOL;
} }
if ($qaVerificationFailed) {
exit(1);
}
@@ -3,9 +3,16 @@
use App\Enums\PurchasingRole; use App\Enums\PurchasingRole;
use App\Models\User; use App\Models\User;
use App\Services\CommonBudget; use App\Services\CommonBudget;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportLandedCosts;
use App\Services\SupplyPlanning;
use Illuminate\Contracts\Console\Kernel; use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection; use Illuminate\Database\Connection;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php'; require __DIR__.'/../../vendor/autoload.php';
@@ -18,8 +25,10 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
throw new LogicException('Recovery is restricted to disposable local PostgreSQL QA.'); throw new LogicException('Recovery is restricted to disposable local PostgreSQL QA.');
} }
require_once __DIR__.'/../Support/ReceiptFixture.php'; require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php'; require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$orderParts = ($argv[2] ?? '') === 'order-parts'; $orderParts = ($argv[2] ?? '') === 'order-parts';
$landedCosts = ($argv[2] ?? '') === 'landed-costs';
$f = receiptFixture(); $f = receiptFixture();
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]); $author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]); $reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
@@ -63,24 +72,96 @@ $pg = static function (string $binary, array $arguments) use ($config): void {
$preDump = $directory.'/before.dump'; $preDump = $directory.'/before.dump';
$postDump = $directory.'/after.dump'; $postDump = $directory.'/after.dump';
$pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]); $pg('pg_dump', ['--format=custom', '--file='.$preDump, '--dbname='.$database]);
budgetDistributionFixtureSchema(); if ($landedCosts) {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
} else {
budgetDistributionFixtureSchema();
}
if ($orderParts) { if ($orderParts) {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up(); (require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
} }
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore $unexpectedEffects = $landedCosts
|| $db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) { ? ($db->table('budget_landed_commands')->exists() || $db->table('budget_landed_entries')->exists())
: ($db->table('budget_distributions')->exists() || $db->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists());
if ($fingerprint($db, $columns) !== $before || app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore || $unexpectedEffects) {
throw new RuntimeException('Optional schema changed pre-existing data or native balances.'); throw new RuntimeException('Optional schema changed pre-existing data or native balances.');
} }
$prepare = new Process([PHP_BINARY, __DIR__.($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php'), $database, 'prepare'], dirname(__DIR__, 2), timeout: 30); $prepare = new Process([PHP_BINARY, __DIR__.($landedCosts ? '/budget-landed-cost-worker.php' : ($orderParts ? '/budget-order-parts-worker.php' : '/budget-distribution-worker.php')), $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun(); $prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR); $input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($input['actor']); $actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor); auth()->guard()->setUser($actor);
$engine = app(CommonBudget::class)->for($actor); $engine = app(CommonBudget::class)->for($actor);
$apply = static fn ($engine) => $orderParts $apply = static fn ($engine) => $landedCosts
? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation']) ? $engine->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation'])
: $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']); : ($orderParts ? $engine->commitOrderParts($input['order'], $input['sources'], $input['operation'])
$apply($engine); : $engine->amendDistribution($input['origin'], $input['plan'], $input['hash'], 'Explicit synthetic amendment preserved in backup.', $input['operation']));
$applied = $apply($engine);
if ($landedCosts) {
foreach (['commit', 'consume'] as $kind) {
$engine->transitionLandedCosts($input['plan'], $input['version'], $applied['plan_hash'], $kind, (string) Str::uuid());
}
$money = ['subtotal_minor' => 500, 'tax_minor' => 0, 'total_minor' => 500, 'reference_subtotal_minor' => 500, 'reference_tax_minor' => 0, 'reference_total_minor' => 500];
$input['documents']['late'] = ['kind' => 'other_charge', 'id' => 2, 'source_key' => (string) Str::uuid(), 'source_version' => 1,
'creditor_key' => 'synthetic-late-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Synthetic late cost for recovery'), ...$money];
$input['components'][] = ['component_key' => 'late', 'kind' => 'other', 'origin' => 'late', ...$money];
$input['amend_operation'] = (string) Str::uuid();
$apply = static fn ($engine) => $engine->amendLandedCosts($input['plan'], $input['version'], $applied['plan_hash'], $input['version'] + 1,
$input['components'], $input['documents'], $input['amend_operation']);
$amended = $apply($engine);
if ($amended['consumed_minor'] !== 2000 || $amended['reserved_minor'] !== 500 || $amended['phase'] !== 'mixed') {
throw new RuntimeException('The recovery fixture must retain a consumption and a separate late reservation.');
}
// Separate native documentary fixture; the core-only source declarations above are not native invoices.
// All three file roots belong to this freshly generated disposable recovery directory.
$privateLive = $directory.'/private-live';
$privateBackup = $directory.'/private-backup';
$privateRestore = $directory.'/private-restored';
File::ensureDirectoryExists($privateLive);
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateLive, 'throw' => true]));
config(['import-landed-costs.qa_enabled' => true]);
supplyGrant($f['issuer'], ['procurement', 'import_prepare']);
supplyGrant($author, ['finance']);
auth()->guard()->setUser($f['issuer']);
$nativeImport = app(SupplyPlanning::class)->save($f['issuer'], 'import', supplyInput([
'purchase_order_id' => $f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic recovery jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic documentary recovery',
]));
auth()->guard()->setUser($author);
$costs = app(ImportLandedCosts::class);
$nativeData = ['operation_key' => (string) Str::uuid(), 'kind' => 'customs_assessment', 'reference' => 'RECOVERY-QA-ONLY',
'issued_on' => today()->toDateString(), 'creditor_reference' => 'Synthetic documentary authority', 'currency' => 'MZN',
'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000, 'exchange_basis' => null,
'reason' => 'Synthetic private evidence recovery; no legal rate or payment.'];
$nativeDoc = $costs->recordDocument($author, $nativeImport, $nativeData,
UploadedFile::fake()->createWithContent('recovery.pdf', "%PDF-1.4\nSynthetic original QA bytes\n%%EOF"));
$correction = $costs->recordDocument($author, $nativeImport, [...$nativeData, 'operation_key' => (string) Str::uuid(),
'record_key' => $nativeDoc->record_key, 'version' => 1, 'subtotal_minor' => 2100, 'total_minor' => 2100],
UploadedFile::fake()->createWithContent('recovery-correction.pdf', "%PDF-1.4\nSynthetic corrected QA bytes\n%%EOF"));
$evidenceManifest = [];
foreach ([$nativeDoc, $correction] as $record) {
$evidence = $record->snapshot['evidence'];
$evidenceManifest[$evidence['path']] = $evidence['sha256'];
}
if (! File::copyDirectory($privateLive, $privateBackup)) {
throw new RuntimeException('Unable to back up isolated native evidence.');
}
foreach ($evidenceManifest as $path => $checksum) {
if (hash_file('sha256', $privateBackup.'/'.$path) !== $checksum) {
throw new RuntimeException('Private evidence backup differs from the frozen documentary hash.');
}
Storage::disk('local')->delete($path);
}
auth()->guard()->logout();
if (app(ImportCostDocumentHealth::class)->inspect()['missing'] !== 2) {
throw new RuntimeException('The recovery test must demonstrate actual loss of its two synthetic original files.');
}
}
auth()->guard()->setUser($author);
if (app(CommonBudget::class)->for($author)->balance($budget) !== $balanceBefore) {
throw new RuntimeException('The original company budget changed while preparing another synthetic source.');
}
auth()->guard()->setUser($actor);
$afterColumns = []; $afterColumns = [];
foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) { foreach (array_column($db->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename') as $table) {
$afterColumns[$table] = $db->getSchemaBuilder()->getColumnListing($table); $afterColumns[$table] = $db->getSchemaBuilder()->getColumnListing($table);
@@ -111,6 +192,31 @@ try {
if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) { if (! $again['replayed'] || $fingerprint($restored, $afterColumns) !== $after) {
throw new RuntimeException('Recovered command was not replayed without new effects.'); throw new RuntimeException('Recovered command was not replayed without new effects.');
} }
if ($landedCosts) {
$position = app(CommonBudget::class)->for($restoredActor)->landedCostState($input['plan']);
if ($position['result']['consumed_minor'] !== 2000 || $position['result']['reserved_minor'] !== 500 || $position['result']['phase'] !== 'mixed') {
throw new RuntimeException('Restored per-origin positions do not match the preserved journal.');
}
if (! File::copyDirectory($privateBackup, $privateRestore)) {
throw new RuntimeException('Unable to restore private evidence into the separate QA root.');
}
Storage::set('local', Storage::build(['driver' => 'local', 'root' => $privateRestore, 'throw' => true]));
auth()->guard()->logout();
$health = app(ImportCostDocumentHealth::class)->inspect();
if (! $health['ok'] || ! $health['complete'] || $health['documents_checked'] !== 2 || $health['files_checked'] !== 2) {
throw new RuntimeException('Restored native evidence did not match the restored SQL metadata.');
}
auth()->guard()->setUser(User::query()->findOrFail($author->id));
foreach ([$nativeDoc, $correction] as $record) {
$recovered = $costs->evidence(auth()->user(), $nativeImport, $record->id);
if ($recovered->snapshot['evidence']['sha256'] !== $evidenceManifest[$recovered->snapshot['evidence']['path']]) {
throw new RuntimeException('Private native download no longer resolves the preserved original version.');
}
}
echo json_encode(['private_original_versions_restored' => 2, 'source_loss_detected' => true,
'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true,
'evidence_manifest_sha256' => hash('sha256', json_encode($evidenceManifest, JSON_THROW_ON_ERROR))], JSON_THROW_ON_ERROR).PHP_EOL;
}
DB::setDefaultConnection($default); DB::setDefaultConnection($default);
DB::purge('distribution_restore'); DB::purge('distribution_restore');
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)'); $admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
@@ -119,8 +225,10 @@ try {
$created = true; $created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]); $pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restore, $preDump]);
$restored = DB::connection('distribution_restore'); $restored = DB::connection('distribution_restore');
if ($fingerprint($restored, $columns) !== $before || $restored->getSchemaBuilder()->hasTable('budget_distributions') $unexpectedSchema = $landedCosts
|| $restored->getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')) { ? ($restored->getSchemaBuilder()->hasTable('budget_landed_commands') || $restored->getSchemaBuilder()->hasTable('budget_landed_entries'))
: ($restored->getSchemaBuilder()->hasTable('budget_distributions') || $restored->getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation'));
if ($fingerprint($restored, $columns) !== $before || $unexpectedSchema) {
throw new RuntimeException('Pre-extension recovery did not restore the original schema/data.'); throw new RuntimeException('Pre-extension recovery did not restore the original schema/data.');
} }
DB::setDefaultConnection('distribution_restore'); DB::setDefaultConnection('distribution_restore');
@@ -128,7 +236,7 @@ try {
if (app(CommonBudget::class)->for(auth()->user())->balance($budget) !== $balanceBefore) { if (app(CommonBudget::class)->for(auth()->user())->balance($budget) !== $balanceBefore) {
throw new RuntimeException('Pre-extension recovery changed the native balance.'); throw new RuntimeException('Pre-extension recovery changed the native balance.');
} }
echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => $orderParts ? 8 : 4, 'existing_balances_preserved' => true, echo json_encode(['previous_tables_preserved' => count($before), 'optional_tables' => $landedCosts ? 2 : ($orderParts ? 8 : 4), 'existing_balances_preserved' => true,
'post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true, 'pre_extension_schema_data_balance_restored' => true, 'post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true, 'pre_extension_schema_data_balance_restored' => true,
'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $postDump)], JSON_THROW_ON_ERROR).PHP_EOL; 'before_dump_sha256' => hash_file('sha256', $preDump), 'after_dump_sha256' => hash_file('sha256', $postDump)], JSON_THROW_ON_ERROR).PHP_EOL;
} finally { } finally {
@@ -28,8 +28,18 @@ require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
$f = receiptFixture(); $f = receiptFixture();
budgetDistributionFixtureSchema(); budgetDistributionFixtureSchema();
config(['budget-distributions.qa_enabled' => true]); config(['budget-distributions.qa_enabled' => true]);
$partsMode = getenv('SGC_ORDER_PARTS_QA_ENABLED') === 'true';
if ($partsMode) {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
config(['order-parts.qa_enabled' => true]);
}
$users = []; $users = [];
foreach (['owner' => PurchasingRole::Requester, 'buyer' => PurchasingRole::Procurement, 'head' => PurchasingRole::DepartmentHead, 'finance' => PurchasingRole::Finance, 'admin' => PurchasingRole::Admin] as $name => $role) { $roles = ['owner' => PurchasingRole::Requester, 'buyer' => PurchasingRole::Procurement, 'head' => PurchasingRole::DepartmentHead, 'finance' => PurchasingRole::Finance, 'admin' => PurchasingRole::Admin];
if ($partsMode) {
$roles += ['receiver' => PurchasingRole::Warehouse, 'finance-reviewer' => PurchasingRole::Finance];
}
foreach ($roles as $name => $role) {
$users[$name] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, $users[$name] = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id,
'name' => 'QA sintética · '.$role->label(), 'email' => 'qa-'.$name.'@sgc.example.invalid', 'purchasing_role' => $role]); 'name' => 'QA sintética · '.$role->label(), 'email' => 'qa-'.$name.'@sgc.example.invalid', 'purchasing_role' => $role]);
} }
@@ -43,7 +53,8 @@ foreach ([$f['r']->cost_center_id, $centre->id] as $id) {
} }
$workflow = app(RequisitionWorkflow::class); $workflow = app(RequisitionWorkflow::class);
$requests = []; $requests = [];
foreach (['draft', 'award', 'foreign'] as $purpose) { $partSuppliers = $partAwards = [];
foreach ($partsMode ? ['draft', 'award', 'award2', 'foreign'] : ['draft', 'award', 'foreign'] as $purpose) {
auth()->guard()->setUser($users['owner']); auth()->guard()->setUser($users['owner']);
$r = $workflow->save($users['owner'], ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, $r = $workflow->save($users['owner'], ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id,
'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade exclusivamente sintética para revisão visual '.$purpose, 'priority' => 'normal', 'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Necessidade exclusivamente sintética para revisão visual '.$purpose,
@@ -72,11 +83,18 @@ foreach (['draft', 'award', 'foreign'] as $purpose) {
} }
$quotes = []; $quotes = [];
for ($index = 0; $index < 3; $index++) { for ($index = 0; $index < 3; $index++) {
$supplier = Supplier::query()->findOrFail($f['order']->supplier_id)->replicate(); if ($partsMode && $purpose === 'award2') {
$supplier->name = 'Fornecedor sintético '.$purpose.' '.$index; $supplier = Supplier::query()->findOrFail($partSuppliers[$index]);
$supplier->nuit = (string) (200000000 + count($requests) * 100 + $index); } else {
$supplier->created_by = $users['buyer']->id; $supplier = Supplier::query()->findOrFail($f['order']->supplier_id)->replicate();
$supplier->save(); $supplier->name = 'Fornecedor sintético '.$purpose.' '.$index;
$supplier->nuit = (string) (200000000 + count($requests) * 100 + $index);
$supplier->created_by = $users['buyer']->id;
$supplier->save();
if ($partsMode && $purpose === 'award') {
$partSuppliers[$index] = $supplier->id;
}
}
$actor = $users['buyer']; $actor = $users['buyer'];
auth()->guard()->setUser($actor); auth()->guard()->setUser($actor);
$input = Request::create('/', 'POST', ['supplier_id' => $supplier->id, 'currency' => $purpose === 'foreign' ? 'USD' : 'MZN', $input = Request::create('/', 'POST', ['supplier_id' => $supplier->id, 'currency' => $purpose === 'foreign' ? 'USD' : 'MZN',
@@ -93,7 +111,7 @@ foreach (['draft', 'award', 'foreign'] as $purpose) {
app(QuotationController::class)->evaluate($input, $quote, $workflow); app(QuotationController::class)->evaluate($input, $quote, $workflow);
} }
} }
if ($purpose === 'foreign') { if ($purpose === 'foreign' || ($partsMode && in_array($purpose, ['award', 'award2'], true))) {
auth()->guard()->setUser($users['buyer']); auth()->guard()->setUser($users['buyer']);
$award = app(PurchaseWorkflow::class)->select($users['buyer'], $r, ['quotation_id' => $quotes[0]->id, $award = app(PurchaseWorkflow::class)->select($users['buyer'], $r, ['quotation_id' => $quotes[0]->id,
'justification' => 'Proposta exclusivamente sintética para revisão visual.', 'delivery_date' => today()->addWeek()->toDateString(), 'justification' => 'Proposta exclusivamente sintética para revisão visual.', 'delivery_date' => today()->addWeek()->toDateString(),
@@ -106,8 +124,13 @@ foreach (['draft', 'award', 'foreign'] as $purpose) {
app(PurchaseWorkflow::class)->decide($actor, $award, 'approved', null); app(PurchaseWorkflow::class)->decide($actor, $award, 'approved', null);
} }
auth()->guard()->setUser($users['buyer']); auth()->guard()->setUser($users['buyer']);
$order = app(PurchaseWorkflow::class)->issue($users['buyer'], $award); if ($purpose === 'foreign') {
$order = app(PurchaseWorkflow::class)->issue($users['buyer'], $award);
} else {
$partAwards[$purpose] = $award->id;
}
} }
} }
echo json_encode(['synthetic_only' => true, 'draft' => $requests['draft']->id, 'award' => $requests['award']->id, echo json_encode(['synthetic_only' => true, 'draft' => $requests['draft']->id, 'award' => $requests['award']->id,
'foreign_order' => $order->id, 'users' => array_map(fn ($user) => $user->email, $users)], JSON_THROW_ON_ERROR).PHP_EOL; 'foreign_order' => $order->id, 'users' => array_map(fn ($user) => $user->email, $users),
...($partsMode ? ['order_parts_awards' => $partAwards, 'receipt_stock' => $f['stock']->id, 'receipt_warehouse' => $f['warehouse']->id] : [])], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,163 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Process\Process;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|| (($argv[2] ?? '') !== 'legacy' && ! method_exists(BudgetControl::class, 'reserveLandedCosts'))) {
throw new LogicException('Landed-cost contention requires the approved common source and isolated local QA.');
}
require_once __DIR__.'/../Support/ReceiptFixture.php';
if (($argv[2] ?? '') === 'legacy') {
$actor = User::query()->findOrFail((int) ($argv[3] ?? 0));
auth()->guard()->setUser($actor);
try {
app(CommonBudget::class)->for($actor);
throw new RuntimeException('The old runtime must refuse balances with landed-cost effects.');
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 503 || (defined(BudgetControl::class.'::LANDED_COSTS_VERSION') && BudgetControl::LANDED_COSTS_VERSION === CommonBudget::LANDED_COSTS_CONTRACT)) {
throw $error;
}
echo json_encode(['old_runtime_rejected_before_balance' => true, 'status' => 503,
'runtime_landed_version' => defined(BudgetControl::class.'::LANDED_COSTS_VERSION') ? BudgetControl::LANDED_COSTS_VERSION : null], JSON_THROW_ON_ERROR).PHP_EOL;
}
exit;
}
if (($argv[2] ?? '') === 'prepare') {
$f = receiptFixture();
$finance = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$reviewer = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
auth()->guard()->setUser($finance);
$budget = app(CommonBudget::class)->for($finance)->create(['cost_center_id' => $f['r']->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Explicit synthetic additional-origin contention.']);
auth()->guard()->setUser($reviewer);
app(CommonBudget::class)->for($reviewer)->approve($budget);
$money = ['subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000,
'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000];
// Contract fixture, not a native document upload or statutory customs action.
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $finance->id, 'budget' => $budget, 'plan' => (string) Str::uuid(),
'version' => 1, 'operation' => (string) Str::uuid(),
'documents' => ['customs' => ['kind' => 'customs_assessment', 'id' => 1, 'source_key' => (string) Str::uuid(), 'source_version' => 1,
'creditor_key' => 'synthetic-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Synthetic customs source'), ...$money]],
'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs', ...$money]]], JSON_THROW_ON_ERROR);
exit;
}
if (($argv[2] ?? '') === 'write') {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
DB::select('select set_config(?, ?, false)', ['application_name', 'sgc_landed_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
$result = app(CommonBudget::class)->for($actor)->reserveLandedCosts($input['plan'], $input['version'], $input['budget'], $input['components'], $input['documents'], $input['operation']);
echo json_encode(['status' => 200, 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
} catch (BudgetFailure $error) {
echo json_encode(['status' => $error->status], JSON_THROW_ON_ERROR);
} catch (HttpExceptionInterface $error) {
echo json_encode(['status' => $error->getStatusCode()], JSON_THROW_ON_ERROR);
}
exit;
}
if (($argv[2] ?? '') !== 'race') {
throw new InvalidArgumentException('Invalid landed-cost worker mode.');
}
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
$db = DB::connection();
$db->beginTransaction();
try {
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
for ($index = 0; $index < 2; $index++) {
$contender = $input;
if ($index === 1 && $scenario !== 'same_operation') {
$contender['operation'] = (string) Str::uuid();
if ($scenario === 'same_source_different_plan') {
$contender['plan'] = (string) Str::uuid();
} else {
$contender['version'] = 2;
}
}
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($contender, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$worker->start();
$workers[] = $worker;
}
$deadline = microtime(true) + 10;
do {
$db->select('select pg_stat_clear_snapshot()');
$blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_landed_write_%' and wait_event_type='Lock'", [$database])->n;
if ($blocked >= 2) {
break;
}
usleep(50000);
} while (microtime(true) < $deadline);
if ($blocked < 2) {
throw new RuntimeException('Both writers must observably wait on the company lock.');
}
$db->commit();
$results = [];
foreach ($workers as $worker) {
$worker->wait();
if (! $worker->isSuccessful()) {
throw new RuntimeException($worker->getErrorOutput());
}
$results[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR);
}
$statuses = array_column($results, 'status');
sort($statuses);
$commands = $db->table('budget_landed_commands')->where('tenant_id', $input['tenant'])->count();
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'budget.landed_reserve')->count();
$reserved = (int) $db->table('budget_landed_entries')->where('tenant_id', $input['tenant'])->sum('reserved_minor');
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $commands !== 1 || $audits !== 1 || $reserved !== 2000
|| ($scenario === 'same_operation' && count(array_filter($results, fn ($result) => $result['replayed'])) !== 1)) {
throw new RuntimeException('Contention must retain exactly one source, budget effect and audit.');
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'commands' => $commands, 'audits' => $audits, 'reserved_minor' => $reserved], JSON_THROW_ON_ERROR).PHP_EOL;
if ($scenario === 'same_operation') {
$artifact = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
$legacy = new Process([PHP_BINARY, __FILE__, $database, 'legacy', (string) $input['actor']], dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => base_path($artifact['path'])], timeout: 30);
$legacy->mustRun();
$legacyResult = json_decode($legacy->getOutput(), true, 32, JSON_THROW_ON_ERROR);
if (($legacyResult['old_runtime_rejected_before_balance'] ?? false) !== true) {
throw new RuntimeException('The installed V1 compatibility refusal was not demonstrated.');
}
echo $legacy->getOutput();
$wholeSource = base_path('storage/framework/testing/budget-landed-whole-source-qa-20261122');
if (hash_file('sha256', $wholeSource.'/src/BudgetLandedCosts.php') !== '583e8a01097398d3acd9985d7c5d6727f62e5877bb4a7cd6be82a86fd190ced8') {
throw new RuntimeException('Preserve the frozen whole-source QA runtime used for downgrade verification.');
}
$whole = new Process([PHP_BINARY, __FILE__, $database, 'legacy', (string) $input['actor']], dirname(__DIR__, 2), ['COMMON_BUDGET_PATH' => $wholeSource], timeout: 30);
$whole->mustRun();
$wholeResult = json_decode($whole->getOutput(), true, 32, JSON_THROW_ON_ERROR);
if (($wholeResult['old_runtime_rejected_before_balance'] ?? false) !== true || ($wholeResult['runtime_landed_version'] ?? null) !== 'COMMON-BUDGET-LANDED-COST-QA-v1') {
throw new RuntimeException('The earlier whole-command runtime must refuse the new per-origin data.');
}
echo $whole->getOutput();
}
} finally {
if ($db->transactionLevel() > 0) {
$db->rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}
@@ -0,0 +1,215 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\RequisitionWorkflow;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetControl;
use Tempo\Finance\Budget\BudgetFailure;
require_once __DIR__.'/../Support/ReceiptFixture.php';
beforeEach(function () {
if (! method_exists(BudgetControl::class, 'reserveLandedCosts')) {
$this->markTestSkipped('Select the authorized unpublished common source for isolated QA.');
}
$this->f = receiptFixture();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
$this->finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($this->finance);
$this->budget = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->f['r']->cost_center_id,
'year' => (int) now()->year, 'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 20000, 'reason' => 'Explicit synthetic landed-cost budget']);
$this->actingAs($this->reviewer);
app(CommonBudget::class)->for($this->reviewer)->approve($this->budget);
$this->actingAs($this->finance);
$this->engine = app(CommonBudget::class)->for($this->finance);
$this->key = (string) Str::uuid();
$this->documents = $this->components = [];
foreach ([['supplier_invoice', 'goods', 10000, 1600], ['carrier_invoice', 'freight', 1000, 160], ['customs_assessment', 'duty', 2000, 0]] as $index => [$kind, $component, $base, $tax]) {
$money = ['subtotal_minor' => $base, 'tax_minor' => $tax, 'total_minor' => $base + $tax,
'reference_subtotal_minor' => $base, 'reference_tax_minor' => $tax, 'reference_total_minor' => $base + $tax];
// Contract-only native source declarations; native invoice integration is tested separately.
$this->documents['source-'.$index] = ['kind' => $kind, 'id' => $index + 1, 'source_key' => 'native:'.$index, 'source_version' => 1,
'creditor_key' => 'creditor:'.$index, 'currency' => 'MZN', 'revision' => hash('sha256', (string) $index), ...$money];
$this->components[] = ['component_key' => 'component-'.$index, 'kind' => $component, 'origin' => 'source-'.$index, ...$money];
}
});
test('landed reserve commit and consume affect only the additional native origin exactly once', function () {
$operation = (string) Str::uuid();
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, $operation);
expect($reserved['total_reference_minor'])->toBe(14760)->and($reserved['additional_amount_minor'])->toBe(2000)
->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(2000);
expect($this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, $operation)['replayed'])->toBeTrue();
$committed = $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid());
expect($committed['phase'])->toBe('committed')->and($this->engine->balance($this->budget)['reserved_minor'])->toBe(0)
->and($this->engine->balance($this->budget)['committed_minor'])->toBe(2000);
$consume = (string) Str::uuid();
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'consume', $consume);
expect($this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'consume', $consume)['replayed'])->toBeTrue();
expect($this->engine->balance($this->budget))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 2000, 'available_minor' => 18000])
->and(DB::table('budget_landed_commands')->count())->toBe(3)->and(DB::table('budget_landed_entries')->count())->toBe(3)
->and(DB::table('budget_landed_entries')->where('source_kind', '!=', 'customs_assessment')->count())->toBe(0)
->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
});
test('landed operation mismatch stale versions and repeated transition fail without changing the balance', function () {
$operation = (string) Str::uuid();
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, $operation);
expect(fn () => $this->engine->reserveLandedCosts($this->key, 3, $this->budget, $this->components, $this->documents, $operation))->toThrow(BudgetFailure::class);
expect(fn () => $this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'commit', (string) Str::uuid()))->toThrow(BudgetFailure::class);
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid());
expect(fn () => $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_landed_commands')->count())->toBe(2)->and($this->engine->balance($this->budget)['committed_minor'])->toBe(2000);
});
test('a native origin cannot be reserved under another plan even after its budget cancellation', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
$this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'cancel', (string) Str::uuid());
expect($this->engine->balance($this->budget)['available_minor'])->toBe(20000);
expect(fn () => $this->engine->reserveLandedCosts((string) Str::uuid(), 1, $this->budget, $this->components, $this->documents, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_landed_commands')->count())->toBe(2);
});
test('consumed customs costs cannot be cancelled or consumed a second time', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
foreach (['commit', 'consume'] as $kind) {
$this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], $kind, (string) Str::uuid());
}
foreach (['cancel', 'consume'] as $kind) {
expect(fn () => $this->engine->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], $kind, (string) Str::uuid()))->toThrow(BudgetFailure::class);
}
expect($this->engine->balance($this->budget)['consumed_minor'])->toBe(2000);
});
test('failure of the host audit rolls back the entire additional-origin financial command', function () {
$this->mock(RequisitionWorkflow::class, function ($mock) {
$mock->shouldReceive('audit')->once()->andThrow(new RuntimeException('Synthetic landed-cost audit failure'));
});
expect(fn () => $this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid()))->toThrow(RuntimeException::class);
expect(DB::table('budget_landed_commands')->count())->toBe(0)->and(DB::table('budget_landed_entries')->count())->toBe(0)
->and($this->engine->balance($this->budget)['available_minor'])->toBe(20000);
});
test('only current Finance can reserve and another company cannot inspect the native plan', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
$this->actingAs($this->f['issuer']);
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->reserveLandedCosts((string) Str::uuid(), 1, $this->budget, $this->components, $this->documents, (string) Str::uuid()))->toThrow(HttpException::class);
$other = receiptFixture();
$foreign = User::factory()->create(['tenant_id' => $other['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($foreign);
expect(app(CommonBudget::class)->for($foreign)->landedCostState($this->key))->toBeNull();
expect(fn () => app(CommonBudget::class)->for($foreign)->transitionLandedCosts($this->key, 1, $reserved['plan_hash'], 'commit', (string) Str::uuid()))->toThrow(BudgetFailure::class);
});
test('the landed history cannot be mutated deleted or silently reinstalled', function () {
$this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
foreach (['budget_landed_commands', 'budget_landed_entries'] as $table) {
$first = DB::table($table)->first();
expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $first->id)->update(['tenant_id' => $first->tenant_id])))->toThrow(QueryException::class);
expect(fn () => DB::transaction(fn () => DB::table($table)->where('id', $first->id)->delete()))->toThrow(QueryException::class);
}
expect(fn () => (require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up())->toThrow(LogicException::class);
});
test('reviewed actual-cost amendments preserve the original commitment and require new documentary versions', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, (string) Str::uuid());
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid());
$before = DB::table('budget_landed_entries')->get()->toArray();
$this->documents['source-2']['subtotal_minor'] = $this->documents['source-2']['total_minor'] = 2100;
$this->documents['source-2']['reference_subtotal_minor'] = $this->documents['source-2']['reference_total_minor'] = 2100;
$this->components[2]['subtotal_minor'] = $this->components[2]['total_minor'] = 2100;
$this->components[2]['reference_subtotal_minor'] = $this->components[2]['reference_total_minor'] = 2100;
expect(fn () => $this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, (string) Str::uuid()))->toThrow(BudgetFailure::class);
$this->documents['source-2']['id'] = 4;
$this->documents['source-2']['source_version'] = 2;
$this->documents['source-2']['revision'] = hash('sha256', 'Explicit synthetic corrected customs document');
$operation = (string) Str::uuid();
$amended = $this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, $operation);
expect($amended['additional_amount_minor'])->toBe(2100)->and($amended['phase'])->toBe('committed')
->and($amended['committed_delta_minor'])->toBe(100)->and($amended['consumed_delta_minor'])->toBe(0)
->and($this->engine->balance($this->budget)['committed_minor'])->toBe(2100)
->and(DB::table('budget_landed_entries')->limit(2)->get()->toArray())->toEqual($before);
expect($this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, $operation)['replayed'])->toBeTrue();
$this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'consume', (string) Str::uuid());
expect($this->engine->balance($this->budget)['consumed_minor'])->toBe(2100)
->and(DB::table('budget_landed_entries')->where('source_version', 1)->count())->toBe(2);
});
test('additional origins reduce funds available to the preserved legacy budget writer', function () {
$this->engine->reserveLandedCosts($this->key, 1, $this->budget, $this->components, $this->documents, (string) Str::uuid());
expect(fn () => $this->engine->record($this->f['r']->id, $this->f['r']->cost_center_id, 'operating', 'reserve', 19000, 19000))->toThrow(BudgetFailure::class);
expect(DB::table('budget_entries')->count())->toBe(0)->and($this->engine->balance($this->budget)['available_minor'])->toBe(18000);
});
function addLandedContractSource(object $test, string $key = 'native:late', int $amount = 500): void
{
$money = ['subtotal_minor' => $amount, 'tax_minor' => 0, 'total_minor' => $amount,
'reference_subtotal_minor' => $amount, 'reference_tax_minor' => 0, 'reference_total_minor' => $amount];
$test->documents['late'] = ['kind' => 'other_charge', 'id' => 4, 'source_key' => $key, 'source_version' => 1,
'creditor_key' => 'synthetic-other-authority', 'currency' => 'MZN', 'revision' => hash('sha256', 'Explicit synthetic additional document'), ...$money];
$test->components[] = ['component_key' => 'late', 'kind' => 'other', 'origin' => 'late', ...$money];
}
test('per-origin consumption and release preserve the consumed source and reject stale financial revisions', function () {
addLandedContractSource($this);
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, (string) Str::uuid());
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'commit', (string) Str::uuid(), ['native:2'], 1);
$consume = (string) Str::uuid();
$partial = $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'consume', $consume, ['native:2'], 2);
expect($partial)->toMatchArray(['phase' => 'mixed', 'revision' => 3, 'reserved_minor' => 500, 'committed_minor' => 0, 'consumed_minor' => 2000]);
expect(fn () => $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'cancel', (string) Str::uuid(), ['native:late'], 2))->toThrow(BudgetFailure::class);
$released = $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'cancel', (string) Str::uuid(), ['native:late'], 3);
expect($released['reserved_delta_minor'])->toBe(-500)->and($released['consumed_minor'])->toBe(2000)
->and($this->engine->balance($this->budget))->toMatchArray(['reserved_minor' => 0, 'committed_minor' => 0, 'consumed_minor' => 2000, 'available_minor' => 18000]);
expect(fn () => $this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'cancel', (string) Str::uuid(), ['native:2'], 4))->toThrow(BudgetFailure::class);
expect($this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], 'consume', $consume, ['native:2'], 2)['replayed'])->toBeTrue();
expect(DB::table('budget_landed_commands')->count())->toBe(4);
});
test('a late documentary origin is reserved and consumed without repeating an earlier consumption', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, (string) Str::uuid());
foreach (['commit', 'consume'] as $kind) {
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], $kind, (string) Str::uuid());
}
addLandedContractSource($this);
$amended = $this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, (string) Str::uuid(), 3);
expect($amended)->toMatchArray(['phase' => 'mixed', 'reserved_minor' => 500, 'committed_minor' => 0, 'consumed_minor' => 2000]);
$this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'commit', (string) Str::uuid());
$final = $this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'consume', (string) Str::uuid());
expect($final)->toMatchArray(['phase' => 'consumed', 'consumed_delta_minor' => 500, 'consumed_minor' => 2500])
->and($this->engine->balance($this->budget)['consumed_minor'])->toBe(2500)
->and(DB::table('budget_landed_entries')->where('source_key', 'native:2')->where('consumed_minor', '>', 0)->count())->toBe(1);
});
test('a corrected consumed source commits only its explicit increment and never reduces the consumed floor', function () {
$reserved = $this->engine->reserveLandedCosts($this->key, 2, $this->budget, $this->components, $this->documents, (string) Str::uuid());
foreach (['commit', 'consume'] as $kind) {
$this->engine->transitionLandedCosts($this->key, 2, $reserved['plan_hash'], $kind, (string) Str::uuid());
}
foreach (['subtotal_minor', 'total_minor', 'reference_subtotal_minor', 'reference_total_minor'] as $field) {
$this->documents['source-2'][$field] = $this->components[2][$field] = 2100;
}
$this->documents['source-2']['id'] = 4;
$this->documents['source-2']['source_version'] = 2;
$this->documents['source-2']['revision'] = hash('sha256', 'Explicit synthetic correction from 2000 to 2100');
$amended = $this->engine->amendLandedCosts($this->key, 2, $reserved['plan_hash'], 4, $this->components, $this->documents, (string) Str::uuid());
expect($amended)->toMatchArray(['reserved_delta_minor' => 100, 'consumed_delta_minor' => 0, 'consumed_minor' => 2000]);
$this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'commit', (string) Str::uuid());
$final = $this->engine->transitionLandedCosts($this->key, 4, $amended['plan_hash'], 'consume', (string) Str::uuid());
expect($final)->toMatchArray(['consumed_delta_minor' => 100, 'consumed_minor' => 2100]);
$before = DB::table('budget_landed_commands')->count();
foreach (['subtotal_minor', 'total_minor', 'reference_subtotal_minor', 'reference_total_minor'] as $field) {
$this->documents['source-2'][$field] = $this->components[2][$field] = 1900;
}
$this->documents['source-2']['id'] = 5;
$this->documents['source-2']['source_version'] = 3;
$this->documents['source-2']['revision'] = hash('sha256', 'Synthetic lower correction needs separate consumed-cost reconciliation');
expect(fn () => $this->engine->amendLandedCosts($this->key, 4, $amended['plan_hash'], 6, $this->components, $this->documents, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_landed_commands')->count())->toBe($before)->and($this->engine->balance($this->budget)['consumed_minor'])->toBe(2100);
});
@@ -161,8 +161,10 @@ test('cancellation releases only its unconsumed issued part and never replenishe
$control->commitOrderParts($order, [orderPartsAmount($source, 4000, 0)], (string) Str::uuid()); $control->commitOrderParts($order, [orderPartsAmount($source, 4000, 0)], (string) Str::uuid());
$key = (string) Str::uuid(); $key = (string) Str::uuid();
$input = [orderPartsAmount($source, 4000, 1)]; $input = [orderPartsAmount($source, 4000, 1)];
expect($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeFalse() $this->actingAs($this->finance);
->and($control->cancelOrderParts($order, $input, $key)['replayed'])->toBeTrue(); $cancel = app(CommonBudget::class)->for($this->finance);
expect($cancel->cancelOrderParts($order, $input, $key)['replayed'])->toBeFalse()
->and($cancel->cancelOrderParts($order, $input, $key)['replayed'])->toBeTrue();
expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 0, 'available_minor' => 94000]); expect(orderPartsBalance($this))->toMatchArray(['reserved_minor' => 6000, 'committed_minor' => 0, 'available_minor' => 94000]);
expect(fn () => $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6001, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(fn () => $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6001, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class);
$control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 2)], (string) Str::uuid()); $control->commitOrderParts((string) Str::uuid(), [orderPartsAmount($source, 6000, 2)], (string) Str::uuid());
@@ -181,8 +183,8 @@ test('consumed orders reject cancellation and over-consumption without changing
$next = orderPartsAmount($source, 5001, 2); $next = orderPartsAmount($source, 5001, 2);
$next['allocations'][0]['order_key'] = $order; $next['allocations'][0]['order_key'] = $order;
expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts(orderPartsInvoice($this, 5001)->id, [$next], (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts(orderPartsInvoice($this, 5001)->id, [$next], (string) Str::uuid()))->toThrow(BudgetFailure::class);
$this->actingAs($this->f['issuer']); $this->actingAs($this->finance);
expect(fn () => app(CommonBudget::class)->for($this->f['issuer'])->cancelOrderParts($order, [orderPartsAmount($source, 10000, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(fn () => app(CommonBudget::class)->for($this->finance)->cancelOrderParts($order, [orderPartsAmount($source, 10000, 2)], (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(orderPartsBalance($this))->toMatchArray(['committed_minor' => 5000, 'consumed_minor' => 5000]); expect(orderPartsBalance($this))->toMatchArray(['committed_minor' => 5000, 'consumed_minor' => 5000]);
}); });
@@ -238,8 +240,8 @@ test('bad invoice allocation rolls back every origin and an unconsumed cancelled
$invoice = orderPartsInvoice($this, 25001); $invoice = orderPartsInvoice($this, 25001);
expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, $input, (string) Str::uuid()))->toThrow(BudgetFailure::class); expect(fn () => app(CommonBudget::class)->for($this->finance)->consumeOrderParts($invoice->id, $input, (string) Str::uuid()))->toThrow(BudgetFailure::class);
expect(DB::table('budget_order_consumptions')->count())->toBe(0)->and(DB::table('budget_order_commands')->count())->toBe(1); expect(DB::table('budget_order_consumptions')->count())->toBe(0)->and(DB::table('budget_order_commands')->count())->toBe(1);
$this->actingAs($this->f['issuer']); $this->actingAs($this->finance);
$control->cancelOrderParts($order, [orderPartsAmount($a, 10000, 1), orderPartsAmount($b, 20000, 1)], (string) Str::uuid()); app(CommonBudget::class)->for($this->finance)->cancelOrderParts($order, [orderPartsAmount($a, 10000, 1), orderPartsAmount($b, 20000, 1)], (string) Str::uuid());
$this->actingAs($this->finance); $this->actingAs($this->finance);
$cancelled = orderPartsAmount($a, 100, 2); $cancelled = orderPartsAmount($a, 100, 2);
$cancelled['allocations'][0]['order_key'] = $order; $cancelled['allocations'][0]['order_key'] = $order;
@@ -0,0 +1,94 @@
<?php
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\Budget\BudgetLandedCostPlan;
beforeEach(function () {
if (! class_exists(BudgetLandedCostPlan::class)) {
$this->markTestSkipped('Select the authorized unpublished common source for isolated QA.');
}
});
/** Explicit synthetic values, not legal rates or real documents. */
function landedCostMoney(int $base, int $tax): array
{
return ['subtotal_minor' => $base, 'tax_minor' => $tax, 'total_minor' => $base + $tax,
'reference_subtotal_minor' => $base, 'reference_tax_minor' => $tax, 'reference_total_minor' => $base + $tax];
}
function landedCostExample(): array
{
$documents = $components = [];
foreach ([['goods', 'supplier_invoice', 10000, 1600], ['freight', 'carrier_invoice', 1000, 160], ['duty', 'customs_assessment', 2000, 0]] as $index => [$kind, $document, $base, $tax]) {
$key = 'source-'.($index + 1);
$documents[$key] = ['kind' => $document, 'id' => $index + 1, 'creditor_key' => 'creditor-'.($index + 1),
'source_key' => 'native:'.($index + 1), 'source_version' => 1,
'currency' => 'MZN', 'revision' => hash('sha256', $key), ...landedCostMoney($base, $tax)];
$components[] = ['component_key' => $kind, 'kind' => $kind, 'origin' => $key, ...landedCostMoney($base, $tax)];
}
return [$components, $documents];
}
test('landed cost reconciles each creditor document and both existing budget tax bases without financial effects', function () {
[$components, $documents] = landedCostExample();
$withTax = BudgetLandedCostPlan::reconcile($components, $documents, true);
$withoutTax = BudgetLandedCostPlan::reconcile($components, $documents, false);
expect($withTax['total_minor'])->toBe(14760)->and($withTax['subtotal_minor'])->toBe(13000)
->and($withTax['budget_amount_minor'])->toBe(14760)->and($withoutTax['budget_amount_minor'])->toBe(13000)
->and($withTax['documents']['source-1']['total_minor'])->toBe(11600)
->and($withTax['documents']['source-2']['total_minor'])->toBe(1160)
->and($withTax['documents']['source-3']['total_minor'])->toBe(2000)
->and($withTax['financial_effects'])->toBeFalse();
expect(BudgetLandedCostPlan::reconcile(array_reverse($components), array_reverse($documents, true), true)['fingerprint'])->toBe($withTax['fingerprint']);
});
test('missing tax and reference values remain unknown instead of becoming zero', function (string $field) {
[$components, $documents] = landedCostExample();
unset($components[2][$field]);
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
})->with(['tax_minor', 'reference_tax_minor', 'reference_total_minor']);
test('an invoice cannot be disguised as a second origin by changing its component role', function () {
[$components, $documents] = landedCostExample();
$documents['source-2']['id'] = $documents['source-1']['id'];
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
});
test('a balanced grand total cannot compensate amounts between different creditors', function () {
[$components, $documents] = landedCostExample();
$components[0] = [...$components[0], ...landedCostMoney(10001, 1600)];
$components[1] = [...$components[1], ...landedCostMoney(999, 160)];
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
});
test('multiple customs components reconcile once to one customs principal', function () {
[$components, $documents] = landedCostExample();
$components[2] = [...$components[2], ...landedCostMoney(1200, 0)];
$components[] = ['component_key' => 'ice', 'kind' => 'ice', 'origin' => 'source-3', ...landedCostMoney(800, 0)];
$plan = BudgetLandedCostPlan::reconcile($components, $documents, true);
expect($plan['total_minor'])->toBe(14760)->and($plan['documents'])->toHaveCount(3)->and($plan['components'])->toHaveCount(4);
});
test('customs impositions require a customs origin and MZN cannot acquire a fictitious conversion', function () {
[$components, $documents] = landedCostExample();
$documents['source-3']['kind'] = 'supplier_invoice';
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
[$components, $documents] = landedCostExample();
$documents['source-1']['reference_total_minor']++;
$documents['source-1']['reference_tax_minor']++;
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
});
test('aggregate values refuse overflow even when every document is individually representable', function () {
[$components, $documents] = landedCostExample();
foreach ($documents as $key => &$document) {
$document = [...$document, ...landedCostMoney(100000000000000, 0)];
}
unset($document);
foreach ($components as &$component) {
$component = [...$component, ...landedCostMoney(100000000000000, 0)];
}
unset($component);
expect(fn () => BudgetLandedCostPlan::reconcile($components, $documents, true))->toThrow(BudgetFailure::class);
});
+414
View File
@@ -0,0 +1,414 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\Invoice;
use App\Models\PurchaseAward;
use App\Models\Quotation;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\BudgetWorkflow;
use App\Services\ConflictGuard;
use App\Services\ImportCostDocumentHealth;
use App\Services\ImportLandedCosts;
use App\Services\InvoiceWorkflow;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\QueryException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetLandedCostPlan;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
if (! class_exists(BudgetLandedCostPlan::class)) {
$this->markTestSkipped('Select the authorized unpublished common source for isolated QA.');
}
config(['import-landed-costs.qa_enabled' => true]);
Storage::fake('local');
$this->f = receiptFixture();
supplyGrant($this->f['issuer'], ['procurement', 'import_prepare']);
$this->actingAs($this->f['issuer']);
$this->import = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
'purchase_order_id' => $this->f['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Synthetic QA jurisdiction',
'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Explicit synthetic test regime',
]));
// Existing explicit organisation membership makes raw role fields insufficient.
$this->finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
supplyGrant($this->finance, ['finance']);
supplyGrant($this->reviewer, ['finance']);
$this->actingAs($this->finance);
$this->budget = Budget::query()->create(['tenant_id' => $this->finance->tenant_id, 'cost_center_id' => $this->f['r']->cost_center_id,
'year' => now()->year, 'amount_minor' => 100000, 'includes_tax' => true, 'created_by' => $this->finance->id,
'approved_by' => $this->reviewer->id, 'reason' => 'Synthetic documentary preparation only']);
$this->input = ['operation_key' => (string) Str::uuid(), 'kind' => 'customs_assessment', 'reference' => 'CUSTOMS-QA-01',
'issued_on' => today()->toDateString(), 'creditor_reference' => 'Synthetic customs authority', 'currency' => 'MZN',
'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000, 'exchange_basis' => null,
'reason' => 'Explicit synthetic document; not a legal rate.'];
$this->file = UploadedFile::fake()->createWithContent('customs.pdf', "%PDF-1.4\nSynthetic QA evidence only\n%%EOF");
});
function importCostSelection(object $test, SupplyRecord $document): array
{
return ['budget_id' => $test->budget->id, 'documents' => [['origin' => 'customs', 'kind' => 'customs_assessment', 'id' => $document->id]],
'components' => [['component_key' => 'duty', 'kind' => 'duty', 'origin' => 'customs',
'subtotal_minor' => 2000, 'tax_minor' => 0, 'total_minor' => 2000,
'reference_subtotal_minor' => 2000, 'reference_tax_minor' => 0, 'reference_total_minor' => 2000]]];
}
test('technical inspection detects private import evidence loss alteration and orphans without repairing facts', function () {
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$path = $document->snapshot['evidence']['path'];
$original = Storage::disk('local')->get($path);
$facts = DB::table('supply_records')->orderBy('id')->get()->toJson();
$this->assertThrows(fn () => app(ImportCostDocumentHealth::class)->inspect(), HttpException::class);
auth()->logout();
$health = app(ImportCostDocumentHealth::class);
expect($health->inspect()['ok'])->toBeTrue();
$changed = $original;
$changed[10] = $changed[10] === 'x' ? 'y' : 'x';
Storage::disk('local')->put($path, $changed);
expect($health->inspect()['altered'])->toBe(1);
Storage::disk('local')->delete($path);
expect($health->inspect()['missing'])->toBe(1);
Storage::disk('local')->put($path, 'Altered synthetic evidence');
Storage::disk('local')->put('import-costs/unreferenced.pdf', 'Synthetic orphan');
Storage::disk('local')->put('unrelated.txt', 'Not part of this inspection');
$result = $health->inspect();
expect($result['altered'])->toBe(1)->and($result['unreferenced'])->toBe(1)->and($result['files_checked'])->toBe(2)
->and($health->inspect(1)['complete'])->toBeFalse()
->and(json_encode($result))->not->toContain($path, $this->input['creditor_reference'], $document->record_key)
->and(DB::table('supply_records')->orderBy('id')->get()->toJson())->toBe($facts);
Storage::disk('local')->put($path, $original);
Storage::disk('local')->assertExists('import-costs/unreferenced.pdf');
});
test('cost to item references are frozen in reviewed preparations without stock valuation or financial effects', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$selection = [...importCostSelection($this, $document), 'item_references' => [
['component_key' => 'duty', 'purchase_order_item_ids' => [$this->f['line']->id]],
]];
$stock = DB::table('stock_movements')->get()->toJson();
$draft = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null,
'version' => 0, 'action' => 'save', 'reason' => 'Synthetic explicit item reference only', 'data' => $selection]);
$this->actingAs($this->reviewer);
$approved = $service->save($this->reviewer, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
'version' => 1, 'action' => 'approve', 'reason' => 'Independent synthetic item reference review', 'data' => []]);
expect($approved->snapshot['plan']['item_references']['duty'])->toBe([$this->f['line']->only(['id', 'description', 'unit', 'quantity'])])
->and($service->workspace($this->reviewer, $this->import)['orderItems']->pluck('id')->all())->toBe([$this->f['line']->id])
->and(DB::table('stock_movements')->get()->toJson())->toBe($stock)
->and(DB::table('budget_landed_commands')->count())->toBe(0);
$this->actingAs($this->finance);
$selection['item_references'] = [];
$next = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key,
'version' => 2, 'action' => 'save', 'reason' => 'Remove reference only in the next synthetic version', 'data' => $selection]);
expect($next->snapshot['plan']['item_references'])->toBe([])
->and($approved->fresh()->snapshot['plan']['item_references']['duty'][0]['id'])->toBe($this->f['line']->id);
});
test('cost item references reject foreign items repeated items and unknown components', function () {
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$foreign = receiptFixture();
$this->actingAs($this->finance);
foreach ([
['component_key' => 'duty', 'purchase_order_item_ids' => [$foreign['line']->id]],
['component_key' => 'duty', 'purchase_order_item_ids' => [$this->f['line']->id, $this->f['line']->id]],
['component_key' => 'missing', 'purchase_order_item_ids' => [$this->f['line']->id]],
] as $reference) {
expect(fn () => $service->preview($this->finance, $this->import, [...importCostSelection($this, $document), 'item_references' => [$reference]]))->toThrow(HttpException::class);
}
expect(SupplyRecord::query()->where('kind', 'import_cost_plan')->count())->toBe(0);
});
test('a customs document and reviewed preparation preserve one native source and create no invoice or budget effect', function () {
$service = app(ImportLandedCosts::class);
$before = DB::table('budget_entries')->get()->toJson();
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
expect($service->recordDocument($this->finance, $this->import, $this->input, $this->file)->id)->toBe($document->id);
Storage::disk('local')->assertExists($document->snapshot['evidence']['path']);
$selection = importCostSelection($this, $document);
$preview = $service->preview($this->finance, $this->import, $selection);
expect($preview['total_minor'])->toBe(2000)->and($preview['financial_effects'])->toBeFalse();
$save = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'action' => 'save',
'reason' => 'Prepare the synthetic documentary cost', 'data' => $selection];
$draft = $service->save($this->finance, $this->import, $save);
expect($service->save($this->finance, $this->import, $save)->id)->toBe($draft->id);
$approve = ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1, 'action' => 'approve',
'reason' => 'Independent synthetic documentary review', 'data' => []];
expect(fn () => $service->save($this->finance, $this->import, $approve))->toThrow(HttpException::class);
$this->actingAs($this->reviewer);
$approved = $service->save($this->reviewer, $this->import, $approve);
expect($approved->state)->toBe('approved')->and($approved->version)->toBe(2)
->and($approved->snapshot['plan'])->toBe($preview)->and($draft->fresh()->state)->toBe('draft')
->and(Invoice::query()->count())->toBe(0)->and(DB::table('budget_entries')->get()->toJson())->toBe($before)
->and(DB::table('budget_consumptions')->count())->toBe(0);
});
test('changed content cannot reuse an operation or duplicate its documentary identity', function () {
$service = app(ImportLandedCosts::class);
$service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$changed = [...$this->input, 'subtotal_minor' => 2001, 'total_minor' => 2001];
expect(fn () => $service->recordDocument($this->finance, $this->import, $changed, $this->file))->toThrow(HttpException::class);
$changed['operation_key'] = (string) Str::uuid();
expect(fn () => $service->recordDocument($this->finance, $this->import, $changed, $this->file))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'import_cost_doc')->count())->toBe(1)
->and(Storage::disk('local')->allFiles())->toHaveCount(1);
});
test('frozen explicit foreign rates preserve original currency and never average customs costs', function () {
$input = [...$this->input, 'currency' => 'USD', 'subtotal_minor' => 3, 'tax_minor' => 1, 'total_minor' => 4,
'exchange_basis' => ['rate' => '63.125', 'quoted_on' => today()->toDateString(), 'source' => 'Explicit synthetic Finance rate']];
$document = app(ImportLandedCosts::class)->recordDocument($this->finance, $this->import, $input, $this->file);
expect($document->data['currency'])->toBe('USD')->and($document->data['total_minor'])->toBe(4)
->and($document->snapshot['reference_amounts'])->toBe(['subtotal_minor' => 189, 'tax_minor' => 63, 'total_minor' => 252]);
$changed = [...$input, 'operation_key' => (string) Str::uuid(), 'record_key' => $document->record_key, 'version' => 1,
'exchange_basis' => [...$input['exchange_basis'], 'rate' => '64.00']];
expect(fn () => app(ImportLandedCosts::class)->recordDocument($this->finance, $this->import, $changed, $this->file))->toThrow(HttpException::class);
expect($document->fresh()->data['exchange_basis']['rate'])->toBe('63.125');
});
test('changed evidence blocks approval while an independent return remains possible', function () {
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$draft = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'action' => 'save', 'reason' => 'Synthetic recoverable preparation', 'data' => importCostSelection($this, $document)]);
Storage::disk('local')->put($document->snapshot['evidence']['path'], 'Altered synthetic bytes');
$this->actingAs($this->reviewer);
$decision = ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
'action' => 'approve', 'reason' => 'Independent review of changed evidence', 'data' => []];
expect(fn () => $service->save($this->reviewer, $this->import, $decision))->toThrow(HttpException::class);
$decision['action'] = 'return';
expect($service->save($this->reviewer, $this->import, $decision)->state)->toBe('returned');
});
test('a stale import and disabled operational runtime cannot write documentary costs', function () {
$service = app(ImportLandedCosts::class);
$this->actingAs($this->f['issuer']);
app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic dispatch evidence', 'event_date' => today()->toDateString()], 'transit', $this->import));
$this->actingAs($this->finance);
expect(fn () => $service->recordDocument($this->finance, $this->import, $this->input, $this->file))->toThrow(HttpException::class);
config(['import-landed-costs.qa_enabled' => false]);
expect($service->ready())->toBeFalse();
expect(fn () => $service->recordDocument($this->finance, $this->import, $this->input, $this->file))->toThrow(HttpException::class);
expect(Storage::disk('local')->allFiles())->toBe([]);
});
test('withdrawn Finance authority and foreign company sources fail before a document is stored', function () {
$service = app(ImportLandedCosts::class);
$other = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
// This account has no active Finance membership in this organisation.
$this->actingAs($other);
expect(fn () => $service->recordDocument($other, $this->import, $this->input, $this->file))->toThrow(HttpException::class);
$this->actingAs($this->finance);
$foreign = receiptFixture();
supplyGrant($foreign['issuer'], ['procurement', 'import_prepare']);
$this->actingAs($foreign['issuer']);
$foreignImport = app(SupplyPlanning::class)->save($foreign['issuer'], 'import', supplyInput([
'purchase_order_id' => $foreign['order']->id, 'purpose' => 'internal', 'jurisdiction' => 'Other synthetic entity',
'origin_country' => 'Other A', 'dispatch_country' => 'Other B', 'regime' => 'Other synthetic regime',
]));
$this->actingAs($this->finance);
expect(fn () => $service->recordDocument($this->finance, $foreignImport, $this->input, $this->file))->toThrow(ModelNotFoundException::class);
expect(Storage::disk('local')->allFiles())->toBe([]);
});
test('failure after private storage rolls back the native source and removes only its new blob', function () {
$this->mock(RequisitionWorkflow::class, function ($mock) {
$mock->shouldReceive('audit')->once()->andThrow(new RuntimeException('Synthetic failure after document storage'));
});
expect(fn () => app(ImportLandedCosts::class)->recordDocument($this->finance, $this->import, $this->input, $this->file))->toThrow(RuntimeException::class);
expect(SupplyRecord::query()->where('kind', 'import_cost_doc')->count())->toBe(0)
->and(Storage::disk('local')->allFiles())->toBe([]);
});
test('the authenticated multipart route stores exact cents and the workspace never exposes private storage paths', function () {
$this->withoutVite(); // HTTP contract only; the new page is compiled separately in a private candidate.
$url = '/compras/importacoes/'.$this->import->id.'/custos';
$this->post($url.'/documentos', [...$this->input, 'subtotal_minor' => '2000', 'tax_minor' => '0', 'total_minor' => '2000', 'file' => $this->file])->assertRedirect($url);
$document = SupplyRecord::query()->where('kind', 'import_cost_doc')->sole();
expect($document->data['total_minor'])->toBe(2000);
$page = $this->get($url)->assertOk()->assertViewHas('page', fn (array $page) => $page['component'] === 'supply/import-costs' && $page['encryptHistory'] === true);
expect($page->headers->get('Cache-Control'))->toContain('no-store');
expect($page->getContent())->not->toContain($document->snapshot['evidence']['path']);
$this->get($url.'/documentos/'.$document->id)->assertOk()->assertHeader('X-Content-Type-Options', 'nosniff');
$this->actingAs($this->f['issuer'])->get($url)->assertForbidden();
});
test('a native validated goods invoice keeps its original principal and budget consumption when included in landed cost', function () {
$this->actingAs($this->f['issuer']);
$event = ['evidence' => 'Explicit synthetic logistics document', 'event_date' => today()->toDateString()];
$transit = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput($event, 'transit', $this->import));
$arrived = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput($event, 'arrive', $transit));
supplyGrant($this->f['receiver'], ['warehouse', 'import_customs']);
$this->actingAs($this->f['receiver']);
$this->import = app(SupplyPlanning::class)->save($this->f['receiver'], 'import', supplyInput($event, 'release', $arrived));
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '1.000'));
$this->actingAs($this->finance);
DB::transaction(function () {
app(ConflictGuard::class)->lockCompany($this->finance);
app(BudgetWorkflow::class)->record($this->finance, $this->f['r'], 'reserve', 10000, 10000);
app(BudgetWorkflow::class)->record($this->finance, $this->f['r'], 'commit', 10000, 10000);
});
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $this->f['order'], [
'number' => 'NATIVE-IMPORT-GOODS-QA', 'issued_on' => today()->toDateString(), 'subtotal' => '100.00', 'tax' => '0.00', 'total' => '100.00',
'items' => [['purchase_order_item_id' => $this->f['line']->id, 'quantity' => '1.000', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0']],
]);
$this->actingAs($this->reviewer);
app(InvoiceWorkflow::class)->validate($this->reviewer, $invoice);
$before = DB::table('budget_consumptions')->get()->toJson();
$this->actingAs($this->finance);
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$selection = importCostSelection($this, $document);
$selection['documents'][] = ['origin' => 'goods', 'kind' => 'supplier_invoice', 'id' => $invoice->id];
$selection['components'][] = ['component_key' => 'goods', 'kind' => 'goods', 'origin' => 'goods',
'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000,
'reference_subtotal_minor' => 10000, 'reference_tax_minor' => 0, 'reference_total_minor' => 10000];
$plan = $service->preview($this->finance, $this->import, $selection);
expect($plan['total_minor'])->toBe(12000)->and($plan['documents']['goods']['total_minor'])->toBe(10000)
->and($plan['document_details']['goods']['financial_authority'])->toBe('native_invoice')
->and(Invoice::query()->count())->toBe(1)->and($invoice->fresh()->total_minor)->toBe(10000)
->and(DB::table('budget_consumptions')->get()->toJson())->toBe($before);
});
test('a documentary correction preserves both original bytes and values and invalidates an older preparation', function () {
$service = app(ImportLandedCosts::class);
$first = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$input = [...$this->input, 'operation_key' => (string) Str::uuid(), 'record_key' => $first->record_key, 'version' => 1,
'subtotal_minor' => 2100, 'total_minor' => 2100, 'reason' => 'Explicit correction in a new documentary version'];
$second = $service->recordDocument($this->finance, $this->import, $input, $this->file);
expect($second->version)->toBe(2)->and($second->record_key)->toBe($first->record_key)->and($first->fresh()->data['total_minor'])->toBe(2000)
->and($second->data['total_minor'])->toBe(2100)->and($second->snapshot['supersedes'])->toBe($first->id)
->and(Storage::disk('local')->allFiles())->toHaveCount(2);
expect($service->evidence($this->finance, $this->import, $first->id)->id)->toBe($first->id);
expect(fn () => $service->preview($this->finance, $this->import, importCostSelection($this, $first)))->toThrow(HttpException::class);
expect(fn () => $service->recordDocument($this->finance, $this->import, [...$input, 'operation_key' => (string) Str::uuid()], $this->file))->toThrow(HttpException::class);
});
test('the native independently reviewed cost plan reserves commits and consumes the additional origin once', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($this->finance, $this->import, $this->input, $this->file);
$draft = $service->save($this->finance, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'action' => 'save', 'reason' => 'Synthetic additional-origin budget preparation', 'data' => importCostSelection($this, $document)]);
$operation = ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0, 'reason' => 'Reserve the independently reviewed synthetic customs cost'];
expect(fn () => $service->financial($this->finance, $this->import, $draft, $operation))->toThrow(HttpException::class);
expect(DB::table('budget_landed_commands')->count())->toBe(0);
$this->actingAs($this->reviewer);
$approved = $service->save($this->reviewer, $this->import, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
'action' => 'approve', 'reason' => 'Independent native review before additional budget effects', 'data' => []]);
$this->actingAs($this->finance);
$receipt = $service->financial($this->finance, $this->import, $approved, $operation);
expect($receipt->state)->toBe('reserved')->and($receipt->snapshot['common_result']['additional_amount_minor'])->toBe(2000);
expect($service->financial($this->finance, $this->import, $approved, $operation)->id)->toBe($receipt->id);
foreach (['commit', 'consume'] as $index => $action) {
$input = ['operation_key' => (string) Str::uuid(), 'action' => $action, 'financial_revision' => $index + 1, 'reason' => 'Explicit synthetic additional-origin '.$action];
$this->post('/compras/importacoes/'.$this->import->id.'/custos/'.$approved->id.'/orcamento', $input)->assertRedirect();
}
$state = $service->workspace($this->finance, $this->import)['financialState'];
expect($state['phase'])->toBe('consumed')->and($state['additional_amount_minor'])->toBe(2000)
->and(DB::table('budget_landed_entries')->sum('reserved_minor'))->toBe(0)
->and(DB::table('budget_landed_entries')->sum('committed_minor'))->toBe(0)
->and((string) DB::table('budget_landed_entries')->sum('consumed_minor'))->toBe('2000')
->and(SupplyRecord::query()->where('kind', 'import_cost_event')->count())->toBe(3)
->and(Invoice::query()->count())->toBe(0)->and(DB::table('budget_consumptions')->count())->toBe(0);
});
/** Native documentary preparation; synthetic evidence is deliberately not a statutory assessment. */
function approvedImportCostPreparation(object $test): array
{
$test->actingAs($test->finance);
$service = app(ImportLandedCosts::class);
$document = $service->recordDocument($test->finance, $test->import, $test->input, $test->file);
$draft = $service->save($test->finance, $test->import, ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0,
'action' => 'save', 'reason' => 'Explicit synthetic documentary cost preparation', 'data' => importCostSelection($test, $document)]);
$test->actingAs($test->reviewer);
$approved = $service->save($test->reviewer, $test->import, ['operation_key' => (string) Str::uuid(), 'record_key' => $draft->record_key, 'version' => 1,
'action' => 'approve', 'reason' => 'Independent review of the synthetic cost sources', 'data' => []]);
$test->actingAs($test->finance);
return [$document, $approved];
}
test('logistics progression does not revoke a reviewed cost preparation or require another financial approval', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
[, $approved] = approvedImportCostPreparation($this);
$service = app(ImportLandedCosts::class);
$service->financial($this->finance, $this->import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve', 'financial_revision' => 0,
'reason' => 'Reserve the reviewed synthetic documentary cost']);
$this->actingAs($this->f['issuer']);
$transit = app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput(['evidence' => 'Synthetic dispatch record', 'event_date' => today()->toDateString()], 'transit', $this->import));
$this->actingAs($this->finance);
$event = $service->financial($this->finance, $transit, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'commit', 'financial_revision' => 1,
'reason' => 'The logistics event did not change the approved financial sources']);
expect($event->state)->toBe('committed')->and(SupplyRecord::query()->where('kind', 'import_cost_plan')->count())->toBe(2)
->and($service->workspace($this->finance, $transit)['importRecord']['context_changed'])->toBeFalse();
expect(fn () => $service->financial($this->finance, $transit, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'consume', 'financial_revision' => 1,
'reason' => 'A stale financial action must retain its preparation']))->toThrow(HttpException::class);
expect(DB::table('budget_landed_commands')->count())->toBe(2);
});
test('a failed native financial receipt rolls back the common journal and its audit together', function () {
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000009_create_budget_landed_costs.php')->up();
[, $approved] = approvedImportCostPreparation($this);
if (DB::getDriverName() === 'pgsql') {
DB::unprepared("CREATE FUNCTION reject_synthetic_import_cost_receipt() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.kind = 'import_cost_event' THEN RAISE EXCEPTION 'Synthetic receipt failure'; END IF; RETURN NEW; END $$;
CREATE TRIGGER reject_synthetic_import_cost_receipt BEFORE INSERT ON supply_records FOR EACH ROW EXECUTE FUNCTION reject_synthetic_import_cost_receipt();");
} else {
DB::unprepared("CREATE TRIGGER reject_synthetic_import_cost_receipt BEFORE INSERT ON supply_records WHEN NEW.kind = 'import_cost_event' BEGIN SELECT RAISE(ABORT, 'Synthetic receipt failure'); END;");
}
expect(fn () => app(ImportLandedCosts::class)->financial($this->finance, $this->import, $approved, ['operation_key' => (string) Str::uuid(), 'action' => 'reserve',
'financial_revision' => 0, 'reason' => 'Synthetic failure after the common financial command']))->toThrow(QueryException::class);
expect(DB::table('budget_landed_commands')->count())->toBe(0)->and(DB::table('budget_landed_entries')->count())->toBe(0)
->and(DB::table('audit_logs')->where('action', 'budget.landed_reserve')->count())->toBe(0)
->and(SupplyRecord::query()->where('kind', 'import_cost_plan')->where('state', 'approved')->count())->toBe(1);
});
test('an import with retained cost evidence cannot be silently moved to another order', function () {
app(ImportLandedCosts::class)->recordDocument($this->finance, $this->import, $this->input, $this->file);
// A separate, internally consistent already-issued synthetic target; no claim of a new approval execution.
$request = $this->f['r']->replicate();
$request->number = 'REQ-TARGET-'.Str::random(8);
$request->save();
$requested = $this->f['r']->items()->sole()->replicate();
$requested->requisition_id = $request->id;
$requested->save();
$oldAward = PurchaseAward::query()->findOrFail($this->f['order']->purchase_award_id);
$quote = Quotation::query()->findOrFail($oldAward->quotation_id)->replicate();
$quote->requisition_id = $request->id;
$quote->reference = 'SYNTHETIC-TARGET';
$quote->save();
$quote->items()->create(['tenant_id' => $request->tenant_id, 'requisition_item_id' => $requested->id,
...$this->f['line']->only(['description', 'quantity', 'unit', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor'])]);
$award = $oldAward->replicate();
$award->requisition_id = $request->id;
$award->quotation_id = $quote->id;
$award->save();
$order = $this->f['order']->replicate();
$order->requisition_id = $request->id;
$order->purchase_award_id = $award->id;
$order->number = 'OC-TARGET-'.Str::random(8);
$order->save();
$line = $this->f['line']->replicate();
$line->purchase_order_id = $order->id;
$line->requisition_item_id = $requested->id;
$line->save();
$this->actingAs($this->f['issuer']);
expect(fn () => app(SupplyPlanning::class)->save($this->f['issuer'], 'import', supplyInput([
...$this->import->data, 'purchase_order_id' => $order->id], 'save', $this->import)))->toThrow(ValidationException::class);
expect(SupplyRecord::query()->where('kind', 'import')->count())->toBe(1)
->and($this->import->fresh()->purchase_order_id)->toBe($this->f['order']->id);
});
+101
View File
@@ -0,0 +1,101 @@
<?php
use App\Models\SupplyRecord;
use App\Services\ImportTariffCodes;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
config(['import-tariffs.qa_enabled' => true]);
$this->withoutVite();
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
$this->lineId = $this->f['r']->items()->sole()->id;
});
function tariffInput(string $action, array $data = []): array
{
return [...['operation_key' => (string) Str::uuid(), 'action' => $action, 'version' => 0,
'reason' => 'Synthetic classification; no legal rate or customs declaration.'], ...$data];
}
test('native tariff master reuse and buyer deviation preserve proposals versions approvals and financial facts', function () {
supplyGrant($this->f['issuer'], ['procurement', 'requester']);
$service = app(ImportTariffCodes::class);
$order = $this->f['order']->fresh()->getAttributes();
$stock = $this->f['stock']->fresh()->getAttributes();
$master = $service->save($this->f['issuer'], $this->f['r'], tariffInput('master', ['stock_item_id' => $this->f['stock']->id,
'code' => '1234.56', 'source_reference' => 'Synthetic source v1; not a legal classification']));
$proposalInput = tariffInput('propose', ['requisition_item_id' => $this->lineId, 'master_id' => $master->id,
'code' => $master->data['code'], 'source_reference' => $master->data['source_reference']]);
$proposal = $service->save($this->f['issuer'], $this->f['r'], $proposalInput);
expect($service->save($this->f['issuer'], $this->f['r'], $proposalInput)->id)->toBe($proposal->id);
$confirmation = $service->save($this->f['issuer'], $this->f['r'], tariffInput('confirm', ['version' => 1,
'requisition_item_id' => $this->lineId, 'code' => '1234.57', 'source_reference' => 'Synthetic buyer source v2',
'reason' => 'Synthetic buyer explains why the proposed code is changed.']));
expect($confirmation->state)->toBe('confirmed')->and($confirmation->data['deviation'])->toBeTrue()
->and($confirmation->data['proposed_code'])->toBe('1234.56')->and($confirmation->data['confirmed_code'])->toBe('1234.57')
->and($confirmation->snapshot['master']['version'])->toBe(1)->and($confirmation->snapshot['calculations_activated'])->toBeFalse()
->and($proposal->fresh()->state)->toBe('proposed')->and($this->f['order']->fresh()->getAttributes())->toBe($order)
->and($this->f['stock']->fresh()->getAttributes())->toBe($stock)->and(DB::table('budget_consumptions')->count())->toBe(0);
$service->save($this->f['issuer'], $this->f['r'], tariffInput('master', ['version' => 1, 'stock_item_id' => $this->f['stock']->id,
'code' => '1234.58', 'source_reference' => 'Synthetic later material source']));
expect($confirmation->fresh()->data['confirmed_code'])->toBe('1234.57');
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$proposalInput, 'operation_key' => (string) Str::uuid(), 'version' => 2]))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'import_tariff')->count())->toBe(2);
});
test('unknown proposed code remains unknown and a requester cannot confirm or edit the material master', function () {
supplyGrant($this->f['issuer'], ['requester']);
$service = app(ImportTariffCodes::class);
$proposal = $service->save($this->f['issuer'], $this->f['r'], tariffInput('propose', ['requisition_item_id' => $this->lineId]));
expect($proposal->data['proposed_code'])->toBeNull()->and($proposal->state)->toBe('proposed');
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], tariffInput('confirm', ['version' => 1,
'requisition_item_id' => $this->lineId, 'code' => '1234', 'source_reference' => 'Synthetic source'])))->toThrow(HttpException::class);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], tariffInput('master', ['stock_item_id' => $this->f['stock']->id,
'code' => '1234', 'source_reference' => 'Synthetic source'])))->toThrow(HttpException::class);
$workspace = $service->workspace($this->f['issuer'], $this->f['r']);
expect($workspace['canConfirm'])->toBeFalse()->and($workspace['masters']->total())->toBe(0)->and($workspace['stockItems']->total())->toBe(0);
});
test('tariff classification rejects stale versions reused operations foreign items and a disabled capability', function () {
supplyGrant($this->f['issuer'], ['procurement']);
$service = app(ImportTariffCodes::class);
$input = tariffInput('propose', ['requisition_item_id' => $this->lineId, 'code' => '1234', 'source_reference' => 'Synthetic source']);
$service->save($this->f['issuer'], $this->f['r'], $input);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'code' => '5678']))->toThrow(HttpException::class);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], [...$input, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
$foreign = receiptFixture();
$foreignItemId = $foreign['r']->items()->sole()->id;
$this->actingAs($this->f['issuer']);
expect(fn () => $service->workspace($this->f['issuer'], $foreign['r']))->toThrow(ModelNotFoundException::class);
expect(fn () => $service->save($this->f['issuer'], $this->f['r'], tariffInput('propose', ['requisition_item_id' => $foreignItemId])))->toThrow(ModelNotFoundException::class);
config(['import-tariffs.qa_enabled' => false]);
expect(fn () => $service->workspace($this->f['issuer'], $this->f['r']))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'import_tariff')->count())->toBe(1);
});
test('authenticated classification forms use private encrypted history and paginated native sources', function () {
supplyGrant($this->f['issuer'], ['procurement']);
$url = '/requisicoes/'.$this->f['r']->id.'/classificacao-pautal';
$this->post($url, tariffInput('master', ['stock_item_id' => $this->f['stock']->id, 'code' => '1234.56', 'source_reference' => 'Synthetic source']))->assertRedirect();
$this->get($url.'?search=1234')->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')
->assertInertia(fn (Assert $page) => $page->component('supply/import-tariffs')->where('canConfirm', true)
->where('masters.total', 1)->where('masters.data.0.data.code', '1234.56')->where('history.total', 0));
$this->getJson($url.'?masters_page=0')->assertUnprocessable();
$this->postJson($url, tariffInput('master', ['stock_item_id' => $this->f['stock']->id]))->assertUnprocessable()->assertJsonValidationErrors(['code', 'source_reference']);
});
test('classification revalidates current company permissions rather than trusting the initial buyer identity', function () {
supplyGrant($this->f['issuer'], ['procurement']);
DB::table('organization_memberships')->where('user_id', $this->f['issuer']->id)->delete();
expect(fn () => app(ImportTariffCodes::class)->save($this->f['issuer'], $this->f['r'], tariffInput('master', [
'stock_item_id' => $this->f['stock']->id, 'code' => '1234', 'source_reference' => 'Synthetic source'])))->toThrow(HttpException::class);
expect(SupplyRecord::query()->whereIn('kind', ['stock_tariff', 'import_tariff'])->count())->toBe(0);
});
+1
View File
@@ -42,6 +42,7 @@ test('operational health integrates native inspections without changing facts or
expect($result['schema_version'])->toBe(1)->and($result['ok'])->toBeTrue()->and($result['complete'])->toBeTrue() expect($result['schema_version'])->toBe(1)->and($result['ok'])->toBeTrue()->and($result['complete'])->toBeTrue()
->and($result['checks']['replenishment']['result']['work']['total'])->toBe(0) ->and($result['checks']['replenishment']['result']['work']['total'])->toBe(0)
->and($result['checks']['receipt_documents']['result']['documents_checked'])->toBe(0); ->and($result['checks']['receipt_documents']['result']['documents_checked'])->toBe(0);
expect($result['checks']['import_cost_documents']['status'])->toBe('passed');
expect($output)->not->toContain($this->temporaryStorage, 'tenant_id', 'password'); expect($output)->not->toContain($this->temporaryStorage, 'tenant_id', 'password');
expect(File::get(storage_path('framework/replenishment-command-status.json')))->toBe($heartbeat); expect(File::get(storage_path('framework/replenishment-command-status.json')))->toBe($heartbeat);
foreach ($before as $table => $rows) { foreach ($before as $table => $rows) {
+406 -26
View File
@@ -13,9 +13,11 @@ use App\Models\Department;
use App\Models\Equipment; use App\Models\Equipment;
use App\Models\EquipmentSparePart; use App\Models\EquipmentSparePart;
use App\Models\InvestmentPolicy; use App\Models\InvestmentPolicy;
use App\Models\Invoice;
use App\Models\PurchaseAward; use App\Models\PurchaseAward;
use App\Models\PurchaseControlPolicy; use App\Models\PurchaseControlPolicy;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\PurchaseRevision; use App\Models\PurchaseRevision;
use App\Models\QualificationSet; use App\Models\QualificationSet;
use App\Models\Quotation; use App\Models\Quotation;
@@ -35,9 +37,12 @@ use App\Services\ConflictGuard;
use App\Services\DocumentaryQualificationWorkflow; use App\Services\DocumentaryQualificationWorkflow;
use App\Services\EquipmentWorkflow; use App\Services\EquipmentWorkflow;
use App\Services\FormalAdmission; use App\Services\FormalAdmission;
use App\Services\ImportTariffCodes;
use App\Services\InvoiceWorkflow;
use App\Services\OrderCancellationPolicyWorkflow; use App\Services\OrderCancellationPolicyWorkflow;
use App\Services\OrderCancellationWorkflow; use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsPreparation; use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementReviewCsv; use App\Services\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport; use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison; use App\Services\ProposalComparison;
@@ -46,11 +51,13 @@ use App\Services\PurchaseControlPolicyWorkflow;
use App\Services\PurchaseRevisionWorkflow; use App\Services\PurchaseRevisionWorkflow;
use App\Services\PurchaseWorkflow; use App\Services\PurchaseWorkflow;
use App\Services\QuotationExchange; use App\Services\QuotationExchange;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionBudgetDistributions; use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionCatalogue; use App\Services\RequisitionCatalogue;
use App\Services\RequisitionWorkflow; use App\Services\RequisitionWorkflow;
use App\Services\SupplyPlanning; use App\Services\SupplyPlanning;
use App\Services\WorkflowTaskInbox; use App\Services\WorkflowTaskInbox;
use Brick\Math\BigDecimal;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str; use Illuminate\Support\Str;
@@ -63,6 +70,79 @@ require_once __DIR__.'/../Support/SupplyFixture.php';
require_once __DIR__.'/../Support/ReceiptFixture.php'; require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/BudgetDistributionSchema.php'; require_once __DIR__.'/../Support/BudgetDistributionSchema.php';
test('confirmed import classifications freeze in a newly issued native order and survive later proposals', function () {
config(['import-tariffs.qa_enabled' => true]);
$tariffs = app(ImportTariffCodes::class);
$this->actingAs($this->buyer);
$proposal = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic documentary classification only',
'reason' => 'Proposed synthetic classification without a legal rate.']);
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$this->actingAs($this->buyer);
$before = DB::table('budget_entries')->get()->toJson();
expect(fn () => app(PurchaseWorkflow::class)->issue($this->buyer, $award))->toThrow(HttpException::class);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('budget_entries')->get()->toJson())->toBe($before);
$confirmed = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => $proposal->version,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic buyer source', 'reason' => 'Buyer confirms the synthetic documentary code.']);
config(['import-tariffs.qa_enabled' => false]);
expect(fn () => app(PurchaseWorkflow::class)->issue($this->buyer, $award))->toThrow(HttpException::class);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('budget_entries')->get()->toJson())->toBe($before);
config(['import-tariffs.qa_enabled' => true]);
$order = app(PurchaseWorkflow::class)->issue($this->buyer, $award);
expect($order->snapshot['import_tariffs'][$this->item->id]['record_id'])->toBe($confirmed->id);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1234.56')->assertSee('Synthetic buyer source');
$tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => $confirmed->version,
'requisition_item_id' => $this->item->id, 'code' => '1234.57', 'source_reference' => 'Later synthetic proposal', 'reason' => 'Later proposal must preserve the earlier issued classification.']);
expect($order->fresh()->snapshot['import_tariffs'][$this->item->id]['data']['confirmed_code'])->toBe('1234.56');
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1234.56')->assertDontSee('1234.57');
});
test('a partial native order retains its confirmed imported item classification before committing funds', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Select the approved isolated-QA common source for native order parts.');
}
config(['import-tariffs.qa_enabled' => true]);
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$this->actingAs($this->buyer);
$tariffs = app(ImportTariffCodes::class);
$proposal = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'propose', 'version' => 0,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic partial order source', 'reason' => 'Synthetic imported item proposal for a partial order.']);
expect(fn () => app(OrderPartsWorkflow::class)->issue($this->buyer, $input))->toThrow(HttpException::class);
expect(DB::table('budget_order_commands')->count())->toBe(0)->and(PurchaseOrder::query()->count())->toBe(0);
$confirmed = $tariffs->save($this->buyer, $this->r, ['operation_key' => (string) Str::uuid(), 'action' => 'confirm', 'version' => $proposal->version,
'requisition_item_id' => $this->item->id, 'code' => '1234.56', 'source_reference' => 'Synthetic confirmed partial order source', 'reason' => 'Buyer confirms the synthetic partial order classification.']);
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
expect($order->snapshot['import_tariffs'][$this->item->id]['record_id'])->toBe($confirmed->id)
->and($order->total_minor)->toBe(4000)->and(DB::table('budget_order_commands')->count())->toBe(1);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('1234.56');
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
supplyGrant($this->buyer, ['procurement', 'import_prepare']);
supplyGrant($receiver, ['warehouse', 'import_customs']);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'TARIFF-QA', 'name' => 'Synthetic tariff receipt warehouse']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'TARIFF-QA', 'name' => 'Synthetic classified material', 'unit' => 'un']);
$payload = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'TARIFF-RECEIPT-QA', 'received_on' => today()->toDateString(),
'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $order->items()->sole()->id,
'received_quantity' => '0.400', 'accepted_quantity' => '0.400', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$this->actingAs($receiver);
expect(fn () => app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload))->toThrow(ValidationException::class);
expect(StockMovement::query()->count())->toBe(0);
$this->actingAs($this->buyer);
$planning = app(SupplyPlanning::class);
$import = $planning->save($this->buyer, 'import', supplyInput(['purchase_order_id' => $order->id, 'purpose' => 'internal',
'jurisdiction' => 'Synthetic jurisdiction', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Synthetic customs regime']));
$event = ['evidence' => 'Synthetic customs evidence only', 'event_date' => today()->toDateString()];
$transit = $planning->save($this->buyer, 'import', supplyInput($event, 'transit', $import));
$arrived = $planning->save($this->buyer, 'import', supplyInput($event, 'arrive', $transit));
$this->actingAs($receiver);
expect(fn () => app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload))->toThrow(ValidationException::class);
$planning->save($receiver, 'import', supplyInput($event, 'release', $arrived));
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload);
expect(app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload)->id)->toBe($receipt->id)
->and(StockMovement::query()->count())->toBe(1)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(400);
});
test('distributed approved synthetic requisition follows native adjudication approval and issuance without parallel entries', function () { test('distributed approved synthetic requisition follows native adjudication approval and issuance without parallel entries', function () {
if (! method_exists(BudgetControl::class, 'recordDistribution')) { if (! method_exists(BudgetControl::class, 'recordDistribution')) {
$this->markTestSkipped('Unpublished common source requires explicit QA selection.'); $this->markTestSkipped('Unpublished common source requires explicit QA selection.');
@@ -640,7 +720,7 @@ test('catalogue origin survives order issue and automatically identifies receive
$this->get('/ordens/'.$order->id.'/recepcoes')->assertInertia(fn (Assert $p) => $p->where('progress.lines.0.stock_item_id', $stock->id)); $this->get('/ordens/'.$order->id.'/recepcoes')->assertInertia(fn (Assert $p) => $p->where('progress.lines.0.stock_item_id', $stock->id));
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertCreated(); $this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertCreated();
$this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertOk()->assertJsonPath('created', false); $this->postJson('/ordens/'.$order->id.'/recepcoes', $body)->assertOk()->assertJsonPath('created', false);
expect(StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe(1000); expect((string) StockMovement::query()->where('stock_item_id', $stock->id)->sum('quantity_milli'))->toBe('1000');
}); });
function prepareEquipmentInvestment(object $test, string $ceiling = '100.00', bool $includesTax = true): InvestmentPolicy function prepareEquipmentInvestment(object $test, string $ceiling = '100.00', bool $includesTax = true): InvestmentPolicy
@@ -1391,31 +1471,7 @@ test('optional partial-order preparation consolidates two independently approved
$first = selectPurchaseAward($this); $first = selectPurchaseAward($this);
approvePurchaseAward($this, $first); approvePurchaseAward($this, $first);
$this->actingAs($this->buyer); $this->actingAs($this->buyer);
$secondRequest = $this->r->fresh()->replicate(); [$secondRequest, $quotes] = secondNativeOrderPartsOrigin($this);
$secondRequest->number = 'REQ-ORDER-SECOND-QA';
$secondRequest->subtotal_minor = $secondRequest->total_minor = 20000;
$secondRequest->save();
$line = $this->item->replicate();
$line->requisition_id = $secondRequest->id;
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = 20000;
$line->save();
foreach ($this->r->steps()->get() as $step) {
$copy = $step->replicate();
$copy->requisition_id = $secondRequest->id;
$copy->save();
}
$quotes = [];
foreach ($this->suppliers as $index => $supplier) {
$this->actingAs($this->buyer)->post('/requisicoes/'.$secondRequest->id.'/cotacoes', ['supplier_id' => $supplier->id,
'reference' => 'PROP-SECOND-'.$index, 'delivery_days' => 5, 'valid_until' => now()->addMonth()->format('Y-m-d'),
'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $line->id, 'unit_price' => (string) (200 + $index * 100)]]])->assertSessionHasNoErrors();
$quote = Quotation::query()->where('requisition_id', $secondRequest->id)->latest('id')->firstOrFail();
$quotes[] = $quote;
foreach ([$this->buyer, $this->finance] as $evaluator) {
$this->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8',
'comment' => 'Independent synthetic evaluation for second origin.', 'no_conflict' => true])->assertSessionHasNoErrors();
}
}
$this->actingAs($this->buyer); $this->actingAs($this->buyer);
$second = app(PurchaseWorkflow::class)->select($this->buyer, $secondRequest, [...$this->selection, 'quotation_id' => $quotes[0]->id]); $second = app(PurchaseWorkflow::class)->select($this->buyer, $secondRequest, [...$this->selection, 'quotation_id' => $quotes[0]->id]);
approvePurchaseAward($this, $second); approvePurchaseAward($this, $second);
@@ -1432,3 +1488,327 @@ test('optional partial-order preparation consolidates two independently approved
->and(array_column($result['sources'], 'exchange_basis'))->toBe([null, null]) ->and(array_column($result['sources'], 'exchange_basis'))->toBe([null, null])
->and([PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()])->toBe($before); ->and([PurchaseOrder::query()->count(), DB::table('budget_entries')->count(), DB::table('audit_logs')->count()])->toBe($before);
}); });
/** Native adjudication/approval fixture; requisition approval itself is the existing synthetic source. */
function nativeOrderPartsAward(object $test, ?Requisition $request = null, ?Quotation $quote = null): PurchaseAward
{
$request ??= $test->r;
$quote ??= $test->quotes[0];
if (! DB::getSchemaBuilder()->hasTable('budget_order_commands')) {
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
}
config(['order-parts.qa_enabled' => true, 'budget-distributions.qa_enabled' => true]);
$test->actingAs($test->finance);
if (! DB::table('budgets')->where('tenant_id', $request->tenant_id)->where('cost_center_id', $request->cost_center_id)->exists()) {
$id = app(CommonBudget::class)->for($test->finance)->create(['cost_center_id' => $request->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Dotacao sintetica de ordens parciais.']);
$test->actingAs($test->admin);
app(CommonBudget::class)->for($test->admin)->approve($id);
}
$host = app(RequisitionBudgetDistributions::class);
$allocations = $quote->items()->get()->map(fn ($line) => ['allocation_key' => (string) Str::uuid(),
'line_id' => $line->requisition_item_id, 'centre_id' => $request->cost_center_id,
'subtotal_minor' => $line->subtotal_minor, 'total_minor' => $line->total_minor])->all();
$request->forceFill(['budget_distribution_preparation' => ['allocations' => $allocations,
'source_revision' => $host->revision($request, $host->requestLines($request)), 'prepared_by' => $test->owner->id,
'reason' => 'Explicit synthetic source allocation.']])->save();
$test->actingAs($test->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($test->finance, $request, 'reserve', $request->total_minor, $request->subtotal_minor));
$test->actingAs($test->buyer);
$data = [...$test->selection, 'quotation_id' => $quote->id, 'reason' => 'Explicit native award distribution.',
'budget_distribution_preparation' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'], 'line_id' => $row['line_id'], 'centre_id' => $row['centre_id'],
'subtotal' => (string) BigDecimal::of($row['subtotal_minor'])->dividedBy(100, 2),
'total' => (string) BigDecimal::of($row['total_minor'])->dividedBy(100, 2)], $allocations)];
$award = app(PurchaseWorkflow::class)->select($test->buyer, $request, $data);
approvePurchaseAward($test, $award);
$test->actingAs($test->buyer);
return $award;
}
function nativeOrderPartsInput(object $test, PurchaseAward $award, string $quantity, int $version): array
{
$quote = Quotation::query()->whereKey($award->quotation_id)->firstOrFail();
$input = ['sources' => [['award_id' => $award->id, 'items' => [['quotation_item_id' => $quote->items()->sole()->id, 'quantity' => $quantity]]]]];
$prepared = app(OrderPartsPreparation::class)->prepare($test->buyer, $input);
$distribution = DB::table('budget_distributions')->where('requisition_id', $award->requisition_id)->first();
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
$line = $prepared['sources'][0]['items'][0];
return [...$input, 'order_key' => (string) Str::uuid(), 'operation_key' => (string) Str::uuid(), 'fingerprint' => $prepared['fingerprint'],
'budget_sources' => [['origin' => $award->requisition_id, 'version' => $version, 'plan_hash' => $snapshot['plan_hash'],
'allocations' => [['allocation_key' => $snapshot['allocations'][0]['allocation_key'], 'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]]]]];
}
test('native partial-order issuance commits only forty then sixty and preserves replay and quantity caps', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
(new PurchaseOrder)->fill(['number' => 'Unpersisted legacy metadata warmup']);
(new PurchaseOrderItem)->fill(['description' => 'Unpersisted legacy metadata warmup']);
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$workflow = app(OrderPartsWorkflow::class);
$first = $workflow->issue($this->buyer, $input);
expect($first->total_minor)->toBe(4000)->and($first->items()->sole()->quantity)->toBe('0.400')
->and($first->items()->sole()->quantity_offset_milli)->toBe(0)
->and($first->hasCompleteDocumentSnapshot())->toBeTrue()
->and($workflow->issue($this->buyer, $input)->id)->toBe($first->id)
->and(DB::table('purchase_order_sources')->count())->toBe(1)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000);
$changed = $input;
$changed['sources'][0]['items'][0]['quantity'] = '0.401';
expect(fn () => $workflow->issue($this->buyer, $changed))->toThrow(HttpException::class);
$second = $workflow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 1));
expect($second->total_minor)->toBe(6000)->and($second->items()->sole()->quantity_offset_milli)->toBe(400)
->and(PurchaseOrder::query()->count())->toBe(2)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(10000)
->and($this->r->fresh()->status)->toBe('approved');
expect(fn () => nativeOrderPartsInput($this, $award, '0.001', 2))->toThrow(ValidationException::class);
$this->withoutVite();
$this->get('/ordens/preparar')->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['candidates']['data'] === []);
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertConflict();
});
test('native partial-order issuance rolls back the document and all financial effects when its audit fails', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$this->mock(RequisitionWorkflow::class)->shouldReceive('audit')->andThrow(new RuntimeException('audit failed'));
expect(fn () => app(OrderPartsWorkflow::class)->issue($this->buyer, $input))->toThrow(RuntimeException::class);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('purchase_order_sources')->count())->toBe(0)
->and(DB::table('budget_order_commands')->count())->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(10000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0);
});
test('native partial-order receipts and independent invoice validation consume exact commitments once with one stock movement per receipt', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$workflow = app(OrderPartsWorkflow::class);
$first = $workflow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$second = $workflow->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 1));
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$validator = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'PARTS-QA', 'name' => 'Armazem de ensaio']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'PARTS-QA', 'name' => 'Material de ensaio', 'unit' => 'un']);
foreach ([[$first, '0.400', '40.00'], [$second, '0.600', '60.00']] as [$order, $quantity, $amount]) {
$this->actingAs($receiver);
$line = $order->items()->sole();
$payload = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GR-PART-'.$order->id, 'received_on' => today()->toDateString(),
'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $line->id, 'received_quantity' => $quantity,
'accepted_quantity' => $quantity, 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload);
expect(app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload)->id)->toBe($receipt->id)
->and($receipt->items()->sole()->snapshot['source_line']['requisition_item_id'])->toBe($this->item->id);
$this->actingAs($this->finance);
$allocation = $order->snapshot['order_parts']['budget_sources'][0]['allocations'][0];
$data = ['number' => 'FT-PART-'.$order->id, 'issued_on' => today()->toDateString(), 'subtotal' => $amount, 'tax' => '0.00', 'total' => $amount,
'items' => [['purchase_order_item_id' => $line->id, 'quantity' => $quantity]], 'reason' => 'Explicit native Finance allocation.',
'order_part_allocations' => [['origin' => $this->r->id, 'allocation_key' => $allocation['allocation_key'], 'subtotal' => $amount, 'total' => $amount]]];
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $order, $data);
expect(fn () => app(InvoiceWorkflow::class)->validate($this->finance, $invoice))->toThrow(HttpException::class);
$this->actingAs($validator);
app(InvoiceWorkflow::class)->validate($validator, $invoice);
app(InvoiceWorkflow::class)->validate($validator, $invoice->fresh());
expect($invoice->fresh()->status)->toBe('validated');
}
expect(Invoice::query()->count())->toBe(2)
->and(DB::table('budget_order_consumptions')->count())->toBe(2)
->and(StockMovement::query()->count())->toBe(2)
->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(1000)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(0)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(10000)
->and(DB::table('budget_distribution_consumptions')->count())->toBe(0)
->and(DB::table('budget_consumptions')->count())->toBe(0);
});
function secondNativeOrderPartsOrigin(object $test): array
{
$secondRequest = $test->r->fresh()->replicate();
$secondRequest->number = 'REQ-ORDER-SECOND-QA';
if (DB::getSchemaBuilder()->hasColumn('requisitions', 'budget_distribution_preparation')) {
$secondRequest->budget_distribution_preparation = null;
}
$secondRequest->subtotal_minor = $secondRequest->total_minor = 20000;
$secondRequest->save();
$line = $test->item->replicate();
$line->requisition_id = $secondRequest->id;
$line->unit_price_minor = $line->subtotal_minor = $line->total_minor = 20000;
$line->save();
foreach ($test->r->steps()->get() as $step) {
$copy = $step->replicate();
$copy->requisition_id = $secondRequest->id;
$copy->save();
}
$quotes = [];
foreach ($test->suppliers as $index => $supplier) {
$test->actingAs($test->buyer)->post('/requisicoes/'.$secondRequest->id.'/cotacoes', ['supplier_id' => $supplier->id,
'reference' => 'PROP-SECOND-'.$index, 'delivery_days' => 5, 'valid_until' => now()->addMonth()->format('Y-m-d'),
'payment_terms' => '30 dias', 'no_conflict' => true, 'items' => [['requisition_item_id' => $line->id, 'unit_price' => (string) (200 + $index * 100)]]])->assertSessionHasNoErrors();
$quote = Quotation::query()->where('requisition_id', $secondRequest->id)->latest('id')->firstOrFail();
$quotes[] = $quote;
foreach ([$test->buyer, $test->finance] as $evaluator) {
$test->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8',
'comment' => 'Independent synthetic evaluation for second origin.', 'no_conflict' => true])->assertSessionHasNoErrors();
}
}
return [$secondRequest, $quotes];
}
test('native consolidated order retains both origins and consumes a single invoice without duplicate stock or debt', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$first = nativeOrderPartsAward($this);
[$request, $quotes] = secondNativeOrderPartsOrigin($this);
$second = nativeOrderPartsAward($this, $request, $quotes[0]);
$a = nativeOrderPartsInput($this, $first, '1.000', 0);
$b = nativeOrderPartsInput($this, $second, '1.000', 0);
$input = [...$a, 'sources' => [...$a['sources'], ...$b['sources']], 'budget_sources' => [...$a['budget_sources'], ...$b['budget_sources']]];
$input['fingerprint'] = app(OrderPartsPreparation::class)->prepare($this->buyer, $input)['fingerprint'];
$order = app(OrderPartsWorkflow::class)->issue($this->buyer, $input);
expect($order->total_minor)->toBe(30000)->and($order->items()->count())->toBe(2)
->and(DB::table('purchase_order_sources')->where('purchase_order_id', $order->id)->count())->toBe(2)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->whereKey($order->id)->exists())->toBeTrue();
$this->withoutVite();
$this->get('/ordens/'.$order->id)->assertOk()->assertViewHas('page', fn (array $page) => count($page['props']['orderPartsSources']) === 2);
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee($this->r->number)->assertSee($request->number)
->assertSee('Origens desta ordem')->assertSee('Controlo orçamental confirmado para as parcelas emitidas.');
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$reviewer = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($receiver);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CONSOL-QA', 'name' => 'Armazem de ensaio']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'CONSOL-QA', 'name' => 'Material de ensaio', 'unit' => 'un']);
$lines = $order->items()->orderBy('id')->get();
$receiptData = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GR-CONSOL-QA', 'received_on' => today()->toDateString(),
'warehouse_id' => $warehouse->id, 'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'received_quantity' => '1.000',
'accepted_quantity' => '1.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id])->all()];
$receipt = app(ReceiptWorkflow::class)->confirm($receiver, $order, $receiptData);
expect($receipt->items()->count())->toBe(2);
$this->actingAs($this->finance);
$data = ['number' => 'FT-CONSOL-QA', 'issued_on' => today()->toDateString(), 'subtotal' => '150.00', 'tax' => '0.00', 'total' => '150.00',
'items' => $lines->map(fn ($line) => ['purchase_order_item_id' => $line->id, 'quantity' => '0.500'])->all(),
'reason' => 'Explicit allocations for both approved origins.', 'order_part_allocations' => [
['origin' => $first->requisition_id, 'allocation_key' => $a['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '50.00', 'total' => '50.00'],
['origin' => $second->requisition_id, 'allocation_key' => $b['budget_sources'][0]['allocations'][0]['allocation_key'], 'subtotal' => '100.00', 'total' => '100.00']]];
$invoice = app(InvoiceWorkflow::class)->register($this->finance, $order, $data);
$this->actingAs($reviewer);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice);
app(InvoiceWorkflow::class)->validate($reviewer, $invoice->fresh());
expect(Invoice::query()->count())->toBe(1)
->and($invoice->fresh()->total_minor)->toBe(15000)->and($invoice->fresh()->status)->toBe('validated')
->and(DB::table('budget_order_consumptions')->where('invoice_id', $invoice->id)->count())->toBe(2)
->and((int) DB::table('budget_order_consumptions')->sum('amount_minor'))->toBe(15000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(15000)
->and(StockMovement::query()->count())->toBe(2)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(2000);
$this->actingAs($this->owner);
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeTrue();
$request->forceFill(['requester_id' => $this->head->id])->save();
expect(PurchaseOrder::query()->visibleTo($this->owner)->whereKey($order->id)->exists())->toBeFalse();
});
test('native partial-order cancellation uses independent Finance and preserves the unissued reservation and requisition', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$issue = app(OrderPartsWorkflow::class);
$order = $issue->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
config(['order_cancellation.enabled' => true]);
$policyFlow = app(OrderCancellationPolicyWorkflow::class);
$admins = [$this->admin, User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin]),
User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin])];
$this->actingAs($admins[0]);
$policy = $policyFlow->propose($admins[0], ['previous_id' => 0, 'mode' => 'issued_order', 'enabled' => true,
'valid_from' => today()->toDateString(), 'valid_until' => today()->addMonth()->toDateString(), 'reason' => 'Synthetic existing cancellation policy.']);
foreach (array_slice($admins, 1) as $admin) {
$this->actingAs($admin);
$policyFlow->review($admin, $policy, 'approved', 'Independent synthetic policy review.');
}
$this->actingAs($this->buyer);
$flow = app(OrderCancellationWorkflow::class);
$record = $flow->request($this->buyer, $order, ['operation_key' => (string) Str::uuid(),
'reason' => 'Synthetic cancellation before any execution.', 'evidence' => 'Documented synthetic business decision.']);
$this->actingAs($this->finance);
$flow->decide($this->finance, $record, 'approved', 'Independent Finance confirmation.');
$flow->decide($this->finance, $record->fresh(), 'approved', 'Independent Finance confirmation.');
expect($flow->state($order))->toBe('cancelled')->and($this->r->fresh()->status)->toBe('approved')
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(0)
->and(DB::table('budget_order_commands')->where('kind', 'cancel')->count())->toBe(1);
$this->actingAs($this->owner);
expect($flow->canRevise($this->owner, $record->fresh()))->toBeFalse()
->and(fn () => $flow->revise($this->owner, $record->fresh(), today()->addMonth()->toDateString(), 'No automatic whole-source reissue.'))->toThrow(HttpException::class);
$this->actingAs($this->buyer);
$remaining = $issue->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.600', 2));
expect($remaining->total_minor)->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(6000)
->and((int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(0);
});
test('native partial-order forms preview without writes and issue through the authenticated encrypted path', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
$award = nativeOrderPartsAward($this);
$this->withoutVite();
$this->get('/ordens/preparar')->assertOk()->assertViewHas('page', fn (array $page) => $page['component'] === 'purchases/parts' && $page['encryptHistory'] === true);
$input = nativeOrderPartsInput($this, $award, '0.400', 0);
$before = DB::table('audit_logs')->count();
$this->post('/ordens/preparar', ['sources' => $input['sources']])->assertOk()
->assertViewHas('page', fn (array $page) => $page['props']['preview']['prepared']['total_minor'] === 4000 && $page['props']['preview']['can_issue'] === true);
expect(PurchaseOrder::query()->count())->toBe(0)->and(DB::table('audit_logs')->count())->toBe($before);
$this->post('/ordens/parcelas/emitir', $input)->assertRedirect();
$order = PurchaseOrder::query()->sole();
$this->post('/ordens/parcelas/emitir', $input)->assertRedirect('/ordens/'.$order->id);
expect(PurchaseOrder::query()->count())->toBe(1);
$this->actingAs($this->finance)->get('/ordens/preparar')->assertForbidden();
$this->actingAs($this->buyer);
config(['order-parts.qa_enabled' => false]);
$this->get('/ordens/preparar')->assertServiceUnavailable();
$this->post('/ordens/parcelas/emitir', $input)->assertServiceUnavailable();
expect(PurchaseOrder::query()->count())->toBe(1);
});
test('native explicit adoption keeps the old reserve unchanged and supports replay after a partial order is issued', function () {
if (! method_exists(BudgetControl::class, 'commitOrderParts')) {
$this->markTestSkipped('Explicit unpublished common source required.');
}
budgetDistributionFixtureSchema();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000007_create_budget_order_parts.php')->up();
(require __DIR__.'/../../database/qa-migrations/2026_11_22_000008_create_purchase_order_sources.php')->up();
config(['order-parts.qa_enabled' => true, 'budget-distributions.qa_enabled' => true]);
$this->actingAs($this->finance);
$id = app(CommonBudget::class)->for($this->finance)->create(['cost_center_id' => $this->r->cost_center_id, 'year' => (int) now()->year,
'kind' => 'operating', 'includes_tax' => true, 'amount_minor' => 100000, 'reason' => 'Synthetic legacy budget before adoption.']);
$this->actingAs($this->admin);
app(CommonBudget::class)->for($this->admin)->approve($id);
$this->actingAs($this->finance);
DB::transaction(fn () => app(BudgetWorkflow::class)->record($this->finance, $this->r, 'reserve', 10000, 10000));
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$old = DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->get()->toArray();
$this->actingAs($this->buyer);
$source = ['sources' => [['award_id' => $award->id, 'items' => [['quotation_item_id' => $this->quotes[0]->items()->sole()->id, 'quantity' => '0.400']]]]];
expect(app(OrderPartsWorkflow::class)->preview($this->buyer, $source)['financial'][0]['requires_adoption'])->toBeTrue();
$operation = (string) Str::uuid();
$this->post('/adjudicacoes/'.$award->id.'/parcelas/adoptar', ['operation_key' => $operation])->assertRedirect('/ordens/preparar');
expect(DB::table('budget_entries')->where('requisition_id', $this->r->id)->orderBy('id')->limit(count($old))->get()->toArray())->toEqual($old)
->and((int) DB::table('budget_entries')->sum('reserved_minor') + (int) DB::table('budget_distribution_entries')->sum('reserved_minor'))->toBe(10000);
app(OrderPartsWorkflow::class)->issue($this->buyer, nativeOrderPartsInput($this, $award, '0.400', 0));
$this->post('/adjudicacoes/'.$award->id.'/parcelas/adoptar', ['operation_key' => $operation])->assertRedirect('/ordens/preparar');
expect(DB::table('budget_order_commands')->where('kind', 'adopt')->count())->toBe(1)
->and((int) DB::table('budget_distribution_entries')->sum('committed_minor'))->toBe(4000);
});
+52
View File
@@ -0,0 +1,52 @@
<?php
/** PostgreSQL migration functions survive table refreshes across different Pest kernels.
* @param list<list<string>> $commands
*/
function landedQaCommandIsolationVerified(array $commands): bool
{
return count(array_filter($commands, fn ($command) => ($command[1] ?? '') === 'vendor/bin/pest')) <= 1;
}
/** Test-only protocol: a successful exit without verification receipts is not a passing proof.
* @param list<string> $command
*/
function landedQaReceiptsVerified(array $command, string $output): bool
{
$records = array_values(array_filter(array_map(fn ($line) => json_decode($line, true), explode("\n", $output)), 'is_array'));
$contains = static function (callable $test) use ($records): bool {
foreach ($records as $record) {
if ($test($record)) {
return true;
}
}
return false;
};
$mode = ($command[1] ?? '') === 'vendor/bin/pest' ? 'pest' : ($command[3] ?? '');
if ($mode === 'migrate') {
return $contains(fn ($row) => ($row['isolated_schema_prepared'] ?? false) === true);
}
if ($mode === 'race') {
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] as $scenario) {
$matches = array_values(array_filter($records, fn ($row) => ($row['scenario'] ?? null) === $scenario));
if (count($matches) !== 1 || ($matches[0]['blocked_writers_observed'] ?? 0) < 2
|| ($matches[0]['commands'] ?? 0) !== 1 || ($matches[0]['audits'] ?? 0) !== 1
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
return false;
}
}
return $contains(fn ($row) => ($row['old_runtime_rejected_before_balance'] ?? false) === true && ($row['status'] ?? 0) === 503);
}
if ($mode === 'landed-costs') {
return $contains(fn ($row) => ($row['post_extension_restore_all_tables_equal'] ?? false) === true
&& ($row['recovered_operation_replay_no_effects'] ?? false) === true && ($row['pre_extension_schema_data_balance_restored'] ?? false) === true)
&& $contains(fn ($row) => ($row['private_original_versions_restored'] ?? 0) === 2 && ($row['source_loss_detected'] ?? false) === true
&& ($row['separate_private_root_restored'] ?? false) === true && ($row['native_authorized_evidence_resolved'] ?? false) === true)
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
}
return $mode === 'pest' && $contains(fn ($row) => ($row['tool'] ?? null) === 'pest' && ($row['result'] ?? null) === 'passed'
&& ($row['tests'] ?? 0) > 0 && ($row['passed'] ?? 0) === $row['tests']);
}
+45
View File
@@ -0,0 +1,45 @@
<?php
require_once __DIR__.'/../Support/LandedQaReceipts.php';
test('separate Pest kernels cannot reuse one disposable database with persistent migration functions', function () {
$pest = ['php', 'vendor/bin/pest', 'tests/Feature/ImportTariffCodesTest.php'];
expect(landedQaCommandIsolationVerified([$pest]))->toBeTrue();
expect(landedQaCommandIsolationVerified([['php', 'worker.php', 'db', 'migrate'], $pest]))->toBeTrue();
expect(landedQaCommandIsolationVerified([$pest, $pest]))->toBeFalse();
});
test('the worker mode follows the database argument and a Laravel console exception is never a passing proof', function () {
$command = ['php', 'tests/Concurrency/quotation-exchange-worker.php', 'compras_receipts_test_000000000001', 'migrate'];
expect(landedQaReceiptsVerified($command, "{\"isolated_schema_prepared\":true}\n"))->toBeTrue();
expect(landedQaReceiptsVerified($command, 'In Connection.php line 864: synthetic missing table'))->toBeFalse();
expect(landedQaReceiptsVerified(['php', 'worker.php', 'compras_receipts_test_000000000001', 'landed-costs'], "{\"isolated_schema_prepared\":true}\n"))->toBeFalse();
});
test('a contention proof requires all three distinct blocked-writer scenarios and the incompatible-runtime refusal', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race'];
$records = [];
foreach (['same_operation', 'conflicting_plan_version', 'same_source_different_plan'] as $scenario) {
$records[] = ['scenario' => $scenario, 'statuses' => $scenario === 'same_operation' ? [200, 200] : [200, 409],
'blocked_writers_observed' => 2, 'commands' => 1, 'audits' => 1];
}
$encode = fn ($rows) => implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows));
expect(landedQaReceiptsVerified($command, $encode($records)))->toBeFalse();
$records[] = ['old_runtime_rejected_before_balance' => true, 'status' => 503];
expect(landedQaReceiptsVerified($command, $encode($records)))->toBeTrue();
$records[2] = $records[0];
expect(landedQaReceiptsVerified($command, $encode($records)))->toBeFalse();
});
test('restore completion requires the restored replay original snapshot and database cleanup', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'landed-costs'];
$proof = json_encode(['post_extension_restore_all_tables_equal' => true, 'recovered_operation_replay_no_effects' => true,
'pre_extension_schema_data_balance_restored' => true], JSON_THROW_ON_ERROR);
expect(landedQaReceiptsVerified($command, $proof))->toBeFalse();
$databaseOnly = $proof."\n".json_encode(['isolated_restore_removed' => true], JSON_THROW_ON_ERROR);
expect(landedQaReceiptsVerified($command, $databaseOnly))->toBeFalse();
$privateFiles = ['private_original_versions_restored' => 2, 'source_loss_detected' => true,
'separate_private_root_restored' => true, 'native_authorized_evidence_resolved' => true];
expect(landedQaReceiptsVerified($command, $databaseOnly."\n".json_encode($privateFiles, JSON_THROW_ON_ERROR)))->toBeTrue();
expect(landedQaReceiptsVerified(['php', 'vendor/bin/pest', '--compact'], '{"tool":"pest","result":"passed","tests":1,"passed":0,"skipped":1}'))->toBeFalse();
});
+54
View File
@@ -0,0 +1,54 @@
import { describe, expect, it } from 'vitest';
import {
orderPartDraftKey,
orderPartMinor,
} from '../../resources/js/lib/order-parts';
it('preserves remembered allocations across label changes but separates quantities and offsets', () => {
const first = {
requisition_id: 1,
award_id: 2,
label: 'old',
items: [
{
quotation_item_id: 3,
quantity_milli: 400,
quantity_offset_milli: 0,
},
],
};
const second = { ...first, requisition_id: 4, award_id: 5 };
expect(orderPartDraftKey([first, second])).toBe(
orderPartDraftKey([second, { ...first, label: 'new' }]),
);
expect(orderPartDraftKey([first])).not.toBe(
orderPartDraftKey([
{ ...first, items: [{ ...first.items[0], quantity_milli: 401 }] },
]),
);
expect(orderPartDraftKey([first])).not.toBe(
orderPartDraftKey([
{
...first,
items: [{ ...first.items[0], quantity_offset_milli: 400 }],
},
]),
);
});
describe('explicit order-part monetary input', () => {
it('preserves cents and large exact native integers without floating rounding', () => {
expect(orderPartMinor('12.34')).toBe(1234);
expect(orderPartMinor('0.01')).toBe(1);
expect(orderPartMinor('0.00')).toBe(0);
expect(orderPartMinor('999999999999.99')).toBe(99999999999999);
expect(orderPartMinor('1000000000000.00')).toBe(100000000000000);
expect(orderPartMinor('1000000000000.01')).toBeNull();
});
it.each(['', '-1', '1,25', '1.234', '1e2', ' 1.00', '10000000000000'])(
'refuses an invalid or rounded monetary representation %s',
(value) => {
expect(orderPartMinor(value)).toBeNull();
},
);
});
+13
View File
@@ -1,4 +1,17 @@
<?php <?php
namespace Tempo\Finance\Budget {
/** Optional QA contract; signature only, never executed or autoloaded. */
final class BudgetLandedCostPlan
{
public const VERSION = 'COMMON-BUDGET-LANDED-COST-QA-v1';
/** @param list<array<string,mixed>> $components
* @param array<string,array<string,mixed>> $documents
* @return array<string,mixed>
*/
public static function reconcile(array $components, array $documents, bool $includesTax): array { throw new \LogicException('Static analysis declaration only.'); }
}
}
// Static analysis declarations for already approved optional package APIs. // Static analysis declarations for already approved optional package APIs.
// No implementation; never loaded by Composer or the application. // No implementation; never loaded by Composer or the application.
// Source signatures are recorded below; no SGF checkout is needed to analyse Compras. // Source signatures are recorded below; no SGF checkout is needed to analyse Compras.