commit compras5 2711
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-27 20:19:21 +02:00
parent 7486007fcf
commit d58b75c87a
57 changed files with 2803 additions and 116 deletions
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Controllers;
use App\Models\ExternalPayment;
use App\Models\User;
use App\Services\ExpenseAllocations;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
final class ExpenseAllocationController extends Controller
{
public function show(Request $request, ExternalPayment $payment, ExpenseAllocations $service): Response
{
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
Inertia::encryptHistory();
$response = Inertia::render('payments/expense-allocation', $service->workspace($actor, $payment->id))->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
}
public function store(Request $request, ExternalPayment $payment, ExpenseAllocations $service): Response
{
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
$service->save($actor, $payment->id, $request->all());
return back()->with('success', 'Imputação da despesa por categoria preservada.');
}
}
@@ -9,10 +9,12 @@ use App\Models\PurchaseOrder;
use App\Models\Supplier;
use App\Models\SupplierBankDetail;
use App\Models\User;
use App\Services\ExpenseAllocations;
use App\Services\ExternalPaymentWorkflow;
use App\Services\OrganizationAccess;
use App\Services\RequisitionWorkflow;
use App\Services\SupplierBankWorkflow;
use App\Services\SupplierPayables;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
@@ -51,7 +53,8 @@ class ExternalPaymentController extends Controller
'bank_id' => $bank['id'] ?? 0, 'bank_revision' => $bank['revision'] ?? 0, 'bank_state' => $approved->isNotEmpty() ? 'approved' : ($banks->first()['state'] ?? 'missing'), 'banks' => $canManage ? $banks->all() : []];
});
Inertia::encryptHistory();
$response = Inertia::render('payments/index', ['focusPaymentId' => $focus, 'focusInvoiceId' => $focusInvoice, 'invoices' => $invoices, 'payments' => $payments, 'canManage' => $canManage])->toResponse($request);
$response = Inertia::render('payments/index', ['focusPaymentId' => $focus, 'focusInvoiceId' => $focusInvoice, 'invoices' => $invoices, 'payments' => $payments, 'canManage' => $canManage,
'expenseAllocationsReady' => app(ExpenseAllocations::class)->ready() && app(SupplierPayables::class)->can($actor, 'view')])->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
@@ -9,6 +9,8 @@ use App\Models\Quotation;
use App\Models\Requisition;
use App\Models\User;
use App\Services\OrganizationAccess;
use App\Services\ProcurementContractInsights;
use App\Services\ProcurementDeliveryInsights;
use App\Services\ProcurementOperationalInsights;
use App\Services\ProcurementPayableInsights;
use App\Services\ProcurementPaymentInsights;
@@ -16,6 +18,7 @@ use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Inertia\Inertia;
use Symfony\Component\HttpFoundation\Response;
@@ -61,6 +64,10 @@ class ProcurementReportController extends Controller
'to' => 'nullable|date_format:Y-m-d',
'department_id' => 'nullable|integer|min:1',
'attention' => 'nullable|in:unapproved_needed,approved_without_quotes,approved_without_order',
'supplier_page' => 'nullable|integer|min:1|max:1000000',
'category_page' => 'nullable|integer|min:1|max:1000000',
'delivery_page' => 'nullable|integer|min:1|max:1000000',
'delivery_state' => 'nullable|in:attention,all,pending_late,pending,partial_late,completed_late,completed_on_time,unknown',
]);
if (! empty($filters['from']) && ! empty($filters['to']) && $filters['from'] > $filters['to']) {
throw ValidationException::withMessages(['to' => 'A data final deve ser igual ou posterior à data inicial.']);
@@ -78,7 +85,16 @@ class ProcurementReportController extends Controller
/** @return Builder<PurchaseOrder> */
private function visibleOrders(User $actor): Builder
{
return PurchaseOrder::query()->visibleTo($actor)->whereColumn('purchase_orders.requisition_id', 'requisitions.id');
return PurchaseOrder::query()->visibleTo($actor)->where(function ($orders) {
$orders->whereColumn('purchase_orders.requisition_id', 'requisitions.id');
if (Schema::hasTable('purchase_order_sources') && Schema::hasColumn('purchase_orders', 'order_key')) {
$orders->orWhere(function ($parts) {
$parts->whereNotNull('purchase_orders.order_key')->whereExists(fn ($source) => $source->selectRaw('1')
->from('purchase_order_sources as report_origin')->whereColumn('report_origin.purchase_order_id', 'purchase_orders.id')
->whereColumn('report_origin.tenant_id', 'purchase_orders.tenant_id')->whereColumn('report_origin.requisition_id', 'requisitions.id'));
});
}
});
}
/** @param array<string,mixed> $filters
@@ -153,10 +169,13 @@ class ProcurementReportController extends Controller
$insights = app(ProcurementOperationalInsights::class)->build($this->records(clone $query, $actor), $instant);
return ['records' => $records, 'counts' => $counts, 'filters' => $filters, 'departments' => $departments, 'generatedAt' => $instant->toIso8601String(), 'insights' => $insights,
'contractInsights' => app(ProcurementContractInsights::class)->build($actor, clone $query),
'deliveryInsights' => app(ProcurementDeliveryInsights::class)->build($actor, clone $query, $instant,
(int) ($filters['delivery_page'] ?? 1), $filters['delivery_state'] ?? 'attention'),
'payableInsights' => app(ProcurementPayableInsights::class)->build($actor, clone $query),
'paymentInsights' => app(ProcurementPaymentInsights::class)->build($actor,
$this->query($actor, array_diff_key($filters, array_flip(['from', 'to'])), $instant->toDateString()),
$filters['from'] ?? null, $filters['to'] ?? null)];
$filters['from'] ?? null, $filters['to'] ?? null, (int) ($filters['supplier_page'] ?? 1), (int) ($filters['category_page'] ?? 1))];
});
Inertia::encryptHistory();
@@ -186,6 +205,7 @@ class ProcurementReportController extends Controller
fwrite($output, "\xEF\xBB\xBF");
fputcsv($output, ['Posição actual das obrigações', 'Gerado em', $data['generated_at']], ';', '"', '');
fputcsv($output, ['Filtros dos pedidos (data de criação)', json_encode($data['filters'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)], ';', '"', '');
fputcsv($output, ['Âmbito documental', 'Cada factura conta uma vez se alguma origem corresponder aos filtros; posição integral sem repartição por pedido.'], ';', '"', '');
fputcsv($output, ['Facturas autorizadas', 'Reconhecidas e determinadas', 'Por reconhecer', 'Posição indeterminada'], ';', '"', '');
$coverage = $data['positions']['coverage'];
fputcsv($output, [$coverage['invoices'], $coverage['recognised'], $coverage['unrecognised'], $coverage['indeterminate']], ';', '"', '');
@@ -205,7 +225,7 @@ class ProcurementReportController extends Controller
$actor = $this->actor($request);
$payments = app(ProcurementPaymentInsights::class)->build($actor,
$this->query($actor, array_diff_key($filters, array_flip(['from', 'to'])), $instant->toDateString()),
$filters['from'] ?? null, $filters['to'] ?? null);
$filters['from'] ?? null, $filters['to'] ?? null, null, null);
abort_unless($payments !== null, 403);
return ['payments' => $payments, 'generated_at' => $instant->toIso8601String()];
@@ -220,16 +240,92 @@ class ProcurementReportController extends Controller
$payments = $data['payments'];
fputcsv($output, ['Pagamentos externos confirmados pela data de confirmação', 'Gerado em', $data['generated_at']], ';', '"', '');
fputcsv($output, ['Confirmação desde', $payments['from'] ?? '', 'Até (inclusive)', $payments['to'] ?? ''], ';', '"', '');
fputcsv($output, ['Âmbito documental', 'Cada factura conta uma vez se alguma origem corresponder aos filtros; pagamentos integrais sem repartição por pedido.'], ';', '"', '');
fputcsv($output, ['Facturas no âmbito', 'Históricos indeterminados excluídos', 'Pagamentos confirmados determinados'], ';', '"', '');
fputcsv($output, array_values($payments['coverage']), ';', '"', '');
fputcsv($output, ['Moeda', 'Pagamentos', 'Despesa (centavos)'], ';', '"', '');
foreach ($payments['currencies'] as $row) {
fputcsv($output, [$row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
}
fputcsv($output, ['Fornecedor (identificador)', 'Nome conservado na factura', 'Moeda', 'Pagamentos', 'Despesa (centavos)'], ';', '"', '');
foreach ($payments['suppliers']['data'] as $row) {
$name = preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $row['supplier_name']) ? "'".$row['supplier_name'] : $row['supplier_name'];
fputcsv($output, [$row['supplier_id'], $name, $row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
}
fputcsv($output, ['Categoria (imputação explícita de Finanças)', 'Moeda', 'Imputações', 'Despesa (centavos)'], ';', '"', '');
foreach ($payments['category_attribution']['groups']['data'] as $row) {
$category = preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $row['category']) ? "'".$row['category'] : $row['category'];
fputcsv($output, [$category, $row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
}
fputcsv($output, ['Imputação pendente', 'Moeda', 'Pagamentos', 'Montante (centavos)'], ';', '"', '');
foreach ($payments['category_attribution']['unassigned'] as $row) {
fputcsv($output, [$row['state'] === 'unallocated' ? 'Não imputada' : 'Imputação indeterminada', $row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
}
fclose($output);
}, 'despesa-confirmada-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
}
public function exportContracts(Request $request): Response
{
$data = $this->snapshot(function () use ($request): array {
$instant = CarbonImmutable::now(config('app.timezone'));
$filters = $this->filters($request);
return ['generated_at' => $instant->toIso8601String(), 'filters' => $filters,
'contracts' => app(ProcurementContractInsights::class)->build($this->actor($request), $this->query($this->actor($request), $filters, $instant->toDateString()))];
});
return response()->streamDownload(function () use ($data) {
$output = fopen('php://output', 'w');
if ($output === false) {
throw new \RuntimeException('Não foi possível exportar as associações contratuais.');
}
fwrite($output, "\xEF\xBB\xBF");
fputcsv($output, ['Associação contratual conservada na emissão', 'Gerado em', $data['generated_at']], ';', '"', '');
fputcsv($output, ['Base', 'Ordens operacionais visíveis; montantes integrais das ordens, não pagamentos; não certifica conformidade.'], ';', '"', '');
fputcsv($output, ['Filtros dos pedidos (data de criação)', json_encode($data['filters'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)], ';', '"', '');
fputcsv($output, ['Classificação', 'Moeda', 'Ordens', 'Montante (centavos)'], ';', '"', '');
foreach ($data['contracts']['currencies'] as $row) {
fputcsv($output, [ProcurementContractInsights::LABELS[$row['classification']], $row['currency'] ?? 'Indeterminada', $row['count'], $row['amount_minor'] ?? 'Indeterminado'], ';', '"', '');
}
fclose($output);
}, 'associacoes-contratuais-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
}
public function exportDeliveries(Request $request): Response
{
$data = $this->snapshot(function () use ($request): array {
$instant = CarbonImmutable::now(config('app.timezone'));
$filters = $this->filters($request);
return ['filters' => $filters, 'deliveries' => app(ProcurementDeliveryInsights::class)->build($this->actor($request),
$this->query($this->actor($request), $filters, $instant->toDateString()), $instant, null, $filters['delivery_state'] ?? 'attention')];
});
return response()->streamDownload(function () use ($data) {
$output = fopen('php://output', 'w');
if ($output === false) {
throw new \RuntimeException('Não foi possível exportar o acompanhamento de entregas.');
}
fwrite($output, "\xEF\xBB\xBF");
$write = static function (array $cells) use ($output): void {
fputcsv($output, array_map(fn ($cell) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', (string) $cell) ? "'".$cell : $cell, $cells), ';', '"', '');
};
$write(['Entregas documentadas face às datas acordadas na ordem', 'Gerado em', $data['deliveries']['generated_at']]);
$write(['Filtros dos pedidos (data de criação)', json_encode($data['filters'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)]);
$write(['Base', 'Recepções nativas não estornadas, por origem; datas desconhecidas ficam por determinar; não certifica qualidade ou culpa do fornecedor.']);
$write(['Ordem', 'Situação', 'Linhas por receber', 'Linhas indeterminadas', 'Maior atraso documentado (dias)']);
foreach ($data['deliveries']['records']['data'] as $row) {
$write([$row['number'], ProcurementDeliveryInsights::LABELS[$row['state']], $row['pending_lines'], $row['unknown_lines'], $row['late_days'] ?? 'Indeterminado']);
foreach ($row['late_lines'] as $line) {
$write(['Linha', $line['description'], 'Data acordada', $line['promised_on'], 'Recepção integral documentada', $line['completed_on'] ?? 'Por completar',
'Quantidade por receber', $line['pending_quantity'], $line['unit']]);
}
}
fclose($output);
}, 'entregas-compras-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
}
public function export(Request $request): Response
{
$this->filters($request);
+18
View File
@@ -69,6 +69,24 @@ class PurchaseOrder extends Model
}
}
/** @param Builder<PurchaseOrder> $query
* @param Builder<Requisition> $requests
*/
public function scopeForRequisitions(Builder $query, Builder $requests): void
{
$query->where(function ($orders) use ($requests) {
$orders->whereIn('purchase_orders.requisition_id', (clone $requests)->reorder()->select('requisitions.id'));
if (Schema::hasTable('purchase_order_sources') && Schema::hasColumn('purchase_orders', 'order_key')) {
$orders->orWhere(function ($parts) use ($requests) {
$parts->whereNotNull('purchase_orders.order_key')->whereExists(fn ($source) => $source->selectRaw('1')
->from('purchase_order_sources as report_origin')->whereColumn('report_origin.purchase_order_id', 'purchase_orders.id')
->whereColumn('report_origin.tenant_id', 'purchase_orders.tenant_id')
->whereIn('report_origin.requisition_id', (clone $requests)->reorder()->select('requisitions.id')));
});
}
});
}
/** @param Builder<PurchaseOrder> $query */
public function scopeOperational(Builder $query): void
{
+1 -1
View File
@@ -115,7 +115,7 @@ final class AgreementOrderLimits
public function freeze(User $actor, Quotation $quote, Requisition $request, array $lines, array $bindings, array $additionalRequests = []): array
{
if ($bindings === []) {
return [];
return ['agreement_order_input_hash' => hash('sha256', json_encode([], JSON_THROW_ON_ERROR)), 'agreement_bindings' => []];
}
abort_unless($this->ready() && Schema::hasTable('supply_records'), 503, 'Limites por ordem preparados apenas em QA isolada.');
abort_unless($this->canRead($actor), 403);
+180
View File
@@ -0,0 +1,180 @@
<?php
namespace App\Services;
use App\Models\ExternalPayment;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\SupplyRecord;
use App\Models\User;
use Brick\Math\BigDecimal;
use Brick\Math\BigInteger;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
/** Explicit analytical attribution; never changes a payment, liability or financial journal. */
final class ExpenseAllocations
{
public function ready(): bool
{
$db = DB::connection();
return config('expense-allocations.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 source(User $actor, int $id): array
{
$payment = ExternalPayment::query()->whereKey($id)->firstOrFail();
$invoice = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->whereKey($payment->invoice_id)->firstOrFail();
try {
$facts = collect(app(SupplierPayables::class)->readPaymentHistory($actor, $invoice->id))->firstWhere('id', $id);
} catch (\DomainException) {
abort(409, 'O histórico auditado do pagamento está indeterminado.');
}
abort_unless($facts !== null && $facts['status'] === 'confirmed', 409, 'A imputação exige um pagamento confirmado e o seu histórico auditado.');
abort_unless(is_int($facts['amount_minor']) && $facts['amount_minor'] > 0 && is_string($facts['currency'])
&& preg_match('/^[A-Z]{3}$/D', $facts['currency']) && is_string($facts['reviewed_at']) && trim($facts['reviewed_at']) !== ''
&& is_int($facts['reviewed_by']) && $facts['reviewed_by'] > 0, 409, 'A confirmação tem dados indeterminados; conserve os originais para conferência.');
$categories = [];
foreach ($invoice->items()->orderBy('id')->get() as $item) {
$line = DB::table('purchase_order_items')->where('tenant_id', $actor->tenant_id)->where('purchase_order_id', $invoice->purchase_order_id)
->where('id', $item->purchase_order_item_id)->first(['category']);
abort_unless($line !== null && is_string($line->category) && trim($line->category) !== '', 409,
'Há linhas da factura sem categoria documental determinada.');
$categories[$line->category] = $line->category;
}
$categories = array_values($categories);
sort($categories, SORT_STRING);
abort_unless($categories !== [], 409, 'A factura exige linhas com categorias documentais para esta imputação.');
$source = ['payment' => $facts, 'invoice_id' => $invoice->id, 'invoice_number' => $invoice->getAttribute('number'),
'purchase_order_id' => $invoice->purchase_order_id, 'categories' => $categories];
return [...$source, 'fingerprint' => hash('sha256', json_encode($source, JSON_THROW_ON_ERROR))];
}
private function actor(User $actor): User
{
abort_unless($this->ready(), 503);
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
abort_unless($actor->hasFunctions(['admin', 'finance']) && app(SupplierPayables::class)->can($actor, 'view'), 403);
return $actor;
}
public function current(int $payment): ?SupplyRecord
{
return SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)->latest('version')->first();
}
/** @return array<string,mixed> */
public function projection(User $actor, int $payment): array
{
$record = $this->current($payment);
if ($record === null) {
return ['state' => 'unallocated', 'allocations' => []];
}
if (! $this->ready()) {
return ['state' => 'indeterminate', 'allocations' => []];
}
try {
$source = $this->source($actor, $payment);
} catch (HttpExceptionInterface $error) {
if (! in_array($error->getStatusCode(), [404, 409], true)) {
throw $error;
}
return ['state' => 'indeterminate', 'allocations' => []];
}
if (($record->snapshot['fingerprint'] ?? '') !== $source['fingerprint']) {
return ['state' => 'indeterminate', 'allocations' => []];
}
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('user_id', $record->created_by)
->where('action', 'expense.allocation_recorded')->where('after->record->id', $record->id)->latest('id')->value('after');
$saved = is_string($audit) ? (json_decode($audit, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null) : null;
if (! is_array($saved) || ($saved['data'] ?? null) !== $record->data || ($saved['snapshot'] ?? null) !== $record->snapshot
|| ($saved['version'] ?? null) !== $record->version || ($saved['input_hash'] ?? null) !== $record->input_hash) {
return ['state' => 'indeterminate', 'allocations' => []];
}
return ['state' => 'allocated', 'allocations' => $record->data['allocations']];
}
/** @return array<string,mixed> */
public function workspace(User $actor, int $payment): array
{
return DB::transaction(function () use ($actor, $payment) {
$actor = $this->actor($actor);
$source = $this->source($actor, $payment);
$current = $this->current($payment);
$row = fn (SupplyRecord $record) => ['id' => $record->id, 'version' => $record->version, 'reason' => $record->reason,
'data' => ['allocations' => $record->data['allocations']]];
return ['payment' => ['id' => $payment, 'invoice_id' => $source['invoice_id'], 'invoice_number' => $source['invoice_number'],
'amount_minor' => (string) $source['payment']['amount_minor'], 'currency' => $source['payment']['currency']],
'categories' => $source['categories'], 'fingerprint' => $source['fingerprint'], 'current' => $current === null ? null : $row($current),
'history' => SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)->latest('version')->paginate(15)->withQueryString()->through($row),
'canWrite' => $actor->hasFunctions(['finance']), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
});
}
/** @param array<string,mixed> $input */
public function save(User $actor, int $payment, array $input): SupplyRecord
{
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
'fingerprint' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'reason' => 'required|string|min:10|max:4000',
'allocations' => 'required|array|list|min:1|max:100', 'allocations.*' => 'array:category,amount',
'allocations.*.category' => 'required|string|max:255|distinct:strict', 'allocations.*.amount' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D']])->validate();
$data['operation_key'] = strtolower($data['operation_key']);
$data['version'] = (int) $data['version'];
usort($data['allocations'], fn ($a, $b) => strcmp($a['category'], $b['category']));
$hash = hash('sha256', json_encode([$payment, $data], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $payment, $data, $hash) {
$actor = $this->actor($actor);
abort_unless($actor->hasFunctions(['finance']), 403);
ExternalPayment::query()->whereKey($payment)->lockForUpdate()->firstOrFail();
$source = $this->source($actor, $payment);
$order = PurchaseOrder::query()->whereKey($source['purchase_order_id'])->firstOrFail();
app(OrderPartsAccess::class)->assertProcess($actor, $order, true);
abort_unless(hash_equals($source['fingerprint'], $data['fingerprint']), 409, 'As origens mudaram. Reveja a factura e o pagamento.');
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
if ($retry !== null) {
abort_unless($retry->kind === 'expense_allocation' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
return $retry;
}
$old = $this->current($payment);
abort_unless(($old->version ?? 0) === $data['version'], 409, 'A imputação mudou. Reveja a versão actual.');
$total = BigInteger::zero();
$allocations = [];
foreach ($data['allocations'] as $row) {
if (! in_array($row['category'], $source['categories'], true)) {
throw ValidationException::withMessages(['allocations' => 'Seleccione apenas categorias das linhas desta factura.']);
}
$minor = BigDecimal::of($row['amount'])->multipliedBy(100)->toBigInteger();
$total = $total->plus($minor);
$allocations[] = ['category' => $row['category'], 'amount_minor' => (string) $minor];
}
if (! $total->isEqualTo($source['payment']['amount_minor'])) {
throw ValidationException::withMessages(['allocations' => 'A soma das imputações deve corresponder exactamente ao pagamento confirmado.']);
}
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'expense_allocation',
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => 'allocated', 'created_by' => $actor->id,
'data' => ['payment_id' => $payment, 'invoice_id' => $source['invoice_id'], 'currency' => $source['payment']['currency'],
'amount_minor' => (string) $total, 'allocations' => $allocations], 'snapshot' => $source,
'reason' => trim($data['reason']), 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'expense.allocation_recorded', null, $old?->toArray(), ['record' => $record->toArray()]);
return $record;
});
}
}
@@ -0,0 +1,75 @@
<?php
namespace App\Services;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\User;
use Brick\Math\BigInteger;
use Illuminate\Database\Eloquent\Builder;
/** Documentary association at issuance, never a retrospective legal compliance decision. */
final class ProcurementContractInsights
{
public const LABELS = ['contract' => 'Todas as linhas com contrato associado', 'partial' => 'Parte das linhas com contrato associado',
'without_contract' => 'Sem contrato associado na emissão', 'unknown' => 'Associação por determinar'];
/** @param Builder<Requisition> $requests
* @return array<string,mixed>
*/
public function build(User $actor, Builder $requests): array
{
$coverage = array_fill_keys(['contract', 'partial', 'without_contract', 'unknown'], 0);
$currencies = [];
$orders = PurchaseOrder::query()->visibleTo($actor)->operational()->forRequisitions($requests)
->with('items:id,purchase_order_id,requisition_item_id');
foreach ($orders->lazyById(200) as $order) {
$state = $this->classification($order);
$coverage[$state]++;
$currency = $order->getAttribute('currency');
$minor = $order->getAttribute('total_minor');
if (! is_string($currency) || ! preg_match('/^[A-Z]{3}$/D', $currency) || ! preg_match('/^\d+$/D', (string) $minor)) {
// Missing amounts are not converted to a zero-valued order.
$currencies['unknown:'.$state] ??= ['currency' => null, 'classification' => $state, 'count' => 0, 'amount_minor' => null];
$currencies['unknown:'.$state]['count']++;
continue;
}
$key = $currency.':'.$state;
$currencies[$key] ??= ['currency' => $currency, 'classification' => $state, 'count' => 0, 'amount_minor' => '0'];
$currencies[$key]['count']++;
$currencies[$key]['amount_minor'] = (string) BigInteger::of($currencies[$key]['amount_minor'])->plus($minor);
}
ksort($currencies);
return ['method' => 'frozen_order_contract_association_v1', 'coverage' => $coverage, 'currencies' => array_values($currencies)];
}
private function classification(PurchaseOrder $order): string
{
$snapshot = $order->snapshot;
if (! is_string($snapshot['agreement_order_input_hash'] ?? null) || ! preg_match('/^[a-f0-9]{64}$/D', $snapshot['agreement_order_input_hash'])
|| ! is_array($snapshot['agreement_bindings'] ?? null) || $order->items->isEmpty()) {
return 'unknown';
}
$contracts = 0;
foreach ($order->items as $line) {
$binding = $snapshot['agreement_bindings'][$line->getAttribute('requisition_item_id')] ?? null;
if ($binding !== null && ! is_array($binding)) {
return 'unknown';
}
if ($binding === null || ! isset($binding['contract_id'])) {
continue;
}
if (($binding['schema'] ?? null) !== 'sgc.agreement.order_limit.v1'
|| ! is_int($binding['contract_id']) || $binding['contract_id'] < 1
|| ($binding['contract']['id'] ?? null) !== $binding['contract_id']
|| ! is_int($binding['contract']['version'] ?? null) || $binding['contract']['version'] < 1) {
return 'unknown';
}
$contracts++;
}
return $contracts === 0 ? 'without_contract' : ($contracts === $order->items->count() ? 'contract' : 'partial');
}
}
@@ -0,0 +1,123 @@
<?php
namespace App\Services;
use App\Models\GoodsReceiptItem;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\User;
use Brick\Math\BigDecimal;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
/** Native documentary receipt dates against each origin's frozen promised date. */
final class ProcurementDeliveryInsights
{
public const LABELS = ['pending_late' => 'Por receber depois da data acordada', 'pending' => 'Por receber, dentro da data acordada',
'partial_late' => 'Recepção parcial tardia; restante em prazo', 'completed_late' => 'Recepção integral depois da data acordada',
'completed_on_time' => 'Recepção integral no prazo acordado', 'unknown' => 'Datas ou quantidades por determinar'];
private function date(mixed $value): ?string
{
if (! is_string($value) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/D', $value)) {
return null;
}
try {
$date = CarbonImmutable::createFromFormat('!Y-m-d', $value, config('app.timezone'));
} catch (\InvalidArgumentException) {
return null;
}
return $date !== null && $date->format('Y-m-d') === $value ? $value : null;
}
private function promised(PurchaseOrder $order, int $item): ?string
{
if (! OrderPartsAccess::applies($order)) {
return $this->date($order->snapshot['award']['delivery_date'] ?? null);
}
$dates = [];
foreach ($order->snapshot['order_parts']['sources'] ?? [] as $source) {
foreach ($source['items'] ?? [] as $line) {
if (($line['requisition_item_id'] ?? null) === $item) {
$dates[] = $this->date($source['award_terms']['delivery_date'] ?? null);
}
}
}
return count($dates) === 1 ? $dates[0] : null;
}
/** @param Builder<Requisition> $requests
* @return array<string,mixed>
*/
public function build(User $actor, Builder $requests, CarbonImmutable $instant, ?int $page = 1, string $view = 'attention'): array
{
$today = $instant->setTimezone(config('app.timezone'))->toDateString();
$coverage = array_fill_keys(array_keys(self::LABELS), 0);
$records = [];
$pendingLines = $unknownLines = 0;
$reversed = array_keys(app(InventoryReversals::class)->corrections('receipt'));
foreach (PurchaseOrder::query()->visibleTo($actor)->operational()->forRequisitions($requests)->with('items')->lazyById(100) as $order) {
app(OrderPartsAccess::class)->origins($order);
$progress = app(ReceiptWorkflow::class)->progress($order);
$items = $order->items->keyBy('id');
$receipts = GoodsReceiptItem::query()->join('goods_receipts as gr', 'gr.id', '=', 'goods_receipt_items.goods_receipt_id')
->where('gr.tenant_id', $actor->tenant_id)->where('gr.purchase_order_id', $order->id)->whereNotIn('goods_receipt_items.id', $reversed)
->orderBy('gr.received_on')->orderBy('gr.id')->orderBy('goods_receipt_items.id')
->get(['goods_receipt_items.id', 'goods_receipt_items.purchase_order_item_id', 'goods_receipt_items.received_milli', 'gr.received_on'])->groupBy('purchase_order_item_id');
$pending = $unknown = $latePending = $lateCompleted = $maxDays = 0;
$details = [];
foreach ($progress['lines'] as $line) {
$item = $items->get($line['id']);
$due = $item === null ? null : $this->promised($order, (int) $item->requisition_item_id);
$quantity = 0;
$completed = null;
$verified = $line['ordered_milli'] > 0 && $line['received_milli'] >= 0 && $line['received_milli'] <= $line['ordered_milli'];
foreach ($receipts->get($line['id'], collect()) as $receipt) {
$received = $this->date($receipt->getAttribute('received_on'));
if ($received === null || $received > $today || (int) $receipt->received_milli < 1) {
$verified = false;
}
$quantity += (int) $receipt->received_milli;
if ($quantity >= $line['ordered_milli'] && $completed === null) {
$completed = $received;
}
}
$verified = $verified && $quantity === $line['received_milli'];
$waiting = $line['received_milli'] < $line['ordered_milli'];
$pending += $waiting ? 1 : 0;
if (! $verified || $due === null || (! $waiting && $completed === null)) {
$unknown++;
continue;
}
$end = $waiting ? $today : $completed;
if ($end > $due) {
$waiting ? $latePending++ : $lateCompleted++;
$days = (int) CarbonImmutable::parse($due, config('app.timezone'))->diffInDays(CarbonImmutable::parse($end, config('app.timezone')));
$maxDays = max($maxDays, $days);
$details[] = ['id' => $line['id'], 'description' => $line['description'], 'unit' => $line['unit'], 'promised_on' => $due,
'completed_on' => $completed, 'pending_quantity' => (string) BigDecimal::of($line['delivery_pending_milli'])->dividedBy(1000, 3)];
}
}
$state = $latePending > 0 ? 'pending_late' : ($unknown > 0 || $items->isEmpty() ? 'unknown'
: ($pending > 0 ? ($lateCompleted > 0 ? 'partial_late' : 'pending') : ($lateCompleted > 0 ? 'completed_late' : 'completed_on_time')));
$coverage[$state]++;
$pendingLines += $pending;
$unknownLines += $unknown;
$records[] = ['id' => $order->id, 'number' => $order->number, 'state' => $state, 'pending_lines' => $pending, 'unknown_lines' => $unknown,
'late_days' => $state === 'unknown' && $maxDays === 0 ? null : $maxDays,
'quality_pending' => $progress['state'] === 'quality_pending', 'late_lines' => $details, 'href' => '/ordens/'.$order->id];
}
$filtered = array_values(array_filter($records, fn ($row) => $view === 'all' || ($view === 'attention'
? in_array($row['state'], ['pending_late', 'partial_late', 'completed_late', 'unknown'], true) : $row['state'] === $view)));
usort($filtered, fn ($a, $b) => (($b['late_days'] ?? -1) <=> ($a['late_days'] ?? -1)) ?: ($a['id'] <=> $b['id']));
$last = max(1, (int) ceil(count($filtered) / 20));
$current = $page === null ? 1 : max(1, min($page, $last));
return ['method' => 'frozen_promised_dates_native_receipts_v1', 'generated_at' => $instant->toIso8601String(), 'view' => $view,
'coverage' => $coverage, 'pending_lines' => $pendingLines, 'unknown_lines' => $unknownLines,
'records' => ['data' => $page === null ? $filtered : array_slice($filtered, ($current - 1) * 20, 20),
'total' => count($filtered), 'current_page' => $current, 'last_page' => $last]];
}
}
+4 -2
View File
@@ -32,8 +32,10 @@ class ProcurementEvidenceBrief
$opening = $report['opening'];
$add('opening', $opening === null ? 'Não consta acta de abertura neste módulo opcional.' : 'Acta de abertura na revisão '.$opening['revision'].'. '.($opening['source_changed'] ? 'Há diferenças face à base actual; a acta conserva a base original.' : 'A base coincide com os dados actuais.'),
'records', 'Registos do processo', 'opening', $opening);
$add('order', $report['order'] === null ? 'Não consta ordem emitida nesta consulta.' : 'Consta uma ordem emitida; a existência da ordem não comprova entrega nem pagamento.',
'records', 'Registos do processo', 'order', $report['order']);
$orders = $report['orders'] ?? ($report['order'] === null ? [] : [$report['order']]);
$add('order', count($orders) > 1 ? count($orders).' ordens emitidas constam da consulta; a existência das ordens não comprova entrega nem pagamento.'
: ($report['order'] === null ? 'Não consta ordem emitida nesta consulta.' : 'Consta uma ordem emitida; a existência da ordem não comprova entrega nem pagamento.'),
'records', 'Registos do processo', count($orders) > 1 ? 'orders' : 'order', count($orders) > 1 ? $orders : $report['order']);
$fulfilment = $report['fulfilment'];
$add('receipts', count($fulfilment['receipts']).' registos de recepção constam da consulta; esta contagem não comprova execução integral.',
'fulfilment', 'Recepção, facturas e registos de pagamento', 'fulfilment.receipts', $fulfilment['receipts']);
+1 -1
View File
@@ -23,7 +23,7 @@ class ProcurementPayableInsights
return null;
}
$engine = $adapter->readEngine($actor);
$orders = PurchaseOrder::query()->visibleTo($actor)->whereIn('requisition_id', (clone $requests)->reorder()->select('id'));
$orders = PurchaseOrder::query()->visibleTo($actor)->forRequisitions($requests);
$invoices = Invoice::query()->whereIn('purchase_order_id', $orders->select('id'));
$counts = ['invoices' => 0, 'recognised' => 0, 'unrecognised' => 0, 'indeterminate' => 0];
$currencies = [];
+48 -4
View File
@@ -17,7 +17,7 @@ class ProcurementPaymentInsights
/** @param Builder<Requisition> $requests
* @return array<string,mixed>|null
*/
public function build(User $actor, Builder $requests, ?string $from, ?string $to): ?array
public function build(User $actor, Builder $requests, ?string $from, ?string $to, ?int $supplierPage = 1, ?int $categoryPage = 1): ?array
{
$adapter = app(SupplierPayables::class);
if (! $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) || ! $adapter->can($actor, 'view')) {
@@ -26,11 +26,15 @@ class ProcurementPaymentInsights
$adapter->readContext($actor);
$start = $from === null ? null : CarbonImmutable::parse($from, config('app.timezone'))->startOfDay();
$end = $to === null ? null : CarbonImmutable::parse($to, config('app.timezone'))->addDay()->startOfDay();
$orders = PurchaseOrder::query()->visibleTo($actor)->whereIn('requisition_id', (clone $requests)->reorder()->select('id'));
$orders = PurchaseOrder::query()->visibleTo($actor)->forRequisitions($requests);
$invoices = Invoice::query()->where('tenant_id', $actor->tenant_id)->whereIn('purchase_order_id', $orders->select('id'));
$coverage = ['invoices' => 0, 'indeterminate' => 0, 'confirmed_payments' => 0];
$currencies = [];
foreach ($invoices->select('id')->lazyById(200) as $invoice) {
$suppliers = [];
$categoryCoverage = ['allocated' => 0, 'unallocated' => 0, 'indeterminate' => 0];
$categories = [];
$unassigned = [];
foreach ($invoices->select(['id', 'supplier_id', 'snapshot'])->lazyById(200) as $invoice) {
$coverage['invoices']++;
$rows = [];
try {
@@ -63,12 +67,52 @@ class ProcurementPaymentInsights
$currencies[$currency] ??= ['currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
$currencies[$currency]['count']++;
$currencies[$currency]['amount_minor'] = (string) BigInteger::of($currencies[$currency]['amount_minor'])->plus($payment['amount_minor']);
$key = $invoice->getAttribute('supplier_id').':'.$currency;
$name = $invoice->snapshot['supplier']['name'] ?? null;
$suppliers[$key] ??= ['supplier_id' => (int) $invoice->getAttribute('supplier_id'),
'supplier_name' => is_string($name) && trim($name) !== '' ? $name : 'Fornecedor #'.$invoice->getAttribute('supplier_id'),
'currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
$suppliers[$key]['count']++;
$suppliers[$key]['amount_minor'] = (string) BigInteger::of($suppliers[$key]['amount_minor'])->plus($payment['amount_minor']);
$attribution = app(ExpenseAllocations::class)->projection($actor, $payment['id']);
$categoryCoverage[$attribution['state']]++;
if ($attribution['state'] === 'allocated') {
foreach ($attribution['allocations'] as $allocation) {
if ($allocation['amount_minor'] === '0') {
continue;
}
$categoryKey = json_encode([$allocation['category'], $currency], JSON_THROW_ON_ERROR);
$categories[$categoryKey] ??= ['category' => $allocation['category'], 'currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
$categories[$categoryKey]['count']++;
$categories[$categoryKey]['amount_minor'] = (string) BigInteger::of($categories[$categoryKey]['amount_minor'])->plus($allocation['amount_minor']);
}
} else {
$unassignedKey = $currency.':'.$attribution['state'];
$unassigned[$unassignedKey] ??= ['state' => $attribution['state'], 'currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
$unassigned[$unassignedKey]['count']++;
$unassigned[$unassignedKey]['amount_minor'] = (string) BigInteger::of($unassigned[$unassignedKey]['amount_minor'])->plus($payment['amount_minor']);
}
$coverage['confirmed_payments']++;
}
}
ksort($currencies);
$suppliers = array_values($suppliers);
usort($suppliers, fn ($a, $b) => ($a['supplier_id'] <=> $b['supplier_id']) ?: strcmp($a['currency'], $b['currency']));
$supplierGroups = count($suppliers);
$lastPage = max(1, (int) ceil($supplierGroups / 20));
$page = $supplierPage === null ? 1 : max(1, min($lastPage, $supplierPage));
$categories = array_values($categories);
usort($categories, fn ($a, $b) => strcmp($a['category'], $b['category']) ?: strcmp($a['currency'], $b['currency']));
$lastCategoryPage = max(1, (int) ceil(count($categories) / 20));
$currentCategoryPage = $categoryPage === null ? 1 : max(1, min($lastCategoryPage, $categoryPage));
ksort($unassigned);
return ['method' => 'audited_original_confirmed_payments_v1', 'from' => $from, 'to' => $to,
'coverage' => $coverage, 'currencies' => array_values($currencies)];
'coverage' => $coverage, 'currencies' => array_values($currencies),
'suppliers' => ['data' => $supplierPage === null ? $suppliers : array_slice($suppliers, ($page - 1) * 20, 20),
'total' => $supplierGroups, 'current_page' => $page, 'last_page' => $lastPage],
'category_attribution' => ['coverage' => $categoryCoverage, 'unassigned' => array_values($unassigned),
'groups' => ['data' => $categoryPage === null ? $categories : array_slice($categories, ($currentCategoryPage - 1) * 20, 20),
'total' => count($categories), 'current_page' => $currentCategoryPage, 'last_page' => $lastCategoryPage]]];
}
}
+18 -3
View File
@@ -102,7 +102,20 @@ class ProcurementReviewCsv
}
}
$fulfilment = $report['fulfilment'];
$limits = $report['agreement_limits'] ?? [];
$documentOrders = $report['orders'] ?? ($report['order'] === null ? [] : [$report['order']]);
$write(['Ordens', '', 'Registos disponíveis', count($documentOrders)]);
foreach ($documentOrders as $documentOrder) {
if ($documentOrder['id'] !== ($report['order']['id'] ?? null)) {
$fields('Ordem', (string) $documentOrder['id'], $documentOrder,
['number' => 'Referência', 'currency' => 'Moeda', 'total_minor' => 'Total (centavos)']);
}
if (isset($documentOrder['origins'])) {
$fields('Ordem', (string) $documentOrder['id'], ['origins' => implode(', ', array_column($documentOrder['origins'], 'number'))], ['origins' => 'Requisições de origem']);
}
}
$orderContexts = $report['orders'] ?? [['number' => $report['order']['number'] ?? '', 'agreement_limits' => $report['agreement_limits'] ?? []]];
foreach ($orderContexts as $documentOrder) {
$limits = $documentOrder['agreement_limits'] ?? [];
if (! is_array($limits)) {
throw new \UnexpectedValueException('A projecção de acordos deve ser uma lista ou mapa de bases preservadas.');
}
@@ -116,6 +129,7 @@ class ProcurementReviewCsv
continue;
}
$seen[$binding['agreement_id']] = true;
$write(['Acordo por ordem', (string) $binding['agreement_id'], 'Ordem de origem', $documentOrder['number'] ?? '']);
if (isset($binding['contract']) && is_array($binding['contract'])) {
$contract = $binding['contract'];
if (! isset($contract['id']) || ! is_int($contract['id']) || $contract['id'] < 1) {
@@ -138,9 +152,10 @@ class ProcurementReviewCsv
'checked_order_value_minor' => 'Total conferido nesta ordem (centavos)', 'checked_order_quantity_milli' => 'Quantidade conferida nesta ordem (milésimos)',
]);
}
}
$write(['Recepções', '', 'Registos disponíveis', count($fulfilment['receipts'])]);
foreach ($fulfilment['receipts'] as $receipt) {
$fields('Recepção', (string) $receipt['id'], $receipt, ['received_on' => 'Recebida em', 'delivery_note' => 'Guia']);
$fields('Recepção', (string) $receipt['id'], $receipt, ['received_on' => 'Recebida em', 'delivery_note' => 'Guia', 'order_number' => 'Ordem de origem']);
}
$write(['Execução financeira', '', 'Consulta autorizada', $fulfilment['finance_visible']]);
if ($fulfilment['finance_visible']) {
@@ -148,7 +163,7 @@ class ProcurementReviewCsv
$write([$section, '', 'Registos disponíveis', count($fulfilment[$key])]);
foreach ($fulfilment[$key] as $record) {
$fields($section, (string) $record['id'], $record, $key === 'invoices'
? ['number' => 'Referência', 'status' => 'Estado', 'issued_on' => 'Emitida em', 'total_minor' => 'Total (centavos)', 'currency' => 'Moeda']
? ['number' => 'Referência', 'status' => 'Estado', 'issued_on' => 'Emitida em', 'total_minor' => 'Total (centavos)', 'currency' => 'Moeda', 'order_number' => 'Ordem de origem']
: ['invoice_id' => 'Factura de origem', 'status' => 'Estado', 'paid_on' => 'Data informada', 'amount_minor' => 'Montante (centavos)', 'currency' => 'Moeda']);
}
}
+16 -7
View File
@@ -31,7 +31,8 @@ class ProcurementReviewReport
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
}
$actor = User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
abort_unless($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
abort_unless(! app(OrganizationAccess::class)->maintenanceOnly($actor)
&& $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
$request = Requisition::query()->visibleTo($actor)->with(['department:id,name', 'requester:id,name'])->findOrFail($requisitionId);
$comparison = app(ProposalComparison::class)->inspect($request);
$rows = [];
@@ -62,12 +63,15 @@ class ProcurementReviewReport
}
$opening = ProposalOpening::query()->where('requisition_id', $request->id)->latest('revision')->first();
$award = PurchaseAward::query()->where('requisition_id', $request->id)->first();
$order = PurchaseOrder::query()->visibleTo($actor)->where('requisition_id', $request->id)->first();
$receipts = $order ? GoodsReceipt::query()->where('purchase_order_id', $order->id)->orderBy('id')->get(['id', 'received_on', 'delivery_note'])->map(fn (GoodsReceipt $receipt) => [
'id' => $receipt->id, 'received_on' => $receipt->received_on->format('Y-m-d'), 'delivery_note' => $receipt->delivery_note,
])->all() : [];
$orders = PurchaseOrder::query()->visibleTo($actor)->forRequisitions(Requisition::query()->whereKey($request->id))->orderBy('id')->get();
$order = $orders->first(); // Retain the earlier singular projection for existing consumers.
$orderNumbers = $orders->pluck('number', 'id');
$receipts = GoodsReceipt::query()->whereIn('purchase_order_id', $orders->modelKeys())->orderBy('id')->get(['id', 'purchase_order_id', 'received_on', 'delivery_note'])->map(fn (GoodsReceipt $receipt) => [
'id' => $receipt->id, 'purchase_order_id' => $receipt->purchase_order_id, 'order_number' => $orderNumbers[$receipt->purchase_order_id],
'received_on' => $receipt->received_on->format('Y-m-d'), 'delivery_note' => $receipt->delivery_note,
])->all();
$financeVisible = $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]);
$invoices = $financeVisible && $order ? Invoice::query()->where('purchase_order_id', $order->id)->orderBy('id')->get(['id', 'number', 'status', 'issued_on', 'total_minor', 'snapshot']) : collect();
$invoices = $financeVisible ? Invoice::query()->whereIn('purchase_order_id', $orders->modelKeys())->orderBy('id')->get(['id', 'purchase_order_id', 'number', 'status', 'issued_on', 'total_minor', 'snapshot']) : collect();
$payments = $financeVisible ? ExternalPayment::query()->whereIn('invoice_id', $invoices->pluck('id'))->orderBy('id')->get(['id', 'invoice_id', 'status', 'amount_minor', 'currency', 'paid_on'])->map(fn ($payment) => [
'id' => $payment->id, 'invoice_id' => $payment->invoice_id, 'status' => $payment->status, 'amount_minor' => (string) $payment->amount_minor, 'currency' => $payment->currency, 'paid_on' => $payment->paid_on,
])->all() : null;
@@ -83,10 +87,15 @@ class ProcurementReviewReport
'opening' => $opening ? [...$opening->only(['id', 'revision', 'reference']), 'source_changed' => $opening->basis_hash !== $basis] : null,
'award' => $award?->only(['id', 'status', 'total_minor']),
'order' => $order?->only(['id', 'number', 'currency', 'total_minor']),
'orders' => $orders->map(fn (PurchaseOrder $document) => [...$document->only(['id', 'number', 'currency', 'total_minor']),
'agreement_limits' => $document->snapshot['agreement_bindings'] ?? [],
'origins' => Requisition::query()->whereIn('id', app(OrderPartsAccess::class)->origins($document))->orderBy('id')->get(['id', 'number'])->toArray()])->all(),
'agreement_limits' => $order?->snapshot['agreement_bindings'] ?? [],
'fulfilment' => [
'receipts' => $receipts, 'finance_visible' => $financeVisible,
'invoices' => $financeVisible ? $invoices->map(fn (Invoice $invoice) => ['id' => $invoice->id, 'number' => $invoice->number, 'status' => $invoice->status, 'issued_on' => $invoice->issued_on, 'total_minor' => (string) $invoice->total_minor, 'currency' => $invoice->snapshot['currency'] ?? null])->all() : null,
'invoices' => $financeVisible ? $invoices->map(fn (Invoice $invoice) => ['id' => $invoice->id, 'purchase_order_id' => $invoice->purchase_order_id,
'order_number' => $orderNumbers[$invoice->purchase_order_id], 'number' => $invoice->number, 'status' => $invoice->status, 'issued_on' => $invoice->issued_on,
'total_minor' => (string) $invoice->total_minor, 'currency' => $invoice->snapshot['currency'] ?? null])->all() : null,
'payments' => $payments,
],
];
+3
View File
@@ -0,0 +1,3 @@
<?php
return ['qa_enabled' => false];
+14
View File
@@ -1,5 +1,19 @@
# Desenvolvimento do SGC
## Análise de despesa e associação contratual — QA, 27/11/2026
Implementadas despesa por fornecedor e por categoria, esta última conforme a decisão «Imputação explícita por Finanças». Pagamentos confirmados originais, data da confirmação, moedas separadas, totais exactos, paginações independentes e CSV integral. A imputação preserva versões, exige a soma exacta do pagamento e categorias documentais da factura; não modifica pagamentos, dívida, orçamento ou stock. Administração com acesso financeiro consulta, sem adquirir a competência de Finanças. Ausência de imputação ou de fonte auditada permanece visível, sem rateio automático.
Corrigidas consultas que só seguiam a primeira origem da ordem consolidada: filtros por outra origem recuperam o documento uma vez, conservando o acesso a todas as origens e identificando montantes integrais. Indicador/CSV de contratos usa associações conservadas na emissão e distingue cobertura integral/parcial, ausência de contrato associado e histórico indeterminado; não converte falta de dados em infracção nem montantes de ordens em despesa paga.
Prova `proofs/procurement-analytics-qa.json`: atribuição/análise11/194, regressão de recepção/facturas/pagamentos87/388, contratos7/231, concorrência com dois operadores de Finanças, restauro de duas versões e fontes, frontend207/207, tipos/PHPStan/check e build privado aprovados. Delta final HTTP/privacidadeSQLite1/57. Contagens sobrepostas, sem soma. Funcionalidade nova de imputação desligada por defeito, sem migração, instalação no piloto ou alteração SGF. Revisão visual/móvel/impressão nova permanece pendente; continuar a matriz, sem declarar conclusão integral.
## Expiração e ciclos de aprovação/reserva — QA autorizada, 27/11/2026
Implementada a decisão de devolver o mesmo pedido ao requisitante para nova submissão. A política empresarial fica preservada por ciclo; lembretes e alertas de escalamento usam destinatários actuais sem delegar aprovação. Devolução/libertação são atómicas; a revisão do rascunho exige novas etapas e reserva. O agendador tem contexto limitado ao pedido, sem sessão ou identidade interactiva, e recusa submissão, criação de orçamento e outras origens. Sem instalação no piloto ou alteração operacional SGF.
Provas em `proofs/requisition-expiry-qa.json` e `proofs/requisition-expiry-artifact.json`: ciclos8/122, regressão de requisições/orçamento40/723, importações24/189 e encomendas8/268; contagens sobrepostas não se somam. Concorrência real confirmou dois processos bloqueados, uma devolução, saldo reservado zero e nenhuma aprovação tardia; runtime antigo recusou saldos503. Restauro pré/pós conferiu115/116tabelas e repetição sem efeitos. Frontend202/202, incluindo guias agora presentes nas duas páginas novas. Pacote privado independente preparado; revisão visual interrompida pelo controlo do computador, ainda pendente. Servidor/raiz/base da pré-visualização encerrados/removidos. Continuar os requisitos e a validação transversal, sem declarar a aplicação concluída por este incremento.
## Conferência adicional e impressão multipágina — 27/11/2026
Conferidos em apresentação isolada os formulários de armazém e suporte documental bancário (edição/consulta), relatórios de Pessoas, melhorias de fornecedores e conferência. Dados inteiramente sintéticos; a390px não foi observado transbordo da página; apresentação de melhorias também observada a1280px. Não demonstra gravações nativas ou validação de servidor nesses cenários.
+9 -5
View File
@@ -1,5 +1,9 @@
# Matriz reconciliada do SGC — 03/11/2026
**27/11/2026 — análise funcional em QA:** despesa por fornecedor e categoria implementadas, com imputação explícita por Finanças conforme decisão registada, originais confirmados, moedas separadas, paginação própria e CSV integral. Indicador contratual distingue associação integral/parcial, ausência de associação na emissão e histórico indeterminado. Consultas consolidadas corrigidas para qualquer origem filtrada, sem duplicação nem perda dos controlos de acesso. Provas em `proofs/procurement-analytics-qa.json`: atribuição/análise11/194, regressão nativa87/388, contratos7/231, concorrência/restauro e frontend207/207. Revisão visual nova e disponibilização operacional pendentes; não declara a aplicação concluída.
**27/11/2026 — ciclos de aprovação e reserva, QA autorizada:** expiração devolve o mesmo pedido ao requisitante, liberta a reserva do ciclo pelo núcleo comum e preserva decisões, itens e valores anteriores; nova submissão cria novas etapas/reserva. Política empresarial versionada, lembretes, alertas de escalamento com destinatários actuais e execução periódica sem sessão. Concorrência real, recusa do runtime antigo, restauro de115/116tabelas e regressões dirigidas aprovados; ver `proofs/requisition-expiry-qa.json`. Revisão visual interrompida pelo controlo do computador, sem instalação/activação operacional. Guias das duas páginas acrescentadas;10testes dirigidos frontend aprovados, ultrapassando a omissão referida no relatório de impressão abaixo.
**Delta de impressão e conferência — 27/11/2026:** provas adicionais de armazém/importação documental e relatórios (Pessoas/melhorias/conferência), em pré-visualização sintética. Impressão real do navegador verificada em9/10/3páginas, sem linhas em falta ou texto fora das páginas; resultados/evidências anteriormente omitidos agora presentes, estado de expansão do ecrã conservado. Relatórios largos emA4horizontal e navegação de ecrã excluída da impressão.17testes dirigidos aprovados; bateria geral199/200 devido às guias ausentes de `organization/approval-timeouts` e `requisitions/expiry` do trabalho paralelo. Tipos/lint/build privado aprovados. Isto reduz a pendência multipágina nestes três relatórios, não declara revisão nativa integral ou publicação. `proofs/screen-print-review-qa.json`.
**Delta de apresentação — 27/11/2026:** uniformização autorizada com os componentes existentes e benchmark de29/10. Títulos/painéis/controlos partilhados (91páginas), barras de acções e tabelas adaptadas explicitamente em31páginas; resumos de erro dos relatórios alinhados.193testes frontend, tipos, formato/lint e build privado aprovados. Revisão estática sintética de requisição/fornecedor a390px e relatório25linhas a390/1280px, com deslocamento da tabela por teclado. Sem alteração de campos, handlers, permissões, dados ou activação de assets do piloto. Não encerra aceitação visual transversal, gravação nativa ou impressão multipágina. Ver `proofs/screen-standardisation-qa.json` e o registo em `desenvolvimento.md`; provas funcionais anteriores preservadas.
@@ -110,15 +114,15 @@ Fonte: `A requisção de insumos de produção.docx`, secções 1–9; exemplar/
| Insumos, peças, maquinaria e escritório | Classificação explícita e regras condicionais verificadas em QA, incluindo critérios opcionais de aprovação; não instaladas no piloto. Ver `rq01-categories.json`; MRP e restantes requisitos não são inferidos desta entrega. |
| Insumos para produção | Primeiro incremento disponível em QA: destino próprio, referência declarada opcional, catálogo de stock obrigatório nativo, entrega/evento/operação única, impressão/CSV e origem da reposição. `production-destination.json`. Não afirma validação de ordem externa ou MRP. |
| Compatibilidade do feed de armazém | Produção é representada como uso interno no contrato v1 existente; o detalhe de produção fica preservado no SGC. Regressão valida o feed com o consumidor actual. Não foi alterado nem activado o SGF; transportar metadados adicionais exige evolução explícita do contrato. |
| Atribuição de conta por linha e distribuições | Distribuições V1 por linha/centro instaladas no piloto autorizado, com escritor comum único; não repetir instalação. Ligação a ordem/projecto/imobilizado e contas conserva requisitos próprios ainda por concluir. |
| Atribuição de conta por linha e distribuições | Distribuições V1 por linha/centro instaladas no piloto autorizado, com escritor comum único; não repetir instalação. Cadastro próprio de projectos/imobilizado e ligação explícita por artigo, congelamento em ordens normais/parciais e rastreio de recepções implementados em QA (`capital-register-qa.json`). Aplicabilidade contabilística integral e revisão visual final continuam por demonstrar. |
| Aprovação por valor/categoria/centro, até oito níveis | Implementado, testado e capacidade instalada no piloto: controlos base mais até cinco níveis condicionais por perfis, máximo oito, um elegível por nível. Versão/encaminhamento congelados, sem concessões automáticas. Provas `configured-requisition-levels.json` e `approval-search-pilot-installation.json`. Configuração pela empresa, revisão visual restante e aceitação pendentes; não repetir instalação. |
| Auto-aprovação | Continua proibida. A opção proposta não é activada sem limite e decisão/configuração concreta; nenhum valor ilustrativo é parametrização da empresa. |
| Orçamento e compromisso | Preservar o núcleo comum e a regra vigente. Não alterar política financeira ou activar regra em dados reais pela importação do documento. |
| Urgência e peça crítica | Metadados/validação técnica existentes; fluxo acelerado, limites e dispensas exigem os parâmetros da empresa ainda ausentes. Não dispensar cotações ou orçamento automaticamente. |
| Maquinaria | Validação técnica e Finanças existentes; direcção, orçamento de capital e rastreio até imobilizado requerem completar o percurso, sem duplicar os motores SGF. |
| Lembretes, escalamento e expiração | Tarefas/avisos existentes não demonstram escalamento hierárquico ou expiração configurável. Prazos concretos ainda não fornecidos. |
| Divisão/consolidação e conversão | Contrato opcional e preparação nativa verificados em QA; ver `rq01-multi-order-qa.json`. Emissão documental, visibilidade entre origens e percurso completo de recepção/factura ainda em desenvolvimento autorizado. V1 instalado preservado. |
| Importação directa | Especificação actualizada, secções 9–10.8, reconciliada em `rq01-import-reconciliation.json`: logística existente; classificação, custo de aterragem, documentos/JUE, intervenientes, regras legais e alertas adicionais ainda por concluir. |
| Lembretes, escalamento e expiração | Política empresarial configurável/fixada por ciclo, lembretes e alertas a perfis expressos, expiração com devolução/libertação e nova submissão implementados em QA autorizada (`requisition-expiry-qa.json`). Agendador sem sessão, recusa de operações alheias, concorrência e recuperação verificados. Alertar não delega aprovação. Revisão visual e disponibilização operacional pendentes; nenhum prazo ilustrativo activado no piloto. |
| Divisão/consolidação e conversão | Emissão documental, visibilidade entre origens, recepção/factura, câmbio por origem e reafectação financeira implementados e verificados em QA; deltas e provas no início desta matriz. Emissão parcial também verificada no segundo ciclo de reserva. Revisão visual restante e disponibilização operacional mantêm requisitos próprios; V1 instalado preservado. |
| Importação directa | Classificação, custo estimado/efectivo, documentos tipificados, intervenientes, suporte bancário, base legal e acompanhamento implementados em QA conforme as provas e deltas iniciais. Legislação partilhada inventariada e originais oficiais preservados; nenhuma taxa real activada por importação. Cobertura legal específica, revisão transversal e disponibilização operacional ainda exigem conferência; documentos não executam submissões JUE ou transferências. |
Primeiro incremento validado: SQLite 50/713 e PostgreSQL 50/713, base removida, 14 frontend dirigidos, tipos/PHPStan/check/build. Preview QA com 150 assets conferidos, manifesto anterior preservado, sem migração, alteração de alçadas ou comandos de negócio no piloto. Móvel/impressão manual, restante RQ-01 e aceitação empresarial continuam pendentes.
@@ -156,7 +160,7 @@ Pedido do proprietário: iniciar a aplicação agora para evitar confusão e per
| Ordens, recepções e impressão | Pré-visualizações de ordem e recepção conferidas, uma página cada; compatibilidade com original antigo incompleto corrigida sem reescrever dados. Prova `product-review-20261122.json`. | Conferir documentos/estados restantes e paginação com várias páginas; preservar a prova aceite. |
| Acordos, contratos e catálogo | Vigência/CSV existentes; multiartigo/limites por ordem e conversões físicas verificados em QA. | Não activar limites/conversões no piloto por inferência. Consulta de vigência não comprova renovação/adendas, nem catálogo comprova análise da sua utilização. |
| Facturas, orçamento e pagamentos | Núcleos, adaptadores e provas financeiras existentes; âmbitos activo/QA documentados. | Preservar motor único e limites de activação. Registo documental não executa transferências. |
| Relatórios e análise | Central, filtros, CSV integral e relatório por processo (`ProcurementReportsTest`, `ProcurementReviewReportTest`). | Reconciliar individualmente despesa por categoria/fornecedor, tempos de aprovação e compras fora de contrato antes de declarar cobertura. Abrir relatório não comprova esses indicadores. |
| Relatórios e análise | Central, filtros, CSV integral e relatório por processo; despesa confirmada por fornecedor/categoria com imputação explícita de Finanças e associação contratual documental verificadas em QA (`procurement-analytics-qa.json`). Tempos de aprovação usam o ciclo actual, com regressão de nova submissão9/173. | Revisão visual/móvel/impressão dos novos indicadores e cobertura de restantes análises, incluindo entregas em atraso, continuam por conferir. Associação contratual não certifica conformidade; desconhecido não é compra fora de contrato. |
| Administração e organização | Dados institucionais, várias contas e sede/sucursais implementados; recortes autorizados instalados no piloto, com provas `benchmark-pilot-installation.json` e `commercial-pilot-installation.json`. Consultas dirigidas também revistas visualmente. | Completar revisão restante e configuração real pela empresa; não repetir migrações nem introduzir dados empresariais por inferência. |
| Pesquisa global, pesquisas guardadas e análise avançada | Pesquisas guardadas privadas implementadas e verificadas em QA, incluindo percurso nativo; ainda sem instalação no piloto. | Reconciliar cobertura global e análises restantes; ver `saved-procurement-searches.json`. |
+4
View File
@@ -1,5 +1,9 @@
# Continuidade do desenvolvimento do SGC
**27/11/2026 — análise de despesa/contratos:** decisão posterior «Imputação explícita por Finanças» registada em `proofs/expense-category-decision.json`, implementada com versões e soma exacta do pagamento, sem rateio automático nem movimento financeiro. Fornecedores/categorias e CSV completos, origens consolidadas corrigidas, associação contratual documental e tempos do ciclo actual verificados; `proofs/procurement-analytics-qa.json`. Atribuição/análise11/194, regressão nativa87/388, contratos7/231, concorrência e restauro de duas versões, frontend207/207, tipos/PHPStan/check/build privado aprovados; delta de privacidadeSQLite1/57. Flag nova false, sem migração/activação no piloto. Próximo: concluir revisão de apresentação quando o controlo estiver disponível e conferir análises restantes na matriz, incluindo entregas em atraso; não reiniciar decisões já dadas nem parar por este incremento.
**27/11/2026 — expiração/ciclos em QA:** autorização específica já registada; não voltar a pedi-la. Mesmo pedido devolvido a rascunho, histórico anterior preservado, reserva libertada e nova submissão com novas aprovações/reserva. Política congelada, lembretes/escalamento por perfis actuais e agendador sem sessão implementados. Provas `proofs/requisition-expiry-qa.json`/`requisition-expiry-artifact.json`: ciclos8/122, concorrência real, recusa do runtime anterior, restauro115/116tabelas e regressões dirigidas; frontend202/202 depois das guias novas. Rever os hashes actuais do artefacto antes de reutilizar provas. Revisão visual não realizada porque Computer Use reportou interrupção por Escape; ambiente privado já removido. Continuar revisão final/pendências na matriz; não activar no piloto nem alterar o SGF operacional.
**27/11/2026 — conferência adicional/impressão:** armazém e suporte bancário (edição/consulta), Pessoas, melhorias e conferência revistos com dados sintéticos. Corrigida a omissão de resultados/evidências fechados no ecrã; PDFs de9/10/3páginas preservam30medidas/30propostas/35ocorrências, com cabeçalhos e limites conferidos. A4horizontal para relatórios largos, paginação de ecrã oculta e nota final agrupada. Prova `proofs/screen-print-review-qa.json`. Dirigidos aprovados, tipos/lint/build privado aprovados; bateria geral199/200 por falta de ajuda das duas páginas de expiração do trabalho paralelo. Não repetir tentativas do mesmo erro sem actualizar essas guias; não alterar fluxos financeiros para o resolver. Sem gravações de negócio, assets operacionais actualizados ou publicação. Conferência nativa integral e implantação do domínio ainda pendentes de âmbito próprio.
**27/11/2026 — uniformização de ecrãs autorizada, concluída no recorte de apresentação comum/QA:** base `PageTitle`/`Panel`/controlos em91páginas e adaptação explícita de31páginas com acções/tabelas comuns; erros dos relatórios uniformizados.45ficheiros/193testes frontend, tipos, formato/lint e build privado aprovados. Pré-visualização estática sintética de requisição/fornecedor a390px e relatório25linhas a390/1280px, deslocamento por teclado observado. Sem gravações, servidor/configuração de negócio ou `public/build` alterados por esta tarefa. Não confundir esta prova com validação nativa de todos os formulários ou impressão multipágina; estes critérios continuam pendentes. Preservar o trabalho financeiro/capital paralelo. Prova `proofs/screen-standardisation-qa.json`; benchmark/regras/permissões existentes mantidos.
@@ -0,0 +1,8 @@
{
"date": "2026-11-27",
"owner_decision": "Imputação explícita por Finanças",
"question_scope": "Attribution of confirmed partial invoice payments across the categories of invoice lines",
"implementation_scope": "Explicit versioned analytical attribution with exact payment-total check, native Finance authority, audited original payment and frozen invoice-line categories; no payment or ledger modification",
"no_automatic_proportional_allocation": true,
"operational_activation": false
}
+39
View File
@@ -0,0 +1,39 @@
{
"date": "2026-11-27",
"status": "implemented_and_verified_in_isolated_qa_native_visual_acceptance_pending",
"decisions": ["confirmed-payment-insights-qa.json", "expense-category-decision.json"],
"implemented": {
"consolidated_origins": "Central reports, payment expense and payable positions match any filtered native origin while retaining all-origin visibility. Individual review HTML/CSV includes every visible partial/consolidated order, its own frozen agreement versions, receipts and invoices. Each order/invoice is counted once; whole-document amounts are explicitly identified, without invented apportionment.",
"supplier_expense": "Audited original confirmed payments, confirmation-date period, frozen invoice supplier identity/name, exact separate currency totals, independent supplier pagination and complete CSV.",
"category_expense": "Explicit Finance attribution to categories of invoice lines, exact confirmed-payment total, append-only corrections, source fingerprint/audit verification, independent category pagination and full CSV. Unallocated and indeterminate amounts remain separate; no automatic proportional allocation.",
"contract_association": "Frozen native issuance references distinguish full/partial/no contract association and indeterminate legacy history. Operational order amounts are distinct from paid expense. No retrospective compliance decision or historical backfill.",
"approval_times": "Current-cycle completion duration verified after expiry/resubmission; earlier approvals are preserved without entering the new-cycle measure."
},
"verification": {
"consolidated_and_native_financial_read_regression": {"tests": 6, "assertions": 184, "passed": true},
"supplier_pagination_and_native_payment_history": {"tests": 6, "assertions": 122, "passed": true, "supplier_groups": 21, "csv_includes_all_groups": true, "formula_prefix_escaped": true},
"contract_report": {"tests": 7, "assertions": 231, "passed": true},
"multi_order_individual_review_postgresql": {"tests": 2, "assertions": 172, "passed": true, "includes_secondary_origin_and_current_access_loss": true},
"individual_review_and_csv_sqlite": {"tests": 16, "assertions": 164, "passed": true, "includes_distinct_agreement_versions_per_order_and_maintenance_denial": true},
"expense_allocation_and_financial_read": {"tests": 11, "assertions": 194, "passed": true},
"native_receipt_invoice_payment_regression": {"tests": 87, "assertions": 388, "passed": true},
"final_workspace_minimisation_delta_sqlite": {"tests": 1, "assertions": 57, "passed": true},
"concurrency": {
"same_operation": {"statuses": [200, 200], "blocked_finance_writers": 2},
"same_version_different_finance_actors": {"statuses": [200, 409], "blocked_finance_writers": 2},
"each_scenario": {"versions_created": 1, "audits": 1, "financial_sources_unchanged": true}
},
"recovery": {"versions": 2, "explicit_minor_amounts": {"Material": "1000", "Serviços": "3000"}, "audited_native_sources_verified": true,
"replay_without_effects": true, "pre_extension_tables_equal": 115, "post_extension_tables_equal": 116, "source_and_restore_databases_removed": true},
"frontend": {"files": 49, "tests": 207, "passed": true},
"receipt_protocol": {"tests": 13, "assertions": 58, "passed": true},
"typescript": "passed", "phpstan": "passed", "scoped_format_lint": "passed", "pint": "passed", "diff_whitespace": "passed",
"private_build": {"path": "storage/framework/testing/sgc-analytics-qa-20261127", "manifest_sha256": "130bf823b96f8cb122afbe50119183163aa22abf24eff26cb537e88a936a4f5a", "passed": true, "note": "Precedes the later individual multi-order review presentation delta; that delta has focused frontend/types validation and awaits the next private build."},
"counts_note": "Suites overlap and must not be added; the final SQLite delta verifies the reduced workspace payload after the PostgreSQL run."
},
"fixtures": "Synthetic QA only. Invoice/order chains used for pagination are labelled synthetic; payment originals use native registration and independent evidence review. Multi-category fixture lines and headers retain the same exact total. No real bank transaction is executed.",
"boundaries": {"expense_attribution_default_enabled": false, "migrations_required_for_attribution": false, "financial_journal_writer_added": false,
"payment_invoice_stock_budget_mutations_by_attribution": false, "pilot_or_sgf_operational_changes": false,
"pilot_manifest_sha256": "1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e"},
"remaining": ["Native visual/mobile/print review of new analytical tables and attribution form", "Operational activation within its concrete authorised scope", "Other application requirements in the existing matrix"]
}
@@ -0,0 +1,38 @@
{
"date": "2026-11-27",
"status": "private_qa_prepared_not_installed",
"path": "storage/framework/testing/requisition-cycles-qa-35701ec1614f871e",
"manifest_sha256": "fe1dec59a6d619670e887fd2f972a6de176b858a90f03cf43a017c681606816a",
"archive": "storage/framework/testing/requisition-cycles-qa-35701ec1614f871e.zip",
"archive_sha256": "75f44c926bffaea30601e018aa6505e84bbe3c5eda84ba56ece5b05fb430ab5b",
"canonical_fingerprint": "35701ec1614f871e551a09fec96693294507c7c6c73e6e23e4cc39bc3a9b737b",
"files": {
"budget-control/bootstrap.php": "c96207d083daedc51d93b1527dca5fe8a0cfb5283920e87516f5c3c62674806f",
"budget-control/README.md": "09c9ad38c3d67706827dab1382a2cf930f12f90532740cd25104af5ed12da02d",
"budget-control/src/BudgetContext.php": "446f2e3910dd87de5ae309c3f5d9ef3ef813be0f561d7e7718d1679d55349b3b",
"budget-control/src/BudgetFailure.php": "30ec4c7a5b45e5980ca517d167aa45e89f22a3429c76365fa1c1a94db5f4d8e0",
"budget-control/src/BudgetControl.php": "91380a29ef980229845ac2988301c27c73aa308731ec8c89b53249a1b9d9edb0",
"budget-control/src/BudgetDistributionPlan.php": "ed42ce7c3ffb789c9b0deb39a880ddd8bb3e5c63d8a14d9871dba73fe8c00acd",
"budget-control/src/BudgetDistributions.php": "edf7e01e0a43cb373e72c80626adaa7dc47e52b87cd62bedb90359d723acd09b",
"budget-control/src/BudgetOrderParts.php": "cbb206faf6e19ba20238a8574715f86f1e9604dc892f23fdb20648dc9259b543",
"budget-control/src/BudgetLandedCosts.php": "a238e6479437023ac91e5526f76ac639ae385f424fc82f5b47fb718ad861ef6c",
"budget-control/src/BudgetLandedCostPlan.php": "5a9f26b3d50abcb0bdc20c5571012da37b1f6403587ca68ea9573f08891f8c7a",
"budget-control/src/BudgetImportEstimate.php": "f6d62bbc8bda4ab75fc679de9bc2e5d19240fd3579c384097d013ccefe7826c0",
"budget-control/src/BudgetRequisitionCycles.php": "4b369c09ead84149ff56c5781d74b2e8b193ceda3baa586ca0c9d732d5b2c815",
"purchasing/bootstrap.php": "d182322577bacc1d04cba2610a4e3be51d6ef2b165021543ad891f72ca720c23",
"purchasing/README.md": "0c012f253f69236f0170c2a37010d7c07d3f9a2bc2f9dc94d0d6813b011ee9fd",
"purchasing/module.json": "33c0c854be9ec41d64165f8d92275cb0c141caf952988128e8fdbcb816c0b0e3",
"purchasing/src/ReplenishmentProjection.php": "446c9b32249c5fa639d00209c6d3cb9d2d26b085f3a77655e8ca6ff66403a48d",
"purchasing/src/QuotationPricing.php": "3ae7c5d90a9075e2f5303bf336fd663c920fab91d15b38b34a6ef8ea5c441d06",
"purchasing/src/ProposalScoring.php": "e6bba763e63d96e51f55b6653a5b3a9079f90e8ddb7d3ff414ea27f93284f9a8",
"purchasing/src/RequisitionPort.php": "46aa5f793a3f6abf7ed3561e337f3bbe7b6a63b1c25a37e230ad4e76a3492814",
"purchasing/src/ExpiryRequisitionPort.php": "647cbe5cc1a0fde5ba2cae2537e51ebb45e0271f2f0c45536c4236000148fd91",
"purchasing/src/RequisitionFailure.php": "72d199f2d2d42a5a40ea9b6afc9fb15f5a7c9f1253adca5d00e9037565ed54d3",
"purchasing/src/InternalRequisitions.php": "925f67d4d31c1a865d4a25a72385aae7ec398fbac10e72804791548c07d9a7a2",
"purchasing/src/Sourcing.php": "c2153a301fa20c72d2e8e285cd6e2bcc38618cade0aab9845e8d8cba8aecc55f",
"database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php": "8ee8aa5b2820c57b4d53f4e0da72933f988996fffe3bf055ec8aeac9072d2983"
},
"independent_financial_load_test": {"passed": true, "postgresql_tests": 8, "assertions": 122, "disposable_database_removed": true},
"installed_packages_changed": false,
"pilot_or_sgf_activation": false
}
+10 -7
View File
@@ -15,12 +15,12 @@
"Old installed financial runtime refuses balances with status 503 after a new cycle"
],
"verification": {
"focused_postgresql": {"tests": 7, "assertions": 78, "passed": true},
"focused_postgresql": {"tests": 9, "assertions": 173, "passed": true, "includes_current_cycle_approval_duration": true},
"submission_budget_regression": {"tests": 40, "assertions": 723, "passed": true, "note": "Before the added seventh escalation test; not additive with focused tests"},
"import_regression": {"tests": 24, "assertions": 189, "passed": true},
"order_regression": {"tests": 8, "assertions": 268, "passed": true},
"partial_order_two_cycles": {"tests": 2, "assertions": 60, "passed": true, "note": "Covered by order regression"},
"frontend": {"tests": 2, "passed": true},
"frontend": {"expiry_and_help_tests": 10, "all_tests": 202, "passed": true},
"concurrency": {
"same_operation": {"statuses": [200, 200], "blocked_writers": 2},
"different_operations": {"statuses": [200, 409], "blocked_writers": 2},
@@ -29,15 +29,18 @@
"old_runtime": {"status": 503, "before_balance_or_effects": true},
"disposable_database_removed": true
},
"phpstan": "passed before final contention-helper changes",
"scheduled_execution": {"without_session": true, "scope_closed": true, "repeat_without_effects": true, "explicit_automatic_audit": true, "unrelated_operations_denied": 3},
"recovery": {"pre_extension_tables_equal": 115, "post_extension_tables_equal": 116, "native_replay_without_effects": true, "reserved_minor_restored": 12000, "source_and_restore_databases_removed": true},
"private_build": {"path": "storage/framework/testing/sgc-expiry-qa-20261127", "manifest_sha256": "5cdbb3bdd27379ba55a32c676ebf791fd90c0a3e89f5c384fea3ea7b98084cd7", "passed": true},
"portable_artifact": {"proof": "requisition-expiry-artifact.json", "independent_financial_load_tests": 8, "assertions": 122, "passed": true},
"native_visual_review": "Not performed: Computer Use reported that the user stopped it with physical Escape; no further UI actions taken",
"phpstan": "passed including scheduled host execution",
"typescript": "passed",
"pint": "passed on edited host files; shared-source final check pending",
"pint": "passed on edited host files and new common cycle trait; common modified PHP files passed syntax checks",
"oversized_regression_attempt": "No result claimed: exceeded 180 seconds; replaced with independently isolated focused groups"
},
"remaining": [
"Verified pre/post extension backup and restoration of complete cycle data",
"Private portable artifact and native administrator/requester visual review",
"Scheduled execution with narrow documented identity and tenant context, without impersonation",
"Native administrator/requester visual review",
"Final shared-source checks and final delta review",
"Remaining application requirements in the existing matrix"
],
@@ -0,0 +1,119 @@
import { TableViewport } from '@/components/procurement';
import { exactMinorAmount } from '@/components/procurement-payable-insights';
export type CategoryAttribution = {
coverage: { allocated: number; unallocated: number; indeterminate: number };
unassigned: {
state: string;
currency: string;
count: number;
amount_minor: string;
}[];
groups: {
data: {
category: string;
currency: string;
count: number;
amount_minor: string;
}[];
total: number;
current_page: number;
last_page: number;
};
};
export function ProcurementCategoryInsights({
data,
pageHref,
}: {
data: CategoryAttribution;
pageHref?: string;
}) {
const href = (page: number) => {
const [path, query] = (pageHref || '/relatorios').split('?');
const params = new URLSearchParams(query);
params.set('category_page', String(page));
return `${path}?${params}`;
};
return (
<section className="mt-5 space-y-3" aria-label="Despesa por categoria">
<h3 className="font-semibold">Despesa por categoria</h3>
<p className="text-sm">
Imputação explícita por Finanças: {data.coverage.allocated}{' '}
pagamento(s) imputado(s), {data.coverage.unallocated} por
imputar e {data.coverage.indeterminate} com imputação
indeterminada. Não há distribuição proporcional automática.
</p>
{data.unassigned.map((row) => (
<p className="text-sm" key={`${row.state}:${row.currency}`}>
{row.state === 'unallocated'
? 'Despesa não imputada'
: 'Imputação indeterminada'}
: {exactMinorAmount(row.amount_minor, row.currency)} ·{' '}
{row.count} pagamento(s).
</p>
))}
{data.groups.data.length > 0 && (
<TableViewport label="Montantes imputados por categoria">
<table className="w-full text-left text-sm">
<thead>
<tr>
<th className="p-2">Categoria da factura</th>
<th className="p-2">Imputações</th>
<th className="p-2">
Despesa confirmada imputada
</th>
</tr>
</thead>
<tbody>
{data.groups.data.map((row) => (
<tr
className="border-t"
key={`${row.category}:${row.currency}`}
>
<td className="p-2">{row.category}</td>
<td className="p-2">{row.count}</td>
<td className="p-2 whitespace-nowrap">
{exactMinorAmount(
row.amount_minor,
row.currency,
)}
</td>
</tr>
))}
</tbody>
</table>
</TableViewport>
)}
{data.groups.total > 0 && (
<p className="text-sm">
{data.groups.total} grupo(s) categoria/moeda · Página{' '}
{data.groups.current_page} de {data.groups.last_page}. Um
pagamento pode ter imputações em várias categorias.
</p>
)}
{pageHref && (
<nav
className="flex gap-4 print:hidden"
aria-label="Páginas de despesa por categoria"
>
{data.groups.current_page > 1 && (
<a
className="underline"
href={href(data.groups.current_page - 1)}
>
Anterior
</a>
)}
{data.groups.current_page < data.groups.last_page && (
<a
className="underline"
href={href(data.groups.current_page + 1)}
>
Seguinte
</a>
)}
</nav>
)}
</section>
);
}
@@ -0,0 +1,89 @@
import { Panel, TableViewport } from '@/components/procurement';
import { exactMinorAmount } from '@/components/procurement-payable-insights';
export type ContractInsights = {
coverage: Record<string, number>;
currencies: {
classification: string;
currency: string | null;
count: number;
amount_minor: string | null;
}[];
};
const labels: Record<string, string> = {
contract: 'Todas as linhas com contrato associado',
partial: 'Parte das linhas com contrato associado',
without_contract: 'Sem contrato associado na emissão',
unknown: 'Associação por determinar',
};
export function ProcurementContractInsights({
data,
exportHref,
}: {
data: ContractInsights;
exportHref?: string;
}) {
return (
<Panel
title="Compras e contratos"
description="Associações documentais conservadas nas ordens operacionais. Os filtros usam a data de criação dos pedidos; cada ordem consolidada conta uma única vez."
>
<p className="text-sm text-muted-foreground">
Os montantes são os totais integrais das ordens, incluindo as
parcialmente associadas. Não representam pagamentos nem uma
decisão de conformidade contratual.
</p>
{data.coverage.unknown > 0 && (
<p className="mt-3 text-sm" role="status">
{data.coverage.unknown} ordem(ns) sem informação suficiente
sobre a associação na emissão; não foram classificadas como
compras fora de contrato.
</p>
)}
{data.currencies.length === 0 ? (
<p className="mt-3">Sem ordens operacionais neste âmbito.</p>
) : (
<TableViewport label="Associações contratuais das ordens">
<table className="w-full text-left text-sm">
<thead>
<tr>
<th className="p-2">Associação na emissão</th>
<th className="p-2">Ordens</th>
<th className="p-2">Montante das ordens</th>
</tr>
</thead>
<tbody>
{data.currencies.map((row) => (
<tr
className="border-t"
key={`${row.classification}:${row.currency}`}
>
<td className="p-2">
{labels[row.classification] ||
'Por determinar'}
</td>
<td className="p-2">{row.count}</td>
<td className="p-2 whitespace-nowrap">
{row.currency === null ||
row.amount_minor === null
? 'Indeterminado'
: exactMinorAmount(
row.amount_minor,
row.currency,
)}
</td>
</tr>
))}
</tbody>
</table>
</TableViewport>
)}
{exportHref && (
<a className="mt-3 inline-block underline" href={exportHref}>
Exportar associações contratuais CSV
</a>
)}
</Panel>
);
}
@@ -0,0 +1,166 @@
import { Panel } from '@/components/procurement';
export type DeliveryInsights = {
view: string;
coverage: Record<string, number>;
pending_lines: number;
unknown_lines: number;
records: {
data: {
id: number;
number: string;
state: string;
pending_lines: number;
unknown_lines: number;
late_days: number | null;
quality_pending: boolean;
href: string;
late_lines: {
id: number;
description: string;
unit: string;
promised_on: string;
completed_on: string | null;
pending_quantity: string;
}[];
}[];
total: number;
current_page: number;
last_page: number;
};
};
const labels: Record<string, string> = {
pending_late: 'Por receber depois da data acordada',
pending: 'Por receber, dentro da data acordada',
partial_late: 'Recepção parcial tardia; restante em prazo',
completed_late: 'Recepção integral depois da data acordada',
completed_on_time: 'Recepção integral no prazo acordado',
unknown: 'Datas ou quantidades por determinar',
};
export function ProcurementDeliveryInsights({
data,
pageHref,
exportHref,
}: {
data: DeliveryInsights;
pageHref: string;
exportHref: string;
}) {
const href = (view: string, page = 1) => {
const [path, query] = pageHref.split('?');
const params = new URLSearchParams(query);
params.set('delivery_state', view);
params.set('delivery_page', String(page));
return `${path}?${params}`;
};
return (
<Panel
title="Entregas face às datas acordadas"
description="Datas conservadas na emissão, incluindo a data própria de cada origem de uma ordem consolidada. Recepções estornadas ficam excluídas; qualidade e aceitação mantêm o seu percurso próprio."
>
<dl className="grid gap-3 text-sm sm:grid-cols-2 lg:grid-cols-3">
{Object.entries(labels).map(([key, label]) => (
<div key={key}>
<dt>{label}</dt>
<dd className="font-semibold">
{data.coverage[key] ?? 0}
</dd>
</div>
))}
</dl>
<nav
className="my-4 flex flex-wrap gap-4 text-sm print:hidden"
aria-label="Filtrar acompanhamento de entregas"
>
<a className="underline" href={href('attention')}>
Atrasos e dados por conferir
</a>
<a className="underline" href={href('all')}>
Todas as ordens operacionais
</a>
<a className="underline" href={href('pending_late')}>
Por receber em atraso
</a>
<a className="underline" href={href('completed_late')}>
Recepções integrais tardias
</a>
</nav>
<p className="text-sm text-muted-foreground">
{data.pending_lines} linha(s) ainda por receber;{' '}
{data.unknown_lines} linha(s) com datas ou quantidades por
determinar. Não são presumidas datas a partir da necessidade do
requisitante.
</p>
{data.records.data.length === 0 && (
<p className="mt-3">Sem ordens nesta selecção.</p>
)}
{data.records.data.map((row) => (
<article
className="space-y-2 border-b py-4 text-sm"
key={row.id}
>
<h3 className="font-semibold">
<a className="underline" href={row.href}>
{row.number}
</a>{' '}
· {labels[row.state] || 'Por determinar'}
</h3>
<p>
Maior atraso documentado:{' '}
{row.late_days === null
? 'por determinar'
: `${row.late_days} dia(s)`}
.{' '}
{row.unknown_lines > 0 &&
`${row.unknown_lines} linha(s) por conferir.`}
</p>
{row.quality_pending && (
<p>
A recepção física está completa; a qualidade ou
aceitação permanece pendente.
</p>
)}
<ul>
{row.late_lines.map((line) => (
<li key={line.id} className="mb-2 break-words">
{line.description} · Data acordada:{' '}
{line.promised_on} · Recepção integral:{' '}
{line.completed_on || 'por completar'} · Por
receber: {line.pending_quantity} {line.unit}
</li>
))}
</ul>
</article>
))}
<p className="mt-3 text-sm">
{data.records.total} ordem(ns) nesta selecção · Página{' '}
{data.records.current_page} de {data.records.last_page}
</p>
<nav
className="mt-3 flex gap-4 print:hidden"
aria-label="Páginas de acompanhamento de entregas"
>
{data.records.current_page > 1 && (
<a
className="underline"
href={href(data.view, data.records.current_page - 1)}
>
Anterior
</a>
)}
{data.records.current_page < data.records.last_page && (
<a
className="underline"
href={href(data.view, data.records.current_page + 1)}
>
Seguinte
</a>
)}
</nav>
<a className="mt-3 inline-block underline" href={exportHref}>
Exportar acompanhamento de entregas CSV
</a>
</Panel>
);
}
@@ -43,6 +43,11 @@ export function ProcurementPayableInsights({
período dos filtros refere-se à criação do pedido; os saldos
são os actuais, na data de geração do relatório.
</p>
<p>
Cada factura é considerada uma única vez se alguma origem da
ordem corresponder aos filtros. A posição apresentada é
integral, sem repartição pelos pedidos seleccionados.
</p>
<p>
{data.coverage.recognised} de {data.coverage.invoices}{' '}
facturas com posição reconhecida e determinada. Por
@@ -1,6 +1,12 @@
import { Panel } from '@/components/procurement';
import { Panel, TableViewport } from '@/components/procurement';
import {
ProcurementCategoryInsights,
type CategoryAttribution,
} from '@/components/procurement-category-insights';
import { exactMinorAmount } from '@/components/procurement-payable-insights';
export type PaymentInsights = {
category_attribution?: CategoryAttribution;
from: string | null;
to: string | null;
coverage: {
@@ -9,15 +15,35 @@ export type PaymentInsights = {
confirmed_payments: number;
};
currencies: { currency: string; count: number; amount_minor: string }[];
suppliers?: {
data: {
supplier_id: number;
supplier_name: string;
currency: string;
count: number;
amount_minor: string;
}[];
total: number;
current_page: number;
last_page: number;
};
};
export function ProcurementPaymentInsights({
data,
exportHref,
pageHref,
}: {
data: PaymentInsights;
exportHref?: string;
pageHref?: string;
}) {
const supplierHref = (page: number) => {
const [path, query] = (pageHref || '/relatorios').split('?');
const params = new URLSearchParams(query);
params.set('supplier_page', String(page));
return `${path}?${params}`;
};
return (
<Panel
title="Despesa por período"
@@ -28,6 +54,11 @@ export function ProcurementPaymentInsights({
{data.to ?? 'Até à data actual'}.{' '}
{data.coverage.confirmed_payments} pagamentos confirmados.
</p>
<p className="mt-2 text-sm text-muted-foreground">
Cada factura é considerada uma única vez, mesmo quando a ordem
reúne vários pedidos. Os pagamentos são integrais, sem
repartição pelos pedidos seleccionados.
</p>
{data.coverage.indeterminate > 0 && (
<p role="status">
{data.coverage.indeterminate} facturas com histórico
@@ -49,6 +80,89 @@ export function ProcurementPaymentInsights({
Nenhum pagamento confirmado determinado neste período.
</p>
)}
{data.suppliers && data.suppliers.total > 0 && (
<section
className="mt-5 space-y-3"
aria-label="Despesa por fornecedor"
>
<h3 className="font-semibold">Despesa por fornecedor</h3>
<p className="text-sm text-muted-foreground">
Identificação pelo fornecedor da factura; designação
conservada no documento. Moedas apresentadas
separadamente.
</p>
<TableViewport>
<table className="w-full text-left text-sm">
<thead>
<tr>
<th className="p-2">Fornecedor</th>
<th className="p-2">Pagamentos</th>
<th className="p-2">Despesa confirmada</th>
</tr>
</thead>
<tbody>
{data.suppliers.data.map((row) => (
<tr
key={`${row.supplier_id}:${row.currency}`}
className="border-t"
>
<td className="p-2">
{row.supplier_name} · #
{row.supplier_id}
</td>
<td className="p-2">{row.count}</td>
<td className="p-2 whitespace-nowrap">
{exactMinorAmount(
row.amount_minor,
row.currency,
)}
</td>
</tr>
))}
</tbody>
</table>
</TableViewport>
<p className="text-sm">
{data.suppliers.total} grupo(s) fornecedor/moeda ·
Página {data.suppliers.current_page} de{' '}
{data.suppliers.last_page}
</p>
{pageHref && (
<nav
className="flex gap-4 print:hidden"
aria-label="Páginas de despesa por fornecedor"
>
{data.suppliers.current_page > 1 && (
<a
className="underline"
href={supplierHref(
data.suppliers.current_page - 1,
)}
>
Anterior
</a>
)}
{data.suppliers.current_page <
data.suppliers.last_page && (
<a
className="underline"
href={supplierHref(
data.suppliers.current_page + 1,
)}
>
Seguinte
</a>
)}
</nav>
)}
</section>
)}
{data.category_attribution && (
<ProcurementCategoryInsights
data={data.category_attribution}
pageHref={pageHref}
/>
)}
{exportHref && (
<a href={exportHref} className="mt-3 inline-block underline">
Exportar despesa CSV
+57
View File
@@ -37,6 +37,60 @@ function topic(
}
export const journeyHelp: JourneyHelp[] = [
topic(
'expense-allocation',
'Imputar despesa confirmada por categoria',
['payments/expense-allocation'],
'Atribuir explicitamente um pagamento confirmado às categorias documentais das linhas da factura, segundo a decisão da empresa.',
[
'Confira a factura, o montante e a moeda do pagamento confirmado.',
'Finanças indica os montantes por categoria da factura; a soma deve coincidir exactamente com o pagamento parcial ou integral.',
'Fundamente e guarde. Para corrigir, reveja a versão actual e prepare uma nova imputação, preservando as anteriores.',
],
[
'Não há distribuição proporcional automática, mesmo quando a factura só tem uma categoria.',
'A imputação serve a análise de despesa; não altera o pagamento, a obrigação, o saldo ou a reserva.',
'Pagamentos sem imputação ou com origens indeterminadas permanecem identificados separadamente no relatório.',
],
'Se o total não coincidir, reveja os montantes. Se a versão ou a origem mudou, confira o pagamento actual antes de preparar outra versão.',
'Regresse ao relatório de Compras para consultar a despesa imputada por categoria e a parte ainda por imputar.',
),
topic(
'approval-timeouts',
'Configurar prazos de aprovação',
['organization/approval-timeouts'],
'Definir os prazos da empresa para novas submissões e conservar as versões anteriores.',
[
'Indique os minutos corridos até à expiração de cada nível aplicável.',
'Quando necessários, configure lembrete e escalamento antes da expiração; escolha expressamente os perfis destinatários do escalamento.',
'Fundamente e guarde a política. Confira a versão actual antes de substituir uma preparação desactualizada.',
],
[
'A submissão conserva a sua política; alterações posteriores não mudam o ciclo pendente.',
'O alerta de escalamento exige acesso e atribuição válidos no momento da execução; não concede competência de aprovação.',
'Na expiração, o mesmo pedido regressa ao requisitante como rascunho e a reserva remanescente do ciclo é libertada.',
],
'Se a versão mudou, reveja os valores actuais e prepare a alteração de forma explícita. A indisponibilidade da extensão exige recuperar a composição compatível.',
'Consulte os prazos no processo submetido e acompanhe os avisos internos.',
),
topic(
'requisition-expiry',
'Acompanhar prazos e nova submissão',
['requisitions/expiry'],
'Consultar o prazo da etapa actual e o histórico dos ciclos do mesmo pedido.',
[
'Confira o início da etapa, a expiração e os avisos previstos na política conservada.',
'A verificação executa as acções devidas; terminado o prazo, devolve o pedido e liberta a reserva do ciclo.',
'Se o pedido lhe foi devolvido, reveja o rascunho e submeta novamente quando estiver preparado.',
],
[
'As decisões e os valores anteriores ficam preservados no histórico.',
'A nova submissão exige novas aprovações e uma nova reserva; não reutiliza aprovações do ciclo anterior.',
'Apenas os intervenientes com acesso actual podem consultar ou executar as acções apresentadas.',
],
'Se a etapa mudou, actualize a conferência e reveja a etapa actual antes de preparar a devolução. Não repita uma operação com conteúdo diferente.',
'Abra o rascunho devolvido ou regresse à requisição para acompanhar a etapa actual.',
),
topic(
'capital-register',
'Ligar compras a projectos e imobilizado',
@@ -409,11 +463,14 @@ export const journeyHelp: JourneyHelp[] = [
'Confira as pendências e os tempos de aprovação, distinguindo datas conhecidas de indeterminadas.',
'Se tiver acesso financeiro, confira a cobertura das posições reconhecidas e abra as respectivas obrigações para consultar a origem.',
'O CSV de processos e o CSV da posição financeira têm conteúdos distintos; escolha a exportação correspondente à conferência pretendida.',
'Na despesa, o período refere-se à confirmação dos pagamentos. A tabela de fornecedores tem paginação própria e o CSV inclui todos os grupos autorizados.',
'Confira as associações contratuais conservadas na emissão; os montantes são totais de ordens operacionais e não pagamentos.',
],
[
'Os saldos financeiros são os actuais na data de geração; não são saldos históricos do período filtrado.',
'Facturas por reconhecer ou com posição divergente ficam identificadas e fora dos totais; não são saldo zero.',
'As moedas são totalizadas separadamente. Principal, pagamentos históricos conferidos, liquidações imputadas e saldo são rubricas distintas.',
'Ordens antigas sem informação suficiente de associação ficam por determinar; a ausência de dados não prova compra fora de contrato.',
],
'Se a cobertura estiver incompleta, abra as obrigações e confira as origens. Não complete montantes em falta com valores presumidos.',
'Use o processo e o relatório correspondente para conferir os documentos; a consulta não executa decisões ou pagamentos.',
@@ -0,0 +1,273 @@
import { Head, Link, useForm } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import {
PageTitle,
Panel,
FormErrors,
controlClass,
} from '@/components/procurement';
import { Button } from '@/components/ui/button';
import { exactMinorAmount } from '@/components/procurement-payable-insights';
type Allocation = { category: string; amount_minor: string };
type RecordVersion = {
id: number;
version: number;
reason: string;
data: { allocations: Allocation[] };
};
type Props = {
payment: {
id: number;
invoice_id: number;
invoice_number: string;
currency: string;
amount_minor: string;
};
categories: string[];
fingerprint: string;
current: RecordVersion | null;
history: {
data: RecordVersion[];
prev_page_url: string | null;
next_page_url: string | null;
};
canWrite: boolean;
actorId: number;
tenantId: number;
};
const decimal = (value: string) => {
const digits = value.padStart(3, '0');
return `${digits.slice(0, -2)}.${digits.slice(-2)}`;
};
export default function ExpenseAllocation(props: Props) {
const payment = props.payment;
const form = useForm(
`expense-allocation:${props.tenantId}:${props.actorId}:${payment.id}`,
{
operation_key: '',
version: props.current?.version || 0,
fingerprint: props.fingerprint,
reason: '',
allocations: props.categories.map((category) => ({
category,
amount: '',
})),
},
);
const ref = useRef<HTMLFormElement>(null);
useEffect(() => {
const node = ref.current;
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: node, dirty: form.isDirty },
}),
);
return () => {
window.dispatchEvent(
new CustomEvent('sgc:context-dirty', {
detail: { form: node, dirty: false },
}),
);
};
}, [form.isDirty]);
const current =
form.data.version === (props.current?.version || 0) &&
form.data.fingerprint === props.fingerprint;
return (
<div className="mx-auto grid w-full max-w-6xl gap-6 p-5 lg:p-8">
<Head title="Imputação da despesa por categoria" />
<PageTitle
title="Imputação da despesa por categoria"
eyebrow={`Pagamento #${payment.id} · ${payment.invoice_number}`}
description="Finanças atribui explicitamente o pagamento confirmado às categorias das linhas da factura. A soma deve coincidir exactamente com o pagamento; o pagamento e o saldo permanecem preservados."
/>
<Link
className="underline"
href={`/pagamentos?payment_id=${payment.id}`}
>
Voltar ao pagamento
</Link>
<Panel
title={`Pagamento confirmado: ${exactMinorAmount(payment.amount_minor, payment.currency)}`}
>
{props.current ? (
<>
<h3 className="font-semibold">
Versão actual {props.current.version}
</h3>
<p>{props.current.reason}</p>
<ul>
{props.current.data.allocations.map((row) => (
<li key={row.category}>
{row.category}:{' '}
{exactMinorAmount(
row.amount_minor,
payment.currency,
)}
</li>
))}
</ul>
</>
) : (
<p>
Ainda sem imputação por categoria. O relatório conserva
esta despesa como não imputada.
</p>
)}
</Panel>
{props.canWrite && (
<Panel title="Preparar imputação explícita">
<form
ref={ref}
className="space-y-4"
onSubmit={(event) => {
event.preventDefault();
const operation =
form.data.operation_key || crypto.randomUUID();
form.setData('operation_key', operation);
form.transform((data) => ({
...data,
operation_key: operation,
allocations: data.allocations.filter(
(row) => row.amount !== '',
),
}));
form.post(`/pagamentos/${payment.id}/categorias`, {
preserveScroll: true,
onSuccess: (page) => {
const saved = page.props
.current as RecordVersion;
const data = {
...form.data,
operation_key: '',
reason: '',
version: saved.version,
fingerprint: page.props
.fingerprint as string,
};
form.setData(data);
form.setDefaults(data);
form.clearErrors();
},
});
}}
>
<FormErrors errors={form.errors} />
{!current && (
<p role="status">
A versão ou a origem mudou. Reveja os valores
actuais antes de preparar outra imputação.
</p>
)}
<Button
type="button"
variant="outline"
onClick={() =>
form.setData((data) => ({
...data,
version: props.current?.version || 0,
fingerprint: props.fingerprint,
operation_key: '',
allocations: props.categories.map(
(category) => ({
category,
amount: props.current?.data.allocations.find(
(row) =>
row.category === category,
)
? decimal(
props.current.data.allocations.find(
(row) =>
row.category ===
category,
)!.amount_minor,
)
: '',
}),
),
}))
}
>
Usar a imputação actual como preparação
</Button>
{form.data.allocations.map((row, index) => (
<label key={row.category} className="grid gap-2">
{row.category} · {payment.currency}
<input
className={controlClass}
inputMode="decimal"
value={row.amount}
onChange={(event) =>
form.setData(
'allocations',
form.data.allocations.map(
(entry, i) =>
i === index
? {
...entry,
amount: event
.target.value,
}
: entry,
),
)
}
/>
</label>
))}
<label className="grid gap-2">
Fundamento
<textarea
className={controlClass}
required
maxLength={4000}
value={form.data.reason}
onChange={(event) =>
form.setData('reason', event.target.value)
}
/>
</label>
<Button disabled={form.processing || !current}>
Guardar imputação
</Button>
</form>
</Panel>
)}
<Panel title="Histórico das imputações">
{props.history.data.length === 0 && (
<p>Ainda não há versões registadas.</p>
)}
{props.history.data.map((row) => (
<article className="border-b py-3" key={row.id}>
<h3 className="font-semibold">Versão {row.version}</h3>
<p>{row.reason}</p>
<ul>
{row.data.allocations.map((entry) => (
<li key={entry.category}>
{entry.category}:{' '}
{exactMinorAmount(
entry.amount_minor,
payment.currency,
)}
</li>
))}
</ul>
</article>
))}
<nav
className="mt-3 flex gap-4"
aria-label="Versões da imputação"
>
{props.history.prev_page_url && (
<Link href={props.history.prev_page_url}>Anterior</Link>
)}
{props.history.next_page_url && (
<Link href={props.history.next_page_url}>Seguinte</Link>
)}
</nav>
</Panel>
</div>
);
}
+11
View File
@@ -99,12 +99,14 @@ export default function Payments({
invoices,
payments,
canManage,
expenseAllocationsReady = false,
focusPaymentId = null,
focusInvoiceId = null,
}: {
invoices: Invoice[];
payments: Page<Payment>;
canManage: boolean;
expenseAllocationsReady?: boolean;
focusPaymentId?: number | null;
focusInvoiceId?: number | null;
}) {
@@ -383,6 +385,15 @@ export default function Payments({
</p>
)}
{p.canReview && <Review id={p.id} />}
{expenseAllocationsReady &&
p.status === 'confirmed' && (
<Link
className="mt-3 inline-block underline"
href={`/pagamentos/${p.id}/categorias`}
>
Imputação por categoria
</Link>
)}
</Panel>
</div>
))}
+92 -17
View File
@@ -60,7 +60,16 @@ type ComparisonRow = {
is_top: boolean;
weights: Record<string, number>;
};
type ReportOrder = {
id: number;
number: string;
currency: string;
total_minor: number;
agreement_limits?: Record<string, FrozenOrderAgreement>;
origins?: { id: number; number: string }[];
};
type Report = {
orders?: ReportOrder[];
agreement_limits?: Record<string, FrozenOrderAgreement>;
generated_at: string;
generated_by: string;
@@ -112,14 +121,10 @@ type Report = {
source_changed: boolean;
} | null;
award: { id: number; status: string; total_minor: number } | null;
order: {
id: number;
number: string;
currency: string;
total_minor: number;
} | null;
order: ReportOrder | null;
fulfilment: {
receipts: {
order_number?: string;
id: number;
received_on: string | null;
delivery_note: string;
@@ -129,6 +134,7 @@ type Report = {
| {
id: number;
number: string;
order_number?: string;
status: string;
issued_on: string;
total_minor: string;
@@ -704,17 +710,48 @@ export default function ReviewReport({
) : (
<p>Sem adjudicação registada.</p>
)}
{report.order ? (
<p>
Ordem {report.order.number} · Valor preservado:{' '}
{money(
report.order.total_minor,
report.order.currency,
{(report.orders ?? (report.order ? [report.order] : []))
.length === 0 && (
<p>Sem ordem visível nesta consulta.</p>
)}
{(
report.orders ??
(report.order ? [report.order] : [])
).map((order) => (
<p key={order.id}>
Ordem{' '}
<Link
className="underline"
href={`/ordens/${order.id}`}
>
{order.number}
</Link>{' '}
· Valor documental integral:{' '}
{money(order.total_minor, order.currency)}.
{(order.origins?.length ?? 0) > 1 && (
<span className="mt-1 block text-sm">
Requisições de origem:{' '}
{order.origins?.map((origin) => (
<Link
key={origin.id}
className="mr-3 underline"
href={`/requisicoes/${origin.id}`}
>
{origin.number}
</Link>
))}
</span>
)}
.
</p>
) : (
<p>Sem ordem emitida.</p>
))}
{report.orders?.some(
(order) => (order.origins?.length ?? 0) > 1,
) && (
<p>
As ordens consolidadas e os seus documentos
podem abranger outros pedidos. Os montantes são
integrais, sem repartição neste relatório.
</p>
)}
<p className="text-muted-foreground">
Valores de documentos emitidos ou da adjudicação são
@@ -723,9 +760,29 @@ export default function ReviewReport({
</p>
</div>
</Panel>
{report.orders ? (
report.orders.map(
(order) =>
Object.keys(order.agreement_limits || {}).length >
0 && (
<section
key={order.id}
aria-label={`Referências contratuais da ordem ${order.number}`}
>
<h3 className="mb-3 font-semibold">
Ordem {order.number}
</h3>
<AgreementOrderLimitSummary
bindings={order.agreement_limits}
/>
</section>
),
)
) : (
<AgreementOrderLimitSummary
bindings={report.agreement_limits}
/>
)}
<Panel
title="Recepção, facturas e registos de pagamento"
id="report-fulfilment"
@@ -735,7 +792,7 @@ export default function ReviewReport({
<section aria-label="Recepções do processo">
<h3 className="font-medium">Recepções</h3>
{report.fulfilment.receipts.length === 0 ? (
<p>Sem recepções registadas.</p>
<p>Sem recepções visíveis nesta consulta.</p>
) : (
<ul className="mt-2 space-y-2">
{report.fulfilment.receipts.map(
@@ -746,6 +803,13 @@ export default function ReviewReport({
? date(receipt.received_on)
: 'Data por indicar'}{' '}
· Guia: {receipt.delivery_note}.{' '}
{receipt.order_number && (
<>
Ordem{' '}
{receipt.order_number}
.{' '}
</>
)}
<Link
className="underline print:hidden"
href={`/recepcoes/${receipt.id}`}
@@ -768,13 +832,24 @@ export default function ReviewReport({
<section aria-label="Facturas do processo">
<h3 className="font-medium">Facturas</h3>
{!report.fulfilment.invoices?.length ? (
<p>Sem facturas registadas.</p>
<p>
Sem facturas visíveis nesta
consulta.
</p>
) : (
<ul className="mt-2 space-y-2">
{report.fulfilment.invoices.map(
(invoice) => (
<li key={invoice.id}>
Factura {invoice.number}{' '}
{invoice.order_number && (
<>
· Ordem{' '}
{
invoice.order_number
}{' '}
</>
)}
·{' '}
{date(
invoice.issued_on,
@@ -1,4 +1,12 @@
import { Head, Link, useForm } from '@inertiajs/react';
import {
ProcurementDeliveryInsights,
type DeliveryInsights,
} from '@/components/procurement-delivery-insights';
import {
ProcurementContractInsights,
type ContractInsights,
} from '@/components/procurement-contract-insights';
import {
ProcurementPaymentInsights,
type PaymentInsights,
@@ -41,6 +49,10 @@ type Filters = {
from?: string;
to?: string;
department_id?: string | number;
supplier_page?: number;
category_page?: number;
delivery_page?: number;
delivery_state?: string;
};
const estimate = (minor: string | null) => {
if (minor === null) return 'Por completar';
@@ -56,6 +68,8 @@ export default function ProcurementReports({
insights,
payableInsights,
paymentInsights,
contractInsights,
deliveryInsights,
}: {
records: {
data: Row[];
@@ -72,6 +86,8 @@ export default function ProcurementReports({
insights?: ProcurementInsights;
payableInsights?: PayableInsights | null;
paymentInsights?: PaymentInsights | null;
contractInsights?: ContractInsights;
deliveryInsights?: DeliveryInsights;
}) {
const form = useForm({
search: filters.search ?? '',
@@ -122,10 +138,24 @@ export default function ProcurementReports({
exportHref={`/relatorios/obrigacoes.csv?${params}`}
/>
)}
{deliveryInsights && (
<ProcurementDeliveryInsights
data={deliveryInsights}
pageHref={`/relatorios?${params}`}
exportHref={`/relatorios/entregas.csv?${params}`}
/>
)}
{paymentInsights && (
<ProcurementPaymentInsights
data={paymentInsights}
exportHref={`/relatorios/despesa.csv?${params}`}
pageHref={`/relatorios?${params}`}
/>
)}
{contractInsights && (
<ProcurementContractInsights
data={contractInsights}
exportHref={`/relatorios/contratos.csv?${params}`}
/>
)}
<Panel
+5
View File
@@ -13,6 +13,7 @@ use App\Http\Controllers\CompanyController;
use App\Http\Controllers\ConflictDeclarationController;
use App\Http\Controllers\DocumentaryQualificationController;
use App\Http\Controllers\EquipmentController;
use App\Http\Controllers\ExpenseAllocationController;
use App\Http\Controllers\ExternalPaymentController;
use App\Http\Controllers\FormalAdmissionController;
use App\Http\Controllers\FormalRecommendationController;
@@ -263,6 +264,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::post('requisicoes/{requisition}/taxas-cambio', [QuotationController::class, 'recordExchange'])->whereNumber('requisition');
Route::get('requisicoes/{requisition}/historico.csv', [RequisitionAuditController::class, 'csv'])->whereNumber('requisition')->name('requisitions.audit.csv');
Route::get('relatorios', [ProcurementReportController::class, 'index'])->name('reports.index');
Route::get('relatorios/contratos.csv', [ProcurementReportController::class, 'exportContracts'])->name('reports.contracts');
Route::get('relatorios/entregas.csv', [ProcurementReportController::class, 'exportDeliveries'])->name('reports.deliveries');
Route::get('relatorios/compras.csv', [ProcurementReportController::class, 'export'])->name('reports.export');
Route::get('relatorios/obrigacoes.csv', [ProcurementReportController::class, 'exportPositions'])->name('reports.positions');
Route::get('relatorios/despesa.csv', [ProcurementReportController::class, 'exportPayments'])->name('reports.payments');
@@ -293,6 +296,8 @@ Route::middleware(['auth', 'verified', EnsureOrganizationAccess::class])->group(
Route::get('pagamentos', [ExternalPaymentController::class, 'index'])->name('payments.index');
Route::post('facturas/{invoice}/pagamentos', [ExternalPaymentController::class, 'store'])->name('payments.store');
Route::post('pagamentos/{payment}/conferir', [ExternalPaymentController::class, 'review'])->name('payments.review');
Route::get('pagamentos/{payment}/categorias', [ExpenseAllocationController::class, 'show'])->name('payments.expense-allocation');
Route::post('pagamentos/{payment}/categorias', [ExpenseAllocationController::class, 'store'])->name('payments.expense-allocation.store');
Route::get('fornecedores/{supplier}/dados-bancarios', [SupplierBankController::class, 'show'])->name('suppliers.bank');
Route::post('fornecedores/{supplier}/dados-bancarios', [SupplierBankController::class, 'store'])->name('suppliers.bank.store');
Route::post('fornecedores/{supplier}/dados-bancarios/{detail}/validar', [SupplierBankController::class, 'review'])->name('suppliers.bank.review');
@@ -0,0 +1,81 @@
<?php
// Private review bundle only: no installed package, application configuration or database is changed.
$root = dirname(__DIR__);
$financial = realpath('C:/laragon/www/sgf-tempo/packages/budget-control');
if ($financial === false || str_replace('\\', '/', $financial) !== 'C:/laragon/www/sgf-tempo/packages/budget-control') {
throw new LogicException('Canonical financial source mismatch.');
}
$budgetFiles = ['bootstrap.php', 'README.md', 'src/BudgetContext.php', 'src/BudgetFailure.php', 'src/BudgetControl.php',
'src/BudgetDistributionPlan.php', 'src/BudgetDistributions.php', 'src/BudgetOrderParts.php', 'src/BudgetLandedCosts.php',
'src/BudgetLandedCostPlan.php', 'src/BudgetImportEstimate.php', 'src/BudgetRequisitionCycles.php'];
$purchasingFiles = ['bootstrap.php', 'README.md', 'module.json', 'src/ReplenishmentProjection.php', 'src/QuotationPricing.php',
'src/ProposalScoring.php', 'src/RequisitionPort.php', 'src/ExpiryRequisitionPort.php', 'src/RequisitionFailure.php', 'src/InternalRequisitions.php', 'src/Sourcing.php'];
$sources = [];
foreach (['budget-control' => [$financial, $budgetFiles], 'purchasing' => [$root.'/packages/purchasing', $purchasingFiles]] as $package => [$directory, $files]) {
foreach ($files as $file) {
$sources[$package.'/'.$file] = $directory.'/'.$file;
}
}
$schema = 'database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php';
$sources[$schema] = $root.'/'.$schema;
$hashes = [];
foreach ($sources as $name => $source) {
if (! is_file($source) || is_link($source)) {
throw new RuntimeException('Missing canonical bundle file: '.$name);
}
$hashes[$name] = hash_file('sha256', $source);
}
$fingerprint = hash('sha256', json_encode($hashes, JSON_THROW_ON_ERROR));
$relative = 'storage/framework/testing/requisition-cycles-qa-'.substr($fingerprint, 0, 16);
$target = $root.'/'.$relative;
foreach ($sources as $name => $source) {
$destination = $target.'/'.$name;
if (! is_dir(dirname($destination)) && ! mkdir(dirname($destination), 0700, true)) {
throw new RuntimeException('Unable to create private cycle bundle.');
}
if (is_link($destination) || (is_file($destination) && hash_file('sha256', $destination) !== $hashes[$name])) {
throw new RuntimeException('Frozen cycle bundle differs; no file overwritten.');
}
if (! is_file($destination) && ! copy($source, $destination)) {
throw new RuntimeException('Cycle bundle copy failed.');
}
if (hash_file('sha256', $destination) !== $hashes[$name]) {
throw new RuntimeException('Cycle bundle verification failed.');
}
}
$manifest = ['contract' => 'COMMON-BUDGET-REQUISITION-CYCLES-QA-v1', 'status' => 'private_qa_not_installed', 'files' => $hashes];
$bytes = json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
if (is_file($target.'/manifest.json') && file_get_contents($target.'/manifest.json') !== $bytes) {
throw new RuntimeException('Frozen cycle manifest differs.');
}
file_put_contents($target.'/manifest.json', $bytes);
$archive = $target.'.zip';
if (! is_file($archive)) {
$zip = new ZipArchive;
if ($zip->open($archive, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
throw new RuntimeException('Unable to create private cycle archive.');
}
foreach ($sources as $name => $source) {
$zip->addFile($target.'/'.$name, $name);
}
$zip->addFile($target.'/manifest.json', 'manifest.json');
$zip->close();
}
$zip = new ZipArchive;
if ($zip->open($archive) !== true || $zip->numFiles !== count($sources) + 1 || $zip->getFromName('manifest.json') !== $bytes) {
throw new RuntimeException('Cycle archive inventory mismatch.');
}
foreach ($hashes as $name => $hash) {
if (hash('sha256', $zip->getFromName($name)) !== $hash) {
throw new RuntimeException('Cycle archive byte mismatch.');
}
}
$zip->close();
$proof = ['date' => '2026-11-27', 'status' => 'private_qa_prepared_not_installed', 'path' => $relative,
'manifest_sha256' => hash('sha256', $bytes), 'archive' => $relative.'.zip', 'archive_sha256' => hash_file('sha256', $archive),
'canonical_fingerprint' => $fingerprint, 'files' => $hashes, 'independent_financial_load_test' => 'pending',
'installed_packages_changed' => false, 'pilot_or_sgf_activation' => false];
file_put_contents($root.'/docs/proofs/requisition-expiry-artifact.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode(['private_cycle_bundle_prepared' => true, 'path' => $relative, 'files' => count($sources),
'manifest_sha256' => $proof['manifest_sha256'], 'archive_sha256' => $proof['archive_sha256']], JSON_THROW_ON_ERROR).PHP_EOL;
+54 -3
View File
@@ -105,6 +105,27 @@ try {
if (in_array('--requisition-cycles-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php']];
}
if (in_array('--requisition-cycles-artifact', $argv, true)) {
$artifact = json_decode(file_get_contents(base_path('docs/proofs/requisition-expiry-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
if (! preg_match('~^storage/framework/testing/requisition-cycles-qa-[a-f0-9]{16}$~D', $artifact['path'] ?? '')
|| hash_file('sha256', base_path($artifact['path'].'/manifest.json')) !== $artifact['manifest_sha256']) {
throw new LogicException('Invalid private cycle artifact manifest.');
}
$manifest = json_decode(file_get_contents(base_path($artifact['path'].'/manifest.json')), true, 32, JSON_THROW_ON_ERROR);
if ($manifest['files'] !== $artifact['files'] || count($manifest['files']) !== 24) {
throw new LogicException('Private cycle artifact inventory mismatch.');
}
foreach ($manifest['files'] as $name => $hash) {
$resolved = realpath(base_path($artifact['path'].'/'.$name));
$boundary = realpath(base_path($artifact['path']));
if ($resolved === false || $boundary === false || ! str_starts_with($resolved, $boundary.DIRECTORY_SEPARATOR)
|| is_link(base_path($artifact['path'].'/'.$name)) || hash_file('sha256', $resolved) !== $hash) {
throw new LogicException('Private cycle artifact byte mismatch.');
}
}
$environment['COMMON_BUDGET_PATH'] = base_path($artifact['path'].'/budget-control');
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php']];
}
if (in_array('--requisition-cycles-regression', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php',
'tests/Feature/InternalRequisitionCandidateTest.php', 'tests/Feature/BudgetTest.php']];
@@ -116,6 +137,36 @@ try {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php',
'--filter=award starts a new approval cycle|distributed approved synthetic|native partial-order issuance|native partial-order receipts|native consolidated order retains|native partial-order cancellation']];
}
if (in_array('--consolidated-report-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/ProcurementPayableInsightsTest.php',
'--filter=native consolidated order retains|financial insights|divergent native position|native imported history|payment period follows|read composition rejects']];
}
if (in_array('--contract-report-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php', 'tests/Feature/ProcurementReportsTest.php',
'--filter=per order global contract sums|award starts a new approval cycle|contract report preserves']];
}
if (in_array('--multi-order-review-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php',
'--filter=native partial-order receipts and independent invoice|native consolidated order retains']];
}
if (in_array('--delivery-analysis-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php',
'--filter=native delivery analysis|native consolidated order retains']];
}
if (in_array('--expense-allocation-focused', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ExpenseAllocationsTest.php', 'tests/Feature/ProcurementPayableInsightsTest.php']];
}
if (in_array('--expense-native-regression', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ReceiptFixtureConsistencyTest.php', 'tests/Feature/ReceiptStockTest.php', 'tests/Feature/InvoiceTest.php', 'tests/Feature/ExternalPaymentTest.php', 'tests/Feature/InventoryReversalsTest.php']];
}
if (in_array('--expense-allocation-concurrency', $argv, true)) {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/expense-allocation-worker.php', $database, 'race-expense']];
}
if (in_array('--expense-allocation-recovery', $argv, true)) {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/requisition-cycle-recovery-worker.php', $database, 'recover-expenses']];
}
if (in_array('--requisition-cycles-orders', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/PurchaseAwardOrderTest.php',
'--filter=native partial-order issuance commits only forty']];
@@ -160,7 +211,7 @@ try {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/import-legal-corpus-worker.php', $database, 'corpus', substr($corpusArguments[0], strlen('--legal-corpus-root='))]];
}
if (in_array('--legal-http', $argv, true) || in_array('--legal-native-review', $argv, true)) {
if (in_array('--legal-http', $argv, true) || in_array('--legal-native-review', $argv, true) || in_array('--expiry-native-review', $argv, true)) {
$values = [];
foreach (['--legal-corpus-root=', '--legal-http-candidate=', '--legal-http-manifest='] as $prefix) {
$matches = array_values(array_filter($argv, fn ($value) => str_starts_with($value, $prefix)));
@@ -170,7 +221,7 @@ try {
$values[] = substr($matches[0], strlen($prefix));
}
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/import-legal-http-worker.php', $database, in_array('--legal-native-review', $argv, true) ? 'legal-review' : 'legal-http', ...$values]];
[PHP_BINARY, 'tests/Concurrency/import-legal-http-worker.php', $database, in_array('--expiry-native-review', $argv, true) ? 'expiry-review' : (in_array('--legal-native-review', $argv, true) ? 'legal-review' : 'legal-http'), ...$values]];
}
if (in_array('--bank-support-native-only', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/ImportBankSupportTest.php']];
@@ -318,7 +369,7 @@ try {
throw new LogicException('Each Pest kernel must use its own disposable PostgreSQL database.');
}
foreach ($commands as $command) {
$nativeReview = ($command[3] ?? '') === 'legal-review';
$nativeReview = in_array($command[3] ?? '', ['legal-review', 'expiry-review'], true);
$process = new Process($command, dirname(__DIR__), $environment, timeout: $nativeReview ? 3660 : 180);
$process->run($nativeReview ? function ($type, $buffer) {
echo $buffer;
@@ -0,0 +1,118 @@
<?php
use App\Models\User;
use App\Services\ExpenseAllocations;
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;
require __DIR__.'/../../vendor/autoload.php';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$database = $argv[1] ?? '';
$mode = $argv[2] ?? '';
$db = DB::connection();
if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->getDatabaseName() !== $database
|| $db->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
throw new LogicException('Expense contention requires disposable local PostgreSQL QA.');
}
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'explicit-expense-qa', 'expense-allocations.qa_enabled' => true]);
require_once __DIR__.'/../Support/ExpenseAllocationQaFixture.php';
$financial = static function () use ($db): string {
$rows = [];
foreach (['external_payments', 'invoices', 'invoice_items', 'budget_entries', 'stock_movements', 'pa_commands'] as $table) {
$rows[$table] = $db->table($table)->orderBy('id')->get()->toJson();
}
return hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
};
if ($mode === 'prepare') {
$fixture = expenseAllocationQaFixture();
$f = $fixture['f'];
if (($argv[3] ?? '') === 'same_version') {
$record = app(ExpenseAllocations::class)->save($f['validator'], $fixture['payment']->id, $fixture['input']);
$fixture['input']['version'] = $record->version;
$fixture['input']['operation_key'] = (string) Str::uuid();
}
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['validator']->id, 'alternate' => $f['author']->id,
'payment' => $fixture['payment']->id, 'input' => $fixture['input'], 'financial_fingerprint' => $financial(),
'records_before' => $db->table('supply_records')->where('tenant_id', $f['tenant']->id)->where('kind', 'expense_allocation')->count(),
'audits_before' => $db->table('audit_logs')->where('tenant_id', $f['tenant']->id)->where('action', 'expense.allocation_recorded')->count()], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'write') {
$input = json_decode($argv[3], true, 32, JSON_THROW_ON_ERROR);
$db->select('select set_config(?, ?, false)', ['application_name', 'sgc_expense_write_'.getmypid()]);
$actor = User::query()->findOrFail($input['actor']);
auth()->guard()->setUser($actor);
try {
app(ExpenseAllocations::class)->save($actor, $input['payment'], $input['input']);
echo json_encode(['status' => 200]);
} catch (HttpExceptionInterface $error) {
echo json_encode(['status' => $error->getStatusCode()]);
}
exit;
}
if ($mode !== 'race-expense') {
throw new InvalidArgumentException('Unknown expense contention mode.');
}
foreach (['same_operation', 'same_version'] as $scenario) {
$prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare', $scenario], dirname(__DIR__, 2), timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
$db->beginTransaction();
try {
$db->table('tenants')->where('id', $input['tenant'])->lockForUpdate()->firstOrFail();
for ($index = 0; $index < 2; $index++) {
$payload = $input;
if ($scenario === 'same_version' && $index === 1) {
$payload['actor'] = $input['alternate'];
$payload['input']['operation_key'] = (string) Str::uuid();
}
$worker = new Process([PHP_BINARY, __FILE__, $database, 'write', json_encode($payload, JSON_THROW_ON_ERROR)], dirname(__DIR__, 2), timeout: 30);
$workers[] = $worker;
$worker->start();
}
$deadline = microtime(true) + 10;
do {
$db->select('select pg_stat_clear_snapshot()');
$blocked = (int) $db->selectOne("select count(*) as n from pg_stat_activity where datname=? and application_name like 'sgc_expense_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 Finance writers must demonstrably wait on the company lock.');
}
$db->commit();
$statuses = [];
foreach ($workers as $worker) {
$worker->wait();
if (! $worker->isSuccessful()) {
throw new RuntimeException($worker->getErrorOutput());
}
$statuses[] = json_decode($worker->getOutput(), true, 32, JSON_THROW_ON_ERROR)['status'];
}
sort($statuses);
$records = $db->table('supply_records')->where('tenant_id', $input['tenant'])->where('kind', 'expense_allocation')->count() - $input['records_before'];
$audits = $db->table('audit_logs')->where('tenant_id', $input['tenant'])->where('action', 'expense.allocation_recorded')->count() - $input['audits_before'];
if ($statuses !== ($scenario === 'same_operation' ? [200, 200] : [200, 409]) || $records !== 1 || $audits !== 1 || $financial() !== $input['financial_fingerprint']) {
throw new RuntimeException('Expense contention must retain one attribution/audit and unchanged native financial sources.');
}
echo json_encode(['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => $blocked,
'expense_versions_created' => $records, 'audits' => $audits, 'financial_sources_unchanged' => true], JSON_THROW_ON_ERROR).PHP_EOL;
} finally {
if ($db->transactionLevel() > 0) {
$db->rollBack();
}
foreach ($workers as $worker) {
if ($worker->isRunning()) {
$worker->stop();
}
}
}
}
+21 -1
View File
@@ -28,7 +28,8 @@ $database = $argv[1] ?? '';
$corpus = realpath($argv[3] ?? '');
$candidateRelative = $argv[4] ?? '';
$candidateHash = $argv[5] ?? '';
$reviewMode = ($argv[2] ?? '') === 'legal-review';
$expiryReview = ($argv[2] ?? '') === 'expiry-review';
$reviewMode = ($argv[2] ?? '') === 'legal-review' || $expiryReview;
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|| DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)
|| $corpus === false || ! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative)
@@ -180,9 +181,28 @@ try {
'jurisdiction' => 'Âmbito fictício QA', 'origin_country' => 'Synthetic A', 'dispatch_country' => 'Synthetic B', 'regime' => 'Regime fictício QA']));
$bank = importBankQaFixture($reviewer, $import);
app(ImportBankSupport::class)->save($reviewer, $import, $bank['input']);
$expiryRequest = null;
if ($expiryReview) {
(require __DIR__.'/../../database/qa-migrations/2026_11_27_000001_add_requisition_cycles.php')->up();
config(['requisition-expiry.qa_enabled' => true]);
supplyGrant($reviewer, ['admin', 'procurement', 'requester', 'import_read', 'import_prepare', 'import_customs']);
$head = User::factory()->create(['tenant_id' => $f['tenant']->id, 'department_id' => $f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
supplyGrant($head, ['department_head']);
app(\App\Services\RequisitionExpiry::class)->savePolicy($reviewer, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => [['role' => 'department_head', 'expire_minutes' => 30, 'reminder_minutes' => 10, 'escalation_minutes' => null, 'profile_ids' => []]],
'reason' => 'Política estritamente sintética para revisão visual do ciclo']);
$workflow = app(\App\Services\RequisitionWorkflow::class);
$expiryRequest = $workflow->save($reviewer, ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['r']->cost_center_id, 'priority' => 'normal',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Ensaio visual sintético da devolução e nova submissão',
'items' => [['description' => 'Material sintético do ciclo', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]);
$workflow->submit($reviewer, $expiryRequest, (string) Str::uuid(), $expiryRequest->process_version);
// Explicit synthetic clock fixture: no existing request or real timestamp is rewritten.
$expiryRequest->update(['submitted_at' => now()->subMinutes(31)]);
}
$stopFile = $directory.'/stop';
echo json_encode(['private_review_running' => true, 'url' => $url, 'stop_file' => $stopFile,
'synthetic_user' => $reviewer->email, 'draft_request' => $draftRequest->id, 'import' => $import->id,
'expiry_request' => $expiryRequest?->id, 'expiry_url' => $expiryRequest === null ? null : $url.'/requisicoes/'.$expiryRequest->id.'/prazos',
'legal_url' => $url.'/requisicoes/'.$draftRequest->id.'/base-legal?'.http_build_query(['code' => '1234', 'origin' => 'Synthetic A', 'sector' => 'Synthetic sector', 'date' => '2026-11-27']),
'private_candidate_manifest' => $candidateHash, 'pilot_assets_changed' => false], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR).PHP_EOL;
$deadline = microtime(true) + 3600;
@@ -2,6 +2,7 @@
use App\Models\Requisition;
use App\Models\User;
use App\Services\ExpenseAllocations;
use App\Services\RequisitionWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Connection;
@@ -21,6 +22,7 @@ if (! $app->environment('testing') || $db->getDriverName() !== 'pgsql' || $db->g
throw new LogicException('Cycle recovery requires disposable local PostgreSQL QA.');
}
config(['requisition-expiry.qa_enabled' => true]);
$expenses = ($argv[2] ?? '') === 'recover-expenses';
require_once __DIR__.'/../Support/ReceiptFixture.php';
receiptFixture();
$fingerprint = static function (Connection $connection): array {
@@ -66,6 +68,16 @@ $request = $workflow->save($owner, ['operation_key' => (string) Str::uuid(), 'pr
$submission = (string) Str::uuid();
$version = $request->process_version;
$workflow->submit($owner, $request, $submission, $version);
$expenseFixture = $expenseInput = null;
if ($expenses) {
require_once __DIR__.'/../Support/ExpenseAllocationQaFixture.php';
$expenseFixture = expenseAllocationQaFixture();
$expenseService = app(ExpenseAllocations::class);
$firstExpense = $expenseService->save($expenseFixture['f']['validator'], $expenseFixture['payment']->id, $expenseFixture['input']);
$expenseInput = [...$expenseFixture['input'], 'operation_key' => (string) Str::uuid(), 'version' => $firstExpense->version,
'allocations' => [['category' => 'Material', 'amount' => '10.00'], ['category' => 'Serviços', 'amount' => '30.00']]];
$expenseService->save($expenseFixture['f']['validator'], $expenseFixture['payment']->id, $expenseInput);
}
$after = $fingerprint($db);
$pg('pg_dump', ['--format=custom', '--file='.$postDump, '--dbname='.$database]);
$restore = 'compras_receipts_test_'.bin2hex(random_bytes(6));
@@ -93,6 +105,21 @@ try {
|| $restored->table('approval_steps')->where('requisition_id', $request->id)->where('decision', 'expired')->count() !== 1) {
throw new RuntimeException('Restored native expiry/submission replay changed history or reservation.');
}
if ($expenses) {
$expenseActor = User::query()->whereKey($expenseFixture['f']['validator']->id)->firstOrFail();
auth()->guard()->setUser($expenseActor);
$expenseService = app(ExpenseAllocations::class);
$paymentId = $expenseFixture['payment']->id;
$projection = $expenseService->projection($expenseActor, $paymentId);
$replay = $expenseService->save($expenseActor, $paymentId, $expenseInput);
if ($replay->version !== 2 || $projection['state'] !== 'allocated'
|| $projection['allocations'] !== [['category' => 'Material', 'amount_minor' => '1000'], ['category' => 'Serviços', 'amount_minor' => '3000']]
|| $fingerprint($restored) !== $after) {
throw new RuntimeException('Explicit expense versions, audited sources or replay changed after restore.');
}
echo json_encode(['expense_versions_restored' => 2, 'expense_native_sources_verified' => true,
'expense_explicit_amounts_restored' => ['Material' => '1000', 'Serviços' => '3000'], 'expense_replay_without_effects' => true], JSON_THROW_ON_ERROR).PHP_EOL;
}
DB::setDefaultConnection($originalDefault);
DB::purge('cycle_recovery_restore');
$admin->statement('DROP DATABASE "'.$restore.'" WITH (FORCE)');
+24 -1
View File
@@ -35,6 +35,29 @@ if ($mode === 'scheduled-cycle') {
if (auth()->check() || request()->hasSession()) {
throw new RuntimeException('Scheduled proof must run without an authenticated session.');
}
$scope = app(RequisitionExpiryRun::class);
$denied = 0;
foreach (['foreign_origin', 'budget_create', 'submit'] as $action) {
try {
$scope->execute($input['request'], function () use ($input, $action) {
$actor = User::query()->findOrFail($input['owner']);
if ($action === 'foreign_origin') {
app(CommonBudget::class)->for($actor, [$input['request'] + 999999 => 1]);
} elseif ($action === 'budget_create') {
app(CommonBudget::class)->for($actor, [$input['request'] => 1])->create([]);
} else {
$request = Requisition::query()->findOrFail($input['request']);
app(RequisitionWorkflow::class)->submit($actor, $request, (string) Str::uuid(), $request->process_version);
}
});
throw new RuntimeException('Scheduled scope unexpectedly allowed '.$action);
} catch (HttpExceptionInterface $error) {
if ($error->getStatusCode() !== 403 || $scope->tenantId() !== null) {
throw $error;
}
$denied++;
}
}
if (Artisan::call('sgc:approval-deadlines-tick') !== 0) {
throw new RuntimeException('Scheduled deadline tick failed: '.Artisan::output());
}
@@ -53,7 +76,7 @@ if ($mode === 'scheduled-cycle') {
throw new RuntimeException('Scheduled audit must distinguish automatic execution from an interactive act.');
}
echo json_encode(['scheduled_expiry_without_session' => true, 'scheduled_scope_closed' => true, 'scheduled_repeat_without_effects' => true,
'scheduled_audit_explicit' => true], JSON_THROW_ON_ERROR);
'scheduled_audit_explicit' => true, 'scheduled_unrelated_operations_denied' => $denied], JSON_THROW_ON_ERROR);
exit;
}
if ($mode === 'legacy-cycles') {
+136
View File
@@ -0,0 +1,136 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\ExpenseAllocations;
use App\Services\ExternalPaymentWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/PaymentFixture.php';
afterEach(function () {
if ($this->committedExpenseReportFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Expense report cleanup requires the disposable local PostgreSQL database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
beforeEach(function () {
$this->f = paymentFixture(['Material', 'Serviços']);
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'explicit-expense-qa', 'expense-allocations.qa_enabled' => true]);
foreach ([$this->f['author'], $this->f['validator']] as $actor) {
DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $actor->id,
'person' => 'expense-qa-'.$actor->id, 'action' => 'view']);
}
$this->actingAs($this->f['author']);
$this->payment = app(ExternalPaymentWorkflow::class)->register($this->f['author'], $this->f['invoice'], $this->f['payment_data']);
$this->actingAs($this->f['validator']);
app(ExternalPaymentWorkflow::class)->review($this->f['validator'], $this->payment, 'confirmed', 'Conferência de evidência estritamente sintética');
$this->service = app(ExpenseAllocations::class);
$this->source = $this->service->source($this->f['validator'], $this->payment->id);
$this->input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $this->source['fingerprint'],
'reason' => 'Imputação explícita de Finanças no ensaio sintético',
'allocations' => [['category' => 'Material', 'amount' => '15.00'], ['category' => 'Serviços', 'amount' => '25.00']]];
});
test('Finance explicitly attributes a partial confirmed payment and replays without changing any financial source', function () {
$this->withoutVite();
$before = [];
foreach (['external_payments', 'invoices', 'invoice_items', 'budget_entries', 'stock_movements', 'pa_commands'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
expect($this->source['categories'])->toBe(['Material', 'Serviços'])
->and($this->service->projection($this->f['validator'], $this->payment->id)['state'])->toBe('unallocated');
$url = '/pagamentos/'.$this->payment->id.'/categorias';
$this->postJson($url, $this->input)->assertRedirect();
$this->postJson($url, $this->input)->assertRedirect();
$current = $this->service->current($this->payment->id);
expect($current->data['allocations'])->toBe([['category' => 'Material', 'amount_minor' => '1500'], ['category' => 'Serviços', 'amount_minor' => '2500']])
->and(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(1)
->and(DB::table('audit_logs')->where('action', 'expense.allocation_recorded')->count())->toBe(1);
$this->get($url)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn (Assert $page) => $page
->component('payments/expense-allocation')->where('canWrite', true)->where('payment.amount_minor', '4000')
->where('current.version', 1)->has('history.data', 1)->missing('payment.bank_snapshot')->missing('payment.external_reference')
->missing('current.snapshot')->missing('current.operation_key')->missing('history.data.0.snapshot'));
foreach ($before as $table => $rows) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($rows);
}
if (DB::getDriverName() === 'pgsql') {
if (DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Commit only the disposable expense report fixture.');
}
DB::commit();
$this->committedExpenseReportFixture = true;
}
$this->get('/relatorios')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('paymentInsights.currencies.0.amount_minor', '4000')->where('paymentInsights.category_attribution.coverage.allocated', 1)
->where('paymentInsights.category_attribution.groups.data.0.amount_minor', '1500')
->where('paymentInsights.category_attribution.groups.data.1.amount_minor', '2500')->has('paymentInsights.category_attribution.unassigned', 0));
$csv = $this->get('/relatorios/despesa.csv')->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain('Material;MZN;1;1500')->toContain('Serviços;MZN;1;2500');
});
test('allocation rejects incorrect totals foreign categories stale sources and reused operations while retaining previous versions', function () {
$actor = $this->f['validator'];
$bad = $this->input;
$bad['allocations'][0]['amount'] = '14.99';
expect(fn () => $this->service->save($actor, $this->payment->id, $bad))->toThrow(ValidationException::class);
$bad = $this->input;
$bad['allocations'][0]['category'] = 'Categoria alheia';
expect(fn () => $this->service->save($actor, $this->payment->id, $bad))->toThrow(ValidationException::class);
$bad = [...$this->input, 'fingerprint' => str_repeat('0', 64)];
expect(fn () => $this->service->save($actor, $this->payment->id, $bad))->toThrow(HttpException::class);
$first = $this->service->save($actor, $this->payment->id, $this->input);
$before = $first->fresh()->toArray();
$next = [...$this->input, 'operation_key' => (string) Str::uuid(), 'version' => 1,
'allocations' => [['category' => 'Material', 'amount' => '10.00'], ['category' => 'Serviços', 'amount' => '30.00']]];
$second = $this->service->save($actor, $this->payment->id, $next);
expect($second->version)->toBe(2)->and($first->fresh()->toArray())->toBe($before)
->and($this->service->projection($actor, $this->payment->id)['allocations'][0]['amount_minor'])->toBe('1000');
expect(fn () => $this->service->save($actor, $this->payment->id, [...$next, 'operation_key' => (string) Str::uuid()]))->toThrow(HttpException::class);
expect(fn () => $this->service->save($actor, $this->payment->id, [...$this->input, 'reason' => 'Outro conteúdo com a mesma operação']))->toThrow(HttpException::class);
});
test('allocation enforces current Finance access and refuses unavailable or unaudited payment sources', function () {
$actor = $this->f['validator'];
$this->actingAs($this->f['issuer']);
expect(fn () => $this->service->save($this->f['issuer'], $this->payment->id, $this->input))->toThrow(HttpException::class);
$this->actingAs($actor);
DB::table('pa_access')->where('user_id', $actor->id)->delete();
expect(fn () => $this->service->save($actor, $this->payment->id, $this->input))->toThrow(HttpException::class);
expect(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(0);
});
test('incomplete confirmation or missing allocation audit keeps analytical attribution indeterminate', function () {
$actor = $this->f['validator'];
$this->service->save($actor, $this->payment->id, $this->input);
expect($this->service->projection($actor, $this->payment->id)['state'])->toBe('allocated');
DB::table('audit_logs')->where('action', 'expense.allocation_recorded')->delete();
expect($this->service->projection($actor, $this->payment->id)['state'])->toBe('indeterminate');
DB::table('external_payments')->where('id', $this->payment->id)->update(['reviewed_at' => null]);
expect(fn () => $this->service->source($actor, $this->payment->id))->toThrow(HttpException::class);
config(['expense-allocations.qa_enabled' => false]);
expect(fn () => $this->service->save($actor, $this->payment->id, $this->input))->toThrow(HttpException::class);
});
test('administrative read access does not grant Finance attribution and foreign payment identity stays private', function () {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
DB::table('pa_access')->insert(['tenant_id' => $admin->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $admin->id,
'person' => 'expense-admin-qa', 'action' => 'view']);
$this->actingAs($admin);
expect($this->service->workspace($admin, $this->payment->id)['canWrite'])->toBeFalse();
expect(fn () => $this->service->save($admin, $this->payment->id, $this->input))->toThrow(HttpException::class);
require_once __DIR__.'/../Support/ExpenseAllocationQaFixture.php';
$foreign = expenseAllocationQaFixture();
$this->actingAs($this->f['validator']);
$this->getJson('/pagamentos/'.$foreign['payment']->id.'/categorias')->assertNotFound();
});
@@ -1,9 +1,12 @@
<?php
use App\Models\PurchaseAward;
use App\Models\Quotation;
use App\Models\Requisition;
use App\Services\ExternalPaymentWorkflow;
use App\Services\ProcurementPayableInsights;
use App\Services\ProcurementPaymentInsights;
use App\Services\SupplierBankWorkflow;
use App\Services\SupplierPayables;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -12,6 +15,65 @@ use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/PaymentFixture.php';
test('supplier payment groups paginate independently while the export projection retains every group', function () {
$f = $this->f;
$this->actingAs($f['validator']);
// Synthetic invoice chains for read coverage; payment originals use the native registration/review workflow.
$originalAward = PurchaseAward::query()->findOrFail($f['order']->purchase_award_id);
$originalQuote = Quotation::query()->findOrFail($originalAward->quotation_id);
foreach (range(1, 21) as $index) {
$request = $f['r']->replicate();
$request->fill(['number' => 'SYNTHETIC-GROUP-'.$index])->save();
$supplier = $f['supplier']->replicate();
$supplier->fill(['name' => $index === 21 ? '=1+1' : 'Synthetic supplier '.$index, 'nuit' => (string) (500000000 + $index)])->save();
$quote = $originalQuote->replicate();
$quote->fill(['requisition_id' => $request->id, 'supplier_id' => $supplier->id, 'reference' => 'SYNTHETIC-GROUP-'.$index])->save();
$award = $originalAward->replicate();
$award->fill(['requisition_id' => $request->id, 'quotation_id' => $quote->id])->save();
$order = $f['order']->replicate();
$order->fill(['requisition_id' => $request->id, 'supplier_id' => $supplier->id, 'purchase_award_id' => $award->id, 'number' => 'SYNTHETIC-GROUP-'.$index,
'snapshot' => [...$f['order']->snapshot, 'supplier' => $supplier->only(['name', 'nuit'])]])->save();
$invoice = $f['invoice']->fresh()->replicate();
$invoice->fill(['supplier_id' => $supplier->id, 'purchase_order_id' => $order->id, 'number' => 'SYNTHETIC-GROUP-'.$index,
'snapshot' => [...$f['invoice']->snapshot, 'supplier' => $supplier->only(['name', 'nuit']), 'order_number' => $order->number]])->save();
$this->actingAs($f['issuer']);
$bank = app(SupplierBankWorkflow::class)->propose($f['issuer'], $supplier,
[...$f['bank_data'], 'account_identifier' => 'SYNTHETIC-GROUP-'.$index]);
foreach ([$f['author'], $f['validator']] as $reviewer) {
$this->actingAs($reviewer);
app(SupplierBankWorkflow::class)->review($reviewer, $bank, 'approved', 'Independent synthetic account review');
}
$this->actingAs($f['author']);
$payment = app(ExternalPaymentWorkflow::class)->register($f['author'], $invoice,
[...$f['payment_data'], 'supplier_bank_detail_id' => $bank->id, 'external_reference' => 'SYNTHETIC-GROUP-'.$index]);
$this->actingAs($f['validator']);
app(ExternalPaymentWorkflow::class)->review($f['validator'], $payment, 'confirmed', 'Independent synthetic payment evidence review');
}
$service = app(ProcurementPaymentInsights::class);
$query = Requisition::query()->visibleTo($f['validator']);
$first = $service->build($f['validator'], clone $query, null, null, 1);
$last = $service->build($f['validator'], clone $query, null, null, 2);
$all = $service->build($f['validator'], clone $query, null, null, null);
expect($first['suppliers']['data'])->toHaveCount(20)->and($last['suppliers']['data'])->toHaveCount(1)
->and($all['suppliers']['data'])->toHaveCount(21)->and($all['suppliers']['total'])->toBe(21)
->and($first['currencies'])->toBe($last['currencies'])->and($all['currencies'][0]['amount_minor'])->toBe('84000')
->and($all['coverage']['confirmed_payments'])->toBe(21)
->and(array_intersect(array_column($first['suppliers']['data'], 'supplier_id'), array_column($last['suppliers']['data'], 'supplier_id')))->toBe([]);
if (DB::getDriverName() === 'pgsql') {
if (DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Commit only the disposable supplier report fixture.');
}
DB::commit();
$this->committedInsightsFixture = true;
}
$before = [DB::table('external_payments')->count(), DB::table('audit_logs')->count()];
$this->get('/relatorios?supplier_page=2')->assertOk()->assertInertia(fn (Assert $page) => $page->has('paymentInsights.suppliers.data', 1)
->where('paymentInsights.suppliers.current_page', 2)->where('paymentInsights.suppliers.total', 21));
$csv = $this->get('/relatorios/despesa.csv?supplier_page=2')->assertOk()->assertDownload()->streamedContent();
expect(substr_count($csv, 'Synthetic supplier'))->toBe(20)->and($csv)->toContain(";'=1+1;MZN;1;4000")
->and([DB::table('external_payments')->count(), DB::table('audit_logs')->count()])->toBe($before);
});
beforeEach(function () {
$this->f = paymentFixture();
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'insights-fixture-instance']);
@@ -121,6 +183,9 @@ test('payment period follows confirmation instead of the original payment or req
$query = Requisition::query()->visibleTo($f['validator']);
$service = app(ProcurementPaymentInsights::class);
expect($service->build($f['validator'], clone $query, today()->format('Y-m-d'), today()->format('Y-m-d'))['currencies'][0]['amount_minor'])->toBe('4000')
->and($service->build($f['validator'], clone $query, null, null)['suppliers']['data'][0])->toMatchArray([
'supplier_id' => $f['supplier']->id, 'supplier_name' => $f['invoice']->snapshot['supplier']['name'],
'currency' => 'MZN', 'count' => 1, 'amount_minor' => '4000'])
->and($service->build($f['validator'], clone $query, today()->subDay()->format('Y-m-d'), today()->subDay()->format('Y-m-d'))['currencies'])->toBe([]);
if (DB::getDriverName() === 'pgsql') {
if (! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
@@ -133,7 +198,8 @@ test('payment period follows confirmation instead of the original payment or req
->assertInertia(fn (Assert $page) => $page->where('records.total', 0)
->where('paymentInsights.coverage.confirmed_payments', 1)->where('paymentInsights.currencies.0.amount_minor', '4000'));
$csv = $this->get('/relatorios/despesa.csv?from='.today()->format('Y-m-d').'&to='.today()->format('Y-m-d'))->assertOk()->assertDownload();
expect($csv->streamedContent())->toContain('MZN;1;4000')->not->toContain('bank_snapshot')->not->toContain('account_identifier');
expect($csv->streamedContent())->toContain('MZN;1;4000')->toContain('Nome conservado na factura')
->toContain((string) $f['supplier']->id)->not->toContain('bank_snapshot')->not->toContain('account_identifier');
$this->actingAs($f['issuer'])->get('/relatorios/despesa.csv')->assertForbidden();
$this->actingAs($f['validator']);
DB::table('external_payments')->where('id', $payment->id)->update(['reviewed_at' => null]);
+12
View File
@@ -48,6 +48,18 @@ function reportCopy(Requisition $original, string $number, array $attributes = [
return $copy;
}
test('contract report preserves unknown legacy associations without writes and exports the same documentary basis', function () {
$this->withoutVite();
$before = [DB::table('purchase_orders')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()];
$this->get('/relatorios')->assertOk()->assertInertia(fn (Assert $page) => $page->where('contractInsights.coverage.unknown', 1)
->where('contractInsights.coverage.without_contract', 0)->where('contractInsights.currencies.0.amount_minor', '10000'));
$csv = $this->get('/relatorios/contratos.csv')->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain('"Associação por determinar";MZN;1;10000')->toContain('não pagamentos')
->and([DB::table('purchase_orders')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()])->toBe($before);
$this->actingAs(User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Requester]));
$this->get('/relatorios/contratos.csv')->assertForbidden();
});
test('needed attention report filters all pages and CSV by native status and needed date without writes', function () {
$this->freezeTime();
foreach (range(1, 27) as $index) {
+12 -1
View File
@@ -37,13 +37,24 @@ test('review csv exports each frozen per order agreement once and distinguishes
$binding = ['agreement_id' => 7, 'record_key' => 'synthetic', 'version' => 2, 'reference' => '=AGREEMENT-QA', 'basis' => 'per_order', 'currency' => 'MZN', 'unit' => 'un', 'includes_tax' => true,
'max_order_value_minor' => null, 'max_order_quantity_milli' => 0, 'checked_order_value_minor' => 12345, 'checked_order_quantity_milli' => '1000'];
$report['agreement_limits'] = [$binding, $binding];
$report['orders'] = [['id' => 1, 'number' => 'QA-ORDER', 'currency' => 'MZN', 'total_minor' => 12345, 'agreement_limits' => [$binding, $binding]]];
$report['order'] = ['id' => 1, 'number' => 'QA-ORDER', 'currency' => 'MZN', 'total_minor' => 12345];
$rows = reviewCsvRows(app(ProcurementReviewCsv::class)->render($report));
expect(array_values(array_filter($rows, fn ($row) => $row === ['Acordo por ordem', '7', 'Referência', "'=AGREEMENT-QA"])))->toHaveCount(1);
expect($rows)->toContain(['Acordo por ordem', '7', 'Limite por ordem (centavos)', 'Não definido'])
->toContain(['Acordo por ordem', '7', 'Limite por ordem (milésimos)', '0'])
->toContain(['Acordo por ordem', '7', 'Total conferido nesta ordem (centavos)', '12345']);
$report['agreement_limits'] = 'invalid';
$report['orders'][] = ['id' => 2, 'number' => 'QA-ORDER-SECOND', 'currency' => 'MZN', 'total_minor' => 12345,
'agreement_limits' => [[...$binding, 'version' => 3, 'reference' => '=AGREEMENT-SECOND']]];
$rows = reviewCsvRows(app(ProcurementReviewCsv::class)->render($report));
expect($rows)->toContain(['Acordo por ordem', '7', 'Versão preservada', '2'])
->toContain(['Acordo por ordem', '7', 'Versão preservada', '3'])
->toContain(['Acordo por ordem', '7', 'Ordem de origem', 'QA-ORDER'])
->toContain(['Acordo por ordem', '7', 'Ordem de origem', 'QA-ORDER-SECOND']);
$report['orders'][0]['agreement_limits'] = 'invalid';
expect(fn () => app(ProcurementReviewCsv::class)->render($report))->toThrow(UnexpectedValueException::class);
unset($report['orders']);
expect(app(ProcurementReviewCsv::class)->render($report))->toContain('Acordo por ordem');
});
test('complete review csv keeps missing scores distinct from zero and makes no business writes', function () {
@@ -12,6 +12,7 @@ use App\Services\ProcurementEvidenceBrief;
use App\Services\ProcurementReviewReport;
use Illuminate\Support\Facades\DB;
use Inertia\Testing\AssertableInertia as Assert;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/QualificationFixture.php';
@@ -44,6 +45,17 @@ test('review report returns a private read-only consultation without inventing m
expect(AuditLog::query()->count())->toBe($before);
});
test('maintenance-only membership cannot read business review documents through HTML CSV or the report service', function () {
$actor = $this->f['issuer'];
$profile = DB::table('organization_profiles')->insertGetId(['tenant_id' => $actor->tenant_id, 'name' => 'Synthetic maintenance only',
'permissions' => json_encode(['procurement'], JSON_THROW_ON_ERROR), 'work_contexts' => json_encode(['procurement.internal'], JSON_THROW_ON_ERROR), 'version' => 1]);
DB::table('organization_memberships')->insert(['tenant_id' => $actor->tenant_id, 'user_id' => $actor->id, 'profile_id' => $profile, 'maintenance' => true]);
DB::table('organization_access')->insert(['tenant_id' => $actor->tenant_id, 'active' => true, 'version' => 1]);
expect(fn () => app(ProcurementReviewReport::class)->build($actor, $this->f['r']->id))->toThrow(HttpException::class);
$this->get($this->url)->assertForbidden();
$this->get('/requisicoes/'.$this->f['r']->id.'/relatorio.csv')->assertForbidden();
});
test('review report separates current comparison from outdated documentary identities and results', function () {
$set = documentaryReportRecords($this);
$this->f['quote']->update(['reference' => 'REFERENCIA-POSTERIOR']);
+109 -3
View File
@@ -46,6 +46,7 @@ use App\Services\OrderCancellationWorkflow;
use App\Services\OrderPartsAmendments;
use App\Services\OrderPartsPreparation;
use App\Services\OrderPartsWorkflow;
use App\Services\ProcurementContractInsights;
use App\Services\ProcurementReviewCsv;
use App\Services\ProcurementReviewReport;
use App\Services\ProposalComparison;
@@ -274,7 +275,7 @@ function perOrderAgreement(object $test, ?string $amount = '100.00', ?string $qu
return compact('agreement', 'binding', 'stock', 'warehouse');
}
test('per order global contract sums different articles and freezes its own approved limit', function (?string $cap, bool $allowed) {
test('per order global contract sums different articles and freezes its own approved limit', function (?string $cap, bool $allowed, bool $partial = false) {
$f = perOrderAgreement($this, '100.00', '1.000');
$planning = app(SupplyPlanning::class);
$this->actingAs($this->buyer);
@@ -303,8 +304,10 @@ test('per order global contract sums different articles and freezes its own appr
'contract_key' => $contract->record_key, 'reference' => 'QA-CONTRACT-ARTICLE-'.($second ? '2' : '1')]));
$this->actingAs($this->finance);
$agreement = $planning->save($this->finance, 'agreement', supplyInput([], 'approve', $draft));
if (! $partial || ! $second) {
$bindings[] = ['requisition_item_id' => $item->id, 'agreement_id' => $agreement->id];
}
}
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
$response = $this->actingAs($this->buyer)->postJson('/adjudicacoes/'.$award->id.'/emitir', ['agreement_bindings' => $bindings]);
@@ -317,14 +320,17 @@ test('per order global contract sums different articles and freezes its own appr
$response->assertRedirect();
$order = PurchaseOrder::query()->sole();
foreach ($order->snapshot['agreement_bindings'] as $row) {
expect($row['contract']['checked_order_value_minor'])->toBe(20000)->and($row['contract']['max_order_value_minor'])->toBe($contract->data['max_order_value_minor'])
expect($row['contract']['checked_order_value_minor'])->toBe($partial ? 10000 : 20000)->and($row['contract']['max_order_value_minor'])->toBe($contract->data['max_order_value_minor'])
->and($row['contract']['version'])->toBe($contract->version)->and($row['checked_order_value_minor'])->toBe(10000);
}
$insights = app(ProcurementContractInsights::class)->build($this->buyer, Requisition::query()->whereKey($this->r->id));
expect($insights['coverage'][$partial ? 'partial' : 'contract'])->toBe(1)
->and($insights['currencies'][0]['amount_minor'])->toBe('20000');
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('Contrato global: QA-GLOBAL-CONTRACT');
$this->withoutVite()->get('/compras/fornecimento?view=contracts')->assertOk();
$this->get('/compras/fornecimento?view=agreements&linked_contract_key='.$contract->record_key)
->assertOk()->assertInertia(fn (Assert $page) => $page->component('supply/index')->has('records', 2)->where('linkedContractKey', $contract->record_key));
})->with([['150.00', false], ['200.00', true], [null, true], ['0', false]]);
})->with([['150.00', false], ['200.00', true], [null, true], ['0', false], ['200.00', true, true]]);
test('per order contract rejects incompatible association and stale approval without changing earlier versions', function () {
$f = perOrderAgreement($this);
@@ -848,6 +854,9 @@ test('award starts a new approval cycle and order freezes all agreed data', func
expect($award->approvals()->firstOrFail()->decision)->toBe('pending');
$this->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasErrors('approvals');
$order = issuePurchaseOrder($this, $award);
$contracts = app(ProcurementContractInsights::class)->build($this->buyer, Requisition::query()->whereKey($this->r->id));
expect($contracts['coverage']['without_contract'])->toBe(1)->and($contracts['coverage']['unknown'])->toBe(0)
->and($contracts['currencies'][0]['amount_minor'])->toBe('10000');
expect($order->number)->toMatch('/^OC-\d{4}-\d{6}$/')->and($order->total_minor)->toBe(10000);
expect($order->snapshot['supplier']['name'])->toBe('Fornecedor 0')->and($order->snapshot['quotation']['payment_terms'])->toBe('30 dias');
expect($order->snapshot['budget_checked'])->toBeFalse()->and($order->snapshot['development_only'])->toBeTrue();
@@ -1903,6 +1912,66 @@ test('native partial-order receipts and independent invoice validation consume e
->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);
commitNativeReviewReportFixture($this);
$this->withoutVite();
$this->get('/requisicoes/'.$this->r->id.'/relatorio')->assertOk()->assertInertia(fn (Assert $page) => $page
->has('report.orders', 2)->has('report.fulfilment.receipts', 2)->has('report.fulfilment.invoices', 2)
->where('report.orders.0.number', $first->number)->where('report.orders.1.number', $second->number)
->where('report.fulfilment.invoices.1.order_number', $second->number));
$csv = $this->get('/requisicoes/'.$this->r->id.'/relatorio.csv')->assertOk()->getContent();
expect($csv)->toContain($first->number)->toContain($second->number)->toContain('FT-PART-'.$first->id)->toContain('FT-PART-'.$second->id);
});
function commitNativeReviewReportFixture(object $test): void
{
if (DB::getDriverName() !== 'pgsql') {
return;
}
if (! app()->environment('testing') || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Native review report requires an isolated committed test fixture.');
}
DB::commit();
$test->committedConsolidatedReportFixture = true;
}
test('native delivery analysis follows the frozen promise partial receipts and actual completion without changing sources', function () {
$award = selectPurchaseAward($this);
$order = issuePurchaseOrder($this, $award);
$service = app(\App\Services\ProcurementDeliveryInsights::class);
$read = fn () => $service->build($this->buyer, Requisition::query()->whereKey($this->r->id), \Carbon\CarbonImmutable::now(), null, 'all');
expect($read()['coverage']['pending'])->toBe(1);
$due = \Carbon\CarbonImmutable::parse($order->snapshot['award']['delivery_date'], config('app.timezone'))->setTime(12, 0);
$this->travelTo($due);
expect($read()['coverage']['pending'])->toBe(1);
$receiver = User::factory()->create(['tenant_id' => $this->tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$warehouse = Warehouse::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'DELIVERY-QA', 'name' => 'Armazém sintético']);
$stock = StockItem::query()->create(['tenant_id' => $this->tenant->id, 'created_by' => $receiver->id, 'code' => 'DELIVERY-QA', 'name' => 'Material sintético', 'unit' => 'un']);
$payload = fn ($quantity) => ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'DELIVERY-'.Str::random(8),
'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id, 'items' => [['purchase_order_item_id' => $order->items()->sole()->id,
'received_quantity' => $quantity, 'accepted_quantity' => $quantity, 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
$this->actingAs($receiver);
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.400'));
$this->travel(1)->days();
$this->actingAs($this->buyer);
$late = $read();
expect($late['coverage']['pending_late'])->toBe(1)->and($late['records']['data'][0]['late_days'])->toBe(1)
->and($late['records']['data'][0]['late_lines'][0]['pending_quantity'])->toBe('0.600');
$this->actingAs($receiver);
app(ReceiptWorkflow::class)->confirm($receiver, $order, $payload('0.600'));
$this->actingAs($this->buyer);
$before = [DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()];
$complete = $read();
expect($complete['coverage']['completed_late'])->toBe(1)->and($complete['pending_lines'])->toBe(0)
->and($complete['records']['data'][0]['late_lines'][0]['completed_on'])->toBe(today()->toDateString())
->and([DB::table('stock_movements')->get()->toJson(), DB::table('budget_entries')->get()->toJson(), DB::table('audit_logs')->get()->toJson()])->toBe($before);
commitNativeReviewReportFixture($this);
$this->withoutVite();
$this->get('/relatorios?delivery_state=completed_late')->assertOk()->assertInertia(fn (Assert $page) => $page
->where('deliveryInsights.coverage.completed_late', 1)->where('deliveryInsights.records.data.0.number', $order->number));
$csv = $this->get('/relatorios/entregas.csv?delivery_state=completed_late')->assertOk()->assertDownload()->streamedContent();
expect($csv)->toContain($order->number)->toContain('Recepção integral depois da data acordada')->toContain('0.000');
$this->travelBack();
});
function secondNativeOrderPartsOrigin(object $test): array
@@ -1939,12 +2008,24 @@ function secondNativeOrderPartsOrigin(object $test): array
return [$secondRequest, $quotes];
}
afterEach(function () {
if ($this->committedConsolidatedReportFixture ?? false) {
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 0) {
throw new LogicException('Consolidated report cleanup requires the disposable local PostgreSQL database.');
}
DB::statement('DROP SCHEMA public CASCADE');
DB::statement('CREATE SCHEMA public');
}
});
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);
$this->selection['delivery_date'] = today()->addWeeks(2)->toDateString();
$second = nativeOrderPartsAward($this, $request, $quotes[0]);
$a = nativeOrderPartsInput($this, $first, '1.000', 0);
$b = nativeOrderPartsInput($this, $second, '1.000', 0);
@@ -1954,10 +2035,29 @@ test('native consolidated order retains both origins and consumes a single invoi
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();
$delivery = app(\App\Services\ProcurementDeliveryInsights::class)->build($this->buyer, Requisition::query()->whereKey($request->id),
\Carbon\CarbonImmutable::now()->addDays(8), null, 'all');
expect($delivery['coverage']['pending_late'])->toBe(1)->and($delivery['unknown_lines'])->toBe(0)
->and($delivery['records']['data'][0]['late_lines'])->toHaveCount(1)
->and($delivery['records']['data'][0]['late_lines'][0]['id'])->toBe($order->items()->where('requisition_item_id', $this->item->id)->value('id'));
$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.');
expect(PurchaseOrder::query()->visibleTo($this->buyer)->forRequisitions(Requisition::query()->whereKey($request->id))->count())->toBe(1)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->forRequisitions(Requisition::query()->whereIn('id', [$this->r->id, $request->id]))->count())->toBe(1)
->and(PurchaseOrder::query()->visibleTo($this->buyer)->forRequisitions(Requisition::query()->whereKey(999999))->count())->toBe(0);
if (DB::getDriverName() === 'pgsql') {
if (DB::connection()->getConfig('host') !== '127.0.0.1' || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName()) || DB::transactionLevel() !== 1) {
throw new LogicException('Consolidated report snapshot requires an isolated committed test fixture.');
}
DB::commit();
$this->committedConsolidatedReportFixture = true;
}
$this->get('/relatorios?search='.urlencode($request->number))->assertOk()
->assertInertia(fn (Assert $page) => $page->where('records.data.0.order_number', $order->number));
$this->get('/relatorios?attention=approved_without_order&search='.urlencode($request->number))->assertOk()
->assertInertia(fn (Assert $page) => $page->where('records.total', 0));
$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);
@@ -1985,16 +2085,22 @@ test('native consolidated order retains both origins and consumes a single invoi
->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->get('/requisicoes/'.$request->id.'/relatorio')->assertOk()->assertInertia(fn (Assert $page) => $page
->has('report.orders', 1)->has('report.orders.0.origins', 2)->has('report.fulfilment.receipts', 1)->has('report.fulfilment.invoices', 1)
->where('report.orders.0.total_minor', 30000)->where('report.fulfilment.invoices.0.total_minor', '15000'));
$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();
expect(PurchaseOrder::query()->visibleTo($this->owner)->forRequisitions(Requisition::query()->whereKey($this->r->id))->count())->toBe(0);
// The search must respect every consolidated origin after a current department change,
// while keeping the native company-wide warehouse reader's receipt access.
$otherDepartment = Department::query()->create(['tenant_id' => $this->tenant->id, 'name' => 'Outro departamento sintético']);
$request->forceFill(['department_id' => $otherDepartment->id])->save();
$this->actingAs($this->head)->get('/compras/pesquisa?q=GR-CONSOL-QA')->assertOk()
->assertInertia(fn (Assert $page) => $page->where('groups.4.key', 'receipts')->where('groups.4.records.total', 0));
$this->get('/requisicoes/'.$this->r->id.'/relatorio')->assertOk()->assertInertia(fn (Assert $page) => $page
->has('report.orders', 0)->has('report.fulfilment.receipts', 0)->where('report.fulfilment.invoices', null));
$this->actingAs($receiver)->get('/compras/pesquisa?q=GR-CONSOL-QA')->assertOk()
->assertInertia(fn (Assert $page) => $page->where('groups.4.key', 'receipts')->where('groups.4.records.total', 1));
});
@@ -0,0 +1,24 @@
<?php
use App\Models\PurchaseAward;
use App\Models\Quotation;
require_once __DIR__.'/../Support/ReceiptFixture.php';
test('synthetic receipt sources preserve explicit unit prices and calculate coherent line and header amounts', function (string $quantity, array $categories, int $unit, int $lineTotal, int $documentTotal) {
$f = receiptFixture($quantity, 'consumable', $categories);
expect($f['r']->total_minor)->toBe($documentTotal)->and($f['order']->total_minor)->toBe($documentTotal)
->and($f['order']->items()->count())->toBe(count($categories))
->and((int) $f['r']->items()->sum('total_minor'))->toBe($documentTotal)
->and((int) $f['order']->items()->sum('total_minor'))->toBe($documentTotal)
->and(Quotation::query()->where('requisition_id', $f['r']->id)->sole()->total_minor)->toBe($documentTotal)
->and(PurchaseAward::query()->where('requisition_id', $f['r']->id)->sole()->total_minor)->toBe($documentTotal);
foreach ($f['lines'] as $line) {
expect($line->unit_price_minor)->toBe($unit)->and($line->total_minor)->toBe($lineTotal);
}
})->with([
['1.000', ['Material'], 10000, 10000, 10000],
['100.000', ['Material'], 10000, 1000000, 1000000],
['0.333', ['Material'], 10000, 3330, 3330],
['1.000', ['Material', 'Serviços'], 5000, 5000, 10000],
]);
+30 -2
View File
@@ -7,10 +7,12 @@ use App\Models\Requisition;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\ProcurementOperationalInsights;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionWorkflow;
use App\Services\WorkflowNotices;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
@@ -193,7 +195,7 @@ test('configured escalation alerts respect current membership and never delegate
$this->travelBack();
});
test('native expiry returns the same request and preserves the approved stage before a fresh revised submission and reservation', function () {
test('native expiry returns the same request and preserves the approved stage before a fresh revised submission and reservation', function (string $secondOutcome) {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
$head = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::DepartmentHead]);
$buyer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Procurement]);
@@ -257,6 +259,32 @@ test('native expiry returns the same request and preserves the approved stage be
$notices = app(WorkflowNotices::class)->visible($owner);
expect(array_column($notices, 'outcome'))->toContain('expired')
->and(DB::table('workflow_notices')->where('requisition_id', $request->id)->where('recipient_id', $owner->id)->count())->toBe(1);
if ($secondOutcome === 'approved') {
$this->travel(2)->minutes();
$this->actingAs($head);
$workflow->decide($head, $request, 'approved', 'Conferência sintética do novo ciclo', (string) Str::uuid(), $request->process_version);
$request->refresh();
$this->travel(3)->minutes();
$this->actingAs($buyer);
$workflow->decide($buyer, $request, 'approved', 'Conferência final sintética do novo ciclo', (string) Str::uuid(), $request->process_version);
$insights = app(ProcurementOperationalInsights::class)->build(Requisition::query()->whereKey($request->id), CarbonImmutable::now());
expect($request->fresh()->status)->toBe('approved')->and($insights['approval_times'])->toMatchArray([
'measured' => 1, 'unknown' => 0, 'total_seconds' => 300, 'min_seconds' => 300, 'max_seconds' => 300]);
$this->travelBack();
return;
}
if ($secondOutcome === 'rejected') {
$this->actingAs($head);
$workflow->decide($head, $request, 'rejected', 'Rejeição sintética da revisão no novo ciclo', (string) Str::uuid(), $request->process_version);
expect($request->fresh()->status)->toBe('rejected')
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0)
->and($request->allSteps()->whereKey($approved['id'])->firstOrFail()->toArray())->toBe($approved)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(1);
$this->travelBack();
return;
}
$this->travel(31)->minutes();
$check = ['operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
$this->postJson('/requisicoes/'.$request->id.'/prazos/verificar', $check)->assertRedirect();
@@ -266,4 +294,4 @@ test('native expiry returns the same request and preserves the approved stage be
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(2);
$this->travelBack();
});
})->with(['expired', 'rejected', 'approved']);
@@ -0,0 +1,29 @@
<?php
use App\Services\ExpenseAllocations;
use App\Services\ExternalPaymentWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
require_once __DIR__.'/PaymentFixture.php';
/** Native payment originals and exact, labelled synthetic categories; guarded by receiptFixture. */
function expenseAllocationQaFixture(): array
{
$f = paymentFixture(['Material', 'Serviços']);
config(['common-payables.enabled' => true, 'common-payables.source_instance' => 'explicit-expense-qa', 'expense-allocations.qa_enabled' => true]);
foreach ([$f['author'], $f['validator']] as $actor) {
DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $actor->id,
'person' => 'expense-qa-'.$actor->id, 'action' => 'view']);
}
auth()->guard()->setUser($f['author']);
$payment = app(ExternalPaymentWorkflow::class)->register($f['author'], $f['invoice'], $f['payment_data']);
auth()->guard()->setUser($f['validator']);
app(ExternalPaymentWorkflow::class)->review($f['validator'], $payment, 'confirmed', 'Conferência de evidência estritamente sintética');
$source = app(ExpenseAllocations::class)->source($f['validator'], $payment->id);
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $source['fingerprint'],
'reason' => 'Imputação explícita de Finanças no ensaio sintético',
'allocations' => [['category' => 'Material', 'amount' => '15.00'], ['category' => 'Serviços', 'amount' => '25.00']]];
return compact('f', 'payment', 'source', 'input');
}
+8 -3
View File
@@ -7,15 +7,18 @@ use App\Services\BudgetWorkflow;
use App\Services\ConflictGuard;
use App\Services\InvoiceWorkflow;
use App\Services\ReceiptWorkflow;
use Brick\Math\BigDecimal;
use Illuminate\Support\Facades\DB;
require_once __DIR__.'/ReceiptFixture.php';
/** Synthetic data: receiptFixture enforces an isolated test database. */
function invoiceFixture(): array
function invoiceFixture(array $categories = ['Material']): array
{
$f = receiptFixture();
app(ReceiptWorkflow::class)->confirm($f['receiver'], $f['order'], receiptPayload($f, '1.000'));
$f = receiptFixture('1.000', 'consumable', $categories);
$receipt = receiptPayload($f, '1.000');
$receipt['items'] = array_map(fn ($line) => [...$receipt['items'][0], 'purchase_order_item_id' => $line->id], $f['lines']);
app(ReceiptWorkflow::class)->confirm($f['receiver'], $f['order'], $receipt);
$author = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
$validator = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
auth()->guard()->setUser($author);
@@ -26,6 +29,8 @@ function invoiceFixture(): array
app(BudgetWorkflow::class)->record($author, $f['r'], 'commit', 10000, 10000);
});
$data = ['number' => 'FT-PG-1', 'issued_on' => today()->format('Y-m-d'), 'subtotal' => '60.00', 'tax' => '0.00', 'total' => '60.00', 'items' => [['purchase_order_item_id' => $f['line']->id, 'quantity' => '0.600', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0']]];
$data['items'] = array_map(fn ($line) => ['purchase_order_item_id' => $line->id, 'quantity' => '0.600', 'unit' => 'cx',
'unit_price' => (string) BigDecimal::of($line->unit_price_minor)->dividedBy(100, 2), 'tax_rate' => '0'], $f['lines']);
$invoice = app(InvoiceWorkflow::class)->register($author, $f['order'], $data);
return [...$f, 'author' => $author, 'validator' => $validator, 'invoice' => $invoice, 'data' => $data];
+22 -4
View File
@@ -24,11 +24,26 @@ function landedQaReceiptsVerified(array $command, string $output): bool
return false;
};
$mode = ($command[1] ?? '') === 'vendor/bin/pest' ? 'pest' : ($command[3] ?? '');
if ($mode === 'recover-cycles') {
if ($mode === 'race-expense') {
foreach (['same_operation', 'same_version'] as $scenario) {
$matches = array_values(array_filter($records, fn ($row) => ($row['scenario'] ?? null) === $scenario));
if (count($matches) !== 1 || ($matches[0]['blocked_writers_observed'] ?? 0) < 2 || ($matches[0]['expense_versions_created'] ?? null) !== 1
|| ($matches[0]['audits'] ?? null) !== 1 || ($matches[0]['financial_sources_unchanged'] ?? false) !== true
|| ($matches[0]['statuses'] ?? null) !== ($scenario === 'same_operation' ? [200, 200] : [200, 409])) {
return false;
}
}
return true;
}
if (in_array($mode, ['recover-cycles', 'recover-expenses'], true)) {
return $contains(fn ($row) => ($row['cycle_post_extension_all_tables_equal'] ?? false) === true
&& ($row['cycle_native_replays_without_effects'] ?? false) === true && ($row['cycle_history_and_reserve_restored'] ?? false) === true
&& ($row['cycle_reserved_minor'] ?? null) === 12000 && ($row['cycle_pre_extension_all_tables_equal'] ?? false) === true)
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true)
&& ($mode !== 'recover-expenses' || $contains(fn ($row) => ($row['expense_versions_restored'] ?? null) === 2
&& ($row['expense_native_sources_verified'] ?? false) === true && ($row['expense_replay_without_effects'] ?? false) === true
&& ($row['expense_explicit_amounts_restored'] ?? null) === ['Material' => '1000', 'Serviços' => '3000']));
}
if ($mode === 'race-cycles') {
foreach (['same_operation', 'different_operations', 'late_decision'] as $scenario) {
@@ -41,7 +56,10 @@ function landedQaReceiptsVerified(array $command, string $output): bool
}
}
return $contains(fn ($row) => ($row['old_cycle_runtime_rejected_before_balance'] ?? false) === true && ($row['status'] ?? null) === 503);
return $contains(fn ($row) => ($row['old_cycle_runtime_rejected_before_balance'] ?? false) === true && ($row['status'] ?? null) === 503)
&& $contains(fn ($row) => ($row['scheduled_expiry_without_session'] ?? false) === true && ($row['scheduled_scope_closed'] ?? false) === true
&& ($row['scheduled_repeat_without_effects'] ?? false) === true && ($row['scheduled_audit_explicit'] ?? false) === true
&& ($row['scheduled_unrelated_operations_denied'] ?? null) === 3);
}
if ($mode === 'capital') {
if (! $contains(fn ($row) => ($row['capital_register_versions_restored'] ?? null) === 2
@@ -100,7 +118,7 @@ function landedQaReceiptsVerified(array $command, string $output): bool
&& $contains(fn ($row) => ($row['isolated_restore_removed'] ?? false) === true);
}
if (in_array($mode, ['legal-http', 'legal-review'], true)) {
if (in_array($mode, ['legal-http', 'legal-review', 'expiry-review'], true)) {
return $contains(fn ($row) => ($row['native_legal_http_login'] ?? false) === true && ($row['csrf_required'] ?? false) === true
&& ($row['large_multipart_upload_bytes'] ?? 0) > 2097152 && ($row['original_unchanged'] ?? false) === true
&& ($row['exact_native_download'] ?? false) === true && ($row['one_source_one_audit_after_replay'] ?? false) === true
+2 -2
View File
@@ -7,9 +7,9 @@ use App\Services\SupplierBankWorkflow;
require_once __DIR__.'/InvoiceFixture.php';
/** invoiceFixture enforces a synthetic, isolated test database. */
function paymentFixture(): array
function paymentFixture(array $categories = ['Material']): array
{
$f = invoiceFixture();
$f = invoiceFixture($categories);
auth()->guard()->setUser($f['validator']);
app(InvoiceWorkflow::class)->validate($f['validator'], $f['invoice']);
$supplier = Supplier::query()->findOrFail($f['order']->supplier_id);
+25 -8
View File
@@ -16,7 +16,7 @@ use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
/** Synthetic fixture: callable only on in-memory SQLite or the dedicated PostgreSQL test database. */
function receiptFixture(string $quantity = '1.000', string $purchaseType = 'consumable'): array
function receiptFixture(string $quantity = '1.000', string $purchaseType = 'consumable', array $categories = ['Material']): array
{
$connection = DB::connection();
$allowed = ($connection->getDriverName() === 'sqlite' && $connection->getDatabaseName() === ':memory:') ||
@@ -24,6 +24,15 @@ function receiptFixture(string $quantity = '1.000', string $purchaseType = 'cons
if (! app()->environment('testing') || ! $allowed) {
throw new LogicException('Fixtures de recepção proibidas fora de uma base de testes isolada.');
}
if ($categories === [] || count($categories) > 100 || 10000 % count($categories) !== 0 || count(array_unique($categories)) !== count($categories)) {
throw new LogicException('Synthetic categories require an exact explicit split of the fixture total.');
}
if (count($categories) > 1 && $quantity !== '1.000') {
throw new LogicException('The explicit multi-category fixture uses one unit per line.');
}
$lineMinor = intdiv(10000, count($categories));
$amounts = \App\Services\PurchaseLineAmounts::portion($lineMinor, '0', 0, \App\Services\ReceiptWorkflow::milli($quantity));
$documentMinor = $amounts['total_minor'] * count($categories);
$tenant = Tenant::query()->create(['name' => 'Empresa fictícia de recepção']);
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações']);
$center = CostCenter::query()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'code' => 'OPS', 'name' => 'Operações']);
@@ -31,17 +40,25 @@ function receiptFixture(string $quantity = '1.000', string $purchaseType = 'cons
$receiver = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
$otherReceiver = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Warehouse]);
auth()->guard()->setUser($receiver);
$r = Requisition::query()->create(['tenant_id' => $tenant->id, 'requester_id' => $issuer->id, 'department_id' => $department->id, 'cost_center_id' => $center->id, 'number' => 'REQ-TEST-'.Str::random(10), 'priority' => 'normal', 'needed_by' => now()->addWeek(), 'justification' => 'Fixture de ordem já emitida para testes de recepção.', 'status' => 'approved', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
$requested = $r->items()->create(['tenant_id' => $tenant->id, 'description' => 'Artigo fictício', 'category' => 'Material', 'purchase_type' => $purchaseType, 'quantity' => $quantity, 'unit' => 'cx', 'unit_price_minor' => 10000, 'tax_rate' => '0', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
$r = Requisition::query()->create(['tenant_id' => $tenant->id, 'requester_id' => $issuer->id, 'department_id' => $department->id, 'cost_center_id' => $center->id, 'number' => 'REQ-TEST-'.Str::random(10), 'priority' => 'normal', 'needed_by' => now()->addWeek(), 'justification' => 'Fixture de ordem já emitida para testes de recepção.', 'status' => 'approved', 'subtotal_minor' => $documentMinor, 'tax_minor' => 0, 'total_minor' => $documentMinor]);
$requested = $r->items()->create(['tenant_id' => $tenant->id, 'description' => 'Artigo fictício', 'category' => $categories[0], 'purchase_type' => $purchaseType, 'quantity' => $quantity, 'unit' => 'cx', 'unit_price_minor' => $lineMinor, 'tax_rate' => '0', ...$amounts]);
$supplier = Supplier::query()->create(['tenant_id' => $tenant->id, 'created_by' => $issuer->id, 'name' => 'Fornecedor fictício', 'nuit' => '123456789', 'contact' => 'Contacto de teste', 'email' => 'fixture@example.invalid', 'phone' => '000000000', 'address' => 'Morada fictícia', 'category' => 'Material', 'beneficiaries' => 'Beneficiário fictício', 'document_references' => 'Documento fictício', 'diligence_notes' => 'Somente para a base de testes.', 'status' => 'active', 'next_review' => now()->addYear()]);
$quote = Quotation::query()->create(['tenant_id' => $tenant->id, 'requisition_id' => $r->id, 'supplier_id' => $supplier->id, 'created_by' => $issuer->id, 'reference' => 'PROP-TEST', 'delivery_days' => 5, 'valid_until' => now()->addWeek(), 'payment_terms' => '30 dias', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000, 'weights' => ['price' => 40, 'quality' => 20, 'delivery' => 15, 'history' => 15, 'payment' => 10]]);
$award = PurchaseAward::query()->create(['tenant_id' => $tenant->id, 'requisition_id' => $r->id, 'quotation_id' => $quote->id, 'created_by' => $issuer->id, 'justification' => 'Adjudicação de fixture, não repetir o fluxo anterior.', 'delivery_date' => now()->addWeek(), 'delivery_location' => 'Armazém fictício', 'status' => 'approved', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000, 'approval_snapshot' => [], 'decision_matrix' => [], 'comparison_hash' => str_repeat('0', 64)]);
$order = PurchaseOrder::query()->create(['tenant_id' => $tenant->id, 'requisition_id' => $r->id, 'purchase_award_id' => $award->id, 'supplier_id' => $supplier->id, 'issued_by' => $issuer->id, 'number' => 'OC-TEST-'.Str::random(10), 'status' => 'issued', 'currency' => 'MZN', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000, 'issued_at' => now(), 'snapshot' => ['supplier' => $supplier->only(['name', 'nuit']), 'company' => ['name' => $tenant->name], 'development_only' => true, 'budget_checked' => false]]);
$line = $order->items()->create(['tenant_id' => $tenant->id, 'requisition_item_id' => $requested->id, 'description' => 'Artigo fictício', 'category' => 'Material', 'purchase_type' => $purchaseType, 'unit' => 'cx', 'quantity' => $quantity, 'unit_price_minor' => 10000, 'tax_rate' => '0', 'subtotal_minor' => 10000, 'tax_minor' => 0, 'total_minor' => 10000]);
$quote = Quotation::query()->create(['tenant_id' => $tenant->id, 'requisition_id' => $r->id, 'supplier_id' => $supplier->id, 'created_by' => $issuer->id, 'reference' => 'PROP-TEST', 'delivery_days' => 5, 'valid_until' => now()->addWeek(), 'payment_terms' => '30 dias', 'subtotal_minor' => $documentMinor, 'tax_minor' => 0, 'total_minor' => $documentMinor, 'weights' => ['price' => 40, 'quality' => 20, 'delivery' => 15, 'history' => 15, 'payment' => 10]]);
$award = PurchaseAward::query()->create(['tenant_id' => $tenant->id, 'requisition_id' => $r->id, 'quotation_id' => $quote->id, 'created_by' => $issuer->id, 'justification' => 'Adjudicação de fixture, não repetir o fluxo anterior.', 'delivery_date' => now()->addWeek(), 'delivery_location' => 'Armazém fictício', 'status' => 'approved', 'subtotal_minor' => $documentMinor, 'tax_minor' => 0, 'total_minor' => $documentMinor, 'approval_snapshot' => [], 'decision_matrix' => [], 'comparison_hash' => str_repeat('0', 64)]);
$order = PurchaseOrder::query()->create(['tenant_id' => $tenant->id, 'requisition_id' => $r->id, 'purchase_award_id' => $award->id, 'supplier_id' => $supplier->id, 'issued_by' => $issuer->id, 'number' => 'OC-TEST-'.Str::random(10), 'status' => 'issued', 'currency' => 'MZN', 'subtotal_minor' => $documentMinor, 'tax_minor' => 0, 'total_minor' => $documentMinor, 'issued_at' => now(), 'snapshot' => ['supplier' => $supplier->only(['name', 'nuit']), 'company' => ['name' => $tenant->name], 'development_only' => true, 'budget_checked' => false]]);
$line = $order->items()->create(['tenant_id' => $tenant->id, 'requisition_item_id' => $requested->id, 'description' => 'Artigo fictício', 'category' => $categories[0], 'purchase_type' => $purchaseType, 'unit' => 'cx', 'quantity' => $quantity, 'unit_price_minor' => $lineMinor, 'tax_rate' => '0', ...$amounts]);
$lines = [$line];
foreach (array_slice($categories, 1) as $category) {
$additional = $requested->replicate();
$additional->fill(['category' => $category])->save();
$copy = $line->replicate();
$copy->fill(['category' => $category, 'requisition_item_id' => $additional->id])->save();
$lines[] = $copy;
}
$warehouse = Warehouse::query()->create(['tenant_id' => $tenant->id, 'created_by' => $receiver->id, 'code' => 'ARM-TEST', 'name' => 'Armazém fictício']);
$stock = StockItem::query()->create(['tenant_id' => $tenant->id, 'created_by' => $receiver->id, 'code' => 'ART-TEST', 'name' => 'Artigo de stock fictício', 'unit' => 'cx']);
return compact('tenant', 'department', 'issuer', 'receiver', 'otherReceiver', 'r', 'order', 'line', 'warehouse', 'stock');
return compact('tenant', 'department', 'issuer', 'receiver', 'otherReceiver', 'r', 'order', 'line', 'lines', 'warehouse', 'stock');
}
function receiptPayload(array $fixture, string $quantity = '0.600'): array
+1 -1
View File
@@ -30,7 +30,7 @@ $app->booted(function () use ($root, $database) {
if (config('database.default') !== 'pgsql' || config('database.connections.pgsql.database') !== $database) {
abort(503);
}
config(['capital-register.qa_enabled' => true, 'import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true,
config(['requisition-expiry.qa_enabled' => true, 'capital-register.qa_enabled' => true, 'import-legal.qa_enabled' => true, 'import-tariffs.qa_enabled' => true,
'import-dossier.qa_enabled' => true, 'import-bank-support.qa_enabled' => true, 'import-readiness.qa_enabled' => true, 'import-estimates.qa_enabled' => true,
'session.driver' => 'file', 'session.files' => $root.'/storage/framework/sessions', 'session.domain' => null,
'session.secure' => false, 'cache.default' => 'array']);
+32
View File
@@ -7,12 +7,15 @@ test('cycle contention requires all three real lock and single-effect receipts',
$rows[] = ['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => 2, 'returns' => 1, 'reserve_minor' => 0, 'late_approvals' => 0];
}
$rows[] = ['old_cycle_runtime_rejected_before_balance' => true, 'status' => 503];
$rows[] = ['scheduled_expiry_without_session' => true, 'scheduled_scope_closed' => true, 'scheduled_repeat_without_effects' => true,
'scheduled_audit_explicit' => true, 'scheduled_unrelated_operations_denied' => 3];
$output = function () use (&$rows) {
return implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows));
};
expect(landedQaReceiptsVerified($command, $output()))->toBeTrue();
$rows[2]['late_approvals'] = 1;
expect(landedQaReceiptsVerified($command, $output()))->toBeFalse();
$rows[2]['late_approvals'] = 0;
array_pop($rows);
expect(landedQaReceiptsVerified($command, $output()))->toBeFalse();
});
@@ -33,6 +36,35 @@ test('capital register contention requires both actual lock receipts and one imm
require_once __DIR__.'/../Support/LandedQaReceipts.php';
test('explicit expense contention requires one audited version with unchanged native financial sources', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-expense'];
$rows = [];
foreach (['same_operation' => [200, 200], 'same_version' => [200, 409]] as $scenario => $statuses) {
$rows[] = ['scenario' => $scenario, 'statuses' => $statuses, 'blocked_writers_observed' => 2,
'expense_versions_created' => 1, 'audits' => 1, 'financial_sources_unchanged' => true];
}
$output = function () use (&$rows) {
return implode("\n", array_map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR), $rows));
};
expect(landedQaReceiptsVerified($command, $output()))->toBeTrue();
$rows[1]['financial_sources_unchanged'] = false;
expect(landedQaReceiptsVerified($command, $output()))->toBeFalse();
$rows[1]['financial_sources_unchanged'] = true;
array_pop($rows);
expect(landedQaReceiptsVerified($command, $output()))->toBeFalse();
});
test('cycle recovery requires exact table restoration replay and disposal receipts', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'recover-cycles'];
$valid = ['cycle_post_extension_all_tables_equal' => true, 'cycle_native_replays_without_effects' => true,
'cycle_history_and_reserve_restored' => true, 'cycle_reserved_minor' => 12000, 'cycle_pre_extension_all_tables_equal' => true];
$cleanup = json_encode(['isolated_restore_removed' => true], JSON_THROW_ON_ERROR);
expect(landedQaReceiptsVerified($command, json_encode($valid, JSON_THROW_ON_ERROR)."\n".$cleanup))->toBeTrue()
->and(landedQaReceiptsVerified($command, json_encode($valid, JSON_THROW_ON_ERROR)))->toBeFalse();
$valid['cycle_reserved_minor'] = 0;
expect(landedQaReceiptsVerified($command, json_encode($valid, JSON_THROW_ON_ERROR)."\n".$cleanup))->toBeFalse();
});
test('estimate contention receipts require all native uniqueness races and explicit estimate effects', function () {
$command = ['php', 'worker.php', 'compras_receipts_test_000000000001', 'race-estimate'];
$rows = [['old_runtime_rejected_before_balance' => true, 'old_estimate_runtime_rejected' => true,
+108
View File
@@ -0,0 +1,108 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import ExpenseAllocation from '../../resources/js/pages/payments/expense-allocation';
import { ProcurementCategoryInsights } from '../../resources/js/components/procurement-category-insights';
function render(canWrite: boolean) {
return renderToStaticMarkup(
<App
initialComponent={ExpenseAllocation}
initialPage={{
component: 'payments/expense-allocation',
url: '/pagamentos/1/categorias',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
canWrite,
actorId: 1,
tenantId: 1,
payment: {
id: 1,
invoice_id: 1,
invoice_number: 'FT-QA',
currency: 'MZN',
amount_minor: '4000',
},
categories: ['Material', '<script>Serviços</script>'],
fingerprint: 'a'.repeat(64),
current: {
id: 1,
version: 1,
reason: 'Synthetic explicit allocation',
data: {
allocations: [
{ category: 'Material', amount_minor: '1500' },
],
},
},
history: {
data: [],
prev_page_url: null,
next_page_url: null,
},
},
}}
/>,
);
}
test('read-only financial viewer sees the preserved attribution without a write form', () => {
const html = render(false);
expect(html).toContain('15,00 MZN');
expect(html).not.toContain('<form');
});
test('Finance starts with blank amounts and deliberately chooses whether to reuse the current attribution', () => {
const html = render(true);
expect(html).toContain('Usar a imputação actual como preparação');
expect(html).toContain('&lt;script&gt;Serviços&lt;/script&gt;');
expect(html).not.toContain('value="15.00"');
expect(html).toContain('Guardar imputação');
});
test('category summary preserves unassigned expenses and separates currencies without allocating them automatically', () => {
const html = renderToStaticMarkup(
<ProcurementCategoryInsights
pageHref="/relatorios?from=2026-11-01&supplier_page=2"
data={{
coverage: { allocated: 1, unallocated: 1, indeterminate: 1 },
unassigned: [
{
state: 'unallocated',
currency: 'USD',
count: 1,
amount_minor: '4000',
},
{
state: 'indeterminate',
currency: 'MZN',
count: 1,
amount_minor: '5000',
},
],
groups: {
data: [
{
category: 'Material',
currency: 'MZN',
count: 1,
amount_minor: '1500',
},
],
total: 21,
current_page: 1,
last_page: 2,
},
}}
/>,
);
expect(html).toContain('Despesa não imputada: 40,00 USD');
expect(html).toContain('Imputação indeterminada: 50,00 MZN');
expect(html).toContain('15,00 MZN');
expect(html).toContain('Não há distribuição proporcional automática');
expect(html).toContain('category_page=2');
expect(html).toContain('supplier_page=2');
});
@@ -0,0 +1,42 @@
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { ProcurementContractInsights } from '../../resources/js/components/procurement-contract-insights';
test('contract association keeps unknown legacy orders distinct from orders without an association and payments', () => {
const html = renderToStaticMarkup(
<ProcurementContractInsights
data={{
coverage: { unknown: 1 },
currencies: [
{
classification: 'unknown',
currency: 'MZN',
count: 1,
amount_minor: '10000',
},
{
classification: 'partial',
currency: 'USD',
count: 1,
amount_minor: '20000',
},
{
classification: 'without_contract',
currency: null,
count: 1,
amount_minor: null,
},
],
}}
/>,
);
expect(html).toContain('Associação por determinar');
expect(html).toContain(
'não foram classificadas como compras fora de contrato',
);
expect(html).toContain('Parte das linhas com contrato associado');
expect(html).toContain('100,00 MZN');
expect(html).toContain('200,00 USD');
expect(html).toContain('Indeterminado');
expect(html).toContain('Não representam pagamentos');
});
@@ -3,6 +3,43 @@ import { describe, expect, it } from 'vitest';
import { ProcurementPaymentInsights } from '../../resources/js/components/procurement-payment-insights';
describe('confirmed payment expense', () => {
it('shows supplier identity with exact totals and preserves filters in its independent pagination', () => {
const html = renderToStaticMarkup(
<ProcurementPaymentInsights
pageHref="/relatorios?from=2026-11-01&search=REQ-QA"
data={{
from: null,
to: null,
coverage: {
invoices: 21,
indeterminate: 0,
confirmed_payments: 21,
},
currencies: [],
suppliers: {
data: [
{
supplier_id: 21,
supplier_name: '<script>synthetic</script>',
currency: 'MZN',
count: 1,
amount_minor: '9007199254740993',
},
],
total: 21,
current_page: 2,
last_page: 2,
},
}}
/>,
);
expect(html).toContain('Despesa por fornecedor');
expect(html).toContain('&lt;script&gt;synthetic&lt;/script&gt;');
expect(html).toContain('90.071.992.547.409,93 MZN');
expect(html).toContain('supplier_page=1');
expect(html).toContain('search=REQ-QA');
expect(html).toContain('Página 2 de 2');
});
it('keeps currencies separate and formats amounts without floating point', () => {
const html = renderToStaticMarkup(
<ProcurementPaymentInsights
+29 -1
View File
@@ -105,7 +105,31 @@ test('long review report preserves all proposals, original amounts and finance v
qualification: null,
opening: null,
award: null,
order: null,
order: {
id: 1,
number: 'OC-PARCELA-1',
currency: 'MZN',
total_minor: 4000,
},
orders: [
{
id: 1,
number: 'OC-PARCELA-1',
currency: 'MZN',
total_minor: 4000,
origins: [{ id: 42, number: 'REQ-SINTETICA-42' }],
},
{
id: 2,
number: 'OC-PARCELA-2',
currency: 'MZN',
total_minor: 6000,
origins: [
{ id: 42, number: 'REQ-SINTETICA-42' },
{ id: 43, number: 'REQ-SINTETICA-43' },
],
},
],
fulfilment: {
receipts: [],
finance_visible: false,
@@ -116,6 +140,10 @@ test('long review report preserves all proposals, original amounts and finance v
const html = render(ReviewReport, { report }, 'review');
for (const row of rows) expect(html).toContain(row.reference);
expect(html).toContain('report-fulfilment');
expect(html).toContain('OC-PARCELA-1');
expect(html).toContain('OC-PARCELA-2');
expect(html).toContain('REQ-SINTETICA-43');
expect(html).toContain('sem repartição neste relatório');
expect(html).not.toContain('QA-FACTURA-PRIVADA');
});
test('improvement report preserves details on every visible row without changing their disclosure state', () => {