Aplicar Pint e formatação de frontend; delimitar o âmbito do lint

Só formatação automática (pint, vp check --fix), sem alterar comportamento.
Excluídos da formatação os registos e artefactos com bytes fixos: docs/,
integrations/, storage/, tmp/, output/, resources/data/, tests/Fixtures/,
compras-release.json e AGENTS*.md. Scripts operacionais, integrations e
auxiliares de teste ficam fora do lint (usam new Function; limpeza na fase 2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 23:01:42 +02:00
co-authored by Claude Opus 5.5
parent 9f719695e3
commit ec934455e7
148 changed files with 9455 additions and 2413 deletions
+67 -38
View File
@@ -2,49 +2,78 @@
// Coordinator: provision disposable databases via maintenance DB, never migrate/read client data.
require __DIR__.'/../../vendor/autoload.php';
foreach (['APP_ENV'=>'budget-coordinator','DB_CONNECTION'=>'pgsql','CACHE_STORE'=>'array','SESSION_DRIVER'=>'array'] as $key=>$value) { putenv($key.'='.$value); $_ENV[$key]=$_SERVER[$key]=$value; }
$app=require __DIR__.'/../../bootstrap/app.php';
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
foreach (['APP_ENV' => 'budget-coordinator', 'DB_CONNECTION' => 'pgsql', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array'] as $key => $value) {
putenv($key.'='.$value);
$_ENV[$key] = $_SERVER[$key] = $value;
}
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process;
$source=DB::connection('pgsql')->getConfig();
if(($source['driver']??'')!=='pgsql'||($source['host']??'')!=='127.0.0.1')throw new LogicException('Local PostgreSQL maintenance connection required.');
$maintenance=[...$source,'database'=>'postgres','url'=>null];
config(['database.connections.budget_admin'=>$maintenance]);
$admin=DB::connection('budget_admin')->getPdo();
$sgf=realpath(base_path('../sgf-tempo'));
$script=$sgf.'/packages/budget-control/tests/run-host.php';
$report=['version'=>'COMMON-BUDGET-SYNTHETIC-v1','checked_at'=>gmdate('c'),'client_databases_touched'=>false,'hosts'=>[]];
$artifact=sys_get_temp_dir().'/common-budget-artifact-'.bin2hex(random_bytes(6));
if(!mkdir($artifact.'/src',0700,true))throw new RuntimeException('Cannot prepare isolated package artifact.');
$artifactFiles=['bootstrap.php','src/BudgetContext.php','src/BudgetFailure.php','src/BudgetControl.php'];
foreach($artifactFiles as $file)if(!copy($sgf.'/packages/budget-control/'.$file,$artifact.'/'.$file))throw new RuntimeException('Cannot build package artifact.');
try {
foreach(['compras','sgf'] as $mode){
$db=($mode==='compras'?'compras_receipts_test_':'budget_core_sgf_').bin2hex(random_bytes(6));
$created=false;
try{
$admin->exec('CREATE DATABASE "'.$db.'"');$created=true;
$environment=['APP_ENV'=>$mode==='compras'?'testing':'budget-testing','DB_CONNECTION'=>'pgsql','DB_DATABASE'=>$db,'DB_URL'=>'','DB_HOST'=>'127.0.0.1','DB_PORT'=>(string)$source['port'],'DB_USERNAME'=>$source['username'],'DB_PASSWORD'=>$source['password'],'CACHE_STORE'=>'array','SESSION_DRIVER'=>'array','QUEUE_CONNECTION'=>'sync','MAIL_MAILER'=>'array','BCRYPT_ROUNDS'=>'4','COMMON_BUDGET_PATH'=>$mode==='compras'?$artifact:$sgf.'/packages/budget-control'];
$php=$mode==='compras'?PHP_BINARY:'C:/laragon/tools/sgf-tempo/php-8.4.27/php.exe';
$root=$mode==='compras'?base_path():$sgf;
$process=new Process([$php,$script,$root,$mode],$root,$environment);$process->setTimeout(120);$process->run();
if(!$process->isSuccessful())throw new RuntimeException('QA host failed: '.$process->getOutput().$process->getErrorOutput());
$report['hosts'][]=json_decode($process->getOutput(),true,64,JSON_THROW_ON_ERROR);
}finally{
if(isset($process)&&$process->isRunning())$process->stop();
if($created){
$stmt=$admin->prepare('SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=? AND pid<>pg_backend_pid()');$stmt->execute([$db]);
$admin->exec('DROP DATABASE "'.$db.'"');
}
$source = DB::connection('pgsql')->getConfig();
if (($source['driver'] ?? '') !== 'pgsql' || ($source['host'] ?? '') !== '127.0.0.1') {
throw new LogicException('Local PostgreSQL maintenance connection required.');
}
$maintenance = [...$source, 'database' => 'postgres', 'url' => null];
config(['database.connections.budget_admin' => $maintenance]);
$admin = DB::connection('budget_admin')->getPdo();
$sgf = realpath(base_path('../sgf-tempo'));
$script = $sgf.'/packages/budget-control/tests/run-host.php';
$report = ['version' => 'COMMON-BUDGET-SYNTHETIC-v1', 'checked_at' => gmdate('c'), 'client_databases_touched' => false, 'hosts' => []];
$artifact = sys_get_temp_dir().'/common-budget-artifact-'.bin2hex(random_bytes(6));
if (! mkdir($artifact.'/src', 0700, true)) {
throw new RuntimeException('Cannot prepare isolated package artifact.');
}
$artifactFiles = ['bootstrap.php', 'src/BudgetContext.php', 'src/BudgetFailure.php', 'src/BudgetControl.php'];
foreach ($artifactFiles as $file) {
if (! copy($sgf.'/packages/budget-control/'.$file, $artifact.'/'.$file)) {
throw new RuntimeException('Cannot build package artifact.');
}
}
try {
foreach (['compras', 'sgf'] as $mode) {
$db = ($mode === 'compras' ? 'compras_receipts_test_' : 'budget_core_sgf_').bin2hex(random_bytes(6));
$created = false;
try {
$admin->exec('CREATE DATABASE "'.$db.'"');
$created = true;
$environment = ['APP_ENV' => $mode === 'compras' ? 'testing' : 'budget-testing', 'DB_CONNECTION' => 'pgsql', 'DB_DATABASE' => $db, 'DB_URL' => '', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => (string) $source['port'], 'DB_USERNAME' => $source['username'], 'DB_PASSWORD' => $source['password'], 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array', 'BCRYPT_ROUNDS' => '4', 'COMMON_BUDGET_PATH' => $mode === 'compras' ? $artifact : $sgf.'/packages/budget-control'];
$php = $mode === 'compras' ? PHP_BINARY : 'C:/laragon/tools/sgf-tempo/php-8.4.27/php.exe';
$root = $mode === 'compras' ? base_path() : $sgf;
$process = new Process([$php, $script, $root, $mode], $root, $environment);
$process->setTimeout(120);
$process->run();
if (! $process->isSuccessful()) {
throw new RuntimeException('QA host failed: '.$process->getOutput().$process->getErrorOutput());
}
$report['hosts'][] = json_decode($process->getOutput(), true, 64, JSON_THROW_ON_ERROR);
} finally {
if (isset($process) && $process->isRunning()) {
$process->stop();
}
if ($created) {
$stmt = $admin->prepare('SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=? AND pid<>pg_backend_pid()');
$stmt->execute([$db]);
$admin->exec('DROP DATABASE "'.$db.'"');
}
}
}
} finally {
// Delete only the exact files created above, never a recursive or computed project path.
foreach($artifactFiles as $file)if(is_file($artifact.'/'.$file))unlink($artifact.'/'.$file);
rmdir($artifact.'/src');rmdir($artifact);
foreach ($artifactFiles as $file) {
if (is_file($artifact.'/'.$file)) {
unlink($artifact.'/'.$file);
}
}
rmdir($artifact.'/src');
rmdir($artifact);
}
if($report['hosts'][0]['core_sha256']!==$report['hosts'][1]['core_sha256']||$report['hosts'][0]['steps']!==$report['hosts'][1]['steps'])throw new RuntimeException('Host equivalence failed.');
$report['equivalent']=true;$report['disposable_databases_dropped']=true;
file_put_contents($sgf.'/docs/proofs/common-budget-hosts.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR).PHP_EOL);
if ($report['hosts'][0]['core_sha256'] !== $report['hosts'][1]['core_sha256'] || $report['hosts'][0]['steps'] !== $report['hosts'][1]['steps']) {
throw new RuntimeException('Host equivalence failed.');
}
$report['equivalent'] = true;
$report['disposable_databases_dropped'] = true;
file_put_contents($sgf.'/docs/proofs/common-budget-hosts.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
echo "Two Laravel hosts passed the same core sequence and PostgreSQL concurrency checks. Disposable databases dropped.\n";
+1 -1
View File
@@ -54,5 +54,5 @@ try {
$event = app(WarehouseFulfilment::class)->command($actor, $data['request'], $data['input']);
echo json_encode(['result' => 'saved', 'event' => $event->id], JSON_THROW_ON_ERROR);
} catch (ValidationException $error) {
echo json_encode(['result' => 'rejected'],JSON_THROW_ON_ERROR);
echo json_encode(['result' => 'rejected'], JSON_THROW_ON_ERROR);
}
@@ -14,6 +14,8 @@ use App\Services\GeneralLedger;
use App\Services\InvoiceWorkflow;
use App\Services\OrderCancellationRuntime;
use App\Services\OrderCancellationWorkflow;
use App\Services\PrivateAuditAccess;
use App\Services\PrivateAuditFiles;
use App\Services\ProcurementPaymentInsights;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
@@ -27,8 +29,11 @@ use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tempo\Finance\Budget\BudgetContext;
use Tempo\Finance\Budget\BudgetFailure;
use Tempo\Finance\OrderCancellation\CommitmentReversal;
@@ -77,24 +82,24 @@ test('standalone audit uses ordinary private application storage and refuses pub
$files = null;
try {
config(['filesystems.disks.local.root' => $root]);
\Illuminate\Support\Facades\Storage::forgetDisk('local');
expect(app(\App\Services\PrivateAuditAccess::class)->ready())->toBeTrue();
$files = new \App\Services\PrivateAuditFiles($this->f['issuer']);
Storage::forgetDisk('local');
expect(app(PrivateAuditAccess::class)->ready())->toBeTrue();
$files = new PrivateAuditFiles($this->f['issuer']);
$written = $files->write('probe.ndjson', "{\"synthetic\":true}\n");
expect(file_get_contents($written['path']))->toBe("{\"synthetic\":true}\n")
->and($written['sha256'])->toBe(hash('sha256', "{\"synthetic\":true}\n"));
foreach ([public_path(), storage_path('app/public'), $external] as $invalid) {
config(['filesystems.disks.local.root' => $invalid]);
\Illuminate\Support\Facades\Storage::forgetDisk('local');
expect(fn () => new \App\Services\PrivateAuditFiles($this->f['issuer']))->toThrow(\Symfony\Component\HttpKernel\Exception\HttpException::class);
Storage::forgetDisk('local');
expect(fn () => new PrivateAuditFiles($this->f['issuer']))->toThrow(HttpException::class);
}
} finally {
$files?->cleanup();
config(['filesystems.disks.local' => $original]);
\Illuminate\Support\Facades\Storage::forgetDisk('local');
Storage::forgetDisk('local');
$resolved = realpath($root);
if ($resolved !== false && dirname($resolved) === realpath(storage_path('app')) && str_starts_with(basename($resolved), 'release-audit-')) {
\Illuminate\Support\Facades\File::deleteDirectory($resolved);
File::deleteDirectory($resolved);
}
if (is_dir($external) && count(scandir($external) ?: []) === 2) {
rmdir($external);
+1 -1
View File
@@ -64,5 +64,5 @@ test('synthetic pilot connects partial delivery shortage purchase draft replenis
->and(app(StockWorkflow::class)->balance($f['stock']->id, $f['warehouse']->id)['quantity'])->toBe(103000)
->and($purchase->fresh()->status)->toBe('draft')->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0)
->and(Requisition::query()->where('status', 'draft')->count())->toBe(1);
$this->get('/stock/requisicoes?view=receipt')->assertOk()->assertInertia(fn (Assert $p) => $p->where('records.total',0));
$this->get('/stock/requisicoes?view=receipt')->assertOk()->assertInertia(fn (Assert $p) => $p->where('records.total', 0));
});
+341 -150
View File
@@ -1,218 +1,409 @@
<?php
namespace Tests\Integration;
use App\Models\User;
use App\Services\{SgfInvoiceDispatches,InvoiceWorkflow};
use Illuminate\Support\Facades\{DB,Schema,Http};
use App\Services\SgfInvoiceDispatches;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\QueryException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\Request as Outbound;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Tests\TestCase;
/** Only this schema and in-memory SQLite. Never RefreshDatabase or a pilot connection. */
final class SgfInvoiceDispatchesTest extends \Tests\TestCase
final class SgfInvoiceDispatchesTest extends TestCase
{
private User $actor;
private SgfInvoiceDispatches $service;
private array $remote=[];
private bool $lose=false;
private array $remote = [];
private bool $lose = false;
private string $privateRoot;
public function createApplication()
{
$repo=dirname(__DIR__,2);$this->privateRoot='C:/laragon/data/sgf-tempo/run/sgc-dispatch-tests-'.bin2hex(random_bytes(6));
foreach(['logs','framework/views','framework/sessions','framework/cache/data']as$d)mkdir($this->privateRoot.'/storage/'.$d,0700,true);
foreach(['DB_CONNECTION'=>'sqlite','DB_DATABASE'=>':memory:','DB_URL'=>'','APP_ENV'=>'testing',
'APP_CONFIG_CACHE'=>$this->privateRoot.'/config.php','APP_SERVICES_CACHE'=>$this->privateRoot.'/services.php','APP_PACKAGES_CACHE'=>$this->privateRoot.'/packages.php',
'APP_ROUTES_CACHE'=>$this->privateRoot.'/routes.php','SESSION_DRIVER'=>'array','CACHE_STORE'=>'array']as$k=>$v){putenv($k.'='.$v);$_ENV[$k]=$v;}
$app=require $repo.'/bootstrap/app.php';$app->addAbsoluteCachePathPrefix('C:');$app->useStoragePath($this->privateRoot.'/storage');
$this->traitsUsedByTest=class_uses_recursive(static::class);$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();return $app;
$repo = dirname(__DIR__, 2);
$this->privateRoot = 'C:/laragon/data/sgf-tempo/run/sgc-dispatch-tests-'.bin2hex(random_bytes(6));
foreach (['logs', 'framework/views', 'framework/sessions', 'framework/cache/data'] as $d) {
mkdir($this->privateRoot.'/storage/'.$d, 0700, true);
}
foreach (['DB_CONNECTION' => 'sqlite', 'DB_DATABASE' => ':memory:', 'DB_URL' => '', 'APP_ENV' => 'testing',
'APP_CONFIG_CACHE' => $this->privateRoot.'/config.php', 'APP_SERVICES_CACHE' => $this->privateRoot.'/services.php', 'APP_PACKAGES_CACHE' => $this->privateRoot.'/packages.php',
'APP_ROUTES_CACHE' => $this->privateRoot.'/routes.php', 'SESSION_DRIVER' => 'array', 'CACHE_STORE' => 'array'] as $k => $v) {
putenv($k.'='.$v);
$_ENV[$k] = $v;
}
$app = require $repo.'/bootstrap/app.php';
$app->addAbsoluteCachePathPrefix('C:');
$app->useStoragePath($this->privateRoot.'/storage');
$this->traitsUsedByTest = class_uses_recursive(self::class);
$app->make(Kernel::class)->bootstrap();
return $app;
}
protected function setUp():void
protected function setUp(): void
{
parent::setUp();
self::assertSame('sqlite',DB::getDriverName());self::assertSame(':memory:',DB::connection()->getDatabaseName());
config(['app.key'=>'base64:'.base64_encode(str_repeat('x',32)),'sgf_invoice.workspace_enabled'=>true,'sgf_invoice.enabled'=>true]);
Schema::create('tenants',fn(Blueprint $t)=>[$t->id(),$t->string('name'),$t->json('work_context_policy')->nullable()]);
Schema::create('users',function(Blueprint $t){$t->id();$t->unsignedBigInteger('tenant_id');$t->string('purchasing_role');$t->string('name');$t->string('email');$t->string('password');$t->timestamp('email_verified_at')->nullable();$t->rememberToken();$t->timestamps();});
Schema::create('suppliers',fn(Blueprint $t)=>[$t->id(),$t->unsignedBigInteger('tenant_id'),$t->string('name')]);
Schema::create('invoices',fn(Blueprint $t)=>[$t->id(),$t->unsignedBigInteger('tenant_id'),$t->unsignedBigInteger('supplier_id'),$t->string('number')]);
DB::table('tenants')->insert([['id'=>1,'name'=>'QA source'],['id'=>2,'name'=>'Foreign QA']]);
foreach([1=>[1,'finance'],2=>[2,'finance'],3=>[1,'warehouse'],4=>[1,'finance']]as$id=>[$tenant,$role])DB::table('users')->insert(['id'=>$id,'tenant_id'=>$tenant,'purchasing_role'=>$role,'name'=>'QA '.$id,'email'=>'qa'.$id.'@example.test','password'=>'unused','email_verified_at'=>now(),'created_at'=>now(),'updated_at'=>now()]);
DB::table('suppliers')->insert([['id'=>1,'tenant_id'=>1,'name'=>'QA Supplier'],['id'=>2,'tenant_id'=>2,'name'=>'Foreign']]);
$migration=require dirname(__DIR__,2).'/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php';$migration->up();
$this->actor=User::findOrFail(1);$this->actingAs($this->actor);$this->service=app(SgfInvoiceDispatches::class);
$package='C:/laragon/www/sgf-tempo/packages/sgc-invoice-client/src/InvoiceClient.php';
config(['sgf_invoice.client_package'=>$package,'sgf_invoice.client_package_sha256'=>hash_file('sha256',$package),
'sgf_invoice.connections'=>['qa'=>['enabled'=>true,'source_scope'=>['tenant_id'=>1],'target_scope'=>['tenant_id'=>1,'company_id'=>2,'unit_id'=>2],
'client_id'=>'qa','token'=>str_repeat('q',64),'context_version'=>str_repeat('a',64),'origin'=>'http://127.0.0.1:8085','mappings'=>['map'=>[
'approved'=>true,'label'=>'Escolha QA','source_supplier_id'=>1,'mapping'=>['id'=>'qa-map','version'=>1,'source_scope'=>['tenant_id'=>1],
'target_scope'=>['tenant_id'=>1,'company_id'=>2,'unit_id'=>2],'authority'=>'sgf_only','order_id'=>7,'lines'=>['QA-LINE'=>8]]]]]]]);
Http::preventStrayRequests();Http::fake(function(Outbound $r){
if($r->method()==='GET')return Http::response(['order'=>['id'=>7],'revision'=>str_repeat('b',64)]);
$key=$r->header('X-Idempotency-Key')[0];
if($r['phase']==='preview')return Http::response(['preview'=>'QA-encrypted-'.$key,'impact'=>['operation'=>'Registar pendente','budget_consumption_minor'=>0,'payable_created'=>false]]);
$replay=isset($this->remote[$key]);$this->remote[$key]??=40+count($this->remote);
if($this->lose){$this->lose=false;throw new \Illuminate\Http\Client\ConnectionException('Synthetic lost response');}
return Http::response(['invoice_id'=>$this->remote[$key],'order_id'=>7,'status'=>'pending','replayed'=>$replay],$replay?200:201);
self::assertSame('sqlite', DB::getDriverName());
self::assertSame(':memory:', DB::connection()->getDatabaseName());
config(['app.key' => 'base64:'.base64_encode(str_repeat('x', 32)), 'sgf_invoice.workspace_enabled' => true, 'sgf_invoice.enabled' => true]);
Schema::create('tenants', fn (Blueprint $t) => [$t->id(), $t->string('name'), $t->json('work_context_policy')->nullable()]);
Schema::create('users', function (Blueprint $t) {
$t->id();
$t->unsignedBigInteger('tenant_id');
$t->string('purchasing_role');
$t->string('name');
$t->string('email');
$t->string('password');
$t->timestamp('email_verified_at')->nullable();
$t->rememberToken();
$t->timestamps();
});
Schema::create('suppliers', fn (Blueprint $t) => [$t->id(), $t->unsignedBigInteger('tenant_id'), $t->string('name')]);
Schema::create('invoices', fn (Blueprint $t) => [$t->id(), $t->unsignedBigInteger('tenant_id'), $t->unsignedBigInteger('supplier_id'), $t->string('number')]);
DB::table('tenants')->insert([['id' => 1, 'name' => 'QA source'], ['id' => 2, 'name' => 'Foreign QA']]);
foreach ([1 => [1, 'finance'], 2 => [2, 'finance'], 3 => [1, 'warehouse'], 4 => [1, 'finance']] as $id => [$tenant,$role]) {
DB::table('users')->insert(['id' => $id, 'tenant_id' => $tenant, 'purchasing_role' => $role, 'name' => 'QA '.$id, 'email' => 'qa'.$id.'@example.test', 'password' => 'unused', 'email_verified_at' => now(), 'created_at' => now(), 'updated_at' => now()]);
}
DB::table('suppliers')->insert([['id' => 1, 'tenant_id' => 1, 'name' => 'QA Supplier'], ['id' => 2, 'tenant_id' => 2, 'name' => 'Foreign']]);
$migration = require dirname(__DIR__, 2).'/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php';
$migration->up();
$this->actor = User::findOrFail(1);
$this->actingAs($this->actor);
$this->service = app(SgfInvoiceDispatches::class);
$package = 'C:/laragon/www/sgf-tempo/packages/sgc-invoice-client/src/InvoiceClient.php';
config(['sgf_invoice.client_package' => $package, 'sgf_invoice.client_package_sha256' => hash_file('sha256', $package),
'sgf_invoice.connections' => ['qa' => ['enabled' => true, 'source_scope' => ['tenant_id' => 1], 'target_scope' => ['tenant_id' => 1, 'company_id' => 2, 'unit_id' => 2],
'client_id' => 'qa', 'token' => str_repeat('q', 64), 'context_version' => str_repeat('a', 64), 'origin' => 'http://127.0.0.1:8085', 'mappings' => ['map' => [
'approved' => true, 'label' => 'Escolha QA', 'source_supplier_id' => 1, 'mapping' => ['id' => 'qa-map', 'version' => 1, 'source_scope' => ['tenant_id' => 1],
'target_scope' => ['tenant_id' => 1, 'company_id' => 2, 'unit_id' => 2], 'authority' => 'sgf_only', 'order_id' => 7, 'lines' => ['QA-LINE' => 8]]]]]]]);
Http::preventStrayRequests();
Http::fake(function (Outbound $r) {
if ($r->method() === 'GET') {
return Http::response(['order' => ['id' => 7], 'revision' => str_repeat('b', 64)]);
}
$key = $r->header('X-Idempotency-Key')[0];
if ($r['phase'] === 'preview') {
return Http::response(['preview' => 'QA-encrypted-'.$key, 'impact' => ['operation' => 'Registar pendente', 'budget_consumption_minor' => 0, 'payable_created' => false]]);
}
$replay = isset($this->remote[$key]);
$this->remote[$key] ??= 40 + count($this->remote);
if ($this->lose) {
$this->lose = false;
throw new ConnectionException('Synthetic lost response');
}
return Http::response(['invoice_id' => $this->remote[$key], 'order_id' => 7, 'status' => 'pending', 'replayed' => $replay], $replay ? 200 : 201);
});
}
private function data(string $ref='QA-SOURCE-1'):array
private function data(string $ref = 'QA-SOURCE-1'): array
{
return ['reference'=>$ref,'connection_id'=>'qa','mapping_id'=>'map','reason'=>'Conferência documental exclusivamente sintética.','document'=>[
'number'=>$ref,'issued_on'=>'2026-11-10','subtotal'=>'100.00','tax'=>'0.00','total'=>'100.00','items'=>[
['source_line_ref'=>'QA-LINE','quantity'=>'1.000','unit'=>'UN','unit_price'=>'100.00','tax_rate'=>'0.00']]]];
return ['reference' => $ref, 'connection_id' => 'qa', 'mapping_id' => 'map', 'reason' => 'Conferência documental exclusivamente sintética.', 'document' => [
'number' => $ref, 'issued_on' => '2026-11-10', 'subtotal' => '100.00', 'tax' => '0.00', 'total' => '100.00', 'items' => [
['source_line_ref' => 'QA-LINE', 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]];
}
private function prepared():object
private function prepared(): object
{
$id=$this->service->create($this->actor,$this->data());return $this->service->dispatch($this->actor,$id,1,'preview','Conferir impacto documental actual.',null);
$id = $this->service->create($this->actor, $this->data());
return $this->service->dispatch($this->actor, $id, 1, 'preview', 'Conferir impacto documental actual.', null);
}
private function approval(object $row):string{return $this->service->presentation($this->actor,$row)['approval_hash'];}
public function test_full_durable_cycle_and_audited_decision():void
private function approval(object $row): string
{
$row=$this->prepared();self::assertSame('previewed',$row->phase);self::assertSame(3,$row->version);
$approved=$this->approval($row);self::assertIsString($approved);self::assertStringNotContainsString('QA-encrypted',$row->state_ciphertext);
$done=$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Aceitar individualmente este impacto.',$approved);
self::assertSame('received_pending',$done->phase);self::assertNotNull($done->receipt);self::assertCount(1,$this->remote);
self::assertSame(0,DB::table('invoices')->count());
$events=DB::table('sgf_invoice_dispatch_events')->orderBy('id')->get();self::assertCount(5,$events);
self::assertSame('decision.confirmed',$events[3]->action);self::assertSame(1,$events[3]->actor_id);self::assertNotNull($events[3]->before_state);
self::assertSame($approved,json_decode($events[3]->after_state,true)['approval_hash']);
return $this->service->presentation($this->actor, $row)['approval_hash'];
}
public function test_lost_response_reuses_same_key_cut_and_durable_intent():void
public function test_full_durable_cycle_and_audited_decision(): void
{
$row=$this->prepared();$this->lose=true;$unknown=$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Aceitar e conservar decisão sintética.',$this->approval($row));
self::assertSame('uncertain',$unknown->phase);$key=$unknown->operation_key;
$recovered=$this->service->dispatch($this->actor,$row->id,$unknown->version,'recover','Recuperar a mesma intenção sem duplicação.',null);
self::assertSame('received_pending',$recovered->phase);self::assertSame($key,$recovered->operation_key);self::assertCount(1,$this->remote);
self::assertTrue(json_decode($recovered->receipt,true)['replayed']);
$row = $this->prepared();
self::assertSame('previewed', $row->phase);
self::assertSame(3, $row->version);
$approved = $this->approval($row);
self::assertIsString($approved);
self::assertStringNotContainsString('QA-encrypted', $row->state_ciphertext);
$done = $this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Aceitar individualmente este impacto.', $approved);
self::assertSame('received_pending', $done->phase);
self::assertNotNull($done->receipt);
self::assertCount(1, $this->remote);
self::assertSame(0, DB::table('invoices')->count());
$events = DB::table('sgf_invoice_dispatch_events')->orderBy('id')->get();
self::assertCount(5, $events);
self::assertSame('decision.confirmed', $events[3]->action);
self::assertSame(1, $events[3]->actor_id);
self::assertNotNull($events[3]->before_state);
self::assertSame($approved, json_decode($events[3]->after_state, true)['approval_hash']);
}
public function test_failure_after_remote_commit_keeps_durable_sending_for_recovery():void
public function test_lost_response_reuses_same_key_cut_and_durable_intent(): void
{
$row=$this->prepared();DB::unprepared("CREATE TRIGGER fail_observation BEFORE INSERT ON sgf_invoice_dispatch_events WHEN NEW.action='transport.observed' BEGIN SELECT RAISE(ABORT,'Synthetic persistence failure'); END");
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Confirmar decisão antes do transporte.',$this->approval($row));self::fail('Expected storage failure');}catch(\Illuminate\Database\QueryException){}
$pending=$this->service->row($this->actor,$row->id);self::assertSame('sending',$pending->phase);self::assertTrue((bool)$pending->ever_sending);self::assertCount(1,$this->remote);
DB::unprepared('DROP TRIGGER fail_observation');$this->travel(121)->seconds();
$done=$this->service->dispatch($this->actor,$row->id,$pending->version,'recover','Recuperar após libertação do lease.',null);
self::assertSame('received_pending',$done->phase);self::assertCount(1,$this->remote);
$row = $this->prepared();
$this->lose = true;
$unknown = $this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Aceitar e conservar decisão sintética.', $this->approval($row));
self::assertSame('uncertain', $unknown->phase);
$key = $unknown->operation_key;
$recovered = $this->service->dispatch($this->actor, $row->id, $unknown->version, 'recover', 'Recuperar a mesma intenção sem duplicação.', null);
self::assertSame('received_pending', $recovered->phase);
self::assertSame($key, $recovered->operation_key);
self::assertCount(1, $this->remote);
self::assertTrue(json_decode($recovered->receipt, true)['replayed']);
}
public function test_revision_preserves_before_after_and_invalidates_preview():void
public function test_failure_after_remote_commit_keeps_durable_sending_for_recovery(): void
{
$row=$this->prepared();$data=$this->data();$data['document']['subtotal']='120.00';$data['document']['total']='120.00';$data['document']['items'][0]['unit_price']='120.00';
$new=$this->service->revise($this->actor,$row->id,$row->version,$data);self::assertSame('draft',$new->phase);self::assertNull($new->operation_key);self::assertNull($new->state_ciphertext);
self::assertSame(2,$new->source_version);$e=DB::table('sgf_invoice_dispatch_events')->orderByDesc('id')->first();
self::assertSame('100.00',json_decode($e->before_state,true)['document']['total']);self::assertSame('120.00',json_decode($e->after_state,true)['document']['total']);
$row = $this->prepared();
DB::unprepared("CREATE TRIGGER fail_observation BEFORE INSERT ON sgf_invoice_dispatch_events WHEN NEW.action='transport.observed' BEGIN SELECT RAISE(ABORT,'Synthetic persistence failure'); END");
try {
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Confirmar decisão antes do transporte.', $this->approval($row));
self::fail('Expected storage failure');
} catch (QueryException) {
}
$pending = $this->service->row($this->actor, $row->id);
self::assertSame('sending', $pending->phase);
self::assertTrue((bool) $pending->ever_sending);
self::assertCount(1, $this->remote);
DB::unprepared('DROP TRIGGER fail_observation');
$this->travel(121)->seconds();
$done = $this->service->dispatch($this->actor, $row->id, $pending->version, 'recover', 'Recuperar após libertação do lease.', null);
self::assertSame('received_pending', $done->phase);
self::assertCount(1, $this->remote);
}
public function test_no_edit_after_any_confirmation_started():void
public function test_revision_preserves_before_after_and_invalidates_preview(): void
{
$row=$this->prepared();$this->lose=true;$row=$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Confirmar individualmente o documento.',$this->approval($row));
$this->expectException(\Symfony\Component\HttpKernel\Exception\HttpException::class);$this->service->revise($this->actor,$row->id,$row->version,$this->data());
$row = $this->prepared();
$data = $this->data();
$data['document']['subtotal'] = '120.00';
$data['document']['total'] = '120.00';
$data['document']['items'][0]['unit_price'] = '120.00';
$new = $this->service->revise($this->actor, $row->id, $row->version, $data);
self::assertSame('draft', $new->phase);
self::assertNull($new->operation_key);
self::assertNull($new->state_ciphertext);
self::assertSame(2, $new->source_version);
$e = DB::table('sgf_invoice_dispatch_events')->orderByDesc('id')->first();
self::assertSame('100.00', json_decode($e->before_state, true)['document']['total']);
self::assertSame('120.00', json_decode($e->after_state, true)['document']['total']);
}
public function test_local_registration_is_blocked_even_when_feature_is_disabled():void
public function test_no_edit_after_any_confirmation_started(): void
{
$this->service->create($this->actor,$this->data());config(['sgf_invoice.workspace_enabled'=>false]);
$this->expectException(\Illuminate\Validation\ValidationException::class);SgfInvoiceDispatches::assertLocalRegistration(1,1,'QA-SOURCE-1');
$row = $this->prepared();
$this->lose = true;
$row = $this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Confirmar individualmente o documento.', $this->approval($row));
$this->expectException(HttpException::class);
$this->service->revise($this->actor, $row->id, $row->version, $this->data());
}
public function test_existing_local_invoice_cannot_be_sent():void
public function test_local_registration_is_blocked_even_when_feature_is_disabled(): void
{
DB::table('invoices')->insert(['tenant_id'=>1,'supplier_id'=>1,'number'=>'QA-SOURCE-1']);
$this->expectException(\Symfony\Component\HttpKernel\Exception\HttpException::class);$this->service->create($this->actor,$this->data());
$this->service->create($this->actor, $this->data());
config(['sgf_invoice.workspace_enabled' => false]);
$this->expectException(ValidationException::class);
SgfInvoiceDispatches::assertLocalRegistration(1, 1, 'QA-SOURCE-1');
}
public function test_duplicate_source_cannot_get_second_intent():void
public function test_existing_local_invoice_cannot_be_sent(): void
{
$this->service->create($this->actor,$this->data());$this->expectException(\Symfony\Component\HttpKernel\Exception\HttpException::class);$this->service->create($this->actor,$this->data());
DB::table('invoices')->insert(['tenant_id' => 1, 'supplier_id' => 1, 'number' => 'QA-SOURCE-1']);
$this->expectException(HttpException::class);
$this->service->create($this->actor, $this->data());
}
public function test_stale_version_and_wrong_approval_do_not_send():void
public function test_duplicate_source_cannot_get_second_intent(): void
{
$row=$this->prepared();foreach([1=>str_repeat('0',64),$row->version=>str_repeat('0',64)]as$version=>$approval){
try{$this->service->dispatch($this->actor,$row->id,$version,'confirm','Fundamento de confirmação explícita.',$approval);self::fail('Expected409');}
catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}}
self::assertCount(0,$this->remote);
$this->service->create($this->actor, $this->data());
$this->expectException(HttpException::class);
$this->service->create($this->actor, $this->data());
}
public function test_operator_context_and_mapping_changes_require_new_conference():void
public function test_stale_version_and_wrong_approval_do_not_send(): void
{
$row=$this->prepared();$approval=$this->approval($row);$this->actingAs(User::find(4));
try{$this->service->dispatch(User::find(4),$row->id,$row->version,'confirm','Outro operador deve conferir novamente.',$approval);self::fail('Expected409');}catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}
$this->actingAs($this->actor);config(['sgf_invoice.connections.qa.mappings.map.mapping.version'=>2]);
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Mapeamento mudou; não deve enviar.',$approval);self::fail('Expected409');}catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}
self::assertCount(0,$this->remote);
$row = $this->prepared();
foreach ([1 => str_repeat('0', 64), $row->version => str_repeat('0', 64)] as $version => $approval) {
try {
$this->service->dispatch($this->actor, $row->id, $version, 'confirm', 'Fundamento de confirmação explícita.', $approval);
self::fail('Expected409');
} catch (HttpException $e) {
self::assertSame(409, $e->getStatusCode());
}
}
self::assertCount(0, $this->remote);
}
public function test_http_screen_csrf_and_audited_history_are_private():void
public function test_operator_context_and_mapping_changes_require_new_conference(): void
{
$r=$this->post('/facturas/envio-sgf',$this->data());$r->assertRedirect('/facturas/envio-sgf/1');
$this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('QA-SOURCE-1')->assertSee('Histórico auditado')->assertHeader('Cache-Control','no-store, private');
$row = $this->prepared();
$approval = $this->approval($row);
$this->actingAs(User::find(4));
try {
$this->service->dispatch(User::find(4), $row->id, $row->version, 'confirm', 'Outro operador deve conferir novamente.', $approval);
self::fail('Expected409');
} catch (HttpException $e) {
self::assertSame(409, $e->getStatusCode());
}
$this->actingAs($this->actor);
config(['sgf_invoice.connections.qa.mappings.map.mapping.version' => 2]);
try {
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Mapeamento mudou; não deve enviar.', $approval);
self::fail('Expected409');
} catch (HttpException $e) {
self::assertSame(409, $e->getStatusCode());
}
self::assertCount(0, $this->remote);
}
public function test_http_screen_csrf_and_audited_history_are_private(): void
{
$r = $this->post('/facturas/envio-sgf', $this->data());
$r->assertRedirect('/facturas/envio-sgf/1');
$this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('QA-SOURCE-1')->assertSee('Histórico auditado')->assertHeader('Cache-Control', 'no-store, private');
$this->get('/facturas/envio-sgf')->assertOk()->assertSee('Escolher explicitamente')->assertDontSee('Guardar novo rascunho');
$this->get('/facturas/envio-sgf?connection=qa&mapping=map')->assertOk()->assertSee('Guardar novo rascunho');
$this->app->instance('env','local');try{$this->post('/facturas/envio-sgf',$this->data('CSRF-FAIL'))->assertStatus(419);}finally{$this->app->instance('env','testing');}
self::assertSame(1,DB::table('sgf_invoice_dispatches')->count());
$this->app->instance('env', 'local');
try {
$this->post('/facturas/envio-sgf', $this->data('CSRF-FAIL'))->assertStatus(419);
} finally {
$this->app->instance('env', 'testing');
}
self::assertSame(1, DB::table('sgf_invoice_dispatches')->count());
}
public function test_foreign_tenant_and_warehouse_actor_cannot_read_or_write():void
public function test_foreign_tenant_and_warehouse_actor_cannot_read_or_write(): void
{
$id=$this->service->create($this->actor,$this->data());$this->actingAs(User::find(2));$this->get('/facturas/envio-sgf/'.$id)->assertNotFound();
$this->post('/facturas/envio-sgf',$this->data('FOREIGN'))->assertForbidden();
$this->actingAs(User::find(3));$this->get('/facturas/envio-sgf')->assertForbidden();
self::assertSame(1,DB::table('sgf_invoice_dispatches')->count());
$id = $this->service->create($this->actor, $this->data());
$this->actingAs(User::find(2));
$this->get('/facturas/envio-sgf/'.$id)->assertNotFound();
$this->post('/facturas/envio-sgf', $this->data('FOREIGN'))->assertForbidden();
$this->actingAs(User::find(3));
$this->get('/facturas/envio-sgf')->assertForbidden();
self::assertSame(1, DB::table('sgf_invoice_dispatches')->count());
}
public function test_pagination_history_and_output_escaping():void
public function test_pagination_history_and_output_escaping(): void
{
for($i=0;$i<27;$i++)$this->service->create($this->actor,$this->data('QA-LIST-'.$i));
for ($i = 0; $i < 27; $i++) {
$this->service->create($this->actor, $this->data('QA-LIST-'.$i));
}
$this->get('/facturas/envio-sgf?page=2')->assertOk()->assertSee('QA-LIST-0')->assertDontSee('QA-LIST-26');
$row=$this->service->row($this->actor,1);for($i=0;$i<27;$i++)$row=$this->service->revise($this->actor,1,$row->version,$this->data('QA-LIST-0'));
$row = $this->service->row($this->actor, 1);
for ($i = 0; $i < 27; $i++) {
$row = $this->service->revise($this->actor, 1, $row->version, $this->data('QA-LIST-0'));
}
$this->get('/facturas/envio-sgf/1?events_page=2')->assertOk()->assertSee('draft.created');
$data=$this->data('XSS');$data['document']['number']='<script>alert(1)</script>';$id=$this->service->create($this->actor,$data);
$this->get('/facturas/envio-sgf/'.$id)->assertOk()->assertDontSee('<script>alert(1)</script>',false)->assertSee('&lt;SCRIPT&gt;',false);
$data = $this->data('XSS');
$data['document']['number'] = '<script>alert(1)</script>';
$id = $this->service->create($this->actor, $data);
$this->get('/facturas/envio-sgf/'.$id)->assertOk()->assertDontSee('<script>alert(1)</script>', false)->assertSee('&lt;SCRIPT&gt;', false);
}
public function test_events_and_drafts_cannot_be_deleted_or_rewritten():void
public function test_events_and_drafts_cannot_be_deleted_or_rewritten(): void
{
$id=$this->service->create($this->actor,$this->data());
foreach([fn()=>DB::table('sgf_invoice_dispatch_events')->update(['action'=>'tampered']),fn()=>DB::table('sgf_invoice_dispatch_events')->delete(),fn()=>DB::table('sgf_invoice_dispatches')->delete()]as$mutate){
try{$mutate();self::fail('Expected immutable audit');}catch(\Illuminate\Database\QueryException){self::assertSame(1,DB::table('sgf_invoice_dispatch_events')->count());}}
$id = $this->service->create($this->actor, $this->data());
foreach ([fn () => DB::table('sgf_invoice_dispatch_events')->update(['action' => 'tampered']), fn () => DB::table('sgf_invoice_dispatch_events')->delete(), fn () => DB::table('sgf_invoice_dispatches')->delete()] as $mutate) {
try {
$mutate();
self::fail('Expected immutable audit');
} catch (QueryException) {
self::assertSame(1, DB::table('sgf_invoice_dispatch_events')->count());
}
}
}
public function test_disabled_transport_keeps_draft_and_disabled_workspace_refuses():void
public function test_disabled_transport_keeps_draft_and_disabled_workspace_refuses(): void
{
$id=$this->service->create($this->actor,$this->data());config(['sgf_invoice.enabled'=>false]);
$this->post('/facturas/envio-sgf/'.$id.'/operar',['version'=>1,'action'=>'preview','reason'=>'Não activar o transporte nesta entrega.'])->assertStatus(423);
self::assertNull($this->service->row($this->actor,$id)->operation_key);Http::assertNothingSent();
config(['sgf_invoice.workspace_enabled'=>false]);$this->get('/facturas/envio-sgf')->assertNotFound();
$id = $this->service->create($this->actor, $this->data());
config(['sgf_invoice.enabled' => false]);
$this->post('/facturas/envio-sgf/'.$id.'/operar', ['version' => 1, 'action' => 'preview', 'reason' => 'Não activar o transporte nesta entrega.'])->assertStatus(423);
self::assertNull($this->service->row($this->actor, $id)->operation_key);
Http::assertNothingSent();
config(['sgf_invoice.workspace_enabled' => false]);
$this->get('/facturas/envio-sgf')->assertNotFound();
}
public function test_changed_remote_context_refuses_decision_before_recording_it():void
public function test_changed_remote_context_refuses_decision_before_recording_it(): void
{
$row=$this->prepared();$hash=$this->approval($row);$events=DB::table('sgf_invoice_dispatch_events')->count();
config(['sgf_invoice.connections.qa.context_version'=>str_repeat('c',64)]);
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Contexto remoto mudou; não confirmar.',$hash);self::fail('Expected409');}
catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}
self::assertSame($events,DB::table('sgf_invoice_dispatch_events')->count());self::assertCount(0,$this->remote);
$new=$this->service->dispatch($this->actor,$row->id,$row->version,'preview','Conferir novamente o contexto actual.',null);
self::assertSame('previewed',$new->phase);self::assertSame($row->operation_key,$new->operation_key);self::assertNotSame($hash,$this->approval($new));
$row = $this->prepared();
$hash = $this->approval($row);
$events = DB::table('sgf_invoice_dispatch_events')->count();
config(['sgf_invoice.connections.qa.context_version' => str_repeat('c', 64)]);
try {
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Contexto remoto mudou; não confirmar.', $hash);
self::fail('Expected409');
} catch (HttpException $e) {
self::assertSame(409, $e->getStatusCode());
}
self::assertSame($events, DB::table('sgf_invoice_dispatch_events')->count());
self::assertCount(0, $this->remote);
$new = $this->service->dispatch($this->actor, $row->id, $row->version, 'preview', 'Conferir novamente o contexto actual.', null);
self::assertSame('previewed', $new->phase);
self::assertSame($row->operation_key, $new->operation_key);
self::assertNotSame($hash, $this->approval($new));
}
public function test_revoked_operator_cannot_confirm_and_live_lease_prevents_duplicate_send():void
public function test_revoked_operator_cannot_confirm_and_live_lease_prevents_duplicate_send(): void
{
$row=$this->prepared();$hash=$this->approval($row);
DB::table('users')->where('id',1)->update(['purchasing_role'=>'warehouse']);
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Não enviar com autoridade revogada.',$hash);self::fail('Expected403');}
catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(403,$e->getStatusCode());}
DB::table('users')->where('id',1)->update(['purchasing_role'=>'finance']);
DB::table('sgf_invoice_dispatches')->where('id',$row->id)->update(['lease_until'=>now('UTC')->addSeconds(120)]);
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Uma operação em curso não duplica.',$hash);self::fail('Expected409');}
catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}
self::assertCount(0,$this->remote);
$row = $this->prepared();
$hash = $this->approval($row);
DB::table('users')->where('id', 1)->update(['purchasing_role' => 'warehouse']);
try {
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Não enviar com autoridade revogada.', $hash);
self::fail('Expected403');
} catch (HttpException $e) {
self::assertSame(403, $e->getStatusCode());
}
DB::table('users')->where('id', 1)->update(['purchasing_role' => 'finance']);
DB::table('sgf_invoice_dispatches')->where('id', $row->id)->update(['lease_until' => now('UTC')->addSeconds(120)]);
try {
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Uma operação em curso não duplica.', $hash);
self::fail('Expected409');
} catch (HttpException $e) {
self::assertSame(409, $e->getStatusCode());
}
self::assertCount(0, $this->remote);
}
public function test_actual_screen_forms_complete_registration_and_keep_exact_sgf_handoff():void
public function test_actual_screen_forms_complete_registration_and_keep_exact_sgf_handoff(): void
{
$this->post('/facturas/envio-sgf',$this->data())->assertRedirect('/facturas/envio-sgf/1');
$this->post('/facturas/envio-sgf/1/operar',['version'=>1,'action'=>'preview','reason'=>'Conferência individual pela interface.'])->assertRedirect('/facturas/envio-sgf/1');
$html=$this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('Impacto devolvido pelo SGF')->assertSee('Confirmar individualmente')->assertDontSee('QA-encrypted',false)->getContent();
preg_match('/name="approval_hash" value="([a-f0-9]{64})"/',$html,$match);self::assertNotEmpty($match);
file_put_contents($this->privateRoot.'/screen-preview.html',$html);
$this->post('/facturas/envio-sgf/1/operar',['version'=>3,'action'=>'confirm','reason'=>'Confirmar apenas este impacto mostrado.','approval_hash'=>$match[1]])->assertRedirect('/facturas/envio-sgf/1');
$done=$this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('Recibo conservado')->assertDontSee('Confirmar individualmente')->assertSee('http://127.0.0.1:8085/compras?',false)->getContent();
file_put_contents($this->privateRoot.'/screen-receipt.html',$done);self::assertCount(1,$this->remote);
$this->post('/facturas/envio-sgf', $this->data())->assertRedirect('/facturas/envio-sgf/1');
$this->post('/facturas/envio-sgf/1/operar', ['version' => 1, 'action' => 'preview', 'reason' => 'Conferência individual pela interface.'])->assertRedirect('/facturas/envio-sgf/1');
$html = $this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('Impacto devolvido pelo SGF')->assertSee('Confirmar individualmente')->assertDontSee('QA-encrypted', false)->getContent();
preg_match('/name="approval_hash" value="([a-f0-9]{64})"/', $html, $match);
self::assertNotEmpty($match);
file_put_contents($this->privateRoot.'/screen-preview.html', $html);
$this->post('/facturas/envio-sgf/1/operar', ['version' => 3, 'action' => 'confirm', 'reason' => 'Confirmar apenas este impacto mostrado.', 'approval_hash' => $match[1]])->assertRedirect('/facturas/envio-sgf/1');
$done = $this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('Recibo conservado')->assertDontSee('Confirmar individualmente')->assertSee('http://127.0.0.1:8085/compras?', false)->getContent();
file_put_contents($this->privateRoot.'/screen-receipt.html',$done);
self::assertCount(1,$this->remote);
}
public function test_missing_schema_is_refused_without_activating_or_migrating():void
public function test_missing_schema_is_refused_without_activating_or_migrating(): void
{
$migration=require dirname(__DIR__,2).'/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php';$migration->down();
$this->get('/facturas/envio-sgf')->assertStatus(503);Http::assertNothingSent();self::assertFalse(Schema::hasTable('sgf_invoice_dispatches'));
$migration = require dirname(__DIR__,2).'/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php';
$migration->down();
$this->get('/facturas/envio-sgf')->assertStatus(503);
Http::assertNothingSent();
self::assertFalse(Schema::hasTable('sgf_invoice_dispatches'));
}
public function test_audit_freezes_preview_actor_and_context_fingerprint():void
public function test_audit_freezes_preview_actor_and_context_fingerprint(): void
{
$row=$this->prepared();$event=DB::table('sgf_invoice_dispatch_events')->orderByDesc('id')->first();$state=json_decode($event->after_state,true);
self::assertSame(1,$state['preview_actor_id']);self::assertSame($row->source_context_hash,$state['source_context_hash']);
$row = $this->prepared();
$event = DB::table('sgf_invoice_dispatch_events')->orderByDesc('id')->first();
$state = json_decode($event->after_state,true);
self::assertSame(1,$state['preview_actor_id']);
self::assertSame($row->source_context_hash,$state['source_context_hash']);
}
}
+3 -1
View File
@@ -12,6 +12,8 @@ use App\Models\Supplier;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Warehouse;
use App\Services\PurchaseLineAmounts;
use App\Services\ReceiptWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
@@ -31,7 +33,7 @@ function receiptFixture(string $quantity = '1.000', string $purchaseType = 'cons
throw new LogicException('The explicit multi-category fixture uses one unit per line.');
}
$lineMinor = intdiv(10000, count($categories));
$amounts = \App\Services\PurchaseLineAmounts::portion($lineMinor, '0', 0, \App\Services\ReceiptWorkflow::milli($quantity));
$amounts = PurchaseLineAmounts::portion($lineMinor, '0', 0, ReceiptWorkflow::milli($quantity));
$documentMinor = $amounts['total_minor'] * count($categories);
$tenant = Tenant::query()->create(['name' => 'Empresa fictícia de recepção']);
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações']);
+40 -15
View File
@@ -1,16 +1,41 @@
<?php
$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$file=realpath($argv[1]??'');
if(!$root||!$file||dirname($file)!==$root)throw new RuntimeException('Unexpected private worker');
require getcwd().'/vendor/autoload.php';$app=require getcwd().'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$db=Illuminate\Support\Facades\DB::connection();$i=$db->selectOne("SELECT current_database() AS name,current_user AS role,current_setting('cluster_name') AS cluster");
if(!preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->name,$m)||$i->role!=='stock_receipt_qa_'.$m[1]||$i->cluster!=='sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'))throw new RuntimeException('Wrong receipt worker database');
$input=json_decode(file_get_contents($file),true,512,JSON_THROW_ON_ERROR);
$db->select("SELECT set_config('application_name',?,false)",[$input['application']]);$db->statement("SET lock_timeout='8s'");$db->statement("SET statement_timeout='12s'");
$actor=App\Models\User::findOrFail($input['actor']);auth()->guard()->setUser($actor);
file_put_contents($file.'.ready','ready');
$start=hrtime(true);
try{$receipt=app(App\Services\ReceiptWorkflow::class)->confirm($actor,App\Models\PurchaseOrder::findOrFail($input['order']),$input['payload']);
$result=['status'=>200,'receipt_id'=>$receipt->id];
}catch(Illuminate\Validation\ValidationException){$result=['status'=>422];}
catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$result=['status'=>$e->getStatusCode()];}
$result['elapsed_ms']=round((hrtime(true)-$start)/1e6,3);file_put_contents($file.'.result',json_encode($result,JSON_THROW_ON_ERROR));
use App\Models\PurchaseOrder;
use App\Models\User;
use App\Services\ReceiptWorkflow;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
$file = realpath($argv[1] ?? '');
if (! $root || ! $file || dirname($file) !== $root) {
throw new RuntimeException('Unexpected private worker');
}
require getcwd().'/vendor/autoload.php';
$app = require getcwd().'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$i = $db->selectOne("SELECT current_database() AS name,current_user AS role,current_setting('cluster_name') AS cluster");
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->name, $m) || $i->role !== 'stock_receipt_qa_'.$m[1] || $i->cluster !== 'sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN')) {
throw new RuntimeException('Wrong receipt worker database');
}
$input = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
$db->select("SELECT set_config('application_name',?,false)", [$input['application']]);
$db->statement("SET lock_timeout='8s'");
$db->statement("SET statement_timeout='12s'");
$actor = User::findOrFail($input['actor']);
auth()->guard()->setUser($actor);
file_put_contents($file.'.ready', 'ready');
$start = hrtime(true);
try {
$receipt = app(ReceiptWorkflow::class)->confirm($actor, PurchaseOrder::findOrFail($input['order']), $input['payload']);
$result = ['status' => 200, 'receipt_id' => $receipt->id];
} catch (ValidationException) {
$result = ['status' => 422];
} catch (HttpExceptionInterface $e) {
$result = ['status' => $e->getStatusCode()];
}
$result['elapsed_ms'] = round((hrtime(true) - $start) / 1e6, 3);
file_put_contents($file.'.result', json_encode($result,JSON_THROW_ON_ERROR));
+91 -23
View File
@@ -9,43 +9,97 @@ 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); },
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 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 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)};`);
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 : [],
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) },
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(); },
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; } };
const event = {
prevented: false,
preventDefault() {
this.prevented = true;
},
};
events.get('beforeunload')?.(event);
return event.prevented;
};
const submit = form => form.onsubmit({ preventDefault() {} });
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']) {
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);
@@ -62,7 +116,10 @@ for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php'
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.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/);
@@ -76,8 +133,13 @@ for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php'
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'); };
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);
@@ -87,14 +149,20 @@ for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php'
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.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; });
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);
+24 -7
View File
@@ -4,22 +4,36 @@ import { test } from 'node:test';
import { createNativeInertiaClient } from '../../scripts/lib/native-inertia-client.mjs';
test('owned native client drains large closed responses while preserving body headers cookies and manual redirects', async () => {
const payload = { synthetic_only: true, content: 'x'.repeat(2 * 1024 * 1024) };
const payload = {
synthetic_only: true,
content: 'x'.repeat(2 * 1024 * 1024),
};
let cookiesSeen = '';
const server = createServer((request, response) => {
response.setHeader('Connection', 'close');
response.useChunkedEncodingByDefault = false;
if (request.url === '/cookies') {
response.setHeader('Set-Cookie', ['QA_SESSION=first; Path=/', 'QA_CONTEXT=second; Path=/']);
response.setHeader('Set-Cookie', [
'QA_SESSION=first; Path=/',
'QA_CONTEXT=second; Path=/',
]);
}
if (request.url === '/empty') {
response.writeHead(204);
response.end();
return;
}
if (request.url === '/redirect') {
response.writeHead(302, { Location: '/large' });
response.end('Synthetic redirect');
return;
}
if (request.url === '/empty') { response.writeHead(204); response.end(); return; }
if (request.url === '/redirect') { response.writeHead(302, { Location: '/large' }); response.end('Synthetic redirect'); return; }
cookiesSeen = request.headers.cookie ?? '';
response.writeHead(200, { 'Content-Type': 'application/json' });
response.write(JSON.stringify(payload));
response.end();
});
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
try {
const origin = `http://127.0.0.1:${server.address().port}`;
const client = createNativeInertiaClient(origin, assert.ok);
@@ -44,9 +58,12 @@ test('owned native client drains large closed responses while preserving body he
assert.equal(redirect.status, 302);
assert.equal(redirect.headers.get('Location'), '/large');
assert.equal(await redirect.text(), 'Synthetic redirect');
await assert.rejects(client.request('//example.test/foreign'), /External HTTP destination refused/);
await assert.rejects(
client.request('//example.test/foreign'),
/External HTTP destination refused/,
);
} finally {
server.closeAllConnections();
await new Promise(resolve => server.close(resolve));
await new Promise((resolve) => server.close(resolve));
}
});
+32 -9
View File
@@ -1,10 +1,33 @@
<?php
$file=realpath($argv[1]??'');$private=realpath(getcwd().'/../private');
if(!$file||!$private||!str_starts_with($file,$private.DIRECTORY_SEPARATOR))throw new LogicException('Private QA worker input refused');
require getcwd().'/vendor/autoload.php';$app=require getcwd().'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$p=json_decode(file_get_contents($file),true,64,JSON_THROW_ON_ERROR);$db=Illuminate\Support\Facades\DB::connection();$i=$db->selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
if(!preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->db,$m)||$i->role!=='stock_receipt_qa_'.$m[1]||(int)$i->port!==55439||$i->cluster!=='sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'))throw new LogicException('QA worker database refused');
config(['common-payables.enabled'=>true,'common-payables.history_enabled'=>true,'common-payables.paged_read_enabled'=>true,'common-payables.source_instance'=>$p['instance']]);$u=App\Models\User::query()->findOrFail($p['actor']);auth()->setUser($u);$time=hrtime(true);
try{$d=app(App\Services\SupplierPayables::class)->listing($u);$out=['status'=>200,'documents'=>count($d['documents']),'balances'=>array_column($d['obligations'],'balance_minor'),'time_ms'=>(hrtime(true)-$time)/1e6];}
catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$out=['status'=>$e->getStatusCode()];}
file_put_contents($file.'.result',json_encode($out,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
use App\Models\User;
use App\Services\SupplierPayables;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
$file = realpath($argv[1] ?? '');
$private = realpath(getcwd().'/../private');
if (! $file || ! $private || ! str_starts_with($file, $private.DIRECTORY_SEPARATOR)) {
throw new LogicException('Private QA worker input refused');
}
require getcwd().'/vendor/autoload.php';
$app = require getcwd().'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$p = json_decode(file_get_contents($file), true, 64, JSON_THROW_ON_ERROR);
$db = DB::connection();
$i = $db->selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->db, $m) || $i->role !== 'stock_receipt_qa_'.$m[1] || (int) $i->port !== 55439 || $i->cluster !== 'sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN')) {
throw new LogicException('QA worker database refused');
}
config(['common-payables.enabled' => true, 'common-payables.history_enabled' => true, 'common-payables.paged_read_enabled' => true, 'common-payables.source_instance' => $p['instance']]);
$u = User::query()->findOrFail($p['actor']);
auth()->setUser($u);
$time = hrtime(true);
try {
$d = app(SupplierPayables::class)->listing($u);
$out = ['status' => 200, 'documents' => count($d['documents']), 'balances' => array_column($d['obligations'], 'balance_minor'), 'time_ms' => (hrtime(true) - $time) / 1e6];
} catch (HttpExceptionInterface $e) {
$out = ['status' => $e->getStatusCode()];
}
file_put_contents($file.'.result', json_encode($out, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
+58 -34
View File
@@ -1,44 +1,68 @@
<?php
use App\Models\User;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Tempo\Purchasing\Delivery\SqlPrivileges;
// Runs only inside the disposable reproduction after its authorised lifecycle.
// Inherits the explicit test scope/clients; never creates grants in the host.
$catalogue=$call($actor,'/api/accesses');
$check($catalogue['status']===200&&in_array('purchasing_requisitions.prepare',$catalogue['data']['catalogue']['unit'],true),'native administration receives complete unit catalogue');
$check(($catalogue['data']['catalogue_labels']['purchasing_requisitions.prepare']??'')==='Preparar e submeter requisições','native administration receives canonical server labels');
$check($call($head,'/api/accesses')['status']===403,'reviewer cannot inspect administrative catalogue without management right');
$check($call($actor,'/api/accesses','POST',['email'=>\App\Models\User::findOrFail($head)->email,'unit_id'=>$scope['unit_id'],'permission'=>'purchasing_budget.consume','reason'=>'Forbidden delegation outside own synthetic authority'])['status']===403,'forged delegation of an unowned catalogue right refused');
$catalogue = $call($actor, '/api/accesses');
$check($catalogue['status'] === 200 && in_array('purchasing_requisitions.prepare', $catalogue['data']['catalogue']['unit'], true), 'native administration receives complete unit catalogue');
$check(($catalogue['data']['catalogue_labels']['purchasing_requisitions.prepare'] ?? '') === 'Preparar e submeter requisições', 'native administration receives canonical server labels');
$check($call($head, '/api/accesses')['status'] === 403, 'reviewer cannot inspect administrative catalogue without management right');
$check($call($actor, '/api/accesses', 'POST', ['email' => User::findOrFail($head)->email, 'unit_id' => $scope['unit_id'], 'permission' => 'purchasing_budget.consume', 'reason' => 'Forbidden delegation outside own synthetic authority'])['status'] === 403, 'forged delegation of an unowned catalogue right refused');
$uiManifest=json_decode(file_get_contents($clone.'/public/build/manifest.json'),true,32,JSON_THROW_ON_ERROR);
foreach($uiManifest as $chunk)foreach([$chunk['file'],...($chunk['css']??[])] as $file){
$asset=$anonymous->get('http://127.0.0.1:'.$port.'/build/'.$file);
$check($asset->getStatusCode()===200&&strlen((string)$asset->getBody())>100,'packaged frontend dependency served before authentication');
$uiManifest = json_decode(file_get_contents($clone.'/public/build/manifest.json'), true, 32, JSON_THROW_ON_ERROR);
foreach ($uiManifest as $chunk) {
foreach ([$chunk['file'], ...($chunk['css'] ?? [])] as $file) {
$asset = $anonymous->get('http://127.0.0.1:'.$port.'/build/'.$file);
$check($asset->getStatusCode() === 200 && strlen((string) $asset->getBody()) > 100, 'packaged frontend dependency served before authentication');
}
}
$main=$anonymous->get('http://127.0.0.1:'.$port.'/');
$check($main->getStatusCode()===200&&str_contains((string)$main->getBody(),'/build/modules/internal-requisitions/assets/'),'native SGF entry renders the packaged frontend manifest');
$check($anonymous->get('http://127.0.0.1:'.$port.'/build/modules/internal-requisitions/assets/missing.js')->getStatusCode()===404,'undeclared frontend asset refused');
$main = $anonymous->get('http://127.0.0.1:'.$port.'/');
$check($main->getStatusCode() === 200 && str_contains((string) $main->getBody(), '/build/modules/internal-requisitions/assets/'), 'native SGF entry renders the packaged frontend manifest');
$check($anonymous->get('http://127.0.0.1:'.$port.'/build/modules/internal-requisitions/assets/missing.js')->getStatusCode() === 404, 'undeclared frontend asset refused');
// Reproduce destination-style broad inherited ACLs on NEW objects, then prove
// the proposed map narrows them without touching any of the 87 prior tables.
$beforeAcl=[];
foreach($inventory['tables'] as $table)$beforeAcl[$table]=$db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass',['public.'.$table])->acl;
foreach(\Tempo\Purchasing\Delivery\SqlPrivileges::TABLES as $table=>$rights)$db->statement('GRANT SELECT,INSERT,UPDATE,DELETE ON TABLE public.'.$q($table).' TO '.$q($runtime));
foreach(\Tempo\Purchasing\Delivery\SqlPrivileges::plan($runtime)['statements'] as $sql)$db->statement($sql);
$check(!$rt->selectOne("SELECT has_table_privilege(current_user,'cb_centres','UPDATE') AS allowed")->allowed&&!$rt->selectOne("SELECT has_table_privilege(current_user,'cb_audit','DELETE') AS allowed")->allowed,'minimal plan removes inherited update and delete on new append-only sources');
$check(!$rt->selectOne("SELECT has_table_privilege(current_user,'ir_requests','TRUNCATE') AS allowed")->allowed,'runtime cannot truncate requisitions');
foreach($beforeAcl as $table=>$acl)$check($db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass',['public.'.$table])->acl===$acl,'existing table ACL preserved '.$table);
try{$rt->transaction(fn()=>$rt->statement('CREATE TABLE forbidden_runtime_ddl (id integer)'));throw new LogicException('Unexpected runtime DDL');}
catch(\Illuminate\Database\QueryException $e){$check($e->errorInfo[0]==='42501','actual runtime CREATE denied');}
try{$rt->transaction(fn()=>$rt->statement('ALTER TABLE permission_grants ADD COLUMN forbidden_runtime integer'));throw new LogicException('Unexpected runtime ALTER');}
catch(\Illuminate\Database\QueryException $e){$check($e->errorInfo[0]==='42501','actual runtime ALTER of identity catalogue denied');}
$badCentre=['operation_key'=>(string)\Illuminate\Support\Str::uuid(),'code'=>'NOT-ALLOWED','reason'=>'Validation in the isolated reproduction only'];
$check($call($head,'/api/internal-requisitions/centres','POST',$badCentre)['status']===403,'centre creation requires own configuration and budget rights');
$check($call($actor,'/api/internal-requisitions/centres','POST',$badCentre+['company_id'=>999999])['status']===422,'centre context cannot be forged');
$check(\Illuminate\Support\Facades\DB::table('cb_centres')->count()===1,'refused centre operations leave original source intact');
foreach(['equipment','part'] as $unsupported){
$r=$call($actor,'/api/internal-requisitions/save','POST',['operation_key'=>(string)\Illuminate\Support\Str::uuid(),'cost_center_id'=>$f['centre'],'priority'=>'normal','needed_by'=>date('Y-m-d',time()+864000),'justification'=>'Unsupported type must remain outside this increment.','items'=>[['description'=>'Unsupported source','category'=>'Excluded','purchase_type'=>$unsupported,'quantity'=>'1.000','unit'=>'UN','unit_price'=>'1.00','tax_rate'=>'0.00']]]);
$check($r['status']===422,'unsupported requisition type refused '.$unsupported);
$beforeAcl = [];
foreach ($inventory['tables'] as $table) {
$beforeAcl[$table] = $db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass', ['public.'.$table])->acl;
}
$data=json_decode(\Illuminate\Support\Facades\DB::table('ir_requests')->where('id',$id)->value('data'),true,32,JSON_THROW_ON_ERROR);
$check(array_column($data['items'],'purchase_type')===['consumable','service','other'],'approved lifecycle covers the three supported basic types');
$check(\Illuminate\Support\Facades\DB::table('ir_requests')->count()===1&&\Illuminate\Support\Facades\DB::table('cb_budget_entries')->where('kind','reserve')->count()===1,'unsupported types create neither a second request nor reservation');
foreach (SqlPrivileges::TABLES as $table => $rights) {
$db->statement('GRANT SELECT,INSERT,UPDATE,DELETE ON TABLE public.'.$q($table).' TO '.$q($runtime));
}
foreach (SqlPrivileges::plan($runtime)['statements'] as $sql) {
$db->statement($sql);
}
$check(! $rt->selectOne("SELECT has_table_privilege(current_user,'cb_centres','UPDATE') AS allowed")->allowed && ! $rt->selectOne("SELECT has_table_privilege(current_user,'cb_audit','DELETE') AS allowed")->allowed, 'minimal plan removes inherited update and delete on new append-only sources');
$check(! $rt->selectOne("SELECT has_table_privilege(current_user,'ir_requests','TRUNCATE') AS allowed")->allowed, 'runtime cannot truncate requisitions');
foreach ($beforeAcl as $table => $acl) {
$check($db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass', ['public.'.$table])->acl === $acl, 'existing table ACL preserved '.$table);
}
try {
$rt->transaction(fn () => $rt->statement('CREATE TABLE forbidden_runtime_ddl (id integer)'));
throw new LogicException('Unexpected runtime DDL');
} catch (QueryException $e) {
$check($e->errorInfo[0] === '42501', 'actual runtime CREATE denied');
}
try {
$rt->transaction(fn () => $rt->statement('ALTER TABLE permission_grants ADD COLUMN forbidden_runtime integer'));
throw new LogicException('Unexpected runtime ALTER');
} catch (QueryException $e) {
$check($e->errorInfo[0] === '42501', 'actual runtime ALTER of identity catalogue denied');
}
$badCentre = ['operation_key' => (string) Str::uuid(), 'code' => 'NOT-ALLOWED', 'reason' => 'Validation in the isolated reproduction only'];
$check($call($head, '/api/internal-requisitions/centres', 'POST', $badCentre)['status'] === 403, 'centre creation requires own configuration and budget rights');
$check($call($actor, '/api/internal-requisitions/centres', 'POST', $badCentre + ['company_id' => 999999])['status'] === 422, 'centre context cannot be forged');
$check(DB::table('cb_centres')->count() === 1, 'refused centre operations leave original source intact');
foreach (['equipment', 'part'] as $unsupported) {
$r = $call($actor, '/api/internal-requisitions/save', 'POST', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['centre'], 'priority' => 'normal', 'needed_by' => date('Y-m-d', time() + 864000), 'justification' => 'Unsupported type must remain outside this increment.', 'items' => [['description' => 'Unsupported source', 'category' => 'Excluded', 'purchase_type' => $unsupported, 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '1.00', 'tax_rate' => '0.00']]]);
$check($r['status'] === 422, 'unsupported requisition type refused '.$unsupported);
}
$data = json_decode(DB::table('ir_requests')->where('id', $id)->value('data'), true, 32, JSON_THROW_ON_ERROR);
$check(array_column($data['items'], 'purchase_type') === ['consumable', 'service', 'other'], 'approved lifecycle covers the three supported basic types');
$check(DB::table('ir_requests')->count() === 1 && DB::table('cb_budget_entries')->where('kind','reserve')->count() === 1, 'unsupported types create neither a second request nor reservation');
+1 -1
View File
@@ -218,7 +218,7 @@ try {
$check($call($actor, '/api/purchasing-budget/movement', 'POST', [], ['Idempotency-Key' => (string) Str::uuid()])['status'] === 403, 'direct budget movements cannot bypass requisition lifecycle');
$policy = ['version' => 0, 'reason' => 'Política sintética na composição integrada.', 'enabled' => true, 'budget_required' => true, 'first_limit_minor' => 1000000, 'second_limit_minor' => 2000000, 'approval_includes_tax' => true, 'centres' => [['id' => $f['centre'], 'department_ref' => 'OPER']], 'members' => [['user_id' => $actor, 'department_ref' => 'OPER'], ['user_id' => $head, 'department_ref' => 'OPER']]];
$check($call($actor, '/api/internal-requisitions/policy', 'POST', $policy)['status'] === 200, 'operational policy configured via HTTP');
$draft = $call($actor, '/api/internal-requisitions/save', 'POST', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['centre'], 'priority' => 'normal', 'needed_by' => date('Y-m-d', time() + 864000), 'justification' => 'Requisição sintética da composição.', 'items' => [['description' => 'Material', 'category' => 'Consumíveis', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00'], ['description'=>'Servi?o sint?tico','category'=>'Servi?os','purchase_type'=>'service','quantity'=>'1.000','unit'=>'UN','unit_price'=>'25.00','tax_rate'=>'0.00'], ['description'=>'Outro sint?tico','category'=>'Outros','purchase_type'=>'other','quantity'=>'1.000','unit'=>'UN','unit_price'=>'10.00','tax_rate'=>'0.00']]]);
$draft = $call($actor, '/api/internal-requisitions/save', 'POST', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['centre'], 'priority' => 'normal', 'needed_by' => date('Y-m-d', time() + 864000), 'justification' => 'Requisição sintética da composição.', 'items' => [['description' => 'Material', 'category' => 'Consumíveis', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00'], ['description' => 'Servi?o sint?tico', 'category' => 'Servi?os', 'purchase_type' => 'service', 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '25.00', 'tax_rate' => '0.00'], ['description' => 'Outro sint?tico', 'category' => 'Outros', 'purchase_type' => 'other', 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '10.00', 'tax_rate' => '0.00']]]);
$check($draft['status'] === 200, 'integrated operational draft');
$id = $draft['data']['id'];
$submitted = $call($actor, "/api/internal-requisitions/$id/submit", 'POST', ['operation_key' => (string) Str::uuid(), 'version' => 1]);
+6 -2
View File
@@ -4,7 +4,9 @@
$variant = $work.'/code-only-successor';
$vm = json_decode(file_get_contents($bundle.'/manifest.json'), true, 32, JSON_THROW_ON_ERROR);
foreach ([...array_keys($vm['support_files']), 'manifest.json'] as $file) {
if (! is_dir(dirname($variant.'/'.$file))) mkdir(dirname($variant.'/'.$file), 0700, true);
if (! is_dir(dirname($variant.'/'.$file))) {
mkdir(dirname($variant.'/'.$file), 0700, true);
}
copy($bundle.'/'.$file, $variant.'/'.$file);
}
$file = 'integrations/sgf/internal-requisitions/screen.php';
@@ -19,6 +21,8 @@ $deploy->rollback($vu['deployment_id'], 'Isolated successor recovery', true);
$check(hash_file('sha256', $clone.'/packages/internal-requisitions/manifest.json') === hash_file('sha256', $bundle.'/manifest.json'), 'code-only successor rollback restores exact candidate');
foreach ($fingerprints as $table => $expected) {
$rows = $db->select('select to_jsonb(t)::text as data from "'.$table.'" t order by to_jsonb(t)::text');
if (hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR)) !== $expected) throw new RuntimeException('Update changed '.$table);
if (hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR)) !== $expected) {
throw new RuntimeException('Update changed '.$table);
}
}
$check(true, 'code update and rollback preserve every reproduced data table');
+35 -13
View File
@@ -1,16 +1,38 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
$host=getenv('SOURCING_CLONE');$work=getenv('SOURCING_WORK');require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
try{
$db=DB::connection();if(!preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D',$db->getDatabaseName()))throw new RuntimeException('Copy only');
$fixture=json_decode(file_get_contents($work.'/fixture.json'),true);$command=$argv[1];
if(in_array($command,['revoke-evaluate','restore-evaluate','revoke-propose','restore-propose','revoke-view','restore-view'])){
$right=str_contains($command,'evaluate')?'purchasing_sourcing.evaluate':(str_contains($command,'propose')?'purchasing_sourcing.propose':'purchasing_requisitions.view');$id=str_contains($command,'evaluate')?$fixture['user_id']:(str_contains($command,'propose')?2:3);
$scope=['user_id'=>$id,'tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'permission'=>$right];
if(str_starts_with($command,'revoke'))$db->table('permission_grants')->where($scope)->delete();else $db->table('permission_grants')->insertOrIgnore($scope+['created_at'=>now(),'updated_at'=>now()]);
}elseif($command==='fail-on')file_put_contents($host.'/storage/framework/sourcing-failure.fixture','isolated failure injection');
elseif($command==='fail-off')unlink($host.'/storage/framework/sourcing-failure.fixture');
else throw new RuntimeException('Unsupported fixture control');
echo json_encode(['ok'=>true]);
}catch(Throwable $e){fwrite(STDERR,$e->getMessage());exit(1);}
$host = getenv('SOURCING_CLONE');
$work = getenv('SOURCING_WORK');
require $host.'/vendor/autoload.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
try {
$db = DB::connection();
if (! preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D', $db->getDatabaseName())) {
throw new RuntimeException('Copy only');
}
$fixture = json_decode(file_get_contents($work.'/fixture.json'), true);
$command = $argv[1];
if (in_array($command, ['revoke-evaluate', 'restore-evaluate', 'revoke-propose', 'restore-propose', 'revoke-view', 'restore-view'])) {
$right = str_contains($command, 'evaluate') ? 'purchasing_sourcing.evaluate' : (str_contains($command, 'propose') ? 'purchasing_sourcing.propose' : 'purchasing_requisitions.view');
$id = str_contains($command, 'evaluate') ? $fixture['user_id'] : (str_contains($command, 'propose') ? 2 : 3);
$scope = ['user_id' => $id, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'permission' => $right];
if (str_starts_with($command, 'revoke')) {
$db->table('permission_grants')->where($scope)->delete();
} else {
$db->table('permission_grants')->insertOrIgnore($scope + ['created_at' => now(), 'updated_at' => now()]);
}
} elseif ($command === 'fail-on') {
file_put_contents($host.'/storage/framework/sourcing-failure.fixture', 'isolated failure injection');
} elseif ($command === 'fail-off') {
unlink($host.'/storage/framework/sourcing-failure.fixture');
} else {
throw new RuntimeException('Unsupported fixture control');
}
echo json_encode(['ok' => true]);
} catch (Throwable $e) {
fwrite(STDERR, $e->getMessage());
exit(1);
}
+126 -46
View File
@@ -1,51 +1,131 @@
<?php
use App\Models\User;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Models\User;
use Tempo\Purchasing\SgfSourcing\Schema;
use Symfony\Component\Process\Process;
use Tempo\Purchasing\Delivery\CodeDeployment;
$host=getenv('SOURCING_CLONE');$root=getenv('SOURCING_REPO');$work=getenv('SOURCING_WORK');
require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
try{
$db=DB::connection();$name=$db->selectOne('select current_database() as db')->db;
if(!preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D',$name)||$name!==getenv('SOURCING_DB')||!str_contains(str_replace('\\','/',$host),'/private/sourcing-')||str_replace('\\','/',$app->basePath())!==$host)throw new RuntimeException('Not an isolated sourcing copy');
$candidate=json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-candidate.json'),true,32,JSON_THROW_ON_ERROR);
if(!class_exists(Schema::class))require_once $candidate['directory'].'/integrations/sgf/sourcing/Schema.php';require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
$deploy=new CodeDeployment($host);$checks=[];$check=function($ok,$label)use(&$checks){if(!$ok)throw new RuntimeException($label);$checks[]=$label;};
$fingerprint=function(string $table)use($db){return hash('sha256',json_encode($db->table($table)->orderBy('id')->get(),JSON_THROW_ON_ERROR));};
if(($argv[1]??'')==='setup'){
$baseline=['request'=>$fingerprint('ir_requests'),'budget'=>$fingerprint('cb_budget_entries'),'consumption'=>$fingerprint('cb_budget_consumptions'),'grants_count'=>$db->table('permission_grants')->count()];file_put_contents($work.'/origin.json',json_encode($baseline));
$armed=true;$db->listen(function($query)use(&$armed){if($armed&&str_contains(strtolower($query->sql),'create table "ss_events"')){$armed=false;throw new RuntimeException('Injected migration failure');}});
try{Schema::migrate($db,hash_file('sha256',$work.'/before.dump'),'Isolated failure proof');throw new RuntimeException('Expected failure');}catch(RuntimeException $e){$check($e->getMessage()==='Injected migration failure','Injected migration failure surfaced');}
$check(!$db->getSchemaBuilder()->hasTable('ss_suppliers')&&!$db->table('sgc_installations')->where('module','sourcing')->exists(),'Migration failure rolls back tables and catalogue');
$migration=Schema::migrate($db,hash_file('sha256',$work.'/before.dump'),'Isolated sourcing proof');$check($migration['prepared'],'Additive migration accepted');$check(Schema::migrate($db,hash_file('sha256',$work.'/before.dump'),'Isolated replay')['replayed'],'Migration replay is stable');
$old=json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'),true);$next=json_decode(file_get_contents($candidate['directory'].'/manifest.json'),true);
$current=json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'),true);
try{$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);throw new RuntimeException('Unprepared plan accepted');}catch(RuntimeException $e){$check(str_contains($e->getMessage(),'migração própria'),'Schema-changing update refuses missing migration receipt');}
$receipt=['from_manifest_sha256'=>$current['manifest_sha256'],'to_manifest_sha256'=>$candidate['archive']['manifest_sha256'],'host'=>$host,'schema_verified'=>Schema::compatible($db),'changes'=>[]];
foreach($next['support_files'] as $file=>$hash)if(($old['support_files'][$file]??null)!==$hash)$receipt['changes'][$file]=['before'=>$old['support_files'][$file]??null,'after'=>$hash];
file_put_contents($host.'/storage/framework/down','{}');
$cli=new Symfony\Component\Process\Process([PHP_BINARY,$candidate['directory'].'/scripts/sgf-sourcing-install.php','migrate',$host,Tempo\Purchasing\Delivery\Installation::target($db),$work.'/before.dump',hash_file('sha256',$work.'/before.dump'),'Isolated migration CLI',$candidate['archive']['manifest_sha256']],$host,['PG_RESTORE_BINARY'=>'C:/Program Files/PostgreSQL/17/bin/pg_restore.exe']);$cli->mustRun();
$cliResult=json_decode($cli->getOutput(),true,32,JSON_THROW_ON_ERROR);$check($cliResult['prepared']&&!$cliResult['activated']&&!$cliResult['rights_granted'],'Packaged migration CLI produces exact receipt without activation or grants');
$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);$applied=$deploy->apply($candidate['directory'],$candidate['archive']['manifest_sha256'],$plan['target_sha256'],'Isolated sourcing update',true);unlink($host.'/storage/framework/down');file_put_contents($work.'/applied.json',json_encode($applied));
$target=Tempo\Purchasing\Delivery\Installation::target($db);file_put_contents($host.'/config/purchasing-operational.php','<?php return '.var_export(['enabled'=>true,'target'=>$target,'scopes'=>['1:1:1']],true).';');file_put_contents($host.'/config/purchasing-sourcing.php','<?php return ["enabled"=>true];');
$private=json_decode(file_get_contents('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json'),true);
$user=User::forceCreate(['name'=>'Synthetic isolated evaluator','email'=>'fixture-'.Str::uuid().'@example.invalid','password'=>$private['password'],'auth_version'=>1]);
$db->table('company_memberships')->insert(['user_id'=>$user->id,'tenant_id'=>1,'company_id'=>1]);
$departmentPolicy=$db->table('ir_policies')->where(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1])->first();$departmentPayload=json_decode($departmentPolicy->payload,true);$departmentPayload['members'][]=['user_id'=>$user->id,'department_ref'=>'OPER'];$db->table('ir_policies')->where('id',$departmentPolicy->id)->update(['payload'=>json_encode($departmentPayload)]); // Disposable configuration fixture only; submitted request snapshot is unchanged.
$grants=[1=>['purchasing_sourcing.prepare'],2=>['purchasing_sourcing.evaluate','purchasing_sourcing.propose'],$user->id=>['company.view','unit.view','purchasing_requisitions.view','purchasing_sourcing.evaluate','purchasing_sourcing.confirm']];
foreach($grants as $id=>$rights)foreach($rights as $right)$db->table('permission_grants')->insert(['user_id'=>$id,'tenant_id'=>1,'company_id'=>1,'unit_id'=>$right==='company.view'?null:1,'permission'=>$right,'created_at'=>now(),'updated_at'=>now()]);
foreach([1,2,3] as $n)$db->table('ss_suppliers')->insert(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'reference'=>'SYNTHETIC-'.$n,'payload'=>json_encode(['name'=>'Fornecedor sintético '.$n,'active'=>true,'blocked'=>false,'review_until'=>'2027-12-31','version'=>1,'synthetic_only'=>true]),'created_at'=>now()]);
file_put_contents($work.'/fixture.json',json_encode(['user_id'=>$user->id,'email'=>$user->email,'password'=>$private['password']]));
echo json_encode(['passed'=>true,'checks'=>$checks,'fixture_user_only_in_disposable_copy'=>true,'deployment'=>$applied]);
}elseif(($argv[1]??'')==='verify'){
$baseline=json_decode(file_get_contents($work.'/origin.json'),true);foreach(['request'=>'ir_requests','budget'=>'cb_budget_entries','consumption'=>'cb_budget_consumptions'] as $key=>$table)$check($baseline[$key]===$fingerprint($table),'Origin '.$key.' unchanged');
$check($db->table('ss_processes')->count()===1,'Exactly one sourcing process');$check($db->table('ss_commands')->count()===$db->table('ss_events')->count(),'One event per committed command');
$saved=$db->table('ss_processes')->first();$state=json_decode($saved->payload,true);$check($state['confirmed']!==null,'Independent award confirmed in isolated copy');
$before=$fingerprint('ss_events');$failed=false;try{$db->transaction(fn()=>$db->table('ss_events')->where('id',1)->update(['action'=>'tampered']));}catch(Throwable){$failed=true;}$check($failed&&$before===$fingerprint('ss_events'),'Database rejects event tampering');
$applied=json_decode(file_get_contents($work.'/applied.json'),true);file_put_contents($host.'/storage/framework/down','{}');$rolled=$deploy->rollback($applied['deployment_id'],'Isolated sourcing code recovery',true);
$check($state===json_decode($db->table('ss_processes')->first()->payload,true),'Code rollback preserves award data');
echo json_encode(['passed'=>true,'checks'=>$checks,'code_recovery'=>$rolled,'old_code_requires_schema_recovery'=>true]);
}else throw new RuntimeException('Use setup/verify');
}catch(Throwable $e){fwrite(STDERR,get_class($e).': '.$e->getMessage()."\n");exit(1);}
use Tempo\Purchasing\Delivery\Installation;
use Tempo\Purchasing\SgfSourcing\Schema;
$host = getenv('SOURCING_CLONE');
$root = getenv('SOURCING_REPO');
$work = getenv('SOURCING_WORK');
require $host.'/vendor/autoload.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
try {
$db = DB::connection();
$name = $db->selectOne('select current_database() as db')->db;
if (! preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D', $name) || $name !== getenv('SOURCING_DB') || ! str_contains(str_replace('\\', '/', $host), '/private/sourcing-') || str_replace('\\', '/', $app->basePath()) !== $host) {
throw new RuntimeException('Not an isolated sourcing copy');
}
$candidate = json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-candidate.json'), true, 32, JSON_THROW_ON_ERROR);
if (! class_exists(Schema::class)) {
require_once $candidate['directory'].'/integrations/sgf/sourcing/Schema.php';
}require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
$deploy = new CodeDeployment($host);
$checks = [];
$check = function ($ok, $label) use (&$checks) {
if (! $ok) {
throw new RuntimeException($label);
}$checks[] = $label;
};
$fingerprint = function (string $table) use ($db) {
return hash('sha256', json_encode($db->table($table)->orderBy('id')->get(), JSON_THROW_ON_ERROR));
};
if (($argv[1] ?? '') === 'setup') {
$baseline = ['request' => $fingerprint('ir_requests'), 'budget' => $fingerprint('cb_budget_entries'), 'consumption' => $fingerprint('cb_budget_consumptions'), 'grants_count' => $db->table('permission_grants')->count()];
file_put_contents($work.'/origin.json', json_encode($baseline));
$armed = true;
$db->listen(function ($query) use (&$armed) {
if ($armed && str_contains(strtolower($query->sql), 'create table "ss_events"')) {
$armed = false;
throw new RuntimeException('Injected migration failure');
}
});
try {
Schema::migrate($db, hash_file('sha256', $work.'/before.dump'), 'Isolated failure proof');
throw new RuntimeException('Expected failure');
} catch (RuntimeException $e) {
$check($e->getMessage() === 'Injected migration failure', 'Injected migration failure surfaced');
}
$check(! $db->getSchemaBuilder()->hasTable('ss_suppliers') && ! $db->table('sgc_installations')->where('module', 'sourcing')->exists(), 'Migration failure rolls back tables and catalogue');
$migration = Schema::migrate($db, hash_file('sha256', $work.'/before.dump'), 'Isolated sourcing proof');
$check($migration['prepared'], 'Additive migration accepted');
$check(Schema::migrate($db, hash_file('sha256', $work.'/before.dump'), 'Isolated replay')['replayed'], 'Migration replay is stable');
$old = json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'), true);
$next = json_decode(file_get_contents($candidate['directory'].'/manifest.json'), true);
$current = json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'), true);
try {
$deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
throw new RuntimeException('Unprepared plan accepted');
} catch (RuntimeException $e) {
$check(str_contains($e->getMessage(), 'migração própria'), 'Schema-changing update refuses missing migration receipt');
}
$receipt = ['from_manifest_sha256' => $current['manifest_sha256'], 'to_manifest_sha256' => $candidate['archive']['manifest_sha256'], 'host' => $host, 'schema_verified' => Schema::compatible($db), 'changes' => []];
foreach ($next['support_files'] as $file => $hash) {
if (($old['support_files'][$file] ?? null) !== $hash) {
$receipt['changes'][$file] = ['before' => $old['support_files'][$file] ?? null, 'after' => $hash];
}
}
file_put_contents($host.'/storage/framework/down', '{}');
$cli = new Process([PHP_BINARY, $candidate['directory'].'/scripts/sgf-sourcing-install.php', 'migrate', $host, Installation::target($db), $work.'/before.dump', hash_file('sha256', $work.'/before.dump'), 'Isolated migration CLI', $candidate['archive']['manifest_sha256']], $host, ['PG_RESTORE_BINARY' => 'C:/Program Files/PostgreSQL/17/bin/pg_restore.exe']);
$cli->mustRun();
$cliResult = json_decode($cli->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$check($cliResult['prepared'] && ! $cliResult['activated'] && ! $cliResult['rights_granted'], 'Packaged migration CLI produces exact receipt without activation or grants');
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
$applied = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Isolated sourcing update', true);
unlink($host.'/storage/framework/down');
file_put_contents($work.'/applied.json', json_encode($applied));
$target = Installation::target($db);
file_put_contents($host.'/config/purchasing-operational.php', '<?php return '.var_export(['enabled' => true, 'target' => $target, 'scopes' => ['1:1:1']], true).';');
file_put_contents($host.'/config/purchasing-sourcing.php', '<?php return ["enabled"=>true];');
$private = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json'), true);
$user = User::forceCreate(['name' => 'Synthetic isolated evaluator', 'email' => 'fixture-'.Str::uuid().'@example.invalid', 'password' => $private['password'], 'auth_version' => 1]);
$db->table('company_memberships')->insert(['user_id' => $user->id, 'tenant_id' => 1, 'company_id' => 1]);
$departmentPolicy = $db->table('ir_policies')->where(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1])->first();
$departmentPayload = json_decode($departmentPolicy->payload, true);
$departmentPayload['members'][] = ['user_id' => $user->id, 'department_ref' => 'OPER'];
$db->table('ir_policies')->where('id', $departmentPolicy->id)->update(['payload' => json_encode($departmentPayload)]); // Disposable configuration fixture only; submitted request snapshot is unchanged.
$grants = [1 => ['purchasing_sourcing.prepare'], 2 => ['purchasing_sourcing.evaluate', 'purchasing_sourcing.propose'], $user->id => ['company.view', 'unit.view', 'purchasing_requisitions.view', 'purchasing_sourcing.evaluate', 'purchasing_sourcing.confirm']];
foreach ($grants as $id => $rights) {
foreach ($rights as $right) {
$db->table('permission_grants')->insert(['user_id' => $id, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => $right === 'company.view' ? null : 1, 'permission' => $right, 'created_at' => now(), 'updated_at' => now()]);
}
}
foreach ([1, 2, 3] as $n) {
$db->table('ss_suppliers')->insert(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'reference' => 'SYNTHETIC-'.$n, 'payload' => json_encode(['name' => 'Fornecedor sintético '.$n, 'active' => true, 'blocked' => false, 'review_until' => '2027-12-31', 'version' => 1, 'synthetic_only' => true]), 'created_at' => now()]);
}
file_put_contents($work.'/fixture.json', json_encode(['user_id' => $user->id, 'email' => $user->email, 'password' => $private['password']]));
echo json_encode(['passed' => true, 'checks' => $checks, 'fixture_user_only_in_disposable_copy' => true, 'deployment' => $applied]);
} elseif (($argv[1] ?? '') === 'verify') {
$baseline = json_decode(file_get_contents($work.'/origin.json'), true);
foreach (['request' => 'ir_requests', 'budget' => 'cb_budget_entries', 'consumption' => 'cb_budget_consumptions'] as $key => $table) {
$check($baseline[$key] === $fingerprint($table), 'Origin '.$key.' unchanged');
}
$check($db->table('ss_processes')->count() === 1, 'Exactly one sourcing process');
$check($db->table('ss_commands')->count() === $db->table('ss_events')->count(), 'One event per committed command');
$saved = $db->table('ss_processes')->first();
$state = json_decode($saved->payload, true);
$check($state['confirmed'] !== null, 'Independent award confirmed in isolated copy');
$before = $fingerprint('ss_events');
$failed = false;
try {
$db->transaction(fn () => $db->table('ss_events')->where('id', 1)->update(['action' => 'tampered']));
} catch (Throwable) {
$failed = true;
}$check($failed && $before === $fingerprint('ss_events'), 'Database rejects event tampering');
$applied = json_decode(file_get_contents($work.'/applied.json'), true);
file_put_contents($host.'/storage/framework/down', '{}');
$rolled = $deploy->rollback($applied['deployment_id'], 'Isolated sourcing code recovery', true);
$check($state === json_decode($db->table('ss_processes')->first()->payload, true), 'Code rollback preserves award data');
echo json_encode(['passed' => true, 'checks' => $checks, 'code_recovery' => $rolled, 'old_code_requires_schema_recovery' => true]);
} else {
throw new RuntimeException('Use setup/verify');
}
} catch (Throwable $e) {
fwrite(STDERR,get_class($e).': '.$e->getMessage()."\n");
exit(1);
}
+331 -51
View File
@@ -1,55 +1,335 @@
import fs from 'node:fs';import assert from 'node:assert/strict';import crypto from 'node:crypto';import {spawn,spawnSync} from 'node:child_process';
const repo=process.env.SOURCING_REPO,work=process.env.SOURCING_WORK,host=process.env.SOURCING_CLONE,base='http://127.0.0.1:'+process.env.SOURCING_PORT,php='C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';
import fs from 'node:fs';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import { spawn, spawnSync } from 'node:child_process';
const repo = process.env.SOURCING_REPO,
work = process.env.SOURCING_WORK,
host = process.env.SOURCING_CLONE,
base = 'http://127.0.0.1:' + process.env.SOURCING_PORT,
php = 'C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';
assert(/^sgf_sourcing_test_[a-f0-9]{12}$/.test(process.env.SOURCING_DB));
const privateData=JSON.parse(fs.readFileSync('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json','utf8')),fixture=JSON.parse(fs.readFileSync(work+'/fixture.json','utf8'));
const clients={},checks=[];
for(const p of [...privateData.profiles,{role:'decisor',email:fixture.email}]){
const jar=new Map();let csrf='',token='';
const api=async(path,method='GET',body,status=200,override={})=>{
const r=await fetch(base+path,{method,headers:{Accept:'application/json','Content-Type':'application/json',Cookie:[...jar].map(([k,v])=>k+'='+v).join('; '),'X-CSRF-TOKEN':csrf,'X-SGF-Context':token,'X-Purchasing-Context':'procurement.internal',...override},...(body===undefined?{}:{body:JSON.stringify(body)})});
for(const cookie of r.headers.getSetCookie()){const pair=cookie.split(';')[0],at=pair.indexOf('=');jar.set(pair.slice(0,at),pair.slice(at+1));}const text=await r.text();let d;try{d=JSON.parse(text);}catch{d={message:text.slice(0,120)};}
assert.equal(r.status,status,`${p.role} ${path}: ${d.message??JSON.stringify(d.errors)}`);if(d.csrf)csrf=d.csrf;if(d.context?.token)token=d.context.token;return d;
};
await api('/api/session');await api('/api/login','POST',{email:p.email,password:privateData.password});await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:1,module_id:'purchasing'});clients[p.role]=api;
const privateData = JSON.parse(
fs.readFileSync(
'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json',
'utf8',
),
),
fixture = JSON.parse(fs.readFileSync(work + '/fixture.json', 'utf8'));
const clients = {},
checks = [];
for (const p of [
...privateData.profiles,
{ role: 'decisor', email: fixture.email },
]) {
const jar = new Map();
let csrf = '',
token = '';
const api = async (
path,
method = 'GET',
body,
status = 200,
override = {},
) => {
const r = await fetch(base + path, {
method,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Cookie: [...jar].map(([k, v]) => k + '=' + v).join('; '),
'X-CSRF-TOKEN': csrf,
'X-SGF-Context': token,
'X-Purchasing-Context': 'procurement.internal',
...override,
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
for (const cookie of r.headers.getSetCookie()) {
const pair = cookie.split(';')[0],
at = pair.indexOf('=');
jar.set(pair.slice(0, at), pair.slice(at + 1));
}
const text = await r.text();
let d;
try {
d = JSON.parse(text);
} catch {
d = { message: text.slice(0, 120) };
}
assert.equal(
r.status,
status,
`${p.role} ${path}: ${d.message ?? JSON.stringify(d.errors)}`,
);
if (d.csrf) csrf = d.csrf;
if (d.context?.token) token = d.context.token;
return d;
};
await api('/api/session');
await api('/api/login', 'POST', {
email: p.email,
password: privateData.password,
});
await api('/api/context', 'POST', {
tenant_id: 1,
company_id: 1,
unit_id: 1,
module_id: 'purchasing',
});
clients[p.role] = api;
}
const read=who=>clients[who]('/api/sourcing/1');
async function command(who,action,data,status=200){const current=await read(who);const payload={operation_key:crypto.randomUUID(),version:current.state.version,...(action==='propose'?{delivery_date:'2027-01-15',delivery_location:'Local de entrega exclusivamente sintético OPER'}:{}),...data};return {result:await clients[who]('/api/sourcing/1/'+action,'POST',payload,status),payload};}
const prep='preparador',rev='revisor',dec='decisor',consult='consulta';
for(const id of [1,2,3])await command(prep,'select',{supplier_id:id});
const quote=(id,price='100.00',days=5)=>({supplier_id:id,reference:'SYNTHETIC-Q-'+id,currency:'MZN',valid_until:'2027-12-31',delivery_days:days,payment_terms:'Pagamento sintético a 30 dias',items:[{line:0,unit_price:price}]});
for(const [id,amount] of [[1,'100.00'],[2,'110.00'],[3,'120.00']])await command(prep,'quote',{...quote(id,amount),delivery_days:'5',supplier_id:String(id)});
const qSaved=await read(prep);assert.equal(qSaved.request.id,1);assert.equal(qSaved.request.total_minor,10000);assert(!qSaved.comparison.ready);
for(const action of ['select','quote','evaluate','propose','confirm'])await clients[consult]('/api/sourcing/1/'+action,'POST',{},403);
await clients[consult]('/api/sourcing/1','GET',undefined,409,{'X-SGF-Context':'bad'});await clients[consult]('/api/sourcing/1','GET',undefined,403,{'X-Purchasing-Context':'procurement.third_party'});await clients[consult]('/api/sourcing/9999999','GET',undefined,404);
checks.push('Source request reused; three suppliers and quotes; consultation is read-only; context and direct access protected');
const evalData=async(id,who)=>{const s=await read(who);return {supplier_id:id,quote_revision:s.state.quotes[id].revision,quality:8,history:8,payment:8,no_conflict:true,reason:'Synthetic independent evaluation for isolated test.'};};
const read = (who) => clients[who]('/api/sourcing/1');
async function command(who, action, data, status = 200) {
const current = await read(who);
const payload = {
operation_key: crypto.randomUUID(),
version: current.state.version,
...(action === 'propose'
? {
delivery_date: '2027-01-15',
delivery_location:
'Local de entrega exclusivamente sintético OPER',
}
: {}),
...data,
};
return {
result: await clients[who](
'/api/sourcing/1/' + action,
'POST',
payload,
status,
),
payload,
};
}
const prep = 'preparador',
rev = 'revisor',
dec = 'decisor',
consult = 'consulta';
for (const id of [1, 2, 3]) await command(prep, 'select', { supplier_id: id });
const quote = (id, price = '100.00', days = 5) => ({
supplier_id: id,
reference: 'SYNTHETIC-Q-' + id,
currency: 'MZN',
valid_until: '2027-12-31',
delivery_days: days,
payment_terms: 'Pagamento sintético a 30 dias',
items: [{ line: 0, unit_price: price }],
});
for (const [id, amount] of [
[1, '100.00'],
[2, '110.00'],
[3, '120.00'],
])
await command(prep, 'quote', {
...quote(id, amount),
delivery_days: '5',
supplier_id: String(id),
});
const qSaved = await read(prep);
assert.equal(qSaved.request.id, 1);
assert.equal(qSaved.request.total_minor, 10000);
assert(!qSaved.comparison.ready);
for (const action of ['select', 'quote', 'evaluate', 'propose', 'confirm'])
await clients[consult]('/api/sourcing/1/' + action, 'POST', {}, 403);
await clients[consult]('/api/sourcing/1', 'GET', undefined, 409, {
'X-SGF-Context': 'bad',
});
await clients[consult]('/api/sourcing/1', 'GET', undefined, 403, {
'X-Purchasing-Context': 'procurement.third_party',
});
await clients[consult]('/api/sourcing/9999999', 'GET', undefined, 404);
checks.push(
'Source request reused; three suppliers and quotes; consultation is read-only; context and direct access protected',
);
const evalData = async (id, who) => {
const s = await read(who);
return {
supplier_id: id,
quote_revision: s.state.quotes[id].revision,
quality: 8,
history: 8,
payment: 8,
no_conflict: true,
reason: 'Synthetic independent evaluation for isolated test.',
};
};
// Real concurrent database sessions, not just serial requests to PHP's development server.
const initial=await read(rev),workerInput={actor_id:2,payload:{operation_key:crypto.randomUUID(),version:initial.state.version,...await evalData(1,rev)}};fs.writeFileSync(work+'/worker.json',JSON.stringify(workerInput));
const worker=(file='worker.json')=>new Promise((resolve,reject)=>{const p=spawn(php,[repo+'/tests/Support/sgf-sourcing-worker.php',work+'/'+file],{cwd:host,env:process.env,windowsHide:true});let out='',err='';p.stdout.on('data',d=>out+=d);p.stderr.on('data',d=>err+=d);p.on('exit',code=>{try{if(code!==0)throw Error(err);resolve(JSON.parse(out));}catch(e){reject(e);}});});
const workers=await Promise.all([worker(),worker()]);assert(workers.every(w=>w.status===200),JSON.stringify(workers));assert.deepEqual(workers[0].result,workers[1].result);checks.push('Concurrent identical commands return one committed version');
const raceVersion=(await read(rev)).state.version;
for(const [file,id] of [['race-a.json',2],['race-b.json',3]])fs.writeFileSync(work+'/'+file,JSON.stringify({actor_id:2,payload:{operation_key:crypto.randomUUID(),version:raceVersion,...await evalData(id,rev)}}));
const racing=await Promise.all([worker('race-a.json'),worker('race-b.json')]);assert.deepEqual(racing.map(r=>r.status).sort(),[200,409]);checks.push('Concurrent distinct commands use compare-and-swap; stale version refused');
for(const id of [1,2,3]){if(id!==1)await command(rev,'evaluate',await evalData(id,rev));await command(dec,'evaluate',await evalData(id,dec));}
let ready=await read(rev);assert(ready.comparison.ready);assert.deepEqual(ready.comparison.top_ids,[1]);
const proposed=await command(rev,'propose',{supplier_id:1,comparison_hash:ready.comparison.fingerprint,reason:'Best eligible synthetic quote with exact comparison version.'});
await clients[rev]('/api/sourcing/1/propose','POST',proposed.payload);checks.push('Proposal retry is idempotent');
const confirmData=async()=>{const d=await read(dec);return {proposal_index:d.state.proposals.length-1,comparison_hash:d.state.proposals.at(-1).comparison_hash,reason:'Independent confirmation of the preserved comparison.'};};
const initial = await read(rev),
workerInput = {
actor_id: 2,
payload: {
operation_key: crypto.randomUUID(),
version: initial.state.version,
...(await evalData(1, rev)),
},
};
fs.writeFileSync(work + '/worker.json', JSON.stringify(workerInput));
const worker = (file = 'worker.json') =>
new Promise((resolve, reject) => {
const p = spawn(
php,
[
repo + '/tests/Support/sgf-sourcing-worker.php',
work + '/' + file,
],
{ cwd: host, env: process.env, windowsHide: true },
);
let out = '',
err = '';
p.stdout.on('data', (d) => (out += d));
p.stderr.on('data', (d) => (err += d));
p.on('exit', (code) => {
try {
if (code !== 0) throw Error(err);
resolve(JSON.parse(out));
} catch (e) {
reject(e);
}
});
});
const workers = await Promise.all([worker(), worker()]);
assert(
workers.every((w) => w.status === 200),
JSON.stringify(workers),
);
assert.deepEqual(workers[0].result, workers[1].result);
checks.push('Concurrent identical commands return one committed version');
const raceVersion = (await read(rev)).state.version;
for (const [file, id] of [
['race-a.json', 2],
['race-b.json', 3],
])
fs.writeFileSync(
work + '/' + file,
JSON.stringify({
actor_id: 2,
payload: {
operation_key: crypto.randomUUID(),
version: raceVersion,
...(await evalData(id, rev)),
},
}),
);
const racing = await Promise.all([
worker('race-a.json'),
worker('race-b.json'),
]);
assert.deepEqual(racing.map((r) => r.status).sort(), [200, 409]);
checks.push(
'Concurrent distinct commands use compare-and-swap; stale version refused',
);
for (const id of [1, 2, 3]) {
if (id !== 1) await command(rev, 'evaluate', await evalData(id, rev));
await command(dec, 'evaluate', await evalData(id, dec));
}
let ready = await read(rev);
assert(ready.comparison.ready);
assert.deepEqual(ready.comparison.top_ids, [1]);
const proposed = await command(rev, 'propose', {
supplier_id: 1,
comparison_hash: ready.comparison.fingerprint,
reason: 'Best eligible synthetic quote with exact comparison version.',
});
await clients[rev]('/api/sourcing/1/propose', 'POST', proposed.payload);
checks.push('Proposal retry is idempotent');
const confirmData = async () => {
const d = await read(dec);
return {
proposal_index: d.state.proposals.length - 1,
comparison_hash: d.state.proposals.at(-1).comparison_hash,
reason: 'Independent confirmation of the preserved comparison.',
};
};
// The proposer does not possess confirm; independence is also tested in the shared core.
await command(rev,'confirm',await confirmData(),403);
await command(prep,'quote',quote(1,'100.00',6));await command(dec,'confirm',await confirmData(),409);checks.push('Changed quote blocks stale confirmation and invalidates evaluations');
function control(name){const r=spawnSync(php,[repo+'/tests/Support/sgf-sourcing-controls.php',name],{cwd:host,env:process.env,encoding:'utf8',windowsHide:true});assert.equal(r.status,0,r.stderr);}
for(const who of [rev,dec])await command(who,'evaluate',await evalData(1,who));
ready=await read(rev);await command(rev,'propose',{supplier_id:1,comparison_hash:ready.comparison.fingerprint,reason:'Re-proposed using current quote revision and comparison.'});
control('revoke-evaluate');await command(dec,'confirm',await confirmData(),409);control('restore-evaluate');
control('revoke-propose');await clients[rev]('/api/sourcing/1/propose','POST',proposed.payload,403);control('restore-propose');
control('revoke-view');await clients[consult]('/api/sourcing/1','GET',undefined,403);control('restore-view');checks.push('Revocation is effective for existing sessions, replay and qualified evaluations');
const beforeFail=await read(prep);control('fail-on');await command(prep,'quote',quote(2,'110.00',7),500);control('fail-off');const afterFail=await read(prep);assert.equal(afterFail.state.version,beforeFail.state.version);assert.equal(afterFail.history.length,beforeFail.history.length);checks.push('Injected failure after event rolls back state, event and receipt');
const confirmVersion=(await read(dec)).state.version,confirmation=await confirmData();
for(const file of ['confirm-a.json','confirm-b.json'])fs.writeFileSync(work+'/'+file,JSON.stringify({actor_id:fixture.user_id,action:'confirm',payload:{operation_key:crypto.randomUUID(),version:confirmVersion,...confirmation}}));
const confirmations=await Promise.all([worker('confirm-a.json'),worker('confirm-b.json')]);assert.deepEqual(confirmations.map(r=>r.status).sort(),[200,409]);
const confirmed=await read(consult);assert(confirmed.state.confirmed);assert.equal(confirmed.state.confirmed.confirmed_by,fixture.user_id);assert.equal(confirmed.state.confirmed.proposal.proposed_by,2);checks.push('Concurrent confirmations produce one immutable independent award');
await command(prep,'quote',quote(1),409);checks.push('Independent confirmation references exact comparison and final state is immutable');
const origin=await clients[consult]('/api/internal-requisitions/1');assert.equal(origin.record.version,3);assert.equal(origin.record.total_minor,10000);assert.equal(origin.history.length,3);checks.push('Accepted requisition read path remains intact');
await clients[consult]('/purchasing/sourcing/1');await clients[consult]('/purchasing/sourcing/screen.mjs');checks.push('Authenticated read-only screen and module script served through protected routes');
console.log(JSON.stringify({passed:true,checks,request_id:1,confirmed_only_in_isolated_copy:true,account_fixture_only_in_copy:true}));
await command(rev, 'confirm', await confirmData(), 403);
await command(prep, 'quote', quote(1, '100.00', 6));
await command(dec, 'confirm', await confirmData(), 409);
checks.push(
'Changed quote blocks stale confirmation and invalidates evaluations',
);
function control(name) {
const r = spawnSync(
php,
[repo + '/tests/Support/sgf-sourcing-controls.php', name],
{ cwd: host, env: process.env, encoding: 'utf8', windowsHide: true },
);
assert.equal(r.status, 0, r.stderr);
}
for (const who of [rev, dec])
await command(who, 'evaluate', await evalData(1, who));
ready = await read(rev);
await command(rev, 'propose', {
supplier_id: 1,
comparison_hash: ready.comparison.fingerprint,
reason: 'Re-proposed using current quote revision and comparison.',
});
control('revoke-evaluate');
await command(dec, 'confirm', await confirmData(), 409);
control('restore-evaluate');
control('revoke-propose');
await clients[rev]('/api/sourcing/1/propose', 'POST', proposed.payload, 403);
control('restore-propose');
control('revoke-view');
await clients[consult]('/api/sourcing/1', 'GET', undefined, 403);
control('restore-view');
checks.push(
'Revocation is effective for existing sessions, replay and qualified evaluations',
);
const beforeFail = await read(prep);
control('fail-on');
await command(prep, 'quote', quote(2, '110.00', 7), 500);
control('fail-off');
const afterFail = await read(prep);
assert.equal(afterFail.state.version, beforeFail.state.version);
assert.equal(afterFail.history.length, beforeFail.history.length);
checks.push('Injected failure after event rolls back state, event and receipt');
const confirmVersion = (await read(dec)).state.version,
confirmation = await confirmData();
for (const file of ['confirm-a.json', 'confirm-b.json'])
fs.writeFileSync(
work + '/' + file,
JSON.stringify({
actor_id: fixture.user_id,
action: 'confirm',
payload: {
operation_key: crypto.randomUUID(),
version: confirmVersion,
...confirmation,
},
}),
);
const confirmations = await Promise.all([
worker('confirm-a.json'),
worker('confirm-b.json'),
]);
assert.deepEqual(confirmations.map((r) => r.status).sort(), [200, 409]);
const confirmed = await read(consult);
assert(confirmed.state.confirmed);
assert.equal(confirmed.state.confirmed.confirmed_by, fixture.user_id);
assert.equal(confirmed.state.confirmed.proposal.proposed_by, 2);
checks.push('Concurrent confirmations produce one immutable independent award');
await command(prep, 'quote', quote(1), 409);
checks.push(
'Independent confirmation references exact comparison and final state is immutable',
);
const origin = await clients[consult]('/api/internal-requisitions/1');
assert.equal(origin.record.version, 3);
assert.equal(origin.record.total_minor, 10000);
assert.equal(origin.history.length, 3);
checks.push('Accepted requisition read path remains intact');
await clients[consult]('/purchasing/sourcing/1');
await clients[consult]('/purchasing/sourcing/screen.mjs');
checks.push(
'Authenticated read-only screen and module script served through protected routes',
);
console.log(
JSON.stringify({
passed: true,
checks,
request_id: 1,
confirmed_only_in_isolated_copy: true,
account_fixture_only_in_copy: true,
}),
);
+28 -11
View File
@@ -1,15 +1,32 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Shared\Context\CompanyContext;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Request;
$host=getenv('SOURCING_CLONE');require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
try{
$db=DB::connection();if(!preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D',$db->getDatabaseName()))throw new RuntimeException('Copy only');
$input=json_decode(file_get_contents($argv[1]),true,32,JSON_THROW_ON_ERROR);$user=User::findOrFail($input['actor_id']);
auth()->setUser($user);app(CompanyContext::class)->selectFor($user->id,1,1,1);
$request=Request::create('/api/sourcing/1/evaluate','POST');$request->headers->set('X-Purchasing-Context','procurement.internal');$app->instance('request',$request);
$result=(new Tempo\Purchasing\SgfSourcing\Workspace($user))->command(1,$input['action']??'evaluate',$input['payload']);
echo json_encode(['status'=>200,'result'=>$result]);
}catch(Throwable $e){echo json_encode(['status'=>$e instanceof Symfony\Component\HttpKernel\Exception\HttpExceptionInterface?$e->getStatusCode():($e instanceof Tempo\Purchasing\Internal\RequisitionFailure?$e->status:500),'message'=>$e->getMessage()]);}
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Tempo\Purchasing\Internal\RequisitionFailure;
use Tempo\Purchasing\SgfSourcing\Workspace;
$host = getenv('SOURCING_CLONE');
require $host.'/vendor/autoload.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
try {
$db = DB::connection();
if (! preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D', $db->getDatabaseName())) {
throw new RuntimeException('Copy only');
}
$input = json_decode(file_get_contents($argv[1]), true, 32, JSON_THROW_ON_ERROR);
$user = User::findOrFail($input['actor_id']);
auth()->setUser($user);
app(CompanyContext::class)->selectFor($user->id, 1, 1, 1);
$request = Request::create('/api/sourcing/1/evaluate', 'POST');
$request->headers->set('X-Purchasing-Context', 'procurement.internal');
$app->instance('request', $request);
$result = (new Workspace($user))->command(1, $input['action'] ?? 'evaluate', $input['payload']);
echo json_encode(['status' => 200, 'result' => $result]);
} catch (Throwable $e) {
echo json_encode(['status' => $e instanceof HttpExceptionInterface ? $e->getStatusCode() : ($e instanceof RequisitionFailure ? $e->status : 500), 'message' => $e->getMessage()]);
}
+10 -6
View File
@@ -37,7 +37,9 @@ function updateFixture(string $original, array $manifest, bool $native = false):
}
copy($original.'/composer.json', $root.'/composer.json');
copy($original.'/artisan', $root.'/artisan');
if (!is_dir($root.'/public')) mkdir($root.'/public', 0700, true);
if (! is_dir($root.'/public')) {
mkdir($root.'/public', 0700, true);
}
copy($original.'/public/index.php', $root.'/public/index.php');
} else {
foreach ($manifest['host_overlays'] as $file => $values) {
@@ -49,9 +51,11 @@ function updateFixture(string $original, array $manifest, bool $native = false):
// Frontend overlays are existing host files too; preserve their exact baseline
// in native copies without sharing mutable assets with the real destination.
foreach ($manifest['host_overlays'] as $file => $values) {
if (!is_file($root.'/'.$file)) {
if (!is_dir(dirname($root.'/'.$file))) mkdir(dirname($root.'/'.$file),0700,true);
copy($original.'/'.$file,$root.'/'.$file);
if (! is_file($root.'/'.$file)) {
if (! is_dir(dirname($root.'/'.$file))) {
mkdir(dirname($root.'/'.$file), 0700, true);
}
copy($original.'/'.$file, $root.'/'.$file);
}
}
foreach (['bootstrap/cache', 'packages/purchasing', 'storage/framework/views', 'storage/framework/cache', 'storage/framework/sessions', 'storage/logs'] as $directory) {
@@ -59,8 +63,8 @@ function updateFixture(string $original, array $manifest, bool $native = false):
mkdir($root.'/'.$directory, 0700, true);
}
}
copy($original.'/packages/purchasing/current.json',$root.'/packages/purchasing/current.json');
file_put_contents($root.'/storage/framework/down','{"status":503}');
copy($original.'/packages/purchasing/current.json', $root.'/packages/purchasing/current.json');
file_put_contents($root.'/storage/framework/down', '{"status":503}');
return $root;
}
+47 -9
View File
@@ -1,11 +1,49 @@
<?php
$file=realpath($argv[1]??'');$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));if(!$file||!$root||!str_starts_with($file,$root.DIRECTORY_SEPARATOR))throw new RuntimeException('Wrong native return worker input');
require getcwd().'/vendor/autoload.php';$app=require getcwd().'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
$db=Illuminate\Support\Facades\DB::connection();$i=$db->selectOne("SELECT current_database() AS db,current_user AS role,current_setting('cluster_name') AS cluster,inet_server_port() AS port");
if(!preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->db,$m)||$i->role!=='stock_receipt_qa_'.$m[1]||(int)$i->port!==55439||$i->cluster!=='sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'))throw new RuntimeException('Wrong worker QA database');
$p=json_decode(file_get_contents($file),true,512,JSON_THROW_ON_ERROR);$db->select("SELECT set_config('application_name',?,false)",[$p['application']]);$db->statement("SET lock_timeout='8s'");
$actor=App\Models\User::findOrFail($p['actor']);auth()->guard()->setUser($actor);config(['stock_returns.enabled'=>true]);
$action=$p['action']??'confirm';if(!in_array($action,['confirm','withdraw','reject'],true))throw new RuntimeException('Invalid worker action');
$input=['version'=>1,'reason'=>'Synthetic concurrent native warehouse decision.']+($action==='confirm'?['received_in_warehouse'=>true]:[]);
try{if($p['http']??false){$request=Illuminate\Http\Request::create('/api/stock-returns/'.$p['proposal'].'/'.$action,'POST',$input,[],[],['HTTP_ACCEPT'=>'application/json','HTTP_X_REQUESTED_WITH'=>'XMLHttpRequest']);$kernel=$app->make(Illuminate\Contracts\Http\Kernel::class);$response=$kernel->handle($request);$out=['status'=>$response->getStatusCode(),'result'=>json_decode($response->getContent(),true)];$kernel->terminate($request,$response);}else{$flow=app(App\Services\WarehouseReturns::class);$result=$action==='confirm'?$flow->confirm($actor,$p['proposal'],$input):$flow->close($actor,$p['proposal'],$input,$action==='withdraw'?'withdrawn':'rejected');$out=['status'=>200,'result'=>$result];}}catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$out=['status'=>$e->getStatusCode()];}
use App\Models\User;
use App\Services\WarehouseReturns;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
$file = realpath($argv[1] ?? '');
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
if (! $file || ! $root || ! str_starts_with($file, $root.DIRECTORY_SEPARATOR)) {
throw new RuntimeException('Wrong native return worker input');
}
require getcwd().'/vendor/autoload.php';
$app = require getcwd().'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$db = DB::connection();
$i = $db->selectOne("SELECT current_database() AS db,current_user AS role,current_setting('cluster_name') AS cluster,inet_server_port() AS port");
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->db, $m) || $i->role !== 'stock_receipt_qa_'.$m[1] || (int) $i->port !== 55439 || $i->cluster !== 'sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN')) {
throw new RuntimeException('Wrong worker QA database');
}
$p = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
$db->select("SELECT set_config('application_name',?,false)", [$p['application']]);
$db->statement("SET lock_timeout='8s'");
$actor = User::findOrFail($p['actor']);
auth()->guard()->setUser($actor);
config(['stock_returns.enabled' => true]);
$action = $p['action'] ?? 'confirm';
if (! in_array($action, ['confirm', 'withdraw', 'reject'], true)) {
throw new RuntimeException('Invalid worker action');
}
$input = ['version' => 1, 'reason' => 'Synthetic concurrent native warehouse decision.'] + ($action === 'confirm' ? ['received_in_warehouse' => true] : []);
try {
if ($p['http'] ?? false) {
$request = Request::create('/api/stock-returns/'.$p['proposal'].'/'.$action, 'POST', $input, [], [], ['HTTP_ACCEPT' => 'application/json', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
$response = $kernel->handle($request);
$out = ['status' => $response->getStatusCode(), 'result' => json_decode($response->getContent(), true)];
$kernel->terminate($request, $response);
} else {
$flow = app(WarehouseReturns::class);
$result = $action === 'confirm' ? $flow->confirm($actor, $p['proposal'], $input) : $flow->close($actor, $p['proposal'], $input, $action === 'withdraw' ? 'withdrawn' : 'rejected');
$out = ['status' => 200, 'result' => $result];
}
} catch (HttpExceptionInterface $e) {
$out = ['status' => $e->getStatusCode()];
}
file_put_contents($file.'.result',json_encode($out,JSON_THROW_ON_ERROR));
-1
View File
@@ -138,7 +138,6 @@ test('connection refusal is diagnosed without losing the last receiving checkpoi
}
});
test('oversized responses and timeouts stop the HTTP read without committing a page', function () {
foreach ([warehouseRemote('oversized', maxBytes: 1024), warehouseRemote('slow', timeout: 200)] as $source) {
try {
+119 -57
View File
@@ -7,35 +7,76 @@ import { spawnSync } from 'node:child_process';
const boundary = await fs.realpath('storage/framework/testing');
const verifier = path.resolve('scripts/verify-compras-release.php');
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
async function fixture(run) {
const root = await fs.mkdtemp(path.join(boundary, 'release-verifier-'));
try {
await fs.mkdir(path.join(root, 'public/build/assets'), { recursive: true });
const source = '<?php exit(99); // verification must never execute product code';
await fs.mkdir(path.join(root, 'public/build/assets'), {
recursive: true,
});
const source =
'<?php exit(99); // verification must never execute product code';
await fs.writeFile(path.join(root, 'main.php'), source);
await fs.writeFile(path.join(root, 'public/build/manifest.json'), '{}');
await fs.writeFile(path.join(root, 'public/build/assets/a.js'), 'test');
const manifest = { contract: 'compras.release.v1', product: 'compras', source_files: { 'main.php': hash(source) },
frontend: { manifest_sha256: hash('{}'), files: { 'assets/a.js': hash('test') } }, components: [] };
const manifest = {
contract: 'compras.release.v1',
product: 'compras',
source_files: { 'main.php': hash(source) },
frontend: {
manifest_sha256: hash('{}'),
files: { 'assets/a.js': hash('test') },
},
components: [],
};
for (const [index, list] of [true, false].entries()) {
const component = path.join(root, 'component-'+index);
const component = path.join(root, 'component-' + index);
await fs.mkdir(component);
await fs.writeFile(path.join(component, 'writer.php'), 'not executable');
const files = list ? [{ file: 'writer.php', sha256: hash('not executable') }] : { 'writer.php': hash('not executable') };
await fs.writeFile(
path.join(component, 'writer.php'),
'not executable',
);
const files = list
? [{ file: 'writer.php', sha256: hash('not executable') }]
: { 'writer.php': hash('not executable') };
const bytes = JSON.stringify({ files });
await fs.writeFile(path.join(component, 'manifest.json'), bytes);
manifest.components.push({ setting: 'COMPONENT_'+index, manifest_sha256: hash(bytes) });
manifest.components.push({
setting: 'COMPONENT_' + index,
manifest_sha256: hash(bytes),
});
}
await fs.writeFile(path.join(root, '.env'), 'COMPRAS_RUNTIME_ENABLED="true"\n'+manifest.components.map((entry, index) => entry.setting+'="'+path.join(root, 'component-'+index).replaceAll('\\', '/')+'"').join('\n'));
await fs.writeFile(
path.join(root, '.env'),
'COMPRAS_RUNTIME_ENABLED="true"\n' +
manifest.components
.map(
(entry, index) =>
entry.setting +
'="' +
path
.join(root, 'component-' + index)
.replaceAll('\\', '/') +
'"',
)
.join('\n'),
);
const save = async () => {
delete manifest.release_id;
manifest.release_id = 'compras-'+hash(JSON.stringify(manifest)).slice(0, 16);
await fs.writeFile(path.join(root, 'compras-release.json'), JSON.stringify(manifest));
manifest.release_id =
'compras-' + hash(JSON.stringify(manifest)).slice(0, 16);
await fs.writeFile(
path.join(root, 'compras-release.json'),
JSON.stringify(manifest),
);
};
await save();
const verify = (...args) => spawnSync('php', [verifier, root, ...args], { encoding: 'utf8', windowsHide: true });
const verify = (...args) =>
spawnSync('php', [verifier, root, ...args], {
encoding: 'utf8',
windowsHide: true,
});
await run({ root, manifest, save, verify });
} finally {
const resolved = await fs.realpath(root);
@@ -45,47 +86,68 @@ async function fixture(run) {
}
}
test('verifies one source, compiled assets and both component manifest formats without executing product code', () => fixture(async ({ verify }) => {
const result = verify('--installed');
assert.equal(result.status, 0, result.stderr);
assert.equal(JSON.parse(result.stdout).installed_components, 2);
}));
test('rejects changed source', () => fixture(async ({ root, verify }) => {
await fs.writeFile(path.join(root, 'main.php'), 'changed');
assert.notEqual(verify().status, 0);
}));
test('accepts Git LF and Windows CRLF as the same source without accepting changed text', () => fixture(async ({ root, manifest, save, verify }) => {
manifest.source_eol = 'lf';
manifest.source_files['main.php'] = hash('first\nsecond\n');
await save();
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nsecond\r\n');
assert.equal(verify().status, 0);
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nchanged\r\n');
assert.notEqual(verify().status, 0);
}));
test('rejects a changed compiled asset', () => fixture(async ({ root, verify }) => {
await fs.writeFile(path.join(root, 'public/build/assets/a.js'), 'changed');
assert.notEqual(verify('--compiled').status, 0);
}));
test('rejects a changed component', () => fixture(async ({ root, verify }) => {
await fs.writeFile(path.join(root, 'component-1/writer.php'), 'changed');
assert.notEqual(verify('--installed').status, 0);
}));
test('rejects forged identity', () => fixture(async ({ root, manifest, verify }) => {
manifest.release_id = 'compras-forged';
await fs.writeFile(path.join(root, 'compras-release.json'), JSON.stringify(manifest));
assert.notEqual(verify().status, 0);
}));
test('rejects path traversal even with a recomputed descriptor', () => fixture(async ({ manifest, save, verify }) => {
manifest.source_files['../outside.php'] = hash('test');
await save();
assert.notEqual(verify().status, 0);
}));
test('rejects disabled installation', () => fixture(async ({ root, verify }) => {
await fs.writeFile(path.join(root, '.env'), 'COMPRAS_RUNTIME_ENABLED=false');
assert.notEqual(verify('--installed').status, 0);
}));
test('rejects a missing descriptor', () => fixture(async ({ root, verify }) => {
await fs.unlink(path.join(root, 'compras-release.json'));
assert.notEqual(verify().status, 0);
}));
test('verifies one source, compiled assets and both component manifest formats without executing product code', () =>
fixture(async ({ verify }) => {
const result = verify('--installed');
assert.equal(result.status, 0, result.stderr);
assert.equal(JSON.parse(result.stdout).installed_components, 2);
}));
test('rejects changed source', () =>
fixture(async ({ root, verify }) => {
await fs.writeFile(path.join(root, 'main.php'), 'changed');
assert.notEqual(verify().status, 0);
}));
test('accepts Git LF and Windows CRLF as the same source without accepting changed text', () =>
fixture(async ({ root, manifest, save, verify }) => {
manifest.source_eol = 'lf';
manifest.source_files['main.php'] = hash('first\nsecond\n');
await save();
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nsecond\r\n');
assert.equal(verify().status, 0);
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nchanged\r\n');
assert.notEqual(verify().status, 0);
}));
test('rejects a changed compiled asset', () =>
fixture(async ({ root, verify }) => {
await fs.writeFile(
path.join(root, 'public/build/assets/a.js'),
'changed',
);
assert.notEqual(verify('--compiled').status, 0);
}));
test('rejects a changed component', () =>
fixture(async ({ root, verify }) => {
await fs.writeFile(
path.join(root, 'component-1/writer.php'),
'changed',
);
assert.notEqual(verify('--installed').status, 0);
}));
test('rejects forged identity', () =>
fixture(async ({ root, manifest, verify }) => {
manifest.release_id = 'compras-forged';
await fs.writeFile(
path.join(root, 'compras-release.json'),
JSON.stringify(manifest),
);
assert.notEqual(verify().status, 0);
}));
test('rejects path traversal even with a recomputed descriptor', () =>
fixture(async ({ manifest, save, verify }) => {
manifest.source_files['../outside.php'] = hash('test');
await save();
assert.notEqual(verify().status, 0);
}));
test('rejects disabled installation', () =>
fixture(async ({ root, verify }) => {
await fs.writeFile(
path.join(root, '.env'),
'COMPRAS_RUNTIME_ENABLED=false',
);
assert.notEqual(verify('--installed').status, 0);
}));
test('rejects a missing descriptor', () =>
fixture(async ({ root, verify }) => {
await fs.unlink(path.join(root, 'compras-release.json'));
assert.notEqual(verify().status, 0);
}));
@@ -13,17 +13,41 @@ test('legacy transfer adds links once and preserves other capabilities', () => {
});
test('current host keeps its stricter feature guard and complete empty state', () => {
const guard = "const requisitions=unit!==null&&context.purchasing?.internal_requisitions===true&&can('purchasing_requisitions.view',unit);";
const source = legacy.replace('\n', '\n'+guard+'\n').replace('<div className="actions">', '<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições</a>}').replace('!budget&&!payables&&', '!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&');
const guard =
"const requisitions=unit!==null&&context.purchasing?.internal_requisitions===true&&can('purchasing_requisitions.view',unit);";
const source = legacy
.replace('\n', '\n' + guard + '\n')
.replace(
'<div className="actions">',
'<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições</a>}',
)
.replace(
'!budget&&!payables&&',
'!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&',
);
const output = purchasingHomeOverlay(source);
assert.ok(output.includes(guard));
assert.equal((output.match(/const requisitions=/g)??[]).length, 1);
assert.equal((output.match(/href="\/purchasing\/internal-requisitions"/g)??[]).length, 1);
assert.ok(output.includes('!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&'));
assert.equal((output.match(/const requisitions=/g) ?? []).length, 1);
assert.equal(
(output.match(/href="\/purchasing\/internal-requisitions"/g) ?? [])
.length,
1,
);
assert.ok(
output.includes(
'!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&',
),
);
assert.equal(purchasingHomeOverlay(output), output);
});
test('unknown or duplicate declarations refuse preparation', () => {
assert.throws(() => purchasingHomeOverlay('const requisitions=true;\n'+legacy));
assert.throws(() => purchasingHomeOverlay('const requisitions=true;const requisitions=false;'+legacy));
assert.throws(() =>
purchasingHomeOverlay('const requisitions=true;\n' + legacy),
);
assert.throws(() =>
purchasingHomeOverlay(
'const requisitions=true;const requisitions=false;' + legacy,
),
);
});