diff --git a/tests/Feature/BudgetDistributionArtifactTest.php b/tests/Feature/BudgetDistributionArtifactTest.php index 0d1e21a..9beb760 100644 --- a/tests/Feature/BudgetDistributionArtifactTest.php +++ b/tests/Feature/BudgetDistributionArtifactTest.php @@ -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); } diff --git a/tests/Feature/CommonReceiptStockTest.php b/tests/Feature/CommonReceiptStockTest.php index 60134ef..64a47f4 100644 --- a/tests/Feature/CommonReceiptStockTest.php +++ b/tests/Feature/CommonReceiptStockTest.php @@ -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)); } } diff --git a/tests/Feature/CommonStockReadTest.php b/tests/Feature/CommonStockReadTest.php index aade9db..3567974 100644 --- a/tests/Feature/CommonStockReadTest.php +++ b/tests/Feature/CommonStockReadTest.php @@ -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)); } } diff --git a/tests/Feature/ExampleTest.php b/tests/Feature/ExampleTest.php index ef7b533..584142e 100644 --- a/tests/Feature/ExampleTest.php +++ b/tests/Feature/ExampleTest.php @@ -1,7 +1,5 @@ get(route('home')); - - $response->assertOk(); +test('home sends guests to the login page', function () { + $this->get(route('home'))->assertRedirect('/login'); }); diff --git a/tests/Feature/InvestmentPolicyTest.php b/tests/Feature/InvestmentPolicyTest.php index 8075c61..284f216 100644 --- a/tests/Feature/InvestmentPolicyTest.php +++ b/tests/Feature/InvestmentPolicyTest.php @@ -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'); }); diff --git a/tests/Feature/NativePayablePageTest.php b/tests/Feature/NativePayablePageTest.php index 4308518..3733b6e 100644 --- a/tests/Feature/NativePayablePageTest.php +++ b/tests/Feature/NativePayablePageTest.php @@ -1,10 +1,14 @@ 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']); } } diff --git a/tests/Feature/PublicPreviewTest.php b/tests/Feature/PublicPreviewTest.php index d272f9b..3a23346 100644 --- a/tests/Feature/PublicPreviewTest.php +++ b/tests/Feature/PublicPreviewTest.php @@ -1,31 +1,41 @@ 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); }); diff --git a/tests/Feature/PurchaseAwardOrderTest.php b/tests/Feature/PurchaseAwardOrderTest.php index bf8d636..ad71afb 100644 --- a/tests/Feature/PurchaseAwardOrderTest.php +++ b/tests/Feature/PurchaseAwardOrderTest.php @@ -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 para teste de impressão.'; $order = issuePurchaseOrder($this, selectPurchaseAward($this)); - $this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('<script>', false)->assertDontSee('', false)->assertSee('Orçamento não verificado')->assertSee('Não autoriza compras reais'); + $this->get('/ordens/'.$order->id.'/imprimir')->assertOk()->assertSee('<script>', false)->assertDontSee('', 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 () { diff --git a/tests/Feature/ReceiptAdapterReplayTest.php b/tests/Feature/ReceiptAdapterReplayTest.php index ae63b6c..44a804c 100644 --- a/tests/Feature/ReceiptAdapterReplayTest.php +++ b/tests/Feature/ReceiptAdapterReplayTest.php @@ -1,8 +1,10 @@ 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()); } } diff --git a/tests/Feature/RequisitionLedgerAccountsTest.php b/tests/Feature/RequisitionLedgerAccountsTest.php index 2c5aac4..d65ef79 100644 --- a/tests/Feature/RequisitionLedgerAccountsTest.php +++ b/tests/Feature/RequisitionLedgerAccountsTest.php @@ -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); diff --git a/tests/Feature/StockOperationsTest.php b/tests/Feature/StockOperationsTest.php index af0ae81..cb693a8 100644 --- a/tests/Feature/StockOperationsTest.php +++ b/tests/Feature/StockOperationsTest.php @@ -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) { diff --git a/tests/Feature/SupplierBankTest.php b/tests/Feature/SupplierBankTest.php index 1d13c06..6b733ba 100644 --- a/tests/Feature/SupplierBankTest.php +++ b/tests/Feature/SupplierBankTest.php @@ -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'); }); diff --git a/tests/Feature/WarehouseReturnIntegrationTest.php b/tests/Feature/WarehouseReturnIntegrationTest.php index eb18508..eea0721 100644 --- a/tests/Feature/WarehouseReturnIntegrationTest.php +++ b/tests/Feature/WarehouseReturnIntegrationTest.php @@ -1,10 +1,24 @@ 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)); } } diff --git a/tests/Pest.php b/tests/Pest.php index c634ac0..d7164ae 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,6 +1,7 @@ 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).'); + } } diff --git a/tests/Support/RequisitionLedgerQaRuntime.php b/tests/Support/RequisitionLedgerQaRuntime.php index 0410d22..aa46355 100644 --- a/tests/Support/RequisitionLedgerQaRuntime.php +++ b/tests/Support/RequisitionLedgerQaRuntime.php @@ -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.'); } diff --git a/tests/Unit/BudgetDistributionPlanTest.php b/tests/Unit/BudgetDistributionPlanTest.php index 79fac69..fe67780 100644 --- a/tests/Unit/BudgetDistributionPlanTest.php +++ b/tests/Unit/BudgetDistributionPlanTest.php @@ -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 {