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']);