commit compras3 2911
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-29 16:03:11 +02:00
parent 7da8d6c87a
commit 30bfb1a773
72 changed files with 10998 additions and 98 deletions
@@ -4,8 +4,10 @@ use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\Requisition;
use App\Models\SupplyRecord;
use App\Models\Tenant;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\CommonFinanceAdministration;
use App\Services\CommonPaymentFacts;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
@@ -21,6 +23,7 @@ use App\Services\SupplierPayables;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Tempo\Finance\Budget\BudgetFailure;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -36,6 +39,7 @@ beforeEach(function () {
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['prepare_only'] = false;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
config(['standalone-runtime' => [...$settings, 'enabled' => false], 'common-payables.source_instance' => 'standalone-business-synthetic']);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
@@ -175,6 +179,9 @@ test('standalone financial pages use explicit read rights and refuse writes or d
'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($finance)->get('/api/supplier-payments')->assertForbidden();
$this->get('/api/general-ledger/cycle')->assertForbidden();
$this->withoutVite()->get('/dashboard')->assertOk()->assertInertia(fn ($page) => $page
->where('commonFinanceNavigation.payments', false)->where('commonFinanceNavigation.ledger', false)
->where('commonFinanceNavigation.configuration', false));
foreach (['view', 'payments_view', 'general_ledger.view'] as $action) {
DB::table('pa_access')->insert(['tenant_id' => $finance->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $finance->id, 'person' => 'synthetic-financial-reader-'.$finance->id, 'action' => $action]);
@@ -187,6 +194,9 @@ test('standalone financial pages use explicit read rights and refuse writes or d
->assertJsonPath('permissions.payment_prepare', false);
$this->get('/supplier-payments')->assertOk()->assertHeader('Cache-Control', 'no-store, private');
$this->get('/api/general-ledger/cycle')->assertOk();
$this->get('/dashboard')->assertOk()->assertInertia(fn ($page) => $page
->where('commonFinanceNavigation.payments', true)->where('commonFinanceNavigation.ledger', true)
->where('commonFinanceNavigation.configuration', false));
$this->get('/general-ledger/cycle')->assertOk();
$this->withHeader('Idempotency-Key', (string) Str::uuid())->postJson('/api/supplier-payments/payment-prepare', [])->assertForbidden();
$this->withHeader('Idempotency-Key', (string) Str::uuid())->postJson('/api/general-ledger/prepare', [
@@ -205,11 +215,23 @@ test('standalone financial pages use explicit read rights and refuse writes or d
test('standalone candidate recognises one invoice and posts one balanced journal using explicitly configured own chart accounts', function () {
$f = paymentFixture();
$admin = User::factory()->create(['tenant_id' => $f['tenant']->id, 'purchasing_role' => PurchasingRole::Admin]);
$configuration = function (string $kind, array $data) use ($admin) {
$this->actingAs($admin);
$service = app(CommonFinanceAdministration::class);
$space = $service->workspace($admin, $data['user_id'] ?? null);
$basis = $space[match ($kind) {
'access' => 'selectedAccess', 'account' => 'accounts', 'period' => 'periods', 'rule' => 'rules'
}];
return $service->save($admin, $kind, $data + ['operation_key' => (string) Str::uuid(),
'basis_hash' => $basis['hash'], 'reason' => 'Explicit synthetic company setup for the real financial cycle']);
};
foreach ([$f['author'], $f['validator']] as $actor) {
foreach (['view', 'prepare', 'validate', 'general_ledger.view', 'general_ledger.prepare', 'general_ledger.validate', 'general_ledger.post'] as $action) {
DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $actor->id, 'person' => 'synthetic-independent-person-'.$actor->id, 'action' => $action]);
}
$configuration('access', ['user_id' => $actor->id, 'person' => 'synthetic-independent-person-'.$actor->id,
'actions' => ['view', 'prepare', 'validate', 'general_ledger.view', 'general_ledger.prepare', 'general_ledger.validate', 'general_ledger.post',
'general_ledger.correct_prepare', 'general_ledger.correct_validate', 'general_ledger.correct_post',
'general_ledger.period_prepare', 'general_ledger.period_validate', 'general_ledger.period_close']]);
}
$payables = app(SupplierPayables::class);
$this->actingAs($f['author']);
@@ -220,15 +242,13 @@ test('standalone candidate recognises one invoice and posts one balanced journal
$scope = ['tenant_id' => $f['author']->tenant_id, 'company_id' => 0, 'unit_id' => 0];
$accounts = [];
foreach (['630100' => 'Synthetic configured expense account', '420100' => 'Synthetic configured supplier account'] as $code => $label) {
$accounts[] = DB::table('gl_accounts')->insertGetId($scope + ['code' => $code, 'label' => $label, 'currency' => 'MZN', 'is_movement' => true]);
$accounts[] = $configuration('account', ['code' => (string) $code, 'label' => $label, 'currency' => 'MZN', 'is_movement' => true])['id'];
}
DB::table('gl_periods')->insert($scope + ['period_key' => 'EXPLICIT', 'version' => 1, 'starts_on' => today()->startOfYear()->toDateString(),
'ends_on' => today()->endOfYear()->toDateString(), 'status' => 'open', 'created_by' => $f['author']->id,
'reason' => 'Explicit synthetic accounting period', 'created_at' => now()]);
DB::table('gl_rules')->insert($scope + ['rule_key' => 'EXPLICIT-SUPPLIER', 'version' => 1, 'policy' => 'COMMON-PAYABLE-JOURNAL-v1',
'effect_type' => 'supplier_payable.recognised', 'currency' => 'MZN', 'valid_from' => today()->startOfYear()->toDateString(),
'valid_to' => today()->endOfYear()->toDateString(), 'debit_account_id' => $accounts[0], 'credit_account_id' => $accounts[1],
'created_by' => $f['author']->id, 'reason' => 'Explicit synthetic own chart accounting rule', 'created_at' => now()]);
$configuration('period', ['period_key' => 'EXPLICIT', 'starts_on' => today()->startOfYear()->toDateString(),
'ends_on' => today()->endOfYear()->toDateString()]);
$configuration('rule', ['rule_key' => 'EXPLICIT-SUPPLIER', 'effect_type' => 'supplier_payable.recognised',
'valid_from' => today()->startOfYear()->toDateString(), 'valid_to' => today()->endOfYear()->toDateString(),
'debit_account_id' => $accounts[0], 'credit_account_id' => $accounts[1]]);
$ledger = app(GeneralLedger::class);
$this->actingAs($f['author']);
$input = ['obligation_id' => $validated['obligation_id'], 'journal_on' => today()->toDateString(), 'period_key' => 'EXPLICIT',
@@ -244,6 +264,7 @@ test('standalone candidate recognises one invoice and posts one balanced journal
$post = ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'], 'reason' => 'Apply the independently reviewed synthetic journal'];
$ledger->engine($f['author'])->command('post', $post, $operation);
DB::statement('SET CONSTRAINTS ALL IMMEDIATE');
DB::statement('SET CONSTRAINTS ALL DEFERRED');
expect($ledger->engine($f['author'])->command('post', $post, $operation)['replayed'])->toBeTrue()
->and(DB::table('gl_journals')->count())->toBe(1)->and(DB::table('gl_lines')->count())->toBe(2)
->and((int) DB::table('gl_lines')->sum('debit_minor'))->toBe(6000)
@@ -252,6 +273,67 @@ test('standalone candidate recognises one invoice and posts one balanced journal
$snapshot = json_decode(DB::table('gl_journals')->value('snapshot'), true, 128, JSON_THROW_ON_ERROR);
expect($snapshot['contract'])->toBe('COMMON-LEDGER-PAYABLE-v1')
->and(array_column($snapshot['lines'], 'account_id'))->toBe($accounts);
$this->get('/general-ledger/cycle')->assertOk()->assertSee('EXPLICIT-SUPPLIER')->assertSee('EXPLICIT')
->assertDontSee('value="2026-10-29"', false)->assertDontSee('value="QA-PAYABLE-JOURNAL"', false);
$interval = http_build_query(['from_on' => today()->startOfYear()->toDateString(), 'to_on' => today()->toDateString()]);
$this->get('/general-ledger/trial-balance?'.$interval)->assertOk()
->assertSee('2 de 2 contas')->assertSee('60,00')->assertSee('print-context')
->assertSee('os totais abrangem todo o filtro');
$this->get('/general-ledger/account-ledger?'.$interval.'&account_id='.$accounts[0])->assertOk()
->assertSee('1 de 1 linhas')->assertSee('60,00')->assertSee(today()->toDateString());
$original = DB::table('gl_journals')->first();
$correctedAccount = DB::table('gl_accounts')->insertGetId($scope + ['code' => '630200',
'label' => 'Explicit synthetic corrected expense account', 'currency' => 'MZN', 'is_movement' => true]);
$baseRule = (array) DB::table('gl_rules')->first();
unset($baseRule['id']);
foreach ([['REVERSE', 'journal.reversal', $accounts[1], $accounts[0]],
['REPLACE', 'journal.replacement', $correctedAccount, $accounts[1]],
['BAD-REVERSE', 'journal.reversal', $accounts[0], $accounts[1]]] as [$key, $effect, $debit, $credit]) {
DB::table('gl_rules')->insert([...$baseRule, 'rule_key' => $key, 'effect_type' => $effect,
'debit_account_id' => $debit, 'credit_account_id' => $credit]);
}
$correctionInput = ['journal_id' => $original->id, 'journal_on' => today()->toDateString(), 'period_key' => 'EXPLICIT',
'reverse_rule_key' => 'REVERSE', 'replacement_rule_key' => 'REPLACE', 'reason' => 'Explicit synthetic correction of account classification'];
expect(fn () => $ledger->engine($f['author'])->command('correct-prepare', [...$correctionInput, 'reverse_rule_key' => 'BAD-REVERSE'], (string) Str::uuid()))
->toThrow(DomainException::class);
expect(DB::table('gl_proposals')->count())->toBe(1)->and(DB::table('gl_journals')->count())->toBe(1);
$correction = $ledger->engine($f['author'])->command('correct-prepare', $correctionInput, (string) Str::uuid());
$this->actingAs($f['validator']);
$ledger->engine($f['validator'])->command('correct-validate', ['correction_id' => $correction['correction_id'],
'revision' => $correction['revision'], 'decision' => 'approved', 'reason' => 'Independent review of both exact synthetic correction impacts'], (string) Str::uuid());
$this->actingAs($f['author']);
$correctionPost = ['correction_id' => $correction['correction_id'], 'revision' => $correction['revision'], 'reason' => 'Apply the independently reviewed synthetic pair'];
$correctionOperation = (string) Str::uuid();
$fault = function (string $checkpoint) {
if ($checkpoint === 'after_correction_first') {
throw new RuntimeException('SYNTHETIC_CORRECTION_INTERRUPTION');
}
};
expect(fn () => $ledger->engine($f['author'], $fault)->command('correct-post', $correctionPost, $correctionOperation))
->toThrow(RuntimeException::class, 'SYNTHETIC_CORRECTION_INTERRUPTION');
expect(DB::table('gl_journals')->count())->toBe(1)->and(DB::table('gl_correction_results')->count())->toBe(0);
$ledger->engine($f['author'])->command('correct-post', $correctionPost, $correctionOperation);
DB::statement('SET CONSTRAINTS ALL IMMEDIATE');
DB::statement('SET CONSTRAINTS ALL DEFERRED');
expect($ledger->engine($f['author'])->command('correct-post', $correctionPost, $correctionOperation)['replayed'])->toBeTrue()
->and((array) DB::table('gl_journals')->where('id', $original->id)->first())->toBe((array) $original)
->and(DB::table('gl_journals')->count())->toBe(3)->and(DB::table('gl_correction_results')->count())->toBe(1)
->and((int) DB::table('gl_lines')->where('account_id', $accounts[0])->sum('debit_minor')
- (int) DB::table('gl_lines')->where('account_id', $accounts[0])->sum('credit_minor'))->toBe(0)
->and((int) DB::table('gl_lines')->where('account_id', $correctedAccount)->sum('debit_minor'))->toBe(6000)
->and(DB::table('pa_obligations')->count())->toBe(1)->and((int) DB::table('pa_obligations')->sum('principal_minor'))->toBe(6000);
$check = $ledger->engine($f['author'])->command('period-prepare', ['period_key' => 'EXPLICIT', 'reason' => 'Synthetic close preparation after complete postings'], (string) Str::uuid());
$this->actingAs($f['validator']);
$ledger->engine($f['validator'])->command('period-validate', ['check_id' => $check['check_id'], 'revision' => $check['revision'],
'decision' => 'approved', 'reason' => 'Independent synthetic review of the closed-period evidence'], (string) Str::uuid());
$this->actingAs($f['author']);
$closeOperation = (string) Str::uuid();
$close = ['check_id' => $check['check_id'], 'revision' => $check['revision'], 'reason' => 'Apply the independently reviewed synthetic period closure'];
$ledger->engine($f['author'])->command('period-close', $close, $closeOperation);
expect($ledger->engine($f['author'])->command('period-close', $close, $closeOperation)['replayed'])->toBeTrue()
->and(DB::table('gl_period_closures')->count())->toBe(1)
->and(DB::table('gl_periods')->orderByDesc('version')->value('status'))->toBe('closed')
->and(DB::table('external_payments')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0);
});
test('common partial payment attribution uses explicit Finance categories without duplicate native payments and preserves reversed history', function () {
@@ -270,16 +352,23 @@ test('common partial payment attribution uses explicit Finance categories withou
$run = function (User $actor, string $action, array $data) use ($payables): array {
$this->actingAs($actor);
return $payables->engine($actor)->settlements()->command($action, $data, (string) Str::uuid());
return $payables->settlements($actor)->command($action, $data, (string) Str::uuid());
};
$payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $recognised['obligation_id'],
$paymentInput = ['obligation_id' => $recognised['obligation_id'],
'source_revision' => $recognised['source_revision'], 'amount' => '40.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(),
'fact_reference' => 'SIM-COMMON-PARTIAL', 'evidence_reference' => 'SIM-COMMON-EVIDENCE', 'reason' => 'Explicit synthetic confirmed payment fact']);
'fact_reference' => 'DOC-COMMON-PARTIAL', 'evidence_reference' => 'DOC-COMMON-EVIDENCE', 'reason' => 'Explicit synthetic confirmed payment fact'];
$this->actingAs($f['author']);
expect(fn () => $payables->engine($f['author'])->settlements()->command('payment-prepare', $paymentInput, (string) Str::uuid()))
->toThrow(InvalidArgumentException::class);
expect(DB::table('ps_payments')->count())->toBe(0);
$payment = $run($f['author'], 'payment-prepare', $paymentInput);
$paymentSnapshot = json_decode(DB::table('ps_payments')->where('id', $payment['payment_id'])->value('snapshot'), true, 32, JSON_THROW_ON_ERROR);
expect($paymentSnapshot['synthetic_only'])->toBeTrue();
$run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
'evidence_reference' => 'SIM-COMMON-CONFIRMED', 'reason' => 'Independent synthetic payment confirmation']);
'evidence_reference' => 'DOC-COMMON-CONFIRMED', 'reason' => 'Independent synthetic payment confirmation']);
$report = fn () => app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->whereKey($f['r']->id), null, null);
expect($report()['coverage']['indeterminate'])->toBe(1)->and($report()['currencies'])->toBe([]);
$allocation = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'SIM-ALLOCATION-EXPLICIT',
$allocation = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'DOC-ALLOCATION-EXPLICIT',
'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00']],
'reason' => 'Explicit synthetic invoice allocation of the confirmed payment']);
$run($f['validator'], 'allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed',
@@ -347,7 +436,7 @@ test('one common payment shared across two invoices is counted once while explic
$run = function (User $actor, string $action, array $data) use ($adapter): array {
$this->actingAs($actor);
return $adapter->engine($actor)->settlements()->command($action, $data, (string) Str::uuid());
return $adapter->settlements($actor)->command($action, $data, (string) Str::uuid());
};
$payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $obligations[0]['obligation_id'], 'source_revision' => $obligations[0]['source_revision'],
'amount' => '70.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(), 'fact_reference' => 'SIM-TWO-INVOICES',
@@ -376,3 +465,100 @@ test('one common payment shared across two invoices is counted once while explic
->and(DB::table('ps_payments')->count())->toBe(1)->and(DB::table('ps_allocations')->count())->toBe(2)
->and(DB::table('external_payments')->count())->toBe(0);
});
test('company finance configuration requires an administrator and records explicit access with safe replay and revocation', function () {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Admin]);
$finance = User::factory()->create(['tenant_id' => $admin->tenant_id, 'department_id' => $admin->department_id,
'purchasing_role' => PurchasingRole::Finance]);
$service = app(CommonFinanceAdministration::class);
$this->actingAs($finance)->get('/administracao/financeiro')->assertForbidden();
$before = DB::table('pa_access')->count();
$this->actingAs($admin);
$space = $service->workspace($admin, $finance->id);
expect($space['selectedAccess']['actions'])->toBe([])->and(DB::table('pa_access')->count())->toBe($before);
$payload = ['operation_key' => (string) Str::uuid(), 'basis_hash' => $space['selectedAccess']['hash'],
'reason' => 'Explicit synthetic company financial access', 'user_id' => $finance->id,
'person' => 'synthetic-person-finance', 'actions' => ['view', 'payments_view']];
$result = $service->save($admin, 'access', $payload);
expect($result['replayed'])->toBeFalse()->and($service->save($admin, 'access', $payload)['replayed'])->toBeTrue()
->and(DB::table('pa_access')->where('user_id', $finance->id)->count())->toBe(2)
->and(DB::table('gl_events')->where('kind', 'configuration.access')->count())->toBe(1);
expect(fn () => $service->save($admin, 'access', [...$payload, 'operation_key' => (string) Str::uuid(), 'actions' => ['view']]))
->toThrow(DomainException::class);
$finance->forceFill(['purchasing_role' => PurchasingRole::Warehouse])->save();
$fresh = $service->workspace($admin, $finance->id);
expect($fresh['selectedAccess']['eligible'])->toBeFalse();
expect(fn () => $service->save($admin, 'access', [...$payload, 'operation_key' => (string) Str::uuid(), 'basis_hash' => $fresh['selectedAccess']['hash']]))
->toThrow(ValidationException::class);
$service->save($admin, 'access', [...$payload, 'operation_key' => (string) Str::uuid(), 'basis_hash' => $fresh['selectedAccess']['hash'], 'actions' => [], 'person' => '']);
expect(DB::table('pa_access')->where('user_id', $finance->id)->count())->toBe(0)
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0);
});
test('company finance configuration creates own chart periods and versioned rules without financial postings', function () {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Admin]);
$service = app(CommonFinanceAdministration::class);
$this->actingAs($admin);
$save = function (string $kind, array $data) use ($service, $admin) {
$space = $service->workspace($admin);
return $service->save($admin, $kind, $data + ['operation_key' => (string) Str::uuid(),
'basis_hash' => $space[match ($kind) {
'account' => 'accounts', 'period' => 'periods', 'rule' => 'rules'
}]['hash'],
'reason' => 'Explicit synthetic own company financial configuration']);
};
$debit = $save('account', ['code' => '32001', 'label' => 'Synthetic inventory', 'currency' => 'MZN', 'is_movement' => true]);
$credit = $save('account', ['code' => '42001', 'label' => 'Synthetic suppliers', 'currency' => 'MZN', 'is_movement' => true]);
expect(fn () => $save('account', ['code' => '32001', 'label' => 'Duplicate', 'currency' => 'MZN', 'is_movement' => true]))->toThrow(DomainException::class);
$save('period', ['period_key' => 'OWN-2026', 'starts_on' => '2026-01-01', 'ends_on' => '2026-12-31']);
expect(fn () => $save('period', ['period_key' => 'OVERLAP', 'starts_on' => '2026-12-01', 'ends_on' => '2027-01-31']))->toThrow(DomainException::class);
$rule = ['rule_key' => 'OWN-SUPPLIER', 'effect_type' => 'supplier_payable.recognised', 'valid_from' => '2026-01-01',
'valid_to' => '2026-12-31', 'debit_account_id' => $debit['id'], 'credit_account_id' => $credit['id']];
$save('rule', $rule);
$save('rule', $rule);
expect(DB::table('gl_rules')->where('rule_key', 'OWN-SUPPLIER')->orderBy('version')->pluck('version')->all())->toBe([1, 2]);
expect(fn () => $save('rule', [...$rule, 'credit_account_id' => $debit['id']]))->toThrow(ValidationException::class);
expect(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0)
->and(DB::table('stock_movements')->count())->toBe(0);
$this->withoutVite()->actingAs($admin)->get('/administracao/financeiro')->assertOk()
->assertInertia(fn ($page) => $page->component('company/finance')->has('accounts.rows', 2)->has('rules.rows', 2)
->where('commonFinanceNavigation.configuration', true)->where('commonFinanceNavigation.payments', false)
->where('commonFinanceNavigation.ledger', false))
->assertHeader('Cache-Control', 'max-age=0, no-store, private');
});
test('financial configuration HTTP rejects foreign targets and preserves permissions belonging to another contract', function () {
$admin = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Admin]);
$finance = User::factory()->create(['tenant_id' => $admin->tenant_id, 'department_id' => $admin->department_id,
'purchasing_role' => PurchasingRole::Finance]);
$foreign = User::factory()->create(['tenant_id' => Tenant::query()->create(['name' => 'Other synthetic company'])->id,
'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($admin);
$service = app(CommonFinanceAdministration::class);
DB::table('pa_access')->insert(['tenant_id' => $admin->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $finance->id, 'person' => 'shared-synthetic-person', 'action' => 'other-contract.read']);
$space = $service->workspace($admin, $finance->id);
$payload = ['operation_key' => (string) Str::uuid(), 'basis_hash' => $space['selectedAccess']['hash'],
'reason' => 'Explicit synthetic configuration HTTP test', 'user_id' => $finance->id,
'person' => 'shared-synthetic-person', 'actions' => ['view']];
$this->get('/administracao/financeiro?user='.$foreign->id)->assertNotFound();
$this->postJson('/administracao/financeiro/access', [...$payload, 'user_id' => $foreign->id])->assertNotFound();
$this->postJson('/administracao/financeiro/access', [...$payload, 'person' => 'changed-synthetic-person'])->assertConflict();
$this->from('/administracao/financeiro?user='.$finance->id)->post('/administracao/financeiro/access', $payload)->assertRedirect();
$events = DB::table('gl_events')->count();
$this->postJson('/administracao/financeiro/access', $payload)->assertRedirect();
expect(DB::table('gl_events')->count())->toBe($events);
$stale = [...$payload, 'operation_key' => (string) Str::uuid()];
$this->postJson('/administracao/financeiro/access', $stale)->assertConflict();
$this->withHeader('X-Inertia', 'true')->post('/administracao/financeiro/access', $stale)
->assertRedirect()->assertSessionHasErrors('configuration');
$fresh = $service->workspace($admin, $finance->id);
$service->save($admin, 'access', [...$payload, 'operation_key' => (string) Str::uuid(),
'basis_hash' => $fresh['selectedAccess']['hash'], 'actions' => [], 'person' => '']);
expect(DB::table('pa_access')->where('user_id', $finance->id)->pluck('action')->all())->toBe(['other-contract.read'])
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0);
});
@@ -0,0 +1,138 @@
<?php
use App\Services\BudgetDistributionSchema;
use App\Services\StandaloneArtifact;
use App\Services\StandaloneComponentSchema;
use App\Services\StandaloneInstallation;
use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Finance\Payables\SettlementSchema;
require_once __DIR__.'/../Support/PaymentFixture.php';
beforeEach(function () {
if (getenv('COMPRAS_STANDALONE_UPGRADE_QA') !== '1') {
$this->markTestSkipped('Use the owned standalone upgrade runner.');
}
if (! app()->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getConfig('host') !== '127.0.0.1'
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName())
|| config('standalone-runtime.enabled') === true || config('standalone-runtime.prepare_only') !== true) {
throw new LogicException('Owned synthetic legacy component fixture required.');
}
BudgetDistributionSchema::install();
SettlementSchema::install();
config(['common-payables.source_instance' => 'synthetic-legacy-component-upgrade']);
$this->installer = app(StandaloneInstallation::class);
$this->arguments = [DB::connection()->getDatabaseName(), DB::connection()->getConfig('username'),
'Synthetic named upgrade operator', 'Explicit synthetic preservation of recognised canonical components'];
});
test('existing canonical components require explicit selection and unknown or partial structures are refused before writes', function () {
expect(StandaloneComponentSchema::reusable(DB::connection()))->toBe(array_keys(StandaloneComponentSchema::SUPPORTED));
expect(fn () => $this->installer->prepare(...[...$this->arguments, true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_EXTENSION_SCHEMA_EXISTS');
expect(DB::getSchemaBuilder()->hasTable('compras_runtime_installations'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasTable('gl_accounts'))->toBeFalse();
DB::statement('ALTER TABLE ps_payments DISABLE TRIGGER ps_history_immutable');
expect(fn () => $this->installer->prepare(...[...$this->arguments, false, false, true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_COMPONENT_SCHEMA_UNSUPPORTED:supplier-settlements-v1');
DB::statement('ALTER TABLE ps_payments ENABLE TRIGGER ps_history_immutable');
DB::statement('ALTER TABLE ps_payments ADD COLUMN unknown_contract text');
expect(fn () => $this->installer->prepare(...[...$this->arguments, true, false, true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_COMPONENT_SCHEMA_UNSUPPORTED:supplier-settlements-v1');
DB::statement('ALTER TABLE ps_payments DROP COLUMN unknown_contract');
DB::statement('ALTER TABLE ps_outbox RENAME TO ps_outbox_unsupported');
expect(fn () => $this->installer->prepare(...[...$this->arguments, true, false, true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_COMPONENT_SCHEMA_UNSUPPORTED:supplier-settlements-v1');
expect(DB::getSchemaBuilder()->hasTable('compras_runtime_installations'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasTable('gl_accounts'))->toBeFalse();
});
test('explicit component upgrade preserves an independently confirmed partial payment and all original columns', function () {
$f = paymentFixture();
foreach ([$f['author'], $f['validator']] as $actor) {
foreach (['view', 'prepare', 'validate', 'payments_view', 'payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm'] as $action) {
DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $actor->id, 'person' => 'synthetic-upgrade-person-'.$actor->id, 'action' => $action]);
}
}
$payables = app(SupplierPayables::class);
$this->actingAs($f['author']);
$proposal = $payables->engine($f['author'])->command('prepare', $f['invoice']->id, 'Legacy synthetic invoice capture', (string) Str::uuid());
$this->actingAs($f['validator']);
$recognised = $payables->engine($f['validator'])->command('validate', $proposal['proposal_id'], 'Independent legacy recognition', (string) Str::uuid());
$run = function ($actor, $action, $data) use ($payables) {
$this->actingAs($actor);
return $payables->engine($actor)->settlements()->command($action, $data, (string) Str::uuid());
};
$payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $recognised['obligation_id'],
'source_revision' => $recognised['source_revision'], 'amount' => '40.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(),
'fact_reference' => 'SIM-UPGRADE-PAYMENT', 'evidence_reference' => 'SIM-UPGRADE-EVIDENCE', 'reason' => 'Existing synthetic partial payment']);
$run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
'evidence_reference' => 'SIM-UPGRADE-CONFIRMED', 'reason' => 'Independent legacy payment confirmation']);
$allocation = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'SIM-UPGRADE-ALLOCATION',
'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00']],
'reason' => 'Explicit legacy invoice allocation']);
$run($f['validator'], 'allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed',
'reason' => 'Independent legacy allocation confirmation']);
$columns = $before = [];
foreach (DB::getSchemaBuilder()->getTableListing() as $table) {
$columns[$table] = DB::getSchemaBuilder()->getColumnListing($table);
$before[$table] = DB::table($table)->select($columns[$table])->orderByRaw('1')->get()->toJson();
}
$prepare = function (bool $apply): array {
$arguments = ['--expected-database' => $this->arguments[0], '--expected-role' => $this->arguments[1],
'--operator' => $this->arguments[2], '--reason' => $this->arguments[3], '--reuse-components' => true];
if ($apply) {
$arguments['--apply'] = true;
}
expect(Artisan::call('compras:runtime:prepare', $arguments))->toBe(0);
return json_decode(Artisan::output(), true, 32, JSON_THROW_ON_ERROR);
};
$preview = $prepare(false);
expect($preview['written'])->toBeFalse()->and($preview['existing_components'])->toBe(array_keys(StandaloneComponentSchema::SUPPORTED))
->and(DB::getSchemaBuilder()->hasTable('compras_runtime_installations'))->toBeFalse();
$applied = $prepare(true);
expect($applied['state'])->toBe('prepared')->and($applied['written'])->toBeTrue();
expect($prepare(true)['state'])->toBe('already_prepared');
foreach ($before as $table => $expected) {
expect(DB::table($table)->select($columns[$table])->orderByRaw('1')->get()->toJson(), $table)->toBe($expected);
}
expect(DB::table('compras_runtime_installations')->count())->toBe(1)
->and(DB::table('compras_runtime_installations')->value('reason'))->toContain('supplier-settlements-v1')
->and(DB::table('ps_proposals')->where('id', $allocation['proposal_id'])->value('allocation_cycle'))->toBe(0);
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['prepare_only'] = false;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
config(['standalone-runtime' => $settings]);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
app()->instance(StandaloneRuntime::class, $runtime);
$runtime->configure(DB::connection());
$this->actingAs($f['validator']);
$listing = $payables->settlements($f['validator'])->listing();
expect($listing['payments'])->toHaveCount(1)->and($listing['allocations'])->toHaveCount(1)
->and($listing['payments'][0]['amount_minor'])->toBe(4000)
->and($payables->engine($f['validator'])->positionForSource($f['invoice']->id)['balance_minor'])->toBe(2000)
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('external_payments')->count())->toBe(0);
});
test('a failure during additive component upgrade rolls back all new schema and permits one safe retry', function () {
DB::statement('CREATE VIEW ps_reversals AS SELECT 1 AS synthetic_conflict');
expect(fn () => $this->installer->prepare(...[...$this->arguments, true, false, true]))
->toThrow(QueryException::class);
expect(StandaloneComponentSchema::reusable(DB::connection()))->toBe(array_keys(StandaloneComponentSchema::SUPPORTED))
->and(DB::getSchemaBuilder()->hasTable('compras_runtime_installations'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasTable('gl_accounts'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasTable('budget_order_commands'))->toBeFalse()
->and(DB::getSchemaBuilder()->hasColumn('ps_proposals', 'allocation_cycle'))->toBeFalse();
DB::statement('DROP VIEW ps_reversals');
expect($this->installer->prepare(...[...$this->arguments, true, false, true])['state'])->toBe('prepared')
->and(DB::table('compras_runtime_installations')->count())->toBe(1);
});
@@ -0,0 +1,86 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Tenant;
use App\Models\User;
use App\Services\CommonFinanceAdministration;
use App\Services\StandaloneRuntime;
use Illuminate\Support\Str;
// Included only after the standalone worker validates its own QA cluster/root/role.
$runtime = app(StandaloneRuntime::class);
$runtime->assertInstallation($db);
$runtime->assertLoadedPackages();
if (! $runtime->syntheticOnly() || ! in_array($argv[3] ?? '', ['same', 'different'], true)) {
throw new LogicException('Explicit synthetic configuration race required.');
}
$round = $argv[3];
$file = $root.'/configuration-race-'.$round.'.json';
$frames = static function () use ($db): array {
$rows = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices', 'gl_journals', 'gl_lines', 'ps_payments', 'ps_allocations'] as $table) {
$rows[$table] = hash('sha256', $db->table($table)->orderBy('id')->get()->toJson());
}
return $rows;
};
if ($mode === 'prepare-configuration-race') {
if (is_file($file)) {
throw new LogicException('Configuration race already prepared.');
}
$tenant = Tenant::query()->create(['name' => 'Synthetic configuration concurrency '.$round]);
$actor = User::factory()->create(['tenant_id' => $tenant->id, 'purchasing_role' => PurchasingRole::Admin]);
auth()->guard()->setUser($actor);
$basis = app(CommonFinanceAdministration::class)->workspace($actor)['accounts']['hash'];
$command = ['basis_hash' => $basis, 'reason' => 'Synthetic concurrent company account configuration',
'code' => 'RACE-OWN', 'label' => 'Synthetic movement account', 'currency' => 'MZN', 'is_movement' => true];
$key = (string) Str::uuid();
file_put_contents($file, json_encode(['actor_id' => $actor->id, 'tenant_id' => $tenant->id, 'frames' => $frames(),
'commands' => [$command + ['operation_key' => $key], $command + ['operation_key' => $round === 'same' ? $key : (string) Str::uuid()]]], JSON_THROW_ON_ERROR));
echo json_encode(['prepared' => true], JSON_THROW_ON_ERROR);
exit;
}
$saved = json_decode(file_get_contents($file), true, 32, JSON_THROW_ON_ERROR);
$actor = User::query()->findOrFail($saved['actor_id']);
auth()->guard()->setUser($actor);
if ($mode === 'run-configuration-race') {
$index = $argv[4] ?? '';
if (! in_array($index, ['0', '1'], true)) {
throw new LogicException('Two explicit concurrent actors required.');
}
file_put_contents($root.'/configuration-'.$round.'-'.$index.'.ready', 'ready');
$until = microtime(true) + 20;
while (! is_file($root.'/configuration-'.$round.'.go')) {
if (microtime(true) > $until) {
throw new LogicException('Configuration concurrency gate timed out.');
}
usleep(10000);
}
try {
$result = app(CommonFinanceAdministration::class)->save($actor, 'account', $saved['commands'][(int) $index]);
echo json_encode(['state' => 'saved', 'replayed' => $result['replayed']], JSON_THROW_ON_ERROR);
} catch (DomainException $error) {
// A conflicting preparation must be rejected, not silently rewritten.
if ($round !== 'different' || ! str_contains($error->getMessage(), 'configuração mudou')) {
throw $error;
}
echo json_encode(['state' => 'stale'], JSON_THROW_ON_ERROR);
}
exit;
}
if ($mode !== 'read-configuration-race') {
throw new LogicException('Unknown configuration concurrency mode.');
}
$db->transaction(function () use ($db, $saved, $frames) {
$db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
if ($saved['frames'] !== $frames() || $db->table('gl_accounts')->where('tenant_id', $saved['tenant_id'])->count() !== 1
|| $db->table('gl_commands')->where('tenant_id', $saved['tenant_id'])->count() !== 1
|| $db->table('gl_events')->where('tenant_id', $saved['tenant_id'])->where('kind', 'configuration.account')->count() !== 1
|| $db->table('pa_access')->where('tenant_id', $saved['tenant_id'])->exists()
|| $db->table('audit_logs')->where('tenant_id', $saved['tenant_id'])->where('action', 'company.finance_configuration_changed')->count() !== 1) {
throw new LogicException('Concurrent configuration duplicated a record or changed protected facts.');
}
});
echo json_encode(['verified' => true, 'round' => $round, 'one_account_command_event_audit' => true,
'protected_financial_stock_frames' => 8, 'no_automatic_grants' => true], JSON_THROW_ON_ERROR);
exit;
@@ -0,0 +1,113 @@
import { readFileSync } from 'node:fs';
import path from 'node:path';
import vm from 'node:vm';
import test from 'node:test';
import assert from 'node:assert/strict';
const root = process.env.COMPRAS_FINANCE_UI_PACKAGE_ROOT;
if (!root) throw Error('Explicit verified candidate package root required');
function workspace(file, host = true) {
const forms = [0, 1].map(() => ({
dataset: { action: file.startsWith('general-ledger') ? 'prepare' : 'payment-prepare' },
values: new Map([['reason', '']]), button: { disabled: false }, appended: [],
querySelector(selector) { return selector === 'button' ? this.button : null; },
querySelectorAll(selector) { return selector === 'button' ? [this.button] : []; },
append(...nodes) { this.appended.push(...nodes); },
}));
const nodes = Object.fromEntries(['#finance', '#reload', '#status', '#error', 'main'].map(id => [id, { textContent: '', focus() {}, prepend() {} }]));
const events = new Map();
const state = { reloads: 0, requests: [], response: async () => ({ ok: true, json: async () => ({ state: 'saved' }) }) };
const settings = { api: '/api/supplier-payments', csrf: 'synthetic', host_journal_policy: host, host_settlement_policy: host };
const source = readFileSync(path.join(root, file), 'utf8');
const script = source.match(/<script>([\s\S]*?)<\/script>/)[1]
.replace(/const settings=<\?=[\s\S]*?\?>;/, `const settings=${JSON.stringify(settings)};`);
let key = 0;
const context = vm.createContext({
document: {
querySelector: selector => nodes[selector],
querySelectorAll: selector => selector === '[data-action]' ? forms : [],
createElement: () => ({ textContent: '', setAttribute() {} }),
},
FormData: class { constructor(form) { this.form = form; } [Symbol.iterator]() { return this.form.values.entries(); } },
window: { addEventListener: (event, callback) => events.set(event, callback) },
location: { reload: () => state.reloads++, assign() {} },
crypto: { randomUUID: () => `synthetic-operation-${++key}` },
fetch: async (url, options) => { state.requests.push({ url, ...options }); return state.response(); },
});
vm.runInContext(script, context);
const leaving = () => {
const event = { prevented: false, preventDefault() { this.prevented = true; } };
events.get('beforeunload')?.(event);
return event.prevented;
};
const submit = form => form.onsubmit({ preventDefault() {} });
return { forms, state, leaving, submit, nodes };
}
for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php']) {
test(`${file}: only an edited preparation warns before leaving`, () => {
const w = workspace(file);
assert.equal(w.leaving(), false);
w.forms[0].values.set('reason', 'Explicit synthetic draft');
assert.equal(w.leaving(), true);
w.forms[0].values.set('reason', '');
assert.equal(w.leaving(), false);
});
test(`${file}: successful command keeps the other form draft and provides explicit refresh`, async () => {
const w = workspace(file);
w.forms[0].values.set('reason', 'Complete this synthetic command');
w.forms[1].values.set('reason', 'Preserve this separate preparation');
await w.submit(w.forms[0]);
assert.equal(w.state.reloads, 0);
assert.equal(w.forms[0].button.disabled, true);
assert.equal(w.forms[1].values.get('reason'), 'Preserve this separate preparation');
assert.equal(w.leaving(), true);
assert.equal(w.forms[0].appended.length, 2);
assert.match(w.forms[0].appended[0].textContent, /registada/);
assert.equal(w.forms[0].appended[1].type, 'button');
await w.submit(w.forms[0]);
assert.equal(w.state.requests.length, 1);
await w.submit(w.forms[1]);
assert.equal(w.state.reloads, 1);
assert.equal(w.leaving(), false);
});
test(`${file}: unknown network result preserves values and retries the same command identity`, async () => {
const w = workspace(file);
w.forms[0].values.set('reason', 'Do not lose an interrupted synthetic operation');
w.state.response = async () => { throw Error('Synthetic lost response'); };
await w.submit(w.forms[0]);
assert.equal(w.forms[0].button.disabled, false);
assert.equal(w.state.reloads, 0);
assert.equal(w.leaving(), true);
const key = w.state.requests[0].headers['Idempotency-Key'];
assert.ok(key);
w.state.response = async () => ({ ok: true, json: async () => ({}) });
await w.submit(w.forms[0]);
assert.equal(w.state.requests[1].headers['Idempotency-Key'], key);
assert.equal(w.forms[0].values.get('reason'), 'Do not lose an interrupted synthetic operation');
assert.equal(w.state.reloads, 1);
});
test(`${file}: a second submit while pending cannot start another request`, async () => {
const w = workspace(file);
let finish;
w.state.response = () => new Promise(resolve => { finish = resolve; });
const pending = w.submit(w.forms[0]);
await w.submit(w.forms[0]);
assert.equal(w.state.requests.length, 1);
finish({ ok: true, json: async () => ({}) });
await pending;
assert.equal(w.state.reloads, 1);
});
test(`${file}: existing legacy mode retains its original refresh behaviour`, async () => {
const w = workspace(file, false);
w.forms[1].values.set('reason', 'Legacy QA preparation');
assert.equal(w.leaving(), false);
await w.submit(w.forms[0]);
assert.equal(w.state.reloads, 1);
});
}
@@ -0,0 +1,114 @@
<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
require dirname(__DIR__, 2).'/vendor/autoload.php';
$database = getenv('DB_DATABASE');
$pilot = in_array('--install-authorized-pilot', $argv, true);
$root = dirname(__DIR__, 2);
$destinationValid = preg_match('/^compras_private_restore_([a-f0-9]{12})$/D', $database ?: '', $match)
&& getenv('DB_USERNAME') === 'compras_private_app_'.$match[1];
if ($pilot) {
$approval = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
$plan = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
$source = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json'), true, 32, JSON_THROW_ON_ERROR);
$destinationValid = ($approval['state'] ?? null) === 'approved' && ($approval['scope'] ?? null) === 'pilot_schema_and_pinned_runtime_only'
&& hash_equals($approval['proposal_sha256'], hash_file('sha256', $root.'/docs/proofs/compras-standalone-pilot-installation-proposal.json'))
&& ($source['APP_ENV'] ?? null) === 'payable-testing' && realpath($source['HOST_ROOT']) === realpath($root)
&& preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $database ?: '', $sourceMatch)
&& $database === $source['DB_DATABASE'] && getenv('DB_USERNAME') === 'payable_qa_'.$sourceMatch[1]
&& getenv('DB_USERNAME') === $source['DB_USERNAME'] && getenv('DB_PORT') === $source['DB_PORT']
&& realpath(getenv('COMPRAS_RUNTIME_ROOT')) === realpath($plan['runtime']['private_installation_directory'])
&& getenv('COMPRAS_RUNTIME_SHA256') === $plan['runtime']['manifest_sha256'];
}
if (! $destinationValid || getenv('DB_HOST') !== '127.0.0.1'
|| getenv('APP_ENV') !== 'private-recovery' || getenv('COMPRAS_RUNTIME_ENABLED') !== 'false'
|| getenv('COMPRAS_RUNTIME_PREPARE_ONLY') !== 'true' || getenv('QUEUE_CONNECTION') !== 'null') {
throw new LogicException('PRIVATE_RECOVERY_DESTINATION_REQUIRED');
}
$proposal = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-recovery-proposal.json'), true, 32, JSON_THROW_ON_ERROR);
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$identity = $db->selectOne('SELECT current_database() AS database_name,current_user AS role_name');
if ($identity->database_name !== $database || $identity->role_name !== getenv('DB_USERNAME')) {
throw new LogicException('PRIVATE_RECOVERY_IDENTITY_MISMATCH');
}
$baseline = null;
if (getenv('COMPRAS_INSTALLATION_BASELINE') !== false) {
$baselinePath = realpath(getenv('COMPRAS_INSTALLATION_BASELINE') ?: '');
$boundary = realpath('C:/laragon/data/sgf-tempo/backups');
if ($baselinePath === false || $boundary === false || ! str_starts_with(str_replace('\\', '/', $baselinePath), str_replace('\\', '/', $boundary).'/')) {
throw new LogicException('PILOT_INSTALLATION_PRIVATE_BASELINE_REQUIRED');
}
$baseline = json_decode(file_get_contents($baselinePath), true, 128, JSON_THROW_ON_ERROR);
$db->beginTransaction();
$db->statement("SET LOCAL lock_timeout = '5s'");
$tables = array_keys($baseline['columns']);
$tables = array_values(array_diff($tables, ['tenants']));
array_unshift($tables, 'tenants');
$db->statement('LOCK TABLE '.implode(',', array_map(static fn ($name) => '"'.str_replace('"', '""', $name).'"', $tables)).' IN SHARE ROW EXCLUSIVE MODE');
}
$frames = static function () use ($db, $baseline): array {
$out = [];
foreach ($baseline['columns'] as $table => $names) {
$quoted = implode(',', array_map(static fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
$rows = array_column($db->select('SELECT row_to_json(t)::text AS row FROM (SELECT '.$quoted.' FROM "'.str_replace('"', '""', $table).'") t ORDER BY row_to_json(t)::text'), 'row');
$out[$table] = ['rows' => count($rows), 'sha256' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))];
}
return $out;
};
if ($baseline !== null && $frames() !== $baseline['frames']) {
throw new LogicException('PILOT_CHANGED_AFTER_VERIFIED_BACKUP');
}
$paths = array_keys($proposal['selected_normal_migrations_in_restored_copy_only']);
foreach ($proposal['selected_normal_migrations_in_restored_copy_only'] as $path => $hash) {
if (! hash_equals($hash, hash_file('sha256', $root.'/'.$path))) {
throw new LogicException('PRIVATE_RECOVERY_MIGRATION_CHANGED');
}
}
if (Artisan::call('migrate', ['--path' => $paths, '--force' => true, '--no-interaction' => true]) !== 0) {
throw new LogicException('PRIVATE_RECOVERY_MIGRATION_FAILED');
}
$arguments = ['--expected-database' => $database, '--expected-role' => getenv('DB_USERNAME'),
'--operator' => 'Authorised private recovery verification', '--reason' => 'Owner authorised upgrade rehearsal on private restored copy only',
'--reuse-components' => true];
$invoke = static function (array $arguments): array {
if (Artisan::call('compras:runtime:prepare', $arguments) !== 0) {
throw new LogicException('PRIVATE_RECOVERY_PREPARATION_FAILED');
}
return json_decode(Artisan::output(), true, 32, JSON_THROW_ON_ERROR);
};
$preview = $invoke($arguments);
$applied = $invoke($arguments + ['--apply' => true]);
$repeated = $invoke($arguments + ['--apply' => true]);
if ($preview['written'] !== false || $applied['state'] !== 'prepared' || $repeated['state'] !== 'already_prepared'
|| $repeated['written'] !== false || $db->table('compras_runtime_installations')->count() !== 1) {
throw new LogicException('PRIVATE_RECOVERY_REPLAY_FAILED');
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$settings['prepare_only'] = false;
$settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
$runtime->configure($db);
if ($baseline !== null) {
$after = $frames();
$before = $baseline['frames'];
unset($after['migrations'], $before['migrations']);
$expected = [...$baseline['migrations'], ...array_map(static fn ($path) => basename($path, '.php'), $paths)];
sort($expected, SORT_STRING);
if ($before !== $after || $db->table('migrations')->orderBy('migration')->pluck('migration')->all() !== $expected) {
throw new LogicException('PILOT_INSTALLATION_CONSERVATION_FAILED');
}
$db->commit();
}
echo json_encode(['verified' => true, 'selected_migrations' => count($paths), 'available_modules' => count(StandaloneRuntime::FEATURES),
'one_receipt_replay_without_write' => true, 'configuration_stays_disabled' => config('standalone-runtime.enabled') === false,
'existing_components' => $preview['existing_components']], JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,33 @@
<?php
// Owned loopback QA only; the application still uses the verified candidate loader.
use Illuminate\Http\Request;
$root = realpath(getenv('SGC_STANDALONE_QA_ROOT') ?: '');
$boundary = realpath(__DIR__.'/../../storage/framework/testing');
$database = getenv('DB_DATABASE') ?: '';
if (getenv('APP_ENV') !== 'standalone-qa' || getenv('COMPRAS_RUNTIME_ENABLED') !== 'true'
|| getenv('COMPRAS_RUNTIME_PREPARE_ONLY') !== 'false' || getenv('COMPRAS_RUNTIME_SYNTHETIC_ONLY') !== 'true'
|| ! preg_match('/^compras_standalone_qa_([a-f0-9]{12})$/D', $database, $matches)
|| getenv('DB_USERNAME') !== 'compras_standalone_app_'.$matches[1]
|| getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| ($_SERVER['REMOTE_ADDR'] ?? '') !== '127.0.0.1' || ($_SERVER['SERVER_PORT'] ?? '') != getenv('SGC_STANDALONE_QA_PORT')
|| $root === false || $boundary === false || dirname($root) !== $boundary || basename($root) !== 'rq01-ledger-qa-'.$matches[1]) {
http_response_code(503);
exit;
}
require __DIR__.'/../../vendor/autoload.php';
$public = $root.'/public';
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$asset = realpath($public.'/'.ltrim(rawurldecode($requestPath), '/'));
$types = ['js' => 'text/javascript', 'css' => 'text/css', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2'];
if ($asset !== false && is_file($asset) && str_starts_with(str_replace('\\', '/', $asset), str_replace('\\', '/', $public).'/')
&& isset($types[pathinfo($asset, PATHINFO_EXTENSION)])) {
header('Content-Type: '.$types[pathinfo($asset, PATHINFO_EXTENSION)]);
readfile($asset);
exit;
}
$app = require __DIR__.'/../../bootstrap/app.php';
$app->useStoragePath($root.'/storage');
$app->usePublicPath($public);
$app->handleRequest(Request::capture());
+75 -4
View File
@@ -5,7 +5,9 @@ use App\Models\Department;
use App\Models\Tenant;
use App\Models\User;
use App\Services\AgreementOrderLimits;
use App\Services\BudgetDistributionSchema;
use App\Services\CapitalRegister;
use App\Services\CommonFinanceAdministration;
use App\Services\ConflictReleases;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
@@ -22,6 +24,8 @@ use App\Services\PrivateAuditAccess;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionLedgerAccounts;
use App\Services\StandaloneArtifact;
use App\Services\StandaloneComponentSchema;
use App\Services\StandaloneInstallation;
use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables;
@@ -33,7 +37,9 @@ use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tempo\Finance\GeneralLedger\LedgerConfiguration;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\Payables\SettlementSchema;
require dirname(__DIR__, 2).'/vendor/autoload.php';
$database = $argv[1] ?? '';
@@ -44,8 +50,9 @@ if (! preg_match('/^compras_standalone_qa_([a-f0-9]{12})(_restored)?$/D', $datab
|| $root === false || $parent === false || dirname($root) !== $parent || basename($root) !== 'rq01-ledger-qa-'.$match[1]
|| getenv('DB_DATABASE') !== $database || getenv('DB_USERNAME') !== 'compras_standalone_app_'.$match[1].($match[2] ?? '')
|| getenv('DB_HOST') !== '127.0.0.1' || getenv('DB_PORT') !== '55439'
|| getenv('APP_ENV') !== 'standalone-qa' || ! in_array($mode, ['prepare', 'verify', 'reject-restore', 'rebind',
'reject-foreign', 'reject-pin', 'reject-dependency', 'reject-old'], true)) {
|| getenv('APP_ENV') !== 'standalone-qa' || ! in_array($mode, ['prepare', 'verify', 'prepare-ui', 'read-ui', 'reject-restore', 'rebind',
'prepare-configuration-race', 'run-configuration-race', 'read-configuration-race', 'prepare-component-profile',
'reject-foreign', 'reject-pin', 'reject-prepare-pin', 'reject-dependency', 'reject-old'], true)) {
throw new LogicException('Owned standalone QA composition required.');
}
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
@@ -56,7 +63,7 @@ if ($mode === 'reject-foreign') {
$expectedRejection = match ($mode) {
'reject-restore' => 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH',
'reject-foreign' => 'COMPRAS_RUNTIME_CLASS_LOCATION',
'reject-pin' => 'COMPRAS_RUNTIME_MANIFEST_HASH',
'reject-pin', 'reject-prepare-pin' => 'COMPRAS_RUNTIME_MANIFEST_HASH',
'reject-dependency' => 'COMPRAS_RUNTIME_FEATURE_DEPENDENCY:import-bank-support:import-dossier',
'reject-old' => 'COMPRAS_RUNTIME_CAPABILITY_UNAVAILABLE',
default => null,
@@ -67,6 +74,9 @@ try {
if ($expectedRejection === null || $e->getMessage() !== $expectedRejection) {
throw $e;
}
if ($mode === 'reject-prepare-pin' && class_exists(LedgerConfiguration::class, false)) {
throw new LogicException('Unverified preparation executed a candidate package.');
}
echo json_encode(['rejected' => true, 'reason' => $e->getMessage()], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
@@ -78,6 +88,67 @@ $identity = $db->selectOne("SELECT current_database() AS d,current_setting('clus
if ($identity->d !== $database || $identity->c !== 'sgf_modular_regression_'.$match[1]) {
throw new LogicException('Owned standalone QA database identity mismatch.');
}
if ($mode === 'prepare-component-profile') {
if (config('standalone-runtime.prepare_only') !== true || config('standalone-runtime.enabled') === true) {
throw new LogicException('Profile fixture requires disabled business runtime and verified console composition.');
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$loader = new StandaloneRuntime($settings, new StandaloneArtifact);
$loader->artifact();
$loader->assertLoadedPackages();
BudgetDistributionSchema::install();
SettlementSchema::installForHost('COMMON-PAYABLE-SETTLEMENT-HOST-SCHEMA-v1', function ($connection) use ($database) {
if ($connection->getDatabaseName() !== $database) {
throw new LogicException('Synthetic component fixture changed database.');
}
});
$profiles = [];
foreach (array_keys(StandaloneComponentSchema::GROUPS) as $group) {
$profiles[$group] = StandaloneComponentSchema::inspect($db, $group);
}
echo json_encode(['synthetic_canonical_component_profiles' => $profiles], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
if (in_array($mode, ['prepare-configuration-race', 'run-configuration-race', 'read-configuration-race'], true)) {
require __DIR__.'/StandaloneConfigurationRace.php';
exit;
}
if (in_array($mode, ['prepare-ui', 'read-ui'], true)) {
$runtime = app(StandaloneRuntime::class);
$runtime->assertInstallation($db);
$runtime->assertLoadedPackages();
if (! $runtime->syntheticOnly()) {
throw new LogicException('Only synthetic UI review allowed.');
}
$frames = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices', 'gl_journals', 'gl_lines', 'ps_payments', 'ps_allocations'] as $table) {
$frames[$table] = hash('sha256', $db->table($table)->orderBy('id')->get()->toJson());
}
if ($mode === 'read-ui') {
$saved = json_decode(file_get_contents($root.'/standalone-ui.json'), true, 32, JSON_THROW_ON_ERROR);
if ($saved['frames'] !== $frames) {
throw new LogicException('UI setup changed protected financial or stock facts.');
}
echo json_encode(['ui_conservation_verified' => true, 'protected_frames' => count($frames), 'synthetic_only' => true], JSON_THROW_ON_ERROR);
exit;
}
if (is_file($root.'/standalone-ui.json')) {
throw new LogicException('UI fixture already prepared.');
}
$tenant = Tenant::query()->create(['name' => 'Synthetic standalone finance UI review']);
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Synthetic company']);
$admin = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id,
'name' => 'QA Finance Administrator', 'email' => 'qa-finance-admin@example.invalid', 'purchasing_role' => PurchasingRole::Admin]);
$finance = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id,
'name' => 'QA Financial Reviewer', 'email' => 'qa-finance-reviewer@example.invalid', 'purchasing_role' => PurchasingRole::Finance]);
$proof = ['admin_login' => $admin->email, 'finance_login' => $finance->email, 'finance_id' => $finance->id,
'tenant_id' => $tenant->id, 'frames' => $frames, 'no_initial_financial_grants' => ! $db->table('pa_access')->where('tenant_id', $tenant->id)->exists()];
file_put_contents($root.'/standalone-ui.json', json_encode($proof, JSON_THROW_ON_ERROR));
unset($proof['frames']);
echo json_encode(['ui_prepared' => true] + $proof, JSON_THROW_ON_ERROR);
exit;
}
if (in_array($mode, ['prepare', 'rebind'], true)) {
$arguments = ['--expected-database' => $database, '--expected-role' => getenv('DB_USERNAME'),
'--operator' => 'Synthetic named QA deployment operator', '--reason' => 'Authorised candidate installation and recovery verification'];
@@ -140,7 +211,7 @@ if (in_array($mode, ['prepare', 'rebind'], true)) {
$runtime = app(StandaloneRuntime::class);
$runtime->assertLoadedPackages();
$checks = 0;
foreach ([CapitalRegister::class, OperationalOrders::class, PrivateAuditAccess::class, ConflictReleases::class,
foreach ([CommonFinanceAdministration::class, CapitalRegister::class, OperationalOrders::class, PrivateAuditAccess::class, ConflictReleases::class,
UrgentQuotationBasis::class, UrgentRequisitionReviews::class, RequisitionLedgerAccounts::class,
RequisitionExpiry::class, RequisitionBudgetDistributions::class,
ExpenseAllocations::class, AgreementOrderLimits::class, OrderPartsPreparation::class,
+8
View File
@@ -59,3 +59,11 @@ test('standalone binding rejects other drivers without querying them', function
$db->shouldReceive('getDriverName')->once()->andReturn('sqlite');
expect(fn () => StandaloneRuntime::databaseBinding($db))->toThrow(LogicException::class, 'COMPRAS_RUNTIME_DATABASE_DRIVER');
});
test('standalone data classification remains explicit and defaults to synthetic', function () {
expect((new StandaloneRuntime([], new StandaloneArtifact))->syntheticOnly())->toBeTrue()
->and((new StandaloneRuntime(['enabled' => true], new StandaloneArtifact))->syntheticOnly())->toBeTrue()
->and((new StandaloneRuntime(['enabled' => true, 'synthetic_only' => false], new StandaloneArtifact))->syntheticOnly())->toBeFalse();
expect(fn () => (new StandaloneRuntime(['enabled' => true, 'synthetic_only' => 'false'], new StandaloneArtifact))->syntheticOnly())
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_DATA_CLASSIFICATION');
});
+129
View File
@@ -0,0 +1,129 @@
import { App } from '@inertiajs/react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import Finance from '@/pages/company/finance';
import { procurementNavigation } from '@/lib/procurement-navigation';
const empty = { data: [], prev_page_url: null, next_page_url: null };
const basis = { hash: 'a'.repeat(64), rows: [] };
function render(selectedAccess: Record<string, unknown> | null = null) {
return renderToStaticMarkup(
<App
initialComponent={Finance}
initialPage={{
component: 'company/finance',
url: '/administracao/financeiro',
version: null,
clearHistory: false,
encryptHistory: true,
props: {
errors: {},
actorId: 1,
tenantId: 1,
q: '',
users: empty,
selectedAccess,
accounts: basis,
periods: basis,
rules: basis,
actions: {
view: 'View supplier debts',
prepare: 'Prepare recognition',
},
effects: {
'supplier_payable.recognised': 'Recognise payable',
},
history: empty,
},
}}
/>,
);
}
test('company setup starts without an implicit target grants accounts dates or posting rules', () => {
const html = render();
expect(html).toContain('href="#finance-access"');
expect(html).not.toContain('checked=""');
expect(html).not.toContain('2026-01-01');
expect(html).not.toContain('QA-2026');
expect(html).not.toContain('value="supplier_payable.recognised" selected');
expect(html).not.toContain('View supplier debts');
});
test('explicit target is escaped and no permission is selected by reading an empty grant list', () => {
const html = render({
...basis,
user: { id: 3, name: '<Finance>', email: 'qa@example.invalid' },
eligible: true,
person: '',
actions: [],
other_actions: [],
identity_inconsistent: false,
});
expect(html).toContain('&lt;Finance&gt;');
expect(html).toContain('View supplier debts');
expect(html).not.toContain('checked=""');
expect(html).not.toContain('<Finance>');
});
test('financial menus expose only explicit capabilities and use full navigation for common package pages', () => {
const menu = (role: string, flags = {}) =>
procurementNavigation(
role,
false,
undefined,
false,
false,
false,
false,
flags,
).flatMap((group) => group.entries);
expect(menu('admin').some((entry) => entry.id === 'general_ledger')).toBe(
false,
);
const flags = { payments: true, ledger: true, configuration: true };
const admin = menu('admin', flags);
expect(admin.find((entry) => entry.id === 'general_ledger')).toMatchObject({
path: '/general-ledger/cycle',
fullPage: true,
});
expect(
admin.find((entry) => entry.id === 'supplier_settlements'),
).toMatchObject({ path: '/supplier-payments', fullPage: true });
expect(
admin.find((entry) => entry.id === 'finance_configuration'),
).toMatchObject({ path: '/administracao/financeiro' });
expect(
menu('finance', flags).some(
(entry) => entry.id === 'finance_configuration',
),
).toBe(false);
expect(
menu('requester', flags).some((entry) =>
[
'general_ledger',
'supplier_settlements',
'finance_configuration',
].includes(entry.id),
),
).toBe(false);
const publicMenu = procurementNavigation(
'admin',
false,
['/dashboard'],
false,
false,
false,
false,
flags,
).flatMap((group) => group.entries);
expect(
publicMenu.some((entry) =>
[
'general_ledger',
'supplier_settlements',
'finance_configuration',
].includes(entry.id),
),
).toBe(false);
});
@@ -65,6 +65,59 @@ test('incomplete detail identifies the missing original and preserves documented
expect(html).not.toContain('Aprovações do valor final');
});
test.each([true, false, undefined])(
'complete order preserves its recorded development classification: %s',
(development) => {
const html = render(Show, {
order: {
...order,
subtotal_minor: 10000,
tax_minor: 0,
snapshot: {
...order.snapshot,
development_only: development,
budget_checked: true,
supplier: {
name: 'Synthetic supplier',
nuit: '000000000',
contact: '',
phone: '',
email: '',
address: '',
},
department: { name: 'Synthetic operations' },
cost_center: { code: 'SYN', name: 'Synthetic centre' },
requisition: { number: 'RQ-SYN' },
issuer: { name: 'Synthetic issuer' },
requester: { name: 'Synthetic requester' },
quotation: {
reference: 'PROP-SYN',
payment_terms: 'Synthetic documentary terms',
},
award: {
justification: 'Synthetic approved example',
delivery_date: '2026-11-29',
delivery_location: 'Synthetic location',
},
approval_rules: {
approval_includes_tax: true,
rules_provisional: false,
},
decision_matrix: [],
final_approvals: [],
},
},
history: [],
snapshotComplete: true,
});
expect(html.includes('Documento de desenvolvimento')).toBe(
development !== false,
);
expect(html).toContain('Controlo orçamental registado na emissão');
expect(html).toContain('RQ-SYN');
},
);
test.each([
{
state: 'issued',