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,49 +5,60 @@ namespace App\Http\Controllers;
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\OrganizationAccess;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tempo\Inventory\InventoryReadSession;
final class CommonStockReadController extends Controller
{
public function index(Request $request): JsonResponse
{
// Native authority, reloaded on every request; no SGF grants or identity assumptions.
$user=User::query()->findOrFail($this->staffIdentity($request)->id);
abort_unless($user->tenant_id!==null && $user->hasFunctions([PurchasingRole::Admin,PurchasingRole::Warehouse,PurchasingRole::Procurement,PurchasingRole::Finance])
&& !app(OrganizationAccess::class)->maintenanceOnly($user),403);
$d=$request->validate(['view'=>'sometimes|in:items,warehouses,balances,movements','search'=>'nullable|string|max:100',
'warehouse_id'=>'sometimes|integer|min:1','page'=>'sometimes|integer|min:1|max:100000','per_page'=>'sometimes|integer|min:1|max:100','snapshot'=>'sometimes|string|max:8192']);
abort_if(array_diff(array_keys($request->query()),array_keys($d))!==[],422);
$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)];
$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');
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");
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D',$identity->name,$m)
&& $identity->role==='stock_read_qa_'.$m[1] && (int)$identity->port===55439
&& preg_match('/^[a-f0-9]{12}$/D',(string)config('stock_read.qa_run'))
&& $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
&& ($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);
$root=base_path('packages/inventory-read/releases/0.1.0');
$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.');
$manifest=json_decode($bytes,true,512,JSON_THROW_ON_ERROR);
foreach(['bootstrap.php','src/InventoryReader.php','src/InventoryReadSession.php'] as $file) {
$actual=is_file($root.'/'.$file)?hash_file('sha256',$root.'/'.$file):false;
abort_unless(is_string($actual)&&isset($manifest['files'][$file])&&hash_equals($manifest['files'][$file],$actual),503,'Pacote de consulta incompatível.');
$user = User::query()->findOrFail($this->staffIdentity($request)->id);
abort_unless($user->tenant_id !== null && $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance])
&& ! app(OrganizationAccess::class)->maintenanceOnly($user), 403);
$d = $request->validate(['view' => 'sometimes|in:items,warehouses,balances,movements', 'search' => 'nullable|string|max:100',
'warehouse_id' => 'sometimes|integer|min:1', 'page' => 'sometimes|integer|min:1|max:100000', 'per_page' => 'sometimes|integer|min:1|max:100', 'snapshot' => 'sometimes|string|max:8192']);
abort_if(array_diff(array_keys($request->query()), array_keys($d)) !== [], 422);
$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)];
$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');
}
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");
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D', $identity->name, $m)
&& $identity->role === 'stock_read_qa_'.$m[1] && (int) $identity->port === 55439
&& preg_match('/^[a-f0-9]{12}$/D', (string) config('stock_read.qa_run'))
&& $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
&& ($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);
}
$root = base_path('packages/inventory-read/releases/0.1.0');
$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.');
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
foreach (['bootstrap.php', 'src/InventoryReader.php', 'src/InventoryReadSession.php'] as $file) {
$actual = is_file($root.'/'.$file) ? hash_file('sha256', $root.'/'.$file) : false;
abort_unless(is_string($actual) && isset($manifest['files'][$file]) && hash_equals($manifest['files'][$file], $actual), 503, 'Pacote de consulta incompatível.');
}
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));
try { $result=(new \Tempo\Inventory\InventoryReadSession(DB::connection()))->read($binding,$fingerprint,$filters,$d['snapshot']??null); }
catch(\Illuminate\Database\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');
$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 InventoryReadSession(DB::connection()))->read($binding, $fingerprint, $filters, $d['snapshot'] ?? null);
} 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($result)->header('Cache-Control','no-store');
}
}
@@ -43,14 +43,21 @@ final class WarehouseReturnController extends Controller
}
/** @param callable():array<string,mixed> $run */
private function response(callable $run,bool $readOnly=false): JsonResponse
private function response(callable $run, bool $readOnly = false): JsonResponse
{
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');
} catch (QueryException $e) {
if (($e->errorInfo[0] ?? null) === '55P03') {
return response()->json(['code'=>'warehouse_return_busy','message' => 'Devolução ocupada. Aguarde e repita manualmente a conferência.'], 423)->header('Cache-Control', 'no-store');
return response()->json(['code' => 'warehouse_return_busy', 'message' => 'Devolução ocupada. Aguarde e repita manualmente a conferência.'], 423)->header('Cache-Control', 'no-store');
}
throw $e;
}
@@ -83,12 +90,25 @@ final class WarehouseReturnController extends Controller
$d['version'] = (int) $d['version'];
$d['received_in_warehouse'] = true;
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');}
private function close(Request $r,int $id,WarehouseReturns $flow,string $state): JsonResponse
public function withdraw(Request $r, int $id, WarehouseReturns $flow): 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));
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
{
$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 Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
/**
* @property array<string,mixed> $data
* @property array<string,mixed> $snapshot
* @property int $version
* @property string $record_key
* @property \Illuminate\Support\Carbon $created_at
* @property Carbon $created_at
*/
class SupplyRecord extends Model
{
-1
View File
@@ -13,7 +13,6 @@ use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Tempo\Finance\GeneralLedger\LedgerSchema;
use Tempo\Finance\GeneralLedger\Receivables;
use Tempo\Finance\GeneralLedger\ReceivablesSchema;
/** Native actor/catalogue adapter. All customer financial writes belong to the common core. */
final class CustomerSales
+4 -4
View File
@@ -288,7 +288,7 @@ final class SgfInvoiceDispatches
$state = $this->state($row);
$out = $this->summary($row);
return array_replace($out,['connection_id' => $row->connection_id, 'mapping_id' => $row->mapping_id, 'document' => json_decode($row->document,true), 'reason' => $row->reason,
return array_replace($out, ['connection_id' => $row->connection_id, 'mapping_id' => $row->mapping_id, 'document' => json_decode($row->document, true), 'reason' => $row->reason,
'impact' => $state['impact'] ?? null, 'approval_hash' => $row->phase === 'previewed' ? ($state['approval_hash'] ?? null) : null,
'lease_until' => $row->lease_until]);
}
@@ -299,14 +299,14 @@ final class SgfInvoiceDispatches
if (! is_array($x)) {
return $x;
}if (! array_is_list($x)) {
ksort($x,SORT_STRING);
ksort($x, SORT_STRING);
}foreach ($x as &$item) {
$item = $normalise($item);
}
return $x;
return $x;
};
return hash('sha256',json_encode($normalise($v),JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
return hash('sha256', json_encode($normalise($v), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
}
}
+45 -28
View File
@@ -5,39 +5,56 @@ namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\Http;
use LogicException;
use Tempo\SgcInvoiceClient\InvoiceClient;
/** Prepared gateway only; no event listener, route, scheduled job or automatic transmission. */
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.');
$all=config('sgf_invoice.connections',[]);$c=$all[$connection]??null;
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);
abort_unless(($c['source_scope']['tenant_id']??null)===$current->tenant_id&&$current->hasFunctions(['finance'])
&&!app(OrganizationAccess::class)->maintenanceOnly($current),403);
$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;
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.');
if(class_exists(\Tempo\SgcInvoiceClient\InvoiceClient::class,false)){
$loaded=(new \ReflectionClass(\Tempo\SgcInvoiceClient\InvoiceClient::class))->getFileName();
$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.');
}else require_once $path;
$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'],
function(string $method,string $url,array $headers,?array $body)use($actor,$connection,$configurationHash):array{
if (config('sgf_invoice.enabled') !== true) {
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);
$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'])
&& ! app(OrganizationAccess::class)->maintenanceOnly($current), 403);
$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;
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.');
}
if (class_exists(InvoiceClient::class, false)) {
$loaded = (new \ReflectionClass(InvoiceClient::class))->getFileName();
$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.');
}
} else {
require_once $path;
}
$configurationHash = hash('sha256', json_encode($c, JSON_THROW_ON_ERROR));
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 {
// Recheck the originating person's authority immediately before every network operation.
$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)))
||auth()->id()!==$actor->id)return ['status'=>403,'json'=>null];
$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];
$http=Http::withHeaders($headers)->acceptJson()->asJson()->withoutRedirecting()->connectTimeout(3)->timeout(15);
$response=$method==='GET'?$http->get($url):$http->post($url,$body);
return ['status'=>$response->status(),'json'=>$response->json()];
},$c['origin']);
$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)))
|| auth()->id() !== $actor->id) {
return ['status' => 403, 'json' => null];
}
$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];
}
$http = Http::withHeaders($headers)->acceptJson()->asJson()->withoutRedirecting()->connectTimeout(3)->timeout(15);
$response = $method === 'GET' ? $http->get($url) : $http->post($url, $body);
return ['status' => $response->status(), 'json' => $response->json()];
}, $c['origin']);
}
}
+21 -10
View File
@@ -1,24 +1,35 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Tempo\Inventory\IssueMovementWriter;
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');
$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.');
$m=json_decode($bytes,true,512,JSON_THROW_ON_ERROR);
foreach(['bootstrap.php','src/IssueMovementWriter.php'] as $f) {
$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.');
$root = base_path('packages/inventory-issue/releases/0.1.0');
$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.');
}
$m = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
foreach (['bootstrap.php', 'src/IssueMovementWriter.php'] as $f) {
$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.');
}
}
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.')};
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]);});
$schema = match (DB::connection()->getDriverName()) {
'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]);
});
}
}
+2 -1
View File
@@ -8,7 +8,8 @@ use Tempo\Inventory\DeliveryReturnWriter;
final class WarehouseReturnMovement
{
public const MANIFEST_SHA256='2850a4f5cb678acfe3a9dbc7a7d62eb233bc72722ad0de374681c2679c90557c';
public const MANIFEST_SHA256 = '2850a4f5cb678acfe3a9dbc7a7d62eb233bc72722ad0de374681c2679c90557c';
private function fileHash(string $file): string
{
$hash = is_file($file) ? hash_file('sha256', $file) : false;
+32 -20
View File
@@ -46,9 +46,9 @@ final class WarehouseReturns
private function lock(User $actor, string $action): User
{
$timeout=config('stock_returns.lock_timeout_ms',2000);
abort_unless(is_int($timeout)&&$timeout>=100&&$timeout<=10000,503,'Tempo de espera de conferência inválido.');
DB::select("SELECT set_config('lock_timeout',?,true)",[$timeout.'ms']);
$timeout = config('stock_returns.lock_timeout_ms', 2000);
abort_unless(is_int($timeout) && $timeout >= 100 && $timeout <= 10000, 503, 'Tempo de espera de conferência inválido.');
DB::select("SELECT set_config('lock_timeout',?,true)", [$timeout.'ms']);
app(ConflictGuard::class)->lockCompany($actor);
$fresh = app(CurrentActor::class)->lock($actor);
@@ -111,7 +111,7 @@ final class WarehouseReturns
}
}
return null;
return null;
}
/**
@@ -172,15 +172,16 @@ return null;
abort_unless($old->created_by === $actor->id && hash_equals($old->input_hash, $hash), 409, 'Chave utilizada com outros dados.');
$this->request($old->snapshot['source']['request_id']);
$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];
$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];
}
$source = $this->source($actor, $d);
abort_unless($source['requester_id'] === $actor->id, 403, 'A declaração de excedente pertence ao destinatário original.');
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'warehouse_return', 'record_key' => $d['operation_key'], 'version' => 1, 'state' => 'prepared', 'stock_item_id' => $source['item']['id'], 'warehouse_id' => $source['warehouse']['id'], 'created_by' => $actor->id, 'data' => $d, 'snapshot' => ['source' => $source, 'source_hash' => $this->hash($source), 'declared_unused' => true], 'reason' => $d['reason'], 'operation_key' => $d['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'warehouse_return.prepared', null, null, ['record_id' => $record->id, 'request_id' => $source['request_id'], 'impact' => $this->impact($source), 'declared_unused' => true]);
return ['id' => $record->id, 'state'=>'prepared', 'impact' => $this->impact($source), 'replayed' => false];
return ['id' => $record->id, 'state' => 'prepared', 'impact' => $this->impact($source), 'replayed' => false];
});
}
@@ -199,7 +200,8 @@ return null;
abort_if($p->created_by === $actor->id, 403, 'Recepção deve ser independente da declaração.');
$done = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $p->record_key)->where('version', 2)->first();
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];
}
abort_unless($d['version'] === 1 && $d['received_in_warehouse'] === true, 422, 'Confirme a recepção física da versão conferida.');
@@ -221,19 +223,29 @@ return null;
* @param array<string,mixed> $d
* @return array<string,mixed>
*/
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);
$action=$state==='withdrawn'?'prepare':'confirm';$this->authorize($actor,$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']);
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();
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];}
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()]);
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];
abort_unless(in_array($state, ['withdrawn', 'rejected'], true), 422);
$action = $state === 'withdrawn' ? 'prepare' : 'confirm';
$this->authorize($actor, $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']);
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();
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];
}
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()]);
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];
});
}
+1
View File
@@ -1,4 +1,5 @@
<?php
return [
'synthetic_sources' => [],
'qa_run' => env('SGF_ISOLATED_REGRESSION_RUN'),
@@ -2,45 +2,81 @@
use Illuminate\Database\Migrations\Migration;
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 {
public function up():void
return new class extends Migration
{
public function up(): void
{
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){
$t->id();$t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete();
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) {
$t->id();
$t->foreignId('tenant_id')->constrained('tenants')->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->json('mapping_snapshot');$t->char('mapping_hash',64);$t->json('document');$t->text('reason');
$t->unsignedInteger('source_version')->default(1);$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']);
$t->string('reference', 120);
$t->string('number', 100);
$t->string('connection_id', 64);
$t->string('mapping_id', 64);
$t->json('mapping_snapshot');
$t->char('mapping_hash', 64);
$t->json('document');
$t->text('reason');
$t->unsignedInteger('source_version')->default(1);
$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){
$t->id();$t->foreignId('dispatch_id')->constrained('sgf_invoice_dispatches')->restrictOnDelete();
$t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete();$t->unsignedInteger('version');
$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']);
Schema::create('sgf_invoice_dispatch_events', function (Blueprint $t) {
$t->id();
$t->foreignId('dispatch_id')->constrained('sgf_invoice_dispatches')->restrictOnDelete();
$t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete();
$t->unsignedInteger('version');
$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 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()');
}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");
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.');
} 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");
}
public function down():void
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
{
Schema::dropIfExists('sgf_invoice_dispatch_events');Schema::dropIfExists('sgf_invoice_dispatches');
if(DB::getDriverName()==='pgsql')DB::unprepared('DROP FUNCTION IF EXISTS sgf_dispatch_preserve()');
Schema::dropIfExists('sgf_invoice_dispatch_events');
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",
"exclude": ["packages"]
"exclude": ["packages", "integrations"]
}
+2 -1
View File
@@ -117,7 +117,8 @@ export default function Clients({
const data = new FormData(event.currentTarget);
const search = data.get('search');
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 { 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 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 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'};
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 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 }) {
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> {
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;
async function api<T>(
url: string,
body?: object,
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 }) {
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(); };
export default function WarehouseReturns({
requestId,
actorId,
canPrepare,
canConfirm,
canWithdraw = false,
}: {
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]);
useEffect(() => { setPreview(null); command.current = null; setPage(1); setSourcePage(1); }, [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; }
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);
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); } } catch (err) { if (n === generation.current) setError((err as Error).message); } finally { setBusy(false); }
useEffect(() => {
setPreview(null);
command.current = null;
setPage(1);
setSourcePage(1);
}, [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));
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); }
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);
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);}}
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></>;
} catch (err) {
if (n === generation.current) setError((err as Error).message);
} finally {
setBusy(false);
}
}
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));
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 assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 routes=[];
for(const [role,expected] of [['admin',200],['procurement',403],['finance',403]]) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 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'});
@@ -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));
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 assert from 'node:assert/strict';
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 source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[];
for(const role of ['admin','procurement','finance','warehouse']) {
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));
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 assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','warehouse']) {
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));
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 assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', '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 = {})')
const source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'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,');
assert.ok(common.includes('extraHeaders = {}'));
await new Function('fs','assert','return (async()=>{'+common+`
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const records=[];
for(const role of ['admin','procurement','finance','warehouse']) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 routes = [];
for (const role of ['procurement', 'department_head', 'finance']) {
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.'
}, null, 2));
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 assert from 'node:assert/strict';
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 source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[];
for(const role of ['admin','procurement','finance','warehouse']) {
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));
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';
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');
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 + `
assert.equal(
installation.status,
'installed_and_capability_enabled_no_business_operations',
);
const source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[];
for(const role of ['requester','admin','procurement','finance']) {
const viewer=client(); await viewer.enter(role);
@@ -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));
console.log(JSON.stringify({http_checks:results.length,result:'passed',business_commands:false}));
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+98 -23
View File
@@ -6,43 +6,118 @@ import assert from 'node:assert/strict';
const frontend = process.argv[2];
assert.ok(frontend, 'Provide the verified frontend build directory.');
const roots = ['app', '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 roots = [
'app',
'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 tracked = execFileSync(listed[0], [...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 tracked = execFileSync(
listed[0],
[...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 exact = [];
for (const file of [...new Set([...tracked, ...added])].filter(Boolean).sort()) {
if (file.startsWith('bootstrap/cache/') || file.startsWith('public/build/')) continue;
for (const file of [...new Set([...tracked, ...added])]
.filter(Boolean)
.sort()) {
if (file.startsWith('bootstrap/cache/') || file.startsWith('public/build/'))
continue;
const info = await fs.lstat(file);
if (!info.isFile() || info.isSymbolicLink()) continue;
const bytes = await fs.readFile(file);
const pinned = file.startsWith('packages/budget-control/') || file.startsWith('packages/payables/')
|| file === 'resources/data/geography/cartografia-moz.json' || bytes.includes(0);
const pinned =
file.startsWith('packages/budget-control/') ||
file.startsWith('packages/payables/') ||
file === 'resources/data/geography/cartografia-moz.json' ||
bytes.includes(0);
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 build = JSON.parse(buildBytes);
const assets = {};
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('..'));
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,
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'))) },
const manifest = {
contract: 'compras.release.v1',
product: 'compras',
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: [
{ setting: 'COMPRAS_RUNTIME_ROOT', 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);
await fs.writeFile('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 }));
{
setting: 'COMPRAS_RUNTIME_ROOT',
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);
await fs.writeFile(
'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,
}),
);
@@ -52,7 +52,7 @@ foreach ($runtime + $verification as $file => $expected) {
throw new RuntimeException('Candidata imutável divergente.');
}
continue;
continue;
}
if (! is_dir(dirname($target))) {
mkdir(dirname($target), 0700, true);
@@ -94,5 +94,5 @@ if (! $rejected) {
throw new RuntimeException('A candidata não deve ser instalável pelo updater de código.');
}
$result = ['candidate_id' => $id, 'directory' => $destination, 'manifest_sha256' => hash('sha256', $manifestText), 'archives' => $archives, 'standard_updater_refuses_candidate' => true, 'activation_performed' => false];
file_put_contents($root.'/docs/proofs/internal-requisitions-candidate.json', json_encode($result,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
echo json_encode($result,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";
file_put_contents($root.'/docs/proofs/internal-requisitions-candidate.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)."\n";
+20 -5
View File
@@ -1,12 +1,27 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
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 source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
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 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);
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 viewer=client(); await viewer.enter('admin');
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);
@@ -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); } }
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.');
`+'})()')(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 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(new URL(entry.headers.get('location'), base).pathname, '/login');
const queue = Object.entries(release.frontend.files);
let checked = 0;
await Promise.all(Array.from({ length: 4 }, async () => {
await Promise.all(
Array.from({ length: 4 }, async () => {
for (;;) {
const entry = queue.shift();
if (!entry) return;
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(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++;
}
}));
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);
const html = await response.text();
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);
const page = JSON.parse(bootstrap[1]);
assert.equal(page.component, component);
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,
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');
const proof = {
state: 'passed',
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));
+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 queue = Object.entries(proof.files);
let checked = 0;
await Promise.all(Array.from({ length: 4 }, async () => {
await Promise.all(
Array.from({ length: 4 }, async () => {
for (;;) {
const entry = queue.shift();
if (!entry) return;
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(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++;
}
}));
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');
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);
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('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');
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 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;
try {
const result = JSON.parse(await fs.readFile('docs/proofs/analytics-print-publication.json', 'utf8'));
const bytes = await fs.readFile('docs/proofs/analytics-print-publication-proposal.json');
const result = JSON.parse(
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 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(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(proposal.previous_manifest_sha256, plan.frontend.manifest_sha256);
assert.equal(
proposal.previous_manifest_sha256,
plan.frontend.manifest_sha256,
);
plan = { ...plan, frontend: proposal };
interfaceDelta = true;
} catch (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(plan.target, 'http://127.0.0.1:8005');
let verified = 0;
const queue = Object.entries(plan.frontend.files);
await Promise.all(Array.from({ length: 3 }, async () => {
await Promise.all(
Array.from({ length: 3 }, async () => {
for (;;) {
const entry = queue.shift();
if (!entry) return;
const [file, hash] = entry;
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(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++;
}
}));
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);
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');
const page = JSON.parse(bootstrap[1]);
assert.equal(page.props.auth.user, null);
assert.deepEqual(page.props.commonFinanceNavigation, { payments: false, ledger: false, configuration: false });
const manifest = JSON.parse(await fs.readFile('public/build/manifest.json', 'utf8'));
assert.deepEqual(page.props.commonFinanceNavigation, {
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 proof = { date: new Date().toISOString(), state: publicCurrent ? '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');
const proof = {
date: new Date().toISOString(),
state: publicCurrent
? '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));
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';
// 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 common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
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 = [];
for (const role of ['admin', 'procurement', 'finance']) {
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));
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
use App\Services\StandaloneRuntime;
use App\Services\WorkContext;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Schema;
$root = dirname(__DIR__);
require $root.'/vendor/autoload.php';
@@ -55,9 +57,9 @@ $collectFlags(config()->all());
ksort($flags);
echo json_encode(['state' => 'passed', 'runtime_enabled' => $runtime->enabled(), 'features' => $features,
'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())),
'routes' => $routes, 'component_flags' => $components, 'company_context_policies' => $tenants,
'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;
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','warehouse','procurement','finance']) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[];
for(const role of ['admin','procurement','finance','warehouse']) {
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));
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 assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','warehouse']) {
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));
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 assert from 'node:assert/strict';
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','outputFile','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',
'outputFile',
'return (async()=>{' +
common +
`
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'];
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));
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 assert from 'node:assert/strict';
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 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 routes = [];
for (const role of ['admin', 'finance']) {
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.'
}, null, 2));
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 assert from 'node:assert/strict';
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 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 routes = [];
for (const role of ['procurement', 'finance', 'department_head']) {
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.'
}, null, 2));
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 assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','procurement','finance']) {
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));
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 assert from 'node:assert/strict';
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 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 records=[];
const admin=client(); await admin.enter('admin');
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});
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','procurement','finance']) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 routes=[];
for (const [role, expected] of [['admin',200],['procurement',403],['finance',403]]) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 viewer = client();
await viewer.enter('admin');
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
}, null, 2));
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 assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',200],['procurement',403],['finance',403]]) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+130 -32
View File
@@ -1,19 +1,37 @@
// Native Fortify, CSRF and Inertia protocol for owned loopback QA only.
export function createNativeInertiaClient(origin, check) {
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();
let version = '';
const request = async (route, options = {}) => {
if (!route.startsWith('/') || new URL(route, base).origin !== base.origin) 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,
} });
if (
!route.startsWith('/') ||
new URL(route, base).origin !== base.origin
)
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()) {
const pair = header.split(';', 1)[0];
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 closed PHP socket can leave Undici paused, retaining a readable clone.
@@ -21,55 +39,135 @@ export function createNativeInertiaClient(origin, check) {
await response.arrayBuffer();
return buffered;
};
const csrf = () => ({ 'X-XSRF-TOKEN': decodeURIComponent(cookies.get('XSRF-TOKEN') ?? '') });
const login = async email => {
const initial = await request('/login', { headers: { Accept: 'text/html' } });
const csrf = () => ({
'X-XSRF-TOKEN': decodeURIComponent(cookies.get('XSRF-TOKEN') ?? ''),
});
const login = async (email) => {
const initial = await request('/login', {
headers: { Accept: 'text/html' },
});
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');
version = JSON.parse(initialPage[1]).version;
check(typeof version === 'string' && version.length > 0, '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(
typeof version === 'string' && version.length > 0,
'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');
const response = await request('/login', { method: 'POST', headers: { 'Content-Type': 'application/json', ...csrf() }, body: payload });
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 response = await request('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...csrf() },
body: payload,
});
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();
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 response = await request(route, { headers: { 'X-Inertia': 'true' } });
const response = await request(route, {
headers: { 'X-Inertia': 'true' },
});
let error = '';
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();
check(page.component === component, `${component} component`);
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;
};
const logout = async () => {
check([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');
check(
[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 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];
let detail = '';
if (!allowed.includes(response.status)) {
try {
const error = await response.clone().json();
detail = String(error.message ?? '').slice(0, 180) + ' fields=' + Object.keys(error.errors ?? {}).join(',');
} catch { /* status is still diagnostic */ }
detail =
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 { 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.
export function purchasingHomeOverlay(source) {
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);
};
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) {
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);");
} 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.');
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);",
);
} 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"')) {
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"')) {
once('<div className="actions">', '<div className="actions">{budget&&<a href="/purchasing/internal-requisitions/budget-setup">Preparação de centros e dotações</a>}');
if (
!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;
}
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+34 -5
View File
@@ -147,12 +147,41 @@ assert.equal(
configuredMulti.some((e) => e.id === 'new_request'),
true,
);
const capitalReaders = ['admin', 'procurement', 'finance', 'department_head', 'warehouse'];
assert.ok(routes.some((route) => route.uri === 'projectos-imobilizado' && route.method.split('|').includes('GET')));
const capitalReaders = [
'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']) {
const groups = procurementNavigation([role], 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 groups = procurementNavigation(
[role],
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 = {
checked_at: new Date().toISOString(),
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','warehouse']) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','warehouse']) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['procurement',200],['finance',200],['warehouse',403]]) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','warehouse','procurement','finance']) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','warehouse','procurement','finance']) {
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));
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';
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 result = spawnSync('php', ['scripts/check-standalone-pilot-profiles.php', '--read-only'], {
cwd: root, stdio: 'inherit', windowsHide: true,
});
const result = spawnSync(
'php',
['scripts/check-standalone-pilot-profiles.php', '--read-only'],
{
cwd: root,
stdio: 'inherit',
windowsHide: true,
},
);
if (result.error) throw result.error;
process.exitCode = result.status ?? 1;
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 viewer = client();
await viewer.enter('admin');
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));
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));
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+5 -3
View File
@@ -12,8 +12,9 @@ foreach ($settings as $key => $value) {
}
require getcwd().'/vendor/autoload.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\PurchaseOrder;
use App\Models\Supplier;
@@ -21,6 +22,7 @@ use App\Models\User;
use App\Services\ExternalPaymentWorkflow;
use App\Services\SupplierBankWorkflow;
use App\Services\SupplierPayables;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
@@ -147,7 +149,7 @@ if ($job === 'setup') {
} elseif (in_array($job, ['decision_fault', 'decision_confirm', 'decision_inspect'], true)) {
config(['common-payables.history_decisions_enabled' => true]);
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()]));
$original = $frozen();
if ($job === 'decision_fault') {
@@ -192,4 +194,4 @@ if ($job === 'setup') {
} else {
throw new LogicException('Unknown proof job.');
}
echo json_encode($result,JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE).PHP_EOL;
echo json_encode($result, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE).PHP_EOL;
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[];
for(const role of ['admin','procurement','finance']) {
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));
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 assert from 'node:assert/strict';
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 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 viewer=client(); await viewer.enter('admin');
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);
@@ -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));
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 assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
const code = common + `
const source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
const code =
common +
`
const viewer = client(); await viewer.enter('admin');
const dashboard = await viewer.request('/dashboard');
if (dashboard.page?.props.context?.enforced) {
@@ -57,4 +65,7 @@ await fs.writeFile('docs/proofs/people-reports-http.json',JSON.stringify({
},null,2));
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 assert from 'node:assert/strict';
const proposal = JSON.parse(await fs.readFile('docs/proofs/pilot-access-proposal.json', 'utf8'));
const applied = JSON.parse(await fs.readFile('docs/proofs/pilot-access-activation.json', 'utf8'));
const proposal = JSON.parse(
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');
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', 'proposal', 'applied', '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',
'proposal',
'applied',
'return (async()=>{' +
common +
`
const viewer = client();
await viewer.enter('admin');
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));
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 assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['department_head','procurement','requester']) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['procurement','finance','department_head']) {
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));
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 assert from 'node:assert/strict';
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 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 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'});
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'));
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+21 -5
View File
@@ -1,10 +1,24 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
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 source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
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=[];
for(const role of ['procurement','finance','department_head']) {
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,
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.');
` + '})()')(fs, assert, proof);
` +
'})()',
)(fs, assert, proof);
@@ -1,10 +1,27 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
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 + `
const source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
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');
const requester = client(); await requester.enter('requester');
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,
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.');
` + '})()')(fs, assert, proof);
` +
'})()',
)(fs, assert, proof);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['requester','department_head']) {
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,
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.');
` + '})()')(fs, assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['procurement',403],['finance',403]]) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+1 -1
View File
@@ -126,5 +126,5 @@ try {
}
}
$result['restore_database_removed'] = true;
file_put_contents($root.'/docs/proofs/audit-access-preparation.json',json_encode($result,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
file_put_contents($root.'/docs/proofs/audit-access-preparation.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
echo 'Audit access proposal rehearsed only in restored disposable backup; pilot grants unchanged.'.PHP_EOL;
+1 -1
View File
@@ -1,9 +1,9 @@
<?php
use Tempo\Purchasing\Delivery\AccessOverlay;
use Tempo\Purchasing\Delivery\AdminUiOverlay;
use Tempo\Purchasing\Delivery\BootOverlay;
use Tempo\Purchasing\Delivery\BudgetOverlay;
use Tempo\Purchasing\Delivery\AdminUiOverlay;
require dirname(__DIR__).'/integrations/sgf/access/AccessOverlay.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 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 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.DB_HOST, '127.0.0.1');
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');
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 = {
'--product-review': ['ee6e7404da9960181980c10b68b3c84c92d3667c163355442036b3fc0f53ab93', 'sgc-product-review-candidate-20261122', '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'],
'--product-review': [
'ee6e7404da9960181980c10b68b3c84c92d3667c163355442036b3fc0f53ab93',
'sgc-product-review-candidate-20261122',
'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.');
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 proofNames = { 'product-review': 'product-review', 'history-review': 'requisition-history', 'financial-review': 'payable-insights', 'history-clean-review': 'requisition-history-clean', 'rq01-production': 'production-destination' };
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 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');
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 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();
for (const entry of Object.values(manifest)) {
for (const file of [entry.file, ...(entry.css ?? []), ...(entry.assets ?? [])]) {
assert.ok(file.startsWith('assets/') && !file.includes('..') && !path.isAbsolute(file));
for (const file of [
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)));
}
}
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);
for (const [file, expected] of files) {
const target = path.join(root, 'public/build', file);
await fs.mkdir(path.dirname(target), { recursive: true });
try { await fs.copyFile(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.');
try {
await fs.copyFile(
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);
const temporary = path.join(root, 'public/build/manifest.rq01-preview.tmp');
await fs.copyFile(path.join(candidate, 'manifest.json'), temporary);
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 };
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 }));
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,
};
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 assert from 'node:assert/strict';
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 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 routes = [];
for (const role of ['procurement', 'finance', 'department_head']) {
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.'
}, null, 2));
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 assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','warehouse','procurement']) {
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));
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 assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','warehouse','procurement']) {
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));
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 assert from 'node:assert/strict';
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 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 viewer=client(); await viewer.enter('admin');
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);
@@ -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));
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.']);
$repaired++;
}
return ['state' => 'passed', 'generated_profile_labels_repaired' => $repaired, 'permissions_contexts_users_and_credentials_changed' => false];
});
$path = '/root/compras-demo-access.json';
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',403]]) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,8 +1,19 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 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 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'});
@@ -15,4 +26,6 @@ await new Function('fs', 'assert', 'return (async()=>{' + common + `
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));
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 assert from 'node:assert/strict';
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 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 records=[];
for(const role of ['admin','procurement','finance','warehouse']) {
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,
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.');
`+'})()')(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';
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 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'];
for (const name of ['payables', 'general-ledger']) {
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 file of fs.readdirSync(path.join(canonical, name, dir)).sort()) {
if (!/^[A-Za-z0-9_-]+\.php$/.test(file)) throw Error('Unexpected runtime source');
for (const file of fs
.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}`);
}
}
}
const content = sources.map(source => {
const content = sources
.map((source) => {
const actual = path.join(canonical, source);
if (!fs.lstatSync(actual).isFile() || 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));
if (
!fs.lstatSync(actual).isFile() ||
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 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 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)) {
fs.mkdirSync(root);
for (const { file, bytes } of content) {
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
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.
for (const { file, sha256 } of files) {
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 checked = spawnSync('php', ['-r', code, root, pin], { 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 }));
const code =
'require $argv[1]."/Bundle.php"; echo json_encode(Tempo\\Finance\\Composition\\Bundle::verify($argv[1],$argv[2]),JSON_THROW_ON_ERROR);';
const checked = spawnSync('php', ['-r', code, root, pin], {
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';
/** 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);
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;
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 guest = client();
check((await guest.request('/auditoria/eventos')).status === 401, 'anonymous metadata access refused');
check(Array.isArray(assets) && assets.length > 0, 'private candidate assets supplied');
check(
(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) {
const file = await guest.request(`/build/${asset.file}`);
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 auditor = client();
@@ -26,105 +52,360 @@ export async function verifyNativeReviewHttp(origin, fixture, { assets, snapshot
await privateAuditor.login(fixture.synthetic_private_audit_login);
// Login/logout may legitimately rotate native authentication fields. Compare the read window only.
const before = await snapshot();
const privateAudit = await privateAuditor.page('/auditoria/privada', 'audit/private');
check(privateAudit.props.families.length === 4 && privateAudit.props.exports.data.length === 0, 'dedicated private authority opens approved families without generating a package');
for (const actor of [reviewer, auditor, requester]) check((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 privateAudit = await privateAuditor.page(
'/auditoria/privada',
'audit/private',
);
check(
privateAudit.props.families.length === 4 &&
privateAudit.props.exports.data.length === 0,
'dedicated private authority opens approved families without generating a package',
);
for (const actor of [reviewer, auditor, requester])
check(
(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');
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');
check(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');
check(
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]) {
await actor.page('/conflitos', 'conflicts/index');
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);
const response = await reviewer.request(route);
check(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');
check(
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);
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);
check(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');
check(
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');
check(companyConfiguration.props.ready === true && Array.isArray(companyConfiguration.props.profiles) && companyConfiguration.props.profiles.length > 0, 'existing synthetic company configuration remains consultable');
const companyResponse = await reviewer.request('/administracao/parametrizacao');
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');
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');
const companyConfiguration = await reviewer.page(
'/administracao/parametrizacao',
'company/parameters',
);
check(
companyConfiguration.props.ready === true &&
Array.isArray(companyConfiguration.props.profiles) &&
companyConfiguration.props.profiles.length > 0,
'existing synthetic company configuration remains consultable',
);
const companyResponse = await reviewer.request(
'/administracao/parametrizacao',
);
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',
);
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);
for (const [view, component] of [['agreements', 'supply/index'], ['contracts', 'supply/index'], ['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`);
for (const [view, component] of [
['agreements', 'supply/index'],
['contracts', 'supply/index'],
['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');
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');
const operationalControls = await reviewer.page(
'/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');
const ownControls = await requester.page('/revisao-compras', 'purchase-controls/index');
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');
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');
const ownControls = await requester.page(
'/revisao-compras',
'purchase-controls/index',
);
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',
);
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);
check(limited.props.requestContext === null, 'metadata-only actor receives no private process locator');
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 => {
check(
limited.props.requestContext === null,
'metadata-only actor receives no private process locator',
);
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}`);
check(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');
check(
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();
check(body.includes(fixture.audit_request_reference), 'CSV preserves exact criteria');
check(
body.includes(fixture.audit_request_reference),
'CSV preserves exact criteria',
);
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();
check(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'};
check(
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);
const prepared = await privateAuditor.page('/auditoria/privada', 'audit/private');
check(prepared.props.exports.data.length === 1, 'one private package prepared after the unchanged read window');
const prepared = await privateAuditor.page(
'/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 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());
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);
const replay = await privateAuditor.page('/auditoria/privada', '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');
const replay = await privateAuditor.page(
'/auditoria/privada',
'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 auditor.logout();
await requester.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,
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 };
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,
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';
/** 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;
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 commands = 0;
let phase = 'login';
const check = (condition, label) => { if (!condition) throw Error(`Office HTTP verification failed [${phase}]: ${label}`); checks++; };
const stage = name => { phase = name; progress?.({ office_http_phase: name, checks }); };
const check = (condition, label) => {
if (!condition)
throw Error(`Office HTTP verification failed [${phase}]: ${label}`);
checks++;
};
const stage = (name) => {
phase = name;
progress?.({ office_http_phase: name, checks });
};
const clients = {};
for (const [name, actor] of Object.entries(office.actors)) {
clients[name] = createNativeInertiaClient(origin, check);
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 source = await readState();
if (source.budget !== null) {
// 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 budget = page.props.budgets.find(row => Number(row.id) === Number(source.budget.id));
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 budget = page.props.budgets.find(
(row) => Number(row.id) === Number(source.budget.id),
);
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();
check(after.financial_fingerprint === source.financial_fingerprint, 'native balance consultation has no financial effects');
after.budget.balance = Object.fromEntries(fields.map(field => [field, budget[field]]));
check(
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 source;
};
const post = async (client, route, data, expected = 302) => { commands++; 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 post = async (client, route, data, expected = 302) => {
commands++;
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 };
let selectorRefused = false;
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');
check((await owner.request('/orcamentos')).status === 403, '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' });
check(
(await owner.request('/orcamentos')).status === 403,
'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();
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);
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`, {});
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');
await post(owner, '/requisicoes', { operation_key: crypto.randomUUID(), cost_center_id: office.cost_center_id,
priority: 'normal', 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' }] });
await post(owner, '/requisicoes', {
operation_key: crypto.randomUUID(),
cost_center_id: office.cost_center_id,
priority: 'normal',
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();
const requestId = current.request.id;
const lineId = current.request.items[0].id;
let capital = null;
if (office.capital_register) {
await post(buyer, '/projectos-imobilizado', { operation_key: crypto.randomUUID(), record_key: null, version: 0,
type: 'project', code: office.capital_register.code, name: 'Projecto exclusivamente sintético do percurso HTTP',
department_id: office.capital_register.department_id, equipment_id: null, reference: 'Origem documental fictícia de ensaio',
state: 'active', 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');
await post(buyer, '/projectos-imobilizado', {
operation_key: crypto.randomUUID(),
record_key: null,
version: 0,
type: 'project',
code: office.capital_register.code,
name: 'Projecto exclusivamente sintético do percurso HTTP',
department_id: office.capital_register.department_id,
equipment_id: null,
reference: 'Origem documental fictícia de ensaio',
state: 'active',
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];
check(account !== undefined, 'actual common movement account available');
await post(owner, `/requisicoes/${requestId}/contas`, { operation_key: crypto.randomUUID(), 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' }] });
await post(owner, `/requisicoes/${requestId}/contas`, {
operation_key: crypto.randomUUID(),
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();
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);
current = await state();
check(current.request.status === 'pending' && Number(current.budget.balance.reserved_minor) === 10000, 'submission replay preserves one native reserve');
await post(owner, `/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' });
check(
current.request.status === 'pending' &&
Number(current.budget.balance.reserved_minor) === 10000,
'submission replay preserves one native reserve',
);
await post(
owner,
`/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();
}
check(current.request.status === 'approved', 'native request circuit completed');
check(
current.request.status === 'approved',
'native request circuit completed',
);
stage('suppliers_and_quotes');
for (let index = 0; index < 3; index++) {
const nuit = String(300000001 + index);
await post(buyer, '/fornecedores', { name: `Fornecedor HTTP QA ${index + 1}`, nuit, 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) });
await post(buyer, '/fornecedores', {
name: `Fornecedor HTTP QA ${index + 1}`,
nuit,
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();
const supplier = current.suppliers.find(s => s.nuit === nuit);
const supplier = current.suppliers.find((s) => s.nuit === nuit);
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(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' }] });
await post(finance, `/fornecedores/${supplier.id}/validar`, {
version: supplier.version,
status: 'active',
comment:
'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();
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');
for (const evaluator of [head, reviewer]) 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 });
for (const evaluator of [head, reviewer])
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();
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');
await post(buyer, `/requisicoes/${requestId}/adjudicacao`, { quotation_id: current.quotes[0].id,
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' });
await post(buyer, `/requisicoes/${requestId}/adjudicacao`, {
quotation_id: current.quotes[0].id,
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();
const awardId = current.award.id;
for (let level = 0; 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');
for (
let level = 0;
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') {
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();
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;
}
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();
}
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`, {});
current = await state();
const orderId = current.order.id;
@@ -148,147 +396,434 @@ export async function verifyOfficePurchaseHttp(origin, fixture, readState, progr
const issued = current.financial_fingerprint;
await post(buyer, `/adjudicacoes/${awardId}/emitir`, {});
current = await state();
check(current.order.id === orderId && current.financial_fingerprint === issued, 'order replay has no financial or document effect');
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');
check(
current.order.id === orderId &&
current.financial_fingerprint === issued,
'order replay has no financial or document effect',
);
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 financeOrder = await finance.page(`/ordens/${orderId}`, '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 financeOrder = await finance.page(
`/ordens/${orderId}`,
'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 printHeaders = { 'X-Inertia': 'true', ...(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 printHeaders = {
'X-Inertia': 'true',
...(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);
check(printDocument.status === 200 && (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');
check(
printDocument.status === 200 &&
(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');
// This synthetic buyer also has Admin; use the independent Procurement-only reviewer to test redaction.
const independentOrder = await procurementReviewer.page(`/ordens/${orderId}`, 'purchases/show');
check(buyerOrder.props.financialDocumentsHref === financialDocumentsHref && independentOrder.props.financialDocumentsHref === null,
'order financial link follows native Admin/Finance access without Procurement inheritance');
const independentOrder = await procurementReviewer.page(
`/ordens/${orderId}`,
'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');
const financeReceipt = await finance.page(`/ordens/${orderId}/recepcoes`, 'receipts/order');
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' });
const financeReceipt = await finance.page(
`/ordens/${orderId}/recepcoes`,
'receipts/order',
);
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();
const receipt = { idempotency_key: crypto.randomUUID(), 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 }] };
const receipt = {
idempotency_key: crypto.randomUUID(),
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);
current = await state();
const received = current.financial_fingerprint;
const confirmedReceiptId = current.order.receipts[0].id;
const financialReceiptDetail = await finance.page(`/recepcoes/${confirmedReceiptId}`, 'receipts/show');
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');
const financialReceiptDetail = await finance.page(
`/recepcoes/${confirmedReceiptId}`,
'receipts/show',
);
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();
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);
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');
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' }] });
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',
);
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();
const invoiceId = current.invoice.id;
await post(finance, `/facturas/${invoiceId}/validar`, {}, 403);
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`, {});
current = await state();
check(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');
check(
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);
stage('bank_and_partial_payment');
const supplierId = current.quotes[0].supplier_id;
await post(buyer, `/fornecedores/${supplierId}/dados-bancarios`, { account_key: crypto.randomUUID(), 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' });
await post(buyer, `/fornecedores/${supplierId}/dados-bancarios`, {
account_key: crypto.randomUUID(),
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();
const bankId = current.bank.id;
for (const bankReviewer of [finance, reviewer]) 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' });
for (const bankReviewer of [finance, reviewer])
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();
check(current.bank.approved_reviews === 2, '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' };
check(
current.bank.approved_reviews === 2,
'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);
current = await state();
const paymentId = current.payments[0].id;
const reviewPage = await reviewer.page(`/pagamentos?payment_id=${paymentId}`, 'payments/index');
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 reviewPage = await reviewer.page(
`/pagamentos?payment_id=${paymentId}`,
'payments/index',
);
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;
await post(finance, `/facturas/${invoiceId}/pagamentos`, payment);
current = await state();
check(current.payments.length === 1 && current.financial_fingerprint === pending, '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' });
check(
current.payments.length === 1 &&
current.financial_fingerprint === pending,
'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();
check(current.payments[0].status === 'confirmed' && 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');
check(
current.payments[0].status === 'confirmed' &&
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 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 data = { 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 }] };
const data = {
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);
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');
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();
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' });
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 attribute(finalPaymentId, '60.00');
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(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(
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(
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');
const report = await process.json();
check(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');
check(
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) {
stage('project_trace');
const beforeTrace = current.financial_fingerprint;
const trace = await finance.page(`/projectos-imobilizado?history=${capital.record_key}`, 'equipment/capital-register');
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');
const trace = await finance.page(
`/projectos-imobilizado?history=${capital.record_key}`,
'equipment/capital-register',
);
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();
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();
return { checks, native_post_requests: commands, fortify_sessions: Object.keys(clients).length,
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,
return {
checks,
native_post_requests: commands,
fortify_sessions: Object.keys(clients).length,
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,
stock_quantity_milli: current.stock.quantity_milli, stock_movements: current.stock.movements, journals: current.journals,
explicit_finance_category_total_minor: current.analytics.category_attribution.groups.data[0].amount_minor,
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 };
stock_quantity_milli: current.stock.quantity_milli,
stock_movements: current.stock.movements,
journals: current.journals,
explicit_finance_category_total_minor:
current.analytics.category_attribution.groups.data[0].amount_minor,
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 assert from 'node:assert/strict';
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 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 records=[];
for(const [role,expected] of [['admin',200],['warehouse',403],['procurement',403],['finance',403]]) {
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,
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.');
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+17 -4
View File
@@ -1,9 +1,20 @@
import fs from 'node:fs/promises';
import assert from 'node:assert/strict';
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 source = await fs.readFile(
'scripts/supplier-evaluation-check.mjs',
'utf8',
);
const common = source.slice(
source.indexOf('const base ='),
source.indexOf('const author ='),
);
await new Function(
'fs',
'assert',
'return (async()=>{' +
common +
`
const results=[];
for(const role of ['admin','procurement','finance','warehouse']) {
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));
console.log(JSON.stringify({roles_checked:results.length,result:'passed',business_commands:false}));
`+'})()')(fs,assert);
` +
'})()',
)(fs, assert);
+131 -40
View File
@@ -2,46 +2,137 @@
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {spawnSync} from 'node:child_process';
import { spawnSync } from 'node:child_process';
import { purchasingHomeOverlay } from './lib/sgf-purchasing-home-overlay.mjs';
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.');
const work=path.join('C:/laragon/data/sgf-tempo/run','candidate-ui-'+crypto.randomBytes(6).toString('hex'));
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);};
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.symlinkSync(path.join(host,'node_modules'),path.join(work,'node_modules'),'junction');
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,'{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);
let home=fs.readFileSync(path.join(work,'resources/js/PurchasingHome.jsx'),'utf8');
home=purchasingHomeOverlay(home);
fs.writeFileSync(path.join(work,'resources/js/PurchasingHome.jsx'),home);
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'))},`);
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'}});
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={};
for(const chunk of Object.values(original))for(const file of [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 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.',
);
const work = path.join(
'C:/laragon/data/sgf-tempo/run',
'candidate-ui-' + crypto.randomBytes(6).toString('hex'),
);
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);
};
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.symlinkSync(
path.join(host, 'node_modules'),
path.join(work, 'node_modules'),
'junction',
);
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,
'{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);
let home = fs.readFileSync(
path.join(work, 'resources/js/PurchasingHome.jsx'),
'utf8',
);
home = purchasingHomeOverlay(home);
fs.writeFileSync(path.join(work, 'resources/js/PurchasingHome.jsx'), home);
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'))},`,
);
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' },
},
);
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 = {};
for (const chunk of Object.values(original))
for (const file of [
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));
for (const chunk of Object.values(manifest)) {
chunk.file = 'modules/internal-requisitions/' + chunk.file;
if (chunk.css)
chunk.css = chunk.css.map((p) => 'modules/internal-requisitions/' + p);
if (chunk.assets)
chunk.assets = chunk.assets.map(
(p) => 'modules/internal-requisitions/' + p,
);
}
const manifest=JSON.parse(JSON.stringify(original));
for(const chunk of Object.values(manifest)){
chunk.file='modules/internal-requisitions/'+chunk.file;
if(chunk.css)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 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};
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}));
const manifestFile = path.join(work, 'candidate-manifest.json');
fs.writeFileSync(manifestFile, JSON.stringify(manifest, null, 2) + '\n');
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,
};
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 }));
+1 -1
View File
@@ -102,5 +102,5 @@ try {
if ($exit === 0) {
$proof['test_database_and_roles_removed'] = true;
file_put_contents($root.'/docs/proofs/sgf-corrected-delivery.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
echo json_encode($proof,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)."\n";
echo json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR)."\n";
}exit($exit);
+329 -73
View File
@@ -1,88 +1,344 @@
import fs from 'node:fs';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
const root='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939';
const privateData=JSON.parse(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 state=fs.existsSync(stateFile)?JSON.parse(fs.readFileSync(stateFile,'utf8')):{};
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 clients={};
for(const p of privateData.profiles){
const jar=new Map();let csrf='',token='';
const api=async(path,method='GET',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;
const root = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939';
const privateData = JSON.parse(
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 state = fs.existsSync(stateFile)
? JSON.parse(fs.readFileSync(stateFile, 'utf8'))
: {};
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 clients = {};
for (const p of privateData.profiles) {
const jar = new Map();
let csrf = '',
token = '';
const api = async (
path,
method = 'GET',
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;
};
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});clients[p.role]=api;
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,
});
clients[p.role] = api;
}
checks.push('Existing three synthetic identities authenticate without password changes');
const prep=clients.preparador,review=clients.revisor,read=clients.consulta;
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(
'Existing three synthetic identities authenticate without password changes',
);
const prep = clients.preparador,
review = clients.revisor,
read = clients.consulta;
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');
for(const api of Object.values(clients))await api('/api/context','POST',{tenant_id:1,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){
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');
fs.writeFileSync(root+'/private/requisitions-recovery/budget-response.json',JSON.stringify(list,null,2));
state.budget_pending=true;persist();
for (const api of Object.values(clients))
await api('/api/context', 'POST', {
tenant_id: 1,
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) {
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');
fs.writeFileSync(
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.
const workspace=await prep('/api/purchasing-budget');
const candidates=workspace.budgets??workspace.allocations??workspace.records;
if(!state.budget_id){
assert(Array.isArray(candidates),'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();
const workspace = await prep('/api/purchasing-budget');
const candidates =
workspace.budgets ?? workspace.allocations ?? workspace.records;
if (!state.budget_id) {
assert(
Array.isArray(candidates),
'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){
await prep('/api/purchasing-budget/approve','POST',{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();
if (!state.budget_approved) {
await prep(
'/api/purchasing-budget/approve',
'POST',
{ 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');
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);
if(!state.policy_configured){await prep('/api/internal-requisitions/policy','POST',policy);state.policy_configured=true;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;
if(!state.submitted){
const submitted=await prep(path+'/submit','POST',{operation_key:key('submit'),version:1});
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');
checks.push(
'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);
if (!state.policy_configured) {
await prep('/api/internal-requisitions/policy', 'POST', policy);
state.policy_configured = true;
persist();
}
if(!state.approved){
const decision={operation_key:key('decision'),version:state.submitted.version,decision:'approved'};
await prep(path+'/decide','POST',decision,403);
await read(path+'/decide','POST',decision,[403,404]);
await read(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();
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();
}
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);
const path = '/api/internal-requisitions/' + state.request_id;
if (!state.submitted) {
const submitted = await prep(path + '/submit', 'POST', {
operation_key: key('submit'),
version: 1,
});
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) {
const decision = {
operation_key: key('decision'),
version: state.submitted.version,
decision: 'approved',
};
await prep(path + '/decide', 'POST', decision, 403);
await read(path + '/decide', 'POST', decision, [403, 404]);
await read(
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);
}
await read(path, 'GET', undefined, 404);
await read('/api/internal-requisitions');
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('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}));
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(
'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 }),
);
+121 -69
View File
@@ -1,4 +1,5 @@
<?php
// Explicitly authorised persistent synthetic demonstration only. No GRANT/REVOKE.
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
@@ -6,79 +7,130 @@ use Symfony\Component\Process\Process;
use Tempo\Purchasing\Delivery\CodeDeployment;
use Tempo\Purchasing\Delivery\Installation;
$root=dirname(__DIR__);
$host='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
$action=$argv[1]??'';
$recovery='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/requisitions-recovery';
$proof=json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'),true,64,JSON_THROW_ON_ERROR);
$bundle=$proof['artifact']['directory'];
$root = dirname(__DIR__);
$host = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
$action = $argv[1] ?? '';
$recovery = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/requisitions-recovery';
$proof = json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'), true, 64, JSON_THROW_ON_ERROR);
$bundle = $proof['artifact']['directory'];
require $host.'/vendor/autoload.php';
$app=require $host.'/bootstrap/app.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$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");
if ($app->basePath()!==str_replace('/',DIRECTORY_SEPARATOR,$host) && str_replace('\\','/',$app->basePath())!==$host) throw new RuntimeException('Wrong application folder');
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);
if ([$private['tenant_id'],$private['company_id'],$private['unit_id']]!==[1,1,1]) throw new RuntimeException('Wrong synthetic provenance');
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';
$deploy=new CodeDeployment($host);
$mh=$proof['artifact']['archive']['manifest_sha256'];
if ($action==='prepare') {
if(is_dir($recovery)) throw new RuntimeException('Recovery already exists; inspect before retry');
$plan=$deploy->plan($bundle,$mh);
mkdir($recovery,0700,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){
if(!is_dir(dirname($recovery.'/files/'.$file)))mkdir(dirname($recovery.'/files/'.$file),0700,true);
copy($host.'/'.$file,$recovery.'/files/'.$file);
$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");
if ($app->basePath() !== str_replace('/', DIRECTORY_SEPARATOR, $host) && str_replace('\\', '/', $app->basePath()) !== $host) {
throw new RuntimeException('Wrong application folder');
}
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);
if ([$private['tenant_id'], $private['company_id'], $private['unit_id']] !== [1, 1, 1]) {
throw new RuntimeException('Wrong synthetic provenance');
}
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');
}
$cfg=$db->getConfig();
$dump=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);
}
if (! class_exists(Installation::class)) {
require_once $bundle.'/integrations/sgf/operational/bootstrap.php';
}
require_once $bundle.'/integrations/sgf/operational/CodeDeployment.php';
$deploy = new CodeDeployment($host);
$mh = $proof['artifact']['archive']['manifest_sha256'];
if ($action === 'prepare') {
if (is_dir($recovery)) {
throw new RuntimeException('Recovery already exists; inspect before retry');
}
$plan = $deploy->plan($bundle, $mh);
mkdir($recovery, 0700, 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) {
if (! is_dir(dirname($recovery.'/files/'.$file))) {
mkdir(dirname($recovery.'/files/'.$file), 0700, true);
}
copy($host.'/'.$file, $recovery.'/files/'.$file);
}
$cfg = $db->getConfig();
$dump = 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);
$dump->mustRun();
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe','--list',$recovery.'/before.dump']))->mustRun();
$baseline=['identity'=>$identity,'host'=>$host,'code_plan'=>$plan,'backup_sha256'=>hash_file('sha256',$recovery.'/before.dump'),'grants'=>$db->table('permission_grants')->orderBy('id')->get()->all(),'users_sha256'=>hash('sha256',json_encode($db->table('users')->orderBy('id')->get())),'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,'host'=>$host,'recovery'=>$recovery,'backup_sha256'=>$baseline['backup_sha256'],'code_plan'=>$plan],JSON_PRETTY_PRINT);
} elseif($action==='install') {
$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(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]));
$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);
file_put_contents($recovery.'/applied.json',json_encode($applied,JSON_PRETTY_PRINT));
$config=['enabled'=>true,'target'=>Installation::target($db),'scopes'=>['1:1:1']];
file_put_contents($host.'/config/purchasing-operational.php','<?php return '.var_export($config,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"]];');
(new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--list', $recovery.'/before.dump']))->mustRun();
$baseline = ['identity' => $identity, 'host' => $host, 'code_plan' => $plan, 'backup_sha256' => hash_file('sha256', $recovery.'/before.dump'), 'grants' => $db->table('permission_grants')->orderBy('id')->get()->all(), 'users_sha256' => hash('sha256', json_encode($db->table('users')->orderBy('id')->get())), '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, 'host' => $host, 'recovery' => $recovery, 'backup_sha256' => $baseline['backup_sha256'], 'code_plan' => $plan], JSON_PRETTY_PRINT);
} elseif ($action === 'install') {
$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 (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]));
$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);
file_put_contents($recovery.'/applied.json', json_encode($applied, JSON_PRETTY_PRINT));
$config = ['enabled' => true, 'target' => Installation::target($db), 'scopes' => ['1:1:1']];
file_put_contents($host.'/config/purchasing-operational.php', '<?php return '.var_export($config, 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"]];');
// 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');
echo json_encode(['installed_synthetic_only'=>true,'migration'=>$migration,'deployment'=>$applied,'recovery'=>$recovery],JSON_PRETTY_PRINT);
} elseif($action==='verify') {
$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);
$current=$db->table('permission_grants')->orderBy('id')->get()->all();
$oldById=[];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');
$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');
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();
if(count($requests)!==1||$requests[0]->status!=='approved'||$requests[0]->requester_id!==1)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();
$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];
file_put_contents($root.'/docs/proofs/sgf-demo-8039-delivery.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
echo json_encode(['installed_synthetic_only' => true, 'migration' => $migration, 'deployment' => $applied, 'recovery' => $recovery], JSON_PRETTY_PRINT);
} elseif ($action === 'verify') {
$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);
$current = $db->table('permission_grants')->orderBy('id')->get()->all();
$oldById = [];
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');
$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');
}
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();
if (count($requests) !== 1 || $requests[0]->status !== 'approved' || $requests[0]->requester_id !== 1) {
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();
$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];
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"=>[]];');
echo json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
} else throw new RuntimeException('Use prepare, install or verify');
echo json_encode($report,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
} else {
throw new RuntimeException('Use prepare, install or verify');
}
+205 -40
View File
@@ -1,49 +1,214 @@
import fs from 'node:fs';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
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'));
assert.deepEqual([privateData.tenant_id,privateData.company_id,privateData.unit_id],[1,1,1]);
const checks=[];
for(const profile of privateData.profiles){
const jar=new Map();let csrf='',token='';
const api=async(path,method='GET',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;
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',
),
);
assert.deepEqual(
[privateData.tenant_id, privateData.company_id, privateData.unit_id],
[1, 1, 1],
);
const checks = [];
for (const profile of privateData.profiles) {
const jar = new Map();
let csrf = '',
token = '';
const api = async (
path,
method = 'GET',
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;
};
await api('/api/session');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');
if(legacy&&profile.role==='consulta'){
assert(!list.records.some(r=>r.id===1));await api('/api/internal-requisitions/1','GET',undefined,404);
checks.push('Previous version reproduces missing read-only listing/detail');continue;
await api('/api/session');
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');
if (legacy && profile.role === 'consulta') {
assert(!list.records.some((r) => r.id === 1));
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');
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.history.length,3);
checks.push(`${profile.role}: existing request 1 listed, detail and three-event history readable`);
if(profile.role==='consulta'){
assert.equal(list.permissions.prepare,false);assert.equal(list.permissions.configure,false);assert.deepEqual(detail.record.allowed_actions,[]);
await api('/api/internal-requisitions/save','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);
checks.push('Consulta: no allowed actions; creation, save, submission, decision, policy, centre, budget approval and administration refused');
await api('/api/internal-requisitions/1','GET',undefined,409,{'X-SGF-Context':'invalid'});
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');
assert(
list.records.some((r) => r.id === 1),
'Existing request must be listed',
);
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.history.length, 3);
checks.push(
`${profile.role}: existing request 1 listed, detail and three-event history readable`,
);
if (profile.role === 'consulta') {
assert.equal(list.permissions.prepare, false);
assert.equal(list.permissions.configure, false);
assert.deepEqual(detail.record.allowed_actions, []);
await api(
'/api/internal-requisitions/save',
'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);
checks.push(
'Consulta: no allowed actions; creation, save, submission, decision, policy, centre, budget approval and administration refused',
);
await api('/api/internal-requisitions/1', 'GET', undefined, 409, {
'X-SGF-Context': 'invalid',
});
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};
fs.writeFileSync('C:/laragon/www/compras/docs/proofs/sgf-read-8039-'+(legacy?'rollback':'http')+'.json',JSON.stringify(report,null,2));
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,
};
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));
+93 -61
View File
@@ -1,75 +1,107 @@
<?php
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Process\Process;
use Tempo\Purchasing\Delivery\CodeDeployment;
$root=dirname(__DIR__);
$host='C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
$recovery=dirname($host).'/private/read-correction-recovery';
$candidate=json_decode(file_get_contents($root.'/docs/proofs/sgf-read-candidate.json'),true,32,JSON_THROW_ON_ERROR);
$root = dirname(__DIR__);
$host = 'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/development-app';
$recovery = dirname($host).'/private/read-correction-recovery';
$candidate = json_decode(file_get_contents($root.'/docs/proofs/sgf-read-candidate.json'), true, 32, JSON_THROW_ON_ERROR);
require $host.'/vendor/autoload.php';
$app=require $host.'/bootstrap/app.php';
$app = require $host.'/bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
$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");
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();
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');
$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");
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();
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';
$deploy=new CodeDeployment($host);
$fingerprints=function()use($db){
return $db->transaction(function()use($db){
$db->statement('SET TRANSACTION READ ONLY');$hashes=[];
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');
$hashes[$t->tablename]=hash('sha256',json_encode(array_column($rows,'data'),JSON_THROW_ON_ERROR));
}return $hashes;
$deploy = new CodeDeployment($host);
$fingerprints = function () use ($db) {
return $db->transaction(function () use ($db) {
$db->statement('SET TRANSACTION READ ONLY');
$hashes = [];
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');
$hashes[$t->tablename] = hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR));
}
return $hashes;
});
};
$action=$argv[1]??'';
if($action==='prepare'){
if(is_dir($recovery))throw new RuntimeException('Recovery exists; no overwrite');
$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);
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();
$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);
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);
}else{
$baseline=json_decode(file_get_contents($recovery.'/baseline.json'),true,64,JSON_THROW_ON_ERROR);
$currentFingerprints=$fingerprints();
$changedTables=array_keys(array_filter($currentFingerprints,fn($hash,$table)=>$hash!==($baseline['data_fingerprints'][$table]??null),ARRAY_FILTER_USE_BOTH));
$auditAppended=false;
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();
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]));
$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');
$auditAppended=true;$changedTables=array_values(array_diff($changedTables,['identity_audit']));
$action = $argv[1] ?? '';
if ($action === 'prepare') {
if (is_dir($recovery)) {
throw new RuntimeException('Recovery exists; no overwrite');
}
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'){
$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);
}else{
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]));
if($action==='rollback'){
$applied=json_decode(file_get_contents($recovery.'/applied.json'),true);
$result=$deploy->rollback($applied['deployment_id'],'Authorised read fix recovery proof 8039',true);
file_put_contents($recovery.'/rollback.json',json_encode($result,JSON_PRETTY_PRINT));
}elseif(in_array($action,['apply','reapply'],true)){
$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);
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');
unlink($host.'/storage/framework/down');echo json_encode($result,JSON_PRETTY_PRINT);
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
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();
$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);
}
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);
} else {
$baseline = json_decode(file_get_contents($recovery.'/baseline.json'), true, 64, JSON_THROW_ON_ERROR);
$currentFingerprints = $fingerprints();
$changedTables = array_keys(array_filter($currentFingerprints, fn ($hash, $table) => $hash !== ($baseline['data_fingerprints'][$table] ?? null), ARRAY_FILTER_USE_BOTH));
$auditAppended = false;
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();
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]));
$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');
}
$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 ($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')];
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 {
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]));
if ($action === 'rollback') {
$applied = json_decode(file_get_contents($recovery.'/applied.json'), true);
$result = $deploy->rollback($applied['deployment_id'], 'Authorised read fix recovery proof 8039', true);
file_put_contents($recovery.'/rollback.json', json_encode($result, JSON_PRETTY_PRINT));
} elseif (in_array($action, ['apply', 'reapply'], true)) {
$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);
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');
}
unlink($host.'/storage/framework/down');
echo json_encode($result,JSON_PRETTY_PRINT);
}
}
+37 -26
View File
@@ -1,31 +1,42 @@
<?php
// Freeze only the authorised adapter correction over the previously proved artifact.
$root=dirname(__DIR__);
$prior=json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'),true,64,JSON_THROW_ON_ERROR);
$old=$prior['artifact']['directory'];
$manifest=json_decode(file_get_contents($old.'/manifest.json'),true,64,JSON_THROW_ON_ERROR);
$file='integrations/sgf/internal-requisitions/Port.php';
$payload=[];
foreach($manifest['support_files'] as $path=>$hash){
$text=file_get_contents($old.'/'.$path);
if(!hash_equals($hash,hash('sha256',$text)))throw new RuntimeException('Prior artifact changed');
$payload[$path]=$path===$file?file_get_contents($root.'/'.$file):$text;
$root = dirname(__DIR__);
$prior = json_decode(file_get_contents($root.'/docs/proofs/sgf-corrected-delivery.json'), true, 64, JSON_THROW_ON_ERROR);
$old = $prior['artifact']['directory'];
$manifest = json_decode(file_get_contents($old.'/manifest.json'), true, 64, JSON_THROW_ON_ERROR);
$file = 'integrations/sgf/internal-requisitions/Port.php';
$payload = [];
foreach ($manifest['support_files'] as $path => $hash) {
$text = file_get_contents($old.'/'.$path);
if (! hash_equals($hash, hash('sha256', $text))) {
throw new RuntimeException('Prior artifact changed');
}
$payload[$path] = $path === $file ? file_get_contents($root.'/'.$file) : $text;
}
$manifest['support_files'][$file]=hash('sha256',$payload[$file]);
$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;
if(file_exists($dir))throw new RuntimeException('Candidate already exists; verify rather than overwrite');
mkdir($dir,0700,true);
foreach($payload+['manifest.json'=>$manifestText] as $path=>$text){
if(!is_dir(dirname($dir.'/'.$path)))mkdir(dirname($dir.'/'.$path),0700,true);
file_put_contents($dir.'/'.$path,$text);
$manifest['support_files'][$file] = hash('sha256', $payload[$file]);
$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;
if (file_exists($dir)) {
throw new RuntimeException('Candidate already exists; verify rather than overwrite');
}
mkdir($dir, 0700, true);
foreach ($payload + ['manifest.json' => $manifestText] as $path => $text) {
if (! is_dir(dirname($dir.'/'.$path))) {
mkdir(dirname($dir.'/'.$path), 0700, true);
}
file_put_contents($dir.'/'.$path, $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 collision');
}
foreach ([...array_keys($payload), 'manifest.json'] as $path) {
$zip->addFile($dir.'/'.$path, $path);
}
$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 collision');
foreach([...array_keys($payload),'manifest.json'] as $path)$zip->addFile($dir.'/'.$path,$path);
$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];
file_put_contents($root.'/docs/proofs/sgf-read-candidate.json',json_encode($result,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
echo json_encode($result,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR);
$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));
echo json_encode($result,JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
+60 -21
View File
@@ -1,24 +1,63 @@
<?php
$root=dirname(__DIR__);
$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);
$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(['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['scripts/sgf-sourcing-install.php']=file_get_contents($root.'/scripts/sgf-sourcing-install.php');
use App\Services\ComparisonPolicy;
use Tempo\Purchasing\Delivery\AccessOverlay;
$root = dirname(__DIR__);
$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);
$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 (['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['scripts/sgf-sourcing-install.php'] = file_get_contents($root.'/scripts/sgf-sourcing-install.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);
$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);
$manifest['host_overlays'][$file]['after_sha256']=hash('sha256',$payload[$file]);
$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';
$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]);
// The same native catalogue and delegation workflow remain in use.
foreach($payload as $file=>$text)$manifest['support_files'][$file]=hash('sha256',$text);
$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;
if(file_exists($dir))throw new RuntimeException('Immutable candidate exists');mkdir($dir,0700,true);
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 Tempo\Purchasing\Delivery\AccessOverlay::RIGHTS;}
foreach ($payload as $file => $text) {
$manifest['support_files'][$file] = hash('sha256', $text);
}
$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;
if (file_exists($dir)) {
throw new RuntimeException('Immutable candidate exists');
}mkdir($dir, 0700, true);
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;
}
+67 -32
View File
@@ -1,35 +1,70 @@
<?php
use App\Services\ComparisonPolicy;
use Tempo\Purchasing\Internal\RequisitionFailure;
use Tempo\Purchasing\Sourcing\Sourcing;
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';
$engine=new Tempo\Purchasing\Sourcing\Sourcing;
$policy=App\Services\ComparisonPolicy::DEFAULTS;
$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=[];
$check=function($ok,$label)use(&$checks){if(!$ok)throw new RuntimeException($label);$checks[]=$label;};
$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);}};
$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');
$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');
foreach([1,2,3] as $id)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'];
$deny(fn()=>$step($state,1,'propose',$proposal),403,'Requester cannot propose award');
$state=$step($state,2,'propose',$proposal);
$confirmation=['proposal_index'=>0,'comparison_hash'=>$comparison['fingerprint'],'reason'=>'Independent synthetic confirmation'];
$deny(fn()=>$step($state,2,'confirm',$confirmation),403,'Proposer cannot confirm own 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']]]);
$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;
$deny(fn()=>$step($revoked,4,'confirm',$confirmation),409,'Evaluator revocation invalidates confirmation basis');
$expired=$state;$expired['quotes'][1]['valid_until']='2026-11-01';
$deny(fn()=>$step($expired,4,'confirm',$confirmation),409,'Expired quote invalidates 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');
$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');
$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);
$engine = new Sourcing;
$policy = ComparisonPolicy::DEFAULTS;
$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 = [];
$check = function ($ok, $label) use (&$checks) {
if (! $ok) {
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');
$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');
foreach ([1, 2, 3] as $id) {
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'];
$deny(fn () => $step($state, 1, 'propose', $proposal), 403, 'Requester cannot propose award');
$state = $step($state, 2, 'propose', $proposal);
$confirmation = ['proposal_index' => 0, 'comparison_hash' => $comparison['fingerprint'], 'reason' => 'Independent synthetic confirmation'];
$deny(fn () => $step($state, 2, 'confirm', $confirmation), 403, 'Proposer cannot confirm own 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']]]);
$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;
$deny(fn () => $step($revoked, 4, 'confirm', $confirmation), 409, 'Evaluator revocation invalidates confirmation basis');
$expired = $state;
$expired['quotes'][1]['valid_until'] = '2026-11-01';
$deny(fn () => $step($expired, 4, 'confirm', $confirmation), 409, 'Expired quote invalidates 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');
$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');
$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);

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