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