Juntar fase5-producao ao main (inclui c9bd6db da máquina Windows)
Conflito em docs/historico/decisoes-do-proprietario.md resolvido mantendo
as decisões de 01/12 da fase 5 e as notas de 30/11 de c9bd6db.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,49 +2,78 @@
|
||||
|
||||
// Coordinator: provision disposable databases via maintenance DB, never migrate/read client data.
|
||||
require __DIR__.'/../../vendor/autoload.php';
|
||||
foreach (['APP_ENV'=>'budget-coordinator','DB_CONNECTION'=>'pgsql','CACHE_STORE'=>'array','SESSION_DRIVER'=>'array'] as $key=>$value) { putenv($key.'='.$value); $_ENV[$key]=$_SERVER[$key]=$value; }
|
||||
$app=require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
foreach (['APP_ENV' => 'budget-coordinator', 'DB_CONNECTION' => 'pgsql', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array'] as $key => $value) {
|
||||
putenv($key.'='.$value);
|
||||
$_ENV[$key] = $_SERVER[$key] = $value;
|
||||
}
|
||||
$app = require __DIR__.'/../../bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\Process\Process;
|
||||
$source=DB::connection('pgsql')->getConfig();
|
||||
if(($source['driver']??'')!=='pgsql'||($source['host']??'')!=='127.0.0.1')throw new LogicException('Local PostgreSQL maintenance connection required.');
|
||||
$maintenance=[...$source,'database'=>'postgres','url'=>null];
|
||||
config(['database.connections.budget_admin'=>$maintenance]);
|
||||
$admin=DB::connection('budget_admin')->getPdo();
|
||||
$sgf=realpath(base_path('../sgf-tempo'));
|
||||
$script=$sgf.'/packages/budget-control/tests/run-host.php';
|
||||
$report=['version'=>'COMMON-BUDGET-SYNTHETIC-v1','checked_at'=>gmdate('c'),'client_databases_touched'=>false,'hosts'=>[]];
|
||||
$artifact=sys_get_temp_dir().'/common-budget-artifact-'.bin2hex(random_bytes(6));
|
||||
if(!mkdir($artifact.'/src',0700,true))throw new RuntimeException('Cannot prepare isolated package artifact.');
|
||||
$artifactFiles=['bootstrap.php','src/BudgetContext.php','src/BudgetFailure.php','src/BudgetControl.php'];
|
||||
foreach($artifactFiles as $file)if(!copy($sgf.'/packages/budget-control/'.$file,$artifact.'/'.$file))throw new RuntimeException('Cannot build package artifact.');
|
||||
try {
|
||||
foreach(['compras','sgf'] as $mode){
|
||||
$db=($mode==='compras'?'compras_receipts_test_':'budget_core_sgf_').bin2hex(random_bytes(6));
|
||||
$created=false;
|
||||
try{
|
||||
$admin->exec('CREATE DATABASE "'.$db.'"');$created=true;
|
||||
$environment=['APP_ENV'=>$mode==='compras'?'testing':'budget-testing','DB_CONNECTION'=>'pgsql','DB_DATABASE'=>$db,'DB_URL'=>'','DB_HOST'=>'127.0.0.1','DB_PORT'=>(string)$source['port'],'DB_USERNAME'=>$source['username'],'DB_PASSWORD'=>$source['password'],'CACHE_STORE'=>'array','SESSION_DRIVER'=>'array','QUEUE_CONNECTION'=>'sync','MAIL_MAILER'=>'array','BCRYPT_ROUNDS'=>'4','COMMON_BUDGET_PATH'=>$mode==='compras'?$artifact:$sgf.'/packages/budget-control'];
|
||||
$php=$mode==='compras'?PHP_BINARY:'C:/laragon/tools/sgf-tempo/php-8.4.27/php.exe';
|
||||
$root=$mode==='compras'?base_path():$sgf;
|
||||
$process=new Process([$php,$script,$root,$mode],$root,$environment);$process->setTimeout(120);$process->run();
|
||||
if(!$process->isSuccessful())throw new RuntimeException('QA host failed: '.$process->getOutput().$process->getErrorOutput());
|
||||
$report['hosts'][]=json_decode($process->getOutput(),true,64,JSON_THROW_ON_ERROR);
|
||||
}finally{
|
||||
if(isset($process)&&$process->isRunning())$process->stop();
|
||||
if($created){
|
||||
$stmt=$admin->prepare('SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=? AND pid<>pg_backend_pid()');$stmt->execute([$db]);
|
||||
$admin->exec('DROP DATABASE "'.$db.'"');
|
||||
}
|
||||
|
||||
$source = DB::connection('pgsql')->getConfig();
|
||||
if (($source['driver'] ?? '') !== 'pgsql' || ($source['host'] ?? '') !== '127.0.0.1') {
|
||||
throw new LogicException('Local PostgreSQL maintenance connection required.');
|
||||
}
|
||||
$maintenance = [...$source, 'database' => 'postgres', 'url' => null];
|
||||
config(['database.connections.budget_admin' => $maintenance]);
|
||||
$admin = DB::connection('budget_admin')->getPdo();
|
||||
$sgf = realpath(base_path('../sgf-tempo'));
|
||||
$script = $sgf.'/packages/budget-control/tests/run-host.php';
|
||||
$report = ['version' => 'COMMON-BUDGET-SYNTHETIC-v1', 'checked_at' => gmdate('c'), 'client_databases_touched' => false, 'hosts' => []];
|
||||
$artifact = sys_get_temp_dir().'/common-budget-artifact-'.bin2hex(random_bytes(6));
|
||||
if (! mkdir($artifact.'/src', 0700, true)) {
|
||||
throw new RuntimeException('Cannot prepare isolated package artifact.');
|
||||
}
|
||||
$artifactFiles = ['bootstrap.php', 'src/BudgetContext.php', 'src/BudgetFailure.php', 'src/BudgetControl.php'];
|
||||
foreach ($artifactFiles as $file) {
|
||||
if (! copy($sgf.'/packages/budget-control/'.$file, $artifact.'/'.$file)) {
|
||||
throw new RuntimeException('Cannot build package artifact.');
|
||||
}
|
||||
}
|
||||
try {
|
||||
foreach (['compras', 'sgf'] as $mode) {
|
||||
$db = ($mode === 'compras' ? 'compras_receipts_test_' : 'budget_core_sgf_').bin2hex(random_bytes(6));
|
||||
$created = false;
|
||||
try {
|
||||
$admin->exec('CREATE DATABASE "'.$db.'"');
|
||||
$created = true;
|
||||
$environment = ['APP_ENV' => $mode === 'compras' ? 'testing' : 'budget-testing', 'DB_CONNECTION' => 'pgsql', 'DB_DATABASE' => $db, 'DB_URL' => '', 'DB_HOST' => '127.0.0.1', 'DB_PORT' => (string) $source['port'], 'DB_USERNAME' => $source['username'], 'DB_PASSWORD' => $source['password'], 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'sync', 'MAIL_MAILER' => 'array', 'BCRYPT_ROUNDS' => '4', 'COMMON_BUDGET_PATH' => $mode === 'compras' ? $artifact : $sgf.'/packages/budget-control'];
|
||||
$php = $mode === 'compras' ? PHP_BINARY : 'C:/laragon/tools/sgf-tempo/php-8.4.27/php.exe';
|
||||
$root = $mode === 'compras' ? base_path() : $sgf;
|
||||
$process = new Process([$php, $script, $root, $mode], $root, $environment);
|
||||
$process->setTimeout(120);
|
||||
$process->run();
|
||||
if (! $process->isSuccessful()) {
|
||||
throw new RuntimeException('QA host failed: '.$process->getOutput().$process->getErrorOutput());
|
||||
}
|
||||
$report['hosts'][] = json_decode($process->getOutput(), true, 64, JSON_THROW_ON_ERROR);
|
||||
} finally {
|
||||
if (isset($process) && $process->isRunning()) {
|
||||
$process->stop();
|
||||
}
|
||||
if ($created) {
|
||||
$stmt = $admin->prepare('SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname=? AND pid<>pg_backend_pid()');
|
||||
$stmt->execute([$db]);
|
||||
$admin->exec('DROP DATABASE "'.$db.'"');
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
// Delete only the exact files created above, never a recursive or computed project path.
|
||||
foreach($artifactFiles as $file)if(is_file($artifact.'/'.$file))unlink($artifact.'/'.$file);
|
||||
rmdir($artifact.'/src');rmdir($artifact);
|
||||
foreach ($artifactFiles as $file) {
|
||||
if (is_file($artifact.'/'.$file)) {
|
||||
unlink($artifact.'/'.$file);
|
||||
}
|
||||
}
|
||||
rmdir($artifact.'/src');
|
||||
rmdir($artifact);
|
||||
}
|
||||
if($report['hosts'][0]['core_sha256']!==$report['hosts'][1]['core_sha256']||$report['hosts'][0]['steps']!==$report['hosts'][1]['steps'])throw new RuntimeException('Host equivalence failed.');
|
||||
$report['equivalent']=true;$report['disposable_databases_dropped']=true;
|
||||
file_put_contents($sgf.'/docs/proofs/common-budget-hosts.json',json_encode($report,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
if ($report['hosts'][0]['core_sha256'] !== $report['hosts'][1]['core_sha256'] || $report['hosts'][0]['steps'] !== $report['hosts'][1]['steps']) {
|
||||
throw new RuntimeException('Host equivalence failed.');
|
||||
}
|
||||
$report['equivalent'] = true;
|
||||
$report['disposable_databases_dropped'] = true;
|
||||
file_put_contents($sgf.'/docs/proofs/common-budget-hosts.json', json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
|
||||
echo "Two Laravel hosts passed the same core sequence and PostgreSQL concurrency checks. Disposable databases dropped.\n";
|
||||
|
||||
@@ -54,5 +54,5 @@ try {
|
||||
$event = app(WarehouseFulfilment::class)->command($actor, $data['request'], $data['input']);
|
||||
echo json_encode(['result' => 'saved', 'event' => $event->id], JSON_THROW_ON_ERROR);
|
||||
} catch (ValidationException $error) {
|
||||
echo json_encode(['result' => 'rejected'],JSON_THROW_ON_ERROR);
|
||||
echo json_encode(['result' => 'rejected'], JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Department;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
use Laravel\Fortify\Actions\EnableTwoFactorAuthentication;
|
||||
|
||||
require_once __DIR__.'/../../Support/FortifyMfa.php';
|
||||
|
||||
// Decisão de 30/11/2026: MFA obrigatório para administração e Finanças, voluntário para os restantes.
|
||||
|
||||
beforeEach(function () {
|
||||
foundationMfaRoutes();
|
||||
$tenant = Tenant::query()->create(['name' => 'Empresa MFA']);
|
||||
$this->department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações']);
|
||||
$this->user = fn (PurchasingRole $role) => User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $this->department->id, 'purchasing_role' => $role]);
|
||||
});
|
||||
|
||||
test('sensitive roles without confirmed MFA are sent to the security settings', function (PurchasingRole $role) {
|
||||
$this->actingAs(($this->user)($role));
|
||||
$this->get('/dashboard')->assertRedirect('/settings/security');
|
||||
$this->get('/facturas')->assertRedirect('/settings/security');
|
||||
$this->getJson('/requisicoes')->assertForbidden();
|
||||
})->with([PurchasingRole::Admin, PurchasingRole::Finance]);
|
||||
|
||||
test('the security settings, password confirmation and logout stay reachable while MFA is pending', function () {
|
||||
$this->actingAs(($this->user)(PurchasingRole::Finance));
|
||||
$this->get('/user/confirm-password')->assertOk();
|
||||
$this->withSession(['auth.password_confirmed_at' => time()])->get('/settings/security')->assertOk()
|
||||
->assertInertia(fn (Assert $page) => $page->component('settings/security')->where('mfaRequired', true)->where('canManageTwoFactor', true));
|
||||
$this->post('/logout')->assertRedirect();
|
||||
$this->assertGuest();
|
||||
});
|
||||
|
||||
test('confirmed MFA unlocks the application for sensitive roles', function () {
|
||||
$finance = ($this->user)(PurchasingRole::Finance);
|
||||
app(EnableTwoFactorAuthentication::class)($finance);
|
||||
$finance->forceFill(['two_factor_confirmed_at' => now()])->save();
|
||||
$this->actingAs($finance)->get('/dashboard')->assertOk();
|
||||
});
|
||||
|
||||
test('other roles keep MFA voluntary', function () {
|
||||
$this->actingAs(($this->user)(PurchasingRole::Requester))->get('/dashboard')->assertOk();
|
||||
});
|
||||
|
||||
test('nothing is enforced while MFA is switched off for the installation', function () {
|
||||
config(['fortify.features' => []]);
|
||||
$this->actingAs(($this->user)(PurchasingRole::Admin))->get('/dashboard')->assertOk();
|
||||
});
|
||||
@@ -6,6 +6,9 @@ use Symfony\Component\Process\Process;
|
||||
|
||||
beforeEach(function () {
|
||||
$proof = json_decode(file_get_contents(base_path('docs/proofs/rq01-distribution-artifact.json')), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (! is_dir(base_path($proof['path']))) {
|
||||
$this->markTestSkipped('The frozen distribution artifact is generated locally by scripts/prepare-budget-distribution-artifact.php.');
|
||||
}
|
||||
$this->artifactDirectory = storage_path('framework/testing/distribution-integrity-'.Str::uuid());
|
||||
mkdir($this->artifactDirectory.'/src', 0700, true);
|
||||
foreach ($proof['files'] as $file => $hash) {
|
||||
@@ -18,6 +21,9 @@ beforeEach(function () {
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
if (! isset($this->artifactDirectory)) {
|
||||
return;
|
||||
}
|
||||
foreach (glob($this->artifactDirectory.'/src/*') as $file) {
|
||||
unlink($file);
|
||||
}
|
||||
|
||||
@@ -2,9 +2,15 @@
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\{GoodsReceipt,GoodsReceiptItem,StockMovement};
|
||||
use App\Services\{ConflictGuard,ReceiptStockMovement,ReceiptWorkflow};
|
||||
use Illuminate\Support\Facades\{Artisan,DB};
|
||||
use App\Models\GoodsReceipt;
|
||||
use App\Models\GoodsReceiptItem;
|
||||
use App\Models\StockMovement;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\ReceiptStockMovement;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Tests\TestCase;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
@@ -13,59 +19,141 @@ final class CommonReceiptStockTest extends TestCase
|
||||
{
|
||||
public function test_native_receipt_shared_writer_and_single_book_evidence(): void
|
||||
{
|
||||
$i=DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
$this->assertMatchesRegularExpression('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->name);$tag=substr($i->name,-12);
|
||||
$this->assertSame('stock_receipt_qa_'.$tag,$i->role);$this->assertSame(55439,(int)$i->port);$this->assertSame('sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'),$i->cluster);
|
||||
if(!DB::getSchemaBuilder()->hasTable('users')){Artisan::call('migrate',['--force'=>true]);}
|
||||
$this->assertSame(0,DB::table('users')->count(),'Use the fresh QA database, never a retained fixture');
|
||||
$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$this->assertNotFalse($root);
|
||||
$f=\receiptFixture('10.000');$this->actingAs($f['receiver']);$url='/ordens/'.$f['order']->id.'/recepcoes';
|
||||
$body=\receiptPayload($f,'6.000');$body['items'][0]['accepted_quantity']='4.000';$body['items'][0]['quality_status']='reservations';$body['items'][0]['notes']='Synthetic acceptance: four accepted, two damaged.';
|
||||
$receipt=$this->postJson($url,$body)->assertCreated()->json('id');
|
||||
$this->postJson($url,$body)->assertOk()->assertJsonPath('id',$receipt)->assertJsonPath('created',false);
|
||||
$line=GoodsReceiptItem::query()->where('goods_receipt_id',$receipt)->firstOrFail();$movement=StockMovement::query()->where('goods_receipt_item_id',$line->id)->firstOrFail();
|
||||
$this->assertSame(4000,(int)$movement->quantity_milli);$this->assertSame(2000,(int)$line->rejected_milli);
|
||||
$this->assertMatchesRegularExpression('/^[a-f0-9]{64}$/D',$movement->snapshot['inventory_source_hash']);
|
||||
$coreReplay=DB::transaction(function () use ($f,$line,$movement){
|
||||
app(ConflictGuard::class)->lockCompany($f['receiver']);$w=app(ReceiptStockMovement::class)->for($f['receiver']);
|
||||
return $w->write($line->id,$movement->snapshot['inventory_source_hash']);
|
||||
});$this->assertTrue($coreReplay['replayed']);$this->assertSame($movement->id,$coreReplay['movement_id']);
|
||||
try{DB::transaction(function()use($f,$line){app(ConflictGuard::class)->lockCompany($f['receiver']);app(ReceiptStockMovement::class)->for($f['receiver'])->write($line->id,str_repeat('0',64));});$this->fail('Old origin hash must be refused');}
|
||||
catch(\Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$this->assertSame(409,$e->getStatusCode());}
|
||||
$bad=$body;$bad['items'][0]['accepted_quantity']='3.000';$this->postJson($url,$bad)->assertUnprocessable();
|
||||
$rejected=\receiptPayload($f,'2.000');$rejected['warehouse_id']=null;$rejected['items'][0]['stock_item_id']=null;$rejected['items'][0]['accepted_quantity']='0';$rejected['items'][0]['quality_status']='nonconforming';$rejected['items'][0]['notes']='Synthetic rejection.';
|
||||
$this->postJson($url,$rejected)->assertCreated()->assertJsonPath('status','rejected');
|
||||
$this->assertSame(1,StockMovement::query()->count());
|
||||
$this->actingAs($f['issuer'])->postJson($url,\receiptPayload($f,'1.000'))->assertForbidden();$this->actingAs($f['receiver']);
|
||||
skipUnlessIsolatedPostgres($this);
|
||||
$i = DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
$this->assertMatchesRegularExpression('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->name);
|
||||
$tag = substr($i->name, -12);
|
||||
$this->assertSame('stock_receipt_qa_'.$tag, $i->role);
|
||||
$this->assertSame(55439, (int) $i->port);
|
||||
$this->assertSame('sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'), $i->cluster);
|
||||
if (! DB::getSchemaBuilder()->hasTable('users')) {
|
||||
Artisan::call('migrate', ['--force' => true]);
|
||||
}
|
||||
$this->assertSame(0, DB::table('users')->count(), 'Use the fresh QA database, never a retained fixture');
|
||||
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
|
||||
$this->assertNotFalse($root);
|
||||
$f = \receiptFixture('10.000');
|
||||
$this->actingAs($f['receiver']);
|
||||
$url = '/ordens/'.$f['order']->id.'/recepcoes';
|
||||
$body = \receiptPayload($f, '6.000');
|
||||
$body['items'][0]['accepted_quantity'] = '4.000';
|
||||
$body['items'][0]['quality_status'] = 'reservations';
|
||||
$body['items'][0]['notes'] = 'Synthetic acceptance: four accepted, two damaged.';
|
||||
$receipt = $this->postJson($url, $body)->assertCreated()->json('id');
|
||||
$this->postJson($url, $body)->assertOk()->assertJsonPath('id', $receipt)->assertJsonPath('created', false);
|
||||
$line = GoodsReceiptItem::query()->where('goods_receipt_id', $receipt)->firstOrFail();
|
||||
$movement = StockMovement::query()->where('goods_receipt_item_id', $line->id)->firstOrFail();
|
||||
$this->assertSame(4000, (int) $movement->quantity_milli);
|
||||
$this->assertSame(2000, (int) $line->rejected_milli);
|
||||
$this->assertMatchesRegularExpression('/^[a-f0-9]{64}$/D', $movement->snapshot['inventory_source_hash']);
|
||||
$coreReplay = DB::transaction(function () use ($f, $line, $movement) {
|
||||
app(ConflictGuard::class)->lockCompany($f['receiver']);
|
||||
$w = app(ReceiptStockMovement::class)->for($f['receiver']);
|
||||
|
||||
return $w->write($line->id, $movement->snapshot['inventory_source_hash']);
|
||||
});
|
||||
$this->assertTrue($coreReplay['replayed']);
|
||||
$this->assertSame($movement->id, $coreReplay['movement_id']);
|
||||
try {
|
||||
DB::transaction(function () use ($f, $line) {
|
||||
app(ConflictGuard::class)->lockCompany($f['receiver']);
|
||||
app(ReceiptStockMovement::class)->for($f['receiver'])->write($line->id, str_repeat('0', 64));
|
||||
});
|
||||
$this->fail('Old origin hash must be refused');
|
||||
} catch (HttpExceptionInterface $e) {
|
||||
$this->assertSame(409, $e->getStatusCode());
|
||||
}
|
||||
$bad = $body;
|
||||
$bad['items'][0]['accepted_quantity'] = '3.000';
|
||||
$this->postJson($url, $bad)->assertUnprocessable();
|
||||
$rejected = \receiptPayload($f, '2.000');
|
||||
$rejected['warehouse_id'] = null;
|
||||
$rejected['items'][0]['stock_item_id'] = null;
|
||||
$rejected['items'][0]['accepted_quantity'] = '0';
|
||||
$rejected['items'][0]['quality_status'] = 'nonconforming';
|
||||
$rejected['items'][0]['notes'] = 'Synthetic rejection.';
|
||||
$this->postJson($url, $rejected)->assertCreated()->assertJsonPath('status', 'rejected');
|
||||
$this->assertSame(1, StockMovement::query()->count());
|
||||
$this->actingAs($f['issuer'])->postJson($url, \receiptPayload($f, '1.000'))->assertForbidden();
|
||||
$this->actingAs($f['receiver']);
|
||||
// Fault after the shared SQL insert must undo receipt, movement and native audit.
|
||||
$failure=\receiptFixture();$this->actingAs($failure['receiver']);$payload=\receiptPayload($failure,'1.000');$fault=true;
|
||||
$before=array_map(fn($t)=>DB::table($t)->count(),['goods_receipts','goods_receipt_items','stock_movements','audit_logs']);
|
||||
DB::listen(function($q)use(&$fault){if($fault&&preg_match('/insert into .*stock_movements/i',$q->sql)){$fault=false;throw new \RuntimeException('Synthetic failure after inventory insert');}});
|
||||
try{app(ReceiptWorkflow::class)->confirm($failure['receiver'],$failure['order'],$payload);$this->fail('Injected failure missing');}
|
||||
catch(\RuntimeException $e){$this->assertSame('Synthetic failure after inventory insert',$e->getMessage());}
|
||||
$this->assertSame($before,array_map(fn($t)=>DB::table($t)->count(),['goods_receipts','goods_receipt_items','stock_movements','audit_logs']));
|
||||
$recovered=app(ReceiptWorkflow::class)->confirm($failure['receiver'],$failure['order'],$payload);
|
||||
$this->assertSame(1,StockMovement::query()->whereIn('goods_receipt_item_id',$recovered->items->pluck('id'))->count());
|
||||
$failure = \receiptFixture();
|
||||
$this->actingAs($failure['receiver']);
|
||||
$payload = \receiptPayload($failure, '1.000');
|
||||
$fault = true;
|
||||
$before = array_map(fn ($t) => DB::table($t)->count(), ['goods_receipts', 'goods_receipt_items', 'stock_movements', 'audit_logs']);
|
||||
DB::listen(function ($q) use (&$fault) {
|
||||
if ($fault && preg_match('/insert into .*stock_movements/i', $q->sql)) {
|
||||
$fault = false;
|
||||
throw new \RuntimeException('Synthetic failure after inventory insert');
|
||||
}
|
||||
});
|
||||
try {
|
||||
app(ReceiptWorkflow::class)->confirm($failure['receiver'], $failure['order'], $payload);
|
||||
$this->fail('Injected failure missing');
|
||||
} catch (\RuntimeException $e) {
|
||||
$this->assertSame('Synthetic failure after inventory insert', $e->getMessage());
|
||||
}
|
||||
$this->assertSame($before, array_map(fn ($t) => DB::table($t)->count(), ['goods_receipts', 'goods_receipt_items', 'stock_movements', 'audit_logs']));
|
||||
$recovered = app(ReceiptWorkflow::class)->confirm($failure['receiver'], $failure['order'], $payload);
|
||||
$this->assertSame(1, StockMovement::query()->whereIn('goods_receipt_item_id', $recovered->items->pluck('id'))->count());
|
||||
// Two real PHP processes contend on the company lock, then recover the same receipt.
|
||||
$concurrent=\receiptFixture();$this->actingAs($concurrent['receiver']);$payload=\receiptPayload($concurrent,'1.000');$process=null;
|
||||
$concurrent = \receiptFixture();
|
||||
$this->actingAs($concurrent['receiver']);
|
||||
$payload = \receiptPayload($concurrent, '1.000');
|
||||
$process = null;
|
||||
DB::beginTransaction();
|
||||
try{
|
||||
$winner=app(ReceiptWorkflow::class)->confirm($concurrent['receiver'],$concurrent['order'],$payload);
|
||||
$input=$root.'/worker.json';$application='stock_receipt_worker_'.$tag;
|
||||
file_put_contents($input,json_encode(['actor'=>$concurrent['receiver']->id,'order'=>$concurrent['order']->id,'payload'=>$payload,'application'=>$application],JSON_THROW_ON_ERROR));
|
||||
$pipes=[];$process=proc_open([PHP_BINARY,base_path('tests/Support/common-receipt-worker.php'),$input],[0=>['pipe','r'],1=>['file',$root.'/worker.stdout','w'],2=>['file',$root.'/worker.stderr','w']],$pipes,base_path());
|
||||
$this->assertIsResource($process);fclose($pipes[0]);$deadline=microtime(true)+10;$wait=null;$parent=(int)DB::selectOne('SELECT pg_backend_pid() AS pid')->pid;
|
||||
do{DB::select('SELECT pg_stat_clear_snapshot()');$wait=DB::selectOne("SELECT wait_event,to_json(pg_blocking_pids(pid)) AS blockers FROM pg_stat_activity WHERE application_name=? AND wait_event_type='Lock'",[$application]);if(!$wait)usleep(25000);}while(!$wait&µtime(true)<$deadline);
|
||||
$this->assertNotNull($wait);$this->assertContains($parent,json_decode($wait->blockers,true));DB::commit();
|
||||
$deadline=microtime(true)+15;do{$status=proc_get_status($process);if(!$status['running'])break;usleep(25000);}while(microtime(true)<$deadline);
|
||||
$this->assertFalse($status['running']);$exit=proc_close($process);$process=null;if($exit===-1)$exit=$status['exitcode'];$this->assertSame(0,$exit);
|
||||
$second=json_decode(file_get_contents($input.'.result'),true,512,JSON_THROW_ON_ERROR);$this->assertSame(200,$second['status']);$this->assertSame($winner->id,$second['receipt_id']);
|
||||
$this->assertSame(1,GoodsReceipt::query()->where('purchase_order_id',$concurrent['order']->id)->count());
|
||||
$this->assertSame(1,StockMovement::query()->whereIn('goods_receipt_item_id',$winner->items->pluck('id'))->count());
|
||||
}finally{if(is_resource($process)){proc_terminate($process);proc_close($process);}while(DB::transactionLevel()>0)DB::rollBack();}
|
||||
file_put_contents($root.'/receipt-results.json',json_encode(['identity'=>$i,'physical_accepted_milli'=>4000,'rejected_milli'=>2000,'movement_count_main'=>1,
|
||||
'source_version_stale_refused'=>true,'core_replay_same_movement'=>true,'fault_atomic_and_recovered'=>true,'concurrency'=>['actual_lock_wait'=>true,'wait_event'=>$wait->wait_event,'same_receipt'=>true,'one_movement'=>true],
|
||||
'link'=>['tenant'=>(int)$f['tenant']->id,'warehouse'=>(int)$f['warehouse']->id,'item'=>(int)$f['stock']->id,'movement'=>(int)$movement->id,'reference'=>$movement->snapshot['reference']],
|
||||
'writer_manifest_sha256'=>hash_file('sha256',base_path('packages/inventory-write/releases/0.1.0/manifest.json'))],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
try {
|
||||
$winner = app(ReceiptWorkflow::class)->confirm($concurrent['receiver'], $concurrent['order'], $payload);
|
||||
$input = $root.'/worker.json';
|
||||
$application = 'stock_receipt_worker_'.$tag;
|
||||
file_put_contents($input, json_encode(['actor' => $concurrent['receiver']->id, 'order' => $concurrent['order']->id, 'payload' => $payload, 'application' => $application], JSON_THROW_ON_ERROR));
|
||||
$pipes = [];
|
||||
$process = proc_open([PHP_BINARY, base_path('tests/Support/common-receipt-worker.php'), $input], [0 => ['pipe', 'r'], 1 => ['file', $root.'/worker.stdout', 'w'], 2 => ['file', $root.'/worker.stderr', 'w']], $pipes, base_path());
|
||||
$this->assertIsResource($process);
|
||||
fclose($pipes[0]);
|
||||
$deadline = microtime(true) + 10;
|
||||
$wait = null;
|
||||
$parent = (int) DB::selectOne('SELECT pg_backend_pid() AS pid')->pid;
|
||||
do {
|
||||
DB::select('SELECT pg_stat_clear_snapshot()');
|
||||
$wait = DB::selectOne("SELECT wait_event,to_json(pg_blocking_pids(pid)) AS blockers FROM pg_stat_activity WHERE application_name=? AND wait_event_type='Lock'", [$application]);
|
||||
if (! $wait) {
|
||||
usleep(25000);
|
||||
}
|
||||
} while (! $wait && microtime(true) < $deadline);
|
||||
$this->assertNotNull($wait);
|
||||
$this->assertContains($parent, json_decode($wait->blockers, true));
|
||||
DB::commit();
|
||||
$deadline = microtime(true) + 15;
|
||||
do {
|
||||
$status = proc_get_status($process);
|
||||
if (! $status['running']) {
|
||||
break;
|
||||
}usleep(25000);
|
||||
} while (microtime(true) < $deadline);
|
||||
$this->assertFalse($status['running']);
|
||||
$exit = proc_close($process);
|
||||
$process = null;
|
||||
if ($exit === -1) {
|
||||
$exit = $status['exitcode'];
|
||||
}$this->assertSame(0, $exit);
|
||||
$second = json_decode(file_get_contents($input.'.result'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$this->assertSame(200, $second['status']);
|
||||
$this->assertSame($winner->id, $second['receipt_id']);
|
||||
$this->assertSame(1, GoodsReceipt::query()->where('purchase_order_id', $concurrent['order']->id)->count());
|
||||
$this->assertSame(1, StockMovement::query()->whereIn('goods_receipt_item_id', $winner->items->pluck('id'))->count());
|
||||
} finally {
|
||||
if (is_resource($process)) {
|
||||
proc_terminate($process);
|
||||
proc_close($process);
|
||||
}while (DB::transactionLevel() > 0) {
|
||||
DB::rollBack();
|
||||
}
|
||||
}
|
||||
file_put_contents($root.'/receipt-results.json', json_encode(['identity' => $i, 'physical_accepted_milli' => 4000, 'rejected_milli' => 2000, 'movement_count_main' => 1,
|
||||
'source_version_stale_refused' => true, 'core_replay_same_movement' => true, 'fault_atomic_and_recovered' => true, 'concurrency' => ['actual_lock_wait' => true, 'wait_event' => $wait->wait_event, 'same_receipt' => true, 'one_movement' => true],
|
||||
'link' => ['tenant' => (int) $f['tenant']->id, 'warehouse' => (int) $f['warehouse']->id, 'item' => (int) $f['stock']->id, 'movement' => (int) $movement->id, 'reference' => $movement->snapshot['reference']],
|
||||
'writer_manifest_sha256' => hash_file('sha256',base_path('packages/inventory-write/releases/0.1.0/manifest.json'))], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,12 +10,15 @@ final class CommonStockReadTest extends TestCase
|
||||
{
|
||||
public function test_authenticated_native_composition_and_common_reader(): void
|
||||
{
|
||||
$run=(string)getenv('SGF_ISOLATED_REGRESSION_RUN');
|
||||
$this->assertMatchesRegularExpression('/^[a-f0-9]{12}$/D',$run);
|
||||
$identity=DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
$this->assertMatchesRegularExpression('/^stock_read_compras_([a-f0-9]{12})$/D',$identity->name);
|
||||
$tag=substr($identity->name,-12);
|
||||
$this->assertSame('stock_read_qa_'.$tag,$identity->role);$this->assertSame(55439,(int)$identity->port);$this->assertSame('sgf_modular_regression_'.$run,$identity->cluster);
|
||||
skipUnlessIsolatedPostgres($this);
|
||||
$run = (string) getenv('SGF_ISOLATED_REGRESSION_RUN');
|
||||
$this->assertMatchesRegularExpression('/^[a-f0-9]{12}$/D', $run);
|
||||
$identity = DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
$this->assertMatchesRegularExpression('/^stock_read_compras_([a-f0-9]{12})$/D', $identity->name);
|
||||
$tag = substr($identity->name, -12);
|
||||
$this->assertSame('stock_read_qa_'.$tag, $identity->role);
|
||||
$this->assertSame(55439, (int) $identity->port);
|
||||
$this->assertSame('sgf_modular_regression_'.$run, $identity->cluster);
|
||||
// Fresh, dedicated QA database only. Never migrate/reset any existing host.
|
||||
$this->assertFalse(DB::getSchemaBuilder()->hasTable('users'));
|
||||
DB::transaction(function () {
|
||||
@@ -26,9 +29,9 @@ final class CommonStockReadTest extends TestCase
|
||||
DB::statement('CREATE TABLE organization_profiles(id bigint PRIMARY KEY,tenant_id bigint,name text,permissions jsonb,work_contexts jsonb)');
|
||||
DB::statement('CREATE TABLE organization_memberships(id bigint PRIMARY KEY,tenant_id bigint,user_id bigint,profile_id bigint,expires_at timestamp,maintenance boolean)');
|
||||
});
|
||||
$actor=User::forceCreate(['tenant_id'=>77,'purchasing_role'=>'warehouse','name'=>'Synthetic warehouse','email'=>'stock@example.test','password'=>bin2hex(random_bytes(16))]);
|
||||
$denied=User::forceCreate(['tenant_id'=>77,'purchasing_role'=>'requester','name'=>'Synthetic requester','email'=>'request@example.test','password'=>bin2hex(random_bytes(16))]);
|
||||
$schema='sgf_stock_read_'.bin2hex(random_bytes(6));
|
||||
$actor = User::forceCreate(['tenant_id' => 77, 'purchasing_role' => 'warehouse', 'name' => 'Synthetic warehouse', 'email' => 'stock@example.test', 'password' => bin2hex(random_bytes(16))]);
|
||||
$denied = User::forceCreate(['tenant_id' => 77, 'purchasing_role' => 'requester', 'name' => 'Synthetic requester', 'email' => 'request@example.test', 'password' => bin2hex(random_bytes(16))]);
|
||||
$schema = 'sgf_stock_read_'.bin2hex(random_bytes(6));
|
||||
DB::transaction(function () use ($schema) {
|
||||
DB::statement("CREATE SCHEMA $schema");
|
||||
DB::statement("CREATE TABLE $schema.stock_items(id bigint PRIMARY KEY,tenant_id bigint,code text,name text,unit text)");
|
||||
@@ -45,41 +48,57 @@ final class CommonStockReadTest extends TestCase
|
||||
DB::statement("CREATE FUNCTION $schema.immutable() RETURNS trigger LANGUAGE plpgsql AS 'BEGIN RAISE EXCEPTION ''Inventory ledger is append-only''; END'");
|
||||
DB::statement("CREATE TRIGGER immutable BEFORE UPDATE OR DELETE ON $schema.stock_movements FOR EACH ROW EXECUTE FUNCTION $schema.immutable()");
|
||||
});
|
||||
$binding=['schema'=>$schema,'source_tenant_id'=>77,'warehouse_ids'=>[11,12],'append_only'=>true];
|
||||
$key='77:'.$actor->id;config(['stock_read.synthetic_sources.'.$key=>$binding]);
|
||||
$binding = ['schema' => $schema, 'source_tenant_id' => 77, 'warehouse_ids' => [11, 12], 'append_only' => true];
|
||||
$key = '77:'.$actor->id;
|
||||
config(['stock_read.synthetic_sources.'.$key => $binding]);
|
||||
$this->getJson('/api/stock-read')->assertUnauthorized();
|
||||
$this->actingAs($denied)->getJson('/api/stock-read')->assertForbidden();
|
||||
$this->actingAs($actor);
|
||||
$queries=[];foreach(['items','warehouses','balances','movements'] as $view)foreach([25,100] as $size)$queries[]='view='.$view.'&per_page='.$size;
|
||||
$queries=[...$queries,'view=balances&per_page=25&page=2','view=items&per_page=25&page=5','view=balances&warehouse_id=12','view=items&search=QA-000001'];
|
||||
$cases=[];
|
||||
foreach($queries as $query){
|
||||
$r=$this->getJson('/api/stock-read?'.$query)->assertOk();
|
||||
$this->assertStringNotContainsString('DO_NOT_RETURN',$r->getContent());$this->assertStringNotContainsString('Foreign',$r->getContent());$this->assertStringNotContainsString('Restricted warehouse',$r->getContent());
|
||||
$cases[$query]=['sha256'=>hash('sha256',json_encode([$r->json('rows'),$r->json('pagination')],JSON_THROW_ON_ERROR)),'total'=>$r->json('pagination.total')];
|
||||
$queries = [];
|
||||
foreach (['items', 'warehouses', 'balances', 'movements'] as $view) {
|
||||
foreach ([25, 100] as $size) {
|
||||
$queries[] = 'view='.$view.'&per_page='.$size;
|
||||
}
|
||||
}
|
||||
$snapshot=$this->getJson('/api/stock-read')->assertOk()->assertJsonPath('rows.0.physical_milli','8000')->json('snapshot');
|
||||
$this->getJson('/api/stock-read?warehouse_id=13')->assertForbidden();$this->getJson('/api/stock-read?warehouse_id=21')->assertForbidden();
|
||||
$this->getJson('/api/stock-read?tenant_id=88')->assertUnprocessable();$this->getJson('/api/stock-read?per_page=101')->assertUnprocessable();
|
||||
$queries = [...$queries, 'view=balances&per_page=25&page=2', 'view=items&per_page=25&page=5', 'view=balances&warehouse_id=12', 'view=items&search=QA-000001'];
|
||||
$cases = [];
|
||||
foreach ($queries as $query) {
|
||||
$r = $this->getJson('/api/stock-read?'.$query)->assertOk();
|
||||
$this->assertStringNotContainsString('DO_NOT_RETURN', $r->getContent());
|
||||
$this->assertStringNotContainsString('Foreign', $r->getContent());
|
||||
$this->assertStringNotContainsString('Restricted warehouse', $r->getContent());
|
||||
$cases[$query] = ['sha256' => hash('sha256', json_encode([$r->json('rows'), $r->json('pagination')], JSON_THROW_ON_ERROR)), 'total' => $r->json('pagination.total')];
|
||||
}
|
||||
$snapshot = $this->getJson('/api/stock-read')->assertOk()->assertJsonPath('rows.0.physical_milli', '8000')->json('snapshot');
|
||||
$this->getJson('/api/stock-read?warehouse_id=13')->assertForbidden();
|
||||
$this->getJson('/api/stock-read?warehouse_id=21')->assertForbidden();
|
||||
$this->getJson('/api/stock-read?tenant_id=88')->assertUnprocessable();
|
||||
$this->getJson('/api/stock-read?per_page=101')->assertUnprocessable();
|
||||
$this->getJson('/api/stock-read?snapshot=invalid')->assertConflict();
|
||||
DB::table($schema.'.stock_movements')->insert(['tenant_id'=>77,'stock_item_id'=>1,'warehouse_id'=>11,'quantity_milli'=>-1000,'movement_type'=>'issue','snapshot'=>'{}','moved_at'=>now()]);
|
||||
DB::table($schema.'.stock_movements')->insert(['tenant_id' => 77, 'stock_item_id' => 1, 'warehouse_id' => 11, 'quantity_milli' => -1000, 'movement_type' => 'issue', 'snapshot' => '{}', 'moved_at' => now()]);
|
||||
$this->getJson('/api/stock-read?snapshot='.urlencode($snapshot))->assertConflict();
|
||||
$this->getJson('/api/stock-read')->assertOk()->assertJsonPath('rows.0.physical_milli','7000');
|
||||
$this->getJson('/api/stock-read')->assertOk()->assertJsonPath('rows.0.physical_milli', '7000');
|
||||
// Exercise configured native permissions too, without inventing a new right.
|
||||
DB::table('organization_access')->insert(['tenant_id'=>77,'active'=>true]);
|
||||
DB::table('organization_profiles')->insert(['id'=>1,'tenant_id'=>77,'name'=>'Synthetic warehouse profile','permissions'=>'["warehouse"]','work_contexts'=>'[]']);
|
||||
DB::table('organization_memberships')->insert(['id'=>1,'tenant_id'=>77,'user_id'=>$actor->id,'profile_id'=>1,'maintenance'=>false]);
|
||||
DB::table('organization_access')->insert(['tenant_id' => 77, 'active' => true]);
|
||||
DB::table('organization_profiles')->insert(['id' => 1, 'tenant_id' => 77, 'name' => 'Synthetic warehouse profile', 'permissions' => '["warehouse"]', 'work_contexts' => '[]']);
|
||||
DB::table('organization_memberships')->insert(['id' => 1, 'tenant_id' => 77, 'user_id' => $actor->id, 'profile_id' => 1, 'maintenance' => false]);
|
||||
$this->getJson('/api/stock-read')->assertOk();
|
||||
DB::table('organization_profiles')->where('id',1)->update(['permissions'=>'["requester"]']);
|
||||
DB::table('organization_profiles')->where('id', 1)->update(['permissions' => '["requester"]']);
|
||||
$this->getJson('/api/stock-read')->assertForbidden();
|
||||
DB::table('organization_profiles')->where('id',1)->update(['permissions'=>'["warehouse"]']);
|
||||
DB::table('organization_profiles')->where('id', 1)->update(['permissions' => '["warehouse"]']);
|
||||
$this->getJson('/api/stock-read')->assertOk();
|
||||
config(['stock_read.synthetic_sources.'.$key=>null]);$this->getJson('/api/stock-read')->assertStatus(503)->assertJsonPath('status','unavailable');
|
||||
config(['stock_read.synthetic_sources.'.$key=>array_replace($binding,['source_tenant_id'=>88])]);$this->getJson('/api/stock-read')->assertStatus(503);
|
||||
config(['stock_read.synthetic_sources.'.$key=>$binding]);$this->getJson('/api/stock-read')->assertOk();
|
||||
$output=getenv('STOCK_READ_COMPOSITION_OUTPUT');$root=realpath((string)getenv('STOCK_READ_COMPOSITION_ROOT'));
|
||||
if(!$output||!$root||realpath(dirname($output))!==$root)throw new \RuntimeException('Unexpected private proof directory');
|
||||
file_put_contents($output,json_encode(['identity'=>$identity,'cases'=>$cases,'native_snapshot'=>$snapshot,'native_roles_and_profiles_revalidated'=>true,
|
||||
'warehouse_isolation'=>true,'stale_snapshot_refused'=>true,'unknown_source_refused'=>true,'package_manifest_sha256'=>config('stock_read.package_manifest_sha256')],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
config(['stock_read.synthetic_sources.'.$key => null]);
|
||||
$this->getJson('/api/stock-read')->assertStatus(503)->assertJsonPath('status', 'unavailable');
|
||||
config(['stock_read.synthetic_sources.'.$key => array_replace($binding, ['source_tenant_id' => 88])]);
|
||||
$this->getJson('/api/stock-read')->assertStatus(503);
|
||||
config(['stock_read.synthetic_sources.'.$key => $binding]);
|
||||
$this->getJson('/api/stock-read')->assertOk();
|
||||
$output = getenv('STOCK_READ_COMPOSITION_OUTPUT');
|
||||
$root = realpath((string) getenv('STOCK_READ_COMPOSITION_ROOT'));
|
||||
if (! $output || ! $root || realpath(dirname($output)) !== $root) {
|
||||
throw new \RuntimeException('Unexpected private proof directory');
|
||||
}
|
||||
file_put_contents($output, json_encode(['identity' => $identity, 'cases' => $cases, 'native_snapshot' => $snapshot, 'native_roles_and_profiles_revalidated' => true,
|
||||
'warehouse_isolation' => true, 'stale_snapshot_refused' => true, 'unknown_source_refused' => true, 'package_manifest_sha256' => config('stock_read.package_manifest_sha256')], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\AuditLog;
|
||||
use App\Models\Budget;
|
||||
use App\Models\BudgetEntry;
|
||||
use App\Models\CostCenter;
|
||||
use App\Models\Department;
|
||||
use App\Models\ExternalPayment;
|
||||
use App\Models\GoodsReceipt;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\StockItem;
|
||||
use App\Models\StockMovement;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\ExternalPaymentWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/*
|
||||
| Circuito do núcleo da v1, ponta a ponta e só pelas rotas HTTP reais:
|
||||
| requisição → submissão → aprovação → 3 cotações com 2 avaliações → adjudicação →
|
||||
| aprovação do valor final → ordem → recepção → factura → validação →
|
||||
| dados bancários (2 validações) → pagamento externo → conferência.
|
||||
| Cada passo é feito por uma pessoa diferente sempre que as regras o exigem.
|
||||
*/
|
||||
test('the v1 core purchasing circuit runs end to end through the real routes', function () {
|
||||
config(['modules.enabled' => ['pessoas' => false, 'armazem_avancado' => false, 'fornecimento' => false]]);
|
||||
$tenant = Tenant::query()->create(['name' => 'Empresa do circuito']);
|
||||
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações']);
|
||||
$centre = CostCenter::query()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'code' => 'OPS', 'name' => 'Operações']);
|
||||
$people = [];
|
||||
foreach (['requester' => PurchasingRole::Requester, 'head' => PurchasingRole::DepartmentHead, 'buyer' => PurchasingRole::Procurement,
|
||||
'secondBuyer' => PurchasingRole::Procurement, 'finance' => PurchasingRole::Finance, 'secondFinance' => PurchasingRole::Finance,
|
||||
'thirdFinance' => PurchasingRole::Finance, 'receiver' => PurchasingRole::Warehouse] as $key => $role) {
|
||||
$people[$key] = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'purchasing_role' => $role]);
|
||||
}
|
||||
Budget::query()->create(['tenant_id' => $tenant->id, 'cost_center_id' => $centre->id, 'year' => now()->year, 'amount_minor' => 100000,
|
||||
'includes_tax' => true, 'created_by' => $people['finance']->id, 'approved_by' => $people['secondFinance']->id, 'reason' => 'Dotação fictícia do circuito']);
|
||||
|
||||
// 1. Requisição, submissão e aprovação pelo chefe do departamento.
|
||||
$this->actingAs($people['requester'])->post('/requisicoes', [
|
||||
'cost_center_id' => $centre->id, 'priority' => 'normal', 'needed_by' => now()->addWeek()->format('Y-m-d'),
|
||||
'justification' => 'Material necessário para as operações do departamento.',
|
||||
'items' => [['description' => 'Resmas de papel A4', 'category' => 'Material', 'purchase_type' => 'consumable', 'quantity' => '2', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0']],
|
||||
])->assertSessionHasNoErrors()->assertRedirect();
|
||||
$requisition = Requisition::query()->sole();
|
||||
$this->post('/requisicoes/'.$requisition->id.'/submeter')->assertSessionHasNoErrors()->assertRedirect();
|
||||
$this->actingAs($people['requester'])->post('/requisicoes/'.$requisition->id.'/decidir', ['decision' => 'approved'])->assertForbidden();
|
||||
$this->actingAs($people['head'])->post('/requisicoes/'.$requisition->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors()->assertRedirect();
|
||||
expect($requisition->refresh()->status)->toBe('approved')
|
||||
->and((int) BudgetEntry::query()->where('requisition_id', $requisition->id)->sum('reserved_minor'))->toBe(20000);
|
||||
|
||||
// 2. Três cotações, cada uma avaliada por duas pessoas.
|
||||
$item = $requisition->items()->sole();
|
||||
foreach (['111222333', '222333444', '333444555'] as $index => $nuit) {
|
||||
$supplier = Supplier::query()->create(['tenant_id' => $tenant->id, 'created_by' => $people['buyer']->id, 'name' => 'Fornecedor '.$index, 'nuit' => $nuit,
|
||||
'contact' => 'Contacto', 'email' => 'fornecedor'.$index.'@example.test', 'phone' => '123456789', 'address' => 'Maputo', 'category' => 'Material',
|
||||
'beneficiaries' => 'Beneficiário', 'document_references' => 'Alvará conferido.', 'diligence_notes' => 'Documentação regular no teste.',
|
||||
'status' => 'active', 'next_review' => now()->addYear()]);
|
||||
$this->actingAs($people['buyer'])->post('/requisicoes/'.$requisition->id.'/cotacoes', ['supplier_id' => $supplier->id, 'reference' => 'PROP-'.$index,
|
||||
'delivery_days' => 5, 'valid_until' => now()->addMonth()->format('Y-m-d'), 'payment_terms' => '30 dias', 'no_conflict' => true,
|
||||
'items' => [['requisition_item_id' => $item->id, 'unit_price' => (string) (100 + $index * 10)]]])->assertSessionHasNoErrors();
|
||||
$quote = Quotation::query()->latest('id')->firstOrFail();
|
||||
foreach ([$people['buyer'], $people['finance']] as $evaluator) {
|
||||
$this->actingAs($evaluator)->post('/cotacoes/'.$quote->id.'/avaliar', ['quality' => '8', 'history' => '5', 'payment' => '8',
|
||||
'comment' => 'Avaliação independente fundamentada.', 'no_conflict' => true])->assertSessionHasNoErrors();
|
||||
}
|
||||
}
|
||||
$winner = Quotation::query()->where('reference', 'PROP-0')->sole();
|
||||
|
||||
// 3. Adjudicação, aprovação do valor final por outras pessoas e emissão da ordem.
|
||||
$awardUrl = '/requisicoes/'.$requisition->id.'/adjudicacao';
|
||||
$this->actingAs($people['buyer'])->post($awardUrl, ['quotation_id' => $winner->id, 'justification' => 'Proposta com melhor pontuação técnica e comercial.',
|
||||
'delivery_date' => now()->addWeek()->format('Y-m-d'), 'delivery_location' => 'Armazém central de Maputo'])->assertSessionHasNoErrors()->assertRedirect($awardUrl);
|
||||
$award = PurchaseAward::query()->sole();
|
||||
foreach ($award->approvals()->get() as $step) {
|
||||
$approver = match ($step->role) {
|
||||
'department_head' => $people['head'], 'procurement' => $people['secondBuyer'], 'finance' => $people['thirdFinance'],
|
||||
};
|
||||
$this->actingAs($approver)->post('/adjudicacoes/'.$award->id.'/decidir', ['decision' => 'approved'])->assertSessionHasNoErrors()->assertRedirect();
|
||||
}
|
||||
$this->actingAs($people['buyer'])->post('/adjudicacoes/'.$award->id.'/emitir')->assertSessionHasNoErrors()->assertRedirect();
|
||||
$order = PurchaseOrder::query()->sole();
|
||||
expect($order->total_minor)->toBe(20000)
|
||||
->and((int) BudgetEntry::query()->where('requisition_id', $requisition->id)->sum('committed_minor'))->toBe(20000);
|
||||
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee($order->number);
|
||||
|
||||
// 4. Recepção total conforme e entrada em stock, uma única vez.
|
||||
$warehouse = Warehouse::query()->create(['tenant_id' => $tenant->id, 'created_by' => $people['receiver']->id, 'code' => 'ARM-1', 'name' => 'Armazém central']);
|
||||
$stock = StockItem::query()->create(['tenant_id' => $tenant->id, 'created_by' => $people['receiver']->id, 'code' => 'PAP-A4', 'name' => 'Resmas de papel A4', 'unit' => 'cx']);
|
||||
$receipt = ['idempotency_key' => (string) Str::uuid(), 'delivery_note' => 'GUIA-1', 'received_on' => today()->toDateString(), 'warehouse_id' => $warehouse->id,
|
||||
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'received_quantity' => '2.000', 'accepted_quantity' => '2.000', 'quality_status' => 'compliant', 'stock_item_id' => $stock->id]]];
|
||||
$this->actingAs($people['receiver'])->postJson('/ordens/'.$order->id.'/recepcoes', $receipt)->assertCreated();
|
||||
$this->postJson('/ordens/'.$order->id.'/recepcoes', $receipt)->assertOk()->assertJsonPath('created', false);
|
||||
expect(GoodsReceipt::query()->count())->toBe(1)->and((int) StockMovement::query()->sum('quantity_milli'))->toBe(2000);
|
||||
|
||||
// 5. Factura registada e validada por pessoas distintas de Finanças.
|
||||
$this->actingAs($people['secondFinance'])->post('/ordens/'.$order->id.'/facturas', ['number' => 'FT-2026-1', 'issued_on' => today()->format('Y-m-d'),
|
||||
'subtotal' => '200.00', 'tax' => '0.00', 'total' => '200.00',
|
||||
'items' => [['purchase_order_item_id' => $order->items()->sole()->id, 'quantity' => '2.000', 'unit' => 'cx', 'unit_price' => '100.00', 'tax_rate' => '0']]])
|
||||
->assertSessionHasNoErrors()->assertRedirect();
|
||||
$invoice = Invoice::query()->sole();
|
||||
$this->post('/facturas/'.$invoice->id.'/validar')->assertForbidden();
|
||||
$this->actingAs($people['thirdFinance'])->post('/facturas/'.$invoice->id.'/validar')->assertSessionHasNoErrors()->assertRedirect();
|
||||
expect($invoice->refresh()->status)->toBe('validated')
|
||||
->and((int) DB::table('budget_consumptions')->where('invoice_id', $invoice->id)->value('amount_minor'))->toBe(20000);
|
||||
|
||||
// 6. Dados bancários propostos por Procurement e validados por duas pessoas de Finanças.
|
||||
$supplier = Supplier::query()->findOrFail($order->supplier_id);
|
||||
$this->actingAs($people['buyer'])->post('/fornecedores/'.$supplier->id.'/dados-bancarios', ['previous_id' => 0, 'bank_name' => 'Banco fictício', 'country' => 'MZ',
|
||||
'currency' => 'MZN', 'beneficiary' => 'Titular de teste', 'account_identifier' => 'TEST-CIRCUIT-ACCOUNT', 'evidence_reference' => 'Evidência de teste',
|
||||
'reason' => 'Somente teste isolado'])->assertSessionHasNoErrors()->assertRedirect();
|
||||
$bank = SupplierBankDetail::query()->sole();
|
||||
foreach (['finance', 'secondFinance'] as $reviewer) {
|
||||
$this->actingAs($people[$reviewer])->post('/fornecedores/'.$supplier->id.'/dados-bancarios/'.$bank->id.'/validar',
|
||||
['decision' => 'approved', 'reason' => 'Conferência independente', 'independently_verified' => true])->assertSessionHasNoErrors();
|
||||
}
|
||||
|
||||
// 7. Pagamento externo registado e conferido por outra pessoa; a dívida fica saldada.
|
||||
$this->actingAs($people['finance'])->post('/facturas/'.$invoice->id.'/pagamentos', ['supplier_bank_detail_id' => $bank->id, 'amount' => '200.00',
|
||||
'paid_on' => today()->format('Y-m-d'), 'external_reference' => 'TRF-CIRCUITO-1', 'evidence_reference' => 'Comprovativo fictício'])
|
||||
->assertSessionHasNoErrors()->assertRedirect('/pagamentos');
|
||||
$payment = ExternalPayment::query()->sole();
|
||||
$this->post('/pagamentos/'.$payment->id.'/conferir', ['decision' => 'confirmed', 'reason' => 'Conferido', 'independently_verified' => true])->assertForbidden();
|
||||
$this->actingAs($people['thirdFinance'])->post('/pagamentos/'.$payment->id.'/conferir', ['decision' => 'confirmed', 'reason' => 'Extracto conferido', 'independently_verified' => true])
|
||||
->assertSessionHasNoErrors();
|
||||
expect($payment->refresh()->status)->toBe('confirmed')
|
||||
->and(app(ExternalPaymentWorkflow::class)->outstanding($invoice->refresh()))->toBe(0);
|
||||
|
||||
// Rasto de auditoria de cada etapa.
|
||||
expect(AuditLog::query()->where('tenant_id', $tenant->id)->distinct()->pluck('action')->all())
|
||||
->toContain('payment.confirmed')->and(AuditLog::query()->where('tenant_id', $tenant->id)->count())->toBeGreaterThan(10);
|
||||
});
|
||||
@@ -1,7 +1,5 @@
|
||||
<?php
|
||||
|
||||
test('returns a successful response', function () {
|
||||
$response = $this->get(route('home'));
|
||||
|
||||
$response->assertOk();
|
||||
test('home sends guests to the login page', function () {
|
||||
$this->get(route('home'))->assertRedirect('/login');
|
||||
});
|
||||
|
||||
@@ -68,7 +68,7 @@ test('invalid dates amounts and bank versions cannot register a payment', functi
|
||||
'negative' => $this->data['amount'] = '-1.00',
|
||||
'future' => $this->data['paid_on'] = today()->addDay()->format('Y-m-d'),
|
||||
'before_invoice' => $this->data['paid_on'] = today()->subDay()->format('Y-m-d'),
|
||||
'old_year' => $this->data['paid_on'] = today()->subYear()->format('Y-m-d'),
|
||||
'old_year' => $this->data['paid_on'] = today()->subYears(2)->format('Y-m-d'),
|
||||
'bank' => $this->data['supplier_bank_detail_id'] = PHP_INT_MAX,
|
||||
'reference' => $this->data['external_reference'] = ' ',
|
||||
'evidence' => $this->data['evidence_reference'] = ' ',
|
||||
@@ -113,6 +113,28 @@ test('loss of reviewer eligibility or supplier eligibility blocks confirmation',
|
||||
expect(fn () => confirmTestPayment($this, $payment))->toThrow(ValidationException::class);
|
||||
})->with(['reviewer', 'supplier']);
|
||||
|
||||
test('a payment from the previous year can still be registered and confirmed in the new year', function () {
|
||||
$payment = registerTestPayment($this);
|
||||
$paidOn = $this->data['paid_on'];
|
||||
$this->travelTo(now()->addYear()->startOfYear()->addDay());
|
||||
confirmTestPayment($this, $payment);
|
||||
expect($payment->refresh()->status)->toBe('confirmed')->and((string) $payment->paid_on)->toStartWith($paidOn);
|
||||
|
||||
$this->data['external_reference'] = 'TEST-EXT-NOVO-ANO';
|
||||
$this->data['amount'] = '10.00';
|
||||
$late = registerTestPayment($this);
|
||||
confirmTestPayment($this, $late);
|
||||
expect($late->refresh()->status)->toBe('confirmed')
|
||||
->and(app(ExternalPaymentWorkflow::class)->outstanding($this->f['invoice']->refresh()))->toBe(1000);
|
||||
});
|
||||
|
||||
test('payments older than the previous year cannot be confirmed', function () {
|
||||
$payment = registerTestPayment($this);
|
||||
$this->travelTo(now()->addYears(2)->startOfYear());
|
||||
expect(fn () => confirmTestPayment($this, $payment))->toThrow(ValidationException::class);
|
||||
expect($payment->refresh()->status)->toBe('pending');
|
||||
});
|
||||
|
||||
test('rejected evidence leaves invoice outstanding and decision cannot be changed', function () {
|
||||
$payment = registerTestPayment($this);
|
||||
confirmTestPayment($this, $payment, 'rejected');
|
||||
|
||||
@@ -133,7 +133,7 @@ test('the documentary VAT rate requires explicit classification and valuation be
|
||||
});
|
||||
|
||||
test('the official second supplement supplies only its eleven ICE positions and explicit two-year period', function () {
|
||||
$path = base_path('tmp/pdfs/import-legal-source-review-20261128/law7-2025-official-second-supplement.pdf');
|
||||
$path = base_path('tests/Fixtures/legal/law7-2025-official-second-supplement.pdf');
|
||||
if (! is_file($path)) {
|
||||
test()->markTestSkipped('The separately retained official second supplement is required.');
|
||||
}
|
||||
|
||||
@@ -136,7 +136,8 @@ test('an administrator losing eligibility before publication blocks the second s
|
||||
expect($policy->refresh()->status)->toBe('pending');
|
||||
});
|
||||
|
||||
test('public investment example contains no company policies', function () {
|
||||
test('former public investment example redirects to the authenticated policies module', function () {
|
||||
auth()->forgetGuards();
|
||||
$this->get('/consulta/investimento')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'investment')->where('auth.user', null)->missing('policies')->missing('reviews'));
|
||||
$this->get('/consulta/investimento')->assertRedirect('/regras-investimento');
|
||||
$this->get('/regras-investimento')->assertRedirect('/login');
|
||||
});
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\{Invoice, Tenant, User};
|
||||
use App\Services\{ExternalPaymentWorkflow, SupplierPayables};
|
||||
use Illuminate\Support\Facades\{Artisan, DB};
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\ExternalPaymentWorkflow;
|
||||
use App\Services\SupplierPayables;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tempo\Finance\Payables\Payables;
|
||||
use Tests\TestCase;
|
||||
@@ -14,69 +18,266 @@ require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
|
||||
final class NativePayablePageTest extends TestCase
|
||||
{
|
||||
private array $f;private User $reader;private string $instance;
|
||||
protected function setUp():void
|
||||
private array $f;
|
||||
|
||||
private User $reader;
|
||||
|
||||
private string $instance;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();$i=DB::selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");$this->assertMatchesRegularExpression('/^compras_receipts_test_[a-f0-9]{12}$/D',$i->db);$this->assertSame('stock_receipt_qa_'.substr($i->db,-12),$i->role);$this->assertSame(55439,(int)$i->port);$this->assertSame('sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'),$i->cluster);
|
||||
if(!DB::getSchemaBuilder()->hasTable('users'))Artisan::call('migrate',['--force'=>true]);
|
||||
$this->f=\paymentFixture();$this->instance='native-page-'.$this->f['tenant']->id;config(['common-payables.enabled'=>true,'common-payables.history_enabled'=>true,'common-payables.paged_read_enabled'=>true,'common-payables.source_instance'=>$this->instance]);
|
||||
$this->reader=User::factory()->create(['tenant_id'=>$this->f['tenant']->id,'purchasing_role'=>PurchasingRole::Finance]);
|
||||
foreach([[$this->f['author'],['view','prepare','validate']],[$this->f['validator'],['view','prepare','validate']],[$this->reader,['view']]] as [$u,$actions])foreach($actions as $a)DB::table('pa_access')->insert(['tenant_id'=>$u->tenant_id,'company_id'=>0,'unit_id'=>0,'user_id'=>$u->id,'person'=>'native-page-person-'.$u->id,'action'=>$a]);
|
||||
foreach([['30.00','confirmed'],['10.00','pending'],['5.00','rejected']] as [$amount,$status]){$this->actingAs($this->f['author']);$p=app(ExternalPaymentWorkflow::class)->register($this->f['author'],$this->f['invoice'],[...$this->f['payment_data'],'amount'=>$amount,'external_reference'=>'NATIVE-PAGE-'.$status]);if($status!=='pending'){$this->actingAs($this->f['validator']);app(ExternalPaymentWorkflow::class)->review($this->f['validator'],$p,$status,'Synthetic independent original payment review.');}}
|
||||
$this->actingAs($this->f['author']);$p=app(SupplierPayables::class)->engine($this->f['author'])->command('prepare_history',$this->f['invoice']->id,'Synthetic original history proposal.',(string)Str::uuid());$this->actingAs($this->f['validator']);app(SupplierPayables::class)->engine($this->f['validator'])->command('validate_history',$p['proposal_id'],'Synthetic distinct original history review.',(string)Str::uuid());$this->actingAs($this->reader);
|
||||
parent::setUp();
|
||||
skipUnlessIsolatedPostgres($this);
|
||||
$i = DB::selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
$this->assertMatchesRegularExpression('/^compras_receipts_test_[a-f0-9]{12}$/D', $i->db);
|
||||
$this->assertSame('stock_receipt_qa_'.substr($i->db, -12), $i->role);
|
||||
$this->assertSame(55439, (int) $i->port);
|
||||
$this->assertSame('sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'), $i->cluster);
|
||||
if (! DB::getSchemaBuilder()->hasTable('users')) {
|
||||
Artisan::call('migrate', ['--force' => true]);
|
||||
}
|
||||
$this->f = \paymentFixture();
|
||||
$this->instance = 'native-page-'.$this->f['tenant']->id;
|
||||
config(['common-payables.enabled' => true, 'common-payables.history_enabled' => true, 'common-payables.paged_read_enabled' => true, 'common-payables.source_instance' => $this->instance]);
|
||||
$this->reader = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
foreach ([[$this->f['author'], ['view', 'prepare', 'validate']], [$this->f['validator'], ['view', 'prepare', 'validate']], [$this->reader, ['view']]] as [$u,$actions]) {
|
||||
foreach ($actions as $a) {
|
||||
DB::table('pa_access')->insert(['tenant_id' => $u->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $u->id, 'person' => 'native-page-person-'.$u->id, 'action' => $a]);
|
||||
}
|
||||
}
|
||||
foreach ([['30.00', 'confirmed'], ['10.00', 'pending'], ['5.00', 'rejected']] as [$amount,$status]) {
|
||||
$this->actingAs($this->f['author']);
|
||||
$p = app(ExternalPaymentWorkflow::class)->register($this->f['author'], $this->f['invoice'], [...$this->f['payment_data'], 'amount' => $amount, 'external_reference' => 'NATIVE-PAGE-'.$status]);
|
||||
if ($status !== 'pending') {
|
||||
$this->actingAs($this->f['validator']);
|
||||
app(ExternalPaymentWorkflow::class)->review($this->f['validator'], $p, $status, 'Synthetic independent original payment review.');
|
||||
}
|
||||
}
|
||||
$this->actingAs($this->f['author']);
|
||||
$p = app(SupplierPayables::class)->engine($this->f['author'])->command('prepare_history', $this->f['invoice']->id, 'Synthetic original history proposal.', (string) Str::uuid());
|
||||
$this->actingAs($this->f['validator']);
|
||||
app(SupplierPayables::class)->engine($this->f['validator'])->command('validate_history', $p['proposal_id'], 'Synthetic distinct original history review.', (string) Str::uuid());
|
||||
$this->actingAs($this->reader);
|
||||
}
|
||||
private function service():SupplierPayables{return app(SupplierPayables::class);}
|
||||
private function clones(int $count):void
|
||||
|
||||
private function service(): SupplierPayables
|
||||
{
|
||||
$row=DB::table('invoices')->where('id',$this->f['invoice']->id)->first();$line=(array)DB::table('invoice_items')->where('invoice_id',$row->id)->first();unset($line['id']);$audit=(array)DB::table('audit_logs')->where('tenant_id',$row->tenant_id)->where('action','invoice.validated')->where('after->invoice_id',$row->id)->first();unset($audit['id']);
|
||||
for($n=1;$n<=$count;$n++){$copy=(array)$row;unset($copy['id']);$copy['number']='PAGE-'.str_pad((string)$n,5,'0',STR_PAD_LEFT);$snapshot=json_decode($copy['snapshot'],true);$snapshot['supplier']['name']=$n%2===0?'Page Alpha':'Page Beta';$copy['snapshot']=json_encode($snapshot,JSON_THROW_ON_ERROR);$id=DB::table('invoices')->insertGetId($copy);DB::table('invoice_items')->insert(array_replace($line,['invoice_id'=>$id]));$after=json_decode($audit['after'],true);$after['invoice_id']=$id;DB::table('audit_logs')->insert(array_replace($audit,['after'=>json_encode($after,JSON_THROW_ON_ERROR)]));}
|
||||
return app(SupplierPayables::class);
|
||||
}
|
||||
private function positions(array $data):string{$rows=$data['obligations'];usort($rows,fn($a,$b)=>$a['id']<=>$b['id']);return Payables::canonical($rows);}
|
||||
private function duplicateRegistration():void
|
||||
|
||||
private function clones(int $count): void
|
||||
{
|
||||
$p=DB::table('external_payments')->where('tenant_id',$this->f['tenant']->id)->where('invoice_id',$this->f['invoice']->id)->where('status','confirmed')->first();$row=(array)DB::table('audit_logs')->where('tenant_id',$p->tenant_id)->where('action','payment.registered')->where('after->payment_id',$p->id)->first();unset($row['id']);DB::table('audit_logs')->insert($row);
|
||||
$row = DB::table('invoices')->where('id', $this->f['invoice']->id)->first();
|
||||
$line = (array) DB::table('invoice_items')->where('invoice_id', $row->id)->first();
|
||||
unset($line['id']);
|
||||
$audit = (array) DB::table('audit_logs')->where('tenant_id', $row->tenant_id)->where('action', 'invoice.validated')->where('after->invoice_id', $row->id)->first();
|
||||
unset($audit['id']);
|
||||
for ($n = 1; $n <= $count; $n++) {
|
||||
$copy = (array) $row;
|
||||
unset($copy['id']);
|
||||
$copy['number'] = 'PAGE-'.str_pad((string) $n, 5, '0', STR_PAD_LEFT);
|
||||
$snapshot = json_decode($copy['snapshot'], true);
|
||||
$snapshot['supplier']['name'] = $n % 2 === 0 ? 'Page Alpha' : 'Page Beta';
|
||||
$copy['snapshot'] = json_encode($snapshot, JSON_THROW_ON_ERROR);
|
||||
$id = DB::table('invoices')->insertGetId($copy);
|
||||
DB::table('invoice_items')->insert(array_replace($line, ['invoice_id' => $id]));
|
||||
$after = json_decode($audit['after'], true);
|
||||
$after['invoice_id'] = $id;
|
||||
DB::table('audit_logs')->insert(array_replace($audit, ['after' => json_encode($after, JSON_THROW_ON_ERROR)]));
|
||||
}
|
||||
}
|
||||
public function test_native_page_matches_live_documents_and_existing_financial_positions():void
|
||||
|
||||
private function positions(array $data): string
|
||||
{
|
||||
$old=$this->service()->engine($this->reader)->listing([$this->f['invoice']->id]);$new=$this->service()->listing($this->reader);$this->assertSame(Payables::canonical($old['documents']),Payables::canonical($new['documents']));$this->assertSame($this->positions($old),$this->positions($new));$o=$new['obligations'][0];$this->assertSame(6000,$o['principal_minor']);$this->assertSame(3000,$o['balance_minor']);$this->assertSame(1000,$o['pending_payments_minor']);$this->assertSame(500,$o['rejected_payments_minor']);$this->assertNull($o['due_on']);$this->assertFalse($new['permissions']['prepare']);$this->getJson('/api/supplier-payables')->assertOk()->assertJsonPath('pagination.documents.total',1)->assertJsonPath('obligations.0.balance_minor',3000);
|
||||
$rows = $data['obligations'];
|
||||
usort($rows, fn ($a, $b) => $a['id'] <=> $b['id']);
|
||||
|
||||
return Payables::canonical($rows);
|
||||
}
|
||||
public function test_native_invoice_filter_survives_document_and_evidence_pagination():void
|
||||
|
||||
private function duplicateRegistration(): void
|
||||
{
|
||||
$this->clones(50);$a=$this->getJson('/api/supplier-payables')->assertOk()->assertJsonPath('pagination.documents.total',51)->assertJsonCount(25,'documents')->json('documents');$b=$this->getJson('/api/supplier-payables?page=2')->assertOk()->assertJsonCount(25,'documents')->json('documents');$this->assertEmpty(array_intersect(array_column($a,'local_id'),array_column($b,'local_id')));$this->assertGreaterThan($b[0]['local_id'],$a[24]['local_id']);
|
||||
$id=$this->f['invoice']->id;$this->getJson('/api/supplier-payables?invoice='.$id)->assertOk()->assertJsonPath('documents.0.local_id',$id)->assertJsonPath('obligations.0.balance_minor',3000)->assertJsonPath('listing_query.invoice',$id);$this->getJson('/api/supplier-payables?recognition=recognised')->assertOk()->assertJsonPath('pagination.documents.total',1);$this->getJson('/api/supplier-payables?recognition=unrecognised&per_page=100')->assertOk()->assertJsonPath('pagination.documents.total',50)->assertJsonCount(0,'obligations');$this->getJson('/api/supplier-payables?q=Page%20Alpha')->assertOk()->assertJsonPath('pagination.documents.total',25);$this->getJson('/api/supplier-payables?q=%25')->assertOk()->assertJsonPath('pagination.documents.total',0);
|
||||
$page=$this->get('/obrigacoes-fornecedores?invoice='.$id)->assertOk()->getContent();$this->assertTrue(str_contains($page,'action="/obrigacoes-fornecedores"'),'Native page action retained');$this->assertTrue(str_contains($page,'name="invoice"'),'Invoice filter retained in search form');$this->assertTrue(str_contains($page,'value="'.$id.'"'),'Original invoice selection retained');
|
||||
$p = DB::table('external_payments')->where('tenant_id', $this->f['tenant']->id)->where('invoice_id', $this->f['invoice']->id)->where('status', 'confirmed')->first();
|
||||
$row = (array) DB::table('audit_logs')->where('tenant_id', $p->tenant_id)->where('action', 'payment.registered')->where('after->payment_id', $p->id)->first();
|
||||
unset($row['id']);
|
||||
DB::table('audit_logs')->insert($row);
|
||||
}
|
||||
public function test_native_page_batches_sources_and_payment_audits_without_writer_locks():void
|
||||
|
||||
public function test_native_page_matches_live_documents_and_existing_financial_positions(): void
|
||||
{
|
||||
$this->clones(50);$queries=[];$capture=true;DB::listen(function($q)use(&$queries,&$capture){if($capture)$queries[]=$q->sql;});$this->service()->listing($this->reader);$capture=false;$small=count($queries);$this->assertEmpty(array_filter($queries,fn($q)=>str_contains(strtolower($q),'for update')));$queries=[];$capture=true;$data=$this->service()->listing($this->reader,null,['per_page'=>100]);$capture=false;$this->assertCount(51,$data['documents']);$this->assertSame($small+2,count($queries),'Only two nonempty proposal/event data queries are added when original recognised invoice enters the window');$this->assertCount(2,array_filter($queries,fn($q)=>str_contains($q,'from "audit_logs"')));$this->assertCount(1,array_filter($queries,fn($q)=>str_contains($q,'from "external_payments"')));
|
||||
file_put_contents((string)getenv('STOCK_RECEIPT_ROOT').'/native-page-query.json',json_encode(['documents'=>51,'page_sizes'=>[25,100],'page25_queries'=>$small,'page100_queries'=>count($queries),'extra_queries_reason'=>'Proposal/event data SELECTs skipped by paginator for empty evidence windows.','audit_selects'=>2,'payment_selects'=>1,'no_writer_lock'=>true],JSON_PRETTY_PRINT));
|
||||
$old = $this->service()->engine($this->reader)->listing([$this->f['invoice']->id]);
|
||||
$new = $this->service()->listing($this->reader);
|
||||
$this->assertSame(Payables::canonical($old['documents']), Payables::canonical($new['documents']));
|
||||
$this->assertSame($this->positions($old), $this->positions($new));
|
||||
$o = $new['obligations'][0];
|
||||
$this->assertSame(6000, $o['principal_minor']);
|
||||
$this->assertSame(3000, $o['balance_minor']);
|
||||
$this->assertSame(1000, $o['pending_payments_minor']);
|
||||
$this->assertSame(500, $o['rejected_payments_minor']);
|
||||
$this->assertNull($o['due_on']);
|
||||
$this->assertFalse($new['permissions']['prepare']);
|
||||
$this->getJson('/api/supplier-payables')->assertOk()->assertJsonPath('pagination.documents.total', 1)->assertJsonPath('obligations.0.balance_minor', 3000);
|
||||
}
|
||||
public function test_native_page_refuses_tenant_leaks_revoked_rights_and_stale_role():void
|
||||
|
||||
public function test_native_invoice_filter_survives_document_and_evidence_pagination(): void
|
||||
{
|
||||
DB::table('pa_access')->where('user_id',$this->reader->id)->delete();$this->getJson('/api/supplier-payables')->assertForbidden();DB::table('pa_access')->insert(['tenant_id'=>$this->reader->tenant_id,'company_id'=>0,'unit_id'=>0,'user_id'=>$this->reader->id,'person'=>'native-page-person-'.$this->reader->id,'action'=>'view']);DB::table('users')->where('id',$this->reader->id)->update(['purchasing_role'=>'requester']);$this->getJson('/api/supplier-payables')->assertForbidden();DB::table('users')->where('id',$this->reader->id)->update(['purchasing_role'=>'finance']);
|
||||
$tenant=Tenant::query()->create(['name'=>'Foreign native page tenant']);$other=User::factory()->create(['tenant_id'=>$tenant->id,'purchasing_role'=>PurchasingRole::Finance]);DB::table('pa_access')->insert(['tenant_id'=>$tenant->id,'company_id'=>0,'unit_id'=>0,'user_id'=>$other->id,'person'=>'foreign-native-page','action'=>'view']);$this->actingAs($other);$this->getJson('/api/supplier-payables')->assertOk()->assertJsonPath('pagination.documents.total',0)->assertJsonCount(0,'obligations');$this->getJson('/api/supplier-payables?invoice='.$this->f['invoice']->id)->assertNotFound();
|
||||
$this->clones(50);
|
||||
$a = $this->getJson('/api/supplier-payables')->assertOk()->assertJsonPath('pagination.documents.total', 51)->assertJsonCount(25, 'documents')->json('documents');
|
||||
$b = $this->getJson('/api/supplier-payables?page=2')->assertOk()->assertJsonCount(25, 'documents')->json('documents');
|
||||
$this->assertEmpty(array_intersect(array_column($a, 'local_id'), array_column($b, 'local_id')));
|
||||
$this->assertGreaterThan($b[0]['local_id'], $a[24]['local_id']);
|
||||
$id = $this->f['invoice']->id;
|
||||
$this->getJson('/api/supplier-payables?invoice='.$id)->assertOk()->assertJsonPath('documents.0.local_id', $id)->assertJsonPath('obligations.0.balance_minor', 3000)->assertJsonPath('listing_query.invoice', $id);
|
||||
$this->getJson('/api/supplier-payables?recognition=recognised')->assertOk()->assertJsonPath('pagination.documents.total', 1);
|
||||
$this->getJson('/api/supplier-payables?recognition=unrecognised&per_page=100')->assertOk()->assertJsonPath('pagination.documents.total', 50)->assertJsonCount(0, 'obligations');
|
||||
$this->getJson('/api/supplier-payables?q=Page%20Alpha')->assertOk()->assertJsonPath('pagination.documents.total', 25);
|
||||
$this->getJson('/api/supplier-payables?q=%25')->assertOk()->assertJsonPath('pagination.documents.total', 0);
|
||||
$page = $this->get('/obrigacoes-fornecedores?invoice='.$id)->assertOk()->getContent();
|
||||
$this->assertTrue(str_contains($page, 'action="/obrigacoes-fornecedores"'), 'Native page action retained');
|
||||
$this->assertTrue(str_contains($page, 'name="invoice"'), 'Invoice filter retained in search form');
|
||||
$this->assertTrue(str_contains($page, 'value="'.$id.'"'), 'Original invoice selection retained');
|
||||
}
|
||||
public function test_native_audit_changes_require_new_conference_without_using_read_snapshots():void
|
||||
|
||||
public function test_native_page_batches_sources_and_payment_audits_without_writer_locks(): void
|
||||
{
|
||||
$this->assertSame(3000,$this->service()->listing($this->reader)['obligations'][0]['balance_minor']);$this->duplicateRegistration();$new=$this->service()->listing($this->reader);$old=$this->service()->engine($this->reader)->listing([$this->f['invoice']->id]);$this->assertSame($this->positions($old),$this->positions($new));$this->assertNull($new['obligations'][0]['balance_minor']);$this->assertTrue($new['obligations'][0]['source_conflict']);$this->actingAs($this->f['author']);$r=$this->service()->engine($this->f['author'])->command('prepare_history',$this->f['invoice']->id,'Synthetic new audit after read.',(string)Str::uuid());$this->assertSame('conflict',$r['state']);$this->assertSame(1,DB::table('pa_obligations')->where('tenant_id',$this->f['tenant']->id)->count());
|
||||
$this->clones(50);
|
||||
$queries = [];
|
||||
$capture = true;
|
||||
DB::listen(function ($q) use (&$queries, &$capture) {
|
||||
if ($capture) {
|
||||
$queries[] = $q->sql;
|
||||
}
|
||||
});
|
||||
$this->service()->listing($this->reader);
|
||||
$capture = false;
|
||||
$small = count($queries);
|
||||
$this->assertEmpty(array_filter($queries, fn ($q) => str_contains(strtolower($q), 'for update')));
|
||||
$queries = [];
|
||||
$capture = true;
|
||||
$data = $this->service()->listing($this->reader, null, ['per_page' => 100]);
|
||||
$capture = false;
|
||||
$this->assertCount(51, $data['documents']);
|
||||
$this->assertSame($small + 2, count($queries), 'Only two nonempty proposal/event data queries are added when original recognised invoice enters the window');
|
||||
$this->assertCount(2, array_filter($queries, fn ($q) => str_contains($q, 'from "audit_logs"')));
|
||||
$this->assertCount(1, array_filter($queries, fn ($q) => str_contains($q, 'from "external_payments"')));
|
||||
file_put_contents((string) getenv('STOCK_RECEIPT_ROOT').'/native-page-query.json', json_encode(['documents' => 51, 'page_sizes' => [25, 100], 'page25_queries' => $small, 'page100_queries' => count($queries), 'extra_queries_reason' => 'Proposal/event data SELECTs skipped by paginator for empty evidence windows.', 'audit_selects' => 2, 'payment_selects' => 1, 'no_writer_lock' => true], JSON_PRETTY_PRINT));
|
||||
}
|
||||
public function test_native_feature_disabled_preserves_legacy_and_invalid_filters_are_refused():void
|
||||
|
||||
public function test_native_page_refuses_tenant_leaks_revoked_rights_and_stale_role(): void
|
||||
{
|
||||
foreach(['page=0','per_page=1000','tenant_id=999','recognition=paid','q%5Ba%5D=x'] as $q)$this->getJson('/api/supplier-payables?'.$q)->assertStatus(422);config(['common-payables.paged_read_enabled'=>false]);$this->getJson('/api/supplier-payables?page=1')->assertStatus(503);$this->getJson('/api/supplier-payables?invoice='.$this->f['invoice']->id)->assertOk()->assertJsonPath('obligations.0.balance_minor',3000)->assertJsonMissingPath('pagination');
|
||||
DB::table('pa_access')->where('user_id', $this->reader->id)->delete();
|
||||
$this->getJson('/api/supplier-payables')->assertForbidden();
|
||||
DB::table('pa_access')->insert(['tenant_id' => $this->reader->tenant_id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $this->reader->id, 'person' => 'native-page-person-'.$this->reader->id, 'action' => 'view']);
|
||||
DB::table('users')->where('id', $this->reader->id)->update(['purchasing_role' => 'requester']);
|
||||
$this->getJson('/api/supplier-payables')->assertForbidden();
|
||||
DB::table('users')->where('id', $this->reader->id)->update(['purchasing_role' => 'finance']);
|
||||
$tenant = Tenant::query()->create(['name' => 'Foreign native page tenant']);
|
||||
$other = User::factory()->create(['tenant_id' => $tenant->id, 'purchasing_role' => PurchasingRole::Finance]);
|
||||
DB::table('pa_access')->insert(['tenant_id' => $tenant->id, 'company_id' => 0, 'unit_id' => 0, 'user_id' => $other->id, 'person' => 'foreign-native-page', 'action' => 'view']);
|
||||
$this->actingAs($other);
|
||||
$this->getJson('/api/supplier-payables')->assertOk()->assertJsonPath('pagination.documents.total', 0)->assertJsonCount(0, 'obligations');
|
||||
$this->getJson('/api/supplier-payables?invoice='.$this->f['invoice']->id)->assertNotFound();
|
||||
}
|
||||
public function test_native_profiles_expiry_maintenance_and_people_context_do_not_grant_financial_read():void
|
||||
|
||||
public function test_native_audit_changes_require_new_conference_without_using_read_snapshots(): void
|
||||
{
|
||||
\supplyGrant($this->reader,['finance']);DB::table('organization_memberships')->where('user_id',$this->reader->id)->update(['expires_at'=>now()->subMinute()]);$this->getJson('/api/supplier-payables')->assertForbidden();DB::table('organization_memberships')->where('user_id',$this->reader->id)->update(['expires_at'=>null,'maintenance'=>true]);$this->getJson('/api/supplier-payables')->assertForbidden();DB::table('organization_memberships')->where('user_id',$this->reader->id)->update(['maintenance'=>false]);
|
||||
$tenant=$this->f['tenant']->id;$this->f['tenant']->update(['rules_provisional'=>false,'work_context_policy'=>['revision'=>1,'enabled'=>['procurement.internal','people.internal']]]);config(['work_context.entitlements.'.$tenant=>['procurement.internal','people.internal']]);DB::table('organization_profiles')->where('tenant_id',$tenant)->update(['work_contexts'=>json_encode(['people.internal'])]);$this->getJson('/api/supplier-payables')->assertForbidden();DB::table('organization_profiles')->where('tenant_id',$tenant)->update(['work_contexts'=>json_encode(['procurement.internal'])]);$this->post('/contexto',['area'=>'procurement','option'=>'procurement.internal'])->assertRedirect('/dashboard');$this->getJson('/api/supplier-payables')->assertOk()->assertJsonPath('obligations.0.balance_minor',3000);
|
||||
$this->assertSame(3000, $this->service()->listing($this->reader)['obligations'][0]['balance_minor']);
|
||||
$this->duplicateRegistration();
|
||||
$new = $this->service()->listing($this->reader);
|
||||
$old = $this->service()->engine($this->reader)->listing([$this->f['invoice']->id]);
|
||||
$this->assertSame($this->positions($old), $this->positions($new));
|
||||
$this->assertNull($new['obligations'][0]['balance_minor']);
|
||||
$this->assertTrue($new['obligations'][0]['source_conflict']);
|
||||
$this->actingAs($this->f['author']);
|
||||
$r = $this->service()->engine($this->f['author'])->command('prepare_history', $this->f['invoice']->id, 'Synthetic new audit after read.', (string) Str::uuid());
|
||||
$this->assertSame('conflict', $r['state']);
|
||||
$this->assertSame(1, DB::table('pa_obligations')->where('tenant_id', $this->f['tenant']->id)->count());
|
||||
}
|
||||
public function test_native_read_finishes_before_writer_release_and_sees_committed_audits_only():void
|
||||
|
||||
public function test_native_feature_disabled_preserves_legacy_and_invalid_filters_are_refused(): void
|
||||
{
|
||||
$dir=base_path('../private/native-page-'.bin2hex(random_bytes(6)));mkdir($dir,0700,true);$input=$dir.'/worker.json';file_put_contents($input,json_encode(['actor'=>$this->reader->id,'instance'=>$this->instance],JSON_THROW_ON_ERROR));$process=null;DB::beginTransaction();
|
||||
try{DB::table('tenants')->where('id',$this->f['tenant']->id)->lockForUpdate()->firstOrFail();$this->duplicateRegistration();$pipes=[];$process=proc_open([PHP_BINARY,base_path('tests/Support/native-payable-page-worker.php'),$input],[0=>['pipe','r'],1=>['file',$dir.'/stdout','w'],2=>['file',$dir.'/stderr','w']],$pipes,base_path());$this->assertIsResource($process);fclose($pipes[0]);$deadline=microtime(true)+8;do{$status=proc_get_status($process);if(!$status['running'])break;usleep(25000);}while(microtime(true)<$deadline);$this->assertFalse($status['running'],'Read must not wait for writer tenant lock');$exit=proc_close($process);$process=null;if($exit===-1)$exit=$status['exitcode'];$this->assertSame(0,$exit);$r=json_decode(file_get_contents($input.'.result'),true);$this->assertSame(200,$r['status']);$this->assertSame([3000],$r['balances']);$this->assertSame(1,DB::transactionLevel());file_put_contents((string)getenv('STOCK_RECEIPT_ROOT').'/native-page-concurrency.json',json_encode(['reader_completed_before_writer_release'=>true,'uncommitted_audit_not_observed'=>true,'balance_minor'=>3000,'reader_time_ms'=>$r['time_ms']],JSON_PRETTY_PRINT));}
|
||||
finally{if(is_resource($process)){proc_terminate($process);proc_close($process);}while(DB::transactionLevel()>0)DB::rollBack();}
|
||||
foreach (['page=0', 'per_page=1000', 'tenant_id=999', 'recognition=paid', 'q%5Ba%5D=x'] as $q) {
|
||||
$this->getJson('/api/supplier-payables?'.$q)->assertStatus(422);
|
||||
}config(['common-payables.paged_read_enabled' => false]);
|
||||
$this->getJson('/api/supplier-payables?page=1')->assertStatus(503);
|
||||
$this->getJson('/api/supplier-payables?invoice='.$this->f['invoice']->id)->assertOk()->assertJsonPath('obligations.0.balance_minor', 3000)->assertJsonMissingPath('pagination');
|
||||
}
|
||||
public function test_native_missing_package_capability_is_503_without_legacy_fallback():void
|
||||
|
||||
public function test_native_profiles_expiry_maintenance_and_people_context_do_not_grant_financial_read(): void
|
||||
{
|
||||
$dir=base_path('../private/native-page-package-'.bin2hex(random_bytes(6)));mkdir($dir,0700,true);$input=$dir.'/worker.json';file_put_contents($input,json_encode(['actor'=>$this->reader->id,'instance'=>$this->instance],JSON_THROW_ON_ERROR));$pipes=[];$environment=getenv();$environment['COMMON_PAYABLES_PATH']='C:/laragon/www/compras/packages/payables';$p=proc_open([PHP_BINARY,base_path('tests/Support/native-payable-page-worker.php'),$input],[0=>['pipe','r'],1=>['file',$dir.'/stdout','w'],2=>['file',$dir.'/stderr','w']],$pipes,base_path(),$environment);$this->assertIsResource($p);fclose($pipes[0]);$this->assertSame(0,proc_close($p));$r=json_decode(file_get_contents($input.'.result'),true);$this->assertSame(503,$r['status']);
|
||||
\supplyGrant($this->reader, ['finance']);
|
||||
DB::table('organization_memberships')->where('user_id', $this->reader->id)->update(['expires_at' => now()->subMinute()]);
|
||||
$this->getJson('/api/supplier-payables')->assertForbidden();
|
||||
DB::table('organization_memberships')->where('user_id', $this->reader->id)->update(['expires_at' => null, 'maintenance' => true]);
|
||||
$this->getJson('/api/supplier-payables')->assertForbidden();
|
||||
DB::table('organization_memberships')->where('user_id', $this->reader->id)->update(['maintenance' => false]);
|
||||
$tenant = $this->f['tenant']->id;
|
||||
$this->f['tenant']->update(['rules_provisional' => false, 'work_context_policy' => ['revision' => 1, 'enabled' => ['procurement.internal', 'people.internal']]]);
|
||||
config(['work_context.entitlements.'.$tenant => ['procurement.internal', 'people.internal']]);
|
||||
DB::table('organization_profiles')->where('tenant_id', $tenant)->update(['work_contexts' => json_encode(['people.internal'])]);
|
||||
$this->getJson('/api/supplier-payables')->assertForbidden();
|
||||
DB::table('organization_profiles')->where('tenant_id', $tenant)->update(['work_contexts' => json_encode(['procurement.internal'])]);
|
||||
$this->post('/contexto', ['area' => 'procurement', 'option' => 'procurement.internal'])->assertRedirect('/dashboard');
|
||||
$this->getJson('/api/supplier-payables')->assertOk()->assertJsonPath('obligations.0.balance_minor', 3000);
|
||||
}
|
||||
|
||||
public function test_native_read_finishes_before_writer_release_and_sees_committed_audits_only(): void
|
||||
{
|
||||
$dir = base_path('../private/native-page-'.bin2hex(random_bytes(6)));
|
||||
mkdir($dir, 0700, true);
|
||||
$input = $dir.'/worker.json';
|
||||
file_put_contents($input, json_encode(['actor' => $this->reader->id, 'instance' => $this->instance], JSON_THROW_ON_ERROR));
|
||||
$process = null;
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
DB::table('tenants')->where('id', $this->f['tenant']->id)->lockForUpdate()->firstOrFail();
|
||||
$this->duplicateRegistration();
|
||||
$pipes = [];
|
||||
$process = proc_open([PHP_BINARY, base_path('tests/Support/native-payable-page-worker.php'), $input], [0 => ['pipe', 'r'], 1 => ['file', $dir.'/stdout', 'w'], 2 => ['file', $dir.'/stderr', 'w']], $pipes, base_path());
|
||||
$this->assertIsResource($process);
|
||||
fclose($pipes[0]);
|
||||
$deadline = microtime(true) + 8;
|
||||
do {
|
||||
$status = proc_get_status($process);
|
||||
if (! $status['running']) {
|
||||
break;
|
||||
}usleep(25000);
|
||||
} while (microtime(true) < $deadline);
|
||||
$this->assertFalse($status['running'], 'Read must not wait for writer tenant lock');
|
||||
$exit = proc_close($process);
|
||||
$process = null;
|
||||
if ($exit === -1) {
|
||||
$exit = $status['exitcode'];
|
||||
}$this->assertSame(0, $exit);
|
||||
$r = json_decode(file_get_contents($input.'.result'), true);
|
||||
$this->assertSame(200, $r['status']);
|
||||
$this->assertSame([3000], $r['balances']);
|
||||
$this->assertSame(1, DB::transactionLevel());
|
||||
file_put_contents((string) getenv('STOCK_RECEIPT_ROOT').'/native-page-concurrency.json', json_encode(['reader_completed_before_writer_release' => true, 'uncommitted_audit_not_observed' => true, 'balance_minor' => 3000, 'reader_time_ms' => $r['time_ms']], JSON_PRETTY_PRINT));
|
||||
} finally {
|
||||
if (is_resource($process)) {
|
||||
proc_terminate($process);
|
||||
proc_close($process);
|
||||
}while (DB::transactionLevel() > 0) {
|
||||
DB::rollBack();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function test_native_missing_package_capability_is_503_without_legacy_fallback(): void
|
||||
{
|
||||
$dir = base_path('../private/native-page-package-'.bin2hex(random_bytes(6)));
|
||||
mkdir($dir, 0700, true);
|
||||
$input = $dir.'/worker.json';
|
||||
file_put_contents($input, json_encode(['actor' => $this->reader->id, 'instance' => $this->instance], JSON_THROW_ON_ERROR));
|
||||
$pipes = [];
|
||||
$environment = getenv();
|
||||
$environment['COMMON_PAYABLES_PATH'] = base_path('packages/payables');
|
||||
$p = proc_open([PHP_BINARY, base_path('tests/Support/native-payable-page-worker.php'), $input],[0 => ['pipe', 'r'], 1 => ['file', $dir.'/stdout', 'w'], 2 => ['file', $dir.'/stderr', 'w']],$pipes,base_path(),$environment);
|
||||
$this->assertIsResource($p);
|
||||
fclose($pipes[0]);
|
||||
$this->assertSame(0,proc_close($p));
|
||||
$r = json_decode(file_get_contents($input.'.result'),true);
|
||||
$this->assertSame(503,$r['status']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Department;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\ProductModules;
|
||||
use App\Services\WorkContext;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
// Âmbito da v1: só o núcleo de compras. Os módulos laterais desligam-se sem afectar o núcleo.
|
||||
|
||||
beforeEach(function () {
|
||||
config(['modules.enabled' => ['pessoas' => false, 'armazem_avancado' => false, 'fornecimento' => false]]);
|
||||
$tenant = Tenant::query()->create(['name' => 'Empresa do núcleo']);
|
||||
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações']);
|
||||
$this->admin = User::factory()->create(['tenant_id' => $tenant->id, 'department_id' => $department->id, 'purchasing_role' => PurchasingRole::Admin]);
|
||||
});
|
||||
|
||||
test('core purchasing pages stay available with every lateral module off', function (string $path) {
|
||||
$this->actingAs($this->admin)->get($path)->assertOk();
|
||||
})->with([
|
||||
'/dashboard', '/requisicoes', '/fornecedores', '/cotacoes', '/ordens', '/recepcoes',
|
||||
'/stock', '/stock/operacoes', '/facturas', '/pagamentos', '/orcamentos', '/regras-investimento',
|
||||
'/empresa', '/conflitos', '/relatorios',
|
||||
]);
|
||||
|
||||
test('lateral module routes answer as missing when their module is off', function (string $path) {
|
||||
$this->actingAs($this->admin)->get($path)->assertNotFound();
|
||||
})->with([
|
||||
'pessoas' => '/pessoas',
|
||||
'pessoas: relatórios' => '/pessoas/relatorios',
|
||||
'pessoas: portal público' => '/candidaturas/1',
|
||||
'armazém: requisições internas' => '/stock/requisicoes',
|
||||
'armazém: reposição automática' => '/stock/reposicao',
|
||||
'armazém: lotes' => '/stock/lotes',
|
||||
'fornecimento: planeado' => '/compras/fornecimento',
|
||||
'fornecimento: equipamentos' => '/equipamentos',
|
||||
'fornecimento: projectos e imobilizado' => '/projectos-imobilizado',
|
||||
]);
|
||||
|
||||
test('a module switched on serves its routes again', function () {
|
||||
config(['modules.enabled.fornecimento' => true]);
|
||||
expect(app(ProductModules::class)->enabled('fornecimento'))->toBeTrue();
|
||||
$this->actingAs($this->admin)->get('/equipamentos')->assertStatus(200);
|
||||
});
|
||||
|
||||
test('menus receive the paths of disabled modules and keep the core ones', function () {
|
||||
$this->actingAs($this->admin)->get('/dashboard')->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->where('modules', ['pessoas' => false, 'armazem_avancado' => false, 'fornecimento' => false])
|
||||
->where('disabledModulePaths', fn ($paths) => collect($paths)->contains('/pessoas')
|
||||
&& collect($paths)->contains('/stock/requisicoes')
|
||||
&& collect($paths)->contains('/equipamentos')
|
||||
&& ! collect($paths)->contains('/stock')
|
||||
&& ! collect($paths)->contains('/requisicoes')
|
||||
&& ! collect($paths)->contains('/compras')));
|
||||
});
|
||||
|
||||
test('people work contexts are not offered while the people module is off', function () {
|
||||
config(['work_context.composition' => 'sgc', 'work_context.entitlements' => [$this->admin->tenant_id => array_keys(WorkContext::OPTIONS)]]);
|
||||
expect(app(WorkContext::class)->purchased($this->admin))->not->toContain('people.internal')->not->toContain('people.third_party')
|
||||
->toContain('procurement.internal');
|
||||
|
||||
config(['modules.enabled.pessoas' => true]);
|
||||
expect(app(WorkContext::class)->purchased($this->admin))->toContain('people.internal');
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Laravel\Fortify\Features;
|
||||
|
||||
function productionConfig(): void
|
||||
{
|
||||
app()->instance('env', 'production');
|
||||
config(['app.debug' => false, 'app.url' => 'https://compras.example.test', 'session.secure' => true, 'session.driver' => 'database',
|
||||
'cache.default' => 'database', 'fortify.features' => [Features::twoFactorAuthentication(['confirm' => true, 'confirmPassword' => true])],
|
||||
'mfa.required_functions' => ['admin', 'finance']]);
|
||||
}
|
||||
|
||||
test('a development installation is reported as not ready for production', function () {
|
||||
config(['app.debug' => true, 'app.url' => 'http://localhost', 'fortify.features' => []]);
|
||||
$this->artisan('sgc:production-check')
|
||||
->expectsOutputToContain('FALHA APP_ENV=production')
|
||||
->expectsOutputToContain('FALHA APP_DEBUG=false')
|
||||
->expectsOutputToContain('FALHA APP_URL em https')
|
||||
->expectsOutputToContain('FALHA MFA ligado')
|
||||
->assertFailed();
|
||||
});
|
||||
|
||||
test('a production configuration passes every check except a non PostgreSQL database', function () {
|
||||
productionConfig();
|
||||
$postgres = DB::connection()->getDriverName() === 'pgsql';
|
||||
$run = $this->artisan('sgc:production-check')
|
||||
->expectsOutputToContain('OK APP_ENV=production')
|
||||
->expectsOutputToContain('OK MFA ligado')
|
||||
->expectsOutputToContain('OK Migrações aplicadas')
|
||||
->expectsOutputToContain('OK Pacotes partilhados conferidos')
|
||||
->expectsOutputToContain(($postgres ? 'OK ' : 'FALHA ').'Base de dados PostgreSQL');
|
||||
$postgres ? $run->assertSuccessful() : $run->assertFailed();
|
||||
});
|
||||
|
||||
test('https without secure session cookies fails', function () {
|
||||
productionConfig();
|
||||
config(['session.secure' => false]);
|
||||
$this->artisan('sgc:production-check')->expectsOutputToContain('FALHA SESSION_SECURE_COOKIE=true')->assertFailed();
|
||||
});
|
||||
@@ -1,31 +1,41 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Inertia\Testing\AssertableInertia as Assert;
|
||||
|
||||
test('visual consultation is accessible without authentication', function (string $path, string $component) {
|
||||
$this->get($path)->assertOk()->assertInertia(fn (Assert $page) => $page
|
||||
->component($component)
|
||||
->where('auth.user', null)
|
||||
->missing('suppliers')->missing('requisitions')->missing('documents')
|
||||
->missing('adoptions')->missing('policies')->missing('recommendations'));
|
||||
// The former public demonstration screens were retired (no parallel simulations):
|
||||
// their links are preserved as redirects to the real, authenticated modules.
|
||||
|
||||
test('former consultation links redirect to the real modules', function (string $path, string $destination) {
|
||||
$this->get($path)->assertRedirect($destination);
|
||||
$this->assertGuest();
|
||||
})->with([['/consulta', 'preview/index'], ['/proposta/qualificacao', 'preview/qualification'], ['/proposta/admissao', 'preview/admission'], ['/proposta/recomendacao', 'preview/recommendation']]);
|
||||
})->with([
|
||||
['/consulta', '/dashboard'],
|
||||
['/consulta?ecra=suppliers', '/fornecedores'],
|
||||
['/consulta?ecra=unknown', '/dashboard'],
|
||||
['/consulta/fornecedores', '/fornecedores'],
|
||||
['/consulta/dados-bancarios', '/fornecedores'],
|
||||
['/consulta/investimento', '/regras-investimento'],
|
||||
['/consulta/operacoes-stock', '/stock/operacoes'],
|
||||
['/proposta/principal', '/dashboard'],
|
||||
['/proposta/qualificacao', '/requisicoes'],
|
||||
['/proposta/admissao', '/requisicoes'],
|
||||
['/proposta/recomendacao', '/requisicoes'],
|
||||
]);
|
||||
|
||||
test('preview does not expose authenticated account data or log it out', function () {
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user)->get('/consulta')->assertOk()->assertInertia(fn (Assert $page) => $page->where('auth.user', null));
|
||||
$this->get('/proposta/recomendacao')->assertOk()->assertInertia(fn (Assert $page) => $page->where('auth.user', null)->missing('recommendations')->missing('policies')->missing('documents'));
|
||||
$this->assertAuthenticatedAs($user);
|
||||
test('unknown consultation screens are not found', function () {
|
||||
$this->get('/consulta/inexistente')->assertNotFound();
|
||||
});
|
||||
|
||||
test('consultation creates no business access or mutation endpoint', function () {
|
||||
$this->get('/consulta')->assertOk();
|
||||
test('redirected modules still require authentication and keep an authenticated session', function () {
|
||||
$this->get('/consulta')->assertRedirect('/dashboard');
|
||||
foreach (['/dashboard', '/fornecedores', '/cotacoes', '/conflitos'] as $path) {
|
||||
$this->get($path)->assertRedirect('/login');
|
||||
}
|
||||
$this->post('/fornecedores', ['name' => 'Tentativa pública'])->assertRedirect('/login');
|
||||
$this->post('/consulta', [])->assertStatus(405);
|
||||
$this->post('/proposta/recomendacao', [])->assertStatus(405);
|
||||
expect(User::query()->count())->toBe(0);
|
||||
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user)->get('/consulta')->assertRedirect('/dashboard');
|
||||
$this->assertAuthenticatedAs($user);
|
||||
});
|
||||
|
||||
@@ -1049,7 +1049,7 @@ test('discount evidence and net prices survive award order and printable report'
|
||||
|
||||
test('native order preserves common ledger account references without creating a journal or changing the chart', function () {
|
||||
$source = getenv('RQ01_LEDGER_QA_SOURCE');
|
||||
if ($source !== 'C:/laragon/www/sgf-tempo/packages/general-ledger') {
|
||||
if ($source !== sgfTempoPath('packages/general-ledger')) {
|
||||
$this->markTestSkipped('Dedicated real common-ledger QA schema required.');
|
||||
}
|
||||
require_once $source.'/bootstrap.php';
|
||||
@@ -1077,7 +1077,7 @@ test('native order preserves common ledger account references without creating a
|
||||
|
||||
test('native order preserves common ledger across partial and consolidated origins', function (string $mode) {
|
||||
$source = getenv('RQ01_LEDGER_QA_SOURCE');
|
||||
if ($source !== 'C:/laragon/www/sgf-tempo/packages/general-ledger' || ! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||
if ($source !== sgfTempoPath('packages/general-ledger') || ! method_exists(BudgetControl::class, 'commitOrderParts')) {
|
||||
$this->markTestSkipped('Dedicated common ledger and authorised order-parts QA composition required.');
|
||||
}
|
||||
require_once $source.'/bootstrap.php';
|
||||
@@ -1391,7 +1391,7 @@ test('supplier names are frozen at issuance rather than read from live records',
|
||||
test('print escapes supplied HTML and keeps the development and budget notices', function () {
|
||||
$this->selection['justification'] = 'Fundamento escrito <script>alert(1)</script> para teste de impressão.';
|
||||
$order = issuePurchaseOrder($this, selectPurchaseAward($this));
|
||||
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('<script>', false)->assertDontSee('<script>alert(1)</script>', false)->assertSee('Orçamento não verificado')->assertSee('Não autoriza compras reais');
|
||||
$this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('<script>', false)->assertDontSee('<script>alert(1)</script>', false)->assertSee('Este documento não preserva confirmação do controlo orçamental')->assertSee('Não autoriza compras reais');
|
||||
});
|
||||
|
||||
test('department heads cannot read or print another departments order', function () {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\{ConflictGuard,ReceiptStockMovement};
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\ReceiptStockMovement;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCase;
|
||||
|
||||
@@ -10,15 +12,27 @@ final class ReceiptAdapterReplayTest extends TestCase
|
||||
{
|
||||
public function test_final_adapter_reuses_existing_movement_without_a_second_effect(): void
|
||||
{
|
||||
$i=DB::selectOne("SELECT current_database() AS name,current_user AS role,current_setting('cluster_name') AS cluster");
|
||||
$this->assertMatchesRegularExpression('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->name);
|
||||
$this->assertSame('stock_receipt_qa_'.substr($i->name,-12),$i->role);$this->assertSame('sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'),$i->cluster);
|
||||
$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$this->assertNotFalse($root);
|
||||
$proof=json_decode(file_get_contents($root.'/receipt-results.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
$row=DB::table('stock_movements')->where('tenant_id',$proof['link']['tenant'])->where('id',$proof['link']['movement'])->first();$this->assertNotNull($row);
|
||||
$actor=User::findOrFail($row->moved_by);$this->actingAs($actor);$count=DB::table('stock_movements')->count();
|
||||
$hash=json_decode($row->snapshot,true)['inventory_source_hash'];
|
||||
$result=DB::transaction(function()use($actor,$row,$hash){app(ConflictGuard::class)->lockCompany($actor);return app(ReceiptStockMovement::class)->for($actor)->write($row->goods_receipt_item_id,$hash);});
|
||||
$this->assertTrue($result['replayed']);$this->assertSame((int)$row->id,$result['movement_id']);$this->assertSame($count,DB::table('stock_movements')->count());
|
||||
skipUnlessIsolatedPostgres($this);
|
||||
$i = DB::selectOne("SELECT current_database() AS name,current_user AS role,current_setting('cluster_name') AS cluster");
|
||||
$this->assertMatchesRegularExpression('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->name);
|
||||
$this->assertSame('stock_receipt_qa_'.substr($i->name, -12), $i->role);
|
||||
$this->assertSame('sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'), $i->cluster);
|
||||
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
|
||||
$this->assertNotFalse($root);
|
||||
$proof = json_decode(file_get_contents($root.'/receipt-results.json'), true, 512, JSON_THROW_ON_ERROR);
|
||||
$row = DB::table('stock_movements')->where('tenant_id', $proof['link']['tenant'])->where('id', $proof['link']['movement'])->first();
|
||||
$this->assertNotNull($row);
|
||||
$actor = User::findOrFail($row->moved_by);
|
||||
$this->actingAs($actor);
|
||||
$count = DB::table('stock_movements')->count();
|
||||
$hash = json_decode($row->snapshot, true)['inventory_source_hash'];
|
||||
$result = DB::transaction(function () use ($actor, $row, $hash) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
|
||||
return app(ReceiptStockMovement::class)->for($actor)->write($row->goods_receipt_item_id, $hash);
|
||||
});
|
||||
$this->assertTrue($result['replayed']);
|
||||
$this->assertSame((int) $row->id, $result['movement_id']);
|
||||
$this->assertSame($count, DB::table('stock_movements')->count());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,14 +69,14 @@ test('pinned private runtime refuses source fallback and mismatched composition
|
||||
$settings = ['common-finance-bundle.manifest_sha256' => config('common-finance-bundle.manifest_sha256'),
|
||||
'common-finance-bundle.root' => config('common-finance-bundle.root'), 'general-ledger.path' => config('general-ledger.path')];
|
||||
try {
|
||||
foreach (['C:/laragon/www/sgf-tempo/packages/general-ledger', base_path('storage/framework/testing/unapproved-ledger-source')] as $wrong) {
|
||||
foreach ([sgfTempoPath('packages/general-ledger'), base_path('storage/framework/testing/unapproved-ledger-source')] as $wrong) {
|
||||
putenv('RQ01_LEDGER_QA_SOURCE='.$wrong);
|
||||
expect(fn () => requisitionLedgerQaSource())->toThrow(LogicException::class);
|
||||
}
|
||||
putenv('RQ01_LEDGER_QA_SOURCE='.$source);
|
||||
foreach (['common-finance-bundle.manifest_sha256' => str_repeat('0', 64),
|
||||
'common-finance-bundle.root' => base_path('storage/framework/testing/unapproved-ledger-source'),
|
||||
'general-ledger.path' => 'C:/laragon/www/sgf-tempo/packages/general-ledger'] as $key => $wrong) {
|
||||
'general-ledger.path' => sgfTempoPath('packages/general-ledger')] as $key => $wrong) {
|
||||
config([$key => $wrong]);
|
||||
expect(fn () => requisitionLedgerQaSource())->toThrow(LogicException::class);
|
||||
config($settings);
|
||||
|
||||
@@ -14,6 +14,8 @@ use App\Services\GeneralLedger;
|
||||
use App\Services\InvoiceWorkflow;
|
||||
use App\Services\OrderCancellationRuntime;
|
||||
use App\Services\OrderCancellationWorkflow;
|
||||
use App\Services\PrivateAuditAccess;
|
||||
use App\Services\PrivateAuditFiles;
|
||||
use App\Services\ProcurementPaymentInsights;
|
||||
use App\Services\RequisitionAccountAssignments;
|
||||
use App\Services\RequisitionExpiry;
|
||||
@@ -27,8 +29,11 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Tempo\Finance\Budget\BudgetContext;
|
||||
use Tempo\Finance\Budget\BudgetFailure;
|
||||
use Tempo\Finance\OrderCancellation\CommitmentReversal;
|
||||
@@ -77,24 +82,24 @@ test('standalone audit uses ordinary private application storage and refuses pub
|
||||
$files = null;
|
||||
try {
|
||||
config(['filesystems.disks.local.root' => $root]);
|
||||
\Illuminate\Support\Facades\Storage::forgetDisk('local');
|
||||
expect(app(\App\Services\PrivateAuditAccess::class)->ready())->toBeTrue();
|
||||
$files = new \App\Services\PrivateAuditFiles($this->f['issuer']);
|
||||
Storage::forgetDisk('local');
|
||||
expect(app(PrivateAuditAccess::class)->ready())->toBeTrue();
|
||||
$files = new PrivateAuditFiles($this->f['issuer']);
|
||||
$written = $files->write('probe.ndjson', "{\"synthetic\":true}\n");
|
||||
expect(file_get_contents($written['path']))->toBe("{\"synthetic\":true}\n")
|
||||
->and($written['sha256'])->toBe(hash('sha256', "{\"synthetic\":true}\n"));
|
||||
foreach ([public_path(), storage_path('app/public'), $external] as $invalid) {
|
||||
config(['filesystems.disks.local.root' => $invalid]);
|
||||
\Illuminate\Support\Facades\Storage::forgetDisk('local');
|
||||
expect(fn () => new \App\Services\PrivateAuditFiles($this->f['issuer']))->toThrow(\Symfony\Component\HttpKernel\Exception\HttpException::class);
|
||||
Storage::forgetDisk('local');
|
||||
expect(fn () => new PrivateAuditFiles($this->f['issuer']))->toThrow(HttpException::class);
|
||||
}
|
||||
} finally {
|
||||
$files?->cleanup();
|
||||
config(['filesystems.disks.local' => $original]);
|
||||
\Illuminate\Support\Facades\Storage::forgetDisk('local');
|
||||
Storage::forgetDisk('local');
|
||||
$resolved = realpath($root);
|
||||
if ($resolved !== false && dirname($resolved) === realpath(storage_path('app')) && str_starts_with(basename($resolved), 'release-audit-')) {
|
||||
\Illuminate\Support\Facades\File::deleteDirectory($resolved);
|
||||
File::deleteDirectory($resolved);
|
||||
}
|
||||
if (is_dir($external) && count(scandir($external) ?: []) === 2) {
|
||||
rmdir($external);
|
||||
|
||||
@@ -120,13 +120,13 @@ test('audit failure rolls back both halves of transfer and operation', function
|
||||
expect(StockOperation::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(1);
|
||||
});
|
||||
|
||||
test('operations are immutable and new public screen contains only demonstration props', function () {
|
||||
test('operations are immutable and the former public screen redirects to the real module', function () {
|
||||
$this->postJson('/stock/operacoes', $this->p)->assertCreated();
|
||||
$op = StockOperation::query()->firstOrFail();
|
||||
expect(fn () => $op->update(['reason' => 'rewrite']))->toThrow(LogicException::class);
|
||||
expect(fn () => $op->delete())->toThrow(LogicException::class);
|
||||
$this->get('/stock/operacoes')->assertInertia(fn (Assert $p) => $p->component('stock/operations')->has('operations.data', 1)->where('canOperate', true));
|
||||
$this->get('/consulta/operacoes-stock')->assertInertia(fn (Assert $p) => $p->component('preview/index')->where('initialScreen', 'operations')->missing('operations')->where('auth.user', null));
|
||||
$this->get('/consulta/operacoes-stock')->assertRedirect('/stock/operacoes');
|
||||
});
|
||||
|
||||
test('invalid precision and missing justification or destination do not write', function ($field, $value) {
|
||||
|
||||
@@ -147,7 +147,8 @@ test('supplier conflict blocks a previously approved banking revision', function
|
||||
expect(app(SupplierBankWorkflow::class)->state($this->supplier))->toBe('blocked');
|
||||
});
|
||||
|
||||
test('public bank example exposes no company banking details', function () {
|
||||
test('former public bank example redirects to the authenticated supplier module', function () {
|
||||
auth()->forgetGuards();
|
||||
$this->get('/consulta/dados-bancarios')->assertOk()->assertInertia(fn ($page) => $page->where('initialScreen', 'bank')->where('auth.user', null)->missing('current')->missing('history'));
|
||||
$this->get('/consulta/dados-bancarios')->assertRedirect('/fornecedores');
|
||||
$this->get('/fornecedores')->assertRedirect('/login');
|
||||
});
|
||||
|
||||
@@ -64,5 +64,5 @@ test('synthetic pilot connects partial delivery shortage purchase draft replenis
|
||||
->and(app(StockWorkflow::class)->balance($f['stock']->id, $f['warehouse']->id)['quantity'])->toBe(103000)
|
||||
->and($purchase->fresh()->status)->toBe('draft')->and(DB::table('invoices')->count())->toBe(0)->and(DB::table('budget_entries')->count())->toBe(0)
|
||||
->and(Requisition::query()->where('status', 'draft')->count())->toBe(1);
|
||||
$this->get('/stock/requisicoes?view=receipt')->assertOk()->assertInertia(fn (Assert $p) => $p->where('records.total',0));
|
||||
$this->get('/stock/requisicoes?view=receipt')->assertOk()->assertInertia(fn (Assert $p) => $p->where('records.total', 0));
|
||||
});
|
||||
|
||||
@@ -1,10 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Models\{StockMovement,StockOperation,SupplyRecord,User,WarehouseRequestEvent};
|
||||
use App\Services\{ReceiptWorkflow,WarehouseFulfilment,WarehouseRequests};
|
||||
use Illuminate\Support\Facades\{Artisan,DB};
|
||||
use App\Models\StockMovement;
|
||||
use App\Models\StockOperation;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\WarehouseRequest;
|
||||
use App\Models\WarehouseRequestEvent;
|
||||
use App\Services\AutomaticPurchases;
|
||||
use App\Services\InventoryReversals;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use App\Services\SupplyHistory;
|
||||
use App\Services\WarehouseFulfilment;
|
||||
use App\Services\WarehouseRequests;
|
||||
use Illuminate\Support\Facades\Artisan;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tests\TestCase;
|
||||
|
||||
require_once __DIR__.'/../Support/ReceiptFixture.php';
|
||||
@@ -12,165 +26,552 @@ require_once __DIR__.'/../Support/SupplyFixture.php';
|
||||
|
||||
final class WarehouseReturnIntegrationTest extends TestCase
|
||||
{
|
||||
private array $f;private User $reviewer;private int $requestId;private int $delivery;private array $payload;
|
||||
protected function setUp():void
|
||||
private array $f;
|
||||
|
||||
private User $reviewer;
|
||||
|
||||
private int $requestId;
|
||||
|
||||
private int $delivery;
|
||||
|
||||
private array $payload;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();$i=DB::selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
$this->assertMatchesRegularExpression('/^compras_receipts_test_[a-f0-9]{12}$/D',$i->db);$this->assertSame('stock_receipt_qa_'.substr($i->db,-12),$i->role);$this->assertSame(55439,(int)$i->port);$this->assertSame('sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'),$i->cluster);
|
||||
if(!DB::getSchemaBuilder()->hasTable('users'))Artisan::call('migrate',['--force'=>true]);config(['stock_returns.enabled'=>true]);
|
||||
$this->f=\receiptFixture('10.000');$this->reviewer=User::factory()->create(['tenant_id'=>$this->f['tenant']->id,'department_id'=>$this->f['issuer']->department_id]);
|
||||
\supplyGrant($this->f['issuer'],['warehouse_request_prepare','warehouse_return_prepare','warehouse_return_read','warehouse_return_confirm','warehouse']);
|
||||
\supplyGrant($this->reviewer,['warehouse_request_review']);\supplyGrant($this->f['receiver'],['warehouse','warehouse_request_deliver','warehouse_return_read','warehouse_return_confirm']);\supplyGrant($this->f['otherReceiver'],['warehouse','warehouse_return_read']);
|
||||
$this->actingAs($this->f['receiver']);app(ReceiptWorkflow::class)->confirm($this->f['receiver'],$this->f['order'],\receiptPayload($this->f,'10.000'));
|
||||
$this->actingAs($this->f['issuer']);$r=app(WarehouseRequests::class)->draft($this->f['issuer'],['operation_key'=>(string)Str::uuid(),'warehouse_id'=>$this->f['warehouse']->id,'cost_center_id'=>$this->f['r']->cost_center_id,'destination'=>'Synthetic internal workshop','reason'=>'Synthetic authorised internal material use.','priority'=>'normal','lines'=>[['stock_item_id'=>$this->f['stock']->id,'quantity'=>'5.000','use'=>'internal','equipment_id'=>null]]]);$this->requestId=$r->id;
|
||||
$this->command($this->f['issuer'],'submit',['partial_allowed'=>false]);$this->command($this->reviewer,'authorize',['partial_allowed'=>false]);$this->command($this->f['receiver'],'deliver',['lines'=>[['index'=>0,'quantity'=>'5.000']]]);
|
||||
$this->delivery=(int)WarehouseRequestEvent::query()->where('warehouse_request_id',$r->id)->where('action','deliver')->value('id');$this->command($this->f['issuer'],'receive',['delivery_event_id'=>$this->delivery]);
|
||||
$this->payload=['operation_key'=>(string)Str::uuid(),'delivery_event_id'=>$this->delivery,'line_index'=>0,'quantity'=>'3.000','declared_unused'=>true,'evidence'=>'Synthetic unused quantity and physical custody evidence.','reason'=>'Synthetic unused material returned to its original warehouse.'];$this->actingAs($this->f['issuer']);
|
||||
parent::setUp();
|
||||
skipUnlessIsolatedPostgres($this);
|
||||
$i = DB::selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
$this->assertMatchesRegularExpression('/^compras_receipts_test_[a-f0-9]{12}$/D', $i->db);
|
||||
$this->assertSame('stock_receipt_qa_'.substr($i->db, -12), $i->role);
|
||||
$this->assertSame(55439, (int) $i->port);
|
||||
$this->assertSame('sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'), $i->cluster);
|
||||
if (! DB::getSchemaBuilder()->hasTable('users')) {
|
||||
Artisan::call('migrate', ['--force' => true]);
|
||||
}config(['stock_returns.enabled' => true]);
|
||||
$this->f = \receiptFixture('10.000');
|
||||
$this->reviewer = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['issuer']->department_id]);
|
||||
\supplyGrant($this->f['issuer'], ['warehouse_request_prepare', 'warehouse_return_prepare', 'warehouse_return_read', 'warehouse_return_confirm', 'warehouse']);
|
||||
\supplyGrant($this->reviewer, ['warehouse_request_review']);
|
||||
\supplyGrant($this->f['receiver'], ['warehouse', 'warehouse_request_deliver', 'warehouse_return_read', 'warehouse_return_confirm']);
|
||||
\supplyGrant($this->f['otherReceiver'], ['warehouse', 'warehouse_return_read']);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], \receiptPayload($this->f, '10.000'));
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$r = app(WarehouseRequests::class)->draft($this->f['issuer'], ['operation_key' => (string) Str::uuid(), 'warehouse_id' => $this->f['warehouse']->id, 'cost_center_id' => $this->f['r']->cost_center_id, 'destination' => 'Synthetic internal workshop', 'reason' => 'Synthetic authorised internal material use.', 'priority' => 'normal', 'lines' => [['stock_item_id' => $this->f['stock']->id, 'quantity' => '5.000', 'use' => 'internal', 'equipment_id' => null]]]);
|
||||
$this->requestId = $r->id;
|
||||
$this->command($this->f['issuer'], 'submit', ['partial_allowed' => false]);
|
||||
$this->command($this->reviewer, 'authorize', ['partial_allowed' => false]);
|
||||
$this->command($this->f['receiver'], 'deliver', ['lines' => [['index' => 0, 'quantity' => '5.000']]]);
|
||||
$this->delivery = (int) WarehouseRequestEvent::query()->where('warehouse_request_id', $r->id)->where('action', 'deliver')->value('id');
|
||||
$this->command($this->f['issuer'], 'receive', ['delivery_event_id' => $this->delivery]);
|
||||
$this->payload = ['operation_key' => (string) Str::uuid(), 'delivery_event_id' => $this->delivery, 'line_index' => 0, 'quantity' => '3.000', 'declared_unused' => true, 'evidence' => 'Synthetic unused quantity and physical custody evidence.', 'reason' => 'Synthetic unused material returned to its original warehouse.'];
|
||||
$this->actingAs($this->f['issuer']);
|
||||
}
|
||||
private function command(User $actor,string $action,array $extra):void
|
||||
|
||||
private function command(User $actor, string $action, array $extra): void
|
||||
{
|
||||
$this->actingAs($actor);$r=\App\Models\WarehouseRequest::query()->findOrFail($this->requestId);$d=['operation_key'=>(string)Str::uuid(),'version'=>app(WarehouseFulfilment::class)->progress($r)['version'],'action'=>$action,'reason'=>'Synthetic explicit request intervention.']+$extra;
|
||||
$this->postJson('/stock/requisicoes/'.$r->id.'/eventos',$d)->assertRedirect();
|
||||
$this->actingAs($actor);
|
||||
$r = WarehouseRequest::query()->findOrFail($this->requestId);
|
||||
$d = ['operation_key' => (string) Str::uuid(), 'version' => app(WarehouseFulfilment::class)->progress($r)['version'], 'action' => $action, 'reason' => 'Synthetic explicit request intervention.'] + $extra;
|
||||
$this->postJson('/stock/requisicoes/'.$r->id.'/eventos', $d)->assertRedirect();
|
||||
}
|
||||
private function prepare(?array $payload=null){return $this->postJson('/api/stock-returns/prepare',$payload??$this->payload);}
|
||||
private function confirm(int $id,int $version=1){return $this->postJson('/api/stock-returns/'.$id.'/confirm',['version'=>$version,'received_in_warehouse'=>true,'reason'=>'Synthetic independent physical warehouse receipt.']);}
|
||||
private function closeProposal(int $id,string $action,int $version=1){return $this->postJson('/api/stock-returns/'.$id.'/'.$action,['version'=>$version,'reason'=>'Synthetic reason for closing without physical movement.']);}
|
||||
private function balance():int{return (int)StockMovement::query()->sum('quantity_milli');}
|
||||
public function test_native_receipt_issue_acknowledgement_and_return_same_book_once():void
|
||||
|
||||
private function prepare(?array $payload = null)
|
||||
{
|
||||
$this->assertSame(5000,$this->balance());$p=$this->prepare()->assertOk()->assertJsonPath('impact.physical_before','5000')->assertJsonPath('impact.physical_after','8000')->json('id');$this->prepare()->assertOk()->assertJsonPath('id',$p)->assertJsonPath('replayed',true);$this->confirm($p)->assertForbidden();
|
||||
$prepared=SupplyRecord::query()->findOrFail($p);$this->assertSame($this->f['issuer']->id,$prepared->snapshot['source']['acknowledgement']['actor_id']);
|
||||
$this->actingAs($this->f['receiver']);$this->postJson('/api/stock-returns/'.$p.'/confirm',['version'=>1,'reason'=>'Synthetic receipt without acknowledgement'])->assertStatus(422);$m=$this->confirm($p)->assertOk()->json('movement_id');$this->confirm($p)->assertOk()->assertJsonPath('movement_id',$m)->assertJsonPath('replayed',true);
|
||||
$this->assertSame(8000,$this->balance());$this->assertSame(3,StockMovement::query()->count());$this->assertSame(2,StockOperation::query()->count());$this->assertSame(2,SupplyRecord::query()->where('kind','warehouse_return')->count());
|
||||
$history=$this->get('/stock/operacoes')->assertOk()->assertInertia(fn($page)=>$page->component('stock/operations')->where('canViewReturns',true)->where('operations.data.0.kind','workshop_return')->where('operations.data.0.snapshot.stock_item.id',$this->f['stock']->id)->where('operations.data.0.snapshot.warehouse.id',$this->f['warehouse']->id)->where('operations.data.0.snapshot.actor.id',$this->f['receiver']->id)->where('operations.data.0.snapshot.responsible.id',$this->f['receiver']->id));
|
||||
$historyRoot=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$this->assertNotFalse($historyRoot);file_put_contents($historyRoot.'/native-stock-history-page.json',json_encode($history->viewData('page'),JSON_THROW_ON_ERROR));
|
||||
$this->getJson('/api/stock-returns?state=confirmed')->assertOk()->assertJsonPath('pagination.total',1)->assertJsonPath('rows.0.version',2);$this->getJson('/api/stock-returns?state=prepared')->assertOk()->assertJsonPath('pagination.total',0);
|
||||
$this->assertTrue(DB::table('audit_logs')->where('tenant_id',$this->f['tenant']->id)->where('action','warehouse_return.confirmed')->exists());
|
||||
$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$this->assertNotFalse($root);file_put_contents($root.'/return-results.json',json_encode(['kind'=>'native_receipt_internal_issue_and_return','tenant'=>$this->f['tenant']->id,'warehouse'=>$this->f['warehouse']->id,'item'=>$this->f['stock']->id,'return_movement'=>$m,'request_id'=>$this->requestId,'physical_milli'=>'8000','native_movements'=>3,'shared_return_manifest_sha256'=>hash_file('sha256',base_path('packages/inventory-return/releases/0.1.0/manifest.json'))],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
return $this->postJson('/api/stock-returns/prepare', $payload ?? $this->payload);
|
||||
}
|
||||
public function test_stale_capacity_idempotency_versions_rights_and_context_refuse_effect():void
|
||||
|
||||
private function confirm(int $id, int $version = 1)
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$changed=$this->payload;$changed['quantity']='2.000';$this->prepare($changed)->assertConflict();$second=$this->payload;$second['operation_key']=(string)Str::uuid();$other=$this->prepare($second)->assertOk()->json('id');
|
||||
$this->actingAs($this->f['otherReceiver']);$this->confirm($p)->assertForbidden();$this->actingAs($this->f['receiver']);$this->confirm($p,2)->assertStatus(422);$this->confirm($p)->assertOk();$this->confirm($other)->assertConflict();$this->assertSame(8000,$this->balance());
|
||||
$this->actingAs($this->f['issuer']);$second['quantity']='2.001';$second['operation_key']=(string)Str::uuid();$this->prepare($second)->assertConflict();$second['quantity']='2.000';$second['operation_key']=(string)Str::uuid();$p=$this->prepare($second)->assertOk()->json('id');$this->actingAs($this->f['receiver']);$this->confirm($p)->assertOk();$this->assertSame(10000,$this->balance());
|
||||
config(['stock_returns.enabled'=>false]);$this->getJson('/api/stock-returns')->assertStatus(503);$this->assertSame(10000,$this->balance());
|
||||
return $this->postJson('/api/stock-returns/'.$id.'/confirm', ['version' => $version, 'received_in_warehouse' => true, 'reason' => 'Synthetic independent physical warehouse receipt.']);
|
||||
}
|
||||
public function test_decision_failure_rolls_back_physical_movement_and_retry_recovers():void
|
||||
|
||||
private function closeProposal(int $id, string $action, int $version = 1)
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$this->actingAs($this->f['receiver']);$fault=true;DB::listen(function($q)use(&$fault){if($fault&&preg_match('/insert into .*supply_records/i',$q->sql)){$fault=false;throw new \RuntimeException('Synthetic native return decision failure');}});
|
||||
$this->withoutExceptionHandling();try{$this->confirm($p);$this->fail('Missing fault');}catch(\RuntimeException $e){$this->assertSame('Synthetic native return decision failure',$e->getMessage());}$this->withExceptionHandling();
|
||||
$this->assertSame(5000,$this->balance());$this->assertSame(2,StockMovement::query()->count());$this->assertSame(1,StockOperation::query()->count());$this->confirm($p)->assertOk();$this->assertSame(8000,$this->balance());
|
||||
return $this->postJson('/api/stock-returns/'.$id.'/'.$action, ['version' => $version, 'reason' => 'Synthetic reason for closing without physical movement.']);
|
||||
}
|
||||
public function test_undeclared_fraction_and_foreign_delivery_are_refused():void
|
||||
|
||||
private function balance(): int
|
||||
{
|
||||
$d=$this->payload;$d['declared_unused']=false;$this->prepare($d)->assertStatus(422);$d=$this->payload;$d['quantity']='0.0001';$this->prepare($d)->assertStatus(422);
|
||||
$foreign=User::factory()->create(['tenant_id'=>\App\Models\Tenant::query()->create(['name'=>'Synthetic other native company'])->id]);\supplyGrant($foreign,['warehouse_return_prepare','warehouse_return_confirm','warehouse_return_read','warehouse']);$this->actingAs($foreign);$this->prepare()->assertNotFound();$this->getJson('/api/stock-returns')->assertOk()->assertJsonPath('pagination.total',0);
|
||||
return (int) StockMovement::query()->sum('quantity_milli');
|
||||
}
|
||||
public function test_source_options_and_page_reuse_request_and_acknowledged_line():void
|
||||
|
||||
public function test_native_receipt_issue_acknowledgement_and_return_same_book_once(): void
|
||||
{
|
||||
$this->getJson('/api/stock-returns/sources?request_id='.$this->requestId)->assertOk()->assertJsonPath('options.0.delivery_event_id',$this->delivery)->assertJsonPath('options.0.item.code',$this->f['stock']->code)->assertJsonPath('can_prepare',true);
|
||||
$this->get('/stock/devolucoes-internas?request_id='.$this->requestId)->assertOk()->assertHeader('Cache-Control','max-age=0, no-store, private')->assertInertia(fn($page)=>$page->component('stock/returns')->where('requestId',$this->requestId)->where('canPrepare',true));
|
||||
$this->getJson('/api/stock-returns?state=wrong')->assertStatus(422);$this->getJson('/api/stock-returns?page=0')->assertStatus(422);$this->getJson('/api/stock-returns?tenant_id=999')->assertStatus(422);
|
||||
$this->actingAs($this->f['receiver']);$this->getJson('/api/stock-returns/sources?request_id='.$this->requestId)->assertOk()->assertJsonPath('can_prepare',false);$this->assertSame(5000,$this->balance());
|
||||
$this->actingAs($this->f['otherReceiver']);$this->get('/stock/operacoes')->assertOk()->assertInertia(fn($page)=>$page->where('canViewReturns',true));$this->get('/stock/devolucoes-internas')->assertOk()->assertInertia(fn($page)=>$page->component('stock/returns')->where('requestId',null)->where('canConfirm',false));$this->get('/stock/devolucoes-internas?request_id='.$this->requestId)->assertForbidden();
|
||||
$this->assertSame(5000, $this->balance());
|
||||
$p = $this->prepare()->assertOk()->assertJsonPath('impact.physical_before', '5000')->assertJsonPath('impact.physical_after', '8000')->json('id');
|
||||
$this->prepare()->assertOk()->assertJsonPath('id', $p)->assertJsonPath('replayed', true);
|
||||
$this->confirm($p)->assertForbidden();
|
||||
$prepared = SupplyRecord::query()->findOrFail($p);
|
||||
$this->assertSame($this->f['issuer']->id, $prepared->snapshot['source']['acknowledgement']['actor_id']);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->postJson('/api/stock-returns/'.$p.'/confirm', ['version' => 1, 'reason' => 'Synthetic receipt without acknowledgement'])->assertStatus(422);
|
||||
$m = $this->confirm($p)->assertOk()->json('movement_id');
|
||||
$this->confirm($p)->assertOk()->assertJsonPath('movement_id', $m)->assertJsonPath('replayed', true);
|
||||
$this->assertSame(8000, $this->balance());
|
||||
$this->assertSame(3, StockMovement::query()->count());
|
||||
$this->assertSame(2, StockOperation::query()->count());
|
||||
$this->assertSame(2, SupplyRecord::query()->where('kind', 'warehouse_return')->count());
|
||||
$history = $this->get('/stock/operacoes')->assertOk()->assertInertia(fn ($page) => $page->component('stock/operations')->where('canViewReturns', true)->where('operations.data.0.kind', 'workshop_return')->where('operations.data.0.snapshot.stock_item.id', $this->f['stock']->id)->where('operations.data.0.snapshot.warehouse.id', $this->f['warehouse']->id)->where('operations.data.0.snapshot.actor.id', $this->f['receiver']->id)->where('operations.data.0.snapshot.responsible.id', $this->f['receiver']->id));
|
||||
$historyRoot = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
|
||||
$this->assertNotFalse($historyRoot);
|
||||
file_put_contents($historyRoot.'/native-stock-history-page.json', json_encode($history->viewData('page'), JSON_THROW_ON_ERROR));
|
||||
$this->getJson('/api/stock-returns?state=confirmed')->assertOk()->assertJsonPath('pagination.total', 1)->assertJsonPath('rows.0.version', 2);
|
||||
$this->getJson('/api/stock-returns?state=prepared')->assertOk()->assertJsonPath('pagination.total', 0);
|
||||
$this->assertTrue(DB::table('audit_logs')->where('tenant_id', $this->f['tenant']->id)->where('action', 'warehouse_return.confirmed')->exists());
|
||||
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
|
||||
$this->assertNotFalse($root);
|
||||
file_put_contents($root.'/return-results.json', json_encode(['kind' => 'native_receipt_internal_issue_and_return', 'tenant' => $this->f['tenant']->id, 'warehouse' => $this->f['warehouse']->id, 'item' => $this->f['stock']->id, 'return_movement' => $m, 'request_id' => $this->requestId, 'physical_milli' => '8000', 'native_movements' => 3, 'shared_return_manifest_sha256' => hash_file('sha256', base_path('packages/inventory-return/releases/0.1.0/manifest.json'))], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
public function test_source_issue_with_return_cannot_be_reversed_as_a_whole():void
|
||||
|
||||
public function test_stale_capacity_idempotency_versions_rights_and_context_refuse_effect(): void
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$this->actingAs($this->f['receiver']);$this->confirm($p)->assertOk();$operation=(int)StockOperation::query()->where('kind','issue')->value('id');
|
||||
try{app(\App\Services\InventoryReversals::class)->basis(['source_kind'=>'operation','source_operation_id'=>$operation]);$this->fail('Original issue with return must not be reversed');}catch(\Illuminate\Validation\ValidationException $e){$this->assertStringContainsString('devolução física',implode(' ',array_merge(...array_values($e->errors()))));}
|
||||
$this->assertSame(8000,$this->balance());
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$changed = $this->payload;
|
||||
$changed['quantity'] = '2.000';
|
||||
$this->prepare($changed)->assertConflict();
|
||||
$second = $this->payload;
|
||||
$second['operation_key'] = (string) Str::uuid();
|
||||
$other = $this->prepare($second)->assertOk()->json('id');
|
||||
$this->actingAs($this->f['otherReceiver']);
|
||||
$this->confirm($p)->assertForbidden();
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p, 2)->assertStatus(422);
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->confirm($other)->assertConflict();
|
||||
$this->assertSame(8000, $this->balance());
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$second['quantity'] = '2.001';
|
||||
$second['operation_key'] = (string) Str::uuid();
|
||||
$this->prepare($second)->assertConflict();
|
||||
$second['quantity'] = '2.000';
|
||||
$second['operation_key'] = (string) Str::uuid();
|
||||
$p = $this->prepare($second)->assertOk()->json('id');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->assertSame(10000, $this->balance());
|
||||
config(['stock_returns.enabled' => false]);
|
||||
$this->getJson('/api/stock-returns')->assertStatus(503);
|
||||
$this->assertSame(10000, $this->balance());
|
||||
}
|
||||
public function test_concurrent_native_confirmation_waits_then_replays_one_movement():void
|
||||
|
||||
public function test_decision_failure_rolls_back_physical_movement_and_retry_recovers(): void
|
||||
{
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$fault = true;
|
||||
DB::listen(function ($q) use (&$fault) {
|
||||
if ($fault && preg_match('/insert into .*supply_records/i', $q->sql)) {
|
||||
$fault = false;
|
||||
throw new \RuntimeException('Synthetic native return decision failure');
|
||||
}
|
||||
});
|
||||
$this->withoutExceptionHandling();
|
||||
try {
|
||||
$this->confirm($p);
|
||||
$this->fail('Missing fault');
|
||||
} catch (\RuntimeException $e) {
|
||||
$this->assertSame('Synthetic native return decision failure', $e->getMessage());
|
||||
}$this->withExceptionHandling();
|
||||
$this->assertSame(5000, $this->balance());
|
||||
$this->assertSame(2, StockMovement::query()->count());
|
||||
$this->assertSame(1, StockOperation::query()->count());
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->assertSame(8000, $this->balance());
|
||||
}
|
||||
|
||||
public function test_undeclared_fraction_and_foreign_delivery_are_refused(): void
|
||||
{
|
||||
$d = $this->payload;
|
||||
$d['declared_unused'] = false;
|
||||
$this->prepare($d)->assertStatus(422);
|
||||
$d = $this->payload;
|
||||
$d['quantity'] = '0.0001';
|
||||
$this->prepare($d)->assertStatus(422);
|
||||
$foreign = User::factory()->create(['tenant_id' => Tenant::query()->create(['name' => 'Synthetic other native company'])->id]);
|
||||
\supplyGrant($foreign, ['warehouse_return_prepare', 'warehouse_return_confirm', 'warehouse_return_read', 'warehouse']);
|
||||
$this->actingAs($foreign);
|
||||
$this->prepare()->assertNotFound();
|
||||
$this->getJson('/api/stock-returns')->assertOk()->assertJsonPath('pagination.total', 0);
|
||||
}
|
||||
|
||||
public function test_source_options_and_page_reuse_request_and_acknowledged_line(): void
|
||||
{
|
||||
$this->getJson('/api/stock-returns/sources?request_id='.$this->requestId)->assertOk()->assertJsonPath('options.0.delivery_event_id', $this->delivery)->assertJsonPath('options.0.item.code', $this->f['stock']->code)->assertJsonPath('can_prepare', true);
|
||||
$this->get('/stock/devolucoes-internas?request_id='.$this->requestId)->assertOk()->assertHeader('Cache-Control', 'max-age=0, no-store, private')->assertInertia(fn ($page) => $page->component('stock/returns')->where('requestId', $this->requestId)->where('canPrepare', true));
|
||||
$this->getJson('/api/stock-returns?state=wrong')->assertStatus(422);
|
||||
$this->getJson('/api/stock-returns?page=0')->assertStatus(422);
|
||||
$this->getJson('/api/stock-returns?tenant_id=999')->assertStatus(422);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->getJson('/api/stock-returns/sources?request_id='.$this->requestId)->assertOk()->assertJsonPath('can_prepare', false);
|
||||
$this->assertSame(5000, $this->balance());
|
||||
$this->actingAs($this->f['otherReceiver']);
|
||||
$this->get('/stock/operacoes')->assertOk()->assertInertia(fn ($page) => $page->where('canViewReturns', true));
|
||||
$this->get('/stock/devolucoes-internas')->assertOk()->assertInertia(fn ($page) => $page->component('stock/returns')->where('requestId', null)->where('canConfirm', false));
|
||||
$this->get('/stock/devolucoes-internas?request_id='.$this->requestId)->assertForbidden();
|
||||
}
|
||||
|
||||
public function test_source_issue_with_return_cannot_be_reversed_as_a_whole(): void
|
||||
{
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p)->assertOk();
|
||||
$operation = (int) StockOperation::query()->where('kind', 'issue')->value('id');
|
||||
try {
|
||||
app(InventoryReversals::class)->basis(['source_kind' => 'operation', 'source_operation_id' => $operation]);
|
||||
$this->fail('Original issue with return must not be reversed');
|
||||
} catch (ValidationException $e) {
|
||||
$this->assertStringContainsString('devolução física', implode(' ', array_merge(...array_values($e->errors()))));
|
||||
}
|
||||
$this->assertSame(8000, $this->balance());
|
||||
}
|
||||
|
||||
public function test_concurrent_native_confirmation_waits_then_replays_one_movement(): void
|
||||
{
|
||||
$this->nativeRace();
|
||||
}
|
||||
private function nativeRace(?int $given=null,?int $workerProposal=null,int $workerStatus=200,bool $parentWithdraw=false,?User $workerActor=null,string $workerAction='confirm'):void
|
||||
|
||||
private function nativeRace(?int $given = null, ?int $workerProposal = null, int $workerStatus = 200, bool $parentWithdraw = false, ?User $workerActor = null, string $workerAction = 'confirm'): void
|
||||
{
|
||||
$p=$given??$this->prepare()->assertOk()->json('id');$this->actingAs($this->f[$parentWithdraw?'issuer':'receiver']);$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$dir=$root.'/return-race-'.bin2hex(random_bytes(6));mkdir($dir,0700,true);$input=$dir.'/worker.json';$application='native_return_'.bin2hex(random_bytes(6));$process=null;
|
||||
file_put_contents($input,json_encode(['actor'=>($workerActor??$this->f['receiver'])->id,'proposal'=>$workerProposal??$p,'application'=>$application,'action'=>$workerAction],JSON_THROW_ON_ERROR));DB::beginTransaction();
|
||||
try{$winner=$parentWithdraw?$this->closeProposal($p,'withdraw')->assertOk()->json('id'):$this->confirm($p)->assertOk()->json('movement_id');$pipes=[];$process=proc_open([PHP_BINARY,base_path('tests/Support/warehouse-return-worker.php'),$input],[0=>['pipe','r'],1=>['file',$dir.'/stdout','w'],2=>['file',$dir.'/stderr','w']],$pipes,base_path());$this->assertIsResource($process);fclose($pipes[0]);$parent=(int)DB::selectOne('SELECT pg_backend_pid() AS id')->id;$wait=null;$deadline=microtime(true)+10;
|
||||
do{DB::select('SELECT pg_stat_clear_snapshot()');$wait=DB::selectOne("SELECT to_json(pg_blocking_pids(pid)) AS blockers FROM pg_stat_activity WHERE application_name=? AND wait_event_type='Lock'",[$application]);if(!$wait)usleep(25000);}while(!$wait&µtime(true)<$deadline);$this->assertNotNull($wait);$this->assertContains($parent,json_decode($wait->blockers,true));DB::commit();
|
||||
$deadline=microtime(true)+15;do{$status=proc_get_status($process);if(!$status['running'])break;usleep(25000);}while(microtime(true)<$deadline);$this->assertFalse($status['running']);$exit=proc_close($process);$process=null;if($exit===-1)$exit=$status['exitcode'];$this->assertSame(0,$exit);$result=json_decode(file_get_contents($input.'.result'),true);$this->assertSame($workerStatus,$result['status']);if($workerStatus===200){$this->assertTrue($result['result']['replayed']);$this->assertSame($winner,$result['result']['movement_id']);}
|
||||
}finally{if(is_resource($process)){proc_terminate($process);proc_close($process);}while(DB::transactionLevel()>0)DB::rollBack();}
|
||||
$this->assertSame($parentWithdraw?5000:8000,$this->balance());$this->assertSame($parentWithdraw?2:3,StockMovement::query()->count());$this->assertSame(1,SupplyRecord::query()->where('kind','warehouse_return')->where('state',$parentWithdraw?'withdrawn':'confirmed')->count());
|
||||
$p = $given ?? $this->prepare()->assertOk()->json('id');
|
||||
$this->actingAs($this->f[$parentWithdraw ? 'issuer' : 'receiver']);
|
||||
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
|
||||
$dir = $root.'/return-race-'.bin2hex(random_bytes(6));
|
||||
mkdir($dir, 0700, true);
|
||||
$input = $dir.'/worker.json';
|
||||
$application = 'native_return_'.bin2hex(random_bytes(6));
|
||||
$process = null;
|
||||
file_put_contents($input, json_encode(['actor' => ($workerActor ?? $this->f['receiver'])->id, 'proposal' => $workerProposal ?? $p, 'application' => $application, 'action' => $workerAction], JSON_THROW_ON_ERROR));
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
$winner = $parentWithdraw ? $this->closeProposal($p, 'withdraw')->assertOk()->json('id') : $this->confirm($p)->assertOk()->json('movement_id');
|
||||
$pipes = [];
|
||||
$process = proc_open([PHP_BINARY, base_path('tests/Support/warehouse-return-worker.php'), $input], [0 => ['pipe', 'r'], 1 => ['file', $dir.'/stdout', 'w'], 2 => ['file', $dir.'/stderr', 'w']], $pipes, base_path());
|
||||
$this->assertIsResource($process);
|
||||
fclose($pipes[0]);
|
||||
$parent = (int) DB::selectOne('SELECT pg_backend_pid() AS id')->id;
|
||||
$wait = null;
|
||||
$deadline = microtime(true) + 10;
|
||||
do {
|
||||
DB::select('SELECT pg_stat_clear_snapshot()');
|
||||
$wait = DB::selectOne("SELECT to_json(pg_blocking_pids(pid)) AS blockers FROM pg_stat_activity WHERE application_name=? AND wait_event_type='Lock'", [$application]);
|
||||
if (! $wait) {
|
||||
usleep(25000);
|
||||
}
|
||||
} while (! $wait && microtime(true) < $deadline);
|
||||
$this->assertNotNull($wait);
|
||||
$this->assertContains($parent, json_decode($wait->blockers, true));
|
||||
DB::commit();
|
||||
$deadline = microtime(true) + 15;
|
||||
do {
|
||||
$status = proc_get_status($process);
|
||||
if (! $status['running']) {
|
||||
break;
|
||||
}usleep(25000);
|
||||
} while (microtime(true) < $deadline);
|
||||
$this->assertFalse($status['running']);
|
||||
$exit = proc_close($process);
|
||||
$process = null;
|
||||
if ($exit === -1) {
|
||||
$exit = $status['exitcode'];
|
||||
}$this->assertSame(0, $exit);
|
||||
$result = json_decode(file_get_contents($input.'.result'), true);
|
||||
$this->assertSame($workerStatus, $result['status']);
|
||||
if ($workerStatus === 200) {
|
||||
$this->assertTrue($result['result']['replayed']);
|
||||
$this->assertSame($winner, $result['result']['movement_id']);
|
||||
}
|
||||
} finally {
|
||||
if (is_resource($process)) {
|
||||
proc_terminate($process);
|
||||
proc_close($process);
|
||||
}while (DB::transactionLevel() > 0) {
|
||||
DB::rollBack();
|
||||
}
|
||||
}
|
||||
$this->assertSame($parentWithdraw ? 5000 : 8000, $this->balance());
|
||||
$this->assertSame($parentWithdraw ? 2 : 3, StockMovement::query()->count());
|
||||
$this->assertSame(1, SupplyRecord::query()->where('kind', 'warehouse_return')->where('state', $parentWithdraw ? 'withdrawn' : 'confirmed')->count());
|
||||
}
|
||||
public function test_competing_native_returns_cannot_exceed_the_original_delivery():void
|
||||
|
||||
public function test_competing_native_returns_cannot_exceed_the_original_delivery(): void
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$d=$this->payload;$d['operation_key']=(string)Str::uuid();$other=$this->prepare($d)->assertOk()->json('id');$this->nativeRace($p,$other,409);
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$d = $this->payload;
|
||||
$d['operation_key'] = (string) Str::uuid();
|
||||
$other = $this->prepare($d)->assertOk()->json('id');
|
||||
$this->nativeRace($p, $other, 409);
|
||||
}
|
||||
public function test_expired_and_maintenance_profiles_are_revalidated_at_confirmation():void
|
||||
|
||||
public function test_expired_and_maintenance_profiles_are_revalidated_at_confirmation(): void
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$this->actingAs($this->f['receiver']);DB::table('organization_memberships')->where('user_id',$this->f['receiver']->id)->update(['maintenance'=>true]);$this->confirm($p)->assertForbidden();DB::table('organization_memberships')->where('user_id',$this->f['receiver']->id)->update(['maintenance'=>false,'expires_at'=>now()->subMinute()]);$this->confirm($p)->assertForbidden();$this->assertSame(5000,$this->balance());DB::table('organization_memberships')->where('user_id',$this->f['receiver']->id)->update(['expires_at'=>null]);$this->confirm($p)->assertOk();$this->assertSame(8000,$this->balance());
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['maintenance' => true]);
|
||||
$this->confirm($p)->assertForbidden();
|
||||
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['maintenance' => false, 'expires_at' => now()->subMinute()]);
|
||||
$this->confirm($p)->assertForbidden();
|
||||
$this->assertSame(5000, $this->balance());
|
||||
DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->update(['expires_at' => null]);
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->assertSame(8000, $this->balance());
|
||||
}
|
||||
public function test_configured_context_and_permissions_cannot_be_inherited_from_people_profile():void
|
||||
|
||||
public function test_configured_context_and_permissions_cannot_be_inherited_from_people_profile(): void
|
||||
{
|
||||
$tenant=$this->f['tenant']->id;$this->f['tenant']->update(['rules_provisional'=>false,'work_context_policy'=>['revision'=>1,'enabled'=>['procurement.internal','people.internal']]]);config(['work_context.entitlements.'.$tenant=>['procurement.internal','people.internal']]);DB::table('organization_profiles')->where('tenant_id',$tenant)->update(['work_contexts'=>json_encode(['procurement.internal'])]);
|
||||
$this->prepare()->assertForbidden();$this->post('/contexto',['area'=>'procurement','option'=>'procurement.internal'])->assertRedirect('/dashboard');$p=$this->prepare()->assertOk()->json('id');$this->actingAs($this->f['receiver']);$this->confirm($p)->assertForbidden();$this->post('/contexto',['area'=>'procurement','option'=>'procurement.internal'])->assertRedirect('/dashboard');
|
||||
$profiles=DB::table('organization_memberships')->where('user_id',$this->f['receiver']->id)->pluck('profile_id');DB::table('organization_profiles')->whereIn('id',$profiles)->update(['permissions'=>json_encode(['warehouse','warehouse_request_deliver','warehouse_return_read'])]);\supplyGrant($this->f['receiver'],['warehouse_return_confirm']);$other=DB::table('organization_profiles')->where('tenant_id',$tenant)->whereNotIn('id',$profiles)->orderByDesc('id')->value('id');DB::table('organization_profiles')->where('id',$other)->update(['work_contexts'=>json_encode(['people.internal'])]);
|
||||
$this->confirm($p)->assertForbidden();$this->assertSame(5000,$this->balance());DB::table('organization_profiles')->where('id',$other)->update(['work_contexts'=>json_encode(['procurement.internal'])]);$this->confirm($p)->assertOk();$this->assertSame(8000,$this->balance());
|
||||
$tenant = $this->f['tenant']->id;
|
||||
$this->f['tenant']->update(['rules_provisional' => false, 'work_context_policy' => ['revision' => 1, 'enabled' => ['procurement.internal', 'people.internal']]]);
|
||||
config(['work_context.entitlements.'.$tenant => ['procurement.internal', 'people.internal']]);
|
||||
DB::table('organization_profiles')->where('tenant_id', $tenant)->update(['work_contexts' => json_encode(['procurement.internal'])]);
|
||||
$this->prepare()->assertForbidden();
|
||||
$this->post('/contexto', ['area' => 'procurement', 'option' => 'procurement.internal'])->assertRedirect('/dashboard');
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p)->assertForbidden();
|
||||
$this->post('/contexto', ['area' => 'procurement', 'option' => 'procurement.internal'])->assertRedirect('/dashboard');
|
||||
$profiles = DB::table('organization_memberships')->where('user_id', $this->f['receiver']->id)->pluck('profile_id');
|
||||
DB::table('organization_profiles')->whereIn('id', $profiles)->update(['permissions' => json_encode(['warehouse', 'warehouse_request_deliver', 'warehouse_return_read'])]);
|
||||
\supplyGrant($this->f['receiver'], ['warehouse_return_confirm']);
|
||||
$other = DB::table('organization_profiles')->where('tenant_id', $tenant)->whereNotIn('id', $profiles)->orderByDesc('id')->value('id');
|
||||
DB::table('organization_profiles')->where('id', $other)->update(['work_contexts' => json_encode(['people.internal'])]);
|
||||
$this->confirm($p)->assertForbidden();
|
||||
$this->assertSame(5000, $this->balance());
|
||||
DB::table('organization_profiles')->where('id', $other)->update(['work_contexts' => json_encode(['procurement.internal'])]);
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->assertSame(8000, $this->balance());
|
||||
}
|
||||
public function test_return_signals_existing_replenishment_only_once_and_inside_transaction():void
|
||||
|
||||
public function test_return_signals_existing_replenishment_only_once_and_inside_transaction(): void
|
||||
{
|
||||
$spy=new class extends \App\Services\AutomaticPurchases {public array $calls=[];public function signal(User $actor,int $item,int $warehouse):void {$this->calls[]=['actor'=>$actor->id,'item'=>$item,'warehouse'=>$warehouse,'transaction_level'=>DB::transactionLevel()];}};
|
||||
$this->app->instance(\App\Services\AutomaticPurchases::class,$spy);$p=$this->prepare()->assertOk()->json('id');$this->assertCount(0,$spy->calls);$this->actingAs($this->f['receiver']);$this->confirm($p)->assertOk();$this->confirm($p)->assertOk()->assertJsonPath('replayed',true);
|
||||
$this->assertCount(1,$spy->calls);$this->assertSame($this->f['stock']->id,$spy->calls[0]['item']);$this->assertSame($this->f['warehouse']->id,$spy->calls[0]['warehouse']);$this->assertGreaterThan(0,$spy->calls[0]['transaction_level']);$this->assertSame(8000,$this->balance());
|
||||
$spy = new class extends AutomaticPurchases
|
||||
{
|
||||
public array $calls = [];
|
||||
|
||||
public function signal(User $actor, int $item, int $warehouse): void
|
||||
{
|
||||
$this->calls[] = ['actor' => $actor->id, 'item' => $item, 'warehouse' => $warehouse, 'transaction_level' => DB::transactionLevel()];
|
||||
}
|
||||
};
|
||||
$this->app->instance(AutomaticPurchases::class, $spy);
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->assertCount(0, $spy->calls);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->confirm($p)->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->assertCount(1, $spy->calls);
|
||||
$this->assertSame($this->f['stock']->id, $spy->calls[0]['item']);
|
||||
$this->assertSame($this->f['warehouse']->id, $spy->calls[0]['warehouse']);
|
||||
$this->assertGreaterThan(0, $spy->calls[0]['transaction_level']);
|
||||
$this->assertSame(8000, $this->balance());
|
||||
}
|
||||
public function test_catalogue_rename_requires_new_review_preserving_original_and_unit_change_refuses():void
|
||||
|
||||
public function test_catalogue_rename_requires_new_review_preserving_original_and_unit_change_refuses(): void
|
||||
{
|
||||
$name=$this->f['stock']->name;$p=$this->prepare()->assertOk()->json('id');$this->f['stock']->update(['name'=>'Synthetic renamed article']);$this->actingAs($this->f['receiver']);$this->confirm($p)->assertConflict();$this->assertSame(5000,$this->balance());
|
||||
$this->actingAs($this->f['issuer']);$this->payload['operation_key']=(string)Str::uuid();$p=$this->prepare()->assertOk()->assertJsonPath('impact.item.name','Synthetic renamed article')->json('id');$this->assertSame($name,SupplyRecord::query()->findOrFail($p)->snapshot['source']['original_item']['name']);$this->actingAs($this->f['receiver']);$this->confirm($p)->assertOk();$this->assertSame(8000,$this->balance());
|
||||
$this->f['stock']->update(['unit'=>'KG']);$this->actingAs($this->f['issuer']);$this->payload['operation_key']=(string)Str::uuid();$this->payload['quantity']='1.000';$this->prepare()->assertConflict();$this->assertSame(8000,$this->balance());
|
||||
$name = $this->f['stock']->name;
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->f['stock']->update(['name' => 'Synthetic renamed article']);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p)->assertConflict();
|
||||
$this->assertSame(5000, $this->balance());
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$this->payload['operation_key'] = (string) Str::uuid();
|
||||
$p = $this->prepare()->assertOk()->assertJsonPath('impact.item.name', 'Synthetic renamed article')->json('id');
|
||||
$this->assertSame($name, SupplyRecord::query()->findOrFail($p)->snapshot['source']['original_item']['name']);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->assertSame(8000, $this->balance());
|
||||
$this->f['stock']->update(['unit' => 'KG']);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$this->payload['operation_key'] = (string) Str::uuid();
|
||||
$this->payload['quantity'] = '1.000';
|
||||
$this->prepare()->assertConflict();
|
||||
$this->assertSame(8000, $this->balance());
|
||||
}
|
||||
public function test_unavailable_private_package_returns_503_and_rolls_back_before_recovery():void
|
||||
|
||||
public function test_unavailable_private_package_returns_503_and_rolls_back_before_recovery(): void
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$this->actingAs($this->f['receiver']);$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$manifest=realpath(base_path('packages/inventory-return/releases/0.1.0/manifest.json'));$this->assertStringStartsWith($root.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR,$manifest);$original=file_get_contents($manifest);$this->assertNotFalse($original);
|
||||
try{file_put_contents($manifest,'{"synthetic_private_fault":true}');$this->confirm($p)->assertStatus(503);}finally{file_put_contents($manifest,$original);}
|
||||
$this->assertSame(5000,$this->balance());$this->assertSame(1,StockOperation::query()->count());$this->assertSame(2,StockMovement::query()->count());$this->confirm($p)->assertOk();$this->assertSame(8000,$this->balance());
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
|
||||
$manifest = realpath(base_path('packages/inventory-return/releases/0.1.0/manifest.json'));
|
||||
$this->assertStringStartsWith($root.DIRECTORY_SEPARATOR.'app'.DIRECTORY_SEPARATOR, $manifest);
|
||||
$original = file_get_contents($manifest);
|
||||
$this->assertNotFalse($original);
|
||||
try {
|
||||
file_put_contents($manifest, '{"synthetic_private_fault":true}');
|
||||
$this->confirm($p)->assertStatus(503);
|
||||
} finally {
|
||||
file_put_contents($manifest, $original);
|
||||
}
|
||||
$this->assertSame(5000, $this->balance());
|
||||
$this->assertSame(1, StockOperation::query()->count());
|
||||
$this->assertSame(2, StockMovement::query()->count());
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->assertSame(8000, $this->balance());
|
||||
}
|
||||
public function test_http_busy_response_leaves_proposal_unconfirmed_then_manual_retry_succeeds():void
|
||||
|
||||
public function test_http_busy_response_leaves_proposal_unconfirmed_then_manual_retry_succeeds(): void
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$this->actingAs($this->f['receiver']);$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$dir=$root.'/return-busy-'.bin2hex(random_bytes(6));mkdir($dir,0700,true);$input=$dir.'/worker.json';$appName='native_return_busy_'.bin2hex(random_bytes(6));$process=null;file_put_contents($input,json_encode(['actor'=>$this->f['receiver']->id,'proposal'=>$p,'application'=>$appName,'http'=>true],JSON_THROW_ON_ERROR));DB::beginTransaction();
|
||||
try{DB::table('tenants')->where('id',$this->f['tenant']->id)->lockForUpdate()->first();$pipes=[];$process=proc_open([PHP_BINARY,base_path('tests/Support/warehouse-return-worker.php'),$input],[0=>['pipe','r'],1=>['file',$dir.'/stdout','w'],2=>['file',$dir.'/stderr','w']],$pipes,base_path());$this->assertIsResource($process);fclose($pipes[0]);$parent=(int)DB::selectOne('SELECT pg_backend_pid() AS id')->id;$wait=null;$deadline=microtime(true)+10;
|
||||
do{DB::select('SELECT pg_stat_clear_snapshot()');$wait=DB::selectOne("SELECT to_json(pg_blocking_pids(pid)) AS blockers FROM pg_stat_activity WHERE application_name=? AND wait_event_type='Lock'",[$appName]);if(!$wait)usleep(25000);}while(!$wait&µtime(true)<$deadline);$this->assertNotNull($wait);$this->assertContains($parent,json_decode($wait->blockers,true));
|
||||
$deadline=microtime(true)+12;do{$status=proc_get_status($process);if(!$status['running'])break;usleep(25000);}while(microtime(true)<$deadline);$this->assertFalse($status['running']);$exit=proc_close($process);$process=null;if($exit===-1)$exit=$status['exitcode'];$this->assertSame(0,$exit);$r=json_decode(file_get_contents($input.'.result'),true);$this->assertSame(423,$r['status']);$this->assertSame('warehouse_return_busy',$r['result']['code']);$this->assertArrayNotHasKey('exception',$r['result']);$this->assertSame(5000,$this->balance());DB::commit();
|
||||
}finally{if(is_resource($process)){proc_terminate($process);proc_close($process);}while(DB::transactionLevel()>0)DB::rollBack();}
|
||||
$this->assertSame(0,SupplyRecord::query()->where('kind','warehouse_return')->where('state','confirmed')->count());$this->confirm($p)->assertOk();$this->assertSame(8000,$this->balance());
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
|
||||
$dir = $root.'/return-busy-'.bin2hex(random_bytes(6));
|
||||
mkdir($dir, 0700, true);
|
||||
$input = $dir.'/worker.json';
|
||||
$appName = 'native_return_busy_'.bin2hex(random_bytes(6));
|
||||
$process = null;
|
||||
file_put_contents($input, json_encode(['actor' => $this->f['receiver']->id, 'proposal' => $p, 'application' => $appName, 'http' => true], JSON_THROW_ON_ERROR));
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
DB::table('tenants')->where('id', $this->f['tenant']->id)->lockForUpdate()->first();
|
||||
$pipes = [];
|
||||
$process = proc_open([PHP_BINARY, base_path('tests/Support/warehouse-return-worker.php'), $input], [0 => ['pipe', 'r'], 1 => ['file', $dir.'/stdout', 'w'], 2 => ['file', $dir.'/stderr', 'w']], $pipes, base_path());
|
||||
$this->assertIsResource($process);
|
||||
fclose($pipes[0]);
|
||||
$parent = (int) DB::selectOne('SELECT pg_backend_pid() AS id')->id;
|
||||
$wait = null;
|
||||
$deadline = microtime(true) + 10;
|
||||
do {
|
||||
DB::select('SELECT pg_stat_clear_snapshot()');
|
||||
$wait = DB::selectOne("SELECT to_json(pg_blocking_pids(pid)) AS blockers FROM pg_stat_activity WHERE application_name=? AND wait_event_type='Lock'", [$appName]);
|
||||
if (! $wait) {
|
||||
usleep(25000);
|
||||
}
|
||||
} while (! $wait && microtime(true) < $deadline);
|
||||
$this->assertNotNull($wait);
|
||||
$this->assertContains($parent, json_decode($wait->blockers, true));
|
||||
$deadline = microtime(true) + 12;
|
||||
do {
|
||||
$status = proc_get_status($process);
|
||||
if (! $status['running']) {
|
||||
break;
|
||||
}usleep(25000);
|
||||
} while (microtime(true) < $deadline);
|
||||
$this->assertFalse($status['running']);
|
||||
$exit = proc_close($process);
|
||||
$process = null;
|
||||
if ($exit === -1) {
|
||||
$exit = $status['exitcode'];
|
||||
}$this->assertSame(0, $exit);
|
||||
$r = json_decode(file_get_contents($input.'.result'), true);
|
||||
$this->assertSame(423, $r['status']);
|
||||
$this->assertSame('warehouse_return_busy', $r['result']['code']);
|
||||
$this->assertArrayNotHasKey('exception', $r['result']);
|
||||
$this->assertSame(5000, $this->balance());
|
||||
DB::commit();
|
||||
} finally {
|
||||
if (is_resource($process)) {
|
||||
proc_terminate($process);
|
||||
proc_close($process);
|
||||
}while (DB::transactionLevel() > 0) {
|
||||
DB::rollBack();
|
||||
}
|
||||
}
|
||||
$this->assertSame(0, SupplyRecord::query()->where('kind', 'warehouse_return')->where('state', 'confirmed')->count());
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->assertSame(8000, $this->balance());
|
||||
}
|
||||
public function test_withdrawal_and_independent_rejection_close_pending_without_stock_effect():void
|
||||
|
||||
public function test_withdrawal_and_independent_rejection_close_pending_without_stock_effect(): void
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$this->closeProposal($p,'reject')->assertForbidden();\supplyGrant($this->f['receiver'],['warehouse_return_prepare']);$this->actingAs($this->f['receiver']);$this->closeProposal($p,'withdraw')->assertForbidden();$this->actingAs($this->f['issuer']);$this->closeProposal($p,'withdraw',2)->assertConflict();$this->closeProposal($p,'withdraw')->assertOk()->assertJsonPath('state','withdrawn');$this->closeProposal($p,'withdraw')->assertOk()->assertJsonPath('replayed',true);$this->prepare()->assertOk()->assertJsonPath('id',$p)->assertJsonPath('state','withdrawn');
|
||||
$this->actingAs($this->f['receiver']);$this->confirm($p)->assertConflict();$this->getJson('/api/stock-returns?state=prepared')->assertOk()->assertJsonPath('pagination.total',0);$this->getJson('/api/stock-returns?state=withdrawn')->assertOk()->assertJsonPath('pagination.total',1);
|
||||
$this->actingAs($this->f['issuer']);$this->payload['operation_key']=(string)Str::uuid();$p=$this->prepare()->assertOk()->json('id');$this->actingAs($this->f['receiver']);$this->closeProposal($p,'reject')->assertOk()->assertJsonPath('state','rejected');$this->closeProposal($p,'reject')->assertOk()->assertJsonPath('replayed',true);$this->confirm($p)->assertConflict();$this->getJson('/api/stock-returns?state=rejected')->assertOk()->assertJsonPath('pagination.total',1);
|
||||
$this->assertSame(5000,$this->balance());$this->assertSame(2,StockMovement::query()->count());$this->assertSame(1,StockOperation::query()->count());$this->assertSame(4,SupplyRecord::query()->where('kind','warehouse_return')->count());$this->assertSame(1,DB::table('audit_logs')->where('tenant_id',$this->f['tenant']->id)->where('action','warehouse_return.withdrawn')->count());
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->closeProposal($p, 'reject')->assertForbidden();
|
||||
\supplyGrant($this->f['receiver'], ['warehouse_return_prepare']);
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->closeProposal($p, 'withdraw')->assertForbidden();
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$this->closeProposal($p, 'withdraw', 2)->assertConflict();
|
||||
$this->closeProposal($p, 'withdraw')->assertOk()->assertJsonPath('state', 'withdrawn');
|
||||
$this->closeProposal($p, 'withdraw')->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->prepare()->assertOk()->assertJsonPath('id', $p)->assertJsonPath('state', 'withdrawn');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p)->assertConflict();
|
||||
$this->getJson('/api/stock-returns?state=prepared')->assertOk()->assertJsonPath('pagination.total', 0);
|
||||
$this->getJson('/api/stock-returns?state=withdrawn')->assertOk()->assertJsonPath('pagination.total', 1);
|
||||
$this->actingAs($this->f['issuer']);
|
||||
$this->payload['operation_key'] = (string) Str::uuid();
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->closeProposal($p, 'reject')->assertOk()->assertJsonPath('state', 'rejected');
|
||||
$this->closeProposal($p, 'reject')->assertOk()->assertJsonPath('replayed', true);
|
||||
$this->confirm($p)->assertConflict();
|
||||
$this->getJson('/api/stock-returns?state=rejected')->assertOk()->assertJsonPath('pagination.total', 1);
|
||||
$this->assertSame(5000, $this->balance());
|
||||
$this->assertSame(2, StockMovement::query()->count());
|
||||
$this->assertSame(1, StockOperation::query()->count());
|
||||
$this->assertSame(4, SupplyRecord::query()->where('kind', 'warehouse_return')->count());
|
||||
$this->assertSame(1, DB::table('audit_logs')->where('tenant_id', $this->f['tenant']->id)->where('action', 'warehouse_return.withdrawn')->count());
|
||||
}
|
||||
public function test_withdrawal_wins_before_confirmation_without_a_movement():void
|
||||
|
||||
public function test_withdrawal_wins_before_confirmation_without_a_movement(): void
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$this->nativeRace($p,$p,409,true);
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->nativeRace($p, $p, 409, true);
|
||||
}
|
||||
public function test_confirmation_wins_before_withdrawal_without_duplicate_terminal_state():void
|
||||
|
||||
public function test_confirmation_wins_before_withdrawal_without_duplicate_terminal_state(): void
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$this->nativeRace($p,$p,409,false,$this->f['issuer'],'withdraw');
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->nativeRace($p, $p, 409, false, $this->f['issuer'], 'withdraw');
|
||||
}
|
||||
public function test_return_changes_physical_history_without_silently_changing_gross_issue_forecast():void
|
||||
|
||||
public function test_return_changes_physical_history_without_silently_changing_gross_issue_forecast(): void
|
||||
{
|
||||
$history=app(\App\Services\SupplyHistory::class);$date=now()->toDateString();
|
||||
$before=$history->analyse($this->f['stock']->id,$this->f['warehouse']->id,$date,$date);
|
||||
$p=$this->prepare()->assertOk()->json('id');$this->actingAs($this->f['receiver']);$this->confirm($p)->assertOk();
|
||||
$after=$history->analyse($this->f['stock']->id,$this->f['warehouse']->id,$date,$date);
|
||||
$this->assertSame(5000,$before['total_milli']);$this->assertSame(5000,$after['total_milli']);
|
||||
$this->assertSame($before['daily_mean_milli'],$after['daily_mean_milli']);
|
||||
$this->assertSame(5000,$before['series'][0]['balance_milli']);$this->assertSame(8000,$after['series'][0]['balance_milli']);
|
||||
$this->assertSame(1,$after['movement_types']['workshop_return_in']);$this->assertNotSame($before['source_hash'],$after['source_hash']);
|
||||
$this->assertSame($before['convention'],$after['convention']);$this->assertSame(3,$after['movement_count']);
|
||||
$history = app(SupplyHistory::class);
|
||||
$date = now()->toDateString();
|
||||
$before = $history->analyse($this->f['stock']->id, $this->f['warehouse']->id, $date, $date);
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p)->assertOk();
|
||||
$after = $history->analyse($this->f['stock']->id, $this->f['warehouse']->id, $date, $date);
|
||||
$this->assertSame(5000, $before['total_milli']);
|
||||
$this->assertSame(5000, $after['total_milli']);
|
||||
$this->assertSame($before['daily_mean_milli'], $after['daily_mean_milli']);
|
||||
$this->assertSame(5000, $before['series'][0]['balance_milli']);
|
||||
$this->assertSame(8000, $after['series'][0]['balance_milli']);
|
||||
$this->assertSame(1, $after['movement_types']['workshop_return_in']);
|
||||
$this->assertNotSame($before['source_hash'], $after['source_hash']);
|
||||
$this->assertSame($before['convention'], $after['convention']);
|
||||
$this->assertSame(3, $after['movement_count']);
|
||||
$this->assertSame(8000, $this->balance());
|
||||
file_put_contents((string) getenv('STOCK_RECEIPT_ROOT').'/return-forecast-boundary.json', json_encode(['gross_issue_milli' => 5000, 'returned_milli' => 3000, 'physical_before_milli' => 5000, 'physical_after_milli' => 8000, 'historical_mean_unchanged' => true, 'source_hash_changed' => true, 'planning_convention_unchanged' => true, 'net_consumption_forecast_implemented' => false], JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
public function test_history_pages_and_batch_preparer_lookup_cover_the_full_pending_universe(): void
|
||||
{
|
||||
$p = $this->prepare()->assertOk()->json('id');
|
||||
$row = SupplyRecord::query()->findOrFail($p)->getAttributes();
|
||||
unset($row['id']);
|
||||
for ($i = 0; $i < 50; $i++) {
|
||||
$copy = $row;
|
||||
$key = (string) Str::uuid();
|
||||
$copy['record_key'] = $key;
|
||||
$copy['operation_key'] = $key;
|
||||
$data = json_decode($copy['data'], true, 512, JSON_THROW_ON_ERROR);
|
||||
$data['operation_key'] = $key;
|
||||
$copy['data'] = json_encode($data, JSON_THROW_ON_ERROR);
|
||||
$copy['input_hash'] = hash('sha256', $copy['data']);
|
||||
DB::table('supply_records')->insert($copy);
|
||||
}
|
||||
$queries = [];
|
||||
$capture = true;
|
||||
DB::listen(function ($q) use (&$queries, &$capture) {
|
||||
if ($capture && str_starts_with(strtolower($q->sql), 'select') && str_contains($q->sql, '"supply_records"')) {
|
||||
$queries[] = $q->sql;
|
||||
}
|
||||
});
|
||||
$first = $this->getJson('/api/stock-returns')->assertOk()->assertJsonPath('pagination.total', 51)->assertJsonPath('pagination.last_page', 3)->assertJsonCount(25, 'rows')->json('rows');
|
||||
$capture = false;
|
||||
$this->assertLessThanOrEqual(4,count($queries));
|
||||
$second = $this->getJson('/api/stock-returns?page=2')->assertOk()->assertJsonCount(25,'rows')->json('rows');
|
||||
$this->assertEmpty(array_intersect(array_column($first,'id'),array_column($second,'id')));
|
||||
$this->assertGreaterThan($second[0]['id'],$first[24]['id']);
|
||||
$this->getJson('/api/stock-returns?page=3')->assertOk()->assertJsonCount(1,'rows');
|
||||
$this->actingAs($this->f['receiver']);
|
||||
$this->confirm($p)->assertOk();
|
||||
$this->getJson('/api/stock-returns?state=prepared')->assertOk()->assertJsonPath('pagination.total',50);
|
||||
$this->getJson('/api/stock-returns?state=confirmed')->assertOk()->assertJsonPath('pagination.total',1);
|
||||
$this->assertSame(8000,$this->balance());
|
||||
file_put_contents((string)getenv('STOCK_RECEIPT_ROOT').'/return-forecast-boundary.json',json_encode(['gross_issue_milli'=>5000,'returned_milli'=>3000,'physical_before_milli'=>5000,'physical_after_milli'=>8000,'historical_mean_unchanged'=>true,'source_hash_changed'=>true,'planning_convention_unchanged'=>true,'net_consumption_forecast_implemented'=>false],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
}
|
||||
public function test_history_pages_and_batch_preparer_lookup_cover_the_full_pending_universe():void
|
||||
{
|
||||
$p=$this->prepare()->assertOk()->json('id');$row=SupplyRecord::query()->findOrFail($p)->getAttributes();unset($row['id']);for($i=0;$i<50;$i++){$copy=$row;$key=(string)Str::uuid();$copy['record_key']=$key;$copy['operation_key']=$key;$data=json_decode($copy['data'],true,512,JSON_THROW_ON_ERROR);$data['operation_key']=$key;$copy['data']=json_encode($data,JSON_THROW_ON_ERROR);$copy['input_hash']=hash('sha256',$copy['data']);DB::table('supply_records')->insert($copy);}
|
||||
$queries=[];$capture=true;DB::listen(function($q)use(&$queries,&$capture){if($capture&&str_starts_with(strtolower($q->sql),'select')&&str_contains($q->sql,'"supply_records"'))$queries[]=$q->sql;});$first=$this->getJson('/api/stock-returns')->assertOk()->assertJsonPath('pagination.total',51)->assertJsonPath('pagination.last_page',3)->assertJsonCount(25,'rows')->json('rows');$capture=false;$this->assertLessThanOrEqual(4,count($queries));
|
||||
$second=$this->getJson('/api/stock-returns?page=2')->assertOk()->assertJsonCount(25,'rows')->json('rows');$this->assertEmpty(array_intersect(array_column($first,'id'),array_column($second,'id')));$this->assertGreaterThan($second[0]['id'],$first[24]['id']);$this->getJson('/api/stock-returns?page=3')->assertOk()->assertJsonCount(1,'rows');
|
||||
$this->actingAs($this->f['receiver']);$this->confirm($p)->assertOk();$this->getJson('/api/stock-returns?state=prepared')->assertOk()->assertJsonPath('pagination.total',50);$this->getJson('/api/stock-returns?state=confirmed')->assertOk()->assertJsonPath('pagination.total',1);$this->assertSame(8000,$this->balance());
|
||||
file_put_contents((string)getenv('STOCK_RECEIPT_ROOT').'/return-history-metrics.json',json_encode(['fixture_records'=>51,'page_size'=>25,'supply_record_selects_for_page'=>count($queries),'pages_disjoint'=>true,'state_filters_cover_latest_versions'=>true,'not_a_load_capacity_benchmark'=>true],JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
file_put_contents((string) getenv('STOCK_RECEIPT_ROOT').'/return-history-metrics.json',json_encode(['fixture_records' => 51, 'page_size' => 25, 'supply_record_selects_for_page' => count($queries), 'pages_disjoint' => true, 'state_filters_cover_latest_versions' => true, 'not_a_load_capacity_benchmark' => true],JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
@@ -1,218 +1,409 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Integration;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\{SgfInvoiceDispatches,InvoiceWorkflow};
|
||||
use Illuminate\Support\Facades\{DB,Schema,Http};
|
||||
use App\Services\SgfInvoiceDispatches;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\Request as Outbound;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
use Tests\TestCase;
|
||||
|
||||
/** Only this schema and in-memory SQLite. Never RefreshDatabase or a pilot connection. */
|
||||
final class SgfInvoiceDispatchesTest extends \Tests\TestCase
|
||||
final class SgfInvoiceDispatchesTest extends TestCase
|
||||
{
|
||||
private User $actor;
|
||||
|
||||
private SgfInvoiceDispatches $service;
|
||||
private array $remote=[];
|
||||
private bool $lose=false;
|
||||
|
||||
private array $remote = [];
|
||||
|
||||
private bool $lose = false;
|
||||
|
||||
private string $privateRoot;
|
||||
|
||||
public function createApplication()
|
||||
{
|
||||
$repo=dirname(__DIR__,2);$this->privateRoot='C:/laragon/data/sgf-tempo/run/sgc-dispatch-tests-'.bin2hex(random_bytes(6));
|
||||
foreach(['logs','framework/views','framework/sessions','framework/cache/data']as$d)mkdir($this->privateRoot.'/storage/'.$d,0700,true);
|
||||
foreach(['DB_CONNECTION'=>'sqlite','DB_DATABASE'=>':memory:','DB_URL'=>'','APP_ENV'=>'testing',
|
||||
'APP_CONFIG_CACHE'=>$this->privateRoot.'/config.php','APP_SERVICES_CACHE'=>$this->privateRoot.'/services.php','APP_PACKAGES_CACHE'=>$this->privateRoot.'/packages.php',
|
||||
'APP_ROUTES_CACHE'=>$this->privateRoot.'/routes.php','SESSION_DRIVER'=>'array','CACHE_STORE'=>'array']as$k=>$v){putenv($k.'='.$v);$_ENV[$k]=$v;}
|
||||
$app=require $repo.'/bootstrap/app.php';$app->addAbsoluteCachePathPrefix('C:');$app->useStoragePath($this->privateRoot.'/storage');
|
||||
$this->traitsUsedByTest=class_uses_recursive(static::class);$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();return $app;
|
||||
$repo = dirname(__DIR__, 2);
|
||||
$this->privateRoot = 'C:/laragon/data/sgf-tempo/run/sgc-dispatch-tests-'.bin2hex(random_bytes(6));
|
||||
foreach (['logs', 'framework/views', 'framework/sessions', 'framework/cache/data'] as $d) {
|
||||
mkdir($this->privateRoot.'/storage/'.$d, 0700, true);
|
||||
}
|
||||
foreach (['DB_CONNECTION' => 'sqlite', 'DB_DATABASE' => ':memory:', 'DB_URL' => '', 'APP_ENV' => 'testing',
|
||||
'APP_CONFIG_CACHE' => $this->privateRoot.'/config.php', 'APP_SERVICES_CACHE' => $this->privateRoot.'/services.php', 'APP_PACKAGES_CACHE' => $this->privateRoot.'/packages.php',
|
||||
'APP_ROUTES_CACHE' => $this->privateRoot.'/routes.php', 'SESSION_DRIVER' => 'array', 'CACHE_STORE' => 'array'] as $k => $v) {
|
||||
putenv($k.'='.$v);
|
||||
$_ENV[$k] = $v;
|
||||
}
|
||||
$app = require $repo.'/bootstrap/app.php';
|
||||
$app->addAbsoluteCachePathPrefix('C:');
|
||||
$app->useStoragePath($this->privateRoot.'/storage');
|
||||
$this->traitsUsedByTest = class_uses_recursive(self::class);
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
|
||||
return $app;
|
||||
}
|
||||
protected function setUp():void
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
self::assertSame('sqlite',DB::getDriverName());self::assertSame(':memory:',DB::connection()->getDatabaseName());
|
||||
config(['app.key'=>'base64:'.base64_encode(str_repeat('x',32)),'sgf_invoice.workspace_enabled'=>true,'sgf_invoice.enabled'=>true]);
|
||||
Schema::create('tenants',fn(Blueprint $t)=>[$t->id(),$t->string('name'),$t->json('work_context_policy')->nullable()]);
|
||||
Schema::create('users',function(Blueprint $t){$t->id();$t->unsignedBigInteger('tenant_id');$t->string('purchasing_role');$t->string('name');$t->string('email');$t->string('password');$t->timestamp('email_verified_at')->nullable();$t->rememberToken();$t->timestamps();});
|
||||
Schema::create('suppliers',fn(Blueprint $t)=>[$t->id(),$t->unsignedBigInteger('tenant_id'),$t->string('name')]);
|
||||
Schema::create('invoices',fn(Blueprint $t)=>[$t->id(),$t->unsignedBigInteger('tenant_id'),$t->unsignedBigInteger('supplier_id'),$t->string('number')]);
|
||||
DB::table('tenants')->insert([['id'=>1,'name'=>'QA source'],['id'=>2,'name'=>'Foreign QA']]);
|
||||
foreach([1=>[1,'finance'],2=>[2,'finance'],3=>[1,'warehouse'],4=>[1,'finance']]as$id=>[$tenant,$role])DB::table('users')->insert(['id'=>$id,'tenant_id'=>$tenant,'purchasing_role'=>$role,'name'=>'QA '.$id,'email'=>'qa'.$id.'@example.test','password'=>'unused','email_verified_at'=>now(),'created_at'=>now(),'updated_at'=>now()]);
|
||||
DB::table('suppliers')->insert([['id'=>1,'tenant_id'=>1,'name'=>'QA Supplier'],['id'=>2,'tenant_id'=>2,'name'=>'Foreign']]);
|
||||
$migration=require dirname(__DIR__,2).'/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php';$migration->up();
|
||||
$this->actor=User::findOrFail(1);$this->actingAs($this->actor);$this->service=app(SgfInvoiceDispatches::class);
|
||||
$package='C:/laragon/www/sgf-tempo/packages/sgc-invoice-client/src/InvoiceClient.php';
|
||||
config(['sgf_invoice.client_package'=>$package,'sgf_invoice.client_package_sha256'=>hash_file('sha256',$package),
|
||||
'sgf_invoice.connections'=>['qa'=>['enabled'=>true,'source_scope'=>['tenant_id'=>1],'target_scope'=>['tenant_id'=>1,'company_id'=>2,'unit_id'=>2],
|
||||
'client_id'=>'qa','token'=>str_repeat('q',64),'context_version'=>str_repeat('a',64),'origin'=>'http://127.0.0.1:8085','mappings'=>['map'=>[
|
||||
'approved'=>true,'label'=>'Escolha QA','source_supplier_id'=>1,'mapping'=>['id'=>'qa-map','version'=>1,'source_scope'=>['tenant_id'=>1],
|
||||
'target_scope'=>['tenant_id'=>1,'company_id'=>2,'unit_id'=>2],'authority'=>'sgf_only','order_id'=>7,'lines'=>['QA-LINE'=>8]]]]]]]);
|
||||
Http::preventStrayRequests();Http::fake(function(Outbound $r){
|
||||
if($r->method()==='GET')return Http::response(['order'=>['id'=>7],'revision'=>str_repeat('b',64)]);
|
||||
$key=$r->header('X-Idempotency-Key')[0];
|
||||
if($r['phase']==='preview')return Http::response(['preview'=>'QA-encrypted-'.$key,'impact'=>['operation'=>'Registar pendente','budget_consumption_minor'=>0,'payable_created'=>false]]);
|
||||
$replay=isset($this->remote[$key]);$this->remote[$key]??=40+count($this->remote);
|
||||
if($this->lose){$this->lose=false;throw new \Illuminate\Http\Client\ConnectionException('Synthetic lost response');}
|
||||
return Http::response(['invoice_id'=>$this->remote[$key],'order_id'=>7,'status'=>'pending','replayed'=>$replay],$replay?200:201);
|
||||
self::assertSame('sqlite', DB::getDriverName());
|
||||
self::assertSame(':memory:', DB::connection()->getDatabaseName());
|
||||
config(['app.key' => 'base64:'.base64_encode(str_repeat('x', 32)), 'sgf_invoice.workspace_enabled' => true, 'sgf_invoice.enabled' => true]);
|
||||
Schema::create('tenants', fn (Blueprint $t) => [$t->id(), $t->string('name'), $t->json('work_context_policy')->nullable()]);
|
||||
Schema::create('users', function (Blueprint $t) {
|
||||
$t->id();
|
||||
$t->unsignedBigInteger('tenant_id');
|
||||
$t->string('purchasing_role');
|
||||
$t->string('name');
|
||||
$t->string('email');
|
||||
$t->string('password');
|
||||
$t->timestamp('email_verified_at')->nullable();
|
||||
$t->rememberToken();
|
||||
$t->timestamps();
|
||||
});
|
||||
Schema::create('suppliers', fn (Blueprint $t) => [$t->id(), $t->unsignedBigInteger('tenant_id'), $t->string('name')]);
|
||||
Schema::create('invoices', fn (Blueprint $t) => [$t->id(), $t->unsignedBigInteger('tenant_id'), $t->unsignedBigInteger('supplier_id'), $t->string('number')]);
|
||||
DB::table('tenants')->insert([['id' => 1, 'name' => 'QA source'], ['id' => 2, 'name' => 'Foreign QA']]);
|
||||
foreach ([1 => [1, 'finance'], 2 => [2, 'finance'], 3 => [1, 'warehouse'], 4 => [1, 'finance']] as $id => [$tenant,$role]) {
|
||||
DB::table('users')->insert(['id' => $id, 'tenant_id' => $tenant, 'purchasing_role' => $role, 'name' => 'QA '.$id, 'email' => 'qa'.$id.'@example.test', 'password' => 'unused', 'email_verified_at' => now(), 'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
DB::table('suppliers')->insert([['id' => 1, 'tenant_id' => 1, 'name' => 'QA Supplier'], ['id' => 2, 'tenant_id' => 2, 'name' => 'Foreign']]);
|
||||
$migration = require dirname(__DIR__, 2).'/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php';
|
||||
$migration->up();
|
||||
$this->actor = User::findOrFail(1);
|
||||
$this->actingAs($this->actor);
|
||||
$this->service = app(SgfInvoiceDispatches::class);
|
||||
$package = 'C:/laragon/www/sgf-tempo/packages/sgc-invoice-client/src/InvoiceClient.php';
|
||||
config(['sgf_invoice.client_package' => $package, 'sgf_invoice.client_package_sha256' => hash_file('sha256', $package),
|
||||
'sgf_invoice.connections' => ['qa' => ['enabled' => true, 'source_scope' => ['tenant_id' => 1], 'target_scope' => ['tenant_id' => 1, 'company_id' => 2, 'unit_id' => 2],
|
||||
'client_id' => 'qa', 'token' => str_repeat('q', 64), 'context_version' => str_repeat('a', 64), 'origin' => 'http://127.0.0.1:8085', 'mappings' => ['map' => [
|
||||
'approved' => true, 'label' => 'Escolha QA', 'source_supplier_id' => 1, 'mapping' => ['id' => 'qa-map', 'version' => 1, 'source_scope' => ['tenant_id' => 1],
|
||||
'target_scope' => ['tenant_id' => 1, 'company_id' => 2, 'unit_id' => 2], 'authority' => 'sgf_only', 'order_id' => 7, 'lines' => ['QA-LINE' => 8]]]]]]]);
|
||||
Http::preventStrayRequests();
|
||||
Http::fake(function (Outbound $r) {
|
||||
if ($r->method() === 'GET') {
|
||||
return Http::response(['order' => ['id' => 7], 'revision' => str_repeat('b', 64)]);
|
||||
}
|
||||
$key = $r->header('X-Idempotency-Key')[0];
|
||||
if ($r['phase'] === 'preview') {
|
||||
return Http::response(['preview' => 'QA-encrypted-'.$key, 'impact' => ['operation' => 'Registar pendente', 'budget_consumption_minor' => 0, 'payable_created' => false]]);
|
||||
}
|
||||
$replay = isset($this->remote[$key]);
|
||||
$this->remote[$key] ??= 40 + count($this->remote);
|
||||
if ($this->lose) {
|
||||
$this->lose = false;
|
||||
throw new ConnectionException('Synthetic lost response');
|
||||
}
|
||||
|
||||
return Http::response(['invoice_id' => $this->remote[$key], 'order_id' => 7, 'status' => 'pending', 'replayed' => $replay], $replay ? 200 : 201);
|
||||
});
|
||||
}
|
||||
private function data(string $ref='QA-SOURCE-1'):array
|
||||
|
||||
private function data(string $ref = 'QA-SOURCE-1'): array
|
||||
{
|
||||
return ['reference'=>$ref,'connection_id'=>'qa','mapping_id'=>'map','reason'=>'Conferência documental exclusivamente sintética.','document'=>[
|
||||
'number'=>$ref,'issued_on'=>'2026-11-10','subtotal'=>'100.00','tax'=>'0.00','total'=>'100.00','items'=>[
|
||||
['source_line_ref'=>'QA-LINE','quantity'=>'1.000','unit'=>'UN','unit_price'=>'100.00','tax_rate'=>'0.00']]]];
|
||||
return ['reference' => $ref, 'connection_id' => 'qa', 'mapping_id' => 'map', 'reason' => 'Conferência documental exclusivamente sintética.', 'document' => [
|
||||
'number' => $ref, 'issued_on' => '2026-11-10', 'subtotal' => '100.00', 'tax' => '0.00', 'total' => '100.00', 'items' => [
|
||||
['source_line_ref' => 'QA-LINE', 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '100.00', 'tax_rate' => '0.00']]]];
|
||||
}
|
||||
private function prepared():object
|
||||
|
||||
private function prepared(): object
|
||||
{
|
||||
$id=$this->service->create($this->actor,$this->data());return $this->service->dispatch($this->actor,$id,1,'preview','Conferir impacto documental actual.',null);
|
||||
$id = $this->service->create($this->actor, $this->data());
|
||||
|
||||
return $this->service->dispatch($this->actor, $id, 1, 'preview', 'Conferir impacto documental actual.', null);
|
||||
}
|
||||
private function approval(object $row):string{return $this->service->presentation($this->actor,$row)['approval_hash'];}
|
||||
public function test_full_durable_cycle_and_audited_decision():void
|
||||
|
||||
private function approval(object $row): string
|
||||
{
|
||||
$row=$this->prepared();self::assertSame('previewed',$row->phase);self::assertSame(3,$row->version);
|
||||
$approved=$this->approval($row);self::assertIsString($approved);self::assertStringNotContainsString('QA-encrypted',$row->state_ciphertext);
|
||||
$done=$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Aceitar individualmente este impacto.',$approved);
|
||||
self::assertSame('received_pending',$done->phase);self::assertNotNull($done->receipt);self::assertCount(1,$this->remote);
|
||||
self::assertSame(0,DB::table('invoices')->count());
|
||||
$events=DB::table('sgf_invoice_dispatch_events')->orderBy('id')->get();self::assertCount(5,$events);
|
||||
self::assertSame('decision.confirmed',$events[3]->action);self::assertSame(1,$events[3]->actor_id);self::assertNotNull($events[3]->before_state);
|
||||
self::assertSame($approved,json_decode($events[3]->after_state,true)['approval_hash']);
|
||||
return $this->service->presentation($this->actor, $row)['approval_hash'];
|
||||
}
|
||||
public function test_lost_response_reuses_same_key_cut_and_durable_intent():void
|
||||
|
||||
public function test_full_durable_cycle_and_audited_decision(): void
|
||||
{
|
||||
$row=$this->prepared();$this->lose=true;$unknown=$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Aceitar e conservar decisão sintética.',$this->approval($row));
|
||||
self::assertSame('uncertain',$unknown->phase);$key=$unknown->operation_key;
|
||||
$recovered=$this->service->dispatch($this->actor,$row->id,$unknown->version,'recover','Recuperar a mesma intenção sem duplicação.',null);
|
||||
self::assertSame('received_pending',$recovered->phase);self::assertSame($key,$recovered->operation_key);self::assertCount(1,$this->remote);
|
||||
self::assertTrue(json_decode($recovered->receipt,true)['replayed']);
|
||||
$row = $this->prepared();
|
||||
self::assertSame('previewed', $row->phase);
|
||||
self::assertSame(3, $row->version);
|
||||
$approved = $this->approval($row);
|
||||
self::assertIsString($approved);
|
||||
self::assertStringNotContainsString('QA-encrypted', $row->state_ciphertext);
|
||||
$done = $this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Aceitar individualmente este impacto.', $approved);
|
||||
self::assertSame('received_pending', $done->phase);
|
||||
self::assertNotNull($done->receipt);
|
||||
self::assertCount(1, $this->remote);
|
||||
self::assertSame(0, DB::table('invoices')->count());
|
||||
$events = DB::table('sgf_invoice_dispatch_events')->orderBy('id')->get();
|
||||
self::assertCount(5, $events);
|
||||
self::assertSame('decision.confirmed', $events[3]->action);
|
||||
self::assertSame(1, $events[3]->actor_id);
|
||||
self::assertNotNull($events[3]->before_state);
|
||||
self::assertSame($approved, json_decode($events[3]->after_state, true)['approval_hash']);
|
||||
}
|
||||
public function test_failure_after_remote_commit_keeps_durable_sending_for_recovery():void
|
||||
|
||||
public function test_lost_response_reuses_same_key_cut_and_durable_intent(): void
|
||||
{
|
||||
$row=$this->prepared();DB::unprepared("CREATE TRIGGER fail_observation BEFORE INSERT ON sgf_invoice_dispatch_events WHEN NEW.action='transport.observed' BEGIN SELECT RAISE(ABORT,'Synthetic persistence failure'); END");
|
||||
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Confirmar decisão antes do transporte.',$this->approval($row));self::fail('Expected storage failure');}catch(\Illuminate\Database\QueryException){}
|
||||
$pending=$this->service->row($this->actor,$row->id);self::assertSame('sending',$pending->phase);self::assertTrue((bool)$pending->ever_sending);self::assertCount(1,$this->remote);
|
||||
DB::unprepared('DROP TRIGGER fail_observation');$this->travel(121)->seconds();
|
||||
$done=$this->service->dispatch($this->actor,$row->id,$pending->version,'recover','Recuperar após libertação do lease.',null);
|
||||
self::assertSame('received_pending',$done->phase);self::assertCount(1,$this->remote);
|
||||
$row = $this->prepared();
|
||||
$this->lose = true;
|
||||
$unknown = $this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Aceitar e conservar decisão sintética.', $this->approval($row));
|
||||
self::assertSame('uncertain', $unknown->phase);
|
||||
$key = $unknown->operation_key;
|
||||
$recovered = $this->service->dispatch($this->actor, $row->id, $unknown->version, 'recover', 'Recuperar a mesma intenção sem duplicação.', null);
|
||||
self::assertSame('received_pending', $recovered->phase);
|
||||
self::assertSame($key, $recovered->operation_key);
|
||||
self::assertCount(1, $this->remote);
|
||||
self::assertTrue(json_decode($recovered->receipt, true)['replayed']);
|
||||
}
|
||||
public function test_revision_preserves_before_after_and_invalidates_preview():void
|
||||
|
||||
public function test_failure_after_remote_commit_keeps_durable_sending_for_recovery(): void
|
||||
{
|
||||
$row=$this->prepared();$data=$this->data();$data['document']['subtotal']='120.00';$data['document']['total']='120.00';$data['document']['items'][0]['unit_price']='120.00';
|
||||
$new=$this->service->revise($this->actor,$row->id,$row->version,$data);self::assertSame('draft',$new->phase);self::assertNull($new->operation_key);self::assertNull($new->state_ciphertext);
|
||||
self::assertSame(2,$new->source_version);$e=DB::table('sgf_invoice_dispatch_events')->orderByDesc('id')->first();
|
||||
self::assertSame('100.00',json_decode($e->before_state,true)['document']['total']);self::assertSame('120.00',json_decode($e->after_state,true)['document']['total']);
|
||||
$row = $this->prepared();
|
||||
DB::unprepared("CREATE TRIGGER fail_observation BEFORE INSERT ON sgf_invoice_dispatch_events WHEN NEW.action='transport.observed' BEGIN SELECT RAISE(ABORT,'Synthetic persistence failure'); END");
|
||||
try {
|
||||
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Confirmar decisão antes do transporte.', $this->approval($row));
|
||||
self::fail('Expected storage failure');
|
||||
} catch (QueryException) {
|
||||
}
|
||||
$pending = $this->service->row($this->actor, $row->id);
|
||||
self::assertSame('sending', $pending->phase);
|
||||
self::assertTrue((bool) $pending->ever_sending);
|
||||
self::assertCount(1, $this->remote);
|
||||
DB::unprepared('DROP TRIGGER fail_observation');
|
||||
$this->travel(121)->seconds();
|
||||
$done = $this->service->dispatch($this->actor, $row->id, $pending->version, 'recover', 'Recuperar após libertação do lease.', null);
|
||||
self::assertSame('received_pending', $done->phase);
|
||||
self::assertCount(1, $this->remote);
|
||||
}
|
||||
public function test_no_edit_after_any_confirmation_started():void
|
||||
|
||||
public function test_revision_preserves_before_after_and_invalidates_preview(): void
|
||||
{
|
||||
$row=$this->prepared();$this->lose=true;$row=$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Confirmar individualmente o documento.',$this->approval($row));
|
||||
$this->expectException(\Symfony\Component\HttpKernel\Exception\HttpException::class);$this->service->revise($this->actor,$row->id,$row->version,$this->data());
|
||||
$row = $this->prepared();
|
||||
$data = $this->data();
|
||||
$data['document']['subtotal'] = '120.00';
|
||||
$data['document']['total'] = '120.00';
|
||||
$data['document']['items'][0]['unit_price'] = '120.00';
|
||||
$new = $this->service->revise($this->actor, $row->id, $row->version, $data);
|
||||
self::assertSame('draft', $new->phase);
|
||||
self::assertNull($new->operation_key);
|
||||
self::assertNull($new->state_ciphertext);
|
||||
self::assertSame(2, $new->source_version);
|
||||
$e = DB::table('sgf_invoice_dispatch_events')->orderByDesc('id')->first();
|
||||
self::assertSame('100.00', json_decode($e->before_state, true)['document']['total']);
|
||||
self::assertSame('120.00', json_decode($e->after_state, true)['document']['total']);
|
||||
}
|
||||
public function test_local_registration_is_blocked_even_when_feature_is_disabled():void
|
||||
|
||||
public function test_no_edit_after_any_confirmation_started(): void
|
||||
{
|
||||
$this->service->create($this->actor,$this->data());config(['sgf_invoice.workspace_enabled'=>false]);
|
||||
$this->expectException(\Illuminate\Validation\ValidationException::class);SgfInvoiceDispatches::assertLocalRegistration(1,1,'QA-SOURCE-1');
|
||||
$row = $this->prepared();
|
||||
$this->lose = true;
|
||||
$row = $this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Confirmar individualmente o documento.', $this->approval($row));
|
||||
$this->expectException(HttpException::class);
|
||||
$this->service->revise($this->actor, $row->id, $row->version, $this->data());
|
||||
}
|
||||
public function test_existing_local_invoice_cannot_be_sent():void
|
||||
|
||||
public function test_local_registration_is_blocked_even_when_feature_is_disabled(): void
|
||||
{
|
||||
DB::table('invoices')->insert(['tenant_id'=>1,'supplier_id'=>1,'number'=>'QA-SOURCE-1']);
|
||||
$this->expectException(\Symfony\Component\HttpKernel\Exception\HttpException::class);$this->service->create($this->actor,$this->data());
|
||||
$this->service->create($this->actor, $this->data());
|
||||
config(['sgf_invoice.workspace_enabled' => false]);
|
||||
$this->expectException(ValidationException::class);
|
||||
SgfInvoiceDispatches::assertLocalRegistration(1, 1, 'QA-SOURCE-1');
|
||||
}
|
||||
public function test_duplicate_source_cannot_get_second_intent():void
|
||||
|
||||
public function test_existing_local_invoice_cannot_be_sent(): void
|
||||
{
|
||||
$this->service->create($this->actor,$this->data());$this->expectException(\Symfony\Component\HttpKernel\Exception\HttpException::class);$this->service->create($this->actor,$this->data());
|
||||
DB::table('invoices')->insert(['tenant_id' => 1, 'supplier_id' => 1, 'number' => 'QA-SOURCE-1']);
|
||||
$this->expectException(HttpException::class);
|
||||
$this->service->create($this->actor, $this->data());
|
||||
}
|
||||
public function test_stale_version_and_wrong_approval_do_not_send():void
|
||||
|
||||
public function test_duplicate_source_cannot_get_second_intent(): void
|
||||
{
|
||||
$row=$this->prepared();foreach([1=>str_repeat('0',64),$row->version=>str_repeat('0',64)]as$version=>$approval){
|
||||
try{$this->service->dispatch($this->actor,$row->id,$version,'confirm','Fundamento de confirmação explícita.',$approval);self::fail('Expected409');}
|
||||
catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}}
|
||||
self::assertCount(0,$this->remote);
|
||||
$this->service->create($this->actor, $this->data());
|
||||
$this->expectException(HttpException::class);
|
||||
$this->service->create($this->actor, $this->data());
|
||||
}
|
||||
public function test_operator_context_and_mapping_changes_require_new_conference():void
|
||||
|
||||
public function test_stale_version_and_wrong_approval_do_not_send(): void
|
||||
{
|
||||
$row=$this->prepared();$approval=$this->approval($row);$this->actingAs(User::find(4));
|
||||
try{$this->service->dispatch(User::find(4),$row->id,$row->version,'confirm','Outro operador deve conferir novamente.',$approval);self::fail('Expected409');}catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}
|
||||
$this->actingAs($this->actor);config(['sgf_invoice.connections.qa.mappings.map.mapping.version'=>2]);
|
||||
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Mapeamento mudou; não deve enviar.',$approval);self::fail('Expected409');}catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}
|
||||
self::assertCount(0,$this->remote);
|
||||
$row = $this->prepared();
|
||||
foreach ([1 => str_repeat('0', 64), $row->version => str_repeat('0', 64)] as $version => $approval) {
|
||||
try {
|
||||
$this->service->dispatch($this->actor, $row->id, $version, 'confirm', 'Fundamento de confirmação explícita.', $approval);
|
||||
self::fail('Expected409');
|
||||
} catch (HttpException $e) {
|
||||
self::assertSame(409, $e->getStatusCode());
|
||||
}
|
||||
}
|
||||
self::assertCount(0, $this->remote);
|
||||
}
|
||||
public function test_http_screen_csrf_and_audited_history_are_private():void
|
||||
|
||||
public function test_operator_context_and_mapping_changes_require_new_conference(): void
|
||||
{
|
||||
$r=$this->post('/facturas/envio-sgf',$this->data());$r->assertRedirect('/facturas/envio-sgf/1');
|
||||
$this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('QA-SOURCE-1')->assertSee('Histórico auditado')->assertHeader('Cache-Control','no-store, private');
|
||||
$row = $this->prepared();
|
||||
$approval = $this->approval($row);
|
||||
$this->actingAs(User::find(4));
|
||||
try {
|
||||
$this->service->dispatch(User::find(4), $row->id, $row->version, 'confirm', 'Outro operador deve conferir novamente.', $approval);
|
||||
self::fail('Expected409');
|
||||
} catch (HttpException $e) {
|
||||
self::assertSame(409, $e->getStatusCode());
|
||||
}
|
||||
$this->actingAs($this->actor);
|
||||
config(['sgf_invoice.connections.qa.mappings.map.mapping.version' => 2]);
|
||||
try {
|
||||
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Mapeamento mudou; não deve enviar.', $approval);
|
||||
self::fail('Expected409');
|
||||
} catch (HttpException $e) {
|
||||
self::assertSame(409, $e->getStatusCode());
|
||||
}
|
||||
self::assertCount(0, $this->remote);
|
||||
}
|
||||
|
||||
public function test_http_screen_csrf_and_audited_history_are_private(): void
|
||||
{
|
||||
$r = $this->post('/facturas/envio-sgf', $this->data());
|
||||
$r->assertRedirect('/facturas/envio-sgf/1');
|
||||
$this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('QA-SOURCE-1')->assertSee('Histórico auditado')->assertHeader('Cache-Control', 'no-store, private');
|
||||
$this->get('/facturas/envio-sgf')->assertOk()->assertSee('Escolher explicitamente')->assertDontSee('Guardar novo rascunho');
|
||||
$this->get('/facturas/envio-sgf?connection=qa&mapping=map')->assertOk()->assertSee('Guardar novo rascunho');
|
||||
$this->app->instance('env','local');try{$this->post('/facturas/envio-sgf',$this->data('CSRF-FAIL'))->assertStatus(419);}finally{$this->app->instance('env','testing');}
|
||||
self::assertSame(1,DB::table('sgf_invoice_dispatches')->count());
|
||||
$this->app->instance('env', 'local');
|
||||
try {
|
||||
$this->post('/facturas/envio-sgf', $this->data('CSRF-FAIL'))->assertStatus(419);
|
||||
} finally {
|
||||
$this->app->instance('env', 'testing');
|
||||
}
|
||||
self::assertSame(1, DB::table('sgf_invoice_dispatches')->count());
|
||||
}
|
||||
public function test_foreign_tenant_and_warehouse_actor_cannot_read_or_write():void
|
||||
|
||||
public function test_foreign_tenant_and_warehouse_actor_cannot_read_or_write(): void
|
||||
{
|
||||
$id=$this->service->create($this->actor,$this->data());$this->actingAs(User::find(2));$this->get('/facturas/envio-sgf/'.$id)->assertNotFound();
|
||||
$this->post('/facturas/envio-sgf',$this->data('FOREIGN'))->assertForbidden();
|
||||
$this->actingAs(User::find(3));$this->get('/facturas/envio-sgf')->assertForbidden();
|
||||
self::assertSame(1,DB::table('sgf_invoice_dispatches')->count());
|
||||
$id = $this->service->create($this->actor, $this->data());
|
||||
$this->actingAs(User::find(2));
|
||||
$this->get('/facturas/envio-sgf/'.$id)->assertNotFound();
|
||||
$this->post('/facturas/envio-sgf', $this->data('FOREIGN'))->assertForbidden();
|
||||
$this->actingAs(User::find(3));
|
||||
$this->get('/facturas/envio-sgf')->assertForbidden();
|
||||
self::assertSame(1, DB::table('sgf_invoice_dispatches')->count());
|
||||
}
|
||||
public function test_pagination_history_and_output_escaping():void
|
||||
|
||||
public function test_pagination_history_and_output_escaping(): void
|
||||
{
|
||||
for($i=0;$i<27;$i++)$this->service->create($this->actor,$this->data('QA-LIST-'.$i));
|
||||
for ($i = 0; $i < 27; $i++) {
|
||||
$this->service->create($this->actor, $this->data('QA-LIST-'.$i));
|
||||
}
|
||||
$this->get('/facturas/envio-sgf?page=2')->assertOk()->assertSee('QA-LIST-0')->assertDontSee('QA-LIST-26');
|
||||
$row=$this->service->row($this->actor,1);for($i=0;$i<27;$i++)$row=$this->service->revise($this->actor,1,$row->version,$this->data('QA-LIST-0'));
|
||||
$row = $this->service->row($this->actor, 1);
|
||||
for ($i = 0; $i < 27; $i++) {
|
||||
$row = $this->service->revise($this->actor, 1, $row->version, $this->data('QA-LIST-0'));
|
||||
}
|
||||
$this->get('/facturas/envio-sgf/1?events_page=2')->assertOk()->assertSee('draft.created');
|
||||
$data=$this->data('XSS');$data['document']['number']='<script>alert(1)</script>';$id=$this->service->create($this->actor,$data);
|
||||
$this->get('/facturas/envio-sgf/'.$id)->assertOk()->assertDontSee('<script>alert(1)</script>',false)->assertSee('<SCRIPT>',false);
|
||||
$data = $this->data('XSS');
|
||||
$data['document']['number'] = '<script>alert(1)</script>';
|
||||
$id = $this->service->create($this->actor, $data);
|
||||
$this->get('/facturas/envio-sgf/'.$id)->assertOk()->assertDontSee('<script>alert(1)</script>', false)->assertSee('<SCRIPT>', false);
|
||||
}
|
||||
public function test_events_and_drafts_cannot_be_deleted_or_rewritten():void
|
||||
|
||||
public function test_events_and_drafts_cannot_be_deleted_or_rewritten(): void
|
||||
{
|
||||
$id=$this->service->create($this->actor,$this->data());
|
||||
foreach([fn()=>DB::table('sgf_invoice_dispatch_events')->update(['action'=>'tampered']),fn()=>DB::table('sgf_invoice_dispatch_events')->delete(),fn()=>DB::table('sgf_invoice_dispatches')->delete()]as$mutate){
|
||||
try{$mutate();self::fail('Expected immutable audit');}catch(\Illuminate\Database\QueryException){self::assertSame(1,DB::table('sgf_invoice_dispatch_events')->count());}}
|
||||
$id = $this->service->create($this->actor, $this->data());
|
||||
foreach ([fn () => DB::table('sgf_invoice_dispatch_events')->update(['action' => 'tampered']), fn () => DB::table('sgf_invoice_dispatch_events')->delete(), fn () => DB::table('sgf_invoice_dispatches')->delete()] as $mutate) {
|
||||
try {
|
||||
$mutate();
|
||||
self::fail('Expected immutable audit');
|
||||
} catch (QueryException) {
|
||||
self::assertSame(1, DB::table('sgf_invoice_dispatch_events')->count());
|
||||
}
|
||||
}
|
||||
}
|
||||
public function test_disabled_transport_keeps_draft_and_disabled_workspace_refuses():void
|
||||
|
||||
public function test_disabled_transport_keeps_draft_and_disabled_workspace_refuses(): void
|
||||
{
|
||||
$id=$this->service->create($this->actor,$this->data());config(['sgf_invoice.enabled'=>false]);
|
||||
$this->post('/facturas/envio-sgf/'.$id.'/operar',['version'=>1,'action'=>'preview','reason'=>'Não activar o transporte nesta entrega.'])->assertStatus(423);
|
||||
self::assertNull($this->service->row($this->actor,$id)->operation_key);Http::assertNothingSent();
|
||||
config(['sgf_invoice.workspace_enabled'=>false]);$this->get('/facturas/envio-sgf')->assertNotFound();
|
||||
$id = $this->service->create($this->actor, $this->data());
|
||||
config(['sgf_invoice.enabled' => false]);
|
||||
$this->post('/facturas/envio-sgf/'.$id.'/operar', ['version' => 1, 'action' => 'preview', 'reason' => 'Não activar o transporte nesta entrega.'])->assertStatus(423);
|
||||
self::assertNull($this->service->row($this->actor, $id)->operation_key);
|
||||
Http::assertNothingSent();
|
||||
config(['sgf_invoice.workspace_enabled' => false]);
|
||||
$this->get('/facturas/envio-sgf')->assertNotFound();
|
||||
}
|
||||
public function test_changed_remote_context_refuses_decision_before_recording_it():void
|
||||
|
||||
public function test_changed_remote_context_refuses_decision_before_recording_it(): void
|
||||
{
|
||||
$row=$this->prepared();$hash=$this->approval($row);$events=DB::table('sgf_invoice_dispatch_events')->count();
|
||||
config(['sgf_invoice.connections.qa.context_version'=>str_repeat('c',64)]);
|
||||
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Contexto remoto mudou; não confirmar.',$hash);self::fail('Expected409');}
|
||||
catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}
|
||||
self::assertSame($events,DB::table('sgf_invoice_dispatch_events')->count());self::assertCount(0,$this->remote);
|
||||
$new=$this->service->dispatch($this->actor,$row->id,$row->version,'preview','Conferir novamente o contexto actual.',null);
|
||||
self::assertSame('previewed',$new->phase);self::assertSame($row->operation_key,$new->operation_key);self::assertNotSame($hash,$this->approval($new));
|
||||
$row = $this->prepared();
|
||||
$hash = $this->approval($row);
|
||||
$events = DB::table('sgf_invoice_dispatch_events')->count();
|
||||
config(['sgf_invoice.connections.qa.context_version' => str_repeat('c', 64)]);
|
||||
try {
|
||||
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Contexto remoto mudou; não confirmar.', $hash);
|
||||
self::fail('Expected409');
|
||||
} catch (HttpException $e) {
|
||||
self::assertSame(409, $e->getStatusCode());
|
||||
}
|
||||
self::assertSame($events, DB::table('sgf_invoice_dispatch_events')->count());
|
||||
self::assertCount(0, $this->remote);
|
||||
$new = $this->service->dispatch($this->actor, $row->id, $row->version, 'preview', 'Conferir novamente o contexto actual.', null);
|
||||
self::assertSame('previewed', $new->phase);
|
||||
self::assertSame($row->operation_key, $new->operation_key);
|
||||
self::assertNotSame($hash, $this->approval($new));
|
||||
}
|
||||
public function test_revoked_operator_cannot_confirm_and_live_lease_prevents_duplicate_send():void
|
||||
|
||||
public function test_revoked_operator_cannot_confirm_and_live_lease_prevents_duplicate_send(): void
|
||||
{
|
||||
$row=$this->prepared();$hash=$this->approval($row);
|
||||
DB::table('users')->where('id',1)->update(['purchasing_role'=>'warehouse']);
|
||||
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Não enviar com autoridade revogada.',$hash);self::fail('Expected403');}
|
||||
catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(403,$e->getStatusCode());}
|
||||
DB::table('users')->where('id',1)->update(['purchasing_role'=>'finance']);
|
||||
DB::table('sgf_invoice_dispatches')->where('id',$row->id)->update(['lease_until'=>now('UTC')->addSeconds(120)]);
|
||||
try{$this->service->dispatch($this->actor,$row->id,$row->version,'confirm','Uma operação em curso não duplica.',$hash);self::fail('Expected409');}
|
||||
catch(\Symfony\Component\HttpKernel\Exception\HttpException $e){self::assertSame(409,$e->getStatusCode());}
|
||||
self::assertCount(0,$this->remote);
|
||||
$row = $this->prepared();
|
||||
$hash = $this->approval($row);
|
||||
DB::table('users')->where('id', 1)->update(['purchasing_role' => 'warehouse']);
|
||||
try {
|
||||
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Não enviar com autoridade revogada.', $hash);
|
||||
self::fail('Expected403');
|
||||
} catch (HttpException $e) {
|
||||
self::assertSame(403, $e->getStatusCode());
|
||||
}
|
||||
DB::table('users')->where('id', 1)->update(['purchasing_role' => 'finance']);
|
||||
DB::table('sgf_invoice_dispatches')->where('id', $row->id)->update(['lease_until' => now('UTC')->addSeconds(120)]);
|
||||
try {
|
||||
$this->service->dispatch($this->actor, $row->id, $row->version, 'confirm', 'Uma operação em curso não duplica.', $hash);
|
||||
self::fail('Expected409');
|
||||
} catch (HttpException $e) {
|
||||
self::assertSame(409, $e->getStatusCode());
|
||||
}
|
||||
self::assertCount(0, $this->remote);
|
||||
}
|
||||
public function test_actual_screen_forms_complete_registration_and_keep_exact_sgf_handoff():void
|
||||
|
||||
public function test_actual_screen_forms_complete_registration_and_keep_exact_sgf_handoff(): void
|
||||
{
|
||||
$this->post('/facturas/envio-sgf',$this->data())->assertRedirect('/facturas/envio-sgf/1');
|
||||
$this->post('/facturas/envio-sgf/1/operar',['version'=>1,'action'=>'preview','reason'=>'Conferência individual pela interface.'])->assertRedirect('/facturas/envio-sgf/1');
|
||||
$html=$this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('Impacto devolvido pelo SGF')->assertSee('Confirmar individualmente')->assertDontSee('QA-encrypted',false)->getContent();
|
||||
preg_match('/name="approval_hash" value="([a-f0-9]{64})"/',$html,$match);self::assertNotEmpty($match);
|
||||
file_put_contents($this->privateRoot.'/screen-preview.html',$html);
|
||||
$this->post('/facturas/envio-sgf/1/operar',['version'=>3,'action'=>'confirm','reason'=>'Confirmar apenas este impacto mostrado.','approval_hash'=>$match[1]])->assertRedirect('/facturas/envio-sgf/1');
|
||||
$done=$this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('Recibo conservado')->assertDontSee('Confirmar individualmente')->assertSee('http://127.0.0.1:8085/compras?',false)->getContent();
|
||||
file_put_contents($this->privateRoot.'/screen-receipt.html',$done);self::assertCount(1,$this->remote);
|
||||
$this->post('/facturas/envio-sgf', $this->data())->assertRedirect('/facturas/envio-sgf/1');
|
||||
$this->post('/facturas/envio-sgf/1/operar', ['version' => 1, 'action' => 'preview', 'reason' => 'Conferência individual pela interface.'])->assertRedirect('/facturas/envio-sgf/1');
|
||||
$html = $this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('Impacto devolvido pelo SGF')->assertSee('Confirmar individualmente')->assertDontSee('QA-encrypted', false)->getContent();
|
||||
preg_match('/name="approval_hash" value="([a-f0-9]{64})"/', $html, $match);
|
||||
self::assertNotEmpty($match);
|
||||
file_put_contents($this->privateRoot.'/screen-preview.html', $html);
|
||||
$this->post('/facturas/envio-sgf/1/operar', ['version' => 3, 'action' => 'confirm', 'reason' => 'Confirmar apenas este impacto mostrado.', 'approval_hash' => $match[1]])->assertRedirect('/facturas/envio-sgf/1');
|
||||
$done = $this->get('/facturas/envio-sgf/1')->assertOk()->assertSee('Recibo conservado')->assertDontSee('Confirmar individualmente')->assertSee('http://127.0.0.1:8085/compras?', false)->getContent();
|
||||
file_put_contents($this->privateRoot.'/screen-receipt.html',$done);
|
||||
self::assertCount(1,$this->remote);
|
||||
}
|
||||
public function test_missing_schema_is_refused_without_activating_or_migrating():void
|
||||
|
||||
public function test_missing_schema_is_refused_without_activating_or_migrating(): void
|
||||
{
|
||||
$migration=require dirname(__DIR__,2).'/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php';$migration->down();
|
||||
$this->get('/facturas/envio-sgf')->assertStatus(503);Http::assertNothingSent();self::assertFalse(Schema::hasTable('sgf_invoice_dispatches'));
|
||||
$migration = require dirname(__DIR__,2).'/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php';
|
||||
$migration->down();
|
||||
$this->get('/facturas/envio-sgf')->assertStatus(503);
|
||||
Http::assertNothingSent();
|
||||
self::assertFalse(Schema::hasTable('sgf_invoice_dispatches'));
|
||||
}
|
||||
public function test_audit_freezes_preview_actor_and_context_fingerprint():void
|
||||
|
||||
public function test_audit_freezes_preview_actor_and_context_fingerprint(): void
|
||||
{
|
||||
$row=$this->prepared();$event=DB::table('sgf_invoice_dispatch_events')->orderByDesc('id')->first();$state=json_decode($event->after_state,true);
|
||||
self::assertSame(1,$state['preview_actor_id']);self::assertSame($row->source_context_hash,$state['source_context_hash']);
|
||||
$row = $this->prepared();
|
||||
$event = DB::table('sgf_invoice_dispatch_events')->orderByDesc('id')->first();
|
||||
$state = json_decode($event->after_state,true);
|
||||
self::assertSame(1,$state['preview_actor_id']);
|
||||
self::assertSame($row->source_context_hash,$state['source_context_hash']);
|
||||
}
|
||||
}
|
||||
|
||||
+18
-2
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tests\TestCase;
|
||||
|
||||
/*
|
||||
@@ -47,7 +48,22 @@ expect()->extend('toBeOne', function () {
|
||||
|
|
||||
*/
|
||||
|
||||
function something()
|
||||
/**
|
||||
* Root of the sibling SGF checkout (common finance sources), portable across machines.
|
||||
* Defaults to the folder next to this repository, e.g. C:/laragon/www/sgf-tempo on Laragon.
|
||||
*/
|
||||
function sgfTempoPath(string $relative = ''): string
|
||||
{
|
||||
// ..
|
||||
$root = getenv('SGF_TEMPO_ROOT') ?: dirname(__DIR__, 2).'/sgf-tempo';
|
||||
$path = rtrim(str_replace('\\', '/', $root), '/');
|
||||
|
||||
return $relative === '' ? $path : $path.'/'.ltrim($relative, '/');
|
||||
}
|
||||
|
||||
/** Tests that assert the identity of an isolated PostgreSQL QA database cannot run on SQLite. */
|
||||
function skipUnlessIsolatedPostgres(PHPUnit\Framework\TestCase $test): void
|
||||
{
|
||||
if (DB::connection()->getDriverName() !== 'pgsql') {
|
||||
$test->markTestSkipped('Requires the isolated PostgreSQL QA database (see tests/Concurrency).');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ use App\Models\Supplier;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Models\Warehouse;
|
||||
use App\Services\PurchaseLineAmounts;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
@@ -31,7 +33,7 @@ function receiptFixture(string $quantity = '1.000', string $purchaseType = 'cons
|
||||
throw new LogicException('The explicit multi-category fixture uses one unit per line.');
|
||||
}
|
||||
$lineMinor = intdiv(10000, count($categories));
|
||||
$amounts = \App\Services\PurchaseLineAmounts::portion($lineMinor, '0', 0, \App\Services\ReceiptWorkflow::milli($quantity));
|
||||
$amounts = PurchaseLineAmounts::portion($lineMinor, '0', 0, ReceiptWorkflow::milli($quantity));
|
||||
$documentMinor = $amounts['total_minor'] * count($categories);
|
||||
$tenant = Tenant::query()->create(['name' => 'Empresa fictícia de recepção']);
|
||||
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => 'Operações']);
|
||||
|
||||
@@ -316,7 +316,7 @@ function requisitionAccountsNativeReviewFixture(bool $integrated = false, bool $
|
||||
$vatSourceId = $vatSource->id;
|
||||
}
|
||||
if (getenv('RQ01_QA_ICE_REFERENCE') === '1') {
|
||||
$icePath = base_path('tmp/pdfs/import-legal-source-review-20261128/law7-2025-official-second-supplement.pdf');
|
||||
$icePath = base_path('tests/Fixtures/legal/law7-2025-official-second-supplement.pdf');
|
||||
if (! is_file($icePath) || hash_file('sha256', $icePath) !== ImportLegalReferenceDrafts::ICE_EDITION_SHA256) {
|
||||
throw new LogicException('The ICE preview requires the exact retained official second supplement.');
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ function requisitionLedgerQaSource(): ?string
|
||||
if (! is_string($source) || $source === '') {
|
||||
return null;
|
||||
}
|
||||
if ($source === 'C:/laragon/www/sgf-tempo/packages/general-ledger') {
|
||||
if ($source === sgfTempoPath('packages/general-ledger')) {
|
||||
if (config('common-finance-bundle.manifest_sha256') === '182e10ceec556e120ecb14b57d17f0132ce0b555041cb054cdf9d17bcc1d51df') {
|
||||
throw new LogicException('A pinned private composition cannot fall back to the canonical development source.');
|
||||
}
|
||||
|
||||
@@ -1,16 +1,41 @@
|
||||
<?php
|
||||
$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));$file=realpath($argv[1]??'');
|
||||
if(!$root||!$file||dirname($file)!==$root)throw new RuntimeException('Unexpected private worker');
|
||||
require getcwd().'/vendor/autoload.php';$app=require getcwd().'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$db=Illuminate\Support\Facades\DB::connection();$i=$db->selectOne("SELECT current_database() AS name,current_user AS role,current_setting('cluster_name') AS cluster");
|
||||
if(!preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->name,$m)||$i->role!=='stock_receipt_qa_'.$m[1]||$i->cluster!=='sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'))throw new RuntimeException('Wrong receipt worker database');
|
||||
$input=json_decode(file_get_contents($file),true,512,JSON_THROW_ON_ERROR);
|
||||
$db->select("SELECT set_config('application_name',?,false)",[$input['application']]);$db->statement("SET lock_timeout='8s'");$db->statement("SET statement_timeout='12s'");
|
||||
$actor=App\Models\User::findOrFail($input['actor']);auth()->guard()->setUser($actor);
|
||||
file_put_contents($file.'.ready','ready');
|
||||
$start=hrtime(true);
|
||||
try{$receipt=app(App\Services\ReceiptWorkflow::class)->confirm($actor,App\Models\PurchaseOrder::findOrFail($input['order']),$input['payload']);
|
||||
$result=['status'=>200,'receipt_id'=>$receipt->id];
|
||||
}catch(Illuminate\Validation\ValidationException){$result=['status'=>422];}
|
||||
catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$result=['status'=>$e->getStatusCode()];}
|
||||
$result['elapsed_ms']=round((hrtime(true)-$start)/1e6,3);file_put_contents($file.'.result',json_encode($result,JSON_THROW_ON_ERROR));
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\User;
|
||||
use App\Services\ReceiptWorkflow;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
|
||||
$file = realpath($argv[1] ?? '');
|
||||
if (! $root || ! $file || dirname($file) !== $root) {
|
||||
throw new RuntimeException('Unexpected private worker');
|
||||
}
|
||||
require getcwd().'/vendor/autoload.php';
|
||||
$app = require getcwd().'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$db = DB::connection();
|
||||
$i = $db->selectOne("SELECT current_database() AS name,current_user AS role,current_setting('cluster_name') AS cluster");
|
||||
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->name, $m) || $i->role !== 'stock_receipt_qa_'.$m[1] || $i->cluster !== 'sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN')) {
|
||||
throw new RuntimeException('Wrong receipt worker database');
|
||||
}
|
||||
$input = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
$db->select("SELECT set_config('application_name',?,false)", [$input['application']]);
|
||||
$db->statement("SET lock_timeout='8s'");
|
||||
$db->statement("SET statement_timeout='12s'");
|
||||
$actor = User::findOrFail($input['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
file_put_contents($file.'.ready', 'ready');
|
||||
$start = hrtime(true);
|
||||
try {
|
||||
$receipt = app(ReceiptWorkflow::class)->confirm($actor, PurchaseOrder::findOrFail($input['order']), $input['payload']);
|
||||
$result = ['status' => 200, 'receipt_id' => $receipt->id];
|
||||
} catch (ValidationException) {
|
||||
$result = ['status' => 422];
|
||||
} catch (HttpExceptionInterface $e) {
|
||||
$result = ['status' => $e->getStatusCode()];
|
||||
}
|
||||
$result['elapsed_ms'] = round((hrtime(true) - $start) / 1e6, 3);
|
||||
file_put_contents($file.'.result', json_encode($result,JSON_THROW_ON_ERROR));
|
||||
|
||||
@@ -9,43 +9,97 @@ if (!root) throw Error('Explicit verified candidate package root required');
|
||||
|
||||
function workspace(file, host = true) {
|
||||
const forms = [0, 1].map(() => ({
|
||||
dataset: { action: file.startsWith('general-ledger') ? 'prepare' : 'payment-prepare' },
|
||||
values: new Map([['reason', '']]), button: { disabled: false }, appended: [],
|
||||
querySelector(selector) { return selector === 'button' ? this.button : null; },
|
||||
querySelectorAll(selector) { return selector === 'button' ? [this.button] : []; },
|
||||
append(...nodes) { this.appended.push(...nodes); },
|
||||
dataset: {
|
||||
action: file.startsWith('general-ledger')
|
||||
? 'prepare'
|
||||
: 'payment-prepare',
|
||||
},
|
||||
values: new Map([['reason', '']]),
|
||||
button: { disabled: false },
|
||||
appended: [],
|
||||
querySelector(selector) {
|
||||
return selector === 'button' ? this.button : null;
|
||||
},
|
||||
querySelectorAll(selector) {
|
||||
return selector === 'button' ? [this.button] : [];
|
||||
},
|
||||
append(...nodes) {
|
||||
this.appended.push(...nodes);
|
||||
},
|
||||
}));
|
||||
const nodes = Object.fromEntries(['#finance', '#reload', '#status', '#error', 'main'].map(id => [id, { textContent: '', focus() {}, prepend() {} }]));
|
||||
const nodes = Object.fromEntries(
|
||||
['#finance', '#reload', '#status', '#error', 'main'].map((id) => [
|
||||
id,
|
||||
{ textContent: '', focus() {}, prepend() {} },
|
||||
]),
|
||||
);
|
||||
const events = new Map();
|
||||
const state = { reloads: 0, requests: [], response: async () => ({ ok: true, json: async () => ({ state: 'saved' }) }) };
|
||||
const settings = { api: '/api/supplier-payments', csrf: 'synthetic', host_journal_policy: host, host_settlement_policy: host };
|
||||
const state = {
|
||||
reloads: 0,
|
||||
requests: [],
|
||||
response: async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ state: 'saved' }),
|
||||
}),
|
||||
};
|
||||
const settings = {
|
||||
api: '/api/supplier-payments',
|
||||
csrf: 'synthetic',
|
||||
host_journal_policy: host,
|
||||
host_settlement_policy: host,
|
||||
};
|
||||
const source = readFileSync(path.join(root, file), 'utf8');
|
||||
const script = source.match(/<script>([\s\S]*?)<\/script>/)[1]
|
||||
.replace(/const settings=<\?=[\s\S]*?\?>;/, `const settings=${JSON.stringify(settings)};`);
|
||||
const script = source
|
||||
.match(/<script>([\s\S]*?)<\/script>/)[1]
|
||||
.replace(
|
||||
/const settings=<\?=[\s\S]*?\?>;/,
|
||||
`const settings=${JSON.stringify(settings)};`,
|
||||
);
|
||||
let key = 0;
|
||||
const context = vm.createContext({
|
||||
document: {
|
||||
querySelector: selector => nodes[selector],
|
||||
querySelectorAll: selector => selector === '[data-action]' ? forms : [],
|
||||
querySelector: (selector) => nodes[selector],
|
||||
querySelectorAll: (selector) =>
|
||||
selector === '[data-action]' ? forms : [],
|
||||
createElement: () => ({ textContent: '', setAttribute() {} }),
|
||||
},
|
||||
FormData: class { constructor(form) { this.form = form; } [Symbol.iterator]() { return this.form.values.entries(); } },
|
||||
window: { addEventListener: (event, callback) => events.set(event, callback) },
|
||||
FormData: class {
|
||||
constructor(form) {
|
||||
this.form = form;
|
||||
}
|
||||
[Symbol.iterator]() {
|
||||
return this.form.values.entries();
|
||||
}
|
||||
},
|
||||
window: {
|
||||
addEventListener: (event, callback) => events.set(event, callback),
|
||||
},
|
||||
location: { reload: () => state.reloads++, assign() {} },
|
||||
crypto: { randomUUID: () => `synthetic-operation-${++key}` },
|
||||
fetch: async (url, options) => { state.requests.push({ url, ...options }); return state.response(); },
|
||||
fetch: async (url, options) => {
|
||||
state.requests.push({ url, ...options });
|
||||
return state.response();
|
||||
},
|
||||
});
|
||||
vm.runInContext(script, context);
|
||||
const leaving = () => {
|
||||
const event = { prevented: false, preventDefault() { this.prevented = true; } };
|
||||
const event = {
|
||||
prevented: false,
|
||||
preventDefault() {
|
||||
this.prevented = true;
|
||||
},
|
||||
};
|
||||
events.get('beforeunload')?.(event);
|
||||
return event.prevented;
|
||||
};
|
||||
const submit = form => form.onsubmit({ preventDefault() {} });
|
||||
const submit = (form) => form.onsubmit({ preventDefault() {} });
|
||||
return { forms, state, leaving, submit, nodes };
|
||||
}
|
||||
|
||||
for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php']) {
|
||||
for (const file of [
|
||||
'general-ledger/ui/cycle.php',
|
||||
'payables/ui/settlements.php',
|
||||
]) {
|
||||
test(`${file}: only an edited preparation warns before leaving`, () => {
|
||||
const w = workspace(file);
|
||||
assert.equal(w.leaving(), false);
|
||||
@@ -62,7 +116,10 @@ for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php'
|
||||
await w.submit(w.forms[0]);
|
||||
assert.equal(w.state.reloads, 0);
|
||||
assert.equal(w.forms[0].button.disabled, true);
|
||||
assert.equal(w.forms[1].values.get('reason'), 'Preserve this separate preparation');
|
||||
assert.equal(
|
||||
w.forms[1].values.get('reason'),
|
||||
'Preserve this separate preparation',
|
||||
);
|
||||
assert.equal(w.leaving(), true);
|
||||
assert.equal(w.forms[0].appended.length, 2);
|
||||
assert.match(w.forms[0].appended[0].textContent, /registada/);
|
||||
@@ -76,8 +133,13 @@ for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php'
|
||||
|
||||
test(`${file}: unknown network result preserves values and retries the same command identity`, async () => {
|
||||
const w = workspace(file);
|
||||
w.forms[0].values.set('reason', 'Do not lose an interrupted synthetic operation');
|
||||
w.state.response = async () => { throw Error('Synthetic lost response'); };
|
||||
w.forms[0].values.set(
|
||||
'reason',
|
||||
'Do not lose an interrupted synthetic operation',
|
||||
);
|
||||
w.state.response = async () => {
|
||||
throw Error('Synthetic lost response');
|
||||
};
|
||||
await w.submit(w.forms[0]);
|
||||
assert.equal(w.forms[0].button.disabled, false);
|
||||
assert.equal(w.state.reloads, 0);
|
||||
@@ -87,14 +149,20 @@ for (const file of ['general-ledger/ui/cycle.php', 'payables/ui/settlements.php'
|
||||
w.state.response = async () => ({ ok: true, json: async () => ({}) });
|
||||
await w.submit(w.forms[0]);
|
||||
assert.equal(w.state.requests[1].headers['Idempotency-Key'], key);
|
||||
assert.equal(w.forms[0].values.get('reason'), 'Do not lose an interrupted synthetic operation');
|
||||
assert.equal(
|
||||
w.forms[0].values.get('reason'),
|
||||
'Do not lose an interrupted synthetic operation',
|
||||
);
|
||||
assert.equal(w.state.reloads, 1);
|
||||
});
|
||||
|
||||
test(`${file}: a second submit while pending cannot start another request`, async () => {
|
||||
const w = workspace(file);
|
||||
let finish;
|
||||
w.state.response = () => new Promise(resolve => { finish = resolve; });
|
||||
w.state.response = () =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
const pending = w.submit(w.forms[0]);
|
||||
await w.submit(w.forms[0]);
|
||||
assert.equal(w.state.requests.length, 1);
|
||||
|
||||
@@ -4,22 +4,36 @@ import { test } from 'node:test';
|
||||
import { createNativeInertiaClient } from '../../scripts/lib/native-inertia-client.mjs';
|
||||
|
||||
test('owned native client drains large closed responses while preserving body headers cookies and manual redirects', async () => {
|
||||
const payload = { synthetic_only: true, content: 'x'.repeat(2 * 1024 * 1024) };
|
||||
const payload = {
|
||||
synthetic_only: true,
|
||||
content: 'x'.repeat(2 * 1024 * 1024),
|
||||
};
|
||||
let cookiesSeen = '';
|
||||
const server = createServer((request, response) => {
|
||||
response.setHeader('Connection', 'close');
|
||||
response.useChunkedEncodingByDefault = false;
|
||||
if (request.url === '/cookies') {
|
||||
response.setHeader('Set-Cookie', ['QA_SESSION=first; Path=/', 'QA_CONTEXT=second; Path=/']);
|
||||
response.setHeader('Set-Cookie', [
|
||||
'QA_SESSION=first; Path=/',
|
||||
'QA_CONTEXT=second; Path=/',
|
||||
]);
|
||||
}
|
||||
if (request.url === '/empty') {
|
||||
response.writeHead(204);
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
if (request.url === '/redirect') {
|
||||
response.writeHead(302, { Location: '/large' });
|
||||
response.end('Synthetic redirect');
|
||||
return;
|
||||
}
|
||||
if (request.url === '/empty') { response.writeHead(204); response.end(); return; }
|
||||
if (request.url === '/redirect') { response.writeHead(302, { Location: '/large' }); response.end('Synthetic redirect'); return; }
|
||||
cookiesSeen = request.headers.cookie ?? '';
|
||||
response.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
response.write(JSON.stringify(payload));
|
||||
response.end();
|
||||
});
|
||||
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));
|
||||
await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
try {
|
||||
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||
const client = createNativeInertiaClient(origin, assert.ok);
|
||||
@@ -44,9 +58,12 @@ test('owned native client drains large closed responses while preserving body he
|
||||
assert.equal(redirect.status, 302);
|
||||
assert.equal(redirect.headers.get('Location'), '/large');
|
||||
assert.equal(await redirect.text(), 'Synthetic redirect');
|
||||
await assert.rejects(client.request('//example.test/foreign'), /External HTTP destination refused/);
|
||||
await assert.rejects(
|
||||
client.request('//example.test/foreign'),
|
||||
/External HTTP destination refused/,
|
||||
);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,10 +1,33 @@
|
||||
<?php
|
||||
$file=realpath($argv[1]??'');$private=realpath(getcwd().'/../private');
|
||||
if(!$file||!$private||!str_starts_with($file,$private.DIRECTORY_SEPARATOR))throw new LogicException('Private QA worker input refused');
|
||||
require getcwd().'/vendor/autoload.php';$app=require getcwd().'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$p=json_decode(file_get_contents($file),true,64,JSON_THROW_ON_ERROR);$db=Illuminate\Support\Facades\DB::connection();$i=$db->selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
if(!preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->db,$m)||$i->role!=='stock_receipt_qa_'.$m[1]||(int)$i->port!==55439||$i->cluster!=='sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'))throw new LogicException('QA worker database refused');
|
||||
config(['common-payables.enabled'=>true,'common-payables.history_enabled'=>true,'common-payables.paged_read_enabled'=>true,'common-payables.source_instance'=>$p['instance']]);$u=App\Models\User::query()->findOrFail($p['actor']);auth()->setUser($u);$time=hrtime(true);
|
||||
try{$d=app(App\Services\SupplierPayables::class)->listing($u);$out=['status'=>200,'documents'=>count($d['documents']),'balances'=>array_column($d['obligations'],'balance_minor'),'time_ms'=>(hrtime(true)-$time)/1e6];}
|
||||
catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$out=['status'=>$e->getStatusCode()];}
|
||||
file_put_contents($file.'.result',json_encode($out,JSON_PRETTY_PRINT|JSON_THROW_ON_ERROR));
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\SupplierPayables;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
$file = realpath($argv[1] ?? '');
|
||||
$private = realpath(getcwd().'/../private');
|
||||
if (! $file || ! $private || ! str_starts_with($file, $private.DIRECTORY_SEPARATOR)) {
|
||||
throw new LogicException('Private QA worker input refused');
|
||||
}
|
||||
require getcwd().'/vendor/autoload.php';
|
||||
$app = require getcwd().'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$p = json_decode(file_get_contents($file), true, 64, JSON_THROW_ON_ERROR);
|
||||
$db = DB::connection();
|
||||
$i = $db->selectOne("SELECT current_database() AS db,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->db, $m) || $i->role !== 'stock_receipt_qa_'.$m[1] || (int) $i->port !== 55439 || $i->cluster !== 'sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN')) {
|
||||
throw new LogicException('QA worker database refused');
|
||||
}
|
||||
config(['common-payables.enabled' => true, 'common-payables.history_enabled' => true, 'common-payables.paged_read_enabled' => true, 'common-payables.source_instance' => $p['instance']]);
|
||||
$u = User::query()->findOrFail($p['actor']);
|
||||
auth()->setUser($u);
|
||||
$time = hrtime(true);
|
||||
try {
|
||||
$d = app(SupplierPayables::class)->listing($u);
|
||||
$out = ['status' => 200, 'documents' => count($d['documents']), 'balances' => array_column($d['obligations'], 'balance_minor'), 'time_ms' => (hrtime(true) - $time) / 1e6];
|
||||
} catch (HttpExceptionInterface $e) {
|
||||
$out = ['status' => $e->getStatusCode()];
|
||||
}
|
||||
file_put_contents($file.'.result', json_encode($out, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
|
||||
|
||||
@@ -1,44 +1,68 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use Tempo\Purchasing\Delivery\SqlPrivileges;
|
||||
|
||||
// Runs only inside the disposable reproduction after its authorised lifecycle.
|
||||
// Inherits the explicit test scope/clients; never creates grants in the host.
|
||||
$catalogue=$call($actor,'/api/accesses');
|
||||
$check($catalogue['status']===200&&in_array('purchasing_requisitions.prepare',$catalogue['data']['catalogue']['unit'],true),'native administration receives complete unit catalogue');
|
||||
$check(($catalogue['data']['catalogue_labels']['purchasing_requisitions.prepare']??'')==='Preparar e submeter requisições','native administration receives canonical server labels');
|
||||
$check($call($head,'/api/accesses')['status']===403,'reviewer cannot inspect administrative catalogue without management right');
|
||||
$check($call($actor,'/api/accesses','POST',['email'=>\App\Models\User::findOrFail($head)->email,'unit_id'=>$scope['unit_id'],'permission'=>'purchasing_budget.consume','reason'=>'Forbidden delegation outside own synthetic authority'])['status']===403,'forged delegation of an unowned catalogue right refused');
|
||||
$catalogue = $call($actor, '/api/accesses');
|
||||
$check($catalogue['status'] === 200 && in_array('purchasing_requisitions.prepare', $catalogue['data']['catalogue']['unit'], true), 'native administration receives complete unit catalogue');
|
||||
$check(($catalogue['data']['catalogue_labels']['purchasing_requisitions.prepare'] ?? '') === 'Preparar e submeter requisições', 'native administration receives canonical server labels');
|
||||
$check($call($head, '/api/accesses')['status'] === 403, 'reviewer cannot inspect administrative catalogue without management right');
|
||||
$check($call($actor, '/api/accesses', 'POST', ['email' => User::findOrFail($head)->email, 'unit_id' => $scope['unit_id'], 'permission' => 'purchasing_budget.consume', 'reason' => 'Forbidden delegation outside own synthetic authority'])['status'] === 403, 'forged delegation of an unowned catalogue right refused');
|
||||
|
||||
$uiManifest=json_decode(file_get_contents($clone.'/public/build/manifest.json'),true,32,JSON_THROW_ON_ERROR);
|
||||
foreach($uiManifest as $chunk)foreach([$chunk['file'],...($chunk['css']??[])] as $file){
|
||||
$asset=$anonymous->get('http://127.0.0.1:'.$port.'/build/'.$file);
|
||||
$check($asset->getStatusCode()===200&&strlen((string)$asset->getBody())>100,'packaged frontend dependency served before authentication');
|
||||
$uiManifest = json_decode(file_get_contents($clone.'/public/build/manifest.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
foreach ($uiManifest as $chunk) {
|
||||
foreach ([$chunk['file'], ...($chunk['css'] ?? [])] as $file) {
|
||||
$asset = $anonymous->get('http://127.0.0.1:'.$port.'/build/'.$file);
|
||||
$check($asset->getStatusCode() === 200 && strlen((string) $asset->getBody()) > 100, 'packaged frontend dependency served before authentication');
|
||||
}
|
||||
}
|
||||
$main=$anonymous->get('http://127.0.0.1:'.$port.'/');
|
||||
$check($main->getStatusCode()===200&&str_contains((string)$main->getBody(),'/build/modules/internal-requisitions/assets/'),'native SGF entry renders the packaged frontend manifest');
|
||||
$check($anonymous->get('http://127.0.0.1:'.$port.'/build/modules/internal-requisitions/assets/missing.js')->getStatusCode()===404,'undeclared frontend asset refused');
|
||||
$main = $anonymous->get('http://127.0.0.1:'.$port.'/');
|
||||
$check($main->getStatusCode() === 200 && str_contains((string) $main->getBody(), '/build/modules/internal-requisitions/assets/'), 'native SGF entry renders the packaged frontend manifest');
|
||||
$check($anonymous->get('http://127.0.0.1:'.$port.'/build/modules/internal-requisitions/assets/missing.js')->getStatusCode() === 404, 'undeclared frontend asset refused');
|
||||
|
||||
// Reproduce destination-style broad inherited ACLs on NEW objects, then prove
|
||||
// the proposed map narrows them without touching any of the 87 prior tables.
|
||||
$beforeAcl=[];
|
||||
foreach($inventory['tables'] as $table)$beforeAcl[$table]=$db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass',['public.'.$table])->acl;
|
||||
foreach(\Tempo\Purchasing\Delivery\SqlPrivileges::TABLES as $table=>$rights)$db->statement('GRANT SELECT,INSERT,UPDATE,DELETE ON TABLE public.'.$q($table).' TO '.$q($runtime));
|
||||
foreach(\Tempo\Purchasing\Delivery\SqlPrivileges::plan($runtime)['statements'] as $sql)$db->statement($sql);
|
||||
$check(!$rt->selectOne("SELECT has_table_privilege(current_user,'cb_centres','UPDATE') AS allowed")->allowed&&!$rt->selectOne("SELECT has_table_privilege(current_user,'cb_audit','DELETE') AS allowed")->allowed,'minimal plan removes inherited update and delete on new append-only sources');
|
||||
$check(!$rt->selectOne("SELECT has_table_privilege(current_user,'ir_requests','TRUNCATE') AS allowed")->allowed,'runtime cannot truncate requisitions');
|
||||
foreach($beforeAcl as $table=>$acl)$check($db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass',['public.'.$table])->acl===$acl,'existing table ACL preserved '.$table);
|
||||
try{$rt->transaction(fn()=>$rt->statement('CREATE TABLE forbidden_runtime_ddl (id integer)'));throw new LogicException('Unexpected runtime DDL');}
|
||||
catch(\Illuminate\Database\QueryException $e){$check($e->errorInfo[0]==='42501','actual runtime CREATE denied');}
|
||||
try{$rt->transaction(fn()=>$rt->statement('ALTER TABLE permission_grants ADD COLUMN forbidden_runtime integer'));throw new LogicException('Unexpected runtime ALTER');}
|
||||
catch(\Illuminate\Database\QueryException $e){$check($e->errorInfo[0]==='42501','actual runtime ALTER of identity catalogue denied');}
|
||||
|
||||
$badCentre=['operation_key'=>(string)\Illuminate\Support\Str::uuid(),'code'=>'NOT-ALLOWED','reason'=>'Validation in the isolated reproduction only'];
|
||||
$check($call($head,'/api/internal-requisitions/centres','POST',$badCentre)['status']===403,'centre creation requires own configuration and budget rights');
|
||||
$check($call($actor,'/api/internal-requisitions/centres','POST',$badCentre+['company_id'=>999999])['status']===422,'centre context cannot be forged');
|
||||
$check(\Illuminate\Support\Facades\DB::table('cb_centres')->count()===1,'refused centre operations leave original source intact');
|
||||
foreach(['equipment','part'] as $unsupported){
|
||||
$r=$call($actor,'/api/internal-requisitions/save','POST',['operation_key'=>(string)\Illuminate\Support\Str::uuid(),'cost_center_id'=>$f['centre'],'priority'=>'normal','needed_by'=>date('Y-m-d',time()+864000),'justification'=>'Unsupported type must remain outside this increment.','items'=>[['description'=>'Unsupported source','category'=>'Excluded','purchase_type'=>$unsupported,'quantity'=>'1.000','unit'=>'UN','unit_price'=>'1.00','tax_rate'=>'0.00']]]);
|
||||
$check($r['status']===422,'unsupported requisition type refused '.$unsupported);
|
||||
$beforeAcl = [];
|
||||
foreach ($inventory['tables'] as $table) {
|
||||
$beforeAcl[$table] = $db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass', ['public.'.$table])->acl;
|
||||
}
|
||||
$data=json_decode(\Illuminate\Support\Facades\DB::table('ir_requests')->where('id',$id)->value('data'),true,32,JSON_THROW_ON_ERROR);
|
||||
$check(array_column($data['items'],'purchase_type')===['consumable','service','other'],'approved lifecycle covers the three supported basic types');
|
||||
$check(\Illuminate\Support\Facades\DB::table('ir_requests')->count()===1&&\Illuminate\Support\Facades\DB::table('cb_budget_entries')->where('kind','reserve')->count()===1,'unsupported types create neither a second request nor reservation');
|
||||
foreach (SqlPrivileges::TABLES as $table => $rights) {
|
||||
$db->statement('GRANT SELECT,INSERT,UPDATE,DELETE ON TABLE public.'.$q($table).' TO '.$q($runtime));
|
||||
}
|
||||
foreach (SqlPrivileges::plan($runtime)['statements'] as $sql) {
|
||||
$db->statement($sql);
|
||||
}
|
||||
$check(! $rt->selectOne("SELECT has_table_privilege(current_user,'cb_centres','UPDATE') AS allowed")->allowed && ! $rt->selectOne("SELECT has_table_privilege(current_user,'cb_audit','DELETE') AS allowed")->allowed, 'minimal plan removes inherited update and delete on new append-only sources');
|
||||
$check(! $rt->selectOne("SELECT has_table_privilege(current_user,'ir_requests','TRUNCATE') AS allowed")->allowed, 'runtime cannot truncate requisitions');
|
||||
foreach ($beforeAcl as $table => $acl) {
|
||||
$check($db->selectOne('SELECT relacl::text AS acl FROM pg_class WHERE oid=?::regclass', ['public.'.$table])->acl === $acl, 'existing table ACL preserved '.$table);
|
||||
}
|
||||
try {
|
||||
$rt->transaction(fn () => $rt->statement('CREATE TABLE forbidden_runtime_ddl (id integer)'));
|
||||
throw new LogicException('Unexpected runtime DDL');
|
||||
} catch (QueryException $e) {
|
||||
$check($e->errorInfo[0] === '42501', 'actual runtime CREATE denied');
|
||||
}
|
||||
try {
|
||||
$rt->transaction(fn () => $rt->statement('ALTER TABLE permission_grants ADD COLUMN forbidden_runtime integer'));
|
||||
throw new LogicException('Unexpected runtime ALTER');
|
||||
} catch (QueryException $e) {
|
||||
$check($e->errorInfo[0] === '42501', 'actual runtime ALTER of identity catalogue denied');
|
||||
}
|
||||
|
||||
$badCentre = ['operation_key' => (string) Str::uuid(), 'code' => 'NOT-ALLOWED', 'reason' => 'Validation in the isolated reproduction only'];
|
||||
$check($call($head, '/api/internal-requisitions/centres', 'POST', $badCentre)['status'] === 403, 'centre creation requires own configuration and budget rights');
|
||||
$check($call($actor, '/api/internal-requisitions/centres', 'POST', $badCentre + ['company_id' => 999999])['status'] === 422, 'centre context cannot be forged');
|
||||
$check(DB::table('cb_centres')->count() === 1, 'refused centre operations leave original source intact');
|
||||
foreach (['equipment', 'part'] as $unsupported) {
|
||||
$r = $call($actor, '/api/internal-requisitions/save', 'POST', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['centre'], 'priority' => 'normal', 'needed_by' => date('Y-m-d', time() + 864000), 'justification' => 'Unsupported type must remain outside this increment.', 'items' => [['description' => 'Unsupported source', 'category' => 'Excluded', 'purchase_type' => $unsupported, 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '1.00', 'tax_rate' => '0.00']]]);
|
||||
$check($r['status'] === 422, 'unsupported requisition type refused '.$unsupported);
|
||||
}
|
||||
$data = json_decode(DB::table('ir_requests')->where('id', $id)->value('data'), true, 32, JSON_THROW_ON_ERROR);
|
||||
$check(array_column($data['items'], 'purchase_type') === ['consumable', 'service', 'other'], 'approved lifecycle covers the three supported basic types');
|
||||
$check(DB::table('ir_requests')->count() === 1 && DB::table('cb_budget_entries')->where('kind','reserve')->count() === 1, 'unsupported types create neither a second request nor reservation');
|
||||
|
||||
@@ -218,7 +218,7 @@ try {
|
||||
$check($call($actor, '/api/purchasing-budget/movement', 'POST', [], ['Idempotency-Key' => (string) Str::uuid()])['status'] === 403, 'direct budget movements cannot bypass requisition lifecycle');
|
||||
$policy = ['version' => 0, 'reason' => 'Política sintética na composição integrada.', 'enabled' => true, 'budget_required' => true, 'first_limit_minor' => 1000000, 'second_limit_minor' => 2000000, 'approval_includes_tax' => true, 'centres' => [['id' => $f['centre'], 'department_ref' => 'OPER']], 'members' => [['user_id' => $actor, 'department_ref' => 'OPER'], ['user_id' => $head, 'department_ref' => 'OPER']]];
|
||||
$check($call($actor, '/api/internal-requisitions/policy', 'POST', $policy)['status'] === 200, 'operational policy configured via HTTP');
|
||||
$draft = $call($actor, '/api/internal-requisitions/save', 'POST', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['centre'], 'priority' => 'normal', 'needed_by' => date('Y-m-d', time() + 864000), 'justification' => 'Requisição sintética da composição.', 'items' => [['description' => 'Material', 'category' => 'Consumíveis', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00'], ['description'=>'Servi?o sint?tico','category'=>'Servi?os','purchase_type'=>'service','quantity'=>'1.000','unit'=>'UN','unit_price'=>'25.00','tax_rate'=>'0.00'], ['description'=>'Outro sint?tico','category'=>'Outros','purchase_type'=>'other','quantity'=>'1.000','unit'=>'UN','unit_price'=>'10.00','tax_rate'=>'0.00']]]);
|
||||
$draft = $call($actor, '/api/internal-requisitions/save', 'POST', ['operation_key' => (string) Str::uuid(), 'cost_center_id' => $f['centre'], 'priority' => 'normal', 'needed_by' => date('Y-m-d', time() + 864000), 'justification' => 'Requisição sintética da composição.', 'items' => [['description' => 'Material', 'category' => 'Consumíveis', 'purchase_type' => 'consumable', 'quantity' => '2.000', 'unit' => 'UN', 'unit_price' => '50.00', 'tax_rate' => '16.00'], ['description' => 'Servi?o sint?tico', 'category' => 'Servi?os', 'purchase_type' => 'service', 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '25.00', 'tax_rate' => '0.00'], ['description' => 'Outro sint?tico', 'category' => 'Outros', 'purchase_type' => 'other', 'quantity' => '1.000', 'unit' => 'UN', 'unit_price' => '10.00', 'tax_rate' => '0.00']]]);
|
||||
$check($draft['status'] === 200, 'integrated operational draft');
|
||||
$id = $draft['data']['id'];
|
||||
$submitted = $call($actor, "/api/internal-requisitions/$id/submit", 'POST', ['operation_key' => (string) Str::uuid(), 'version' => 1]);
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
$variant = $work.'/code-only-successor';
|
||||
$vm = json_decode(file_get_contents($bundle.'/manifest.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
foreach ([...array_keys($vm['support_files']), 'manifest.json'] as $file) {
|
||||
if (! is_dir(dirname($variant.'/'.$file))) mkdir(dirname($variant.'/'.$file), 0700, true);
|
||||
if (! is_dir(dirname($variant.'/'.$file))) {
|
||||
mkdir(dirname($variant.'/'.$file), 0700, true);
|
||||
}
|
||||
copy($bundle.'/'.$file, $variant.'/'.$file);
|
||||
}
|
||||
$file = 'integrations/sgf/internal-requisitions/screen.php';
|
||||
@@ -19,6 +21,8 @@ $deploy->rollback($vu['deployment_id'], 'Isolated successor recovery', true);
|
||||
$check(hash_file('sha256', $clone.'/packages/internal-requisitions/manifest.json') === hash_file('sha256', $bundle.'/manifest.json'), 'code-only successor rollback restores exact candidate');
|
||||
foreach ($fingerprints as $table => $expected) {
|
||||
$rows = $db->select('select to_jsonb(t)::text as data from "'.$table.'" t order by to_jsonb(t)::text');
|
||||
if (hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR)) !== $expected) throw new RuntimeException('Update changed '.$table);
|
||||
if (hash('sha256', json_encode(array_column($rows, 'data'), JSON_THROW_ON_ERROR)) !== $expected) {
|
||||
throw new RuntimeException('Update changed '.$table);
|
||||
}
|
||||
}
|
||||
$check(true, 'code update and rollback preserve every reproduced data table');
|
||||
|
||||
@@ -1,16 +1,38 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
$host=getenv('SOURCING_CLONE');$work=getenv('SOURCING_WORK');require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
|
||||
try{
|
||||
$db=DB::connection();if(!preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D',$db->getDatabaseName()))throw new RuntimeException('Copy only');
|
||||
$fixture=json_decode(file_get_contents($work.'/fixture.json'),true);$command=$argv[1];
|
||||
if(in_array($command,['revoke-evaluate','restore-evaluate','revoke-propose','restore-propose','revoke-view','restore-view'])){
|
||||
$right=str_contains($command,'evaluate')?'purchasing_sourcing.evaluate':(str_contains($command,'propose')?'purchasing_sourcing.propose':'purchasing_requisitions.view');$id=str_contains($command,'evaluate')?$fixture['user_id']:(str_contains($command,'propose')?2:3);
|
||||
$scope=['user_id'=>$id,'tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'permission'=>$right];
|
||||
if(str_starts_with($command,'revoke'))$db->table('permission_grants')->where($scope)->delete();else $db->table('permission_grants')->insertOrIgnore($scope+['created_at'=>now(),'updated_at'=>now()]);
|
||||
}elseif($command==='fail-on')file_put_contents($host.'/storage/framework/sourcing-failure.fixture','isolated failure injection');
|
||||
elseif($command==='fail-off')unlink($host.'/storage/framework/sourcing-failure.fixture');
|
||||
else throw new RuntimeException('Unsupported fixture control');
|
||||
echo json_encode(['ok'=>true]);
|
||||
}catch(Throwable $e){fwrite(STDERR,$e->getMessage());exit(1);}
|
||||
|
||||
$host = getenv('SOURCING_CLONE');
|
||||
$work = getenv('SOURCING_WORK');
|
||||
require $host.'/vendor/autoload.php';
|
||||
$app = require $host.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
try {
|
||||
$db = DB::connection();
|
||||
if (! preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D', $db->getDatabaseName())) {
|
||||
throw new RuntimeException('Copy only');
|
||||
}
|
||||
$fixture = json_decode(file_get_contents($work.'/fixture.json'), true);
|
||||
$command = $argv[1];
|
||||
if (in_array($command, ['revoke-evaluate', 'restore-evaluate', 'revoke-propose', 'restore-propose', 'revoke-view', 'restore-view'])) {
|
||||
$right = str_contains($command, 'evaluate') ? 'purchasing_sourcing.evaluate' : (str_contains($command, 'propose') ? 'purchasing_sourcing.propose' : 'purchasing_requisitions.view');
|
||||
$id = str_contains($command, 'evaluate') ? $fixture['user_id'] : (str_contains($command, 'propose') ? 2 : 3);
|
||||
$scope = ['user_id' => $id, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'permission' => $right];
|
||||
if (str_starts_with($command, 'revoke')) {
|
||||
$db->table('permission_grants')->where($scope)->delete();
|
||||
} else {
|
||||
$db->table('permission_grants')->insertOrIgnore($scope + ['created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
} elseif ($command === 'fail-on') {
|
||||
file_put_contents($host.'/storage/framework/sourcing-failure.fixture', 'isolated failure injection');
|
||||
} elseif ($command === 'fail-off') {
|
||||
unlink($host.'/storage/framework/sourcing-failure.fixture');
|
||||
} else {
|
||||
throw new RuntimeException('Unsupported fixture control');
|
||||
}
|
||||
echo json_encode(['ok' => true]);
|
||||
} catch (Throwable $e) {
|
||||
fwrite(STDERR, $e->getMessage());
|
||||
exit(1);
|
||||
}
|
||||
|
||||
@@ -1,51 +1,131 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Str;
|
||||
use App\Models\User;
|
||||
use Tempo\Purchasing\SgfSourcing\Schema;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Tempo\Purchasing\Delivery\CodeDeployment;
|
||||
$host=getenv('SOURCING_CLONE');$root=getenv('SOURCING_REPO');$work=getenv('SOURCING_WORK');
|
||||
require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
|
||||
try{
|
||||
$db=DB::connection();$name=$db->selectOne('select current_database() as db')->db;
|
||||
if(!preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D',$name)||$name!==getenv('SOURCING_DB')||!str_contains(str_replace('\\','/',$host),'/private/sourcing-')||str_replace('\\','/',$app->basePath())!==$host)throw new RuntimeException('Not an isolated sourcing copy');
|
||||
$candidate=json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-candidate.json'),true,32,JSON_THROW_ON_ERROR);
|
||||
if(!class_exists(Schema::class))require_once $candidate['directory'].'/integrations/sgf/sourcing/Schema.php';require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
|
||||
$deploy=new CodeDeployment($host);$checks=[];$check=function($ok,$label)use(&$checks){if(!$ok)throw new RuntimeException($label);$checks[]=$label;};
|
||||
$fingerprint=function(string $table)use($db){return hash('sha256',json_encode($db->table($table)->orderBy('id')->get(),JSON_THROW_ON_ERROR));};
|
||||
if(($argv[1]??'')==='setup'){
|
||||
$baseline=['request'=>$fingerprint('ir_requests'),'budget'=>$fingerprint('cb_budget_entries'),'consumption'=>$fingerprint('cb_budget_consumptions'),'grants_count'=>$db->table('permission_grants')->count()];file_put_contents($work.'/origin.json',json_encode($baseline));
|
||||
$armed=true;$db->listen(function($query)use(&$armed){if($armed&&str_contains(strtolower($query->sql),'create table "ss_events"')){$armed=false;throw new RuntimeException('Injected migration failure');}});
|
||||
try{Schema::migrate($db,hash_file('sha256',$work.'/before.dump'),'Isolated failure proof');throw new RuntimeException('Expected failure');}catch(RuntimeException $e){$check($e->getMessage()==='Injected migration failure','Injected migration failure surfaced');}
|
||||
$check(!$db->getSchemaBuilder()->hasTable('ss_suppliers')&&!$db->table('sgc_installations')->where('module','sourcing')->exists(),'Migration failure rolls back tables and catalogue');
|
||||
$migration=Schema::migrate($db,hash_file('sha256',$work.'/before.dump'),'Isolated sourcing proof');$check($migration['prepared'],'Additive migration accepted');$check(Schema::migrate($db,hash_file('sha256',$work.'/before.dump'),'Isolated replay')['replayed'],'Migration replay is stable');
|
||||
$old=json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'),true);$next=json_decode(file_get_contents($candidate['directory'].'/manifest.json'),true);
|
||||
$current=json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'),true);
|
||||
try{$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);throw new RuntimeException('Unprepared plan accepted');}catch(RuntimeException $e){$check(str_contains($e->getMessage(),'migração própria'),'Schema-changing update refuses missing migration receipt');}
|
||||
$receipt=['from_manifest_sha256'=>$current['manifest_sha256'],'to_manifest_sha256'=>$candidate['archive']['manifest_sha256'],'host'=>$host,'schema_verified'=>Schema::compatible($db),'changes'=>[]];
|
||||
foreach($next['support_files'] as $file=>$hash)if(($old['support_files'][$file]??null)!==$hash)$receipt['changes'][$file]=['before'=>$old['support_files'][$file]??null,'after'=>$hash];
|
||||
file_put_contents($host.'/storage/framework/down','{}');
|
||||
$cli=new Symfony\Component\Process\Process([PHP_BINARY,$candidate['directory'].'/scripts/sgf-sourcing-install.php','migrate',$host,Tempo\Purchasing\Delivery\Installation::target($db),$work.'/before.dump',hash_file('sha256',$work.'/before.dump'),'Isolated migration CLI',$candidate['archive']['manifest_sha256']],$host,['PG_RESTORE_BINARY'=>'C:/Program Files/PostgreSQL/17/bin/pg_restore.exe']);$cli->mustRun();
|
||||
$cliResult=json_decode($cli->getOutput(),true,32,JSON_THROW_ON_ERROR);$check($cliResult['prepared']&&!$cliResult['activated']&&!$cliResult['rights_granted'],'Packaged migration CLI produces exact receipt without activation or grants');
|
||||
$plan=$deploy->plan($candidate['directory'],$candidate['archive']['manifest_sha256']);$applied=$deploy->apply($candidate['directory'],$candidate['archive']['manifest_sha256'],$plan['target_sha256'],'Isolated sourcing update',true);unlink($host.'/storage/framework/down');file_put_contents($work.'/applied.json',json_encode($applied));
|
||||
$target=Tempo\Purchasing\Delivery\Installation::target($db);file_put_contents($host.'/config/purchasing-operational.php','<?php return '.var_export(['enabled'=>true,'target'=>$target,'scopes'=>['1:1:1']],true).';');file_put_contents($host.'/config/purchasing-sourcing.php','<?php return ["enabled"=>true];');
|
||||
$private=json_decode(file_get_contents('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json'),true);
|
||||
$user=User::forceCreate(['name'=>'Synthetic isolated evaluator','email'=>'fixture-'.Str::uuid().'@example.invalid','password'=>$private['password'],'auth_version'=>1]);
|
||||
$db->table('company_memberships')->insert(['user_id'=>$user->id,'tenant_id'=>1,'company_id'=>1]);
|
||||
$departmentPolicy=$db->table('ir_policies')->where(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1])->first();$departmentPayload=json_decode($departmentPolicy->payload,true);$departmentPayload['members'][]=['user_id'=>$user->id,'department_ref'=>'OPER'];$db->table('ir_policies')->where('id',$departmentPolicy->id)->update(['payload'=>json_encode($departmentPayload)]); // Disposable configuration fixture only; submitted request snapshot is unchanged.
|
||||
$grants=[1=>['purchasing_sourcing.prepare'],2=>['purchasing_sourcing.evaluate','purchasing_sourcing.propose'],$user->id=>['company.view','unit.view','purchasing_requisitions.view','purchasing_sourcing.evaluate','purchasing_sourcing.confirm']];
|
||||
foreach($grants as $id=>$rights)foreach($rights as $right)$db->table('permission_grants')->insert(['user_id'=>$id,'tenant_id'=>1,'company_id'=>1,'unit_id'=>$right==='company.view'?null:1,'permission'=>$right,'created_at'=>now(),'updated_at'=>now()]);
|
||||
foreach([1,2,3] as $n)$db->table('ss_suppliers')->insert(['tenant_id'=>1,'company_id'=>1,'unit_id'=>1,'reference'=>'SYNTHETIC-'.$n,'payload'=>json_encode(['name'=>'Fornecedor sintético '.$n,'active'=>true,'blocked'=>false,'review_until'=>'2027-12-31','version'=>1,'synthetic_only'=>true]),'created_at'=>now()]);
|
||||
file_put_contents($work.'/fixture.json',json_encode(['user_id'=>$user->id,'email'=>$user->email,'password'=>$private['password']]));
|
||||
echo json_encode(['passed'=>true,'checks'=>$checks,'fixture_user_only_in_disposable_copy'=>true,'deployment'=>$applied]);
|
||||
}elseif(($argv[1]??'')==='verify'){
|
||||
$baseline=json_decode(file_get_contents($work.'/origin.json'),true);foreach(['request'=>'ir_requests','budget'=>'cb_budget_entries','consumption'=>'cb_budget_consumptions'] as $key=>$table)$check($baseline[$key]===$fingerprint($table),'Origin '.$key.' unchanged');
|
||||
$check($db->table('ss_processes')->count()===1,'Exactly one sourcing process');$check($db->table('ss_commands')->count()===$db->table('ss_events')->count(),'One event per committed command');
|
||||
$saved=$db->table('ss_processes')->first();$state=json_decode($saved->payload,true);$check($state['confirmed']!==null,'Independent award confirmed in isolated copy');
|
||||
$before=$fingerprint('ss_events');$failed=false;try{$db->transaction(fn()=>$db->table('ss_events')->where('id',1)->update(['action'=>'tampered']));}catch(Throwable){$failed=true;}$check($failed&&$before===$fingerprint('ss_events'),'Database rejects event tampering');
|
||||
$applied=json_decode(file_get_contents($work.'/applied.json'),true);file_put_contents($host.'/storage/framework/down','{}');$rolled=$deploy->rollback($applied['deployment_id'],'Isolated sourcing code recovery',true);
|
||||
$check($state===json_decode($db->table('ss_processes')->first()->payload,true),'Code rollback preserves award data');
|
||||
echo json_encode(['passed'=>true,'checks'=>$checks,'code_recovery'=>$rolled,'old_code_requires_schema_recovery'=>true]);
|
||||
}else throw new RuntimeException('Use setup/verify');
|
||||
}catch(Throwable $e){fwrite(STDERR,get_class($e).': '.$e->getMessage()."\n");exit(1);}
|
||||
use Tempo\Purchasing\Delivery\Installation;
|
||||
use Tempo\Purchasing\SgfSourcing\Schema;
|
||||
|
||||
$host = getenv('SOURCING_CLONE');
|
||||
$root = getenv('SOURCING_REPO');
|
||||
$work = getenv('SOURCING_WORK');
|
||||
require $host.'/vendor/autoload.php';
|
||||
$app = require $host.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
try {
|
||||
$db = DB::connection();
|
||||
$name = $db->selectOne('select current_database() as db')->db;
|
||||
if (! preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D', $name) || $name !== getenv('SOURCING_DB') || ! str_contains(str_replace('\\', '/', $host), '/private/sourcing-') || str_replace('\\', '/', $app->basePath()) !== $host) {
|
||||
throw new RuntimeException('Not an isolated sourcing copy');
|
||||
}
|
||||
$candidate = json_decode(file_get_contents($root.'/docs/proofs/sgf-sourcing-candidate.json'), true, 32, JSON_THROW_ON_ERROR);
|
||||
if (! class_exists(Schema::class)) {
|
||||
require_once $candidate['directory'].'/integrations/sgf/sourcing/Schema.php';
|
||||
}require_once $root.'/integrations/sgf/operational/CodeDeployment.php';
|
||||
$deploy = new CodeDeployment($host);
|
||||
$checks = [];
|
||||
$check = function ($ok, $label) use (&$checks) {
|
||||
if (! $ok) {
|
||||
throw new RuntimeException($label);
|
||||
}$checks[] = $label;
|
||||
};
|
||||
$fingerprint = function (string $table) use ($db) {
|
||||
return hash('sha256', json_encode($db->table($table)->orderBy('id')->get(), JSON_THROW_ON_ERROR));
|
||||
};
|
||||
if (($argv[1] ?? '') === 'setup') {
|
||||
$baseline = ['request' => $fingerprint('ir_requests'), 'budget' => $fingerprint('cb_budget_entries'), 'consumption' => $fingerprint('cb_budget_consumptions'), 'grants_count' => $db->table('permission_grants')->count()];
|
||||
file_put_contents($work.'/origin.json', json_encode($baseline));
|
||||
$armed = true;
|
||||
$db->listen(function ($query) use (&$armed) {
|
||||
if ($armed && str_contains(strtolower($query->sql), 'create table "ss_events"')) {
|
||||
$armed = false;
|
||||
throw new RuntimeException('Injected migration failure');
|
||||
}
|
||||
});
|
||||
try {
|
||||
Schema::migrate($db, hash_file('sha256', $work.'/before.dump'), 'Isolated failure proof');
|
||||
throw new RuntimeException('Expected failure');
|
||||
} catch (RuntimeException $e) {
|
||||
$check($e->getMessage() === 'Injected migration failure', 'Injected migration failure surfaced');
|
||||
}
|
||||
$check(! $db->getSchemaBuilder()->hasTable('ss_suppliers') && ! $db->table('sgc_installations')->where('module', 'sourcing')->exists(), 'Migration failure rolls back tables and catalogue');
|
||||
$migration = Schema::migrate($db, hash_file('sha256', $work.'/before.dump'), 'Isolated sourcing proof');
|
||||
$check($migration['prepared'], 'Additive migration accepted');
|
||||
$check(Schema::migrate($db, hash_file('sha256', $work.'/before.dump'), 'Isolated replay')['replayed'], 'Migration replay is stable');
|
||||
$old = json_decode(file_get_contents($host.'/packages/internal-requisitions/manifest.json'), true);
|
||||
$next = json_decode(file_get_contents($candidate['directory'].'/manifest.json'), true);
|
||||
$current = json_decode(file_get_contents($host.'/storage/app/private/module-deployments/current.json'), true);
|
||||
try {
|
||||
$deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
|
||||
throw new RuntimeException('Unprepared plan accepted');
|
||||
} catch (RuntimeException $e) {
|
||||
$check(str_contains($e->getMessage(), 'migração própria'), 'Schema-changing update refuses missing migration receipt');
|
||||
}
|
||||
$receipt = ['from_manifest_sha256' => $current['manifest_sha256'], 'to_manifest_sha256' => $candidate['archive']['manifest_sha256'], 'host' => $host, 'schema_verified' => Schema::compatible($db), 'changes' => []];
|
||||
foreach ($next['support_files'] as $file => $hash) {
|
||||
if (($old['support_files'][$file] ?? null) !== $hash) {
|
||||
$receipt['changes'][$file] = ['before' => $old['support_files'][$file] ?? null, 'after' => $hash];
|
||||
}
|
||||
}
|
||||
file_put_contents($host.'/storage/framework/down', '{}');
|
||||
$cli = new Process([PHP_BINARY, $candidate['directory'].'/scripts/sgf-sourcing-install.php', 'migrate', $host, Installation::target($db), $work.'/before.dump', hash_file('sha256', $work.'/before.dump'), 'Isolated migration CLI', $candidate['archive']['manifest_sha256']], $host, ['PG_RESTORE_BINARY' => 'C:/Program Files/PostgreSQL/17/bin/pg_restore.exe']);
|
||||
$cli->mustRun();
|
||||
$cliResult = json_decode($cli->getOutput(), true, 32, JSON_THROW_ON_ERROR);
|
||||
$check($cliResult['prepared'] && ! $cliResult['activated'] && ! $cliResult['rights_granted'], 'Packaged migration CLI produces exact receipt without activation or grants');
|
||||
$plan = $deploy->plan($candidate['directory'], $candidate['archive']['manifest_sha256']);
|
||||
$applied = $deploy->apply($candidate['directory'], $candidate['archive']['manifest_sha256'], $plan['target_sha256'], 'Isolated sourcing update', true);
|
||||
unlink($host.'/storage/framework/down');
|
||||
file_put_contents($work.'/applied.json', json_encode($applied));
|
||||
$target = Installation::target($db);
|
||||
file_put_contents($host.'/config/purchasing-operational.php', '<?php return '.var_export(['enabled' => true, 'target' => $target, 'scopes' => ['1:1:1']], true).';');
|
||||
file_put_contents($host.'/config/purchasing-sourcing.php', '<?php return ["enabled"=>true];');
|
||||
$private = json_decode(file_get_contents('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json'), true);
|
||||
$user = User::forceCreate(['name' => 'Synthetic isolated evaluator', 'email' => 'fixture-'.Str::uuid().'@example.invalid', 'password' => $private['password'], 'auth_version' => 1]);
|
||||
$db->table('company_memberships')->insert(['user_id' => $user->id, 'tenant_id' => 1, 'company_id' => 1]);
|
||||
$departmentPolicy = $db->table('ir_policies')->where(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1])->first();
|
||||
$departmentPayload = json_decode($departmentPolicy->payload, true);
|
||||
$departmentPayload['members'][] = ['user_id' => $user->id, 'department_ref' => 'OPER'];
|
||||
$db->table('ir_policies')->where('id', $departmentPolicy->id)->update(['payload' => json_encode($departmentPayload)]); // Disposable configuration fixture only; submitted request snapshot is unchanged.
|
||||
$grants = [1 => ['purchasing_sourcing.prepare'], 2 => ['purchasing_sourcing.evaluate', 'purchasing_sourcing.propose'], $user->id => ['company.view', 'unit.view', 'purchasing_requisitions.view', 'purchasing_sourcing.evaluate', 'purchasing_sourcing.confirm']];
|
||||
foreach ($grants as $id => $rights) {
|
||||
foreach ($rights as $right) {
|
||||
$db->table('permission_grants')->insert(['user_id' => $id, 'tenant_id' => 1, 'company_id' => 1, 'unit_id' => $right === 'company.view' ? null : 1, 'permission' => $right, 'created_at' => now(), 'updated_at' => now()]);
|
||||
}
|
||||
}
|
||||
foreach ([1, 2, 3] as $n) {
|
||||
$db->table('ss_suppliers')->insert(['tenant_id' => 1, 'company_id' => 1, 'unit_id' => 1, 'reference' => 'SYNTHETIC-'.$n, 'payload' => json_encode(['name' => 'Fornecedor sintético '.$n, 'active' => true, 'blocked' => false, 'review_until' => '2027-12-31', 'version' => 1, 'synthetic_only' => true]), 'created_at' => now()]);
|
||||
}
|
||||
file_put_contents($work.'/fixture.json', json_encode(['user_id' => $user->id, 'email' => $user->email, 'password' => $private['password']]));
|
||||
echo json_encode(['passed' => true, 'checks' => $checks, 'fixture_user_only_in_disposable_copy' => true, 'deployment' => $applied]);
|
||||
} elseif (($argv[1] ?? '') === 'verify') {
|
||||
$baseline = json_decode(file_get_contents($work.'/origin.json'), true);
|
||||
foreach (['request' => 'ir_requests', 'budget' => 'cb_budget_entries', 'consumption' => 'cb_budget_consumptions'] as $key => $table) {
|
||||
$check($baseline[$key] === $fingerprint($table), 'Origin '.$key.' unchanged');
|
||||
}
|
||||
$check($db->table('ss_processes')->count() === 1, 'Exactly one sourcing process');
|
||||
$check($db->table('ss_commands')->count() === $db->table('ss_events')->count(), 'One event per committed command');
|
||||
$saved = $db->table('ss_processes')->first();
|
||||
$state = json_decode($saved->payload, true);
|
||||
$check($state['confirmed'] !== null, 'Independent award confirmed in isolated copy');
|
||||
$before = $fingerprint('ss_events');
|
||||
$failed = false;
|
||||
try {
|
||||
$db->transaction(fn () => $db->table('ss_events')->where('id', 1)->update(['action' => 'tampered']));
|
||||
} catch (Throwable) {
|
||||
$failed = true;
|
||||
}$check($failed && $before === $fingerprint('ss_events'), 'Database rejects event tampering');
|
||||
$applied = json_decode(file_get_contents($work.'/applied.json'), true);
|
||||
file_put_contents($host.'/storage/framework/down', '{}');
|
||||
$rolled = $deploy->rollback($applied['deployment_id'], 'Isolated sourcing code recovery', true);
|
||||
$check($state === json_decode($db->table('ss_processes')->first()->payload, true), 'Code rollback preserves award data');
|
||||
echo json_encode(['passed' => true, 'checks' => $checks, 'code_recovery' => $rolled, 'old_code_requires_schema_recovery' => true]);
|
||||
} else {
|
||||
throw new RuntimeException('Use setup/verify');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
fwrite(STDERR,get_class($e).': '.$e->getMessage()."\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
@@ -1,55 +1,335 @@
|
||||
import fs from 'node:fs';import assert from 'node:assert/strict';import crypto from 'node:crypto';import {spawn,spawnSync} from 'node:child_process';
|
||||
const repo=process.env.SOURCING_REPO,work=process.env.SOURCING_WORK,host=process.env.SOURCING_CLONE,base='http://127.0.0.1:'+process.env.SOURCING_PORT,php='C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
const repo = process.env.SOURCING_REPO,
|
||||
work = process.env.SOURCING_WORK,
|
||||
host = process.env.SOURCING_CLONE,
|
||||
base = 'http://127.0.0.1:' + process.env.SOURCING_PORT,
|
||||
php = 'C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe';
|
||||
assert(/^sgf_sourcing_test_[a-f0-9]{12}$/.test(process.env.SOURCING_DB));
|
||||
const privateData=JSON.parse(fs.readFileSync('C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json','utf8')),fixture=JSON.parse(fs.readFileSync(work+'/fixture.json','utf8'));
|
||||
const clients={},checks=[];
|
||||
for(const p of [...privateData.profiles,{role:'decisor',email:fixture.email}]){
|
||||
const jar=new Map();let csrf='',token='';
|
||||
const api=async(path,method='GET',body,status=200,override={})=>{
|
||||
const r=await fetch(base+path,{method,headers:{Accept:'application/json','Content-Type':'application/json',Cookie:[...jar].map(([k,v])=>k+'='+v).join('; '),'X-CSRF-TOKEN':csrf,'X-SGF-Context':token,'X-Purchasing-Context':'procurement.internal',...override},...(body===undefined?{}:{body:JSON.stringify(body)})});
|
||||
for(const cookie of r.headers.getSetCookie()){const pair=cookie.split(';')[0],at=pair.indexOf('=');jar.set(pair.slice(0,at),pair.slice(at+1));}const text=await r.text();let d;try{d=JSON.parse(text);}catch{d={message:text.slice(0,120)};}
|
||||
assert.equal(r.status,status,`${p.role} ${path}: ${d.message??JSON.stringify(d.errors)}`);if(d.csrf)csrf=d.csrf;if(d.context?.token)token=d.context.token;return d;
|
||||
};
|
||||
await api('/api/session');await api('/api/login','POST',{email:p.email,password:privateData.password});await api('/api/context','POST',{tenant_id:1,company_id:1,unit_id:1,module_id:'purchasing'});clients[p.role]=api;
|
||||
const privateData = JSON.parse(
|
||||
fs.readFileSync(
|
||||
'C:/laragon/data/sgf-tempo/run/modular-regression-2576427d1939/private/development.json',
|
||||
'utf8',
|
||||
),
|
||||
),
|
||||
fixture = JSON.parse(fs.readFileSync(work + '/fixture.json', 'utf8'));
|
||||
const clients = {},
|
||||
checks = [];
|
||||
for (const p of [
|
||||
...privateData.profiles,
|
||||
{ role: 'decisor', email: fixture.email },
|
||||
]) {
|
||||
const jar = new Map();
|
||||
let csrf = '',
|
||||
token = '';
|
||||
const api = async (
|
||||
path,
|
||||
method = 'GET',
|
||||
body,
|
||||
status = 200,
|
||||
override = {},
|
||||
) => {
|
||||
const r = await fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
Cookie: [...jar].map(([k, v]) => k + '=' + v).join('; '),
|
||||
'X-CSRF-TOKEN': csrf,
|
||||
'X-SGF-Context': token,
|
||||
'X-Purchasing-Context': 'procurement.internal',
|
||||
...override,
|
||||
},
|
||||
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
||||
});
|
||||
for (const cookie of r.headers.getSetCookie()) {
|
||||
const pair = cookie.split(';')[0],
|
||||
at = pair.indexOf('=');
|
||||
jar.set(pair.slice(0, at), pair.slice(at + 1));
|
||||
}
|
||||
const text = await r.text();
|
||||
let d;
|
||||
try {
|
||||
d = JSON.parse(text);
|
||||
} catch {
|
||||
d = { message: text.slice(0, 120) };
|
||||
}
|
||||
assert.equal(
|
||||
r.status,
|
||||
status,
|
||||
`${p.role} ${path}: ${d.message ?? JSON.stringify(d.errors)}`,
|
||||
);
|
||||
if (d.csrf) csrf = d.csrf;
|
||||
if (d.context?.token) token = d.context.token;
|
||||
return d;
|
||||
};
|
||||
await api('/api/session');
|
||||
await api('/api/login', 'POST', {
|
||||
email: p.email,
|
||||
password: privateData.password,
|
||||
});
|
||||
await api('/api/context', 'POST', {
|
||||
tenant_id: 1,
|
||||
company_id: 1,
|
||||
unit_id: 1,
|
||||
module_id: 'purchasing',
|
||||
});
|
||||
clients[p.role] = api;
|
||||
}
|
||||
const read=who=>clients[who]('/api/sourcing/1');
|
||||
async function command(who,action,data,status=200){const current=await read(who);const payload={operation_key:crypto.randomUUID(),version:current.state.version,...(action==='propose'?{delivery_date:'2027-01-15',delivery_location:'Local de entrega exclusivamente sintético OPER'}:{}),...data};return {result:await clients[who]('/api/sourcing/1/'+action,'POST',payload,status),payload};}
|
||||
const prep='preparador',rev='revisor',dec='decisor',consult='consulta';
|
||||
for(const id of [1,2,3])await command(prep,'select',{supplier_id:id});
|
||||
const quote=(id,price='100.00',days=5)=>({supplier_id:id,reference:'SYNTHETIC-Q-'+id,currency:'MZN',valid_until:'2027-12-31',delivery_days:days,payment_terms:'Pagamento sintético a 30 dias',items:[{line:0,unit_price:price}]});
|
||||
for(const [id,amount] of [[1,'100.00'],[2,'110.00'],[3,'120.00']])await command(prep,'quote',{...quote(id,amount),delivery_days:'5',supplier_id:String(id)});
|
||||
const qSaved=await read(prep);assert.equal(qSaved.request.id,1);assert.equal(qSaved.request.total_minor,10000);assert(!qSaved.comparison.ready);
|
||||
for(const action of ['select','quote','evaluate','propose','confirm'])await clients[consult]('/api/sourcing/1/'+action,'POST',{},403);
|
||||
await clients[consult]('/api/sourcing/1','GET',undefined,409,{'X-SGF-Context':'bad'});await clients[consult]('/api/sourcing/1','GET',undefined,403,{'X-Purchasing-Context':'procurement.third_party'});await clients[consult]('/api/sourcing/9999999','GET',undefined,404);
|
||||
checks.push('Source request reused; three suppliers and quotes; consultation is read-only; context and direct access protected');
|
||||
const evalData=async(id,who)=>{const s=await read(who);return {supplier_id:id,quote_revision:s.state.quotes[id].revision,quality:8,history:8,payment:8,no_conflict:true,reason:'Synthetic independent evaluation for isolated test.'};};
|
||||
const read = (who) => clients[who]('/api/sourcing/1');
|
||||
async function command(who, action, data, status = 200) {
|
||||
const current = await read(who);
|
||||
const payload = {
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: current.state.version,
|
||||
...(action === 'propose'
|
||||
? {
|
||||
delivery_date: '2027-01-15',
|
||||
delivery_location:
|
||||
'Local de entrega exclusivamente sintético OPER',
|
||||
}
|
||||
: {}),
|
||||
...data,
|
||||
};
|
||||
return {
|
||||
result: await clients[who](
|
||||
'/api/sourcing/1/' + action,
|
||||
'POST',
|
||||
payload,
|
||||
status,
|
||||
),
|
||||
payload,
|
||||
};
|
||||
}
|
||||
const prep = 'preparador',
|
||||
rev = 'revisor',
|
||||
dec = 'decisor',
|
||||
consult = 'consulta';
|
||||
for (const id of [1, 2, 3]) await command(prep, 'select', { supplier_id: id });
|
||||
const quote = (id, price = '100.00', days = 5) => ({
|
||||
supplier_id: id,
|
||||
reference: 'SYNTHETIC-Q-' + id,
|
||||
currency: 'MZN',
|
||||
valid_until: '2027-12-31',
|
||||
delivery_days: days,
|
||||
payment_terms: 'Pagamento sintético a 30 dias',
|
||||
items: [{ line: 0, unit_price: price }],
|
||||
});
|
||||
for (const [id, amount] of [
|
||||
[1, '100.00'],
|
||||
[2, '110.00'],
|
||||
[3, '120.00'],
|
||||
])
|
||||
await command(prep, 'quote', {
|
||||
...quote(id, amount),
|
||||
delivery_days: '5',
|
||||
supplier_id: String(id),
|
||||
});
|
||||
const qSaved = await read(prep);
|
||||
assert.equal(qSaved.request.id, 1);
|
||||
assert.equal(qSaved.request.total_minor, 10000);
|
||||
assert(!qSaved.comparison.ready);
|
||||
for (const action of ['select', 'quote', 'evaluate', 'propose', 'confirm'])
|
||||
await clients[consult]('/api/sourcing/1/' + action, 'POST', {}, 403);
|
||||
await clients[consult]('/api/sourcing/1', 'GET', undefined, 409, {
|
||||
'X-SGF-Context': 'bad',
|
||||
});
|
||||
await clients[consult]('/api/sourcing/1', 'GET', undefined, 403, {
|
||||
'X-Purchasing-Context': 'procurement.third_party',
|
||||
});
|
||||
await clients[consult]('/api/sourcing/9999999', 'GET', undefined, 404);
|
||||
checks.push(
|
||||
'Source request reused; three suppliers and quotes; consultation is read-only; context and direct access protected',
|
||||
);
|
||||
const evalData = async (id, who) => {
|
||||
const s = await read(who);
|
||||
return {
|
||||
supplier_id: id,
|
||||
quote_revision: s.state.quotes[id].revision,
|
||||
quality: 8,
|
||||
history: 8,
|
||||
payment: 8,
|
||||
no_conflict: true,
|
||||
reason: 'Synthetic independent evaluation for isolated test.',
|
||||
};
|
||||
};
|
||||
// Real concurrent database sessions, not just serial requests to PHP's development server.
|
||||
const initial=await read(rev),workerInput={actor_id:2,payload:{operation_key:crypto.randomUUID(),version:initial.state.version,...await evalData(1,rev)}};fs.writeFileSync(work+'/worker.json',JSON.stringify(workerInput));
|
||||
const worker=(file='worker.json')=>new Promise((resolve,reject)=>{const p=spawn(php,[repo+'/tests/Support/sgf-sourcing-worker.php',work+'/'+file],{cwd:host,env:process.env,windowsHide:true});let out='',err='';p.stdout.on('data',d=>out+=d);p.stderr.on('data',d=>err+=d);p.on('exit',code=>{try{if(code!==0)throw Error(err);resolve(JSON.parse(out));}catch(e){reject(e);}});});
|
||||
const workers=await Promise.all([worker(),worker()]);assert(workers.every(w=>w.status===200),JSON.stringify(workers));assert.deepEqual(workers[0].result,workers[1].result);checks.push('Concurrent identical commands return one committed version');
|
||||
const raceVersion=(await read(rev)).state.version;
|
||||
for(const [file,id] of [['race-a.json',2],['race-b.json',3]])fs.writeFileSync(work+'/'+file,JSON.stringify({actor_id:2,payload:{operation_key:crypto.randomUUID(),version:raceVersion,...await evalData(id,rev)}}));
|
||||
const racing=await Promise.all([worker('race-a.json'),worker('race-b.json')]);assert.deepEqual(racing.map(r=>r.status).sort(),[200,409]);checks.push('Concurrent distinct commands use compare-and-swap; stale version refused');
|
||||
for(const id of [1,2,3]){if(id!==1)await command(rev,'evaluate',await evalData(id,rev));await command(dec,'evaluate',await evalData(id,dec));}
|
||||
let ready=await read(rev);assert(ready.comparison.ready);assert.deepEqual(ready.comparison.top_ids,[1]);
|
||||
const proposed=await command(rev,'propose',{supplier_id:1,comparison_hash:ready.comparison.fingerprint,reason:'Best eligible synthetic quote with exact comparison version.'});
|
||||
await clients[rev]('/api/sourcing/1/propose','POST',proposed.payload);checks.push('Proposal retry is idempotent');
|
||||
const confirmData=async()=>{const d=await read(dec);return {proposal_index:d.state.proposals.length-1,comparison_hash:d.state.proposals.at(-1).comparison_hash,reason:'Independent confirmation of the preserved comparison.'};};
|
||||
const initial = await read(rev),
|
||||
workerInput = {
|
||||
actor_id: 2,
|
||||
payload: {
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: initial.state.version,
|
||||
...(await evalData(1, rev)),
|
||||
},
|
||||
};
|
||||
fs.writeFileSync(work + '/worker.json', JSON.stringify(workerInput));
|
||||
const worker = (file = 'worker.json') =>
|
||||
new Promise((resolve, reject) => {
|
||||
const p = spawn(
|
||||
php,
|
||||
[
|
||||
repo + '/tests/Support/sgf-sourcing-worker.php',
|
||||
work + '/' + file,
|
||||
],
|
||||
{ cwd: host, env: process.env, windowsHide: true },
|
||||
);
|
||||
let out = '',
|
||||
err = '';
|
||||
p.stdout.on('data', (d) => (out += d));
|
||||
p.stderr.on('data', (d) => (err += d));
|
||||
p.on('exit', (code) => {
|
||||
try {
|
||||
if (code !== 0) throw Error(err);
|
||||
resolve(JSON.parse(out));
|
||||
} catch (e) {
|
||||
reject(e);
|
||||
}
|
||||
});
|
||||
});
|
||||
const workers = await Promise.all([worker(), worker()]);
|
||||
assert(
|
||||
workers.every((w) => w.status === 200),
|
||||
JSON.stringify(workers),
|
||||
);
|
||||
assert.deepEqual(workers[0].result, workers[1].result);
|
||||
checks.push('Concurrent identical commands return one committed version');
|
||||
const raceVersion = (await read(rev)).state.version;
|
||||
for (const [file, id] of [
|
||||
['race-a.json', 2],
|
||||
['race-b.json', 3],
|
||||
])
|
||||
fs.writeFileSync(
|
||||
work + '/' + file,
|
||||
JSON.stringify({
|
||||
actor_id: 2,
|
||||
payload: {
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: raceVersion,
|
||||
...(await evalData(id, rev)),
|
||||
},
|
||||
}),
|
||||
);
|
||||
const racing = await Promise.all([
|
||||
worker('race-a.json'),
|
||||
worker('race-b.json'),
|
||||
]);
|
||||
assert.deepEqual(racing.map((r) => r.status).sort(), [200, 409]);
|
||||
checks.push(
|
||||
'Concurrent distinct commands use compare-and-swap; stale version refused',
|
||||
);
|
||||
for (const id of [1, 2, 3]) {
|
||||
if (id !== 1) await command(rev, 'evaluate', await evalData(id, rev));
|
||||
await command(dec, 'evaluate', await evalData(id, dec));
|
||||
}
|
||||
let ready = await read(rev);
|
||||
assert(ready.comparison.ready);
|
||||
assert.deepEqual(ready.comparison.top_ids, [1]);
|
||||
const proposed = await command(rev, 'propose', {
|
||||
supplier_id: 1,
|
||||
comparison_hash: ready.comparison.fingerprint,
|
||||
reason: 'Best eligible synthetic quote with exact comparison version.',
|
||||
});
|
||||
await clients[rev]('/api/sourcing/1/propose', 'POST', proposed.payload);
|
||||
checks.push('Proposal retry is idempotent');
|
||||
const confirmData = async () => {
|
||||
const d = await read(dec);
|
||||
return {
|
||||
proposal_index: d.state.proposals.length - 1,
|
||||
comparison_hash: d.state.proposals.at(-1).comparison_hash,
|
||||
reason: 'Independent confirmation of the preserved comparison.',
|
||||
};
|
||||
};
|
||||
// The proposer does not possess confirm; independence is also tested in the shared core.
|
||||
await command(rev,'confirm',await confirmData(),403);
|
||||
await command(prep,'quote',quote(1,'100.00',6));await command(dec,'confirm',await confirmData(),409);checks.push('Changed quote blocks stale confirmation and invalidates evaluations');
|
||||
function control(name){const r=spawnSync(php,[repo+'/tests/Support/sgf-sourcing-controls.php',name],{cwd:host,env:process.env,encoding:'utf8',windowsHide:true});assert.equal(r.status,0,r.stderr);}
|
||||
for(const who of [rev,dec])await command(who,'evaluate',await evalData(1,who));
|
||||
ready=await read(rev);await command(rev,'propose',{supplier_id:1,comparison_hash:ready.comparison.fingerprint,reason:'Re-proposed using current quote revision and comparison.'});
|
||||
control('revoke-evaluate');await command(dec,'confirm',await confirmData(),409);control('restore-evaluate');
|
||||
control('revoke-propose');await clients[rev]('/api/sourcing/1/propose','POST',proposed.payload,403);control('restore-propose');
|
||||
control('revoke-view');await clients[consult]('/api/sourcing/1','GET',undefined,403);control('restore-view');checks.push('Revocation is effective for existing sessions, replay and qualified evaluations');
|
||||
const beforeFail=await read(prep);control('fail-on');await command(prep,'quote',quote(2,'110.00',7),500);control('fail-off');const afterFail=await read(prep);assert.equal(afterFail.state.version,beforeFail.state.version);assert.equal(afterFail.history.length,beforeFail.history.length);checks.push('Injected failure after event rolls back state, event and receipt');
|
||||
const confirmVersion=(await read(dec)).state.version,confirmation=await confirmData();
|
||||
for(const file of ['confirm-a.json','confirm-b.json'])fs.writeFileSync(work+'/'+file,JSON.stringify({actor_id:fixture.user_id,action:'confirm',payload:{operation_key:crypto.randomUUID(),version:confirmVersion,...confirmation}}));
|
||||
const confirmations=await Promise.all([worker('confirm-a.json'),worker('confirm-b.json')]);assert.deepEqual(confirmations.map(r=>r.status).sort(),[200,409]);
|
||||
const confirmed=await read(consult);assert(confirmed.state.confirmed);assert.equal(confirmed.state.confirmed.confirmed_by,fixture.user_id);assert.equal(confirmed.state.confirmed.proposal.proposed_by,2);checks.push('Concurrent confirmations produce one immutable independent award');
|
||||
await command(prep,'quote',quote(1),409);checks.push('Independent confirmation references exact comparison and final state is immutable');
|
||||
const origin=await clients[consult]('/api/internal-requisitions/1');assert.equal(origin.record.version,3);assert.equal(origin.record.total_minor,10000);assert.equal(origin.history.length,3);checks.push('Accepted requisition read path remains intact');
|
||||
await clients[consult]('/purchasing/sourcing/1');await clients[consult]('/purchasing/sourcing/screen.mjs');checks.push('Authenticated read-only screen and module script served through protected routes');
|
||||
console.log(JSON.stringify({passed:true,checks,request_id:1,confirmed_only_in_isolated_copy:true,account_fixture_only_in_copy:true}));
|
||||
await command(rev, 'confirm', await confirmData(), 403);
|
||||
await command(prep, 'quote', quote(1, '100.00', 6));
|
||||
await command(dec, 'confirm', await confirmData(), 409);
|
||||
checks.push(
|
||||
'Changed quote blocks stale confirmation and invalidates evaluations',
|
||||
);
|
||||
function control(name) {
|
||||
const r = spawnSync(
|
||||
php,
|
||||
[repo + '/tests/Support/sgf-sourcing-controls.php', name],
|
||||
{ cwd: host, env: process.env, encoding: 'utf8', windowsHide: true },
|
||||
);
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
}
|
||||
for (const who of [rev, dec])
|
||||
await command(who, 'evaluate', await evalData(1, who));
|
||||
ready = await read(rev);
|
||||
await command(rev, 'propose', {
|
||||
supplier_id: 1,
|
||||
comparison_hash: ready.comparison.fingerprint,
|
||||
reason: 'Re-proposed using current quote revision and comparison.',
|
||||
});
|
||||
control('revoke-evaluate');
|
||||
await command(dec, 'confirm', await confirmData(), 409);
|
||||
control('restore-evaluate');
|
||||
control('revoke-propose');
|
||||
await clients[rev]('/api/sourcing/1/propose', 'POST', proposed.payload, 403);
|
||||
control('restore-propose');
|
||||
control('revoke-view');
|
||||
await clients[consult]('/api/sourcing/1', 'GET', undefined, 403);
|
||||
control('restore-view');
|
||||
checks.push(
|
||||
'Revocation is effective for existing sessions, replay and qualified evaluations',
|
||||
);
|
||||
const beforeFail = await read(prep);
|
||||
control('fail-on');
|
||||
await command(prep, 'quote', quote(2, '110.00', 7), 500);
|
||||
control('fail-off');
|
||||
const afterFail = await read(prep);
|
||||
assert.equal(afterFail.state.version, beforeFail.state.version);
|
||||
assert.equal(afterFail.history.length, beforeFail.history.length);
|
||||
checks.push('Injected failure after event rolls back state, event and receipt');
|
||||
const confirmVersion = (await read(dec)).state.version,
|
||||
confirmation = await confirmData();
|
||||
for (const file of ['confirm-a.json', 'confirm-b.json'])
|
||||
fs.writeFileSync(
|
||||
work + '/' + file,
|
||||
JSON.stringify({
|
||||
actor_id: fixture.user_id,
|
||||
action: 'confirm',
|
||||
payload: {
|
||||
operation_key: crypto.randomUUID(),
|
||||
version: confirmVersion,
|
||||
...confirmation,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const confirmations = await Promise.all([
|
||||
worker('confirm-a.json'),
|
||||
worker('confirm-b.json'),
|
||||
]);
|
||||
assert.deepEqual(confirmations.map((r) => r.status).sort(), [200, 409]);
|
||||
const confirmed = await read(consult);
|
||||
assert(confirmed.state.confirmed);
|
||||
assert.equal(confirmed.state.confirmed.confirmed_by, fixture.user_id);
|
||||
assert.equal(confirmed.state.confirmed.proposal.proposed_by, 2);
|
||||
checks.push('Concurrent confirmations produce one immutable independent award');
|
||||
await command(prep, 'quote', quote(1), 409);
|
||||
checks.push(
|
||||
'Independent confirmation references exact comparison and final state is immutable',
|
||||
);
|
||||
const origin = await clients[consult]('/api/internal-requisitions/1');
|
||||
assert.equal(origin.record.version, 3);
|
||||
assert.equal(origin.record.total_minor, 10000);
|
||||
assert.equal(origin.history.length, 3);
|
||||
checks.push('Accepted requisition read path remains intact');
|
||||
await clients[consult]('/purchasing/sourcing/1');
|
||||
await clients[consult]('/purchasing/sourcing/screen.mjs');
|
||||
checks.push(
|
||||
'Authenticated read-only screen and module script served through protected routes',
|
||||
);
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
passed: true,
|
||||
checks,
|
||||
request_id: 1,
|
||||
confirmed_only_in_isolated_copy: true,
|
||||
account_fixture_only_in_copy: true,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -1,15 +1,32 @@
|
||||
<?php
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Shared\Context\CompanyContext;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Http\Request;
|
||||
$host=getenv('SOURCING_CLONE');require $host.'/vendor/autoload.php';$app=require $host.'/bootstrap/app.php';$app->make(Kernel::class)->bootstrap();
|
||||
try{
|
||||
$db=DB::connection();if(!preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D',$db->getDatabaseName()))throw new RuntimeException('Copy only');
|
||||
$input=json_decode(file_get_contents($argv[1]),true,32,JSON_THROW_ON_ERROR);$user=User::findOrFail($input['actor_id']);
|
||||
auth()->setUser($user);app(CompanyContext::class)->selectFor($user->id,1,1,1);
|
||||
$request=Request::create('/api/sourcing/1/evaluate','POST');$request->headers->set('X-Purchasing-Context','procurement.internal');$app->instance('request',$request);
|
||||
$result=(new Tempo\Purchasing\SgfSourcing\Workspace($user))->command(1,$input['action']??'evaluate',$input['payload']);
|
||||
echo json_encode(['status'=>200,'result'=>$result]);
|
||||
}catch(Throwable $e){echo json_encode(['status'=>$e instanceof Symfony\Component\HttpKernel\Exception\HttpExceptionInterface?$e->getStatusCode():($e instanceof Tempo\Purchasing\Internal\RequisitionFailure?$e->status:500),'message'=>$e->getMessage()]);}
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Tempo\Purchasing\Internal\RequisitionFailure;
|
||||
use Tempo\Purchasing\SgfSourcing\Workspace;
|
||||
|
||||
$host = getenv('SOURCING_CLONE');
|
||||
require $host.'/vendor/autoload.php';
|
||||
$app = require $host.'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
try {
|
||||
$db = DB::connection();
|
||||
if (! preg_match('/^sgf_sourcing_test_[a-f0-9]{12}$/D', $db->getDatabaseName())) {
|
||||
throw new RuntimeException('Copy only');
|
||||
}
|
||||
$input = json_decode(file_get_contents($argv[1]), true, 32, JSON_THROW_ON_ERROR);
|
||||
$user = User::findOrFail($input['actor_id']);
|
||||
auth()->setUser($user);
|
||||
app(CompanyContext::class)->selectFor($user->id, 1, 1, 1);
|
||||
$request = Request::create('/api/sourcing/1/evaluate', 'POST');
|
||||
$request->headers->set('X-Purchasing-Context', 'procurement.internal');
|
||||
$app->instance('request', $request);
|
||||
$result = (new Workspace($user))->command(1, $input['action'] ?? 'evaluate', $input['payload']);
|
||||
echo json_encode(['status' => 200, 'result' => $result]);
|
||||
} catch (Throwable $e) {
|
||||
echo json_encode(['status' => $e instanceof HttpExceptionInterface ? $e->getStatusCode() : ($e instanceof RequisitionFailure ? $e->status : 500), 'message' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
@@ -37,7 +37,9 @@ function updateFixture(string $original, array $manifest, bool $native = false):
|
||||
}
|
||||
copy($original.'/composer.json', $root.'/composer.json');
|
||||
copy($original.'/artisan', $root.'/artisan');
|
||||
if (!is_dir($root.'/public')) mkdir($root.'/public', 0700, true);
|
||||
if (! is_dir($root.'/public')) {
|
||||
mkdir($root.'/public', 0700, true);
|
||||
}
|
||||
copy($original.'/public/index.php', $root.'/public/index.php');
|
||||
} else {
|
||||
foreach ($manifest['host_overlays'] as $file => $values) {
|
||||
@@ -49,9 +51,11 @@ function updateFixture(string $original, array $manifest, bool $native = false):
|
||||
// Frontend overlays are existing host files too; preserve their exact baseline
|
||||
// in native copies without sharing mutable assets with the real destination.
|
||||
foreach ($manifest['host_overlays'] as $file => $values) {
|
||||
if (!is_file($root.'/'.$file)) {
|
||||
if (!is_dir(dirname($root.'/'.$file))) mkdir(dirname($root.'/'.$file),0700,true);
|
||||
copy($original.'/'.$file,$root.'/'.$file);
|
||||
if (! is_file($root.'/'.$file)) {
|
||||
if (! is_dir(dirname($root.'/'.$file))) {
|
||||
mkdir(dirname($root.'/'.$file), 0700, true);
|
||||
}
|
||||
copy($original.'/'.$file, $root.'/'.$file);
|
||||
}
|
||||
}
|
||||
foreach (['bootstrap/cache', 'packages/purchasing', 'storage/framework/views', 'storage/framework/cache', 'storage/framework/sessions', 'storage/logs'] as $directory) {
|
||||
@@ -59,8 +63,8 @@ function updateFixture(string $original, array $manifest, bool $native = false):
|
||||
mkdir($root.'/'.$directory, 0700, true);
|
||||
}
|
||||
}
|
||||
copy($original.'/packages/purchasing/current.json',$root.'/packages/purchasing/current.json');
|
||||
file_put_contents($root.'/storage/framework/down','{"status":503}');
|
||||
copy($original.'/packages/purchasing/current.json', $root.'/packages/purchasing/current.json');
|
||||
file_put_contents($root.'/storage/framework/down', '{"status":503}');
|
||||
|
||||
return $root;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,49 @@
|
||||
<?php
|
||||
$file=realpath($argv[1]??'');$root=realpath((string)getenv('STOCK_RECEIPT_ROOT'));if(!$file||!$root||!str_starts_with($file,$root.DIRECTORY_SEPARATOR))throw new RuntimeException('Wrong native return worker input');
|
||||
require getcwd().'/vendor/autoload.php';$app=require getcwd().'/bootstrap/app.php';$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();
|
||||
$db=Illuminate\Support\Facades\DB::connection();$i=$db->selectOne("SELECT current_database() AS db,current_user AS role,current_setting('cluster_name') AS cluster,inet_server_port() AS port");
|
||||
if(!preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D',$i->db,$m)||$i->role!=='stock_receipt_qa_'.$m[1]||(int)$i->port!==55439||$i->cluster!=='sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN'))throw new RuntimeException('Wrong worker QA database');
|
||||
$p=json_decode(file_get_contents($file),true,512,JSON_THROW_ON_ERROR);$db->select("SELECT set_config('application_name',?,false)",[$p['application']]);$db->statement("SET lock_timeout='8s'");
|
||||
$actor=App\Models\User::findOrFail($p['actor']);auth()->guard()->setUser($actor);config(['stock_returns.enabled'=>true]);
|
||||
$action=$p['action']??'confirm';if(!in_array($action,['confirm','withdraw','reject'],true))throw new RuntimeException('Invalid worker action');
|
||||
$input=['version'=>1,'reason'=>'Synthetic concurrent native warehouse decision.']+($action==='confirm'?['received_in_warehouse'=>true]:[]);
|
||||
try{if($p['http']??false){$request=Illuminate\Http\Request::create('/api/stock-returns/'.$p['proposal'].'/'.$action,'POST',$input,[],[],['HTTP_ACCEPT'=>'application/json','HTTP_X_REQUESTED_WITH'=>'XMLHttpRequest']);$kernel=$app->make(Illuminate\Contracts\Http\Kernel::class);$response=$kernel->handle($request);$out=['status'=>$response->getStatusCode(),'result'=>json_decode($response->getContent(),true)];$kernel->terminate($request,$response);}else{$flow=app(App\Services\WarehouseReturns::class);$result=$action==='confirm'?$flow->confirm($actor,$p['proposal'],$input):$flow->close($actor,$p['proposal'],$input,$action==='withdraw'?'withdrawn':'rejected');$out=['status'=>200,'result'=>$result];}}catch(Symfony\Component\HttpKernel\Exception\HttpExceptionInterface $e){$out=['status'=>$e->getStatusCode()];}
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\WarehouseReturns;
|
||||
use Illuminate\Contracts\Console\Kernel;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
$file = realpath($argv[1] ?? '');
|
||||
$root = realpath((string) getenv('STOCK_RECEIPT_ROOT'));
|
||||
if (! $file || ! $root || ! str_starts_with($file, $root.DIRECTORY_SEPARATOR)) {
|
||||
throw new RuntimeException('Wrong native return worker input');
|
||||
}
|
||||
require getcwd().'/vendor/autoload.php';
|
||||
$app = require getcwd().'/bootstrap/app.php';
|
||||
$app->make(Kernel::class)->bootstrap();
|
||||
$db = DB::connection();
|
||||
$i = $db->selectOne("SELECT current_database() AS db,current_user AS role,current_setting('cluster_name') AS cluster,inet_server_port() AS port");
|
||||
if (! preg_match('/^compras_receipts_test_([a-f0-9]{12})$/D', $i->db, $m) || $i->role !== 'stock_receipt_qa_'.$m[1] || (int) $i->port !== 55439 || $i->cluster !== 'sgf_modular_regression_'.getenv('SGF_ISOLATED_REGRESSION_RUN')) {
|
||||
throw new RuntimeException('Wrong worker QA database');
|
||||
}
|
||||
$p = json_decode(file_get_contents($file), true, 512, JSON_THROW_ON_ERROR);
|
||||
$db->select("SELECT set_config('application_name',?,false)", [$p['application']]);
|
||||
$db->statement("SET lock_timeout='8s'");
|
||||
$actor = User::findOrFail($p['actor']);
|
||||
auth()->guard()->setUser($actor);
|
||||
config(['stock_returns.enabled' => true]);
|
||||
$action = $p['action'] ?? 'confirm';
|
||||
if (! in_array($action, ['confirm', 'withdraw', 'reject'], true)) {
|
||||
throw new RuntimeException('Invalid worker action');
|
||||
}
|
||||
$input = ['version' => 1, 'reason' => 'Synthetic concurrent native warehouse decision.'] + ($action === 'confirm' ? ['received_in_warehouse' => true] : []);
|
||||
try {
|
||||
if ($p['http'] ?? false) {
|
||||
$request = Request::create('/api/stock-returns/'.$p['proposal'].'/'.$action, 'POST', $input, [], [], ['HTTP_ACCEPT' => 'application/json', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest']);
|
||||
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
|
||||
$response = $kernel->handle($request);
|
||||
$out = ['status' => $response->getStatusCode(), 'result' => json_decode($response->getContent(), true)];
|
||||
$kernel->terminate($request, $response);
|
||||
} else {
|
||||
$flow = app(WarehouseReturns::class);
|
||||
$result = $action === 'confirm' ? $flow->confirm($actor, $p['proposal'], $input) : $flow->close($actor, $p['proposal'], $input, $action === 'withdraw' ? 'withdrawn' : 'rejected');
|
||||
$out = ['status' => 200, 'result' => $result];
|
||||
}
|
||||
} catch (HttpExceptionInterface $e) {
|
||||
$out = ['status' => $e->getStatusCode()];
|
||||
}
|
||||
file_put_contents($file.'.result',json_encode($out,JSON_THROW_ON_ERROR));
|
||||
|
||||
@@ -8,7 +8,15 @@ use Tempo\Finance\Budget\BudgetFailure;
|
||||
if (! class_exists(BudgetControl::class)) {
|
||||
require_once (getenv('COMMON_BUDGET_PATH') ?: __DIR__.'/../../packages/budget-control').'/bootstrap.php';
|
||||
}
|
||||
require_once 'C:/laragon/www/sgf-tempo/packages/budget-control/src/BudgetDistributionPlan.php';
|
||||
$distributionPlanSource = sgfTempoPath('packages/budget-control/src/BudgetDistributionPlan.php');
|
||||
if (! class_exists(BudgetDistributionPlan::class) && is_file($distributionPlanSource)) {
|
||||
require_once $distributionPlanSource;
|
||||
}
|
||||
beforeEach(function () {
|
||||
if (! class_exists(BudgetDistributionPlan::class)) {
|
||||
$this->markTestSkipped('BudgetDistributionPlan lives in the SGF common source; set SGF_TEMPO_ROOT to run it.');
|
||||
}
|
||||
});
|
||||
|
||||
function distributionPlanFixture(): array
|
||||
{
|
||||
|
||||
@@ -138,7 +138,6 @@ test('connection refusal is diagnosed without losing the last receiving checkpoi
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
test('oversized responses and timeouts stop the HTTP read without committing a page', function () {
|
||||
foreach ([warehouseRemote('oversized', maxBytes: 1024), warehouseRemote('slow', timeout: 200)] as $source) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { expect, test } from 'vitest';
|
||||
import {
|
||||
isModulePathDisabled,
|
||||
procurementNavigation,
|
||||
} from '@/lib/procurement-navigation';
|
||||
|
||||
const disabled = ['/pessoas', '/stock/requisicoes', '/compras/fornecimento'];
|
||||
|
||||
test('only paths served by disabled modules are hidden', () => {
|
||||
expect(isModulePathDisabled('/pessoas', disabled)).toBe(true);
|
||||
expect(isModulePathDisabled('/pessoas/relatorios', disabled)).toBe(true);
|
||||
expect(
|
||||
isModulePathDisabled('/compras/fornecimento?view=imports', disabled),
|
||||
).toBe(true);
|
||||
expect(isModulePathDisabled('/stock', disabled)).toBe(false);
|
||||
expect(isModulePathDisabled('/stock/operacoes', disabled)).toBe(false);
|
||||
expect(isModulePathDisabled('/pessoasx', disabled)).toBe(false);
|
||||
expect(isModulePathDisabled('/requisicoes', [])).toBe(false);
|
||||
});
|
||||
|
||||
test('navigation drops entries of disabled modules and keeps the core', () => {
|
||||
const paths = (hidden: string[]) =>
|
||||
procurementNavigation(
|
||||
['admin'],
|
||||
false,
|
||||
undefined,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
{},
|
||||
hidden,
|
||||
)
|
||||
.flatMap((group) => group.entries)
|
||||
.map((entry) => entry.path.split('?')[0]);
|
||||
|
||||
const all = paths([]);
|
||||
const core = paths(disabled);
|
||||
expect(all).toContain('/compras/fornecimento');
|
||||
expect(core).not.toContain('/compras/fornecimento');
|
||||
expect(core.some((path) => path.startsWith('/pessoas'))).toBe(false);
|
||||
expect(core).toContain('/requisicoes');
|
||||
expect(core).toContain('/stock');
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { App } from '@inertiajs/react';
|
||||
import type { Page } from '@inertiajs/core';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { renderToString } from 'react-dom/server';
|
||||
import { expect, test } from 'vitest';
|
||||
import Bank from '@/pages/suppliers/bank';
|
||||
@@ -23,7 +24,7 @@ const accounts = [
|
||||
},
|
||||
];
|
||||
function render(
|
||||
Component: typeof Bank | typeof Payments,
|
||||
Component: ComponentProps<typeof App>['initialComponent'],
|
||||
props: Record<string, unknown>,
|
||||
) {
|
||||
const page = {
|
||||
|
||||
@@ -7,35 +7,76 @@ import { spawnSync } from 'node:child_process';
|
||||
|
||||
const boundary = await fs.realpath('storage/framework/testing');
|
||||
const verifier = path.resolve('scripts/verify-compras-release.php');
|
||||
const hash = bytes => crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
const hash = (bytes) => crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
|
||||
async function fixture(run) {
|
||||
const root = await fs.mkdtemp(path.join(boundary, 'release-verifier-'));
|
||||
try {
|
||||
await fs.mkdir(path.join(root, 'public/build/assets'), { recursive: true });
|
||||
const source = '<?php exit(99); // verification must never execute product code';
|
||||
await fs.mkdir(path.join(root, 'public/build/assets'), {
|
||||
recursive: true,
|
||||
});
|
||||
const source =
|
||||
'<?php exit(99); // verification must never execute product code';
|
||||
await fs.writeFile(path.join(root, 'main.php'), source);
|
||||
await fs.writeFile(path.join(root, 'public/build/manifest.json'), '{}');
|
||||
await fs.writeFile(path.join(root, 'public/build/assets/a.js'), 'test');
|
||||
const manifest = { contract: 'compras.release.v1', product: 'compras', source_files: { 'main.php': hash(source) },
|
||||
frontend: { manifest_sha256: hash('{}'), files: { 'assets/a.js': hash('test') } }, components: [] };
|
||||
const manifest = {
|
||||
contract: 'compras.release.v1',
|
||||
product: 'compras',
|
||||
source_files: { 'main.php': hash(source) },
|
||||
frontend: {
|
||||
manifest_sha256: hash('{}'),
|
||||
files: { 'assets/a.js': hash('test') },
|
||||
},
|
||||
components: [],
|
||||
};
|
||||
for (const [index, list] of [true, false].entries()) {
|
||||
const component = path.join(root, 'component-'+index);
|
||||
const component = path.join(root, 'component-' + index);
|
||||
await fs.mkdir(component);
|
||||
await fs.writeFile(path.join(component, 'writer.php'), 'not executable');
|
||||
const files = list ? [{ file: 'writer.php', sha256: hash('not executable') }] : { 'writer.php': hash('not executable') };
|
||||
await fs.writeFile(
|
||||
path.join(component, 'writer.php'),
|
||||
'not executable',
|
||||
);
|
||||
const files = list
|
||||
? [{ file: 'writer.php', sha256: hash('not executable') }]
|
||||
: { 'writer.php': hash('not executable') };
|
||||
const bytes = JSON.stringify({ files });
|
||||
await fs.writeFile(path.join(component, 'manifest.json'), bytes);
|
||||
manifest.components.push({ setting: 'COMPONENT_'+index, manifest_sha256: hash(bytes) });
|
||||
manifest.components.push({
|
||||
setting: 'COMPONENT_' + index,
|
||||
manifest_sha256: hash(bytes),
|
||||
});
|
||||
}
|
||||
await fs.writeFile(path.join(root, '.env'), 'COMPRAS_RUNTIME_ENABLED="true"\n'+manifest.components.map((entry, index) => entry.setting+'="'+path.join(root, 'component-'+index).replaceAll('\\', '/')+'"').join('\n'));
|
||||
await fs.writeFile(
|
||||
path.join(root, '.env'),
|
||||
'COMPRAS_RUNTIME_ENABLED="true"\n' +
|
||||
manifest.components
|
||||
.map(
|
||||
(entry, index) =>
|
||||
entry.setting +
|
||||
'="' +
|
||||
path
|
||||
.join(root, 'component-' + index)
|
||||
.replaceAll('\\', '/') +
|
||||
'"',
|
||||
)
|
||||
.join('\n'),
|
||||
);
|
||||
const save = async () => {
|
||||
delete manifest.release_id;
|
||||
manifest.release_id = 'compras-'+hash(JSON.stringify(manifest)).slice(0, 16);
|
||||
await fs.writeFile(path.join(root, 'compras-release.json'), JSON.stringify(manifest));
|
||||
manifest.release_id =
|
||||
'compras-' + hash(JSON.stringify(manifest)).slice(0, 16);
|
||||
await fs.writeFile(
|
||||
path.join(root, 'compras-release.json'),
|
||||
JSON.stringify(manifest),
|
||||
);
|
||||
};
|
||||
await save();
|
||||
const verify = (...args) => spawnSync('php', [verifier, root, ...args], { encoding: 'utf8', windowsHide: true });
|
||||
const verify = (...args) =>
|
||||
spawnSync('php', [verifier, root, ...args], {
|
||||
encoding: 'utf8',
|
||||
windowsHide: true,
|
||||
});
|
||||
await run({ root, manifest, save, verify });
|
||||
} finally {
|
||||
const resolved = await fs.realpath(root);
|
||||
@@ -45,47 +86,68 @@ async function fixture(run) {
|
||||
}
|
||||
}
|
||||
|
||||
test('verifies one source, compiled assets and both component manifest formats without executing product code', () => fixture(async ({ verify }) => {
|
||||
const result = verify('--installed');
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(JSON.parse(result.stdout).installed_components, 2);
|
||||
}));
|
||||
test('rejects changed source', () => fixture(async ({ root, verify }) => {
|
||||
await fs.writeFile(path.join(root, 'main.php'), 'changed');
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
test('accepts Git LF and Windows CRLF as the same source without accepting changed text', () => fixture(async ({ root, manifest, save, verify }) => {
|
||||
manifest.source_eol = 'lf';
|
||||
manifest.source_files['main.php'] = hash('first\nsecond\n');
|
||||
await save();
|
||||
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nsecond\r\n');
|
||||
assert.equal(verify().status, 0);
|
||||
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nchanged\r\n');
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
test('rejects a changed compiled asset', () => fixture(async ({ root, verify }) => {
|
||||
await fs.writeFile(path.join(root, 'public/build/assets/a.js'), 'changed');
|
||||
assert.notEqual(verify('--compiled').status, 0);
|
||||
}));
|
||||
test('rejects a changed component', () => fixture(async ({ root, verify }) => {
|
||||
await fs.writeFile(path.join(root, 'component-1/writer.php'), 'changed');
|
||||
assert.notEqual(verify('--installed').status, 0);
|
||||
}));
|
||||
test('rejects forged identity', () => fixture(async ({ root, manifest, verify }) => {
|
||||
manifest.release_id = 'compras-forged';
|
||||
await fs.writeFile(path.join(root, 'compras-release.json'), JSON.stringify(manifest));
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
test('rejects path traversal even with a recomputed descriptor', () => fixture(async ({ manifest, save, verify }) => {
|
||||
manifest.source_files['../outside.php'] = hash('test');
|
||||
await save();
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
test('rejects disabled installation', () => fixture(async ({ root, verify }) => {
|
||||
await fs.writeFile(path.join(root, '.env'), 'COMPRAS_RUNTIME_ENABLED=false');
|
||||
assert.notEqual(verify('--installed').status, 0);
|
||||
}));
|
||||
test('rejects a missing descriptor', () => fixture(async ({ root, verify }) => {
|
||||
await fs.unlink(path.join(root, 'compras-release.json'));
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
test('verifies one source, compiled assets and both component manifest formats without executing product code', () =>
|
||||
fixture(async ({ verify }) => {
|
||||
const result = verify('--installed');
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(JSON.parse(result.stdout).installed_components, 2);
|
||||
}));
|
||||
test('rejects changed source', () =>
|
||||
fixture(async ({ root, verify }) => {
|
||||
await fs.writeFile(path.join(root, 'main.php'), 'changed');
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
test('accepts Git LF and Windows CRLF as the same source without accepting changed text', () =>
|
||||
fixture(async ({ root, manifest, save, verify }) => {
|
||||
manifest.source_eol = 'lf';
|
||||
manifest.source_files['main.php'] = hash('first\nsecond\n');
|
||||
await save();
|
||||
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nsecond\r\n');
|
||||
assert.equal(verify().status, 0);
|
||||
await fs.writeFile(path.join(root, 'main.php'), 'first\r\nchanged\r\n');
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
test('rejects a changed compiled asset', () =>
|
||||
fixture(async ({ root, verify }) => {
|
||||
await fs.writeFile(
|
||||
path.join(root, 'public/build/assets/a.js'),
|
||||
'changed',
|
||||
);
|
||||
assert.notEqual(verify('--compiled').status, 0);
|
||||
}));
|
||||
test('rejects a changed component', () =>
|
||||
fixture(async ({ root, verify }) => {
|
||||
await fs.writeFile(
|
||||
path.join(root, 'component-1/writer.php'),
|
||||
'changed',
|
||||
);
|
||||
assert.notEqual(verify('--installed').status, 0);
|
||||
}));
|
||||
test('rejects forged identity', () =>
|
||||
fixture(async ({ root, manifest, verify }) => {
|
||||
manifest.release_id = 'compras-forged';
|
||||
await fs.writeFile(
|
||||
path.join(root, 'compras-release.json'),
|
||||
JSON.stringify(manifest),
|
||||
);
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
test('rejects path traversal even with a recomputed descriptor', () =>
|
||||
fixture(async ({ manifest, save, verify }) => {
|
||||
manifest.source_files['../outside.php'] = hash('test');
|
||||
await save();
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
test('rejects disabled installation', () =>
|
||||
fixture(async ({ root, verify }) => {
|
||||
await fs.writeFile(
|
||||
path.join(root, '.env'),
|
||||
'COMPRAS_RUNTIME_ENABLED=false',
|
||||
);
|
||||
assert.notEqual(verify('--installed').status, 0);
|
||||
}));
|
||||
test('rejects a missing descriptor', () =>
|
||||
fixture(async ({ root, verify }) => {
|
||||
await fs.unlink(path.join(root, 'compras-release.json'));
|
||||
assert.notEqual(verify().status, 0);
|
||||
}));
|
||||
|
||||
@@ -13,17 +13,41 @@ test('legacy transfer adds links once and preserves other capabilities', () => {
|
||||
});
|
||||
|
||||
test('current host keeps its stricter feature guard and complete empty state', () => {
|
||||
const guard = "const requisitions=unit!==null&&context.purchasing?.internal_requisitions===true&&can('purchasing_requisitions.view',unit);";
|
||||
const source = legacy.replace('\n', '\n'+guard+'\n').replace('<div className="actions">', '<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições</a>}').replace('!budget&&!payables&&', '!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&');
|
||||
const guard =
|
||||
"const requisitions=unit!==null&&context.purchasing?.internal_requisitions===true&&can('purchasing_requisitions.view',unit);";
|
||||
const source = legacy
|
||||
.replace('\n', '\n' + guard + '\n')
|
||||
.replace(
|
||||
'<div className="actions">',
|
||||
'<div className="actions">{requisitions&&<a href="/purchasing/internal-requisitions">Requisições</a>}',
|
||||
)
|
||||
.replace(
|
||||
'!budget&&!payables&&',
|
||||
'!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&',
|
||||
);
|
||||
const output = purchasingHomeOverlay(source);
|
||||
assert.ok(output.includes(guard));
|
||||
assert.equal((output.match(/const requisitions=/g)??[]).length, 1);
|
||||
assert.equal((output.match(/href="\/purchasing\/internal-requisitions"/g)??[]).length, 1);
|
||||
assert.ok(output.includes('!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&'));
|
||||
assert.equal((output.match(/const requisitions=/g) ?? []).length, 1);
|
||||
assert.equal(
|
||||
(output.match(/href="\/purchasing\/internal-requisitions"/g) ?? [])
|
||||
.length,
|
||||
1,
|
||||
);
|
||||
assert.ok(
|
||||
output.includes(
|
||||
'!requisitions&&!sourceRequests&&!suppliers&&!budget&&!payables&&',
|
||||
),
|
||||
);
|
||||
assert.equal(purchasingHomeOverlay(output), output);
|
||||
});
|
||||
|
||||
test('unknown or duplicate declarations refuse preparation', () => {
|
||||
assert.throws(() => purchasingHomeOverlay('const requisitions=true;\n'+legacy));
|
||||
assert.throws(() => purchasingHomeOverlay('const requisitions=true;const requisitions=false;'+legacy));
|
||||
assert.throws(() =>
|
||||
purchasingHomeOverlay('const requisitions=true;\n' + legacy),
|
||||
);
|
||||
assert.throws(() =>
|
||||
purchasingHomeOverlay(
|
||||
'const requisitions=true;const requisitions=false;' + legacy,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user