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

This commit is contained in:
2026-11-29 10:48:22 +02:00
parent 448948a487
commit 7da8d6c87a
64 changed files with 2538 additions and 288 deletions
+46
View File
@@ -8,6 +8,7 @@ use App\Models\Tenant;
use App\Models\User;
use App\Services\PrivateAuditAccess;
use App\Services\PrivateAuditSourceReader;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -187,3 +188,48 @@ test('private audit includes versioned import document metadata but excludes ban
->and($rows[0]['purchase_order_id'])->toBe($this->f['order']->id)
->and(json_encode($rows, JSON_THROW_ON_ERROR))->not->toContain('bank_commitment')->not->toContain('bank_support')->not->toContain('PRIVATE-PATH-NEVER-EXPORT');
});
test('private financial audit scopes common settlement rows and outbox by tenant company and unit without bank references', function () {
$schema = DB::getSchemaBuilder();
foreach (['ps_payments', 'ps_events'] as $name) {
$schema->create($name, function (Blueprint $table) use ($name) {
$table->id();
$table->unsignedBigInteger('tenant_id');
$table->unsignedBigInteger('company_id');
$table->unsignedBigInteger('unit_id');
if ($name === 'ps_payments') {
$table->bigInteger('amount_minor');
$table->string('fact_reference');
$table->string('evidence_reference');
$table->json('snapshot');
} else {
$table->unsignedBigInteger('payment_id');
$table->unsignedBigInteger('actor_id');
$table->string('kind');
$table->json('payload');
}
});
}
$schema->create('ps_outbox', function (Blueprint $table) {
$table->unsignedBigInteger('event_id')->primary();
$table->string('state');
});
$foreign = Tenant::query()->create(['name' => 'Synthetic other common payment tenant']);
$own = null;
foreach ([[$this->actor->tenant_id, 0, 0], [$this->actor->tenant_id, 7, 0], [$this->actor->tenant_id, 0, 9], [$foreign->id, 0, 0]] as [$tenant, $company, $unit]) {
$scope = ['tenant_id' => $tenant, 'company_id' => $company, 'unit_id' => $unit];
$payment = DB::table('ps_payments')->insertGetId($scope + ['amount_minor' => 123,
'fact_reference' => 'PRIVATE-BANK-FACT-SENTINEL', 'evidence_reference' => 'PRIVATE-BANK-EVIDENCE-SENTINEL',
'snapshot' => json_encode(['account_identifier' => 'PRIVATE-BANK-SNAPSHOT-SENTINEL'], JSON_THROW_ON_ERROR)]);
$event = DB::table('ps_events')->insertGetId($scope + ['payment_id' => $payment, 'actor_id' => $this->actor->id,
'kind' => 'supplier_payment.confirmed', 'payload' => json_encode(['amount_minor' => 123,
'account_identifier' => 'PRIVATE-BANK-PAYLOAD-SENTINEL'], JSON_THROW_ON_ERROR)]);
DB::table('ps_outbox')->insert(['event_id' => $event, 'state' => 'captured']);
$own ??= ['payment' => $payment, 'event' => $event];
}
$sources = collectedPrivateAuditSources($this->actor, ['finance']);
expect(array_column($sources['finance:ps_payments']['rows'], 'id'))->toBe([$own['payment']])
->and(array_column($sources['finance:ps_events']['rows'], 'id'))->toBe([$own['event']])
->and($sources['finance:ps_outbox']['rows'])->toBe([['event_id' => $own['event'], 'state' => 'captured']])
->and(json_encode($sources, JSON_THROW_ON_ERROR))->not->toContain('PRIVATE-BANK-');
});
@@ -0,0 +1,378 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\Requisition;
use App\Models\SupplyRecord;
use App\Models\User;
use App\Services\CommonBudget;
use App\Services\CommonPaymentFacts;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
use App\Services\InvoiceWorkflow;
use App\Services\ProcurementPaymentInsights;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionLedgerAccounts;
use App\Services\RequisitionWorkflow;
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Finance\Budget\BudgetFailure;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/PaymentFixture.php';
beforeEach(function () {
if (getenv('COMPRAS_STANDALONE_BUSINESS_QA') !== '1') {
$this->markTestSkipped('Use the owned standalone candidate business regression 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())) {
throw new LogicException('Synthetic standalone business database required.');
}
$settings = config('standalone-runtime');
$settings['enabled'] = true;
$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);
$runtime->artifact();
(require base_path('database/standalone-migrations/2026_11_29_000001_create_runtime_installations.php'))->up();
DB::table('compras_runtime_installations')->insert(['id' => $settings['installation_id'], 'product' => 'compras',
'contract' => StandaloneArtifact::CONTRACT, 'manifest_sha256' => $settings['manifest_sha256'],
'database_binding_sha256' => StandaloneRuntime::databaseBinding(DB::connection()),
'recorded_by' => 'Synthetic standalone business regression', 'reason' => 'Authorised isolated candidate verification', 'installed_at' => now()]);
(require base_path('database/standalone-migrations/2026_11_29_000002_install_standalone_extensions.php'))->up();
config(['standalone-runtime' => $settings]);
app()->instance(StandaloneRuntime::class, $runtime);
$paths = $runtime->configure(DB::connection());
config(['general-ledger.path' => $paths['general-ledger']]);
$runtime->assertLoadedPackages();
$this->f = receiptFixture();
$this->actingAs($this->f['issuer']);
});
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']);
$account = DB::table('gl_accounts')->insertGetId(['tenant_id' => $this->f['tenant']->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'OWN-CANDIDATE', 'label' => 'Synthetic standalone movement account', 'currency' => 'MZN', 'is_movement' => true]);
expect(config('requisition-accounts.qa_enabled'))->toBeFalse()->and(app(RequisitionLedgerAccounts::class)->ready())->toBeTrue();
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($this->f['issuer'], $request);
$selected = $space['accounts']['data'][0];
expect($selected['id'])->toBe($account);
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'item_id' => $space['items'][0]['id'],
'basis_hash' => $space['items'][0]['basis_hash'], 'reason' => 'Explicit synthetic standalone account attribution',
'allocations' => [['account_id' => $account, 'source_hash' => $selected['source_hash'], 'subtotal' => '100.00', 'total' => '100.00']]];
$record = $service->save($this->f['issuer'], $request, $input);
expect($service->save($this->f['issuer'], $request, $input)->id)->toBe($record->id)
->and($record->data['allocations'][0]['account']['code'])->toBe('OWN-CANDIDATE')
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0);
$this->actingAs($this->f['receiver']);
expect(fn () => $service->save($this->f['receiver'], $request, [...$input, 'operation_key' => (string) Str::uuid()]))->toThrow(ModelNotFoundException::class);
expect(DB::table('supply_records')->where('kind', 'req_account')->count())->toBe(1);
});
test('standalone candidate closes an old reservation cycle and reserves a revised amount once without rewriting history', function () {
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Finance]);
Budget::query()->create(['tenant_id' => $this->f['tenant']->id, 'cost_center_id' => $this->f['r']->cost_center_id,
'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true,
'reason' => 'Synthetic standalone cycle budget', 'created_by' => $this->f['issuer']->id, 'approved_by' => $finance->id]);
$origin = $this->f['r']->id;
$service = app(CommonBudget::class);
$first = $service->for($this->f['issuer'], [$origin => 1]);
$first->beginRequisitionCycle($origin, 1, (string) Str::uuid());
$first->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
expect(fn () => $first->closeRequisitionCycle($origin, 1, (string) Str::uuid()))->toThrow(BudgetFailure::class);
$first->record($origin, $this->f['r']->cost_center_id, 'operating', 'release');
$close = (string) Str::uuid();
$first->closeRequisitionCycle($origin, 1, $close);
$original = DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson();
expect($first->closeRequisitionCycle($origin, 1, $close)['replayed'])->toBeTrue();
$second = $service->for($this->f['issuer'], [$origin => 2]);
$second->beginRequisitionCycle($origin, 2, (string) Str::uuid());
$second->record($origin, $this->f['r']->cost_center_id, 'operating', 'reserve', 12000, 12000);
expect(DB::table('budget_entries')->where('requisition_cycle', 1)->orderBy('id')->get()->toJson())->toBe($original)
->and((int) DB::table('budget_entries')->sum('reserved_minor'))->toBe(12000)
->and(DB::table('stock_movements')->count())->toBe(0)->and(DB::table('gl_journals')->count())->toBe(0);
});
test('standalone candidate returns an expired request to its owner and requires new approvals and reservation on resubmission', function () {
$staff = fn (PurchasingRole $role) => User::factory()->create(['tenant_id' => $this->f['tenant']->id,
'department_id' => $this->f['department']->id, 'purchasing_role' => $role]);
$admin = $staff(PurchasingRole::Admin);
$head = $staff(PurchasingRole::DepartmentHead);
$finance = $staff(PurchasingRole::Finance);
$owner = $this->f['issuer'];
$this->f['tenant']->update(['first_limit_minor' => 5000, 'second_limit_minor' => 20000]);
Budget::query()->create(['tenant_id' => $owner->tenant_id, 'cost_center_id' => $this->f['r']->cost_center_id,
'year' => now()->year, 'kind' => 'operating', 'amount_minor' => 100000, 'includes_tax' => true,
'reason' => 'Synthetic standalone resubmission budget', 'created_by' => $owner->id, 'approved_by' => $finance->id]);
$expiry = app(RequisitionExpiry::class);
$this->actingAs($admin);
$expiry->savePolicy($admin, ['operation_key' => (string) Str::uuid(), 'version' => 0, 'enabled' => true,
'levels' => array_map(fn ($role) => ['role' => $role, 'expire_minutes' => 30, 'reminder_minutes' => null,
'escalation_minutes' => null, 'profile_ids' => []], ['department_head', 'procurement']),
'reason' => 'Explicit synthetic elapsed deadlines for candidate verification']);
$this->actingAs($owner);
$workflow = app(RequisitionWorkflow::class);
$input = ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $this->f['r']->cost_center_id, 'priority' => 'normal',
'needed_by' => today()->addWeek()->toDateString(), 'justification' => 'Synthetic standalone request with independent resubmission',
'items' => [['description' => 'Synthetic item', 'category' => 'Material', 'purchase_type' => 'consumable',
'quantity' => '1.000', 'unit' => 'un', 'unit_price' => '100.00', 'tax_rate' => '0.00']]];
$request = $workflow->save($owner, $input);
$account = DB::table('gl_accounts')->insertGetId(['tenant_id' => $owner->tenant_id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'EXPLICIT-CANDIDATE', 'label' => 'Synthetic cycle account', 'currency' => 'MZN', 'is_movement' => true]);
$assign = function (string $amount) use ($owner, $request, $account) {
$service = app(RequisitionAccountAssignments::class);
$space = $service->workspace($owner, $request);
$line = $space['items'][0];
$old = SupplyRecord::query()->where('kind', 'req_account')->where('data->requisition_item_id', $line['id'])->latest('id')->first();
$selected = $space['accounts']['data'][0];
$service->save($owner, $request, ['operation_key' => (string) Str::uuid(), 'version' => $old?->version ?? 0,
'item_id' => $line['id'], 'basis_hash' => $line['basis_hash'], 'reason' => 'Explicit candidate account for the current reviewed line',
'allocations' => [['account_id' => $account, 'source_hash' => $selected['source_hash'], 'subtotal' => $amount, 'total' => $amount]]]);
};
$assign('100.00');
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
$this->actingAs($head);
$workflow->decide($head, $request, 'approved', 'Independent synthetic first-stage decision', (string) Str::uuid(), $request->process_version);
$request->refresh();
$approved = $request->steps()->where('decision', 'approved')->sole()->toArray();
$this->travel(31)->minutes();
$deadline = $expiry->deadline($request);
$this->actingAs($owner);
$body = ['basis_hash' => $deadline['basis_hash'], 'operation_key' => (string) Str::uuid(), 'process_version' => $request->process_version];
$this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect();
$this->postJson('/requisicoes/'.$request->id.'/expiracao', $body)->assertRedirect();
$request->refresh();
expect($request->status)->toBe('draft')->and($request->requester_id)->toBe($owner->id)->and($request->approval_cycle)->toBe(2)
->and($request->allSteps()->whereKey($approved['id'])->firstOrFail()->toArray())->toBe($approved)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->sum('reserved_minor'))->toBe(0)
->and(SupplyRecord::query()->where('kind', 'req_expiration')->count())->toBe(1);
$input['operation_key'] = (string) Str::uuid();
$input['process_version'] = $request->process_version;
$input['items'][0]['unit_price'] = '120.00';
$workflow->save($owner, $input, $request);
$request->refresh();
$assign('120.00');
$workflow->submit($owner, $request, (string) Str::uuid(), $request->process_version);
$request->refresh();
expect($request->status)->toBe('pending')->and($request->steps()->count())->toBe(2)
->and($request->steps()->where('decision', 'approved')->count())->toBe(0)->and($request->allSteps()->count())->toBe(4)
->and((int) DB::table('budget_entries')->where('requisition_id', $request->id)->where('requisition_cycle', 2)->sum('reserved_minor'))->toBe(12000)
->and(DB::table('gl_journals')->count())->toBe(0)->and(DB::table('stock_movements')->count())->toBe(0);
});
test('standalone financial pages use explicit read rights and refuse writes or disabled modules', function () {
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Finance]);
$this->actingAs($finance)->get('/api/supplier-payments')->assertForbidden();
$this->get('/api/general-ledger/cycle')->assertForbidden();
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]);
}
$before = [];
foreach (['ps_payments', 'ps_allocations', 'ps_commands', 'ps_events', 'gl_journals', 'gl_commands', 'gl_events', 'budget_entries', 'stock_movements'] as $table) {
$before[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$this->get('/api/supplier-payments')->assertOk()->assertJsonPath('payments', [])->assertJsonPath('allocations', [])
->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('/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', [
'obligation_id' => 1, 'journal_on' => today()->toDateString(), 'period_key' => 'QA', 'rule_key' => 'QA',
'reason' => 'Synthetic attempt without writer authority'])->assertForbidden();
$settings = config('standalone-runtime');
$settings['features']['supplier-settlements'] = false;
$settings['features']['general-ledger-cycle'] = false;
app()->instance(StandaloneRuntime::class, new StandaloneRuntime($settings, new StandaloneArtifact));
$this->get('/api/supplier-payments')->assertForbidden();
$this->get('/api/general-ledger/cycle')->assertForbidden();
foreach ($before as $table => $frame) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($frame);
}
});
test('standalone candidate recognises one invoice and posts one balanced journal using explicitly configured own chart accounts', function () {
$f = paymentFixture();
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]);
}
}
$payables = app(SupplierPayables::class);
$this->actingAs($f['author']);
$prepared = $payables->engine($f['author'])->command('prepare', $f['invoice']->id, 'Explicit synthetic invoice review', (string) Str::uuid());
$this->actingAs($f['validator']);
$validated = $payables->engine($f['validator'])->command('validate', $prepared['proposal_id'], 'Independent synthetic recognition', (string) Str::uuid());
expect($validated['state'])->toBe('recognised')->and(DB::table('pa_obligations')->count())->toBe(1);
$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]);
}
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()]);
$ledger = app(GeneralLedger::class);
$this->actingAs($f['author']);
$input = ['obligation_id' => $validated['obligation_id'], 'journal_on' => today()->toDateString(), 'period_key' => 'EXPLICIT',
'rule_key' => 'EXPLICIT-SUPPLIER', 'reason' => 'Prepare the explicitly configured synthetic journal'];
$proposal = $ledger->engine($f['author'])->command('prepare', $input, (string) Str::uuid());
expect(fn () => $ledger->engine($f['author'])->command('validate', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'decision' => 'approved', 'reason' => 'Forbidden self review'], (string) Str::uuid()))->toThrow(DomainException::class);
$this->actingAs($f['validator']);
$ledger->engine($f['validator'])->command('validate', ['proposal_id' => $proposal['proposal_id'], 'revision' => $proposal['revision'],
'decision' => 'approved', 'reason' => 'Independent review of the explicit synthetic rule'], (string) Str::uuid());
$this->actingAs($f['author']);
$operation = (string) Str::uuid();
$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');
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)
->and((int) DB::table('gl_lines')->sum('credit_minor'))->toBe(6000)
->and(DB::table('external_payments')->count())->toBe(0)->and(DB::table('ps_payments')->count())->toBe(0);
$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);
});
test('common partial payment attribution uses explicit Finance categories without duplicate native payments and preserves reversed history', function () {
$f = paymentFixture(['Material', 'Serviços']);
$payables = app(SupplierPayables::class);
foreach ([$f['author'], $f['validator']] as $actor) {
foreach (['view', 'prepare', 'validate', 'payments_view', 'payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm', 'reversal_prepare', 'reversal_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-common-finance-'.$actor->id, 'action' => $action]);
}
}
$this->actingAs($f['author']);
$proposal = $payables->engine($f['author'])->command('prepare', $f['invoice']->id, 'Synthetic partial payment invoice', (string) Str::uuid());
$this->actingAs($f['validator']);
$recognised = $payables->engine($f['validator'])->command('validate', $proposal['proposal_id'], 'Independent synthetic invoice recognition', (string) Str::uuid());
$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());
};
$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-COMMON-PARTIAL', 'evidence_reference' => 'SIM-COMMON-EVIDENCE', 'reason' => 'Explicit synthetic confirmed payment fact']);
$run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
'evidence_reference' => 'SIM-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',
'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',
'reason' => 'Independent synthetic allocation confirmation']);
$allocationId = (int) DB::table('ps_allocations')->where('payment_id', $payment['payment_id'])->value('id');
$facts = app(CommonPaymentFacts::class)->source($f['validator'], $allocationId);
expect($facts['amount_minor'])->toBe(4000)->and($report()['currencies'][0]['amount_minor'])->toBe('4000')
->and($report()['category_attribution']['coverage']['unallocated'])->toBe(1);
$service = app(ExpenseAllocations::class);
$source = $service->source($f['validator'], $allocationId, 'common_allocation');
$input = ['operation_key' => (string) Str::uuid(), 'version' => 0, 'fingerprint' => $source['fingerprint'],
'reason' => 'Finance explicitly attributes the synthetic partial payment',
'allocations' => [['category' => 'Material', 'amount' => '15.00'], ['category' => 'Serviços', 'amount' => '25.00']]];
$frames = [];
foreach (['ps_payments', 'ps_payment_decisions', 'ps_allocations', 'ps_commands', 'ps_events', 'pa_obligations', 'gl_journals', 'external_payments', 'stock_movements', 'budget_entries'] as $table) {
$frames[$table] = DB::table($table)->orderBy('id')->get()->toJson();
}
$url = '/afectacoes-fornecedores/'.$allocationId.'/imputacao';
$this->withoutVite();
$this->get($url)->assertOk()->assertViewHas('page', fn (array $page) => $page['props']['sourceType'] === 'common_allocation'
&& $page['props']['submitUrl'] === $url && $page['props']['payment']['amount_minor'] === '4000');
$this->postJson($url, $input)->assertRedirect();
$this->postJson($url, $input)->assertRedirect();
$this->get('/supplier-payments')->assertOk()->assertSee($url);
expect($service->current($allocationId))->toBeNull()
->and($service->current($allocationId, 'common_allocation')->data['source_type'])->toBe('common_allocation')
->and(SupplyRecord::query()->where('kind', 'expense_allocation')->count())->toBe(1)
->and($report()['category_attribution']['groups']['data'])->toBe([
['category' => 'Material', 'currency' => 'MZN', 'count' => 1, 'amount_minor' => '1500'],
['category' => 'Serviços', 'currency' => 'MZN', 'count' => 1, 'amount_minor' => '2500'],
]);
foreach ($frames as $table => $frame) {
expect(DB::table($table)->orderBy('id')->get()->toJson())->toBe($frame);
}
$reversal = $run($f['author'], 'reversal-prepare', ['allocation_id' => $allocationId, 'source_revision' => $recognised['source_revision'],
'reason' => 'Synthetic reversal preserves the earlier analytical record']);
$run($f['validator'], 'reversal-confirm', ['proposal_id' => $reversal['proposal_id'], 'reason' => 'Independent synthetic reversal confirmation']);
expect($service->projection($f['validator'], $allocationId, 'common_allocation')['state'])->toBe('indeterminate')
->and($service->current($allocationId, 'common_allocation')->version)->toBe(1)
->and($report()['coverage']['indeterminate'])->toBe(1)->and(DB::table('external_payments')->count())->toBe(0);
});
test('one common payment shared across two invoices is counted once while explicit category amounts are summed exactly', function () {
$f = paymentFixture();
$this->actingAs($f['author']);
$secondInput = [...$f['data'], 'number' => 'FT-CANDIDATE-SECOND', 'subtotal' => '40.00', 'tax' => '0.00', 'total' => '40.00'];
$secondInput['items'][0]['quantity'] = '0.400';
$second = app(InvoiceWorkflow::class)->register($f['author'], $f['order'], $secondInput);
$this->actingAs($f['validator']);
app(InvoiceWorkflow::class)->validate($f['validator'], $second);
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-multiple-invoice-'.$actor->id, 'action' => $action]);
}
}
$adapter = app(SupplierPayables::class);
$obligations = [];
foreach ([$f['invoice'], $second] as $invoice) {
$this->actingAs($f['author']);
$prepared = $adapter->engine($f['author'])->command('prepare', $invoice->id, 'Explicit synthetic multi-invoice source', (string) Str::uuid());
$this->actingAs($f['validator']);
$obligations[] = $adapter->engine($f['validator'])->command('validate', $prepared['proposal_id'], 'Independent synthetic invoice confirmation', (string) Str::uuid());
}
$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());
};
$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',
'evidence_reference' => 'SIM-TWO-INVOICES-EVIDENCE', 'reason' => 'One explicit synthetic supplier payment covering two invoices']);
$run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
'evidence_reference' => 'SIM-TWO-INVOICES-CONFIRMED', 'reason' => 'Independent confirmation of one synthetic payment']);
$plan = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'SIM-TWO-INVOICE-PLAN',
'allocations' => [
['obligation_id' => $obligations[0]['obligation_id'], 'source_revision' => $obligations[0]['source_revision'], 'amount' => '30.00'],
['obligation_id' => $obligations[1]['obligation_id'], 'source_revision' => $obligations[1]['source_revision'], 'amount' => '40.00'],
], 'reason' => 'Explicit synthetic invoice split of the single supplier payment']);
$run($f['validator'], 'allocation-decide', ['proposal_id' => $plan['proposal_id'], 'decision' => 'confirmed',
'reason' => 'Independent confirmation of the explicit invoice split']);
foreach (DB::table('ps_allocations')->where('payment_id', $payment['payment_id'])->orderBy('id')->get() as $row) {
$service = app(ExpenseAllocations::class);
$source = $service->source($f['validator'], (int) $row->id, 'common_allocation');
$service->save($f['validator'], (int) $row->id, ['operation_key' => (string) Str::uuid(), 'version' => 0,
'fingerprint' => $source['fingerprint'], 'reason' => 'Finance explicitly chooses the documentary category for this invoice portion',
'allocations' => [['category' => 'Material', 'amount' => (int) $row->amount_minor === 3000 ? '30.00' : '40.00']]], 'common_allocation');
}
$report = app(ProcurementPaymentInsights::class)->build($f['validator'], Requisition::query()->whereKey($f['r']->id), null, null);
expect($report['coverage']['confirmed_payments'])->toBe(1)
->and($report['currencies'])->toBe([['currency' => 'MZN', 'count' => 1, 'amount_minor' => '7000']])
->and($report['suppliers']['data'][0]['count'])->toBe(1)
->and($report['category_attribution']['groups']['data'])->toBe([['category' => 'Material', 'currency' => 'MZN', 'count' => 1, 'amount_minor' => '7000']])
->and(DB::table('ps_payments')->count())->toBe(1)->and(DB::table('ps_allocations')->count())->toBe(2)
->and(DB::table('external_payments')->count())->toBe(0);
});
@@ -0,0 +1,11 @@
<?php
use App\Services\StandaloneSchema;
use Illuminate\Support\Facades\DB;
test('standalone preflight accepts the actual common payables schema including event keyed outbox', function () {
StandaloneSchema::verify(DB::getSchemaBuilder(), ['supplier-payables' => true]);
expect(DB::getSchemaBuilder()->hasColumn('pa_outbox', 'event_id'))->toBeTrue()
->and(DB::getSchemaBuilder()->hasColumn('pa_outbox', 'id'))->toBeFalse()
->and(DB::table('pa_access')->count())->toBe(0);
});
+257
View File
@@ -0,0 +1,257 @@
<?php
use App\Enums\PurchasingRole;
use App\Models\Department;
use App\Models\Tenant;
use App\Models\User;
use App\Services\AgreementOrderLimits;
use App\Services\CapitalRegister;
use App\Services\ConflictReleases;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
use App\Services\ImportBankSupport;
use App\Services\ImportDossier;
use App\Services\ImportEstimates;
use App\Services\ImportLandedCosts;
use App\Services\ImportLegalRules;
use App\Services\ImportReadiness;
use App\Services\ImportTariffCodes;
use App\Services\OperationalOrders;
use App\Services\OrderPartsPreparation;
use App\Services\PrivateAuditAccess;
use App\Services\RequisitionBudgetDistributions;
use App\Services\RequisitionExpiry;
use App\Services\RequisitionLedgerAccounts;
use App\Services\StandaloneInstallation;
use App\Services\StandaloneRuntime;
use App\Services\SupplierPayables;
use App\Services\UrgentQuotationBasis;
use App\Services\UrgentRequisitionReviews;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tempo\Finance\GeneralLedger\LedgerSchema;
require dirname(__DIR__, 2).'/vendor/autoload.php';
$database = $argv[1] ?? '';
$mode = $argv[2] ?? '';
$root = realpath(getenv('SGC_STANDALONE_QA_ROOT') ?: '');
$parent = realpath(dirname(__DIR__, 2).'/storage/framework/testing');
if (! preg_match('/^compras_standalone_qa_([a-f0-9]{12})(_restored)?$/D', $database, $match)
|| $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)) {
throw new LogicException('Owned standalone QA composition required.');
}
$app = require dirname(__DIR__, 2).'/bootstrap/app.php';
$app->useStoragePath($root.'/storage');
if ($mode === 'reject-foreign') {
require dirname(__DIR__, 2).'/packages/purchasing/bootstrap.php';
}
$expectedRejection = match ($mode) {
'reject-restore' => 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH',
'reject-foreign' => 'COMPRAS_RUNTIME_CLASS_LOCATION',
'reject-pin' => 'COMPRAS_RUNTIME_MANIFEST_HASH',
'reject-dependency' => 'COMPRAS_RUNTIME_FEATURE_DEPENDENCY:import-bank-support:import-dossier',
'reject-old' => 'COMPRAS_RUNTIME_CAPABILITY_UNAVAILABLE',
default => null,
};
try {
$app->make(Kernel::class)->bootstrap();
} catch (LogicException $e) {
if ($expectedRejection === null || $e->getMessage() !== $expectedRejection) {
throw $e;
}
echo json_encode(['rejected' => true, 'reason' => $e->getMessage()], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
if ($expectedRejection !== null) {
throw new LogicException('Invalid standalone composition started without refusal.');
}
$db = DB::connection();
$identity = $db->selectOne("SELECT current_database() AS d,current_setting('cluster_name') AS c");
if ($identity->d !== $database || $identity->c !== 'sgf_modular_regression_'.$match[1]) {
throw new LogicException('Owned standalone QA database identity mismatch.');
}
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'];
if ($mode === 'rebind') {
$arguments['--rebind'] = true;
}
$invoke = static function (array $arguments): array {
if (Artisan::call('compras:runtime:prepare', $arguments) !== 0) {
throw new LogicException('Standalone installation CLI failed.');
}
$result = json_decode(trim(Artisan::output()), true, 32, JSON_THROW_ON_ERROR);
if (! is_array($result) || ($result['feature_activation'] ?? null) !== false || ($result['actor_grants'] ?? null) !== false) {
throw new LogicException('Standalone CLI result changed feature or actor authority.');
}
return $result;
};
$preview = $invoke($arguments);
if ($preview['state'] !== 'preview' || $preview['written'] !== false
|| $db->getSchemaBuilder()->hasTable('compras_runtime_installations') !== ($mode === 'rebind')) {
throw new LogicException('Standalone CLI preview wrote an installation.');
}
try {
app(StandaloneInstallation::class)->prepare($database.'_unexpected', getenv('DB_USERNAME'),
'Synthetic named QA operator', 'Synthetic destination mismatch refusal', true);
throw new LogicException('Wrong standalone CLI destination was accepted.');
} catch (LogicException $e) {
if ($e->getMessage() !== 'COMPRAS_RUNTIME_EXPECTED_DESTINATION') {
throw $e;
}
}
$hostChecks = 0;
if ($mode === 'prepare') {
$ledger = new ReflectionClass(LedgerSchema::class);
foreach (['wrong-contract', 'failed-host-verification'] as $check) {
try {
$ledger->getMethod('installForHost')->invoke(null, $db,
$check === 'wrong-contract' ? 'INCOMPATIBLE' : 'COMMON-LEDGER-HOST-SCHEMA-v1',
fn () => throw new LogicException('SYNTHETIC_HOST_INSTALLATION_REFUSED'));
throw new LogicException('Unverified host installed ledger DDL.');
} catch (LogicException $e) {
$expected = $check === 'wrong-contract' ? 'LEDGER_HOST_SCHEMA_CONTRACT' : 'SYNTHETIC_HOST_INSTALLATION_REFUSED';
if ($e->getMessage() !== $expected || $db->getSchemaBuilder()->hasTable('gl_accounts')) {
throw $e;
}
$hostChecks++;
}
}
}
$applied = $invoke([...$arguments, '--apply' => true]);
$replayed = $invoke([...$arguments, '--apply' => true]);
if ($applied['state'] !== ($mode === 'rebind' ? 'rebound' : 'prepared') || $applied['written'] !== true
|| $replayed['state'] !== 'already_prepared' || $replayed['written'] !== false) {
throw new LogicException('Standalone installation CLI replay changed history.');
}
echo json_encode(['prepared' => true, 'synthetic_only' => true, 'cli_preview_and_replay' => true,
'wrong_destination_refused' => true, 'unverified_ledger_host_checks' => $hostChecks], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
$runtime = app(StandaloneRuntime::class);
$runtime->assertLoadedPackages();
$checks = 0;
foreach ([CapitalRegister::class, OperationalOrders::class, PrivateAuditAccess::class, ConflictReleases::class,
UrgentQuotationBasis::class, UrgentRequisitionReviews::class, RequisitionLedgerAccounts::class,
RequisitionExpiry::class, RequisitionBudgetDistributions::class,
ExpenseAllocations::class, AgreementOrderLimits::class, OrderPartsPreparation::class,
ImportTariffCodes::class, ImportLegalRules::class, ImportDossier::class,
ImportBankSupport::class, ImportReadiness::class, ImportEstimates::class,
ImportLandedCosts::class] as $service) {
if (! app($service)->ready()) {
throw new LogicException('Standalone module unavailable: '.$service);
}
$checks++;
}
if ($app->environment('testing') || config('capital-register.qa_enabled') === true
|| $runtime->feature('not-configured', $db) !== false || $db->table('compras_runtime_installations')->count() !== (isset($match[2]) ? 2 : 1)) {
throw new LogicException('Standalone composition inherited QA activation or an unselected capability.');
}
if (! SupplierPayables::enabled() || ! $runtime->feature('general-ledger', $db)
|| ! $runtime->feature('supplier-settlements', $db) || ! app(GeneralLedger::class)->cycleEnabled()) {
throw new LogicException('Standalone common financial modules unavailable.');
}
$checks += 4;
$snapshot = static function () use ($db): string {
$frames = [];
foreach (['tenants', 'users', 'departments', 'supply_records', 'audit_logs', 'gl_accounts', 'gl_journals',
'budget_entries', 'purchase_orders', 'invoices', 'stock_movements', 'budget_requisition_cycles', 'approval_steps', 'pa_access'] as $table) {
$frames[$table] = $db->table($table)->orderBy('id')->get()->toArray();
}
return hash('sha256', json_encode($frames, JSON_THROW_ON_ERROR));
};
if (isset($match[2])) {
$saved = file_get_contents($root.'/standalone-preservation.sha256');
if (! is_string($saved) || ! hash_equals($saved, $snapshot())) {
throw new LogicException('Standalone restore changed original data or relations.');
}
}
$tenant = Tenant::query()->create(['name' => 'Synthetic standalone candidate QA']);
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Synthetic purchasing department']);
$actor = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id,
'purchasing_role' => PurchasingRole::Procurement]);
auth()->guard()->setUser($actor);
if ($db->table('pa_access')->where('tenant_id', $tenant->id)->exists() || app(SupplierPayables::class)->can($actor, 'view')) {
throw new LogicException('Standalone composition automatically granted financial authority.');
}
$finance = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Finance]);
foreach (['view', 'payments_view', 'general_ledger.view'] as $action) {
$db->table('pa_access')->insert(['tenant_id' => $tenant->id, 'company_id' => 0, 'unit_id' => 0,
'user_id' => $finance->id, 'person' => 'synthetic-standalone-finance-'.$finance->id, 'action' => $action]);
}
auth()->guard()->setUser($finance);
app(GeneralLedger::class)->listing($finance);
app(GeneralLedger::class)->workspace($finance);
app(SupplierPayables::class)->engine($finance)->settlements()->listing();
if (app(GeneralLedger::class)->can($finance, 'prepare')) {
throw new LogicException('Read-only common ledger access acquired a writer capability.');
}
auth()->guard()->setUser($actor);
$account = $db->table('gl_accounts')->insertGetId(['tenant_id' => $tenant->id, 'company_id' => 0, 'unit_id' => 0,
'code' => 'STANDALONE-ONLY', 'label' => 'Synthetic own chart movement account', 'currency' => 'MZN', 'is_movement' => true]);
$options = app(RequisitionLedgerAccounts::class)->options($actor, 'STANDALONE-ONLY');
if (count($options['data']) !== 1 || $options['data'][0]['id'] !== $account) {
throw new LogicException('Standalone chart lookup lost own company scope.');
}
$before = [];
foreach (['budget_entries', 'stock_movements', 'purchase_orders', 'invoices', 'gl_accounts', 'gl_journals'] as $table) {
$before[$table] = $db->table($table)->orderBy('id')->get()->toJson();
}
$input = ['operation_key' => (string) Str::uuid(), 'record_key' => null, 'version' => 0, 'type' => 'project',
'code' => 'STANDALONE-QA', 'name' => 'Synthetic standalone project', 'department_id' => $department->id,
'equipment_id' => null, 'reference' => 'Synthetic candidate acceptance source', 'state' => 'active',
'reason' => 'Authorised isolated candidate regression verification'];
$register = app(CapitalRegister::class);
$first = $register->save($actor, $input);
$retry = $register->save($actor, $input);
$archived = $register->save($actor, [...$input, 'operation_key' => (string) Str::uuid(),
'record_key' => $first->record_key, 'version' => 1, 'state' => 'archived']);
if ($first->id !== $retry->id || $first->fresh()->state !== 'active' || $archived->version !== 2) {
throw new LogicException('Standalone project replay or history changed.');
}
foreach ($before as $table => $frame) {
if ($db->table($table)->orderBy('id')->get()->toJson() !== $frame) {
throw new LogicException('Documentary project changed a financial or physical writer.');
}
}
try {
app(PrivateAuditAccess::class)->current($actor);
throw new LogicException('Standalone composition granted private audit authority.');
} catch (HttpExceptionInterface $e) {
if ($e->getStatusCode() !== 403) {
throw $e;
}
}
$immutableChecks = 0;
foreach (["UPDATE compras_runtime_installations SET reason='changed'", 'DELETE FROM compras_runtime_installations',
'TRUNCATE compras_runtime_installations'] as $statement) {
try {
$db->transaction(fn () => $db->unprepared($statement));
throw new LogicException('Installation history mutation was accepted.');
} catch (QueryException $e) {
if (($e->errorInfo[0] ?? null) !== 'P0001') {
throw $e;
}
$immutableChecks++;
}
}
if (! isset($match[2])) {
if (file_put_contents($root.'/standalone-preservation.sha256', $snapshot()) !== 64) {
throw new LogicException('Unable to record private preservation evidence.');
}
}
echo json_encode(['verified' => true, 'available_modules' => $checks, 'outside_testing_environment' => true,
'own_database_and_role_names' => true, 'runtime_classes_pinned' => true, 'project_replay_and_history' => true,
'private_audit_authority_not_inherited' => true, 'financial_stock_frames_preserved' => count($before),
'immutable_installation_checks' => $immutableChecks, 'restored_originals_preserved' => isset($match[2]),
'common_ledger_read_with_explicit_synthetic_rights' => true, 'real_operations' => false], JSON_THROW_ON_ERROR).PHP_EOL;
+138
View File
@@ -0,0 +1,138 @@
<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use Illuminate\Database\Connection;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Schema\Builder as SchemaBuilder;
beforeEach(function () {
$this->artifactParent = realpath(__DIR__.'/../../storage/framework/testing');
expect($this->artifactParent)->not->toBeFalse();
$this->artifactRoot = $this->artifactParent.'/standalone-artifact-'.bin2hex(random_bytes(6));
mkdir($this->artifactRoot, 0700);
$this->manifest = ['contract' => StandaloneArtifact::CONTRACT, 'product' => 'compras', 'version' => 1,
'capabilities' => ['capital-register'], 'files' => []];
foreach (StandaloneArtifact::PACKAGES as $package) {
mkdir($this->artifactRoot.'/'.$package, 0700);
$bytes = '<?php throw new RuntimeException("VERIFIER_MUST_NOT_EXECUTE_PACKAGE");';
file_put_contents($this->artifactRoot.'/'.$package.'/bootstrap.php', $bytes);
$this->manifest['files'][] = ['file' => $package.'/bootstrap.php', 'sha256' => hash('sha256', $bytes)];
}
$this->writeArtifactManifest = function (): string {
$bytes = json_encode($this->manifest, JSON_THROW_ON_ERROR);
file_put_contents($this->artifactRoot.'/manifest.json', $bytes);
return hash('sha256', $bytes);
};
$this->artifactPin = ($this->writeArtifactManifest)();
});
afterEach(function () {
$root = realpath($this->artifactRoot);
if ($root === false || dirname($root) !== $this->artifactParent || ! preg_match('/^standalone-artifact-[a-f0-9]{12}$/D', basename($root))) {
throw new LogicException('Owned artifact fixture cleanup refused.');
}
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $file) {
$file->isDir() && ! $file->isLink() ? rmdir($file->getPathname()) : unlink($file->getPathname());
}
rmdir($root);
});
test('standalone artifact verifies the complete portable package without executing it', function () {
$result = (new StandaloneArtifact)->verify($this->artifactRoot, $this->artifactPin);
expect($result['manifest']['product'])->toBe('compras')
->and($result['manifest']['capabilities'])->toBe(['capital-register']);
foreach (StandaloneArtifact::PACKAGES as $package) {
expect(realpath($result['paths'][$package]))->toBe(realpath($this->artifactRoot.'/'.$package));
}
});
test('standalone artifact rejects changed source bytes and unlisted files before execution', function (string $mutation) {
if ($mutation === 'changed') {
file_put_contents($this->artifactRoot.'/payables/bootstrap.php', '<?php echo "ALTERED";');
} else {
file_put_contents($this->artifactRoot.'/payables/extra.php', '<?php echo "UNLISTED";');
}
expect(fn () => (new StandaloneArtifact)->verify($this->artifactRoot, $this->artifactPin))->toThrow(LogicException::class);
})->with(['changed', 'unlisted']);
test('standalone artifact rejects incompatible metadata duplicate and escaping identities', function (string $mutation) {
match ($mutation) {
'product' => $this->manifest['product'] = 'sgf',
'version' => $this->manifest['version'] = 2,
'contract' => $this->manifest['contract'] = 'QA-UNPUBLISHED',
'duplicate-file' => $this->manifest['files'][] = $this->manifest['files'][0],
'escaping-file' => $this->manifest['files'][0]['file'] = 'budget-control/../../outside.php',
'absolute-file' => $this->manifest['files'][0]['file'] = 'C:/outside.php',
'malformed-file' => $this->manifest['files'][0] = 'budget-control/bootstrap.php',
'duplicate-capability' => $this->manifest['capabilities'][] = 'capital-register',
'invalid-capability' => $this->manifest['capabilities'][] = ['capital-register'],
'missing-package' => $this->manifest['files'][0]['file'] = 'budget-control/other.php',
};
if ($mutation === 'missing-package') {
rename($this->artifactRoot.'/budget-control/bootstrap.php', $this->artifactRoot.'/budget-control/other.php');
}
$pin = ($this->writeArtifactManifest)();
expect(fn () => (new StandaloneArtifact)->verify($this->artifactRoot, $pin))->toThrow(LogicException::class);
})->with(['product', 'version', 'contract', 'duplicate-file', 'escaping-file', 'absolute-file', 'malformed-file', 'duplicate-capability', 'invalid-capability', 'missing-package']);
test('standalone artifact requires the caller pin even for an otherwise valid package', function () {
expect(fn () => (new StandaloneArtifact)->verify($this->artifactRoot, str_repeat('0', 64)))->toThrow(LogicException::class, 'COMPRAS_RUNTIME_MANIFEST_HASH');
});
test('standalone composition rejects capabilities absent from its pinned package', function (mixed $features) {
$runtime = new StandaloneRuntime(['enabled' => true, 'root' => $this->artifactRoot,
'manifest_sha256' => $this->artifactPin, 'installation_id' => '2998ee93-322b-4bd9-9c7b-c16725056a99',
'features' => $features], new StandaloneArtifact);
expect(fn () => $runtime->artifact())->toThrow(LogicException::class);
})->with([
'unsupported enabled feature' => [['private-audit' => true]],
'truthy string' => [['capital-register' => 'true']],
'malformed feature collection' => ['capital-register'],
]);
test('standalone composition accepts explicitly disabled unavailable capabilities', function () {
$runtime = new StandaloneRuntime(['enabled' => true, 'root' => $this->artifactRoot,
'manifest_sha256' => $this->artifactPin, 'installation_id' => '2998ee93-322b-4bd9-9c7b-c16725056a99',
'features' => ['capital-register' => true, 'private-audit' => false]], new StandaloneArtifact);
expect($runtime->artifact()['manifest']['capabilities'])->toBe(['capital-register']);
});
test('standalone feature checks the installation receipt before permitting availability', function (string $mutation) {
$settings = ['enabled' => true, 'root' => $this->artifactRoot, 'manifest_sha256' => $this->artifactPin,
'installation_id' => '2998ee93-322b-4bd9-9c7b-c16725056a99', 'features' => ['capital-register' => true]];
$db = Mockery::mock(Connection::class);
$db->shouldReceive('getDriverName')->once()->andReturn('pgsql');
$db->shouldReceive('selectOne')->once()->andReturn((object) ['database_name' => 'purchasing_company',
'role_name' => 'purchasing_app', 'database_oid' => '45000', 'server_address' => '192.0.2.10',
'server_port' => 5432, 'elevated' => 0]);
$schema = Mockery::mock(SchemaBuilder::class);
$db->shouldReceive('getSchemaBuilder')->once()->andReturn($schema);
$schema->shouldReceive('hasTable')->with('compras_runtime_installations')->once()->andReturn($mutation !== 'schema');
if ($mutation !== 'schema') {
$query = Mockery::mock(Builder::class);
$db->shouldReceive('table')->with('compras_runtime_installations')->once()->andReturn($query);
$query->shouldReceive('where')->with('id', $settings['installation_id'])->once()->andReturnSelf();
$receipt = (object) ['product' => 'compras', 'contract' => StandaloneArtifact::CONTRACT,
'manifest_sha256' => $this->artifactPin, 'database_binding_sha256' => hash('sha256', json_encode([
'product' => 'compras', 'database' => 'purchasing_company', 'oid' => '45000', 'role' => 'purchasing_app',
'address' => '192.0.2.10', 'port' => 5432,
], JSON_THROW_ON_ERROR))];
match ($mutation) {
'product' => $receipt->product = 'sgf',
'contract' => $receipt->contract = 'OLD',
'manifest' => $receipt->manifest_sha256 = str_repeat('0', 64),
'database' => $receipt->database_binding_sha256 = str_repeat('0', 64),
default => null,
};
$query->shouldReceive('first')->once()->andReturn($mutation === 'missing' ? null : $receipt);
}
$runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
if ($mutation === 'valid') {
expect($runtime->feature('capital-register', $db))->toBeTrue();
} else {
expect(fn () => $runtime->feature('capital-register', $db))->toThrow(LogicException::class,
$mutation === 'schema' ? 'COMPRAS_RUNTIME_INSTALLATION_MISSING' : 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH');
}
})->with(['valid', 'schema', 'missing', 'product', 'contract', 'manifest', 'database']);
+61
View File
@@ -0,0 +1,61 @@
<?php
use App\Services\StandaloneArtifact;
use App\Services\StandaloneRuntime;
use Illuminate\Database\Connection;
test('disabled standalone composition does not inspect the database or package', function () {
$db = Mockery::mock(Connection::class);
$runtime = new StandaloneRuntime([], new StandaloneArtifact);
expect($runtime->enabled())->toBeFalse()
->and($runtime->requested('capital-register'))->toBeFalse()
->and($runtime->feature('capital-register', $db))->toBeFalse();
});
test('standalone feature opt in requires a boolean rather than a truthy setting', function (mixed $value) {
$db = Mockery::mock(Connection::class);
$runtime = new StandaloneRuntime(['enabled' => $value, 'features' => ['capital-register' => true]], new StandaloneArtifact);
expect($runtime->feature('capital-register', $db))->toBeFalse();
})->with([false, 1, 'true', 'false', null]);
test('standalone requested features remain explicit before readiness validation', function () {
$runtime = new StandaloneRuntime(['enabled' => true, 'features' => ['requisition-accounts' => true]], new StandaloneArtifact);
expect($runtime->requested('requisition-accounts'))->toBeTrue()
->and($runtime->requested('private-audit'))->toBeFalse();
expect(fn () => $runtime->artifact())->toThrow(LogicException::class, 'COMPRAS_RUNTIME_CONFIGURATION');
});
test('standalone database binding accepts an ordinary own installation without QA names', function () {
$db = Mockery::mock(Connection::class);
$db->shouldReceive('getDriverName')->once()->andReturn('pgsql');
$db->shouldReceive('selectOne')->once()->andReturn((object) [
'database_name' => 'purchasing_company', 'role_name' => 'purchasing_app', 'database_oid' => '45000',
'server_address' => '192.0.2.10', 'server_port' => 5432, 'elevated' => 0,
]);
expect(StandaloneRuntime::databaseBinding($db))->toBe(hash('sha256', json_encode([
'product' => 'compras', 'database' => 'purchasing_company', 'oid' => '45000', 'role' => 'purchasing_app',
'address' => '192.0.2.10', 'port' => 5432,
], JSON_THROW_ON_ERROR)));
});
test('standalone binding rejects elevated or unavailable database identities', function (string $failure) {
$db = Mockery::mock(Connection::class);
$db->shouldReceive('getDriverName')->once()->andReturn('pgsql');
$identity = (object) ['database_name' => 'own', 'role_name' => 'app', 'database_oid' => '1',
'server_address' => '127.0.0.1', 'server_port' => 5432, 'elevated' => 0];
if ($failure === 'elevated') {
$identity->elevated = 1;
} elseif ($failure === 'address') {
$identity->server_address = null;
} elseif ($failure === 'port') {
$identity->server_port = null;
}
$db->shouldReceive('selectOne')->once()->andReturn($failure === 'missing' ? null : $identity);
expect(fn () => StandaloneRuntime::databaseBinding($db))->toThrow(LogicException::class, 'COMPRAS_RUNTIME_DATABASE_IDENTITY');
})->with(['elevated', 'address', 'port', 'missing']);
test('standalone binding rejects other drivers without querying them', function () {
$db = Mockery::mock(Connection::class);
$db->shouldReceive('getDriverName')->once()->andReturn('sqlite');
expect(fn () => StandaloneRuntime::databaseBinding($db))->toThrow(LogicException::class, 'COMPRAS_RUNTIME_DATABASE_DRIVER');
});
+47
View File
@@ -0,0 +1,47 @@
<?php
use App\Services\StandaloneSchema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\SQLiteConnection;
beforeEach(function () {
$this->standaloneDb = new SQLiteConnection(new PDO('sqlite::memory:'), ':memory:', '', ['driver' => 'sqlite']);
$this->standaloneSchema = $this->standaloneDb->getSchemaBuilder();
foreach (['supply_records' => ['id', 'tenant_id', 'kind', 'record_key', 'version', 'data', 'snapshot', 'operation_key'],
'requisitions' => ['id', 'tenant_id', 'status'], 'users' => ['id', 'tenant_id']] as $table => $columns) {
$this->standaloneSchema->create($table, function (Blueprint $definition) use ($columns) {
foreach ($columns as $column) {
$definition->text($column)->nullable();
}
});
}
});
test('standalone preflight does not create optional structures when no feature is selected', function () {
StandaloneSchema::verify($this->standaloneSchema, ['private-audit' => false]);
expect($this->standaloneSchema->hasTable('private_audit_exports'))->toBeFalse()
->and($this->standaloneDb->table('supply_records')->count())->toBe(0);
});
test('standalone preflight rejects an incomplete own chart instead of activating account attribution', function () {
$this->standaloneSchema->create('gl_accounts', function (Blueprint $table) {
$table->id();
$table->string('code');
$table->string('label');
});
expect(fn () => StandaloneSchema::verify($this->standaloneSchema, ['requisition-accounts' => true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_SCHEMA_INCOMPLETE:gl_accounts');
expect($this->standaloneSchema->hasColumn('gl_accounts', 'tenant_id'))->toBeFalse();
});
test('standalone preflight preserves documented import module dependencies', function (string $feature, string $dependency) {
expect(fn () => StandaloneSchema::verify($this->standaloneSchema, [$feature => true, $dependency => false]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_FEATURE_DEPENDENCY:'.$feature.':'.$dependency);
})->with([['import-legal', 'import-tariffs'], ['import-bank-support', 'import-dossier'], ['import-readiness', 'import-dossier']]);
test('standalone preflight rejects an incomplete cycle schema without repairing it', function () {
$this->standaloneSchema->create('budget_requisition_cycles', fn (Blueprint $table) => $table->id());
expect(fn () => StandaloneSchema::verify($this->standaloneSchema, ['requisition-expiry' => true]))
->toThrow(LogicException::class, 'COMPRAS_RUNTIME_SCHEMA_INCOMPLETE:requisitions');
expect($this->standaloneSchema->hasColumn('requisitions', 'approval_cycle'))->toBeFalse();
});
+15 -1
View File
@@ -4,7 +4,7 @@ import { expect, test } from 'vitest';
import ExpenseAllocation from '../../resources/js/pages/payments/expense-allocation';
import { ProcurementCategoryInsights } from '../../resources/js/components/procurement-category-insights';
function render(canWrite: boolean) {
function render(canWrite: boolean, common = false) {
return renderToStaticMarkup(
<App
initialComponent={ExpenseAllocation}
@@ -15,6 +15,12 @@ function render(canWrite: boolean) {
clearHistory: false,
encryptHistory: true,
props: {
...(common
? {
sourceType: 'common_allocation',
submitUrl: '/afectacoes-fornecedores/1/imputacao',
}
: {}),
errors: {},
canWrite,
actorId: 1,
@@ -63,6 +69,14 @@ test('Finance starts with blank amounts and deliberately chooses whether to reus
expect(html).toContain('Guardar imputação');
});
test('common allocation keeps its own source and returns to the common financial workspace', () => {
const html = render(true, true);
expect(html).toContain('Afectação #1');
expect(html).toContain('href="/supplier-payments"');
expect(html).not.toContain('href="/pagamentos?payment_id=1"');
expect(html).toContain('Guardar imputação');
});
test('category summary preserves unassigned expenses and separates currencies without allocating them automatically', () => {
const html = renderToStaticMarkup(
<ProcurementCategoryInsights