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:
2026-11-30 23:01:42 +02:00
co-authored by Claude Opus 5.5
parent 9f719695e3
commit ec934455e7
148 changed files with 9455 additions and 2413 deletions
-1
View File
@@ -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
+2 -2
View File
@@ -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')
+4 -4
View File
@@ -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));
}
}
+45 -28
View File
@@ -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']);
}
}
+21 -10
View File
@@ -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]);
});
}
}
+2 -1
View File
@@ -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;
+33 -21
View File
@@ -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];
});
}