@@ -22,7 +22,7 @@ class BudgetWorkflow
|
||||
}
|
||||
$adapter = app(CommonBudget::class);
|
||||
|
||||
return $adapter->execute(fn () => $adapter->for($user)->record(
|
||||
return $adapter->execute(fn () => $adapter->for($user, RequisitionExpiry::cycles($request))->record(
|
||||
$request->id, $request->cost_center_id,
|
||||
$request->items()->where('purchase_type', 'equipment')->exists() ? 'investment' : 'operating',
|
||||
$kind, $amount, $subtotal,
|
||||
|
||||
@@ -10,6 +10,7 @@ use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/** Explicit documentary destination per line. Budget allocations retain their native authority. */
|
||||
final class CapitalAssignments
|
||||
@@ -31,15 +32,17 @@ final class CapitalAssignments
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $request) {
|
||||
[$actor, $request] = $this->context($actor, $request);
|
||||
$canWrite = $request->status === 'draft' && $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor)
|
||||
&& ! app(ConflictGuard::class)->participationBlocked($actor, $request);
|
||||
|
||||
return ['requisition' => $request->only(['id', 'number', 'status']), 'items' => $request->items()->orderBy('id')->get(['id', 'description']),
|
||||
'current' => app(SupplyPlanning::class)->latest('capital_assignment')->where('data->requisition_id', $request->id)->get(),
|
||||
'choices' => app(SupplyPlanning::class)->latest('capital_register')->where('state', 'active')->where('data->department_id', $request->department_id)
|
||||
->when(! $canWrite, fn ($q) => $q->whereRaw('1 = 0'))
|
||||
->orderBy('data->code')->paginate(15, ['id', 'version', 'data'], 'choices_page')->withQueryString(),
|
||||
'history' => SupplyRecord::query()->where('kind', 'capital_assignment')->where('data->requisition_id', $request->id)
|
||||
->latest('id')->paginate(15, ['*'], 'history_page')->withQueryString(),
|
||||
'canWrite' => $request->status === 'draft' && $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor)
|
||||
&& ! app(ConflictGuard::class)->participationBlocked($actor, $request),
|
||||
'canWrite' => $canWrite,
|
||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
@@ -86,6 +89,24 @@ final class CapitalAssignments
|
||||
return $item->only(['id', 'description', 'unit', 'quantity', 'purchase_type', 'equipment_id', 'category_context']);
|
||||
}
|
||||
|
||||
public function assertSubmission(User $actor, Requisition $request): void
|
||||
{
|
||||
$items = $request->items()->orderBy('id')->get();
|
||||
$itemIds = [];
|
||||
foreach ($items as $item) {
|
||||
$itemIds[] = $item->id;
|
||||
}
|
||||
$frozen = $this->freezeForItems($actor, $itemIds);
|
||||
if (! app(CapitalRegister::class)->ready()) {
|
||||
return;
|
||||
}
|
||||
foreach ($items as $item) {
|
||||
if (($item->category_context['category'] ?? null) === 'capital_equipment' && ! isset($frozen[$item->id])) {
|
||||
throw ValidationException::withMessages(['capital_assignment' => 'Maquinaria: ligue cada artigo ao projecto ou imobilizado no cadastro de Compras antes de submeter. Não foram criadas reservas ou aprovações.']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Preserve accepted choices even after a later rename/archive. New choices require a current active source.
|
||||
* @param list<int> $itemIds
|
||||
* @return array<int,array<string,mixed>>
|
||||
|
||||
@@ -25,6 +25,7 @@ final class CapitalTrace
|
||||
} else {
|
||||
abort(503, 'A consulta de origens requer um motor verificado.');
|
||||
}
|
||||
|
||||
return $query;
|
||||
}
|
||||
|
||||
@@ -42,6 +43,7 @@ final class CapitalTrace
|
||||
$documents = GoodsReceipt::query()->whereIn('id', $receipts->getCollection()->pluck('goods_receipt_id'))->get()->keyBy('id');
|
||||
$receipts->through(function (GoodsReceiptItem $item) use ($documents) {
|
||||
$document = $documents->get($item->goods_receipt_id);
|
||||
|
||||
return ['id' => $item->id, 'description' => $item->snapshot['order_item']['description'] ?? null, 'unit' => $item->snapshot['order_item']['unit'] ?? null,
|
||||
'receipt_id' => $item->goods_receipt_id, 'order_id' => $document?->purchase_order_id,
|
||||
'received_on' => $document?->received_on->toDateString(), 'quality_status' => $item->quality_status,
|
||||
@@ -49,6 +51,7 @@ final class CapitalTrace
|
||||
'reversed' => app(InventoryReversals::class)->receiptReversed($item->id),
|
||||
'returned_quantity' => (string) BigDecimal::of(app(InventoryDispositions::class)->returnedForReceipt($item->id))->dividedBy(1000, 3)];
|
||||
});
|
||||
|
||||
return ['orders' => $orders, 'receipts' => $receipts];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,10 +23,19 @@ final class CommonBudget
|
||||
|
||||
public const IMPORT_ESTIMATE_CONTRACT = 'COMMON-BUDGET-IMPORT-ESTIMATE-QA-v1';
|
||||
|
||||
public function for(User $user): BudgetControl
|
||||
public const REQUISITION_CYCLES_CONTRACT = 'COMMON-BUDGET-REQUISITION-CYCLES-QA-v1';
|
||||
|
||||
/** @param array<int,int> $cycles */
|
||||
public function for(User $user, array $cycles = []): BudgetControl
|
||||
{
|
||||
abort_unless(auth()->id() === $user->id && $user->tenant_id !== null, 403);
|
||||
$runtime = new \ReflectionClass(BudgetControl::class);
|
||||
$cycleRuntime = $runtime->hasConstant('REQUISITION_CYCLES_VERSION') && $runtime->getConstant('REQUISITION_CYCLES_VERSION') === self::REQUISITION_CYCLES_CONTRACT;
|
||||
if (! $cycleRuntime) {
|
||||
abort_if(($cycles !== [] && max($cycles) > 1) || (Schema::hasTable('budget_requisition_cycles')
|
||||
&& DB::table('budget_requisition_cycles')->where('tenant_id', $user->tenant_id)->where('cycle', '>', 1)->exists()), 503,
|
||||
'Existem novos ciclos de requisição. Preserve o núcleo compatível antes de operar ou consultar saldos.');
|
||||
}
|
||||
$landedTables = ['budget_landed_commands', 'budget_landed_entries'];
|
||||
$landedPresent = array_values(array_filter($landedTables, fn ($table) => Schema::hasTable($table)));
|
||||
abort_if(count($landedPresent) !== 0 && count($landedPresent) !== count($landedTables), 503, 'Estrutura de aterragem incompleta; saldo não presumido.');
|
||||
@@ -64,7 +73,8 @@ final class CommonBudget
|
||||
}
|
||||
}
|
||||
abort_unless(DB::table('tenants')->where('id', $user->tenant_id)->value('currency') === 'MZN', 422, 'Controlo comum desta entrega suporta apenas MZN; câmbio permanece pendente.');
|
||||
$context = new BudgetContext($user->id, ['tenant_id' => (int) $user->tenant_id], (int) now()->year, 'MZN');
|
||||
$context = $cycleRuntime ? (new \ReflectionClass(BudgetContext::class))->newInstanceArgs([$user->id, ['tenant_id' => (int) $user->tenant_id], (int) now()->year, 'MZN', $cycles])
|
||||
: new BudgetContext($user->id, ['tenant_id' => (int) $user->tenant_id], (int) now()->year, 'MZN');
|
||||
|
||||
return new BudgetControl(DB::connection(), $context, '',
|
||||
function (string $action) use ($user): void {
|
||||
|
||||
@@ -34,7 +34,12 @@ final class ImportEstimates
|
||||
return null;
|
||||
}
|
||||
|
||||
return SupplyRecord::query()->where('kind', 'import_estimate')->where('data->requisition_id', $request->id)->latest('version')->first();
|
||||
$cycle = (int) ($request->getAttribute('approval_cycle') ?? 1);
|
||||
|
||||
return SupplyRecord::query()->where('kind', 'import_estimate')->where('data->requisition_id', $request->id)
|
||||
->when($cycle > 1, fn ($q) => $q->where('data->requisition_cycle', $cycle),
|
||||
fn ($q) => $q->where(fn ($first) => $first->whereNull('data->requisition_cycle')->orWhere('data->requisition_cycle', 1)))
|
||||
->latest('version')->first();
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
@@ -95,7 +100,7 @@ final class ImportEstimates
|
||||
$record = $this->current($request);
|
||||
abort_unless($record !== null, 409);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$engine = $adapter->for($actor, RequisitionExpiry::cycles($request));
|
||||
abort_unless(in_array('reserveImportEstimate', get_class_methods($engine), true), 503, 'Motor sem reserva pré-documental.');
|
||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'reserveImportEstimate'))->invoke($engine, $record->record_key, $record->version, $record->data['budget_id'],
|
||||
$request->id, $record->snapshot['plan']['goods'], $record->data['components'], $record->operation_key));
|
||||
@@ -110,7 +115,7 @@ final class ImportEstimates
|
||||
}
|
||||
abort_unless($this->ready(), 503, 'Preserve o motor das estimativas reservadas.');
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$engine = $adapter->for($actor, RequisitionExpiry::cycles($request));
|
||||
abort_unless(in_array('releaseImportEstimate', get_class_methods($engine), true), 503);
|
||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'releaseImportEstimate'))->invoke($engine, $estimate['record_key'], $estimate['version'],
|
||||
$estimate['plan']['fingerprint'], (string) Str::uuid()));
|
||||
@@ -267,7 +272,8 @@ final class ImportEstimates
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'import_estimate',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => $plan['complete'] ? 'prepared' : 'incomplete', 'created_by' => $actor->id,
|
||||
'data' => ['requisition_id' => $request->id, 'budget_id' => $budget->id, 'components' => $data['components']],
|
||||
'data' => ['requisition_id' => $request->id, 'budget_id' => $budget->id, 'components' => $data['components'],
|
||||
...((int) ($request->getAttribute('approval_cycle') ?? 1) > 1 ? ['requisition_cycle' => $request->getAttribute('approval_cycle')] : [])],
|
||||
'snapshot' => ['native' => $native, 'plan' => $plan, 'budget' => $budget->only(['id', 'cost_center_id', 'year', 'kind', 'includes_tax']), 'legal_sources' => $legalSources],
|
||||
'reason' => $data['reason'], 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'import.estimate_prepared', $request, null,
|
||||
|
||||
@@ -9,9 +9,9 @@ use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Purchasing\Internal\RequisitionPort;
|
||||
use Tempo\Purchasing\Internal\ExpiryRequisitionPort;
|
||||
|
||||
final class InternalRequisitionPort implements RequisitionPort
|
||||
final class InternalRequisitionPort implements ExpiryRequisitionPort
|
||||
{
|
||||
/** @param \Closure(array<string,mixed>,?Requisition):Requisition $save */
|
||||
public function __construct(private User $actor, private \Closure $save, private ?SupplyRecord $automaticRule = null) {}
|
||||
@@ -57,6 +57,9 @@ final class InternalRequisitionPort implements RequisitionPort
|
||||
}
|
||||
if ($record !== null) {
|
||||
$r = $this->model($record['id']);
|
||||
if ($action !== 'view') {
|
||||
app(RequisitionExpiry::class)->assertOperational($r);
|
||||
}
|
||||
if ($action === 'view') {
|
||||
Requisition::query()->visibleTo($this->actor)->findOrFail($record['id']);
|
||||
}
|
||||
@@ -74,6 +77,9 @@ final class InternalRequisitionPort implements RequisitionPort
|
||||
}
|
||||
} elseif ($action === 'decide') {
|
||||
abort_unless($this->actor->hasFunctions(['department_head', 'procurement', 'finance', 'requisition_approve']), 403);
|
||||
} elseif ($action === 'expire') {
|
||||
abort_unless($record !== null, 404);
|
||||
Requisition::query()->visibleTo($this->actor)->whereKey($record['id'])->firstOrFail();
|
||||
} elseif (str_starts_with($action, 'step:')) {
|
||||
$role = substr($action, 5);
|
||||
if (str_starts_with($role, 'configured_')) {
|
||||
@@ -118,6 +124,7 @@ final class InternalRequisitionPort implements RequisitionPort
|
||||
foreach ($r->items()->get() as $item) {
|
||||
app(EquipmentWorkflow::class)->line($item->toArray(), $r->department_id, $r->priority);
|
||||
}
|
||||
app(CapitalAssignments::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.']);
|
||||
@@ -127,8 +134,10 @@ final class InternalRequisitionPort implements RequisitionPort
|
||||
$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'];
|
||||
$expiry = app(RequisitionExpiry::class)->policy($r);
|
||||
|
||||
return [...$base, ...app(RequisitionApprovalLevels::class)->policy($r, $amount),
|
||||
...($expiry === null ? [] : ['approval_expiry' => $expiry]),
|
||||
...($estimate === null ? [] : ['import_estimate' => $estimate, 'approval_basis' => $basis])];
|
||||
}
|
||||
|
||||
@@ -141,12 +150,40 @@ final class InternalRequisitionPort implements RequisitionPort
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function prepareCycle(array $record, array $policy, ?string $operation): void
|
||||
{
|
||||
app(RequisitionExpiry::class)->begin($this->actor, $this->model($record['id']), $policy, $operation);
|
||||
}
|
||||
|
||||
public function assertDecisionTimely(array $record): void
|
||||
{
|
||||
abort_if(app(RequisitionExpiry::class)->deadline($this->model($record['id']))['state'] === 'expired', 409,
|
||||
'O prazo desta etapa terminou. Confirme a devolução por expiração antes de uma nova submissão.');
|
||||
}
|
||||
|
||||
public function expiration(array $record, array $input): array
|
||||
{
|
||||
return app(RequisitionExpiry::class)->proof($this->actor, $this->model($record['id']), $input);
|
||||
}
|
||||
|
||||
public function expired(array $record, array $proof): array
|
||||
{
|
||||
$request = $this->model($record['id']);
|
||||
app(RequisitionExpiry::class)->returned($this->actor, $request, $proof);
|
||||
|
||||
return $this->snapshot($request);
|
||||
}
|
||||
|
||||
public function submitted(array $record, array $policy, array $roles): array
|
||||
{
|
||||
$r = $this->model($record['id']);
|
||||
foreach ($roles as $position => $role) {
|
||||
$r->steps()->create(['tenant_id' => $this->actor->tenant_id, 'position' => $position + 1, 'role' => $role,
|
||||
$step = $r->steps()->make(['tenant_id' => $this->actor->tenant_id, 'position' => $position + 1, 'role' => $role,
|
||||
...(isset($policy['additional_levels'][$role]) ? ['routing' => $policy['additional_levels'][$role]] : [])]);
|
||||
if (Schema::hasColumn('approval_steps', 'approval_cycle')) {
|
||||
$step->setAttribute('approval_cycle', $r->getAttribute('approval_cycle') ?? 1);
|
||||
}
|
||||
$step->save();
|
||||
}
|
||||
$values = ['status' => 'pending', 'submitted_at' => now(), 'approval_snapshot' => $policy];
|
||||
if (Schema::hasColumn('requisitions', 'process_version')) {
|
||||
|
||||
@@ -58,7 +58,7 @@ class InvoiceBudgetDistributions
|
||||
if (array_sum(array_column($lines, 'subtotal_minor')) !== $reference['subtotal_minor'] || array_sum(array_column($lines, 'total_minor')) !== $reference['total_minor']) {
|
||||
throw ValidationException::withMessages(['allocations' => 'As parcelas em MZN devem reconciliar exactamente com a referência nativa desta factura parcial.']);
|
||||
}
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
$engine = app(CommonBudget::class)->for($actor, RequisitionExpiry::cycles($request));
|
||||
$check = new \ReflectionMethod($engine, 'checkDistributionConsumption');
|
||||
app(CommonBudget::class)->execute(fn () => $check->invoke($engine, $order->requisition_id, $allocations, $lines));
|
||||
|
||||
@@ -95,7 +95,8 @@ class InvoiceBudgetDistributions
|
||||
if (! is_array($plan) || $plan['revision'] !== $this->revision($invoice, $order) || $plan['reference'] !== $reference) {
|
||||
throw ValidationException::withMessages(['allocations' => 'Distribuição da factura ausente ou desactualizada; não foi usado o contrato de centro único.']);
|
||||
}
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
$request = Requisition::query()->whereKey($order->requisition_id)->firstOrFail();
|
||||
$engine = app(CommonBudget::class)->for($actor, RequisitionExpiry::cycles($request));
|
||||
$method = new \ReflectionMethod($engine, 'consumeDistribution');
|
||||
$result = app(CommonBudget::class)->execute(fn () => $method->invoke($engine, $order->requisition_id, $invoice->id,
|
||||
$plan['allocations'], $plan['lines'], $plan['revision'], $plan['operation_key']));
|
||||
|
||||
@@ -176,7 +176,7 @@ class InvoiceWorkflow
|
||||
$reference = app(QuotationExchange::class)->invoiceAmounts($order, $invoice);
|
||||
$effect = app(RequisitionBudgetDistributions::class)->applies($request)
|
||||
? app(InvoiceBudgetDistributions::class)->consume($user, $invoice, $order, $reference)
|
||||
: $adapter->execute(fn () => $adapter->for($user)->consume($request->id, $invoice->id, $reference['total_minor'], $reference['subtotal_minor']));
|
||||
: $adapter->execute(fn () => $adapter->for($user, RequisitionExpiry::cycles($request))->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,
|
||||
...($order->currency === 'MZN' ? [] : ['reference_amounts' => $reference, 'exchange_basis' => $order->snapshot['exchange_basis']])] + $effect);
|
||||
|
||||
@@ -236,7 +236,7 @@ class OrderCancellationWorkflow
|
||||
}
|
||||
unset($source);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$engine = $adapter->for($actor, RequisitionExpiry::orderCycles($order));
|
||||
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'cancelOrderParts'))->invoke($engine, $order->getAttribute('order_key'), $sources, $record->operation_key));
|
||||
if (! is_array($result)) {
|
||||
throw new \LogicException('Resposta incompatível da reversão por parcelas.');
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace App\Services;
|
||||
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -23,7 +24,8 @@ final class OrderPartsAmendments
|
||||
$sources = [];
|
||||
foreach ($order->snapshot['order_parts']['budget_sources'] as $original) {
|
||||
$origin = $original['origin'];
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $origin)->first();
|
||||
$originRequest = Requisition::query()->whereKey($origin)->firstOrFail();
|
||||
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest);
|
||||
abort_unless($distribution !== null && $distribution->phase === 'orders', 409);
|
||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$frozen = array_column($snapshot['allocations'], null, 'allocation_key');
|
||||
@@ -70,7 +72,7 @@ final class OrderPartsAmendments
|
||||
'subtotal_minor' => BigDecimal::of($row['subtotal'])->multipliedBy(100)->toInt(),
|
||||
'total_minor' => BigDecimal::of($row['total'])->multipliedBy(100)->toInt()], $source['allocations'])], $data['sources']);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$engine = $adapter->for($actor, RequisitionExpiry::orderCycles($order));
|
||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'amendOrderParts'))->invoke($engine,
|
||||
$order->getAttribute('order_key'), $sources, $data['reason'], strtolower($data['operation_key'])));
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Services;
|
||||
use App\Enums\PurchasingRole;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -25,7 +26,8 @@ final class OrderPartsInvoices
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||
$rows = [];
|
||||
foreach ($order->snapshot['order_parts']['sources'] as $source) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->first();
|
||||
$originRequest = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest);
|
||||
abort_unless($distribution !== null, 503);
|
||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$nativeLines = array_column($source['items'], null, 'requisition_item_id');
|
||||
@@ -82,7 +84,7 @@ final class OrderPartsInvoices
|
||||
usort($rows, fn ($a, $b) => [$a['origin'], $a['allocation_key']] <=> [$b['origin'], $b['allocation_key']]);
|
||||
$sources = $this->bindings($actor, $order, $rows, $nativeLines);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$engine = $adapter->for($actor, RequisitionExpiry::orderCycles($order));
|
||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'checkOrderPartsConsumption'))->invoke($engine, $sources));
|
||||
|
||||
return ['allocations' => $rows, 'source_versions_at_preparation' => array_column($sources, 'version', 'origin'),
|
||||
@@ -121,7 +123,8 @@ final class OrderPartsInvoices
|
||||
throw ValidationException::withMessages(['order_part_allocations' => 'Origem fora desta ordem.']);
|
||||
}
|
||||
if (! isset($sources[$row['origin']])) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $row['origin'])->lockForUpdate()->first();
|
||||
$originRequest = Requisition::query()->whereKey($row['origin'])->firstOrFail();
|
||||
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest, true);
|
||||
abort_unless($distribution !== null, 503, 'Preserve a distribuição da origem.');
|
||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$sources[$row['origin']] = ['origin' => $row['origin'], 'version' => DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count(),
|
||||
@@ -187,7 +190,7 @@ final class OrderPartsInvoices
|
||||
}
|
||||
$sources = $this->bindings($actor, $order, $plan['allocations'], $lines);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$engine = $adapter->for($actor, RequisitionExpiry::orderCycles($order));
|
||||
$result = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'consumeOrderParts'))->invoke($engine, $invoice->id, $sources, $plan['operation_key']));
|
||||
if (! is_array($result)) {
|
||||
throw new \LogicException('Resposta incompatível do consumo por origem.');
|
||||
|
||||
@@ -31,7 +31,8 @@ final class OrderPartsWorkflow
|
||||
$prepared = app(OrderPartsPreparation::class)->prepare($actor, $selection);
|
||||
$financial = [];
|
||||
foreach ($prepared['sources'] as $source) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first();
|
||||
$originRequest = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest, true);
|
||||
if ($distribution === null) {
|
||||
$adoptionLines = Quotation::query()->whereKey($source['quotation_id'])->firstOrFail()->items()->orderBy('id')->get()
|
||||
->map(fn ($line) => ['line_id' => $line->requisition_item_id, 'description' => $line->description,
|
||||
@@ -111,7 +112,7 @@ final class OrderPartsWorkflow
|
||||
}
|
||||
$revision = hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR));
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$engine = $adapter->for($actor, RequisitionExpiry::cycles($request));
|
||||
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'adoptOrderSource'))->invoke($engine, $request->id,
|
||||
$allocations, $lines, $revision, strtolower($operation)));
|
||||
});
|
||||
@@ -234,7 +235,7 @@ final class OrderPartsWorkflow
|
||||
$limits = app(AgreementOrderLimits::class)->freeze($actor, $firstQuote, $requests[0], $lines,
|
||||
$data['agreement_bindings'] ?? [], array_slice($requests, 1));
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$engine = $adapter->for($actor, RequisitionExpiry::origins(array_column($prepared['sources'], 'requisition_id')));
|
||||
$commit = $adapter->execute(fn () => (new \ReflectionMethod($engine, 'commitOrderParts'))->invoke($engine,
|
||||
$orderKey, $budgetSources, strtolower($data['operation_key'])));
|
||||
$foreign = $prepared['currency'] !== 'MZN';
|
||||
@@ -291,7 +292,8 @@ final class OrderPartsWorkflow
|
||||
}
|
||||
$byOrigin = array_column($financial, null, 'origin');
|
||||
foreach ($sources as $source) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['requisition_id'])->lockForUpdate()->first();
|
||||
$originRequest = Requisition::query()->whereKey($source['requisition_id'])->firstOrFail();
|
||||
$distribution = app(RequisitionBudgetDistributions::class)->source($originRequest, true);
|
||||
abort_unless($distribution !== null, 422, 'Prepare a distribuição ou a adopção explícita da reserva antes de emitir parcelas.');
|
||||
$snapshot = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$frozen = array_column($snapshot['allocations'], null, 'allocation_key');
|
||||
|
||||
@@ -57,7 +57,14 @@ class RequisitionBudgetDistributions
|
||||
public function applies(Requisition $request): bool
|
||||
{
|
||||
return $request->getAttribute('budget_distribution_preparation') !== null
|
||||
|| (Schema::hasTable('budget_distributions') && DB::table('budget_distributions')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)->exists());
|
||||
|| (Schema::hasTable('budget_distributions') && $this->source($request) !== null);
|
||||
}
|
||||
|
||||
public function source(Requisition $request, bool $lock = false): ?\stdClass
|
||||
{
|
||||
return DB::table('budget_distributions')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)
|
||||
->when(Schema::hasColumn('budget_distributions', 'requisition_cycle'), fn ($q) => $q->where('requisition_cycle', $request->getAttribute('approval_cycle') ?? 1))
|
||||
->when($lock, fn ($q) => $q->lockForUpdate())->first();
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>>|null */
|
||||
@@ -68,7 +75,7 @@ class RequisitionBudgetDistributions
|
||||
}
|
||||
abort_unless(auth()->id() === $actor->id && $actor->tenant_id === $request->tenant_id
|
||||
&& Requisition::query()->visibleTo($actor)->whereKey($request->id)->exists(), 403);
|
||||
$source = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->first();
|
||||
$source = $this->source($request);
|
||||
$plan = $source ? json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR)['allocations'] : ($request->budget_distribution_preparation['allocations'] ?? []);
|
||||
$lines = $request->items()->get()->keyBy('id');
|
||||
$centres = CostCenter::query()->where('tenant_id', $actor->tenant_id)->whereIn('id', array_column($plan, 'centre_id'))->get()->keyBy('id');
|
||||
@@ -98,7 +105,7 @@ class RequisitionBudgetDistributions
|
||||
$request = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
||||
$data = Validator::make($input, [...$this->rules($request), 'operation_key' => 'required|uuid', 'expected_plan_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D']])->validate();
|
||||
$source = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->lockForUpdate()->first();
|
||||
$source = $this->source($request, true);
|
||||
abort_unless($source !== null && $source->phase === 'commit', 409);
|
||||
$snapshot = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$reference = app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
|
||||
@@ -115,7 +122,7 @@ class RequisitionBudgetDistributions
|
||||
$lines[$allocation['line_id']]['subtotal_minor'] += $allocation['subtotal_minor'];
|
||||
$lines[$allocation['line_id']]['total_minor'] += $allocation['total_minor'];
|
||||
}
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
$engine = app(CommonBudget::class)->for($actor, RequisitionExpiry::cycles($request));
|
||||
$method = new \ReflectionMethod($engine, 'amendDistribution');
|
||||
$result = app(CommonBudget::class)->execute(fn () => $method->invoke($engine, $request->id, $allocations,
|
||||
$data['expected_plan_hash'], $data['reason'], $data['operation_key'], $lines));
|
||||
@@ -234,7 +241,7 @@ class RequisitionBudgetDistributions
|
||||
{
|
||||
abort_unless($this->ready(), 503, 'A distribuição exige a composição compatível; não foi aplicado o contrato antigo.');
|
||||
$prepared = $request->budget_distribution_preparation;
|
||||
$source = DB::table('budget_distributions')->where('tenant_id', $request->tenant_id)->where('requisition_id', $request->id)->first();
|
||||
$source = $this->source($request);
|
||||
if (in_array($kind, ['release', 'cancel'], true) && $source !== null) {
|
||||
$frozen = json_decode($source->snapshot, true, 64, JSON_THROW_ON_ERROR);
|
||||
$allocations = array_map(fn (array $row) => array_intersect_key($row, array_flip(['allocation_key', 'line_id', 'centre_id', 'subtotal_minor', 'total_minor'])), $frozen['allocations']);
|
||||
@@ -269,7 +276,7 @@ class RequisitionBudgetDistributions
|
||||
}
|
||||
$revision = $quote === null ? $prepared['source_revision'] : hash('sha256', json_encode(['quotation_id' => $quote->id, 'lines' => $lines], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
$engine = app(CommonBudget::class)->for($actor);
|
||||
$engine = app(CommonBudget::class)->for($actor, RequisitionExpiry::cycles($request));
|
||||
$method = new \ReflectionMethod($engine, 'recordDistribution');
|
||||
$result = app(CommonBudget::class)->execute(fn () => $method->invoke($engine, $request->id, $kind, $allocations, $lines, $revision, (string) Str::uuid()));
|
||||
if (! is_array($result)) {
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Tempo\Finance\Budget\BudgetControl;
|
||||
use Tempo\Purchasing\Internal\InternalRequisitions;
|
||||
|
||||
/** Company-defined elapsed-time policy; no default deadlines, approvers or grants. */
|
||||
final class RequisitionExpiry
|
||||
{
|
||||
public const ROLES = ['department_head', 'procurement', 'finance', 'configured_1', 'configured_2', 'configured_3', 'configured_4', 'configured_5'];
|
||||
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
$purchasing = new \ReflectionClass(InternalRequisitions::class);
|
||||
|
||||
return config('requisition-expiry.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())))
|
||||
&& $purchasing->hasMethod('supportsExpiryCycles') && $purchasing->getMethod('supportsExpiryCycles')->invoke(null) === true
|
||||
&& defined(BudgetControl::class.'::REQUISITION_CYCLES_VERSION')
|
||||
&& constant(BudgetControl::class.'::REQUISITION_CYCLES_VERSION') === CommonBudget::REQUISITION_CYCLES_CONTRACT
|
||||
&& Schema::hasTable('budget_requisition_cycles') && Schema::hasColumn('requisitions', 'approval_cycle')
|
||||
&& Schema::hasTable('workflow_notices') && Schema::hasTable('requisition_commands') && Schema::hasColumn('requisitions', 'process_version')
|
||||
&& Schema::hasColumn('approval_steps', 'approval_cycle') && Schema::hasColumn('budget_entries', 'requisition_cycle');
|
||||
}
|
||||
|
||||
/** @return array<int,int> */
|
||||
public static function cycles(Requisition $request): array
|
||||
{
|
||||
return [$request->id => (int) ($request->getAttribute('approval_cycle') ?? 1)];
|
||||
}
|
||||
|
||||
/** Identifiers can originate in a validated command payload; resolve actual scoped models.
|
||||
* @param array<mixed> $originIds
|
||||
* @return array<int,int>
|
||||
*/
|
||||
public static function origins(array $originIds): array
|
||||
{
|
||||
Validator::make(['origins' => $originIds], ['origins' => 'required|array|list', 'origins.*' => 'required|integer|min:1'])->validate();
|
||||
$requests = Requisition::query()->whereIn('id', $originIds)->get(Schema::hasColumn('requisitions', 'approval_cycle') ? ['id', 'approval_cycle'] : ['id']);
|
||||
abort_unless($requests->count() === count(array_unique($originIds)), 404);
|
||||
$result = [];
|
||||
foreach ($requests as $request) {
|
||||
$result += self::cycles($request);
|
||||
}
|
||||
ksort($result, SORT_NUMERIC);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
/** @return array<int,int> */
|
||||
public static function orderCycles(PurchaseOrder $order): array
|
||||
{
|
||||
return self::origins(app(OrderPartsAccess::class)->origins($order));
|
||||
}
|
||||
|
||||
public function assertOperational(Requisition $request): void
|
||||
{
|
||||
if ((int) ($request->getAttribute('approval_cycle') ?? 1) > 1 || isset($request->approval_snapshot['approval_expiry'])) {
|
||||
abort_unless($this->ready(), 503, 'Preserve a composição compatível dos ciclos antes de alterar esta requisição.');
|
||||
}
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function settings(User $actor): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
|
||||
return DB::transaction(function () use ($actor) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_unless($actor->hasFunctions(['admin']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
|
||||
return ['current' => SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->first(),
|
||||
'history' => SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->paginate(15)->withQueryString(),
|
||||
'profiles' => DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->orderBy('name')->get(['id', 'name']),
|
||||
'roles' => ['department_head' => 'Chefia de departamento', 'procurement' => 'Compras', 'finance' => 'Finanças',
|
||||
'configured_1' => 'Nível adicional 1', 'configured_2' => 'Nível adicional 2', 'configured_3' => 'Nível adicional 3',
|
||||
'configured_4' => 'Nível adicional 4', 'configured_5' => 'Nível adicional 5'],
|
||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, Requisition $request): array
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
|
||||
return DB::transaction(function () use ($actor, $request) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
abort_unless(app(OrganizationAccess::class)->permissions($actor) !== [], 403);
|
||||
$request = Requisition::query()->visibleTo($actor)->whereKey($request->id)->firstOrFail();
|
||||
$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]);
|
||||
|
||||
return ['requisition' => [...$request->only(['id', 'number', 'status', 'process_version', 'requester_id']),
|
||||
'approval_cycle' => $request->getAttribute('approval_cycle') ?? 1], 'deadline' => $deadline, 'history' => $history,
|
||||
'canExpire' => $deadline['state'] === 'expired' && ! app(ConflictGuard::class)->participationBlocked($actor, $request),
|
||||
'canEdit' => $request->status === 'draft' && (int) ($request->getAttribute('approval_cycle') ?? 1) > 1
|
||||
&& $request->requester_id === $actor->id && app(OrganizationAccess::class)->canRequest($actor),
|
||||
'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input */
|
||||
public function savePolicy(User $actor, array $input): SupplyRecord
|
||||
{
|
||||
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.*.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();
|
||||
$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];
|
||||
}
|
||||
$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'] !== [])) {
|
||||
throw ValidationException::withMessages(['levels.'.$index => 'Configure lembrete e escalamento antes da expiração, com destinatários explícitos apenas quando houver escalamento.']);
|
||||
}
|
||||
}
|
||||
unset($level);
|
||||
usort($data['levels'], fn ($a, $b) => strcmp($a['role'], $b['role']));
|
||||
if ($data['enabled'] && $data['levels'] === []) {
|
||||
throw ValidationException::withMessages(['levels' => 'Configure pelo menos um nível antes de activar a política.']);
|
||||
}
|
||||
$hash = hash('sha256', json_encode($data, JSON_THROW_ON_ERROR));
|
||||
|
||||
return DB::transaction(function () use ($actor, $data, $hash) {
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_unless($actor->hasFunctions(['admin']) && ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'req_expiry_policy' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
$old = SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->first();
|
||||
abort_unless((int) $data['version'] === ($old->version ?? 0), 409, 'A política mudou. Consulte a versão actual.');
|
||||
foreach ($data['levels'] as $level) {
|
||||
abort_unless(DB::table('organization_profiles')->where('tenant_id', $actor->tenant_id)->whereIn('id', $level['profile_ids'])->count() === count($level['profile_ids']), 422);
|
||||
}
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_expiry_policy',
|
||||
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1,
|
||||
'state' => $data['enabled'] ? 'active' : 'inactive', 'created_by' => $actor->id,
|
||||
'data' => ['enabled' => $data['enabled'], 'levels' => $data['levels'], 'time_basis' => 'elapsed_minutes', 'expiry_effect' => 'return_to_requester_draft'],
|
||||
'snapshot' => ['new_permissions' => false], 'reason' => trim($data['reason']), 'operation_key' => $data['operation_key'],
|
||||
'input_hash' => $hash, 'created_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'requisition.expiry_policy_saved', null, $old?->toArray(), ['record' => $record->toArray()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public function policy(Requisition $request): ?array
|
||||
{
|
||||
$this->assertOperational($request);
|
||||
if (! $this->ready()) {
|
||||
return null;
|
||||
}
|
||||
$source = SupplyRecord::query()->where('kind', 'req_expiry_policy')->latest('id')->first();
|
||||
if ($source === null || $source->state !== 'active') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return ['id' => $source->id, 'version' => $source->version, 'data' => $source->data,
|
||||
'fingerprint' => hash('sha256', json_encode($source->data, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function deadline(Requisition $request): array
|
||||
{
|
||||
$this->assertOperational($request);
|
||||
$inactive = ['state' => 'inactive', 'step_id' => null, 'expires_at' => null, 'basis_hash' => null];
|
||||
if ($request->status !== 'pending') {
|
||||
return $inactive;
|
||||
}
|
||||
$policy = $request->approval_snapshot['approval_expiry'] ?? null;
|
||||
if ($policy === null) {
|
||||
return [...$inactive, 'state' => 'unconfigured'];
|
||||
}
|
||||
$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.');
|
||||
$steps = $request->steps()->orderBy('position')->get();
|
||||
$step = $steps->firstWhere('decision', 'pending');
|
||||
$settings = null;
|
||||
if ($step !== null) {
|
||||
foreach ($policy['data']['levels'] as $level) {
|
||||
if ($level['role'] === $step->role) {
|
||||
$settings = $level;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($step === null || $settings === null || $request->submitted_at === null) {
|
||||
return [...$inactive, 'state' => 'unconfigured', 'step_id' => $step?->id];
|
||||
}
|
||||
$start = CarbonImmutable::parse($request->submitted_at);
|
||||
foreach ($steps->where('position', '<', $step->position) as $previous) {
|
||||
if ($previous->decision !== 'approved' || $previous->decided_at === null) {
|
||||
return [...$inactive, 'state' => 'unverified', 'step_id' => $step->id];
|
||||
}
|
||||
$date = CarbonImmutable::parse($previous->decided_at, config('app.timezone'));
|
||||
if ($date < $start || $date > now()) {
|
||||
return [...$inactive, 'state' => 'unverified', 'step_id' => $step->id];
|
||||
}
|
||||
$start = $date;
|
||||
}
|
||||
if ($start > now()) {
|
||||
return [...$inactive, 'state' => 'unverified', 'step_id' => $step->id];
|
||||
}
|
||||
$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()];
|
||||
|
||||
return ['state' => now()->greaterThanOrEqualTo($end) ? 'expired' : 'running', 'step_id' => $step->id,
|
||||
'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(),
|
||||
'profile_ids' => $settings['profile_ids'], 'policy_id' => $source->id, 'basis_hash' => hash('sha256', json_encode($basis, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $policy */
|
||||
public function begin(User $actor, Requisition $request, array $policy, ?string $operation): void
|
||||
{
|
||||
$cycle = (int) ($request->getAttribute('approval_cycle') ?? 1);
|
||||
if ($cycle === 1 && ! isset($policy['approval_expiry'])) {
|
||||
return;
|
||||
}
|
||||
abort_unless($this->ready(), 503);
|
||||
if ($operation === null) {
|
||||
throw ValidationException::withMessages(['operation_key' => 'A submissão por ciclos exige uma operação identificada.']);
|
||||
}
|
||||
$engine = app(CommonBudget::class)->for($actor, self::cycles($request));
|
||||
app(CommonBudget::class)->execute(fn () => (new \ReflectionMethod($engine, 'beginRequisitionCycle'))->invoke($engine, $request->id, $cycle, $operation));
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $input
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function proof(User $actor, Requisition $request, array $input): array
|
||||
{
|
||||
abort_unless($this->ready() && DB::transactionLevel() > 0, 503);
|
||||
Requisition::query()->visibleTo($actor)->whereKey($request->id)->firstOrFail();
|
||||
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'basis_hash' => ['required', 'regex:/^[a-f0-9]{64}$/D'],
|
||||
'comment' => 'nullable|string|max:2000'])->validate();
|
||||
$deadline = $this->deadline($request);
|
||||
abort_unless($deadline['state'] === 'expired' && hash_equals($deadline['basis_hash'], $data['basis_hash']), 409,
|
||||
'O prazo ou a etapa mudou, ou ainda não terminou. Actualize a conferência antes de devolver o pedido.');
|
||||
abort_if(SupplyRecord::query()->where('operation_key', $data['operation_key'])->exists(), 409, 'A operação pertence a outro registo.');
|
||||
|
||||
return [...$deadline, 'operation_key' => strtolower($data['operation_key']),
|
||||
'reason' => 'Prazo da etapa terminado em '.$deadline['expires_at'].'; devolução para nova submissão conforme a política #'.$deadline['policy_id'].'.'
|
||||
.(empty($data['comment']) ? '' : ' '.trim($data['comment']))];
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $proof */
|
||||
public function returned(User $actor, Requisition $request, array $proof): void
|
||||
{
|
||||
abort_unless($this->ready() && DB::transactionLevel() > 0 && $request->status === 'pending', 409);
|
||||
$cycle = (int) $request->getAttribute('approval_cycle');
|
||||
abort_unless($cycle > 0 && $cycle < 1000000, 409);
|
||||
$engine = app(CommonBudget::class)->for($actor, self::cycles($request));
|
||||
app(CommonBudget::class)->execute(fn () => (new \ReflectionMethod($engine, 'closeRequisitionCycle'))->invoke($engine, $request->id, $cycle, $proof['operation_key']));
|
||||
$before = $request->only(['id', 'number', 'status', 'approval_cycle', 'submitted_at', 'process_version', 'requester_id', 'department_id',
|
||||
'cost_center_id', 'priority', 'needed_by', 'justification', 'subtotal_minor', 'tax_minor', 'total_minor']);
|
||||
$steps = $request->steps()->get()->toArray();
|
||||
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'req_expiration', 'record_key' => (string) Str::uuid(),
|
||||
'version' => 1, 'state' => 'returned', 'created_by' => $actor->id,
|
||||
'data' => ['requisition_id' => $request->id, 'cycle' => $cycle, 'step_id' => $proof['step_id'], 'expires_at' => $proof['expires_at'],
|
||||
'policy_id' => $proof['policy_id'], 'next_cycle' => $cycle + 1],
|
||||
'snapshot' => ['request' => $before, 'items' => $request->items()->orderBy('id')->get()->toArray(), 'steps' => $steps,
|
||||
'approval_snapshot' => $request->approval_snapshot, 'proof' => $proof],
|
||||
'reason' => $proof['reason'], 'operation_key' => $proof['operation_key'], 'input_hash' => hash('sha256', json_encode($proof, JSON_THROW_ON_ERROR)), 'created_at' => now()]);
|
||||
// Close only unacted tasks. Approved decisions remain unchanged in their original rows.
|
||||
$request->steps()->where('decision', 'pending')->update(['decision' => 'expired', 'comment' => $proof['reason']]);
|
||||
$request->setAttribute('status', 'draft');
|
||||
$request->setAttribute('approval_cycle', $cycle + 1);
|
||||
$request->setAttribute('submitted_at', null);
|
||||
$request->setAttribute('process_version', (int) $request->getAttribute('process_version') + 1);
|
||||
$request->save();
|
||||
app(WorkflowNotices::class)->expired($request, $proof['step_id']);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'requisition.expired_returned', $request, $before,
|
||||
['status' => 'draft', 'cycle' => $cycle + 1, 'expiration_record_id' => $record->id, 'reason' => $proof['reason']]);
|
||||
}
|
||||
}
|
||||
@@ -173,6 +173,11 @@ class RequisitionWorkflow
|
||||
app(AutomaticPurchases::class)->requisitionChanged($user, $requisition);
|
||||
}
|
||||
|
||||
public function expire(User $user, Requisition $requisition, string $basisHash, string $operationKey, int $version, ?string $comment = null): void
|
||||
{
|
||||
$this->execute($user, 'expire', $requisition->id, $version, $operationKey, ['basis_hash' => $basisHash, 'comment' => $comment]);
|
||||
}
|
||||
|
||||
/** @param array<string, mixed>|null $before
|
||||
* @param array<string, mixed> $after
|
||||
*/
|
||||
|
||||
@@ -80,6 +80,23 @@ class WorkflowNotices
|
||||
}
|
||||
}
|
||||
|
||||
public function expired(Requisition $requisition, int $stepId): void
|
||||
{
|
||||
if (! Schema::hasTable('workflow_notices')) {
|
||||
return;
|
||||
}
|
||||
if (DB::transactionLevel() === 0) {
|
||||
throw new \LogicException('Aviso de devolução exige a transacção da expiração.');
|
||||
}
|
||||
$step = $requisition->allSteps()->whereKey($stepId)->firstOrFail();
|
||||
if ($requisition->status !== 'draft' || $step->decision !== 'expired') {
|
||||
throw new \LogicException('O aviso exige a devolução efectivamente registada.');
|
||||
}
|
||||
$recipient = User::query()->where('tenant_id', $requisition->tenant_id)->whereKey($requisition->requester_id)->firstOrFail();
|
||||
DB::table('workflow_notices')->insertOrIgnore(['tenant_id' => $requisition->tenant_id, 'requisition_id' => $requisition->id,
|
||||
'approval_step_id' => $step->id, 'recipient_id' => $recipient->id, 'reference' => $requisition->number, 'role' => $step->role, 'created_at' => now()]);
|
||||
}
|
||||
|
||||
/** @return list<array<string,mixed>> */
|
||||
public function visible(User $actor): array
|
||||
{
|
||||
@@ -92,14 +109,15 @@ class WorkflowNotices
|
||||
if ($request === null) {
|
||||
continue;
|
||||
}
|
||||
$step = $request->steps->firstWhere('id', $notice->approval_step_id);
|
||||
$outcome = $request->requester_id === $actor->id && $step !== null && in_array($step->decision, ['approved', 'rejected'], true);
|
||||
$step = $request->steps->firstWhere('id', $notice->approval_step_id)
|
||||
?? $request->allSteps()->whereKey($notice->approval_step_id)->first();
|
||||
$outcome = $request->requester_id === $actor->id && $step !== null && in_array($step->decision, ['approved', 'rejected', 'expired'], true);
|
||||
if (! $outcome && (! $request->canDecide($actor) || $request->steps->firstWhere('decision', 'pending')?->id !== $notice->approval_step_id)) {
|
||||
continue;
|
||||
}
|
||||
$items[] = ['id' => $notice->id, 'reference' => $notice->reference, 'role' => $notice->role, 'role_label' => $step?->routing['name'] ?? null,
|
||||
'kind' => $outcome ? 'outcome' : 'task', 'outcome' => $outcome ? $step->decision : null, 'current_status' => $request->status,
|
||||
'created_at' => $notice->created_at, 'read_at' => $notice->read_at, 'href' => '/requisicoes/'.$request->id];
|
||||
'created_at' => $notice->created_at, 'read_at' => $notice->read_at, 'href' => '/requisicoes/'.$request->id.($outcome && $step->decision === 'expired' ? '/prazos' : '')];
|
||||
}
|
||||
|
||||
return $items;
|
||||
|
||||
Reference in New Issue
Block a user