@@ -21,7 +21,7 @@ class BudgetController extends Controller
|
||||
{
|
||||
private function access(Request $request): void
|
||||
{
|
||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
||||
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
||||
}
|
||||
|
||||
public function index(Request $request): Response
|
||||
@@ -31,20 +31,20 @@ class BudgetController extends Controller
|
||||
return Inertia::render('budgets/index', ['centers' => CostCenter::query()->orderBy('code')->get(), 'budgets' => Budget::query()->latest('id')->get()->map(function (Budget $budget) use ($request) {
|
||||
$adapter = app(CommonBudget::class);
|
||||
|
||||
return [...$budget->toArray(), ...$adapter->execute(fn () => $adapter->for($request->user())->balance($budget->id))];
|
||||
return [...$budget->toArray(), ...$adapter->execute(fn () => $adapter->for($this->staffIdentity($request))->balance($budget->id))];
|
||||
}), 'reinforcements' => BudgetReinforcement::query()->latest('id')->paginate(20)]);
|
||||
}
|
||||
|
||||
public function store(Request $request): RedirectResponse
|
||||
{
|
||||
$this->access($request);
|
||||
$data = $request->validate(['cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $request->user()->tenant_id)], 'year' => 'required|integer|min:2026|max:2100', 'includes_tax' => 'required|boolean', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'reason' => 'required|string|max:4000']);
|
||||
$data = $request->validate(['cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)], 'year' => 'required|integer|min:2026|max:2100', 'includes_tax' => 'required|boolean', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'reason' => 'required|string|max:4000']);
|
||||
$kind = $request->validate(['kind' => ['sometimes', Rule::in(['operating', 'investment'])]])['kind'] ?? 'operating';
|
||||
DB::transaction(function () use ($request, $data, $kind) {
|
||||
app(ConflictGuard::class)->lockCompany($request->user());
|
||||
app(CurrentActor::class)->lock($request->user(), [PurchasingRole::Admin, PurchasingRole::Finance]);
|
||||
app(ConflictGuard::class)->lockCompany($this->staffIdentity($request));
|
||||
app(CurrentActor::class)->lock($this->staffIdentity($request), [PurchasingRole::Admin, PurchasingRole::Finance]);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$adapter->execute(fn () => $adapter->for($request->user())->create(['cost_center_id' => (int) $data['cost_center_id'], 'year' => (int) $data['year'], 'kind' => $kind, 'includes_tax' => (bool) $data['includes_tax'], 'amount_minor' => BigDecimal::of($data['amount'])->multipliedBy(100)->toInt(), 'reason' => $data['reason']]));
|
||||
$adapter->execute(fn () => $adapter->for($this->staffIdentity($request))->create(['cost_center_id' => (int) $data['cost_center_id'], 'year' => (int) $data['year'], 'kind' => $kind, 'includes_tax' => (bool) $data['includes_tax'], 'amount_minor' => BigDecimal::of($data['amount'])->multipliedBy(100)->toInt(), 'reason' => $data['reason']]));
|
||||
});
|
||||
|
||||
return back();
|
||||
@@ -54,10 +54,10 @@ class BudgetController extends Controller
|
||||
{
|
||||
$this->access($request);
|
||||
DB::transaction(function () use ($request, $budget) {
|
||||
app(ConflictGuard::class)->lockCompany($request->user());
|
||||
app(CurrentActor::class)->lock($request->user(), [PurchasingRole::Admin, PurchasingRole::Finance]);
|
||||
app(ConflictGuard::class)->lockCompany($this->staffIdentity($request));
|
||||
app(CurrentActor::class)->lock($this->staffIdentity($request), [PurchasingRole::Admin, PurchasingRole::Finance]);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$adapter->execute(fn () => $adapter->for($request->user())->approve($budget->id));
|
||||
$adapter->execute(fn () => $adapter->for($this->staffIdentity($request))->approve($budget->id));
|
||||
});
|
||||
|
||||
return back();
|
||||
|
||||
@@ -13,9 +13,9 @@ class BudgetReinforcementController extends Controller
|
||||
{
|
||||
public function store(Request $request, Budget $budget, BudgetReinforcementWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
||||
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]), 403);
|
||||
$data = $request->validate(['reference' => 'required|string|max:100', 'amount' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'reason' => 'required|string|max:4000']);
|
||||
$workflow->propose($request->user(), $budget, $data);
|
||||
$workflow->propose($this->staffIdentity($request), $budget, $data);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -23,7 +23,7 @@ class BudgetReinforcementController extends Controller
|
||||
public function review(Request $request, BudgetReinforcement $reinforcement, BudgetReinforcementWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:4000']);
|
||||
$workflow->review($request->user(), $reinforcement, $data['decision'], $data['reason']);
|
||||
$workflow->review($this->staffIdentity($request), $reinforcement, $data['decision'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
@@ -6,14 +6,15 @@ use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
use App\Services\OrganizationAccess;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class CommonStockReadController extends Controller
|
||||
{
|
||||
public function index(Request $request)
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
// Native authority, reloaded on every request; no SGF grants or identity assumptions.
|
||||
$user=User::query()->findOrFail($request->user()->id);
|
||||
$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',
|
||||
@@ -33,10 +34,13 @@ final class CommonStockReadController extends Controller
|
||||
&& ($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');
|
||||
abort_unless(is_file($root.'/manifest.json')&&hash_equals(config('stock_read.package_manifest_sha256'),hash_file('sha256',$root.'/manifest.json')),503,'Pacote de consulta incompatível.');
|
||||
$manifest=json_decode(file_get_contents($root.'/manifest.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
foreach(['bootstrap.php','src/InventoryReader.php','src/InventoryReadSession.php'] as $file)
|
||||
abort_unless(is_file($root.'/'.$file)&&isset($manifest['files'][$file])&&hash_equals($manifest['files'][$file],hash_file('sha256',$root.'/'.$file)),503,'Pacote de consulta incompatível.');
|
||||
$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); }
|
||||
|
||||
@@ -21,17 +21,17 @@ class CompanyController extends Controller
|
||||
{
|
||||
public function setup(Request $request): Response|RedirectResponse
|
||||
{
|
||||
return $request->user()->tenant_id ? to_route('dashboard') : Inertia::render('company/setup');
|
||||
return $this->staffIdentity($request)->tenant_id ? to_route('dashboard') : Inertia::render('company/setup');
|
||||
}
|
||||
|
||||
public function store(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
abort_if($request->user()->tenant_id !== null, 403);
|
||||
abort_if($this->staffIdentity($request)->tenant_id !== null, 403);
|
||||
$data = $request->validate(['name' => 'required|string|max:150', 'department' => 'required|string|max:100',
|
||||
'second_name' => 'required|string|max:100', 'second_email' => 'required|email|max:255|unique:users,email', 'second_password' => 'required|string|min:12|confirmed',
|
||||
'first_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'second_limit' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D'], 'includes_tax' => 'required|boolean']);
|
||||
DB::transaction(function () use ($request, $data, $workflow) {
|
||||
$user = User::query()->lockForUpdate()->findOrFail($request->user()->id);
|
||||
$user = User::query()->lockForUpdate()->findOrFail($this->staffIdentity($request)->id);
|
||||
abort_if($user->tenant_id !== null, 403);
|
||||
$tenant = Tenant::query()->create(['name' => $data['name'], ...OrganizationConfiguration::rules($data)]);
|
||||
$department = Department::query()->create(['tenant_id' => $tenant->id, 'name' => $data['department']]);
|
||||
@@ -49,15 +49,15 @@ class CompanyController extends Controller
|
||||
public function index(Request $request): Response|RedirectResponse
|
||||
{
|
||||
$this->admin($request);
|
||||
if (app(OrganizationAccess::class)->active($request->user()->tenant_id)) {
|
||||
if (app(OrganizationAccess::class)->active($this->staffIdentity($request)->tenant_id)) {
|
||||
return to_route('organization.parameters');
|
||||
}
|
||||
|
||||
return Inertia::render('company/index', [
|
||||
'company' => Tenant::query()->findOrFail($request->user()->tenant_id),
|
||||
'company' => Tenant::query()->findOrFail($this->staffIdentity($request)->tenant_id),
|
||||
'departments' => Department::query()->orderBy('name')->get(),
|
||||
'costCenters' => CostCenter::query()->orderBy('code')->get(),
|
||||
'users' => User::query()->where('tenant_id', $request->user()->tenant_id)->orderBy('name')->get(['id', 'name', 'email', 'department_id', 'purchasing_role']),
|
||||
'users' => User::query()->where('tenant_id', $this->staffIdentity($request)->tenant_id)->orderBy('name')->get(['id', 'name', 'email', 'department_id', 'purchasing_role']),
|
||||
'roles' => collect(PurchasingRole::cases())->reject(fn (PurchasingRole $role) => $role === PurchasingRole::Configured)->values()->map(fn (PurchasingRole $role) => ['value' => $role->value, 'label' => $role->label()]),
|
||||
]);
|
||||
}
|
||||
@@ -65,10 +65,10 @@ class CompanyController extends Controller
|
||||
public function department(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$this->admin($request);
|
||||
$data = $request->validate(['name' => ['required', 'string', 'max:100', Rule::unique('departments')->where('tenant_id', $request->user()->tenant_id)]]);
|
||||
$data = $request->validate(['name' => ['required', 'string', 'max:100', Rule::unique('departments')->where('tenant_id', $this->staffIdentity($request)->tenant_id)]]);
|
||||
DB::transaction(function () use ($request, $data, $workflow) {
|
||||
$department = Department::query()->create(['tenant_id' => $request->user()->tenant_id, ...$data]);
|
||||
$workflow->audit($request->user(), 'department.created', null, null, $department->toArray());
|
||||
$department = Department::query()->create(['tenant_id' => $this->staffIdentity($request)->tenant_id, ...$data]);
|
||||
$workflow->audit($this->staffIdentity($request), 'department.created', null, null, $department->toArray());
|
||||
});
|
||||
|
||||
return back();
|
||||
@@ -78,13 +78,13 @@ class CompanyController extends Controller
|
||||
{
|
||||
$this->admin($request);
|
||||
$data = $request->validate([
|
||||
'department_id' => ['required', Rule::exists('departments', 'id')->where('tenant_id', $request->user()->tenant_id)],
|
||||
'code' => ['required', 'string', 'max:30', Rule::unique('cost_centers')->where('tenant_id', $request->user()->tenant_id)],
|
||||
'department_id' => ['required', Rule::exists('departments', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||
'code' => ['required', 'string', 'max:30', Rule::unique('cost_centers')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||
'name' => 'required|string|max:100',
|
||||
]);
|
||||
DB::transaction(function () use ($request, $data, $workflow) {
|
||||
$center = CostCenter::query()->create(['tenant_id' => $request->user()->tenant_id, ...$data]);
|
||||
$workflow->audit($request->user(), 'cost_center.created', null, null, $center->toArray());
|
||||
$center = CostCenter::query()->create(['tenant_id' => $this->staffIdentity($request)->tenant_id, ...$data]);
|
||||
$workflow->audit($this->staffIdentity($request), 'cost_center.created', null, null, $center->toArray());
|
||||
});
|
||||
|
||||
return back();
|
||||
@@ -93,17 +93,17 @@ class CompanyController extends Controller
|
||||
public function user(Request $request, RequisitionWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$this->admin($request);
|
||||
abort_if(app(OrganizationAccess::class)->active($request->user()->tenant_id), 409, 'Crie utilizadores e atribua perfis na parametrização.');
|
||||
abort_if(app(OrganizationAccess::class)->active($this->staffIdentity($request)->tenant_id), 409, 'Crie utilizadores e atribua perfis na parametrização.');
|
||||
$data = $request->validate([
|
||||
'name' => 'required|string|max:100', 'email' => 'required|email|max:255|unique:users',
|
||||
'password' => 'required|string|min:12|confirmed',
|
||||
'department_id' => ['required', Rule::exists('departments', 'id')->where('tenant_id', $request->user()->tenant_id)],
|
||||
'department_id' => ['required', Rule::exists('departments', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||
'purchasing_role' => ['required', Rule::enum(PurchasingRole::class)],
|
||||
]);
|
||||
DB::transaction(function () use ($request, $data, $workflow) {
|
||||
$user = new User;
|
||||
$user->forceFill($data + ['tenant_id' => $request->user()->tenant_id])->save();
|
||||
$workflow->audit($request->user(), 'user.created', null, null, $user->only(['id', 'name', 'email', 'department_id', 'purchasing_role']));
|
||||
$user->forceFill($data + ['tenant_id' => $this->staffIdentity($request)->tenant_id])->save();
|
||||
$workflow->audit($this->staffIdentity($request), 'user.created', null, null, $user->only(['id', 'name', 'email', 'department_id', 'purchasing_role']));
|
||||
});
|
||||
|
||||
return back();
|
||||
@@ -111,6 +111,6 @@ class CompanyController extends Controller
|
||||
|
||||
private function admin(Request $request): void
|
||||
{
|
||||
app(OrganizationConfiguration::class)->administrator($request->user());
|
||||
app(OrganizationConfiguration::class)->administrator($this->staffIdentity($request));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,12 +20,12 @@ class ConflictDeclarationController extends Controller
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
return Inertia::render('conflicts/index', [
|
||||
'declarations' => ConflictDeclaration::query()->visibleTo($request->user())
|
||||
'declarations' => ConflictDeclaration::query()->visibleTo($this->staffIdentity($request))
|
||||
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number', 'successor:id,previous_id'])
|
||||
->latest('id')->paginate(15),
|
||||
// These minimal choices allow personal declarations without granting supplier-management access.
|
||||
'suppliers' => Supplier::query()->orderBy('name')->get(['id', 'name']),
|
||||
'requisitions' => Requisition::query()->visibleTo($request->user())->latest()->get(['id', 'number']),
|
||||
'requisitions' => Requisition::query()->visibleTo($this->staffIdentity($request))->latest()->get(['id', 'number']),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -33,25 +33,25 @@ class ConflictDeclarationController extends Controller
|
||||
{
|
||||
$data = $request->validate([
|
||||
'scope' => ['required', Rule::in(['supplier', 'process', 'process_supplier'])],
|
||||
'supplier_id' => ['nullable', 'required_if:scope,supplier,process_supplier', 'prohibited_if:scope,process', 'integer', Rule::exists('suppliers', 'id')->where('tenant_id', $request->user()->tenant_id)],
|
||||
'requisition_id' => ['nullable', 'required_if:scope,process,process_supplier', 'prohibited_if:scope,supplier', 'integer', Rule::exists('requisitions', 'id')->where('tenant_id', $request->user()->tenant_id)],
|
||||
'supplier_id' => ['nullable', 'required_if:scope,supplier,process_supplier', 'prohibited_if:scope,process', 'integer', Rule::exists('suppliers', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||
'requisition_id' => ['nullable', 'required_if:scope,process,process_supplier', 'prohibited_if:scope,supplier', 'integer', Rule::exists('requisitions', 'id')->where('tenant_id', $this->staffIdentity($request)->tenant_id)],
|
||||
'has_conflict' => 'required|boolean', 'known_since' => 'required|date_format:Y-m-d|before_or_equal:today',
|
||||
'reason' => 'required|string|min:10|max:5000',
|
||||
'user_id' => 'prohibited', 'tenant_id' => 'prohibited', 'declared_at' => 'prohibited',
|
||||
'root_id' => 'prohibited', 'previous_id' => 'prohibited',
|
||||
]);
|
||||
DB::transaction(function () use ($request, $guard, $workflow, $data) {
|
||||
$guard->lockCompany($request->user());
|
||||
$guard->lockCompany($this->staffIdentity($request));
|
||||
if (! empty($data['requisition_id'])) {
|
||||
Requisition::query()->visibleTo($request->user())->findOrFail($data['requisition_id']);
|
||||
Requisition::query()->visibleTo($this->staffIdentity($request))->findOrFail($data['requisition_id']);
|
||||
}
|
||||
$declaration = ConflictDeclaration::query()->create([
|
||||
'tenant_id' => $request->user()->tenant_id, 'user_id' => $request->user()->id,
|
||||
'tenant_id' => $this->staffIdentity($request)->tenant_id, 'user_id' => $this->staffIdentity($request)->id,
|
||||
'supplier_id' => $data['supplier_id'] ?? null, 'requisition_id' => $data['requisition_id'] ?? null,
|
||||
'has_conflict' => $data['has_conflict'], 'known_since' => $data['known_since'],
|
||||
'reason' => $data['reason'], 'declared_at' => now(),
|
||||
]);
|
||||
$workflow->audit($request->user(), 'conflict.declared', null, null, $declaration->toArray());
|
||||
$workflow->audit($this->staffIdentity($request), 'conflict.declared', null, null, $declaration->toArray());
|
||||
});
|
||||
|
||||
return to_route('conflicts.index');
|
||||
@@ -59,18 +59,18 @@ class ConflictDeclarationController extends Controller
|
||||
|
||||
public function show(Request $request, ConflictDeclaration $declaration): Response
|
||||
{
|
||||
ConflictDeclaration::query()->visibleTo($request->user())->findOrFail($declaration->id);
|
||||
ConflictDeclaration::query()->visibleTo($this->staffIdentity($request))->findOrFail($declaration->id);
|
||||
$rootId = $declaration->root_id ?? $declaration->id;
|
||||
$history = ConflictDeclaration::query()->where(fn ($query) => $query->whereKey($rootId)->orWhere('root_id', $rootId))
|
||||
->with(['author:id,name', 'supplier:id,name', 'requisition:id,number'])->orderBy('id')->get();
|
||||
$latest = $history->last();
|
||||
|
||||
return Inertia::render('conflicts/show', ['history' => $history, 'canCorrect' => $latest?->user_id === $request->user()->id]);
|
||||
return Inertia::render('conflicts/show', ['history' => $history, 'canCorrect' => $latest?->user_id === $this->staffIdentity($request)->id]);
|
||||
}
|
||||
|
||||
public function update(Request $request, ConflictDeclaration $declaration, ConflictGuard $guard, RequisitionWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
abort_unless($declaration->user_id === $request->user()->id, 403);
|
||||
abort_unless($declaration->user_id === $this->staffIdentity($request)->id, 403);
|
||||
$data = $request->validate([
|
||||
'known_since' => 'required|date_format:Y-m-d|before_or_equal:today', 'reason' => 'required|string|min:10|max:5000',
|
||||
'has_conflict' => 'prohibited', 'supplier_id' => 'prohibited', 'requisition_id' => 'prohibited',
|
||||
@@ -78,7 +78,7 @@ class ConflictDeclarationController extends Controller
|
||||
'root_id' => 'prohibited', 'previous_id' => 'prohibited',
|
||||
]);
|
||||
DB::transaction(function () use ($request, $guard, $workflow, $declaration, $data) {
|
||||
$guard->lockCompany($request->user());
|
||||
$guard->lockCompany($this->staffIdentity($request));
|
||||
$declaration = ConflictDeclaration::query()->lockForUpdate()->findOrFail($declaration->id);
|
||||
if ($declaration->successor()->exists()) {
|
||||
throw ValidationException::withMessages(['history' => 'Já existe uma correcção mais recente. Reabra o histórico antes de corrigir.']);
|
||||
@@ -87,7 +87,7 @@ class ConflictDeclarationController extends Controller
|
||||
...$declaration->only(['tenant_id', 'user_id', 'supplier_id', 'requisition_id', 'has_conflict']),
|
||||
...$data, 'declared_at' => now(), 'root_id' => $declaration->root_id ?? $declaration->id, 'previous_id' => $declaration->id,
|
||||
]);
|
||||
$workflow->audit($request->user(), 'conflict.corrected', null, $declaration->toArray(), $revision->toArray());
|
||||
$workflow->audit($this->staffIdentity($request), 'conflict.corrected', null, $declaration->toArray(), $revision->toArray());
|
||||
});
|
||||
|
||||
return to_route('conflicts.show', $declaration);
|
||||
|
||||
@@ -2,7 +2,17 @@
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
abstract class Controller
|
||||
{
|
||||
//
|
||||
/** Staff endpoints use the web identity; candidate accounts have their own realm. */
|
||||
protected function staffIdentity(Request $request): User
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,11 +36,19 @@ class ExternalPaymentController extends Controller
|
||||
if ($canManage && $payments->count() > 0) {
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'payment.viewed', null, null, ['payment_ids' => $payments->pluck('id')->all()]);
|
||||
}
|
||||
$invoices = $visibleInvoices->where('status', 'validated')->when($focus !== null, fn ($q) => $q->whereIn('id', $payments->pluck('invoice_id')))->when($focusInvoice !== null, fn ($q) => $q->whereKey($focusInvoice))->latest('id')->get()->map(function (Invoice $invoice) use ($workflow) {
|
||||
$invoices = $visibleInvoices->where('status', 'validated')->when($focus !== null, fn ($q) => $q->whereIn('id', $payments->pluck('invoice_id')))->when($focusInvoice !== null, fn ($q) => $q->whereKey($focusInvoice))->latest('id')->get()->map(function (Invoice $invoice) use ($workflow, $canManage) {
|
||||
$supplier = Supplier::query()->findOrFail($invoice->supplier_id);
|
||||
$bank = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
|
||||
$bankWorkflow = app(SupplierBankWorkflow::class);
|
||||
$currency = $invoice->snapshot['currency'] ?? 'MZN';
|
||||
$banks = $bankWorkflow->currentAccounts($supplier)->where('currency', $currency)->map(fn (SupplierBankDetail $bank) => [
|
||||
'id' => $bank->id, 'revision' => $bank->revision, 'currency' => $bank->currency, 'label' => $bank->bank_name.' · '.$bank->currency.' · v'.$bank->revision,
|
||||
'state' => $bankWorkflow->state($supplier, $bank->account_key),
|
||||
])->values();
|
||||
$approved = $banks->where('state', 'approved');
|
||||
$bank = $approved->count() === 1 ? $approved->first() : null;
|
||||
|
||||
return ['id' => $invoice->id, 'number' => $invoice->number, 'supplier_id' => $supplier->id, 'supplier_name' => $supplier->name, 'total_minor' => $invoice->total_minor, 'outstanding_minor' => $workflow->outstanding($invoice), 'bank_id' => $bank->id ?? 0, 'bank_revision' => $bank->revision ?? 0, 'bank_state' => app(SupplierBankWorkflow::class)->state($supplier)];
|
||||
return ['id' => $invoice->id, 'number' => $invoice->number, 'currency' => $currency, 'supplier_id' => $supplier->id, 'supplier_name' => $supplier->name, 'total_minor' => $invoice->total_minor, 'outstanding_minor' => $workflow->outstanding($invoice),
|
||||
'bank_id' => $bank['id'] ?? 0, 'bank_revision' => $bank['revision'] ?? 0, 'bank_state' => $approved->isNotEmpty() ? 'approved' : ($banks->first()['state'] ?? 'missing'), 'banks' => $canManage ? $banks->all() : []];
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('payments/index', ['focusPaymentId' => $focus, 'focusInvoiceId' => $focusInvoice, 'invoices' => $invoices, 'payments' => $payments, 'canManage' => $canManage])->toResponse($request);
|
||||
|
||||
@@ -68,6 +68,7 @@ class GoodsReceiptController extends Controller
|
||||
'receipts' => GoodsReceipt::query()->where('purchase_order_id', $order->id)->latest('id')->get(),
|
||||
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']),
|
||||
'stockItems' => StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']),
|
||||
'conversionQaEnabled' => app()->environment('testing') && config('inventory_conversion.qa_enabled') === true,
|
||||
'canConfirm' => $request->user()->can('create', [GoodsReceipt::class, $order]),
|
||||
'lotScopes' => Schema::hasTable('inventory_lot_allocations')
|
||||
? app(InventoryLots::class)->activeSetups()->get()->map(fn ($r) => ['stock_item_id' => $r->stock_item_id, 'warehouse_id' => $r->warehouse_id, 'quarantine_on_receipt' => $r->data['quarantine_on_receipt'] ?? true])->values()->all() : [],
|
||||
|
||||
@@ -11,6 +11,7 @@ use App\Services\InventoryCorrectionPage;
|
||||
use App\Services\InventoryDispositions;
|
||||
use App\Services\InventoryLots;
|
||||
use App\Services\InventoryReversals;
|
||||
use App\Services\ReceiptQuantityConversion;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -54,7 +55,7 @@ class InventoryDispositionController extends Controller
|
||||
foreach (app(InventoryCorrectionPage::class)->receipts($records->pluck('data.receipt_item_id')->push($page['lookup']['receipt']), $page['lookup']['search']) as $line) {
|
||||
$receipt = GoodsReceipt::query()->whereKey($line->goods_receipt_id)->firstOrFail();
|
||||
$receipts[] = ['id' => $line->id, 'stock_item_id' => $line->stock_item_id, 'warehouse_id' => $receipt->warehouse_id, 'accepted_milli' => $line->accepted_milli,
|
||||
'returned_milli' => $workflow->returnedForReceipt($line->id), 'label' => $receipt->number.' · '.$receipt->snapshot['supplier']['name'].' · '.$line->snapshot['stock_item']['name']];
|
||||
'returned_milli' => $workflow->returnedForReceipt($line->id), 'physical_accepted_milli' => app(ReceiptQuantityConversion::class)->physicalAccepted($line), 'label' => $receipt->number.' · '.$receipt->snapshot['supplier']['name'].' · '.$line->snapshot['stock_item']['name']];
|
||||
}
|
||||
foreach (app(InventoryLots::class)->activeSetups()->get() as $setup) {
|
||||
$context = app(InventoryLots::class)->context($setup->stock_item_id, $setup->warehouse_id);
|
||||
|
||||
@@ -15,17 +15,17 @@ class InvestmentPolicyController extends Controller
|
||||
{
|
||||
public function index(Request $request, InvestmentWorkflow $workflow): Response
|
||||
{
|
||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::Procurement]), 403);
|
||||
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance, PurchasingRole::Procurement]), 403);
|
||||
$current = $workflow->current();
|
||||
|
||||
return Inertia::render('investment/index', ['policies' => InvestmentPolicy::query()->latest('revision')->get(), 'reviews' => InvestmentPolicyReview::query()->orderBy('id')->get(), 'currentPolicyId' => $current && $current->valid_until >= today()->format('Y-m-d') ? $current->id : null, 'canManage' => $request->user()->hasFunctions([PurchasingRole::Admin])]);
|
||||
return Inertia::render('investment/index', ['policies' => InvestmentPolicy::query()->latest('revision')->get(), 'reviews' => InvestmentPolicyReview::query()->orderBy('id')->get(), 'currentPolicyId' => $current && $current->valid_until >= today()->format('Y-m-d') ? $current->id : null, 'canManage' => $this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin])]);
|
||||
}
|
||||
|
||||
public function store(Request $request, InvestmentWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin]), 403);
|
||||
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin]), 403);
|
||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'mode' => 'required|in:ceiling', 'scope' => 'required|in:process_total', 'currency' => 'required|in:MZN', 'ceiling' => ['required', 'regex:/^\d{1,12}(\.\d{1,2})?$/'], 'includes_tax' => 'required|boolean', 'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from', 'reason' => 'required|string|max:4000']);
|
||||
$workflow->propose($request->user(), $data);
|
||||
$workflow->propose($this->staffIdentity($request), $data);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -33,7 +33,7 @@ class InvestmentPolicyController extends Controller
|
||||
public function review(Request $request, InvestmentPolicy $policy, InvestmentWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:4000']);
|
||||
$workflow->review($request->user(), $policy, $data['decision'], $data['reason']);
|
||||
$workflow->review($this->staffIdentity($request), $policy, $data['decision'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ class InvoiceController extends Controller
|
||||
$response = Inertia::render('invoices/index', ['focusInvoiceId' => $focus, 'focusOrderId' => $focusOrder, 'stockReversals' => app(InventoryReversals::class)->financialNotices(), 'stockReturns' => app(InventoryDispositions::class)->financialNotices(),
|
||||
'invoices' => Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->when($focus !== null, fn ($q) => $q->whereKey($focus))->when($focusOrder !== null, fn ($q) => $q->where('purchase_order_id', $focusOrder))->with('items')->latest('id')->paginate(15)->withQueryString()
|
||||
->through(fn (Invoice $invoice) => [...$invoice->toArray(), 'canValidate' => app(InvoiceWorkflow::class)->reviewerEligible($actor, $invoice)]),
|
||||
'orders' => PurchaseOrder::query()->visibleTo($actor)->operational()->with('items')->latest('id')->get()->map(fn ($order) => ['id' => $order->id, 'number' => $order->number, 'supplier' => $order->snapshot['supplier']['name'], 'items' => $order->items]),
|
||||
'orders' => PurchaseOrder::query()->visibleTo($actor)->operational()->with('items')->latest('id')->get()->map(fn ($order) => ['id' => $order->id, 'number' => $order->number, 'currency' => $order->currency, 'supplier' => $order->snapshot['supplier']['name'], 'items' => $order->items]),
|
||||
'sgfDispatchAvailable' => config('sgf_invoice.workspace_enabled')===true && $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor),
|
||||
'payablesAvailable' => SupplierPayables::enabled() && app(SupplierPayables::class)->can($actor, 'view'), 'canManage' => $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
@@ -12,22 +12,22 @@ class PeopleRegistryController extends Controller
|
||||
{
|
||||
public function index(Request $request, PeopleRegistry $registry): Response
|
||||
{
|
||||
abort_unless($registry->canRead($request->user()), 403);
|
||||
abort_unless($registry->canRead($this->staffIdentity($request)), 403);
|
||||
$filter = $request->validate(['search' => 'nullable|string|max:100', 'status' => 'nullable|in:active,archived,all']);
|
||||
$ready = Schema::hasTable('people_registry');
|
||||
$records = null;
|
||||
if ($ready) {
|
||||
$query = $registry->visible($request->user());
|
||||
$query = $registry->visible($this->staffIdentity($request));
|
||||
if (($filter['search'] ?? '') !== '') {
|
||||
$query->where(fn ($q) => $q->whereLike('name', '%'.$filter['search'].'%')->orWhereLike('reference', '%'.$filter['search'].'%'));
|
||||
}
|
||||
if (($filter['status'] ?? 'active') !== 'all') {
|
||||
$query->where('active', ($filter['status'] ?? 'active') === 'active');
|
||||
}
|
||||
$records = $query->orderBy('name')->orderBy('id')->paginate(15)->withQueryString()->through(fn ($row) => $registry->item($request->user(), $row));
|
||||
$records = $query->orderBy('name')->orderBy('id')->paginate(15)->withQueryString()->through(fn ($row) => $registry->item($this->staffIdentity($request), $row));
|
||||
}
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('people/registry', ['ready' => $ready, 'canCreate' => $registry->canCreate($request->user()), 'records' => $records, 'filters' => $filter])->toResponse($request);
|
||||
$response = Inertia::render('people/registry', ['ready' => $ready, 'canCreate' => $registry->canCreate($this->staffIdentity($request)), 'records' => $records, 'filters' => $filter])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
@@ -36,7 +36,7 @@ class PeopleRegistryController extends Controller
|
||||
public function save(Request $request, PeopleRegistry $registry, ?int $person = null): Response
|
||||
{
|
||||
abort_unless(Schema::hasTable('people_registry'), 503, 'Instalação do cadastro de pessoas pendente.');
|
||||
$record = $registry->execute($request->user(), $person, $request->all());
|
||||
$record = $registry->execute($this->staffIdentity($request), $person, $request->all());
|
||||
|
||||
return redirect('/pessoas/cadastro?'.http_build_query(['search' => $record->reference, 'status' => 'all']));
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@ namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Services\AiPreparationPlan;
|
||||
use App\Services\IntelligencePolicy;
|
||||
use App\Services\ProcurementEvidenceBrief;
|
||||
use App\Services\ProcurementReviewCsv;
|
||||
use App\Services\ProcurementReviewReport;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
@@ -14,11 +16,27 @@ use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
class ProcurementReviewReportController extends Controller
|
||||
{
|
||||
public function csv(Request $request, Requisition $requisition, ProcurementReviewReport $builder, ProcurementReviewCsv $csv): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$report = $builder->build($actor, $requisition->id);
|
||||
|
||||
return response($csv->render($report), 200, [
|
||||
'Content-Type' => 'text/csv; charset=UTF-8',
|
||||
'Content-Disposition' => 'attachment; filename="conferencia-requisicao-'.$requisition->id.'.csv"',
|
||||
'Cache-Control' => 'private, no-store, max-age=0',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
]);
|
||||
}
|
||||
|
||||
public function show(Request $request, Requisition $requisition, ProcurementReviewReport $builder): Response
|
||||
{
|
||||
$report = $builder->build($request->user(), $requisition->id);
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$report = $builder->build($actor, $requisition->id);
|
||||
Inertia::encryptHistory();
|
||||
$company = Tenant::query()->findOrFail($request->user()->tenant_id);
|
||||
$company = Tenant::query()->findOrFail($actor->tenant_id);
|
||||
$policy = app(IntelligencePolicy::class)->company($company);
|
||||
$brief = app(ProcurementEvidenceBrief::class)->build($report);
|
||||
$response = Inertia::render('purchases/review-report', ['report' => $report, 'brief' => $policy['procurement_brief'] ? $brief : null,
|
||||
|
||||
@@ -19,9 +19,9 @@ class ProposalOpeningController extends Controller
|
||||
{
|
||||
private function access(Request $request, int $requisitionId): Requisition
|
||||
{
|
||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||
|
||||
return Requisition::query()->visibleTo($request->user())->findOrFail($requisitionId);
|
||||
return Requisition::query()->visibleTo($this->staffIdentity($request))->findOrFail($requisitionId);
|
||||
}
|
||||
|
||||
public function show(Request $request, Requisition $requisition, ProposalOpeningWorkflow $workflow): Response
|
||||
@@ -36,7 +36,7 @@ class ProposalOpeningController extends Controller
|
||||
'requisition' => $requisition->only(['id', 'number', 'justification']), 'proposals' => $proposals, 'basisHash' => $workflow->basis($proposals), 'openings' => $openings,
|
||||
'sourceChanged' => $latest && $workflow->basis($proposals) !== $latest->basis_hash,
|
||||
'latestId' => $latest->id ?? 0,
|
||||
'canRecord' => $request->user()->hasFunctions([PurchasingRole::Procurement]) && $requisition->status === 'approved' && ! PurchaseAward::query()->where('requisition_id', $requisition->id)->exists() && ! app(ConflictGuard::class)->participationBlocked($request->user(), $requisition),
|
||||
'canRecord' => $this->staffIdentity($request)->hasFunctions([PurchasingRole::Procurement]) && $requisition->status === 'approved' && ! PurchaseAward::query()->where('requisition_id', $requisition->id)->exists() && ! app(ConflictGuard::class)->participationBlocked($this->staffIdentity($request), $requisition),
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
@@ -68,7 +68,7 @@ class ProposalOpeningController extends Controller
|
||||
$data['opened_at'] = $opened->utc()->format('Y-m-d H:i:s');
|
||||
$data['submission_deadline'] = empty($data['submission_deadline']) ? null : CarbonImmutable::createFromFormat('!Y-m-d\TH:i', $data['submission_deadline'], $data['timezone'])->utc()->format('Y-m-d H:i:s');
|
||||
$data['quotation_ids'] = array_map(intval(...), $data['quotation_ids']);
|
||||
$workflow->record($request->user(), $requisition, $data);
|
||||
$workflow->record($this->staffIdentity($request), $requisition, $data);
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ class PurchaseControlController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$user = $request->user();
|
||||
$user = $this->staffIdentity($request);
|
||||
$operational = $user->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]);
|
||||
$sources = Requisition::query()->where('requester_id', $user->id)->select('id');
|
||||
$ownAwards = PurchaseAward::query()->whereIn('requisition_id', $sources)->select('id');
|
||||
@@ -45,9 +45,9 @@ class PurchaseControlController extends Controller
|
||||
|
||||
public function propose(Request $request, PurchaseControlPolicyWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin]), 403);
|
||||
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin]), 403);
|
||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'mode' => 'required|in:unissued_award', 'enabled' => 'required|boolean', 'valid_from' => 'required|date_format:Y-m-d', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:valid_from', 'reason' => 'required|string|min:10|max:4000']);
|
||||
$workflow->propose($request->user(), $data);
|
||||
$workflow->propose($this->staffIdentity($request), $data);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -55,7 +55,7 @@ class PurchaseControlController extends Controller
|
||||
public function policyReview(Request $request, PurchaseControlPolicy $policy, PurchaseControlPolicyWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000']);
|
||||
$workflow->review($request->user(), $policy, $data['decision'], $data['reason']);
|
||||
$workflow->review($this->staffIdentity($request), $policy, $data['decision'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -63,7 +63,7 @@ class PurchaseControlController extends Controller
|
||||
public function cancel(Request $request, PurchaseAward $award, PurchaseRevisionWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['reason' => 'required|string|min:10|max:4000']);
|
||||
$workflow->request($request->user(), $award, $data['reason']);
|
||||
$workflow->request($this->staffIdentity($request), $award, $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -71,7 +71,7 @@ class PurchaseControlController extends Controller
|
||||
public function review(Request $request, AwardCancellation $cancellation, PurchaseRevisionWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|min:10|max:4000']);
|
||||
$workflow->review($request->user(), $cancellation, $data['decision'], $data['reason']);
|
||||
$workflow->review($this->staffIdentity($request), $cancellation, $data['decision'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -79,7 +79,7 @@ class PurchaseControlController extends Controller
|
||||
public function revise(Request $request, AwardCancellation $cancellation, PurchaseRevisionWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['needed_by' => 'required|date_format:Y-m-d|after_or_equal:today', 'justification' => 'required|string|min:10|max:4000']);
|
||||
$revision = $workflow->revise($request->user(), $cancellation, $data['needed_by'], $data['justification']);
|
||||
$revision = $workflow->revise($this->staffIdentity($request), $cancellation, $data['needed_by'], $data['justification']);
|
||||
|
||||
return to_route('requisitions.edit', $revision);
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ class PurchasePlanningController extends Controller
|
||||
{
|
||||
public function index(Request $request): Response
|
||||
{
|
||||
$actor = $request->user();
|
||||
$actor = $this->staffIdentity($request);
|
||||
$canManage = $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement]);
|
||||
$filters = $request->validate(['item' => 'nullable|integer|min:1']);
|
||||
$items = PurchasePlanItem::query()->visibleTo($actor)->when($filters['item'] ?? null, fn ($query, $id) => $query->whereKey($id))->latest('id')->paginate(15)->withQueryString();
|
||||
@@ -62,7 +62,7 @@ class PurchasePlanningController extends Controller
|
||||
$data = $request->validate(['title' => 'required|string|min:3|max:200', 'department_id' => 'required|integer', 'responsible_id' => 'required|integer', 'requisition_id' => 'nullable|integer', 'nature' => 'required|in:goods,works,services,consulting']);
|
||||
$data['department_id'] = (int) $data['department_id'];
|
||||
$data['responsible_id'] = (int) $data['responsible_id'];
|
||||
$workflow->create($request->user(), $data);
|
||||
$workflow->create($this->staffIdentity($request), $data);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -70,7 +70,7 @@ class PurchasePlanningController extends Controller
|
||||
public function assign(Request $request, PurchasePlanItem $item, PurchasePlanningWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['responsible_id' => 'required|integer', 'version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:2000']);
|
||||
$workflow->assign($request->user(), $item, (int) $data['responsible_id'], (int) $data['version'], $data['reason']);
|
||||
$workflow->assign($this->staffIdentity($request), $item, (int) $data['responsible_id'], (int) $data['version'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -78,7 +78,7 @@ class PurchasePlanningController extends Controller
|
||||
public function milestone(Request $request, PurchasePlanItem $item, PurchasePlanningWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['label' => 'required|string|min:3|max:120', 'planned_on' => 'required|date_format:Y-m-d']);
|
||||
$workflow->milestone($request->user(), $item, $data['label'], $data['planned_on']);
|
||||
$workflow->milestone($this->staffIdentity($request), $item, $data['label'], $data['planned_on']);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -86,7 +86,7 @@ class PurchasePlanningController extends Controller
|
||||
public function link(Request $request, PurchasePlanItem $item, PurchasePlanningWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$data = $request->validate(['requisition_id' => 'required|integer', 'version' => 'required|integer|min:1', 'reason' => 'required|string|min:10|max:2000']);
|
||||
$workflow->link($request->user(), $item, (int) $data['requisition_id'], (int) $data['version'], $data['reason']);
|
||||
$workflow->link($this->staffIdentity($request), $item, (int) $data['requisition_id'], (int) $data['version'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -104,7 +104,7 @@ class PurchasePlanningController extends Controller
|
||||
if (array_key_exists('actual_on', $data)) {
|
||||
$changes['actual_on'] = $data['actual_on'];
|
||||
}
|
||||
$workflow->update($request->user(), $milestone, $changes);
|
||||
$workflow->update($this->staffIdentity($request), $milestone, $changes);
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\ProposalEvaluation;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\Supplier;
|
||||
@@ -11,7 +12,9 @@ use App\Models\User;
|
||||
use App\Services\ComparisonPolicy;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\CurrentActor;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\ProposalComparison;
|
||||
use App\Services\QuotationExchange;
|
||||
use App\Services\QuotationParticipation;
|
||||
use App\Services\QuotationPricing;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
@@ -69,6 +72,10 @@ class QuotationController extends Controller
|
||||
'ready' => $result['ready'],
|
||||
'topIds' => $result['top_ids'],
|
||||
'comparisonPolicy' => $result['policy'],
|
||||
'exchangeRates' => app(QuotationExchange::class)->rates($requisition),
|
||||
'exchangeAvailable' => app(QuotationExchange::class)->ready(),
|
||||
'canRecordExchange' => $actor->hasFunctions([PurchasingRole::Finance]) && ! app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||
&& $requisition->status === 'approved' && ! PurchaseAward::query()->where('requisition_id', $requisition->id)->exists(),
|
||||
])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
@@ -80,6 +87,7 @@ class QuotationController extends Controller
|
||||
$actor = $this->access($request);
|
||||
abort_unless($actor->hasFunctions([PurchasingRole::Procurement]), 403);
|
||||
$data = $request->validate([
|
||||
'currency' => ['sometimes', 'required', 'regex:/^[A-Z]{3}$/'],
|
||||
'supplier_id' => 'required|integer', 'reference' => 'required|string|max:100',
|
||||
'delivery_days' => 'required|integer|min:1|max:3650', 'valid_until' => 'required|date_format:Y-m-d|after_or_equal:today',
|
||||
'payment_terms' => 'required|string|min:3|max:500', 'no_conflict' => 'accepted',
|
||||
@@ -103,6 +111,8 @@ class QuotationController extends Controller
|
||||
throw ValidationException::withMessages(['supplier_id' => 'Já existe uma proposta deste fornecedor neste processo.']);
|
||||
}
|
||||
$lines = $requisition->items()->get()->keyBy('id');
|
||||
$currency = $data['currency'] ?? 'MZN';
|
||||
$exchange = app(QuotationExchange::class)->basis($requisition, $currency);
|
||||
if ($lines->count() !== count($data['items'])) {
|
||||
throw ValidationException::withMessages(['items' => 'A proposta deve conter todas as linhas da requisição.']);
|
||||
}
|
||||
@@ -128,16 +138,18 @@ class QuotationController extends Controller
|
||||
$items[] = ['tenant_id' => $actor->tenant_id, 'requisition_item_id' => $line->id, 'description' => $line->description, 'quantity' => $line->quantity, 'unit_price_minor' => $price, 'tax_rate' => $line->tax_rate, 'subtotal_minor' => $amount, 'tax_minor' => $vat, 'total_minor' => $amount + $vat];
|
||||
}
|
||||
if ($subtotal <= 0) {
|
||||
throw ValidationException::withMessages(['items' => 'O total arredondado deve ser pelo menos 0,01 MZN.']);
|
||||
throw ValidationException::withMessages(['items' => 'O total arredondado deve ser pelo menos 0,01 na moeda da proposta.']);
|
||||
}
|
||||
$quote = Quotation::query()->create([
|
||||
'tenant_id' => $actor->tenant_id, 'requisition_id' => $requisition->id, 'supplier_id' => $supplier->id, 'created_by' => $actor->id,
|
||||
'reference' => $data['reference'], 'delivery_days' => $data['delivery_days'], 'valid_until' => $data['valid_until'], 'payment_terms' => $data['payment_terms'],
|
||||
'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'currency' => 'MZN',
|
||||
'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'currency' => $currency,
|
||||
...($exchange === null ? [] : ['exchange_basis' => $exchange]),
|
||||
'weights' => app(ComparisonPolicy::class)->forRequest($requisition)['weights'],
|
||||
'commercial_terms' => array_filter($terms, fn ($term) => $term['discount_type'] !== 'none') === [] ? null : ['version' => 1, 'discount_basis' => 'unit_before_vat', 'rounding' => 'net_unit_half_up_cent', 'lines' => $terms],
|
||||
]);
|
||||
$quote->items()->createMany($items);
|
||||
app(QuotationExchange::class)->amounts($quote);
|
||||
$workflow->audit($actor, 'quotation.created', $requisition, null, [...$quote->load('items')->toArray(), 'no_conflict' => true]);
|
||||
});
|
||||
|
||||
@@ -162,4 +174,12 @@ class QuotationController extends Controller
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
public function recordExchange(Request $request, Requisition $requisition, QuotationExchange $exchange): RedirectResponse
|
||||
{
|
||||
$actor = $this->access($request);
|
||||
$exchange->record($actor, $requisition, $request->only(['operation_id', 'currency', 'rate', 'quoted_on', 'source']));
|
||||
|
||||
return back();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,15 +14,15 @@ class RequisitionCatalogueController extends Controller
|
||||
{
|
||||
public function index(Request $request, RequisitionCatalogue $catalogue): Response
|
||||
{
|
||||
abort_unless($request->user()->hasFunctions(['admin', 'warehouse']), 403);
|
||||
abort_unless($this->staffIdentity($request)->hasFunctions(['admin', 'warehouse']), 403);
|
||||
$filter = $request->validate(['search' => 'nullable|string|max:100']);
|
||||
$ready = Schema::hasTable('requisition_catalogue');
|
||||
$query = StockItem::query()->where('tenant_id', $request->user()->tenant_id);
|
||||
$query = StockItem::query()->where('tenant_id', $this->staffIdentity($request)->tenant_id);
|
||||
if (($filter['search'] ?? '') !== '') {
|
||||
$query->where(fn ($q) => $q->whereLike('name', '%'.$filter['search'].'%')->orWhereLike('code', '%'.$filter['search'].'%'));
|
||||
}
|
||||
$records = $query->orderBy('code')->paginate(15)->withQueryString();
|
||||
$entries = $ready ? DB::table('requisition_catalogue')->where('tenant_id', $request->user()->tenant_id)->whereIn('stock_item_id', $records->pluck('id'))->get()->keyBy('stock_item_id') : collect();
|
||||
$entries = $ready ? DB::table('requisition_catalogue')->where('tenant_id', $this->staffIdentity($request)->tenant_id)->whereIn('stock_item_id', $records->pluck('id'))->get()->keyBy('stock_item_id') : collect();
|
||||
$records->through(function (StockItem $stock) use ($entries, $catalogue) {
|
||||
$entry = $entries->get($stock->id);
|
||||
|
||||
@@ -31,7 +31,7 @@ class RequisitionCatalogueController extends Controller
|
||||
'source_current' => $entry === null || json_decode($entry->source_snapshot, true, 16, JSON_THROW_ON_ERROR) === $catalogue->source($stock)];
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('stock/catalogue', ['records' => $records, 'ready' => $ready, 'canManage' => $catalogue->canManage($request->user()), 'filters' => $filter])->toResponse($request);
|
||||
$response = Inertia::render('stock/catalogue', ['records' => $records, 'ready' => $ready, 'canManage' => $catalogue->canManage($this->staffIdentity($request)), 'filters' => $filter])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
@@ -40,7 +40,7 @@ class RequisitionCatalogueController extends Controller
|
||||
public function save(Request $request, int $stock, RequisitionCatalogue $catalogue): Response
|
||||
{
|
||||
abort_unless(Schema::hasTable('requisition_catalogue'), 503, 'Instalação do catálogo pendente.');
|
||||
$catalogue->save($request->user(), $stock, $request->all());
|
||||
$catalogue->save($this->staffIdentity($request), $stock, $request->all());
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
@@ -1,47 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Services\SgfInvoiceDispatches;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
final class SgfInvoiceDispatchController extends Controller
|
||||
{
|
||||
private function actor(Request $r,SgfInvoiceDispatches $service):User
|
||||
{ $user=$r->user('web');abort_unless($user instanceof User,403);return $service->actor($user); }
|
||||
public function index(Request $r,SgfInvoiceDispatches $service)
|
||||
private function actor(Request $r, SgfInvoiceDispatches $service): User
|
||||
{
|
||||
$user=$this->actor($r,$service);$d=$r->validate(['page'=>'sometimes|integer|min:1|max:100000','phase'=>'nullable|in:draft,previewing,previewed,sending,uncertain,received_pending,blocked,review_required,not_sent','connection'=>'nullable|string|max:64','mapping'=>'nullable|string|max:64']);
|
||||
abort_if(array_diff(array_keys($r->query()),array_keys($d)),422);
|
||||
$rows=DB::table('sgf_invoice_dispatches')->where('tenant_id',$user->tenant_id)->when($d['phase']??null,fn($q,$v)=>$q->where('phase',$v))
|
||||
->orderByDesc('id')->paginate(25,['id','reference','number','phase','version','updated_at'])->withQueryString();
|
||||
$mapping=null;foreach($service->mappings($user)as$m)if($m['connection']===($d['connection']??null)&&$m['id']===($d['mapping']??null))$mapping=$m;
|
||||
return response()->view('sgf-invoices.index',['rows'=>$rows,'options'=>$service->mappings($user),'selection'=>$mapping])->header('Cache-Control','private, no-store');
|
||||
$user = $r->user('web');
|
||||
abort_unless($user instanceof User, 403);
|
||||
|
||||
return $service->actor($user);
|
||||
}
|
||||
public function show(int $id,Request $r,SgfInvoiceDispatches $service)
|
||||
|
||||
public function index(Request $r, SgfInvoiceDispatches $service): Response
|
||||
{
|
||||
$user=$this->actor($r,$service);$d=$r->validate(['events_page'=>'sometimes|integer|min:1|max:100000']);abort_if(array_diff(array_keys($r->query()),array_keys($d)),422);
|
||||
$row=$service->row($user,$id);$events=DB::table('sgf_invoice_dispatch_events')->where('tenant_id',$user->tenant_id)->where('dispatch_id',$id)->orderByDesc('id')
|
||||
->paginate(25,['actor_id','action','reason','before_state','after_state','created_at'],'events_page')->withQueryString();
|
||||
return response()->view('sgf-invoices.show',['row'=>$service->presentation($user,$row),'events'=>$events,'options'=>$service->mappings($user),'transportEnabled'=>config('sgf_invoice.enabled')===true])->header('Cache-Control','private, no-store');
|
||||
$user = $this->actor($r, $service);
|
||||
$d = $r->validate(['page' => 'sometimes|integer|min:1|max:100000', 'phase' => 'nullable|in:draft,previewing,previewed,sending,uncertain,received_pending,blocked,review_required,not_sent', 'connection' => 'nullable|string|max:64', 'mapping' => 'nullable|string|max:64']);
|
||||
abort_if(array_diff(array_keys($r->query()), array_keys($d)) !== [], 422);
|
||||
$rows = DB::table('sgf_invoice_dispatches')->where('tenant_id', $user->tenant_id)->when($d['phase'] ?? null, fn ($q, $v) => $q->where('phase', $v))
|
||||
->orderByDesc('id')->paginate(25, ['id', 'reference', 'number', 'phase', 'version', 'updated_at'])->withQueryString();
|
||||
$mapping = null;
|
||||
foreach ($service->mappings($user) as $m) {
|
||||
if ($m['connection'] === ($d['connection'] ?? null) && $m['id'] === ($d['mapping'] ?? null)) {
|
||||
$mapping = $m;
|
||||
}
|
||||
}
|
||||
|
||||
return response()->view('sgf-invoices.index', ['rows' => $rows, 'options' => $service->mappings($user), 'selection' => $mapping])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
public function create(Request $r,SgfInvoiceDispatches $service)
|
||||
|
||||
public function show(int $id, Request $r, SgfInvoiceDispatches $service): Response
|
||||
{
|
||||
$user=$this->actor($r,$service);$input=$r->except('_token');$id=$service->create($user,$input);
|
||||
$user = $this->actor($r, $service);
|
||||
$d = $r->validate(['events_page' => 'sometimes|integer|min:1|max:100000']);
|
||||
abort_if(array_diff(array_keys($r->query()), array_keys($d)) !== [], 422);
|
||||
$row = $service->row($user, $id);
|
||||
$events = DB::table('sgf_invoice_dispatch_events')->where('tenant_id', $user->tenant_id)->where('dispatch_id', $id)->orderByDesc('id')
|
||||
->paginate(25, ['actor_id', 'action', 'reason', 'before_state', 'after_state', 'created_at'], 'events_page')->withQueryString();
|
||||
|
||||
return response()->view('sgf-invoices.show', ['row' => $service->presentation($user, $row), 'events' => $events, 'options' => $service->mappings($user), 'transportEnabled' => config('sgf_invoice.enabled') === true])->header('Cache-Control', 'private, no-store');
|
||||
}
|
||||
|
||||
public function create(Request $r, SgfInvoiceDispatches $service): RedirectResponse
|
||||
{
|
||||
$user = $this->actor($r, $service);
|
||||
$input = $r->except('_token');
|
||||
$id = $service->create($user, $input);
|
||||
|
||||
return redirect('/facturas/envio-sgf/'.$id);
|
||||
}
|
||||
public function revise(int $id,Request $r,SgfInvoiceDispatches $service)
|
||||
|
||||
public function revise(int $id, Request $r, SgfInvoiceDispatches $service): RedirectResponse
|
||||
{
|
||||
$user=$this->actor($r,$service);$d=$r->validate(['version'=>'required|integer|min:1']);
|
||||
$service->revise($user,$id,(int)$d['version'],$r->except('_token','version'));
|
||||
$user = $this->actor($r, $service);
|
||||
$d = $r->validate(['version' => 'required|integer|min:1']);
|
||||
$service->revise($user, $id, (int) $d['version'], $r->except('_token', 'version'));
|
||||
|
||||
return redirect('/facturas/envio-sgf/'.$id);
|
||||
}
|
||||
public function dispatch(int $id,Request $r,SgfInvoiceDispatches $service)
|
||||
|
||||
public function dispatch(int $id, Request $r, SgfInvoiceDispatches $service): RedirectResponse
|
||||
{
|
||||
$user=$this->actor($r,$service);$d=$r->validate(['version'=>'required|integer|min:1','action'=>'required|in:preview,confirm,recover','reason'=>'required|string|min:10|max:2000','approval_hash'=>'nullable|string|size:64']);
|
||||
abort_if(array_diff(array_keys($r->except('_token')),array_keys($d)),422);
|
||||
$service->dispatch($user,$id,(int)$d['version'],$d['action'],$d['reason'],$d['approval_hash']??null);
|
||||
$user = $this->actor($r, $service);
|
||||
$d = $r->validate(['version' => 'required|integer|min:1', 'action' => 'required|in:preview,confirm,recover', 'reason' => 'required|string|min:10|max:2000', 'approval_hash' => 'nullable|string|size:64']);
|
||||
abort_if(array_diff(array_keys($r->except('_token')), array_keys($d)) !== [], 422);
|
||||
$service->dispatch($user, $id, (int) $d['version'], $d['action'], $d['reason'], $d['approval_hash'] ?? null);
|
||||
|
||||
return redirect('/facturas/envio-sgf/'.$id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ class SubmissionFormsController extends Controller
|
||||
{
|
||||
public function index(Request $request, SubmissionForms $forms, OrganizationConfiguration $configuration): Response
|
||||
{
|
||||
$actor = $configuration->administrator($request->user());
|
||||
$actor = $configuration->administrator($this->staffIdentity($request));
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('company/submission-forms', ['forms' => $forms->listing($actor), 'canManage' => $forms->canManage($actor),
|
||||
'ready' => Schema::hasTable('submission_forms'), 'externalPortalAvailable' => false])->toResponse($request);
|
||||
@@ -24,7 +24,7 @@ class SubmissionFormsController extends Controller
|
||||
|
||||
public function save(Request $request, SubmissionForms $forms): Response
|
||||
{
|
||||
$forms->save($request->user(), $request->all());
|
||||
$forms->save($this->staffIdentity($request), $request->all());
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
@@ -18,18 +18,31 @@ class SupplierBankController extends Controller
|
||||
{
|
||||
public function show(Request $request, Supplier $supplier, SupplierBankWorkflow $workflow): Response
|
||||
{
|
||||
abort_unless($request->user()->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]), 403);
|
||||
$details = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->get();
|
||||
abort_unless($this->staffIdentity($request)->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance]), 403);
|
||||
$filters = $request->validate(['account' => 'nullable|uuid']);
|
||||
$key = isset($filters['account']) ? strtolower($filters['account']) : null;
|
||||
$details = $workflow->account($supplier, $key)->latest('revision')->get();
|
||||
$current = $details->first();
|
||||
$canRead = $request->user()->hasFunctions([PurchasingRole::Procurement, PurchasingRole::Finance]);
|
||||
abort_unless($key === null || $current !== null, 404);
|
||||
$canRead = $this->staffIdentity($request)->hasFunctions([PurchasingRole::Procurement, PurchasingRole::Finance]);
|
||||
$data = null;
|
||||
if ($current && $canRead) {
|
||||
app(RequisitionWorkflow::class)->audit($request->user(), 'supplier.bank_viewed', null, null, ['supplier_id' => $supplier->id, 'bank_detail_id' => $current->id]);
|
||||
app(RequisitionWorkflow::class)->audit($this->staffIdentity($request), 'supplier.bank_viewed', null, null, ['supplier_id' => $supplier->id, 'bank_detail_id' => $current->id]);
|
||||
$data = [...$current->toArray(), ...$current->only(['account_identifier', 'beneficiary', 'evidence_reference', 'reason'])];
|
||||
}
|
||||
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('suppliers/bank', ['supplier' => $supplier->only(['id', 'name']), 'current' => $data, 'currentId' => $current->id ?? 0, 'state' => $workflow->state($supplier), 'history' => $details->map(fn ($detail) => $detail->only(['id', 'revision', 'created_by', 'created_at'])), 'reviews' => SupplierBankReview::query()->whereIn('supplier_bank_detail_id', $details->pluck('id'))->orderBy('id')->get(), 'canPropose' => $request->user()->hasFunctions([PurchasingRole::Procurement]), 'canReview' => $current && $request->user()->hasFunctions([PurchasingRole::Finance]) && $current->created_by !== $request->user()->id && ! SupplierBankReview::query()->where('supplier_bank_detail_id', $current->id)->where('reviewed_by', $request->user()->id)->exists()])->toResponse($request);
|
||||
$response = Inertia::render('suppliers/bank', ['supplier' => $supplier->only(['id', 'name']), 'current' => $data, 'currentId' => $current->id ?? 0,
|
||||
'accountKey' => $key, 'actorId' => $this->staffIdentity($request)->id, 'multiAccountsAvailable' => $workflow->multipleReady(),
|
||||
'accounts' => $workflow->currentAccounts($supplier)->map(fn (SupplierBankDetail $detail) => [
|
||||
'id' => $detail->id, 'key' => $detail->account_key, 'revision' => $detail->revision,
|
||||
'label' => $canRead ? $detail->bank_name.' · '.$detail->currency.' · v'.$detail->revision : 'Conta #'.$detail->id.' · v'.$detail->revision,
|
||||
'state' => $workflow->state($supplier, $detail->account_key),
|
||||
]),
|
||||
'state' => $workflow->state($supplier, $key), 'history' => $details->map(fn ($detail) => $detail->only(['id', 'revision', 'created_by', 'created_at'])),
|
||||
'reviews' => SupplierBankReview::query()->whereIn('supplier_bank_detail_id', $details->pluck('id'))->orderBy('id')->get(),
|
||||
'canPropose' => $this->staffIdentity($request)->hasFunctions([PurchasingRole::Procurement]),
|
||||
'canReview' => $current !== null && $workflow->canReview($this->staffIdentity($request), $current)])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
@@ -38,8 +51,11 @@ class SupplierBankController extends Controller
|
||||
public function store(Request $request, Supplier $supplier, SupplierBankWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$request->merge(['country' => Str::upper(trim($request->string('country')->toString())), 'currency' => Str::upper(trim($request->string('currency')->toString())), 'account_identifier' => Str::upper(preg_replace('/\s+/', '', $request->string('account_identifier')->toString()) ?? '')]);
|
||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'bank_name' => 'required|string|max:200', 'country' => ['required', 'regex:/^[A-Z]{2}$/'], 'currency' => ['required', 'regex:/^[A-Z]{3}$/'], 'beneficiary' => 'required|string|max:200', 'account_identifier' => ['required', 'regex:/^[A-Z0-9.\/-]{4,100}$/'], 'evidence_reference' => 'required|string|max:1000', 'reason' => 'required|string|max:2000']);
|
||||
$workflow->propose($request->user(), $supplier, $data);
|
||||
$data = $request->validate(['previous_id' => 'required|integer|min:0', 'account_key' => 'nullable|uuid', 'bank_name' => 'required|string|max:200', 'country' => ['required', 'regex:/^[A-Z]{2}$/'], 'currency' => ['required', 'regex:/^[A-Z]{3}$/'], 'beneficiary' => 'required|string|max:200', 'account_identifier' => ['required', 'regex:/^[A-Z0-9.\/-]{4,100}$/'], 'evidence_reference' => 'required|string|max:1000', 'reason' => 'required|string|max:2000']);
|
||||
$detail = $workflow->propose($this->staffIdentity($request), $supplier, $data);
|
||||
if ($detail->account_key !== null) {
|
||||
return redirect('/fornecedores/'.$supplier->id.'/dados-bancarios?account='.rawurlencode($detail->account_key));
|
||||
}
|
||||
|
||||
return back();
|
||||
}
|
||||
@@ -48,7 +64,7 @@ class SupplierBankController extends Controller
|
||||
{
|
||||
abort_unless($detail->supplier_id === $supplier->id, 404);
|
||||
$data = $request->validate(['decision' => 'required|in:approved,rejected', 'reason' => 'required|string|max:2000', 'independently_verified' => 'accepted']);
|
||||
$workflow->review($request->user(), $detail, $data['decision'], $data['reason']);
|
||||
$workflow->review($this->staffIdentity($request), $detail, $data['decision'], $data['reason']);
|
||||
|
||||
return back();
|
||||
}
|
||||
|
||||
@@ -4,6 +4,9 @@ namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierDocument;
|
||||
use App\Models\User;
|
||||
use App\Services\ConflictGuard;
|
||||
use App\Services\CurrentActor;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
@@ -20,6 +23,8 @@ class SupplierDocumentController extends Controller
|
||||
{
|
||||
public function store(Request $request, Supplier $supplier, RequisitionWorkflow $workflow): RedirectResponse
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
Gate::authorize('update', $supplier);
|
||||
$data = $request->validate([
|
||||
'document_type' => ['required', Rule::in(['license', 'tax', 'conflict', 'other'])],
|
||||
@@ -30,18 +35,21 @@ class SupplierDocumentController extends Controller
|
||||
$path = $file->store($supplier->tenant_id.'/'.$supplier->id, 'supplier_documents');
|
||||
abort_if($path === false, 500);
|
||||
try {
|
||||
DB::transaction(function () use ($request, $supplier, $workflow, $data, $file, $path) {
|
||||
DB::transaction(function () use ($actor, $supplier, $workflow, $data, $file, $path) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
|
||||
Gate::forUser($actor)->authorize('update', $supplier);
|
||||
$before = $supplier->toArray();
|
||||
$name = Str::substr(Str::replaceMatches('/[^\pL\pN ._()-]/u', '_', basename(str_replace('\\', '/', $file->getClientOriginalName()))), 0, 180);
|
||||
$document = $supplier->documents()->create([
|
||||
'tenant_id' => $supplier->tenant_id, 'uploaded_by' => $request->user()->id,
|
||||
'tenant_id' => $supplier->tenant_id, 'uploaded_by' => $actor->id,
|
||||
'document_type' => $data['document_type'], 'original_name' => $name,
|
||||
'path' => $path, 'mime_type' => $file->getMimeType(), 'size' => $file->getSize(),
|
||||
'sha256' => hash_file('sha256', $file->getPathname()),
|
||||
]);
|
||||
$supplier->update(['status' => 'pending', 'reviewed_by' => null, 'review_comment' => null, 'last_changed_by' => $request->user()->id, 'version' => $supplier->version + 1]);
|
||||
$workflow->audit($request->user(), 'supplier.document_uploaded', null, $before, ['supplier' => $supplier->toArray(), 'document' => $document->toArray()]);
|
||||
$supplier->update(['status' => 'pending', 'reviewed_by' => null, 'review_comment' => null, 'last_changed_by' => $actor->id, 'version' => $supplier->version + 1]);
|
||||
$workflow->audit($actor, 'supplier.document_uploaded', null, $before, ['supplier' => $supplier->toArray(), 'document' => $document->toArray()]);
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
Storage::disk('supplier_documents')->delete($path);
|
||||
@@ -53,13 +61,35 @@ class SupplierDocumentController extends Controller
|
||||
|
||||
public function download(Request $request, Supplier $supplier, SupplierDocument $document, RequisitionWorkflow $workflow): StreamedResponse
|
||||
{
|
||||
Gate::authorize('viewDocuments', $supplier);
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
|
||||
Gate::forUser($actor)->authorize('viewDocuments', $supplier);
|
||||
abort_unless($document->supplier_id === $supplier->id, 404);
|
||||
$prefix = $supplier->tenant_id.'/'.$supplier->id.'/';
|
||||
abort_unless(str_starts_with($document->path, $prefix)
|
||||
&& preg_match('/\A[A-Za-z0-9_-]+\.[A-Za-z0-9]+\z/D', substr($document->path, strlen($prefix))), 409,
|
||||
'Documento indisponível para descarga. Solicite conferência ao responsável.');
|
||||
$disk = Storage::disk('supplier_documents');
|
||||
abort_unless($disk->exists($document->path), 404);
|
||||
$workflow->audit($request->user(), 'supplier.document_downloaded', null, null, ['supplier_id' => $supplier->id, 'document_id' => $document->id, 'name' => $document->original_name]);
|
||||
$stream = $disk->readStream($document->path);
|
||||
abort_unless(is_resource($stream), 404);
|
||||
try {
|
||||
// Capture at most the accepted upload size plus one byte. The response uses
|
||||
// these verified bytes even if the underlying file subsequently changes.
|
||||
$content = stream_get_contents($stream, 2097153);
|
||||
} finally {
|
||||
fclose($stream);
|
||||
}
|
||||
abort_unless(is_string($content) && strlen($content) > 0 && strlen($content) <= 2097152
|
||||
&& strlen($content) === (int) $document->size
|
||||
&& hash_equals($document->sha256, hash('sha256', $content)), 409,
|
||||
'Documento indisponível para descarga. Solicite conferência ao responsável.');
|
||||
$workflow->audit($actor, 'supplier.document_downloaded', null, null, ['supplier_id' => $supplier->id, 'document_id' => $document->id, 'name' => $document->original_name]);
|
||||
|
||||
return $disk->download($document->path, $document->original_name, [
|
||||
return response()->streamDownload(static function () use ($content): void {
|
||||
echo $content;
|
||||
}, $document->original_name, [
|
||||
'Content-Type' => 'application/octet-stream',
|
||||
'X-Content-Type-Options' => 'nosniff',
|
||||
'Cache-Control' => 'private, no-store',
|
||||
|
||||
@@ -37,7 +37,7 @@ class SupplierImprovementController extends Controller
|
||||
$rules += ['result' => 'prohibited', 'evidence' => 'prohibited'];
|
||||
}
|
||||
}
|
||||
$workflow->execute($request->user(), $evaluation, $measure, $command, $request->validate($rules));
|
||||
$workflow->execute($this->staffIdentity($request), $evaluation, $measure, $command, $request->validate($rules));
|
||||
|
||||
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Medida de melhoria e histórico actualizados.');
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ class SupplierResponseController extends Controller
|
||||
} else {
|
||||
$rules += ['outcome' => 'prohibited', 'follow_up' => 'prohibited', 'response_reference' => 'prohibited'];
|
||||
}
|
||||
$workflow->execute($request->user(), $evaluation, $record, $command, $request->validate($rules));
|
||||
$workflow->execute($this->staffIdentity($request), $evaluation, $record, $command, $request->validate($rules));
|
||||
|
||||
return to_route('supplier-evaluations.show', $evaluation)->with('supplier_evaluation_notice', 'Contraditório e histórico actualizados.');
|
||||
}
|
||||
|
||||
@@ -28,6 +28,11 @@ class ConfirmReceiptRequest extends FormRequest
|
||||
'items.*.accepted_quantity' => ['required', 'string', 'numeric', 'min:0', 'max:1000000', 'regex:/^\d+(\.\d{1,3})?$/'],
|
||||
'items.*.quality_status' => ['required', Rule::in(['compliant', 'reservations', 'nonconforming'])],
|
||||
'items.*.notes' => 'nullable|string|max:3000',
|
||||
'items.*.conversion' => 'sometimes|nullable|array:numerator,denominator,source,version',
|
||||
'items.*.conversion.numerator' => ['required_with:items.*.conversion', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
||||
'items.*.conversion.denominator' => ['required_with:items.*.conversion', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
||||
'items.*.conversion.source' => 'required_with:items.*.conversion|string|max:500',
|
||||
'items.*.conversion.version' => 'required_with:items.*.conversion|string|max:100',
|
||||
'items.*.lots' => 'sometimes|array|max:100',
|
||||
'items.*.lots.*.code' => 'nullable|string|max:100',
|
||||
'items.*.lots.*.expires_on' => 'nullable|date_format:Y-m-d',
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Http\Requests;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
@@ -9,18 +10,21 @@ class StoreRequisitionRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
$user = $this->user();
|
||||
$user = $this->user('web');
|
||||
|
||||
return $user !== null && $user->tenant_id !== null && $user->department_id !== null;
|
||||
return $user instanceof User && $user->tenant_id !== null && $user->department_id !== null;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
public function rules(): array
|
||||
{
|
||||
$user = $this->user('web');
|
||||
abort_unless($user instanceof User, 403);
|
||||
|
||||
return [
|
||||
'operation_key' => 'nullable|uuid',
|
||||
'process_version' => 'nullable|integer|min:1',
|
||||
'cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $this->user()?->tenant_id)->where('department_id', $this->user()?->department_id)],
|
||||
'cost_center_id' => ['required', 'integer', Rule::exists('cost_centers', 'id')->where('tenant_id', $user->tenant_id)->where('department_id', $user->department_id)],
|
||||
'priority' => ['required', Rule::in(['normal', 'high', 'urgent'])],
|
||||
'needed_by' => ['required', 'date_format:Y-m-d', 'after_or_equal:today'],
|
||||
'justification' => ['required', 'string', 'min:10', 'max:5000'],
|
||||
@@ -31,8 +35,8 @@ class StoreRequisitionRequest extends FormRequest
|
||||
'items.*.description' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:255'],
|
||||
'items.*.category' => ['required_without:items.*.catalogue_entry_id', 'string', 'max:100'],
|
||||
'items.*.purchase_type' => ['required_without:items.*.catalogue_entry_id', Rule::in(['consumable', 'service', 'other', 'equipment', 'spare_part'])],
|
||||
'items.*.equipment_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('equipment', 'id')->where('tenant_id', $this->user()?->tenant_id)->where('department_id', $this->user()?->department_id)],
|
||||
'items.*.spare_part_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('spare_parts', 'id')->where('tenant_id', $this->user()?->tenant_id)],
|
||||
'items.*.equipment_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('equipment', 'id')->where('tenant_id', $user->tenant_id)->where('department_id', $user->department_id)],
|
||||
'items.*.spare_part_id' => ['exclude_unless:items.*.purchase_type,spare_part', 'required', 'integer', Rule::exists('spare_parts', 'id')->where('tenant_id', $user->tenant_id)],
|
||||
'items.*.production_area' => 'exclude_unless:items.*.purchase_type,equipment|required|string|max:200',
|
||||
'items.*.downtime_started_at' => 'exclude_unless:items.*.purchase_type,spare_part|nullable|date_format:Y-m-d\TH:i|before_or_equal:now',
|
||||
'items.*.quantity' => ['required', 'numeric', 'min:0.001', 'max:1000000', 'regex:/^\d+(\.\d{1,3})?$/'],
|
||||
|
||||
@@ -10,6 +10,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
/**
|
||||
* @property array<string, mixed> $weights
|
||||
* @property array<string, mixed>|null $commercial_terms Stored JSON is validated against the pricing contract before comparison.
|
||||
* @property array<string, mixed>|null $exchange_basis Frozen process rate for original foreign-currency amounts.
|
||||
*/
|
||||
class Quotation extends Model
|
||||
{
|
||||
@@ -19,7 +20,7 @@ class Quotation extends Model
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return ['weights' => 'array', 'commercial_terms' => 'array', 'valid_until' => 'date:Y-m-d'];
|
||||
return ['weights' => 'array', 'commercial_terms' => 'array', 'exchange_basis' => 'array', 'valid_until' => 'date:Y-m-d'];
|
||||
}
|
||||
|
||||
/** @return BelongsTo<Supplier, $this> */
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\AppendOnlyInventoryRecord;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Casts\Attribute;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/** @property int $id
|
||||
@@ -13,6 +14,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
* @property int $revision
|
||||
* @property string $account_identifier
|
||||
* @property string $beneficiary
|
||||
* @property string|null $account_key
|
||||
*/
|
||||
class SupplierBankDetail extends Model
|
||||
{
|
||||
@@ -28,4 +30,12 @@ class SupplierBankDetail extends Model
|
||||
{
|
||||
return ['account_identifier' => 'encrypted', 'beneficiary' => 'encrypted', 'evidence_reference' => 'encrypted', 'reason' => 'encrypted'];
|
||||
}
|
||||
|
||||
/** Missing column means the preserved legacy chain, including before installation.
|
||||
* @return Attribute<string|null,never>
|
||||
*/
|
||||
protected function accountKey(): Attribute
|
||||
{
|
||||
return Attribute::get(fn (?string $value): ?string => $value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,15 +82,17 @@ class ExternalPaymentWorkflow
|
||||
$request = Requisition::query()->findOrFail($order->requisition_id);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user);
|
||||
$supplier = Supplier::query()->lockForUpdate()->findOrFail($order->supplier_id);
|
||||
$bank = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
|
||||
$bank = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->whereKey($bankId)->first();
|
||||
$bankWorkflow = app(SupplierBankWorkflow::class);
|
||||
if ($bank) {
|
||||
User::query()->where('tenant_id', $user->tenant_id)->whereIn('id', SupplierBankReview::query()->where('supplier_bank_detail_id', $bank->id)->select('reviewed_by'))->orderBy('id')->lockForUpdate()->get();
|
||||
}
|
||||
if (! $bank || $bank->id !== $bankId || app(SupplierBankWorkflow::class)->state($supplier) !== 'approved') {
|
||||
if (! $bank || $bankWorkflow->latest($supplier, $bank->account_key)?->id !== $bankId || $bankWorkflow->state($supplier, $bank->account_key) !== 'approved') {
|
||||
$this->invalid('A versão bancária actual deve ter duas validações elegíveis. Actualize a ficha; não reutilize uma versão substituída.');
|
||||
}
|
||||
if ($bank->currency !== $order->currency || $order->currency !== 'MZN') {
|
||||
$this->invalid('A moeda da conta deve coincidir com a factura. Câmbio não suportado.');
|
||||
app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
|
||||
if ($bank->currency !== $order->currency || ($invoice->snapshot['currency'] ?? 'MZN') !== $order->currency) {
|
||||
$this->invalid('A moeda da conta deve coincidir com a factura e a ordem. Não é executada conversão bancária.');
|
||||
}
|
||||
|
||||
return $bank;
|
||||
|
||||
@@ -100,7 +100,9 @@ class FormalRecommendation
|
||||
$admissions = [];
|
||||
foreach ($comparison['rows'] as $row) {
|
||||
// Freeze the decision inputs without supplier contacts or private documents.
|
||||
$rows[] = [...array_intersect_key($row, array_flip(['id', 'supplier_id', 'reference', 'currency', 'subtotal_minor', 'tax_minor', 'total_minor', 'delivery_days', 'valid_until', 'payment_terms', 'weights', 'eligible', 'ineligibility_reasons', 'evaluation_count', 'score_minor', 'items', 'evaluations', 'qualified_evaluations'])), 'supplier_name' => $row['supplier']['name'] ?? 'Fornecedor indisponível'];
|
||||
$rows[] = [...array_intersect_key($row, array_flip(['id', 'supplier_id', 'reference', 'currency', 'subtotal_minor', 'tax_minor', 'total_minor', 'delivery_days', 'valid_until', 'payment_terms', 'weights', 'eligible', 'ineligibility_reasons', 'evaluation_count', 'score_minor', 'items', 'evaluations', 'qualified_evaluations'])),
|
||||
...($row['exchange_basis'] === null ? [] : ['exchange_basis' => $row['exchange_basis'], 'reference_amounts' => $row['reference_amounts']]),
|
||||
'supplier_name' => $row['supplier']['name'] ?? 'Fornecedor indisponível'];
|
||||
$decision = AdmissionDecision::query()->where('admission_adoption_id', $adoption->id ?? 0)->where('quotation_id', $row['id'])->latest('revision')->first();
|
||||
$admissions[] = ['quotation_id' => $row['id'], 'basis' => $admission->basis($request, $row['id']), 'decision' => $decision?->toArray(), 'reviews' => AdmissionReview::query()->where('admission_decision_id', $decision->id ?? 0)->orderBy('id')->get()->toArray()];
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ class InventoryDispositions
|
||||
$reversed = app(InventoryReversals::class)->corrections('operation');
|
||||
|
||||
return (int) app(SupplyPlanning::class)->latest('stock_event')->where('state', 'executed')->whereJsonContains('data->kind', 'supplier_return')
|
||||
->whereJsonContains('data->purchase_order_item_id', $line)->get()->reject(fn ($r) => isset($reversed[$r->data['stock_operation_id']]))->sum(fn ($r) => $r->data['quantity_milli']);
|
||||
->whereJsonContains('data->purchase_order_item_id', $line)->get()->reject(fn ($r) => isset($reversed[$r->data['stock_operation_id']]))->sum(fn ($r) => $r->data['document_quantity_milli'] ?? $r->data['quantity_milli']);
|
||||
}
|
||||
|
||||
/** Minimal receipt facts for the existing Finance reconciliation screen.
|
||||
@@ -114,9 +114,15 @@ class InventoryDispositions
|
||||
$this->check(($source['lot']['origin']['receipt_item_id'] ?? null) === $line->id, 'data.receipt_item_id', 'O lote deve ter origem comprovada nesta linha de recepção; igualdade de código não prova a origem.');
|
||||
}
|
||||
$returned = $this->returnedForReceipt($line->id);
|
||||
$this->check($returned + $data['quantity_milli'] <= $line->accepted_milli, 'data.quantity', 'A soma das devoluções não pode exceder a quantidade originalmente aceite.');
|
||||
$conversion = app(ReceiptQuantityConversion::class);
|
||||
$this->check($returned + $data['quantity_milli'] <= $conversion->physicalAccepted($line), 'data.quantity', 'A soma das devoluções não pode exceder a quantidade física originalmente aceite.');
|
||||
$documentQuantity = $conversion->documentary($line, $data['quantity_milli']);
|
||||
$source['receipt'] = ['id' => $receipt->id, 'number' => $receipt->number, 'item_id' => $line->id, 'purchase_order_item_id' => $line->purchase_order_item_id,
|
||||
'purchase_order_id' => $order->id, 'order_number' => $order->number, 'supplier_id' => $order->supplier_id, 'supplier_name' => $receipt->snapshot['supplier']['name'], 'accepted_milli' => $line->accepted_milli];
|
||||
if (isset($line->snapshot['quantity_conversion'])) {
|
||||
$source['receipt']['quantity_conversion'] = $line->snapshot['quantity_conversion'];
|
||||
$source['receipt']['document_quantity_milli'] = $documentQuantity;
|
||||
}
|
||||
$observed['previously_returned_milli'] = $returned;
|
||||
}
|
||||
|
||||
@@ -168,6 +174,9 @@ class InventoryDispositions
|
||||
$snapshot = $this->basis($data);
|
||||
$snapshot['contributors'] = array_values(array_unique([...($old?->snapshot['contributors'] ?? []), $actor->id]));
|
||||
$data['purchase_order_item_id'] = $snapshot['source']['receipt']['purchase_order_item_id'] ?? null;
|
||||
if (isset($snapshot['source']['receipt']['document_quantity_milli'])) {
|
||||
$data['document_quantity_milli'] = $snapshot['source']['receipt']['document_quantity_milli'];
|
||||
}
|
||||
$state = 'draft';
|
||||
} else {
|
||||
$this->check($old !== null, 'action', 'Prepare primeiro o processo.');
|
||||
|
||||
@@ -104,8 +104,9 @@ class InvestmentWorkflow
|
||||
return null;
|
||||
}
|
||||
$policy = $this->requireCurrent();
|
||||
$amount = $policy->includes_tax ? $quotation->total_minor : $quotation->subtotal_minor;
|
||||
if ($amount > $policy->ceiling_minor || $quotation->currency !== 'MZN') {
|
||||
$reference = app(QuotationExchange::class)->amounts($quotation);
|
||||
$amount = $policy->includes_tax ? $reference['total_minor'] : $reference['subtotal_minor'];
|
||||
if ($amount > $policy->ceiling_minor) {
|
||||
throw ValidationException::withMessages(['investment' => 'O total do processo excede o tecto de investimento da empresa ou usa moeda não suportada. Não há dispensa automática.']);
|
||||
}
|
||||
app(EquipmentWorkflow::class)->assertTechnical($request);
|
||||
|
||||
@@ -105,12 +105,13 @@ class InvoiceWorkflow
|
||||
$request = Requisition::query()->findOrFail($order->requisition_id);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $user);
|
||||
$number = Str::upper(Str::squish($data['number']));
|
||||
SgfInvoiceDispatches::assertLocalRegistration($user->tenant_id,$order->supplier_id,$number);
|
||||
SgfInvoiceDispatches::assertLocalRegistration($user->tenant_id, $order->supplier_id, $number);
|
||||
if ($number === '' || Invoice::query()->where('supplier_id', $order->supplier_id)->where('number', $number)->exists()) {
|
||||
$this->invalid('Número de factura vazio ou já registado para este fornecedor.');
|
||||
}
|
||||
if ($order->status !== 'issued' || $order->currency !== 'MZN' || substr($data['issued_on'], 0, 4) !== now()->format('Y') || $data['issued_on'] > today()->format('Y-m-d') || $data['issued_on'] < substr((string) $order->getRawOriginal('issued_at'), 0, 10)) {
|
||||
$this->invalid('Factura deve referir ordem emitida em MZN, com data válida no exercício actual e posterior à emissão.');
|
||||
app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
|
||||
if ($order->status !== 'issued' || substr($data['issued_on'], 0, 4) !== now()->format('Y') || $data['issued_on'] > today()->format('Y-m-d') || $data['issued_on'] < substr((string) $order->getRawOriginal('issued_at'), 0, 10)) {
|
||||
$this->invalid('Factura deve referir ordem emitida, com data válida no exercício actual e posterior à emissão.');
|
||||
}
|
||||
$lines = $this->lines($order, $data['items']);
|
||||
$subtotal = array_sum(array_column($lines, 'subtotal_minor'));
|
||||
@@ -120,7 +121,9 @@ class InvoiceWorkflow
|
||||
$this->invalid('Totais da factura divergem da conferência com a ordem e recepção. Verifique os arredondamentos das facturas parciais.');
|
||||
}
|
||||
}
|
||||
$invoice = Invoice::query()->create(['tenant_id' => $user->tenant_id, 'purchase_order_id' => $order->id, 'supplier_id' => $order->supplier_id, 'created_by' => $user->id, 'number' => $number, 'issued_on' => $data['issued_on'], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'snapshot' => ['supplier' => $order->snapshot['supplier'], 'order_number' => $order->number, 'author' => $user->only(['id', 'name']), 'currency' => 'MZN', 'development_only' => true, 'matching_tolerance' => 'zero', 'rounding' => 'cumulative_half_up']]);
|
||||
$invoice = Invoice::query()->create(['tenant_id' => $user->tenant_id, 'purchase_order_id' => $order->id, 'supplier_id' => $order->supplier_id, 'created_by' => $user->id, 'number' => $number, 'issued_on' => $data['issued_on'], 'subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax, 'snapshot' => ['supplier' => $order->snapshot['supplier'], 'order_number' => $order->number, 'author' => $user->only(['id', 'name']), 'currency' => $order->currency,
|
||||
...($order->currency === 'MZN' ? [] : ['exchange_basis' => $order->snapshot['exchange_basis']]),
|
||||
'development_only' => true, 'matching_tolerance' => 'zero', 'rounding' => 'cumulative_half_up']]);
|
||||
$invoice->items()->createMany($lines);
|
||||
app(RequisitionWorkflow::class)->audit($user, 'invoice.created', $request, null, $invoice->load('items')->toArray());
|
||||
|
||||
@@ -158,9 +161,11 @@ class InvoiceWorkflow
|
||||
}
|
||||
}
|
||||
$adapter = app(CommonBudget::class);
|
||||
$effect = $adapter->execute(fn () => $adapter->for($user)->consume($request->id, $invoice->id, (int) $invoice->total_minor, (int) $invoice->subtotal_minor));
|
||||
$reference = app(QuotationExchange::class)->invoiceAmounts($order, $invoice);
|
||||
$effect = $adapter->execute(fn () => $adapter->for($user)->consume($request->id, $invoice->id, $reference['total_minor'], $reference['subtotal_minor']));
|
||||
$invoice->update(['status' => 'validated', 'validated_by' => $user->id, 'validated_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($user, 'invoice.validated', $request, null, ['invoice_id' => $invoice->id] + $effect);
|
||||
app(RequisitionWorkflow::class)->audit($user, 'invoice.validated', $request, null, ['invoice_id' => $invoice->id,
|
||||
...($order->currency === 'MZN' ? [] : ['reference_amounts' => $reference, 'exchange_basis' => $order->snapshot['exchange_basis']])] + $effect);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,9 +82,10 @@ class OrderCancellationWorkflow
|
||||
|
||||
private function source(PurchaseOrder $order): void
|
||||
{
|
||||
if ($order->getRawOriginal('status') !== 'issued' || $order->currency !== 'MZN' || GoodsReceipt::query()->where('purchase_order_id', $order->id)->exists()
|
||||
app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
|
||||
if ($order->getRawOriginal('status') !== 'issued' || GoodsReceipt::query()->where('purchase_order_id', $order->id)->exists()
|
||||
|| Invoice::query()->where('purchase_order_id', $order->id)->exists()) {
|
||||
throw ValidationException::withMessages(['order' => 'Este circuito exige ordem emitida em MZN sem qualquer recepção, factura ou pagamento.']);
|
||||
throw ValidationException::withMessages(['order' => 'Este circuito exige ordem emitida sem qualquer recepção, factura ou pagamento.']);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
/** Exports only the already authorised projection, without reading other sources. */
|
||||
class ProcurementReviewCsv
|
||||
{
|
||||
/** @param array<string,mixed> $report */
|
||||
public function render(array $report): string
|
||||
{
|
||||
$file = fopen('php://temp', 'w+');
|
||||
if ($file === false) {
|
||||
throw new \RuntimeException('Não foi possível preparar a exportação.');
|
||||
}
|
||||
$write = static function (array $cells) use ($file): void {
|
||||
$safe = array_map(static function (mixed $value): string {
|
||||
$text = $value === null ? 'Não disponível' : (is_bool($value) ? ($value ? 'Sim' : 'Não') : (string) $value);
|
||||
|
||||
return preg_match('/^[\s\x00-\x1F]*[=+\-@]/u', $text) ? "'".$text : $text;
|
||||
}, $cells);
|
||||
if (fputcsv($file, $safe, ';', '"', '') === false) {
|
||||
throw new \RuntimeException('Não foi possível escrever a exportação.');
|
||||
}
|
||||
};
|
||||
$fields = static function (string $section, string $reference, array $source, array $labels) use ($write): void {
|
||||
foreach ($labels as $key => $label) {
|
||||
$write([$section, $reference, $label, $source[$key] ?? null]);
|
||||
}
|
||||
};
|
||||
try {
|
||||
fwrite($file, "\xEF\xBB\xBF");
|
||||
$write(['Secção', 'Registo', 'Campo', 'Valor']);
|
||||
$fields('Consulta', '', $report, ['company' => 'Empresa', 'generated_at' => 'Consultado em', 'generated_by' => 'Consultado por']);
|
||||
$write(['Consulta', '', 'Natureza', 'Consulta actual; não constitui decisão, assinatura ou autorização financeira.']);
|
||||
$fields('Pedido', '', $report['requisition'], ['id' => 'Identificador', 'number' => 'Referência', 'status' => 'Estado', 'justification' => 'Fundamentação', 'department' => 'Departamento', 'requester' => 'Solicitante']);
|
||||
$comparison = $report['comparison'];
|
||||
$fields('Comparação actual', '', $comparison, ['ready' => 'Comparação completa', 'top_count' => 'Propostas com maior pontuação']);
|
||||
$fields('Regra de comparação', '', $comparison['policy'], ['revision' => 'Versão', 'configured' => 'Configuração explícita', 'minimum_proposals' => 'Mínimo de propostas', 'minimum_evaluators' => 'Mínimo de avaliadores']);
|
||||
$criteria = ['price' => 'Preço', 'quality' => 'Qualidade', 'delivery' => 'Entrega', 'history' => 'Histórico', 'payment' => 'Pagamento'];
|
||||
$fields('Ponderações da regra (%)', '', $comparison['policy']['weights'], $criteria);
|
||||
foreach ($comparison['rows'] as $row) {
|
||||
$ref = (string) $row['id'];
|
||||
$fields('Proposta actual', $ref, $row, ['reference' => 'Referência', 'supplier' => 'Fornecedor', 'currency' => 'Moeda', 'subtotal_minor' => 'Subtotal (centavos)', 'tax_minor' => 'IVA (centavos)', 'total_minor' => 'Total (centavos)', 'delivery_days' => 'Prazo de entrega (dias)', 'valid_until' => 'Válida até', 'eligible' => 'Elegível na consulta', 'evaluation_count' => 'Avaliações elegíveis', 'score_minor' => 'Pontuação (centésimos de 10)', 'is_top' => 'Maior pontuação numa comparação completa']);
|
||||
$fields('Ponderações da proposta (%)', $ref, $row['weights'], $criteria);
|
||||
if (isset($row['exchange_basis'])) {
|
||||
$fields('Taxa congelada da proposta', $ref, $row['exchange_basis'], ['id' => 'Registo da taxa', 'currency' => 'Moeda original', 'rate' => 'MZN por unidade original', 'quoted_on' => 'Data da taxa', 'source' => 'Fonte', 'recorded_by' => 'Registada por (utilizador)', 'rounding' => 'Arredondamento']);
|
||||
if ($row['reference_amounts'] !== null) {
|
||||
$fields('Referência em MZN', $ref, $row['reference_amounts'], ['subtotal_minor' => 'Subtotal (centavos MZN)', 'tax_minor' => 'IVA (centavos MZN)', 'total_minor' => 'Total (centavos MZN)']);
|
||||
}
|
||||
}
|
||||
foreach ($row['ineligibility_reasons'] as $reason) {
|
||||
$write(['Proposta actual', $ref, 'Motivo de inelegibilidade', $reason]);
|
||||
}
|
||||
if ($row['commercial_terms'] !== null) {
|
||||
$terms = $row['commercial_terms'];
|
||||
$fields('Condições económicas', $ref, $terms, ['version' => 'Versão', 'discount_basis' => 'Base do desconto', 'rounding' => 'Arredondamento']);
|
||||
foreach ($terms['lines'] as $line) {
|
||||
$fields('Desconto por linha', $ref.':'.$line['requisition_item_id'], $line, ['gross_unit_minor' => 'Preço unitário antes do desconto (centavos)', 'discount_type' => 'Tipo', 'discount_value' => 'Valor informado', 'net_unit_minor' => 'Preço unitário líquido (centavos)']);
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (['admission' => 'Regime de admissão', 'recommendation' => 'Regime de recomendação'] as $key => $section) {
|
||||
$record = $report[$key];
|
||||
$write([$section, '', 'Adopção registada', $record !== null]);
|
||||
if ($record !== null) {
|
||||
$fields($section, (string) $record['id'], $record, ['revision' => 'Versão', 'reason' => 'Fundamentação']);
|
||||
$fields($section, (string) $record['id'], $record['snapshot'], ['policy_revision' => 'Versão da política', 'required_count' => 'Confirmações independentes']);
|
||||
foreach ($record['snapshot']['roles'] as $role) {
|
||||
$write([$section, (string) $record['id'], 'Função prevista', $role]);
|
||||
}
|
||||
}
|
||||
}
|
||||
$qualification = $report['qualification'];
|
||||
$write(['Qualificação documental', '', 'Versão registada', $qualification !== null]);
|
||||
if ($qualification !== null) {
|
||||
$ref = (string) $qualification['id'];
|
||||
$fields('Qualificação documental', $ref, $qualification, ['revision' => 'Versão', 'created_at' => 'Registada em', 'author' => 'Autor', 'reason' => 'Fundamentação', 'is_current' => 'Base corresponde às propostas actuais']);
|
||||
foreach ($qualification['criteria'] as $criterion) {
|
||||
$fields('Requisito documental', $ref.':'.$criterion['id'], $criterion, ['label' => 'Requisito', 'category' => 'Categoria', 'required' => 'Obrigatório']);
|
||||
}
|
||||
foreach ($qualification['proposals'] as $proposal) {
|
||||
$fields('Proposta na qualificação', (string) $proposal['id'], $proposal, ['reference' => 'Referência preservada', 'supplier' => 'Fornecedor preservado']);
|
||||
foreach ($proposal['analyses'] as $analysis) {
|
||||
$ref = $proposal['id'].':'.$analysis['id'];
|
||||
$fields('Análise documental', $ref, $analysis, ['revision' => 'Versão', 'created_at' => 'Registada em', 'reason' => 'Fundamentação']);
|
||||
$fields('Analista preservado', $ref, $analysis['analyst'], ['name' => 'Nome', 'profile_label' => 'Perfil', 'purchasing_role' => 'Função']);
|
||||
foreach ($analysis['answers'] as $answer) {
|
||||
$fields('Resposta documental', $ref.':'.$answer['criterion_id'], $answer, ['result' => 'Resultado', 'evidence' => 'Evidência', 'reason' => 'Fundamentação']);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (['opening' => 'Abertura', 'award' => 'Adjudicação', 'order' => 'Ordem'] as $key => $section) {
|
||||
$record = $report[$key];
|
||||
$write([$section, '', 'Registo disponível', $record !== null]);
|
||||
if ($record !== null) {
|
||||
$fields($section, (string) $record['id'], $record, match ($key) {
|
||||
'opening' => ['revision' => 'Versão', 'reference' => 'Referência', 'source_changed' => 'Base difere das propostas actuais'],
|
||||
'award' => ['status' => 'Estado', 'total_minor' => 'Total (centavos)'],
|
||||
default => ['number' => 'Referência', 'currency' => 'Moeda', 'total_minor' => 'Total (centavos)'],
|
||||
});
|
||||
}
|
||||
}
|
||||
$fulfilment = $report['fulfilment'];
|
||||
$write(['Recepções', '', 'Registos disponíveis', count($fulfilment['receipts'])]);
|
||||
foreach ($fulfilment['receipts'] as $receipt) {
|
||||
$fields('Recepção', (string) $receipt['id'], $receipt, ['received_on' => 'Recebida em', 'delivery_note' => 'Guia']);
|
||||
}
|
||||
$write(['Execução financeira', '', 'Consulta autorizada', $fulfilment['finance_visible']]);
|
||||
if ($fulfilment['finance_visible']) {
|
||||
foreach (['invoices' => 'Factura', 'payments' => 'Pagamento externo'] as $key => $section) {
|
||||
$write([$section, '', 'Registos disponíveis', count($fulfilment[$key])]);
|
||||
foreach ($fulfilment[$key] as $record) {
|
||||
$fields($section, (string) $record['id'], $record, $key === 'invoices'
|
||||
? ['number' => 'Referência', 'status' => 'Estado', 'issued_on' => 'Emitida em', 'total_minor' => 'Total (centavos)', 'currency' => 'Moeda']
|
||||
: ['invoice_id' => 'Factura de origem', 'status' => 'Estado', 'paid_on' => 'Data informada', 'amount_minor' => 'Montante (centavos)', 'currency' => 'Moeda']);
|
||||
}
|
||||
}
|
||||
}
|
||||
rewind($file);
|
||||
$content = stream_get_contents($file);
|
||||
if ($content === false) {
|
||||
throw new \RuntimeException('Não foi possível ler a exportação.');
|
||||
}
|
||||
|
||||
return $content;
|
||||
} finally {
|
||||
fclose($file);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,7 @@ class ProcurementReviewReport
|
||||
...array_intersect_key($row, array_flip(['id', 'reference', 'currency', 'subtotal_minor', 'tax_minor', 'total_minor', 'delivery_days', 'valid_until', 'weights', 'eligible', 'ineligibility_reasons', 'evaluation_count', 'score_minor', 'commercial_terms'])),
|
||||
'supplier' => $row['supplier']['name'] ?? 'Fornecedor indisponível',
|
||||
'is_top' => $comparison['ready'] && in_array($row['id'], $comparison['top_ids'], true),
|
||||
...($row['exchange_basis'] === null ? [] : ['exchange_basis' => $row['exchange_basis'], 'reference_amounts' => $row['reference_amounts']]),
|
||||
];
|
||||
}
|
||||
$openingWorkflow = app(ProposalOpeningWorkflow::class);
|
||||
|
||||
@@ -11,6 +11,7 @@ use Brick\Math\BigDecimal;
|
||||
use Brick\Math\Exception\MathException;
|
||||
use Brick\Math\RoundingMode;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Tempo\Purchasing\Economic\ProposalScoring;
|
||||
|
||||
class ProposalComparison
|
||||
@@ -27,6 +28,12 @@ class ProposalComparison
|
||||
$rows = [];
|
||||
foreach ($quotes as $quote) {
|
||||
$reasons = [];
|
||||
$reference = null;
|
||||
try {
|
||||
$reference = app(QuotationExchange::class)->amounts($quote);
|
||||
} catch (\InvalidArgumentException|HttpExceptionInterface|ValidationException $error) {
|
||||
$reasons[] = 'Base cambial ausente, inválida ou incompatível com o processo.';
|
||||
}
|
||||
if ($adopted && ! app(FormalAdmission::class)->admitted($requisition, $quote->id)) {
|
||||
$reasons[] = 'O regime adoptado exige admissão confirmada na base actual.';
|
||||
}
|
||||
@@ -51,10 +58,13 @@ class ProposalComparison
|
||||
'eligible' => $reasons === [], 'ineligibility_reasons' => $reasons,
|
||||
'qualified_evaluations' => $evaluations->toArray(), 'evaluation_count' => $evaluations->count(),
|
||||
'score' => null, 'score_minor' => null,
|
||||
'reference_amounts' => $reference,
|
||||
'exchange_basis' => $quote->exchange_basis,
|
||||
];
|
||||
}
|
||||
$eligible = array_values(array_filter($rows, fn ($row) => $row['eligible']));
|
||||
$ranking = (new ProposalScoring)->rank($rows, $policy['minimum_evaluators']);
|
||||
$rankingRows = array_map(fn ($row) => [...$row, 'subtotal_minor' => $row['reference_amounts']['subtotal_minor'] ?? $row['subtotal_minor']], $rows);
|
||||
$ranking = (new ProposalScoring)->rank($rankingRows, $policy['minimum_evaluators']);
|
||||
$topIds = $ranking['top_ids'];
|
||||
foreach ($rows as &$row) {
|
||||
if (isset($ranking['scores'][$row['id']])) {
|
||||
@@ -72,6 +82,7 @@ class ProposalComparison
|
||||
'qualified_ids' => array_column($row['qualified_evaluations'], 'id'),
|
||||
'eligible' => $row['eligible'], 'score_minor' => $row['score_minor'],
|
||||
...($row['commercial_terms'] === null ? [] : ['commercial_terms' => $row['commercial_terms']]),
|
||||
...($row['exchange_basis'] === null ? [] : ['exchange_basis' => $row['exchange_basis'], 'reference_amounts' => $row['reference_amounts']]),
|
||||
];
|
||||
}
|
||||
if ($requisition->comparison_policy !== null) {
|
||||
@@ -128,7 +139,7 @@ class ProposalComparison
|
||||
|
||||
private function validAmounts(Quotation $quote, Requisition $requisition): bool
|
||||
{
|
||||
if ($quote->currency !== 'MZN' || $quote->delivery_days < 1 || $quote->subtotal_minor <= 0 || $quote->total_minor > 100000000000000) {
|
||||
if (! preg_match('/^[A-Z]{3}$/', $quote->currency) || $quote->delivery_days < 1 || $quote->subtotal_minor <= 0 || $quote->total_minor > 100000000000000) {
|
||||
return false;
|
||||
}
|
||||
$requested = $requisition->items()->get()->keyBy('id');
|
||||
|
||||
@@ -23,6 +23,7 @@ class ProposalOpeningWorkflow
|
||||
...$quote->only(['id', 'reference', 'currency', 'subtotal_minor', 'tax_minor', 'total_minor', 'delivery_days', 'valid_until', 'payment_terms']),
|
||||
'supplier' => $quote->supplier?->only(['id', 'name', 'nuit']),
|
||||
...($quote->commercial_terms === null ? [] : ['commercial_terms' => $quote->commercial_terms]),
|
||||
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis]),
|
||||
'items' => $quote->items->map(fn ($item) => $item->only(['requisition_item_id', 'description', 'quantity', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor']))->all(),
|
||||
])->all());
|
||||
}
|
||||
|
||||
@@ -42,18 +42,19 @@ class PurchaseWorkflow
|
||||
$admission = app(FormalAdmission::class)->selection($requisition, $quote->id);
|
||||
$recommendation = app(FormalRecommendation::class)->selection($requisition, $quote->id);
|
||||
$investment = app(InvestmentWorkflow::class)->check($requisition, $quote);
|
||||
app(BudgetWorkflow::class)->record($user, $requisition, 'award', $quote->total_minor, $quote->subtotal_minor);
|
||||
$reference = app(QuotationExchange::class)->amounts($quote);
|
||||
app(BudgetWorkflow::class)->record($user, $requisition, 'award', $reference['total_minor'], $reference['subtotal_minor']);
|
||||
$award = PurchaseAward::query()->create([
|
||||
'tenant_id' => $user->tenant_id, 'requisition_id' => $requisition->id, 'quotation_id' => $quote->id,
|
||||
'created_by' => $user->id, 'justification' => $data['justification'], 'delivery_date' => $data['delivery_date'],
|
||||
'delivery_location' => $data['delivery_location'], 'status' => 'pending',
|
||||
'subtotal_minor' => $quote->subtotal_minor, 'tax_minor' => $quote->tax_minor, 'total_minor' => $quote->total_minor,
|
||||
...$reference,
|
||||
'approval_snapshot' => $rules, 'decision_matrix' => $result['rows'], 'comparison_hash' => $result['fingerprint'],
|
||||
'investment_snapshot' => $investment,
|
||||
'admission_snapshot' => $admission,
|
||||
'recommendation_snapshot' => $recommendation,
|
||||
]);
|
||||
$roles = $this->roles($rules, $rules['approval_includes_tax'] ? $quote->total_minor : $quote->subtotal_minor, $requisition->items()->where('purchase_type', 'equipment')->exists());
|
||||
$roles = $this->roles($rules, $rules['approval_includes_tax'] ? $reference['total_minor'] : $reference['subtotal_minor'], $requisition->items()->where('purchase_type', 'equipment')->exists());
|
||||
foreach ($roles as $position => $role) {
|
||||
$award->approvals()->create(['tenant_id' => $user->tenant_id, 'position' => $position + 1, 'role' => $role]);
|
||||
}
|
||||
@@ -162,9 +163,10 @@ class PurchaseWorkflow
|
||||
}
|
||||
}
|
||||
$snapshot = [
|
||||
...($quote->exchange_basis === null ? [] : ['exchange_basis' => $quote->exchange_basis, 'reference_amounts' => app(QuotationExchange::class)->amounts($quote)]),
|
||||
...($catalogueSources === [] ? [] : ['catalogue_sources' => $catalogueSources]),
|
||||
'development_only' => true, 'budget_checked' => false,
|
||||
'budget_control' => app(BudgetWorkflow::class)->record($user, $requisition, 'commit', $quote->total_minor, $quote->subtotal_minor),
|
||||
'budget_control' => app(BudgetWorkflow::class)->record($user, $requisition, 'commit', $award->total_minor, $award->subtotal_minor),
|
||||
'investment_rules' => $award->investment_snapshot,
|
||||
'equipment_requests' => $requisition->items()->where('purchase_type', 'equipment')->get()->map(fn ($line) => $line->only(['id', 'description', 'production_area']))->all(),
|
||||
'company' => Tenant::query()->findOrFail($user->tenant_id)->only(['id', 'name']),
|
||||
@@ -216,8 +218,9 @@ class PurchaseWorkflow
|
||||
if (app(FormalRecommendation::class)->selection($requisition, $quote->id) !== $award->recommendation_snapshot) {
|
||||
throw ValidationException::withMessages(['recommendation' => 'A recomendação já não corresponde à base da adjudicação. Prepare a revisão autorizada antes de emitir.']);
|
||||
}
|
||||
$reference = app(QuotationExchange::class)->amounts($quote);
|
||||
if ($result['fingerprint'] !== $award->comparison_hash || $award->approval_snapshot !== $rules ||
|
||||
$quote->subtotal_minor !== $award->subtotal_minor || $quote->tax_minor !== $award->tax_minor || $quote->total_minor !== $award->total_minor) {
|
||||
$reference['subtotal_minor'] !== $award->subtotal_minor || $reference['tax_minor'] !== $award->tax_minor || $reference['total_minor'] !== $award->total_minor) {
|
||||
throw ValidationException::withMessages(['comparison' => 'A base da adjudicação mudou. As aprovações anteriores não autorizam a emissão com dados diferentes.']);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseAward;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Quotation;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Brick\Math\RoundingMode;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Explicit frozen process rates. No market lookup, payment execution or inferred rate. */
|
||||
class QuotationExchange
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
return Schema::hasTable('quotation_exchange_rates') && Schema::hasColumn('quotations', 'exchange_basis');
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function rates(Requisition $request): array
|
||||
{
|
||||
if (! $this->ready()) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(DB::table('quotation_exchange_rates')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)->orderBy('currency')->get()
|
||||
->map(fn ($row) => $this->snapshot($row))->all());
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function record(User $actor, Requisition $request, array $input): void
|
||||
{
|
||||
abort_unless($this->ready(), 503, 'A estrutura de câmbio ainda não está instalada neste ambiente.');
|
||||
if (isset($input['source']) && is_string($input['source'])) {
|
||||
$input['source'] = trim($input['source']);
|
||||
}
|
||||
$data = Validator::make($input, [
|
||||
'operation_id' => 'required|uuid', 'currency' => ['required', 'regex:/^[A-Z]{3}$/', 'not_in:MZN'],
|
||||
'rate' => ['required', 'regex:/^\d{1,8}(\.\d{1,10})?$/', 'numeric', 'gt:0'],
|
||||
'quoted_on' => 'required|date_format:Y-m-d|before_or_equal:today',
|
||||
'source' => 'required|string|min:3|max:1000',
|
||||
])->validate();
|
||||
$data['rate'] = (string) BigDecimal::of($data['rate'])->toScale(10);
|
||||
$data['source'] = trim($data['source']);
|
||||
$hash = hash('sha256', json_encode([$request->id, $data['currency'], $data['rate'], $data['quoted_on'], $data['source']], JSON_THROW_ON_ERROR));
|
||||
DB::transaction(function () use ($actor, $request, $data, $hash) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Finance]);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$request = Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id);
|
||||
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||
$existing = DB::table('quotation_exchange_rates')->where('tenant_id', $actor->tenant_id)->where('operation_id', $data['operation_id'])->first();
|
||||
if ($existing !== null) {
|
||||
abort_unless($existing->recorded_by === $actor->id && hash_equals($existing->payload_hash, $hash), 409, 'A referência de operação já foi utilizada com outros dados.');
|
||||
|
||||
return;
|
||||
}
|
||||
abort_unless($request->status === 'approved' && ! PurchaseAward::query()->where('requisition_id', $request->id)->exists(), 409, 'O registo de taxas exige processo aprovado, ainda sem adjudicação.');
|
||||
if (DB::table('quotation_exchange_rates')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->where('currency', $data['currency'])->exists()) {
|
||||
throw ValidationException::withMessages(['currency' => 'A taxa desta moeda já está congelada neste processo.']);
|
||||
}
|
||||
$id = DB::table('quotation_exchange_rates')->insertGetId([
|
||||
'tenant_id' => $actor->tenant_id, 'requisition_id' => $request->id, 'recorded_by' => $actor->id,
|
||||
'currency' => $data['currency'], 'rate' => $data['rate'], 'quoted_on' => $data['quoted_on'], 'source' => $data['source'],
|
||||
'operation_id' => $data['operation_id'], 'payload_hash' => $hash, 'created_at' => now(),
|
||||
]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'quotation.exchange_rate_recorded', $request, null,
|
||||
['id' => $id, 'currency' => $data['currency'], 'rate' => $data['rate'], 'quoted_on' => $data['quoted_on'], 'source' => $data['source'], 'operation_id' => $data['operation_id']]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public function basis(Requisition $request, string $currency): ?array
|
||||
{
|
||||
if ($currency === 'MZN') {
|
||||
return null;
|
||||
}
|
||||
abort_unless($this->ready(), 503);
|
||||
$row = DB::table('quotation_exchange_rates')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)->where('currency', $currency)->first();
|
||||
if ($row === null) {
|
||||
throw ValidationException::withMessages(['currency' => 'Finanças deve registar a taxa, data e fonte desta moeda para o processo.']);
|
||||
}
|
||||
|
||||
return $this->snapshot($row);
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function snapshot(\stdClass $row): array
|
||||
{
|
||||
return ['schema' => 'sgc.quotation.exchange.v1', 'id' => (int) $row->id, 'tenant_id' => (int) $row->tenant_id,
|
||||
'requisition_id' => (int) $row->requisition_id, 'currency' => $row->currency, 'rate' => (string) BigDecimal::of((string) $row->rate)->toScale(10),
|
||||
'quoted_on' => $row->quoted_on, 'source' => $row->source, 'recorded_by' => (int) $row->recorded_by,
|
||||
'rounding' => 'subtotal_and_tax_half_up_cent', 'reference_currency' => 'MZN'];
|
||||
}
|
||||
|
||||
public function convert(int $minor, string $rate): int
|
||||
{
|
||||
if ($minor < 0 || ! preg_match('/^\d{1,8}(\.\d{1,10})?$/', $rate) || ! BigDecimal::of($rate)->isGreaterThan(0)) {
|
||||
throw new \InvalidArgumentException('Montante ou taxa de câmbio inválidos.');
|
||||
}
|
||||
$result = BigDecimal::of($minor)->multipliedBy($rate)->toScale(0, RoundingMode::HalfUp);
|
||||
if ($result->isGreaterThan(100000000000000)) {
|
||||
throw new \InvalidArgumentException('O valor convertido excede o limite suportado.');
|
||||
}
|
||||
|
||||
return $result->toInt();
|
||||
}
|
||||
|
||||
/** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
|
||||
public function amounts(Quotation $quote): array
|
||||
{
|
||||
$basis = $quote->exchange_basis;
|
||||
if ($quote->currency === 'MZN') {
|
||||
abort_unless($basis === null, 409, 'Base cambial incompatível com proposta em MZN.');
|
||||
|
||||
return ['subtotal_minor' => $quote->subtotal_minor, 'tax_minor' => $quote->tax_minor, 'total_minor' => $quote->total_minor];
|
||||
}
|
||||
$request = Requisition::query()->findOrFail($quote->requisition_id);
|
||||
abort_unless(is_array($basis) && $basis === $this->basis($request, $quote->currency), 409, 'A base cambial não corresponde à taxa congelada no processo.');
|
||||
try {
|
||||
$subtotal = $this->convert($quote->subtotal_minor, $basis['rate']);
|
||||
$tax = $this->convert($quote->tax_minor, $basis['rate']);
|
||||
} catch (\InvalidArgumentException) {
|
||||
throw ValidationException::withMessages(['currency' => 'O valor convertido excede o limite suportado.']);
|
||||
}
|
||||
if ($subtotal < 1 || $subtotal + $tax > 100000000000000) {
|
||||
throw ValidationException::withMessages(['currency' => 'O valor convertido deve ser positivo e estar dentro do limite suportado.']);
|
||||
}
|
||||
|
||||
return ['subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax];
|
||||
}
|
||||
|
||||
/** @return array{subtotal_minor:int,tax_minor:int,total_minor:int} */
|
||||
public function orderAmounts(PurchaseOrder $order, int $subtotal, int $tax): array
|
||||
{
|
||||
abort_unless($subtotal >= 0 && $tax >= 0, 409);
|
||||
if ($order->currency === 'MZN') {
|
||||
abort_unless(($order->snapshot['exchange_basis'] ?? null) === null, 409, 'Base cambial incompatível com ordem em MZN.');
|
||||
|
||||
return ['subtotal_minor' => $subtotal, 'tax_minor' => $tax, 'total_minor' => $subtotal + $tax];
|
||||
}
|
||||
$request = Requisition::query()->findOrFail($order->requisition_id);
|
||||
$basis = $order->snapshot['exchange_basis'] ?? null;
|
||||
abort_unless(is_array($basis) && $basis === $this->basis($request, $order->currency), 409, 'Base cambial da ordem indisponível ou inconsistente.');
|
||||
$fullNet = $this->convert($order->subtotal_minor, $basis['rate']);
|
||||
$fullTax = $this->convert($order->tax_minor, $basis['rate']);
|
||||
abort_unless($order->total_minor === $order->subtotal_minor + $order->tax_minor
|
||||
&& ($order->snapshot['reference_amounts'] ?? null) === ['subtotal_minor' => $fullNet, 'tax_minor' => $fullTax, 'total_minor' => $fullNet + $fullTax],
|
||||
409, 'Os valores da ordem não correspondem à referência cambial congelada.');
|
||||
$net = $this->convert($subtotal, $basis['rate']);
|
||||
$vat = $this->convert($tax, $basis['rate']);
|
||||
|
||||
return ['subtotal_minor' => $net, 'tax_minor' => $vat, 'total_minor' => $net + $vat];
|
||||
}
|
||||
|
||||
/** Cumulative conversion preserves the order's frozen MZN commitment across partial invoices.
|
||||
* @return array{subtotal_minor:int,tax_minor:int,total_minor:int}
|
||||
*/
|
||||
public function invoiceAmounts(PurchaseOrder $order, Invoice $invoice): array
|
||||
{
|
||||
if ($order->currency === 'MZN') {
|
||||
return ['subtotal_minor' => $invoice->subtotal_minor, 'tax_minor' => $invoice->tax_minor, 'total_minor' => $invoice->total_minor];
|
||||
}
|
||||
$previous = DB::table('invoices')->where('tenant_id', $order->tenant_id)->where('purchase_order_id', $order->id)
|
||||
->where('status', 'validated')->where('id', '!=', $invoice->id)
|
||||
->selectRaw('COALESCE(SUM(subtotal_minor), 0) AS net, COALESCE(SUM(tax_minor), 0) AS vat')->first();
|
||||
$before = $this->orderAmounts($order, (int) $previous->net, (int) $previous->vat);
|
||||
$after = $this->orderAmounts($order, (int) $previous->net + $invoice->subtotal_minor, (int) $previous->vat + $invoice->tax_minor);
|
||||
|
||||
return ['subtotal_minor' => $after['subtotal_minor'] - $before['subtotal_minor'],
|
||||
'tax_minor' => $after['tax_minor'] - $before['tax_minor'], 'total_minor' => $after['total_minor'] - $before['total_minor']];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\GoodsReceiptItem;
|
||||
use App\Models\PurchaseOrderItem;
|
||||
use App\Models\StockItem;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Inventory\QuantityConversion;
|
||||
|
||||
/** Host basis frozen on first accepted receipt of this order line/article. */
|
||||
final class ReceiptQuantityConversion
|
||||
{
|
||||
/** @param array<string,mixed>|null $input
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public function freeze(User $actor, PurchaseOrderItem $line, StockItem $stock, int $accepted, ?array $input): ?array
|
||||
{
|
||||
$same = mb_strtolower(trim($stock->unit)) === mb_strtolower(trim($line->unit));
|
||||
foreach (GoodsReceiptItem::query()->where('purchase_order_item_id', $line->id)->where('accepted_milli', '>', 0)->get() as $previous) {
|
||||
$frozen = $previous->snapshot['quantity_conversion'] ?? null;
|
||||
if (is_array($frozen) && ($same || $frozen['stock_item_id'] !== $stock->id || $frozen['stock_unit'] !== $stock->unit || $frozen['document_unit'] !== $line->unit)) {
|
||||
throw ValidationException::withMessages(['items' => 'O artigo e as unidades já estão congelados nesta linha.']);
|
||||
}
|
||||
}
|
||||
if ($same) {
|
||||
if ($input !== null) {
|
||||
throw ValidationException::withMessages(['items' => 'Unidades coincidentes não exigem um factor de conversão.']);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
if (config('inventory_conversion.qa_enabled') !== true || ! app()->environment('testing')) {
|
||||
throw ValidationException::withMessages(['items' => 'A conversão de unidades está preparada apenas para QA.']);
|
||||
}
|
||||
$v = Validator::make($input ?? [], [
|
||||
'numerator' => ['required', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
||||
'denominator' => ['required', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
|
||||
'source' => 'required|string|max:500', 'version' => 'required|string|max:100',
|
||||
])->validate();
|
||||
$basis = ['schema' => 'inventory.quantity.v1', 'stock_item_id' => $stock->id, 'document_unit' => $line->unit, 'stock_unit' => $stock->unit,
|
||||
'numerator' => $v['numerator'], 'denominator' => $v['denominator'], 'source' => trim($v['source']), 'version' => trim($v['version'])];
|
||||
if ($basis['source'] === '' || $basis['version'] === '') {
|
||||
throw ValidationException::withMessages(['items' => 'Indique fonte e versão da conversão.']);
|
||||
}
|
||||
foreach (GoodsReceiptItem::query()->where('purchase_order_item_id', $line->id)->where('accepted_milli', '>', 0)->get() as $previous) {
|
||||
$frozen = $previous->snapshot['quantity_conversion'] ?? null;
|
||||
if (! is_array($frozen) || array_intersect_key($frozen, $basis) !== $basis) {
|
||||
throw ValidationException::withMessages(['items' => 'Conserve artigo, unidades, factor, fonte e versão já congelados nesta linha.']);
|
||||
}
|
||||
}
|
||||
// Load and validate the same writer artifact before using its arithmetic; never a second implementation.
|
||||
app(ReceiptStockMovement::class)->for($actor);
|
||||
try {
|
||||
$physical = QuantityConversion::toBase((string) $accepted, $basis['numerator'], $basis['denominator']);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw ValidationException::withMessages(['items' => $e->getMessage()]);
|
||||
}
|
||||
|
||||
return [...$basis, 'accepted_document_milli' => (string) $accepted, 'accepted_stock_milli' => $physical];
|
||||
}
|
||||
|
||||
public function physicalAccepted(GoodsReceiptItem $line): int
|
||||
{
|
||||
$basis = $line->snapshot['quantity_conversion'] ?? null;
|
||||
|
||||
return $basis === null ? $line->accepted_milli : (int) $basis['accepted_stock_milli'];
|
||||
}
|
||||
|
||||
public function documentary(GoodsReceiptItem $line, int $physical): int
|
||||
{
|
||||
$basis = $line->snapshot['quantity_conversion'] ?? null;
|
||||
if ($basis === null) {
|
||||
return $physical;
|
||||
}
|
||||
abort_unless(config('inventory_conversion.qa_enabled') === true, 503, 'Convers?o ainda n?o instalada.');
|
||||
app(ReceiptStockMovement::class)->load();
|
||||
try {
|
||||
return (int) QuantityConversion::fromBase((string) $physical, $basis['numerator'], $basis['denominator']);
|
||||
} catch (\InvalidArgumentException $e) {
|
||||
throw ValidationException::withMessages(['data.quantity' => $e->getMessage()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,24 +5,56 @@ namespace App\Services;
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Tempo\Inventory\ReceiptMovementWriter;
|
||||
|
||||
/** Called only within ReceiptWorkflow's company-locked transaction. */
|
||||
final class ReceiptStockMovement
|
||||
{
|
||||
public function for(User $actor): \Tempo\Inventory\ReceiptMovementWriter
|
||||
public function load(): void
|
||||
{
|
||||
$root=base_path('packages/inventory-write/releases/0.1.0');
|
||||
if(!is_file($root.'/manifest.json')||!hash_equals('f0b99e591f9a4df135e685f64ceffad77bed259222debe0f34c20f95e3cad800',hash_file('sha256',$root.'/manifest.json')))
|
||||
$root = base_path('packages/inventory-write/releases/0.1.0');
|
||||
$pin = 'f0b99e591f9a4df135e685f64ceffad77bed259222debe0f34c20f95e3cad800';
|
||||
$files = ['bootstrap.php', 'src/ReceiptMovementWriter.php'];
|
||||
if (config('inventory_conversion.qa_enabled') === true) {
|
||||
abort_unless(app()->environment('testing'), 503, 'Extensão de conversão limitada a QA.');
|
||||
$connection = DB::connection();
|
||||
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';
|
||||
$files[] = 'src/QuantityConversion.php';
|
||||
}
|
||||
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
|
||||
if (! is_string($bytes) || ! hash_equals($pin, hash('sha256', $bytes))) {
|
||||
throw new \LogicException('Pacote de recepção incompatível; não executar outro escritor.');
|
||||
$manifest=json_decode(file_get_contents($root.'/manifest.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
foreach(['bootstrap.php','src/ReceiptMovementWriter.php'] as $file)
|
||||
if(!is_file($root.'/'.$file)||!hash_equals($manifest['files'][$file]??'',hash_file('sha256',$root.'/'.$file)))throw new \LogicException('Pacote de recepção alterado.');
|
||||
}
|
||||
$manifest = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
|
||||
foreach ($files as $file) {
|
||||
$actual = is_file($root.'/'.$file) ? hash_file('sha256', $root.'/'.$file) : false;
|
||||
if (! is_string($actual) || ! hash_equals($manifest['files'][$file] ?? '', $actual)) {
|
||||
throw new \LogicException('Pacote de recepção alterado.');
|
||||
}
|
||||
}
|
||||
if (class_exists(ReceiptMovementWriter::class, false)) {
|
||||
$loaded = (new \ReflectionClass(ReceiptMovementWriter::class))->getFileName();
|
||||
if (! is_string($loaded) || realpath($loaded) !== realpath($root.'/src/ReceiptMovementWriter.php')) {
|
||||
throw new \LogicException('Escritor já carregado de outra versão; use um kernel QA separado.');
|
||||
}
|
||||
}
|
||||
require_once $root.'/bootstrap.php';
|
||||
$schema=match(DB::connection()->getDriverName()){
|
||||
'pgsql'=>'public','sqlite'=>'main','mysql','mariadb'=>DB::connection()->getDatabaseName(),
|
||||
default=>throw new \LogicException('Driver de inventário não suportado.'),
|
||||
}
|
||||
|
||||
public function for(User $actor): ReceiptMovementWriter
|
||||
{
|
||||
$this->load();
|
||||
$schema = match (DB::connection()->getDriverName()) {
|
||||
'pgsql' => 'public','sqlite' => 'main','mysql','mariadb' => DB::connection()->getDatabaseName(),
|
||||
default => throw new \LogicException('Driver de inventário não suportado.'),
|
||||
};
|
||||
return new \Tempo\Inventory\ReceiptMovementWriter(DB::connection(),$schema,(int)$actor->tenant_id,(int)$actor->id,
|
||||
function () use ($actor) {app(CurrentActor::class)->lock($actor,[PurchasingRole::Warehouse]);});
|
||||
|
||||
return new ReceiptMovementWriter(DB::connection(), $schema, (int) $actor->tenant_id, (int) $actor->id,
|
||||
function () use ($actor) {
|
||||
app(CurrentActor::class)->lock($actor, [PurchasingRole::Warehouse]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ class ReceiptWorkflow
|
||||
throw ValidationException::withMessages(['delivery_note' => 'Indique a guia de remessa do fornecedor.']);
|
||||
}
|
||||
$inputs = [];
|
||||
/** @var list<array{purchase_order_item_id: int, received_quantity: string, accepted_quantity: string, quality_status: string, stock_item_id?: int|null, notes?: string|null, lots?:list<array<string,mixed>>}> $requested */
|
||||
/** @var list<array{purchase_order_item_id: int, received_quantity: string, accepted_quantity: string, quality_status: string, stock_item_id?: int|null, notes?: string|null, conversion?:array<string,mixed>|null, lots?:list<array<string,mixed>>}> $requested */
|
||||
$requested = $data['items'];
|
||||
$supplyMappings = Schema::hasTable('supply_records')
|
||||
? app(SupplyPlanning::class)->latest('delivery')->where('purchase_order_id', $order->id)->get() : collect();
|
||||
@@ -108,6 +108,7 @@ class ReceiptWorkflow
|
||||
}
|
||||
$inputs[] = [
|
||||
...(! empty($line['lots']) ? ['lots' => $line['lots']] : []),
|
||||
...(! empty($line['conversion']) ? ['conversion' => $line['conversion']] : []),
|
||||
'purchase_order_item_id' => $line['purchase_order_item_id'],
|
||||
'received_milli' => self::milli($line['received_quantity']), 'accepted_milli' => self::milli($line['accepted_quantity']),
|
||||
'quality_status' => $line['quality_status'], 'stock_item_id' => $line['stock_item_id'] ?? null,
|
||||
@@ -188,9 +189,11 @@ class ReceiptWorkflow
|
||||
if (! $physical && $source->purchase_type !== 'service') {
|
||||
throw ValidationException::withMessages(['items' => 'Este tipo de artigo exige controlos adicionais ainda não implementados.']);
|
||||
}
|
||||
if ($physical && $accepted > 0 && (! $warehouse || ! $stockItem || Str::lower(trim($stockItem->unit)) !== Str::lower(trim($source->unit)))) {
|
||||
throw ValidationException::withMessages(['items' => 'Para bens aceites, indique armazém e artigo de stock com a mesma unidade da ordem. Não há conversões automáticas.']);
|
||||
if ($physical && $accepted > 0 && (! $warehouse || ! $stockItem)) {
|
||||
throw ValidationException::withMessages(['items' => 'Para bens aceites, indique armazém e artigo de stock.']);
|
||||
}
|
||||
$conversion = $physical && $accepted > 0 && $stockItem !== null
|
||||
? app(ReceiptQuantityConversion::class)->freeze($user, $source, $stockItem, $accepted, $input['conversion'] ?? null) : null;
|
||||
if (! $physical && $stockItem !== null) {
|
||||
throw ValidationException::withMessages(['items' => 'Serviços não geram existências nem recebem artigo de stock.']);
|
||||
}
|
||||
@@ -204,6 +207,7 @@ class ReceiptWorkflow
|
||||
'stock_item' => $stockItem?->only(['id', 'code', 'name', 'unit']),
|
||||
'warehouse' => $warehouse?->only(['id', 'code', 'name']),
|
||||
'physical' => $physical,
|
||||
...($conversion === null ? [] : ['quantity_conversion' => $conversion]),
|
||||
'equipment_id' => $source->equipment_id, 'spare_part_id' => $source->spare_part_id,
|
||||
],
|
||||
];
|
||||
|
||||
@@ -1,186 +1,312 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\{User,Supplier,Invoice};
|
||||
use Illuminate\Support\Facades\{Crypt,DB,Schema,Validator};
|
||||
use App\Models\Invoice;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Crypt;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\SgcInvoiceClient\InvoiceClient;
|
||||
|
||||
/** Durable source intent and audit. No native invoice, payment, budget or stock writer. */
|
||||
final class SgfInvoiceDispatches
|
||||
{
|
||||
public function actor(User $actor,bool $locked=false):User
|
||||
public function actor(User $actor, bool $locked = false): User
|
||||
{
|
||||
abort_unless(config('sgf_invoice.workspace_enabled')===true,404);
|
||||
abort_unless(auth()->id()===$actor->id&&$actor->tenant_id!==null,403);
|
||||
if($locked)app(ConflictGuard::class)->lockCompany($actor);
|
||||
$q=User::where('tenant_id',$actor->tenant_id)->whereKey($actor->id);if($locked)$q->lockForUpdate();$user=$q->firstOrFail();
|
||||
abort_unless($user->hasFunctions(['finance'])&&!app(OrganizationAccess::class)->maintenanceOnly($user),403);
|
||||
abort_unless(Schema::hasTable('sgf_invoice_dispatches')&&Schema::hasTable('sgf_invoice_dispatch_events'),503,'Estrutura de envio ainda não instalada.');
|
||||
abort_unless(config('sgf_invoice.workspace_enabled') === true, 404);
|
||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
||||
if ($locked) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
}
|
||||
$q = User::where('tenant_id', $actor->tenant_id)->whereKey($actor->id);
|
||||
if ($locked) {
|
||||
$q->lockForUpdate();
|
||||
}$user = $q->firstOrFail();
|
||||
abort_unless($user->hasFunctions(['finance']) && ! app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
abort_unless(Schema::hasTable('sgf_invoice_dispatches') && Schema::hasTable('sgf_invoice_dispatch_events'), 503, 'Estrutura de envio ainda não instalada.');
|
||||
|
||||
return $user;
|
||||
}
|
||||
public static function assertLocalRegistration(int $tenant,int $supplier,string $number):void
|
||||
|
||||
public static function assertLocalRegistration(int $tenant, int $supplier, string $number): void
|
||||
{
|
||||
// Keep the claim even if the workspace/transport is later disabled.
|
||||
if(Schema::hasTable('sgf_invoice_dispatches')&&DB::table('sgf_invoice_dispatches')->where(['tenant_id'=>$tenant,'supplier_id'=>$supplier,'number'=>$number])->exists())
|
||||
throw ValidationException::withMessages(['invoice'=>'Documento reservado ao envio SGF; consultar o recibo, sem segundo registo local.']);
|
||||
}
|
||||
public function mappings(User $actor):array
|
||||
{
|
||||
$this->actor($actor);$out=[];
|
||||
foreach(config('sgf_invoice.connections',[])as$c=>$connection)if(($connection['source_scope']['tenant_id']??null)===$actor->tenant_id)
|
||||
foreach($connection['mappings']??[]as$m=>$entry)if(($entry['approved']??false)===true)$out[]=['connection'=>$c,'id'=>$m,'label'=>$entry['label']??$m,'mapping'=>$entry['mapping']];
|
||||
return $out;
|
||||
}
|
||||
private function mapping(User $actor,string $connection,string $id):array
|
||||
{
|
||||
$all=config('sgf_invoice.connections',[]);$c=$all[$connection]??null;$m=$c['mappings'][$id]??null;
|
||||
abort_unless(is_array($c)&&($c['source_scope']['tenant_id']??null)===$actor->tenant_id&&is_array($m)&&($m['approved']??false)===true,403);
|
||||
abort_if(array_diff(array_keys($m),['approved','label','source_supplier_id','mapping','approved_by','approved_at']),503,'Configuração de mapeamento inválida.');
|
||||
abort_unless(($m['mapping']['source_scope']['tenant_id']??null)===$actor->tenant_id&&($m['mapping']['authority']??null)==='sgf_only',403);
|
||||
abort_unless(is_int($m['source_supplier_id']??null)&&Supplier::where('tenant_id',$actor->tenant_id)->whereKey($m['source_supplier_id'])->exists(),403);
|
||||
return $m;
|
||||
}
|
||||
private function checkSource(object $row,User $actor):array
|
||||
{
|
||||
$m=$this->mapping($actor,$row->connection_id,$row->mapping_id);
|
||||
abort_unless(hash_equals($row->mapping_hash,self::hash($m)),409,'O mapeamento mudou; exige nova conferência.');
|
||||
abort_if(Invoice::where('tenant_id',$actor->tenant_id)->where('supplier_id',$row->supplier_id)->where('number',$row->number)->exists(),409,'Documento já registado no SGC. Não reenviar.');
|
||||
return $m;
|
||||
}
|
||||
private function validated(array $input):array
|
||||
{
|
||||
$d=Validator::make($input,['reference'=>'required|string|min:2|max:120','connection_id'=>'required|string|max:64','mapping_id'=>'required|string|max:64','reason'=>'required|string|min:10|max:2000',
|
||||
'document'=>'required|array:number,issued_on,subtotal,tax,total,items','document.number'=>'required|string|max:100','document.issued_on'=>'required|date_format:Y-m-d',
|
||||
'document.subtotal'=>'required|string|regex:/^\d{1,12}\.\d{2}$/D','document.tax'=>'required|string|regex:/^\d{1,12}\.\d{2}$/D','document.total'=>'required|string|regex:/^\d{1,12}\.\d{2}$/D',
|
||||
'document.items'=>'required|array|min:1|max:50','document.items.*'=>'array:source_line_ref,quantity,unit,unit_price,tax_rate',
|
||||
'document.items.*.source_line_ref'=>'required|string|max:120|distinct','document.items.*.quantity'=>'required|string|regex:/^\d{1,9}(\.\d{1,3})?$/D',
|
||||
'document.items.*.unit'=>'required|string|max:20','document.items.*.unit_price'=>'required|string|regex:/^\d{1,12}\.\d{2}$/D','document.items.*.tax_rate'=>'required|string|regex:/^\d{1,3}(\.\d{1,2})?$/D'])->validate();
|
||||
abort_if(array_diff(array_keys($input),array_keys($d)),422);
|
||||
return $d;
|
||||
}
|
||||
public function create(User $actor,array $input):int
|
||||
{
|
||||
$d=$this->validated($input);
|
||||
return DB::transaction(function()use($actor,$d){
|
||||
$user=$this->actor($actor,true);$m=$this->mapping($user,$d['connection_id'],$d['mapping_id']);$doc=$d['document'];$doc['number']=Str::upper(Str::squish($doc['number']));
|
||||
$ids=[];foreach($doc['items']as$item){$id=$m['mapping']['lines'][$item['source_line_ref']]??null;abort_unless(is_int($id)&&$id>0&&!in_array($id,$ids,true),422,'Linha sem mapeamento explícito.');$ids[]=$id;}
|
||||
abort_if(Invoice::where('tenant_id',$user->tenant_id)->where('supplier_id',$m['source_supplier_id'])->where('number',$doc['number'])->exists(),409,'Documento já registado no SGC.');
|
||||
abort_if(DB::table('sgf_invoice_dispatches')->where('tenant_id',$user->tenant_id)->where(fn($q)=>$q->where('reference',$d['reference'])->orWhere(fn($q)=>$q->where('supplier_id',$m['source_supplier_id'])->where('number',$doc['number'])))->exists(),409,'Já existe uma intenção para esta fonte.');
|
||||
$id=DB::table('sgf_invoice_dispatches')->insertGetId(['tenant_id'=>$user->tenant_id,'supplier_id'=>$m['source_supplier_id'],'reference'=>$d['reference'],'number'=>$doc['number'],
|
||||
'connection_id'=>$d['connection_id'],'mapping_id'=>$d['mapping_id'],'mapping_snapshot'=>json_encode($m,JSON_THROW_ON_ERROR),'mapping_hash'=>self::hash($m),
|
||||
'document'=>json_encode($doc,JSON_THROW_ON_ERROR),'reason'=>$d['reason'],'created_by'=>$user->id,'created_at'=>now('UTC'),'updated_at'=>now('UTC')]);
|
||||
$row=$this->row($user,$id);$this->event($row,$user,'draft.created',$d['reason'],null);return $id;
|
||||
});
|
||||
}
|
||||
public function revise(User $actor,int $id,int $version,array $input):object
|
||||
{
|
||||
$d=$this->validated($input);
|
||||
return DB::transaction(function()use($actor,$id,$version,$d){
|
||||
$user=$this->actor($actor,true);$row=$this->row($user,$id,true);
|
||||
abort_unless((int)$row->version===$version&&!$row->ever_sending&&$row->phase!=='received_pending'
|
||||
&&(!$row->lease_until||now('UTC')->gte($row->lease_until)),409,'Fonte já enviada/em curso ou versão alterada.');
|
||||
abort_unless($d['reference']===$row->reference,422,'Referência de origem imutável.');
|
||||
$m=$this->mapping($user,$d['connection_id'],$d['mapping_id']);$doc=$d['document'];$doc['number']=Str::upper(Str::squish($doc['number']));
|
||||
$used=[];foreach($doc['items']as$item){$line=$m['mapping']['lines'][$item['source_line_ref']]??null;abort_unless(is_int($line)&&!in_array($line,$used,true),422);$used[]=$line;}
|
||||
abort_if(Invoice::where('tenant_id',$user->tenant_id)->where('supplier_id',$m['source_supplier_id'])->where('number',$doc['number'])->exists()
|
||||
||DB::table('sgf_invoice_dispatches')->where('tenant_id',$user->tenant_id)->where('supplier_id',$m['source_supplier_id'])->where('number',$doc['number'])->where('id','<>',$id)->exists(),409,'Documento já reservado/registado.');
|
||||
return $this->update($row,$user,['supplier_id'=>$m['source_supplier_id'],'number'=>$doc['number'],'connection_id'=>$d['connection_id'],'mapping_id'=>$d['mapping_id'],
|
||||
'mapping_snapshot'=>json_encode($m,JSON_THROW_ON_ERROR),'mapping_hash'=>self::hash($m),'document'=>json_encode($doc,JSON_THROW_ON_ERROR),'reason'=>$d['reason'],
|
||||
'source_version'=>$row->source_version+1,'phase'=>'draft','operation_key'=>null,'state_ciphertext'=>null,'approval_hash'=>null,'lease_id'=>null,'lease_until'=>null], 'draft.revised',$d['reason']);
|
||||
});
|
||||
}
|
||||
public function row(User $actor,int $id,bool $locked=false):object
|
||||
{
|
||||
$q=DB::table('sgf_invoice_dispatches')->where('tenant_id',$actor->tenant_id)->where('id',$id);if($locked)$q->lockForUpdate();
|
||||
$row=$q->first();abort_unless($row,404);return $row;
|
||||
}
|
||||
private function summary(object $row):array
|
||||
{
|
||||
$state=$this->state($row);
|
||||
return ['id'=>$row->id,'reference'=>$row->reference,'number'=>$row->number,'version'=>(int)$row->version,'source_version'=>(int)$row->source_version,
|
||||
'phase'=>$row->phase,'mapping_hash'=>$row->mapping_hash,'document_hash'=>self::hash(json_decode($row->document,true)),
|
||||
'document'=>json_decode($row->document,true),'mapping_snapshot'=>json_decode($row->mapping_snapshot,true),'reason'=>$row->reason,
|
||||
'operation_key'=>$row->operation_key,'approval_hash'=>$row->approval_hash,'ever_sending'=>(bool)$row->ever_sending,
|
||||
'intent_hash'=>$state['intent']['intent_hash']??null,'impact_hash'=>isset($state['impact'])?self::hash($state['impact']):null,
|
||||
'preview_actor_id'=>$row->preview_actor_id,'source_context_hash'=>$row->source_context_hash,
|
||||
'receipt'=>$row->receipt?json_decode($row->receipt,true):null];
|
||||
}
|
||||
private function event(object $row,User $actor,string $action,string $reason,?array $before):void
|
||||
{
|
||||
DB::table('sgf_invoice_dispatch_events')->insert(['dispatch_id'=>$row->id,'tenant_id'=>$row->tenant_id,'version'=>$row->version,'actor_id'=>$actor->id,
|
||||
'action'=>$action,'reason'=>$reason,'before_state'=>$before?json_encode($before,JSON_THROW_ON_ERROR):null,'after_state'=>json_encode($this->summary($row),JSON_THROW_ON_ERROR),'created_at'=>now('UTC')]);
|
||||
}
|
||||
private function update(object $row,User $actor,array $changes,string $action,string $reason):object
|
||||
{
|
||||
$before=$this->summary($row);$changes+=['version'=>$row->version+1,'updated_at'=>now('UTC')];
|
||||
DB::table('sgf_invoice_dispatches')->where('id',$row->id)->where('tenant_id',$row->tenant_id)->update($changes);
|
||||
$next=$this->row($actor,$row->id);$this->event($next,$actor,$action,$reason,$before);return $next;
|
||||
}
|
||||
private function state(object $row):?array{return $row->state_ciphertext?json_decode(Crypt::decryptString($row->state_ciphertext),true,128,JSON_THROW_ON_ERROR):null;}
|
||||
private function contextHash(User $actor):string
|
||||
{
|
||||
return self::hash([$actor->tenant_id,request()->hasSession()?request()->session()->get('work_context'):null]);
|
||||
if (Schema::hasTable('sgf_invoice_dispatches') && DB::table('sgf_invoice_dispatches')->where(['tenant_id' => $tenant, 'supplier_id' => $supplier, 'number' => $number])->exists()) {
|
||||
throw ValidationException::withMessages(['invoice' => 'Documento reservado ao envio SGF; consultar o recibo, sem segundo registo local.']);
|
||||
}
|
||||
}
|
||||
|
||||
public function dispatch(User $actor,int $id,int $version,string $action,string $reason,?string $approval):object
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function mappings(User $actor): array
|
||||
{
|
||||
abort_unless(in_array($action,['preview','confirm','recover'],true),422);
|
||||
abort_unless(config('sgf_invoice.enabled')===true,423,'Transporte desligado; o rascunho permanece conservado.');
|
||||
Validator::make(['reason'=>$reason],['reason'=>'required|string|min:10|max:2000'])->validate();
|
||||
// Commit the intent/decision/lease BEFORE network. Neither DB locks nor an HTTP retry may silently duplicate a decision.
|
||||
[$row,$client,$state,$m,$lease]=DB::transaction(function()use($actor,$id,$version,$action,$reason,$approval){
|
||||
$user=$this->actor($actor,true);$row=$this->row($user,$id,true);abort_unless((int)$row->version===$version,409,'Versão desactualizada.');
|
||||
abort_unless(!$row->lease_until||now('UTC')->gte($row->lease_until),409,'Operação em curso; aguarde e consulte o estado.');
|
||||
abort_if($row->phase==='received_pending',409,'Recibo já conservado.');$m=$this->checkSource($row,$user);
|
||||
$client=app(SgfInvoiceGateway::class)->clientFor($user,$row->connection_id);$state=$this->state($row);
|
||||
if($state){
|
||||
$expected=$client->intent($m['mapping'],['reference'=>$row->reference,'version'=>(string)$row->source_version,'state'=>'unregistered_draft','document'=>json_decode($row->document,true)],$row->operation_key,$row->reason);
|
||||
if(($state['intent']['intent_hash']??null)!==$expected['intent_hash']){
|
||||
abort_unless($action==='preview',409,'Ligação ou contexto mudaram; exige nova conferência.');
|
||||
$state=['intent'=>$expected,'phase'=>'draft'];
|
||||
$this->actor($actor);
|
||||
$out = [];
|
||||
foreach (config('sgf_invoice.connections', []) as $c => $connection) {
|
||||
if (($connection['source_scope']['tenant_id'] ?? null) === $actor->tenant_id) {
|
||||
foreach ($connection['mappings'] ?? [] as $m => $entry) {
|
||||
if (($entry['approved'] ?? false) === true) {
|
||||
$out[] = ['connection' => $c, 'id' => $m, 'label' => $entry['label'] ?? $m, 'mapping' => $entry['mapping']];
|
||||
}
|
||||
}
|
||||
}
|
||||
$lease=(string)Str::uuid();$changes=['lease_id'=>$lease,'lease_until'=>now('UTC')->addSeconds(120),'phase'=>$action==='preview'?'previewing':'sending'];
|
||||
if($action==='preview'){
|
||||
$changes+=['preview_actor_id'=>$user->id,'source_context_hash'=>$this->contextHash($user)];
|
||||
if(!$state){$key=(string)Str::uuid();$intent=$client->intent($m['mapping'],['reference'=>$row->reference,'version'=>(string)$row->source_version,'state'=>'unregistered_draft','document'=>json_decode($row->document,true)],$key,$row->reason);$state=['intent'=>$intent,'phase'=>'draft'];$changes['operation_key']=$key;}
|
||||
}elseif($action==='confirm'){
|
||||
abort_unless($row->phase==='previewed'&&$state&&is_string($approval)&&hash_equals($state['approval_hash']??'',$approval),409,'Aprovar individualmente a prévia actual.');
|
||||
abort_unless((int)$row->preview_actor_id===$user->id&&$row->source_context_hash===$this->contextHash($user),409,'Operador ou contexto mudaram; conferir novamente.');
|
||||
$changes+=['ever_sending'=>true,'approval_hash'=>$approval];
|
||||
}else{
|
||||
abort_unless((bool)$row->ever_sending&&in_array($row->phase,['sending','uncertain','blocked','review_required','not_sent'],true)&&$state&&$row->approval_hash,409,'Sem confirmação anterior para recuperar.');
|
||||
$state['phase']='uncertain';$approval=$row->approval_hash;
|
||||
}
|
||||
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function mapping(User $actor, string $connection, string $id): array
|
||||
{
|
||||
$all = config('sgf_invoice.connections', []);
|
||||
$c = $all[$connection] ?? null;
|
||||
$m = $c['mappings'][$id] ?? null;
|
||||
abort_unless(is_array($c) && ($c['source_scope']['tenant_id'] ?? null) === $actor->tenant_id && is_array($m) && ($m['approved'] ?? false) === true, 403);
|
||||
abort_if(array_diff(array_keys($m), ['approved', 'label', 'source_supplier_id', 'mapping', 'approved_by', 'approved_at']) !== [], 503, 'Configuração de mapeamento inválida.');
|
||||
abort_unless(($m['mapping']['source_scope']['tenant_id'] ?? null) === $actor->tenant_id && ($m['mapping']['authority'] ?? null) === 'sgf_only', 403);
|
||||
abort_unless(is_int($m['source_supplier_id'] ?? null) && Supplier::where('tenant_id', $actor->tenant_id)->whereKey($m['source_supplier_id'])->exists(), 403);
|
||||
|
||||
return $m;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function checkSource(\stdClass $row, User $actor): array
|
||||
{
|
||||
$m = $this->mapping($actor, $row->connection_id, $row->mapping_id);
|
||||
abort_unless(hash_equals($row->mapping_hash, self::hash($m)), 409, 'O mapeamento mudou; exige nova conferência.');
|
||||
abort_if(Invoice::where('tenant_id', $actor->tenant_id)->where('supplier_id', $row->supplier_id)->where('number', $row->number)->exists(), 409, 'Documento já registado no SGC. Não reenviar.');
|
||||
|
||||
return $m;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function validated(array $input): array
|
||||
{
|
||||
$d = Validator::make($input, ['reference' => 'required|string|min:2|max:120', 'connection_id' => 'required|string|max:64', 'mapping_id' => 'required|string|max:64', 'reason' => 'required|string|min:10|max:2000',
|
||||
'document' => 'required|array:number,issued_on,subtotal,tax,total,items', 'document.number' => 'required|string|max:100', 'document.issued_on' => 'required|date_format:Y-m-d',
|
||||
'document.subtotal' => 'required|string|regex:/^\d{1,12}\.\d{2}$/D', 'document.tax' => 'required|string|regex:/^\d{1,12}\.\d{2}$/D', 'document.total' => 'required|string|regex:/^\d{1,12}\.\d{2}$/D',
|
||||
'document.items' => 'required|array|min:1|max:50', 'document.items.*' => 'array:source_line_ref,quantity,unit,unit_price,tax_rate',
|
||||
'document.items.*.source_line_ref' => 'required|string|max:120|distinct', 'document.items.*.quantity' => 'required|string|regex:/^\d{1,9}(\.\d{1,3})?$/D',
|
||||
'document.items.*.unit' => 'required|string|max:20', 'document.items.*.unit_price' => 'required|string|regex:/^\d{1,12}\.\d{2}$/D', 'document.items.*.tax_rate' => 'required|string|regex:/^\d{1,3}(\.\d{1,2})?$/D'])->validate();
|
||||
abort_if(array_diff(array_keys($input), array_keys($d)) !== [], 422);
|
||||
|
||||
return $d;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function create(User $actor, array $input): int
|
||||
{
|
||||
$d = $this->validated($input);
|
||||
|
||||
return DB::transaction(function () use ($actor, $d) {
|
||||
$user = $this->actor($actor, true);
|
||||
$m = $this->mapping($user, $d['connection_id'], $d['mapping_id']);
|
||||
$doc = $d['document'];
|
||||
$doc['number'] = Str::upper(Str::squish($doc['number']));
|
||||
$ids = [];
|
||||
foreach ($doc['items'] as $item) {
|
||||
$id = $m['mapping']['lines'][$item['source_line_ref']] ?? null;
|
||||
abort_unless(is_int($id) && $id > 0 && ! in_array($id, $ids, true), 422, 'Linha sem mapeamento explícito.');
|
||||
$ids[] = $id;
|
||||
}
|
||||
$changes['state_ciphertext']=Crypt::encryptString(json_encode($state,JSON_THROW_ON_ERROR));
|
||||
$row=$this->update($row,$user,$changes,$action==='confirm'?'decision.confirmed':($action==='recover'?'recovery.started':'preview.started'),$reason);
|
||||
return [$row,$client,$state,$m,$lease];
|
||||
});
|
||||
try{
|
||||
if($action==='preview')$result=array_replace($state,$client->preview($state['intent'],(string)$row->source_version,\Tempo\SgcInvoiceClient\InvoiceClient::mappingHash($m['mapping'])));
|
||||
else $result=$client->confirm($state,$action==='confirm'?$approval:$row->approval_hash,(string)$row->source_version,\Tempo\SgcInvoiceClient\InvoiceClient::mappingHash($m['mapping']));
|
||||
}catch(\Throwable){$result=array_replace($state,['phase'=>$action==='preview'?'not_sent':'uncertain','error'=>'DELIVERY_NOT_CONFIRMED']);}
|
||||
return DB::transaction(function()use($actor,$id,$lease,$result,$reason){
|
||||
app(ConflictGuard::class)->lockCompany($actor);$current=$this->row($actor,$id,true);
|
||||
abort_unless($current->lease_id===$lease,409,'Operação recuperada por outra sessão; actualizar.');
|
||||
$allowed=['previewed','received_pending','uncertain','blocked','review_required','not_sent'];
|
||||
$phase=in_array($result['phase']??null,$allowed,true)?$result['phase']:'uncertain';
|
||||
return $this->update($current,$actor,['phase'=>$phase,'lease_id'=>null,'lease_until'=>null,
|
||||
'state_ciphertext'=>Crypt::encryptString(json_encode($result,JSON_THROW_ON_ERROR)),
|
||||
'receipt'=>isset($result['receipt'])?json_encode($result['receipt'],JSON_THROW_ON_ERROR):null], 'transport.observed',$reason);
|
||||
abort_if(Invoice::where('tenant_id', $user->tenant_id)->where('supplier_id', $m['source_supplier_id'])->where('number', $doc['number'])->exists(), 409, 'Documento já registado no SGC.');
|
||||
abort_if(DB::table('sgf_invoice_dispatches')->where('tenant_id', $user->tenant_id)->where(fn ($q) => $q->where('reference', $d['reference'])->orWhere(fn ($q) => $q->where('supplier_id', $m['source_supplier_id'])->where('number', $doc['number'])))->exists(), 409, 'Já existe uma intenção para esta fonte.');
|
||||
$id = DB::table('sgf_invoice_dispatches')->insertGetId(['tenant_id' => $user->tenant_id, 'supplier_id' => $m['source_supplier_id'], 'reference' => $d['reference'], 'number' => $doc['number'],
|
||||
'connection_id' => $d['connection_id'], 'mapping_id' => $d['mapping_id'], 'mapping_snapshot' => json_encode($m, JSON_THROW_ON_ERROR), 'mapping_hash' => self::hash($m),
|
||||
'document' => json_encode($doc, JSON_THROW_ON_ERROR), 'reason' => $d['reason'], 'created_by' => $user->id, 'created_at' => now('UTC'), 'updated_at' => now('UTC')]);
|
||||
$row = $this->row($user, $id);
|
||||
$this->event($row, $user, 'draft.created', $d['reason'], null);
|
||||
|
||||
return $id;
|
||||
});
|
||||
}
|
||||
public function presentation(User $actor,object $row):array
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function revise(User $actor, int $id, int $version, array $input): \stdClass
|
||||
{
|
||||
$this->actor($actor);$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,
|
||||
'impact'=>$state['impact']??null,'approval_hash'=>$row->phase==='previewed'?($state['approval_hash']??null):null,
|
||||
'lease_until'=>$row->lease_until]);
|
||||
$d = $this->validated($input);
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $version, $d) {
|
||||
$user = $this->actor($actor, true);
|
||||
$row = $this->row($user, $id, true);
|
||||
abort_unless((int) $row->version === $version && ! $row->ever_sending && $row->phase !== 'received_pending'
|
||||
&& (! $row->lease_until || now('UTC')->gte($row->lease_until)), 409, 'Fonte já enviada/em curso ou versão alterada.');
|
||||
abort_unless($d['reference'] === $row->reference, 422, 'Referência de origem imutável.');
|
||||
$m = $this->mapping($user, $d['connection_id'], $d['mapping_id']);
|
||||
$doc = $d['document'];
|
||||
$doc['number'] = Str::upper(Str::squish($doc['number']));
|
||||
$used = [];
|
||||
foreach ($doc['items'] as $item) {
|
||||
$line = $m['mapping']['lines'][$item['source_line_ref']] ?? null;
|
||||
abort_unless(is_int($line) && ! in_array($line, $used, true), 422);
|
||||
$used[] = $line;
|
||||
}
|
||||
abort_if(Invoice::where('tenant_id', $user->tenant_id)->where('supplier_id', $m['source_supplier_id'])->where('number', $doc['number'])->exists()
|
||||
|| DB::table('sgf_invoice_dispatches')->where('tenant_id', $user->tenant_id)->where('supplier_id', $m['source_supplier_id'])->where('number', $doc['number'])->where('id', '<>', $id)->exists(), 409, 'Documento já reservado/registado.');
|
||||
|
||||
return $this->update($row, $user, ['supplier_id' => $m['source_supplier_id'], 'number' => $doc['number'], 'connection_id' => $d['connection_id'], 'mapping_id' => $d['mapping_id'],
|
||||
'mapping_snapshot' => json_encode($m, JSON_THROW_ON_ERROR), 'mapping_hash' => self::hash($m), 'document' => json_encode($doc, JSON_THROW_ON_ERROR), 'reason' => $d['reason'],
|
||||
'source_version' => $row->source_version + 1, 'phase' => 'draft', 'operation_key' => null, 'state_ciphertext' => null, 'approval_hash' => null, 'lease_id' => null, 'lease_until' => null], 'draft.revised', $d['reason']);
|
||||
});
|
||||
}
|
||||
public static function hash(mixed $v):string
|
||||
|
||||
public function row(User $actor, int $id, bool $locked = false): \stdClass
|
||||
{
|
||||
$normalise=function($x)use(&$normalise){if(!is_array($x))return $x;if(!array_is_list($x))ksort($x,SORT_STRING);foreach($x as&$item)$item=$normalise($item);return $x;};
|
||||
return hash('sha256',json_encode($normalise($v),JSON_THROW_ON_ERROR|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
|
||||
$q = DB::table('sgf_invoice_dispatches')->where('tenant_id', $actor->tenant_id)->where('id', $id);
|
||||
if ($locked) {
|
||||
$q->lockForUpdate();
|
||||
}
|
||||
$row = $q->first();
|
||||
abort_unless($row !== null, 404);
|
||||
|
||||
return $row;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function summary(\stdClass $row): array
|
||||
{
|
||||
$state = $this->state($row);
|
||||
|
||||
return ['id' => $row->id, 'reference' => $row->reference, 'number' => $row->number, 'version' => (int) $row->version, 'source_version' => (int) $row->source_version,
|
||||
'phase' => $row->phase, 'mapping_hash' => $row->mapping_hash, 'document_hash' => self::hash(json_decode($row->document, true)),
|
||||
'document' => json_decode($row->document, true), 'mapping_snapshot' => json_decode($row->mapping_snapshot, true), 'reason' => $row->reason,
|
||||
'operation_key' => $row->operation_key, 'approval_hash' => $row->approval_hash, 'ever_sending' => (bool) $row->ever_sending,
|
||||
'intent_hash' => $state['intent']['intent_hash'] ?? null, 'impact_hash' => isset($state['impact']) ? self::hash($state['impact']) : null,
|
||||
'preview_actor_id' => $row->preview_actor_id, 'source_context_hash' => $row->source_context_hash,
|
||||
'receipt' => $row->receipt ? json_decode($row->receipt, true) : null];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed>|null $before */
|
||||
private function event(\stdClass $row, User $actor, string $action, string $reason, ?array $before): void
|
||||
{
|
||||
DB::table('sgf_invoice_dispatch_events')->insert(['dispatch_id' => $row->id, 'tenant_id' => $row->tenant_id, 'version' => $row->version, 'actor_id' => $actor->id,
|
||||
'action' => $action, 'reason' => $reason, 'before_state' => $before ? json_encode($before, JSON_THROW_ON_ERROR) : null, 'after_state' => json_encode($this->summary($row), JSON_THROW_ON_ERROR), 'created_at' => now('UTC')]);
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $changes */
|
||||
private function update(\stdClass $row, User $actor, array $changes, string $action, string $reason): \stdClass
|
||||
{
|
||||
$before = $this->summary($row);
|
||||
$changes += ['version' => $row->version + 1, 'updated_at' => now('UTC')];
|
||||
DB::table('sgf_invoice_dispatches')->where('id', $row->id)->where('tenant_id', $row->tenant_id)->update($changes);
|
||||
$next = $this->row($actor, $row->id);
|
||||
$this->event($next, $actor, $action, $reason, $before);
|
||||
|
||||
return $next;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
private function state(\stdClass $row): ?array
|
||||
{
|
||||
return $row->state_ciphertext ? json_decode(Crypt::decryptString($row->state_ciphertext), true, 128, JSON_THROW_ON_ERROR) : null;
|
||||
}
|
||||
|
||||
private function contextHash(User $actor): string
|
||||
{
|
||||
return self::hash([$actor->tenant_id, request()->hasSession() ? request()->session()->get('work_context') : null]);
|
||||
}
|
||||
|
||||
public function dispatch(User $actor, int $id, int $version, string $action, string $reason, ?string $approval): \stdClass
|
||||
{
|
||||
abort_unless(in_array($action, ['preview', 'confirm', 'recover'], true), 422);
|
||||
abort_unless(config('sgf_invoice.enabled') === true, 423, 'Transporte desligado; o rascunho permanece conservado.');
|
||||
Validator::make(['reason' => $reason], ['reason' => 'required|string|min:10|max:2000'])->validate();
|
||||
// Commit the intent/decision/lease BEFORE network. Neither DB locks nor an HTTP retry may silently duplicate a decision.
|
||||
[$row,$client,$state,$m,$lease] = DB::transaction(function () use ($actor, $id, $version, $action, $reason, $approval) {
|
||||
$user = $this->actor($actor, true);
|
||||
$row = $this->row($user, $id, true);
|
||||
abort_unless((int) $row->version === $version, 409, 'Versão desactualizada.');
|
||||
abort_unless(! $row->lease_until || now('UTC')->gte($row->lease_until), 409, 'Operação em curso; aguarde e consulte o estado.');
|
||||
abort_if($row->phase === 'received_pending', 409, 'Recibo já conservado.');
|
||||
$m = $this->checkSource($row, $user);
|
||||
$client = app(SgfInvoiceGateway::class)->clientFor($user, $row->connection_id);
|
||||
$state = $this->state($row);
|
||||
if ($state) {
|
||||
$expected = $client->intent($m['mapping'], ['reference' => $row->reference, 'version' => (string) $row->source_version, 'state' => 'unregistered_draft', 'document' => json_decode($row->document, true)], $row->operation_key, $row->reason);
|
||||
if (($state['intent']['intent_hash'] ?? null) !== $expected['intent_hash']) {
|
||||
abort_unless($action === 'preview', 409, 'Ligação ou contexto mudaram; exige nova conferência.');
|
||||
$state = ['intent' => $expected, 'phase' => 'draft'];
|
||||
}
|
||||
}
|
||||
$lease = (string) Str::uuid();
|
||||
$changes = ['lease_id' => $lease, 'lease_until' => now('UTC')->addSeconds(120), 'phase' => $action === 'preview' ? 'previewing' : 'sending'];
|
||||
if ($action === 'preview') {
|
||||
$changes += ['preview_actor_id' => $user->id, 'source_context_hash' => $this->contextHash($user)];
|
||||
if (! $state) {
|
||||
$key = (string) Str::uuid();
|
||||
$intent = $client->intent($m['mapping'], ['reference' => $row->reference, 'version' => (string) $row->source_version, 'state' => 'unregistered_draft', 'document' => json_decode($row->document, true)], $key, $row->reason);
|
||||
$state = ['intent' => $intent, 'phase' => 'draft'];
|
||||
$changes['operation_key'] = $key;
|
||||
}
|
||||
} elseif ($action === 'confirm') {
|
||||
abort_unless($row->phase === 'previewed' && $state && is_string($approval) && hash_equals($state['approval_hash'] ?? '', $approval), 409, 'Aprovar individualmente a prévia actual.');
|
||||
abort_unless((int) $row->preview_actor_id === $user->id && $row->source_context_hash === $this->contextHash($user), 409, 'Operador ou contexto mudaram; conferir novamente.');
|
||||
$changes += ['ever_sending' => true, 'approval_hash' => $approval];
|
||||
} else {
|
||||
abort_unless((bool) $row->ever_sending && in_array($row->phase, ['sending', 'uncertain', 'blocked', 'review_required', 'not_sent'], true) && $state && $row->approval_hash, 409, 'Sem confirmação anterior para recuperar.');
|
||||
$state['phase'] = 'uncertain';
|
||||
$approval = $row->approval_hash;
|
||||
}
|
||||
$changes['state_ciphertext'] = Crypt::encryptString(json_encode($state, JSON_THROW_ON_ERROR));
|
||||
$row = $this->update($row, $user, $changes, $action === 'confirm' ? 'decision.confirmed' : ($action === 'recover' ? 'recovery.started' : 'preview.started'), $reason);
|
||||
|
||||
return [$row, $client, $state, $m, $lease];
|
||||
});
|
||||
try {
|
||||
if ($action === 'preview') {
|
||||
$result = array_replace($state, $client->preview($state['intent'], (string) $row->source_version, InvoiceClient::mappingHash($m['mapping'])));
|
||||
} else {
|
||||
$result = $client->confirm($state, $action === 'confirm' ? $approval : $row->approval_hash, (string) $row->source_version, InvoiceClient::mappingHash($m['mapping']));
|
||||
}
|
||||
} catch (\Throwable) {
|
||||
$result = array_replace($state, ['phase' => $action === 'preview' ? 'not_sent' : 'uncertain', 'error' => 'DELIVERY_NOT_CONFIRMED']);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $lease, $result, $reason) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$current = $this->row($actor, $id, true);
|
||||
abort_unless($current->lease_id === $lease, 409, 'Operação recuperada por outra sessão; actualizar.');
|
||||
$allowed = ['previewed', 'received_pending', 'uncertain', 'blocked', 'review_required', 'not_sent'];
|
||||
$phase = in_array($result['phase'] ?? null, $allowed, true) ? $result['phase'] : 'uncertain';
|
||||
|
||||
return $this->update($current, $actor, ['phase' => $phase, 'lease_id' => null, 'lease_until' => null,
|
||||
'state_ciphertext' => Crypt::encryptString(json_encode($result, JSON_THROW_ON_ERROR)),
|
||||
'receipt' => isset($result['receipt']) ? json_encode($result['receipt'], JSON_THROW_ON_ERROR) : null], 'transport.observed', $reason);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function presentation(User $actor, \stdClass $row): array
|
||||
{
|
||||
$this->actor($actor);
|
||||
$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,
|
||||
'impact' => $state['impact'] ?? null, 'approval_hash' => $row->phase === 'previewed' ? ($state['approval_hash'] ?? null) : null,
|
||||
'lease_until' => $row->lease_until]);
|
||||
}
|
||||
|
||||
public static function hash(mixed $v): string
|
||||
{
|
||||
$normalise = function ($x) use (&$normalise) {
|
||||
if (! is_array($x)) {
|
||||
return $x;
|
||||
}if (! array_is_list($x)) {
|
||||
ksort($x,SORT_STRING);
|
||||
}foreach ($x as &$item) {
|
||||
$item = $normalise($item);
|
||||
}
|
||||
|
||||
return $x;
|
||||
};
|
||||
|
||||
return hash('sha256',json_encode($normalise($v),JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,10 +18,13 @@ final class SgfInvoiceGateway
|
||||
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)
|
||||
||!hash_equals($pin,hash_file('sha256',$path)))throw new LogicException('Verified client package required.');
|
||||
||!is_string($actual)||!hash_equals($pin,$actual))throw new LogicException('Verified client package required.');
|
||||
if(class_exists(\Tempo\SgcInvoiceClient\InvoiceClient::class,false)){
|
||||
if(!hash_equals($pin,hash_file('sha256',(new \ReflectionClass(\Tempo\SgcInvoiceClient\InvoiceClient::class))->getFileName())))throw new LogicException('Client version changed; restart separately.');
|
||||
$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'],
|
||||
|
||||
@@ -10,9 +10,13 @@ final class StockIssueMovement
|
||||
public function for(User $actor): \Tempo\Inventory\IssueMovementWriter
|
||||
{
|
||||
$root=base_path('packages/inventory-issue/releases/0.1.0');
|
||||
if(!is_file($root.'/manifest.json')||!hash_equals('3c24d9e9fb99bfbb274077495c3a42ddb7eccab06b5c6a956cd739b2bc9b56f0',hash_file('sha256',$root.'/manifest.json')))throw new \LogicException('Pacote de saída incompatível.');
|
||||
$m=json_decode(file_get_contents($root.'/manifest.json'),true,512,JSON_THROW_ON_ERROR);
|
||||
foreach(['bootstrap.php','src/IssueMovementWriter.php'] as $f)if(!is_file($root.'/'.$f)||!hash_equals($m['files'][$f]??'',hash_file('sha256',$root.'/'.$f)))throw new \LogicException('Pacote de saída alterado.');
|
||||
$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]);});
|
||||
|
||||
@@ -280,6 +280,7 @@ class StockWorkflow
|
||||
{
|
||||
if($type==='issue'&&$operation->kind==='issue'){
|
||||
$writer=app(StockIssueMovement::class)->for($actor);$result=$writer->write($operation->id,$writer->preview($operation->id));
|
||||
if(!is_int($result['movement_id']??null)||$result['movement_id']<1)throw new \LogicException('Referência de movimento devolvida pelo escritor incompatível.');
|
||||
return StockMovement::query()->findOrFail($result['movement_id']);
|
||||
}
|
||||
return StockMovement::query()->create(['tenant_id' => $actor->tenant_id, 'stock_operation_id' => $operation->id, 'stock_item_id' => $operation->stock_item_id, 'warehouse_id' => $warehouse, 'equipment_id' => $operation->equipment_id, 'spare_part_id' => $operation->spare_part_id, 'moved_by' => $actor->id, 'movement_type' => $type, 'quantity_milli' => $quantity, 'snapshot' => [...$operation->snapshot, 'warehouse' => Warehouse::query()->findOrFail($warehouse)->only(['id', 'code', 'name']), 'reference' => $operation->reference, 'reason' => $operation->reason], 'moved_at' => now()]);
|
||||
|
||||
@@ -7,14 +7,54 @@ use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\SupplierBankReview;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
class SupplierBankWorkflow
|
||||
{
|
||||
public function multipleReady(): bool
|
||||
{
|
||||
return Schema::hasColumn('supplier_bank_details', 'account_key');
|
||||
}
|
||||
|
||||
/** @return Builder<SupplierBankDetail> */
|
||||
public function account(Supplier $supplier, ?string $key = null): Builder
|
||||
{
|
||||
$query = SupplierBankDetail::query()->where('tenant_id', $supplier->tenant_id)->where('supplier_id', $supplier->id);
|
||||
if ($this->multipleReady()) {
|
||||
$query->where('account_key', $key);
|
||||
} else {
|
||||
abort_unless($key === null, 503, 'A estrutura de contas independentes ainda não está instalada.');
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
public function latest(Supplier $supplier, ?string $key = null): ?SupplierBankDetail
|
||||
{
|
||||
return $this->account($supplier, $key)->latest('revision')->first();
|
||||
}
|
||||
|
||||
/** @return Collection<int,SupplierBankDetail> */
|
||||
public function currentAccounts(Supplier $supplier): Collection
|
||||
{
|
||||
$query = SupplierBankDetail::query()->where('tenant_id', $supplier->tenant_id)->where('supplier_id', $supplier->id);
|
||||
if (! $this->multipleReady()) {
|
||||
return $query->latest('revision')->limit(1)->get();
|
||||
}
|
||||
|
||||
return $query->whereIn('revision', fn ($q) => $q->from('supplier_bank_details')->where('tenant_id', $supplier->tenant_id)
|
||||
->where('supplier_id', $supplier->id)->groupBy('account_key')->selectRaw('MAX(revision)'))
|
||||
->orderBy('revision')->get();
|
||||
}
|
||||
|
||||
private function actor(User $user, Supplier $supplier): void
|
||||
{
|
||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null && $supplier->tenant_id === $user->tenant_id, 403);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($user), 403);
|
||||
if (app(ConflictGuard::class)->hasConflict($user->id, $supplier->id, null)) {
|
||||
throw ValidationException::withMessages(['bank' => 'Conflito de interesses com este fornecedor.']);
|
||||
}
|
||||
@@ -31,11 +71,24 @@ class SupplierBankWorkflow
|
||||
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Procurement]);
|
||||
$supplier = Supplier::query()->lockForUpdate()->findOrFail($supplier->id);
|
||||
$this->actor($user, $supplier);
|
||||
$latest = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
|
||||
$key = validator($data, ['account_key' => 'nullable|uuid'])->validate()['account_key'] ?? null;
|
||||
$key = $key === null ? null : strtolower($key);
|
||||
$latest = $this->latest($supplier, $key);
|
||||
$fields = ['bank_name', 'country', 'currency', 'beneficiary', 'account_identifier', 'evidence_reference', 'reason'];
|
||||
if ($key !== null && (int) $data['previous_id'] === 0 && $latest !== null) {
|
||||
$original = $this->account($supplier, $key)->oldest('revision')->firstOrFail();
|
||||
if ($original->created_by === $user->id
|
||||
&& array_map(fn ($field) => $original->$field, $fields) === array_map(fn ($field) => $data[$field] ?? null, $fields)) {
|
||||
return $original;
|
||||
}
|
||||
throw ValidationException::withMessages(['account_key' => 'A identidade desta conta já foi utilizada com outros dados.']);
|
||||
}
|
||||
if ((int) $data['previous_id'] !== ($latest->id ?? 0)) {
|
||||
throw ValidationException::withMessages(['previous_id' => 'Dados bancários alterados. Reabra a ficha antes de propor outra versão.']);
|
||||
}
|
||||
$detail = SupplierBankDetail::query()->create(['tenant_id' => $user->tenant_id, 'supplier_id' => $supplier->id, 'created_by' => $user->id, 'revision' => ($latest->revision ?? 0) + 1, ...array_intersect_key($data, array_flip(['bank_name', 'country', 'currency', 'beneficiary', 'account_identifier', 'evidence_reference', 'reason'])), 'created_at' => now()]);
|
||||
$revision = (int) SupplierBankDetail::query()->where('supplier_id', $supplier->id)->max('revision') + 1;
|
||||
$detail = SupplierBankDetail::query()->create(['tenant_id' => $user->tenant_id, 'supplier_id' => $supplier->id, 'created_by' => $user->id, 'revision' => $revision,
|
||||
...($key === null ? [] : ['account_key' => $key]), ...array_intersect_key($data, array_flip($fields)), 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($user, 'supplier.bank_proposed', null, null, ['supplier_id' => $supplier->id, 'bank_detail_id' => $detail->id, 'revision' => $detail->revision]);
|
||||
|
||||
return $detail;
|
||||
@@ -53,8 +106,8 @@ class SupplierBankWorkflow
|
||||
$user = app(CurrentActor::class)->lock($user, [PurchasingRole::Finance]);
|
||||
$supplier = Supplier::query()->lockForUpdate()->findOrFail($detail->supplier_id);
|
||||
$this->actor($user, $supplier);
|
||||
$latest = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->firstOrFail();
|
||||
if ($latest->id !== $detail->id) {
|
||||
$latest = $this->latest($supplier, $detail->account_key);
|
||||
if ($latest === null || $latest->id !== $detail->id) {
|
||||
throw ValidationException::withMessages(['bank' => 'Versão substituída. Reveja os dados bancários actuais.']);
|
||||
}
|
||||
$existing = SupplierBankReview::query()->where('supplier_bank_detail_id', $detail->id)->where('reviewed_by', $user->id)->first();
|
||||
@@ -74,9 +127,9 @@ class SupplierBankWorkflow
|
||||
}
|
||||
|
||||
/** Re-evaluate inside the payment transaction in the future; UI readiness is not authorisation. */
|
||||
public function state(Supplier $supplier): string
|
||||
public function state(Supplier $supplier, ?string $key = null): string
|
||||
{
|
||||
$detail = SupplierBankDetail::query()->where('supplier_id', $supplier->id)->latest('revision')->first();
|
||||
$detail = $this->latest($supplier, $key);
|
||||
if (! $detail) {
|
||||
return 'missing';
|
||||
}
|
||||
@@ -99,4 +152,18 @@ class SupplierBankWorkflow
|
||||
|
||||
return 'approved';
|
||||
}
|
||||
|
||||
public function canReview(User $actor, SupplierBankDetail $detail): bool
|
||||
{
|
||||
if ($actor->tenant_id !== $detail->tenant_id || $actor->id === $detail->created_by || ! $actor->hasFunctions([PurchasingRole::Finance])
|
||||
|| app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||
|| SupplierBankReview::query()->where('supplier_bank_detail_id', $detail->id)->where('reviewed_by', $actor->id)->exists()) {
|
||||
return false;
|
||||
}
|
||||
$supplier = Supplier::query()->find($detail->supplier_id);
|
||||
|
||||
return $supplier !== null && $supplier->eligible() && $this->latest($supplier, $detail->account_key)?->id === $detail->id
|
||||
&& ! app(ConflictGuard::class)->hasConflict($actor->id, $supplier->id, null)
|
||||
&& $this->state($supplier, $detail->account_key) === 'pending';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,14 @@ final class SupplierPayablePage
|
||||
$now = $adapter->readContext($user);
|
||||
abort_unless($now['scope'] === $context['scope'] && $now['person'] === $context['person'], 409, 'Identidade/contexto alterado; reabra a consulta.');
|
||||
};
|
||||
$engine = new Payables(DB::connection(), $actor->id, $context['person'], $scope,
|
||||
// The default local engine is deliberately older than the optional paged
|
||||
// composition. Negotiate the checked runtime capability, without replacing it.
|
||||
$definition = new \ReflectionClass(Payables::class);
|
||||
$constructor = $definition->getConstructor();
|
||||
abort_unless($constructor !== null && $constructor->getNumberOfParameters() >= 8 && $constructor->getNumberOfRequiredParameters() <= 8
|
||||
&& $definition->hasMethod('listingPage'), 503,
|
||||
'Pacote financeiro sem autorização de leitura paginada; composição explícita pendente.');
|
||||
$engine = $definition->newInstanceArgs([DB::connection(), $actor->id, $context['person'], $scope,
|
||||
static function () {
|
||||
throw new \LogicException('Snapshots de consulta nunca executam comandos.');
|
||||
},
|
||||
@@ -65,8 +72,12 @@ final class SupplierPayablePage
|
||||
}
|
||||
|
||||
return $history;
|
||||
} : null, $read);
|
||||
$data = $engine->listingPage(array_keys($documents), (int) ($options['proposal_page'] ?? 1), (int) ($options['event_page'] ?? 1), $size);
|
||||
} : null, $read]);
|
||||
$listing = $definition->getMethod('listingPage');
|
||||
abort_unless($listing->isPublic() && $listing->getNumberOfRequiredParameters() <= 4 && $listing->getNumberOfParameters() >= 4,
|
||||
503, 'Pacote financeiro sem leitura paginada compatível.');
|
||||
$data = $listing->invoke($engine, array_keys($documents), (int) ($options['proposal_page'] ?? 1), (int) ($options['event_page'] ?? 1), $size);
|
||||
abort_unless(is_array($data), 503, 'Resposta de leitura paginada incompatível.');
|
||||
$data['pagination']['documents'] = ['page' => $pager->currentPage(), 'last_page' => $pager->lastPage(), 'total' => $pager->total(), 'per_page' => $pager->perPage()];
|
||||
$data['listing_query'] = ['page' => $page, 'per_page' => $size, 'q' => $text, 'recognition' => $recognition, 'proposal_page' => (int) ($options['proposal_page'] ?? 1), 'event_page' => (int) ($options['event_page'] ?? 1)];
|
||||
if ($invoiceId !== null) {
|
||||
|
||||
@@ -18,7 +18,7 @@ class WarehouseReservations
|
||||
|
||||
public function committed(int $item, int $warehouse): int
|
||||
{
|
||||
return $this->ready() ? (int) DB::table('warehouse_reservations')->where('tenant_id', auth()->user()?->tenant_id ?? app(ReplenishmentRun::class)->tenantId())->where('stock_item_id', $item)->where('warehouse_id', $warehouse)->sum('quantity_milli') : 0;
|
||||
return $this->ready() ? (int) DB::table('warehouse_reservations')->where('tenant_id', auth()->user()->tenant_id ?? app(ReplenishmentRun::class)->tenantId())->where('stock_item_id', $item)->where('warehouse_id', $warehouse)->sum('quantity_milli') : 0;
|
||||
}
|
||||
|
||||
/** @return array<int,int> */
|
||||
|
||||
@@ -15,6 +15,7 @@ use App\Models\Quotation;
|
||||
use App\Models\RecommendationAttempt;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\SupplierEvaluation;
|
||||
use App\Models\SupplierImprovement;
|
||||
use App\Models\SupplierResponse;
|
||||
@@ -26,6 +27,36 @@ use Illuminate\Support\Facades\Schema;
|
||||
/** Current tasks delegated to the existing module authorities, never another workflow. */
|
||||
class WorkflowTaskInbox
|
||||
{
|
||||
/** @return list<array<string,mixed>> */
|
||||
private function bankReviews(User $actor): array
|
||||
{
|
||||
if (! $actor->hasFunctions(['finance']) || ! Schema::hasTable('supplier_bank_details')) {
|
||||
return [];
|
||||
}
|
||||
$workflow = app(SupplierBankWorkflow::class);
|
||||
$multiple = $workflow->multipleReady();
|
||||
$query = SupplierBankDetail::query()->whereNotExists(function ($q) use ($multiple) {
|
||||
$q->selectRaw('1')->from('supplier_bank_details as newer')->whereColumn('newer.tenant_id', 'supplier_bank_details.tenant_id')
|
||||
->whereColumn('newer.supplier_id', 'supplier_bank_details.supplier_id')->whereColumn('newer.revision', '>', 'supplier_bank_details.revision');
|
||||
if ($multiple) {
|
||||
$q->where(fn ($scope) => $scope->whereColumn('newer.account_key', 'supplier_bank_details.account_key')
|
||||
->orWhere(fn ($legacy) => $legacy->whereNull('newer.account_key')->whereNull('supplier_bank_details.account_key')));
|
||||
}
|
||||
});
|
||||
$rows = [];
|
||||
foreach ($query->lazyById(100) as $detail) {
|
||||
if (! $workflow->canReview($actor, $detail)) {
|
||||
continue;
|
||||
}
|
||||
$rows[] = ['id' => 'supplier-bank:'.$detail->id.':review', 'module' => 'finance', 'reference' => 'Fornecedor #'.$detail->supplier_id,
|
||||
'label' => 'Conferir dados bancários · versão '.$detail->revision, 'task' => 'supplier_bank_review', 'status' => 'pending', 'blocked' => false,
|
||||
'created_at' => $this->date($detail->created_at), 'due_on' => null,
|
||||
'href' => '/fornecedores/'.$detail->supplier_id.'/dados-bancarios'.($detail->account_key === null ? '' : '?account='.rawurlencode($detail->account_key))];
|
||||
}
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function build(User $actor, string $area): array
|
||||
{
|
||||
@@ -36,7 +67,7 @@ class WorkflowTaskInbox
|
||||
}
|
||||
$rows = $area === 'people' ? $this->people($actor) : [...$this->purchases($actor), ...$this->suppliers($actor), ...$this->quotations($actor), ...$this->documentary($actor), ...$this->formalReviews($actor), ...$this->supply($actor), ...$this->suggestions($actor), ...$this->awards($actor), ...$this->warehouse($actor), ...$this->inventoryCorrections($actor), ...$this->lotSetups($actor), ...$this->finance($actor)];
|
||||
if ($area === 'procurement') {
|
||||
$rows = [...$rows, ...$this->supplierImprovements($actor), ...$this->supplierQuality($actor), ...$this->supplyFollowUp($actor), ...$this->lotQuality($actor)];
|
||||
$rows = [...$rows, ...$this->supplierImprovements($actor), ...$this->supplierQuality($actor), ...$this->supplyFollowUp($actor), ...$this->lotQuality($actor), ...$this->bankReviews($actor)];
|
||||
if (config('order_cancellation.enabled') && Schema::hasTable('order_cancellations')) {
|
||||
foreach (OrderCancellation::query()->where('status', 'pending')->lazyById(100) as $record) {
|
||||
if (app(OrderCancellationWorkflow::class)->canDecide($actor, $record)) {
|
||||
|
||||
Reference in New Issue
Block a user