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
@@ -5,9 +5,11 @@ namespace App\Http\Controllers;
use App\Enums\PurchasingRole; use App\Enums\PurchasingRole;
use App\Models\User; use App\Models\User;
use App\Services\OrganizationAccess; use App\Services\OrganizationAccess;
use Illuminate\Http\Request; use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse; use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Tempo\Inventory\InventoryReadSession;
final class CommonStockReadController extends Controller final class CommonStockReadController extends Controller
{ {
@@ -23,7 +25,9 @@ final class CommonStockReadController extends Controller
$filters = ['view' => $d['view'] ?? 'balances', 'search' => $d['search'] ?? '', 'warehouse_id' => isset($d['warehouse_id']) ? (int) $d['warehouse_id'] : null, $filters = ['view' => $d['view'] ?? 'balances', 'search' => $d['search'] ?? '', 'warehouse_id' => isset($d['warehouse_id']) ? (int) $d['warehouse_id'] : null,
'page' => (int) ($d['page'] ?? 1), 'per_page' => (int) ($d['per_page'] ?? 25)]; 'page' => (int) ($d['page'] ?? 1), 'per_page' => (int) ($d['per_page'] ?? 25)];
$binding = config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id); $binding = config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id);
if(!$binding)return response()->json(['status'=>'unavailable','message'=>'Fonte autorizada de stock ainda não ligada a este contexto.'],503)->header('Cache-Control','no-store'); if (! $binding) {
return response()->json(['status' => 'unavailable', 'message' => 'Fonte autorizada de stock ainda não ligada a este contexto.'], 503)->header('Cache-Control', 'no-store');
}
abort_unless(app()->environment('testing') && DB::connection()->getDriverName() === 'pgsql', 403); abort_unless(app()->environment('testing') && DB::connection()->getDriverName() === 'pgsql', 403);
$identity = DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster"); $identity = DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D', $identity->name, $m) abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D', $identity->name, $m)
@@ -32,7 +36,9 @@ final class CommonStockReadController extends Controller
&& $identity->cluster === 'sgf_modular_regression_'.config('stock_read.qa_run'), 403); && $identity->cluster === 'sgf_modular_regression_'.config('stock_read.qa_run'), 403);
abort_unless(preg_match('/^sgf_stock_read_[a-f0-9]{12}$/D', $binding['schema'] ?? '') && ($binding['append_only'] ?? false) === true abort_unless(preg_match('/^sgf_stock_read_[a-f0-9]{12}$/D', $binding['schema'] ?? '') && ($binding['append_only'] ?? false) === true
&& ($binding['source_tenant_id'] ?? null) === (int) $user->tenant_id, 503, 'Fonte de stock incompatível.'); && ($binding['source_tenant_id'] ?? null) === (int) $user->tenant_id, 503, 'Fonte de stock incompatível.');
if($filters['warehouse_id']!==null)abort_unless(in_array($filters['warehouse_id'],$binding['warehouse_ids'],true),403); if ($filters['warehouse_id'] !== null) {
abort_unless(in_array($filters['warehouse_id'], $binding['warehouse_ids'], true), 403);
}
$root = base_path('packages/inventory-read/releases/0.1.0'); $root = base_path('packages/inventory-read/releases/0.1.0');
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false; $bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
abort_unless(is_string($bytes) && hash_equals(config('stock_read.package_manifest_sha256'), hash('sha256', $bytes)), 503, 'Pacote de consulta incompatível.'); abort_unless(is_string($bytes) && hash_equals(config('stock_read.package_manifest_sha256'), hash('sha256', $bytes)), 503, 'Pacote de consulta incompatível.');
@@ -43,11 +49,16 @@ final class CommonStockReadController extends Controller
} }
require_once $root.'/bootstrap.php'; require_once $root.'/bootstrap.php';
$fingerprint = hash('sha256', json_encode(['compras', $user->tenant_id, $user->id, $request->session()->get('work_context'), $binding, array_diff_key($filters, ['page' => true])], JSON_THROW_ON_ERROR)); $fingerprint = hash('sha256', json_encode(['compras', $user->tenant_id, $user->id, $request->session()->get('work_context'), $binding, array_diff_key($filters, ['page' => true])], JSON_THROW_ON_ERROR));
try { $result=(new \Tempo\Inventory\InventoryReadSession(DB::connection()))->read($binding,$fingerprint,$filters,$d['snapshot']??null); } try {
catch(\Illuminate\Database\QueryException $e){ $result = (new InventoryReadSession(DB::connection()))->read($binding, $fingerprint, $filters, $d['snapshot'] ?? null);
if(!in_array($e->errorInfo[0]??null,['42P01','42703','42883','57014'],true))throw $e; } catch (QueryException $e) {
if (! in_array($e->errorInfo[0] ?? null, ['42P01', '42703', '42883', '57014'], true)) {
throw $e;
}
return response()->json(['status' => 'unavailable', 'message' => 'A fonte de stock está indisponível ou incompatível. Actualize a consulta mais tarde.'], 503)->header('Cache-Control','no-store'); return response()->json(['status' => 'unavailable', 'message' => 'A fonte de stock está indisponível ou incompatível. Actualize a consulta mais tarde.'], 503)->header('Cache-Control','no-store');
} }
return response()->json($result)->header('Cache-Control','no-store'); return response()->json($result)->header('Cache-Control','no-store');
} }
} }
@@ -46,7 +46,14 @@ final class WarehouseReturnController extends Controller
private function response(callable $run, bool $readOnly = false): JsonResponse private function response(callable $run, bool $readOnly = false): JsonResponse
{ {
try { try {
$result=$readOnly?DB::transaction(function()use($run){if(DB::getDriverName()==='pgsql'&&DB::transactionLevel()===1)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');return $run();}):$run(); $result = $readOnly ? DB::transaction(function () use ($run) {
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
}
return $run();
}) : $run();
return response()->json($result)->header('Cache-Control', 'no-store'); return response()->json($result)->header('Cache-Control', 'no-store');
} catch (QueryException $e) { } catch (QueryException $e) {
if (($e->errorInfo[0] ?? null) === '55P03') { if (($e->errorInfo[0] ?? null) === '55P03') {
@@ -85,10 +92,23 @@ final class WarehouseReturnController extends Controller
return $this->response(fn () => $flow->confirm($this->actor($r), $id, $d)); return $this->response(fn () => $flow->confirm($this->actor($r), $id, $d));
} }
public function withdraw(Request $r,int $id,WarehouseReturns $flow): JsonResponse {return $this->close($r,$id,$flow,'withdrawn');}
public function reject(Request $r,int $id,WarehouseReturns $flow): JsonResponse {return $this->close($r,$id,$flow,'rejected');} public function withdraw(Request $r, int $id, WarehouseReturns $flow): JsonResponse
{
return $this->close($r, $id, $flow, 'withdrawn');
}
public function reject(Request $r, int $id, WarehouseReturns $flow): JsonResponse
{
return $this->close($r, $id, $flow, 'rejected');
}
private function close(Request $r, int $id, WarehouseReturns $flow, string $state): JsonResponse private function close(Request $r, int $id, WarehouseReturns $flow, string $state): JsonResponse
{ {
$d=$r->validate(['version'=>'required|integer|min:1','reason'=>'required|string|min:10|max:1000']);abort_if(array_diff(array_keys($r->all()),array_keys($d))!==[],422);$d['version']=(int)$d['version'];return $this->response(fn()=>$flow->close($this->actor($r),$id,$d,$state)); $d = $r->validate(['version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:1000']);
abort_if(array_diff(array_keys($r->all()), array_keys($d)) !== [], 422);
$d['version'] = (int) $d['version'];
return $this->response(fn () => $flow->close($this->actor($r), $id, $d, $state));
} }
} }
+2 -1
View File
@@ -4,13 +4,14 @@ namespace App\Models;
use App\Models\Concerns\BelongsToTenant; use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/** /**
* @property array<string,mixed> $data * @property array<string,mixed> $data
* @property array<string,mixed> $snapshot * @property array<string,mixed> $snapshot
* @property int $version * @property int $version
* @property string $record_key * @property string $record_key
* @property \Illuminate\Support\Carbon $created_at * @property Carbon $created_at
*/ */
class SupplyRecord extends Model class SupplyRecord extends Model
{ {
-1
View File
@@ -13,7 +13,6 @@ use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Validator;
use Tempo\Finance\GeneralLedger\LedgerSchema; use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\GeneralLedger\Receivables; use Tempo\Finance\GeneralLedger\Receivables;
use Tempo\Finance\GeneralLedger\ReceivablesSchema;
/** Native actor/catalogue adapter. All customer financial writes belong to the common core. */ /** Native actor/catalogue adapter. All customer financial writes belong to the common core. */
final class CustomerSales final class CustomerSales
+29 -12
View File
@@ -5,38 +5,55 @@ namespace App\Services;
use App\Models\User; use App\Models\User;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
use LogicException; use LogicException;
use Tempo\SgcInvoiceClient\InvoiceClient;
/** Prepared gateway only; no event listener, route, scheduled job or automatic transmission. */ /** Prepared gateway only; no event listener, route, scheduled job or automatic transmission. */
final class SgfInvoiceGateway final class SgfInvoiceGateway
{ {
public function clientFor(User $actor,string $connection): \Tempo\SgcInvoiceClient\InvoiceClient public function clientFor(User $actor, string $connection): InvoiceClient
{ {
if(config('sgf_invoice.enabled')!==true)throw new LogicException('SGF invoice gateway disabled.'); if (config('sgf_invoice.enabled') !== true) {
$all=config('sgf_invoice.connections',[]);$c=$all[$connection]??null; throw new LogicException('SGF invoice gateway disabled.');
}
$all = config('sgf_invoice.connections', []);
$c = $all[$connection] ?? null;
abort_unless(is_array($c) && ($c['enabled'] ?? false) === true && auth()->id() === $actor->id, 403); abort_unless(is_array($c) && ($c['enabled'] ?? false) === true && auth()->id() === $actor->id, 403);
$current = User::where('tenant_id', $actor->tenant_id)->findOrFail($actor->id); $current = User::where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
abort_unless(($c['source_scope']['tenant_id'] ?? null) === $current->tenant_id && $current->hasFunctions(['finance']) abort_unless(($c['source_scope']['tenant_id'] ?? null) === $current->tenant_id && $current->hasFunctions(['finance'])
&& ! app(OrganizationAccess::class)->maintenanceOnly($current), 403); && ! app(OrganizationAccess::class)->maintenanceOnly($current), 403);
$path=config('sgf_invoice.client_package');$pin=config('sgf_invoice.client_package_sha256'); $path = config('sgf_invoice.client_package');
$pin = config('sgf_invoice.client_package_sha256');
$actual = is_string($path) && is_file($path) ? hash_file('sha256', $path) : false; $actual = is_string($path) && is_file($path) ? hash_file('sha256', $path) : false;
if (! is_string($path) || is_link($path) || ! is_file($path) || ! is_string($pin) || ! preg_match('/^[a-f0-9]{64}$/D', $pin) if (! is_string($path) || is_link($path) || ! is_file($path) || ! is_string($pin) || ! preg_match('/^[a-f0-9]{64}$/D', $pin)
||!is_string($actual)||!hash_equals($pin,$actual))throw new LogicException('Verified client package required.'); || ! is_string($actual) || ! hash_equals($pin, $actual)) {
if(class_exists(\Tempo\SgcInvoiceClient\InvoiceClient::class,false)){ throw new LogicException('Verified client package required.');
$loaded=(new \ReflectionClass(\Tempo\SgcInvoiceClient\InvoiceClient::class))->getFileName(); }
if (class_exists(InvoiceClient::class, false)) {
$loaded = (new \ReflectionClass(InvoiceClient::class))->getFileName();
$loadedHash = is_string($loaded) && is_file($loaded) ? hash_file('sha256', $loaded) : false; $loadedHash = is_string($loaded) && is_file($loaded) ? hash_file('sha256', $loaded) : false;
if(!is_string($loadedHash)||!hash_equals($pin,$loadedHash))throw new LogicException('Client version changed; restart separately.'); if (! is_string($loadedHash) || ! hash_equals($pin, $loadedHash)) {
}else require_once $path; throw new LogicException('Client version changed; restart separately.');
}
} else {
require_once $path;
}
$configurationHash = hash('sha256', json_encode($c, JSON_THROW_ON_ERROR)); $configurationHash = hash('sha256', json_encode($c, JSON_THROW_ON_ERROR));
return new \Tempo\SgcInvoiceClient\InvoiceClient($c['client_id'],$c['token'],$c['context_version'],$c['source_scope'],$c['target_scope'],
return new InvoiceClient($c['client_id'], $c['token'], $c['context_version'], $c['source_scope'], $c['target_scope'],
function (string $method, string $url, array $headers, ?array $body) use ($actor, $connection, $configurationHash): array { function (string $method, string $url, array $headers, ?array $body) use ($actor, $connection, $configurationHash): array {
// Recheck the originating person's authority immediately before every network operation. // Recheck the originating person's authority immediately before every network operation.
$now = config('sgf_invoice.connections', [])[$connection] ?? null; $now = config('sgf_invoice.connections', [])[$connection] ?? null;
if (config('sgf_invoice.enabled') !== true || ! is_array($now) || ! hash_equals($configurationHash, hash('sha256', json_encode($now, JSON_THROW_ON_ERROR))) if (config('sgf_invoice.enabled') !== true || ! is_array($now) || ! hash_equals($configurationHash, hash('sha256', json_encode($now, JSON_THROW_ON_ERROR)))
||auth()->id()!==$actor->id)return ['status'=>403,'json'=>null]; || auth()->id() !== $actor->id) {
return ['status' => 403, 'json' => null];
}
$current = User::where('tenant_id', $actor->tenant_id)->find($actor->id); $current = User::where('tenant_id', $actor->tenant_id)->find($actor->id);
if(!$current||!$current->hasFunctions(['finance'])||app(OrganizationAccess::class)->maintenanceOnly($current))return ['status'=>403,'json'=>null]; if (! $current || ! $current->hasFunctions(['finance']) || app(OrganizationAccess::class)->maintenanceOnly($current)) {
return ['status' => 403, 'json' => null];
}
$http = Http::withHeaders($headers)->acceptJson()->asJson()->withoutRedirecting()->connectTimeout(3)->timeout(15); $http = Http::withHeaders($headers)->acceptJson()->asJson()->withoutRedirecting()->connectTimeout(3)->timeout(15);
$response = $method === 'GET' ? $http->get($url) : $http->post($url, $body); $response = $method === 'GET' ? $http->get($url) : $http->post($url, $body);
return ['status' => $response->status(), 'json' => $response->json()]; return ['status' => $response->status(), 'json' => $response->json()];
}, $c['origin']); }, $c['origin']);
} }
+16 -5
View File
@@ -1,24 +1,35 @@
<?php <?php
namespace App\Services; namespace App\Services;
use App\Enums\PurchasingRole; use App\Enums\PurchasingRole;
use App\Models\User; use App\Models\User;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Tempo\Inventory\IssueMovementWriter;
final class StockIssueMovement final class StockIssueMovement
{ {
public function for(User $actor): \Tempo\Inventory\IssueMovementWriter public function for(User $actor): IssueMovementWriter
{ {
$root = base_path('packages/inventory-issue/releases/0.1.0'); $root = base_path('packages/inventory-issue/releases/0.1.0');
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false; $bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
if(!is_string($bytes)||!hash_equals('3c24d9e9fb99bfbb274077495c3a42ddb7eccab06b5c6a956cd739b2bc9b56f0',hash('sha256',$bytes)))throw new \LogicException('Pacote de saída incompatível.'); if (! is_string($bytes) || ! hash_equals('3c24d9e9fb99bfbb274077495c3a42ddb7eccab06b5c6a956cd739b2bc9b56f0', hash('sha256', $bytes))) {
throw new \LogicException('Pacote de saída incompatível.');
}
$m = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR); $m = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
foreach (['bootstrap.php', 'src/IssueMovementWriter.php'] as $f) { foreach (['bootstrap.php', 'src/IssueMovementWriter.php'] as $f) {
$actual = is_file($root.'/'.$f) ? hash_file('sha256', $root.'/'.$f) : false; $actual = is_file($root.'/'.$f) ? hash_file('sha256', $root.'/'.$f) : false;
if(!is_string($actual)||!hash_equals($m['files'][$f]??'',$actual))throw new \LogicException('Pacote de saída alterado.'); if (! is_string($actual) || ! hash_equals($m['files'][$f] ?? '', $actual)) {
throw new \LogicException('Pacote de saída alterado.');
}
} }
require_once $root.'/bootstrap.php'; require_once $root.'/bootstrap.php';
$schema=match(DB::connection()->getDriverName()){'pgsql'=>'public','sqlite'=>'main','mysql','mariadb'=>DB::connection()->getDatabaseName(),default=>throw new \LogicException('Driver não suportado.')}; $schema = match (DB::connection()->getDriverName()) {
return new \Tempo\Inventory\IssueMovementWriter(DB::connection(),$schema,(int)$actor->tenant_id,(int)$actor->id,function()use($actor){app(CurrentActor::class)->lock($actor,[PurchasingRole::Warehouse]);}); 'pgsql' => 'public','sqlite' => 'main','mysql','mariadb' => DB::connection()->getDatabaseName(),default => throw new \LogicException('Driver não suportado.')
};
return new IssueMovementWriter(DB::connection(), $schema, (int) $actor->tenant_id, (int) $actor->id, function () use ($actor) {
app(CurrentActor::class)->lock($actor, [PurchasingRole::Warehouse]);
});
} }
} }
+1
View File
@@ -9,6 +9,7 @@ use Tempo\Inventory\DeliveryReturnWriter;
final class WarehouseReturnMovement final class WarehouseReturnMovement
{ {
public const MANIFEST_SHA256 = '2850a4f5cb678acfe3a9dbc7a7d62eb233bc72722ad0de374681c2679c90557c'; public const MANIFEST_SHA256 = '2850a4f5cb678acfe3a9dbc7a7d62eb233bc72722ad0de374681c2679c90557c';
private function fileHash(string $file): string private function fileHash(string $file): string
{ {
$hash = is_file($file) ? hash_file('sha256', $file) : false; $hash = is_file($file) ? hash_file('sha256', $file) : false;
+16 -4
View File
@@ -173,6 +173,7 @@ return null;
$this->request($old->snapshot['source']['request_id']); $this->request($old->snapshot['source']['request_id']);
$state = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $old->record_key)->orderByDesc('version')->value('state'); $state = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $old->record_key)->orderByDesc('version')->value('state');
return ['id' => $old->id, 'state' => $state, 'impact' => $this->impact($old->snapshot['source']), 'replayed' => true]; return ['id' => $old->id, 'state' => $state, 'impact' => $this->impact($old->snapshot['source']), 'replayed' => true];
} }
$source = $this->source($actor, $d); $source = $this->source($actor, $d);
@@ -200,6 +201,7 @@ return null;
$done = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $p->record_key)->where('version', 2)->first(); $done = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $p->record_key)->where('version', 2)->first();
if ($done) { if ($done) {
abort_unless($done->state === 'confirmed', 409, 'Proposta encerrada sem movimento. Prepare uma nova proposta se necessário.'); abort_unless($done->state === 'confirmed', 409, 'Proposta encerrada sem movimento. Prepare uma nova proposta se necessário.');
return ['id' => $done->id, 'movement_id' => $done->data['movement_id'], 'replayed' => true]; return ['id' => $done->id, 'movement_id' => $done->data['movement_id'], 'replayed' => true];
} }
abort_unless($d['version'] === 1 && $d['received_in_warehouse'] === true, 422, 'Confirme a recepção física da versão conferida.'); abort_unless($d['version'] === 1 && $d['received_in_warehouse'] === true, 422, 'Confirme a recepção física da versão conferida.');
@@ -224,15 +226,25 @@ return null;
public function close(User $actor, int $id, array $d, string $state): array public function close(User $actor, int $id, array $d, string $state): array
{ {
abort_unless(in_array($state, ['withdrawn', 'rejected'], true), 422); abort_unless(in_array($state, ['withdrawn', 'rejected'], true), 422);
$action=$state==='withdrawn'?'prepare':'confirm';$this->authorize($actor,$action); $action = $state === 'withdrawn' ? 'prepare' : 'confirm';
$this->authorize($actor, $action);
return DB::transaction(function () use ($actor, $id, $d, $state, $action) { return DB::transaction(function () use ($actor, $id, $d, $state, $action) {
$actor=$this->lock($actor,$action);$p=SupplyRecord::query()->where('kind','warehouse_return')->where('version',1)->lockForUpdate()->findOrFail($id);$this->request($p->snapshot['source']['request_id']); $actor = $this->lock($actor, $action);
$p = SupplyRecord::query()->where('kind', 'warehouse_return')->where('version', 1)->lockForUpdate()->findOrFail($id);
$this->request($p->snapshot['source']['request_id']);
abort_unless($state === 'withdrawn' ? $p->created_by === $actor->id : $p->created_by !== $actor->id, 403, 'Retirada pertence ao preparador; recusa exige conferência independente.'); abort_unless($state === 'withdrawn' ? $p->created_by === $actor->id : $p->created_by !== $actor->id, 403, 'Retirada pertence ao preparador; recusa exige conferência independente.');
$done = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $p->record_key)->where('version', 2)->first(); $done = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $p->record_key)->where('version', 2)->first();
if($done){abort_unless($done->state===$state,409,'A proposta já tem outra decisão terminal.');return ['id'=>$done->id,'state'=>$done->state,'replayed'=>true];} if ($done) {
abort_unless($d['version']===1,409,'Versão de proposta desactualizada.');$book=app(StockWorkflow::class)->balance($p->stock_item_id,$p->warehouse_id); abort_unless($done->state === $state, 409, 'A proposta já tem outra decisão terminal.');
return ['id' => $done->id, 'state' => $done->state, 'replayed' => true];
}
abort_unless($d['version'] === 1, 409, 'Versão de proposta desactualizada.');
$book = app(StockWorkflow::class)->balance($p->stock_item_id, $p->warehouse_id);
$closed = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'warehouse_return', 'record_key' => $p->record_key, 'version' => 2, 'state' => $state, 'stock_item_id' => $p->stock_item_id, 'warehouse_id' => $p->warehouse_id, 'created_by' => $actor->id, 'data' => ['prepared_id' => $p->id, 'action' => $state, 'reason' => $d['reason']], 'snapshot' => ['source' => $p->snapshot['source'], 'before' => $book['quantity'], 'after' => $book['quantity'], 'preparer_id' => $p->created_by], 'reason' => $d['reason'], 'operation_key' => (string) Str::uuid(), 'input_hash' => $this->hash($d + ['action' => $state]), 'created_at' => now()]); $closed = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'warehouse_return', 'record_key' => $p->record_key, 'version' => 2, 'state' => $state, 'stock_item_id' => $p->stock_item_id, 'warehouse_id' => $p->warehouse_id, 'created_by' => $actor->id, 'data' => ['prepared_id' => $p->id, 'action' => $state, 'reason' => $d['reason']], 'snapshot' => ['source' => $p->snapshot['source'], 'before' => $book['quantity'], 'after' => $book['quantity'], 'preparer_id' => $p->created_by], 'reason' => $d['reason'], 'operation_key' => (string) Str::uuid(), 'input_hash' => $this->hash($d + ['action' => $state]), 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'warehouse_return.'.$state, null, null, ['record_id' => $closed->id, 'declaration_id' => $p->id, 'reason' => $d['reason'], 'before' => $book['quantity'], 'after' => $book['quantity'], 'physical_effect' => 0]); app(RequisitionWorkflow::class)->audit($actor, 'warehouse_return.'.$state, null, null, ['record_id' => $closed->id, 'declaration_id' => $p->id, 'reason' => $d['reason'], 'before' => $book['quantity'], 'after' => $book['quantity'], 'physical_effect' => 0]);
return ['id' => $closed->id, 'state' => $state, 'replayed' => false]; return ['id' => $closed->id, 'state' => $state, 'replayed' => false];
}); });
} }
+1
View File
@@ -1,4 +1,5 @@
<?php <?php
return [ return [
'synthetic_sources' => [], 'synthetic_sources' => [],
'qa_run' => env('SGF_ISOLATED_REGRESSION_RUN'), 'qa_run' => env('SGF_ISOLATED_REGRESSION_RUN'),
@@ -2,45 +2,81 @@
use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\{DB,Schema}; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration { return new class extends Migration
{
public function up(): void public function up(): void
{ {
if(!in_array(DB::getDriverName(),['pgsql','sqlite'],true))throw new LogicException('SGF dispatch schema requires PostgreSQL/SQLite.'); if (! in_array(DB::getDriverName(), ['pgsql', 'sqlite'], true)) {
throw new LogicException('SGF dispatch schema requires PostgreSQL/SQLite.');
}
Schema::create('sgf_invoice_dispatches', function (Blueprint $t) { Schema::create('sgf_invoice_dispatches', function (Blueprint $t) {
$t->id();$t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete(); $t->id();
$t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete();
$t->foreignId('supplier_id')->constrained('suppliers')->restrictOnDelete(); $t->foreignId('supplier_id')->constrained('suppliers')->restrictOnDelete();
$t->string('reference',120);$t->string('number',100);$t->string('connection_id',64);$t->string('mapping_id',64); $t->string('reference', 120);
$t->json('mapping_snapshot');$t->char('mapping_hash',64);$t->json('document');$t->text('reason'); $t->string('number', 100);
$t->unsignedInteger('source_version')->default(1);$t->unsignedInteger('version')->default(1); $t->string('connection_id', 64);
$t->string('phase',32)->default('draft');$t->boolean('ever_sending')->default(false); $t->string('mapping_id', 64);
$t->text('state_ciphertext')->nullable();$t->char('approval_hash',64)->nullable(); $t->json('mapping_snapshot');
$t->foreignId('preview_actor_id')->nullable()->constrained('users')->restrictOnDelete();$t->char('source_context_hash',64)->nullable(); $t->char('mapping_hash', 64);
$t->uuid('operation_key')->nullable()->unique();$t->uuid('lease_id')->nullable();$t->timestamp('lease_until')->nullable(); $t->json('document');
$t->json('receipt')->nullable();$t->foreignId('created_by')->constrained('users')->restrictOnDelete();$t->timestamps(); $t->text('reason');
$t->unique(['tenant_id','reference']);$t->unique(['tenant_id','supplier_id','number'],'sgf_dispatch_document_unique'); $t->unsignedInteger('source_version')->default(1);
$t->index(['tenant_id','id']);$t->index(['tenant_id','phase','id']); $t->unsignedInteger('version')->default(1);
$t->string('phase', 32)->default('draft');
$t->boolean('ever_sending')->default(false);
$t->text('state_ciphertext')->nullable();
$t->char('approval_hash', 64)->nullable();
$t->foreignId('preview_actor_id')->nullable()->constrained('users')->restrictOnDelete();
$t->char('source_context_hash', 64)->nullable();
$t->uuid('operation_key')->nullable()->unique();
$t->uuid('lease_id')->nullable();
$t->timestamp('lease_until')->nullable();
$t->json('receipt')->nullable();
$t->foreignId('created_by')->constrained('users')->restrictOnDelete();
$t->timestamps();
$t->unique(['tenant_id', 'reference']);
$t->unique(['tenant_id', 'supplier_id', 'number'], 'sgf_dispatch_document_unique');
$t->index(['tenant_id', 'id']);
$t->index(['tenant_id', 'phase', 'id']);
}); });
Schema::create('sgf_invoice_dispatch_events', function (Blueprint $t) { Schema::create('sgf_invoice_dispatch_events', function (Blueprint $t) {
$t->id();$t->foreignId('dispatch_id')->constrained('sgf_invoice_dispatches')->restrictOnDelete(); $t->id();
$t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete();$t->unsignedInteger('version'); $t->foreignId('dispatch_id')->constrained('sgf_invoice_dispatches')->restrictOnDelete();
$t->foreignId('actor_id')->constrained('users')->restrictOnDelete();$t->string('action',40);$t->text('reason'); $t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete();
$t->json('before_state')->nullable();$t->json('after_state');$t->timestamp('created_at'); $t->unsignedInteger('version');
$t->unique(['dispatch_id','version']);$t->index(['tenant_id','dispatch_id','id']); $t->foreignId('actor_id')->constrained('users')->restrictOnDelete();
$t->string('action', 40);
$t->text('reason');
$t->json('before_state')->nullable();
$t->json('after_state');
$t->timestamp('created_at');
$t->unique(['dispatch_id', 'version']);
$t->index(['tenant_id', 'dispatch_id', 'id']);
}); });
if (DB::getDriverName() === 'pgsql') { if (DB::getDriverName() === 'pgsql') {
DB::unprepared("CREATE FUNCTION sgf_dispatch_preserve() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN RAISE EXCEPTION 'Preserve SGF dispatch audit/history'; END; \$\$;"); DB::unprepared("CREATE FUNCTION sgf_dispatch_preserve() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN RAISE EXCEPTION 'Preserve SGF dispatch audit/history'; END; \$\$;");
DB::unprepared('CREATE TRIGGER sgf_dispatch_event_immutable BEFORE UPDATE OR DELETE ON sgf_invoice_dispatch_events FOR EACH ROW EXECUTE FUNCTION sgf_dispatch_preserve()'); DB::unprepared('CREATE TRIGGER sgf_dispatch_event_immutable BEFORE UPDATE OR DELETE ON sgf_invoice_dispatch_events FOR EACH ROW EXECUTE FUNCTION sgf_dispatch_preserve()');
DB::unprepared('CREATE TRIGGER sgf_dispatch_no_delete BEFORE DELETE ON sgf_invoice_dispatches FOR EACH ROW EXECUTE FUNCTION sgf_dispatch_preserve()'); DB::unprepared('CREATE TRIGGER sgf_dispatch_no_delete BEFORE DELETE ON sgf_invoice_dispatches FOR EACH ROW EXECUTE FUNCTION sgf_dispatch_preserve()');
} elseif (DB::getDriverName() === 'sqlite') { } elseif (DB::getDriverName() === 'sqlite') {
foreach(['UPDATE','DELETE']as$action)DB::unprepared("CREATE TRIGGER sgf_dispatch_events_".strtolower($action)." BEFORE $action ON sgf_invoice_dispatch_events BEGIN SELECT RAISE(ABORT,'Preserve SGF dispatch audit'); END"); foreach (['UPDATE', 'DELETE'] as $action) {
DB::unprepared("CREATE TRIGGER sgf_dispatch_no_delete BEFORE DELETE ON sgf_invoice_dispatches BEGIN SELECT RAISE(ABORT,'Preserve SGF dispatch history'); END"); DB::unprepared('CREATE TRIGGER sgf_dispatch_events_'.strtolower($action)." BEFORE $action ON sgf_invoice_dispatch_events BEGIN SELECT RAISE(ABORT,'Preserve SGF dispatch audit'); END");
}else throw new LogicException('SGF dispatch schema validated only for PostgreSQL/SQLite.');
} }
DB::unprepared("CREATE TRIGGER sgf_dispatch_no_delete BEFORE DELETE ON sgf_invoice_dispatches BEGIN SELECT RAISE(ABORT,'Preserve SGF dispatch history'); END");
} else {
throw new LogicException('SGF dispatch schema validated only for PostgreSQL/SQLite.');
}
}
public function down(): void public function down(): void
{ {
Schema::dropIfExists('sgf_invoice_dispatch_events');Schema::dropIfExists('sgf_invoice_dispatches'); Schema::dropIfExists('sgf_invoice_dispatch_events');
if(DB::getDriverName()==='pgsql')DB::unprepared('DROP FUNCTION IF EXISTS sgf_dispatch_preserve()'); Schema::dropIfExists('sgf_invoice_dispatches');
if (DB::getDriverName() === 'pgsql') {
DB::unprepared('DROP FUNCTION IF EXISTS sgf_dispatch_preserve()');
}
} }
}; };
+1 -1
View File
@@ -1,4 +1,4 @@
{ {
"preset": "laravel", "preset": "laravel",
"exclude": ["packages"] "exclude": ["packages", "integrations"]
} }
+2 -1
View File
@@ -117,7 +117,8 @@ export default function Clients({
const data = new FormData(event.currentTarget); const data = new FormData(event.currentTarget);
const search = data.get('search'); const search = data.get('search');
router.get('/empresa/clientes', { router.get('/empresa/clientes', {
search: typeof search === 'string' ? search : '', search:
typeof search === 'string' ? search : '',
}); });
}} }}
> >
+530 -38
View File
@@ -3,49 +3,541 @@ import { useEffect, useRef, useState, type FormEvent } from 'react';
import { PageTitle, Panel, controlClass } from '@/components/procurement'; import { PageTitle, Panel, controlClass } from '@/components/procurement';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
type Impact = { physical_before: string; physical_after: string; return_quantity_milli: string; not_returned_before: string; not_returned_after: string; original_movement_id: number; item: { code: string; name: string; unit: string }; warehouse: { code: string; name: string } }; type Impact = {
physical_before: string;
physical_after: string;
return_quantity_milli: string;
not_returned_before: string;
not_returned_after: string;
original_movement_id: number;
item: { code: string; name: string; unit: string };
warehouse: { code: string; name: string };
};
type Page = { page: number; last_page: number; total: number }; type Page = { page: number; last_page: number; total: number };
type Row = { id: number; prepared_id: number; version: number; state: string; reason: string; evidence: string; preparer_id: number; author_id: number; created_at: string; impact: Impact }; type Row = {
type Option = { delivery_event_id: number; line_index: number; delivered_milli: string; item: Impact['item'] }; id: number;
const milli = (value: string) => { const q = BigInt(value); return `${q / 1000n},${(q % 1000n).toString().padStart(3, '0')}`; }; prepared_id: number;
const states: Record<string,string> = {prepared:'Por confirmar',confirmed:'Confirmada',withdrawn:'Retirada',rejected:'Recusada'}; version: number;
state: string;
reason: string;
evidence: string;
preparer_id: number;
author_id: number;
created_at: string;
impact: Impact;
};
type Option = {
delivery_event_id: number;
line_index: number;
delivered_milli: string;
item: Impact['item'];
};
const milli = (value: string) => {
const q = BigInt(value);
return `${q / 1000n},${(q % 1000n).toString().padStart(3, '0')}`;
};
const states: Record<string, string> = {
prepared: 'Por confirmar',
confirmed: 'Confirmada',
withdrawn: 'Retirada',
rejected: 'Recusada',
};
export function WarehouseReturnImpact({ impact: p }: { impact: Impact }) { export function WarehouseReturnImpact({ impact: p }: { impact: Impact }) {
return <p>Stock físico: {milli(p.physical_before)} → {milli(p.physical_after)}. Devolução: {milli(p.return_quantity_milli)} {p.item.unit}. Entrega ainda não devolvida: {milli(p.not_returned_before)} → {milli(p.not_returned_after)}. {p.item.code} · {p.warehouse.code} · Saída original #{p.original_movement_id}.</p>; return (
<p>
Stock físico: {milli(p.physical_before)} → {milli(p.physical_after)}
. Devolução: {milli(p.return_quantity_milli)} {p.item.unit}. Entrega
ainda não devolvida: {milli(p.not_returned_before)} →{' '}
{milli(p.not_returned_after)}. {p.item.code} · {p.warehouse.code} ·
Saída original #{p.original_movement_id}.
</p>
);
} }
async function api<T>(url: string, body?: object, signal?: AbortSignal): Promise<T> { async function api<T>(
const token = document.cookie.split('; ').find((c) => c.startsWith('XSRF-TOKEN='))?.slice(11); url: string,
const response = await fetch(url, { method: body ? 'POST' : 'GET', credentials: 'same-origin', signal, headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', ...(token ? { 'X-XSRF-TOKEN': decodeURIComponent(token) } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) }); body?: object,
const result = await response.json(); if (!response.ok) throw new Error(result.errors ? Object.values(result.errors).flat().join(' ') : result.message || `Pedido recusado (${response.status})`); return result; signal?: AbortSignal,
): Promise<T> {
const token = document.cookie
.split('; ')
.find((c) => c.startsWith('XSRF-TOKEN='))
?.slice(11);
const response = await fetch(url, {
method: body ? 'POST' : 'GET',
credentials: 'same-origin',
signal,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
...(token ? { 'X-XSRF-TOKEN': decodeURIComponent(token) } : {}),
},
...(body ? { body: JSON.stringify(body) } : {}),
});
const result = await response.json();
if (!response.ok)
throw new Error(
result.errors
? Object.values(result.errors).flat().join(' ')
: result.message || `Pedido recusado (${response.status})`,
);
return result;
} }
export default function WarehouseReturns({ requestId, actorId, canPrepare, canConfirm, canWithdraw=false }: { requestId: number | null; actorId: number; canPrepare: boolean; canConfirm: boolean; canWithdraw?:boolean }) { export default function WarehouseReturns({
const [history, setHistory] = useState<{ rows: Row[]; pagination: Page } | null>(null), [sources, setSources] = useState<{ options: Option[]; pagination: Page } | null>(null); requestId,
const [page, setPage] = useState(1), [sourcePage, setSourcePage] = useState(1), [state, setState] = useState('all'), [reload, setReload] = useState(0), [error, setError] = useState(''), [busy, setBusy] = useState(false), [preview, setPreview] = useState<{ id: number; impact: Impact; state?:string } | null>(null); actorId,
const generation = useRef(0), command = useRef<{ data: string; key: string } | null>(null); canPrepare,
useEffect(() => { const n = ++generation.current, abort = new AbortController(); setHistory(null); setSources(null); setError(''); canConfirm,
Promise.all([api<{ rows: Row[]; pagination: Page }>(`/api/stock-returns?page=${page}&state=${state}`, undefined, abort.signal), requestId ? api<{ options: Option[]; pagination: Page }>(`/api/stock-returns/sources?request_id=${requestId}&source_page=${sourcePage}`, undefined, abort.signal) : Promise.resolve(null)]) canWithdraw = false,
.then(([h, s]) => { if (n === generation.current) { setHistory(h); setSources(s); } }).catch((e: Error) => { if (!abort.signal.aborted && n === generation.current) setError(e.message); }); }: {
return () => { generation.current++; abort.abort(); }; requestId: number | null;
actorId: number;
canPrepare: boolean;
canConfirm: boolean;
canWithdraw?: boolean;
}) {
const [history, setHistory] = useState<{
rows: Row[];
pagination: Page;
} | null>(null),
[sources, setSources] = useState<{
options: Option[];
pagination: Page;
} | null>(null);
const [page, setPage] = useState(1),
[sourcePage, setSourcePage] = useState(1),
[state, setState] = useState('all'),
[reload, setReload] = useState(0),
[error, setError] = useState(''),
[busy, setBusy] = useState(false),
[preview, setPreview] = useState<{
id: number;
impact: Impact;
state?: string;
} | null>(null);
const generation = useRef(0),
command = useRef<{ data: string; key: string } | null>(null);
useEffect(() => {
const n = ++generation.current,
abort = new AbortController();
setHistory(null);
setSources(null);
setError('');
Promise.all([
api<{ rows: Row[]; pagination: Page }>(
`/api/stock-returns?page=${page}&state=${state}`,
undefined,
abort.signal,
),
requestId
? api<{ options: Option[]; pagination: Page }>(
`/api/stock-returns/sources?request_id=${requestId}&source_page=${sourcePage}`,
undefined,
abort.signal,
)
: Promise.resolve(null),
])
.then(([h, s]) => {
if (n === generation.current) {
setHistory(h);
setSources(s);
}
})
.catch((e: Error) => {
if (!abort.signal.aborted && n === generation.current)
setError(e.message);
});
return () => {
generation.current++;
abort.abort();
};
}, [requestId, actorId, page, sourcePage, state, reload]); }, [requestId, actorId, page, sourcePage, state, reload]);
useEffect(() => { setPreview(null); command.current = null; setPage(1); setSourcePage(1); }, [requestId, actorId]); useEffect(() => {
async function prepare(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const n = generation.current; setBusy(true); setError(''); const fields = Object.fromEntries(new FormData(e.currentTarget)), choice = sources?.options.find((o) => `${o.delivery_event_id}:${o.line_index}` === fields.source); setPreview(null);
if (!choice) { setError('Seleccione uma entrega recebida.'); setBusy(false); return; } command.current = null;
const body = { delivery_event_id: choice.delivery_event_id, line_index: choice.line_index, quantity: fields.quantity, declared_unused: fields.declared_unused === 'on', reason: fields.reason, evidence: fields.evidence }, data = JSON.stringify(body); setPage(1);
if (command.current?.data !== data) command.current = { data, key: crypto.randomUUID() }; setSourcePage(1);
try { const p = await api<{ id: number; impact: Impact }>('/api/stock-returns/prepare', { ...body, operation_key: command.current.key }); if (n === generation.current) { setPreview(p); setReload((x) => x + 1); } } catch (err) { if (n === generation.current) setError((err as Error).message); } finally { setBusy(false); } }, [requestId, actorId]);
async function prepare(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const n = generation.current;
setBusy(true);
setError('');
const fields = Object.fromEntries(new FormData(e.currentTarget)),
choice = sources?.options.find(
(o) =>
`${o.delivery_event_id}:${o.line_index}` === fields.source,
);
if (!choice) {
setError('Seleccione uma entrega recebida.');
setBusy(false);
return;
} }
async function confirm(e: FormEvent<HTMLFormElement>, row: Row) { e.preventDefault(); const n = generation.current; setBusy(true); setError(''); const fields = Object.fromEntries(new FormData(e.currentTarget)); const body = {
try { await api(`/api/stock-returns/${row.prepared_id}/confirm`, { version: 1, received_in_warehouse: fields.received_in_warehouse === 'on', reason: fields.reason }); if (n === generation.current) { setPreview(null); setReload((x) => x + 1); } } catch (err) { if (n === generation.current) setError((err as Error).message); } finally { setBusy(false); } delivery_event_id: choice.delivery_event_id,
line_index: choice.line_index,
quantity: fields.quantity,
declared_unused: fields.declared_unused === 'on',
reason: fields.reason,
evidence: fields.evidence,
},
data = JSON.stringify(body);
if (command.current?.data !== data)
command.current = { data, key: crypto.randomUUID() };
try {
const p = await api<{ id: number; impact: Impact }>(
'/api/stock-returns/prepare',
{ ...body, operation_key: command.current.key },
);
if (n === generation.current) {
setPreview(p);
setReload((x) => x + 1);
} }
async function close(e:FormEvent<HTMLFormElement>,row:Row,action:'withdraw'|'reject'){e.preventDefault();const n=generation.current;setBusy(true);setError('');const fields=Object.fromEntries(new FormData(e.currentTarget));try{await api(`/api/stock-returns/${row.prepared_id}/${action}`,{version:1,reason:fields.reason});if(n===generation.current){setPreview(null);setReload(x=>x+1);}}catch(err){if(n===generation.current)setError((err as Error).message);}finally{setBusy(false);}} } catch (err) {
return <><Head title="Devoluções de excedentes" /><div className="space-y-6 p-6"><PageTitle eyebrow="Armazém · Material não consumido" title="Devoluções de excedentes" description="Declaração do destinatário e recepção física independente. O original permanece intacto." /> if (n === generation.current) setError((err as Error).message);
<Link href={requestId ? `/stock/requisicoes/${requestId}` : '/dashboard'}>{requestId ? 'Consultar a requisição de origem' : 'Voltar ao Painel Inicial'}</Link> } finally {
{error && <p role="alert">{error}</p>}<Button disabled={busy} onClick={() => setReload((x) => x + 1)}>Actualizar</Button> setBusy(false);
{canPrepare && requestId && sources && <Panel title={`Entregas recebidas · RA-${requestId}`}><form onSubmit={prepare} className="space-y-4"><label>Entrega e linha de origem<select name="source" className={controlClass} defaultValue="" required><option value="" disabled>Seleccione a origem</option>{sources.options.map((o) => <option key={`${o.delivery_event_id}:${o.line_index}`} value={`${o.delivery_event_id}:${o.line_index}`}>Entrega #{o.delivery_event_id} · {o.item.code} · {o.item.name} · entregue {milli(o.delivered_milli)} {o.item.unit}</option>)}</select></label> }
<label>Quantidade efectivamente devolvida<input name="quantity" className={controlClass} pattern="[0-9]{1,6}(\.[0-9]{1,3})?" required /></label><label>Evidência de excedente e entrega física<textarea name="evidence" className={controlClass} minLength={10} maxLength={1000} required /></label><label>Fundamento<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required /></label><label><input type="checkbox" name="declared_unused" required />Declaro que esta quantidade não foi consumida</label><Button disabled={busy}>Conferir impacto</Button></form> }
<Button disabled={sourcePage <= 1 || busy} onClick={() => setSourcePage((x) => x - 1)}>Entregas anteriores</Button><Button disabled={sourcePage >= sources.pagination.last_page || busy} onClick={() => setSourcePage((x) => x + 1)}>Entregas seguintes</Button></Panel>} async function confirm(e: FormEvent<HTMLFormElement>, row: Row) {
{preview && <Panel title={`Prévia da proposta #${preview.id}`}><WarehouseReturnImpact impact={preview.impact} /><p>{preview.state&&preview.state!=='prepared'?`Decisão já registada: ${states[preview.state]??'Arquivada'}. Sem novo efeito.`:'A preparação não altera stock. Aguarda outra identidade autorizada.'}</p></Panel>} e.preventDefault();
<Panel title="Histórico e decisões"><label>Estado<select className={controlClass} value={state} onChange={(e) => { setState(e.target.value); setPage(1); }}><option value="all">Todos</option><option value="prepared">Por confirmar</option><option value="confirmed">Confirmados</option><option value="withdrawn">Retirados</option><option value="rejected">Recusados</option></select></label> const n = generation.current;
{!history ? <p role="status">A consultar decisões…</p> : <>{history.rows.map((r) => <article key={r.id} className="space-y-3 border-b py-4"><h3>Proposta #{r.prepared_id} · v{r.version} · {states[r.state]??'Estado arquivado'}</h3><p>{r.state==="confirmed"?"Entrada efectuada":r.state==="prepared"?"Impacto proposto":"Prévia arquivada, não executada"}</p><WarehouseReturnImpact impact={r.impact} /><p>{r.reason} · Evidência: {r.evidence}</p><p>Preparação #{r.preparer_id} · Autor desta versão #{r.author_id} · {r.created_at}</p> setBusy(true);
{r.state === 'prepared' && canConfirm && r.preparer_id !== actorId && <form onSubmit={(e) => confirm(e, r)}><label>Fundamento da recepção<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required /></label><label><input type="checkbox" name="received_in_warehouse" required />Recebi fisicamente esta quantidade no armazém indicado</label><Button disabled={busy}>Confirmar entrada conferida</Button></form>}<>{r.state==="prepared"&&canWithdraw&&r.preparer_id===actorId&&<details><summary>Retirar proposta sem movimento</summary><form onSubmit={e=>close(e,r,"withdraw")}><label>Fundamento da retirada<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required/></label><Button disabled={busy}>Retirar proposta</Button></form></details>}{r.state==="prepared"&&canConfirm&&r.preparer_id!==actorId&&<details><summary>Recusar recepção sem movimento</summary><form onSubmit={e=>close(e,r,"reject")}><label>Fundamento da recusa<textarea name="reason" className={controlClass} minLength={10} maxLength={1000} required/></label><Button disabled={busy}>Recusar conferência</Button></form></details>}</></article>)}{!history.rows.length && <p>Sem decisões neste filtro.</p>}<Button disabled={page <= 1 || busy} onClick={() => setPage((x) => x - 1)}>Anterior</Button><Button disabled={page >= history.pagination.last_page || busy} onClick={() => setPage((x) => x + 1)}>Seguinte</Button></>} setError('');
</Panel></div></>; const fields = Object.fromEntries(new FormData(e.currentTarget));
try {
await api(`/api/stock-returns/${row.prepared_id}/confirm`, {
version: 1,
received_in_warehouse: fields.received_in_warehouse === 'on',
reason: fields.reason,
});
if (n === generation.current) {
setPreview(null);
setReload((x) => x + 1);
}
} catch (err) {
if (n === generation.current) setError((err as Error).message);
} finally {
setBusy(false);
}
}
async function close(
e: FormEvent<HTMLFormElement>,
row: Row,
action: 'withdraw' | 'reject',
) {
e.preventDefault();
const n = generation.current;
setBusy(true);
setError('');
const fields = Object.fromEntries(new FormData(e.currentTarget));
try {
await api(`/api/stock-returns/${row.prepared_id}/${action}`, {
version: 1,
reason: fields.reason,
});
if (n === generation.current) {
setPreview(null);
setReload((x) => x + 1);
}
} catch (err) {
if (n === generation.current) setError((err as Error).message);
} finally {
setBusy(false);
}
}
return (
<>
<Head title="Devoluções de excedentes" />
<div className="space-y-6 p-6">
<PageTitle
eyebrow="Armazém · Material não consumido"
title="Devoluções de excedentes"
description="Declaração do destinatário e recepção física independente. O original permanece intacto."
/>
<Link
href={
requestId
? `/stock/requisicoes/${requestId}`
: '/dashboard'
}
>
{requestId
? 'Consultar a requisição de origem'
: 'Voltar ao Painel Inicial'}
</Link>
{error && <p role="alert">{error}</p>}
<Button disabled={busy} onClick={() => setReload((x) => x + 1)}>
Actualizar
</Button>
{canPrepare && requestId && sources && (
<Panel title={`Entregas recebidas · RA-${requestId}`}>
<form onSubmit={prepare} className="space-y-4">
<label>
Entrega e linha de origem
<select
name="source"
className={controlClass}
defaultValue=""
required
>
<option value="" disabled>
Seleccione a origem
</option>
{sources.options.map((o) => (
<option
key={`${o.delivery_event_id}:${o.line_index}`}
value={`${o.delivery_event_id}:${o.line_index}`}
>
Entrega #{o.delivery_event_id} ·{' '}
{o.item.code} · {o.item.name} ·
entregue {milli(o.delivered_milli)}{' '}
{o.item.unit}
</option>
))}
</select>
</label>
<label>
Quantidade efectivamente devolvida
<input
name="quantity"
className={controlClass}
pattern="[0-9]{1,6}(\.[0-9]{1,3})?"
required
/>
</label>
<label>
Evidência de excedente e entrega física
<textarea
name="evidence"
className={controlClass}
minLength={10}
maxLength={1000}
required
/>
</label>
<label>
Fundamento
<textarea
name="reason"
className={controlClass}
minLength={10}
maxLength={1000}
required
/>
</label>
<label>
<input
type="checkbox"
name="declared_unused"
required
/>
Declaro que esta quantidade não foi consumida
</label>
<Button disabled={busy}>Conferir impacto</Button>
</form>
<Button
disabled={sourcePage <= 1 || busy}
onClick={() => setSourcePage((x) => x - 1)}
>
Entregas anteriores
</Button>
<Button
disabled={
sourcePage >= sources.pagination.last_page ||
busy
}
onClick={() => setSourcePage((x) => x + 1)}
>
Entregas seguintes
</Button>
</Panel>
)}
{preview && (
<Panel title={`Prévia da proposta #${preview.id}`}>
<WarehouseReturnImpact impact={preview.impact} />
<p>
{preview.state && preview.state !== 'prepared'
? `Decisão já registada: ${states[preview.state] ?? 'Arquivada'}. Sem novo efeito.`
: 'A preparação não altera stock. Aguarda outra identidade autorizada.'}
</p>
</Panel>
)}
<Panel title="Histórico e decisões">
<label>
Estado
<select
className={controlClass}
value={state}
onChange={(e) => {
setState(e.target.value);
setPage(1);
}}
>
<option value="all">Todos</option>
<option value="prepared">Por confirmar</option>
<option value="confirmed">Confirmados</option>
<option value="withdrawn">Retirados</option>
<option value="rejected">Recusados</option>
</select>
</label>
{!history ? (
<p role="status">A consultar decisões…</p>
) : (
<>
{history.rows.map((r) => (
<article
key={r.id}
className="space-y-3 border-b py-4"
>
<h3>
Proposta #{r.prepared_id} · v{r.version}{' '}
·{' '}
{states[r.state] ?? 'Estado arquivado'}
</h3>
<p>
{r.state === 'confirmed'
? 'Entrada efectuada'
: r.state === 'prepared'
? 'Impacto proposto'
: 'Prévia arquivada, não executada'}
</p>
<WarehouseReturnImpact impact={r.impact} />
<p>
{r.reason} · Evidência: {r.evidence}
</p>
<p>
Preparação #{r.preparer_id} · Autor
desta versão #{r.author_id} ·{' '}
{r.created_at}
</p>
{r.state === 'prepared' &&
canConfirm &&
r.preparer_id !== actorId && (
<form
onSubmit={(e) => confirm(e, r)}
>
<label>
Fundamento da recepção
<textarea
name="reason"
className={controlClass}
minLength={10}
maxLength={1000}
required
/>
</label>
<label>
<input
type="checkbox"
name="received_in_warehouse"
required
/>
Recebi fisicamente esta
quantidade no armazém
indicado
</label>
<Button disabled={busy}>
Confirmar entrada conferida
</Button>
</form>
)}
<>
{r.state === 'prepared' &&
canWithdraw &&
r.preparer_id === actorId && (
<details>
<summary>
Retirar proposta sem
movimento
</summary>
<form
onSubmit={(e) =>
close(
e,
r,
'withdraw',
)
}
>
<label>
Fundamento da
retirada
<textarea
name="reason"
className={
controlClass
}
minLength={10}
maxLength={1000}
required
/>
</label>
<Button disabled={busy}>
Retirar proposta
</Button>
</form>
</details>
)}
{r.state === 'prepared' &&
canConfirm &&
r.preparer_id !== actorId && (
<details>
<summary>
Recusar recepção sem
movimento
</summary>
<form
onSubmit={(e) =>
close(
e,
r,
'reject',
)
}
>
<label>
Fundamento da recusa
<textarea
name="reason"
className={
controlClass
}
minLength={10}
maxLength={1000}
required
/>
</label>
<Button disabled={busy}>
Recusar conferência
</Button>
</form>
</details>
)}
</>
</article>
))}
{!history.rows.length && (
<p>Sem decisões neste filtro.</p>
)}
<Button
disabled={page <= 1 || busy}
onClick={() => setPage((x) => x - 1)}
>
Anterior
</Button>
<Button
disabled={
page >= history.pagination.last_page || busy
}
onClick={() => setPage((x) => x + 1)}
>
Seguinte
</Button>
</>
)}
</Panel>
</div>
</>
);
} }
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) { for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -22,4 +33,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
coverage:'Existing pilot access and required source scope; positive old source selection tested in disposable databases.'},null,2)); coverage:'Existing pilot access and required source scope; positive old source selection tested in disposable databases.'},null,2));
console.log('Escolha de acordos conferida em leitura no piloto.'); console.log('Escolha de acordos conferida em leitura no piloto.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const routes=[]; const routes=[];
for(const [role,expected] of [['admin',200],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['procurement',403],['finance',403]]) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -22,4 +33,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Live synthetic scope has no technical alternatives or specific execution grants; technical review, independence and source changes tested in disposable databases.'},null,2)); coverage:'Live synthetic scope has no technical alternatives or specific execution grants; technical review, independence and source changes tested in disposable databases.'},null,2));
console.log('Alternativas tecnicas e tarefas conferidas, preservando competencias especificas.'); console.log('Alternativas tecnicas e tarefas conferidas, preservando competencias especificas.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const viewer = client(); await viewer.enter('admin'); const viewer = client(); await viewer.enter('admin');
const dashboard = await viewer.request('/dashboard'); const dashboard = await viewer.request('/dashboard');
if (dashboard.page?.props.context?.enforced) await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'}); if (dashboard.page?.props.context?.enforced) await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'});
@@ -43,4 +54,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/approval-routing-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,profile_task_catalogue:'passed',workflow_notices:'ready',existing_requisition_routing:detail,business_commands:false,accounts_or_grants_changed:false,visual_browser_review:false},null,2)); await fs.writeFile('docs/proofs/approval-routing-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,profile_task_catalogue:'passed',workflow_notices:'ready',existing_requisition_routing:detail,business_commands:false,accounts_or_grants_changed:false,visual_browser_review:false},null,2));
console.log('Profile task catalogue and existing requisition routing verified.'); console.log('Profile task catalogue and existing requisition routing verified.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[]; const results=[];
for(const role of ['admin','procurement','finance','warehouse']) { for(const role of ['admin','procurement','finance','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -24,4 +35,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/approval-search-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2)); await fs.writeFile('docs/proofs/approval-search-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false})); console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) { for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -24,4 +35,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
coverage:'Existing pilot facts and authorised CSV; populated overlap, registered expired proposals and pagination tested in disposable databases.'},null,2)); coverage:'Existing pilot facts and authorised CSV; populated overlap, registered expired proposals and pagination tested in disposable databases.'},null,2));
console.log('Consultas de aprovadas conferidas sem novas decisões no piloto.'); console.log('Consultas de aprovadas conferidas sem novas decisões no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','warehouse']) { for(const role of ['admin','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -15,4 +26,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/audit-metadata-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,pilot_grants_changed:false,business_commands:false,visual_review:false,coverage:'Denial before explicit permission; positive access exercised in disposable databases.'},null,2)); await fs.writeFile('docs/proofs/audit-metadata-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,pilot_grants_changed:false,business_commands:false,visual_review:false,coverage:'Denial before explicit permission; positive access exercised in disposable databases.'},null,2));
console.log('Auditoria recusa acesso no piloto sem nova competência explícita.'); console.log('Auditoria recusa acesso no piloto sem nova competência explícita.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+19 -5
View File
@@ -1,11 +1,23 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')) 'scripts/supplier-evaluation-check.mjs',
.replace('async function request(path, method = \'GET\', data, inertia = true)', 'async function request(path, method = \'GET\', data, inertia = true, extraHeaders = {})') 'utf8',
);
const common = source
.slice(source.indexOf('const base ='), source.indexOf('const author ='))
.replace(
"async function request(path, method = 'GET', data, inertia = true)",
"async function request(path, method = 'GET', data, inertia = true, extraHeaders = {})",
)
.replace('headers: {', 'headers: { ...extraHeaders,'); .replace('headers: {', 'headers: { ...extraHeaders,');
assert.ok(common.includes('extraHeaders = {}')); assert.ok(common.includes('extraHeaders = {}'));
await new Function('fs','assert','return (async()=>{'+common+` await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','procurement','finance','warehouse']) { for(const role of ['admin','procurement','finance','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -30,4 +42,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
coverage:'Existing synthetic requisition 2: scoped detail, partial audit pagination and full CSV access.'},null,2)); coverage:'Existing synthetic requisition 2: scoped detail, partial audit pagination and full CSV access.'},null,2));
console.log('Paginação parcial do histórico conferida sem comandos de negócio no piloto.'); console.log('Paginação parcial do histórico conferida sem comandos de negócio no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const routes = []; const routes = [];
for (const role of ['procurement', 'department_head', 'finance']) { for (const role of ['procurement', 'department_head', 'finance']) {
const viewer = client(); const viewer = client();
@@ -33,4 +44,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
note: 'Only current first-page tasks are followed; disposable tests cover pending approval and issuance.' note: 'Only current first-page tasks are followed; disposable tests cover pending approval and issuance.'
}, null, 2)); }, null, 2));
console.log('Encaminhamento de adjudicacoes conferido com o ambito actual dos perfis existentes.'); console.log('Encaminhamento de adjudicacoes conferido com o ambito actual dos perfis existentes.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[]; const results=[];
for(const role of ['admin','procurement','finance','warehouse']) { for(const role of ['admin','procurement','finance','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -26,4 +37,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/benchmark-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2)); await fs.writeFile('docs/proofs/benchmark-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false})); console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+25 -6
View File
@@ -2,12 +2,29 @@ import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const installation = JSON.parse( const installation = JSON.parse(
await fs.readFile('docs/proofs/rq01-distribution-pilot-installation.json', 'utf8'), await fs.readFile(
'docs/proofs/rq01-distribution-pilot-installation.json',
'utf8',
),
); );
assert.equal(installation.status, 'installed_and_capability_enabled_no_business_operations'); assert.equal(
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); installation.status,
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'installed_and_capability_enabled_no_business_operations',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` );
const source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[]; const results=[];
for(const role of ['requester','admin','procurement','finance']) { for(const role of ['requester','admin','procurement','finance']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -30,4 +47,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/rq01-distribution-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2)); await fs.writeFile('docs/proofs/rq01-distribution-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false})); console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+97 -22
View File
@@ -6,43 +6,118 @@ import assert from 'node:assert/strict';
const frontend = process.argv[2]; const frontend = process.argv[2];
assert.ok(frontend, 'Provide the verified frontend build directory.'); assert.ok(frontend, 'Provide the verified frontend build directory.');
const roots = ['app', 'bootstrap', 'config', 'database', 'resources', 'routes', 'integrations', 'packages', 'public', const roots = [
'composer.json', 'composer.lock', 'package.json', 'package-lock.json', 'artisan', '.gitattributes', '.env.example', 'app',
'scripts/verify-compras-release.php', 'scripts/build-compras-release.mjs', 'scripts/archive-compras-release.py', 'scripts/deployment/compras-tempo-deploy.sh']; 'bootstrap',
'config',
'database',
'resources',
'routes',
'integrations',
'packages',
'public',
'composer.json',
'composer.lock',
'package.json',
'package-lock.json',
'artisan',
'.gitattributes',
'.env.example',
'scripts/verify-compras-release.php',
'scripts/build-compras-release.mjs',
'scripts/archive-compras-release.py',
'scripts/deployment/compras-tempo-deploy.sh',
];
const listed = ['git', 'ls-files']; const listed = ['git', 'ls-files'];
const tracked = execFileSync(listed[0], [...listed.slice(1), '-z', '--', ...roots], { encoding: 'utf8' }).split('\0'); const tracked = execFileSync(
const added = execFileSync('git', ['ls-files', '--others', '--exclude-standard', '-z', '--', ...roots], { encoding: 'utf8' }).split('\0'); listed[0],
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); [...listed.slice(1), '-z', '--', ...roots],
{ encoding: 'utf8' },
).split('\0');
const added = execFileSync(
'git',
['ls-files', '--others', '--exclude-standard', '-z', '--', ...roots],
{ encoding: 'utf8' },
).split('\0');
const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
const source = {}; const source = {};
const exact = []; const exact = [];
for (const file of [...new Set([...tracked, ...added])].filter(Boolean).sort()) { for (const file of [...new Set([...tracked, ...added])]
if (file.startsWith('bootstrap/cache/') || file.startsWith('public/build/')) continue; .filter(Boolean)
.sort()) {
if (file.startsWith('bootstrap/cache/') || file.startsWith('public/build/'))
continue;
const info = await fs.lstat(file); const info = await fs.lstat(file);
if (!info.isFile() || info.isSymbolicLink()) continue; if (!info.isFile() || info.isSymbolicLink()) continue;
const bytes = await fs.readFile(file); const bytes = await fs.readFile(file);
const pinned = file.startsWith('packages/budget-control/') || file.startsWith('packages/payables/') const pinned =
|| file === 'resources/data/geography/cartografia-moz.json' || bytes.includes(0); file.startsWith('packages/budget-control/') ||
file.startsWith('packages/payables/') ||
file === 'resources/data/geography/cartografia-moz.json' ||
bytes.includes(0);
if (pinned) exact.push(file); if (pinned) exact.push(file);
source[file] = hash(pinned ? bytes : Buffer.from(bytes.toString('utf8').replaceAll('\r\n', '\n'))); source[file] = hash(
pinned
? bytes
: Buffer.from(bytes.toString('utf8').replaceAll('\r\n', '\n')),
);
} }
const buildBytes = await fs.readFile(path.join(frontend, 'manifest.json')); const buildBytes = await fs.readFile(path.join(frontend, 'manifest.json'));
const build = JSON.parse(buildBytes); const build = JSON.parse(buildBytes);
const assets = {}; const assets = {};
for (const entry of Object.values(build)) { for (const entry of Object.values(build)) {
for (const file of [entry.file, ...(entry.css ?? []), ...(entry.assets ?? [])]) { for (const file of [
entry.file,
...(entry.css ?? []),
...(entry.assets ?? []),
]) {
assert.ok(file.startsWith('assets/') && !file.includes('..')); assert.ok(file.startsWith('assets/') && !file.includes('..'));
assets[file] = hash(await fs.readFile(path.join(frontend, file))); assets[file] = hash(await fs.readFile(path.join(frontend, file)));
} }
} }
const manifest = { contract: 'compras.release.v1', product: 'compras', source_eol: 'lf', exact_source_files: exact, const manifest = {
source_files: source, frontend: { manifest_sha256: hash(buildBytes), entry: build['resources/js/app.tsx'].file, contract: 'compras.release.v1',
fonts_manifest_sha256: hash(await fs.readFile(path.join(frontend, 'fonts-manifest.json'))), product: 'compras',
files: Object.fromEntries(Object.entries(assets).sort(([a], [b]) => a.localeCompare(b, 'en'))) }, source_eol: 'lf',
exact_source_files: exact,
source_files: source,
frontend: {
manifest_sha256: hash(buildBytes),
entry: build['resources/js/app.tsx'].file,
fonts_manifest_sha256: hash(
await fs.readFile(path.join(frontend, 'fonts-manifest.json')),
),
files: Object.fromEntries(
Object.entries(assets).sort(([a], [b]) => a.localeCompare(b, 'en')),
),
},
components: [ components: [
{ setting: 'COMPRAS_RUNTIME_ROOT', manifest_sha256: '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7' }, {
{ setting: 'COMPRAS_INVENTORY_ROOT', manifest_sha256: '8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd' }, setting: 'COMPRAS_RUNTIME_ROOT',
{ setting: 'COMPRAS_ORDER_CANCELLATION_ROOT', manifest_sha256: '52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f' }, manifest_sha256:
] }; '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7',
},
{
setting: 'COMPRAS_INVENTORY_ROOT',
manifest_sha256:
'8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd',
},
{
setting: 'COMPRAS_ORDER_CANCELLATION_ROOT',
manifest_sha256:
'52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f',
},
],
};
manifest.release_id = 'compras-' + hash(JSON.stringify(manifest)).slice(0, 16); manifest.release_id = 'compras-' + hash(JSON.stringify(manifest)).slice(0, 16);
await fs.writeFile('compras-release.json', JSON.stringify(manifest, null, 2)+'\n'); await fs.writeFile(
console.log(JSON.stringify({ release_id: manifest.release_id, source_files: Object.keys(source).length, asset_files: Object.keys(assets).length })); 'compras-release.json',
JSON.stringify(manifest, null, 2) + '\n',
);
console.log(
JSON.stringify({
release_id: manifest.release_id,
source_files: Object.keys(source).length,
asset_files: Object.keys(assets).length,
}),
);
+20 -5
View File
@@ -1,12 +1,27 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const proofName = process.argv.includes('--additional') ? 'candidate-additional-geography-http.json' : 'candidate-geography-http.json'; 'scripts/supplier-evaluation-check.mjs',
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'utf8',
await new Function('fs','assert','return (async()=>{'+common+` );
const proofName = process.argv.includes('--additional')
? 'candidate-additional-geography-http.json'
: 'candidate-geography-http.json';
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const guest=await fetch(base+'/candidaturas/1/divisao-administrativa',{headers:{Accept:'application/json'},redirect:'manual'}); assert.equal(guest.status,401); const guest=await fetch(base+'/candidaturas/1/divisao-administrativa',{headers:{Accept:'application/json'},redirect:'manual'}); assert.equal(guest.status,401);
const staff=client(); await staff.enter('admin'); assert.equal((await staff.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302); const denied=await staff.request('/candidaturas/1/divisao-administrativa','GET',undefined,false); assert.equal(denied.status,401); const staff=client(); await staff.enter('admin'); assert.equal((await staff.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302); const denied=await staff.request('/candidaturas/1/divisao-administrativa','GET',undefined,false); assert.equal(denied.status,401);
const catalogue=await staff.request('/api/divisao-administrativa'); assert.equal(catalogue.status,200); assert.equal(catalogue.page.data.length,11); const catalogue=await staff.request('/api/divisao-administrativa'); assert.equal(catalogue.status,200); assert.equal(catalogue.page.data.length,11);
await fs.writeFile('docs/proofs/${proofName}',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',guest_status:401,staff_without_candidate_status:401,existing_staff_catalogue_status:200,registration_commands:false,profile_commands:false,portal_configuration_commands:false,business_commands:false,mfa_activation:false,positive_candidate_session_coverage:'disposable tests only',visual_review:false},null,2)); await fs.writeFile('docs/proofs/${proofName}',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',guest_status:401,staff_without_candidate_status:401,existing_staff_catalogue_status:200,registration_commands:false,profile_commands:false,portal_configuration_commands:false,business_commands:false,mfa_activation:false,positive_candidate_session_coverage:'disposable tests only',visual_review:false},null,2));
console.log('Candidate catalogue denied to guests and staff-only sessions; no candidate registration or profile changes.'); console.log('Candidate catalogue denied to guests and staff-only sessions; no candidate registration or profile changes.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const viewer=client(); await viewer.enter('admin'); const viewer=client(); await viewer.enter('admin');
assert.equal((await viewer.request('/contexto','POST',{area:'people',option:'people.internal'})).status,302); assert.equal((await viewer.request('/contexto','POST',{area:'people',option:'people.internal'})).status,302);
const index=await viewer.request('/pessoas'); assert.equal(index.status,200); const index=await viewer.request('/pessoas'); assert.equal(index.status,200);
@@ -11,4 +22,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
let inboxes=0; for(const record of index.page.props.processes.data.slice(0,2)) { const page=await viewer.request('/pessoas/'+record.id+'/recebidas'); if(page.status===200) { assert.equal(page.page.props.geographyEnabled,true); inboxes++; } else { assert.equal(page.status,403); } } let inboxes=0; for(const record of index.page.props.processes.data.slice(0,2)) { const page=await viewer.request('/pessoas/'+record.id+'/recebidas'); if(page.status===200) { assert.equal(page.page.props.geographyEnabled,true); inboxes++; } else { assert.equal(page.status,403); } }
await fs.writeFile('docs/proofs/candidate-territory-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',people_index_status:200,unknown_process_catalogue_status:404,procurement_catalogue_in_people_context_status:403,visible_inboxes_checked:inboxes,business_commands:false,process_or_portal_created:false,profile_commands:false,triage_commands:false,visual_review:false,positive_process_filter_coverage:'disposable tests'},null,2)); await fs.writeFile('docs/proofs/candidate-territory-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',people_index_status:200,unknown_process_catalogue_status:404,procurement_catalogue_in_people_context_status:403,visible_inboxes_checked:inboxes,business_commands:false,process_or_portal_created:false,profile_commands:false,triage_commands:false,visual_review:false,positive_process_filter_coverage:'disposable tests'},null,2));
console.log('People access remains scoped; no new processes, profiles or triage decisions.'); console.log('People access remains scoped; no new processes, profiles or triage decisions.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+49 -12
View File
@@ -4,35 +4,72 @@ import assert from 'node:assert/strict';
const release = JSON.parse(await fs.readFile('compras-release.json', 'utf8')); const release = JSON.parse(await fs.readFile('compras-release.json', 'utf8'));
const base = 'https://compras.tempo.co.mz'; const base = 'https://compras.tempo.co.mz';
const entry = await fetch(base+'/', { redirect: 'manual', signal: AbortSignal.timeout(15000) }); const entry = await fetch(base + '/', {
redirect: 'manual',
signal: AbortSignal.timeout(15000),
});
assert.equal(entry.status, 302); assert.equal(entry.status, 302);
assert.equal(new URL(entry.headers.get('location'), base).pathname, '/login'); assert.equal(new URL(entry.headers.get('location'), base).pathname, '/login');
const queue = Object.entries(release.frontend.files); const queue = Object.entries(release.frontend.files);
let checked = 0; let checked = 0;
await Promise.all(Array.from({ length: 4 }, async () => { await Promise.all(
Array.from({ length: 4 }, async () => {
for (;;) { for (;;) {
const entry = queue.shift(); const entry = queue.shift();
if (!entry) return; if (!entry) return;
const [name, expected] = entry; const [name, expected] = entry;
const response = await fetch(base+'/build/'+name, { signal: AbortSignal.timeout(20000) }); const response = await fetch(base + '/build/' + name, {
signal: AbortSignal.timeout(20000),
});
assert.equal(response.status, 200, name); assert.equal(response.status, 200, name);
assert.equal(crypto.createHash('sha256').update(new Uint8Array(await response.arrayBuffer())).digest('hex'), expected, name); assert.equal(
crypto
.createHash('sha256')
.update(new Uint8Array(await response.arrayBuffer()))
.digest('hex'),
expected,
name,
);
checked++; checked++;
} }
})); }),
for (const [path, component] of [['/', 'auth/login'], ['/login', 'auth/login'], ['/apresentacao', 'home']]) { );
const response = await fetch(base+path, { signal: AbortSignal.timeout(15000) }); for (const [path, component] of [
['/', 'auth/login'],
['/login', 'auth/login'],
['/apresentacao', 'home'],
]) {
const response = await fetch(base + path, {
signal: AbortSignal.timeout(15000),
});
assert.equal(response.status, 200); assert.equal(response.status, 200);
const html = await response.text(); const html = await response.text();
assert.ok(html.includes(release.frontend.entry)); assert.ok(html.includes(release.frontend.entry));
const bootstrap = html.match(/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/); const bootstrap = html.match(
/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/,
);
assert.ok(bootstrap); assert.ok(bootstrap);
const page = JSON.parse(bootstrap[1]); const page = JSON.parse(bootstrap[1]);
assert.equal(page.component, component); assert.equal(page.component, component);
assert.equal(page.props.auth.user, null); assert.equal(page.props.auth.user, null);
assert.deepEqual(page.props.commonFinanceNavigation, { payments: false, ledger: false, configuration: false }); assert.deepEqual(page.props.commonFinanceNavigation, {
payments: false,
ledger: false,
configuration: false,
});
} }
const proof = { state: 'passed', product: 'compras', release_id: release.release_id, public_url: base, const proof = {
assets_verified: checked, real_product_entry: true, login_entry: true, anonymous_private_identity_or_financial_access: false }; state: 'passed',
await fs.writeFile('docs/proofs/compras-release-http.json', JSON.stringify(proof, null, 2)+'\n'); product: 'compras',
release_id: release.release_id,
public_url: base,
assets_verified: checked,
real_product_entry: true,
login_entry: true,
anonymous_private_identity_or_financial_access: false,
};
await fs.writeFile(
'docs/proofs/compras-release-http.json',
JSON.stringify(proof, null, 2) + '\n',
);
console.log(JSON.stringify(proof)); console.log(JSON.stringify(proof));
+42 -9
View File
@@ -6,25 +6,58 @@ const file = 'docs/proofs/public-demonstration-frontend.json';
const proof = JSON.parse(await fs.readFile(file, 'utf8')); const proof = JSON.parse(await fs.readFile(file, 'utf8'));
const queue = Object.entries(proof.files); const queue = Object.entries(proof.files);
let checked = 0; let checked = 0;
await Promise.all(Array.from({ length: 4 }, async () => { await Promise.all(
Array.from({ length: 4 }, async () => {
for (;;) { for (;;) {
const entry = queue.shift(); const entry = queue.shift();
if (!entry) return; if (!entry) return;
const [name, hash] = entry; const [name, hash] = entry;
const response = await fetch('https://compras.tempo.co.mz/build/' + name, { signal: AbortSignal.timeout(20000) }); const response = await fetch(
'https://compras.tempo.co.mz/build/' + name,
{ signal: AbortSignal.timeout(20000) },
);
assert.equal(response.status, 200, name); assert.equal(response.status, 200, name);
assert.equal(crypto.createHash('sha256').update(new Uint8Array(await response.arrayBuffer())).digest('hex'), hash, name); assert.equal(
crypto
.createHash('sha256')
.update(new Uint8Array(await response.arrayBuffer()))
.digest('hex'),
hash,
name,
);
checked++; checked++;
} }
})); }),
Object.assign(proof, { state: 'assets_passed_banner_pending', public_assets_responses_and_hashes: checked }); );
Object.assign(proof, {
state: 'assets_passed_banner_pending',
public_assets_responses_and_hashes: checked,
});
await fs.writeFile(file, JSON.stringify(proof, null, 2) + '\n'); await fs.writeFile(file, JSON.stringify(proof, null, 2) + '\n');
const response = await fetch('https://compras.tempo.co.mz/login', { signal: AbortSignal.timeout(15000) }); const response = await fetch('https://compras.tempo.co.mz/login', {
signal: AbortSignal.timeout(15000),
});
assert.equal(response.status, 200); assert.equal(response.status, 200);
const html = await response.text(); const html = await response.text();
const manifest = JSON.parse(await fs.readFile('storage/framework/testing/compras-presentation-final-ui-20261129/manifest.json', 'utf8')); const manifest = JSON.parse(
await fs.readFile(
'storage/framework/testing/compras-presentation-final-ui-20261129/manifest.json',
'utf8',
),
);
assert.ok(html.includes(manifest['resources/js/app.tsx'].file)); assert.ok(html.includes(manifest['resources/js/app.tsx'].file));
assert.ok(html.includes('Empresa e dados fictícios')); assert.ok(html.includes('Empresa e dados fictícios'));
Object.assign(proof, { state: 'passed', date: new Date().toISOString(), public_entry_current: true, demonstration_banner_present: true }); Object.assign(proof, {
state: 'passed',
date: new Date().toISOString(),
public_entry_current: true,
demonstration_banner_present: true,
});
await fs.writeFile(file, JSON.stringify(proof, null, 2) + '\n'); await fs.writeFile(file, JSON.stringify(proof, null, 2) + '\n');
console.log(JSON.stringify({ state: proof.state, public_assets_responses_and_hashes: checked, public_entry_current: true })); console.log(
JSON.stringify({
state: proof.state,
public_assets_responses_and_hashes: checked,
public_entry_current: true,
}),
);
+81 -19
View File
@@ -2,53 +2,115 @@ import fs from 'node:fs/promises';
import crypto from 'node:crypto'; import crypto from 'node:crypto';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
let plan = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation-proposal.json', 'utf8')); let plan = JSON.parse(
await fs.readFile(
'docs/proofs/compras-standalone-pilot-activation-proposal.json',
'utf8',
),
);
let interfaceDelta = false; let interfaceDelta = false;
try { try {
const result = JSON.parse(await fs.readFile('docs/proofs/analytics-print-publication.json', 'utf8')); const result = JSON.parse(
const bytes = await fs.readFile('docs/proofs/analytics-print-publication-proposal.json'); await fs.readFile(
'docs/proofs/analytics-print-publication.json',
'utf8',
),
);
const bytes = await fs.readFile(
'docs/proofs/analytics-print-publication-proposal.json',
);
const proposal = JSON.parse(bytes); const proposal = JSON.parse(bytes);
const approval = JSON.parse(await fs.readFile('docs/proofs/analytics-print-publication-authorization.json', 'utf8')); const approval = JSON.parse(
await fs.readFile(
'docs/proofs/analytics-print-publication-authorization.json',
'utf8',
),
);
assert.equal(result.pilot_state ?? result.state, 'passed'); assert.equal(result.pilot_state ?? result.state, 'passed');
assert.equal(approval.state, 'approved'); assert.equal(approval.state, 'approved');
assert.equal(approval.proposal_sha256, crypto.createHash('sha256').update(bytes).digest('hex')); assert.equal(
approval.proposal_sha256,
crypto.createHash('sha256').update(bytes).digest('hex'),
);
assert.equal(result.manifest_sha256, proposal.manifest_sha256); assert.equal(result.manifest_sha256, proposal.manifest_sha256);
assert.equal(proposal.previous_manifest_sha256, plan.frontend.manifest_sha256); assert.equal(
proposal.previous_manifest_sha256,
plan.frontend.manifest_sha256,
);
plan = { ...plan, frontend: proposal }; plan = { ...plan, frontend: proposal };
interfaceDelta = true; interfaceDelta = true;
} catch (error) { } catch (error) {
if (error.code !== 'ENOENT') throw error; if (error.code !== 'ENOENT') throw error;
} }
const activation = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation.json', 'utf8')); const activation = JSON.parse(
await fs.readFile(
'docs/proofs/compras-standalone-pilot-activation.json',
'utf8',
),
);
assert.equal(activation.state, 'passed'); assert.equal(activation.state, 'passed');
assert.equal(plan.target, 'http://127.0.0.1:8005'); assert.equal(plan.target, 'http://127.0.0.1:8005');
let verified = 0; let verified = 0;
const queue = Object.entries(plan.frontend.files); const queue = Object.entries(plan.frontend.files);
await Promise.all(Array.from({ length: 3 }, async () => { await Promise.all(
Array.from({ length: 3 }, async () => {
for (;;) { for (;;) {
const entry = queue.shift(); const entry = queue.shift();
if (!entry) return; if (!entry) return;
const [file, hash] = entry; const [file, hash] = entry;
assert.ok(file.startsWith('assets/') && !file.includes('..')); assert.ok(file.startsWith('assets/') && !file.includes('..'));
const response = await fetch(`${plan.target}/build/${file}`, { signal: AbortSignal.timeout(10000) }); const response = await fetch(`${plan.target}/build/${file}`, {
signal: AbortSignal.timeout(10000),
});
assert.equal(response.status, 200, file); assert.equal(response.status, 200, file);
assert.equal(crypto.createHash('sha256').update(new Uint8Array(await response.arrayBuffer())).digest('hex'), hash, file); assert.equal(
crypto
.createHash('sha256')
.update(new Uint8Array(await response.arrayBuffer()))
.digest('hex'),
hash,
file,
);
verified++; verified++;
} }
})); }),
const response = await fetch('https://compras.tempo.co.mz/dashboard', { signal: AbortSignal.timeout(15000) }); );
const response = await fetch('https://compras.tempo.co.mz/dashboard', {
signal: AbortSignal.timeout(15000),
});
assert.equal(response.status, 200); assert.equal(response.status, 200);
const html = await response.text(); const html = await response.text();
const bootstrap = html.match(/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/); const bootstrap = html.match(
/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/,
);
assert.ok(bootstrap, 'Expected public Inertia bootstrap'); assert.ok(bootstrap, 'Expected public Inertia bootstrap');
const page = JSON.parse(bootstrap[1]); const page = JSON.parse(bootstrap[1]);
assert.equal(page.props.auth.user, null); assert.equal(page.props.auth.user, null);
assert.deepEqual(page.props.commonFinanceNavigation, { payments: false, ledger: false, configuration: false }); assert.deepEqual(page.props.commonFinanceNavigation, {
const manifest = JSON.parse(await fs.readFile('public/build/manifest.json', 'utf8')); payments: false,
ledger: false,
configuration: false,
});
const manifest = JSON.parse(
await fs.readFile('public/build/manifest.json', 'utf8'),
);
const publicCurrent = html.includes(manifest['resources/js/app.tsx'].file); const publicCurrent = html.includes(manifest['resources/js/app.tsx'].file);
const proof = { date: new Date().toISOString(), state: publicCurrent ? 'passed' : 'pilot_passed_public_installation_pending', pilot_asset_responses_and_hashes: verified, const proof = {
public_domain_html_delivers_new_entry: publicCurrent, public_anonymous_identity_preserved: true, date: new Date().toISOString(),
private_finance_navigation_not_exposed_publicly: true, new_grants_or_business_operations: false }; state: publicCurrent
await fs.writeFile(interfaceDelta ? 'docs/proofs/analytics-print-publication-http.json' : 'docs/proofs/compras-standalone-published-assets.json', JSON.stringify(proof, null, 2) + '\n'); ? 'passed'
: 'pilot_passed_public_installation_pending',
pilot_asset_responses_and_hashes: verified,
public_domain_html_delivers_new_entry: publicCurrent,
public_anonymous_identity_preserved: true,
private_finance_navigation_not_exposed_publicly: true,
new_grants_or_business_operations: false,
};
await fs.writeFile(
interfaceDelta
? 'docs/proofs/analytics-print-publication-http.json'
: 'docs/proofs/compras-standalone-published-assets.json',
JSON.stringify(proof, null, 2) + '\n',
);
console.log(JSON.stringify(proof)); console.log(JSON.stringify(proof));
if (!publicCurrent) process.exitCode = 1; if (!publicCurrent) process.exitCode = 1;
+17 -4
View File
@@ -2,9 +2,20 @@ import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
// Reuse the established isolated-host session client; do not copy credentials or bypass normal routes. // Reuse the established isolated-host session client; do not copy credentials or bypass normal routes.
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results = []; const results = [];
for (const role of ['admin', 'procurement', 'finance']) { for (const role of ['admin', 'procurement', 'finance']) {
const viewer = client(); const viewer = client();
@@ -41,4 +52,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/commercial-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true},null,2)); await fs.writeFile('docs/proofs/commercial-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true},null,2));
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false})); console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+4 -2
View File
@@ -1,9 +1,11 @@
<?php <?php
use App\Services\StandaloneRuntime; use App\Services\StandaloneRuntime;
use App\Services\WorkContext;
use Illuminate\Contracts\Console\Kernel; use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
$root = dirname(__DIR__); $root = dirname(__DIR__);
require $root.'/vendor/autoload.php'; require $root.'/vendor/autoload.php';
@@ -55,9 +57,9 @@ $collectFlags(config()->all());
ksort($flags); ksort($flags);
echo json_encode(['state' => 'passed', 'runtime_enabled' => $runtime->enabled(), 'features' => $features, echo json_encode(['state' => 'passed', 'runtime_enabled' => $runtime->enabled(), 'features' => $features,
'deployment_flags' => $flags, 'deployment_flags' => $flags,
'history_schema' => ['pa_history_imports' => Illuminate\Support\Facades\Schema::hasTable('pa_history_imports'), 'pa_imported_payments' => Illuminate\Support\Facades\Schema::hasTable('pa_imported_payments')], 'history_schema' => ['pa_history_imports' => Schema::hasTable('pa_history_imports'), 'pa_imported_payments' => Schema::hasTable('pa_imported_payments')],
'pending_application_migrations' => array_values(array_diff(array_map(fn ($file) => basename($file, '.php'), glob($root.'/database/migrations/*.php')), DB::table('migrations')->pluck('migration')->all())), 'pending_application_migrations' => array_values(array_diff(array_map(fn ($file) => basename($file, '.php'), glob($root.'/database/migrations/*.php')), DB::table('migrations')->pluck('migration')->all())),
'routes' => $routes, 'component_flags' => $components, 'company_context_policies' => $tenants, 'routes' => $routes, 'component_flags' => $components, 'company_context_policies' => $tenants,
'context_entitlements_configured' => count(config('work_context.entitlements', [])) > 0, 'context_entitlements_configured' => count(config('work_context.entitlements', [])) > 0,
'operational_contexts' => array_combine(array_keys(App\Services\WorkContext::OPTIONS), array_map(fn ($key) => App\Services\WorkContext::operational($key), array_keys(App\Services\WorkContext::OPTIONS))), 'operational_contexts' => array_combine(array_keys(WorkContext::OPTIONS), array_map(fn ($key) => WorkContext::operational($key), array_keys(WorkContext::OPTIONS))),
'business_data_changed' => false], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL; 'business_data_changed' => false], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL;
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -23,4 +34,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
coverage:'Existing pilot export access; populated exports and native quantities tested in disposable databases.'},null,2)); coverage:'Existing pilot export access; populated exports and native quantities tested in disposable databases.'},null,2));
console.log('Exportação conferida sem comandos de negócio no piloto.'); console.log('Exportação conferida sem comandos de negócio no piloto.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -25,4 +36,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
coverage:'Existing pilot access and validation; positive record filtering verified in disposable databases.'},null,2)); coverage:'Existing pilot access and validation; positive record filtering verified in disposable databases.'},null,2));
console.log('Consulta filtrada conferida no piloto sem comandos de negócio.'); console.log('Consulta filtrada conferida no piloto sem comandos de negócio.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','warehouse','procurement','finance']) { for(const role of ['admin','warehouse','procurement','finance']) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -28,4 +39,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Read-only pilot access; partial/full receipts, allocations and corrections exercised in disposable databases.'},null,2)); coverage:'Read-only pilot access; partial/full receipts, allocations and corrections exercised in disposable databases.'},null,2));
console.log('Acompanhamento e paginação conferidos sem criar previsões, reservas ou movimentos no piloto.'); console.log('Acompanhamento e paginação conferidos sem criar previsões, reservas ou movimentos no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -22,4 +33,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Existing pilot read rights; positive old origins and native reversals tested in disposable databases.'},null,2)); coverage:'Existing pilot read rights; positive old origins and native reversals tested in disposable databases.'},null,2));
console.log('Pesquisa de origens de correcção conferida sem decisões, concessões ou movimentos no piloto.'); console.log('Pesquisa de origens de correcção conferida sem decisões, concessões ou movimentos no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[]; const results=[];
for(const role of ['admin','procurement','finance','warehouse']) { for(const role of ['admin','procurement','finance','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -24,4 +35,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/draft-preparation-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2)); await fs.writeFile('docs/proofs/draft-preparation-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false})); console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','warehouse']) { for(const role of ['admin','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -21,4 +32,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/equipment-integration-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,grants_changed:false,visual_review:false,coverage:'Existing equipment only; complete native journeys exercised in disposable databases.'},null,2)); await fs.writeFile('docs/proofs/equipment-integration-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,grants_changed:false,visual_review:false,coverage:'Existing equipment only; complete native journeys exercised in disposable databases.'},null,2));
console.log('Equipamentos consultados no piloto; sem novas compras ou movimentos.'); console.log('Equipamentos consultados no piloto; sem novas compras ou movimentos.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+18 -4
View File
@@ -1,9 +1,21 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','outputFile','return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'outputFile',
'return (async()=>{' +
common +
`
const rows=[], prints=new Set(); const rows=[], prints=new Set();
const paths=['/ordens','/recepcoes','/stock','/stock/requisicoes','/equipamentos','/orcamentos','/facturas','/pagamentos','/planeamento','/revisao-compras','/relatorios','/relatorios/medidas-fornecedores','/compras/fornecimento?view=calendar','/compras/fornecimento?view=imports','/compras/acordos/vigencia']; const paths=['/ordens','/recepcoes','/stock','/stock/requisicoes','/equipamentos','/orcamentos','/facturas','/pagamentos','/planeamento','/revisao-compras','/relatorios','/relatorios/medidas-fornecedores','/compras/fornecimento?view=calendar','/compras/fornecimento?view=imports','/compras/acordos/vigencia'];
for(const role of ['admin','procurement','finance','warehouse']){ for(const role of ['admin','procurement','finance','warehouse']){
@@ -27,4 +39,6 @@ await new Function('fs','assert','outputFile','return (async()=>{' + common + `
} }
await fs.writeFile(outputFile,JSON.stringify({environment:base,scope:'existing authorised records only',rows,print_paths:[...prints],business_commands:false,visual_review:false},null,2)); await fs.writeFile(outputFile,JSON.stringify({environment:base,scope:'existing authorised records only',rows,print_paths:[...prints],business_commands:false,visual_review:false},null,2));
console.log(JSON.stringify({routes_checked:rows.length,print_paths:[...prints],statuses:rows.reduce((a,r)=>(a[r.status]=(a[r.status]??0)+1,a),{})})); console.log(JSON.stringify({routes_checked:rows.length,print_paths:[...prints],statuses:rows.reduce((a,r)=>(a[r.status]=(a[r.status]??0)+1,a),{})}));
`+'})()')(fs,assert,process.argv[2]??'docs/proofs/final-review-inventory.json'); ` +
'})()',
)(fs, assert, process.argv[2] ?? 'docs/proofs/final-review-inventory.json');
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const routes = []; const routes = [];
for (const role of ['admin', 'finance']) { for (const role of ['admin', 'finance']) {
const viewer = client(); const viewer = client();
@@ -36,4 +47,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
note: 'Payment consultation retains its existing access audit; no financial decision is executed.' note: 'Payment consultation retains its existing access audit; no financial decision is executed.'
}, null, 2)); }, null, 2));
console.log('Facturas, pagamentos e tarefas financeiras conferidos com as contas existentes.'); console.log('Facturas, pagamentos e tarefas financeiras conferidos com as contas existentes.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const routes = []; const routes = [];
for (const role of ['procurement', 'finance', 'department_head']) { for (const role of ['procurement', 'finance', 'department_head']) {
const viewer = client(); const viewer = client();
@@ -38,4 +49,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
visual_review: false, coverage: 'Existing current scope and first-page tasks only; pending decisions tested in disposable databases.' visual_review: false, coverage: 'Existing current scope and first-page tasks only; pending decisions tested in disposable databases.'
}, null, 2)); }, null, 2));
console.log('Analise documental, admissao, recomendacao e tarefas conferidas nos ambitos existentes.'); console.log('Analise documental, admissao, recomendacao e tarefas conferidas nos ambitos existentes.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','procurement','finance']) { for(const role of ['admin','procurement','finance']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -18,4 +29,6 @@ for(const role of ['admin','procurement','finance']) {
} }
await fs.writeFile('docs/proofs/administrative-geography-installation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,classification_commands:false,approval_changes:false,mfa_activation:false,visual_review:false},null,2)); await fs.writeFile('docs/proofs/administrative-geography-installation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,classification_commands:false,approval_changes:false,mfa_activation:false,visual_review:false},null,2));
console.log('Geographic selection available in company and supplier pages; no classification submitted.'); console.log('Geographic selection available in company and supplier pages; no classification submitted.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
const admin=client(); await admin.enter('admin'); const admin=client(); await admin.enter('admin');
assert.equal((await admin.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302); assert.equal((await admin.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
@@ -14,4 +25,6 @@ records.push({role:'admin',pendingRecords:10729,firstPage:50,blankDesignations:9
records.push({role:'procurement',reviewStatus:403}); records.push({role:'procurement',reviewStatus:403});
await fs.writeFile('docs/proofs/administrative-geography-review-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,classification_commands:false,approval_changes:false,mfa_activation:false,visual_review:false},null,2)); await fs.writeFile('docs/proofs/administrative-geography-review-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,classification_commands:false,approval_changes:false,mfa_activation:false,visual_review:false},null,2));
console.log('Administrative review and filtered CSV checked read-only; no geography or entity changes.'); console.log('Administrative review and filtered CSV checked read-only; no geography or entity changes.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','procurement','finance']) { for(const role of ['admin','procurement','finance']) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -18,4 +29,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Existing pilot scope and lookup validation; approved historical periods and suspensions tested in disposable databases.'},null,2)); coverage:'Existing pilot scope and lookup validation; approved historical periods and suspensions tested in disposable databases.'},null,2));
console.log('Pesquisa de análises conferida sem criar origens, decisões ou acessos no piloto.'); console.log('Pesquisa de análises conferida sem criar origens, decisões ou acessos no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const routes=[]; const routes=[];
for (const [role, expected] of [['admin',200],['procurement',403],['finance',403]]) { for (const [role, expected] of [['admin',200],['procurement',403],['finance',403]]) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -28,4 +39,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Existing current scope has no historical analysis and no historical execution grants; pending historical reviews tested only in disposable databases.'},null,2)); coverage:'Existing current scope has no historical analysis and no historical execution grants; pending historical reviews tested only in disposable databases.'},null,2));
console.log('Historico, competencias especificas, tarefas e diagnostico da instalacao conferidos.'); console.log('Historico, competencias especificas, tarefas e diagnostico da instalacao conferidos.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const viewer = client(); const viewer = client();
await viewer.enter('admin'); await viewer.enter('admin');
const dashboard = await viewer.request('/dashboard'); const dashboard = await viewer.request('/dashboard');
@@ -27,4 +38,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
accounts_or_grants_changed: false, sgf_installation_changed: false, visual_review: false accounts_or_grants_changed: false, sgf_installation_changed: false, visual_review: false
}, null, 2)); }, null, 2));
console.log('Consulta da integração interna conferida; detalhes existentes verificados: ' + checkedDetails); console.log('Consulta da integração interna conferida; detalhes existentes verificados: ' + checkedDetails);
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -27,4 +38,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Pilot access and empty paginated/filtered lists; pending processes, native corrections and old sources tested in disposable databases.'},null,2)); coverage:'Pilot access and empty paginated/filtered lists; pending processes, native corrections and old sources tested in disposable databases.'},null,2));
console.log('Ocorrências e estornos paginados conferidos sem decisões ou movimentos novos no piloto.'); console.log('Ocorrências e estornos paginados conferidos sem decisões ou movimentos novos no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -24,4 +35,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'No persistent stock dispositions or reversals exist; pending decisions and physical movements tested in disposable databases only.'},null,2)); coverage:'No persistent stock dispositions or reversals exist; pending decisions and physical movements tested in disposable databases only.'},null,2));
console.log('Ocorrencias, estornos e tarefas conferidos nos perfis existentes.'); console.log('Ocorrencias, estornos e tarefas conferidos nos perfis existentes.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+130 -32
View File
@@ -1,19 +1,37 @@
// Native Fortify, CSRF and Inertia protocol for owned loopback QA only. // Native Fortify, CSRF and Inertia protocol for owned loopback QA only.
export function createNativeInertiaClient(origin, check) { export function createNativeInertiaClient(origin, check) {
const base = new URL(origin); const base = new URL(origin);
if (base.protocol !== "http:" || !["localhost", "127.0.0.1"].includes(base.hostname) || !base.port) throw Error("Owned loopback client required"); if (
base.protocol !== 'http:' ||
!['localhost', '127.0.0.1'].includes(base.hostname) ||
!base.port
)
throw Error('Owned loopback client required');
const cookies = new Map(); const cookies = new Map();
let version = ''; let version = '';
const request = async (route, options = {}) => { const request = async (route, options = {}) => {
if (!route.startsWith('/') || new URL(route, base).origin !== base.origin) throw Error('External HTTP destination refused'); if (
const response = await fetch(new URL(route, base), { ...options, redirect: 'manual', headers: { !route.startsWith('/') ||
Accept: 'application/json', Cookie: [...cookies].map(([k, v]) => `${k}=${v}`).join('; '), new URL(route, base).origin !== base.origin
...(options.headers?.['X-Inertia'] === 'true' ? { 'X-Inertia-Version': version } : {}), ...options.headers, )
} }); throw Error('External HTTP destination refused');
const response = await fetch(new URL(route, base), {
...options,
redirect: 'manual',
headers: {
Accept: 'application/json',
Cookie: [...cookies].map(([k, v]) => `${k}=${v}`).join('; '),
...(options.headers?.['X-Inertia'] === 'true'
? { 'X-Inertia-Version': version }
: {}),
...options.headers,
},
});
for (const header of response.headers.getSetCookie()) { for (const header of response.headers.getSetCookie()) {
const pair = header.split(';', 1)[0]; const pair = header.split(';', 1)[0];
const index = pair.indexOf('='); const index = pair.indexOf('=');
if (index > 0) cookies.set(pair.slice(0, index), pair.slice(index + 1)); if (index > 0)
cookies.set(pair.slice(0, index), pair.slice(index + 1));
} }
// A checker may inspect only status/headers. Drain the network body before // A checker may inspect only status/headers. Drain the network body before
// a closed PHP socket can leave Undici paused, retaining a readable clone. // a closed PHP socket can leave Undici paused, retaining a readable clone.
@@ -21,55 +39,135 @@ export function createNativeInertiaClient(origin, check) {
await response.arrayBuffer(); await response.arrayBuffer();
return buffered; return buffered;
}; };
const csrf = () => ({ 'X-XSRF-TOKEN': decodeURIComponent(cookies.get('XSRF-TOKEN') ?? '') }); const csrf = () => ({
const login = async email => { 'X-XSRF-TOKEN': decodeURIComponent(cookies.get('XSRF-TOKEN') ?? ''),
const initial = await request('/login', { headers: { Accept: 'text/html' } }); });
const login = async (email) => {
const initial = await request('/login', {
headers: { Accept: 'text/html' },
});
check(initial.status === 200, 'native login page'); check(initial.status === 200, 'native login page');
const initialPage = (await initial.text()).match(/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/); const initialPage = (await initial.text()).match(
/<script data-page="app" type="application\/json">([\s\S]*?)<\/script>/,
);
check(initialPage !== null, 'native initial page protocol'); check(initialPage !== null, 'native initial page protocol');
version = JSON.parse(initialPage[1]).version; version = JSON.parse(initialPage[1]).version;
check(typeof version === 'string' && version.length > 0, 'native asset version'); check(
const payload = JSON.stringify({ email, password: 'password', remember: false }); typeof version === 'string' && version.length > 0,
const invalid = await request('/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: payload }); 'native asset version',
);
const payload = JSON.stringify({
email,
password: 'password',
remember: false,
});
const invalid = await request('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: payload,
});
check(invalid.status === 419, 'missing CSRF refused before login'); check(invalid.status === 419, 'missing CSRF refused before login');
const response = await request('/login', { method: 'POST', headers: { 'Content-Type': 'application/json', ...csrf() }, body: payload }); const response = await request('/login', {
check([200, 302].includes(response.status), 'native Fortify credentials accepted'); method: 'POST',
const stale = await request('/dashboard', { headers: { 'X-Inertia': 'true', 'X-Inertia-Version': 'deliberately-stale-synthetic-version' } }); headers: { 'Content-Type': 'application/json', ...csrf() },
check(stale.status === 409 && stale.headers.has('X-Inertia-Location'), 'stale asset protocol refused without changing access rules'); body: payload,
const dashboard = await request('/dashboard', { headers: { 'X-Inertia': 'true' } }); });
check(dashboard.status === 200, `authenticated dashboard status ${dashboard.status}`); check(
[200, 302].includes(response.status),
'native Fortify credentials accepted',
);
const stale = await request('/dashboard', {
headers: {
'X-Inertia': 'true',
'X-Inertia-Version': 'deliberately-stale-synthetic-version',
},
});
check(
stale.status === 409 && stale.headers.has('X-Inertia-Location'),
'stale asset protocol refused without changing access rules',
);
const dashboard = await request('/dashboard', {
headers: { 'X-Inertia': 'true' },
});
check(
dashboard.status === 200,
`authenticated dashboard status ${dashboard.status}`,
);
const state = await dashboard.json(); const state = await dashboard.json();
check(state.props.auth?.user?.email === email, 'session retains the exact native actor'); check(
state.props.auth?.user?.email === email,
'session retains the exact native actor',
);
}; };
const page = async (route, component) => { const page = async (route, component) => {
const response = await request(route, { headers: { 'X-Inertia': 'true' } }); const response = await request(route, {
headers: { 'X-Inertia': 'true' },
});
let error = ''; let error = '';
if (response.status !== 200) { if (response.status !== 200) {
try { error = String((await response.clone().json()).message ?? '').slice(0, 180); } catch { /* status remains diagnostic */ } try {
error = String(
(await response.clone().json()).message ?? '',
).slice(0, 180);
} catch {
/* status remains diagnostic */
} }
check(response.status === 200, `${component} native route status ${response.status} ${error}`); }
check(response.headers.get('X-Inertia') === 'true', `${component} native Inertia response`); check(
response.status === 200,
`${component} native route status ${response.status} ${error}`,
);
check(
response.headers.get('X-Inertia') === 'true',
`${component} native Inertia response`,
);
const page = await response.json(); const page = await response.json();
check(page.component === component, `${component} component`); check(page.component === component, `${component} component`);
check(page.encryptHistory === true, `${component} encrypted history`); check(page.encryptHistory === true, `${component} encrypted history`);
if (component.startsWith('purchase-controls/')) check(response.headers.get('Cache-Control')?.includes('private') && response.headers.get('Cache-Control')?.includes('no-store'), 'purchase controls private response'); if (component.startsWith('purchase-controls/'))
check(
response.headers.get('Cache-Control')?.includes('private') &&
response.headers.get('Cache-Control')?.includes('no-store'),
'purchase controls private response',
);
return page; return page;
}; };
const logout = async () => { const logout = async () => {
check([200, 204, 302].includes((await request('/logout', { method: 'POST', headers: csrf() })).status), 'native logout'); check(
check((await request('/auditoria/eventos')).status === 401, 'closed session cannot read metadata'); [200, 204, 302].includes(
(await request('/logout', { method: 'POST', headers: csrf() }))
.status,
),
'native logout',
);
check(
(await request('/auditoria/eventos')).status === 401,
'closed session cannot read metadata',
);
}; };
const post = async (route, payload, expected = 302) => { const post = async (route, payload, expected = 302) => {
const response = await request(route, { method: 'POST', headers: { 'Content-Type': 'application/json', ...csrf() }, body: JSON.stringify(payload) }); const response = await request(route, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...csrf() },
body: JSON.stringify(payload),
});
const allowed = Array.isArray(expected) ? expected : [expected]; const allowed = Array.isArray(expected) ? expected : [expected];
let detail = ''; let detail = '';
if (!allowed.includes(response.status)) { if (!allowed.includes(response.status)) {
try { try {
const error = await response.clone().json(); const error = await response.clone().json();
detail = String(error.message ?? '').slice(0, 180) + ' fields=' + Object.keys(error.errors ?? {}).join(','); detail =
} catch { /* status is still diagnostic */ } String(error.message ?? '').slice(0, 180) +
' fields=' +
Object.keys(error.errors ?? {}).join(',');
} catch {
/* status is still diagnostic */
} }
check(allowed.includes(response.status), `native command ${route} status ${response.status} ${detail}`); }
check(
allowed.includes(response.status),
`native command ${route} status ${response.status} ${detail}`,
);
return response; return response;
}; };
return { request, login, page, logout, post }; return { request, login, page, logout, post };
+31 -9
View File
@@ -1,22 +1,44 @@
// Prepare a source overlay only; keep the host's existing feature and permission guards. // Prepare a source overlay only; keep the host's existing feature and permission guards.
export function purchasingHomeOverlay(source) { export function purchasingHomeOverlay(source) {
const once = (old, value) => { const once = (old, value) => {
if (source.split(old).length !== 2) throw Error('Purchasing home baseline changed: ' + old); if (source.split(old).length !== 2)
throw Error('Purchasing home baseline changed: ' + old);
source = source.replace(old, value); source = source.replace(old, value);
}; };
const declarations = source.match(/\bconst\s+requisitions\s*=/g) ?? []; const declarations = source.match(/\bconst\s+requisitions\s*=/g) ?? [];
if (declarations.length > 1) throw Error('Ambiguous requisition capability declaration.'); if (declarations.length > 1)
throw Error('Ambiguous requisition capability declaration.');
if (declarations.length === 0) { if (declarations.length === 0) {
once("const payables=unit!==null&&can('supplier_payables.view',unit);", "const payables=unit!==null&&can('supplier_payables.view',unit);\n const requisitions=unit!==null&&can('purchasing_requisitions.view',unit);"); once(
} else if (!/const\s+requisitions\s*=\s*unit\s*!==\s*null\s*&&\s*(?:context\.purchasing\?\.internal_requisitions\s*===\s*true\s*&&\s*)?can\(['"]purchasing_requisitions\.view['"],\s*unit\);/.test(source)) { "const payables=unit!==null&&can('supplier_payables.view',unit);",
throw Error('Unknown requisition capability guard; reconcile before preparing.'); "const payables=unit!==null&&can('supplier_payables.view',unit);\n const requisitions=unit!==null&&can('purchasing_requisitions.view',unit);",
);
} else if (
!/const\s+requisitions\s*=\s*unit\s*!==\s*null\s*&&\s*(?:context\.purchasing\?\.internal_requisitions\s*===\s*true\s*&&\s*)?can\(['"]purchasing_requisitions\.view['"],\s*unit\);/.test(
source,
)
) {
throw Error(
'Unknown requisition capability guard; reconcile before preparing.',
);
} }
if (!source.includes('href="/purchasing/internal-requisitions"')) { if (!source.includes('href="/purchasing/internal-requisitions"')) {
once('<div className="actions">', '<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições internas</a>}'); once(
'<div className="actions">',
'<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições internas</a>}',
);
} }
if (!source.includes('href="/purchasing/internal-requisitions/budget-setup"')) { if (
once('<div className="actions">', '<div className="actions">{budget&&<a href="/purchasing/internal-requisitions/budget-setup">Preparação de centros e dotações</a>}'); !source.includes(
'href="/purchasing/internal-requisitions/budget-setup"',
)
) {
once(
'<div className="actions">',
'<div className="actions">{budget&&<a href="/purchasing/internal-requisitions/budget-setup">Preparação de centros e dotações</a>}',
);
} }
if (!/!requisitions\s*&&/.test(source)) once('!budget&&!payables&&', '!budget&&!payables&&!requisitions&&'); if (!/!requisitions\s*&&/.test(source))
once('!budget&&!payables&&', '!budget&&!payables&&!requisitions&&');
return source; return source;
} }
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -22,4 +33,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Read-only pilot access and empty pagination; 210 controls/history and pending-active pairs tested in disposable databases.'},null,2)); coverage:'Read-only pilot access and empty pagination; 210 controls/history and pending-active pairs tested in disposable databases.'},null,2));
console.log('Paginação de lotes conferida no piloto, sem novos dados ou permissões.'); console.log('Paginação de lotes conferida no piloto, sem novos dados ou permissões.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -23,4 +34,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Pilot has no active lot controls or operational quality grants; pending decisions and lot links exercised in disposable databases.'},null,2)); coverage:'Pilot has no active lot controls or operational quality grants; pending decisions and lot links exercised in disposable databases.'},null,2));
console.log('Consulta e restrições de qualidade conferidas sem alterar lotes, decisões ou direitos no piloto.'); console.log('Consulta e restrições de qualidade conferidas sem alterar lotes, decisões ou direitos no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -21,4 +32,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Live pilot has no lot setups or operational lot grants; pending configuration review tested only in disposable databases.'},null,2)); coverage:'Live pilot has no lot setups or operational lot grants; pending configuration review tested only in disposable databases.'},null,2));
console.log('Controlo por lotes e tarefas conferidos sem novas concessoes.'); console.log('Controlo por lotes e tarefas conferidos sem novas concessoes.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+34 -5
View File
@@ -147,12 +147,41 @@ assert.equal(
configuredMulti.some((e) => e.id === 'new_request'), configuredMulti.some((e) => e.id === 'new_request'),
true, true,
); );
const capitalReaders = ['admin', 'procurement', 'finance', 'department_head', 'warehouse']; const capitalReaders = [
assert.ok(routes.some((route) => route.uri === 'projectos-imobilizado' && route.method.split('|').includes('GET'))); 'admin',
'procurement',
'finance',
'department_head',
'warehouse',
];
assert.ok(
routes.some(
(route) =>
route.uri === 'projectos-imobilizado' &&
route.method.split('|').includes('GET'),
),
);
for (const role of [...capitalReaders, 'requester']) { for (const role of [...capitalReaders, 'requester']) {
const groups = procurementNavigation([role], false, undefined, false, false, false, true); const groups = procurementNavigation(
assert.equal(groups.flatMap((group) => group.entries).some((entry) => entry.id === 'capital_register'), capitalReaders.includes(role)); [role],
if (capitalReaders.includes(role)) assert.equal(activeProcurementEntry(groups, '/projectos-imobilizado?history=qa'), 'capital_register'); false,
undefined,
false,
false,
false,
true,
);
assert.equal(
groups
.flatMap((group) => group.entries)
.some((entry) => entry.id === 'capital_register'),
capitalReaders.includes(role),
);
if (capitalReaders.includes(role))
assert.equal(
activeProcurementEntry(groups, '/projectos-imobilizado?history=qa'),
'capital_register',
);
} }
const proof = { const proof = {
checked_at: new Date().toISOString(), checked_at: new Date().toISOString(),
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','warehouse']) { for(const role of ['admin','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -16,4 +27,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
await fs.writeFile('docs/proofs/mfa-foundation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records, await fs.writeFile('docs/proofs/mfa-foundation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
enrollment_commands:false,password_changes:false,accounts_or_grants_changed:false,pilot_migration_applied:false,sgf_changed:false,visual_review:false},null,2)); enrollment_commands:false,password_changes:false,accounts_or_grants_changed:false,pilot_migration_applied:false,sgf_changed:false,visual_review:false},null,2));
console.log('Base de confirmação conferida; MFA do piloto continua desactivado.'); console.log('Base de confirmação conferida; MFA do piloto continua desactivado.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','warehouse']) { for(const role of ['admin','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -21,4 +32,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
enrollment_commands:false,password_changes:false,accounts_or_grants_changed:false,migration_status_not_inferred_from_http:true,sgf_changed:false,visual_review:false, enrollment_commands:false,password_changes:false,accounts_or_grants_changed:false,migration_status_not_inferred_from_http:true,sgf_changed:false,visual_review:false,
coverage:'Pilot remains disabled; enabled native management flows tested in disposable databases.'},null,2)); coverage:'Pilot remains disabled; enabled native management flows tested in disposable databases.'},null,2));
console.log('Interface de segurança conferida; adesão MFA do piloto permanece desactivada.'); console.log('Interface de segurança conferida; adesão MFA do piloto permanece desactivada.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) { for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -27,4 +38,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
coverage:'Existing pilot report scopes; populated dates, pagination and revoked streaming access tested in disposable databases.'},null,2)); coverage:'Existing pilot report scopes; populated dates, pagination and revoked streaming access tested in disposable databases.'},null,2));
console.log('Filtro de necessidades por aprovar conferido em leitura no piloto.'); console.log('Filtro de necessidades por aprovar conferido em leitura no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','warehouse','procurement','finance']) { for(const role of ['admin','warehouse','procurement','finance']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -23,4 +34,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
read_commands:false,business_decisions:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false, read_commands:false,business_decisions:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
coverage:'Existing synthetic profiles in read-only consultation; populated notice and mark-read flows tested in disposable databases.'},null,2)); coverage:'Existing synthetic profiles in read-only consultation; populated notice and mark-read flows tested in disposable databases.'},null,2));
console.log('Consulta dos avisos conferida sem marcar avisos do piloto como lidos.'); console.log('Consulta dos avisos conferida sem marcar avisos do piloto como lidos.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','warehouse','procurement','finance']) { for(const role of ['admin','warehouse','procurement','finance']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -15,4 +26,6 @@ for(const role of ['admin','warehouse','procurement','finance']) {
} }
await fs.writeFile('docs/proofs/operational-geography-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,classification_commands:false,approval_changes:false,mfa_activation:false,visual_review:false},null,2)); await fs.writeFile('docs/proofs/operational-geography-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,classification_commands:false,approval_changes:false,mfa_activation:false,visual_review:false},null,2));
console.log('Operational controls remain hidden pending schema approval; current geography catalogue remains available.'); console.log('Operational controls remain hidden pending schema approval; current geography catalogue remains available.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+12 -4
View File
@@ -4,11 +4,19 @@ import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
if (process.argv.length !== 3 || process.argv[2] !== '--read-only') { if (process.argv.length !== 3 || process.argv[2] !== '--read-only') {
throw new Error('Use --read-only for in-process GET checks with existing pilot actors.'); throw new Error(
'Use --read-only for in-process GET checks with existing pilot actors.',
);
} }
const root = fileURLToPath(new URL('../', import.meta.url)); const root = fileURLToPath(new URL('../', import.meta.url));
const result = spawnSync('php', ['scripts/check-standalone-pilot-profiles.php', '--read-only'], { const result = spawnSync(
cwd: root, stdio: 'inherit', windowsHide: true, 'php',
}); ['scripts/check-standalone-pilot-profiles.php', '--read-only'],
{
cwd: root,
stdio: 'inherit',
windowsHide: true,
},
);
if (result.error) throw result.error; if (result.error) throw result.error;
process.exitCode = result.status ?? 1; process.exitCode = result.status ?? 1;
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const viewer = client(); const viewer = client();
await viewer.enter('admin'); await viewer.enter('admin');
const response = await viewer.request('/administracao/parametrizacao'); const response = await viewer.request('/administracao/parametrizacao');
@@ -31,4 +42,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
await fs.writeFile('storage/app/pilot-access-source.json', JSON.stringify(snapshot, null, 2)); await fs.writeFile('storage/app/pilot-access-source.json', JSON.stringify(snapshot, null, 2));
console.log(JSON.stringify({ ...proof, current_rules: props.companyRules, console.log(JSON.stringify({ ...proof, current_rules: props.companyRules,
registered: snapshot.users.map(person => ({ id: person.id, name: person.name, department_id: person.department_id, functions: person.current_permissions, contexts: person.current_contexts })) }, null, 2)); registered: snapshot.users.map(person => ({ id: person.id, name: person.name, department_id: person.department_id, functions: person.current_permissions, contexts: person.current_contexts })) }, null, 2));
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+4 -2
View File
@@ -12,8 +12,9 @@ foreach ($settings as $key => $value) {
} }
require getcwd().'/vendor/autoload.php'; require getcwd().'/vendor/autoload.php';
$app = require getcwd().'/bootstrap/app.php'; $app = require getcwd().'/bootstrap/app.php';
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap(); $app->make(Kernel::class)->bootstrap();
use App\Models\ExternalPayment;
use App\Models\Invoice; use App\Models\Invoice;
use App\Models\PurchaseOrder; use App\Models\PurchaseOrder;
use App\Models\Supplier; use App\Models\Supplier;
@@ -21,6 +22,7 @@ use App\Models\User;
use App\Services\ExternalPaymentWorkflow; use App\Services\ExternalPaymentWorkflow;
use App\Services\SupplierBankWorkflow; use App\Services\SupplierBankWorkflow;
use App\Services\SupplierPayables; use App\Services\SupplierPayables;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Events\QueryExecuted; use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Database\QueryException; use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -147,7 +149,7 @@ if ($job === 'setup') {
} elseif (in_array($job, ['decision_fault', 'decision_confirm', 'decision_inspect'], true)) { } elseif (in_array($job, ['decision_fault', 'decision_confirm', 'decision_inspect'], true)) {
config(['common-payables.history_decisions_enabled' => true]); config(['common-payables.history_decisions_enabled' => true]);
auth()->guard()->setUser($validator); auth()->guard()->setUser($validator);
$payment = \App\Models\ExternalPayment::query()->where('amount_minor', 100000)->sole(); $payment = ExternalPayment::query()->where('amount_minor', 100000)->sole();
$frozen = fn () => hash('sha256', Payables::canonical(['imports' => DB::table('pa_history_imports')->get()->toArray(), 'links' => DB::table('pa_imported_payments')->get()->toArray()])); $frozen = fn () => hash('sha256', Payables::canonical(['imports' => DB::table('pa_history_imports')->get()->toArray(), 'links' => DB::table('pa_imported_payments')->get()->toArray()]));
$original = $frozen(); $original = $frozen();
if ($job === 'decision_fault') { if ($job === 'decision_fault') {
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[]; const results=[];
for(const role of ['admin','procurement','finance']) { for(const role of ['admin','procurement','finance']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -19,4 +30,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/payable-insights-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2)); await fs.writeFile('docs/proofs/payable-insights-pilot-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
console.log(JSON.stringify({http_checks:results.length*2,result:'passed',business_commands:false})); console.log(JSON.stringify({http_checks:results.length*2,result:'passed',business_commands:false}));
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const viewer=client(); await viewer.enter('admin'); const viewer=client(); await viewer.enter('admin');
assert.equal((await viewer.request('/contexto','POST',{area:'people',option:'people.internal'})).status,302); assert.equal((await viewer.request('/contexto','POST',{area:'people',option:'people.internal'})).status,302);
const index=await viewer.request('/pessoas'); assert.equal(index.status,200); const index=await viewer.request('/pessoas'); assert.equal(index.status,200);
@@ -18,4 +29,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/people-dossier-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',dossiersChecked,business_commands:false,visual_review:false,coverage:'Existing visible processes only; service and staff journeys exercised in disposable databases.'},null,2)); await fs.writeFile('docs/proofs/people-dossier-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',dossiersChecked,business_commands:false,visual_review:false,coverage:'Existing visible processes only; service and staff journeys exercised in disposable databases.'},null,2));
console.log('Consulta de Pessoas conferida; sem decisões ou novos registos.'); console.log('Consulta de Pessoas conferida; sem decisões ou novos registos.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+15 -4
View File
@@ -1,9 +1,17 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
const code = common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
const code =
common +
`
const viewer = client(); await viewer.enter('admin'); const viewer = client(); await viewer.enter('admin');
const dashboard = await viewer.request('/dashboard'); const dashboard = await viewer.request('/dashboard');
if (dashboard.page?.props.context?.enforced) { if (dashboard.page?.props.context?.enforced) {
@@ -57,4 +65,7 @@ await fs.writeFile('docs/proofs/people-reports-http.json',JSON.stringify({
},null,2)); },null,2));
console.log('People report and CSV verified in local evaluation.'); console.log('People report and CSV verified in local evaluation.');
`; `;
await new Function('fs', 'assert', 'return (async()=>{'+code+'})()')(fs, assert); await new Function('fs', 'assert', 'return (async()=>{' + code + '})()')(
fs,
assert,
);
+25 -6
View File
@@ -1,12 +1,29 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const proposal = JSON.parse(await fs.readFile('docs/proofs/pilot-access-proposal.json', 'utf8')); const proposal = JSON.parse(
const applied = JSON.parse(await fs.readFile('docs/proofs/pilot-access-activation.json', 'utf8')); await fs.readFile('docs/proofs/pilot-access-proposal.json', 'utf8'),
);
const applied = JSON.parse(
await fs.readFile('docs/proofs/pilot-access-activation.json', 'utf8'),
);
assert.equal(applied.result, 'applied'); assert.equal(applied.result, 'applied');
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'proposal', 'applied', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'proposal',
'applied',
'return (async()=>{' +
common +
`
const viewer = client(); const viewer = client();
await viewer.enter('admin'); await viewer.enter('admin');
const parameters = await viewer.request('/administracao/parametrizacao'); const parameters = await viewer.request('/administracao/parametrizacao');
@@ -83,4 +100,6 @@ await new Function('fs', 'assert', 'proposal', 'applied', 'return (async()=>{' +
}; };
await fs.writeFile('docs/proofs/pilot-access-activation-http.json', JSON.stringify(proof, null, 2)); await fs.writeFile('docs/proofs/pilot-access-activation-http.json', JSON.stringify(proof, null, 2));
console.log(JSON.stringify(proof, null, 2)); console.log(JSON.stringify(proof, null, 2));
` + '})()')(fs, assert, proposal, applied); ` +
'})()',
)(fs, assert, proposal, applied);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['department_head','procurement','requester']) { for(const role of ['department_head','procurement','requester']) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -22,4 +33,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
await fs.writeFile('docs/proofs/pilot-approval-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records, await fs.writeFile('docs/proofs/pilot-approval-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
quantity:'2.000',total_minor_mzn:2320,approved_by:10,business_commands:false,supplier_selection_or_order:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2)); quantity:'2.000',total_minor_mzn:2320,approved_by:10,business_commands:false,supplier_selection_or_order:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2));
console.log('Aprovacao unica e encaminhamento para consulta ao mercado confirmados.'); console.log('Aprovacao unica e encaminhamento para consulta ao mercado confirmados.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['procurement','finance','department_head']) { for(const role of ['procurement','finance','department_head']) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -26,4 +37,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/pilot-evaluation-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,supplier_selection_or_order:false,visual_review:false},null,2)); await fs.writeFile('docs/proofs/pilot-evaluation-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,supplier_selection_or_order:false,visual_review:false},null,2));
console.log('Seis avaliações neutras e encaminhamento para comparação conferidos por HTTP.'); console.log('Seis avaliações neutras e encaminhamento para comparação conferidos por HTTP.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,12 +1,25 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const viewer=client();await viewer.enter('admin');const dashboard=await viewer.request('/dashboard'); const viewer=client();await viewer.enter('admin');const dashboard=await viewer.request('/dashboard');
if(dashboard.page?.props.context?.enforced)await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'}); if(dashboard.page?.props.context?.enforced)await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'});
const response=await viewer.request('/stock/piloto.csv','GET',undefined,false); const response=await viewer.request('/stock/piloto.csv','GET',undefined,false);
assert.equal(response.status,200);assert.ok(response.text.includes('Conferido em'));assert.ok(response.text.includes('SGC autónomo'));assert.ok(response.text.includes('A preparar'));assert.ok(!response.text.includes('Solicitante — avaliação local')); assert.equal(response.status,200);assert.ok(response.text.includes('Conferido em'));assert.ok(response.text.includes('SGC autónomo'));assert.ok(response.text.includes('A preparar'));assert.ok(!response.text.includes('Solicitante — avaliação local'));
await fs.writeFile('docs/proofs/pilot-export-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,csv:'passed',dated_configuration_checks:true,account_register_exported:false,business_commands:false,accounts_or_grants_changed:false,visual_print_review:false},null,2)); await fs.writeFile('docs/proofs/pilot-export-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,csv:'passed',dated_configuration_checks:true,account_register_exported:false,business_commands:false,accounts_or_grants_changed:false,visual_print_review:false},null,2));
console.log('Exportação administrativa do diagnóstico conferida em HTTP.'); console.log('Exportação administrativa do diagnóstico conferida em HTTP.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+21 -5
View File
@@ -1,10 +1,24 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
const proof = JSON.parse(await fs.readFile('docs/proofs/pilot-market-activation.json', 'utf8')); 'utf8',
await new Function('fs', 'assert', 'proof', 'return (async()=>{' + common + ` );
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
const proof = JSON.parse(
await fs.readFile('docs/proofs/pilot-market-activation.json', 'utf8'),
);
await new Function(
'fs',
'assert',
'proof',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['procurement','finance','department_head']) { for(const role of ['procurement','finance','department_head']) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -29,4 +43,6 @@ await new Function('fs', 'assert', 'proof', 'return (async()=>{' + common + `
await fs.writeFile('docs/proofs/pilot-market-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records, await fs.writeFile('docs/proofs/pilot-market-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
totals_minor_mzn:[2320,2552,2784],business_commands:false,supplier_selection_or_order:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2)); totals_minor_mzn:[2320,2552,2784],business_commands:false,supplier_selection_or_order:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2));
console.log('Cadastros independentes, tres propostas e encaminhamento conferidos sem avaliar.'); console.log('Cadastros independentes, tres propostas e encaminhamento conferidos sem avaliar.');
` + '})()')(fs, assert, proof); ` +
'})()',
)(fs, assert, proof);
@@ -1,10 +1,27 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
const proof = JSON.parse(await fs.readFile('docs/proofs/pilot-replenishment-activation.json', 'utf8')); 'utf8',
await new Function('fs', 'assert', 'proof', 'return (async()=>{' + common + ` );
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
const proof = JSON.parse(
await fs.readFile(
'docs/proofs/pilot-replenishment-activation.json',
'utf8',
),
);
await new Function(
'fs',
'assert',
'proof',
'return (async()=>{' +
common +
`
assert.equal(proof.result, 'applied'); assert.equal(proof.result, 'applied');
const requester = client(); await requester.enter('requester'); const requester = client(); await requester.enter('requester');
assert.equal((await requester.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302); assert.equal((await requester.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
@@ -32,4 +49,6 @@ await new Function('fs', 'assert', 'proof', 'return (async()=>{' + common + `
automatic_source_reused:true,physical_milli:row.physical_milli,free_milli:row.free_milli,checks, automatic_source_reused:true,physical_milli:row.physical_milli,free_milli:row.free_milli,checks,
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2)); business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2));
console.log('Rascunho, origem da reposicao, tarefas, competencias e saldo confirmados por HTTP.'); console.log('Rascunho, origem da reposicao, tarefas, competencias e saldo confirmados por HTTP.');
` + '})()')(fs, assert, proof); ` +
'})()',
)(fs, assert, proof);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['requester','department_head']) { for(const role of ['requester','department_head']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -22,4 +33,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
await fs.writeFile('docs/proofs/pilot-submission-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records, await fs.writeFile('docs/proofs/pilot-submission-activation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,
quantity:'2.000',total_minor_mzn:2320,all_approval_steps_pending:true,business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2)); quantity:'2.000',total_minor_mzn:2320,all_approval_steps_pending:true,business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false},null,2));
console.log('Submissao e encaminhamento confirmados, sem aprovar a compra.'); console.log('Submissao e encaminhamento confirmados, sem aprovar a compra.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['procurement',403],['finance',403]]) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -21,4 +32,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Existing pilot access and lookup validation; positive source choices and suspensions tested in disposable databases.'},null,2)); coverage:'Existing pilot access and lookup validation; positive source choices and suspensions tested in disposable databases.'},null,2));
console.log('Pesquisa de políticas conferida sem criar sugestões, compras ou competências no piloto.'); console.log('Pesquisa de políticas conferida sem criar sugestões, compras ou competências no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+1 -1
View File
@@ -1,9 +1,9 @@
<?php <?php
use Tempo\Purchasing\Delivery\AccessOverlay; use Tempo\Purchasing\Delivery\AccessOverlay;
use Tempo\Purchasing\Delivery\AdminUiOverlay;
use Tempo\Purchasing\Delivery\BootOverlay; use Tempo\Purchasing\Delivery\BootOverlay;
use Tempo\Purchasing\Delivery\BudgetOverlay; use Tempo\Purchasing\Delivery\BudgetOverlay;
use Tempo\Purchasing\Delivery\AdminUiOverlay;
require dirname(__DIR__).'/integrations/sgf/access/AccessOverlay.php'; require dirname(__DIR__).'/integrations/sgf/access/AccessOverlay.php';
require dirname(__DIR__).'/integrations/sgf/operational/BudgetOverlay.php'; require dirname(__DIR__).'/integrations/sgf/operational/BudgetOverlay.php';
+120 -22
View File
@@ -3,49 +3,147 @@ import path from 'node:path';
import { createHash } from 'node:crypto'; import { createHash } from 'node:crypto';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
assert.ok(process.argv.includes('--apply-qa-preview'), 'Explicit QA preview switch required.'); assert.ok(
process.argv.includes('--apply-qa-preview'),
'Explicit QA preview switch required.',
);
const root = await fs.realpath(process.cwd()); const root = await fs.realpath(process.cwd());
const settings = JSON.parse(await fs.readFile('C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json', 'utf8')); const settings = JSON.parse(
await fs.readFile(
'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json',
'utf8',
),
);
assert.equal(settings.APP_ENV, 'payable-testing'); assert.equal(settings.APP_ENV, 'payable-testing');
assert.equal(settings.DB_HOST, '127.0.0.1'); assert.equal(settings.DB_HOST, '127.0.0.1');
assert.equal(await fs.realpath(settings.HOST_ROOT), root); assert.equal(await fs.realpath(settings.HOST_ROOT), root);
const authorization = JSON.parse(await fs.readFile('docs/proofs/rq01-source-authorization.json', 'utf8')); const authorization = JSON.parse(
await fs.readFile('docs/proofs/rq01-source-authorization.json', 'utf8'),
);
assert.equal(authorization.owner_decision, 'autorizo as melhorias propostas'); assert.equal(authorization.owner_decision, 'autorizo as melhorias propostas');
const sha = async file => createHash('sha256').update(await fs.readFile(file)).digest('hex'); const sha = async (file) =>
createHash('sha256')
.update(await fs.readFile(file))
.digest('hex');
const definitions = { const definitions = {
'--product-review': ['ee6e7404da9960181980c10b68b3c84c92d3667c163355442036b3fc0f53ab93', 'sgc-product-review-candidate-20261122', 'product-review', 'QA product presentation and order compatibility correction'], '--product-review': [
'--history-review': ['9bbca2dc15b40c05f268b118e4f16178a3120ae19329fdbe19403178e22cf251', 'sgc-history-candidate-20261122', 'history-review', 'Requisition preparation in native encrypted browser history'], 'ee6e7404da9960181980c10b68b3c84c92d3667c163355442036b3fc0f53ab93',
'--financial-review': ['4b4801f658ef0cbbc3f83311afbb610add0c7985916ba25c21af2a8b77cf683f', 'sgc-payable-insights-candidate-20261122', 'financial-review', 'Read-only native payable positions and CSV for existing financial viewers'], 'sgc-product-review-candidate-20261122',
'--history-clean-review': ['aad78d2d79f03e3d95ca880875e331973bb2f2702288945852a818837a259057', 'sgc-history-clean-candidate-20261122', 'history-clean-review', 'Correct false dirty state caused by restored technical identities; preserve protection of edited preparation'], 'product-review',
'QA product presentation and order compatibility correction',
],
'--history-review': [
'9bbca2dc15b40c05f268b118e4f16178a3120ae19329fdbe19403178e22cf251',
'sgc-history-candidate-20261122',
'history-review',
'Requisition preparation in native encrypted browser history',
],
'--financial-review': [
'4b4801f658ef0cbbc3f83311afbb610add0c7985916ba25c21af2a8b77cf683f',
'sgc-payable-insights-candidate-20261122',
'financial-review',
'Read-only native payable positions and CSV for existing financial viewers',
],
'--history-clean-review': [
'aad78d2d79f03e3d95ca880875e331973bb2f2702288945852a818837a259057',
'sgc-history-clean-candidate-20261122',
'history-clean-review',
'Correct false dirty state caused by restored technical identities; preserve protection of edited preparation',
],
}; };
const selected = Object.keys(definitions).filter(flag => process.argv.includes(flag)); const selected = Object.keys(definitions).filter((flag) =>
process.argv.includes(flag),
);
assert.ok(selected.length <= 1, 'Select exactly one reviewed delta.'); assert.ok(selected.length <= 1, 'Select exactly one reviewed delta.');
const [previous, directory, label, scope] = selected.length ? definitions[selected[0]] : ['c2203372527050e083f6cc0aab47a1e08534015d692b3a8781a26ddf65109c23', 'rq01-production-candidate-20261122', 'rq01-production', 'QA presentation of approved production destination increment']; const [previous, directory, label, scope] = selected.length
const proofNames = { 'product-review': 'product-review', 'history-review': 'requisition-history', 'financial-review': 'payable-insights', 'history-clean-review': 'requisition-history-clean', 'rq01-production': 'production-destination' }; ? definitions[selected[0]]
: [
'c2203372527050e083f6cc0aab47a1e08534015d692b3a8781a26ddf65109c23',
'rq01-production-candidate-20261122',
'rq01-production',
'QA presentation of approved production destination increment',
];
const proofNames = {
'product-review': 'product-review',
'history-review': 'requisition-history',
'financial-review': 'payable-insights',
'history-clean-review': 'requisition-history-clean',
'rq01-production': 'production-destination',
};
const currentManifest = path.join(root, 'public/build/manifest.json'); const currentManifest = path.join(root, 'public/build/manifest.json');
assert.equal(await sha(currentManifest), previous, 'Preview target changed; review before updating.'); assert.equal(
await sha(currentManifest),
previous,
'Preview target changed; review before updating.',
);
const candidate = path.join(root, 'storage/framework/testing', directory); const candidate = path.join(root, 'storage/framework/testing', directory);
const manifest = JSON.parse(await fs.readFile(path.join(candidate, 'manifest.json'), 'utf8')); const manifest = JSON.parse(
await fs.readFile(path.join(candidate, 'manifest.json'), 'utf8'),
);
const files = new Map(); const files = new Map();
for (const entry of Object.values(manifest)) { for (const entry of Object.values(manifest)) {
for (const file of [entry.file, ...(entry.css ?? []), ...(entry.assets ?? [])]) { for (const file of [
assert.ok(file.startsWith('assets/') && !file.includes('..') && !path.isAbsolute(file)); entry.file,
...(entry.css ?? []),
...(entry.assets ?? []),
]) {
assert.ok(
file.startsWith('assets/') &&
!file.includes('..') &&
!path.isAbsolute(file),
);
files.set(file, await sha(path.join(candidate, file))); files.set(file, await sha(path.join(candidate, file)));
} }
} }
const backup = path.join(root, `storage/framework/testing/manifest-before-${label}-20261122.json`); const backup = path.join(
root,
`storage/framework/testing/manifest-before-${label}-20261122.json`,
);
await fs.copyFile(currentManifest, backup, fs.constants.COPYFILE_EXCL); await fs.copyFile(currentManifest, backup, fs.constants.COPYFILE_EXCL);
for (const [file, expected] of files) { for (const [file, expected] of files) {
const target = path.join(root, 'public/build', file); const target = path.join(root, 'public/build', file);
await fs.mkdir(path.dirname(target), { recursive: true }); await fs.mkdir(path.dirname(target), { recursive: true });
try { await fs.copyFile(path.join(candidate, file), target, fs.constants.COPYFILE_EXCL); } try {
catch (error) { if (error.code !== 'EEXIST') throw error; } await fs.copyFile(
assert.equal(await sha(target), expected, 'Never replace an existing divergent chunk.'); path.join(candidate, file),
target,
fs.constants.COPYFILE_EXCL,
);
} catch (error) {
if (error.code !== 'EEXIST') throw error;
}
assert.equal(
await sha(target),
expected,
'Never replace an existing divergent chunk.',
);
} }
assert.equal(await sha(currentManifest), previous); assert.equal(await sha(currentManifest), previous);
const temporary = path.join(root, 'public/build/manifest.rq01-preview.tmp'); const temporary = path.join(root, 'public/build/manifest.rq01-preview.tmp');
await fs.copyFile(path.join(candidate, 'manifest.json'), temporary); await fs.copyFile(path.join(candidate, 'manifest.json'), temporary);
await fs.rename(temporary, currentManifest); await fs.rename(temporary, currentManifest);
const proof = { environment: 'http://127.0.0.1:8005', scope, authorization: 'rq01-source-authorization.json', assets_verified: files.size, previous_manifest_sha256: previous, manifest_sha256: await sha(currentManifest), previous_manifest_backup: backup, schemas_changed: false, business_commands: false, capability_settings_changed: false, visual_review: false }; const proof = {
await fs.writeFile(`docs/proofs/${proofNames[label]}-preview.json`, JSON.stringify(proof, null, 2) + '\n'); environment: 'http://127.0.0.1:8005',
console.log(JSON.stringify({ result: 'passed', assets_verified: files.size, manifest_sha256: proof.manifest_sha256, business_commands: false })); scope,
authorization: 'rq01-source-authorization.json',
assets_verified: files.size,
previous_manifest_sha256: previous,
manifest_sha256: await sha(currentManifest),
previous_manifest_backup: backup,
schemas_changed: false,
business_commands: false,
capability_settings_changed: false,
visual_review: false,
};
await fs.writeFile(
`docs/proofs/${proofNames[label]}-preview.json`,
JSON.stringify(proof, null, 2) + '\n',
);
console.log(
JSON.stringify({
result: 'passed',
assets_verified: files.size,
manifest_sha256: proof.manifest_sha256,
business_commands: false,
}),
);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const routes = []; const routes = [];
for (const role of ['procurement', 'finance', 'department_head']) { for (const role of ['procurement', 'finance', 'department_head']) {
const viewer = client(); const viewer = client();
@@ -36,4 +47,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
visual_review: false, coverage: 'Current first-page tasks only; complete pending journeys covered by disposable tests.' visual_review: false, coverage: 'Current first-page tasks only; complete pending journeys covered by disposable tests.'
}, null, 2)); }, null, 2));
console.log('Consulta ao mercado e ligacoes das tarefas conferidas com os perfis existentes.'); console.log('Consulta ao mercado e ligacoes das tarefas conferidas com os perfis existentes.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','warehouse','procurement']) { for(const role of ['admin','warehouse','procurement']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -20,4 +31,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
} }
await fs.writeFile('docs/proofs/receipt-block-installation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,documents_uploaded:false,visual_review:false},null,2)); await fs.writeFile('docs/proofs/receipt-block-installation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,documents_uploaded:false,visual_review:false},null,2));
console.log('Recepções consultadas no piloto; sem comandos de negócio.'); console.log('Recepções consultadas no piloto; sem comandos de negócio.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','warehouse','procurement']) { for(const role of ['admin','warehouse','procurement']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -20,4 +31,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/receipt-print-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,visual_review:false},null,2)); await fs.writeFile('docs/proofs/receipt-print-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,visual_review:false},null,2));
console.log('Reprodução imprimível consultada; sem movimentos ou decisões.'); console.log('Reprodução imprimível consultada; sem movimentos ou decisões.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const viewer=client(); await viewer.enter('admin'); const viewer=client(); await viewer.enter('admin');
assert.equal((await viewer.request('/contexto','POST',{area:'people',option:'people.internal'})).status,302); assert.equal((await viewer.request('/contexto','POST',{area:'people',option:'people.internal'})).status,302);
const index=await viewer.request('/pessoas'); assert.equal(index.status,200); const index=await viewer.request('/pessoas'); assert.equal(index.status,200);
@@ -21,4 +32,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/received-availability-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',dossiersChecked,availabilityRows,business_commands:false,visual_review:false,coverage:'Existing visible processes only; positive received-availability cases exercised in disposable tests.'},null,2)); await fs.writeFile('docs/proofs/received-availability-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',dossiersChecked,availabilityRows,business_commands:false,visual_review:false,coverage:'Existing visible processes only; positive received-availability cases exercised in disposable tests.'},null,2));
console.log('People page/dossier availability projection checked for existing visible sources only.'); console.log('People page/dossier availability projection checked for existing visible sources only.');
` + '})()')(fs, assert); ` +
'})()',
)(fs, assert);
@@ -39,6 +39,7 @@ $result = DB::transaction(function () use ($backup): array {
'reason' => 'Corrigir apenas a codificacao dos rotulos sinteticos gerados, reutilizando o nome existente do titular.']); 'reason' => 'Corrigir apenas a codificacao dos rotulos sinteticos gerados, reutilizando o nome existente do titular.']);
$repaired++; $repaired++;
} }
return ['state' => 'passed', 'generated_profile_labels_repaired' => $repaired, 'permissions_contexts_users_and_credentials_changed' => false]; return ['state' => 'passed', 'generated_profile_labels_repaired' => $repaired, 'permissions_contexts_users_and_credentials_changed' => false];
}); });
$path = '/root/compras-demo-access.json'; $path = '/root/compras-demo-access.json';
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',403]]) { for(const [role,expected] of [['admin',200],['warehouse',403]]) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -21,4 +32,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
pilot_health_command_executed:false,business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false, pilot_health_command_executed:false,business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
coverage:'Existing tenant-scoped diagnostic UI and rights preserved; CLI health executed only in disposable databases.'},null,2)); coverage:'Existing tenant-scoped diagnostic UI and rights preserved; CLI health executed only in disposable databases.'},null,2));
console.log('Diagnóstico do piloto conferido em leitura, sem executar reposições.'); console.log('Diagnóstico do piloto conferido em leitura, sem executar reposições.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const viewer=client(); await viewer.enter('admin'); const viewer=client(); await viewer.enter('admin');
const dashboard=await viewer.request('/dashboard'); const dashboard=await viewer.request('/dashboard');
if(dashboard.page?.props.context?.enforced)await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'}); if(dashboard.page?.props.context?.enforced)await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'});
@@ -15,4 +26,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
assert.ok(Date.now()-Date.parse(p.schedulerStatus.finished_at)<120000); assert.ok(Date.now()-Date.parse(p.schedulerStatus.finished_at)<120000);
await fs.writeFile('docs/proofs/replenishment-pilot-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,component:'stock/replenishment',recovery_installed:true,pagination:['rules','needs','history','workItems'],filter:'pending',scheduler:p.schedulerStatus,administrator_read_only:true,business_commands:false,accounts_or_grants_changed:false,visual_browser_review:false},null,2)); await fs.writeFile('docs/proofs/replenishment-pilot-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,component:'stock/replenishment',recovery_installed:true,pagination:['rules','needs','history','workItems'],filter:'pending',scheduler:p.schedulerStatus,administrator_read_only:true,business_commands:false,accounts_or_grants_changed:false,visual_browser_review:false},null,2));
console.log('Reposição: paginação, filtro, recuperação e passagem recente do serviço confirmados por HTTP.'); console.log('Reposição: paginação, filtro, recuperação e passagem recente do serviço confirmados por HTTP.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const role of ['admin','procurement','finance','warehouse']) { for(const role of ['admin','procurement','finance','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -22,4 +33,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_changed:false,visual_review:false,
coverage:'Read-only metadata export of existing synthetic requisition 2, compared with native detail visibility.'},null,2)); coverage:'Read-only metadata export of existing synthetic requisition 2, compared with native detail visibility.'},null,2));
console.log('Metadados do histórico conferidos no piloto sem decisões ou alterações de dados.'); console.log('Metadados do histórico conferidos no piloto sem decisões ou alterações de dados.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
File diff suppressed because it is too large Load Diff
+64 -18
View File
@@ -6,45 +6,91 @@ import crypto from 'node:crypto';
import { spawnSync } from 'node:child_process'; import { spawnSync } from 'node:child_process';
const workspace = 'C:/laragon/www/compras'; const workspace = 'C:/laragon/www/compras';
if (path.resolve(process.cwd()) !== path.resolve(workspace)) throw Error('Compras workspace required'); if (path.resolve(process.cwd()) !== path.resolve(workspace))
throw Error('Compras workspace required');
const canonical = 'C:/laragon/www/sgf-tempo/packages'; const canonical = 'C:/laragon/www/sgf-tempo/packages';
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex'); const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
const sources = ['finance-bundle/Bundle.php']; const sources = ['finance-bundle/Bundle.php'];
for (const name of ['payables', 'general-ledger']) { for (const name of ['payables', 'general-ledger']) {
for (const file of ['bootstrap.php', 'README.md']) { for (const file of ['bootstrap.php', 'README.md']) {
if (fs.existsSync(path.join(canonical, name, file))) sources.push(`${name}/${file}`); if (fs.existsSync(path.join(canonical, name, file)))
sources.push(`${name}/${file}`);
} }
for (const dir of ['src', 'ui']) { for (const dir of ['src', 'ui']) {
for (const file of fs.readdirSync(path.join(canonical, name, dir)).sort()) { for (const file of fs
if (!/^[A-Za-z0-9_-]+\.php$/.test(file)) throw Error('Unexpected runtime source'); .readdirSync(path.join(canonical, name, dir))
.sort()) {
if (!/^[A-Za-z0-9_-]+\.php$/.test(file))
throw Error('Unexpected runtime source');
sources.push(`${name}/${dir}/${file}`); sources.push(`${name}/${dir}/${file}`);
} }
} }
} }
const content = sources.map(source => { const content = sources
.map((source) => {
const actual = path.join(canonical, source); const actual = path.join(canonical, source);
if (!fs.lstatSync(actual).isFile() || fs.lstatSync(actual).isSymbolicLink()) throw Error('Regular runtime files required'); if (
return { file: source === 'finance-bundle/Bundle.php' ? 'Bundle.php' : source, bytes: fs.readFileSync(actual) }; !fs.lstatSync(actual).isFile() ||
}).sort((a, b) => a.file.localeCompare(b.file)); fs.lstatSync(actual).isSymbolicLink()
)
throw Error('Regular runtime files required');
return {
file:
source === 'finance-bundle/Bundle.php' ? 'Bundle.php' : source,
bytes: fs.readFileSync(actual),
};
})
.sort((a, b) => a.file.localeCompare(b.file));
const files = content.map(({ file, bytes }) => ({ file, sha256: hash(bytes) })); const files = content.map(({ file, bytes }) => ({ file, sha256: hash(bytes) }));
const manifest = JSON.stringify({ contract: 'COMMON-FINANCE-BUNDLE-v1', synthetic_only: true, files }, null, 2) + '\n'; const manifest =
JSON.stringify(
{ contract: 'COMMON-FINANCE-BUNDLE-v1', synthetic_only: true, files },
null,
2,
) + '\n';
const pin = hash(manifest); const pin = hash(manifest);
const root = path.join(workspace, 'storage/framework/testing', `requisition-ledger-runtime-qa-${pin.slice(0, 16)}`); const root = path.join(
workspace,
'storage/framework/testing',
`requisition-ledger-runtime-qa-${pin.slice(0, 16)}`,
);
if (!fs.existsSync(root)) { if (!fs.existsSync(root)) {
fs.mkdirSync(root); fs.mkdirSync(root);
for (const { file, bytes } of content) { for (const { file, bytes } of content) {
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
fs.writeFileSync(path.join(root, file), bytes, { flag: 'wx' }); fs.writeFileSync(path.join(root, file), bytes, { flag: 'wx' });
} }
fs.writeFileSync(path.join(root, 'manifest.json'), manifest, { flag: 'wx' }); fs.writeFileSync(path.join(root, 'manifest.json'), manifest, {
flag: 'wx',
});
} }
if (hash(fs.readFileSync(path.join(root, 'manifest.json'))) !== pin) throw Error('Existing artefact differs; never overwrite'); if (hash(fs.readFileSync(path.join(root, 'manifest.json'))) !== pin)
throw Error('Existing artefact differs; never overwrite');
// The caller fixes this manifest and loader hash before loading any executable. // The caller fixes this manifest and loader hash before loading any executable.
for (const { file, sha256 } of files) { for (const { file, sha256 } of files) {
const target = path.join(root, file); const target = path.join(root, file);
if (!fs.lstatSync(target).isFile() || fs.lstatSync(target).isSymbolicLink() || hash(fs.readFileSync(target)) !== sha256) throw Error('Artefact byte mismatch'); if (
!fs.lstatSync(target).isFile() ||
fs.lstatSync(target).isSymbolicLink() ||
hash(fs.readFileSync(target)) !== sha256
)
throw Error('Artefact byte mismatch');
} }
const code = 'require $argv[1]."/Bundle.php"; echo json_encode(Tempo\\Finance\\Composition\\Bundle::verify($argv[1],$argv[2]),JSON_THROW_ON_ERROR);'; const code =
const checked = spawnSync('php', ['-r', code, root, pin], { windowsHide: true, encoding: 'utf8' }); 'require $argv[1]."/Bundle.php"; echo json_encode(Tempo\\Finance\\Composition\\Bundle::verify($argv[1],$argv[2]),JSON_THROW_ON_ERROR);';
if (checked.status !== 0) throw Error('Existing common bundle verifier refused the private artefact'); const checked = spawnSync('php', ['-r', code, root, pin], {
console.log(JSON.stringify({ root, manifest_sha256: pin, files: files.length, verified: true, synthetic_only: true, installed_or_activated: false })); windowsHide: true,
encoding: 'utf8',
});
if (checked.status !== 0)
throw Error('Existing common bundle verifier refused the private artefact');
console.log(
JSON.stringify({
root,
manifest_sha256: pin,
files: files.length,
verified: true,
synthetic_only: true,
installed_or_activated: false,
}),
);
+357 -76
View File
@@ -2,19 +2,45 @@ import crypto from 'node:crypto';
import { createNativeInertiaClient } from './lib/native-inertia-client.mjs'; import { createNativeInertiaClient } from './lib/native-inertia-client.mjs';
/** Exercise native Fortify sessions and read routes, without business commands or a browser claim. */ /** Exercise native Fortify sessions and read routes, without business commands or a browser claim. */
export async function verifyNativeReviewHttp(origin, fixture, { assets, snapshot }) { export async function verifyNativeReviewHttp(
origin,
fixture,
{ assets, snapshot },
) {
const base = new URL(origin); const base = new URL(origin);
if (base.protocol !== 'http:' || !['localhost', '127.0.0.1'].includes(base.hostname) || !base.port || typeof snapshot !== 'function') throw Error('Owned loopback review required'); if (
base.protocol !== 'http:' ||
!['localhost', '127.0.0.1'].includes(base.hostname) ||
!base.port ||
typeof snapshot !== 'function'
)
throw Error('Owned loopback review required');
let checks = 0; let checks = 0;
const check = (condition, label) => { if (!condition) throw Error(`Native HTTP verification failed: ${label}`); checks++; }; const check = (condition, label) => {
if (!condition)
throw Error(`Native HTTP verification failed: ${label}`);
checks++;
};
const client = () => createNativeInertiaClient(base.href, check); const client = () => createNativeInertiaClient(base.href, check);
const guest = client(); const guest = client();
check((await guest.request('/auditoria/eventos')).status === 401, 'anonymous metadata access refused'); check(
check(Array.isArray(assets) && assets.length > 0, 'private candidate assets supplied'); (await guest.request('/auditoria/eventos')).status === 401,
'anonymous metadata access refused',
);
check(
Array.isArray(assets) && assets.length > 0,
'private candidate assets supplied',
);
for (const asset of assets) { for (const asset of assets) {
const file = await guest.request(`/build/${asset.file}`); const file = await guest.request(`/build/${asset.file}`);
check(file.status === 200, 'private candidate asset served'); check(file.status === 200, 'private candidate asset served');
check(crypto.createHash('sha256').update(Buffer.from(await file.arrayBuffer())).digest('hex') === asset.sha256, 'HTTP asset bytes match private build'); check(
crypto
.createHash('sha256')
.update(Buffer.from(await file.arrayBuffer()))
.digest('hex') === asset.sha256,
'HTTP asset bytes match private build',
);
} }
const reviewer = client(); const reviewer = client();
const auditor = client(); const auditor = client();
@@ -26,105 +52,360 @@ export async function verifyNativeReviewHttp(origin, fixture, { assets, snapshot
await privateAuditor.login(fixture.synthetic_private_audit_login); await privateAuditor.login(fixture.synthetic_private_audit_login);
// Login/logout may legitimately rotate native authentication fields. Compare the read window only. // Login/logout may legitimately rotate native authentication fields. Compare the read window only.
const before = await snapshot(); const before = await snapshot();
const privateAudit = await privateAuditor.page('/auditoria/privada', 'audit/private'); const privateAudit = await privateAuditor.page(
check(privateAudit.props.families.length === 4 && privateAudit.props.exports.data.length === 0, 'dedicated private authority opens approved families without generating a package'); '/auditoria/privada',
for (const actor of [reviewer, auditor, requester]) check((await actor.request('/auditoria/privada')).status === 403, 'other authorities cannot open private audit'); 'audit/private',
check((await privateAuditor.request('/orcamentos')).status === 403, 'private audit never grants native financial workspace'); );
const operationalOrders = await reviewer.page('/ordens-operacionais', 'requisitions/operational-orders'); check(
check((await auditor.request('/ordens-operacionais')).status === 403, 'metadata authority never grants operational order register access'); privateAudit.props.families.length === 4 &&
check(operationalOrders.props.canConfigure === true && operationalOrders.props.policy === null, 'native admin can configure origin but a GET does not select an origin'); privateAudit.props.exports.data.length === 0,
const ownOperationalOrders = await requester.page('/ordens-operacionais', 'requisitions/operational-orders'); 'dedicated private authority opens approved families without generating a package',
check(ownOperationalOrders.props.canConfigure === false && ownOperationalOrders.props.allowedTypes.length === 0, 'requester receives no production workshop or procurement order creation grant'); );
const urgentStock = await reviewer.page(`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`, 'requisitions/urgent-stock'); for (const actor of [reviewer, auditor, requester])
check(urgentStock.props.eligible.length === 0, 'ordinary historical source receives no implicit urgent reduction'); check(
check((await requester.request(`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`)).status === 403, 'request ownership does not grant stock threshold preparation or quotation oversight'); (await actor.request('/auditoria/privada')).status === 403,
'other authorities cannot open private audit',
);
check(
(await privateAuditor.request('/orcamentos')).status === 403,
'private audit never grants native financial workspace',
);
const operationalOrders = await reviewer.page(
'/ordens-operacionais',
'requisitions/operational-orders',
);
check(
(await auditor.request('/ordens-operacionais')).status === 403,
'metadata authority never grants operational order register access',
);
check(
operationalOrders.props.canConfigure === true &&
operationalOrders.props.policy === null,
'native admin can configure origin but a GET does not select an origin',
);
const ownOperationalOrders = await requester.page(
'/ordens-operacionais',
'requisitions/operational-orders',
);
check(
ownOperationalOrders.props.canConfigure === false &&
ownOperationalOrders.props.allowedTypes.length === 0,
'requester receives no production workshop or procurement order creation grant',
);
const urgentStock = await reviewer.page(
`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`,
'requisitions/urgent-stock',
);
check(
urgentStock.props.eligible.length === 0,
'ordinary historical source receives no implicit urgent reduction',
);
check(
(
await requester.request(
`/requisicoes/${fixture.historical_decision_request}/urgencia-stock`,
)
).status === 403,
'request ownership does not grant stock threshold preparation or quotation oversight',
);
const budgets = await reviewer.page('/orcamentos', 'budgets/index'); const budgets = await reviewer.page('/orcamentos', 'budgets/index');
check(budgets.props.budgets.length > 0, 'native synthetic budget is visible to its authorised reader'); check(
budgets.props.budgets.length > 0,
'native synthetic budget is visible to its authorised reader',
);
const budgetHeaders = await reviewer.request('/orcamentos'); const budgetHeaders = await reviewer.request('/orcamentos');
check(budgetHeaders.headers.get('Cache-Control')?.includes('no-store'), 'private budget response not cacheable'); check(
check((await requester.request('/orcamentos')).status === 403, 'requester cannot read operational budget preparations'); budgetHeaders.headers.get('Cache-Control')?.includes('no-store'),
'private budget response not cacheable',
);
check(
(await requester.request('/orcamentos')).status === 403,
'requester cannot read operational budget preparations',
);
for (const actor of [reviewer, requester]) { for (const actor of [reviewer, requester]) {
await actor.page('/conflitos', 'conflicts/index'); await actor.page('/conflitos', 'conflicts/index');
const response = await actor.request('/conflitos'); const response = await actor.request('/conflitos');
check(response.headers.get('Cache-Control')?.includes('no-store'), 'personal conflicts not cacheable'); check(
response.headers.get('Cache-Control')?.includes('no-store'),
'personal conflicts not cacheable',
);
} }
for (const [route, component] of [['/stock', 'stock/index'], ['/stock/operacoes', 'stock/operations']]) { for (const [route, component] of [
['/stock', 'stock/index'],
['/stock/operacoes', 'stock/operations'],
]) {
await reviewer.page(route, component); await reviewer.page(route, component);
const response = await reviewer.request(route); const response = await reviewer.request(route);
check(response.headers.get('Cache-Control')?.includes('no-store'), 'stock workspace not cacheable'); check(
check((await requester.request(route)).status === 403, 'requester cannot read operational stock workspace'); response.headers.get('Cache-Control')?.includes('no-store'),
'stock workspace not cacheable',
);
check(
(await requester.request(route)).status === 403,
'requester cannot read operational stock workspace',
);
} }
for (const [route, component] of [['/equipamentos', 'equipment/index'], ['/regras-investimento', 'investment/index']]) { for (const [route, component] of [
['/equipamentos', 'equipment/index'],
['/regras-investimento', 'investment/index'],
]) {
const page = await reviewer.page(route, component); const page = await reviewer.page(route, component);
check(page.props.canManage === true, 'native administrative preparation scope retained'); check(
page.props.canManage === true,
'native administrative preparation scope retained',
);
const response = await reviewer.request(route); const response = await reviewer.request(route);
check(response.headers.get('Cache-Control')?.includes('no-store'), 'equipment and investment preparation not cacheable'); check(
check((await requester.request(route)).status === 403, 'requester cannot inherit equipment or investment administration'); response.headers.get('Cache-Control')?.includes('no-store'),
'equipment and investment preparation not cacheable',
);
check(
(await requester.request(route)).status === 403,
'requester cannot inherit equipment or investment administration',
);
} }
const companyConfiguration = await reviewer.page('/administracao/parametrizacao', 'company/parameters'); const companyConfiguration = await reviewer.page(
check(companyConfiguration.props.ready === true && Array.isArray(companyConfiguration.props.profiles) && companyConfiguration.props.profiles.length > 0, 'existing synthetic company configuration remains consultable'); '/administracao/parametrizacao',
const companyResponse = await reviewer.request('/administracao/parametrizacao'); 'company/parameters',
check(companyResponse.headers.get('Cache-Control')?.includes('no-store'), 'company configuration not cacheable'); );
check((await requester.request('/administracao/parametrizacao')).status === 403, 'requester cannot inherit configuration administration'); check(
const detail = await reviewer.page(`/requisicoes/${fixture.historical_decision_request}`, 'requisitions/show'); companyConfiguration.props.ready === true &&
check(detail.props.canReadAuditMetadata === true, 'native request audit navigation permission'); Array.isArray(companyConfiguration.props.profiles) &&
const history = await reviewer.page(`/requisicoes/${fixture.historical_decision_request}/prazos`, 'requisitions/expiry'); companyConfiguration.props.profiles.length > 0,
check(history.props.history.data[0].request.total_minor === 10000, 'original cycle amount survives native HTTP'); 'existing synthetic company configuration remains consultable',
const query = new URLSearchParams({ request_reference: fixture.audit_request_reference }); );
const metadata = await reviewer.page(`/auditoria/eventos?${query}`, 'audit/metadata'); const companyResponse = await reviewer.request(
check(metadata.props.requestContext?.number === fixture.audit_request_reference, 'authorised native context locator'); '/administracao/parametrizacao',
const minimalEvents = page => { );
check(page.props.events.data.length > 0, 'filtered native events present'); check(
check(page.props.events.data.every(e => JSON.stringify(Object.keys(e).sort()) === JSON.stringify(['action', 'created_at', 'id', 'user_id'])), 'events contain only four metadata fields'); companyResponse.headers.get('Cache-Control')?.includes('no-store'),
'company configuration not cacheable',
);
check(
(await requester.request('/administracao/parametrizacao')).status ===
403,
'requester cannot inherit configuration administration',
);
const detail = await reviewer.page(
`/requisicoes/${fixture.historical_decision_request}`,
'requisitions/show',
);
check(
detail.props.canReadAuditMetadata === true,
'native request audit navigation permission',
);
const history = await reviewer.page(
`/requisicoes/${fixture.historical_decision_request}/prazos`,
'requisitions/expiry',
);
check(
history.props.history.data[0].request.total_minor === 10000,
'original cycle amount survives native HTTP',
);
const query = new URLSearchParams({
request_reference: fixture.audit_request_reference,
});
const metadata = await reviewer.page(
`/auditoria/eventos?${query}`,
'audit/metadata',
);
check(
metadata.props.requestContext?.number ===
fixture.audit_request_reference,
'authorised native context locator',
);
const minimalEvents = (page) => {
check(
page.props.events.data.length > 0,
'filtered native events present',
);
check(
page.props.events.data.every(
(e) =>
JSON.stringify(Object.keys(e).sort()) ===
JSON.stringify(['action', 'created_at', 'id', 'user_id']),
),
'events contain only four metadata fields',
);
}; };
minimalEvents(metadata); minimalEvents(metadata);
for (const [view, component] of [['agreements', 'supply/index'], ['contracts', 'supply/index'], ['calendar', 'supply/index'], ['imports', 'supply/index'], for (const [view, component] of [
['history', 'supply/history'], ['suggestions', 'supply/suggestions'], ['reservations', 'supply/coordination'], ['deliveries', 'supply/coordination'], ['alternatives', 'supply/coordination']]) { ['agreements', 'supply/index'],
const page = await reviewer.page(`/compras/fornecimento?view=${view}`, component); ['contracts', 'supply/index'],
if (['imports', 'reservations', 'deliveries', 'alternatives'].includes(view)) check(page.props.canPrepare === false, `${view} read does not grant preparation`); ['calendar', 'supply/index'],
['imports', 'supply/index'],
['history', 'supply/history'],
['suggestions', 'supply/suggestions'],
['reservations', 'supply/coordination'],
['deliveries', 'supply/coordination'],
['alternatives', 'supply/coordination'],
]) {
const page = await reviewer.page(
`/compras/fornecimento?view=${view}`,
component,
);
if (
['imports', 'reservations', 'deliveries', 'alternatives'].includes(
view,
)
)
check(
page.props.canPrepare === false,
`${view} read does not grant preparation`,
);
} }
const operationalControls = await reviewer.page('/revisao-compras', 'purchase-controls/index'); const operationalControls = await reviewer.page(
check(operationalControls.props.policies.length === 1 && operationalControls.props.policies[0].status === 'pending' && operationalControls.props.policies[0].enabled === false, 'existing synthetic policy remains pending and disabled in operational view'); '/revisao-compras',
'purchase-controls/index',
);
check(
operationalControls.props.policies.length === 1 &&
operationalControls.props.policies[0].status === 'pending' &&
operationalControls.props.policies[0].enabled === false,
'existing synthetic policy remains pending and disabled in operational view',
);
await reviewer.page('/ordens/cancelamentos', 'purchase-controls/orders'); await reviewer.page('/ordens/cancelamentos', 'purchase-controls/orders');
const ownControls = await requester.page('/revisao-compras', 'purchase-controls/index'); const ownControls = await requester.page(
check(ownControls.props.policies.length === 0 && ownControls.props.awards.length === 0 && ownControls.props.cancellations.length === 0, 'requester does not inherit operational policy or cancellation data'); '/revisao-compras',
const ownRequest = await requester.page(`/requisicoes/${fixture.historical_decision_request}`, 'requisitions/show'); 'purchase-controls/index',
check(ownRequest.props.canReadAuditMetadata === false, 'request ownership does not grant metadata audit'); );
check((await requester.request('/auditoria/eventos')).status === 403, 'requester audit route refuses absent capability'); check(
const limited = await auditor.page(`/auditoria/eventos?${query}`, 'audit/metadata'); ownControls.props.policies.length === 0 &&
ownControls.props.awards.length === 0 &&
ownControls.props.cancellations.length === 0,
'requester does not inherit operational policy or cancellation data',
);
const ownRequest = await requester.page(
`/requisicoes/${fixture.historical_decision_request}`,
'requisitions/show',
);
check(
ownRequest.props.canReadAuditMetadata === false,
'request ownership does not grant metadata audit',
);
check(
(await requester.request('/auditoria/eventos')).status === 403,
'requester audit route refuses absent capability',
);
const limited = await auditor.page(
`/auditoria/eventos?${query}`,
'audit/metadata',
);
minimalEvents(limited); minimalEvents(limited);
check(limited.props.requestContext === null, 'metadata-only actor receives no private process locator'); check(
check((await auditor.request(`/requisicoes/${fixture.historical_decision_request}`)).status === 404, 'metadata-only actor cannot read private request'); limited.props.requestContext === null,
check((await auditor.request('/compras/fornecimento?view=agreements')).status === 403, 'metadata grant does not grant supply access'); 'metadata-only actor receives no private process locator',
const csv = async actor => { );
check(
(
await auditor.request(
`/requisicoes/${fixture.historical_decision_request}`,
)
).status === 404,
'metadata-only actor cannot read private request',
);
check(
(await auditor.request('/compras/fornecimento?view=agreements'))
.status === 403,
'metadata grant does not grant supply access',
);
const csv = async (actor) => {
const response = await actor.request(`/auditoria/eventos.csv?${query}`); const response = await actor.request(`/auditoria/eventos.csv?${query}`);
check(response.status === 200 && response.headers.get('Content-Type')?.includes('text/csv'), 'native metadata CSV'); check(
check(response.headers.get('Cache-Control')?.includes('no-store'), 'private CSV not cacheable'); response.status === 200 &&
response.headers.get('Content-Type')?.includes('text/csv'),
'native metadata CSV',
);
check(
response.headers.get('Cache-Control')?.includes('no-store'),
'private CSV not cacheable',
);
const body = await response.text(); const body = await response.text();
check(body.includes(fixture.audit_request_reference), 'CSV preserves exact criteria'); check(
body.includes(fixture.audit_request_reference),
'CSV preserves exact criteria',
);
return body; return body;
}; };
check(await csv(reviewer) === await csv(auditor), 'both metadata grants export the same scoped metadata without private context'); check(
(await csv(reviewer)) === (await csv(auditor)),
'both metadata grants export the same scoped metadata without private context',
);
const after = await snapshot(); const after = await snapshot();
check(JSON.stringify(before) === JSON.stringify(after), 'all native table rows and columns unchanged during read window'); check(
const auditInput = {operation_key: crypto.randomUUID(), families: ['purchasing', 'stock', 'finance', 'configuration'], purpose: 'Owned synthetic native QA export'}; JSON.stringify(before) === JSON.stringify(after),
'all native table rows and columns unchanged during read window',
);
const auditInput = {
operation_key: crypto.randomUUID(),
families: ['purchasing', 'stock', 'finance', 'configuration'],
purpose: 'Owned synthetic native QA export',
};
await privateAuditor.post('/auditoria/privada', auditInput); await privateAuditor.post('/auditoria/privada', auditInput);
const prepared = await privateAuditor.page('/auditoria/privada', 'audit/private'); const prepared = await privateAuditor.page(
check(prepared.props.exports.data.length === 1, 'one private package prepared after the unchanged read window'); '/auditoria/privada',
'audit/private',
);
check(
prepared.props.exports.data.length === 1,
'one private package prepared after the unchanged read window',
);
const packageRow = prepared.props.exports.data[0]; const packageRow = prepared.props.exports.data[0];
const download = await privateAuditor.request(packageRow.download_url); const download = await privateAuditor.request(packageRow.download_url);
check(download.status === 200 && download.headers.get('Cache-Control')?.includes('no-store'), 'authenticated private package download'); check(
download.status === 200 &&
download.headers.get('Cache-Control')?.includes('no-store'),
'authenticated private package download',
);
const bytes = Buffer.from(await download.arrayBuffer()); const bytes = Buffer.from(await download.arrayBuffer());
check(bytes.length === packageRow.size && crypto.createHash('sha256').update(bytes).digest('hex') === packageRow.sha256, 'native download bytes match immutable package size and SHA256'); check(
bytes.length === packageRow.size &&
crypto.createHash('sha256').update(bytes).digest('hex') ===
packageRow.sha256,
'native download bytes match immutable package size and SHA256',
);
await privateAuditor.post('/auditoria/privada', auditInput); await privateAuditor.post('/auditoria/privada', auditInput);
const replay = await privateAuditor.page('/auditoria/privada', 'audit/private'); const replay = await privateAuditor.page(
check(replay.props.exports.data.length === 1 && replay.props.exports.data[0].sha256 === packageRow.sha256, 'replay preserves the same archive'); '/auditoria/privada',
check((await auditor.request(packageRow.download_url)).status === 403, 'metadata cannot download private package'); 'audit/private',
);
check(
replay.props.exports.data.length === 1 &&
replay.props.exports.data[0].sha256 === packageRow.sha256,
'replay preserves the same archive',
);
check(
(await auditor.request(packageRow.download_url)).status === 403,
'metadata cannot download private package',
);
await reviewer.logout(); await reviewer.logout();
await auditor.logout(); await auditor.logout();
await requester.logout(); await requester.logout();
await privateAuditor.logout(); await privateAuditor.logout();
return { checks, fortify_sessions: 4, missing_csrf_refused: true, stale_inertia_version_refused: true, supply_views: 9, purchase_control_views: 2, requester_scope_verified: true, encrypted_history_verified: true, return {
budget_view_verified: true, conflict_index_verified: true, stock_views_verified: 2, equipment_view_verified: true, investment_view_verified: true, company_configuration_verified: true, operational_orders_verified: true, urgent_stock_verified: true, metadata_scope_isolation_verified: true, readonly_tables_equal: Object.keys(before).length, checks,
private_asset_verified: true, private_assets_verified: assets.length, business_commands_sent: 0, audit_export_commands_sent: 2, private_audit_download_verified: true, browser_visual_acceptance: false }; fortify_sessions: 4,
missing_csrf_refused: true,
stale_inertia_version_refused: true,
supply_views: 9,
purchase_control_views: 2,
requester_scope_verified: true,
encrypted_history_verified: true,
budget_view_verified: true,
conflict_index_verified: true,
stock_views_verified: 2,
equipment_view_verified: true,
investment_view_verified: true,
company_configuration_verified: true,
operational_orders_verified: true,
urgent_stock_verified: true,
metadata_scope_isolation_verified: true,
readonly_tables_equal: Object.keys(before).length,
private_asset_verified: true,
private_assets_verified: assets.length,
business_commands_sent: 0,
audit_export_commands_sent: 2,
private_audit_download_verified: true,
browser_visual_acceptance: false,
};
} }
+697 -162
View File
@@ -2,145 +2,393 @@ import crypto from 'node:crypto';
import { createNativeInertiaClient } from './lib/native-inertia-client.mjs'; import { createNativeInertiaClient } from './lib/native-inertia-client.mjs';
/** Same 100 MZN illustrative office scenario as the native Pest journey, through real HTTP sessions. */ /** Same 100 MZN illustrative office scenario as the native Pest journey, through real HTTP sessions. */
export async function verifyOfficePurchaseHttp(origin, fixture, readState, progress) { export async function verifyOfficePurchaseHttp(
origin,
fixture,
readState,
progress,
) {
const office = fixture.office_journey; const office = fixture.office_journey;
if (!office || fixture.synthetic_only !== true || typeof readState !== 'function') throw Error('Dedicated synthetic office HTTP fixture required'); if (
!office ||
fixture.synthetic_only !== true ||
typeof readState !== 'function'
)
throw Error('Dedicated synthetic office HTTP fixture required');
let checks = 0; let checks = 0;
let commands = 0; let commands = 0;
let phase = 'login'; let phase = 'login';
const check = (condition, label) => { if (!condition) throw Error(`Office HTTP verification failed [${phase}]: ${label}`); checks++; }; const check = (condition, label) => {
const stage = name => { phase = name; progress?.({ office_http_phase: name, checks }); }; if (!condition)
throw Error(`Office HTTP verification failed [${phase}]: ${label}`);
checks++;
};
const stage = (name) => {
phase = name;
progress?.({ office_http_phase: name, checks });
};
const clients = {}; const clients = {};
for (const [name, actor] of Object.entries(office.actors)) { for (const [name, actor] of Object.entries(office.actors)) {
clients[name] = createNativeInertiaClient(origin, check); clients[name] = createNativeInertiaClient(origin, check);
await clients[name].login(actor.email); await clients[name].login(actor.email);
} }
const { owner, buyer, head, finance, reviewer, warehouse, procurement_reviewer: procurementReviewer } = clients; const {
owner,
buyer,
head,
finance,
reviewer,
warehouse,
procurement_reviewer: procurementReviewer,
} = clients;
const state = async () => { const state = async () => {
const source = await readState(); const source = await readState();
if (source.budget !== null) { if (source.budget !== null) {
// The common balance contract takes a lock. Use its native authorised endpoint, never a second calculator. // The common balance contract takes a lock. Use its native authorised endpoint, never a second calculator.
const page = await finance.page('/orcamentos', 'budgets/index'); const page = await finance.page('/orcamentos', 'budgets/index');
const budget = page.props.budgets.find(row => Number(row.id) === Number(source.budget.id)); const budget = page.props.budgets.find(
const fields = ['approved_total_minor', 'reinforced_minor', 'reserved_minor', 'committed_minor', 'consumed_minor', 'available_minor']; (row) => Number(row.id) === Number(source.budget.id),
check(budget !== undefined && fields.every(field => Object.hasOwn(budget, field)), 'native authoritative budget balance fields'); );
const fields = [
'approved_total_minor',
'reinforced_minor',
'reserved_minor',
'committed_minor',
'consumed_minor',
'available_minor',
];
check(
budget !== undefined &&
fields.every((field) => Object.hasOwn(budget, field)),
'native authoritative budget balance fields',
);
const after = await readState(); const after = await readState();
check(after.financial_fingerprint === source.financial_fingerprint, 'native balance consultation has no financial effects'); check(
after.budget.balance = Object.fromEntries(fields.map(field => [field, budget[field]])); after.financial_fingerprint === source.financial_fingerprint,
'native balance consultation has no financial effects',
);
after.budget.balance = Object.fromEntries(
fields.map((field) => [field, budget[field]]),
);
return after; return after;
} }
return source; return source;
}; };
const post = async (client, route, data, expected = 302) => { commands++; return client.post(route, data, expected); }; const post = async (client, route, data, expected = 302) => {
const date = days => new Date(Date.parse(fixture.clock) + days * 86400000).toISOString().slice(0, 10); commands++;
const roles = { department_head: head, procurement: buyer, finance: reviewer }; return client.post(route, data, expected);
};
const date = (days) =>
new Date(Date.parse(fixture.clock) + days * 86400000)
.toISOString()
.slice(0, 10);
const roles = {
department_head: head,
procurement: buyer,
finance: reviewer,
};
const awardRoles = { ...roles, procurement: procurementReviewer }; const awardRoles = { ...roles, procurement: procurementReviewer };
let selectorRefused = false; let selectorRefused = false;
let current = await state(); let current = await state();
check(current.request === null && current.budget === null && current.stock === null, 'dedicated purchase references are initially unused'); check(
current.request === null &&
current.budget === null &&
current.stock === null,
'dedicated purchase references are initially unused',
);
stage('budget'); stage('budget');
check((await owner.request('/orcamentos')).status === 403, 'requester cannot read company budget data'); check(
await post(finance, '/orcamentos', { cost_center_id: office.cost_center_id, year: Number(date(0).slice(0, 4)), (await owner.request('/orcamentos')).status === 403,
kind: 'operating', includes_tax: true, amount: '1000.00', reason: 'Dotação exclusivamente sintética do percurso HTTP, sem valores reais' }); 'requester cannot read company budget data',
);
await post(finance, '/orcamentos', {
cost_center_id: office.cost_center_id,
year: Number(date(0).slice(0, 4)),
kind: 'operating',
includes_tax: true,
amount: '1000.00',
reason: 'Dotação exclusivamente sintética do percurso HTTP, sem valores reais',
});
current = await state(); current = await state();
check(current.budget !== null && Number(current.budget.created_by) === office.actors.finance.id, 'native budget issuer'); check(
current.budget !== null &&
Number(current.budget.created_by) === office.actors.finance.id,
'native budget issuer',
);
await post(finance, `/orcamentos/${current.budget.id}/aprovar`, {}, 403); await post(finance, `/orcamentos/${current.budget.id}/aprovar`, {}, 403);
check((await state()).budget.approved_by === null, 'budget issuer cannot approve their own allocation'); check(
(await state()).budget.approved_by === null,
'budget issuer cannot approve their own allocation',
);
await post(reviewer, `/orcamentos/${current.budget.id}/aprovar`, {}); await post(reviewer, `/orcamentos/${current.budget.id}/aprovar`, {});
current = await state(); current = await state();
check(Number(current.budget.approved_by) === office.actors.reviewer.id && Number(current.budget.balance.available_minor) === 100000, 'independent native budget approval'); check(
Number(current.budget.approved_by) === office.actors.reviewer.id &&
Number(current.budget.balance.available_minor) === 100000,
'independent native budget approval',
);
stage('request_and_accounts'); stage('request_and_accounts');
await post(owner, '/requisicoes', { operation_key: crypto.randomUUID(), cost_center_id: office.cost_center_id, await post(owner, '/requisicoes', {
priority: 'normal', needed_by: date(7), justification: 'Compra HTTP exclusivamente sintética; taxa ilustrativa zero, sem regra fiscal real', operation_key: crypto.randomUUID(),
items: [{ description: 'Material de escritório HTTP QA', category: office.category, purchase_type: 'consumable', cost_center_id: office.cost_center_id,
production_area: null, quantity: '1.000', unit: 'un', unit_price: '100.00', tax_rate: '0.00', priority: 'normal',
procurement_category: 'office_equipment', category_reason: 'Aquisição de escritório exclusivamente sintética para testar o percurso HTTP' }] }); needed_by: date(7),
justification:
'Compra HTTP exclusivamente sintética; taxa ilustrativa zero, sem regra fiscal real',
items: [
{
description: 'Material de escritório HTTP QA',
category: office.category,
purchase_type: 'consumable',
production_area: null,
quantity: '1.000',
unit: 'un',
unit_price: '100.00',
tax_rate: '0.00',
procurement_category: 'office_equipment',
category_reason:
'Aquisição de escritório exclusivamente sintética para testar o percurso HTTP',
},
],
});
current = await state(); current = await state();
const requestId = current.request.id; const requestId = current.request.id;
const lineId = current.request.items[0].id; const lineId = current.request.items[0].id;
let capital = null; let capital = null;
if (office.capital_register) { if (office.capital_register) {
await post(buyer, '/projectos-imobilizado', { operation_key: crypto.randomUUID(), record_key: null, version: 0, await post(buyer, '/projectos-imobilizado', {
type: 'project', code: office.capital_register.code, name: 'Projecto exclusivamente sintético do percurso HTTP', operation_key: crypto.randomUUID(),
department_id: office.capital_register.department_id, equipment_id: null, reference: 'Origem documental fictícia de ensaio', record_key: null,
state: 'active', reason: 'Cadastro próprio de Compras para conferir rastreabilidade sem dados reais' }); version: 0,
const register = await buyer.page('/projectos-imobilizado', 'equipment/capital-register'); type: 'project',
capital = register.props.records.data.find(row => row.data.code === office.capital_register.code); code: office.capital_register.code,
check(capital !== undefined && capital.version === 1, 'own project created through native HTTP'); name: 'Projecto exclusivamente sintético do percurso HTTP',
const choices = await owner.page(`/requisicoes/${requestId}/projectos-imobilizado`, 'requisitions/capital-assignments'); department_id: office.capital_register.department_id,
check(choices.props.canWrite && choices.props.choices.data.some(row => row.id === capital.id), 'request owner sees the native capital destination'); equipment_id: null,
await post(owner, `/requisicoes/${requestId}/projectos-imobilizado`, { operation_key: crypto.randomUUID(), version: 0, reference: 'Origem documental fictícia de ensaio',
item_id: lineId, capital_id: capital.id, reason: 'Destino explícito da linha para o projecto estritamente sintético' }); state: 'active',
check((await owner.request('/projectos-imobilizado')).status === 403, 'assignment visibility does not grant the requester access to the register'); reason: 'Cadastro próprio de Compras para conferir rastreabilidade sem dados reais',
});
const register = await buyer.page(
'/projectos-imobilizado',
'equipment/capital-register',
);
capital = register.props.records.data.find(
(row) => row.data.code === office.capital_register.code,
);
check(
capital !== undefined && capital.version === 1,
'own project created through native HTTP',
);
const choices = await owner.page(
`/requisicoes/${requestId}/projectos-imobilizado`,
'requisitions/capital-assignments',
);
check(
choices.props.canWrite &&
choices.props.choices.data.some((row) => row.id === capital.id),
'request owner sees the native capital destination',
);
await post(owner, `/requisicoes/${requestId}/projectos-imobilizado`, {
operation_key: crypto.randomUUID(),
version: 0,
item_id: lineId,
capital_id: capital.id,
reason: 'Destino explícito da linha para o projecto estritamente sintético',
});
check(
(await owner.request('/projectos-imobilizado')).status === 403,
'assignment visibility does not grant the requester access to the register',
);
} }
const accountPage = await owner.page(`/requisicoes/${requestId}/contas`, 'requisitions/accounts'); const accountPage = await owner.page(
`/requisicoes/${requestId}/contas`,
'requisitions/accounts',
);
const account = accountPage.props.accounts.data[0]; const account = accountPage.props.accounts.data[0];
check(account !== undefined, 'actual common movement account available'); check(account !== undefined, 'actual common movement account available');
await post(owner, `/requisicoes/${requestId}/contas`, { operation_key: crypto.randomUUID(), version: 0, item_id: lineId, await post(owner, `/requisicoes/${requestId}/contas`, {
basis_hash: accountPage.props.items[0].basis_hash, reason: 'Imputação documental explícita na base própria do percurso HTTP QA', operation_key: crypto.randomUUID(),
allocations: [{ account_id: account.id, source_hash: account.source_hash, subtotal: '100.00', total: '100.00' }] }); version: 0,
item_id: lineId,
basis_hash: accountPage.props.items[0].basis_hash,
reason: 'Imputação documental explícita na base própria do percurso HTTP QA',
allocations: [
{
account_id: account.id,
source_hash: account.source_hash,
subtotal: '100.00',
total: '100.00',
},
],
});
current = await state(); current = await state();
const submit = { operation_key: crypto.randomUUID(), process_version: current.request.process_version }; const submit = {
operation_key: crypto.randomUUID(),
process_version: current.request.process_version,
};
await post(owner, `/requisicoes/${requestId}/submeter`, submit); await post(owner, `/requisicoes/${requestId}/submeter`, submit);
await post(owner, `/requisicoes/${requestId}/submeter`, submit); await post(owner, `/requisicoes/${requestId}/submeter`, submit);
current = await state(); current = await state();
check(current.request.status === 'pending' && Number(current.budget.balance.reserved_minor) === 10000, 'submission replay preserves one native reserve'); check(
await post(owner, `/requisicoes/${requestId}/decidir`, { operation_key: crypto.randomUUID(), process_version: current.request.process_version, current.request.status === 'pending' &&
decision: 'approved', comment: 'Tentativa própria exclusivamente sintética, que deve ser recusada' }, 403); Number(current.budget.balance.reserved_minor) === 10000,
for (let level = 0; current.request.status === 'pending' && level < 8; level++) { 'submission replay preserves one native reserve',
const step = current.request.steps.find(s => s.decision === 'pending'); );
check(step !== undefined && roles[step.role] !== undefined, 'frozen request level has a native eligible actor'); await post(
await post(roles[step.role], `/requisicoes/${requestId}/decidir`, { operation_key: crypto.randomUUID(), owner,
process_version: current.request.process_version, decision: 'approved', comment: 'Conferência independente do pedido HTTP exclusivamente sintético' }); `/requisicoes/${requestId}/decidir`,
{
operation_key: crypto.randomUUID(),
process_version: current.request.process_version,
decision: 'approved',
comment:
'Tentativa própria exclusivamente sintética, que deve ser recusada',
},
403,
);
for (
let level = 0;
current.request.status === 'pending' && level < 8;
level++
) {
const step = current.request.steps.find(
(s) => s.decision === 'pending',
);
check(
step !== undefined && roles[step.role] !== undefined,
'frozen request level has a native eligible actor',
);
await post(roles[step.role], `/requisicoes/${requestId}/decidir`, {
operation_key: crypto.randomUUID(),
process_version: current.request.process_version,
decision: 'approved',
comment:
'Conferência independente do pedido HTTP exclusivamente sintético',
});
current = await state(); current = await state();
} }
check(current.request.status === 'approved', 'native request circuit completed'); check(
current.request.status === 'approved',
'native request circuit completed',
);
stage('suppliers_and_quotes'); stage('suppliers_and_quotes');
for (let index = 0; index < 3; index++) { for (let index = 0; index < 3; index++) {
const nuit = String(300000001 + index); const nuit = String(300000001 + index);
await post(buyer, '/fornecedores', { name: `Fornecedor HTTP QA ${index + 1}`, nuit, contact: 'Contacto sintético', await post(buyer, '/fornecedores', {
email: `office-http-${index}@example.invalid`, phone: '123456789', address: 'Morada exclusivamente sintética', name: `Fornecedor HTTP QA ${index + 1}`,
category: office.category, beneficiaries: 'Beneficiário exclusivamente sintético', document_references: 'Referências fictícias de ensaio', nuit,
diligence_notes: 'Preparação de dados sintéticos sem fornecedor real', blocked: false, next_review: date(365) }); contact: 'Contacto sintético',
email: `office-http-${index}@example.invalid`,
phone: '123456789',
address: 'Morada exclusivamente sintética',
category: office.category,
beneficiaries: 'Beneficiário exclusivamente sintético',
document_references: 'Referências fictícias de ensaio',
diligence_notes:
'Preparação de dados sintéticos sem fornecedor real',
blocked: false,
next_review: date(365),
});
current = await state(); current = await state();
const supplier = current.suppliers.find(s => s.nuit === nuit); const supplier = current.suppliers.find((s) => s.nuit === nuit);
check(supplier !== undefined, 'native supplier created'); check(supplier !== undefined, 'native supplier created');
await post(finance, `/fornecedores/${supplier.id}/validar`, { version: supplier.version, status: 'active', comment: 'Conferência financeira independente de dados exclusivamente sintéticos' }); await post(finance, `/fornecedores/${supplier.id}/validar`, {
await post(buyer, `/requisicoes/${requestId}/cotacoes`, { currency: 'MZN', supplier_id: supplier.id, version: supplier.version,
reference: `HTTP-OFFICE-QUOTE-${index + 1}`, delivery_days: 5, valid_until: date(30), status: 'active',
payment_terms: 'Condições exclusivamente sintéticas de trinta dias', no_conflict: true, comment:
items: [{ requisition_item_id: lineId, unit_price: `${100 + index * 10}.00`, discount_type: 'none', discount_value: '0.00' }] }); 'Conferência financeira independente de dados exclusivamente sintéticos',
});
await post(buyer, `/requisicoes/${requestId}/cotacoes`, {
currency: 'MZN',
supplier_id: supplier.id,
reference: `HTTP-OFFICE-QUOTE-${index + 1}`,
delivery_days: 5,
valid_until: date(30),
payment_terms: 'Condições exclusivamente sintéticas de trinta dias',
no_conflict: true,
items: [
{
requisition_item_id: lineId,
unit_price: `${100 + index * 10}.00`,
discount_type: 'none',
discount_value: '0.00',
},
],
});
current = await state(); current = await state();
const quote = current.quotes.find(q => q.supplier_id === supplier.id); const quote = current.quotes.find((q) => q.supplier_id === supplier.id);
check(quote !== undefined, 'native quote created'); check(quote !== undefined, 'native quote created');
for (const evaluator of [head, reviewer]) await post(evaluator, `/cotacoes/${quote.id}/avaliar`, { for (const evaluator of [head, reviewer])
quality: '5', history: '5', payment: '5', comment: 'Avaliação independente exclusivamente sintética do percurso HTTP', no_conflict: true }); await post(evaluator, `/cotacoes/${quote.id}/avaliar`, {
quality: '5',
history: '5',
payment: '5',
comment:
'Avaliação independente exclusivamente sintética do percurso HTTP',
no_conflict: true,
});
} }
current = await state(); current = await state();
check(current.quotes.length === 3 && Number(current.quotes[0].total_minor) === 10000, 'three independently evaluated native quotations'); check(
current.quotes.length === 3 &&
Number(current.quotes[0].total_minor) === 10000,
'three independently evaluated native quotations',
);
stage('award_and_order'); stage('award_and_order');
await post(buyer, `/requisicoes/${requestId}/adjudicacao`, { quotation_id: current.quotes[0].id, await post(buyer, `/requisicoes/${requestId}/adjudicacao`, {
justification: 'Escolha exclusivamente sintética da proposta com maior pontuação pelo circuito nativo', quotation_id: current.quotes[0].id,
delivery_date: date(7), delivery_location: 'Armazém exclusivamente sintético de ensaio HTTP' }); justification:
'Escolha exclusivamente sintética da proposta com maior pontuação pelo circuito nativo',
delivery_date: date(7),
delivery_location: 'Armazém exclusivamente sintético de ensaio HTTP',
});
current = await state(); current = await state();
const awardId = current.award.id; const awardId = current.award.id;
for (let level = 0; current.award.status !== 'approved' && level < 8; level++) { for (
const step = current.award.steps.find(s => s.decision === 'pending'); let level = 0;
check(step !== undefined && awardRoles[step.role] !== undefined, 'final-value level has a native eligible actor'); current.award.status !== 'approved' && level < 8;
level++
) {
const step = current.award.steps.find((s) => s.decision === 'pending');
check(
step !== undefined && awardRoles[step.role] !== undefined,
'final-value level has a native eligible actor',
);
if (step.role === 'procurement') { if (step.role === 'procurement') {
await post(buyer, `/adjudicacoes/${awardId}/decidir`, { decision: 'approved', comment: 'Tentativa do próprio selector exclusivamente sintética, que deve ser recusada' }, 403); await post(
buyer,
`/adjudicacoes/${awardId}/decidir`,
{
decision: 'approved',
comment:
'Tentativa do próprio selector exclusivamente sintética, que deve ser recusada',
},
403,
);
current = await state(); current = await state();
check(current.award.steps.find(row => row.id === step.id)?.decision === 'pending', 'selector refusal preserves the pending independent decision'); check(
current.award.steps.find((row) => row.id === step.id)
?.decision === 'pending',
'selector refusal preserves the pending independent decision',
);
selectorRefused = true; selectorRefused = true;
} }
await post(awardRoles[step.role], `/adjudicacoes/${awardId}/decidir`, { decision: 'approved', comment: 'Conferência independente do valor final exclusivamente sintético HTTP' }); await post(awardRoles[step.role], `/adjudicacoes/${awardId}/decidir`, {
decision: 'approved',
comment:
'Conferência independente do valor final exclusivamente sintético HTTP',
});
current = await state(); current = await state();
} }
check(current.award.status === 'approved' && selectorRefused, 'native final-value approvals completed by an independent buyer'); check(
current.award.status === 'approved' && selectorRefused,
'native final-value approvals completed by an independent buyer',
);
await post(buyer, `/adjudicacoes/${awardId}/emitir`, {}); await post(buyer, `/adjudicacoes/${awardId}/emitir`, {});
current = await state(); current = await state();
const orderId = current.order.id; const orderId = current.order.id;
@@ -148,147 +396,434 @@ export async function verifyOfficePurchaseHttp(origin, fixture, readState, progr
const issued = current.financial_fingerprint; const issued = current.financial_fingerprint;
await post(buyer, `/adjudicacoes/${awardId}/emitir`, {}); await post(buyer, `/adjudicacoes/${awardId}/emitir`, {});
current = await state(); current = await state();
check(current.order.id === orderId && current.financial_fingerprint === issued, 'order replay has no financial or document effect'); check(
check(Number(current.order.total_minor) === 10000 && current.order.account_assignments[lineId].data.allocations[0].account.id === account.id, 'order preserves exact amount and native chart attribution'); current.order.id === orderId &&
check(current.order.budget_checked === true, 'new order preserves the budget authority confirmation already returned at issuance'); current.financial_fingerprint === issued,
if (capital) check(current.order.capital_assignments[lineId].snapshot.source.record_key === capital.record_key 'order replay has no financial or document effect',
&& current.order.capital_assignments[lineId].snapshot.source.version === 1, 'issued order preserves the exact native project version'); );
check(
Number(current.order.total_minor) === 10000 &&
current.order.account_assignments[lineId].data.allocations[0]
.account.id === account.id,
'order preserves exact amount and native chart attribution',
);
check(
current.order.budget_checked === true,
'new order preserves the budget authority confirmation already returned at issuance',
);
if (capital)
check(
current.order.capital_assignments[lineId].snapshot.source
.record_key === capital.record_key &&
current.order.capital_assignments[lineId].snapshot.source
.version === 1,
'issued order preserves the exact native project version',
);
const financialDocumentsHref = `/facturas?purchase_order_id=${orderId}#invoice-documents`; const financialDocumentsHref = `/facturas?purchase_order_id=${orderId}#invoice-documents`;
const financeOrder = await finance.page(`/ordens/${orderId}`, 'purchases/show'); const financeOrder = await finance.page(
check(financeOrder.props.financialDocumentsHref === financialDocumentsHref `/ordens/${orderId}`,
&& financeOrder.props.relatedProcesses.some(source => source.id === requestId && source.href === `/requisicoes/${requestId}/processo`), 'order navigation preserves exact financial and process context'); 'purchases/show',
);
check(
financeOrder.props.financialDocumentsHref === financialDocumentsHref &&
financeOrder.props.relatedProcesses.some(
(source) =>
source.id === requestId &&
source.href === `/requisicoes/${requestId}/processo`,
),
'order navigation preserves exact financial and process context',
);
const printRoute = `/ordens/${orderId}/imprimir`; const printRoute = `/ordens/${orderId}/imprimir`;
const printHeaders = { 'X-Inertia': 'true', ...(financeOrder.version === null ? {} : { 'X-Inertia-Version': financeOrder.version }) }; const printHeaders = {
const printNavigation = await finance.request(printRoute, { headers: printHeaders }); 'X-Inertia': 'true',
check(printNavigation.status === 409 && printNavigation.headers.get('x-inertia-location') === printRoute, 'authorised print navigation requests the complete HTML document'); ...(financeOrder.version === null
? {}
: { 'X-Inertia-Version': financeOrder.version }),
};
const printNavigation = await finance.request(printRoute, {
headers: printHeaders,
});
check(
printNavigation.status === 409 &&
printNavigation.headers.get('x-inertia-location') === printRoute,
'authorised print navigation requests the complete HTML document',
);
const printDocument = await finance.request(printRoute); const printDocument = await finance.request(printRoute);
check(printDocument.status === 200 && (await printDocument.text()).includes('Controlo orçamental registado na emissão.'), 'native controlled print preserves the actual budget confirmation'); check(
const privatePrint = await owner.request(printRoute, { headers: printHeaders }); printDocument.status === 200 &&
check(privatePrint.status === 403 && !privatePrint.headers.has('x-inertia-location'), 'requester receives no print redirect without native order access'); (await printDocument.text()).includes(
'Controlo orçamental registado na emissão.',
),
'native controlled print preserves the actual budget confirmation',
);
const privatePrint = await owner.request(printRoute, {
headers: printHeaders,
});
check(
privatePrint.status === 403 &&
!privatePrint.headers.has('x-inertia-location'),
'requester receives no print redirect without native order access',
);
const buyerOrder = await buyer.page(`/ordens/${orderId}`, 'purchases/show'); const buyerOrder = await buyer.page(`/ordens/${orderId}`, 'purchases/show');
// This synthetic buyer also has Admin; use the independent Procurement-only reviewer to test redaction. // This synthetic buyer also has Admin; use the independent Procurement-only reviewer to test redaction.
const independentOrder = await procurementReviewer.page(`/ordens/${orderId}`, 'purchases/show'); const independentOrder = await procurementReviewer.page(
check(buyerOrder.props.financialDocumentsHref === financialDocumentsHref && independentOrder.props.financialDocumentsHref === null, `/ordens/${orderId}`,
'order financial link follows native Admin/Finance access without Procurement inheritance'); 'purchases/show',
);
check(
buyerOrder.props.financialDocumentsHref === financialDocumentsHref &&
independentOrder.props.financialDocumentsHref === null,
'order financial link follows native Admin/Finance access without Procurement inheritance',
);
stage('receipt_and_invoice'); stage('receipt_and_invoice');
const financeReceipt = await finance.page(`/ordens/${orderId}/recepcoes`, 'receipts/order'); const financeReceipt = await finance.page(
const warehouseReceipt = await warehouse.page(`/ordens/${orderId}/recepcoes`, 'receipts/order'); `/ordens/${orderId}/recepcoes`,
check(financeReceipt.props.financialDocumentsHref === financialDocumentsHref && warehouseReceipt.props.financialDocumentsHref === null, 'receipts/order',
'receipt navigation exposes financial context only to the native reader'); );
await post(warehouse, '/stock/artigos', { code: 'HTTP-OFFICE-QA', name: 'Material de escritório HTTP QA', unit: 'un' }); const warehouseReceipt = await warehouse.page(
`/ordens/${orderId}/recepcoes`,
'receipts/order',
);
check(
financeReceipt.props.financialDocumentsHref ===
financialDocumentsHref &&
warehouseReceipt.props.financialDocumentsHref === null,
'receipt navigation exposes financial context only to the native reader',
);
await post(warehouse, '/stock/artigos', {
code: 'HTTP-OFFICE-QA',
name: 'Material de escritório HTTP QA',
unit: 'un',
});
current = await state(); current = await state();
const receipt = { idempotency_key: crypto.randomUUID(), delivery_note: 'HTTP-OFFICE-DELIVERY-QA', received_on: date(0), const receipt = {
warehouse_id: office.warehouse_id, items: [{ purchase_order_item_id: orderLineId, received_quantity: '1.000', accepted_quantity: '1.000', idempotency_key: crypto.randomUUID(),
quality_status: 'compliant', stock_item_id: current.stock.id }] }; delivery_note: 'HTTP-OFFICE-DELIVERY-QA',
received_on: date(0),
warehouse_id: office.warehouse_id,
items: [
{
purchase_order_item_id: orderLineId,
received_quantity: '1.000',
accepted_quantity: '1.000',
quality_status: 'compliant',
stock_item_id: current.stock.id,
},
],
};
await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 201); await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 201);
current = await state(); current = await state();
const received = current.financial_fingerprint; const received = current.financial_fingerprint;
const confirmedReceiptId = current.order.receipts[0].id; const confirmedReceiptId = current.order.receipts[0].id;
const financialReceiptDetail = await finance.page(`/recepcoes/${confirmedReceiptId}`, 'receipts/show'); const financialReceiptDetail = await finance.page(
const warehouseReceiptDetail = await warehouse.page(`/recepcoes/${confirmedReceiptId}`, 'receipts/show'); `/recepcoes/${confirmedReceiptId}`,
check(financialReceiptDetail.props.financialDocumentsHref === financialDocumentsHref 'receipts/show',
&& warehouseReceiptDetail.props.financialDocumentsHref === null, );
'confirmed receipt detail offers the exact financial context only to its native reader'); const warehouseReceiptDetail = await warehouse.page(
`/recepcoes/${confirmedReceiptId}`,
'receipts/show',
);
check(
financialReceiptDetail.props.financialDocumentsHref ===
financialDocumentsHref &&
warehouseReceiptDetail.props.financialDocumentsHref === null,
'confirmed receipt detail offers the exact financial context only to its native reader',
);
current = await state(); current = await state();
check(current.financial_fingerprint === received, 'receipt detail consultation preserves financial and stock sources'); check(
current.financial_fingerprint === received,
'receipt detail consultation preserves financial and stock sources',
);
await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 200); await post(warehouse, `/ordens/${orderId}/recepcoes`, receipt, 200);
current = await state(); current = await state();
check(current.financial_fingerprint === received && current.order.receipts.length === 1 && current.stock.movements === 1 && current.stock.quantity_milli === 1000, 'receipt replay preserves one physical movement'); check(
await post(finance, `/ordens/${orderId}/facturas`, { number: 'HTTP-OFFICE-INVOICE-QA', issued_on: date(0), subtotal: '100.00', tax: '0.00', total: '100.00', current.financial_fingerprint === received &&
items: [{ purchase_order_item_id: orderLineId, quantity: '1.000', unit: 'un', unit_price: '100.00', tax_rate: '0.00' }] }); current.order.receipts.length === 1 &&
current.stock.movements === 1 &&
current.stock.quantity_milli === 1000,
'receipt replay preserves one physical movement',
);
await post(finance, `/ordens/${orderId}/facturas`, {
number: 'HTTP-OFFICE-INVOICE-QA',
issued_on: date(0),
subtotal: '100.00',
tax: '0.00',
total: '100.00',
items: [
{
purchase_order_item_id: orderLineId,
quantity: '1.000',
unit: 'un',
unit_price: '100.00',
tax_rate: '0.00',
},
],
});
current = await state(); current = await state();
const invoiceId = current.invoice.id; const invoiceId = current.invoice.id;
await post(finance, `/facturas/${invoiceId}/validar`, {}, 403); await post(finance, `/facturas/${invoiceId}/validar`, {}, 403);
current = await state(); current = await state();
check(current.invoice.status === 'pending', 'invoice author cannot validate their own invoice'); check(
current.invoice.status === 'pending',
'invoice author cannot validate their own invoice',
);
await post(reviewer, `/facturas/${invoiceId}/validar`, {}); await post(reviewer, `/facturas/${invoiceId}/validar`, {});
current = await state(); current = await state();
check(current.invoice.status === 'validated' && Number(current.budget.balance.consumed_minor) === 10000 check(
&& Number(current.budget.balance.available_minor) === 90000, 'native invoice validation consumes the exact commitment'); current.invoice.status === 'validated' &&
Number(current.budget.balance.consumed_minor) === 10000 &&
Number(current.budget.balance.available_minor) === 90000,
'native invoice validation consumes the exact commitment',
);
const consumedBudget = JSON.stringify(current.budget.balance); const consumedBudget = JSON.stringify(current.budget.balance);
stage('bank_and_partial_payment'); stage('bank_and_partial_payment');
const supplierId = current.quotes[0].supplier_id; const supplierId = current.quotes[0].supplier_id;
await post(buyer, `/fornecedores/${supplierId}/dados-bancarios`, { account_key: crypto.randomUUID(), previous_id: 0, await post(buyer, `/fornecedores/${supplierId}/dados-bancarios`, {
bank_name: 'Banco exclusivamente sintético HTTP QA', country: 'MZ', currency: 'MZN', beneficiary: 'Titular exclusivamente sintético', account_key: crypto.randomUUID(),
account_identifier: 'HTTP-OFFICE-ACCOUNT-QA', evidence_reference: 'Evidência bancária fictícia para o ensaio HTTP', reason: 'Preparação de conta fictícia sem operação bancária real' }); previous_id: 0,
bank_name: 'Banco exclusivamente sintético HTTP QA',
country: 'MZ',
currency: 'MZN',
beneficiary: 'Titular exclusivamente sintético',
account_identifier: 'HTTP-OFFICE-ACCOUNT-QA',
evidence_reference: 'Evidência bancária fictícia para o ensaio HTTP',
reason: 'Preparação de conta fictícia sem operação bancária real',
});
current = await state(); current = await state();
const bankId = current.bank.id; const bankId = current.bank.id;
for (const bankReviewer of [finance, reviewer]) await post(bankReviewer, `/fornecedores/${supplierId}/dados-bancarios/${bankId}/validar`, { for (const bankReviewer of [finance, reviewer])
decision: 'approved', independently_verified: true, reason: 'Conferência independente de evidência exclusivamente sintética HTTP' }); await post(
bankReviewer,
`/fornecedores/${supplierId}/dados-bancarios/${bankId}/validar`,
{
decision: 'approved',
independently_verified: true,
reason: 'Conferência independente de evidência exclusivamente sintética HTTP',
},
);
current = await state(); current = await state();
check(current.bank.approved_reviews === 2, 'two independent native bank reviews'); check(
const payment = { supplier_bank_detail_id: bankId, amount: '40.00', paid_on: date(0), external_reference: 'HTTP-OFFICE-PARTIAL-QA', current.bank.approved_reviews === 2,
evidence_reference: 'Registo exclusivamente sintético de pagamento externo parcial, sem execução bancária' }; 'two independent native bank reviews',
);
const payment = {
supplier_bank_detail_id: bankId,
amount: '40.00',
paid_on: date(0),
external_reference: 'HTTP-OFFICE-PARTIAL-QA',
evidence_reference:
'Registo exclusivamente sintético de pagamento externo parcial, sem execução bancária',
};
await post(finance, `/facturas/${invoiceId}/pagamentos`, payment); await post(finance, `/facturas/${invoiceId}/pagamentos`, payment);
current = await state(); current = await state();
const paymentId = current.payments[0].id; const paymentId = current.payments[0].id;
const reviewPage = await reviewer.page(`/pagamentos?payment_id=${paymentId}`, 'payments/index'); const reviewPage = await reviewer.page(
check(reviewPage.props.payments.data[0].canReview === true && reviewPage.props.focusPaymentId === paymentId, 'independent native payment review workspace'); `/pagamentos?payment_id=${paymentId}`,
const registrationPage = await finance.page(`/pagamentos?invoice_id=${invoiceId}`, 'payments/index'); 'payments/index',
check(registrationPage.props.focusInvoiceId === invoiceId && registrationPage.props.invoices[0].outstanding_minor === 10000, 'native payment registration workspace uses the authoritative invoice balance'); );
check(
reviewPage.props.payments.data[0].canReview === true &&
reviewPage.props.focusPaymentId === paymentId,
'independent native payment review workspace',
);
const registrationPage = await finance.page(
`/pagamentos?invoice_id=${invoiceId}`,
'payments/index',
);
check(
registrationPage.props.focusInvoiceId === invoiceId &&
registrationPage.props.invoices[0].outstanding_minor === 10000,
'native payment registration workspace uses the authoritative invoice balance',
);
const pending = current.financial_fingerprint; const pending = current.financial_fingerprint;
await post(finance, `/facturas/${invoiceId}/pagamentos`, payment); await post(finance, `/facturas/${invoiceId}/pagamentos`, payment);
current = await state(); current = await state();
check(current.payments.length === 1 && current.financial_fingerprint === pending, 'payment registration replay has no financial effect'); check(
await post(finance, `/pagamentos/${paymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Tentativa própria exclusivamente sintética que deve ser recusada' }, 403); current.payments.length === 1 &&
check((await reviewer.request(`/pagamentos/${paymentId}/categorias`)).status === 409, 'unconfirmed payment cannot be attributed to expense categories'); current.financial_fingerprint === pending,
await post(reviewer, `/pagamentos/${paymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Conferência independente de evidência fictícia de pagamento parcial' }); 'payment registration replay has no financial effect',
);
await post(
finance,
`/pagamentos/${paymentId}/conferir`,
{
decision: 'confirmed',
independently_verified: true,
reason: 'Tentativa própria exclusivamente sintética que deve ser recusada',
},
403,
);
check(
(await reviewer.request(`/pagamentos/${paymentId}/categorias`))
.status === 409,
'unconfirmed payment cannot be attributed to expense categories',
);
await post(reviewer, `/pagamentos/${paymentId}/conferir`, {
decision: 'confirmed',
independently_verified: true,
reason: 'Conferência independente de evidência fictícia de pagamento parcial',
});
current = await state(); current = await state();
check(current.payments[0].status === 'confirmed' && current.invoice.outstanding_minor === 6000, 'confirmed partial payment preserves the exact outstanding amount'); check(
const overpay = await post(finance, `/facturas/${invoiceId}/pagamentos`, { ...payment, amount: '60.01', external_reference: 'HTTP-OFFICE-OVERPAY-QA' }, 422); current.payments[0].status === 'confirmed' &&
check(Object.hasOwn((await overpay.json()).errors ?? {}, 'payment'), 'overpayment is refused by the native financial rule'); current.invoice.outstanding_minor === 6000,
'confirmed partial payment preserves the exact outstanding amount',
);
const overpay = await post(
finance,
`/facturas/${invoiceId}/pagamentos`,
{
...payment,
amount: '60.01',
external_reference: 'HTTP-OFFICE-OVERPAY-QA',
},
422,
);
check(
Object.hasOwn((await overpay.json()).errors ?? {}, 'payment'),
'overpayment is refused by the native financial rule',
);
const attribute = async (id, amount) => { const attribute = async (id, amount) => {
const page = await reviewer.page(`/pagamentos/${id}/categorias`, 'payments/expense-allocation'); const page = await reviewer.page(
`/pagamentos/${id}/categorias`,
'payments/expense-allocation',
);
const before = (await state()).financial_fingerprint; const before = (await state()).financial_fingerprint;
const data = { operation_key: crypto.randomUUID(), version: page.props.current?.version ?? 0, fingerprint: page.props.fingerprint, const data = {
reason: 'Imputação explícita de Finanças de pagamento exclusivamente sintético HTTP', allocations: [{ category: office.category, amount }] }; operation_key: crypto.randomUUID(),
version: page.props.current?.version ?? 0,
fingerprint: page.props.fingerprint,
reason: 'Imputação explícita de Finanças de pagamento exclusivamente sintético HTTP',
allocations: [{ category: office.category, amount }],
};
await post(reviewer, `/pagamentos/${id}/categorias`, data); await post(reviewer, `/pagamentos/${id}/categorias`, data);
await post(reviewer, `/pagamentos/${id}/categorias`, data); await post(reviewer, `/pagamentos/${id}/categorias`, data);
check((await state()).financial_fingerprint === before, 'explicit attribution and its replay never change financial or stock sources'); check(
(await state()).financial_fingerprint === before,
'explicit attribution and its replay never change financial or stock sources',
);
}; };
await attribute(paymentId, '40.00'); await attribute(paymentId, '40.00');
stage('settlement_and_privacy'); stage('settlement_and_privacy');
await post(finance, `/facturas/${invoiceId}/pagamentos`, { ...payment, amount: '60.00', external_reference: 'HTTP-OFFICE-FINAL-QA' }); await post(finance, `/facturas/${invoiceId}/pagamentos`, {
...payment,
amount: '60.00',
external_reference: 'HTTP-OFFICE-FINAL-QA',
});
current = await state(); current = await state();
const finalPaymentId = current.payments.find(p => p.id !== paymentId).id; const finalPaymentId = current.payments.find((p) => p.id !== paymentId).id;
await post(reviewer, `/pagamentos/${finalPaymentId}/conferir`, { decision: 'confirmed', independently_verified: true, reason: 'Conferência independente do saldo exclusivamente sintético HTTP' }); await post(reviewer, `/pagamentos/${finalPaymentId}/conferir`, {
decision: 'confirmed',
independently_verified: true,
reason: 'Conferência independente do saldo exclusivamente sintético HTTP',
});
await attribute(finalPaymentId, '60.00'); await attribute(finalPaymentId, '60.00');
current = await state(); current = await state();
check(current.invoice.outstanding_minor === 0 && current.payments.length === 2 && current.payments.every(p => p.status === 'confirmed'), 'two independently confirmed payments settle exactly 100 MZN'); check(
check(String(current.analytics.currencies[0].amount_minor) === '10000' && current.analytics.coverage.confirmed_payments === 2 current.invoice.outstanding_minor === 0 &&
&& String(current.analytics.category_attribution.groups.data[0].amount_minor) === '10000', 'native confirmed-payment analytics and explicit category attribution agree'); current.payments.length === 2 &&
check(JSON.stringify(current.budget.balance) === consumedBudget && current.stock.quantity_milli === 1000 && current.stock.movements === 1 && current.journals === 0, current.payments.every((p) => p.status === 'confirmed'),
'settlement preserves budget consumption, stock and documentary chart boundary'); 'two independently confirmed payments settle exactly 100 MZN',
const process = await owner.request(`/requisicoes/${requestId}/processo`, { headers: { 'X-Inertia': 'true' } }); );
check(
String(current.analytics.currencies[0].amount_minor) === '10000' &&
current.analytics.coverage.confirmed_payments === 2 &&
String(
current.analytics.category_attribution.groups.data[0]
.amount_minor,
) === '10000',
'native confirmed-payment analytics and explicit category attribution agree',
);
check(
JSON.stringify(current.budget.balance) === consumedBudget &&
current.stock.quantity_milli === 1000 &&
current.stock.movements === 1 &&
current.journals === 0,
'settlement preserves budget consumption, stock and documentary chart boundary',
);
const process = await owner.request(`/requisicoes/${requestId}/processo`, {
headers: { 'X-Inertia': 'true' },
});
check(process.status === 200, 'requester native process route'); check(process.status === 200, 'requester native process route');
const report = await process.json(); const report = await process.json();
check(report.props.stages[7].state === 'restricted' && report.props.stages[8].state === 'restricted' check(
&& !Object.hasOwn(report.props, 'invoices') && !Object.hasOwn(report.props, 'payments') && !Object.hasOwn(report.props, 'bank_snapshot'), 'requester process does not disclose financial or bank records'); report.props.stages[7].state === 'restricted' &&
report.props.stages[8].state === 'restricted' &&
!Object.hasOwn(report.props, 'invoices') &&
!Object.hasOwn(report.props, 'payments') &&
!Object.hasOwn(report.props, 'bank_snapshot'),
'requester process does not disclose financial or bank records',
);
if (capital) { if (capital) {
stage('project_trace'); stage('project_trace');
const beforeTrace = current.financial_fingerprint; const beforeTrace = current.financial_fingerprint;
const trace = await finance.page(`/projectos-imobilizado?history=${capital.record_key}`, 'equipment/capital-register'); const trace = await finance.page(
check(trace.props.trace.orders.data.some(row => row.order_id === orderId), 'project trace reaches its actual issued order'); `/projectos-imobilizado?history=${capital.record_key}`,
check(trace.props.trace.receipts.data.some(row => row.order_id === orderId), 'project trace reaches its actual physical receipt'); 'equipment/capital-register',
check(trace.props.history.data[0].record_key === capital.record_key && trace.props.history.data[0].version === 1, 'project history remains its native version'); );
check(
trace.props.trace.orders.data.some(
(row) => row.order_id === orderId,
),
'project trace reaches its actual issued order',
);
check(
trace.props.trace.receipts.data.some(
(row) => row.order_id === orderId,
),
'project trace reaches its actual physical receipt',
);
check(
trace.props.history.data[0].record_key === capital.record_key &&
trace.props.history.data[0].version === 1,
'project history remains its native version',
);
current = await state(); current = await state();
check(current.financial_fingerprint === beforeTrace, 'project trace consultation changes no financial or stock source'); check(
current.financial_fingerprint === beforeTrace,
'project trace consultation changes no financial or stock source',
);
} }
for (const client of Object.values(clients)) await client.logout(); for (const client of Object.values(clients)) await client.logout();
return { checks, native_post_requests: commands, fortify_sessions: Object.keys(clients).length, return {
request_id: requestId, order_id: orderId, invoice_id: invoiceId, payment_ids: current.payments.map(p => p.id), checks,
request_total_minor: current.request.total_minor, order_total_minor: current.order.total_minor, invoice_total_minor: current.invoice.total_minor, native_post_requests: commands,
confirmed_payments_minor: current.payments.map(p => p.amount_minor), outstanding_minor: current.invoice.outstanding_minor, fortify_sessions: Object.keys(clients).length,
budget_consumed_minor: current.budget.balance.consumed_minor, budget_available_minor: current.budget.balance.available_minor, request_id: requestId,
order_id: orderId,
invoice_id: invoiceId,
payment_ids: current.payments.map((p) => p.id),
request_total_minor: current.request.total_minor,
order_total_minor: current.order.total_minor,
invoice_total_minor: current.invoice.total_minor,
confirmed_payments_minor: current.payments.map((p) => p.amount_minor),
outstanding_minor: current.invoice.outstanding_minor,
budget_consumed_minor: current.budget.balance.consumed_minor,
budget_available_minor: current.budget.balance.available_minor,
order_budget_checked: current.order.budget_checked, order_budget_checked: current.order.budget_checked,
stock_quantity_milli: current.stock.quantity_milli, stock_movements: current.stock.movements, journals: current.journals, stock_quantity_milli: current.stock.quantity_milli,
explicit_finance_category_total_minor: current.analytics.category_attribution.groups.data[0].amount_minor, stock_movements: current.stock.movements,
all_business_mutations_via_native_http: true, assertions_use_readonly_transactions: true, budget_balance_via_native_http: true, journals: current.journals,
selector_self_final_approval_refused: selectorRefused, synthetic_only: true, explicit_finance_category_total_minor:
project_trace: capital ? { record_key: capital.record_key, code: capital.data.code, version: capital.version, order_id: orderId } : null, current.analytics.category_attribution.groups.data[0].amount_minor,
real_bank_or_sgf_operations: false, browser_visual_acceptance: false }; all_business_mutations_via_native_http: true,
assertions_use_readonly_transactions: true,
budget_balance_via_native_http: true,
selector_self_final_approval_refused: selectorRefused,
synthetic_only: true,
project_trace: capital
? {
record_key: capital.record_key,
code: capital.data.code,
version: capital.version,
order_id: orderId,
}
: null,
real_bank_or_sgf_operations: false,
browser_visual_acceptance: false,
};
} }
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source=await fs.readFile('scripts/supplier-evaluation-check.mjs','utf8'); const source = await fs.readFile(
const common=source.slice(source.indexOf('const base ='),source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs','assert','return (async()=>{'+common+` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[]; const records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) { for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
const viewer=client();await viewer.enter(role); const viewer=client();await viewer.enter(role);
@@ -20,4 +31,6 @@ await new Function('fs','assert','return (async()=>{'+common+`
business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false, business_commands:false,accounts_or_grants_changed:false,sgf_installation_changed:false,visual_review:false,
coverage:'Existing pilot access and source binding validation; positive searches and associations exercised in disposable databases.'},null,2)); coverage:'Existing pilot access and source binding validation; positive searches and associations exercised in disposable databases.'},null,2));
console.log('Pesquisa de saídas conferida sem conceder competências ou criar movimentos no piloto.'); console.log('Pesquisa de saídas conferida sem conceder competências ou criar movimentos no piloto.');
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises'; import fs from 'node:fs/promises';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8'); const source = await fs.readFile(
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author =')); 'scripts/supplier-evaluation-check.mjs',
await new Function('fs', 'assert', 'return (async()=>{' + common + ` 'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[]; const results=[];
for(const role of ['admin','procurement','finance','warehouse']) { for(const role of ['admin','procurement','finance','warehouse']) {
const viewer=client(); await viewer.enter(role); const viewer=client(); await viewer.enter(role);
@@ -18,4 +29,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
} }
await fs.writeFile('docs/proofs/search-expansion-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2)); await fs.writeFile('docs/proofs/search-expansion-http.json',JSON.stringify({environment:base,result:'passed',results,business_commands:false,session_context_only:true,visual_review:false},null,2));
console.log(JSON.stringify({roles_checked:results.length,result:'passed',business_commands:false})); console.log(JSON.stringify({roles_checked:results.length,result:'passed',business_commands:false}));
`+'})()')(fs,assert); ` +
'})()',
)(fs, assert);
+115 -24
View File
@@ -6,42 +6,133 @@ import {spawnSync} from 'node:child_process';
import { purchasingHomeOverlay } from './lib/sgf-purchasing-home-overlay.mjs'; import { purchasingHomeOverlay } from './lib/sgf-purchasing-home-overlay.mjs';
const host = fs.realpathSync(process.argv[2] || ''); const host = fs.realpathSync(process.argv[2] || '');
if(fs.existsSync(path.join(host,'public/hot')))throw Error('Stop the source frontend watcher before freezing a candidate.'); if (fs.existsSync(path.join(host, 'public/hot')))
const work=path.join('C:/laragon/data/sgf-tempo/run','candidate-ui-'+crypto.randomBytes(6).toString('hex')); throw Error(
'Stop the source frontend watcher before freezing a candidate.',
);
const work = path.join(
'C:/laragon/data/sgf-tempo/run',
'candidate-ui-' + crypto.randomBytes(6).toString('hex'),
);
fs.mkdirSync(work, { recursive: true }); fs.mkdirSync(work, { recursive: true });
const replace=(text,old,next)=>{if(text.split(old).length!==2)throw Error('Frontend baseline changed: '+old.slice(0,70));return text.replace(old,next);}; const replace = (text, old, next) => {
fs.cpSync(path.join(host,'resources'),path.join(work,'resources'),{recursive:true}); if (text.split(old).length !== 2)
for(const file of ['package.json','vite.config.js'])fs.copyFileSync(path.join(host,file),path.join(work,file)); throw Error('Frontend baseline changed: ' + old.slice(0, 70));
return text.replace(old, next);
};
fs.cpSync(path.join(host, 'resources'), path.join(work, 'resources'), {
recursive: true,
});
for (const file of ['package.json', 'vite.config.js'])
fs.copyFileSync(path.join(host, file), path.join(work, file));
fs.mkdirSync(path.join(work, 'public/build'), { recursive: true }); fs.mkdirSync(path.join(work, 'public/build'), { recursive: true });
fs.symlinkSync(path.join(host,'node_modules'),path.join(work,'node_modules'),'junction'); fs.symlinkSync(
path.join(host, 'node_modules'),
path.join(work, 'node_modules'),
'junction',
);
let app = fs.readFileSync(path.join(work, 'resources/js/app.jsx'), 'utf8'); let app = fs.readFileSync(path.join(work, 'resources/js/app.jsx'), 'utf8');
app=replace(app,"const options = (unit === null ? ['company.view', 'company.edit', 'unit.create', 'access.manage'] : ['unit.view', 'unit.edit']).filter(p => can(p, unit));", "const options = (list?.catalogue?.[unit === null ? 'company' : 'unit'] ?? []).filter(p => can(p, unit));"); app = replace(
app=replace(app,'{labels[p]}','{list?.catalogue_labels?.[p] ?? labels[p] ?? p}'); app,
app=replace(app,'{labels[g.permission]}','{list?.catalogue_labels?.[g.permission] ?? labels[g.permission] ?? g.permission}'); "const options = (unit === null ? ['company.view', 'company.edit', 'unit.create', 'access.manage'] : ['unit.view', 'unit.edit']).filter(p => can(p, unit));",
"const options = (list?.catalogue?.[unit === null ? 'company' : 'unit'] ?? []).filter(p => can(p, unit));",
);
app = replace(
app,
'{labels[p]}',
'{list?.catalogue_labels?.[p] ?? labels[p] ?? p}',
);
app = replace(
app,
'{labels[g.permission]}',
'{list?.catalogue_labels?.[g.permission] ?? labels[g.permission] ?? g.permission}',
);
fs.writeFileSync(path.join(work, 'resources/js/app.jsx'), app); fs.writeFileSync(path.join(work, 'resources/js/app.jsx'), app);
let home=fs.readFileSync(path.join(work,'resources/js/PurchasingHome.jsx'),'utf8'); let home = fs.readFileSync(
path.join(work, 'resources/js/PurchasingHome.jsx'),
'utf8',
);
home = purchasingHomeOverlay(home); home = purchasingHomeOverlay(home);
fs.writeFileSync(path.join(work, 'resources/js/PurchasingHome.jsx'), home); fs.writeFileSync(path.join(work, 'resources/js/PurchasingHome.jsx'), home);
let config = fs.readFileSync(path.join(work, 'vite.config.js'), 'utf8'); let config = fs.readFileSync(path.join(work, 'vite.config.js'), 'utf8');
config=replace(config,'defineConfig({',`defineConfig({\n cacheDir: ${JSON.stringify(path.join(work,'vite-cache'))},`); config = replace(
config,
'defineConfig({',
`defineConfig({\n cacheDir: ${JSON.stringify(path.join(work, 'vite-cache'))},`,
);
fs.writeFileSync(path.join(work, 'vite.config.js'), config); fs.writeFileSync(path.join(work, 'vite.config.js'), config);
const result=spawnSync(process.execPath,[path.join(host,'node_modules/vite/bin/vite.js'),'build','--config',path.join(work,'vite.config.js'),'--configLoader','native'],{cwd:work,encoding:'utf8',windowsHide:true,maxBuffer:4*1024*1024,env:{...process.env,NODE_ENV:'production'}}); const result = spawnSync(
fs.writeFileSync(path.join(work,'build.log'),(result.stdout||'')+(result.stderr||'')); process.execPath,
if(result.status!==0)throw Error('Candidate frontend build failed; private log '+path.join(work,'build.log')); [
const original=JSON.parse(fs.readFileSync(path.join(work,'public/build/manifest.json'),'utf8')); path.join(host, 'node_modules/vite/bin/vite.js'),
'build',
'--config',
path.join(work, 'vite.config.js'),
'--configLoader',
'native',
],
{
cwd: work,
encoding: 'utf8',
windowsHide: true,
maxBuffer: 4 * 1024 * 1024,
env: { ...process.env, NODE_ENV: 'production' },
},
);
fs.writeFileSync(
path.join(work, 'build.log'),
(result.stdout || '') + (result.stderr || ''),
);
if (result.status !== 0)
throw Error(
'Candidate frontend build failed; private log ' +
path.join(work, 'build.log'),
);
const original = JSON.parse(
fs.readFileSync(path.join(work, 'public/build/manifest.json'), 'utf8'),
);
const assets = {}; const assets = {};
for(const chunk of Object.values(original))for(const file of [chunk.file,...(chunk.css||[]),...(chunk.assets||[])]){ for (const chunk of Object.values(original))
if(!/^assets\/[A-Za-z0-9_-]+\.(js|css)$/.test(file))throw Error('Unsupported frontend asset '+file); for (const file of [
assets['integrations/sgf/frontend/'+file]=path.join(work,'public/build',file); chunk.file,
...(chunk.css || []),
...(chunk.assets || []),
]) {
if (!/^assets\/[A-Za-z0-9_-]+\.(js|css)$/.test(file))
throw Error('Unsupported frontend asset ' + file);
assets['integrations/sgf/frontend/' + file] = path.join(
work,
'public/build',
file,
);
} }
const manifest = JSON.parse(JSON.stringify(original)); const manifest = JSON.parse(JSON.stringify(original));
for (const chunk of Object.values(manifest)) { for (const chunk of Object.values(manifest)) {
chunk.file = 'modules/internal-requisitions/' + chunk.file; chunk.file = 'modules/internal-requisitions/' + chunk.file;
if(chunk.css)chunk.css=chunk.css.map(p=>'modules/internal-requisitions/'+p); if (chunk.css)
if(chunk.assets)chunk.assets=chunk.assets.map(p=>'modules/internal-requisitions/'+p); chunk.css = chunk.css.map((p) => 'modules/internal-requisitions/' + p);
if (chunk.assets)
chunk.assets = chunk.assets.map(
(p) => 'modules/internal-requisitions/' + p,
);
} }
const manifestFile=path.join(work,'candidate-manifest.json');fs.writeFileSync(manifestFile,JSON.stringify(manifest,null,2)+'\n'); const manifestFile = path.join(work, 'candidate-manifest.json');
const overlays={'resources/js/app.jsx':path.join(work,'resources/js/app.jsx'),'resources/js/PurchasingHome.jsx':path.join(work,'resources/js/PurchasingHome.jsx'),'public/build/manifest.json':manifestFile}; fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2) + '\n');
const metadata={work,overlays,assets,dependency_install:false,source_host_modified:false}; const overlays = {
const metadataFile=path.join(work,'candidate-ui.json');fs.writeFileSync(metadataFile,JSON.stringify(metadata,null,2)); 'resources/js/app.jsx': path.join(work, 'resources/js/app.jsx'),
'resources/js/PurchasingHome.jsx': path.join(
work,
'resources/js/PurchasingHome.jsx',
),
'public/build/manifest.json': manifestFile,
};
const metadata = {
work,
overlays,
assets,
dependency_install: false,
source_host_modified: false,
};
const metadataFile = path.join(work, 'candidate-ui.json');
fs.writeFileSync(metadataFile, JSON.stringify(metadata, null, 2));
console.log(JSON.stringify({ metadata: metadataFile })); console.log(JSON.stringify({ metadata: metadataFile }));
+311 -55
View File
@@ -2,87 +2,343 @@ import fs from 'node:fs';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import crypto from 'node:crypto'; import crypto from 'node:crypto';
const root = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939'; const root = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939';
const privateData=JSON.parse(fs.readFileSync(root+'/private/development.json','utf8')); const privateData = JSON.parse(
assert.deepEqual([privateData.tenant_id,privateData.company_id,privateData.unit_id],[1,1,1]); fs.readFileSync(root + '/private/development.json', 'utf8'),
);
assert.deepEqual(
[privateData.tenant_id, privateData.company_id, privateData.unit_id],
[1, 1, 1],
);
const stateFile = root + '/private/requisitions-recovery/http-state.json'; const stateFile = root + '/private/requisitions-recovery/http-state.json';
const state=fs.existsSync(stateFile)?JSON.parse(fs.readFileSync(stateFile,'utf8')):{}; const state = fs.existsSync(stateFile)
const persist=()=>fs.writeFileSync(stateFile,JSON.stringify(state,null,2)); ? JSON.parse(fs.readFileSync(stateFile, 'utf8'))
const key=name=>{state.keys??={};state.keys[name]??=crypto.randomUUID();persist();return state.keys[name];}; : {};
const persist = () =>
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2));
const key = (name) => {
state.keys ??= {};
state.keys[name] ??= crypto.randomUUID();
persist();
return state.keys[name];
};
const checks = []; const checks = [];
const clients = {}; const clients = {};
for (const p of privateData.profiles) { for (const p of privateData.profiles) {
const jar=new Map();let csrf='',token=''; const jar = new Map();
const api=async(path,method='GET',body,expected=200,commandKey)=>{ let csrf = '',
const r=await fetch('http://127.0.0.1:8039'+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','Idempotency-Key':commandKey??crypto.randomUUID()},...(body===undefined?{}:{body:JSON.stringify(body)})}); token = '';
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 api = async (
const text=await r.text();let d;try{d=JSON.parse(text);}catch{d={message:text.slice(0,120)};} path,
assert((Array.isArray(expected)?expected:[expected]).includes(r.status),`${p.role} ${path}: expected ${expected}, got ${r.status}: ${d.message??text.slice(0,180)}`); method = 'GET',
if(d.csrf)csrf=d.csrf;if(d.context?.token)token=d.context.token; body,
expected = 200,
commandKey,
) => {
const r = await fetch('http://127.0.0.1:8039' + 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',
'Idempotency-Key': commandKey ?? crypto.randomUUID(),
},
...(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(
(Array.isArray(expected) ? expected : [expected]).includes(
r.status,
),
`${p.role} ${path}: expected ${expected}, got ${r.status}: ${d.message ?? text.slice(0, 180)}`,
);
if (d.csrf) csrf = d.csrf;
if (d.context?.token) token = d.context.token;
return d; return d;
}; };
await api('/api/session');await api('/api/login','POST',{email:p.email,password:privateData.password}); await api('/api/session');
await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:1});clients[p.role]=api; 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,
});
clients[p.role] = api;
} }
checks.push('Existing three synthetic identities authenticate without password changes'); checks.push(
const prep=clients.preparador,review=clients.revisor,read=clients.consulta; 'Existing three synthetic identities authenticate without password changes',
const rights={1:['purchasing_requisitions.view','purchasing_requisitions.prepare','purchasing_requisitions.configure','purchasing_requisitions.approve.department_head','purchasing_budget.view','purchasing_budget.create','purchasing_budget.approve','purchasing_budget.record'],2:['purchasing_requisitions.view','purchasing_requisitions.approve.department_head','purchasing_budget.view','purchasing_budget.approve'],3:['purchasing_requisitions.view','purchasing_budget.view']}; );
await prep('/api/internal-requisitions/access-initialisation','POST',{operation_key:key('initial'),reason:'Owner-confirmed fourteen rights in synthetic demonstration 8039 only.',administrators:[{user_id:1,rights:rights[1]}]}); const prep = clients.preparador,
for(const [role,id] of [['revisor',2],['consulta',3]]){ review = clients.revisor,
const profile=privateData.profiles.find(p=>p.role===role); read = clients.consulta;
for(const permission of rights[id])await prep('/api/accesses','POST',{email:profile.email,unit_id:1,permission,reason:'Owner-confirmed synthetic demonstration access 8039.'}); const rights = {
1: [
'purchasing_requisitions.view',
'purchasing_requisitions.prepare',
'purchasing_requisitions.configure',
'purchasing_requisitions.approve.department_head',
'purchasing_budget.view',
'purchasing_budget.create',
'purchasing_budget.approve',
'purchasing_budget.record',
],
2: [
'purchasing_requisitions.view',
'purchasing_requisitions.approve.department_head',
'purchasing_budget.view',
'purchasing_budget.approve',
],
3: ['purchasing_requisitions.view', 'purchasing_budget.view'],
};
await prep('/api/internal-requisitions/access-initialisation', 'POST', {
operation_key: key('initial'),
reason: 'Owner-confirmed fourteen rights in synthetic demonstration 8039 only.',
administrators: [{ user_id: 1, rights: rights[1] }],
});
for (const [role, id] of [
['revisor', 2],
['consulta', 3],
]) {
const profile = privateData.profiles.find((p) => p.role === role);
for (const permission of rights[id])
await prep('/api/accesses', 'POST', {
email: profile.email,
unit_id: 1,
permission,
reason: 'Owner-confirmed synthetic demonstration access 8039.',
});
} }
checks.push('Eight plus four plus two explicit authorised grants'); checks.push('Eight plus four plus two explicit authorised grants');
for(const api of Object.values(clients))await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:1,module_id:'purchasing'}); for (const api of Object.values(clients))
const centre=await prep('/api/internal-requisitions/centres','POST',{operation_key:key('centre'),code:'SINTETICO-REPRO',reason:'Owner-authorised synthetic centre for demonstration only.'}); await api('/api/context', 'POST', {
state.centre_id=centre.centre_id;persist(); tenant_id: 1,
await read('/api/internal-requisitions/centres','POST',{operation_key:key('read-centre'),code:'REFUSED',reason:'Synthetic read-only refusal verification.'},403); company_id: 1,
unit_id: 1,
module_id: 'purchasing',
});
const centre = await prep('/api/internal-requisitions/centres', 'POST', {
operation_key: key('centre'),
code: 'SINTETICO-REPRO',
reason: 'Owner-authorised synthetic centre for demonstration only.',
});
state.centre_id = centre.centre_id;
persist();
await read(
'/api/internal-requisitions/centres',
'POST',
{
operation_key: key('read-centre'),
code: 'REFUSED',
reason: 'Synthetic read-only refusal verification.',
},
403,
);
if (!state.budget_id) { if (!state.budget_id) {
await prep('/api/purchasing-budget/create','POST',{cost_center_id:state.centre_id,year:2026,kind:'operating',includes_tax:true,amount:'10000.00',reason:'Owner-authorised synthetic 10000 MZN allocation for 2026.'},200,key('budget')); await prep(
'/api/purchasing-budget/create',
'POST',
{
cost_center_id: state.centre_id,
year: 2026,
kind: 'operating',
includes_tax: true,
amount: '10000.00',
reason: 'Owner-authorised synthetic 10000 MZN allocation for 2026.',
},
200,
key('budget'),
);
const list = await prep('/api/purchasing-budget'); const list = await prep('/api/purchasing-budget');
fs.writeFileSync(root+'/private/requisitions-recovery/budget-response.json',JSON.stringify(list,null,2)); fs.writeFileSync(
state.budget_pending=true;persist(); root + '/private/requisitions-recovery/budget-response.json',
JSON.stringify(list, null, 2),
);
state.budget_pending = true;
persist();
} }
// Obtain exact budget identifier from the native response; no guessing IDs. // Obtain exact budget identifier from the native response; no guessing IDs.
const workspace = await prep('/api/purchasing-budget'); const workspace = await prep('/api/purchasing-budget');
const candidates=workspace.budgets??workspace.allocations??workspace.records; const candidates =
workspace.budgets ?? workspace.allocations ?? workspace.records;
if (!state.budget_id) { if (!state.budget_id) {
assert(Array.isArray(candidates),'Inspect native budget response shape before proceeding'); assert(
const found=candidates.filter(b=>Number(b.cost_center_id??b.centre_id)===Number(state.centre_id)&&Number(b.year)===2026); Array.isArray(candidates),
assert.equal(found.length,1,'Exactly one synthetic allocation');state.budget_id=found[0].id;persist(); 'Inspect native budget response shape before proceeding',
);
const found = candidates.filter(
(b) =>
Number(b.cost_center_id ?? b.centre_id) ===
Number(state.centre_id) && Number(b.year) === 2026,
);
assert.equal(found.length, 1, 'Exactly one synthetic allocation');
state.budget_id = found[0].id;
persist();
} }
if (!state.budget_approved) { if (!state.budget_approved) {
await prep('/api/purchasing-budget/approve','POST',{budget_id:state.budget_id},403,key('self-budget')); await prep(
await read('/api/purchasing-budget/approve','POST',{budget_id:state.budget_id},403,key('read-budget')); '/api/purchasing-budget/approve',
await review('/api/purchasing-budget/approve','POST',{budget_id:state.budget_id},200,key('approve-budget')); 'POST',
state.budget_approved=true;persist(); { budget_id: state.budget_id },
403,
key('self-budget'),
);
await read(
'/api/purchasing-budget/approve',
'POST',
{ budget_id: state.budget_id },
403,
key('read-budget'),
);
await review(
'/api/purchasing-budget/approve',
'POST',
{ budget_id: state.budget_id },
200,
key('approve-budget'),
);
state.budget_approved = true;
persist();
} }
checks.push('Synthetic allocation 10000 MZN approved by second identity; self and read-only approvals refused'); checks.push(
const policy={version:0,reason:'Owner-confirmed synthetic OPER policy, demonstration 8039 only.',enabled:true,budget_required:true,first_limit_minor:1000000,second_limit_minor:2000000,approval_includes_tax:true,centres:[{id:state.centre_id,department_ref:'OPER'}],members:[{user_id:1,department_ref:'OPER'},{user_id:2,department_ref:'OPER'}]}; 'Synthetic allocation 10000 MZN approved by second identity; self and read-only approvals refused',
);
const policy = {
version: 0,
reason: 'Owner-confirmed synthetic OPER policy, demonstration 8039 only.',
enabled: true,
budget_required: true,
first_limit_minor: 1000000,
second_limit_minor: 2000000,
approval_includes_tax: true,
centres: [{ id: state.centre_id, department_ref: 'OPER' }],
members: [
{ user_id: 1, department_ref: 'OPER' },
{ user_id: 2, department_ref: 'OPER' },
],
};
await read('/api/internal-requisitions/policy', 'POST', policy, 403); await read('/api/internal-requisitions/policy', 'POST', policy, 403);
if(!state.policy_configured){await prep('/api/internal-requisitions/policy','POST',policy);state.policy_configured=true;persist();} if (!state.policy_configured) {
const draft={operation_key:key('draft'),cost_center_id:state.centre_id,priority:'normal',needed_by:'2026-11-30',justification:'Synthetic demonstration requisition, no Tempo business operation.',items:[{description:'Synthetic demonstration material',category:'Consumiveis',purchase_type:'consumable',quantity:'1.000',unit:'UN',unit_price:'100.00',tax_rate:'0.00'}]}; await prep('/api/internal-requisitions/policy', 'POST', policy);
await read('/api/internal-requisitions/save','POST',{...draft,operation_key:key('read-save')},403); state.policy_configured = true;
if(!state.request_id){const saved=await prep('/api/internal-requisitions/save','POST',draft);state.request_id=saved.id;persist();} persist();
}
const draft = {
operation_key: key('draft'),
cost_center_id: state.centre_id,
priority: 'normal',
needed_by: '2026-11-30',
justification:
'Synthetic demonstration requisition, no Tempo business operation.',
items: [
{
description: 'Synthetic demonstration material',
category: 'Consumiveis',
purchase_type: 'consumable',
quantity: '1.000',
unit: 'UN',
unit_price: '100.00',
tax_rate: '0.00',
},
],
};
await read(
'/api/internal-requisitions/save',
'POST',
{ ...draft, operation_key: key('read-save') },
403,
);
if (!state.request_id) {
const saved = await prep('/api/internal-requisitions/save', 'POST', draft);
state.request_id = saved.id;
persist();
}
const path = '/api/internal-requisitions/' + state.request_id; const path = '/api/internal-requisitions/' + state.request_id;
if (!state.submitted) { if (!state.submitted) {
const submitted=await prep(path+'/submit','POST',{operation_key:key('submit'),version:1}); const submitted = await prep(path + '/submit', 'POST', {
state.submitted=submitted;persist(); operation_key: key('submit'),
const replay=await prep(path+'/submit','POST',{operation_key:key('submit'),version:1}); version: 1,
assert.equal(replay.id,state.request_id);checks.push('Submission retry reuses same requisition'); });
state.submitted = submitted;
persist();
const replay = await prep(path + '/submit', 'POST', {
operation_key: key('submit'),
version: 1,
});
assert.equal(replay.id, state.request_id);
checks.push('Submission retry reuses same requisition');
} }
if (!state.approved) { if (!state.approved) {
const decision={operation_key:key('decision'),version:state.submitted.version,decision:'approved'}; const decision = {
operation_key: key('decision'),
version: state.submitted.version,
decision: 'approved',
};
await prep(path + '/decide', 'POST', decision, 403); await prep(path + '/decide', 'POST', decision, 403);
await read(path + '/decide', 'POST', decision, [403, 404]); await read(path + '/decide', 'POST', decision, [403, 404]);
await read(path+'/submit','POST',{operation_key:key('read-submit'),version:state.submitted.version},[403,404]); await read(
const approved=await review(path+'/decide','POST',decision);assert.equal(approved.status,'approved');state.approved=true;persist(); path + '/submit',
'POST',
{ operation_key: key('read-submit'), version: state.submitted.version },
[403, 404],
);
const approved = await review(path + '/decide', 'POST', decision);
assert.equal(approved.status, 'approved');
state.approved = true;
persist();
}
for (const api of [prep, review]) {
const d = await api(path);
assert.equal(d.record.status, 'approved');
assert.equal(d.history.length, 3);
} }
for(const api of [prep,review]){const d=await api(path);assert.equal(d.record.status,'approved');assert.equal(d.history.length,3);}
await read(path, 'GET', undefined, 404); await read(path, 'GET', undefined, 404);
await read('/api/internal-requisitions'); await read('/api/internal-requisitions');
await read('/api/accesses', 'GET', undefined, 403); await read('/api/accesses', 'GET', undefined, 403);
checks.push('Full request lifecycle, independent approval and three-event history consulted by preparer and reviewer'); checks.push(
checks.push('Existing record visibility rule returns 404 to read-only third identity; listing remains accessible; no extra rights granted'); 'Full request lifecycle, independent approval and three-event history consulted by preparer and reviewer',
checks.push('Read-only profile refused centre, budget approval, policy, preparation, submission, decision and access administration'); );
fs.writeFileSync('C:/laragon/www/compras/docs/proofs/sgf-demo-8039-http.json',JSON.stringify({passed:true,url:'http://127.0.0.1:8039',scope:'1:1:1',rights,centre_id:state.centre_id,budget_id:state.budget_id,request_id:state.request_id,checks,checked_at:new Date().toISOString(),visual_review:false,real_installation_changed:false},null,2)); checks.push(
console.log(JSON.stringify({passed:true,checks,request_id:state.request_id})); 'Existing record visibility rule returns 404 to read-only third identity; listing remains accessible; no extra rights granted',
);
checks.push(
'Read-only profile refused centre, budget approval, policy, preparation, submission, decision and access administration',
);
fs.writeFileSync(
'C:/laragon/www/compras/docs/proofs/sgf-demo-8039-http.json',
JSON.stringify(
{
passed: true,
url: 'http://127.0.0.1:8039',
scope: '1:1:1',
rights,
centre_id: state.centre_id,
budget_id: state.budget_id,
request_id: state.request_id,
checks,
checked_at: new Date().toISOString(),
visual_review: false,
real_installation_changed: false,
},
null,
2,
),
);
console.log(
JSON.stringify({ passed: true, checks, request_id: state.request_id }),
);
+73 -21
View File
@@ -1,4 +1,5 @@
<?php <?php
// Explicitly authorised persistent synthetic demonstration only. No GRANT/REVOKE. // Explicitly authorised persistent synthetic demonstration only. No GRANT/REVOKE.
use Illuminate\Contracts\Console\Kernel; use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
@@ -17,23 +18,41 @@ $app=require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap(); $app->make(Kernel::class)->bootstrap();
$db = DB::connection(); $db = DB::connection();
$identity = $db->selectOne("select current_database() as db,current_user as role,current_setting('cluster_name') as cluster,inet_server_port() as port"); $identity = $db->selectOne("select current_database() as db,current_user as role,current_setting('cluster_name') as cluster,inet_server_port() as port");
if ($app->basePath()!==str_replace('/',DIRECTORY_SEPARATOR,$host) && str_replace('\\','/',$app->basePath())!==$host) throw new RuntimeException('Wrong application folder'); if ($app->basePath() !== str_replace('/', DIRECTORY_SEPARATOR, $host) && str_replace('\\', '/', $app->basePath()) !== $host) {
if ($identity->db!=='sgf_modules_dev_2576427d1939'||$identity->role!=='sgf_modules_qa_2576427d1939'||$identity->cluster!=='sgf_modular_regression_2576427d1939'||(int)$identity->port!==55439||config('app.url')!=='http://127.0.0.1:8039') throw new RuntimeException('Wrong isolated identity'); throw new RuntimeException('Wrong application folder');
if (!$db->table('units')->where(['id'=>1,'tenant_id'=>1,'company_id'=>1])->exists()) throw new RuntimeException('Wrong scope'); }
if ($identity->db !== 'sgf_modules_dev_2576427d1939' || $identity->role !== 'sgf_modules_qa_2576427d1939' || $identity->cluster !== 'sgf_modular_regression_2576427d1939' || (int) $identity->port !== 55439 || config('app.url') !== 'http://127.0.0.1:8039') {
throw new RuntimeException('Wrong isolated identity');
}
if (! $db->table('units')->where(['id' => 1, 'tenant_id' => 1, 'company_id' => 1])->exists()) {
throw new RuntimeException('Wrong scope');
}
$private = json_decode(file_get_contents(dirname($host).'/private/development.json'), true, 32, JSON_THROW_ON_ERROR); $private = json_decode(file_get_contents(dirname($host).'/private/development.json'), true, 32, JSON_THROW_ON_ERROR);
if ([$private['tenant_id'],$private['company_id'],$private['unit_id']]!==[1,1,1]) throw new RuntimeException('Wrong synthetic provenance'); if ([$private['tenant_id'], $private['company_id'], $private['unit_id']] !== [1, 1, 1]) {
foreach([1=>'Preparador',2=>'Revisor',3=>'Consulta'] as $id=>$suffix) if(!str_ends_with($db->table('users')->where('id',$id)->value('name'),$suffix)) throw new RuntimeException('Wrong synthetic user'); throw new RuntimeException('Wrong synthetic provenance');
if(!class_exists(Installation::class))require_once $bundle.'/integrations/sgf/operational/bootstrap.php'; }
foreach ([1 => 'Preparador', 2 => 'Revisor', 3 => 'Consulta'] as $id => $suffix) {
if (! str_ends_with($db->table('users')->where('id', $id)->value('name'), $suffix)) {
throw new RuntimeException('Wrong synthetic user');
}
}
if (! class_exists(Installation::class)) {
require_once $bundle.'/integrations/sgf/operational/bootstrap.php';
}
require_once $bundle.'/integrations/sgf/operational/CodeDeployment.php'; require_once $bundle.'/integrations/sgf/operational/CodeDeployment.php';
$deploy = new CodeDeployment($host); $deploy = new CodeDeployment($host);
$mh = $proof['artifact']['archive']['manifest_sha256']; $mh = $proof['artifact']['archive']['manifest_sha256'];
if ($action === 'prepare') { if ($action === 'prepare') {
if(is_dir($recovery)) throw new RuntimeException('Recovery already exists; inspect before retry'); if (is_dir($recovery)) {
throw new RuntimeException('Recovery already exists; inspect before retry');
}
$plan = $deploy->plan($bundle, $mh); $plan = $deploy->plan($bundle, $mh);
mkdir($recovery, 0700, true); mkdir($recovery, 0700, true);
$manifest = json_decode(file_get_contents($bundle.'/manifest.json'), true); $manifest = json_decode(file_get_contents($bundle.'/manifest.json'), true);
foreach ([...array_keys($manifest['host_overlays']), '.env', 'config/modules.php', 'packages/purchasing/current.json'] as $file) { foreach ([...array_keys($manifest['host_overlays']), '.env', 'config/modules.php', 'packages/purchasing/current.json'] as $file) {
if(!is_dir(dirname($recovery.'/files/'.$file)))mkdir(dirname($recovery.'/files/'.$file),0700,true); if (! is_dir(dirname($recovery.'/files/'.$file))) {
mkdir(dirname($recovery.'/files/'.$file), 0700, true);
}
copy($host.'/'.$file, $recovery.'/files/'.$file); copy($host.'/'.$file, $recovery.'/files/'.$file);
} }
$cfg = $db->getConfig(); $cfg = $db->getConfig();
@@ -45,9 +64,15 @@ if ($action==='prepare') {
echo json_encode(['prepared' => true, 'identity' => $identity, 'host' => $host, 'recovery' => $recovery, 'backup_sha256' => $baseline['backup_sha256'], 'code_plan' => $plan], JSON_PRETTY_PRINT); echo json_encode(['prepared' => true, 'identity' => $identity, 'host' => $host, 'recovery' => $recovery, 'backup_sha256' => $baseline['backup_sha256'], 'code_plan' => $plan], JSON_PRETTY_PRINT);
} elseif ($action === 'install') { } elseif ($action === 'install') {
$baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR); $baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
if(!hash_equals($baseline['backup_sha256'],hash_file('sha256',$recovery.'/before.dump')))throw new RuntimeException('Backup changed'); if (! hash_equals($baseline['backup_sha256'], hash_file('sha256', $recovery.'/before.dump'))) {
if(json_decode(json_encode($db->table('permission_grants')->orderBy('id')->get()),true)!==$baseline['grants'])throw new RuntimeException('Grants changed since backup'); throw new RuntimeException('Backup changed');
if(is_file($host.'/storage/framework/down'))throw new RuntimeException('Unexpected prior maintenance'); }
if (json_decode(json_encode($db->table('permission_grants')->orderBy('id')->get()), true) !== $baseline['grants']) {
throw new RuntimeException('Grants changed since backup');
}
if (is_file($host.'/storage/framework/down')) {
throw new RuntimeException('Unexpected prior maintenance');
}
file_put_contents($host.'/storage/framework/down', json_encode(['time' => time(), 'retry' => 60])); file_put_contents($host.'/storage/framework/down', json_encode(['time' => time(), 'retry' => 60]));
$migration = Installation::migrate($db, Installation::target($db), $baseline['backup_sha256'], 'Owner-authorised synthetic 8039 setup'); $migration = Installation::migrate($db, Installation::target($db), $baseline['backup_sha256'], 'Owner-authorised synthetic 8039 setup');
$applied = $deploy->apply($bundle, $mh, $baseline['code_plan']['target_sha256'], 'Owner-authorised synthetic 8039 setup', true); $applied = $deploy->apply($bundle, $mh, $baseline['code_plan']['target_sha256'], 'Owner-authorised synthetic 8039 setup', true);
@@ -57,28 +82,55 @@ if ($action==='prepare') {
file_put_contents($host.'/config/purchasing-internal.php', '<?php return ["candidate_enabled"=>true];'); file_put_contents($host.'/config/purchasing-internal.php', '<?php return ["candidate_enabled"=>true];');
file_put_contents($host.'/config/purchasing-access.php', '<?php return ["initialisation_scopes"=>["1:1:1"]];'); file_put_contents($host.'/config/purchasing-access.php', '<?php return ["initialisation_scopes"=>["1:1:1"]];');
// The development server reloads PHP for every request; keep normal uncached config. // The development server reloads PHP for every request; keep normal uncached config.
foreach(['config.php','routes-v7.php','events.php'] as $file)if(is_file($host.'/bootstrap/cache/'.$file))throw new RuntimeException('Unexpected native cache; retain maintenance and reconcile'); foreach (['config.php', 'routes-v7.php', 'events.php'] as $file) {
if (is_file($host.'/bootstrap/cache/'.$file)) {
throw new RuntimeException('Unexpected native cache; retain maintenance and reconcile');
}
}
unlink($host.'/storage/framework/down'); unlink($host.'/storage/framework/down');
echo json_encode(['installed_synthetic_only' => true, 'migration' => $migration, 'deployment' => $applied, 'recovery' => $recovery], JSON_PRETTY_PRINT); echo json_encode(['installed_synthetic_only' => true, 'migration' => $migration, 'deployment' => $applied, 'recovery' => $recovery], JSON_PRETTY_PRINT);
} elseif ($action === 'verify') { } elseif ($action === 'verify') {
$baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR); $baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
$http = json_decode(file_get_contents($root.'/docs/proofs/sgf-demo-8039-http.json'), true, 64, JSON_THROW_ON_ERROR); $http = json_decode(file_get_contents($root.'/docs/proofs/sgf-demo-8039-http.json'), true, 64, JSON_THROW_ON_ERROR);
$current = $db->table('permission_grants')->orderBy('id')->get()->all(); $current = $db->table('permission_grants')->orderBy('id')->get()->all();
$oldById=[];foreach($current as $grant)$oldById[$grant->id]=json_decode(json_encode($grant),true); $oldById = [];
foreach($baseline['grants'] as $grant)if(($oldById[$grant['id']]??null)!==$grant)throw new RuntimeException('Existing grant changed'); foreach ($current as $grant) {
$oldById[$grant->id] = json_decode(json_encode($grant), true);
}
foreach ($baseline['grants'] as $grant) {
if (($oldById[$grant['id']] ?? null) !== $grant) {
throw new RuntimeException('Existing grant changed');
}
}
$oldIds = array_column($baseline['grants'], 'id'); $oldIds = array_column($baseline['grants'], 'id');
$added = array_values(array_filter($current, fn ($g) => ! in_array($g->id, $oldIds, true))); $added = array_values(array_filter($current, fn ($g) => ! in_array($g->id, $oldIds, true)));
if(count($added)!==14)throw new RuntimeException('Expected exactly fourteen new grants'); if (count($added) !== 14) {
foreach($added as $grant)if([$grant->tenant_id,$grant->company_id,$grant->unit_id]!==[1,1,1]||!in_array($grant->permission,$http['rights'][$grant->user_id]??[],true))throw new RuntimeException('Unapproved new grant'); throw new RuntimeException('Expected exactly fourteen new grants');
if(hash('sha256',json_encode($db->table('users')->orderBy('id')->get()))!==$baseline['users_sha256'])throw new RuntimeException('Existing accounts changed'); }
if(hash_file('sha256',$host.'/packages/purchasing/current.json')!==$baseline['pointer_sha256'])throw new RuntimeException('Pointer changed'); foreach ($added as $grant) {
if ([$grant->tenant_id, $grant->company_id, $grant->unit_id] !== [1, 1, 1] || ! in_array($grant->permission, $http['rights'][$grant->user_id] ?? [], true)) {
throw new RuntimeException('Unapproved new grant');
}
}
if (hash('sha256', json_encode($db->table('users')->orderBy('id')->get())) !== $baseline['users_sha256']) {
throw new RuntimeException('Existing accounts changed');
}
if (hash_file('sha256', $host.'/packages/purchasing/current.json') !== $baseline['pointer_sha256']) {
throw new RuntimeException('Pointer changed');
}
$requests = $db->table('ir_requests')->where(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1])->get(); $requests = $db->table('ir_requests')->where(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1])->get();
if(count($requests)!==1||$requests[0]->status!=='approved'||$requests[0]->requester_id!==1)throw new RuntimeException('Unexpected request state'); if (count($requests) !== 1 || $requests[0]->status !== 'approved' || $requests[0]->requester_id !== 1) {
if($db->table('cb_budget_entries')->where('kind','reserve')->count()!==1)throw new RuntimeException('Expected exactly one reservation'); throw new RuntimeException('Unexpected request state');
}
if ($db->table('cb_budget_entries')->where('kind', 'reserve')->count() !== 1) {
throw new RuntimeException('Expected exactly one reservation');
}
$budget = $db->table('cb_budgets')->first(); $budget = $db->table('cb_budgets')->first();
$decision = $db->table('ir_steps')->first(); $decision = $db->table('ir_steps')->first();
$report = ['passed' => true, 'identity' => $identity, 'scope' => '1:1:1', 'added_grants' => $added, 'existing_grants_preserved' => true, 'existing_accounts_preserved' => true, 'single_approved_request' => true, 'single_reservation' => true, 'reservation' => $db->table('cb_budget_entries')->where('kind', 'reserve')->first(), 'budget' => $budget, 'decision' => $decision, 'pointer_preserved' => true, 'backup_sha256' => $baseline['backup_sha256'], 'recovery_directory' => $recovery, 'checked_at' => gmdate('c'), 'owner_runtime_limitation' => true, 'visual_review' => false, 'read_only_record_visibility_limitation' => true]; $report = ['passed' => true, 'identity' => $identity, 'scope' => '1:1:1', 'added_grants' => $added, 'existing_grants_preserved' => true, 'existing_accounts_preserved' => true, 'single_approved_request' => true, 'single_reservation' => true, 'reservation' => $db->table('cb_budget_entries')->where('kind', 'reserve')->first(), 'budget' => $budget, 'decision' => $decision, 'pointer_preserved' => true, 'backup_sha256' => $baseline['backup_sha256'], 'recovery_directory' => $recovery, 'checked_at' => gmdate('c'), 'owner_runtime_limitation' => true, 'visual_review' => false, 'read_only_record_visibility_limitation' => true];
file_put_contents($root.'/docs/proofs/sgf-demo-8039-delivery.json',json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)); file_put_contents($root.'/docs/proofs/sgf-demo-8039-delivery.json',json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
file_put_contents($host.'/config/purchasing-access.php','<?php return ["initialisation_scopes"=>[]];'); file_put_contents($host.'/config/purchasing-access.php','<?php return ["initialisation_scopes"=>[]];');
echo json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR); echo json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
} else throw new RuntimeException('Use prepare, install or verify'); } else {
throw new RuntimeException('Use prepare, install or verify');
}
+196 -31
View File
@@ -2,48 +2,213 @@ import fs from 'node:fs';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import crypto from 'node:crypto'; import crypto from 'node:crypto';
const legacy = process.argv.includes('--previous'); const legacy = process.argv.includes('--previous');
const privateData=JSON.parse(fs.readFileSync('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json','utf8')); const privateData = JSON.parse(
assert.deepEqual([privateData.tenant_id,privateData.company_id,privateData.unit_id],[1,1,1]); fs.readFileSync(
'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json',
'utf8',
),
);
assert.deepEqual(
[privateData.tenant_id, privateData.company_id, privateData.unit_id],
[1, 1, 1],
);
const checks = []; const checks = [];
for (const profile of privateData.profiles) { for (const profile of privateData.profiles) {
const jar=new Map();let csrf='',token=''; const jar = new Map();
const api=async(path,method='GET',body,status=200,overrides={})=>{ let csrf = '',
const response=await fetch('http://127.0.0.1:8039'+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','Idempotency-Key':crypto.randomUUID(),...overrides},...(body===undefined?{}:{body:JSON.stringify(body)})}); token = '';
for(const cookie of response.headers.getSetCookie()){const pair=cookie.split(';')[0],at=pair.indexOf('=');jar.set(pair.slice(0,at),pair.slice(at+1));} const api = async (
const text=await response.text();let d;try{d=JSON.parse(text);}catch{d={};} path,
assert((Array.isArray(status)?status:[status]).includes(response.status),`${profile.role} ${path}: expected ${status}, got ${response.status}: ${d.message??''}`); method = 'GET',
if(d.csrf)csrf=d.csrf;if(d.context?.token)token=d.context.token; body,
status = 200,
overrides = {},
) => {
const response = await fetch('http://127.0.0.1:8039' + 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',
'Idempotency-Key': crypto.randomUUID(),
...overrides,
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
for (const cookie of response.headers.getSetCookie()) {
const pair = cookie.split(';')[0],
at = pair.indexOf('=');
jar.set(pair.slice(0, at), pair.slice(at + 1));
}
const text = await response.text();
let d;
try {
d = JSON.parse(text);
} catch {
d = {};
}
assert(
(Array.isArray(status) ? status : [status]).includes(
response.status,
),
`${profile.role} ${path}: expected ${status}, got ${response.status}: ${d.message ?? ''}`,
);
if (d.csrf) csrf = d.csrf;
if (d.context?.token) token = d.context.token;
return d; return d;
}; };
await api('/api/session');await api('/api/login','POST',{email:profile.email,password:privateData.password}); await api('/api/session');
await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:1,module_id:'purchasing'}); await api('/api/login', 'POST', {
email: profile.email,
password: privateData.password,
});
await api('/api/context', 'POST', {
tenant_id: 1,
company_id: 1,
unit_id: 1,
module_id: 'purchasing',
});
const list = await api('/api/internal-requisitions'); const list = await api('/api/internal-requisitions');
if (legacy && profile.role === 'consulta') { if (legacy && profile.role === 'consulta') {
assert(!list.records.some(r=>r.id===1));await api('/api/internal-requisitions/1','GET',undefined,404); assert(!list.records.some((r) => r.id === 1));
checks.push('Previous version reproduces missing read-only listing/detail');continue; await api('/api/internal-requisitions/1', 'GET', undefined, 404);
checks.push(
'Previous version reproduces missing read-only listing/detail',
);
continue;
} }
assert(list.records.some(r=>r.id===1),'Existing request must be listed'); assert(
list.records.some((r) => r.id === 1),
'Existing request must be listed',
);
const detail = await api('/api/internal-requisitions/1'); const detail = await api('/api/internal-requisitions/1');
assert.equal(detail.record.id,1);assert.equal(detail.record.version,3);assert.equal(detail.record.status,'approved');assert.equal(detail.record.total_minor,10000); assert.equal(detail.record.id, 1);
assert.equal(detail.record.version, 3);
assert.equal(detail.record.status, 'approved');
assert.equal(detail.record.total_minor, 10000);
assert.equal(detail.history.length, 3); assert.equal(detail.history.length, 3);
checks.push(`${profile.role}: existing request 1 listed, detail and three-event history readable`); checks.push(
`${profile.role}: existing request 1 listed, detail and three-event history readable`,
);
if (profile.role === 'consulta') { if (profile.role === 'consulta') {
assert.equal(list.permissions.prepare,false);assert.equal(list.permissions.configure,false);assert.deepEqual(detail.record.allowed_actions,[]); assert.equal(list.permissions.prepare, false);
await api('/api/internal-requisitions/save','POST',{operation_key:crypto.randomUUID()},403); assert.equal(list.permissions.configure, false);
for(const action of ['save','submit','decide'])await api('/api/internal-requisitions/1/'+action,'POST',{operation_key:crypto.randomUUID(),version:3,...(action==='decide'?{decision:'approved'}:{})},[403,404]); assert.deepEqual(detail.record.allowed_actions, []);
await api('/api/internal-requisitions/policy','POST',{version:1,reason:'Denied read-only configuration verification.',enabled:true,budget_required:true,first_limit_minor:1000000,second_limit_minor:2000000,approval_includes_tax:true,centres:[{id:1,department_ref:'OPER'}],members:[{user_id:1,department_ref:'OPER'},{user_id:2,department_ref:'OPER'}]},403); await api(
await api('/api/internal-requisitions/centres','POST',{operation_key:crypto.randomUUID(),code:'REFUSED',reason:'Read-only denial check.'},403); '/api/internal-requisitions/save',
await api('/api/purchasing-budget/approve','POST',{budget_id:1},403); 'POST',
{ operation_key: crypto.randomUUID() },
403,
);
for (const action of ['save', 'submit', 'decide'])
await api(
'/api/internal-requisitions/1/' + action,
'POST',
{
operation_key: crypto.randomUUID(),
version: 3,
...(action === 'decide' ? { decision: 'approved' } : {}),
},
[403, 404],
);
await api(
'/api/internal-requisitions/policy',
'POST',
{
version: 1,
reason: 'Denied read-only configuration verification.',
enabled: true,
budget_required: true,
first_limit_minor: 1000000,
second_limit_minor: 2000000,
approval_includes_tax: true,
centres: [{ id: 1, department_ref: 'OPER' }],
members: [
{ user_id: 1, department_ref: 'OPER' },
{ user_id: 2, department_ref: 'OPER' },
],
},
403,
);
await api(
'/api/internal-requisitions/centres',
'POST',
{
operation_key: crypto.randomUUID(),
code: 'REFUSED',
reason: 'Read-only denial check.',
},
403,
);
await api(
'/api/purchasing-budget/approve',
'POST',
{ budget_id: 1 },
403,
);
await api('/api/accesses', 'GET', undefined, 403); await api('/api/accesses', 'GET', undefined, 403);
checks.push('Consulta: no allowed actions; creation, save, submission, decision, policy, centre, budget approval and administration refused'); checks.push(
await api('/api/internal-requisitions/1','GET',undefined,409,{'X-SGF-Context':'invalid'}); 'Consulta: no allowed actions; creation, save, submission, decision, policy, centre, budget approval and administration refused',
await api('/api/internal-requisitions/1','GET',undefined,403,{'X-Purchasing-Context':'procurement.third_party'}); );
await api('/api/internal-requisitions/999999999','GET',undefined,404); await api('/api/internal-requisitions/1', 'GET', undefined, 409, {
await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:2,module_id:'purchasing'},403); 'X-SGF-Context': 'invalid',
await api('/api/context','POST',{tenant_id:1,company_id:2,unit_id:3,module_id:'purchasing'},403); });
checks.push('Consulta: forged context, wrong option, missing record and unauthorised company/unit refused'); await api('/api/internal-requisitions/1', 'GET', undefined, 403, {
'X-Purchasing-Context': 'procurement.third_party',
});
await api(
'/api/internal-requisitions/999999999',
'GET',
undefined,
404,
);
await api(
'/api/context',
'POST',
{
tenant_id: 1,
company_id: 1,
unit_id: 2,
module_id: 'purchasing',
},
403,
);
await api(
'/api/context',
'POST',
{
tenant_id: 1,
company_id: 2,
unit_id: 3,
module_id: 'purchasing',
},
403,
);
checks.push(
'Consulta: forged context, wrong option, missing record and unauthorised company/unit refused',
);
} }
} }
const report={passed:true,mode:legacy?'previous-version-recovery':'corrected-version',url:'http://127.0.0.1:8039',scope:'1:1:1',request_id:1,request_recreated:false,reservation_commands_executed:false,rights_changed:false,checks,checked_at:new Date().toISOString(),visual_review:false}; const report = {
fs.writeFileSync('C:/laragon/www/compras/docs/proofs/sgf-read-8039-'+(legacy?'rollback':'http')+'.json',JSON.stringify(report,null,2)); passed: true,
mode: legacy ? 'previous-version-recovery' : 'corrected-version',
url: 'http://127.0.0.1:8039',
scope: '1:1:1',
request_id: 1,
request_recreated: false,
reservation_commands_executed: false,
rights_changed: false,
checks,
checked_at: new Date().toISOString(),
visual_review: false,
};
fs.writeFileSync(
'C:/laragon/www/compras/docs/proofs/sgf-read-8039-' +
(legacy ? 'rollback' : 'http') +
'.json',
JSON.stringify(report, null, 2),
);
console.log(JSON.stringify(report)); console.log(JSON.stringify(report));
+49 -17
View File
@@ -1,4 +1,5 @@
<?php <?php
use Illuminate\Contracts\Console\Kernel; use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
@@ -13,30 +14,41 @@ $app=require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap(); $app->make(Kernel::class)->bootstrap();
$db = DB::connection(); $db = DB::connection();
$identity = $db->selectOne("select current_database() as db,current_user as role,inet_server_port() as port,current_setting('cluster_name') as cluster"); $identity = $db->selectOne("select current_database() as db,current_user as role,inet_server_port() as port,current_setting('cluster_name') as cluster");
if(str_replace('\\','/',$app->basePath())!==$host||$identity->db!=='sgf_modules_dev_2576427d1939'||$identity->role!=='sgf_modules_qa_2576427d1939'||(int)$identity->port!==55439||$identity->cluster!=='sgf_modular_regression_2576427d1939'||config('app.url')!=='http://127.0.0.1:8039')throw new RuntimeException('Wrong demonstration'); if (str_replace('\\', '/', $app->basePath()) !== $host || $identity->db !== 'sgf_modules_dev_2576427d1939' || $identity->role !== 'sgf_modules_qa_2576427d1939' || (int) $identity->port !== 55439 || $identity->cluster !== 'sgf_modular_regression_2576427d1939' || config('app.url') !== 'http://127.0.0.1:8039') {
throw new RuntimeException('Wrong demonstration');
}
$record = $db->table('ir_requests')->where(['id' => 1, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1])->first(); $record = $db->table('ir_requests')->where(['id' => 1, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1])->first();
if(!$record||$record->status!=='approved'||$record->total_minor!==10000||$record->version!==3||$db->table('cb_budget_entries')->where('kind','reserve')->count()!==1)throw new RuntimeException('Wrong existing request'); if (! $record || $record->status !== 'approved' || $record->total_minor !== 10000 || $record->version !== 3 || $db->table('cb_budget_entries')->where('kind', 'reserve')->count() !== 1) {
throw new RuntimeException('Wrong existing request');
}
require_once $root.'/integrations/sgf/operational/CodeDeployment.php'; require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
$deploy = new CodeDeployment($host); $deploy = new CodeDeployment($host);
$fingerprints = function () use ($db) { $fingerprints = function () use ($db) {
return $db->transaction(function () use ($db) { return $db->transaction(function () use ($db) {
$db->statement('SET TRANSACTION READ ONLY');$hashes=[]; $db->statement('SET TRANSACTION READ ONLY');
$hashes = [];
foreach ($db->select("select tablename from pg_tables where schemaname='public' order by tablename") as $t) { foreach ($db->select("select tablename from pg_tables where schemaname='public' order by tablename") as $t) {
$rows = $db->select('select to_jsonb(t)::text as data from "'.$t->tablename.'" t order by to_jsonb(t)::text'); $rows = $db->select('select to_jsonb(t)::text as data from "'.$t->tablename.'" t order by to_jsonb(t)::text');
$hashes[$t->tablename] = hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR)); $hashes[$t->tablename] = hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR));
}return $hashes; }
return $hashes;
}); });
}; };
$action = $argv[1] ?? ''; $action = $argv[1] ?? '';
if ($action === 'prepare') { if ($action === 'prepare') {
if(is_dir($recovery))throw new RuntimeException('Recovery exists; no overwrite'); if (is_dir($recovery)) {
throw new RuntimeException('Recovery exists; no overwrite');
}
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']); $plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
mkdir($recovery, 0700, true); mkdir($recovery, 0700, true);
$cfg = $db->getConfig(); $cfg = $db->getConfig();
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--format=custom', '--file='.$recovery.'/before.dump', '--dbname='.$identity->db], null, ['PGHOST' => '127.0.0.1', 'PGPORT' => '55439', 'PGUSER' => $identity->role, 'PGPASSWORD' => $cfg['password']], null, 90))->mustRun(); (new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--format=custom', '--file='.$recovery.'/before.dump', '--dbname='.$identity->db], null, ['PGHOST' => '127.0.0.1', 'PGPORT' => '55439', 'PGUSER' => $identity->role, 'PGPASSWORD' => $cfg['password']], null, 90))->mustRun();
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--list', $recovery.'/before.dump']))->mustRun(); (new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--list', $recovery.'/before.dump']))->mustRun();
$baseline = ['identity' => $identity, 'plan' => $plan, 'data_fingerprints' => $fingerprints(), 'backup_sha256' => hash_file('sha256', $recovery.'/before.dump'), 'pointer_sha256' => hash_file('sha256', $host.'/packages/purchasing/current.json'), 'config_hashes' => []]; $baseline = ['identity' => $identity, 'plan' => $plan, 'data_fingerprints' => $fingerprints(), 'backup_sha256' => hash_file('sha256', $recovery.'/before.dump'), 'pointer_sha256' => hash_file('sha256', $host.'/packages/purchasing/current.json'), 'config_hashes' => []];
foreach(['.env','config/modules.php','config/purchasing-operational.php','config/purchasing-internal.php','config/purchasing-access.php'] as $file)$baseline['config_hashes'][$file]=hash_file('sha256',$host.'/'.$file); foreach (['.env', 'config/modules.php', 'config/purchasing-operational.php', 'config/purchasing-internal.php', 'config/purchasing-access.php'] as $file) {
$baseline['config_hashes'][$file] = hash_file('sha256', $host.'/'.$file);
}
file_put_contents($recovery.'/baseline.json', json_encode($baseline, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)); file_put_contents($recovery.'/baseline.json', json_encode($baseline, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode(['prepared' => true, 'tables' => count($baseline['data_fingerprints']), 'backup_sha256' => $baseline['backup_sha256'], 'plan' => $plan], JSON_PRETTY_PRINT); echo json_encode(['prepared' => true, 'tables' => count($baseline['data_fingerprints']), 'backup_sha256' => $baseline['backup_sha256'], 'plan' => $plan], JSON_PRETTY_PRINT);
} else { } else {
@@ -45,21 +57,38 @@ if($action==='prepare'){
$changedTables = array_keys(array_filter($currentFingerprints, fn ($hash, $table) => $hash !== ($baseline['data_fingerprints'][$table] ?? null), ARRAY_FILTER_USE_BOTH)); $changedTables = array_keys(array_filter($currentFingerprints, fn ($hash, $table) => $hash !== ($baseline['data_fingerprints'][$table] ?? null), ARRAY_FILTER_USE_BOTH));
$auditAppended = false; $auditAppended = false;
if (in_array('identity_audit', $changedTables, true)) { if (in_array('identity_audit', $changedTables, true)) {
$extract=new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe','--data-only','--table=identity_audit','--file=-',$recovery.'/before.dump']);$extract->mustRun(); $extract = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--data-only', '--table=identity_audit', '--file=-', $recovery.'/before.dump']);
if(!preg_match('~COPY public\.identity_audit \(id,[^)]*\) FROM stdin;\r?\n(.*?)\r?\n\\\\\.~s',$extract->getOutput(),$match))throw new RuntimeException('Audit baseline cannot be reconciled'); $extract->mustRun();
if (! preg_match('~COPY public\.identity_audit \(id,[^)]*\) FROM stdin;\r?\n(.*?)\r?\n\\\\\.~s', $extract->getOutput(), $match)) {
throw new RuntimeException('Audit baseline cannot be reconciled');
}
$ids = array_map(fn ($line) => (int) explode("\t", $line)[0], preg_split('/\r?\n/', $match[1])); $ids = array_map(fn ($line) => (int) explode("\t", $line)[0], preg_split('/\r?\n/', $match[1]));
$rows = $db->select('select to_jsonb(t)::text as data from identity_audit t where id<=? order by to_jsonb(t)::text', [max($ids)]); $rows = $db->select('select to_jsonb(t)::text as data from identity_audit t where id<=? order by to_jsonb(t)::text', [max($ids)]);
if(hash('sha256',json_encode(array_column($rows,'data'),JSON_THROW_ON_ERROR))!==$baseline['data_fingerprints']['identity_audit'])throw new RuntimeException('Existing audit modified'); if (hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR)) !== $baseline['data_fingerprints']['identity_audit']) {
$auditAppended=true;$changedTables=array_values(array_diff($changedTables,['identity_audit'])); throw new RuntimeException('Existing audit modified');
}
$auditAppended = true;
$changedTables = array_values(array_diff($changedTables, ['identity_audit']));
}
if ($changedTables !== []) {
throw new RuntimeException('Database rows changed: '.implode(', ', $changedTables));
}
if (hash_file('sha256', $host.'/packages/purchasing/current.json') !== $baseline['pointer_sha256']) {
throw new RuntimeException('Pointer changed');
}
foreach ($baseline['config_hashes'] as $file => $hash) {
if (hash_file('sha256', $host.'/'.$file) !== $hash) {
throw new RuntimeException('Configuration changed');
}
} }
if($changedTables!==[])throw new RuntimeException('Database rows changed: '.implode(', ',$changedTables));
if(hash_file('sha256',$host.'/packages/purchasing/current.json')!==$baseline['pointer_sha256'])throw new RuntimeException('Pointer changed');
foreach($baseline['config_hashes'] as $file=>$hash)if(hash_file('sha256',$host.'/'.$file)!==$hash)throw new RuntimeException('Configuration changed');
if ($action === 'verify') { if ($action === 'verify') {
$report = ['passed' => true, 'identity' => $identity, 'data_tables_reconciled' => count($baseline['data_fingerprints']), 'audit_appended_only' => $auditAppended, 'request_id' => 1, 'request_version' => 3, 'amount_minor' => 10000, 'reservation_count' => 1, 'rights_and_accounts_unchanged' => true, 'config_unchanged' => true, 'pointer_unchanged' => true, 'candidate_manifest_sha256' => hash_file('sha256', $host.'/packages/internal-requisitions/manifest.json'), 'backup_sha256' => $baseline['backup_sha256'], 'checked_at' => gmdate('c')]; $report = ['passed' => true, 'identity' => $identity, 'data_tables_reconciled' => count($baseline['data_fingerprints']), 'audit_appended_only' => $auditAppended, 'request_id' => 1, 'request_version' => 3, 'amount_minor' => 10000, 'reservation_count' => 1, 'rights_and_accounts_unchanged' => true, 'config_unchanged' => true, 'pointer_unchanged' => true, 'candidate_manifest_sha256' => hash_file('sha256', $host.'/packages/internal-requisitions/manifest.json'), 'backup_sha256' => $baseline['backup_sha256'], 'checked_at' => gmdate('c')];
file_put_contents($root.'/docs/proofs/sgf-read-8039-data.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($report,JSON_PRETTY_PRINT); file_put_contents($root.'/docs/proofs/sgf-read-8039-data.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($report, JSON_PRETTY_PRINT);
} else { } else {
if(is_file($host.'/storage/framework/down'))throw new RuntimeException('Unexpected maintenance'); if (is_file($host.'/storage/framework/down')) {
throw new RuntimeException('Unexpected maintenance');
}
file_put_contents($host.'/storage/framework/down', json_encode(['time' => time(), 'retry' => 60])); file_put_contents($host.'/storage/framework/down', json_encode(['time' => time(), 'retry' => 60]));
if ($action === 'rollback') { if ($action === 'rollback') {
$applied = json_decode(file_get_contents($recovery.'/applied.json'), true); $applied = json_decode(file_get_contents($recovery.'/applied.json'), true);
@@ -69,7 +98,10 @@ if($action==='prepare'){
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']); $plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
$result = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Authorised read-only visibility correction 8039', true); $result = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Authorised read-only visibility correction 8039', true);
file_put_contents($recovery.'/'.($action === 'apply' ? 'applied' : 'reapplied').'.json',json_encode($result,JSON_PRETTY_PRINT)); file_put_contents($recovery.'/'.($action === 'apply' ? 'applied' : 'reapplied').'.json',json_encode($result,JSON_PRETTY_PRINT));
}else throw new RuntimeException('Use prepare/apply/rollback/reapply/verify'); } else {
unlink($host.'/storage/framework/down');echo json_encode($result,JSON_PRETTY_PRINT); throw new RuntimeException('Use prepare/apply/rollback/reapply/verify');
}
unlink($host.'/storage/framework/down');
echo json_encode($result,JSON_PRETTY_PRINT);
} }
} }
+16 -5
View File
@@ -1,4 +1,5 @@
<?php <?php
// Freeze only the authorised adapter correction over the previously proved artifact. // Freeze only the authorised adapter correction over the previously proved artifact.
$root = dirname(__DIR__); $root = dirname(__DIR__);
$prior = json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'), true, 64, JSON_THROW_ON_ERROR); $prior = json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'), true, 64, JSON_THROW_ON_ERROR);
@@ -8,23 +9,33 @@ $file='integrations/sgf/internal-requisitions/Port.php';
$payload = []; $payload = [];
foreach ($manifest['support_files'] as $path => $hash) { foreach ($manifest['support_files'] as $path => $hash) {
$text = file_get_contents($old.'/'.$path); $text = file_get_contents($old.'/'.$path);
if(!hash_equals($hash,hash('sha256',$text)))throw new RuntimeException('Prior artifact changed'); if (! hash_equals($hash, hash('sha256', $text))) {
throw new RuntimeException('Prior artifact changed');
}
$payload[$path] = $path === $file ? file_get_contents($root.'/'.$file) : $text; $payload[$path] = $path === $file ? file_get_contents($root.'/'.$file) : $text;
} }
$manifest['support_files'][$file] = hash('sha256', $payload[$file]); $manifest['support_files'][$file] = hash('sha256', $payload[$file]);
$manifestText = json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR); $manifestText = json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
$id = 'OPERATIONAL-CANDIDATE-'.substr(hash('sha256', $manifestText), 0, 16); $id = 'OPERATIONAL-CANDIDATE-'.substr(hash('sha256', $manifestText), 0, 16);
$dir = $root.'/storage/app/private/candidates/'.$id; $dir = $root.'/storage/app/private/candidates/'.$id;
if(file_exists($dir))throw new RuntimeException('Candidate already exists; verify rather than overwrite'); if (file_exists($dir)) {
throw new RuntimeException('Candidate already exists; verify rather than overwrite');
}
mkdir($dir, 0700, true); mkdir($dir, 0700, true);
foreach ($payload + ['manifest.json' => $manifestText] as $path => $text) { foreach ($payload + ['manifest.json' => $manifestText] as $path => $text) {
if(!is_dir(dirname($dir.'/'.$path)))mkdir(dirname($dir.'/'.$path),0700,true); if (! is_dir(dirname($dir.'/'.$path))) {
mkdir(dirname($dir.'/'.$path), 0700, true);
}
file_put_contents($dir.'/'.$path, $text); file_put_contents($dir.'/'.$path, $text);
} }
$archive = $root.'/storage/app/private/candidate-archives/'.$id.'.zip'; $archive = $root.'/storage/app/private/candidate-archives/'.$id.'.zip';
$zip = new ZipArchive; $zip = new ZipArchive;
if($zip->open($archive,ZipArchive::CREATE|ZipArchive::EXCL)!==true)throw new RuntimeException('Archive collision'); if ($zip->open($archive, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
foreach([...array_keys($payload),'manifest.json'] as $path)$zip->addFile($dir.'/'.$path,$path); throw new RuntimeException('Archive collision');
}
foreach ([...array_keys($payload), 'manifest.json'] as $path) {
$zip->addFile($dir.'/'.$path, $path);
}
$zip->close(); $zip->close();
$result = ['directory' => $dir, 'archive' => ['file' => $archive, 'sha256' => hash_file('sha256', $archive), 'manifest_sha256' => hash('sha256', $manifestText)], 'prior_manifest_sha256' => $prior['artifact']['archive']['manifest_sha256'], 'changed_files' => [$file], 'schema_changed' => false, 'rights_changed' => false, 'installed_real' => false]; $result = ['directory' => $dir, 'archive' => ['file' => $archive, 'sha256' => hash_file('sha256', $archive), 'manifest_sha256' => hash('sha256', $manifestText)], 'prior_manifest_sha256' => $prior['artifact']['archive']['manifest_sha256'], 'changed_files' => [$file], 'schema_changed' => false, 'rights_changed' => false, 'installed_real' => false];
file_put_contents($root.'/docs/proofs/sgf-read-candidate.json', json_encode($result,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)); file_put_contents($root.'/docs/proofs/sgf-read-candidate.json', json_encode($result,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
+50 -11
View File
@@ -1,24 +1,63 @@
<?php <?php
use App\Services\ComparisonPolicy;
use Tempo\Purchasing\Delivery\AccessOverlay;
$root = dirname(__DIR__); $root = dirname(__DIR__);
$old = json_decode(file_get_contents($root.'/docs/proofs/sgf-read-candidate.json'), true, 32, JSON_THROW_ON_ERROR); $old = json_decode(file_get_contents($root.'/docs/proofs/sgf-read-candidate.json'), true, 32, JSON_THROW_ON_ERROR);
$manifest = json_decode(file_get_contents($old['directory'].'/manifest.json'), true, 64, JSON_THROW_ON_ERROR); $manifest = json_decode(file_get_contents($old['directory'].'/manifest.json'), true, 64, JSON_THROW_ON_ERROR);
$payload = []; $payload = [];
foreach($manifest['support_files'] as $file=>$hash){$text=file_get_contents($old['directory'].'/'.$file);if(hash('sha256',$text)!==$hash)throw new RuntimeException('Prior candidate changed');$payload[$file]=$text;} foreach ($manifest['support_files'] as $file => $hash) {
foreach(['integrations/sgf/sourcing','packages/purchasing/src'] as $dir)foreach(new DirectoryIterator($root.'/'.$dir) as $file)if($file->isFile())$payload[$dir.'/'.$file->getFilename()]=file_get_contents($file->getPathname()); $text = file_get_contents($old['directory'].'/'.$file);
foreach(['integrations/sgf/operational/Installation.php','integrations/sgf/operational/CodeDeployment.php','integrations/sgf/access/AccessOverlay.php','integrations/sgf/operational/routes.php','integrations/sgf/internal-requisitions/Controller.php','integrations/sgf/internal-requisitions/screen.mjs'] as $file)$payload[$file]=file_get_contents($root.'/'.$file); if (hash('sha256', $text) !== $hash) {
throw new RuntimeException('Prior candidate changed');
}$payload[$file] = $text;
}
foreach (['integrations/sgf/sourcing', 'packages/purchasing/src'] as $dir) {
foreach (new DirectoryIterator($root.'/'.$dir) as $file) {
if ($file->isFile()) {
$payload[$dir.'/'.$file->getFilename()] = file_get_contents($file->getPathname());
}
}
}
foreach (['integrations/sgf/operational/Installation.php', 'integrations/sgf/operational/CodeDeployment.php', 'integrations/sgf/access/AccessOverlay.php', 'integrations/sgf/operational/routes.php', 'integrations/sgf/internal-requisitions/Controller.php', 'integrations/sgf/internal-requisitions/screen.mjs'] as $file) {
$payload[$file] = file_get_contents($root.'/'.$file);
}
$payload['bootstrap.php'] = file_get_contents($root.'/integrations/sgf/operational/entry.php'); $payload['bootstrap.php'] = file_get_contents($root.'/integrations/sgf/operational/entry.php');
$payload['scripts/sgf-sourcing-install.php'] = file_get_contents($root.'/scripts/sgf-sourcing-install.php'); $payload['scripts/sgf-sourcing-install.php'] = file_get_contents($root.'/scripts/sgf-sourcing-install.php');
require_once $root.'/app/Services/ComparisonPolicy.php'; require_once $root.'/app/Services/ComparisonPolicy.php';
$payload['integrations/sgf/sourcing/comparison-defaults.json']=json_encode(App\Services\ComparisonPolicy::DEFAULTS,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR); $payload['integrations/sgf/sourcing/comparison-defaults.json'] = json_encode(ComparisonPolicy::DEFAULTS, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
$file = 'app/Modules/Identity/Services/Permissions.php'; $file = 'app/Modules/Identity/Services/Permissions.php';
$payload[$file] = preg_replace('/public const UNIT = .*?;/s', 'public const UNIT = '.var_export(['unit.view', 'unit.edit', ...requireRights($root)], true).';', $payload[$file], 1); $payload[$file] = preg_replace('/public const UNIT = .*?;/s', 'public const UNIT = '.var_export(['unit.view', 'unit.edit', ...requireRights($root)], true).';', $payload[$file], 1);
$manifest['host_overlays'][$file]['after_sha256'] = hash('sha256', $payload[$file]); $manifest['host_overlays'][$file]['after_sha256'] = hash('sha256', $payload[$file]);
// The same native catalogue and delegation workflow remain in use. // The same native catalogue and delegation workflow remain in use.
foreach($payload as $file=>$text)$manifest['support_files'][$file]=hash('sha256',$text); foreach ($payload as $file => $text) {
$manifest['support_files'][$file] = hash('sha256', $text);
}
$manifestText = json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR); $manifestText = json_encode($manifest, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
$id='OPERATIONAL-CANDIDATE-'.substr(hash('sha256',$manifestText),0,16);$dir=$root.'/storage/app/private/candidates/'.$id; $id = 'OPERATIONAL-CANDIDATE-'.substr(hash('sha256', $manifestText), 0, 16);
if(file_exists($dir))throw new RuntimeException('Immutable candidate exists');mkdir($dir,0700,true); $dir = $root.'/storage/app/private/candidates/'.$id;
foreach($payload+['manifest.json'=>$manifestText] as $file=>$text){if(!is_dir(dirname($dir.'/'.$file)))mkdir(dirname($dir.'/'.$file),0700,true);file_put_contents($dir.'/'.$file,$text);} if (file_exists($dir)) {
$archive=$root.'/storage/app/private/candidate-archives/'.$id.'.zip';$zip=new ZipArchive;if($zip->open($archive,ZipArchive::CREATE|ZipArchive::EXCL)!==true)throw new RuntimeException('Archive exists');foreach([...array_keys($payload),'manifest.json'] as $file)$zip->addFile($dir.'/'.$file,$file);$zip->close(); throw new RuntimeException('Immutable candidate exists');
$out=['directory'=>$dir,'archive'=>['file'=>$archive,'sha256'=>hash_file('sha256',$archive),'manifest_sha256'=>hash('sha256',$manifestText)],'prior_manifest_sha256'=>$old['archive']['manifest_sha256'],'schema_extension'=>'sourcing revision 1; four ss_* tables and explicit catalogue extension','real_activated'=>false];file_put_contents($root.'/docs/proofs/sgf-sourcing-candidate.json',json_encode($out,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($out,JSON_PRETTY_PRINT); }mkdir($dir, 0700, true);
function requireRights(string $root):array{require_once $root.'/integrations/sgf/access/AccessOverlay.php';return Tempo\Purchasing\Delivery\AccessOverlay::RIGHTS;} foreach ($payload + ['manifest.json' => $manifestText] as $file => $text) {
if (! is_dir(dirname($dir.'/'.$file))) {
mkdir(dirname($dir.'/'.$file), 0700, true);
}file_put_contents($dir.'/'.$file, $text);
}
$archive = $root.'/storage/app/private/candidate-archives/'.$id.'.zip';
$zip = new ZipArchive;
if ($zip->open($archive, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
throw new RuntimeException('Archive exists');
}foreach ([...array_keys($payload), 'manifest.json'] as $file) {
$zip->addFile($dir.'/'.$file, $file);
}$zip->close();
$out = ['directory' => $dir, 'archive' => ['file' => $archive, 'sha256' => hash_file('sha256', $archive), 'manifest_sha256' => hash('sha256', $manifestText)], 'prior_manifest_sha256' => $old['archive']['manifest_sha256'], 'schema_extension' => 'sourcing revision 1; four ss_* tables and explicit catalogue extension', 'real_activated' => false];
file_put_contents($root.'/docs/proofs/sgf-sourcing-candidate.json', json_encode($out, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($out, JSON_PRETTY_PRINT);
function requireRights(string $root): array
{
require_once $root.'/integrations/sgf/access/AccessOverlay.php';
return AccessOverlay::RIGHTS;
}
+48 -13
View File
@@ -1,20 +1,52 @@
<?php <?php
use App\Services\ComparisonPolicy;
use Tempo\Purchasing\Internal\RequisitionFailure;
use Tempo\Purchasing\Sourcing\Sourcing;
require dirname(__DIR__).'/vendor/autoload.php'; require dirname(__DIR__).'/vendor/autoload.php';
foreach(['QuotationPricing','ProposalScoring','RequisitionFailure','Sourcing'] as $c)require_once dirname(__DIR__).'/packages/purchasing/src/'.$c.'.php'; foreach (['QuotationPricing', 'ProposalScoring', 'RequisitionFailure', 'Sourcing'] as $c) {
require_once dirname(__DIR__).'/packages/purchasing/src/'.$c.'.php';
}
require_once dirname(__DIR__).'/app/Services/ComparisonPolicy.php'; require_once dirname(__DIR__).'/app/Services/ComparisonPolicy.php';
$engine=new Tempo\Purchasing\Sourcing\Sourcing; $engine = new Sourcing;
$policy=App\Services\ComparisonPolicy::DEFAULTS; $policy = ComparisonPolicy::DEFAULTS;
$request = ['status' => 'approved', 'requester_id' => 1, 'data' => ['items' => [['description' => 'Synthetic material', 'quantity' => '1.000', 'tax_rate' => '0.00']]]]; $request = ['status' => 'approved', 'requester_id' => 1, 'data' => ['items' => [['description' => 'Synthetic material', 'quantity' => '1.000', 'tax_rate' => '0.00']]]];
$state=['version'=>0,'suppliers'=>[],'quotes'=>[],'proposals'=>[],'confirmed'=>null];$checks=[]; $state = ['version' => 0, 'suppliers' => [], 'quotes' => [], 'proposals' => [], 'confirmed' => null];
$check=function($ok,$label)use(&$checks){if(!$ok)throw new RuntimeException($label);$checks[]=$label;}; $checks = [];
$deny=function($call,$status,$label)use($check){try{$call();throw new RuntimeException('Unexpected success: '.$label);}catch(Tempo\Purchasing\Internal\RequisitionFailure $e){$check($e->status===$status,$label);}}; $check = function ($ok, $label) use (&$checks) {
$step=function($s,$actor,$action,$input)use($engine,$request,$policy){$next=$engine->transition($s,$request,$actor,$action,$input,$policy,'2026-11-02');$next['version']=$s['version']+1;return $next;}; if (! $ok) {
foreach([1,2,3] as $id){$state=$step($state,1,'select',['supplier'=>['id'=>$id,'eligible'=>true,'snapshot'=>['name'=>'Synthetic '.$id]]]);$state=$step($state,1,'quote',['supplier_id'=>$id,'reference'=>'Q-'.$id,'currency'=>'MZN','valid_until'=>'2026-12-31','delivery_days'=>5,'payment_terms'=>'30 days','items'=>[['line'=>0,'unit_price'=>(string)(90+$id*10)]]]);} throw new RuntimeException($label);
}$checks[] = $label;
};
$deny = function ($call, $status, $label) use ($check) {
try {
$call();
throw new RuntimeException('Unexpected success: '.$label);
} catch (RequisitionFailure $e) {
$check($e->status === $status, $label);
}
};
$step = function ($s, $actor, $action, $input) use ($engine, $request, $policy) {
$next = $engine->transition($s, $request, $actor, $action, $input, $policy, '2026-11-02');
$next['version'] = $s['version'] + 1;
return $next;
};
foreach ([1, 2, 3] as $id) {
$state = $step($state, 1, 'select', ['supplier' => ['id' => $id, 'eligible' => true, 'snapshot' => ['name' => 'Synthetic '.$id]]]);
$state = $step($state, 1, 'quote', ['supplier_id' => $id, 'reference' => 'Q-'.$id, 'currency' => 'MZN', 'valid_until' => '2026-12-31', 'delivery_days' => 5, 'payment_terms' => '30 days', 'items' => [['line' => 0, 'unit_price' => (string) (90 + $id * 10)]]]);
}
$check(! $engine->comparison($state, $policy, '2026-11-02')['ready'], 'Existing minimum independent evaluations retained'); $check(! $engine->comparison($state, $policy, '2026-11-02')['ready'], 'Existing minimum independent evaluations retained');
$evaluation = fn ($id) => ['supplier_id' => $id, 'quote_revision' => 1, 'quality' => 8, 'history' => 8, 'payment' => 8, 'reason' => 'Synthetic evaluation reason']; $evaluation = fn ($id) => ['supplier_id' => $id, 'quote_revision' => 1, 'quality' => 8, 'history' => 8, 'payment' => 8, 'reason' => 'Synthetic evaluation reason'];
$deny(fn () => $step($state, 1, 'evaluate', $evaluation(1)), 403, 'Requester cannot evaluate'); $deny(fn () => $step($state, 1, 'evaluate', $evaluation(1)), 403, 'Requester cannot evaluate');
foreach([1,2,3] as $id)foreach([2,4] as $actor)$state=$step($state,$actor,'evaluate',$evaluation($id)); foreach ([1, 2, 3] as $id) {
$comparison=$engine->comparison($state,$policy,'2026-11-02');$check($comparison['ready']&&$comparison['top_ids']===[1],'Existing weighted scoring identifies best eligible quote'); foreach ([2, 4] as $actor) {
$state = $step($state, $actor, 'evaluate', $evaluation($id));
}
}
$comparison = $engine->comparison($state, $policy, '2026-11-02');
$check($comparison['ready'] && $comparison['top_ids'] === [1], 'Existing weighted scoring identifies best eligible quote');
$proposal = ['supplier_id' => 1, 'comparison_hash' => $comparison['fingerprint'], 'reason' => 'Synthetic award proposal justification', 'delivery_date' => '2027-01-15', 'delivery_location' => 'Local de entrega exclusivamente sintético OPER']; $proposal = ['supplier_id' => 1, 'comparison_hash' => $comparison['fingerprint'], 'reason' => 'Synthetic award proposal justification', 'delivery_date' => '2027-01-15', 'delivery_location' => 'Local de entrega exclusivamente sintético OPER'];
$deny(fn () => $step($state, 1, 'propose', $proposal), 403, 'Requester cannot propose award'); $deny(fn () => $step($state, 1, 'propose', $proposal), 403, 'Requester cannot propose award');
$state = $step($state, 2, 'propose', $proposal); $state = $step($state, 2, 'propose', $proposal);
@@ -23,13 +55,16 @@ $deny(fn()=>$step($state,2,'confirm',$confirmation),403,'Proposer cannot confirm
$deny(fn () => $step($state, 1, 'confirm', $confirmation), 403, 'Requester cannot confirm award'); $deny(fn () => $step($state, 1, 'confirm', $confirmation), 403, 'Requester cannot confirm award');
$changed = $step($state, 1, 'quote', ['supplier_id' => 1, 'reference' => 'Q-1-r2', 'currency' => 'MZN', 'valid_until' => '2026-12-31', 'delivery_days' => 6, 'payment_terms' => '30 days', 'items' => [['line' => 0, 'unit_price' => '100.00']]]); $changed = $step($state, 1, 'quote', ['supplier_id' => 1, 'reference' => 'Q-1-r2', 'currency' => 'MZN', 'valid_until' => '2026-12-31', 'delivery_days' => 6, 'payment_terms' => '30 days', 'items' => [['line' => 0, 'unit_price' => '100.00']]]);
$deny(fn () => $step($changed, 4, 'confirm', $confirmation), 409, 'Quote revision invalidates existing award basis and evaluations'); $deny(fn () => $step($changed, 4, 'confirm', $confirmation), 409, 'Quote revision invalidates existing award basis and evaluations');
$revoked=$state;$revoked['quotes'][1]['evaluations'][4]['eligible']=false; $revoked = $state;
$revoked['quotes'][1]['evaluations'][4]['eligible'] = false;
$deny(fn () => $step($revoked, 4, 'confirm', $confirmation), 409, 'Evaluator revocation invalidates confirmation basis'); $deny(fn () => $step($revoked, 4, 'confirm', $confirmation), 409, 'Evaluator revocation invalidates confirmation basis');
$expired=$state;$expired['quotes'][1]['valid_until']='2026-11-01'; $expired = $state;
$expired['quotes'][1]['valid_until'] = '2026-11-01';
$deny(fn () => $step($expired, 4, 'confirm', $confirmation), 409, 'Expired quote invalidates confirmation'); $deny(fn () => $step($expired, 4, 'confirm', $confirmation), 409, 'Expired quote invalidates confirmation');
$ok = $step($state, 4, 'confirm', $confirmation); $ok = $step($state, 4, 'confirm', $confirmation);
$check($ok['confirmed']['confirmed_by'] === 4 && $ok['confirmed']['proposal']['proposed_by'] === 2, 'Independent confirmation preserves exact proposed comparison'); $check($ok['confirmed']['confirmed_by'] === 4 && $ok['confirmed']['proposal']['proposed_by'] === 2, 'Independent confirmation preserves exact proposed comparison');
$deny(fn () => $step($ok, 1, 'quote', []), 409, 'Confirmed process cannot be rewritten'); $deny(fn () => $step($ok, 1, 'quote', []), 409, 'Confirmed process cannot be rewritten');
$check($state['proposals'][0]['comparison']['fingerprint'] === $comparison['fingerprint'], 'Comparison snapshot and justification preserved'); $check($state['proposals'][0]['comparison']['fingerprint'] === $comparison['fingerprint'], 'Comparison snapshot and justification preserved');
$report = ['passed' => true, 'checks' => $checks, 'synthetic_only' => true, 'persistent_demo_accounts_created' => false, 'checked_at' => gmdate('c')]; $report = ['passed' => true, 'checks' => $checks, 'synthetic_only' => true, 'persistent_demo_accounts_created' => false, 'checked_at' => gmdate('c')];
file_put_contents(dirname(__DIR__).'/docs/proofs/sgf-sourcing-core.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($report,JSON_PRETTY_PRINT); file_put_contents(dirname(__DIR__).'/docs/proofs/sgf-sourcing-core.json',json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($report,JSON_PRETTY_PRINT);
+190 -21
View File
@@ -1,26 +1,195 @@
import fs from 'node:fs';import assert from 'node:assert/strict';import crypto from 'node:crypto'; import fs from 'node:fs';
const privateData=JSON.parse(fs.readFileSync('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json','utf8')); import assert from 'node:assert/strict';
assert.deepEqual([privateData.tenant_id,privateData.company_id,privateData.unit_id],[1,1,1]); import crypto from 'node:crypto';
const clients={},checks=[]; const privateData = JSON.parse(
for(const p of privateData.profiles){let csrf='',token='';const jar=new Map(); fs.readFileSync(
const api=async(path,method='GET',body,status=200)=>{const r=await fetch('http://127.0.0.1:8039'+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'},...(body===undefined?{}:{body:JSON.stringify(body)})});for(const c of r.headers.getSetCookie()){const pair=c.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,160)};}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;}; 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json',
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; 'utf8',
),
);
assert.deepEqual(
[privateData.tenant_id, privateData.company_id, privateData.unit_id],
[1, 1, 1],
);
const clients = {},
checks = [];
for (const p of privateData.profiles) {
let csrf = '',
token = '';
const jar = new Map();
const api = async (path, method = 'GET', body, status = 200) => {
const r = await fetch('http://127.0.0.1:8039' + 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',
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
for (const c of r.headers.getSetCookie()) {
const pair = c.split(';')[0],
at = pair.indexOf('=');
jar.set(pair.slice(0, at), pair.slice(at + 1));
} }
const read=who=>clients[who]('/api/sourcing/1'); const text = await r.text();
async function command(who,action,body,status=200){const current=await read(who);return clients[who]('/api/sourcing/1/'+action,'POST',{operation_key:crypto.randomUUID(),version:current.state.version,...(action==='propose'?{delivery_date:'2027-01-15',delivery_location:'Local de entrega apenas sintético para teste de recusa'}:{}),...body},status);} let d;
let initial=await read('preparador');assert.equal(initial.request.total_minor,10000);assert.equal(initial.request.version,3);assert.equal(initial.suppliers.length,3); try {
d = JSON.parse(text);
} catch {
d = { message: text.slice(0, 160) };
}
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, body, status = 200) {
const current = await read(who);
return clients[who](
'/api/sourcing/1/' + action,
'POST',
{
operation_key: crypto.randomUUID(),
version: current.state.version,
...(action === 'propose'
? {
delivery_date: '2027-01-15',
delivery_location:
'Local de entrega apenas sintético para teste de recusa',
}
: {}),
...body,
},
status,
);
}
let initial = await read('preparador');
assert.equal(initial.request.total_minor, 10000);
assert.equal(initial.request.version, 3);
assert.equal(initial.suppliers.length, 3);
for (const [index, supplier] of initial.suppliers.entries()) { for (const [index, supplier] of initial.suppliers.entries()) {
let current=await read('preparador');if(!current.state.suppliers[supplier.id])await command('preparador','select',{supplier_id:supplier.id}); let current = await read('preparador');
if (!current.state.suppliers[supplier.id])
await command('preparador', 'select', { supplier_id: supplier.id });
current = await read('preparador'); current = await read('preparador');
if(!current.state.quotes[supplier.id])await command('preparador','quote',{supplier_id:supplier.id,reference:'DEMO-COTACAO-'+supplier.reference,currency:'MZN',valid_until:'2027-12-31',delivery_days:5+index,payment_terms:'Condições sintéticas: pagamento a 30 dias',items:current.request.data.items.map((_,line)=>({line,unit_price:(100+index*10).toFixed(2)}))}); if (!current.state.quotes[supplier.id])
current=await read('revisor');const q=current.state.quotes[supplier.id]; await command('preparador', 'quote', {
if(!q.evaluations[2])await command('revisor','evaluate',{supplier_id:supplier.id,quote_revision:q.revision,quality:8,history:8,payment:8,no_conflict:true,reason:'Avaliação exclusivamente sintética de demonstração; sem contacto externo.'}); supplier_id: supplier.id,
reference: 'DEMO-COTACAO-' + supplier.reference,
currency: 'MZN',
valid_until: '2027-12-31',
delivery_days: 5 + index,
payment_terms: 'Condições sintéticas: pagamento a 30 dias',
items: current.request.data.items.map((_, line) => ({
line,
unit_price: (100 + index * 10).toFixed(2),
})),
});
current = await read('revisor');
const q = current.state.quotes[supplier.id];
if (!q.evaluations[2])
await command('revisor', 'evaluate', {
supplier_id: supplier.id,
quote_revision: q.revision,
quality: 8,
history: 8,
payment: 8,
no_conflict: true,
reason: 'Avaliação exclusivamente sintética de demonstração; sem contacto externo.',
});
} }
const pending=await read('consulta');assert.equal(pending.comparison.ready,false);assert(pending.comparison.rows.every(r=>r.evaluation_count===1));assert.equal(pending.state.confirmed,null);assert.equal(pending.state.proposals.length,0); const pending = await read('consulta');
await command('revisor','propose',{supplier_id:pending.comparison.rows[0].supplier_id,comparison_hash:pending.comparison.fingerprint,reason:'Verificar bloqueio por falta de segundo avaliador independente.'},422); assert.equal(pending.comparison.ready, false);
await command('revisor','propose',{supplier_id:pending.comparison.rows[1].supplier_id,comparison_hash:pending.comparison.fingerprint,reason:'Verificar sinalização de adaptação orçamental sem movimento financeiro.'},409); assert(pending.comparison.rows.every((r) => r.evaluation_count === 1));
for(const action of ['select','quote','evaluate','propose','confirm'])await clients.consulta('/api/sourcing/1/'+action,'POST',{},403); assert.equal(pending.state.confirmed, null);
assert.equal(pending.state.proposals.length, 0);
await command(
'revisor',
'propose',
{
supplier_id: pending.comparison.rows[0].supplier_id,
comparison_hash: pending.comparison.fingerprint,
reason: 'Verificar bloqueio por falta de segundo avaliador independente.',
},
422,
);
await command(
'revisor',
'propose',
{
supplier_id: pending.comparison.rows[1].supplier_id,
comparison_hash: pending.comparison.fingerprint,
reason: 'Verificar sinalização de adaptação orçamental sem movimento financeiro.',
},
409,
);
for (const action of ['select', 'quote', 'evaluate', 'propose', 'confirm'])
await clients.consulta('/api/sourcing/1/' + action, 'POST', {}, 403);
await clients.revisor('/api/sourcing/1/confirm', 'POST', {}, 403); await clients.revisor('/api/sourcing/1/confirm', 'POST', {}, 403);
for(const who of ['preparador','revisor','consulta']){const origin=await clients[who]('/api/internal-requisitions/1');assert.equal(origin.record.version,3);assert.equal(origin.record.total_minor,10000);assert.equal(origin.history.length,3);assert(origin.canSourcing);await clients[who]('/purchasing/sourcing/1');} for (const who of ['preparador', 'revisor', 'consulta']) {
checks.push('Existing request reused with version 3 and unchanged three-event history');checks.push('Three selected synthetic suppliers, three quotes and one eligible evaluation per quote');checks.push('Comparison and award proposal remain blocked without second eligible evaluator');checks.push('Quoted amount differing from reserved amount is signalled without a budget movement');checks.push('Consulta retains full sourcing read and no preparation/evaluation/proposal/confirmation');checks.push('No persistent identity has award-confirmation right; no award created');checks.push('Protected sourcing screen is accessible to all three existing profiles'); const origin = await clients[who]('/api/internal-requisitions/1');
const proof={passed:true,url:'http://127.0.0.1:8039',scope:'1:1:1',request_id:1,checks,confirmation_completed:false,owner_decision_no_fourth_account:true,visual_review:false,checked_at:new Date().toISOString()};fs.writeFileSync('C:/laragon/www/compras/docs/proofs/sgf-sourcing-demo-http.json',JSON.stringify(proof,null,2));console.log(JSON.stringify(proof)); assert.equal(origin.record.version, 3);
assert.equal(origin.record.total_minor, 10000);
assert.equal(origin.history.length, 3);
assert(origin.canSourcing);
await clients[who]('/purchasing/sourcing/1');
}
checks.push(
'Existing request reused with version 3 and unchanged three-event history',
);
checks.push(
'Three selected synthetic suppliers, three quotes and one eligible evaluation per quote',
);
checks.push(
'Comparison and award proposal remain blocked without second eligible evaluator',
);
checks.push(
'Quoted amount differing from reserved amount is signalled without a budget movement',
);
checks.push(
'Consulta retains full sourcing read and no preparation/evaluation/proposal/confirmation',
);
checks.push(
'No persistent identity has award-confirmation right; no award created',
);
checks.push(
'Protected sourcing screen is accessible to all three existing profiles',
);
const proof = {
passed: true,
url: 'http://127.0.0.1:8039',
scope: '1:1:1',
request_id: 1,
checks,
confirmation_completed: false,
owner_decision_no_fourth_account: true,
visual_review: false,
checked_at: new Date().toISOString(),
};
fs.writeFileSync(
'C:/laragon/www/compras/docs/proofs/sgf-sourcing-demo-http.json',
JSON.stringify(proof, null, 2),
);
console.log(JSON.stringify(proof));
+142 -43
View File
@@ -1,65 +1,164 @@
<?php <?php
use App\Modules\Identity\Services\Audit;
use App\Modules\Identity\Services\Permissions;
use Illuminate\Contracts\Console\Kernel; use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
use App\Modules\Identity\Services\Permissions;
use App\Modules\Identity\Services\Audit;
use Tempo\Purchasing\Delivery\CodeDeployment; use Tempo\Purchasing\Delivery\CodeDeployment;
use Tempo\Purchasing\SgfSourcing\Schema; use Tempo\Purchasing\SgfSourcing\Schema;
$root=dirname(__DIR__);$host='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';$recovery=dirname($host).'/private/sourcing-recovery';
require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap(); $root = dirname(__DIR__);
$host = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
$recovery = dirname($host).'/private/sourcing-recovery';
require $host.'/vendor/autoload.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
try { try {
$db=DB::connection();$identity=$db->selectOne("select current_database() as db,current_user as role,inet_server_port() as port,current_setting('cluster_name') as cluster"); $db = DB::connection();
if(str_replace('\\','/',$app->basePath())!==$host||$identity->db!=='sgf_modules_dev_2576427d1939'||$identity->role!=='sgf_modules_qa_2576427d1939'||(int)$identity->port!==55439||$identity->cluster!=='sgf_modular_regression_2576427d1939'||config('app.url')!=='http://127.0.0.1:8039')throw new RuntimeException('Wrong persistent synthetic demonstration'); $identity = $db->selectOne("select current_database() as db,current_user as role,inet_server_port() as port,current_setting('cluster_name') as cluster");
if (str_replace('\\', '/', $app->basePath()) !== $host || $identity->db !== 'sgf_modules_dev_2576427d1939' || $identity->role !== 'sgf_modules_qa_2576427d1939' || (int) $identity->port !== 55439 || $identity->cluster !== 'sgf_modular_regression_2576427d1939' || config('app.url') !== 'http://127.0.0.1:8039') {
throw new RuntimeException('Wrong persistent synthetic demonstration');
}
app(Permissions::class)->require(1, 1, 1, 'access.manage'); app(Permissions::class)->require(1, 1, 1, 'access.manage');
$candidate = json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-candidate.json'), true, 32, JSON_THROW_ON_ERROR); $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'; if (! class_exists(Schema::class)) {
$hash=function(string $table)use($db){return hash('sha256',json_encode($db->table($table)->orderBy('id')->get(),JSON_THROW_ON_ERROR));}; require_once $candidate['directory'].'/integrations/sgf/sourcing/Schema.php';
}require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
$hash = function (string $table) use ($db) {
return hash('sha256', json_encode($db->table($table)->orderBy('id')->get(), JSON_THROW_ON_ERROR));
};
$action = $argv[1] ?? ''; $action = $argv[1] ?? '';
if ($action === 'prepare') { if ($action === 'prepare') {
if(is_dir($recovery))throw new RuntimeException('Recovery exists: do not overwrite'); if (is_dir($recovery)) {
$proof=json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-isolated.json'),true);if(!$proof['passed']||!$proof['persistent_demo_unchanged']||!($proof['recovery']['data_schema_restore_verified']??false)||$proof['setup']['deployment']['deployment_id']!==substr($candidate['archive']['manifest_sha256'],0,24))throw new RuntimeException('Current candidate needs accepted isolation/recovery proof'); throw new RuntimeException('Recovery exists: do not overwrite');
if($db->table('users')->count()!==3)throw new RuntimeException('Unexpected accounts: reconcile before proceeding'); }
mkdir($recovery,0700,true);$cfg=$db->getConfig();(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe','--format=custom','--file='.$recovery.'/before.dump','--dbname='.$identity->db],null,['PGHOST'=>'127.0.0.1','PGPORT'=>'55439','PGUSER'=>$identity->role,'PGPASSWORD'=>$cfg['password']],null,90))->mustRun(); $proof = json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-isolated.json'), true);
if (! $proof['passed'] || ! $proof['persistent_demo_unchanged'] || ! ($proof['recovery']['data_schema_restore_verified'] ?? false) || $proof['setup']['deployment']['deployment_id'] !== substr($candidate['archive']['manifest_sha256'], 0, 24)) {
throw new RuntimeException('Current candidate needs accepted isolation/recovery proof');
}
if ($db->table('users')->count() !== 3) {
throw new RuntimeException('Unexpected accounts: reconcile before proceeding');
}
mkdir($recovery, 0700, true);
$cfg = $db->getConfig();
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--format=custom', '--file='.$recovery.'/before.dump', '--dbname='.$identity->db], null, ['PGHOST' => '127.0.0.1', 'PGPORT' => '55439', 'PGUSER' => $identity->role, 'PGPASSWORD' => $cfg['password']], null, 90))->mustRun();
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--list', $recovery.'/before.dump']))->mustRun(); (new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--list', $recovery.'/before.dump']))->mustRun();
$baseline = ['candidate' => $candidate, 'identity' => $identity, 'backup_sha256' => hash_file('sha256', $recovery.'/before.dump'), 'users' => $hash('users'), 'requests' => $hash('ir_requests'), 'budget' => $hash('cb_budget_entries'), 'consumption' => $hash('cb_budget_consumptions'), 'grants' => $db->table('permission_grants')->orderBy('id')->get()->all(), 'pointer_sha256' => hash_file('sha256', $host.'/packages/purchasing/current.json')]; $baseline = ['candidate' => $candidate, 'identity' => $identity, 'backup_sha256' => hash_file('sha256', $recovery.'/before.dump'), 'users' => $hash('users'), 'requests' => $hash('ir_requests'), 'budget' => $hash('cb_budget_entries'), 'consumption' => $hash('cb_budget_consumptions'), 'grants' => $db->table('permission_grants')->orderBy('id')->get()->all(), 'pointer_sha256' => hash_file('sha256', $host.'/packages/purchasing/current.json')];
file_put_contents($recovery.'/baseline.json',json_encode($baseline,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode(['prepared'=>true,'identity'=>$identity,'backup_sha256'=>$baseline['backup_sha256']]); file_put_contents($recovery.'/baseline.json', json_encode($baseline, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode(['prepared' => true, 'identity' => $identity, 'backup_sha256' => $baseline['backup_sha256']]);
} elseif ($action === 'apply') { } elseif ($action === 'apply') {
$baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR); $baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
foreach(['users'=>'users','requests'=>'ir_requests','budget'=>'cb_budget_entries','consumption'=>'cb_budget_consumptions'] as $key=>$table)if($baseline[$key]!==$hash($table))throw new RuntimeException('Baseline changed: '.$table); foreach (['users' => 'users', 'requests' => 'ir_requests', 'budget' => 'cb_budget_entries', 'consumption' => 'cb_budget_consumptions'] as $key => $table) {
if($baseline['candidate']['archive']['manifest_sha256']!==$candidate['archive']['manifest_sha256']||!hash_equals($baseline['backup_sha256'],hash_file('sha256',$recovery.'/before.dump')))throw new RuntimeException('Candidate/backup changed'); if ($baseline[$key] !== $hash($table)) {
if(is_file($host.'/storage/framework/down'))throw new RuntimeException('Unexpected prior maintenance');file_put_contents($host.'/storage/framework/down','{}'); throw new RuntimeException('Baseline changed: '.$table);
$old=json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'),true);$current=json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'),true);$next=json_decode(file_get_contents($candidate['directory'].'/manifest.json'),true); }
}
if ($baseline['candidate']['archive']['manifest_sha256'] !== $candidate['archive']['manifest_sha256'] || ! hash_equals($baseline['backup_sha256'], hash_file('sha256', $recovery.'/before.dump'))) {
throw new RuntimeException('Candidate/backup changed');
}
if (is_file($host.'/storage/framework/down')) {
throw new RuntimeException('Unexpected prior maintenance');
}file_put_contents($host.'/storage/framework/down', '{}');
$old = json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'), true);
$current = json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'), true);
$next = json_decode(file_get_contents($candidate['directory'].'/manifest.json'), true);
$migration = Schema::migrate($db, $baseline['backup_sha256'], 'Owner-confirmed synthetic sourcing 8039'); $migration = Schema::migrate($db, $baseline['backup_sha256'], 'Owner-confirmed synthetic sourcing 8039');
$receipt = ['host' => $host, 'from_manifest_sha256' => $current['manifest_sha256'], 'to_manifest_sha256' => $candidate['archive']['manifest_sha256'], 'schema_verified' => Schema::compatible($db), 'changes' => []]; $receipt = ['host' => $host, 'from_manifest_sha256' => $current['manifest_sha256'], 'to_manifest_sha256' => $candidate['archive']['manifest_sha256'], 'schema_verified' => Schema::compatible($db), 'changes' => []];
foreach($next['support_files'] as $file=>$sha)if(($old['support_files'][$file]??null)!==$sha)$receipt['changes'][$file]=['before'=>$old['support_files'][$file]??null,'after'=>$sha]; foreach ($next['support_files'] as $file => $sha) {
file_put_contents($host.'/storage/app/private/module-deployments/schema-transition-'.$candidate['archive']['manifest_sha256'].'.json',json_encode($receipt)); if (($old['support_files'][$file] ?? null) !== $sha) {
$deploy=new CodeDeployment($host);$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);$applied=$deploy->apply($candidate['directory'],$candidate['archive']['manifest_sha256'],$plan['target_sha256'],'Owner-confirmed synthetic sourcing 8039',true);file_put_contents($recovery.'/applied.json',json_encode($applied,JSON_PRETTY_PRINT)); $receipt['changes'][$file] = ['before' => $old['support_files'][$file] ?? null, 'after' => $sha];
$db->transaction(function()use($db){ }
foreach([1=>['purchasing_sourcing.prepare'],2=>['purchasing_sourcing.evaluate','purchasing_sourcing.propose']] as $id=>$rights)foreach($rights as $right){ }
$scope=['user_id'=>$id,'tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'permission'=>$right];$inserted=$db->table('permission_grants')->insertOrIgnore($scope+['created_at'=>now(),'updated_at'=>now()]); file_put_contents($host.'/storage/app/private/module-deployments/schema-transition-'.$candidate['archive']['manifest_sha256'].'.json', json_encode($receipt));
if($inserted)Audit::record('access.granted',1,1,1,1,$id,details:['permission'=>$right,'reason'=>'Owner explicitly authorised exact sourcing map; no fourth persistent account.']); $deploy = new CodeDeployment($host);
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
$applied = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Owner-confirmed synthetic sourcing 8039', true);
file_put_contents($recovery.'/applied.json', json_encode($applied, JSON_PRETTY_PRINT));
$db->transaction(function () use ($db) {
foreach ([1 => ['purchasing_sourcing.prepare'], 2 => ['purchasing_sourcing.evaluate', 'purchasing_sourcing.propose']] as $id => $rights) {
foreach ($rights as $right) {
$scope = ['user_id' => $id, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'permission' => $right];
$inserted = $db->table('permission_grants')->insertOrIgnore($scope + ['created_at' => now(), 'updated_at' => now()]);
if ($inserted) {
Audit::record('access.granted', 1, 1, 1, 1, $id, details: ['permission' => $right, 'reason' => 'Owner explicitly authorised exact sourcing map; no fourth persistent account.']);
}
}
}
foreach (['A', 'B', 'C'] as $letter) {
$db->table('ss_suppliers')->insertOrIgnore(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'reference' => 'SOURCING-DEMO-'.$letter, 'payload' => json_encode(['name' => 'Fornecedor sintético '.$letter, 'active' => true, 'blocked' => false, 'review_until' => '2027-12-31', 'version' => 1, 'synthetic_only' => true]), 'created_at' => now()]);
} }
foreach(['A','B','C'] as $letter)$db->table('ss_suppliers')->insertOrIgnore(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'reference'=>'SOURCING-DEMO-'.$letter,'payload'=>json_encode(['name'=>'Fornecedor sintético '.$letter,'active'=>true,'blocked'=>false,'review_until'=>'2027-12-31','version'=>1,'synthetic_only'=>true]),'created_at'=>now()]);
}); });
file_put_contents($host.'/config/purchasing-sourcing.php','<?php return ["enabled"=>true];');unlink($host.'/storage/framework/down');echo json_encode(['applied'=>true,'deployment'=>$applied,'schema'=>$migration,'persistent_accounts_created'=>false,'grants_added'=>3,'confirmation_blocked_without_independent_identity'=>true]); file_put_contents($host.'/config/purchasing-sourcing.php', '<?php return ["enabled"=>true];');
unlink($host.'/storage/framework/down');
echo json_encode(['applied' => true, 'deployment' => $applied, 'schema' => $migration, 'persistent_accounts_created' => false, 'grants_added' => 3, 'confirmation_blocked_without_independent_identity' => true]);
} elseif ($action === 'apply-code') { } elseif ($action === 'apply-code') {
if(!Schema::compatible($db))throw new RuntimeException('Code-only update requires the existing compatible sourcing schema'); if (! Schema::compatible($db)) {
$proof=json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-isolated.json'),true);if(!$proof['passed']||$proof['setup']['deployment']['deployment_id']!==substr($candidate['archive']['manifest_sha256'],0,24))throw new RuntimeException('Candidate proof mismatch'); throw new RuntimeException('Code-only update requires the existing compatible sourcing schema');
$before=[];foreach([...Schema::TABLES,'ir_requests','cb_budget_entries','cb_budget_consumptions','permission_grants','users'] as $table)$before[$table]=$hash($table); }
if(is_file($host.'/storage/framework/down'))throw new RuntimeException('Unexpected prior maintenance'); $proof = json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-isolated.json'), true);
$deploy=new CodeDeployment($host);$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']); if (! $proof['passed'] || $proof['setup']['deployment']['deployment_id'] !== substr($candidate['archive']['manifest_sha256'], 0, 24)) {
file_put_contents($recovery.'/before-final-code.json',json_encode(['candidate'=>$candidate,'data_hashes'=>$before,'plan'=>$plan],JSON_PRETTY_PRINT));file_put_contents($host.'/storage/framework/down','{}'); throw new RuntimeException('Candidate proof mismatch');
}
$before = [];
foreach ([...Schema::TABLES, 'ir_requests', 'cb_budget_entries', 'cb_budget_consumptions', 'permission_grants', 'users'] as $table) {
$before[$table] = $hash($table);
}
if (is_file($host.'/storage/framework/down')) {
throw new RuntimeException('Unexpected prior maintenance');
}
$deploy = new CodeDeployment($host);
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
file_put_contents($recovery.'/before-final-code.json', json_encode(['candidate' => $candidate, 'data_hashes' => $before, 'plan' => $plan], JSON_PRETTY_PRINT));
file_put_contents($host.'/storage/framework/down', '{}');
$applied = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Authorised sourcing final code refinement', true); $applied = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Authorised sourcing final code refinement', true);
foreach($before as $table=>$expected)if($hash($table)!==$expected)throw new RuntimeException('Code update changed data: '.$table); foreach ($before as $table => $expected) {
file_put_contents($recovery.'/final-code.json',json_encode($applied,JSON_PRETTY_PRINT));unlink($host.'/storage/framework/down');echo json_encode(['applied'=>true,'code_only'=>true,'deployment'=>$applied,'data_preserved'=>true,'schema_changed'=>false,'rights_changed'=>false]); if ($hash($table) !== $expected) {
throw new RuntimeException('Code update changed data: '.$table);
}
}
file_put_contents($recovery.'/final-code.json', json_encode($applied, JSON_PRETTY_PRINT));
unlink($host.'/storage/framework/down');
echo json_encode(['applied' => true, 'code_only' => true, 'deployment' => $applied, 'data_preserved' => true, 'schema_changed' => false, 'rights_changed' => false]);
} elseif ($action === 'verify') { } elseif ($action === 'verify') {
if(hash_file('sha256',$host.'/packages/internal-requisitions/manifest.json')!==$candidate['archive']['manifest_sha256'])throw new RuntimeException('Installed candidate does not match the delivery report'); if (hash_file('sha256', $host.'/packages/internal-requisitions/manifest.json') !== $candidate['archive']['manifest_sha256']) {
$baseline=json_decode(file_get_contents($recovery.'/baseline.json'),true,64,JSON_THROW_ON_ERROR);foreach(['users'=>'users','requests'=>'ir_requests','budget'=>'cb_budget_entries','consumption'=>'cb_budget_consumptions'] as $key=>$table)if($baseline[$key]!==$hash($table))throw new RuntimeException('Protected baseline changed: '.$table); throw new RuntimeException('Installed candidate does not match the delivery report');
$current=$db->table('permission_grants')->orderBy('id')->get()->keyBy('id');foreach($baseline['grants'] as $old)if((array)$current[$old['id']]!=$old)throw new RuntimeException('Previous grant changed'); }
$new=$current->except(array_column($baseline['grants'],'id'))->values()->all();if(count($new)!==3)throw new RuntimeException('Expected exactly three authorised new rights');foreach($new as $g)if([$g->tenant_id,$g->company_id,$g->unit_id]!==[1,1,1]||!in_array([$g->user_id,$g->permission],[[1,'purchasing_sourcing.prepare'],[2,'purchasing_sourcing.evaluate'],[2,'purchasing_sourcing.propose']],true))throw new RuntimeException('Unapproved grant'); $baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
if(hash_file('sha256',$host.'/packages/purchasing/current.json')!==$baseline['pointer_sha256'])throw new RuntimeException('Pointer changed'); foreach (['users' => 'users', 'requests' => 'ir_requests', 'budget' => 'cb_budget_entries', 'consumption' => 'cb_budget_consumptions'] as $key => $table) {
$process=$db->table('ss_processes')->where(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'request_id'=>1])->first();$state=json_decode($process->payload,true);if($state['confirmed']!==null||$state['proposals']!==[])throw new RuntimeException('Incomplete comparison must not be awarded'); if ($baseline[$key] !== $hash($table)) {
$report=['passed'=>true,'identity'=>$identity,'scope'=>'1:1:1','candidate'=>$candidate,'protected_users_requisition_reservation_consumption_unchanged'=>true,'previous_grants_preserved'=>true,'new_grants'=>$new,'persistent_accounts_created'=>false,'proposals'=>0,'confirmed'=>false,'suppliers_selected'=>count($state['suppliers']),'quotations'=>count($state['quotes']),'pending'=>'Second eligible evaluator and independent confirmer absent; no account created by owner decision.','backup_sha256'=>$baseline['backup_sha256'],'recovery_directory'=>$recovery,'checked_at'=>gmdate('c')];file_put_contents($root.'/docs/proofs/sgf-sourcing-demo.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));echo json_encode($report,JSON_PRETTY_PRINT); throw new RuntimeException('Protected baseline changed: '.$table);
}else throw new RuntimeException('Use prepare/apply/verify'); }
}catch(Throwable $e){fwrite(STDERR,$e->getMessage()."\n");exit(1);} }
$current = $db->table('permission_grants')->orderBy('id')->get()->keyBy('id');
foreach ($baseline['grants'] as $old) {
if ((array) $current[$old['id']] != $old) {
throw new RuntimeException('Previous grant changed');
}
}
$new = $current->except(array_column($baseline['grants'], 'id'))->values()->all();
if (count($new) !== 3) {
throw new RuntimeException('Expected exactly three authorised new rights');
}foreach ($new as $g) {
if ([$g->tenant_id, $g->company_id, $g->unit_id] !== [1, 1, 1] || ! in_array([$g->user_id, $g->permission], [[1, 'purchasing_sourcing.prepare'], [2, 'purchasing_sourcing.evaluate'], [2, 'purchasing_sourcing.propose']], true)) {
throw new RuntimeException('Unapproved grant');
}
}
if (hash_file('sha256', $host.'/packages/purchasing/current.json') !== $baseline['pointer_sha256']) {
throw new RuntimeException('Pointer changed');
}
$process = $db->table('ss_processes')->where(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'request_id' => 1])->first();
$state = json_decode($process->payload, true);
if ($state['confirmed'] !== null || $state['proposals'] !== []) {
throw new RuntimeException('Incomplete comparison must not be awarded');
}
$report = ['passed' => true, 'identity' => $identity, 'scope' => '1:1:1', 'candidate' => $candidate, 'protected_users_requisition_reservation_consumption_unchanged' => true, 'previous_grants_preserved' => true, 'new_grants' => $new, 'persistent_accounts_created' => false, 'proposals' => 0, 'confirmed' => false, 'suppliers_selected' => count($state['suppliers']), 'quotations' => count($state['quotes']), 'pending' => 'Second eligible evaluator and independent confirmer absent; no account created by owner decision.', 'backup_sha256' => $baseline['backup_sha256'], 'recovery_directory' => $recovery, 'checked_at' => gmdate('c')];
file_put_contents($root.'/docs/proofs/sgf-sourcing-demo.json',json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($report,JSON_PRETTY_PRINT);
} else {
throw new RuntimeException('Use prepare/apply/verify');
}
} catch (Throwable $e) {
fwrite(STDERR,$e->getMessage()."\n");
exit(1);
}
+48 -14
View File
@@ -1,31 +1,65 @@
<?php <?php
// Offline additive migration; no rights, credentials, contacts or activation are provisioned. // Offline additive migration; no rights, credentials, contacts or activation are provisioned.
use Illuminate\Contracts\Console\Kernel; use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
use Tempo\Purchasing\Delivery\Installation;
use Tempo\Purchasing\Delivery\CodeDeployment; use Tempo\Purchasing\Delivery\CodeDeployment;
use Tempo\Purchasing\Delivery\Installation;
use Tempo\Purchasing\SgfSourcing\Schema; use Tempo\Purchasing\SgfSourcing\Schema;
$root=dirname(__DIR__);$action=$argv[1]??'';$host=realpath($argv[2]??'');
$root = dirname(__DIR__);
$action = $argv[1] ?? '';
$host = realpath($argv[2] ?? '');
try { try {
if(!$host||!in_array($action,['plan','migrate'],true))throw new RuntimeException('Usage: plan <host> | migrate <host> <target-sha> <backup-file> <backup-sha> <operator> <manifest-sha>'); if (! $host || ! in_array($action, ['plan', 'migrate'], true)) {
$host=str_replace('\\','/',$host);$manifestText=file_get_contents($root.'/manifest.json');$manifest=json_decode($manifestText,true,64,JSON_THROW_ON_ERROR);$manifestHash=hash('sha256',$manifestText); throw new RuntimeException('Usage: plan <host> | migrate <host> <target-sha> <backup-file> <backup-sha> <operator> <manifest-sha>');
foreach($manifest['support_files'] as $file=>$hash)if(str_contains($file,'..')||!preg_match('~^[A-Za-z0-9_./-]+$~D',$file)||is_link($root.'/'.$file)||!hash_equals($hash,hash_file('sha256',$root.'/'.$file)))throw new RuntimeException('Bundle integrity failed'); }
require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap(); $host = str_replace('\\', '/', $host);
if(!class_exists(Installation::class))require_once $root.'/integrations/sgf/operational/bootstrap.php'; $manifestText = file_get_contents($root.'/manifest.json');
if(!class_exists(Schema::class))require_once $root.'/integrations/sgf/sourcing/Schema.php'; $manifest = json_decode($manifestText, true, 64, JSON_THROW_ON_ERROR);
$manifestHash = hash('sha256', $manifestText);
foreach ($manifest['support_files'] as $file => $hash) {
if (str_contains($file, '..') || ! preg_match('~^[A-Za-z0-9_./-]+$~D', $file) || is_link($root.'/'.$file) || ! hash_equals($hash, hash_file('sha256', $root.'/'.$file))) {
throw new RuntimeException('Bundle integrity failed');
}
}
require $host.'/vendor/autoload.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
if (! class_exists(Installation::class)) {
require_once $root.'/integrations/sgf/operational/bootstrap.php';
}
if (! class_exists(Schema::class)) {
require_once $root.'/integrations/sgf/sourcing/Schema.php';
}
require_once $root.'/integrations/sgf/operational/CodeDeployment.php'; require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
$db=DB::connection();$current=json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'),true,32,JSON_THROW_ON_ERROR); $db = DB::connection();
$current = json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'), true, 32, JSON_THROW_ON_ERROR);
(new CodeDeployment($host))->plan($host.'/packages/internal-requisitions', $current['manifest_sha256']); (new CodeDeployment($host))->plan($host.'/packages/internal-requisitions', $current['manifest_sha256']);
$plan = ['target_sha256' => Installation::target($db), 'manifest_sha256' => $manifestHash, 'schema_changes' => Schema::TABLES, 'new_rights' => Schema::RIGHTS, 'grant_performed' => false, 'activated' => false]; $plan = ['target_sha256' => Installation::target($db), 'manifest_sha256' => $manifestHash, 'schema_changes' => Schema::TABLES, 'new_rights' => Schema::RIGHTS, 'grant_performed' => false, 'activated' => false];
if($action==='plan'){echo json_encode($plan,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);exit;} if ($action === 'plan') {
$backup=$argv[4]??'';$backupHash=$argv[5]??'';$operator=$argv[6]??''; echo json_encode($plan, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
if(!hash_equals($plan['target_sha256'],$argv[3]??'')||!hash_equals($manifestHash,$argv[7]??'')||!is_file($backup)||!hash_equals($backupHash,hash_file('sha256',$backup))||trim($operator)===''||!is_file($host.'/storage/framework/down'))throw new RuntimeException('Target, manifest, backup, operator and maintenance are required'); exit;
}
$backup = $argv[4] ?? '';
$backupHash = $argv[5] ?? '';
$operator = $argv[6] ?? '';
if (! hash_equals($plan['target_sha256'], $argv[3] ?? '') || ! hash_equals($manifestHash, $argv[7] ?? '') || ! is_file($backup) || ! hash_equals($backupHash, hash_file('sha256', $backup)) || trim($operator) === '' || ! is_file($host.'/storage/framework/down')) {
throw new RuntimeException('Target, manifest, backup, operator and maintenance are required');
}
(new Process([getenv('PG_RESTORE_BINARY') ?: 'pg_restore', '--list', $backup], null, null, null, 60))->mustRun(); (new Process([getenv('PG_RESTORE_BINARY') ?: 'pg_restore', '--list', $backup], null, null, null, 60))->mustRun();
$result = Schema::migrate($db, $backupHash, $operator); $result = Schema::migrate($db, $backupHash, $operator);
$old = json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'), true, 64, JSON_THROW_ON_ERROR); $old = json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'), true, 64, JSON_THROW_ON_ERROR);
$receipt = ['host' => $host, 'from_manifest_sha256' => $current['manifest_sha256'], 'to_manifest_sha256' => $manifestHash, 'schema_verified' => Schema::compatible($db), 'changes' => []]; $receipt = ['host' => $host, 'from_manifest_sha256' => $current['manifest_sha256'], 'to_manifest_sha256' => $manifestHash, 'schema_verified' => Schema::compatible($db), 'changes' => []];
foreach($manifest['support_files'] as $file=>$hash)if(($old['support_files'][$file]??null)!==$hash)$receipt['changes'][$file]=['before'=>$old['support_files'][$file]??null,'after'=>$hash]; foreach ($manifest['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/app/private/module-deployments/schema-transition-'.$manifestHash.'.json', json_encode($receipt, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)); file_put_contents($host.'/storage/app/private/module-deployments/schema-transition-'.$manifestHash.'.json', json_encode($receipt, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($result + ['activated' => false, 'rights_granted' => false], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR); echo json_encode($result + ['activated' => false, 'rights_granted' => false], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
}catch(Throwable $e){fwrite(STDERR,$e->getMessage()."\n");exit(1);} } catch (Throwable $e) {
fwrite(STDERR,$e->getMessage()."\n");
exit(1);
}
+438 -44
View File
@@ -1,54 +1,448 @@
import fs from 'node:fs';import path from 'node:path';import crypto from 'node:crypto';import {spawnSync,spawn} from 'node:child_process';import net from 'node:net'; import fs from 'node:fs';
const repo='C:/laragon/www/compras',parent='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939',source=parent+'/development-app'; import path from 'node:path';
const suffix=crypto.randomBytes(6).toString('hex'),database='sgf_sourcing_test_'+suffix,work=parent+'/private/sourcing-'+suffix,clone=work+'/app'; import crypto from 'node:crypto';
const pg='C:/Program Files/PostgreSQL/17/bin',php='C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';fs.mkdirSync(work,{recursive:true}); import { spawnSync, spawn } from 'node:child_process';
const envText=fs.readFileSync(source+'/.env','utf8');const env=Object.fromEntries([...envText.matchAll(/^([A-Z_]+)=(.*)$/gm)].map(m=>[m[1],m[2].trim().replace(/^['"]|['"]$/g,'')])); import net from 'node:net';
if(env.DB_DATABASE!=='sgf_modules_dev_2576427d1939'||env.DB_PORT!=='55439')throw Error('Wrong demonstration'); const repo = 'C:/laragon/www/compras',
parent = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939',
source = parent + '/development-app';
const suffix = crypto.randomBytes(6).toString('hex'),
database = 'sgf_sourcing_test_' + suffix,
work = parent + '/private/sourcing-' + suffix,
clone = work + '/app';
const pg = 'C:/Program Files/PostgreSQL/17/bin',
php = 'C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';
fs.mkdirSync(work, { recursive: true });
const envText = fs.readFileSync(source + '/.env', 'utf8');
const env = Object.fromEntries(
[...envText.matchAll(/^([A-Z_]+)=(.*)$/gm)].map((m) => [
m[1],
m[2].trim().replace(/^['"]|['"]$/g, ''),
]),
);
if (
env.DB_DATABASE !== 'sgf_modules_dev_2576427d1939' ||
env.DB_PORT !== '55439'
)
throw Error('Wrong demonstration');
const admin = fs.readFileSync(parent + '/private/admin-password.txt', 'utf8'); const admin = fs.readFileSync(parent + '/private/admin-password.txt', 'utf8');
function run(exe,args,options={}){const r=spawnSync(exe,args,{windowsHide:true,encoding:'utf8',maxBuffer:16*1024*1024,...options});if(r.status!==0)throw Error((r.stdout??'')+(r.stderr??''));return r.stdout;} function run(exe, args, options = {}) {
const adminEnv={...process.env,PGPASSWORD:admin};const qaEnv={...process.env,PGPASSWORD:env.DB_PASSWORD}; const r = spawnSync(exe, args, {
const fingerprintSQL="BEGIN READ ONLY;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM ir_requests t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM cb_budget_entries t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM users t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM permission_grants t;COMMIT;"; windowsHide: true,
const sourceFingerprint=(db=env.DB_DATABASE)=>run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',db,'-At','-v','ON_ERROR_STOP=1','-c',fingerprintSQL],{env:qaEnv}); encoding: 'utf8',
const before=sourceFingerprint();let created=false,server; maxBuffer: 16 * 1024 * 1024,
...options,
});
if (r.status !== 0) throw Error((r.stdout ?? '') + (r.stderr ?? ''));
return r.stdout;
}
const adminEnv = { ...process.env, PGPASSWORD: admin };
const qaEnv = { ...process.env, PGPASSWORD: env.DB_PASSWORD };
const fingerprintSQL =
"BEGIN READ ONLY;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM ir_requests t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM cb_budget_entries t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM users t;SELECT md5(coalesce(jsonb_agg(to_jsonb(t) ORDER BY id)::text,'')) FROM permission_grants t;COMMIT;";
const sourceFingerprint = (db = env.DB_DATABASE) =>
run(
pg + '/psql.exe',
[
'-X',
'-h',
'127.0.0.1',
'-p',
'55439',
'-U',
env.DB_USERNAME,
'-d',
db,
'-At',
'-v',
'ON_ERROR_STOP=1',
'-c',
fingerprintSQL,
],
{ env: qaEnv },
);
const before = sourceFingerprint();
let created = false,
server;
try { try {
const archivedBaseline=parent+'/private/sourcing-recovery/before.dump',useArchivedBaseline=fs.existsSync(archivedBaseline); const archivedBaseline = parent + '/private/sourcing-recovery/before.dump',
if(useArchivedBaseline)fs.copyFileSync(archivedBaseline,work+'/before.dump');else run(pg+'/pg_dump.exe',['-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',env.DB_DATABASE,'-Fc','-f',work+'/before.dump'],{env:qaEnv}); useArchivedBaseline = fs.existsSync(archivedBaseline);
const cluster=run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U','sgf_regression_owner','-d','postgres','-At','-c',"select current_setting('cluster_name')"],{env:adminEnv}).trim();if(cluster!=='sgf_modular_regression_2576427d1939')throw Error('Wrong cluster'); if (useArchivedBaseline)
run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U','sgf_regression_owner','-d','postgres','-v','ON_ERROR_STOP=1','-c',`CREATE DATABASE ${database} OWNER sgf_modules_qa_2576427d1939`],{env:adminEnv});created=true; fs.copyFileSync(archivedBaseline, work + '/before.dump');
run(pg+'/pg_restore.exe',['-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',database,'--no-owner','--no-privileges','--exit-on-error',work+'/before.dump'],{env:qaEnv}); else
run(
pg + '/pg_dump.exe',
[
'-h',
'127.0.0.1',
'-p',
'55439',
'-U',
env.DB_USERNAME,
'-d',
env.DB_DATABASE,
'-Fc',
'-f',
work + '/before.dump',
],
{ env: qaEnv },
);
const cluster = run(
pg + '/psql.exe',
[
'-X',
'-h',
'127.0.0.1',
'-p',
'55439',
'-U',
'sgf_regression_owner',
'-d',
'postgres',
'-At',
'-c',
"select current_setting('cluster_name')",
],
{ env: adminEnv },
).trim();
if (cluster !== 'sgf_modular_regression_2576427d1939')
throw Error('Wrong cluster');
run(
pg + '/psql.exe',
[
'-X',
'-h',
'127.0.0.1',
'-p',
'55439',
'-U',
'sgf_regression_owner',
'-d',
'postgres',
'-v',
'ON_ERROR_STOP=1',
'-c',
`CREATE DATABASE ${database} OWNER sgf_modules_qa_2576427d1939`,
],
{ env: adminEnv },
);
created = true;
run(
pg + '/pg_restore.exe',
[
'-h',
'127.0.0.1',
'-p',
'55439',
'-U',
env.DB_USERNAME,
'-d',
database,
'--no-owner',
'--no-privileges',
'--exit-on-error',
work + '/before.dump',
],
{ env: qaEnv },
);
const copyBaselineFingerprint = sourceFingerprint(database); const copyBaselineFingerprint = sourceFingerprint(database);
fs.mkdirSync(clone, { recursive: true }); fs.mkdirSync(clone, { recursive: true });
for(const dir of ['app','config','routes','bootstrap','scripts','packages','resources','public'])fs.cpSync(source+'/'+dir,clone+'/'+dir,{recursive:true}); for (const dir of [
const guard=clone+'/app/Shared/Testing/TestingDatabaseGuard.php';fs.writeFileSync(guard,fs.readFileSync(guard,'utf8').replaceAll('sgf_modules_dev_2576427d1939',database)); // Exact physical identity adaptation; guards remain enabled. 'app',
for(const file of ['artisan','composer.json','composer.lock'])fs.copyFileSync(source+'/'+file,clone+'/'+file);fs.cpSync(source+'/storage/app/private/module-deployments',clone+'/storage/app/private/module-deployments',{recursive:true}); 'config',
for(const d of ['storage/framework/sessions','storage/framework/views','storage/framework/cache/data','storage/logs'])fs.mkdirSync(clone+'/'+d,{recursive:true}); 'routes',
'bootstrap',
'scripts',
'packages',
'resources',
'public',
])
fs.cpSync(source + '/' + dir, clone + '/' + dir, { recursive: true });
const guard = clone + '/app/Shared/Testing/TestingDatabaseGuard.php';
fs.writeFileSync(
guard,
fs
.readFileSync(guard, 'utf8')
.replaceAll('sgf_modules_dev_2576427d1939', database),
); // Exact physical identity adaptation; guards remain enabled.
for (const file of ['artisan', 'composer.json', 'composer.lock'])
fs.copyFileSync(source + '/' + file, clone + '/' + file);
fs.cpSync(
source + '/storage/app/private/module-deployments',
clone + '/storage/app/private/module-deployments',
{ recursive: true },
);
for (const d of [
'storage/framework/sessions',
'storage/framework/views',
'storage/framework/cache/data',
'storage/logs',
])
fs.mkdirSync(clone + '/' + d, { recursive: true });
fs.cpSync(source + '/vendor', clone + '/vendor', { recursive: true }); // Independent autoloader and dependencies; never mutate the demo vendor. fs.cpSync(source + '/vendor', clone + '/vendor', { recursive: true }); // Independent autoloader and dependencies; never mutate the demo vendor.
for(const dir of fs.readdirSync(clone+'/storage/app/private/module-deployments',{withFileTypes:true})){if(!dir.isDirectory())continue;const file=clone+'/storage/app/private/module-deployments/'+dir.name+'/journal.json';if(fs.existsSync(file)){const j=JSON.parse(fs.readFileSync(file));j.host_identity=crypto.createHash('sha256').update(clone).digest('hex');fs.writeFileSync(file,JSON.stringify(j,null,2));}} for (const dir of fs.readdirSync(
if(useArchivedBaseline){ clone + '/storage/app/private/module-deployments',
const expectedBaseline=JSON.parse(fs.readFileSync(repo+'/docs/proofs/sgf-read-candidate.json','utf8')).archive.manifest_sha256;let hops=0;fs.writeFileSync(clone+'/storage/framework/down','{}'); { withFileTypes: true },
while(true){const current=JSON.parse(fs.readFileSync(clone+'/storage/app/private/module-deployments/current.json','utf8'));if(current.manifest_sha256===expectedBaseline)break;if(++hops>4)throw Error('Unexpected baseline ancestry');const rolled=JSON.parse(run(php,[repo+'/scripts/sgf-code-deploy.php','rollback',clone,current.deployment_id,'Disposable reproduction of pre-sourcing baseline','--offline'],{cwd:clone}));if(rolled.state!=='rolled-back')throw Error('Failed to reproduce prior code');}fs.unlinkSync(clone+'/storage/framework/down'); )) {
if (!dir.isDirectory()) continue;
const file =
clone +
'/storage/app/private/module-deployments/' +
dir.name +
'/journal.json';
if (fs.existsSync(file)) {
const j = JSON.parse(fs.readFileSync(file));
j.host_identity = crypto
.createHash('sha256')
.update(clone)
.digest('hex');
fs.writeFileSync(file, JSON.stringify(j, null, 2));
} }
fs.writeFileSync(clone+'/.env',envText.replace(/^DB_DATABASE=.*$/m,'DB_DATABASE='+database).replace(/^APP_ENV=.*$/m,'APP_ENV=testing').replace(/^APP_DEBUG=.*$/m,'APP_DEBUG=false')); }
const vars={...process.env,SOURCING_CLONE:clone,SOURCING_DB:database,SOURCING_WORK:work,SOURCING_REPO:repo,APP_BASE_PATH:clone}; if (useArchivedBaseline) {
const setup=run(php,[repo+'/tests/Support/sgf-sourcing-copy.php','setup'],{cwd:clone,env:vars}); const expectedBaseline = JSON.parse(
fs.writeFileSync(work+'/setup-output.txt',setup);let receipt;try{receipt=JSON.parse(setup);}catch{throw Error('Setup failed; private diagnostic '+work+'/setup-output.txt');}if(!receipt.passed)throw Error('Setup proof did not pass'); fs.readFileSync(
const listener=net.createServer();await new Promise(r=>listener.listen(0,'127.0.0.1',r));const port=listener.address().port;await new Promise(r=>listener.close(r)); repo + '/docs/proofs/sgf-read-candidate.json',
server=spawn(php,['-S','127.0.0.1:'+port,'-t','public','scripts/router.php'],{cwd:clone,env:vars,windowsHide:true,stdio:['ignore',fs.openSync(work+'/web-out.log','a'),fs.openSync(work+'/web-error.log','a')]}); 'utf8',
await new Promise((resolve,reject)=>{let tries=0;const poll=()=>{const s=net.connect(port,'127.0.0.1');s.once('connect',()=>{s.destroy();resolve();});s.once('error',()=>{s.destroy();if(++tries>50)reject(Error('Test web host unavailable'));else setTimeout(poll,100);});};poll();}); ),
const http=run(process.execPath,[repo+'/tests/Support/sgf-sourcing-http.mjs'],{cwd:repo,env:{...vars,SOURCING_PORT:String(port)}});fs.writeFileSync(work+'/http-output.txt',http); ).archive.manifest_sha256;
const result=JSON.parse(http);if(!result.passed)throw Error('HTTP test failed'); let hops = 0;
server.kill();await new Promise(r=>setTimeout(r,200));server=null; fs.writeFileSync(clone + '/storage/framework/down', '{}');
const recovered=JSON.parse(run(php,[repo+'/tests/Support/sgf-sourcing-copy.php','verify'],{cwd:clone,env:vars})); while (true) {
const current = JSON.parse(
fs.readFileSync(
clone +
'/storage/app/private/module-deployments/current.json',
'utf8',
),
);
if (current.manifest_sha256 === expectedBaseline) break;
if (++hops > 4) throw Error('Unexpected baseline ancestry');
const rolled = JSON.parse(
run(
php,
[
repo + '/scripts/sgf-code-deploy.php',
'rollback',
clone,
current.deployment_id,
'Disposable reproduction of pre-sourcing baseline',
'--offline',
],
{ cwd: clone },
),
);
if (rolled.state !== 'rolled-back')
throw Error('Failed to reproduce prior code');
}
fs.unlinkSync(clone + '/storage/framework/down');
}
fs.writeFileSync(
clone + '/.env',
envText
.replace(/^DB_DATABASE=.*$/m, 'DB_DATABASE=' + database)
.replace(/^APP_ENV=.*$/m, 'APP_ENV=testing')
.replace(/^APP_DEBUG=.*$/m, 'APP_DEBUG=false'),
);
const vars = {
...process.env,
SOURCING_CLONE: clone,
SOURCING_DB: database,
SOURCING_WORK: work,
SOURCING_REPO: repo,
APP_BASE_PATH: clone,
};
const setup = run(
php,
[repo + '/tests/Support/sgf-sourcing-copy.php', 'setup'],
{ cwd: clone, env: vars },
);
fs.writeFileSync(work + '/setup-output.txt', setup);
let receipt;
try {
receipt = JSON.parse(setup);
} catch {
throw Error(
'Setup failed; private diagnostic ' + work + '/setup-output.txt',
);
}
if (!receipt.passed) throw Error('Setup proof did not pass');
const listener = net.createServer();
await new Promise((r) => listener.listen(0, '127.0.0.1', r));
const port = listener.address().port;
await new Promise((r) => listener.close(r));
server = spawn(
php,
['-S', '127.0.0.1:' + port, '-t', 'public', 'scripts/router.php'],
{
cwd: clone,
env: vars,
windowsHide: true,
stdio: [
'ignore',
fs.openSync(work + '/web-out.log', 'a'),
fs.openSync(work + '/web-error.log', 'a'),
],
},
);
await new Promise((resolve, reject) => {
let tries = 0;
const poll = () => {
const s = net.connect(port, '127.0.0.1');
s.once('connect', () => {
s.destroy();
resolve();
});
s.once('error', () => {
s.destroy();
if (++tries > 50) reject(Error('Test web host unavailable'));
else setTimeout(poll, 100);
});
};
poll();
});
const http = run(
process.execPath,
[repo + '/tests/Support/sgf-sourcing-http.mjs'],
{ cwd: repo, env: { ...vars, SOURCING_PORT: String(port) } },
);
fs.writeFileSync(work + '/http-output.txt', http);
const result = JSON.parse(http);
if (!result.passed) throw Error('HTTP test failed');
server.kill();
await new Promise((r) => setTimeout(r, 200));
server = null;
const recovered = JSON.parse(
run(php, [repo + '/tests/Support/sgf-sourcing-copy.php', 'verify'], {
cwd: clone,
env: vars,
}),
);
// Data/schema recovery is separate from the successful code rollback above. // Data/schema recovery is separate from the successful code rollback above.
run(pg+'/pg_dump.exe',['-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',database,'-Fc','-f',work+'/confirmed-before-recovery.dump'],{env:qaEnv}); run(
run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U','sgf_regression_owner','-d','postgres','-v','ON_ERROR_STOP=1','-c',`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid()`,'-c',`DROP DATABASE ${database}`,'-c',`CREATE DATABASE ${database} OWNER sgf_modules_qa_2576427d1939`],{env:adminEnv}); pg + '/pg_dump.exe',
run(pg+'/pg_restore.exe',['-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',database,'--no-owner','--no-privileges','--exit-on-error',work+'/before.dump'],{env:qaEnv}); [
if(sourceFingerprint(database)!==copyBaselineFingerprint)throw Error('Restored source request, reservation, accounts or grants diverged'); '-h',
const schemaRestored=run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U',env.DB_USERNAME,'-d',database,'-At','-c',"SELECT count(*) FROM pg_tables WHERE schemaname='public' AND tablename LIKE 'ss_%'; SELECT count(*) FROM sgc_installations WHERE module='sourcing'"],{env:qaEnv}).trim();if(schemaRestored!=='0\n0'&&schemaRestored!=='0\r\n0')throw Error('Schema recovery diverged'); '127.0.0.1',
recovered.data_schema_restore_verified=true;recovered.pre_recovery_state_archived=true;recovered.restored_requests_reservations_accounts_grants_match=true; '-p',
const proof={passed:true,database,work,setup:receipt,http:result,recovery:recovered,persistent_demo_unchanged:before===sourceFingerprint(),synthetic_copy_only:true,checked_at:new Date().toISOString()};if(!proof.persistent_demo_unchanged)throw Error('Original demo changed'); '55439',
fs.writeFileSync(repo+'/docs/proofs/sgf-sourcing-isolated.json',JSON.stringify(proof,null,2));console.log(JSON.stringify(proof)); '-U',
env.DB_USERNAME,
'-d',
database,
'-Fc',
'-f',
work + '/confirmed-before-recovery.dump',
],
{ env: qaEnv },
);
run(
pg + '/psql.exe',
[
'-X',
'-h',
'127.0.0.1',
'-p',
'55439',
'-U',
'sgf_regression_owner',
'-d',
'postgres',
'-v',
'ON_ERROR_STOP=1',
'-c',
`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid()`,
'-c',
`DROP DATABASE ${database}`,
'-c',
`CREATE DATABASE ${database} OWNER sgf_modules_qa_2576427d1939`,
],
{ env: adminEnv },
);
run(
pg + '/pg_restore.exe',
[
'-h',
'127.0.0.1',
'-p',
'55439',
'-U',
env.DB_USERNAME,
'-d',
database,
'--no-owner',
'--no-privileges',
'--exit-on-error',
work + '/before.dump',
],
{ env: qaEnv },
);
if (sourceFingerprint(database) !== copyBaselineFingerprint)
throw Error(
'Restored source request, reservation, accounts or grants diverged',
);
const schemaRestored = run(
pg + '/psql.exe',
[
'-X',
'-h',
'127.0.0.1',
'-p',
'55439',
'-U',
env.DB_USERNAME,
'-d',
database,
'-At',
'-c',
"SELECT count(*) FROM pg_tables WHERE schemaname='public' AND tablename LIKE 'ss_%'; SELECT count(*) FROM sgc_installations WHERE module='sourcing'",
],
{ env: qaEnv },
).trim();
if (schemaRestored !== '0\n0' && schemaRestored !== '0\r\n0')
throw Error('Schema recovery diverged');
recovered.data_schema_restore_verified = true;
recovered.pre_recovery_state_archived = true;
recovered.restored_requests_reservations_accounts_grants_match = true;
const proof = {
passed: true,
database,
work,
setup: receipt,
http: result,
recovery: recovered,
persistent_demo_unchanged: before === sourceFingerprint(),
synthetic_copy_only: true,
checked_at: new Date().toISOString(),
};
if (!proof.persistent_demo_unchanged) throw Error('Original demo changed');
fs.writeFileSync(
repo + '/docs/proofs/sgf-sourcing-isolated.json',
JSON.stringify(proof, null, 2),
);
console.log(JSON.stringify(proof));
} finally { } finally {
if (server) server.kill(); if (server) server.kill();
if(created)run(pg+'/psql.exe',['-X','-h','127.0.0.1','-p','55439','-U','sgf_regression_owner','-d','postgres','-v','ON_ERROR_STOP=1','-c',`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid()`,'-c',`DROP DATABASE ${database}`],{env:adminEnv}); if (created)
run(
pg + '/psql.exe',
[
'-X',
'-h',
'127.0.0.1',
'-p',
'55439',
'-U',
'sgf_regression_owner',
'-d',
'postgres',
'-v',
'ON_ERROR_STOP=1',
'-c',
`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname='${database}' AND pid<>pg_backend_pid()`,
'-c',
`DROP DATABASE ${database}`,
],
{ env: adminEnv },
);
} }

Some files were not shown because too many files have changed in this diff Show More