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