@@ -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;
|
||||
Reference in New Issue
Block a user