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:
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Services\ProductModules;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Database\Migrations\Migrator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Laravel\Fortify\Features;
|
||||
use Symfony\Component\Process\Process;
|
||||
use Throwable;
|
||||
|
||||
/** Conferência da instalação de produção (fase 5). Só lê configuração e esquema; não altera dados. */
|
||||
class SgcProductionCheck extends Command
|
||||
{
|
||||
protected $signature = 'sgc:production-check';
|
||||
|
||||
protected $description = 'Conferir se a instalação está pronta para produção (ambiente, base de dados, migrações, MFA, ficheiros); não altera dados';
|
||||
|
||||
private int $failures = 0;
|
||||
|
||||
public function handle(Migrator $migrator): int
|
||||
{
|
||||
$this->check(app()->environment('production'), 'APP_ENV=production');
|
||||
$this->check(! config('app.debug'), 'APP_DEBUG=false');
|
||||
$this->check(filled(config('app.key')), 'APP_KEY definida');
|
||||
$https = str_starts_with((string) config('app.url'), 'https://');
|
||||
$this->check($https, 'APP_URL em https');
|
||||
$this->check(! $https || config('session.secure') === true, 'SESSION_SECURE_COOKIE=true');
|
||||
$this->check(! in_array(config('session.driver'), ['array', 'cookie'], true), 'Sessões persistentes (SESSION_DRIVER)');
|
||||
$this->check(config('cache.default') !== 'array', 'Cache persistente (CACHE_STORE)');
|
||||
|
||||
$this->database($migrator);
|
||||
|
||||
$this->check(Features::enabled(Features::twoFactorAuthentication()), 'MFA ligado (SGC_TWO_FACTOR_ENABLED=true)');
|
||||
$this->check(array_filter((array) config('mfa.required_functions')) !== [], 'Funções com MFA obrigatório (SGC_MFA_REQUIRED_FUNCTIONS)');
|
||||
|
||||
foreach ([storage_path('app/private'), storage_path('logs'), storage_path('framework/sessions'), base_path('bootstrap/cache')] as $path) {
|
||||
$this->check(is_dir($path) && is_writable($path), 'Pasta gravável: '.str_replace(base_path().'/', '', $path));
|
||||
}
|
||||
|
||||
$runtime = new Process([PHP_BINARY, base_path('scripts/check-runtime-packages.php')], base_path());
|
||||
$runtime->run();
|
||||
$this->check($runtime->isSuccessful(), 'Pacotes partilhados conferidos (runtime:check)');
|
||||
|
||||
if (in_array(config('mail.default'), ['log', 'array'], true)) {
|
||||
$this->warn('AVISO Email não configurado (MAIL_MAILER='.config('mail.default').'): avisos de prazos não saem da aplicação.');
|
||||
}
|
||||
$modules = collect(app(ProductModules::class)->states())->map(fn (bool $on, string $key) => $key.'='.($on ? 'ligado' : 'desligado'))->implode(', ');
|
||||
$this->line('INFO Módulos: '.$modules.'; cancelamento de ordens='.(config('order_cancellation.enabled') ? 'ligado' : 'desligado'));
|
||||
$this->line('INFO Confirme também: cron com `php artisan schedule:run` a cada minuto e cópias de segurança diárias (docs/producao.md).');
|
||||
|
||||
if ($this->failures > 0) {
|
||||
$this->error($this->failures.' verificação(ões) falharam. A instalação não está pronta para produção.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
$this->info('Instalação pronta para produção. Não substitui o restauro de teste nem a aceitação do piloto.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function database(Migrator $migrator): void
|
||||
{
|
||||
try {
|
||||
DB::connection()->getPdo();
|
||||
} catch (Throwable) {
|
||||
$this->check(false, 'Ligação à base de dados');
|
||||
|
||||
return;
|
||||
}
|
||||
$this->check(DB::connection()->getDriverName() === 'pgsql', 'Base de dados PostgreSQL');
|
||||
if (! $migrator->repositoryExists()) {
|
||||
$this->check(false, 'Tabela de migrações presente');
|
||||
|
||||
return;
|
||||
}
|
||||
$files = $migrator->getMigrationFiles([database_path('migrations'), ...$migrator->paths()]);
|
||||
$pending = array_diff(array_keys($files), $migrator->getRepository()->getRan());
|
||||
$this->check($pending === [], $pending === [] ? 'Migrações aplicadas' : 'Migrações pendentes: '.count($pending).' ('.implode(', ', array_slice($pending, 0, 3)).')');
|
||||
}
|
||||
|
||||
private function check(bool $passed, string $label): void
|
||||
{
|
||||
if ($passed) {
|
||||
$this->line('OK '.$label);
|
||||
|
||||
return;
|
||||
}
|
||||
$this->failures++;
|
||||
$this->line('<fg=red>FALHA</> '.$label);
|
||||
}
|
||||
}
|
||||
@@ -5,49 +5,60 @@ namespace App\Http\Controllers;
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
use App\Services\OrganizationAccess;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tempo\Inventory\InventoryReadSession;
|
||||
|
||||
final class CommonStockReadController extends Controller
|
||||
{
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
// Native authority, reloaded on every request; no SGF grants or identity assumptions.
|
||||
$user=User::query()->findOrFail($this->staffIdentity($request)->id);
|
||||
abort_unless($user->tenant_id!==null && $user->hasFunctions([PurchasingRole::Admin,PurchasingRole::Warehouse,PurchasingRole::Procurement,PurchasingRole::Finance])
|
||||
&& !app(OrganizationAccess::class)->maintenanceOnly($user),403);
|
||||
$d=$request->validate(['view'=>'sometimes|in:items,warehouses,balances,movements','search'=>'nullable|string|max:100',
|
||||
'warehouse_id'=>'sometimes|integer|min:1','page'=>'sometimes|integer|min:1|max:100000','per_page'=>'sometimes|integer|min:1|max:100','snapshot'=>'sometimes|string|max:8192']);
|
||||
abort_if(array_diff(array_keys($request->query()),array_keys($d))!==[],422);
|
||||
$filters=['view'=>$d['view']??'balances','search'=>$d['search']??'','warehouse_id'=>isset($d['warehouse_id'])?(int)$d['warehouse_id']:null,
|
||||
'page'=>(int)($d['page']??1),'per_page'=>(int)($d['per_page']??25)];
|
||||
$binding=config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id);
|
||||
if(!$binding)return response()->json(['status'=>'unavailable','message'=>'Fonte autorizada de stock ainda não ligada a este contexto.'],503)->header('Cache-Control','no-store');
|
||||
abort_unless(app()->environment('testing')&&DB::connection()->getDriverName()==='pgsql',403);
|
||||
$identity=DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D',$identity->name,$m)
|
||||
&& $identity->role==='stock_read_qa_'.$m[1] && (int)$identity->port===55439
|
||||
&& preg_match('/^[a-f0-9]{12}$/D',(string)config('stock_read.qa_run'))
|
||||
&& $identity->cluster==='sgf_modular_regression_'.config('stock_read.qa_run'),403);
|
||||
abort_unless(preg_match('/^sgf_stock_read_[a-f0-9]{12}$/D',$binding['schema']??'')&&($binding['append_only']??false)===true
|
||||
&& ($binding['source_tenant_id']??null)===(int)$user->tenant_id,503,'Fonte de stock incompatível.');
|
||||
if($filters['warehouse_id']!==null)abort_unless(in_array($filters['warehouse_id'],$binding['warehouse_ids'],true),403);
|
||||
$root=base_path('packages/inventory-read/releases/0.1.0');
|
||||
$bytes=is_file($root.'/manifest.json')?file_get_contents($root.'/manifest.json'):false;
|
||||
abort_unless(is_string($bytes)&&hash_equals(config('stock_read.package_manifest_sha256'),hash('sha256',$bytes)),503,'Pacote de consulta incompatível.');
|
||||
$manifest=json_decode($bytes,true,512,JSON_THROW_ON_ERROR);
|
||||
foreach(['bootstrap.php','src/InventoryReader.php','src/InventoryReadSession.php'] as $file) {
|
||||
$actual=is_file($root.'/'.$file)?hash_file('sha256',$root.'/'.$file):false;
|
||||
abort_unless(is_string($actual)&&isset($manifest['files'][$file])&&hash_equals($manifest['files'][$file],$actual),503,'Pacote de consulta incompatível.');
|
||||
$user = User::query()->findOrFail($this->staffIdentity($request)->id);
|
||||
abort_unless($user->tenant_id !== null && $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Warehouse, PurchasingRole::Procurement, PurchasingRole::Finance])
|
||||
&& ! app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
$d = $request->validate(['view' => 'sometimes|in:items,warehouses,balances,movements', 'search' => 'nullable|string|max:100',
|
||||
'warehouse_id' => 'sometimes|integer|min:1', 'page' => 'sometimes|integer|min:1|max:100000', 'per_page' => 'sometimes|integer|min:1|max:100', 'snapshot' => 'sometimes|string|max:8192']);
|
||||
abort_if(array_diff(array_keys($request->query()), array_keys($d)) !== [], 422);
|
||||
$filters = ['view' => $d['view'] ?? 'balances', 'search' => $d['search'] ?? '', 'warehouse_id' => isset($d['warehouse_id']) ? (int) $d['warehouse_id'] : null,
|
||||
'page' => (int) ($d['page'] ?? 1), 'per_page' => (int) ($d['per_page'] ?? 25)];
|
||||
$binding = config('stock_read.synthetic_sources.'.$user->tenant_id.':'.$user->id);
|
||||
if (! $binding) {
|
||||
return response()->json(['status' => 'unavailable', 'message' => 'Fonte autorizada de stock ainda não ligada a este contexto.'], 503)->header('Cache-Control', 'no-store');
|
||||
}
|
||||
abort_unless(app()->environment('testing') && DB::connection()->getDriverName() === 'pgsql', 403);
|
||||
$identity = DB::selectOne("SELECT current_database() AS name,current_user AS role,inet_server_port() AS port,current_setting('cluster_name') AS cluster");
|
||||
abort_unless(preg_match('/^stock_read_compras_([a-f0-9]{12})$/D', $identity->name, $m)
|
||||
&& $identity->role === 'stock_read_qa_'.$m[1] && (int) $identity->port === 55439
|
||||
&& preg_match('/^[a-f0-9]{12}$/D', (string) config('stock_read.qa_run'))
|
||||
&& $identity->cluster === 'sgf_modular_regression_'.config('stock_read.qa_run'), 403);
|
||||
abort_unless(preg_match('/^sgf_stock_read_[a-f0-9]{12}$/D', $binding['schema'] ?? '') && ($binding['append_only'] ?? false) === true
|
||||
&& ($binding['source_tenant_id'] ?? null) === (int) $user->tenant_id, 503, 'Fonte de stock incompatível.');
|
||||
if ($filters['warehouse_id'] !== null) {
|
||||
abort_unless(in_array($filters['warehouse_id'], $binding['warehouse_ids'], true), 403);
|
||||
}
|
||||
$root = base_path('packages/inventory-read/releases/0.1.0');
|
||||
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
|
||||
abort_unless(is_string($bytes) && hash_equals(config('stock_read.package_manifest_sha256'), hash('sha256', $bytes)), 503, 'Pacote de consulta incompatível.');
|
||||
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
foreach (['bootstrap.php', 'src/InventoryReader.php', 'src/InventoryReadSession.php'] as $file) {
|
||||
$actual = is_file($root.'/'.$file) ? hash_file('sha256', $root.'/'.$file) : false;
|
||||
abort_unless(is_string($actual) && isset($manifest['files'][$file]) && hash_equals($manifest['files'][$file], $actual), 503, 'Pacote de consulta incompatível.');
|
||||
}
|
||||
require_once $root.'/bootstrap.php';
|
||||
$fingerprint=hash('sha256',json_encode(['compras',$user->tenant_id,$user->id,$request->session()->get('work_context'),$binding,array_diff_key($filters,['page'=>true])],JSON_THROW_ON_ERROR));
|
||||
try { $result=(new \Tempo\Inventory\InventoryReadSession(DB::connection()))->read($binding,$fingerprint,$filters,$d['snapshot']??null); }
|
||||
catch(\Illuminate\Database\QueryException $e){
|
||||
if(!in_array($e->errorInfo[0]??null,['42P01','42703','42883','57014'],true))throw $e;
|
||||
return response()->json(['status'=>'unavailable','message'=>'A fonte de stock está indisponível ou incompatível. Actualize a consulta mais tarde.'],503)->header('Cache-Control','no-store');
|
||||
$fingerprint = hash('sha256', json_encode(['compras', $user->tenant_id, $user->id, $request->session()->get('work_context'), $binding, array_diff_key($filters, ['page' => true])], JSON_THROW_ON_ERROR));
|
||||
try {
|
||||
$result = (new InventoryReadSession(DB::connection()))->read($binding, $fingerprint, $filters, $d['snapshot'] ?? null);
|
||||
} catch (QueryException $e) {
|
||||
if (! in_array($e->errorInfo[0] ?? null, ['42P01', '42703', '42883', '57014'], true)) {
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return response()->json(['status' => 'unavailable', 'message' => 'A fonte de stock está indisponível ou incompatível. Actualize a consulta mais tarde.'], 503)->header('Cache-Control','no-store');
|
||||
}
|
||||
|
||||
return response()->json($result)->header('Cache-Control','no-store');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Http\Controllers\Settings;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Middleware\RequireTwoFactorForSensitiveRoles;
|
||||
use App\Http\Requests\Settings\PasswordUpdateRequest;
|
||||
use App\Http\Requests\Settings\TwoFactorAuthenticationRequest;
|
||||
use App\Models\User;
|
||||
@@ -41,6 +42,7 @@ class SecurityController extends Controller
|
||||
'twoFactorEnabled' => $actor->hasEnabledTwoFactorAuthentication(),
|
||||
'twoFactorPending' => $actor->two_factor_secret !== null && ! $actor->hasEnabledTwoFactorAuthentication(),
|
||||
'requiresConfirmation' => Fortify::confirmsTwoFactorAuthentication(),
|
||||
'mfaRequired' => RequireTwoFactorForSensitiveRoles::requiredFor($actor),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -43,14 +43,21 @@ final class WarehouseReturnController extends Controller
|
||||
}
|
||||
|
||||
/** @param callable():array<string,mixed> $run */
|
||||
private function response(callable $run,bool $readOnly=false): JsonResponse
|
||||
private function response(callable $run, bool $readOnly = false): JsonResponse
|
||||
{
|
||||
try {
|
||||
$result=$readOnly?DB::transaction(function()use($run){if(DB::getDriverName()==='pgsql'&&DB::transactionLevel()===1)DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');return $run();}):$run();
|
||||
$result = $readOnly ? DB::transaction(function () use ($run) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
|
||||
return $run();
|
||||
}) : $run();
|
||||
|
||||
return response()->json($result)->header('Cache-Control', 'no-store');
|
||||
} catch (QueryException $e) {
|
||||
if (($e->errorInfo[0] ?? null) === '55P03') {
|
||||
return response()->json(['code'=>'warehouse_return_busy','message' => 'Devolução ocupada. Aguarde e repita manualmente a conferência.'], 423)->header('Cache-Control', 'no-store');
|
||||
return response()->json(['code' => 'warehouse_return_busy', 'message' => 'Devolução ocupada. Aguarde e repita manualmente a conferência.'], 423)->header('Cache-Control', 'no-store');
|
||||
}
|
||||
throw $e;
|
||||
}
|
||||
@@ -83,12 +90,25 @@ final class WarehouseReturnController extends Controller
|
||||
$d['version'] = (int) $d['version'];
|
||||
$d['received_in_warehouse'] = true;
|
||||
|
||||
return $this->response(fn () => $flow->confirm($this->actor($r),$id,$d));
|
||||
return $this->response(fn () => $flow->confirm($this->actor($r), $id, $d));
|
||||
}
|
||||
public function withdraw(Request $r,int $id,WarehouseReturns $flow): JsonResponse {return $this->close($r,$id,$flow,'withdrawn');}
|
||||
public function reject(Request $r,int $id,WarehouseReturns $flow): JsonResponse {return $this->close($r,$id,$flow,'rejected');}
|
||||
private function close(Request $r,int $id,WarehouseReturns $flow,string $state): JsonResponse
|
||||
|
||||
public function withdraw(Request $r, int $id, WarehouseReturns $flow): JsonResponse
|
||||
{
|
||||
$d=$r->validate(['version'=>'required|integer|min:1','reason'=>'required|string|min:10|max:1000']);abort_if(array_diff(array_keys($r->all()),array_keys($d))!==[],422);$d['version']=(int)$d['version'];return $this->response(fn()=>$flow->close($this->actor($r),$id,$d,$state));
|
||||
return $this->close($r, $id, $flow, 'withdrawn');
|
||||
}
|
||||
|
||||
public function reject(Request $r, int $id, WarehouseReturns $flow): JsonResponse
|
||||
{
|
||||
return $this->close($r, $id, $flow, 'rejected');
|
||||
}
|
||||
|
||||
private function close(Request $r, int $id, WarehouseReturns $flow, string $state): JsonResponse
|
||||
{
|
||||
$d = $r->validate(['version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:1000']);
|
||||
abort_if(array_diff(array_keys($r->all()), array_keys($d)) !== [], 422);
|
||||
$d['version'] = (int) $d['version'];
|
||||
|
||||
return $this->response(fn () => $flow->close($this->actor($r), $id, $d, $state));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Services\ProductModules;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Route;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/** Rotas de módulos desligados nesta instalação respondem como inexistentes. */
|
||||
class EnsureModuleEnabled
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$route = $request->route();
|
||||
abort_if($route instanceof Route && ! app(ProductModules::class)->allows($route), 404);
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ use App\Services\GeneralLedger;
|
||||
use App\Services\OperationalOrders;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\PrivateAuditAccess;
|
||||
use App\Services\ProductModules;
|
||||
use App\Services\StandaloneRuntime;
|
||||
use App\Services\SupplierPayables;
|
||||
use App\Services\WorkContext;
|
||||
@@ -76,6 +77,8 @@ class HandleInertiaRequests extends Middleware
|
||||
'privateAuditAvailable' => $actor !== null && app(PrivateAuditAccess::class)->ready(),
|
||||
'capitalRegisterAvailable' => $actor !== null && app(CapitalRegister::class)->searchQuery($actor) !== null,
|
||||
'sidebarOpen' => ! $request->hasCookie('sidebar_state') || $request->cookie('sidebar_state') === 'true',
|
||||
'modules' => app(ProductModules::class)->states(),
|
||||
'disabledModulePaths' => fn () => app(ProductModules::class)->disabledPaths(),
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\EvaluationNavigation;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Laravel\Fortify\Features;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/** Perfis sensíveis (config/mfa.php) só usam a aplicação depois de confirmarem o MFA. */
|
||||
class RequireTwoFactorForSensitiveRoles
|
||||
{
|
||||
/** Configurar o MFA, confirmar a palavra-passe e sair continuam sempre disponíveis. */
|
||||
private const ALLOWED = ['settings', 'settings/*', 'user/*', 'two-factor-challenge', 'logout', 'login', 'up'];
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
if (! self::applies($request) || $request->is(...self::ALLOWED)) {
|
||||
return $next($request);
|
||||
}
|
||||
if ($request->expectsJson()) {
|
||||
abort(403, 'Configure a autenticação de dois factores antes de continuar.');
|
||||
}
|
||||
|
||||
return redirect()->route('security.edit');
|
||||
}
|
||||
|
||||
public static function applies(Request $request): bool
|
||||
{
|
||||
$user = $request->user('web');
|
||||
|
||||
return $user instanceof User
|
||||
&& Features::enabled(Features::twoFactorAuthentication())
|
||||
&& ! EvaluationNavigation::local($request)
|
||||
&& self::requiredFor($user);
|
||||
}
|
||||
|
||||
/** O utilizador tem uma função que exige MFA e ainda não o confirmou. */
|
||||
public static function requiredFor(User $user): bool
|
||||
{
|
||||
$functions = array_values(array_filter((array) config('mfa.required_functions', []), 'is_string'));
|
||||
|
||||
return $user->two_factor_confirmed_at === null && $functions !== [] && $user->hasFunctions($functions);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
{
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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)) : [];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user