@@ -67,6 +67,30 @@ final class CapitalRegister
|
||||
});
|
||||
}
|
||||
|
||||
/** Read-only backlink; equipment access does not grant access to a capital reference.
|
||||
* @return array{record_key:string,code:string,name:string,version:int,state:string,href:string}|null
|
||||
*/
|
||||
public function referenceForEquipment(User $actor, Equipment $equipment): ?array
|
||||
{
|
||||
if (! $this->ready() || auth()->id() !== $actor->id || $actor->tenant_id !== $equipment->tenant_id) {
|
||||
return null;
|
||||
}
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->find($actor->id);
|
||||
if ($actor === null || app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||
|| ! $actor->hasFunctions(['admin', 'warehouse', 'procurement', 'finance', 'department_head'])
|
||||
|| ($actor->departmentScoped() && $actor->department_id !== $equipment->department_id)) {
|
||||
return null;
|
||||
}
|
||||
$record = $this->visible($actor)->where('tenant_id', $actor->tenant_id)->where('data->type', 'asset')
|
||||
->where('data->equipment_id', $equipment->id)->first();
|
||||
if ($record === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['record_key' => $record->record_key, 'code' => (string) $record->data['code'], 'name' => (string) $record->data['name'],
|
||||
'version' => $record->version, 'state' => $record->state, 'href' => '/projectos-imobilizado?history='.rawurlencode($record->record_key)];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, array $input): SupplyRecord
|
||||
{
|
||||
|
||||
@@ -129,12 +129,21 @@ final class InternalRequisitionPort implements ExpiryRequisitionPort
|
||||
app(EquipmentWorkflow::class)->line($item->toArray(), $r->department_id, $r->priority);
|
||||
}
|
||||
app(CapitalAssignments::class)->assertSubmission($this->actor, $r);
|
||||
app(RequisitionAccountAssignments::class)->assertSubmission($this->actor, $r);
|
||||
app(EquipmentWorkflow::class)->assertTechnical($r);
|
||||
if ($r->needed_by < today()) {
|
||||
throw ValidationException::withMessages(['submission' => 'Actualize a data de entrega antes de submeter.']);
|
||||
}
|
||||
|
||||
$base = Tenant::query()->findOrFail($this->actor->tenant_id)->only(['first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional']);
|
||||
return $this->approvalPlan($r);
|
||||
}
|
||||
|
||||
/** Read-only plan shared by submission and its provisional presentation.
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function approvalPlan(Requisition $r): array
|
||||
{
|
||||
$base = Tenant::query()->findOrFail($r->tenant_id)->only(['first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional']);
|
||||
$estimate = app(ImportEstimates::class)->approval($r);
|
||||
$basis = $estimate['plan']['reference_totals'] ?? null;
|
||||
$amount = $basis === null ? null : $basis[$base['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor'];
|
||||
|
||||
@@ -196,7 +196,7 @@ final class OrderPartsWorkflow
|
||||
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
||||
abort_unless(hash_equals($prepared['fingerprint'], $data['fingerprint']), 409, 'A preparação mudou; consulte as origens actuais.');
|
||||
$this->checkAllocations($actor, $prepared['sources'], $budgetSources);
|
||||
$frames = $requests = $lines = $catalogue = $tariffs = $capital = [];
|
||||
$frames = $requests = $lines = $catalogue = $tariffs = $capital = $accounts = [];
|
||||
$firstQuote = null;
|
||||
foreach ($prepared['sources'] as $source) {
|
||||
$request = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||
@@ -210,6 +210,7 @@ final class OrderPartsWorkflow
|
||||
$requested = $request->items()->get()->keyBy('id');
|
||||
$tariffs += app(ImportTariffCodes::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||
$capital += app(CapitalAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||
$accounts += app(RequisitionAccountAssignments::class)->freezeForItems($actor, array_column($source['items'], 'requisition_item_id'));
|
||||
foreach ($source['items'] as $item) {
|
||||
$native = $requested->get($item['requisition_item_id']);
|
||||
abort_unless($native !== null, 409);
|
||||
@@ -242,7 +243,7 @@ final class OrderPartsWorkflow
|
||||
$exchange = $foreign ? ['exchange_basis' => null,
|
||||
'exchange_sources' => array_map(fn ($s) => ['requisition_id' => $s['requisition_id'], 'exchange_basis' => $s['exchange_basis']], $prepared['sources']),
|
||||
'reference_amounts' => app(OrderPartsExchange::class)->sum(array_column($prepared['sources'], 'reference_amounts'))] : [];
|
||||
$snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), ...($capital === [] ? [] : ['capital_assignments' => $capital]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
|
||||
$snapshot = [...$frames[0], ...$limits, ...$exchange, ...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]), ...($capital === [] ? [] : ['capital_assignments' => $capital]), ...($accounts === [] ? [] : ['account_assignments' => $accounts]), 'company' => Tenant::query()->whereKey($actor->tenant_id)->firstOrFail()->only(['id', 'name']),
|
||||
'supplier' => $firstQuote->supplier?->only(['id', 'name', 'nuit', 'contact', 'email', 'phone', 'address']),
|
||||
'issuer' => $actor->only(['id', 'name']), 'items' => $lines, 'catalogue_sources' => $catalogue,
|
||||
'budget_control' => $commit, 'development_only' => true, 'budget_checked' => true,
|
||||
|
||||
@@ -56,7 +56,7 @@ final class ProcurementDeliveryInsights
|
||||
$today = $instant->setTimezone(config('app.timezone'))->toDateString();
|
||||
$coverage = array_fill_keys(array_keys(self::LABELS), 0);
|
||||
$records = [];
|
||||
$pendingLines = $unknownLines = 0;
|
||||
$pendingLines = $unknownLines = $unverifiedReceipts = 0;
|
||||
$reversed = array_keys(app(InventoryReversals::class)->corrections('receipt'));
|
||||
foreach (PurchaseOrder::query()->visibleTo($actor)->operational()->forRequisitions($requests)->with('items')->lazyById(100) as $order) {
|
||||
app(OrderPartsAccess::class)->origins($order);
|
||||
@@ -66,7 +66,7 @@ final class ProcurementDeliveryInsights
|
||||
->where('gr.tenant_id', $actor->tenant_id)->where('gr.purchase_order_id', $order->id)->whereNotIn('goods_receipt_items.id', $reversed)
|
||||
->orderBy('gr.received_on')->orderBy('gr.id')->orderBy('goods_receipt_items.id')
|
||||
->get(['goods_receipt_items.id', 'goods_receipt_items.purchase_order_item_id', 'goods_receipt_items.received_milli', 'gr.received_on'])->groupBy('purchase_order_item_id');
|
||||
$pending = $unknown = $latePending = $lateCompleted = $maxDays = 0;
|
||||
$pending = $unknown = $unverified = $latePending = $lateCompleted = $maxDays = 0;
|
||||
$details = [];
|
||||
foreach ($progress['lines'] as $line) {
|
||||
$item = $items->get($line['id']);
|
||||
@@ -85,10 +85,12 @@ final class ProcurementDeliveryInsights
|
||||
}
|
||||
}
|
||||
$verified = $verified && $quantity === $line['received_milli'];
|
||||
$unverified += $verified ? 0 : 1;
|
||||
$waiting = $line['received_milli'] < $line['ordered_milli'];
|
||||
$pending += $waiting ? 1 : 0;
|
||||
if (! $verified || $due === null || (! $waiting && $completed === null)) {
|
||||
$unknown++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$end = $waiting ? $today : $completed;
|
||||
@@ -105,7 +107,9 @@ final class ProcurementDeliveryInsights
|
||||
$coverage[$state]++;
|
||||
$pendingLines += $pending;
|
||||
$unknownLines += $unknown;
|
||||
$unverifiedReceipts += $unverified;
|
||||
$records[] = ['id' => $order->id, 'number' => $order->number, 'state' => $state, 'pending_lines' => $pending, 'unknown_lines' => $unknown,
|
||||
'unverified_receipt_lines' => $unverified,
|
||||
'late_days' => $state === 'unknown' && $maxDays === 0 ? null : $maxDays,
|
||||
'quality_pending' => $progress['state'] === 'quality_pending', 'late_lines' => $details, 'href' => '/ordens/'.$order->id];
|
||||
}
|
||||
@@ -116,7 +120,7 @@ final class ProcurementDeliveryInsights
|
||||
$current = $page === null ? 1 : max(1, min($page, $last));
|
||||
|
||||
return ['method' => 'frozen_promised_dates_native_receipts_v1', 'generated_at' => $instant->toIso8601String(), 'view' => $view,
|
||||
'coverage' => $coverage, 'pending_lines' => $pendingLines, 'unknown_lines' => $unknownLines,
|
||||
'coverage' => $coverage, 'pending_lines' => $pendingLines, 'unknown_lines' => $unknownLines, 'unverified_receipt_lines' => $unverifiedReceipts,
|
||||
'records' => ['data' => $page === null ? $filtered : array_slice($filtered, ($current - 1) * 20, 20),
|
||||
'total' => count($filtered), 'current_page' => $current, 'last_page' => $last]];
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||
|
||||
class PurchaseWorkflow
|
||||
{
|
||||
@@ -171,7 +172,9 @@ class PurchaseWorkflow
|
||||
}
|
||||
$tariffs = app(ImportTariffCodes::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||
$capital = app(CapitalAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||
$accounts = app(RequisitionAccountAssignments::class)->freezeForItems($user, array_column($lines, 'requisition_item_id'));
|
||||
$snapshot = [
|
||||
...($accounts === [] ? [] : ['account_assignments' => $accounts]),
|
||||
...($capital === [] ? [] : ['capital_assignments' => $capital]),
|
||||
...($tariffs === [] ? [] : ['import_tariffs' => $tariffs]),
|
||||
...app(AgreementOrderLimits::class)->freeze($user, $quote, $requisition, $lines, $agreementBindings),
|
||||
@@ -314,7 +317,9 @@ class PurchaseWorkflow
|
||||
/** @param array{first_limit_minor: int, second_limit_minor: int, approval_includes_tax: bool, rules_provisional: bool} $rules */
|
||||
private function sourceApproved(Requisition $requisition, array $rules): void
|
||||
{
|
||||
$roles = $this->roles($rules, $rules['approval_includes_tax'] ? $requisition->total_minor : $requisition->subtotal_minor, $requisition->items()->where('purchase_type', 'equipment')->exists());
|
||||
$policy = $requisition->approval_snapshot;
|
||||
$roles = InternalRequisitions::roles(['subtotal_minor' => $requisition->subtotal_minor, 'total_minor' => $requisition->total_minor,
|
||||
'has_equipment' => $requisition->items()->where('purchase_type', 'equipment')->exists()], $policy);
|
||||
$steps = $requisition->steps()->get();
|
||||
$seen = [$requisition->requester_id];
|
||||
if ($requisition->status !== 'approved' || $steps->count() !== count($roles)) {
|
||||
@@ -322,6 +327,7 @@ class PurchaseWorkflow
|
||||
}
|
||||
foreach ($steps as $index => $step) {
|
||||
if ($step->decision !== 'approved' || $step->decided_at === null || $step->role !== $roles[$index] || $step->approver_id === null || in_array($step->approver_id, $seen, true) ||
|
||||
(isset($policy['additional_levels'][$step->role]) && $step->routing !== $policy['additional_levels'][$step->role]) ||
|
||||
! User::query()->where('tenant_id', $requisition->tenant_id)->whereKey($step->approver_id)->exists()) {
|
||||
throw ValidationException::withMessages(['approvals' => 'O histórico de aprovação da estimativa está incompleto ou inconsistente.']);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\RequisitionItem;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Documentary account imputations; the common ledger remains the sole journal writer. */
|
||||
final class RequisitionAccountAssignments
|
||||
{
|
||||
/** @return array{User,Requisition} */
|
||||
private function context(User $actor, Requisition $request): array
|
||||
{
|
||||
abort_unless(app(RequisitionLedgerAccounts::class)->ready(), 503);
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
|
||||
return [$actor, Requisition::query()->visibleTo($actor)->lockForUpdate()->findOrFail($request->id)];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function basis(RequisitionItem $item, Requisition $request): array
|
||||
{
|
||||
return ['line' => $item->only(['id', 'description', 'category', 'purchase_type', 'quantity', 'unit', 'unit_price_minor', 'tax_rate',
|
||||
'subtotal_minor', 'tax_minor', 'total_minor', 'equipment_id', 'spare_part_id', 'category_context', 'catalogue_entry_id']),
|
||||
'cost_center_id' => $request->cost_center_id, 'budget_distribution_preparation' => $request->budget_distribution_preparation];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, Requisition $request, string $search = ''): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $request, $search) {
|
||||
[$actor, $request] = $this->context($actor, $request);
|
||||
$write = $request->status === 'draft' && $request->getAttribute('draft_input') === null && $request->total_minor !== null
|
||||
&& $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor)
|
||||
&& ! app(ConflictGuard::class)->participationBlocked($actor, $request);
|
||||
$items = $request->items()->orderBy('id')->get();
|
||||
|
||||
return ['requisition' => $request->only(['id', 'number', 'status']),
|
||||
'items' => $items->map(fn ($line) => [...$this->basis($line, $request)['line'], 'subtotal_minor' => (string) $line->subtotal_minor,
|
||||
'total_minor' => (string) $line->total_minor, 'basis_hash' => hash('sha256', json_encode($this->basis($line, $request), JSON_THROW_ON_ERROR))]),
|
||||
'current' => app(SupplyPlanning::class)->latest('req_account')->where('data->requisition_id', $request->id)->get(),
|
||||
'history' => SupplyRecord::query()->where('kind', 'req_account')->where('data->requisition_id', $request->id)
|
||||
->latest('id')->paginate(15, ['*'], 'history_page')->withQueryString(),
|
||||
'accounts' => $write ? app(RequisitionLedgerAccounts::class)->options($actor, $search) : null,
|
||||
'canWrite' => $write, 'search' => $search, 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function save(User $actor, Requisition $request, array $input): SupplyRecord
|
||||
{
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'item_id' => 'required|integer|min:1',
|
||||
'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'reason' => 'required|string|min:10|max:4000',
|
||||
'allocations' => 'required|array|min:1|max:20', 'allocations.*.account_id' => 'required|integer|min:1|distinct',
|
||||
'allocations.*.source_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'],
|
||||
'allocations.*.subtotal' => ['required', 'regex:/^\d{1,18}(\.\d{1,2})?$/D'],
|
||||
'allocations.*.total' => ['required', 'regex:/^\d{1,18}(\.\d{1,2})?$/D']])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
usort($data['allocations'], fn ($a, $b) => $a['account_id'] <=> $b['account_id']);
|
||||
$hash = hash('sha256', json_encode([$request->id, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $request, $data, $hash) {
|
||||
[$actor, $request] = $this->context($actor, $request);
|
||||
abort_unless($request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor), 403);
|
||||
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'req_account' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
abort_unless($request->status === 'draft', 409);
|
||||
abort_unless($request->getAttribute('draft_input') === null && $request->total_minor !== null, 409, 'Complete primeiro as linhas e os campos da requisição.');
|
||||
$item = $request->items()->whereKey($data['item_id'])->firstOrFail();
|
||||
$basis = $this->basis($item, $request);
|
||||
abort_unless(hash_equals(hash('sha256', json_encode($basis, JSON_THROW_ON_ERROR)), $data['basis_hash']), 409, 'A linha ou a distribuição mudou. Reveja a imputação.');
|
||||
$old = app(SupplyPlanning::class)->latest('req_account')->where('data->requisition_item_id', $item->id)->first();
|
||||
abort_unless((int) ($old->version ?? 0) === (int) $data['version'], 409);
|
||||
$subtotal = BigDecimal::of(0);
|
||||
$total = BigDecimal::of(0);
|
||||
$allocations = [];
|
||||
foreach ($data['allocations'] as $allocation) {
|
||||
$account = app(RequisitionLedgerAccounts::class)->resolve($actor, (int) $allocation['account_id'], $allocation['source_hash']);
|
||||
$net = BigDecimal::of($allocation['subtotal'])->multipliedBy(100)->toScale(0);
|
||||
$gross = BigDecimal::of($allocation['total'])->multipliedBy(100)->toScale(0);
|
||||
if ($gross->isLessThan($net)) {
|
||||
throw ValidationException::withMessages(['allocations' => 'O total de cada parcela não pode ser inferior à base sem IVA.']);
|
||||
}
|
||||
$subtotal = $subtotal->plus($net);
|
||||
$total = $total->plus($gross);
|
||||
$allocations[] = ['account' => $account, 'subtotal_minor' => (string) $net, 'total_minor' => (string) $gross];
|
||||
}
|
||||
if (! $subtotal->isEqualTo($item->subtotal_minor) || ! $total->isEqualTo($item->total_minor)) {
|
||||
throw ValidationException::withMessages(['allocations' => 'As parcelas devem corresponder exactamente à base sem IVA e ao total da linha.']);
|
||||
}
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_account',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => 'assigned', 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'reason' => $data['reason'],
|
||||
'data' => ['requisition_id' => $request->id, 'requisition_item_id' => $item->id, 'allocations' => $allocations],
|
||||
'snapshot' => $basis, 'created_by' => $actor->id, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'requisition.accounts_assigned', $request, $old?->toArray(), ['record' => $record->toArray()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
public function assertSubmission(User $actor, Requisition $request): void
|
||||
{
|
||||
$items = $request->items()->get();
|
||||
$ids = [];
|
||||
foreach ($items as $item) {
|
||||
$ids[] = $item->id;
|
||||
}
|
||||
$frozen = $this->freezeForItems($actor, $ids);
|
||||
if (! app(RequisitionLedgerAccounts::class)->ready()) {
|
||||
abort_if(config('requisition-accounts.qa_enabled') === true && $items->isNotEmpty(),
|
||||
503, 'Plano de contas indisponível. Não foram criadas reservas ou aprovações.');
|
||||
|
||||
return;
|
||||
}
|
||||
foreach ($items as $item) {
|
||||
if (! isset($frozen[$item->id])) {
|
||||
throw ValidationException::withMessages(['account_assignment' => 'Indique a conta contabilística de cada linha antes de submeter. Não foram criadas reservas ou aprovações.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @param list<int> $ids
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function freezeForItems(User $actor, array $ids): array
|
||||
{
|
||||
if (! Schema::hasTable('supply_records')) {
|
||||
return [];
|
||||
}
|
||||
$records = app(SupplyPlanning::class)->latest('req_account')->whereIn('data->requisition_item_id', $ids)->get();
|
||||
if ($records->isEmpty()) {
|
||||
return [];
|
||||
}
|
||||
abort_unless(app(RequisitionLedgerAccounts::class)->ready(), 503, 'Preserve a origem das contas atribuídas antes de prosseguir.');
|
||||
$result = [];
|
||||
foreach ($records as $record) {
|
||||
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $record->data['requisition_id'])
|
||||
->where('action', 'requisition.accounts_assigned')->where('user_id', $record->created_by)->where('after->record->id', $record->id)->first();
|
||||
$saved = $audit === null ? null : json_decode($audit->after, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null;
|
||||
abort_unless(is_array($saved) && ($saved['data'] ?? null) === $record->data && ($saved['snapshot'] ?? null) === $record->snapshot
|
||||
&& ($saved['version'] ?? null) === $record->version && ($saved['input_hash'] ?? null) === $record->input_hash, 409,
|
||||
'A imputação não corresponde ao registo auditado. Confira a origem antes de prosseguir.');
|
||||
$item = RequisitionItem::query()->whereKey($record->data['requisition_item_id'])->firstOrFail();
|
||||
$request = Requisition::query()->visibleTo($actor)->whereKey($item->requisition_id)->firstOrFail();
|
||||
abort_unless($record->snapshot === $this->basis($item, $request), 409, 'A linha ou a distribuição mudou. Reveja a imputação contabilística.');
|
||||
$result[$item->id] = $record->only(['id', 'version', 'data', 'snapshot', 'reason']);
|
||||
}
|
||||
ksort($result, SORT_NUMERIC);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\RequisitionItem;
|
||||
use App\Models\User;
|
||||
|
||||
/** Advisory exact-content comparison, never an eligibility or approval rule. */
|
||||
final class RequisitionDuplicateHints
|
||||
{
|
||||
/** @return list<string> */
|
||||
private function lines(Requisition $request): array
|
||||
{
|
||||
$rows = $request->items->map(function (RequisitionItem $item): string {
|
||||
return json_encode($item->only(['description', 'category', 'purchase_type', 'quantity', 'unit', 'unit_price_minor',
|
||||
'tax_rate', 'equipment_id', 'spare_part_id', 'production_area', 'downtime_started_at', 'catalogue_entry_id', 'category_context']), JSON_THROW_ON_ERROR);
|
||||
})->all();
|
||||
sort($rows, SORT_STRING);
|
||||
|
||||
return $rows;
|
||||
}
|
||||
|
||||
/** @return array{matches:list<array{id:int,number:string,status:string}>,complete:bool}|null */
|
||||
public function for(User $actor, Requisition $request): ?array
|
||||
{
|
||||
if ($request->status !== 'draft' || $request->requester_id !== $actor->id || $request->tenant_id !== $actor->tenant_id
|
||||
|| ! app(OrganizationAccess::class)->canRequest($actor) || app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||
|| $request->total_minor === null || $request->needed_by === null || $request->items->isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
$source = $this->lines($request);
|
||||
$candidates = Requisition::query()->visibleTo($actor)->where('requester_id', $actor->id)->where('id', '!=', $request->id)
|
||||
->whereIn('status', ['draft', 'pending', 'approved'])->where('cost_center_id', $request->cost_center_id)
|
||||
->whereDate('needed_by', $request->needed_by->toDateString())->where('total_minor', $request->total_minor)
|
||||
->latest('id')->limit(101)->with('items')->get();
|
||||
$matches = [];
|
||||
foreach ($candidates->take(100) as $candidate) {
|
||||
if ($this->lines($candidate) === $source) {
|
||||
$matches[] = ['id' => $candidate->id, 'number' => $candidate->number, 'status' => $candidate->status];
|
||||
}
|
||||
}
|
||||
|
||||
return ['matches' => $matches, 'complete' => $candidates->count() <= 100];
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
@@ -109,8 +110,31 @@ final class RequisitionExpiry
|
||||
$deadline = $this->deadline($request);
|
||||
unset($deadline['profile_ids']);
|
||||
$history = SupplyRecord::query()->where('kind', 'req_expiration')->where('data->requisition_id', $request->id)->latest('id')->paginate(15)->withQueryString();
|
||||
$history->through(fn ($row) => ['id' => $row->id, 'data' => $row->data, 'reason' => $row->reason,
|
||||
'request' => $row->snapshot['request'], 'steps' => $row->snapshot['steps'], 'created_at' => $row->created_at]);
|
||||
$history->through(function (SupplyRecord $row) {
|
||||
$sourceItems = $row->snapshot['items'] ?? null;
|
||||
$items = null;
|
||||
if (is_array($sourceItems)) {
|
||||
$items = [];
|
||||
foreach ($sourceItems as $item) {
|
||||
if (! is_array($item)) {
|
||||
$items = null;
|
||||
break;
|
||||
}
|
||||
$items[] = Arr::only($item, ['id', 'description', 'category', 'quantity', 'unit', 'unit_price_minor', 'tax_rate', 'subtotal_minor', 'tax_minor', 'total_minor']);
|
||||
}
|
||||
}
|
||||
$rules = $row->snapshot['approval_snapshot'] ?? null;
|
||||
$basis = is_array($rules) ? ($rules['approval_basis'] ?? $row->snapshot['request']) : null;
|
||||
$basisField = is_array($rules) && is_bool($rules['approval_includes_tax'] ?? null)
|
||||
? ($rules['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor') : null;
|
||||
$approvalAmount = is_array($basis) && $basisField !== null ? ($basis[$basisField] ?? null) : null;
|
||||
|
||||
return ['id' => $row->id, 'data' => $row->data, 'reason' => $row->reason,
|
||||
'request' => $row->snapshot['request'], 'steps' => $row->snapshot['steps'], 'created_at' => $row->created_at,
|
||||
'items' => $items, 'rules' => is_array($rules) ? Arr::only($rules, ['first_limit_minor', 'second_limit_minor', 'approval_includes_tax', 'rules_provisional', 'routing_plan_revision']) : [],
|
||||
'approval_amount_minor' => is_int($approvalAmount) && $approvalAmount >= 0 ? $approvalAmount : null,
|
||||
'approval_uses_separate_basis' => is_array($rules) && is_array($rules['approval_basis'] ?? null)];
|
||||
});
|
||||
|
||||
return ['requisition' => [...$request->only(['id', 'number', 'status', 'process_version', 'requester_id']),
|
||||
'approval_cycle' => $request->getAttribute('approval_cycle') ?? 1], 'deadline' => $deadline, 'history' => $history,
|
||||
@@ -127,25 +151,44 @@ final class RequisitionExpiry
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'enabled' => 'required|boolean',
|
||||
'levels' => 'present|array|list|max:8', 'levels.*' => 'array:role,expire_minutes,reminder_minutes,escalation_minutes,profile_ids',
|
||||
'levels' => 'present|array|list|max:8', 'levels.*' => 'array:role,expire_minutes,reminder_minutes,escalation_minutes,profile_ids,urgent_expire_minutes,urgent_reminder_minutes,urgent_escalation_minutes',
|
||||
'levels.*.role' => ['required', 'distinct', Rule::in(self::ROLES)], 'levels.*.expire_minutes' => 'required|integer|min:1|max:5256000',
|
||||
'levels.*.reminder_minutes' => 'present|nullable|integer|min:1|max:5256000',
|
||||
'levels.*.escalation_minutes' => 'present|nullable|integer|min:1|max:5256000', 'levels.*.profile_ids' => 'present|array|list|max:50',
|
||||
'levels.*.profile_ids.*' => 'required|distinct|integer|min:1', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
'levels.*.profile_ids.*' => 'required|distinct|integer|min:1',
|
||||
'levels.*.urgent_expire_minutes' => 'sometimes|nullable|integer|min:1|max:5256000',
|
||||
'levels.*.urgent_reminder_minutes' => 'sometimes|nullable|integer|min:1|max:5256000',
|
||||
'levels.*.urgent_escalation_minutes' => 'sometimes|nullable|integer|min:1|max:5256000',
|
||||
'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$data['enabled'] = (bool) $data['enabled'];
|
||||
foreach ($data['levels'] as $index => &$level) {
|
||||
foreach (['expire_minutes', 'reminder_minutes', 'escalation_minutes'] as $field) {
|
||||
$level[$field] = $level[$field] === null ? null : (int) $level[$field];
|
||||
if (array_key_exists('urgent_'.$field, $level)) {
|
||||
$level['urgent_'.$field] = $level['urgent_'.$field] === null ? null : (int) $level['urgent_'.$field];
|
||||
}
|
||||
}
|
||||
$level['profile_ids'] = array_map(intval(...), $level['profile_ids']);
|
||||
sort($level['profile_ids'], SORT_NUMERIC);
|
||||
if (($level['reminder_minutes'] !== null && $level['reminder_minutes'] >= $level['expire_minutes'])
|
||||
|| ($level['escalation_minutes'] !== null && ($level['escalation_minutes'] >= $level['expire_minutes'] || $level['profile_ids'] === []))
|
||||
|| ($level['reminder_minutes'] !== null && $level['escalation_minutes'] !== null && $level['reminder_minutes'] >= $level['escalation_minutes'])
|
||||
|| ($level['escalation_minutes'] === null && $level['profile_ids'] !== [])) {
|
||||
|| ($level['escalation_minutes'] === null && ($level['urgent_escalation_minutes'] ?? null) === null && $level['profile_ids'] !== [])) {
|
||||
throw ValidationException::withMessages(['levels.'.$index => 'Configure lembrete e escalamento antes da expiração, com destinatários explícitos apenas quando houver escalamento.']);
|
||||
}
|
||||
$urgent = $level['urgent_expire_minutes'] ?? null;
|
||||
$reminder = $level['urgent_reminder_minutes'] ?? null;
|
||||
$escalation = $level['urgent_escalation_minutes'] ?? null;
|
||||
if (($urgent === null && ($reminder !== null || $escalation !== null))
|
||||
|| ($urgent !== null && ($urgent >= $level['expire_minutes']
|
||||
|| ($reminder !== null && $reminder >= $urgent)
|
||||
|| ($escalation !== null && ($escalation >= $urgent || $level['profile_ids'] === []))
|
||||
|| ($reminder !== null && $escalation !== null && $reminder >= $escalation)
|
||||
|| ($level['reminder_minutes'] !== null && ($reminder === null || $reminder >= $level['reminder_minutes']))
|
||||
|| ($level['escalation_minutes'] !== null && ($escalation === null || $escalation >= $level['escalation_minutes']))))) {
|
||||
throw ValidationException::withMessages(['levels.'.$index => 'Nas urgências, indique prazos reduzidos e conserve os alertas configurados, antes da expiração, com destinatários explícitos.']);
|
||||
}
|
||||
}
|
||||
unset($level);
|
||||
usort($data['levels'], fn ($a, $b) => strcmp($a['role'], $b['role']));
|
||||
@@ -193,7 +236,7 @@ final class RequisitionExpiry
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['id' => $source->id, 'version' => $source->version, 'data' => $source->data,
|
||||
return ['id' => $source->id, 'version' => $source->version, 'data' => $source->data, 'request_priority' => $request->priority,
|
||||
'fingerprint' => hash('sha256', json_encode($source->data, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
@@ -212,6 +255,7 @@ final class RequisitionExpiry
|
||||
$source = SupplyRecord::query()->where('kind', 'req_expiry_policy')->whereKey($policy['id'])->firstOrFail();
|
||||
abort_unless($source->version === $policy['version'] && $source->data === $policy['data']
|
||||
&& hash_equals(hash('sha256', json_encode($source->data, JSON_THROW_ON_ERROR)), $policy['fingerprint']), 409, 'A política preservada requer conferência.');
|
||||
abort_unless(! isset($policy['request_priority']) || $policy['request_priority'] === $request->priority, 409, 'A prioridade diverge da submissão preservada.');
|
||||
$steps = $request->steps()->orderBy('position')->get();
|
||||
$step = $steps->firstWhere('decision', 'pending');
|
||||
$settings = null;
|
||||
@@ -226,6 +270,13 @@ final class RequisitionExpiry
|
||||
if ($step === null || $settings === null || $request->submitted_at === null) {
|
||||
return [...$inactive, 'state' => 'unconfigured', 'step_id' => $step?->id];
|
||||
}
|
||||
$timing = 'standard';
|
||||
if (($policy['request_priority'] ?? null) === 'urgent' && ($settings['urgent_expire_minutes'] ?? null) !== null) {
|
||||
foreach (['expire_minutes', 'reminder_minutes', 'escalation_minutes'] as $field) {
|
||||
$settings[$field] = $settings['urgent_'.$field] ?? null;
|
||||
}
|
||||
$timing = 'urgent_override';
|
||||
}
|
||||
$start = CarbonImmutable::parse($request->submitted_at);
|
||||
foreach ($steps->where('position', '<', $step->position) as $previous) {
|
||||
if ($previous->decision !== 'approved' || $previous->decided_at === null) {
|
||||
@@ -242,9 +293,9 @@ final class RequisitionExpiry
|
||||
}
|
||||
$end = $start->addMinutes($settings['expire_minutes']);
|
||||
$basis = [$request->id, $request->getAttribute('approval_cycle') ?? 1, $request->getAttribute('process_version'), $step->id,
|
||||
$policy['fingerprint'], $start->toIso8601String(), $end->toIso8601String()];
|
||||
$policy['fingerprint'], $start->toIso8601String(), $end->toIso8601String(), ...($timing === 'urgent_override' ? ['urgent_override'] : [])];
|
||||
|
||||
return ['state' => now()->greaterThanOrEqualTo($end) ? 'expired' : 'running', 'step_id' => $step->id,
|
||||
return ['state' => now()->greaterThanOrEqualTo($end) ? 'expired' : 'running', 'step_id' => $step->id, 'timing' => $timing,
|
||||
'started_at' => $start->toIso8601String(), 'expires_at' => $end->toIso8601String(),
|
||||
'reminder_at' => $settings['reminder_minutes'] === null ? null : $start->addMinutes($settings['reminder_minutes'])->toIso8601String(),
|
||||
'escalation_at' => $settings['escalation_minutes'] === null ? null : $start->addMinutes($settings['escalation_minutes'])->toIso8601String(),
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Query\Builder;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/** Minimal read-only catalogue of the common ledger in this Compras database. */
|
||||
final class RequisitionLedgerAccounts
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
|
||||
return config('requisition-accounts.qa_enabled') === true && app()->environment('testing')
|
||||
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
||||
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())))
|
||||
&& Schema::hasColumns('gl_accounts', ['id', 'tenant_id', 'company_id', 'unit_id', 'code', 'label', 'currency', 'is_movement']);
|
||||
}
|
||||
|
||||
private function query(User $actor): Builder
|
||||
{
|
||||
abort_unless($this->ready(), 503, 'Plano de contas do núcleo comum indisponível nesta composição.');
|
||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
|
||||
// Standalone Compras uses its existing native company/unit zero context.
|
||||
// Only code/label/currency are exposed; ledger balances, grants and journals are never read.
|
||||
return DB::table('gl_accounts')->where(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0]);
|
||||
}
|
||||
|
||||
/** @return array{id:int,code:string,label:string,currency:string,source_hash:string} */
|
||||
private function row(\stdClass $account): array
|
||||
{
|
||||
$source = ['id' => (int) $account->id, 'tenant_id' => (int) $account->tenant_id, 'company_id' => (int) $account->company_id,
|
||||
'unit_id' => (int) $account->unit_id, 'code' => (string) $account->code, 'label' => (string) $account->label,
|
||||
'currency' => (string) $account->currency, 'is_movement' => (bool) $account->is_movement];
|
||||
|
||||
return ['id' => $source['id'], 'code' => $source['code'], 'label' => $source['label'], 'currency' => $source['currency'],
|
||||
'source_hash' => hash('sha256', json_encode($source, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function options(User $actor, string $search = ''): array
|
||||
{
|
||||
abort_unless(app(OrganizationAccess::class)->canRequest($actor), 403);
|
||||
$query = $this->query($actor)->where('is_movement', true)->where('currency', 'MZN');
|
||||
$search = trim($search);
|
||||
if ($search !== '') {
|
||||
// Literal substring search: user wildcards never widen the catalogue unexpectedly.
|
||||
$search = str_replace(['!', '%', '_'], ['!!', '!%', '!_'], $search);
|
||||
$query->where(fn ($q) => $q->whereRaw("LOWER(code) LIKE LOWER(?) ESCAPE '!'", ['%'.$search.'%'])
|
||||
->orWhereRaw("LOWER(label) LIKE LOWER(?) ESCAPE '!'", ['%'.$search.'%']));
|
||||
}
|
||||
$page = $query->orderBy('code')->orderBy('id')->paginate(20, ['*'], 'accounts_page')->withQueryString();
|
||||
$page->setCollection($page->getCollection()->map(fn ($row) => $this->row($row)));
|
||||
|
||||
return $page->toArray();
|
||||
}
|
||||
|
||||
/** Current movement account, checked again inside the host's company transaction. No account is created.
|
||||
* @return array{id:int,code:string,label:string,currency:string,source_hash:string}
|
||||
*/
|
||||
public function resolve(User $actor, int $id, string $hash): array
|
||||
{
|
||||
$account = $this->query($actor)->where('id', $id)->where('is_movement', true)->where('currency', 'MZN')->first();
|
||||
abort_unless($account !== null, 409, 'Conta indisponível no plano próprio de Compras.');
|
||||
$row = $this->row($account);
|
||||
abort_unless(hash_equals($row['source_hash'], $hash), 409, 'A conta mudou. Confira a referência actual antes de guardar.');
|
||||
|
||||
return $row;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||
use Tempo\Purchasing\Internal\RequisitionFailure;
|
||||
|
||||
/** Provisional presentation only: no reservation, authorization grant or command receipt. */
|
||||
final class RequisitionSubmissionPreview
|
||||
{
|
||||
/** @return array<string,mixed>|null */
|
||||
public function for(User $viewer, Requisition $request): ?array
|
||||
{
|
||||
if (auth()->id() !== $viewer->id) {
|
||||
return null;
|
||||
}
|
||||
$actor = User::query()->findOrFail($viewer->id);
|
||||
if ($actor->tenant_id !== $request->tenant_id || $request->requester_id !== $actor->id || $request->status !== 'draft'
|
||||
|| ! app(OrganizationAccess::class)->canRequest($actor) || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
||||
return null;
|
||||
}
|
||||
Requisition::query()->visibleTo($actor)->findOrFail($request->id);
|
||||
if ($request->getAttribute('draft_input') !== null || $request->total_minor === null || $request->subtotal_minor === null) {
|
||||
return ['state' => 'incomplete', 'message' => 'Complete e guarde o pedido antes de conferir a submissão.'];
|
||||
}
|
||||
try {
|
||||
$port = new InternalRequisitionPort($actor, static function (): never {
|
||||
throw new \LogicException('A conferência não pode gravar a requisição.');
|
||||
});
|
||||
$policy = $port->approvalPlan($request);
|
||||
$record = ['subtotal_minor' => $request->subtotal_minor, 'total_minor' => $request->total_minor,
|
||||
'has_equipment' => $request->items()->where('purchase_type', 'equipment')->exists()];
|
||||
$roles = InternalRequisitions::roles($record, $policy);
|
||||
$basis = $policy['approval_basis'] ?? $record;
|
||||
|
||||
return ['state' => 'planned', 'process_version' => $request->getAttribute('process_version'),
|
||||
'subtotal_minor' => (string) $request->subtotal_minor, 'total_minor' => (string) $request->total_minor,
|
||||
'approval_amount_minor' => (string) $basis[$policy['approval_includes_tax'] ? 'total_minor' : 'subtotal_minor'],
|
||||
'includes_tax' => $policy['approval_includes_tax'], 'provisional_rules' => $policy['rules_provisional'],
|
||||
'import_basis' => isset($policy['import_estimate']),
|
||||
'steps' => array_map(fn ($role) => ['role' => $role, 'label' => $policy['additional_levels'][$role]['name'] ?? null], $roles)];
|
||||
} catch (ValidationException $error) {
|
||||
return ['state' => 'unavailable', 'message' => collect($error->errors())->flatten()->first()];
|
||||
} catch (HttpExceptionInterface|RequisitionFailure $error) {
|
||||
$status = $error instanceof RequisitionFailure ? $error->status : $error->getStatusCode();
|
||||
if (! in_array($status, [409, 422, 503], true)) {
|
||||
throw $error;
|
||||
}
|
||||
|
||||
return ['state' => 'unavailable', 'message' => $error->getMessage()];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Posterior documentary review of a concluded cycle, never another approval or financial writer. */
|
||||
final class UrgentRequisitionReviews
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
|
||||
return config('urgent-reviews.qa_enabled') === true && app()->environment('testing')
|
||||
&& (($db->getDriverName() === 'sqlite' && $db->getDatabaseName() === ':memory:')
|
||||
|| ($db->getDriverName() === 'pgsql' && $db->getConfig('host') === '127.0.0.1'
|
||||
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
|
||||
}
|
||||
|
||||
private function actor(User $actor, bool $settings = false, bool $write = true): User
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
if ($write) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
} else {
|
||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id !== null, 403);
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->whereKey($actor->id)->firstOrFail();
|
||||
}
|
||||
abort_unless($actor->hasFunctions($settings ? ['admin'] : ['admin', 'procurement']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
public function canReview(User $actor): bool
|
||||
{
|
||||
if (! $this->ready() || auth()->id() !== $actor->id) {
|
||||
return false;
|
||||
}
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->whereKey($actor->id)->first();
|
||||
if ($actor === null || ! $actor->hasFunctions(['procurement']) || app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
||||
return false;
|
||||
}
|
||||
$policy = SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->first();
|
||||
if ($policy === null || $policy->state !== 'active') {
|
||||
return false;
|
||||
}
|
||||
$members = DB::table('organization_memberships as m')->join('organization_profiles as p', 'p.id', '=', 'm.profile_id')
|
||||
->where('m.tenant_id', $actor->tenant_id)->where('p.tenant_id', $actor->tenant_id)->where('m.user_id', $actor->id)
|
||||
->whereIn('p.id', $policy->data['profile_ids'])->where('m.maintenance', false)
|
||||
->where(fn ($q) => $q->whereNull('m.expires_at')->orWhere('m.expires_at', '>', now()));
|
||||
if (app(WorkContext::class)->enforced($actor)) {
|
||||
$members->whereJsonContains('p.work_contexts', 'procurement.internal');
|
||||
}
|
||||
|
||||
return $members->exists();
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function settings(User $actor): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor) {
|
||||
$actor = $this->actor($actor, true, false);
|
||||
|
||||
return ['current' => SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->first(),
|
||||
'history' => SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->paginate(15)->withQueryString(),
|
||||
'profiles' => DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function savePolicy(User $actor, array $input): SupplyRecord
|
||||
{
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0', 'enabled' => 'required|boolean',
|
||||
'profile_ids' => 'present|array|list|max:50', 'profile_ids.*' => 'required|integer|min:1|distinct', 'reason' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$data['enabled'] = (bool) $data['enabled'];
|
||||
$data['profile_ids'] = array_map(intval(...), $data['profile_ids']);
|
||||
sort($data['profile_ids'], SORT_NUMERIC);
|
||||
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $hash) {
|
||||
$actor = $this->actor($actor, true);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'urgent_review_policy' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
abort_unless(! $data['enabled'] || $data['profile_ids'] !== [], 422, 'Seleccione os perfis responsáveis pela revisão posterior.');
|
||||
abort_unless(DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->whereIn('id', $data['profile_ids'])->count() === count($data['profile_ids']), 422);
|
||||
$old = SupplyRecord::query()->where('kind', 'urgent_review_policy')->latest('id')->first();
|
||||
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'urgent_review_policy',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => $data['enabled'] ? 'active' : 'inactive',
|
||||
'data' => ['enabled' => $data['enabled'], 'profile_ids' => $data['profile_ids'], 'trigger' => 'final_decision_including_rejection_expiry'],
|
||||
'snapshot' => ['new_permissions' => false, 'financial_effects' => false], 'reason' => $data['reason'], 'created_by' => $actor->id,
|
||||
'created_at' => now(), 'operation_key' => $data['operation_key'], 'input_hash' => $hash]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'urgent.review_policy_saved', null, $old?->toArray(), ['record' => $record->toArray()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve the actual concluded cycle; drafts/pending work and later edited drafts are never substituted.
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
private function source(User $actor, int $id, int $cycle): array
|
||||
{
|
||||
$request = Requisition::query()->visibleTo($actor)->whereKey($id)->firstOrFail();
|
||||
$expiration = SupplyRecord::query()->where('kind', 'req_expiration')->where('data->requisition_id', $id)->where('data->cycle', $cycle)->first();
|
||||
if ($expiration !== null) {
|
||||
$header = $expiration->snapshot['request'] ?? null;
|
||||
abort_unless(is_array($header) && is_array($expiration->snapshot['items'] ?? null) && is_array($expiration->snapshot['steps'] ?? null), 409,
|
||||
'O ciclo expirado exige conferência dos dados preservados.');
|
||||
abort_unless(($header['priority'] ?? null) === 'urgent', 404);
|
||||
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $id)
|
||||
->where('action', 'requisition.expired_returned')->where('after->expiration_record_id', $expiration->id)->first();
|
||||
abort_unless($audit !== null && is_string($audit->before) && json_decode($audit->before, true, 64, JSON_THROW_ON_ERROR) === $header, 409, 'A expiração exige conferência da sua origem auditada.');
|
||||
$source = ['kind' => 'expiry', 'id' => $expiration->id, 'outcome' => 'expired', 'closed_at' => (string) $expiration->created_at,
|
||||
'request' => $header, 'items' => $expiration->snapshot['items'], 'steps' => $expiration->snapshot['steps']];
|
||||
} else {
|
||||
abort_unless($request->priority === 'urgent' && in_array($request->status, ['approved', 'rejected'], true)
|
||||
&& (int) ($request->getAttribute('approval_cycle') ?? 1) === $cycle, 409, 'O ciclo ainda não tem uma decisão final disponível para revisão.');
|
||||
$steps = $request->steps()->get();
|
||||
abort_unless($steps->isNotEmpty() && ($request->status !== 'approved' || $steps->every(fn ($step) => $step->decision === 'approved')), 409,
|
||||
'As etapas preservadas não demonstram a conclusão da aprovação.');
|
||||
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $id)
|
||||
->where('action', 'approval.'.$request->status)->where('after->status', $request->status)->whereIn('after->step_id', $steps->modelKeys())->latest('id')->first();
|
||||
abort_unless($audit !== null, 409, 'A decisão final exige conferência da sua origem auditada.');
|
||||
$decision = json_decode($audit->after, true, 64, JSON_THROW_ON_ERROR);
|
||||
abort_unless($steps->where('id', $decision['step_id'])->where('decision', $request->status)->isNotEmpty(), 409);
|
||||
$source = ['kind' => 'decision', 'id' => $audit->id, 'outcome' => $request->status, 'closed_at' => $audit->created_at,
|
||||
'request' => $request->only(['id', 'number', 'requester_id', 'department_id', 'cost_center_id', 'priority', 'needed_by', 'justification', 'subtotal_minor', 'tax_minor', 'total_minor']),
|
||||
'items' => $request->items()->orderBy('id')->get()->toArray(), 'steps' => $steps->toArray()];
|
||||
}
|
||||
abort_unless($source['items'] !== [] && $source['steps'] !== [], 409, 'O ciclo concluído exige conferência das linhas e etapas conservadas.');
|
||||
foreach ($source['steps'] as $step) {
|
||||
abort_unless(is_array($step) && isset($step['id'], $step['role'], $step['decision']), 409, 'As etapas conservadas exigem conferência.');
|
||||
}
|
||||
foreach (['subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
|
||||
$source['request'][$field] = isset($source['request'][$field]) ? (string) $source['request'][$field] : null;
|
||||
}
|
||||
foreach ($source['items'] as &$item) {
|
||||
abort_unless(is_array($item) && isset($item['id'], $item['description'], $item['quantity'], $item['unit']), 409,
|
||||
'As linhas conservadas exigem conferência antes da revisão.');
|
||||
foreach (['unit_price_minor', 'subtotal_minor', 'tax_minor', 'total_minor'] as $field) {
|
||||
$item[$field] = isset($item[$field]) ? (string) $item[$field] : null;
|
||||
}
|
||||
}
|
||||
unset($item);
|
||||
$source['cycle'] = $cycle;
|
||||
$source['fingerprint'] = hash('sha256', json_encode($source, JSON_THROW_ON_ERROR));
|
||||
|
||||
return $source;
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, int $id, int $cycle): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $id, $cycle) {
|
||||
$actor = $this->actor($actor, false, false);
|
||||
$source = $this->source($actor, $id, $cycle);
|
||||
$current = $this->current($id, $cycle);
|
||||
$audited = $current === null || $this->audited($current);
|
||||
$verified = $audited && ($current === null || ($current->snapshot['fingerprint'] ?? null) === $source['fingerprint']);
|
||||
|
||||
return ['source' => $source, 'current' => $current, 'currentVerified' => $verified,
|
||||
'canReview' => $this->canReview($actor) && $audited,
|
||||
'history' => SupplyRecord::query()->where('kind', 'urgent_review')->where('data->requisition_id', $id)->where('data->cycle', $cycle)
|
||||
->latest('id')->paginate(15)->withQueryString(), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function queue(User $actor, ?int $page = 1, string $state = 'pending'): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $page, $state) {
|
||||
$actor = $this->actor($actor, false, false);
|
||||
$candidates = [];
|
||||
foreach (Requisition::query()->visibleTo($actor)->where('priority', 'urgent')->whereIn('status', ['approved', 'rejected'])->lazyById(100) as $request) {
|
||||
$cycle = (int) ($request->getAttribute('approval_cycle') ?? 1);
|
||||
$candidates[$request->id.':'.$cycle] = ['request_id' => $request->id, 'cycle' => $cycle, 'number' => $request->number,
|
||||
'outcome' => $request->status];
|
||||
}
|
||||
foreach (SupplyRecord::query()->where('kind', 'req_expiration')->where('snapshot->request->priority', 'urgent')->lazyById(100) as $expiration) {
|
||||
$id = (int) $expiration->data['requisition_id'];
|
||||
$visible = Requisition::query()->visibleTo($actor)->whereKey($id)->first(['id', 'number']);
|
||||
if ($visible === null) {
|
||||
continue;
|
||||
}
|
||||
$cycle = (int) $expiration->data['cycle'];
|
||||
$candidates[$id.':'.$cycle] = ['request_id' => $id, 'cycle' => $cycle, 'number' => $expiration->snapshot['request']['number'] ?? $visible->number,
|
||||
'outcome' => 'expired'];
|
||||
}
|
||||
$coverage = ['pending' => 0, 'reviewed' => 0, 'indeterminate' => 0];
|
||||
$rows = [];
|
||||
foreach ($candidates as $key => $candidate) {
|
||||
$status = 'indeterminate';
|
||||
$closed = null;
|
||||
try {
|
||||
$source = $this->source($actor, $candidate['request_id'], $candidate['cycle']);
|
||||
$closed = $source['closed_at'];
|
||||
$review = $this->current($candidate['request_id'], $candidate['cycle']);
|
||||
$status = $review === null ? 'pending' : ($this->audited($review) && ($review->snapshot['fingerprint'] ?? null) === $source['fingerprint'] ? 'reviewed' : 'indeterminate');
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
if ($error->getStatusCode() !== 409) {
|
||||
throw $error;
|
||||
}
|
||||
}
|
||||
$coverage[$status]++;
|
||||
if ($state === 'all' || $state === $status) {
|
||||
$rows[] = [...$candidate, 'key' => $key, 'status' => $status, 'closed_at' => $closed,
|
||||
'href' => $status === 'indeterminate' ? '/requisicoes/'.$candidate['request_id']
|
||||
: '/requisicoes/'.$candidate['request_id'].'/ciclos/'.$candidate['cycle'].'/revisao-urgencia'];
|
||||
}
|
||||
}
|
||||
usort($rows, fn ($a, $b) => strcmp($a['closed_at'] ?? '', $b['closed_at'] ?? '') ?: strcmp($a['key'], $b['key']));
|
||||
$last = max(1, (int) ceil(count($rows) / 20));
|
||||
$current = $page === null ? 1 : max(1, min($last, $page));
|
||||
|
||||
return ['coverage' => $coverage, 'state' => $state, 'canReview' => $this->canReview($actor),
|
||||
'canConfigure' => $actor->hasFunctions(['admin']), 'records' => ['data' => $page === null ? $rows : array_slice($rows, ($current - 1) * 20, 20),
|
||||
'total' => count($rows), 'current_page' => $current, 'last_page' => $last]];
|
||||
});
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function tasks(User $actor): array
|
||||
{
|
||||
if (! $this->canReview($actor)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_values(array_map(fn ($row) => ['id' => 'urgent-review:'.$row['key'], 'module' => 'purchases', 'reference' => $row['number'],
|
||||
'label' => 'Revisão posterior de urgência · ciclo '.$row['cycle'], 'task' => 'urgent_requisition_review', 'status' => 'pending',
|
||||
'blocked' => false, 'created_at' => $row['closed_at'], 'due_on' => null, 'href' => $row['href']], $this->queue($actor, null)['records']['data']));
|
||||
}
|
||||
|
||||
private function current(int $id, int $cycle): ?SupplyRecord
|
||||
{
|
||||
return SupplyRecord::query()->where('kind', 'urgent_review')->where('data->requisition_id', $id)->where('data->cycle', $cycle)->latest('version')->first();
|
||||
}
|
||||
|
||||
private function audited(SupplyRecord $record): bool
|
||||
{
|
||||
$audit = DB::table('audit_logs')->where('tenant_id', $record->tenant_id)->where('requisition_id', $record->data['requisition_id'])
|
||||
->where('action', 'urgent.review_recorded')->where('user_id', $record->created_by)->where('after->record->id', $record->id)->first();
|
||||
$saved = $audit === null || ! is_string($audit->after) ? null : json_decode($audit->after, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null;
|
||||
|
||||
return is_array($saved) && ($saved['data'] ?? null) === $record->data && ($saved['snapshot'] ?? null) === $record->snapshot
|
||||
&& ($saved['version'] ?? null) === $record->version && ($saved['input_hash'] ?? null) === $record->input_hash;
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function review(User $actor, int $id, int $cycle, array $input): SupplyRecord
|
||||
{
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
|
||||
'source_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'notes' => 'required|string|min:10|max:4000'])->validate();
|
||||
$data['operation_key'] = strtolower($data['operation_key']);
|
||||
$hash = hash('sha256', json_encode([$id, $cycle, $data], JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $id, $cycle, $data, $hash) {
|
||||
$actor = $this->actor($actor);
|
||||
abort_unless($this->canReview($actor), 403, 'A revisão exige o perfil designado e a função de Compras actualmente válidos.');
|
||||
$source = $this->source($actor, $id, $cycle);
|
||||
$request = Requisition::query()->whereKey($id)->firstOrFail();
|
||||
app(ConflictGuard::class)->assertParticipation($actor, $request);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'urgent_review' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
abort_unless(hash_equals($source['fingerprint'], $data['source_hash']), 409, 'A origem mudou. Confira o ciclo concluído antes de registar a revisão.');
|
||||
$old = $this->current($id, $cycle);
|
||||
abort_unless($old === null || $this->audited($old), 409, 'A revisão anterior exige conferência da sua origem auditada.');
|
||||
abort_unless((int) $data['version'] === ($old->version ?? 0), 409);
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'urgent_review',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => 'reviewed',
|
||||
'data' => ['requisition_id' => $id, 'cycle' => $cycle, 'outcome' => $source['outcome'], 'notes' => trim($data['notes'])],
|
||||
'snapshot' => $source, 'reason' => trim($data['notes']), 'created_by' => $actor->id, 'created_at' => now(),
|
||||
'operation_key' => $data['operation_key'], 'input_hash' => $hash]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'urgent.review_recorded', $request, $old?->toArray(), ['record' => $record->toArray()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -51,7 +51,10 @@ class WarehouseWorkdesk
|
||||
$query = WarehouseRequest::query();
|
||||
if (! $actor->hasFunctions(['admin', 'warehouse_request_read']) && ! ($actor->hasFunctions(['warehouse_request_deliver']) && $actor->hasFunctions(['warehouse']))) {
|
||||
$query->where(function ($q) use ($actor) {
|
||||
$q->where('created_by', $actor->id);
|
||||
$q->whereRaw('1 = 0');
|
||||
if ($actor->hasFunctions(['warehouse_request_prepare'])) {
|
||||
$q->orWhere('created_by', $actor->id);
|
||||
}
|
||||
if ($actor->hasFunctions(['warehouse_request_review']) && $actor->department_id !== null) {
|
||||
$q->orWhere('snapshot->requester->department_id', $actor->department_id);
|
||||
}
|
||||
|
||||
@@ -67,6 +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, ...app(UrgentRequisitionReviews::class)->tasks($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) {
|
||||
|
||||
Reference in New Issue
Block a user