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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 17:38:46 +02:00
co-authored by Claude Opus 5.5
321 changed files with 12781 additions and 5528 deletions
+1 -1
View File
@@ -267,7 +267,7 @@ final class AgreementOrderLimits
}
$root = base_path('packages/inventory-write/development');
$bytes = file_get_contents($root.'/manifest.json');
if ($bytes === false || ! hash_equals('90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38', hash('sha256', $bytes))) {
if ($bytes === false || ! hash_equals('c7ba216ff4f61f1435f7fc7ac423bf56dc729c228aa3acb165b960675cb96dbb', hash('sha256', $bytes))) {
throw new \LogicException('Artefacto aritmético incompatível.');
}
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
-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
+17 -4
View File
@@ -123,8 +123,8 @@ class ExternalPaymentWorkflow
return $existing;
}
if ($reference === '' || trim($data['evidence_reference']) === '' || $data['paid_on'] < (string) $invoice->issued_on || $data['paid_on'] > today()->format('Y-m-d') || substr($data['paid_on'], 0, 4) !== now()->format('Y')) {
$this->invalid('Referência, evidência e data válida do exercício actual são obrigatórias.');
if ($reference === '' || trim($data['evidence_reference']) === '' || $data['paid_on'] < (string) $invoice->issued_on || $data['paid_on'] > today()->format('Y-m-d') || ! self::withinFiscalWindow((string) $data['paid_on'])) {
$this->invalid('Referência, evidência e data válida do exercício actual ou anterior são obrigatórias.');
}
$bank = $this->bank($user, $invoice, (int) $data['supplier_bank_detail_id'], $amount);
$payment = ExternalPayment::query()->create(['tenant_id' => $user->tenant_id, 'invoice_id' => $invoice->id, 'supplier_bank_detail_id' => $bank->id, 'created_by' => $user->id, 'amount_minor' => $amount, 'currency' => $bank->currency, 'paid_on' => $data['paid_on'], 'external_reference' => $reference, 'reference_hash' => $referenceHash, 'payload_hash' => $hash, 'evidence_reference' => trim($data['evidence_reference']), 'bank_snapshot' => ['bank_id' => $bank->id, 'revision' => $bank->revision, 'bank_name' => $bank->bank_name, 'country' => $bank->country, 'currency' => $bank->currency, 'beneficiary' => $bank->beneficiary, 'account_identifier' => $bank->account_identifier, 'reviewer_ids' => SupplierBankReview::query()->where('supplier_bank_detail_id', $bank->id)->pluck('reviewed_by')->all(), 'development_only' => app(StandaloneRuntime::class)->syntheticOnly(), 'bank_transfer_executed' => false]]);
@@ -159,8 +159,8 @@ class ExternalPaymentWorkflow
$order = PurchaseOrder::query()->findOrFail($invoice->purchase_order_id);
app(ConflictGuard::class)->assertProcess(Requisition::query()->findOrFail($order->requisition_id), $order->supplier_id, $user);
if ($decision === 'confirmed') {
if (substr((string) $payment->paid_on, 0, 4) !== now()->format('Y')) {
$this->invalid('Conferência entre exercícios não suportada.');
if (! self::withinFiscalWindow((string) $payment->paid_on)) {
$this->invalid('Só se conferem pagamentos do exercício actual ou do anterior.');
}
$this->bank($user, $invoice, $payment->supplier_bank_detail_id, $payment->amount_minor);
$author = User::query()->where('tenant_id', $user->tenant_id)->lockForUpdate()->find($payment->created_by);
@@ -184,6 +184,19 @@ class ExternalPaymentWorkflow
});
}
/**
* Decisão de 01/12/2026: um pagamento do exercício anterior pode ainda ser registado e conferido
* no ano novo (ex.: transferência de 30/12 conferida a 2/1). Não toca no orçamento: o consumo
* foi lançado na validação da factura. A data do pagamento mantém-se a original.
*/
public static function withinFiscalWindow(string $paidOn): bool
{
$year = (int) substr($paidOn, 0, 4);
$current = (int) now()->format('Y');
return $year === $current || $year === $current - 1;
}
private function audit(User $user, Invoice $invoice, ExternalPayment $payment, string $action): void
{
$order = PurchaseOrder::query()->findOrFail($invoice->purchase_order_id);
+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')
+81
View File
@@ -0,0 +1,81 @@
<?php
namespace App\Services;
use Illuminate\Routing\Route;
use Illuminate\Routing\Router;
/** Módulos do produto fora do núcleo da v1, ligados ou desligados por instalação (config/modules.php). */
final class ProductModules
{
/** @var list<string>|null */
private ?array $disabledPaths = null;
public function __construct(private readonly Router $router) {}
public function enabled(string $module): bool
{
return (bool) config('modules.enabled.'.$module, false);
}
/** @return array<string, bool> */
public function states(): array
{
return array_map(fn ($value) => (bool) $value, (array) config('modules.enabled', []));
}
/** O módulo a que a rota pertence, ou null quando é do núcleo. */
public function moduleFor(Route $route): ?string
{
$controller = ltrim((string) $route->getControllerClass(), '\\');
$uri = trim($route->uri(), '/');
foreach ((array) config('modules.controllers', []) as $module => $controllers) {
if ($controller !== '' && in_array($controller, (array) $controllers, true)) {
return (string) $module;
}
}
foreach ((array) config('modules.paths', []) as $module => $prefixes) {
foreach ((array) $prefixes as $prefix) {
if ($uri === $prefix || str_starts_with($uri, $prefix.'/')) {
return (string) $module;
}
}
}
return null;
}
public function allows(Route $route): bool
{
$module = $this->moduleFor($route);
return $module === null || $this->enabled($module);
}
/**
* Caminhos (parte fixa da URL) servidos só por módulos desligados, para esconder entradas de menu.
*
* @return list<string>
*/
public function disabledPaths(): array
{
if ($this->disabledPaths !== null) {
return $this->disabledPaths;
}
$disabled = [];
$enabled = [];
foreach ($this->router->getRoutes()->getRoutes() as $route) {
if (! in_array('GET', $route->methods(), true)) {
continue;
}
$path = '/'.trim(preg_replace('/\/?\{.*$/', '', $route->uri()) ?? '', '/');
if ($this->allows($route)) {
$enabled[$path] = true;
} else {
$disabled[$path] = true;
}
}
return $this->disabledPaths = array_values(array_diff(array_keys($disabled), array_keys($enabled)));
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ final class ReceiptStockMovement
abort_unless(($connection->getDriverName() === 'sqlite' && $connection->getDatabaseName() === ':memory:')
|| ($connection->getDriverName() === 'pgsql' && preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $connection->getDatabaseName())), 503, 'Base QA isolada obrigatória.');
$root = base_path('packages/inventory-write/development');
$pin = '90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38';
$pin = 'c7ba216ff4f61f1435f7fc7ac423bf56dc729c228aa3acb165b960675cb96dbb';
$files[] = 'src/QuantityConversion.php';
} else {
$conversion->assertLegacyCompatible();
+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];
});
}
+3
View File
@@ -39,6 +39,9 @@ class WorkContext
if (config('work_context.composition') === 'sgf' && is_array($keys)) {
$keys = array_diff($keys, ['people.third_party']);
}
if (! app(ProductModules::class)->enabled('pessoas') && is_array($keys)) {
$keys = array_diff($keys, ['people.internal', 'people.third_party']);
}
return is_array($keys) ? array_values(array_intersect(array_keys(self::OPTIONS), $keys)) : [];
}