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,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']);
+110 -4
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,7 +304,9 @@ 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));
$bindings[] = ['requisition_item_id' => $item->id, 'agreement_id' => $agreement->id];
if (! $partial || ! $second) {
$bindings[] = ['requisition_item_id' => $item->id, 'agreement_id' => $agreement->id];
}
}
$award = selectPurchaseAward($this);
approvePurchaseAward($this, $award);
@@ -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', () => {