commit melhorias compras5
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-22 19:39:09 +02:00
parent 36dcfdf00c
commit db1615fac1
79 changed files with 4082 additions and 120 deletions
@@ -0,0 +1,33 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
const installation = JSON.parse(
await fs.readFile('docs/proofs/rq01-distribution-pilot-installation.json', 'utf8'),
);
assert.equal(installation.status, 'installed_and_capability_enabled_no_business_operations');
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
await new Function('fs', 'assert', 'return (async()=>{' + common + `
const results=[];
for(const role of ['requester','admin','procurement','finance']) {
const viewer=client(); await viewer.enter(role);
assert.equal((await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
const detail=await viewer.request('/requisicoes/2');
assert.equal(detail.status,200);
const owner=detail.page.props.requisition.requester_id===detail.page.props.auth.user.id;
const eligible=owner && detail.page.props.requisition.status==='draft' && detail.page.props.canEdit;
assert.equal(detail.page.props.canPrepareDistributions,eligible);
assert.equal('budget_distribution_preparation' in detail.page.props.requisition,false);
results.push({role,path:'/requisicoes/2',status:200,request_status:detail.page.props.requisition.status,can_prepare:eligible,restricted_preparation_hidden:true});
const form=await viewer.request('/requisicoes/2/distribuicoes');
assert.equal(form.status,eligible?200:403);
if(eligible) {
assert.equal(form.page.component,'requisitions/distributions');
assert.equal(form.page.encryptHistory,true);
assert.equal(form.page.props.preparation,null);
}
results.push({role,path:'/requisicoes/2/distribuicoes',status:form.status});
}
await fs.writeFile('docs/proofs/rq01-distribution-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
`+'})()')(fs,assert);
@@ -24,6 +24,38 @@ if (DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $
throw new LogicException('Review verification database mismatch.');
}
$request = DB::table('requisitions')->where('id', $proof['synthetic_fixture']['draft'])->first();
if (in_array('--saved-searches', $argv, true)) {
$owner = DB::table('users')->where('email', $proof['synthetic_fixture']['users']['owner'])->sole();
$saved = DB::table('procurement_saved_searches')->sole();
if ($saved->tenant_id !== $owner->tenant_id || $saved->user_id !== $owner->id || (int) $saved->version !== 4
|| $saved->name !== 'Meus pedidos revistos QA' || $saved->term !== 'REQ' || $saved->archived_at !== null
|| $request->status !== 'draft' || (int) $request->process_version !== 2
|| DB::table('audit_logs')->where('requisition_id', $request->id)->where('action', 'requisition.updated')->exists()
|| DB::table('budget_entries')->where('requisition_id', $request->id)->exists()
|| DB::table('budget_distributions')->where('requisition_id', $request->id)->exists()
|| DB::table('invoices')->exists()) {
throw new RuntimeException('Saved criteria must preserve owner, four native versions and absence of draft or financial operations.');
}
echo json_encode(['native_private_search_cycle' => true, 'one_preference' => true, 'version' => 4, 'criterion_preserved' => true,
'active_after_restore' => true, 'no_draft_update_reservation_or_invoice' => true], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
if (in_array('--category', $argv, true)) {
$line = DB::table('requisition_items')->where('requisition_id', $request->id)->sole();
$context = json_decode($line->category_context, true, 32, JSON_THROW_ON_ERROR);
if ($request->status !== 'draft' || (int) $request->process_version !== 3
|| $context !== ['version' => 1, 'category' => 'office_equipment', 'reason' => 'Artigo sintético de escritório ainda sem entrada no catálogo.']
|| $line->category !== 'Material' || $line->purchase_type !== 'consumable' || (int) $request->total_minor !== 10000
|| DB::table('budget_entries')->where('requisition_id', $request->id)->exists()
|| DB::table('budget_distributions')->where('requisition_id', $request->id)->exists()
|| DB::table('audit_logs')->where('requisition_id', $request->id)->where('action', 'requisition.updated')->count() !== 1
|| DB::table('invoices')->exists()) {
throw new RuntimeException('Native classification save must preserve the original category, type, totals and absence of business effects.');
}
echo json_encode(['native_category_saved' => true, 'explicit_reason_preserved' => true, 'original_descriptors_and_totals_preserved' => true,
'draft_version' => 3, 'one_update_audit' => true, 'no_reservation_or_invoice' => true], JSON_THROW_ON_ERROR).PHP_EOL;
exit;
}
$plan = json_decode($request->budget_distribution_preparation, true, 32, JSON_THROW_ON_ERROR);
if ((int) $request->process_version !== 3 || $request->status !== 'draft' || count($plan['allocations']) !== 2
|| array_column($plan['allocations'], 'subtotal_minor') !== [5000, 5000] || array_column($plan['allocations'], 'total_minor') !== [5000, 5000]
+20 -3
View File
@@ -15,7 +15,14 @@ if (in_array('--refresh-running-preview', $argv, true)) {
|| ! is_file($private.'/settings.json')) {
throw new LogicException('Private review identity mismatch.');
}
$candidate = storage_path('framework/testing/sgc-distribution-integrated-qa-20261122');
$candidateRelative = 'storage/framework/testing/sgc-distribution-integrated-qa-20261122';
if (in_array('--candidate', $argv, true)) {
$candidateRelative = $argv[array_search('--candidate', $argv, true) + 1] ?? '';
}
if (! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative)) {
throw new LogicException('Only an explicit private candidate can refresh this review.');
}
$candidate = base_path($candidateRelative);
$expected = $argv[array_search('--refresh-running-preview', $argv, true) + 1] ?? '';
if (! preg_match('/^[a-f0-9]{64}$/D', $expected) || hash_file('sha256', $candidate.'/manifest.json') !== $expected) {
throw new LogicException('Explicit validated private manifest hash required.');
@@ -58,8 +65,18 @@ $private = 'C:/laragon/data/sgf-tempo/qa/distribution-visual-'.$database;
if (! mkdir($private.'/public', 0700, true) && ! is_dir($private.'/public')) {
throw new RuntimeException('Private review directory creation failed.');
}
$candidate = storage_path('framework/testing/sgc-distribution-integrated-qa-20261122');
if (hash_file('sha256', $candidate.'/manifest.json') !== '1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e') {
$candidateRelative = 'storage/framework/testing/sgc-distribution-integrated-qa-20261122';
$candidateHash = '1edb9ab0aa62fcf4e9c9075ce6e405de5435dc8ea4799d1949535a96c718df4e';
if (in_array('--candidate', $argv, true)) {
$position = array_search('--candidate', $argv, true);
$candidateRelative = $argv[$position + 1] ?? '';
$candidateHash = $argv[$position + 2] ?? '';
}
if (! preg_match('~^storage/framework/testing/[A-Za-z0-9_-]+$~D', $candidateRelative) || ! preg_match('/^[a-f0-9]{64}$/D', $candidateHash)) {
throw new LogicException('Explicit private candidate path and hash required.');
}
$candidate = base_path($candidateRelative);
if (hash_file('sha256', $candidate.'/manifest.json') !== $candidateHash) {
throw new RuntimeException('The private candidate differs from the validated build.');
}
(new Filesystem)->copyDirectory($candidate, $private.'/public/build');
@@ -0,0 +1,274 @@
<?php
use App\Services\BudgetDistributionArtifact;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process;
// Default: read the pilot and rehearse on a private restore. Application needs a separate exact approval.
require dirname(__DIR__).'/vendor/autoload.php';
$root = dirname(__DIR__);
$apply = in_array('--apply-authorized', $argv, true);
if (! $apply && ! in_array('--restore-and-rehearse', $argv, true)) {
throw new LogicException('Explicit preparation or separately authorised installation required.');
}
$proposalPath = $root.'/docs/proofs/rq01-distribution-pilot-proposal.json';
$installationProof = $root.'/docs/proofs/rq01-distribution-pilot-installation.json';
if ($apply) {
$authorizationPath = $root.'/docs/proofs/rq01-distribution-pilot-authorization.json';
$authorization = is_file($authorizationPath) ? json_decode(file_get_contents($authorizationPath), true, 32, JSON_THROW_ON_ERROR) : null;
if (! is_array($authorization) || ($authorization['status'] ?? null) !== 'approved'
|| ($authorization['environment'] ?? null) !== 'http://127.0.0.1:8005'
|| ($authorization['proposal_sha256'] ?? null) !== hash_file('sha256', $proposalPath) || is_file($installationProof)) {
throw new LogicException('Exact installation authorisation required; recorded installations are never repeated.');
}
$proposal = json_decode(file_get_contents($proposalPath), true, 64, JSON_THROW_ON_ERROR);
foreach ($proposal['reviewed_files'] as $file => $hash) {
if (hash_file('sha256', $root.'/'.$file) !== $hash) {
throw new LogicException('Reviewed installation file changed:'.$file);
}
}
}
$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$settingsBytes = file_get_contents($settingsPath);
$settings = json_decode($settingsBytes, true, 32, JSON_THROW_ON_ERROR);
if (($settings['APP_ENV'] ?? '') !== 'payable-testing' || ($settings['DB_HOST'] ?? '') !== '127.0.0.1'
|| realpath($settings['HOST_ROOT'] ?? '') !== realpath($root)
|| ! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $settings['DB_DATABASE'] ?? '', $match)
|| $settings['DB_USERNAME'] !== 'payable_qa_'.$match[1]
|| filter_var($settings['SGC_BUDGET_DISTRIBUTIONS_ENABLED'] ?? false, FILTER_VALIDATE_BOOLEAN)) {
throw new LogicException('Original named pilot with distributions disabled required.');
}
$artifactPath = $root.'/docs/proofs/rq01-distribution-artifact.json';
$artifact = json_decode(file_get_contents($artifactPath), true, 32, JSON_THROW_ON_ERROR);
BudgetDistributionArtifact::verify($root.'/'.$artifact['path'], $artifactPath, hash_file('sha256', $artifactPath));
$app = require $root.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$owner = DB::connection('pgsql')->getConfig();
unset($owner['name']);
if ($owner['host'] !== '127.0.0.1') {
throw new LogicException('Local administrative connection required.');
}
$pilotConfig = [...$owner, 'url' => null, 'host' => $settings['DB_HOST'], 'database' => $settings['DB_DATABASE'],
'username' => $settings['DB_USERNAME'], 'password' => $settings['DB_PASSWORD']];
config(['database.connections.distribution_pilot_read' => $pilotConfig,
'database.connections.distribution_prepare_owner' => [...$owner, 'database' => 'postgres', 'url' => null]]);
$pilot = DB::connection('distribution_pilot_read');
$admin = DB::connection('distribution_prepare_owner');
$restoreName = 'compras_distribution_restore_'.bin2hex(random_bytes(6));
$directory = 'C:/laragon/data/sgf-tempo/backups/compras-distribution-preparation-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(3));
if (! mkdir($directory, 0700, true)) {
throw new RuntimeException('Could not create private recovery directory.');
}
$dump = $directory.'/before.dump';
$originalManifest = hash_file('sha256', $root.'/public/build/manifest.json');
if ($apply && $originalManifest !== $proposal['previous_manifest_sha256']) {
throw new LogicException('Pilot assets changed after the reviewed proposal.');
}
$previous = DB::getDefaultConnection();
$created = false;
$fingerprint = static function ($connection, array $columns): array {
$out = [];
foreach ($columns as $table => $names) {
$selected = implode(',', array_map(fn ($name) => '"'.str_replace('"', '""', $name).'"', $names));
$rows = $connection->select('select row_to_json(t)::text as row from (select '.$selected.' from "'.$table.'") t order by row_to_json(t)::text');
$out[$table] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
}
return $out;
};
$pg = static function (string $binary, array $arguments) use ($pilotConfig): void {
$process = new Process(['C:/Program Files/PostgreSQL/17/bin/'.$binary.'.exe', ...$arguments], null,
['PGHOST' => $pilotConfig['host'], 'PGPORT' => (string) $pilotConfig['port'],
'PGUSER' => $pilotConfig['username'], 'PGPASSWORD' => $pilotConfig['password']], timeout: 120);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('Private backup or restore failed; pilot untouched.');
}
};
try {
$pilot->beginTransaction();
$pilot->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
$identity = $pilot->selectOne('select current_database() as db, current_user as role');
if ($identity->db !== $settings['DB_DATABASE'] || $identity->role !== $settings['DB_USERNAME']) {
throw new LogicException('Effective pilot identity mismatch.');
}
$schema = $pilot->getSchemaBuilder();
if ($schema->hasTable('budget_distributions') || $schema->hasColumn('requisitions', 'budget_distribution_preparation')) {
throw new LogicException('Optional schema already exists; inspect without reapplying.');
}
$tables = array_column($pilot->select("select tablename from pg_tables where schemaname='public' order by tablename"), 'tablename');
$columns = $keys = [];
foreach ($tables as $table) {
$columns[$table] = $schema->getColumnListing($table);
$keys[$table] = $schema->getForeignKeys($table);
}
$baseline = $fingerprint($pilot, $columns);
$migrationCount = $pilot->table('migrations')->count();
$snapshot = $pilot->selectOne('select pg_export_snapshot() as snapshot')->snapshot;
$pg('pg_dump', ['--format=custom', '--snapshot='.$snapshot, '--file='.$dump, '--dbname='.$pilotConfig['database']]);
$pilot->commit();
$admin->statement('CREATE DATABASE "'.$restoreName.'" OWNER "'.$settings['DB_USERNAME'].'"');
$created = true;
$pg('pg_restore', ['--no-owner', '--no-privileges', '--exit-on-error', '--dbname='.$restoreName, $dump]);
config(['database.connections.distribution_rehearsal' => [...$pilotConfig, 'database' => $restoreName]]);
$restored = DB::connection('distribution_rehearsal');
if ($fingerprint($restored, $columns) !== $baseline) {
throw new LogicException('Same-role restore differs from original snapshot.');
}
DB::setDefaultConnection('distribution_rehearsal');
config(['budget-distributions.schema_installation' => ['database' => $restoreName, 'username' => $settings['DB_USERNAME']]]);
$migration = 'database/deployment-migrations/2026_11_22_000004_create_budget_distributions.php';
if (Artisan::call('migrate', ['--database' => 'distribution_rehearsal', '--path' => [$migration], '--force' => true]) !== 0) {
throw new RuntimeException('Exact restored migration failed.');
}
$after = $fingerprint($restored, $columns);
unset($after['migrations'], $baseline['migrations']);
if ($after !== $baseline || $restored->table('migrations')->count() !== $migrationCount + 1
|| $restored->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
throw new LogicException('Previous records changed or new values are not empty.');
}
foreach ($keys as $table => $expected) {
if ($restored->getSchemaBuilder()->getForeignKeys($table) !== $expected) {
throw new LogicException('Previous foreign keys changed.');
}
}
foreach (['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions'] as $table) {
if ($restored->table($table)->exists()) {
throw new LogicException('Optional schema must remain empty.');
}
}
if (hash_file('sha256', $settingsPath) !== hash('sha256', $settingsBytes)
|| hash_file('sha256', $root.'/public/build/manifest.json') !== $originalManifest) {
throw new LogicException('Deployment changed during preparation; reassess the destination.');
}
$proof = ['date' => gmdate('Y-m-d'), 'status' => 'restored_pilot_rehearsal_passed_not_installed', 'environment' => 'http://127.0.0.1:8005',
'pilot_read_only' => true, 'backup' => $dump, 'backup_sha256' => hash_file('sha256', $dump),
'same_restore_role' => true, 'restored_tables_checked' => count($tables), 'previous_business_tables_preserved' => count($tables) - 1,
'previous_foreign_keys_preserved' => true, 'new_values_empty' => true, 'optional_tables' => 4,
'deployment_settings_unchanged' => true, 'pilot_manifest_sha256' => $originalManifest,
'migration' => $migration, 'migration_sha256' => hash_file('sha256', $root.'/'.$migration),
'schema_definition_sha256' => hash_file('sha256', $root.'/app/Services/BudgetDistributionSchema.php'),
'artifact_manifest_sha256' => hash_file('sha256', $artifactPath), 'pilot_schema_or_activation_changed' => false];
if ($apply) {
// Preserve deployment state before copying immutable, separately selected release files.
if (file_put_contents($directory.'/settings.before.json', $settingsBytes) !== strlen($settingsBytes)
|| ! copy($root.'/public/build/manifest.json', $directory.'/manifest.before.json')) {
throw new RuntimeException('Could not preserve deployment state.');
}
$release = $root.'/'.$proposal['release_path'];
if (! is_dir($release.'/src') && ! mkdir($release.'/src', 0700, true)) {
throw new RuntimeException('Could not create the private release directory.');
}
foreach ($artifact['files'] as $file => $hash) {
if (is_file($release.'/'.$file) && hash_file('sha256', $release.'/'.$file) !== $hash) {
throw new LogicException('Existing release differs; it was not overwritten.');
}
if (! is_file($release.'/'.$file)) {
copy($root.'/'.$artifact['path'].'/'.$file, $release.'/'.$file);
}
}
$releaseManifest = $release.'/artifact-manifest.json';
if (is_file($releaseManifest) && hash_file('sha256', $releaseManifest) !== hash_file('sha256', $artifactPath)) {
throw new LogicException('Existing release manifest differs.');
}
if (! is_file($releaseManifest)) {
copy($artifactPath, $releaseManifest);
}
BudgetDistributionArtifact::verify($release, $releaseManifest, $proposal['artifact_manifest_sha256']);
foreach ($proposal['assets'] as $file => $hash) {
$target = $root.'/public/build/'.$file;
if (! preg_match('~^assets/[A-Za-z0-9_.-]+$~D', $file)
|| hash_file('sha256', $root.'/'.$proposal['candidate_path'].'/'.$file) !== $hash
|| (is_file($target) && hash_file('sha256', $target) !== $hash)) {
throw new LogicException('Candidate asset changed or collides with an existing asset.');
}
if (! is_file($target)) {
copy($root.'/'.$proposal['candidate_path'].'/'.$file, $target);
}
if (hash_file('sha256', $target) !== $hash) {
throw new RuntimeException('Copied asset verification failed.');
}
}
DB::setDefaultConnection('distribution_pilot_read');
config(['budget-distributions.schema_installation' => ['database' => $settings['DB_DATABASE'], 'username' => $settings['DB_USERNAME']]]);
$pilot->transaction(function () use ($pilot, $tables, $fingerprint, $columns, $keys, $baseline, $migration, $migrationCount, $settingsPath, $settingsBytes): void {
$pilot->statement("SET LOCAL lock_timeout = '5s'");
foreach ($tables as $table) {
$pilot->statement('LOCK TABLE "'.$table.'" IN SHARE MODE');
}
$current = $fingerprint($pilot, $columns);
unset($current['migrations']);
if ($current !== $baseline || hash_file('sha256', $settingsPath) !== hash('sha256', $settingsBytes)) {
throw new LogicException('Pilot changed after backup; installation refused.');
}
foreach ($keys as $table => $expected) {
if ($pilot->getSchemaBuilder()->getForeignKeys($table) !== $expected) {
throw new LogicException('Pilot foreign keys changed after backup.');
}
}
if (Artisan::call('migrate', ['--database' => 'distribution_pilot_read', '--path' => [$migration], '--force' => true]) !== 0
|| $pilot->table('migrations')->count() !== $migrationCount + 1) {
throw new RuntimeException('Exact pilot migration failed.');
}
$after = $fingerprint($pilot, $columns);
unset($after['migrations']);
if ($after !== $baseline || $pilot->table('requisitions')->whereNotNull('budget_distribution_preparation')->exists()) {
throw new LogicException('Previous data changed; installation rolled back.');
}
foreach ($keys as $table => $expected) {
if ($pilot->getSchemaBuilder()->getForeignKeys($table) !== $expected) {
throw new LogicException('Previous foreign keys changed; installation rolled back.');
}
}
});
$proof['status'] = 'schema_installed_activation_pending';
$proof['pilot_read_only'] = false;
$proof['pilot_schema_or_activation_changed'] = true;
file_put_contents($installationProof, json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL);
// All copied chunks are verified before the manifest is atomically switched.
$manifestBytes = file_get_contents($root.'/'.$proposal['candidate_path'].'/manifest.json');
if (hash('sha256', $manifestBytes) !== $proposal['candidate_manifest_sha256']
|| hash_file('sha256', $settingsPath) !== hash('sha256', $settingsBytes)) {
throw new LogicException('Activation inputs changed; new empty schema retained, activation refused.');
}
$nextSettings = [...$settings, 'COMMON_BUDGET_PATH' => str_replace('\\', '/', $release),
'SGC_BUDGET_DISTRIBUTIONS_ENABLED' => 'true', 'SGC_BUDGET_DISTRIBUTIONS_MANIFEST' => str_replace('\\', '/', $releaseManifest),
'SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256' => $proposal['artifact_manifest_sha256']];
$settingsNextBytes = json_encode($nextSettings, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
$manifestNext = $root.'/public/build/manifest.distribution-next.json';
$settingsNext = $settingsPath.'.distribution-next';
if (file_put_contents($manifestNext, $manifestBytes) !== strlen($manifestBytes)
|| file_put_contents($settingsNext, $settingsNextBytes) !== strlen($settingsNextBytes)
|| ! rename($manifestNext, $root.'/public/build/manifest.json')) {
throw new RuntimeException('Could not switch reviewed assets; deployment state preserved in backup.');
}
if (! rename($settingsNext, $settingsPath)) {
copy($directory.'/manifest.before.json', $root.'/public/build/manifest.json');
throw new RuntimeException('Capability switch failed; previous assets restored, schema retained.');
}
$proof['status'] = 'installed_and_capability_enabled_no_business_operations';
$proof['pilot_read_only'] = false;
$proof['deployment_settings_unchanged'] = false;
$proof['unrelated_deployment_settings_preserved'] = true;
$proof['manifest_sha256'] = hash_file('sha256', $root.'/public/build/manifest.json');
$proof['release_path'] = $proposal['release_path'];
$proof['business_operations'] = false;
$proof['grants_changed'] = false;
$proof['pinned_packages_changed'] = false;
}
} finally {
if ($pilot->transactionLevel() > 0) {
$pilot->rollBack();
}
DB::setDefaultConnection($previous);
config(['budget-distributions.schema_installation' => null]);
DB::purge('distribution_rehearsal');
if ($created) {
$admin->statement('DROP DATABASE "'.$restoreName.'" WITH (FORCE)');
}
}
$proof['restored_database_removed'] = true;
file_put_contents($apply ? $installationProof : $root.'/docs/proofs/rq01-distribution-pilot-preparation.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode($proof, JSON_THROW_ON_ERROR).PHP_EOL;
@@ -0,0 +1,69 @@
<?php
// Produce a reviewable, hash-bound proposal; no application bootstrap, database or deployment writes.
$root = dirname(__DIR__);
$read = static fn (string $path): array => json_decode(file_get_contents($root.'/'.$path), true, 64, JSON_THROW_ON_ERROR);
$artifact = $read('docs/proofs/rq01-distribution-artifact.json');
$rehearsal = $read('docs/proofs/rq01-distribution-pilot-preparation.json');
if ($rehearsal['status'] !== 'restored_pilot_rehearsal_passed_not_installed' || ! $rehearsal['restored_database_removed']) {
throw new LogicException('Successful same-role restored rehearsal required.');
}
$candidate = 'storage/framework/testing/sgc-distribution-integrated-qa-20261122';
$manifest = $read($candidate.'/manifest.json');
$assets = [];
foreach ($manifest as $entry) {
foreach ([$entry['file'], ...($entry['css'] ?? []), ...($entry['assets'] ?? [])] as $file) {
if (! preg_match('~^assets/[A-Za-z0-9_.-]+$~D', $file) || ! is_file($root.'/'.$candidate.'/'.$file)) {
throw new LogicException('Candidate asset inventory mismatch.');
}
$assets[$file] = hash_file('sha256', $root.'/'.$candidate.'/'.$file);
}
}
ksort($assets);
$files = ['scripts/prepare-budget-distribution-pilot.php', 'scripts/budget-distribution-pilot-http.mjs', 'app/Services/BudgetDistributionArtifact.php', 'app/Services/BudgetDistributionSchema.php',
'database/deployment-migrations/2026_11_22_000004_create_budget_distributions.php', 'app/Providers/AppServiceProvider.php',
'app/Services/RequisitionBudgetDistributions.php', 'app/Services/InvoiceBudgetDistributions.php', 'app/Services/CommonBudget.php',
'app/Services/BudgetWorkflow.php', 'app/Services/PurchaseWorkflow.php', 'app/Services/InvoiceWorkflow.php', 'app/Services/RequisitionWorkflow.php',
'app/Models/Requisition.php', 'app/Http/Controllers/RequisitionController.php', 'app/Http/Controllers/PurchaseController.php', 'app/Http/Controllers/InvoiceController.php',
'app/Http/Controllers/PurchaseProcessController.php', 'config/budget-distributions.php', 'config/common-budget.php', 'routes/web.php',
'docs/proofs/rq01-distribution-artifact.json'];
$reviewed = [];
foreach ($files as $file) {
if (! is_file($root.'/'.$file)) {
throw new LogicException('Required reviewed host file missing:'.$file);
}
$reviewed[$file] = hash_file('sha256', $root.'/'.$file);
}
foreach ($artifact['files'] as $file => $hash) {
if (hash_file('sha256', $root.'/'.$artifact['path'].'/'.$file) !== $hash) {
throw new LogicException('Frozen common source changed.');
}
$reviewed[$artifact['path'].'/'.$file] = $hash;
}
$proposal = ['date' => '2026-11-22', 'status' => 'prepared_not_authorised_not_installed', 'environment' => 'http://127.0.0.1:8005',
'scope' => 'Install only the optional line/cost-centre distributions and explicit Finance amendments in the named SGC pilot; no SGF activation or business operations.',
'schema' => ['migration' => $rehearsal['migration'], 'migration_sha256' => $reviewed[$rehearsal['migration']],
'nullable_column' => 'requisitions.budget_distribution_preparation', 'new_empty_tables' => ['budget_distributions', 'budget_distribution_events', 'budget_distribution_entries', 'budget_distribution_consumptions']],
'release_path' => 'storage/app/private/releases/budget-distribution-'.substr($artifact['canonical_fingerprint'], 0, 16),
'artifact_manifest_sha256' => hash_file('sha256', $root.'/docs/proofs/rq01-distribution-artifact.json'),
'archive_sha256' => $artifact['archive_sha256'], 'candidate_path' => $candidate,
'candidate_manifest_sha256' => hash_file('sha256', $root.'/'.$candidate.'/manifest.json'),
'previous_manifest_sha256' => $rehearsal['pilot_manifest_sha256'], 'assets' => $assets, 'reviewed_files' => $reviewed,
'private_settings_changes' => ['COMMON_BUDGET_PATH' => 'Selected independent SGC release directory; original pinned package preserved',
'SGC_BUDGET_DISTRIBUTIONS_ENABLED' => 'true', 'SGC_BUDGET_DISTRIBUTIONS_MANIFEST' => 'Frozen manifest inside the selected release',
'SGC_BUDGET_DISTRIBUTIONS_MANIFEST_SHA256' => 'Exact artifact_manifest_sha256 above'],
'verification' => ['native_visual' => 'rq01-distribution-visual.json', 'financial_qa' => 'rq01-distribution-qa.json',
'same_role_pilot_restore' => 'rq01-distribution-pilot-preparation.json', 'runtime_integrity_log' => 'storage/logs/budget-distribution-release-integrity.txt',
'postgres_schema_and_contract_log' => 'storage/logs/budget-distribution-deployment-schema-pg.txt'],
'execution' => ['Exact separate approval bound to this proposal SHA-256', 'Fresh consistent backup and same-role restore before applying',
'Recheck pilot data and configuration under locks; refuse intervening changes', 'Apply only the staged migration, preserve all previous columns/data/FKs',
'Verify separately copied release and all asset bytes before switching manifest and four settings', 'Confirm named pilot HTTP and effective capability without business commands'],
'recovery' => ['Before use: previous settings and manifest preserved privately; new empty schema can remain',
'After distribution use: retain compatible runtime and append-only history; never select old runtime or restore a backup automatically',
'Any restore affecting later operations requires a separate reviewed decision'],
'excluded' => ['Real business operations, budgets, commitments, invoices, payments or accounting commands', 'Changes to roles or grants',
'SGF deployment or activation', 'Replacing published or pinned financial packages', 'MFA, inventory conversions, per-order limits, People formalisation',
'Production publication and enterprise acceptance']];
file_put_contents($root.'/docs/proofs/rq01-distribution-pilot-proposal.json', json_encode($proposal, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL);
echo json_encode(['proposal_prepared' => true, 'assets' => count($assets), 'reviewed_files' => count($reviewed),
'proposal_sha256' => hash_file('sha256', $root.'/docs/proofs/rq01-distribution-pilot-proposal.json')], JSON_THROW_ON_ERROR).PHP_EOL;
+32 -2
View File
@@ -48,6 +48,36 @@ try {
$orderDocumentMode = in_array('--order-document-only', $argv, true);
$payableInsightsMode = in_array('--payable-insights-only', $argv, true);
$budgetDistributionMode = in_array('--budget-distribution-only', $argv, true);
$categoriesMode = in_array('--requisition-categories-only', $argv, true);
$savedSearchesMode = in_array('--saved-searches-only', $argv, true);
$categoryApprovalsMode = in_array('--category-approvals-only', $argv, true);
$orderPartsMode = in_array('--budget-order-parts-only', $argv, true);
if ($orderPartsMode) {
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php']];
if (in_array('--order-parts-native', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetOrderPartsContractTest.php',
'tests/Feature/InvoiceTest.php', 'tests/Unit/PurchaseLineAmountsTest.php', 'tests/Feature/PurchaseAwardOrderTest.php',
'--filter=BudgetOrderPartsContractTest|InvoiceTest|PurchaseLineAmountsTest|optional partial-order']];
}
if (in_array('--order-parts-recovery', $argv, true)) {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/budget-distribution-recovery-worker.php', $database, 'order-parts']];
}
if (in_array('--order-parts-concurrency', $argv, true)) {
$commands = [[PHP_BINARY, 'tests/Concurrency/quotation-exchange-worker.php', $database, 'migrate'],
[PHP_BINARY, 'tests/Concurrency/budget-order-parts-worker.php', $database, 'race']];
}
}
if ($categoryApprovalsMode) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionApprovalLevelsTest.php', 'tests/Feature/RequisitionCategoriesTest.php']];
}
if ($savedSearchesMode) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/SavedProcurementSearchesTest.php', 'tests/Feature/ProcurementSearchTest.php']];
}
if ($categoriesMode) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionCategoriesTest.php', 'tests/Feature/RequisitionCatalogueTest.php', 'tests/Feature/IncompleteRequisitionDraftTest.php', 'tests/Feature/EquipmentSparePartsTest.php']];
}
if ($budgetDistributionMode) {
$environment['COMMON_BUDGET_PATH'] = 'C:/laragon/www/sgf-tempo/packages/budget-control';
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetDistributionContractTest.php', 'tests/Feature/BudgetTest.php', 'tests/Feature/BudgetReinforcementTest.php', 'tests/Feature/InvoiceTest.php']];
@@ -67,7 +97,7 @@ try {
[PHP_BINARY, 'tests/Concurrency/budget-distribution-visual-seed.php', $database]];
}
if (in_array('--distribution-schema', $argv, true)) {
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetDistributionSchemaTest.php', 'tests/Feature/BudgetDistributionContractTest.php']];
$commands = [[PHP_BINARY, 'vendor/bin/pest', '--compact', 'tests/Feature/BudgetDistributionSchemaTest.php', 'tests/Feature/BudgetDistributionDeploymentSchemaTest.php', 'tests/Feature/BudgetDistributionContractTest.php']];
}
}
if ($payableInsightsMode) {
@@ -118,7 +148,7 @@ try {
throw new RuntimeException('Validação PostgreSQL não aprovada.');
}
}
if ($conversionMode || $agreementMode || $orderLimitMode || $upgradeMode || $benchmarkMode || $draftMode || $searchMode || $productionMode || $configuredLevelsMode || $orderDocumentMode || $payableInsightsMode || $budgetDistributionMode) {
if ($conversionMode || $agreementMode || $orderLimitMode || $upgradeMode || $benchmarkMode || $draftMode || $searchMode || $productionMode || $configuredLevelsMode || $orderDocumentMode || $payableInsightsMode || $budgetDistributionMode || $categoriesMode || $savedSearchesMode || $categoryApprovalsMode || $orderPartsMode) {
return;
}
config(['database.connections.quotation_fx_proof' => [...$config, 'database' => $database, 'url' => null]]);