Aplicar Pint e formatação de frontend; delimitar o âmbito do lint
Só formatação automática (pint, vp check --fix), sem alterar comportamento. Excluídos da formatação os registos e artefactos com bytes fixos: docs/, integrations/, storage/, tmp/, output/, resources/data/, tests/Fixtures/, compras-release.json e AGENTS*.md. Scripts operacionais, integrations e auxiliares de teste ficam fora do lint (usam new Function; limpeza na fase 2). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,49 +5,60 @@ namespace App\Http\Controllers;
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
use App\Services\OrganizationAccess;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tempo\Inventory\InventoryReadSession;
|
||||
|
||||
final class CommonStockReadController extends Controller
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
// Native authority, reloaded on every request; no SGF grants or identity assumptions.
|
||||
$user=User::query()->findOrFail($this->staffIdentity($request)->id);
|
||||
abort_unless($user->tenant_id!==null && $user->hasFunctions([PurchasingRole::Admin,PurchasingRole::Warehouse,PurchasingRole::Procurement,PurchasingRole::Finance])
|
||||
&& !app(OrganizationAccess::class)->maintenanceOnly($user),403);
|
||||
$d=$request->validate(['view'=>'sometimes|in:items,warehouses,balances,movements','search'=>'nullable|string|max:100',
|
||||
'warehouse_id'=>'sometimes|integer|min:1','page'=>'sometimes|integer|min:1|max:100000','per_page'=>'sometimes|integer|min:1|max:100','snapshot'=>'sometimes|string|max:8192']);
|
||||
abort_if(array_diff(array_keys($request->query()),array_keys($d))!==[],422);
|
||||
$filters=['view'=>$d['view']??'balances','search'=>$d['search']??'','warehouse_id'=>isset($d['warehouse_id'])?(int)$d['warehouse_id']:null,
|
||||
'page'=>(int)($d['page']??1),'per_page'=>(int)($d['per_page']??25)];
|
||||
$binding=config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id);
|
||||
if(!$binding)return response()->json(['status'=>'unavailable','message'=>'Fonte autorizada de stock ainda não ligada a este contexto.'],503)->header('Cache-Control','no-store');
|
||||
abort_unless(app()->environment('testing')&&DB::connection()->getDriverName()==='pgsql',403);
|
||||
$identity=DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D',$identity->name,$m)
|
||||
&& $identity->role==='stock_read_qa_'.$m[1] && (int)$identity->port===55439
|
||||
&& preg_match('/^[a-f0-9]{12}$/D',(string)config('stock_read.qa_run'))
|
||||
&& $identity->cluster==='sgf_modular_regression_'.config('stock_read.qa_run'),403);
|
||||
abort_unless(preg_match('/^sgf_stock_read_[a-f0-9]{12}$/D',$binding['schema']??'')&&($binding['append_only']??false)===true
|
||||
&& ($binding['source_tenant_id']??null)===(int)$user->tenant_id,503,'Fonte de stock incompatível.');
|
||||
if($filters['warehouse_id']!==null)abort_unless(in_array($filters['warehouse_id'],$binding['warehouse_ids'],true),403);
|
||||
$root=base_path('packages/inventory-read/releases/0.1.0');
|
||||
$bytes=is_file($root.'/manifest.json')?file_get_contents($root.'/manifest.json'):false;
|
||||
abort_unless(is_string($bytes)&&hash_equals(config('stock_read.package_manifest_sha256'),hash('sha256',$bytes)),503,'Pacote de consulta incompatível.');
|
||||
$manifest=json_decode($bytes,true,512,JSON_THROW_ON_ERROR);
|
||||
foreach(['bootstrap.php','src/InventoryReader.php','src/InventoryReadSession.php'] as $file) {
|
||||
$actual=is_file($root.'/'.$file)?hash_file('sha256',$root.'/'.$file):false;
|
||||
abort_unless(is_string($actual)&&isset($manifest['files'][$file])&&hash_equals($manifest['files'][$file],$actual),503,'Pacote de consulta incompatível.');
|
||||
$user = User::query()->findOrFail($this->staffIdentity($request)->id);
|
||||
abort_unless($user->tenant_id !== null && $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance])
|
||||
&& ! app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
$d = $request->validate(['view' => 'sometimes|in:items,warehouses,balances,movements', 'search' => 'nullable|string|max:100',
|
||||
'warehouse_id' => 'sometimes|integer|min:1', 'page' => 'sometimes|integer|min:1|max:100000', 'per_page' => 'sometimes|integer|min:1|max:100', 'snapshot' => 'sometimes|string|max:8192']);
|
||||
abort_if(array_diff(array_keys($request->query()), array_keys($d)) !== [], 422);
|
||||
$filters = ['view' => $d['view'] ?? 'balances', 'search' => $d['search'] ?? '', 'warehouse_id' => isset($d['warehouse_id']) ? (int) $d['warehouse_id'] : null,
|
||||
'page' => (int) ($d['page'] ?? 1), 'per_page' => (int) ($d['per_page'] ?? 25)];
|
||||
$binding = config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id);
|
||||
if (! $binding) {
|
||||
return response()->json(['status' => 'unavailable', 'message' => 'Fonte autorizada de stock ainda não ligada a este contexto.'], 503)->header('Cache-Control', 'no-store');
|
||||
}
|
||||
abort_unless(app()->environment('testing') && DB::connection()->getDriverName() === 'pgsql', 403);
|
||||
$identity = DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D', $identity->name, $m)
|
||||
&& $identity->role === 'stock_read_qa_'.$m[1] && (int) $identity->port === 55439
|
||||
&& preg_match('/^[a-f0-9]{12}$/D', (string) config('stock_read.qa_run'))
|
||||
&& $identity->cluster === 'sgf_modular_regression_'.config('stock_read.qa_run'), 403);
|
||||
abort_unless(preg_match('/^sgf_stock_read_[a-f0-9]{12}$/D', $binding['schema'] ?? '') && ($binding['append_only'] ?? false) === true
|
||||
&& ($binding['source_tenant_id'] ?? null) === (int) $user->tenant_id, 503, 'Fonte de stock incompatível.');
|
||||
if ($filters['warehouse_id'] !== null) {
|
||||
abort_unless(in_array($filters['warehouse_id'], $binding['warehouse_ids'], true), 403);
|
||||
}
|
||||
$root = base_path('packages/inventory-read/releases/0.1.0');
|
||||
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
|
||||
abort_unless(is_string($bytes) && hash_equals(config('stock_read.package_manifest_sha256'), hash('sha256', $bytes)), 503, 'Pacote de consulta incompatível.');
|
||||
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
foreach (['bootstrap.php', 'src/InventoryReader.php', 'src/InventoryReadSession.php'] as $file) {
|
||||
$actual = is_file($root.'/'.$file) ? hash_file('sha256', $root.'/'.$file) : false;
|
||||
abort_unless(is_string($actual) && isset($manifest['files'][$file]) && hash_equals($manifest['files'][$file], $actual), 503, 'Pacote de consulta incompatível.');
|
||||
}
|
||||
require_once $root.'/bootstrap.php';
|
||||
$fingerprint=hash('sha256',json_encode(['compras',$user->tenant_id,$user->id,$request->session()->get('work_context'),$binding,array_diff_key($filters,['page'=>true])],JSON_THROW_ON_ERROR));
|
||||
try { $result=(new \Tempo\Inventory\InventoryReadSession(DB::connection()))->read($binding,$fingerprint,$filters,$d['snapshot']??null); }
|
||||
catch(\Illuminate\Database\QueryException $e){
|
||||
if(!in_array($e->errorInfo[0]??null,['42P01','42703','42883','57014'],true))throw $e;
|
||||
return response()->json(['status'=>'unavailable','message'=>'A fonte de stock está indisponível ou incompatível. Actualize a consulta mais tarde.'],503)->header('Cache-Control','no-store');
|
||||
$fingerprint = hash('sha256', json_encode(['compras', $user->tenant_id, $user->id, $request->session()->get('work_context'), $binding, array_diff_key($filters, ['page' => true])], JSON_THROW_ON_ERROR));
|
||||
try {
|
||||
$result = (new InventoryReadSession(DB::connection()))->read($binding, $fingerprint, $filters, $d['snapshot'] ?? null);
|
||||
} catch (QueryException $e) {
|
||||
if (! in_array($e->errorInfo[0] ?? null, ['42P01', '42703', '42883', '57014'], true)) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return response()->json(['status' => 'unavailable', 'message' => 'A fonte de stock está indisponível ou incompatível. Actualize a consulta mais tarde.'], 503)->header('Cache-Control','no-store');
|
||||
}
|
||||
|
||||
return response()->json($result)->header('Cache-Control','no-store');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,14 +43,21 @@ final class WarehouseReturnController extends Controller
|
||||
}
|
||||
|
||||
/** @param callable():array<string,mixed> $run */
|
||||
private function response(callable $run,bool $readOnly=false): JsonResponse
|
||||
private function response(callable $run, bool $readOnly = false): JsonResponse
|
||||
{
|
||||
try {
|
||||
$result=$readOnly?DB::transaction(function()use($run){if(DB::getDriverName()==='pgsql'&&DB::transactionLevel()===1)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');return $run();}):$run();
|
||||
$result = $readOnly ? DB::transaction(function () use ($run) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
|
||||
return $run();
|
||||
}) : $run();
|
||||
|
||||
return response()->json($result)->header('Cache-Control', 'no-store');
|
||||
} catch (QueryException $e) {
|
||||
if (($e->errorInfo[0] ?? null) === '55P03') {
|
||||
return response()->json(['code'=>'warehouse_return_busy','message' => 'Devolução ocupada. Aguarde e repita manualmente a conferência.'], 423)->header('Cache-Control', 'no-store');
|
||||
return response()->json(['code' => 'warehouse_return_busy', 'message' => 'Devolução ocupada. Aguarde e repita manualmente a conferência.'], 423)->header('Cache-Control', 'no-store');
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
@@ -83,12 +90,25 @@ final class WarehouseReturnController extends Controller
|
||||
$d['version'] = (int) $d['version'];
|
||||
$d['received_in_warehouse'] = true;
|
||||
|
||||
return $this->response(fn () => $flow->confirm($this->actor($r),$id,$d));
|
||||
return $this->response(fn () => $flow->confirm($this->actor($r), $id, $d));
|
||||
}
|
||||
public function withdraw(Request $r,int $id,WarehouseReturns $flow): JsonResponse {return $this->close($r,$id,$flow,'withdrawn');}
|
||||
public function reject(Request $r,int $id,WarehouseReturns $flow): JsonResponse {return $this->close($r,$id,$flow,'rejected');}
|
||||
private function close(Request $r,int $id,WarehouseReturns $flow,string $state): JsonResponse
|
||||
|
||||
public function withdraw(Request $r, int $id, WarehouseReturns $flow): JsonResponse
|
||||
{
|
||||
$d=$r->validate(['version'=>'required|integer|min:1','reason'=>'required|string|min:10|max:1000']);abort_if(array_diff(array_keys($r->all()),array_keys($d))!==[],422);$d['version']=(int)$d['version'];return $this->response(fn()=>$flow->close($this->actor($r),$id,$d,$state));
|
||||
return $this->close($r, $id, $flow, 'withdrawn');
|
||||
}
|
||||
|
||||
public function reject(Request $r, int $id, WarehouseReturns $flow): JsonResponse
|
||||
{
|
||||
return $this->close($r, $id, $flow, 'rejected');
|
||||
}
|
||||
|
||||
private function close(Request $r, int $id, WarehouseReturns $flow, string $state): JsonResponse
|
||||
{
|
||||
$d = $r->validate(['version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:1000']);
|
||||
abort_if(array_diff(array_keys($r->all()), array_keys($d)) !== [], 422);
|
||||
$d['version'] = (int) $d['version'];
|
||||
|
||||
return $this->response(fn () => $flow->close($this->actor($r), $id, $d, $state));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,13 +4,14 @@ namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
/**
|
||||
* @property array<string,mixed> $data
|
||||
* @property array<string,mixed> $snapshot
|
||||
* @property int $version
|
||||
* @property string $record_key
|
||||
* @property \Illuminate\Support\Carbon $created_at
|
||||
* @property Carbon $created_at
|
||||
*/
|
||||
class SupplyRecord extends Model
|
||||
{
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tempo\Inventory\IssueMovementWriter;
|
||||
|
||||
final class StockIssueMovement
|
||||
{
|
||||
public function for(User $actor): \Tempo\Inventory\IssueMovementWriter
|
||||
public function for(User $actor): IssueMovementWriter
|
||||
{
|
||||
$root=base_path('packages/inventory-issue/releases/0.1.0');
|
||||
$bytes=is_file($root.'/manifest.json')?file_get_contents($root.'/manifest.json'):false;
|
||||
if(!is_string($bytes)||!hash_equals('3c24d9e9fb99bfbb274077495c3a42ddb7eccab06b5c6a956cd739b2bc9b56f0',hash('sha256',$bytes)))throw new \LogicException('Pacote de saída incompatível.');
|
||||
$m=json_decode($bytes,true,512,JSON_THROW_ON_ERROR);
|
||||
foreach(['bootstrap.php','src/IssueMovementWriter.php'] as $f) {
|
||||
$actual=is_file($root.'/'.$f)?hash_file('sha256',$root.'/'.$f):false;
|
||||
if(!is_string($actual)||!hash_equals($m['files'][$f]??'',$actual))throw new \LogicException('Pacote de saída alterado.');
|
||||
$root = base_path('packages/inventory-issue/releases/0.1.0');
|
||||
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
|
||||
if (! is_string($bytes) || ! hash_equals('3c24d9e9fb99bfbb274077495c3a42ddb7eccab06b5c6a956cd739b2bc9b56f0', hash('sha256', $bytes))) {
|
||||
throw new \LogicException('Pacote de saída incompatível.');
|
||||
}
|
||||
$m = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
foreach (['bootstrap.php', 'src/IssueMovementWriter.php'] as $f) {
|
||||
$actual = is_file($root.'/'.$f) ? hash_file('sha256', $root.'/'.$f) : false;
|
||||
if (! is_string($actual) || ! hash_equals($m['files'][$f] ?? '', $actual)) {
|
||||
throw new \LogicException('Pacote de saída alterado.');
|
||||
}
|
||||
}
|
||||
require_once $root.'/bootstrap.php';
|
||||
$schema=match(DB::connection()->getDriverName()){'pgsql'=>'public','sqlite'=>'main','mysql','mariadb'=>DB::connection()->getDatabaseName(),default=>throw new \LogicException('Driver não suportado.')};
|
||||
return new \Tempo\Inventory\IssueMovementWriter(DB::connection(),$schema,(int)$actor->tenant_id,(int)$actor->id,function()use($actor){app(CurrentActor::class)->lock($actor,[PurchasingRole::Warehouse]);});
|
||||
$schema = match (DB::connection()->getDriverName()) {
|
||||
'pgsql' => 'public','sqlite' => 'main','mysql','mariadb' => DB::connection()->getDatabaseName(),default => throw new \LogicException('Driver não suportado.')
|
||||
};
|
||||
|
||||
return new IssueMovementWriter(DB::connection(), $schema, (int) $actor->tenant_id, (int) $actor->id, function () use ($actor) {
|
||||
app(CurrentActor::class)->lock($actor, [PurchasingRole::Warehouse]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<string,mixed> $d
|
||||
* @param array<string,mixed> $d
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function close(User $actor,int $id,array $d,string $state): array
|
||||
public function close(User $actor, int $id, array $d, string $state): array
|
||||
{
|
||||
abort_unless(in_array($state,['withdrawn','rejected'],true),422);
|
||||
$action=$state==='withdrawn'?'prepare':'confirm';$this->authorize($actor,$action);
|
||||
return DB::transaction(function()use($actor,$id,$d,$state,$action){
|
||||
$actor=$this->lock($actor,$action);$p=SupplyRecord::query()->where('kind','warehouse_return')->where('version',1)->lockForUpdate()->findOrFail($id);$this->request($p->snapshot['source']['request_id']);
|
||||
abort_unless($state==='withdrawn'?$p->created_by===$actor->id:$p->created_by!==$actor->id,403,'Retirada pertence ao preparador; recusa exige conferência independente.');
|
||||
$done=SupplyRecord::query()->where('kind','warehouse_return')->where('record_key',$p->record_key)->where('version',2)->first();
|
||||
if($done){abort_unless($done->state===$state,409,'A proposta já tem outra decisão terminal.');return ['id'=>$done->id,'state'=>$done->state,'replayed'=>true];}
|
||||
abort_unless($d['version']===1,409,'Versão de proposta desactualizada.');$book=app(StockWorkflow::class)->balance($p->stock_item_id,$p->warehouse_id);
|
||||
$closed=SupplyRecord::query()->create(['tenant_id'=>$actor->tenant_id,'kind'=>'warehouse_return','record_key'=>$p->record_key,'version'=>2,'state'=>$state,'stock_item_id'=>$p->stock_item_id,'warehouse_id'=>$p->warehouse_id,'created_by'=>$actor->id,'data'=>['prepared_id'=>$p->id,'action'=>$state,'reason'=>$d['reason']],'snapshot'=>['source'=>$p->snapshot['source'],'before'=>$book['quantity'],'after'=>$book['quantity'],'preparer_id'=>$p->created_by],'reason'=>$d['reason'],'operation_key'=>(string)Str::uuid(),'input_hash'=>$this->hash($d+['action'=>$state]),'created_at'=>now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor,'warehouse_return.'.$state,null,null,['record_id'=>$closed->id,'declaration_id'=>$p->id,'reason'=>$d['reason'],'before'=>$book['quantity'],'after'=>$book['quantity'],'physical_effect'=>0]);
|
||||
return ['id'=>$closed->id,'state'=>$state,'replayed'=>false];
|
||||
abort_unless(in_array($state, ['withdrawn', 'rejected'], true), 422);
|
||||
$action = $state === 'withdrawn' ? 'prepare' : 'confirm';
|
||||
$this->authorize($actor, $action);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $d, $state, $action) {
|
||||
$actor = $this->lock($actor, $action);
|
||||
$p = SupplyRecord::query()->where('kind', 'warehouse_return')->where('version', 1)->lockForUpdate()->findOrFail($id);
|
||||
$this->request($p->snapshot['source']['request_id']);
|
||||
abort_unless($state === 'withdrawn' ? $p->created_by === $actor->id : $p->created_by !== $actor->id, 403, 'Retirada pertence ao preparador; recusa exige conferência independente.');
|
||||
$done = SupplyRecord::query()->where('kind', 'warehouse_return')->where('record_key', $p->record_key)->where('version', 2)->first();
|
||||
if ($done) {
|
||||
abort_unless($done->state === $state, 409, 'A proposta já tem outra decisão terminal.');
|
||||
|
||||
return ['id' => $done->id, 'state' => $done->state, 'replayed' => true];
|
||||
}
|
||||
abort_unless($d['version'] === 1, 409, 'Versão de proposta desactualizada.');
|
||||
$book = app(StockWorkflow::class)->balance($p->stock_item_id, $p->warehouse_id);
|
||||
$closed = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'warehouse_return', 'record_key' => $p->record_key, 'version' => 2, 'state' => $state, 'stock_item_id' => $p->stock_item_id, 'warehouse_id' => $p->warehouse_id, 'created_by' => $actor->id, 'data' => ['prepared_id' => $p->id, 'action' => $state, 'reason' => $d['reason']], 'snapshot' => ['source' => $p->snapshot['source'], 'before' => $book['quantity'], 'after' => $book['quantity'], 'preparer_id' => $p->created_by], 'reason' => $d['reason'], 'operation_key' => (string) Str::uuid(), 'input_hash' => $this->hash($d + ['action' => $state]), 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'warehouse_return.'.$state, null, null, ['record_id' => $closed->id, 'declaration_id' => $p->id, 'reason' => $d['reason'], 'before' => $book['quantity'], 'after' => $book['quantity'], 'physical_effect' => 0]);
|
||||
|
||||
return ['id' => $closed->id, 'state' => $state, 'replayed' => false];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user