Juntar fase5-producao ao main (inclui c9bd6db da máquina Windows)

Conflito em docs/historico/decisoes-do-proprietario.md resolvido mantendo
as decisões de 01/12 da fase 5 e as notas de 30/11 de c9bd6db.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 17:38:46 +02:00
co-authored by Claude Opus 5.5
321 changed files with 12781 additions and 5528 deletions
@@ -5,49 +5,60 @@ namespace App\Http\Controllers;
use App\Enums\PurchasingRole;
use App\Models\User;
use App\Services\OrganizationAccess;
use Illuminate\Http\Request;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tempo\Inventory\InventoryReadSession;
final class CommonStockReadController extends Controller
{
public function index(Request $request): JsonResponse
{
// Native authority, reloaded on every request; no SGF grants or identity assumptions.
$user=User::query()->findOrFail($this->staffIdentity($request)->id);
abort_unless($user->tenant_id!==null && $user->hasFunctions([PurchasingRole::Admin,PurchasingRole::Warehouse,PurchasingRole::Procurement,PurchasingRole::Finance])
&& !app(OrganizationAccess::class)->maintenanceOnly($user),403);
$d=$request->validate(['view'=>'sometimes|in:items,warehouses,balances,movements','search'=>'nullable|string|max:100',
'warehouse_id'=>'sometimes|integer|min:1','page'=>'sometimes|integer|min:1|max:100000','per_page'=>'sometimes|integer|min:1|max:100','snapshot'=>'sometimes|string|max:8192']);
abort_if(array_diff(array_keys($request->query()),array_keys($d))!==[],422);
$filters=['view'=>$d['view']??'balances','search'=>$d['search']??'','warehouse_id'=>isset($d['warehouse_id'])?(int)$d['warehouse_id']:null,
'page'=>(int)($d['page']??1),'per_page'=>(int)($d['per_page']??25)];
$binding=config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id);
if(!$binding)return response()->json(['status'=>'unavailable','message'=>'Fonte autorizada de stock ainda não ligada a este contexto.'],503)->header('Cache-Control','no-store');
abort_unless(app()->environment('testing')&&DB::connection()->getDriverName()==='pgsql',403);
$identity=DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D',$identity->name,$m)
&& $identity->role==='stock_read_qa_'.$m[1] && (int)$identity->port===55439
&& preg_match('/^[a-f0-9]{12}$/D',(string)config('stock_read.qa_run'))
&& $identity->cluster==='sgf_modular_regression_'.config('stock_read.qa_run'),403);
abort_unless(preg_match('/^sgf_stock_read_[a-f0-9]{12}$/D',$binding['schema']??'')&&($binding['append_only']??false)===true
&& ($binding['source_tenant_id']??null)===(int)$user->tenant_id,503,'Fonte de stock incompatível.');
if($filters['warehouse_id']!==null)abort_unless(in_array($filters['warehouse_id'],$binding['warehouse_ids'],true),403);
$root=base_path('packages/inventory-read/releases/0.1.0');
$bytes=is_file($root.'/manifest.json')?file_get_contents($root.'/manifest.json'):false;
abort_unless(is_string($bytes)&&hash_equals(config('stock_read.package_manifest_sha256'),hash('sha256',$bytes)),503,'Pacote de consulta incompatível.');
$manifest=json_decode($bytes,true,512,JSON_THROW_ON_ERROR);
foreach(['bootstrap.php','src/InventoryReader.php','src/InventoryReadSession.php'] as $file) {
$actual=is_file($root.'/'.$file)?hash_file('sha256',$root.'/'.$file):false;
abort_unless(is_string($actual)&&isset($manifest['files'][$file])&&hash_equals($manifest['files'][$file],$actual),503,'Pacote de consulta incompatível.');
$user = User::query()->findOrFail($this->staffIdentity($request)->id);
abort_unless($user->tenant_id !== null && $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance])
&& ! app(OrganizationAccess::class)->maintenanceOnly($user), 403);
$d = $request->validate(['view' => 'sometimes|in:items,warehouses,balances,movements', 'search' => 'nullable|string|max:100',
'warehouse_id' => 'sometimes|integer|min:1', 'page' => 'sometimes|integer|min:1|max:100000', 'per_page' => 'sometimes|integer|min:1|max:100', 'snapshot' => 'sometimes|string|max:8192']);
abort_if(array_diff(array_keys($request->query()), array_keys($d)) !== [], 422);
$filters = ['view' => $d['view'] ?? 'balances', 'search' => $d['search'] ?? '', 'warehouse_id' => isset($d['warehouse_id']) ? (int) $d['warehouse_id'] : null,
'page' => (int) ($d['page'] ?? 1), 'per_page' => (int) ($d['per_page'] ?? 25)];
$binding = config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id);
if (! $binding) {
return response()->json(['status' => 'unavailable', 'message' => 'Fonte autorizada de stock ainda não ligada a este contexto.'], 503)->header('Cache-Control', 'no-store');
}
abort_unless(app()->environment('testing') && DB::connection()->getDriverName() === 'pgsql', 403);
$identity = DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D', $identity->name, $m)
&& $identity->role === 'stock_read_qa_'.$m[1] && (int) $identity->port === 55439
&& preg_match('/^[a-f0-9]{12}$/D', (string) config('stock_read.qa_run'))
&& $identity->cluster === 'sgf_modular_regression_'.config('stock_read.qa_run'), 403);
abort_unless(preg_match('/^sgf_stock_read_[a-f0-9]{12}$/D', $binding['schema'] ?? '') && ($binding['append_only'] ?? false) === true
&& ($binding['source_tenant_id'] ?? null) === (int) $user->tenant_id, 503, 'Fonte de stock incompatível.');
if ($filters['warehouse_id'] !== null) {
abort_unless(in_array($filters['warehouse_id'], $binding['warehouse_ids'], true), 403);
}
$root = base_path('packages/inventory-read/releases/0.1.0');
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
abort_unless(is_string($bytes) && hash_equals(config('stock_read.package_manifest_sha256'), hash('sha256', $bytes)), 503, 'Pacote de consulta incompatível.');
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
foreach (['bootstrap.php', 'src/InventoryReader.php', 'src/InventoryReadSession.php'] as $file) {
$actual = is_file($root.'/'.$file) ? hash_file('sha256', $root.'/'.$file) : false;
abort_unless(is_string($actual) && isset($manifest['files'][$file]) && hash_equals($manifest['files'][$file], $actual), 503, 'Pacote de consulta incompatível.');
}
require_once $root.'/bootstrap.php';
$fingerprint=hash('sha256',json_encode(['compras',$user->tenant_id,$user->id,$request->session()->get('work_context'),$binding,array_diff_key($filters,['page'=>true])],JSON_THROW_ON_ERROR));
try { $result=(new \Tempo\Inventory\InventoryReadSession(DB::connection()))->read($binding,$fingerprint,$filters,$d['snapshot']??null); }
catch(\Illuminate\Database\QueryException $e){
if(!in_array($e->errorInfo[0]??null,['42P01','42703','42883','57014'],true))throw $e;
return response()->json(['status'=>'unavailable','message'=>'A fonte de stock está indisponível ou incompatível. Actualize a consulta mais tarde.'],503)->header('Cache-Control','no-store');
$fingerprint = hash('sha256', json_encode(['compras', $user->tenant_id, $user->id, $request->session()->get('work_context'), $binding, array_diff_key($filters, ['page' => true])], JSON_THROW_ON_ERROR));
try {
$result = (new InventoryReadSession(DB::connection()))->read($binding, $fingerprint, $filters, $d['snapshot'] ?? null);
} catch (QueryException $e) {
if (! in_array($e->errorInfo[0] ?? null, ['42P01', '42703', '42883', '57014'], true)) {
throw $e;
}
return response()->json(['status' => 'unavailable', 'message' => 'A fonte de stock está indisponível ou incompatível. Actualize a consulta mais tarde.'], 503)->header('Cache-Control','no-store');
}
return response()->json($result)->header('Cache-Control','no-store');
}
}
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Settings;
use App\Http\Controllers\Controller;
use App\Http\Middleware\RequireTwoFactorForSensitiveRoles;
use App\Http\Requests\Settings\PasswordUpdateRequest;
use App\Http\Requests\Settings\TwoFactorAuthenticationRequest;
use App\Models\User;
@@ -41,6 +42,7 @@ class SecurityController extends Controller
'twoFactorEnabled' => $actor->hasEnabledTwoFactorAuthentication(),
'twoFactorPending' => $actor->two_factor_secret !== null && ! $actor->hasEnabledTwoFactorAuthentication(),
'requiresConfirmation' => Fortify::confirmsTwoFactorAuthentication(),
'mfaRequired' => RequireTwoFactorForSensitiveRoles::requiredFor($actor),
];
}
@@ -43,14 +43,21 @@ final class WarehouseReturnController extends Controller
}
/** @param callable():array<string,mixed> $run */
private function response(callable $run,bool $readOnly=false): JsonResponse
private function response(callable $run, bool $readOnly = false): JsonResponse
{
try {
$result=$readOnly?DB::transaction(function()use($run){if(DB::getDriverName()==='pgsql'&&DB::transactionLevel()===1)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');return $run();}):$run();
$result = $readOnly ? DB::transaction(function () use ($run) {
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
}
return $run();
}) : $run();
return response()->json($result)->header('Cache-Control', 'no-store');
} catch (QueryException $e) {
if (($e->errorInfo[0] ?? null) === '55P03') {
return response()->json(['code'=>'warehouse_return_busy','message' => 'Devolução ocupada. Aguarde e repita manualmente a conferência.'], 423)->header('Cache-Control', 'no-store');
return response()->json(['code' => 'warehouse_return_busy', 'message' => 'Devolução ocupada. Aguarde e repita manualmente a conferência.'], 423)->header('Cache-Control', 'no-store');
}
throw $e;
}
@@ -83,12 +90,25 @@ final class WarehouseReturnController extends Controller
$d['version'] = (int) $d['version'];
$d['received_in_warehouse'] = true;
return $this->response(fn () => $flow->confirm($this->actor($r),$id,$d));
return $this->response(fn () => $flow->confirm($this->actor($r), $id, $d));
}
public function withdraw(Request $r,int $id,WarehouseReturns $flow): JsonResponse {return $this->close($r,$id,$flow,'withdrawn');}
public function reject(Request $r,int $id,WarehouseReturns $flow): JsonResponse {return $this->close($r,$id,$flow,'rejected');}
private function close(Request $r,int $id,WarehouseReturns $flow,string $state): JsonResponse
public function withdraw(Request $r, int $id, WarehouseReturns $flow): JsonResponse
{
$d=$r->validate(['version'=>'required|integer|min:1','reason'=>'required|string|min:10|max:1000']);abort_if(array_diff(array_keys($r->all()),array_keys($d))!==[],422);$d['version']=(int)$d['version'];return $this->response(fn()=>$flow->close($this->actor($r),$id,$d,$state));
return $this->close($r, $id, $flow, 'withdrawn');
}
public function reject(Request $r, int $id, WarehouseReturns $flow): JsonResponse
{
return $this->close($r, $id, $flow, 'rejected');
}
private function close(Request $r, int $id, WarehouseReturns $flow, string $state): JsonResponse
{
$d = $r->validate(['version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:1000']);
abort_if(array_diff(array_keys($r->all()), array_keys($d)) !== [], 422);
$d['version'] = (int) $d['version'];
return $this->response(fn () => $flow->close($this->actor($r), $id, $d, $state));
}
}