diff --git a/app/Http/Controllers/CommonStockReadController.php b/app/Http/Controllers/CommonStockReadController.php index 7f6287e..ef3c73d 100644 --- a/app/Http/Controllers/CommonStockReadController.php +++ b/app/Http/Controllers/CommonStockReadController.php @@ -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'); } } diff --git a/app/Http/Controllers/WarehouseReturnController.php b/app/Http/Controllers/WarehouseReturnController.php index 94263e0..8a58ce9 100644 --- a/app/Http/Controllers/WarehouseReturnController.php +++ b/app/Http/Controllers/WarehouseReturnController.php @@ -43,14 +43,21 @@ final class WarehouseReturnController extends Controller } /** @param callable():array $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)); } } diff --git a/app/Models/SupplyRecord.php b/app/Models/SupplyRecord.php index d4dec94..cabe483 100644 --- a/app/Models/SupplyRecord.php +++ b/app/Models/SupplyRecord.php @@ -4,13 +4,14 @@ namespace App\Models; use App\Models\Concerns\BelongsToTenant; use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Carbon; /** * @property array $data * @property array $snapshot * @property int $version * @property string $record_key - * @property \Illuminate\Support\Carbon $created_at + * @property Carbon $created_at */ class SupplyRecord extends Model { diff --git a/app/Services/CustomerSales.php b/app/Services/CustomerSales.php index 5469241..e101c59 100644 --- a/app/Services/CustomerSales.php +++ b/app/Services/CustomerSales.php @@ -13,7 +13,6 @@ use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Validator; use Tempo\Finance\GeneralLedger\LedgerSchema; use Tempo\Finance\GeneralLedger\Receivables; -use Tempo\Finance\GeneralLedger\ReceivablesSchema; /** Native actor/catalogue adapter. All customer financial writes belong to the common core. */ final class CustomerSales diff --git a/app/Services/ImportParties.php b/app/Services/ImportParties.php index ea0057b..0673d6d 100644 --- a/app/Services/ImportParties.php +++ b/app/Services/ImportParties.php @@ -42,8 +42,8 @@ final class ImportParties 'issues' => $this->issues($actor, $order, $record)]); $suppliers = Supplier::query()->when(! $canSelect, fn ($q) => $q->whereRaw('1=0'))->where('status', 'active')->where('blocked', false) ->where('next_review', '>=', today())->when($search !== '', fn ($q) => $q->where(fn ($match) => $match - ->whereRaw('LOWER(name) LIKE ?', ['%'.addcslashes(mb_strtolower($search), '%_\\').'%']) - ->orWhereRaw('LOWER(nuit) LIKE ?', ['%'.addcslashes(mb_strtolower($search), '%_\\').'%']))) + ->whereRaw('LOWER(name) LIKE ?', ['%'.addcslashes(mb_strtolower($search), '%_\\').'%']) + ->orWhereRaw('LOWER(nuit) LIKE ?', ['%'.addcslashes(mb_strtolower($search), '%_\\').'%']))) ->orderBy('name')->orderBy('id')->paginate(20, ['id', 'name', 'nuit', 'version'], 'party_suppliers_page')->withQueryString(); $instructions = app(SupplyPlanning::class)->latest('import_document')->where('purchase_order_id', $order->id) ->where('snapshot->import_key', $current->record_key)->where('data->type', 'written_instructions') diff --git a/app/Services/SgfInvoiceDispatches.php b/app/Services/SgfInvoiceDispatches.php index ccfd783..6b2756c 100644 --- a/app/Services/SgfInvoiceDispatches.php +++ b/app/Services/SgfInvoiceDispatches.php @@ -288,7 +288,7 @@ final class SgfInvoiceDispatches $state = $this->state($row); $out = $this->summary($row); - return array_replace($out,['connection_id' => $row->connection_id, 'mapping_id' => $row->mapping_id, 'document' => json_decode($row->document,true), 'reason' => $row->reason, + return array_replace($out, ['connection_id' => $row->connection_id, 'mapping_id' => $row->mapping_id, 'document' => json_decode($row->document, true), 'reason' => $row->reason, 'impact' => $state['impact'] ?? null, 'approval_hash' => $row->phase === 'previewed' ? ($state['approval_hash'] ?? null) : null, 'lease_until' => $row->lease_until]); } @@ -299,14 +299,14 @@ final class SgfInvoiceDispatches if (! is_array($x)) { return $x; }if (! array_is_list($x)) { - ksort($x,SORT_STRING); + ksort($x, SORT_STRING); }foreach ($x as &$item) { $item = $normalise($item); } -return $x; + return $x; }; - return hash('sha256',json_encode($normalise($v),JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + return hash('sha256', json_encode($normalise($v), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); } } diff --git a/app/Services/SgfInvoiceGateway.php b/app/Services/SgfInvoiceGateway.php index 1eb85e9..6c5a4ad 100644 --- a/app/Services/SgfInvoiceGateway.php +++ b/app/Services/SgfInvoiceGateway.php @@ -5,39 +5,56 @@ namespace App\Services; use App\Models\User; use Illuminate\Support\Facades\Http; use LogicException; +use Tempo\SgcInvoiceClient\InvoiceClient; /** Prepared gateway only; no event listener, route, scheduled job or automatic transmission. */ final class SgfInvoiceGateway { - public function clientFor(User $actor,string $connection): \Tempo\SgcInvoiceClient\InvoiceClient + public function clientFor(User $actor, string $connection): InvoiceClient { - if(config('sgf_invoice.enabled')!==true)throw new LogicException('SGF invoice gateway disabled.'); - $all=config('sgf_invoice.connections',[]);$c=$all[$connection]??null; - abort_unless(is_array($c)&&($c['enabled']??false)===true&&auth()->id()===$actor->id,403); - $current=User::where('tenant_id',$actor->tenant_id)->findOrFail($actor->id); - abort_unless(($c['source_scope']['tenant_id']??null)===$current->tenant_id&&$current->hasFunctions(['finance']) - &&!app(OrganizationAccess::class)->maintenanceOnly($current),403); - $path=config('sgf_invoice.client_package');$pin=config('sgf_invoice.client_package_sha256'); - $actual=is_string($path)&&is_file($path)?hash_file('sha256',$path):false; - if(!is_string($path)||is_link($path)||!is_file($path)||!is_string($pin)||!preg_match('/^[a-f0-9]{64}$/D',$pin) - ||!is_string($actual)||!hash_equals($pin,$actual))throw new LogicException('Verified client package required.'); - if(class_exists(\Tempo\SgcInvoiceClient\InvoiceClient::class,false)){ - $loaded=(new \ReflectionClass(\Tempo\SgcInvoiceClient\InvoiceClient::class))->getFileName(); - $loadedHash=is_string($loaded)&&is_file($loaded)?hash_file('sha256',$loaded):false; - if(!is_string($loadedHash)||!hash_equals($pin,$loadedHash))throw new LogicException('Client version changed; restart separately.'); - }else require_once $path; - $configurationHash=hash('sha256',json_encode($c,JSON_THROW_ON_ERROR)); - return new \Tempo\SgcInvoiceClient\InvoiceClient($c['client_id'],$c['token'],$c['context_version'],$c['source_scope'],$c['target_scope'], - function(string $method,string $url,array $headers,?array $body)use($actor,$connection,$configurationHash):array{ + if (config('sgf_invoice.enabled') !== true) { + throw new LogicException('SGF invoice gateway disabled.'); + } + $all = config('sgf_invoice.connections', []); + $c = $all[$connection] ?? null; + abort_unless(is_array($c) && ($c['enabled'] ?? false) === true && auth()->id() === $actor->id, 403); + $current = User::where('tenant_id', $actor->tenant_id)->findOrFail($actor->id); + abort_unless(($c['source_scope']['tenant_id'] ?? null) === $current->tenant_id && $current->hasFunctions(['finance']) + && ! app(OrganizationAccess::class)->maintenanceOnly($current), 403); + $path = config('sgf_invoice.client_package'); + $pin = config('sgf_invoice.client_package_sha256'); + $actual = is_string($path) && is_file($path) ? hash_file('sha256', $path) : false; + if (! is_string($path) || is_link($path) || ! is_file($path) || ! is_string($pin) || ! preg_match('/^[a-f0-9]{64}$/D', $pin) + || ! is_string($actual) || ! hash_equals($pin, $actual)) { + throw new LogicException('Verified client package required.'); + } + if (class_exists(InvoiceClient::class, false)) { + $loaded = (new \ReflectionClass(InvoiceClient::class))->getFileName(); + $loadedHash = is_string($loaded) && is_file($loaded) ? hash_file('sha256', $loaded) : false; + if (! is_string($loadedHash) || ! hash_equals($pin, $loadedHash)) { + throw new LogicException('Client version changed; restart separately.'); + } + } else { + require_once $path; + } + $configurationHash = hash('sha256', json_encode($c, JSON_THROW_ON_ERROR)); + + return new InvoiceClient($c['client_id'], $c['token'], $c['context_version'], $c['source_scope'], $c['target_scope'], + function (string $method, string $url, array $headers, ?array $body) use ($actor, $connection, $configurationHash): array { // Recheck the originating person's authority immediately before every network operation. - $now=config('sgf_invoice.connections',[])[$connection]??null; - if(config('sgf_invoice.enabled')!==true||!is_array($now)||!hash_equals($configurationHash,hash('sha256',json_encode($now,JSON_THROW_ON_ERROR))) - ||auth()->id()!==$actor->id)return ['status'=>403,'json'=>null]; - $current=User::where('tenant_id',$actor->tenant_id)->find($actor->id); - if(!$current||!$current->hasFunctions(['finance'])||app(OrganizationAccess::class)->maintenanceOnly($current))return ['status'=>403,'json'=>null]; - $http=Http::withHeaders($headers)->acceptJson()->asJson()->withoutRedirecting()->connectTimeout(3)->timeout(15); - $response=$method==='GET'?$http->get($url):$http->post($url,$body); - return ['status'=>$response->status(),'json'=>$response->json()]; - },$c['origin']); + $now = config('sgf_invoice.connections', [])[$connection] ?? null; + if (config('sgf_invoice.enabled') !== true || ! is_array($now) || ! hash_equals($configurationHash, hash('sha256', json_encode($now, JSON_THROW_ON_ERROR))) + || auth()->id() !== $actor->id) { + return ['status' => 403, 'json' => null]; + } + $current = User::where('tenant_id', $actor->tenant_id)->find($actor->id); + if (! $current || ! $current->hasFunctions(['finance']) || app(OrganizationAccess::class)->maintenanceOnly($current)) { + return ['status' => 403, 'json' => null]; + } + $http = Http::withHeaders($headers)->acceptJson()->asJson()->withoutRedirecting()->connectTimeout(3)->timeout(15); + $response = $method === 'GET' ? $http->get($url) : $http->post($url, $body); + + return ['status' => $response->status(), 'json' => $response->json()]; + }, $c['origin']); } } diff --git a/app/Services/StockIssueMovement.php b/app/Services/StockIssueMovement.php index 99982b5..7ee5a14 100644 --- a/app/Services/StockIssueMovement.php +++ b/app/Services/StockIssueMovement.php @@ -1,24 +1,35 @@ getDriverName()){'pgsql'=>'public','sqlite'=>'main','mysql','mariadb'=>DB::connection()->getDatabaseName(),default=>throw new \LogicException('Driver não suportado.')}; - return new \Tempo\Inventory\IssueMovementWriter(DB::connection(),$schema,(int)$actor->tenant_id,(int)$actor->id,function()use($actor){app(CurrentActor::class)->lock($actor,[PurchasingRole::Warehouse]);}); + $schema = match (DB::connection()->getDriverName()) { + 'pgsql' => 'public','sqlite' => 'main','mysql','mariadb' => DB::connection()->getDatabaseName(),default => throw new \LogicException('Driver não suportado.') + }; + + return new IssueMovementWriter(DB::connection(), $schema, (int) $actor->tenant_id, (int) $actor->id, function () use ($actor) { + app(CurrentActor::class)->lock($actor, [PurchasingRole::Warehouse]); + }); } } diff --git a/app/Services/WarehouseReturnMovement.php b/app/Services/WarehouseReturnMovement.php index 2bbc4ba..b2f8398 100644 --- a/app/Services/WarehouseReturnMovement.php +++ b/app/Services/WarehouseReturnMovement.php @@ -8,7 +8,8 @@ use Tempo\Inventory\DeliveryReturnWriter; final class WarehouseReturnMovement { - public const MANIFEST_SHA256='2850a4f5cb678acfe3a9dbc7a7d62eb233bc72722ad0de374681c2679c90557c'; + public const MANIFEST_SHA256 = '2850a4f5cb678acfe3a9dbc7a7d62eb233bc72722ad0de374681c2679c90557c'; + private function fileHash(string $file): string { $hash = is_file($file) ? hash_file('sha256', $file) : false; diff --git a/app/Services/WarehouseReturns.php b/app/Services/WarehouseReturns.php index 90842f7..9cf9ea6 100644 --- a/app/Services/WarehouseReturns.php +++ b/app/Services/WarehouseReturns.php @@ -46,9 +46,9 @@ final class WarehouseReturns private function lock(User $actor, string $action): User { - $timeout=config('stock_returns.lock_timeout_ms',2000); - abort_unless(is_int($timeout)&&$timeout>=100&&$timeout<=10000,503,'Tempo de espera de conferência inválido.'); - DB::select("SELECT set_config('lock_timeout',?,true)",[$timeout.'ms']); + $timeout = config('stock_returns.lock_timeout_ms', 2000); + abort_unless(is_int($timeout) && $timeout >= 100 && $timeout <= 10000, 503, 'Tempo de espera de conferência inválido.'); + DB::select("SELECT set_config('lock_timeout',?,true)", [$timeout.'ms']); app(ConflictGuard::class)->lockCompany($actor); $fresh = app(CurrentActor::class)->lock($actor); @@ -111,7 +111,7 @@ final class WarehouseReturns } } -return null; + return null; } /** @@ -172,15 +172,16 @@ return null; abort_unless($old->created_by === $actor->id && hash_equals($old->input_hash, $hash), 409, 'Chave utilizada com outros dados.'); $this->request($old->snapshot['source']['request_id']); - $state=SupplyRecord::query()->where('kind','warehouse_return')->where('record_key',$old->record_key)->orderByDesc('version')->value('state'); - return ['id' => $old->id, 'state'=>$state, 'impact' => $this->impact($old->snapshot['source']), 'replayed' => true]; + $state = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $old->record_key)->orderByDesc('version')->value('state'); + + return ['id' => $old->id, 'state' => $state, 'impact' => $this->impact($old->snapshot['source']), 'replayed' => true]; } $source = $this->source($actor, $d); abort_unless($source['requester_id'] === $actor->id, 403, 'A declaração de excedente pertence ao destinatário original.'); $record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'warehouse_return', 'record_key' => $d['operation_key'], 'version' => 1, 'state' => 'prepared', 'stock_item_id' => $source['item']['id'], 'warehouse_id' => $source['warehouse']['id'], 'created_by' => $actor->id, 'data' => $d, 'snapshot' => ['source' => $source, 'source_hash' => $this->hash($source), 'declared_unused' => true], 'reason' => $d['reason'], 'operation_key' => $d['operation_key'], 'input_hash' => $hash, 'created_at' => now()]); app(RequisitionWorkflow::class)->audit($actor, 'warehouse_return.prepared', null, null, ['record_id' => $record->id, 'request_id' => $source['request_id'], 'impact' => $this->impact($source), 'declared_unused' => true]); - return ['id' => $record->id, 'state'=>'prepared', 'impact' => $this->impact($source), 'replayed' => false]; + return ['id' => $record->id, 'state' => 'prepared', 'impact' => $this->impact($source), 'replayed' => false]; }); } @@ -199,7 +200,8 @@ return null; abort_if($p->created_by === $actor->id, 403, 'Recepção deve ser independente da declaração.'); $done = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $p->record_key)->where('version', 2)->first(); if ($done) { - abort_unless($done->state==='confirmed',409,'Proposta encerrada sem movimento. Prepare uma nova proposta se necessário.'); + abort_unless($done->state === 'confirmed', 409, 'Proposta encerrada sem movimento. Prepare uma nova proposta se necessário.'); + return ['id' => $done->id, 'movement_id' => $done->data['movement_id'], 'replayed' => true]; } abort_unless($d['version'] === 1 && $d['received_in_warehouse'] === true, 422, 'Confirme a recepção física da versão conferida.'); @@ -218,22 +220,32 @@ return null; } /** - * @param array $d + * @param array $d * @return array */ - public function close(User $actor,int $id,array $d,string $state): array + public function close(User $actor, int $id, array $d, string $state): array { - abort_unless(in_array($state,['withdrawn','rejected'],true),422); - $action=$state==='withdrawn'?'prepare':'confirm';$this->authorize($actor,$action); - return DB::transaction(function()use($actor,$id,$d,$state,$action){ - $actor=$this->lock($actor,$action);$p=SupplyRecord::query()->where('kind','warehouse_return')->where('version',1)->lockForUpdate()->findOrFail($id);$this->request($p->snapshot['source']['request_id']); - abort_unless($state==='withdrawn'?$p->created_by===$actor->id:$p->created_by!==$actor->id,403,'Retirada pertence ao preparador; recusa exige conferência independente.'); - $done=SupplyRecord::query()->where('kind','warehouse_return')->where('record_key',$p->record_key)->where('version',2)->first(); - if($done){abort_unless($done->state===$state,409,'A proposta já tem outra decisão terminal.');return ['id'=>$done->id,'state'=>$done->state,'replayed'=>true];} - abort_unless($d['version']===1,409,'Versão de proposta desactualizada.');$book=app(StockWorkflow::class)->balance($p->stock_item_id,$p->warehouse_id); - $closed=SupplyRecord::query()->create(['tenant_id'=>$actor->tenant_id,'kind'=>'warehouse_return','record_key'=>$p->record_key,'version'=>2,'state'=>$state,'stock_item_id'=>$p->stock_item_id,'warehouse_id'=>$p->warehouse_id,'created_by'=>$actor->id,'data'=>['prepared_id'=>$p->id,'action'=>$state,'reason'=>$d['reason']],'snapshot'=>['source'=>$p->snapshot['source'],'before'=>$book['quantity'],'after'=>$book['quantity'],'preparer_id'=>$p->created_by],'reason'=>$d['reason'],'operation_key'=>(string)Str::uuid(),'input_hash'=>$this->hash($d+['action'=>$state]),'created_at'=>now()]); - app(RequisitionWorkflow::class)->audit($actor,'warehouse_return.'.$state,null,null,['record_id'=>$closed->id,'declaration_id'=>$p->id,'reason'=>$d['reason'],'before'=>$book['quantity'],'after'=>$book['quantity'],'physical_effect'=>0]); - return ['id'=>$closed->id,'state'=>$state,'replayed'=>false]; + abort_unless(in_array($state, ['withdrawn', 'rejected'], true), 422); + $action = $state === 'withdrawn' ? 'prepare' : 'confirm'; + $this->authorize($actor, $action); + + return DB::transaction(function () use ($actor, $id, $d, $state, $action) { + $actor = $this->lock($actor, $action); + $p = SupplyRecord::query()->where('kind', 'warehouse_return')->where('version', 1)->lockForUpdate()->findOrFail($id); + $this->request($p->snapshot['source']['request_id']); + abort_unless($state === 'withdrawn' ? $p->created_by === $actor->id : $p->created_by !== $actor->id, 403, 'Retirada pertence ao preparador; recusa exige conferência independente.'); + $done = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $p->record_key)->where('version', 2)->first(); + if ($done) { + abort_unless($done->state === $state, 409, 'A proposta já tem outra decisão terminal.'); + + return ['id' => $done->id, 'state' => $done->state, 'replayed' => true]; + } + abort_unless($d['version'] === 1, 409, 'Versão de proposta desactualizada.'); + $book = app(StockWorkflow::class)->balance($p->stock_item_id, $p->warehouse_id); + $closed = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'warehouse_return', 'record_key' => $p->record_key, 'version' => 2, 'state' => $state, 'stock_item_id' => $p->stock_item_id, 'warehouse_id' => $p->warehouse_id, 'created_by' => $actor->id, 'data' => ['prepared_id' => $p->id, 'action' => $state, 'reason' => $d['reason']], 'snapshot' => ['source' => $p->snapshot['source'], 'before' => $book['quantity'], 'after' => $book['quantity'], 'preparer_id' => $p->created_by], 'reason' => $d['reason'], 'operation_key' => (string) Str::uuid(), 'input_hash' => $this->hash($d + ['action' => $state]), 'created_at' => now()]); + app(RequisitionWorkflow::class)->audit($actor, 'warehouse_return.'.$state, null, null, ['record_id' => $closed->id, 'declaration_id' => $p->id, 'reason' => $d['reason'], 'before' => $book['quantity'], 'after' => $book['quantity'], 'physical_effect' => 0]); + + return ['id' => $closed->id, 'state' => $state, 'replayed' => false]; }); } diff --git a/config/stock_read.php b/config/stock_read.php index 3197e88..ecb8d94 100644 --- a/config/stock_read.php +++ b/config/stock_read.php @@ -1,4 +1,5 @@ [], 'qa_run' => env('SGF_ISOLATED_REGRESSION_RUN'), diff --git a/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php b/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php index 957e870..c2c4f79 100644 --- a/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php +++ b/database/migrations/2026_11_10_000001_create_sgf_invoice_dispatches.php @@ -2,45 +2,81 @@ use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; -use Illuminate\Support\Facades\{DB,Schema}; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Schema; -return new class extends Migration { - public function up():void +return new class extends Migration +{ + public function up(): void { - if(!in_array(DB::getDriverName(),['pgsql','sqlite'],true))throw new LogicException('SGF dispatch schema requires PostgreSQL/SQLite.'); - Schema::create('sgf_invoice_dispatches',function(Blueprint $t){ - $t->id();$t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete(); + if (! in_array(DB::getDriverName(), ['pgsql', 'sqlite'], true)) { + throw new LogicException('SGF dispatch schema requires PostgreSQL/SQLite.'); + } + Schema::create('sgf_invoice_dispatches', function (Blueprint $t) { + $t->id(); + $t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete(); $t->foreignId('supplier_id')->constrained('suppliers')->restrictOnDelete(); - $t->string('reference',120);$t->string('number',100);$t->string('connection_id',64);$t->string('mapping_id',64); - $t->json('mapping_snapshot');$t->char('mapping_hash',64);$t->json('document');$t->text('reason'); - $t->unsignedInteger('source_version')->default(1);$t->unsignedInteger('version')->default(1); - $t->string('phase',32)->default('draft');$t->boolean('ever_sending')->default(false); - $t->text('state_ciphertext')->nullable();$t->char('approval_hash',64)->nullable(); - $t->foreignId('preview_actor_id')->nullable()->constrained('users')->restrictOnDelete();$t->char('source_context_hash',64)->nullable(); - $t->uuid('operation_key')->nullable()->unique();$t->uuid('lease_id')->nullable();$t->timestamp('lease_until')->nullable(); - $t->json('receipt')->nullable();$t->foreignId('created_by')->constrained('users')->restrictOnDelete();$t->timestamps(); - $t->unique(['tenant_id','reference']);$t->unique(['tenant_id','supplier_id','number'],'sgf_dispatch_document_unique'); - $t->index(['tenant_id','id']);$t->index(['tenant_id','phase','id']); + $t->string('reference', 120); + $t->string('number', 100); + $t->string('connection_id', 64); + $t->string('mapping_id', 64); + $t->json('mapping_snapshot'); + $t->char('mapping_hash', 64); + $t->json('document'); + $t->text('reason'); + $t->unsignedInteger('source_version')->default(1); + $t->unsignedInteger('version')->default(1); + $t->string('phase', 32)->default('draft'); + $t->boolean('ever_sending')->default(false); + $t->text('state_ciphertext')->nullable(); + $t->char('approval_hash', 64)->nullable(); + $t->foreignId('preview_actor_id')->nullable()->constrained('users')->restrictOnDelete(); + $t->char('source_context_hash', 64)->nullable(); + $t->uuid('operation_key')->nullable()->unique(); + $t->uuid('lease_id')->nullable(); + $t->timestamp('lease_until')->nullable(); + $t->json('receipt')->nullable(); + $t->foreignId('created_by')->constrained('users')->restrictOnDelete(); + $t->timestamps(); + $t->unique(['tenant_id', 'reference']); + $t->unique(['tenant_id', 'supplier_id', 'number'], 'sgf_dispatch_document_unique'); + $t->index(['tenant_id', 'id']); + $t->index(['tenant_id', 'phase', 'id']); }); - Schema::create('sgf_invoice_dispatch_events',function(Blueprint $t){ - $t->id();$t->foreignId('dispatch_id')->constrained('sgf_invoice_dispatches')->restrictOnDelete(); - $t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete();$t->unsignedInteger('version'); - $t->foreignId('actor_id')->constrained('users')->restrictOnDelete();$t->string('action',40);$t->text('reason'); - $t->json('before_state')->nullable();$t->json('after_state');$t->timestamp('created_at'); - $t->unique(['dispatch_id','version']);$t->index(['tenant_id','dispatch_id','id']); + Schema::create('sgf_invoice_dispatch_events', function (Blueprint $t) { + $t->id(); + $t->foreignId('dispatch_id')->constrained('sgf_invoice_dispatches')->restrictOnDelete(); + $t->foreignId('tenant_id')->constrained('tenants')->restrictOnDelete(); + $t->unsignedInteger('version'); + $t->foreignId('actor_id')->constrained('users')->restrictOnDelete(); + $t->string('action', 40); + $t->text('reason'); + $t->json('before_state')->nullable(); + $t->json('after_state'); + $t->timestamp('created_at'); + $t->unique(['dispatch_id', 'version']); + $t->index(['tenant_id', 'dispatch_id', 'id']); }); - if(DB::getDriverName()==='pgsql'){ + if (DB::getDriverName() === 'pgsql') { DB::unprepared("CREATE FUNCTION sgf_dispatch_preserve() RETURNS trigger LANGUAGE plpgsql AS \$\$ BEGIN RAISE EXCEPTION 'Preserve SGF dispatch audit/history'; END; \$\$;"); DB::unprepared('CREATE TRIGGER sgf_dispatch_event_immutable BEFORE UPDATE OR DELETE ON sgf_invoice_dispatch_events FOR EACH ROW EXECUTE FUNCTION sgf_dispatch_preserve()'); DB::unprepared('CREATE TRIGGER sgf_dispatch_no_delete BEFORE DELETE ON sgf_invoice_dispatches FOR EACH ROW EXECUTE FUNCTION sgf_dispatch_preserve()'); - }elseif(DB::getDriverName()==='sqlite'){ - foreach(['UPDATE','DELETE']as$action)DB::unprepared("CREATE TRIGGER sgf_dispatch_events_".strtolower($action)." BEFORE $action ON sgf_invoice_dispatch_events BEGIN SELECT RAISE(ABORT,'Preserve SGF dispatch audit'); END"); + } elseif (DB::getDriverName() === 'sqlite') { + foreach (['UPDATE', 'DELETE'] as $action) { + DB::unprepared('CREATE TRIGGER sgf_dispatch_events_'.strtolower($action)." BEFORE $action ON sgf_invoice_dispatch_events BEGIN SELECT RAISE(ABORT,'Preserve SGF dispatch audit'); END"); + } DB::unprepared("CREATE TRIGGER sgf_dispatch_no_delete BEFORE DELETE ON sgf_invoice_dispatches BEGIN SELECT RAISE(ABORT,'Preserve SGF dispatch history'); END"); - }else throw new LogicException('SGF dispatch schema validated only for PostgreSQL/SQLite.'); + } else { + throw new LogicException('SGF dispatch schema validated only for PostgreSQL/SQLite.'); + } } - public function down():void + + public function down(): void { - Schema::dropIfExists('sgf_invoice_dispatch_events');Schema::dropIfExists('sgf_invoice_dispatches'); - if(DB::getDriverName()==='pgsql')DB::unprepared('DROP FUNCTION IF EXISTS sgf_dispatch_preserve()'); + Schema::dropIfExists('sgf_invoice_dispatch_events'); + Schema::dropIfExists('sgf_invoice_dispatches'); + if (DB::getDriverName() === 'pgsql') { + DB::unprepared('DROP FUNCTION IF EXISTS sgf_dispatch_preserve()'); + } } }; diff --git a/pint.json b/pint.json index 0c0f5f2..9ad308a 100644 --- a/pint.json +++ b/pint.json @@ -1,4 +1,4 @@ { "preset": "laravel", - "exclude": ["packages"] + "exclude": ["packages", "integrations"] } diff --git a/resources/js/pages/company/clients.tsx b/resources/js/pages/company/clients.tsx index 4b77fac..7a945e2 100644 --- a/resources/js/pages/company/clients.tsx +++ b/resources/js/pages/company/clients.tsx @@ -115,10 +115,11 @@ export default function Clients({ onSubmit={(event) => { event.preventDefault(); const data = new FormData(event.currentTarget); - const search = data.get('search'); - router.get('/empresa/clientes', { - search: typeof search === 'string' ? search : '', - }); + const search = data.get('search'); + router.get('/empresa/clientes', { + search: + typeof search === 'string' ? search : '', + }); }} > { const q = BigInt(value); return `${q / 1000n},${(q % 1000n).toString().padStart(3, '0')}`; }; -const states: Record = {prepared:'Por confirmar',confirmed:'Confirmada',withdrawn:'Retirada',rejected:'Recusada'}; +type Row = { + id: number; + prepared_id: number; + version: number; + state: string; + reason: string; + evidence: string; + preparer_id: number; + author_id: number; + created_at: string; + impact: Impact; +}; +type Option = { + delivery_event_id: number; + line_index: number; + delivered_milli: string; + item: Impact['item']; +}; +const milli = (value: string) => { + const q = BigInt(value); + return `${q / 1000n},${(q % 1000n).toString().padStart(3, '0')}`; +}; +const states: Record = { + prepared: 'Por confirmar', + confirmed: 'Confirmada', + withdrawn: 'Retirada', + rejected: 'Recusada', +}; export function WarehouseReturnImpact({ impact: p }: { impact: Impact }) { - return

Stock físico: {milli(p.physical_before)} → {milli(p.physical_after)}. Devolução: {milli(p.return_quantity_milli)} {p.item.unit}. Entrega ainda não devolvida: {milli(p.not_returned_before)} → {milli(p.not_returned_after)}. {p.item.code} · {p.warehouse.code} · Saída original #{p.original_movement_id}.

; + return ( +

+ Stock físico: {milli(p.physical_before)} → {milli(p.physical_after)} + . Devolução: {milli(p.return_quantity_milli)} {p.item.unit}. Entrega + ainda não devolvida: {milli(p.not_returned_before)} →{' '} + {milli(p.not_returned_after)}. {p.item.code} · {p.warehouse.code} · + Saída original #{p.original_movement_id}. +

+ ); } -async function api(url: string, body?: object, signal?: AbortSignal): Promise { - const token = document.cookie.split('; ').find((c) => c.startsWith('XSRF-TOKEN='))?.slice(11); - const response = await fetch(url, { method: body ? 'POST' : 'GET', credentials: 'same-origin', signal, headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', ...(token ? { 'X-XSRF-TOKEN': decodeURIComponent(token) } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}) }); - const result = await response.json(); if (!response.ok) throw new Error(result.errors ? Object.values(result.errors).flat().join(' ') : result.message || `Pedido recusado (${response.status})`); return result; +async function api( + url: string, + body?: object, + signal?: AbortSignal, +): Promise { + const token = document.cookie + .split('; ') + .find((c) => c.startsWith('XSRF-TOKEN=')) + ?.slice(11); + const response = await fetch(url, { + method: body ? 'POST' : 'GET', + credentials: 'same-origin', + signal, + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'X-Requested-With': 'XMLHttpRequest', + ...(token ? { 'X-XSRF-TOKEN': decodeURIComponent(token) } : {}), + }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + const result = await response.json(); + if (!response.ok) + throw new Error( + result.errors + ? Object.values(result.errors).flat().join(' ') + : result.message || `Pedido recusado (${response.status})`, + ); + return result; } -export default function WarehouseReturns({ requestId, actorId, canPrepare, canConfirm, canWithdraw=false }: { requestId: number | null; actorId: number; canPrepare: boolean; canConfirm: boolean; canWithdraw?:boolean }) { - const [history, setHistory] = useState<{ rows: Row[]; pagination: Page } | null>(null), [sources, setSources] = useState<{ options: Option[]; pagination: Page } | null>(null); - const [page, setPage] = useState(1), [sourcePage, setSourcePage] = useState(1), [state, setState] = useState('all'), [reload, setReload] = useState(0), [error, setError] = useState(''), [busy, setBusy] = useState(false), [preview, setPreview] = useState<{ id: number; impact: Impact; state?:string } | null>(null); - const generation = useRef(0), command = useRef<{ data: string; key: string } | null>(null); - useEffect(() => { const n = ++generation.current, abort = new AbortController(); setHistory(null); setSources(null); setError(''); - Promise.all([api<{ rows: Row[]; pagination: Page }>(`/api/stock-returns?page=${page}&state=${state}`, undefined, abort.signal), requestId ? api<{ options: Option[]; pagination: Page }>(`/api/stock-returns/sources?request_id=${requestId}&source_page=${sourcePage}`, undefined, abort.signal) : Promise.resolve(null)]) - .then(([h, s]) => { if (n === generation.current) { setHistory(h); setSources(s); } }).catch((e: Error) => { if (!abort.signal.aborted && n === generation.current) setError(e.message); }); - return () => { generation.current++; abort.abort(); }; +export default function WarehouseReturns({ + requestId, + actorId, + canPrepare, + canConfirm, + canWithdraw = false, +}: { + requestId: number | null; + actorId: number; + canPrepare: boolean; + canConfirm: boolean; + canWithdraw?: boolean; +}) { + const [history, setHistory] = useState<{ + rows: Row[]; + pagination: Page; + } | null>(null), + [sources, setSources] = useState<{ + options: Option[]; + pagination: Page; + } | null>(null); + const [page, setPage] = useState(1), + [sourcePage, setSourcePage] = useState(1), + [state, setState] = useState('all'), + [reload, setReload] = useState(0), + [error, setError] = useState(''), + [busy, setBusy] = useState(false), + [preview, setPreview] = useState<{ + id: number; + impact: Impact; + state?: string; + } | null>(null); + const generation = useRef(0), + command = useRef<{ data: string; key: string } | null>(null); + useEffect(() => { + const n = ++generation.current, + abort = new AbortController(); + setHistory(null); + setSources(null); + setError(''); + Promise.all([ + api<{ rows: Row[]; pagination: Page }>( + `/api/stock-returns?page=${page}&state=${state}`, + undefined, + abort.signal, + ), + requestId + ? api<{ options: Option[]; pagination: Page }>( + `/api/stock-returns/sources?request_id=${requestId}&source_page=${sourcePage}`, + undefined, + abort.signal, + ) + : Promise.resolve(null), + ]) + .then(([h, s]) => { + if (n === generation.current) { + setHistory(h); + setSources(s); + } + }) + .catch((e: Error) => { + if (!abort.signal.aborted && n === generation.current) + setError(e.message); + }); + return () => { + generation.current++; + abort.abort(); + }; }, [requestId, actorId, page, sourcePage, state, reload]); - useEffect(() => { setPreview(null); command.current = null; setPage(1); setSourcePage(1); }, [requestId, actorId]); - async function prepare(e: FormEvent) { e.preventDefault(); const n = generation.current; setBusy(true); setError(''); const fields = Object.fromEntries(new FormData(e.currentTarget)), choice = sources?.options.find((o) => `${o.delivery_event_id}:${o.line_index}` === fields.source); - if (!choice) { setError('Seleccione uma entrega recebida.'); setBusy(false); return; } - const body = { delivery_event_id: choice.delivery_event_id, line_index: choice.line_index, quantity: fields.quantity, declared_unused: fields.declared_unused === 'on', reason: fields.reason, evidence: fields.evidence }, data = JSON.stringify(body); - if (command.current?.data !== data) command.current = { data, key: crypto.randomUUID() }; - try { const p = await api<{ id: number; impact: Impact }>('/api/stock-returns/prepare', { ...body, operation_key: command.current.key }); if (n === generation.current) { setPreview(p); setReload((x) => x + 1); } } catch (err) { if (n === generation.current) setError((err as Error).message); } finally { setBusy(false); } + useEffect(() => { + setPreview(null); + command.current = null; + setPage(1); + setSourcePage(1); + }, [requestId, actorId]); + async function prepare(e: FormEvent) { + e.preventDefault(); + const n = generation.current; + setBusy(true); + setError(''); + const fields = Object.fromEntries(new FormData(e.currentTarget)), + choice = sources?.options.find( + (o) => + `${o.delivery_event_id}:${o.line_index}` === fields.source, + ); + if (!choice) { + setError('Seleccione uma entrega recebida.'); + setBusy(false); + return; + } + const body = { + delivery_event_id: choice.delivery_event_id, + line_index: choice.line_index, + quantity: fields.quantity, + declared_unused: fields.declared_unused === 'on', + reason: fields.reason, + evidence: fields.evidence, + }, + data = JSON.stringify(body); + if (command.current?.data !== data) + command.current = { data, key: crypto.randomUUID() }; + try { + const p = await api<{ id: number; impact: Impact }>( + '/api/stock-returns/prepare', + { ...body, operation_key: command.current.key }, + ); + if (n === generation.current) { + setPreview(p); + setReload((x) => x + 1); + } + } catch (err) { + if (n === generation.current) setError((err as Error).message); + } finally { + setBusy(false); + } } - async function confirm(e: FormEvent, row: Row) { e.preventDefault(); const n = generation.current; setBusy(true); setError(''); const fields = Object.fromEntries(new FormData(e.currentTarget)); - try { await api(`/api/stock-returns/${row.prepared_id}/confirm`, { version: 1, received_in_warehouse: fields.received_in_warehouse === 'on', reason: fields.reason }); if (n === generation.current) { setPreview(null); setReload((x) => x + 1); } } catch (err) { if (n === generation.current) setError((err as Error).message); } finally { setBusy(false); } + async function confirm(e: FormEvent, row: Row) { + e.preventDefault(); + const n = generation.current; + setBusy(true); + setError(''); + const fields = Object.fromEntries(new FormData(e.currentTarget)); + try { + await api(`/api/stock-returns/${row.prepared_id}/confirm`, { + version: 1, + received_in_warehouse: fields.received_in_warehouse === 'on', + reason: fields.reason, + }); + if (n === generation.current) { + setPreview(null); + setReload((x) => x + 1); + } + } catch (err) { + if (n === generation.current) setError((err as Error).message); + } finally { + setBusy(false); + } } - async function close(e:FormEvent,row:Row,action:'withdraw'|'reject'){e.preventDefault();const n=generation.current;setBusy(true);setError('');const fields=Object.fromEntries(new FormData(e.currentTarget));try{await api(`/api/stock-returns/${row.prepared_id}/${action}`,{version:1,reason:fields.reason});if(n===generation.current){setPreview(null);setReload(x=>x+1);}}catch(err){if(n===generation.current)setError((err as Error).message);}finally{setBusy(false);}} - return <>
- {requestId ? 'Consultar a requisição de origem' : 'Voltar ao Painel Inicial'} - {error &&

{error}

} - {canPrepare && requestId && sources &&
-