commit compras1 3011
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-30 09:33:36 +02:00
parent 96b30368bc
commit 47649bd46c
163 changed files with 9419 additions and 145 deletions
+1 -1
View File
@@ -163,5 +163,5 @@ test('different companies may use their own identical reinforcement references a
test('public reinforcement example contains no company allocations', function () {
auth()->forgetGuards();
$this->get('/consulta/reforcos')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'reinforcements')->where('auth.user', null)->missing('budgets')->missing('reinforcements'));
$this->get('/consulta/reforcos')->assertRedirect('/orcamentos');
});
+72
View File
@@ -0,0 +1,72 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\BusinessClient;
use App\Models\Tenant;
use App\Models\User;
use App\Services\BusinessClients;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpException;
beforeEach(function () {
$this->tenant = Tenant::query()->create(['name' => 'Prestadora de teste']);
$this->admin = User::factory()->create(['tenant_id' => $this->tenant->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($this->admin)->withoutVite();
$this->clientInput = ['client_key' => (string) Str::uuid(), 'code' => 'CLIENTE-001', 'name' => 'Entidade cliente de teste',
'tax_number' => 'FISCAL-EXEMPLO', 'email' => null, 'address' => null, 'active' => true, 'reason' => 'Identificação sintética para conferir o cadastro.'];
});
test('business clients are saved once and preserve frozen snapshots after versioned edits', function () {
$service = app(BusinessClients::class);
$record = $service->save($this->admin, null, $this->clientInput);
expect($service->save($this->admin, null, $this->clientInput)->id)->toBe($record->id)
->and(BusinessClient::query()->count())->toBe(1);
$frozen = DB::transaction(fn () => $service->snapshot($this->admin, $record->id, 1));
$edited = $this->clientInput;
unset($edited['client_key']);
$edited['version'] = 1;
$edited['name'] = 'Cliente com nome actualizado';
$service->save($this->admin, $record->id, $edited);
expect($frozen['name'])->toBe('Entidade cliente de teste')->and($record->fresh()->name)->toBe($edited['name'])
->and($record->fresh()->version)->toBe(2);
$this->patch('/empresa/clientes/'.$record->id, $edited)->assertStatus(409);
$this->get('/empresa/clientes')->assertOk()->assertSee('Cliente com nome actualizado');
});
test('business clients refuse changed replays blank identities and a foreign company', function () {
$service = app(BusinessClients::class);
$record = $service->save($this->admin, null, $this->clientInput);
$this->post('/empresa/clientes', [...$this->clientInput, 'name' => 'Outro conteúdo para a mesma chave'])->assertStatus(409);
$this->post('/empresa/clientes', [...$this->clientInput, 'client_key' => (string) Str::uuid(), 'code' => ' ', 'name' => ' '])->assertSessionHasErrors(['code', 'name']);
$foreign = Tenant::query()->create(['name' => 'Outra empresa']);
$other = User::factory()->create(['tenant_id' => $foreign->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->actingAs($other)->patch('/empresa/clientes/'.$record->id, ['version' => 1, 'reason' => 'Não alterar outra empresa.'])->assertNotFound();
expect(BusinessClient::withoutGlobalScope('tenant')->count())->toBe(1);
});
test('a create replay preserves its identity after an edited code is reused', function () {
$service = app(BusinessClients::class);
$record = $service->save($this->admin, null, $this->clientInput);
$edited = $this->clientInput;
unset($edited['client_key']);
$service->save($this->admin, $record->id, [...$edited, 'version' => 1, 'code' => 'CLIENTE-RENOMEADO']);
$other = $service->save($this->admin, null, [...$this->clientInput, 'client_key' => (string) Str::uuid()]);
expect($service->save($this->admin, null, $this->clientInput)->id)->toBe($record->id)
->and($record->fresh()->code)->toBe('CLIENTE-RENOMEADO')
->and($other->fresh()->code)->toBe($this->clientInput['code'])
->and(BusinessClient::query()->count())->toBe(2);
});
test('client identities cannot be moved or deleted by direct SQL and inactive clients cannot start a new process', function () {
$service = app(BusinessClients::class);
$record = $service->save($this->admin, null, $this->clientInput);
expect(fn () => DB::transaction(fn () => DB::table('business_clients')->where('id', $record->id)->update(['client_key' => (string) Str::uuid(), 'version' => 2])))->toThrow(QueryException::class);
expect(fn () => DB::transaction(fn () => DB::table('business_clients')->where('id', $record->id)->delete()))->toThrow(QueryException::class);
$edited = $this->clientInput;
unset($edited['client_key']);
$service->save($this->admin, $record->id, [...$edited, 'version' => 1, 'active' => false]);
expect($service->choices($this->admin))->toBe([]);
expect(fn () => DB::transaction(fn () => $service->snapshot($this->admin, $record->id, 2)))->toThrow(HttpException::class);
});
+142
View File
@@ -0,0 +1,142 @@
<?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Finance\GeneralLedger\ConfiguredSales;
use Tempo\Finance\GeneralLedger\ConfiguredSalesSchema;
use Tempo\Finance\GeneralLedger\CycleSchema;
use Tempo\Finance\GeneralLedger\LedgerConfiguration;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\GeneralLedger\PayableJournal;
beforeEach(function () {
if (DB::getDriverName() !== 'pgsql' || ! getenv('RQ01_LEDGER_QA_SOURCE')) {
$this->markTestSkipped('Requires the owned PostgreSQL common-core regression.');
}
require_once getenv('RQ01_LEDGER_QA_SOURCE').'/bootstrap.php';
LedgerSchema::assertSynthetic(DB::connection());
LedgerSchema::install(DB::connection());
CycleSchema::install(DB::connection());
$this->scope = ['tenant_id' => 1, 'company_id' => 0, 'unit_id' => 0];
$this->accounts = [];
foreach (['CLIENTES', 'RECEITAS', 'IMPOSTO', 'RECEBIMENTOS', 'CUSTO', 'FORNECEDORES'] as $code) {
$this->accounts[$code] = DB::table('gl_accounts')->insertGetId($this->scope + ['code' => $code, 'label' => $code, 'is_movement' => true, 'currency' => 'MZN']);
}
DB::table('gl_periods')->insert($this->scope + ['period_key' => 'PERIODO', 'version' => 1, 'starts_on' => '2026-01-01', 'ends_on' => '2026-12-31',
'status' => 'open', 'created_by' => 1, 'reason' => 'Período sintético do teste.', 'created_at' => now()]);
$this->supplierSource = ['effect_type' => 'supplier_payable.recognised', 'origin_key' => 'supplier-native', 'obligation_id' => 1,
'principal_minor' => 10000, 'tax_minor' => 0, 'currency' => 'MZN', 'history_imported' => false, 'compatible' => true, 'recognition_revision' => str_repeat('a', 64)];
salesLedgerRule($this, 'FORNECEDOR', 'supplier_payable.recognised', 'CUSTO', 'FORNECEDORES', null, PayableJournal::HOST_POLICY);
$this->customerSource = ['effect_type' => 'sales.invoice', 'source_contract' => 'COMMON-RECEIVABLES-v1', 'origin_key' => 'invoice-native',
'obligation_id' => 1, 'source_id' => 1, 'invoice_id' => 1, 'client_id' => 19, 'amount_minor' => 11600, 'base_minor' => 10000,
'tax_minor' => 1600, 'currency' => 'MZN', 'history_imported' => false, 'compatible' => true, 'recognition_revision' => str_repeat('b', 64)];
});
function salesLedgerRule(object $test, string $key, string $effect, string $debit, string $credit, ?string $tax = null, string $policy = ConfiguredSales::CONTRACT): void
{
if ($policy === ConfiguredSales::CONTRACT) {
$configuration = new LedgerConfiguration(DB::connection(), $test->scope, 1, fn () => null, fn () => null);
$configuration->command('sales_rule', ['rule_key' => $key, 'effect_type' => $effect,
'valid_from' => '2026-01-01', 'valid_to' => '2026-12-31', 'debit_account_id' => $test->accounts[$debit],
'credit_account_id' => $test->accounts[$credit], 'tax_account_id' => $tax === null ? null : $test->accounts[$tax],
'basis_hash' => $configuration->basis('sales_rule')['hash'], 'reason' => 'Regra explicitamente configurada no teste.'], (string) Str::uuid());
return;
}
DB::table('gl_rules')->insert($test->scope + ['rule_key' => $key, 'version' => 1, 'policy' => $policy, 'effect_type' => $effect,
'currency' => 'MZN', 'valid_from' => '2026-01-01', 'valid_to' => '2026-12-31', 'debit_account_id' => $test->accounts[$debit],
'credit_account_id' => $test->accounts[$credit], ...($policy === ConfiguredSales::CONTRACT ? ['tax_account_id' => $tax === null ? null : $test->accounts[$tax]] : []),
'created_by' => 1, 'reason' => 'Regra explicitamente configurada no teste.', 'created_at' => now()]);
}
function salesLedgerWriter(object $test, int $actor): PayableJournal
{
return new PayableJournal(DB::connection(), $test->scope, $actor, 'person-'.$actor, fn () => null, fn () => null,
fn () => $test->supplierSource, checkpoint: $test->ledgerCheckpoint ?? null, additionalSource: fn () => $test->customerSource, hostPolicy: PayableJournal::HOST_POLICY);
}
function salesLedgerPrepare(object $test, string $rule = 'VENDA'): array
{
return salesLedgerWriter($test, 1)->command('effect-prepare', ['effect_type' => $test->customerSource['effect_type'], 'source_id' => 1,
'journal_on' => '2026-11-29', 'period_key' => 'PERIODO', 'rule_key' => $rule, 'reason' => 'Preparação explícita do documento no teste.'], (string) Str::uuid());
}
function salesLedgerReview(object $test, array $proposal): void
{
salesLedgerWriter($test, 2)->command('validate', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'decision' => 'approved', 'reason' => 'Conferência por outra pessoa no teste.'], (string) Str::uuid());
}
test('configured customer journals extend a populated ledger while preserving supplier journals and their validator', function () {
$supplier = salesLedgerWriter($this, 1)->command('prepare', ['obligation_id' => 1, 'journal_on' => '2026-11-29', 'period_key' => 'PERIODO',
'rule_key' => 'FORNECEDOR', 'reason' => 'Preparação do fornecedor anterior à extensão.'], (string) Str::uuid());
salesLedgerReview($this, $supplier);
salesLedgerWriter($this, 1)->command('post', ['proposal_id' => $supplier['proposal_id'], 'revision' => $supplier['revision'],
'reason' => 'Lançamento anterior à extensão comercial.'], (string) Str::uuid());
$before = DB::table('gl_journals')->get()->toJson();
ConfiguredSalesSchema::installForHost(DB::connection(), ConfiguredSales::CONTRACT, fn ($db) => LedgerSchema::assertSynthetic($db));
expect(DB::table('gl_journals')->get()->toJson())->toBe($before);
salesLedgerRule($this, 'VENDA', 'sales.invoice', 'CLIENTES', 'RECEITAS', 'IMPOSTO');
$proposal = salesLedgerPrepare($this);
salesLedgerReview($this, $proposal);
$input = ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'reason' => 'Aplicação única do documento de cliente.'];
$key = (string) Str::uuid();
$result = salesLedgerWriter($this, 1)->command('post', $input, $key);
expect($result['state'])->toBe('posted')->and(salesLedgerWriter($this, 1)->command('post', $input, $key)['replayed'])->toBeTrue();
$lines = DB::table('gl_lines')->where('journal_id', $result['journal_id'])->orderBy('line_no')->get();
expect($lines)->toHaveCount(3)->and($lines->sum('debit_minor'))->toBe(11600)->and($lines->sum('credit_minor'))->toBe(11600)
->and($lines->pluck('account_id')->all())->toBe([$this->accounts['CLIENTES'], $this->accounts['RECEITAS'], $this->accounts['IMPOSTO']]);
foreach (DB::table('gl_journals')->pluck('id') as $id) {
DB::select('SELECT gl_assert_balanced(?)', [$id]);
}
expect(DB::table('gl_journals')->count())->toBe(2);
});
test('configured customer capture rejects amount and account mismatches and independent review remains mandatory', function () {
ConfiguredSalesSchema::installForHost(DB::connection(), ConfiguredSales::CONTRACT, fn ($db) => LedgerSchema::assertSynthetic($db));
salesLedgerRule($this, 'VENDA', 'sales.invoice', 'CLIENTES', 'RECEITAS', 'IMPOSTO');
$this->customerSource['tax_minor'] = 1500;
expect(fn () => salesLedgerPrepare($this))->toThrow(DomainException::class);
$this->customerSource['tax_minor'] = 1600;
$proposal = salesLedgerPrepare($this);
expect(fn () => salesLedgerWriter($this, 1)->command('validate', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'decision' => 'approved', 'reason' => 'A mesma pessoa não pode validar.'], (string) Str::uuid()))->toThrow(DomainException::class);
salesLedgerReview($this, $proposal);
$this->customerSource['recognition_revision'] = str_repeat('c', 64);
expect(fn () => salesLedgerWriter($this, 1)->command('post', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'reason' => 'Uma fotografia alterada não pode ser aplicada.'], (string) Str::uuid()))->toThrow(DomainException::class);
expect(DB::table('gl_journals')->count())->toBe(0);
});
test('an explicitly untaxed customer invoice retains two lines without an invented tax account', function () {
ConfiguredSalesSchema::installForHost(DB::connection(), ConfiguredSales::CONTRACT, fn ($db) => LedgerSchema::assertSynthetic($db));
salesLedgerRule($this, 'VENDA', 'sales.invoice', 'CLIENTES', 'RECEITAS');
$this->customerSource['tax_minor'] = 0;
$this->customerSource['amount_minor'] = 10000;
$proposal = salesLedgerPrepare($this);
salesLedgerReview($this, $proposal);
$result = salesLedgerWriter($this, 1)->command('post', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'reason' => 'Documento explicitamente sem imposto no teste.'], (string) Str::uuid());
expect(DB::table('gl_lines')->where('journal_id', $result['journal_id'])->count())->toBe(2);
});
test('a failed taxed posting rolls back the whole journal and recovers once using the same command', function () {
ConfiguredSalesSchema::installForHost(DB::connection(), ConfiguredSales::CONTRACT, fn ($db) => LedgerSchema::assertSynthetic($db));
salesLedgerRule($this, 'VENDA', 'sales.invoice', 'CLIENTES', 'RECEITAS', 'IMPOSTO');
$proposal = salesLedgerPrepare($this);
salesLedgerReview($this, $proposal);
$this->ledgerCheckpoint = function (string $stage): void {
if ($stage === 'after_lines') {
throw new RuntimeException('Interrupted before the native journal receipt.');
}
};
$input = ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'reason' => 'Recuperação da aplicação interrompida no teste.'];
$key = (string) Str::uuid();
expect(fn () => salesLedgerWriter($this, 1)->command('post', $input, $key))->toThrow(RuntimeException::class);
expect(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('gl_lines')->count())->toBe(0)
->and(DB::table('gl_commands')->where('command_key', $key)->exists())->toBeFalse();
$this->ledgerCheckpoint = null;
salesLedgerWriter($this, 1)->command('post', $input, $key);
salesLedgerWriter($this, 1)->command('post', $input, $key);
expect(DB::table('gl_journals')->count())->toBe(1)->and(DB::table('gl_lines')->count())->toBe(3);
});
+219
View File
@@ -0,0 +1,219 @@
<?php
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Finance\GeneralLedger\ConfiguredSales;
use Tempo\Finance\GeneralLedger\ConfiguredSalesSchema;
use Tempo\Finance\GeneralLedger\CustomerInvoiceMath;
use Tempo\Finance\GeneralLedger\CycleSchema;
use Tempo\Finance\GeneralLedger\LedgerConfiguration;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\GeneralLedger\PayableJournal;
use Tempo\Finance\GeneralLedger\Receivables;
use Tempo\Finance\GeneralLedger\ReceivablesSchema;
beforeEach(function () {
if (DB::getDriverName() !== 'pgsql' || ! getenv('RQ01_LEDGER_QA_SOURCE')) {
$this->markTestSkipped('Requires the owned PostgreSQL common-core regression.');
}
require_once getenv('RQ01_LEDGER_QA_SOURCE').'/bootstrap.php';
LedgerSchema::assertSynthetic(DB::connection());
ReceivablesSchema::installForHost(DB::connection(), ReceivablesSchema::CONTRACT, fn ($db) => LedgerSchema::assertSynthetic($db));
$this->customerVersion = 1;
$this->customerScope = ['tenant_id' => 1, 'company_id' => 0, 'unit_id' => 0];
$this->invoiceInput = ['client_id' => 31, 'client_version' => 1, 'series_key' => 'VENDA-2026', 'issued_on' => '2026-11-29',
'due_on' => '2026-12-29', 'reason' => 'Documento inteiramente sintético para conferir o núcleo comum.',
'lines' => [['stock_item_id' => 11, 'quantity_milli' => 1000, 'unit_price_minor' => 10000, 'tax_rate' => '16',
'tax_basis' => 'Tratamento fiscal ilustrativo explicitamente parametrizado no teste.']]];
customerBook($this, 1)->command('series', ['series_key' => 'VENDA-2026', 'prefix' => 'V/2026', 'starts_on' => '2026-01-01',
'ends_on' => '2026-12-31', 'first_number' => 1, 'reason' => 'Série sintética explicitamente configurada no teste.'], (string) Str::uuid());
});
function customerBook(object $test, int $actor, ?array $scope = null): Receivables
{
return new Receivables(DB::connection(), $scope ?? $test->customerScope, $actor, 'person-'.$actor,
function (string $action) use ($test): void {
if (in_array($action, $test->customerDenied ?? [], true)) {
throw new DomainException('Actor authority revoked.');
}
}, fn () => DB::select('SELECT pg_advisory_xact_lock(91741)'),
fn (string $kind, array $input) => ['client' => ['id' => 31, 'version' => $test->customerVersion, 'name' => 'Cliente sintético'],
...($kind === 'invoice' ? ['lines' => $input['lines']] : [])], $test->customerCheckpoint ?? null);
}
function customerIssuedInvoice(object $test): array
{
$proposal = customerBook($test, 1)->command('invoice_prepare', $test->invoiceInput, (string) Str::uuid());
customerBook($test, 2)->command('invoice_review', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'decision' => 'approved', 'reason' => 'Conferência explícita por outra pessoa no teste.'], (string) Str::uuid());
return customerBook($test, 1)->command('invoice_issue', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'reason' => 'Emissão do documento sintético já conferido.'], (string) Str::uuid());
}
function customerConfirmedReceipt(object $test, int $amount, string $reference): array
{
$proposal = customerBook($test, 1)->command('receipt_prepare', ['client_id' => 31, 'client_version' => $test->customerVersion,
'amount_minor' => $amount, 'received_on' => '2026-11-29', 'reference' => $reference,
'reason' => 'Recebimento documental fictício, sem transferência bancária.'], (string) Str::uuid());
customerBook($test, 2)->command('receipt_decide', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'decision' => 'confirmed', 'reason' => 'Conferência distinta do recebimento fictício.'], (string) Str::uuid());
return $proposal;
}
test('customer issue receipts explicit partial allocation and reversal share one immutable book', function () {
$invoice = customerIssuedInvoice($this);
expect($invoice['reference'])->toBe('V/2026/1');
$original = DB::table('cr_invoices')->sole();
$receipt = customerConfirmedReceipt($this, 4000, 'REC-001');
$allocation = customerBook($this, 1)->command('allocation_prepare', ['invoice_id' => $invoice['invoice_id'], 'receipt_id' => $receipt['proposal_id'],
'amount_minor' => 4000, 'reason' => 'Imputação explícita do recebimento à factura.'], (string) Str::uuid());
$decision = ['proposal_id' => $allocation['proposal_id'], 'revision' => $allocation['revision'], 'decision' => 'confirmed',
'reason' => 'Confirmar a imputação documental por outra pessoa.'];
$key = (string) Str::uuid();
customerBook($this, 2)->command('allocation_decide', $decision, $key);
expect(customerBook($this, 2)->command('allocation_decide', $decision, $key)['replayed'])->toBeTrue()
->and(customerBook($this, 1)->invoice($invoice['invoice_id'])['outstanding_minor'])->toBe(7600);
expect(fn () => customerBook($this, 1)->command('allocation_prepare', ['invoice_id' => $invoice['invoice_id'], 'receipt_id' => $receipt['proposal_id'],
'amount_minor' => 1, 'reason' => 'Não imputar mais do que o saldo do recebimento.'], (string) Str::uuid()))->toThrow(DomainException::class);
$source = customerBook($this, 1)->ledgerSource('receivable.allocated', $allocation['proposal_id']);
expect($source['amount_minor'])->toBe(4000)->and($source['client_id'])->toBe(31)->and($source['source_contract'])->toBe(ReceivablesSchema::CONTRACT);
$reversal = customerBook($this, 1)->command('reversal_prepare', ['allocation_id' => $allocation['proposal_id'], 'reason' => 'Estorno explícito da imputação fictícia.'], (string) Str::uuid());
customerBook($this, 2)->command('reversal_decide', ['proposal_id' => $reversal['proposal_id'], 'revision' => $reversal['revision'],
'decision' => 'confirmed', 'reason' => 'Confirmar o estorno por outra pessoa.'], (string) Str::uuid());
expect(customerBook($this, 1)->invoice($invoice['invoice_id'])['outstanding_minor'])->toBe(11600)
->and(DB::table('cr_invoices')->sole())->toEqual($original)
->and(customerBook($this, 1)->ledgerSource('receivable.reversed', $reversal['proposal_id'])['amount_minor'])->toBe(4000);
expect(fn () => customerBook($this, 1)->command('reversal_prepare', ['allocation_id' => $allocation['proposal_id'],
'reason' => 'Não estornar duas vezes a mesma imputação.'], (string) Str::uuid()))->toThrow(DomainException::class);
});
test('invoice review refuses its preparer and stale client revisions without consuming a series number', function () {
$proposal = customerBook($this, 1)->command('invoice_prepare', $this->invoiceInput, (string) Str::uuid());
$decision = ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'decision' => 'approved',
'reason' => 'Revisão explícita da fotografia documental.'];
expect(fn () => customerBook($this, 1)->command('invoice_review', $decision, (string) Str::uuid()))->toThrow(DomainException::class);
$this->customerVersion = 2;
expect(fn () => customerBook($this, 2)->command('invoice_review', $decision, (string) Str::uuid()))->toThrow(DomainException::class);
expect(DB::table('cr_invoice_reviews')->count())->toBe(0)->and(DB::table('cr_invoices')->count())->toBe(0);
$this->invoiceInput['client_version'] = 2;
expect(customerIssuedInvoice($this)['reference'])->toBe('V/2026/1');
});
test('a customer command interruption rolls back issue numbering and a revoked authority cannot replay', function () {
$proposal = customerBook($this, 1)->command('invoice_prepare', $this->invoiceInput, (string) Str::uuid());
customerBook($this, 2)->command('invoice_review', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'decision' => 'approved', 'reason' => 'Conferência antes do ensaio de recuperação.'], (string) Str::uuid());
$input = ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'reason' => 'Emissão documental com recuperação do mesmo comando.'];
$key = (string) Str::uuid();
$this->customerCheckpoint = fn () => throw new RuntimeException('Interrupted before command receipt.');
expect(fn () => customerBook($this, 1)->command('invoice_issue', $input, $key))->toThrow(RuntimeException::class);
expect(DB::table('cr_invoices')->count())->toBe(0);
$this->customerCheckpoint = null;
$issued = customerBook($this, 1)->command('invoice_issue', $input, $key);
expect($issued['reference'])->toBe('V/2026/1')->and(customerBook($this, 1)->command('invoice_issue', $input, $key)['replayed'])->toBeTrue();
$this->customerDenied = ['invoice_issue'];
expect(fn () => customerBook($this, 1)->command('invoice_issue', $input, $key))->toThrow(DomainException::class);
expect(fn () => customerBook($this, 1, ['tenant_id' => 2, 'company_id' => 0, 'unit_id' => 0])->invoice($issued['invoice_id']))->toThrow(DomainException::class);
});
test('receipt confirmation is independent and duplicate evidence cannot create a second confirmed receipt', function () {
customerConfirmedReceipt($this, 4000, 'REC-REPETIDO');
$other = customerBook($this, 1)->command('receipt_prepare', ['client_id' => 31, 'client_version' => 1, 'amount_minor' => 4000,
'received_on' => '2026-11-29', 'reference' => 'REC-REPETIDO', 'reason' => 'Proposta repetida para conferir a referência documental.'], (string) Str::uuid());
$decision = ['proposal_id' => $other['proposal_id'], 'revision' => $other['revision'], 'decision' => 'confirmed', 'reason' => 'Não confirmar evidência documental já confirmada.'];
expect(fn () => customerBook($this, 1)->command('receipt_decide', $decision, (string) Str::uuid()))->toThrow(DomainException::class);
expect(fn () => customerBook($this, 2)->command('receipt_decide', $decision, (string) Str::uuid()))->toThrow(DomainException::class);
expect(fn () => DB::transaction(fn () => DB::table('cr_receipt_decisions')->insert($this->customerScope + ['proposal_id' => $other['proposal_id'],
'revision' => $other['revision'], 'decision' => 'confirmed', 'created_by' => 2, 'person' => 'person-2',
'reason' => 'A guarda SQL também recusa a duplicação.', 'created_at' => now()])))->toThrow(QueryException::class);
expect(DB::table('cr_receipt_decisions')->count())->toBe(1);
});
test('customer amounts use explicit tax treatment and remain consistent at fractional quantity and integer limits', function () {
$result = CustomerInvoiceMath::calculate([
['quantity_milli' => 333, 'unit_price_minor' => 101, 'tax_rate' => '16', 'tax_basis' => 'Taxa ilustrativa explícita.'],
['quantity_milli' => 1000, 'unit_price_minor' => 500, 'tax_rate' => '0', 'tax_basis' => 'Tratamento sem imposto explicitamente documentado.'],
]);
expect($result['base_minor'])->toBe(534)->and($result['tax_minor'])->toBe(5)->and($result['total_minor'])->toBe(539);
expect(fn () => CustomerInvoiceMath::calculate([['quantity_milli' => 1000, 'unit_price_minor' => 100, 'tax_rate' => '0', 'tax_basis' => '']]))->toThrow(InvalidArgumentException::class);
expect(fn () => CustomerInvoiceMath::calculate([['quantity_milli' => PHP_INT_MAX, 'unit_price_minor' => PHP_INT_MAX, 'tax_rate' => '16', 'tax_basis' => 'Não exceder a precisão.']]))->toThrow(InvalidArgumentException::class);
});
test('native issued invoices confirmed allocations and reversals feed the existing general ledger writer', function () {
LedgerSchema::install(DB::connection());
CycleSchema::install(DB::connection());
ConfiguredSalesSchema::installForHost(DB::connection(), ConfiguredSales::CONTRACT, fn ($db) => LedgerSchema::assertSynthetic($db));
$accounts = [];
foreach (['CLIENTE-CONFIGURADO', 'RECEITA-CONFIGURADA', 'IMPOSTO-CONFIGURADO', 'RECEBIMENTO-CONFIGURADO'] as $code) {
$accounts[] = DB::table('gl_accounts')->insertGetId($this->customerScope + ['code' => $code, 'label' => $code, 'is_movement' => true, 'currency' => 'MZN']);
}
DB::table('gl_periods')->insert($this->customerScope + ['period_key' => '2026', 'version' => 1, 'starts_on' => '2026-01-01',
'ends_on' => '2026-12-31', 'status' => 'open', 'created_by' => 1, 'reason' => 'Período sintético explicitamente configurado.', 'created_at' => now()]);
$configuration = new LedgerConfiguration(DB::connection(), $this->customerScope, 1, fn () => null, fn () => null);
foreach ([['VENDA', 'sales.invoice', $accounts[0], $accounts[1], $accounts[2]],
['RECEBIMENTO', 'receivable.allocated', $accounts[3], $accounts[0], null],
['ESTORNO', 'receivable.reversed', $accounts[0], $accounts[3], null]] as [$key, $effect, $debit, $credit, $tax]) {
$configuration->command('sales_rule', ['rule_key' => $key, 'effect_type' => $effect, 'valid_from' => '2026-01-01', 'valid_to' => '2026-12-31',
'debit_account_id' => $debit, 'credit_account_id' => $credit, 'tax_account_id' => $tax,
'basis_hash' => $configuration->basis('sales_rule')['hash'], 'reason' => 'Correspondência explícita das contas de cliente.'], (string) Str::uuid());
}
$writer = fn (int $actor) => new PayableJournal(DB::connection(), $this->customerScope, $actor, 'person-'.$actor, fn () => null, fn () => null,
fn () => throw new DomainException('Supplier source is outside this customer test.'),
additionalSource: fn (string $kind, int $id) => customerBook($this, $actor)->ledgerSource($kind, $id), hostPolicy: PayableJournal::HOST_POLICY);
$post = function (string $effect, int $id, string $rule) use ($writer): void {
$proposal = $writer(1)->command('effect-prepare', ['effect_type' => $effect, 'source_id' => $id, 'journal_on' => '2026-11-29',
'period_key' => '2026', 'rule_key' => $rule, 'reason' => 'Preparação do efeito documental comum de cliente.'], (string) Str::uuid());
$writer(2)->command('validate', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'decision' => 'approved',
'reason' => 'Conferência distinta da fotografia contabilística.'], (string) Str::uuid());
$writer(1)->command('post', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'reason' => 'Aplicação pelo mesmo escritor contabilístico.'], (string) Str::uuid());
};
$invoice = customerIssuedInvoice($this);
$post('sales.invoice', $invoice['invoice_id'], 'VENDA');
$receipt = customerConfirmedReceipt($this, 4000, 'REC-INTEGRADO');
$allocation = customerBook($this, 1)->command('allocation_prepare', ['invoice_id' => $invoice['invoice_id'], 'receipt_id' => $receipt['proposal_id'],
'amount_minor' => 4000, 'reason' => 'Imputação explícita no percurso integrado.'], (string) Str::uuid());
customerBook($this, 2)->command('allocation_decide', ['proposal_id' => $allocation['proposal_id'], 'revision' => $allocation['revision'],
'decision' => 'confirmed', 'reason' => 'Confirmação distinta da imputação integrada.'], (string) Str::uuid());
$post('receivable.allocated', $allocation['proposal_id'], 'RECEBIMENTO');
expect(customerBook($this, 1)->invoice($invoice['invoice_id'])['outstanding_minor'])->toBe(7600);
$reversal = customerBook($this, 1)->command('reversal_prepare', ['allocation_id' => $allocation['proposal_id'], 'reason' => 'Estorno explícito do recebimento imputado.'], (string) Str::uuid());
customerBook($this, 2)->command('reversal_decide', ['proposal_id' => $reversal['proposal_id'], 'revision' => $reversal['revision'],
'decision' => 'confirmed', 'reason' => 'Confirmação distinta do estorno documental.'], (string) Str::uuid());
$post('receivable.reversed', $reversal['proposal_id'], 'ESTORNO');
expect(DB::table('gl_journals')->count())->toBe(3)->and(DB::table('gl_lines')->count())->toBe(7)
->and(DB::table('gl_lines')->sum('debit_minor'))->toBe('19600')->and(DB::table('gl_lines')->sum('credit_minor'))->toBe('19600')
->and(customerBook($this, 1)->invoice($invoice['invoice_id'])['outstanding_minor'])->toBe(11600);
});
test('database customer guards refuse balance bypasses and deletion of an issued document', function () {
$invoice = customerIssuedInvoice($this);
$receipt = customerConfirmedReceipt($this, 4000, 'REC-GUARDAS');
$revision = str_repeat('c', 64);
$proposal = DB::table('cr_allocation_proposals')->insertGetId($this->customerScope + ['invoice_id' => $invoice['invoice_id'], 'receipt_id' => $receipt['proposal_id'],
'amount_minor' => 5000, 'snapshot' => '{}', 'revision' => $revision, 'created_by' => 1, 'person' => 'person-1',
'reason' => 'Proposta malformada para conferir a guarda SQL.', 'created_at' => now()]);
expect(fn () => DB::transaction(fn () => DB::table('cr_allocation_decisions')->insert($this->customerScope + ['proposal_id' => $proposal,
'revision' => $revision, 'decision' => 'confirmed', 'created_by' => 2, 'person' => 'person-2',
'reason' => 'Não confirmar mais do que o saldo recebido.', 'created_at' => now()])))->toThrow(QueryException::class);
expect(fn () => DB::transaction(fn () => DB::table('cr_invoices')->where('id', $invoice['invoice_id'])->delete()))->toThrow(QueryException::class);
expect(DB::table('cr_allocation_decisions')->count())->toBe(0)->and(DB::table('cr_invoices')->count())->toBe(1);
});
test('warehouse customer evidence omits prices and receipt data requires its own authority', function () {
$invoice = customerIssuedInvoice($this);
customerConfirmedReceipt($this, 4000, 'REC-PRIVADO');
$this->customerDenied = ['view', 'receipts_view'];
$delivery = customerBook($this, 3)->deliveryInvoice($invoice['invoice_id']);
expect($delivery['lines'][0]['quantity_milli'])->toBe(1000)->and($delivery['lines'][0]['line_no'])->toBe(1)
->and($delivery['lines'][0])->not->toHaveKeys(['unit_price_minor', 'tax_rate', 'tax_basis', 'base_minor', 'tax_minor', 'total_minor']);
expect(fn () => customerBook($this, 3)->invoice($invoice['invoice_id']))->toThrow(DomainException::class);
$this->customerDenied = ['receipts_view'];
expect(customerBook($this, 1)->workspace()['receipts'])->toBe([]);
expect(fn () => customerBook($this, 1)->workspace(withReceipts: true))->toThrow(DomainException::class);
$this->customerDenied = [];
expect(customerBook($this, 2)->workspace(withReceipts: true)['receipts'][0]['reference'])->toBe('REC-PRIVADO');
});
+113
View File
@@ -0,0 +1,113 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\StockMovement;
use App\Models\User;
use App\Services\BusinessClients;
use App\Services\CustomerDeliveries;
use App\Services\CustomerDeliverySchema;
use App\Services\CustomerSales;
use App\Services\ReceiptWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\GeneralLedger\ReceivablesSchema;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
beforeEach(function () {
if (DB::getDriverName() !== 'pgsql' || ! getenv('RQ01_LEDGER_QA_SOURCE')) {
$this->markTestSkipped('Requires the owned PostgreSQL common-core regression.');
}
require_once getenv('RQ01_LEDGER_QA_SOURCE').'/bootstrap.php';
LedgerSchema::assertSynthetic(DB::connection());
$this->f = receiptFixture('10.000');
$this->actingAs($this->f['receiver']);
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], receiptPayload($this->f, '10.000'));
ReceivablesSchema::installForHost(DB::connection(), ReceivablesSchema::CONTRACT, fn ($db) => LedgerSchema::assertSynthetic($db));
CustomerDeliverySchema::install(DB::connection(), fn ($db) => LedgerSchema::assertSynthetic($db));
config(['third_party.sales_enabled' => true, 'customer_sales.qa_enabled' => true]);
$this->salesAdmin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Admin]);
$this->salesFinance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->salesReviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id, 'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($this->salesAdmin);
$this->salesClient = app(BusinessClients::class)->save($this->salesAdmin, null, ['client_key' => (string) Str::uuid(), 'code' => 'CLIENTE-NATIVO',
'name' => 'Cliente inteiramente sintético', 'active' => true, 'reason' => 'Cliente sintético para conferir a ligação real entre módulos.']);
app(CustomerSales::class)->command($this->salesAdmin, 'series', ['operation_key' => (string) Str::uuid(), 'series_key' => 'VENDA-2026',
'prefix' => 'V/2026', 'starts_on' => '2026-01-01', 'ends_on' => '2026-12-31', 'first_number' => '1', 'reason' => 'Configuração explícita da série de teste.']);
$this->saleInput = ['operation_key' => (string) Str::uuid(), 'client_id' => (string) $this->salesClient->id, 'client_version' => '1',
'series_key' => 'VENDA-2026', 'issued_on' => '2026-11-29', 'due_on' => '2026-12-29', 'reason' => 'Preparação documental da venda inteiramente sintética.',
'lines' => [['stock_item_id' => (string) $this->f['stock']->id, 'quantity' => '2.000', 'unit_price' => '100.00',
'tax_rate' => '16', 'tax_basis' => 'Taxa ilustrativa explicitamente indicada para este teste.']]];
});
function nativeCustomerCommand(object $test, User $actor, string $action, array $data): array
{
$test->actingAs($actor);
return app(CustomerSales::class)->command($actor, $action, ['operation_key' => (string) Str::uuid(),
'reason' => 'Intervenção explícita no percurso nativo de teste.', ...$data]);
}
function nativeCustomerInvoice(object $test): array
{
$proposal = nativeCustomerCommand($test, $test->f['issuer'], 'invoice_prepare', $test->saleInput);
nativeCustomerCommand($test, $test->salesFinance, 'invoice_review', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'decision' => 'approved']);
return nativeCustomerCommand($test, $test->f['issuer'], 'invoice_issue', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision']]);
}
test('native customer invoice physical deliveries and partial receipt use the original common writers once', function () {
$invoice = nativeCustomerInvoice($this);
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(10000);
$this->actingAs($this->f['receiver']);
$data = ['operation_key' => (string) Str::uuid(), 'invoice_id' => $invoice['invoice_id'], 'line_no' => '1', 'warehouse_id' => (string) $this->f['warehouse']->id,
'quantity' => '1.000', 'reference' => 'ENT-CLIENTE-01', 'reason' => 'Entrega física parcial ao cliente indicado na factura.'];
$delivery = app(CustomerDeliveries::class)->record($this->f['receiver'], $data);
expect(app(CustomerDeliveries::class)->record($this->f['receiver'], $data)['replayed'])->toBeTrue()
->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(9000);
$movement = StockMovement::query()->where('stock_operation_id', $delivery['stock_operation_id'])->sole();
expect($movement->snapshot['inventory_operation_hash'])->toMatch('/^[a-f0-9]{64}$/D')
->and($movement->snapshot['sales_invoice']['invoice_id'])->toBe($invoice['invoice_id']);
app(CustomerDeliveries::class)->record($this->f['receiver'], [...$data, 'operation_key' => (string) Str::uuid(), 'reference' => 'ENT-CLIENTE-02']);
expect(fn () => app(CustomerDeliveries::class)->record($this->f['receiver'], [...$data, 'operation_key' => (string) Str::uuid(),
'reference' => 'ENT-CLIENTE-03', 'quantity' => '0.001']))->toThrow(HttpException::class);
expect((int) StockMovement::query()->sum('quantity_milli'))->toBe(8000)->and(DB::table('customer_deliveries')->count())->toBe(2);
$warehouse = app(CustomerDeliveries::class)->workspace($this->f['receiver']);
expect($warehouse['invoices'][0]['lines'][0]['remaining_milli'])->toBe(0)
->and($warehouse['invoices'][0]['lines'][0])->not->toHaveKeys(['unit_price_minor', 'tax_minor', 'total_minor']);
$receipt = nativeCustomerCommand($this, $this->salesFinance, 'receipt_prepare', ['client_id' => $this->salesClient->id, 'client_version' => 1,
'amount' => '100.00', 'received_on' => '2026-11-29', 'reference' => 'REC-CLIENTE-01']);
nativeCustomerCommand($this, $this->salesReviewer, 'receipt_decide', ['proposal_id' => $receipt['proposal_id'], 'revision' => $receipt['revision'], 'decision' => 'confirmed']);
$allocation = nativeCustomerCommand($this, $this->salesFinance, 'allocation_prepare', ['invoice_id' => $invoice['invoice_id'], 'receipt_id' => $receipt['proposal_id'], 'amount' => '100.00']);
nativeCustomerCommand($this, $this->salesReviewer, 'allocation_decide', ['proposal_id' => $allocation['proposal_id'], 'revision' => $allocation['revision'], 'decision' => 'confirmed']);
expect(app(CustomerSales::class)->engine($this->salesReviewer)->invoice($invoice['invoice_id'])['outstanding_minor'])->toBe(13200)
->and(DB::table('cr_invoices')->count())->toBe(1)->and(DB::table('cr_allocation_decisions')->count())->toBe(1);
});
test('an invoice does not fabricate stock when the linked physical delivery exceeds available quantity', function () {
$this->saleInput['lines'][0]['quantity'] = '12.000';
$invoice = nativeCustomerInvoice($this);
$this->actingAs($this->f['receiver']);
expect(fn () => app(CustomerDeliveries::class)->record($this->f['receiver'], ['operation_key' => (string) Str::uuid(),
'invoice_id' => $invoice['invoice_id'], 'line_no' => 1, 'warehouse_id' => $this->f['warehouse']->id, 'quantity' => '11.000',
'reference' => 'ENT-SEM-SALDO', 'reason' => 'A factura não substitui a existência física de material.']))->toThrow(ValidationException::class);
expect(DB::table('customer_deliveries')->count())->toBe(0)->and(DB::table('stock_operations')->count())->toBe(0)
->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(10000);
});
test('native customer roles do not confer warehouse financial access or allow procurement to confirm receipts', function () {
$invoice = nativeCustomerInvoice($this);
$this->actingAs($this->f['receiver']);
expect(fn () => app(CustomerSales::class)->engine($this->f['receiver'])->invoice($invoice['invoice_id']))->toThrow(HttpException::class);
expect(app(CustomerSales::class)->engine($this->f['receiver'])->deliveryInvoice($invoice['invoice_id'])['lines'][0]['quantity_milli'])->toBe(2000);
$this->actingAs($this->f['issuer']);
expect(fn () => app(CustomerSales::class)->command($this->f['issuer'], 'receipt_prepare', []))->toThrow(HttpException::class);
$this->f['receiver']->forceFill(['purchasing_role' => PurchasingRole::Requester])->save();
expect($this->f['receiver']->fresh()->purchasing_role)->toBe(PurchasingRole::Requester);
$this->actingAs($this->f['receiver']);
expect(fn () => app(CustomerDeliveries::class)->workspace($this->f['receiver']))->toThrow(HttpException::class);
});
+1 -1
View File
@@ -327,7 +327,7 @@ test('spare receipts preserve authorised item and equipment traceability', funct
});
test('public equipment page has fictional props only', function () {
$this->get('/consulta/equipamentos')->assertInertia(fn (Assert $p) => $p->component('preview/index')->where('initialScreen', 'equipment')->where('auth.user', null)->missing('equipment')->missing('parts'));
$this->get('/consulta/equipamentos')->assertRedirect('/equipamentos');
});
test('technical reviewer of another department and foreign company cannot decide', function () {
+4 -4
View File
@@ -4,12 +4,12 @@ use App\Services\EvaluationAccess;
use App\Services\EvaluationNavigation;
use Illuminate\Http\Request;
test('local evaluation root opens the dashboard while other installations retain their home page', function () {
$this->get('/')->assertOk();
test('local evaluation root retains its dashboard while other guest installations use login', function () {
$this->get('/')->assertRedirect('/login');
app()->instance('env', 'payable-testing');
$this->get('http://127.0.0.1:8005/')->assertRedirect('/dashboard');
$this->get('http://127.0.0.1:8015/')->assertOk();
$this->get('http://compras.tempo.co.mz:8005/')->assertOk();
$this->get('http://127.0.0.1:8015/')->assertRedirect('/login');
$this->get('http://compras.tempo.co.mz:8005/')->assertRedirect('/login');
});
test('local evaluation links send a guest to the existing password-free entry and retain the intended report', function () {
+1 -1
View File
@@ -197,7 +197,7 @@ test('browser cannot forge a confirmed payment or its encrypted banking snapshot
test('public payment example exposes no company payment data', function () {
auth()->forgetGuards();
$this->get('/consulta/pagamentos')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'payments')->where('auth.user', null)->missing('payments')->missing('invoices'));
$this->get('/consulta/pagamentos')->assertRedirect('/pagamentos');
});
test('financial role is reloaded after the company lock rather than trusting a stale session user', function () {
+10 -7
View File
@@ -3,19 +3,22 @@
use App\Models\User;
use Inertia\Testing\AssertableInertia as Assert;
test('home is a distinct public entry point without business data', function () {
$this->get('/')->assertOk()->assertInertia(fn (Assert $page) => $page->component('home')->where('auth.user', null)->missing('orders')->missing('receipts')->missing('balances'));
test('application entry directs guests to login and keeps presentation without business data', function () {
$this->get('/')->assertRedirect('/login');
$this->get('/apresentacao')->assertOk()->assertInertia(fn (Assert $page) => $page->component('home')->where('auth.user', null)->missing('orders')->missing('receipts')->missing('balances'));
$this->assertGuest();
});
test('each demo area has a dedicated address without exposing operational data', function (string $path, string $screen) {
$this->get($path)->assertOk()->assertInertia(fn (Assert $page) => $page->component('preview/index')->where('initialScreen', $screen)->where('auth.user', null)->missing('orders')->missing('receipts')->missing('movements')->missing('balances'));
})->with([['/consulta', 'overview'], ['/consulta/requisicoes', 'requests'], ['/consulta/fornecedores', 'suppliers'], ['/consulta/cotacoes', 'quotes'], ['/consulta/ordens', 'orders'], ['/consulta/recepcoes', 'receipts'], ['/consulta/stock', 'stock'], ['/consulta/conflitos', 'conflicts'], ['/consulta/aparencia', 'appearance']]);
test('old presentation addresses lead to real authenticated functionality', function (string $path, string $destination) {
$this->get($path)->assertRedirect($destination);
$this->get($destination)->assertRedirect('/login');
})->with([['/consulta', '/dashboard'], ['/consulta/requisicoes', '/requisicoes'], ['/consulta/fornecedores', '/fornecedores'], ['/consulta/cotacoes', '/requisicoes'], ['/consulta/ordens', '/ordens'], ['/consulta/recepcoes', '/recepcoes'], ['/consulta/stock', '/stock'], ['/consulta/conflitos', '/conflitos'], ['/consulta/aparencia', '/settings/appearance'], ['/proposta/principal', '/dashboard'], ['/proposta/qualificacao', '/requisicoes'], ['/proposta/admissao', '/requisicoes'], ['/proposta/recomendacao', '/requisicoes'], ['/consulta?ecra=invoices', '/facturas']]);
test('home and public navigation preserve authenticated accounts without exposing identity', function () {
$user = User::factory()->create();
$this->actingAs($user)->get('/')->assertInertia(fn (Assert $page) => $page->where('auth.user', null));
$this->get('/consulta/recepcoes')->assertInertia(fn (Assert $page) => $page->where('auth.user', null));
$this->actingAs($user)->get('/')->assertRedirect('/dashboard');
$this->get('/apresentacao')->assertInertia(fn (Assert $page) => $page->where('auth.user', null));
$this->get('/consulta/recepcoes')->assertRedirect('/recepcoes');
$this->assertAuthenticatedAs($user);
});
+1 -1
View File
@@ -191,5 +191,5 @@ test('partial invoices preserve cents and VAT across cumulative rounding', funct
test('public invoice example is available without exposing company invoices', function () {
auth()->forgetGuards();
$this->get('/consulta/facturas')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'invoices')->where('auth.user', null)->missing('invoices')->missing('orders'));
$this->get('/consulta/facturas')->assertRedirect('/facturas');
});
+122
View File
@@ -2,20 +2,27 @@
use App\Enums\PurchasingRole;
use App\Models\AuditLog;
use App\Models\BusinessClient;
use App\Models\PeopleProcess;
use App\Models\Tenant;
use App\Models\User;
use App\Services\AiPreparationPlan;
use App\Services\BusinessClients;
use App\Services\PeopleAccess;
use App\Services\PeopleClarifications;
use App\Services\PeopleContractFormalization;
use App\Services\PeopleContractHandoff;
use App\Services\PeopleEvidenceBrief;
use App\Services\PeopleHiring;
use App\Services\PeopleOperationalInsights;
use App\Services\PeopleSelectionReport;
use App\Services\RequisitionWorkflow;
use App\Services\SubmissionForms;
use App\Services\WorkContext;
use Illuminate\Database\QueryException;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Testing\TestResponse;
use Inertia\Testing\AssertableInertia as Assert;
@@ -66,6 +73,46 @@ test('people dossier block shares page redactions and rejects expired or foreign
$this->actingAs($user)->getJson('/pessoas/'.$record->id.'/dossier.json')->assertNotFound();
});
test('direction alone formalizes a signed contract with immutable evidence and no admission', function (string $kind) {
Storage::fake('people_contracts');
$record = hiringAssessment($this, $kind);
$application = DB::table('people_applications')->sole();
hiringCommand($this, $this->reviewer, $record, 'evaluate', ['application_id' => $application->id, 'answers' => [
['score' => 8, 'evidence' => 'Competências fictícias verificadas.'], ['score' => 8, 'evidence' => 'Experiência fictícia verificada.']]])->assertRedirect();
hiringCommand($this, $this->preparer, $record, 'select', ['application_id' => $application->id])->assertRedirect();
hiringCommand($this, $this->approver, $record, 'confirm', ['outcome' => 'approved'])->assertRedirect();
hiringCommand($this, $this->preparer, $record, 'contract', ['reference' => 'DEMO-MINUTA', 'starts_on' => today()->addWeek()->toDateString(), 'terms' => 'Condições fictícias para o teste de formalização.'])->assertRedirect();
$body = ['version' => $record->fresh()->version, 'operation_key' => (string) Str::uuid(), 'reference' => 'DEMO-ASSINADO', 'signed_on' => today()->toDateString(),
'reason' => 'Confirmação documental fictícia pela direcção.', 'no_conflict' => true,
'signed_document' => UploadedFile::fake()->createWithContent('signed.pdf', "%PDF-1.4\nSynthetic signed evidence\n%%EOF")];
$url = '/pessoas/'.$record->id.'/formalizar';
$this->actingAs($this->preparer)->post($url, $body)->assertForbidden();
require_once __DIR__.'/../Support/SupplyFixture.php';
supplyGrant($this->preparer, ['admin', 'people_contract_formalize']);
$this->post($url, [...$body, 'version' => 1])->assertConflict();
$this->post($url, [...$body, 'signed_on' => today()->addDay()->toDateString()])->assertSessionHasErrors('signed_on');
$this->post($url, $body)->assertRedirect();
$this->post($url, $body)->assertRedirect();
$this->post($url, [...$body, 'reference' => 'CHANGED'])->assertConflict();
expect($record->fresh()->status)->toBe('contract_formalized')
->and($record->fresh()->contract['formalized_by'])->toBe($this->preparer->id)
->and($record->fresh()->selected_application_id)->toBe($application->id)
->and(AuditLog::query()->where('action', 'people.contract_formalized')->count())->toBe(1);
$this->get('/pessoas/'.$record->id.'/contrato-assinado')->assertOk()->assertDownload();
$this->getJson('/pessoas/'.$record->id.'/dossier.json')->assertJsonPath('schema', 'sgc.people.process-dossier.v2')->assertJsonPath('effect', 'signed_contract_record_only')
->assertJsonMissingPath('process.contract.signed_document.path')->assertJsonMissingPath('process.contract.formalization_hash');
$facts = app(PeopleSelectionReport::class)->facts($record->fresh(), $this->preparer);
expect($facts['selection_state'])->toBe('Selecção aprovada')->and($facts['pending'])->toBe('Contrato assinado confirmado pela direcção');
expect(app(PeopleContractHandoff::class)->envelope($record->fresh())['contract']['signed_document'])->not->toHaveKey('path');
expect(fn () => DB::transaction(fn () => DB::table('people_processes')->where('id', $record->id)->update(['status' => 'selected'])))->toThrow(QueryException::class);
$this->actingAs($this->approver)->get('/pessoas/'.$record->id.'/contrato-assinado')->assertForbidden();
Storage::disk('people_contracts')->put($record->fresh()->contract['signed_document']['path'], 'changed');
$this->actingAs($this->preparer)->get('/pessoas/'.$record->id.'/contrato-assinado')->assertConflict();
DB::table('migrations')->where('migration', '2026_11_29_000003_allow_signed_people_contract')->delete();
expect(app(PeopleContractFormalization::class)->can($this->preparer, $record->fresh()))->toBeFalse();
$this->post($url, $body)->assertStatus(503);
})->with(['service', 'staff']);
beforeEach(function () {
$this->tenant = Tenant::query()->create(['name' => 'Empresa de contratação fictícia']);
foreach (['preparer', 'reviewer', 'approver'] as $key) {
@@ -172,10 +219,85 @@ function hiringCreate(object $test, string $kind = 'service'): PeopleProcess
function hiringCommand(object $test, User $actor, PeopleProcess $record, string $command, array $data = []): TestResponse
{
$test->actingAs($actor);
if (app(WorkContext::class)->enforced($actor)) {
$test->post('/contexto', ['area' => 'people', 'option' => $record->getAttribute('work_context_key')])->assertRedirect('/dashboard');
}
return $test->actingAs($actor)->postJson('/pessoas/'.$record->id.'/'.$command,
['version' => $record->fresh()->version, 'reason' => 'Fundamento fictício para esta intervenção.', 'no_conflict' => true, ...$data]);
}
function hiringForClient(object $test): BusinessClient
{
require_once __DIR__.'/../Support/SupplyFixture.php';
$client = app(BusinessClients::class)->save($test->preparer, null, ['client_key' => (string) Str::uuid(),
'code' => 'CLIENTE-01', 'name' => 'Cliente do processo', 'active' => true, 'reason' => 'Entidade cliente identificada para o processo de teste.']);
config(['third_party.people_enabled' => true, 'work_context.entitlements.'.$test->tenant->id => array_keys(WorkContext::OPTIONS)]);
$test->tenant->update(['work_context_policy' => ['revision' => 1, 'enabled' => array_keys(WorkContext::OPTIONS)]]);
supplyGrant($test->preparer, ['admin']);
supplyGrant($test->reviewer, ['admin']);
supplyGrant($test->approver, ['admin', 'people_contract_formalize']);
DB::table('organization_profiles')->where('tenant_id', $test->tenant->id)->update(['work_contexts' => json_encode(array_keys(WorkContext::OPTIONS))]);
$test->actingAs($test->preparer)->post('/contexto', ['area' => 'people', 'option' => 'people.third_party'])->assertRedirect('/dashboard');
$test->body += ['client_id' => $client->id, 'client_version' => $client->version];
return $client;
}
test('third party hiring completes the native lifecycle with the client frozen and provider direction deciding', function (string $kind) {
Storage::fake('people_contracts');
$client = hiringForClient($this);
$record = hiringAssessment($this, $kind);
expect($record->getAttribute('work_context_key'))->toBe('people.third_party')
->and($record->rules['client']['name'])->toBe('Cliente do processo')
->and($record->rules['decision_authority'])->toBe('provider_direction');
$application = DB::table('people_applications')->sole();
hiringCommand($this, $this->reviewer, $record, 'evaluate', ['application_id' => $application->id,
'answers' => [['score' => 8, 'evidence' => 'Competência documentada para a função.'], ['score' => 7, 'evidence' => 'Experiência documentada para a função.']]])->assertRedirect();
hiringCommand($this, $this->preparer, $record, 'select', ['application_id' => $application->id])->assertRedirect();
$profiles = DB::table('organization_memberships')->where('user_id', $this->approver->id)->pluck('profile_id');
DB::table('organization_profiles')->whereIn('id', $profiles)->update(['permissions' => json_encode(['admin'])]);
hiringCommand($this, $this->approver, $record, 'confirm', ['outcome' => 'approved'])->assertForbidden();
expect($record->fresh()->status)->toBe('selection_review');
DB::table('organization_profiles')->whereIn('id', $profiles)->update(['permissions' => json_encode(['admin', 'people_contract_formalize'])]);
hiringCommand($this, $this->approver, $record, 'confirm', ['outcome' => 'approved'])->assertRedirect();
hiringCommand($this, $this->preparer, $record, 'contract', ['reference' => 'CLIENTE-MINUTA', 'starts_on' => today()->toDateString(),
'terms' => 'Termos documentados entre as partes identificadas no processo.'])->assertRedirect();
$this->actingAs($this->approver)->post('/contexto', ['area' => 'people', 'option' => 'people.third_party'])->assertRedirect('/dashboard');
app(PeopleAccess::class)->assign($this->approver, $record->id, ['version' => 3, 'user_id' => $this->approver->id,
'scopes' => ['approve', 'contract_view'], 'reason' => 'Direcção da prestadora confere a formalização.']);
$body = ['version' => $record->fresh()->version, 'operation_key' => (string) Str::uuid(), 'reference' => 'CLIENTE-ASSINADO',
'signed_on' => today()->toDateString(), 'reason' => 'Confirmação documental pela Direcção da prestadora.', 'no_conflict' => true,
'signed_document' => UploadedFile::fake()->createWithContent('contrato.pdf', "%PDF-1.4\nSigned test evidence\n%%EOF")];
$this->post('/pessoas/'.$record->id.'/formalizar', $body)->assertRedirect();
$this->getJson('/pessoas/'.$record->id.'/dossier.json')->assertOk()->assertJsonPath('process.rules.client.name', 'Cliente do processo')
->assertJsonPath('process.status', 'contract_formalized')->assertJsonMissingPath('process.contract.signed_document.path');
$this->get('/pessoas/'.$record->id.'/contrato-assinado')->assertOk();
expect(fn () => app(PeopleContractHandoff::class)->envelope($record->fresh()))->toThrow(HttpException::class);
expect($record->fresh()->confirmed_by)->toBe($this->approver->id);
})->with(['service', 'staff']);
test('third party hiring requires the current own client and keeps original identities when the client changes', function () {
$client = hiringForClient($this);
$original = $this->body;
$this->postJson('/pessoas', array_diff_key($original, ['client_id' => true, 'client_version' => true]))->assertUnprocessable();
$record = hiringCreate($this);
$this->get('/pessoas')->assertInertia(fn (Assert $page) => $page->where('clientMode', true)->where('processes.data.0.client.name', 'Cliente do processo')->missing('processes.data.0.rules'));
$this->get('/pessoas/relatorios?search=Cliente')->assertOk()->assertSee('Cliente do processo');
app(BusinessClients::class)->save($this->preparer, $client->id, ['version' => 1, 'code' => $client->code,
'name' => 'Cliente actualizado no cadastro', 'active' => false, 'reason' => 'Actualizar a ficha sem reescrever o processo anterior.']);
$this->postJson('/pessoas', $original)->assertRedirect();
expect(PeopleProcess::query()->count())->toBe(1)->and($record->fresh()->rules['client']['name'])->toBe('Cliente do processo');
$this->postJson('/pessoas', [...$original, 'operation_key' => (string) Str::uuid(), 'client_version' => 2])->assertConflict();
$this->post('/contexto', ['area' => 'people', 'option' => 'people.internal'])->assertRedirect();
$this->get('/pessoas/'.$record->id)->assertNotFound();
$this->get('/pessoas/relatorios')->assertDontSee('Cliente do processo');
$internal = array_diff_key($original, ['client_id' => true, 'client_version' => true]);
$this->postJson('/pessoas', $internal)->assertConflict();
$this->postJson('/pessoas', [...$original, 'operation_key' => (string) Str::uuid()])->assertUnprocessable();
});
function hiringAssessment(object $test, string $kind = 'service'): PeopleProcess
{
$record = hiringCreate($test, $kind);
@@ -10,11 +10,43 @@ use App\Services\PrivateAuditExporter;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia;
use Symfony\Component\HttpKernel\Exception\HttpException;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
test('context activation preserves only explicitly pinned own legacy archives and keeps original bytes and family authority', function () {
$service = app(PrivateAuditExporter::class);
$export = $service->generate($this->actor, ['operation_key' => (string) Str::uuid(), 'families' => ['purchasing'], 'purpose' => 'Synthetic transition regression']);
$before = DB::table('private_audit_exports')->where('id', $export->id)->first();
$this->f['tenant']->update(['work_context_policy' => ['revision' => 1, 'enabled' => ['procurement.internal']]]);
config(['work_context.entitlements.'.$this->actor->tenant_id => ['procurement.internal']]);
DB::table('organization_profiles')->where('tenant_id', $this->actor->tenant_id)->update(['work_contexts' => json_encode(['procurement.internal'])]);
$this->post('/contexto', ['area' => 'procurement', 'option' => 'procurement.internal'])->assertRedirect('/dashboard');
$this->get('/auditoria/privada')->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('exports.total', 0));
$this->get('/auditoria/privada/'.$export->id.'/download')->assertStatus(409);
config(['private-audit.legacy_export_transitions.'.$this->actor->tenant_id => [$export->id => str_repeat('0', 64)]]);
$this->get('/auditoria/privada/'.$export->id.'/download')->assertStatus(409);
config(['private-audit.legacy_export_transitions.'.$this->actor->tenant_id => [$export->id => $export->sha256]]);
$this->get('/auditoria/privada')->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('exports.total', 1));
$this->get('/auditoria/privada/'.$export->id.'/download')->assertOk();
expect(DB::table('private_audit_exports')->where('id', $export->id)->first())->toEqual($before)
->and(hash_file('sha256', Storage::disk('local')->path($export->path)))->toBe($export->sha256)
->and(app(PrivateAuditAccess::class)->legacyExportIds($this->actor, 'people.internal'))->toBe([]);
$other = User::factory()->create(['tenant_id' => $this->actor->tenant_id, 'department_id' => $this->actor->department_id, 'purchasing_role' => PurchasingRole::Configured]);
supplyGrant($other, ['audit_private_purchasing_read']);
$otherProfiles = DB::table('organization_memberships')->where('user_id', $other->id)->pluck('profile_id');
DB::table('organization_profiles')->whereIn('id', $otherProfiles)->update(['work_contexts' => json_encode(['procurement.internal'])]);
$this->actingAs($other)->post('/contexto', ['area' => 'procurement', 'option' => 'procurement.internal'])->assertRedirect('/dashboard');
$this->get('/auditoria/privada')->assertOk()->assertInertia(fn (AssertableInertia $page) => $page->where('exports.total', 0));
$this->get('/auditoria/privada/'.$export->id.'/download')->assertNotFound();
$this->actingAs($this->actor)->post('/contexto', ['area' => 'procurement', 'option' => 'procurement.internal'])->assertRedirect('/dashboard');
$profiles = DB::table('organization_memberships')->where('user_id', $this->actor->id)->pluck('profile_id');
DB::table('organization_profiles')->whereIn('id', $profiles)->update(['permissions' => json_encode(['audit_private_stock_read'])]);
$this->get('/auditoria/privada/'.$export->id.'/download')->assertForbidden();
});
beforeEach(function () {
config(['private-audit.qa_enabled' => true]);
Storage::fake('local');
+3 -2
View File
@@ -13,8 +13,9 @@ beforeEach(function () {
$this->withoutVite();
});
test('anonymous visitors enter the real dashboard without creating an authenticated identity', function () {
$this->get('/')->assertRedirect('/dashboard');
test('anonymous visitors enter through login and can still consult public screens without an identity', function () {
$this->get('/')->assertRedirect('/login');
$this->get('/apresentacao')->assertOk()->assertInertia(fn (Assert $p) => $p->component('home')->where('auth.user', null)->missing('company')->missing('stats'));
$this->get('/dashboard')->assertInertia(fn (Assert $p) => $p->component('dashboard')->where('auth.user', null)->where('company', null)->where('stats.total', 0)->where('publicNavigation.dataScope', 'none'));
$this->assertGuest('web');
expect(User::query()->count())->toBe(0);
@@ -67,6 +67,41 @@ beforeEach(function () {
$this->actingAs($this->f['issuer']);
});
test('standalone audit uses ordinary private application storage and refuses public or external roots', function () {
config(['private-audit.qa_enabled' => false]);
$original = config('filesystems.disks.local');
$root = storage_path('app/release-audit-'.Str::uuid());
$external = sys_get_temp_dir().DIRECTORY_SEPARATOR.'release-audit-'.Str::uuid();
mkdir($root, 0700, true);
mkdir($external, 0700);
$files = null;
try {
config(['filesystems.disks.local.root' => $root]);
\Illuminate\Support\Facades\Storage::forgetDisk('local');
expect(app(\App\Services\PrivateAuditAccess::class)->ready())->toBeTrue();
$files = new \App\Services\PrivateAuditFiles($this->f['issuer']);
$written = $files->write('probe.ndjson', "{\"synthetic\":true}\n");
expect(file_get_contents($written['path']))->toBe("{\"synthetic\":true}\n")
->and($written['sha256'])->toBe(hash('sha256', "{\"synthetic\":true}\n"));
foreach ([public_path(), storage_path('app/public'), $external] as $invalid) {
config(['filesystems.disks.local.root' => $invalid]);
\Illuminate\Support\Facades\Storage::forgetDisk('local');
expect(fn () => new \App\Services\PrivateAuditFiles($this->f['issuer']))->toThrow(\Symfony\Component\HttpKernel\Exception\HttpException::class);
}
} finally {
$files?->cleanup();
config(['filesystems.disks.local' => $original]);
\Illuminate\Support\Facades\Storage::forgetDisk('local');
$resolved = realpath($root);
if ($resolved !== false && dirname($resolved) === realpath(storage_path('app')) && str_starts_with(basename($resolved), 'release-audit-')) {
\Illuminate\Support\Facades\File::deleteDirectory($resolved);
}
if (is_dir($external) && count(scandir($external) ?: []) === 2) {
rmdir($external);
}
}
});
test('standalone candidate preserves explicit line account attribution without a journal or a parallel budget writer', function () {
$request = $this->f['r'];
$request->update(['status' => 'draft']);
+53
View File
@@ -0,0 +1,53 @@
<?php
use Tempo\Purchasing\Delivery\BootOverlay;
require_once __DIR__.'/../../integrations/sgf/operational/BootOverlay.php';
beforeEach(function () {
$this->host = __DIR__.'/../../storage/framework/testing/boot-overlay-'.bin2hex(random_bytes(6));
mkdir($this->host.'/app/Providers', 0700, true);
mkdir($this->host.'/app/Shared/Context', 0700, true);
file_put_contents($this->host.'/app/Providers/AppServiceProvider.php', '<?php class Provider { public function register() { $this->app->scoped(CompanyContext::class); }'."\npublic function boot(): void\n {\n }\n}");
});
afterEach(function () {
foreach (['app/Providers/AppServiceProvider.php', 'app/Shared/Context/ModuleNavigation.php'] as $file) {
unlink($this->host.'/'.$file);
}
foreach (['app/Providers', 'app/Shared/Context', 'app/Shared', 'app', ''] as $directory) {
rmdir($this->host.($directory === '' ? '' : '/'.$directory));
}
});
test('prepares legacy host without changing source files or grants', function () {
$file = $this->host.'/app/Shared/Context/ModuleNavigation.php';
$before = "<?php class Nav { const RIGHTS=['purchasing'=>['purchasing_budget.', 'supplier_payables.']]; }";
file_put_contents($file, $before);
$result = BootOverlay::prepare($this->host);
expect($result['app/Shared/Context/ModuleNavigation.php']['contents'])->toContain("'purchasing_requisitions.'")
->and(file_get_contents($file))->toBe($before);
});
test('preserves expanded host navigation and is repeatable', function () {
$before = "<?php class Nav { const RIGHTS=['purchasing' => ['purchasing_budget.', 'purchasing_requisitions.', 'purchasing_orders.', 'purchasing_invoices.', 'supplier_payables.']]; }";
file_put_contents($this->host.'/app/Shared/Context/ModuleNavigation.php', $before);
$result = BootOverlay::prepare($this->host);
expect($result['app/Shared/Context/ModuleNavigation.php']['contents'])->toBe($before);
foreach ($result as $file => $entry) {
file_put_contents($this->host.'/'.$file, $entry['contents']);
}
$again = BootOverlay::prepare($this->host);
foreach ($result as $file => $entry) {
expect($again[$file]['contents'])->toBe($entry['contents']);
}
});
test('refuses ambiguous or executable host prefix lists', function (string $navigation) {
file_put_contents($this->host.'/app/Shared/Context/ModuleNavigation.php', $navigation);
expect(fn () => BootOverlay::prepare($this->host))->toThrow(RuntimeException::class);
})->with([
'unknown expression' => "<?php class Nav { const RIGHTS=['purchasing'=>['purchasing_budget.', dynamicPrefix(), 'supplier_payables.']]; }",
'missing anchor' => "<?php class Nav { const RIGHTS=['purchasing'=>['supplier_payables.']]; }",
'duplicate' => "<?php class Nav { const RIGHTS=['purchasing'=>['purchasing_budget.', 'supplier_payables.'], 'purchasing'=>['purchasing_budget.', 'supplier_payables.']]; }",
]);
+59
View File
@@ -0,0 +1,59 @@
<?php
use Tempo\Purchasing\Inventory\StockCosting;
require_once __DIR__.'/../../packages/purchasing/src/StockCosting.php';
function costingOpening(): array
{
return ['reference' => 'synthetic-empty-cut', 'quantity_milli' => 0, 'value_minor' => 0, 'layers' => []];
}
function costingReceipt(int $id, int $quantity, int $value): array
{
return ['id' => $id, 'reference' => 'synthetic-receipt-'.$id, 'kind' => 'receipt', 'quantity_milli' => $quantity, 'value_minor' => $value];
}
function costingIssue(int $id, int $quantity): array
{
return ['id' => $id, 'reference' => 'synthetic-issue-'.$id, 'kind' => 'issue', 'quantity_milli' => $quantity];
}
test('FIFO and weighted average are selected explicitly and give distinct exact costs', function () {
$facts = [costingReceipt(1, 1000, 100), costingReceipt(2, 1000, 200), costingIssue(3, 1000)];
$fifo = StockCosting::project('fifo', costingOpening(), $facts);
$average = StockCosting::project('weighted_average', costingOpening(), $facts);
expect($fifo['movements'][2]['value']['amount_minor'])->toBe('100')
->and($average['movements'][2]['value']['amount_minor'])->toBe('150')
->and($fifo['closing']['value']['amount_minor'])->toBe('200')
->and($average['closing']['value']['amount_minor'])->toBe('150');
});
test('partial FIFO layers preserve the full remaining value', function () {
$r = StockCosting::project('fifo', costingOpening(), [costingReceipt(1, 3000, 100), costingIssue(2, 1000), costingIssue(3, 2000)]);
expect($r['movements'][1]['value'])->toMatchArray(['numerator' => '100', 'denominator' => '3', 'amount_minor' => null, 'rounding_required' => true])
->and($r['movements'][2]['value']['numerator'])->toBe('200')
->and($r['closing'])->toMatchArray(['quantity_milli' => 0, 'value' => ['numerator' => '0', 'denominator' => '1', 'amount_minor' => '0', 'rounding_required' => false]]);
});
test('unknown receipt costs are not converted to zero', function () {
$r = costingReceipt(1, 1000, 100);
unset($r['value_minor']);
expect(fn () => StockCosting::project('weighted_average', costingOpening(), [$r]))->toThrow(InvalidArgumentException::class);
});
test('FIFO does not invent layers for an opening balance', function () {
expect(fn () => StockCosting::project('fifo', ['reference' => 'opening', 'quantity_milli' => 1000, 'value_minor' => 100], []))->toThrow(DomainException::class);
});
test('unknown methods, reordered facts and negative stock are refused', function (string $method, array $facts, string $exception) {
expect(fn () => StockCosting::project($method, costingOpening(), $facts))->toThrow($exception);
})->with([
'unknown method' => ['default', [], InvalidArgumentException::class],
'reordered' => ['fifo', [costingReceipt(2, 1000, 100), costingReceipt(1, 1000, 100)], DomainException::class],
'shortage' => ['weighted_average', [costingReceipt(1, 1000, 100), costingIssue(2, 1001)], DomainException::class],
'override' => ['fifo', [costingReceipt(1, 1000, 100), costingIssue(2, 1000) + ['value_minor' => 1]], InvalidArgumentException::class],
]);
test('explicit zero-value receipt differs from unknown cost', function () {
$r = StockCosting::project('fifo', costingOpening(), [costingReceipt(1, 1000, 0), costingIssue(2, 1000)]);
expect($r['movements'][1]['value']['amount_minor'])->toBe('0')->and($r['journals_written'])->toBeFalse();
});
+74
View File
@@ -3,6 +3,7 @@ import type { Page } from '@inertiajs/core';
import { renderToString } from 'react-dom/server';
import { expect, test } from 'vitest';
import PeopleIndex from '@/pages/people';
import BusinessClients from '@/pages/company/clients';
import PeopleShow from '@/pages/people/show';
import PeopleAccess from '@/pages/people/access';
import { PeopleClarifications } from '@/components/people-clarifications';
@@ -18,6 +19,79 @@ const base = {
encryptHistory: false,
} satisfies Page;
test('third party preparation identifies its client and the providers direction', () => {
const page = {
...base,
props: {
errors: {},
ready: true,
kinds: ['service'],
canPrepare: ['service'],
clientMode: true,
clients: [
{
id: 12,
code: 'CLI-12',
name: 'Cliente identificado',
version: 3,
},
],
processes: { data: [], links: [] },
},
};
const html = renderToString(
<App initialPage={page} initialComponent={PeopleIndex} />,
);
expect(html).toContain('Cliente identificado');
expect(html).toContain('name="client_id"');
expect(html).toContain('Direcção');
expect(html).toContain('/empresa/clientes');
});
test('the client registry provides real versioned edit forms and no edit control to readers', () => {
const props = {
errors: {},
filters: {},
canManage: true,
clients: {
data: [
{
id: 12,
client_key: 'test-key',
code: 'CLI-12',
name: 'Cliente identificado',
tax_number: null,
address: null,
email: null,
active: true,
version: 3,
},
],
current_page: 1,
last_page: 1,
prev_page_url: null,
next_page_url: null,
},
};
const html = renderToString(
<App
initialPage={{ ...base, props }}
initialComponent={BusinessClients}
/>,
);
expect(html).toContain('/empresa/clientes/12');
expect(html).toContain('name="version"');
expect(html).toContain('Guardar alterações');
const reader = renderToString(
<App
initialPage={{ ...base, props: { ...props, canManage: false } }}
initialComponent={BusinessClients}
/>,
);
expect(reader).toContain('Cliente identificado');
expect(reader).not.toContain('Guardar alterações');
});
test('operational reading explains its scope and missing deadlines without suggesting candidate decisions', () => {
function Screen() {
return (
+25 -1
View File
@@ -29,11 +29,35 @@ test.each(Object.entries(fixtures))(
const html = renderToString(
<App initialPage={initialPage} initialComponent={Component} />,
);
expect(html).toContain('Consulta pública de desenvolvimento');
expect(html).toContain('Consulta pública');
expect(html).toContain('Consulta pública sem sessão');
expect(html).toContain('Entrar na aplicação');
expect(html).toContain('href="/login"');
expect(html).not.toContain('Consulta pública de desenvolvimento');
expect(html).not.toContain('/consulta?');
expect(html).toContain('/dashboard');
},
);
test('product entry presents six areas and directs work to the application login', () => {
const Home = modules['../../resources/js/pages/home.tsx'].default;
const initialPage = { ...Object.values(fixtures)[0], component: 'home' };
const html = renderToString(
<App initialPage={initialPage} initialComponent={Home} />,
);
for (const title of [
'Pedidos e aprovações',
'Fornecedores e compras',
'Recepção e armazém',
'Orçamento e finanças',
'Importações',
'Pessoas e contratações',
]) {
expect(html).toContain(title);
}
expect(html).toContain('href="/login"');
expect(html).not.toContain('href="/consulta');
});
test('public menu links only to the explicit public screens and never grants a staff role', () => {
const paths = (
fixtures.dashboard.props.publicNavigation as { paths: string[] }
+91
View File
@@ -0,0 +1,91 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs/promises';
import path from 'node:path';
import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process';
const boundary = await fs.realpath('storage/framework/testing');
const verifier = path.resolve('scripts/verify-compras-release.php');
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
async function fixture(run) {
const root = await fs.mkdtemp(path.join(boundary, 'release-verifier-'));
try {
await fs.mkdir(path.join(root, 'public/build/assets'), { recursive: true });
const source = '<?php exit(99); // verification must never execute product code';
await fs.writeFile(path.join(root, 'main.php'), source);
await fs.writeFile(path.join(root, 'public/build/manifest.json'), '{}');
await fs.writeFile(path.join(root, 'public/build/assets/a.js'), 'test');
const manifest = { contract: 'compras.release.v1', product: 'compras', source_files: { 'main.php': hash(source) },
frontend: { manifest_sha256: hash('{}'), files: { 'assets/a.js': hash('test') } }, components: [] };
for (const [index, list] of [true, false].entries()) {
const component = path.join(root, 'component-'+index);
await fs.mkdir(component);
await fs.writeFile(path.join(component, 'writer.php'), 'not executable');
const files = list ? [{ file: 'writer.php', sha256: hash('not executable') }] : { 'writer.php': hash('not executable') };
const bytes = JSON.stringify({ files });
await fs.writeFile(path.join(component, 'manifest.json'), bytes);
manifest.components.push({ setting: 'COMPONENT_'+index, manifest_sha256: hash(bytes) });
}
await fs.writeFile(path.join(root, '.env'), 'COMPRAS_RUNTIME_ENABLED="true"\n'+manifest.components.map((entry, index) => entry.setting+'="'+path.join(root, 'component-'+index).replaceAll('\\', '/')+'"').join('\n'));
const save = async () => {
delete manifest.release_id;
manifest.release_id = 'compras-'+hash(JSON.stringify(manifest)).slice(0, 16);
await fs.writeFile(path.join(root, 'compras-release.json'), JSON.stringify(manifest));
};
await save();
const verify = (...args) => spawnSync('php', [verifier, root, ...args], { encoding: 'utf8', windowsHide: true });
await run({ root, manifest, save, verify });
} finally {
const resolved = await fs.realpath(root);
assert.equal(path.dirname(resolved), boundary);
assert.ok(path.basename(resolved).startsWith('release-verifier-'));
await fs.rm(resolved, { recursive: true });
}
}
test('verifies one source, compiled assets and both component manifest formats without executing product code', () => fixture(async ({ verify }) => {
const result = verify('--installed');
assert.equal(result.status, 0, result.stderr);
assert.equal(JSON.parse(result.stdout).installed_components, 2);
}));
test('rejects changed source', () => fixture(async ({ root, verify }) => {
await fs.writeFile(path.join(root, 'main.php'), 'changed');
assert.notEqual(verify().status, 0);
}));
test('accepts Git LF and Windows CRLF as the same source without accepting changed text', () => fixture(async ({ root, manifest, save, verify }) => {
manifest.source_eol = 'lf';
manifest.source_files['main.php'] = hash('first\nsecond\n');
await save();
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nsecond\r\n');
assert.equal(verify().status, 0);
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nchanged\r\n');
assert.notEqual(verify().status, 0);
}));
test('rejects a changed compiled asset', () => fixture(async ({ root, verify }) => {
await fs.writeFile(path.join(root, 'public/build/assets/a.js'), 'changed');
assert.notEqual(verify('--compiled').status, 0);
}));
test('rejects a changed component', () => fixture(async ({ root, verify }) => {
await fs.writeFile(path.join(root, 'component-1/writer.php'), 'changed');
assert.notEqual(verify('--installed').status, 0);
}));
test('rejects forged identity', () => fixture(async ({ root, manifest, verify }) => {
manifest.release_id = 'compras-forged';
await fs.writeFile(path.join(root, 'compras-release.json'), JSON.stringify(manifest));
assert.notEqual(verify().status, 0);
}));
test('rejects path traversal even with a recomputed descriptor', () => fixture(async ({ manifest, save, verify }) => {
manifest.source_files['../outside.php'] = hash('test');
await save();
assert.notEqual(verify().status, 0);
}));
test('rejects disabled installation', () => fixture(async ({ root, verify }) => {
await fs.writeFile(path.join(root, '.env'), 'COMPRAS_RUNTIME_ENABLED=false');
assert.notEqual(verify('--installed').status, 0);
}));
test('rejects a missing descriptor', () => fixture(async ({ root, verify }) => {
await fs.unlink(path.join(root, 'compras-release.json'));
assert.notEqual(verify().status, 0);
}));
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { purchasingHomeOverlay } from '../../scripts/lib/sgf-purchasing-home-overlay.mjs';
const legacy = `const payables=unit!==null&&can('supplier_payables.view',unit);
<div className="actions">{suppliers&&<a href="/purchasing/suppliers">Fornecedores</a>}</div>{!budget&&!payables&&<p>Sem acesso</p>}`;
test('legacy transfer adds links once and preserves other capabilities', () => {
const output = purchasingHomeOverlay(legacy);
assert.match(output, /requisitions&&<a/);
assert.match(output, /suppliers&&<a/);
assert.equal(purchasingHomeOverlay(output), output);
});
test('current host keeps its stricter feature guard and complete empty state', () => {
const guard = "const requisitions=unit!==null&&context.purchasing?.internal_requisitions===true&&can('purchasing_requisitions.view',unit);";
const source = legacy.replace('\n', '\n'+guard+'\n').replace('<div className="actions">', '<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições</a>}').replace('!budget&&!payables&&', '!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&');
const output = purchasingHomeOverlay(source);
assert.ok(output.includes(guard));
assert.equal((output.match(/const requisitions=/g)??[]).length, 1);
assert.equal((output.match(/href="\/purchasing\/internal-requisitions"/g)??[]).length, 1);
assert.ok(output.includes('!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&'));
assert.equal(purchasingHomeOverlay(output), output);
});
test('unknown or duplicate declarations refuse preparation', () => {
assert.throws(() => purchasingHomeOverlay('const requisitions=true;\n'+legacy));
assert.throws(() => purchasingHomeOverlay('const requisitions=true;const requisitions=false;'+legacy));
});