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
@@ -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,