@@ -27,7 +27,8 @@ class OrderCancellationWorkflow
|
||||
}
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id);
|
||||
|
||||
return $order && Requisition::query()->whereKey($order->requisition_id)->where('requester_id', $actor->id)->where('department_id', $actor->department_id)->exists();
|
||||
return $order && ! OrderPartsAccess::applies($order)
|
||||
&& Requisition::query()->whereKey($order->requisition_id)->where('requester_id', $actor->id)->where('department_id', $actor->department_id)->exists();
|
||||
}
|
||||
|
||||
public function canRequest(User $actor, PurchaseOrder $order): bool
|
||||
@@ -38,6 +39,17 @@ class OrderCancellationWorkflow
|
||||
}
|
||||
$request = Requisition::query()->visibleTo($actor)->find($order->requisition_id);
|
||||
$policy = app(OrderCancellationPolicyWorkflow::class)->current();
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
if (! PurchaseOrder::query()->visibleTo($actor)->whereKey($order->id)->exists()) {
|
||||
return false;
|
||||
}
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
|
||||
$source = Requisition::query()->whereKey($origin)->first();
|
||||
if (! $source || $source->requester_id === $actor->id || app(ConflictGuard::class)->processBlocked($source, $order->supplier_id, $actor)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $request && $request->requester_id !== $actor->id && $policy && $policy->enabled && $policy->mode === 'issued_order'
|
||||
&& $policy->valid_until >= today()->format('Y-m-d')
|
||||
@@ -53,6 +65,16 @@ class OrderCancellationWorkflow
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->find($record->purchase_order_id);
|
||||
$request = $order ? Requisition::query()->find($order->requisition_id) : null;
|
||||
$award = $order ? PurchaseAward::query()->find($order->purchase_award_id) : null;
|
||||
if ($order && OrderPartsAccess::applies($order)) {
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
|
||||
$source = Requisition::query()->whereKey($origin)->first();
|
||||
$sourceAward = PurchaseAward::query()->where('requisition_id', $origin)->first();
|
||||
if (! $source || ! $sourceAward || in_array($actor->id, [$source->requester_id, $sourceAward->created_by], true)
|
||||
|| app(ConflictGuard::class)->processBlocked($source, $order->supplier_id, $actor)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $order && $request && $award && ! in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true);
|
||||
}
|
||||
@@ -92,6 +114,8 @@ class OrderCancellationWorkflow
|
||||
private function basis(PurchaseOrder $order): string
|
||||
{
|
||||
return hash('sha256', json_encode(['order' => $order->getAttributes(), 'items' => $order->items()->orderBy('id')->get()->toArray(),
|
||||
...(OrderPartsAccess::applies($order) ? ['order_parts_financial' => DB::table('budget_order_allocations')->where('tenant_id', $order->tenant_id)
|
||||
->where('order_key', $order->getAttribute('order_key'))->orderBy('id')->get()->toArray()] : []),
|
||||
'budget' => DB::table('budget_entries')->where('tenant_id', $order->tenant_id)->where('requisition_id', $order->requisition_id)->orderBy('id')->get()->toArray()], JSON_THROW_ON_ERROR));
|
||||
}
|
||||
|
||||
@@ -111,6 +135,10 @@ class OrderCancellationWorkflow
|
||||
$request = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
||||
abort_if($actor->id === $request->requester_id, 403);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||
abort_if(Requisition::query()->whereIn('id', app(OrderPartsAccess::class)->origins($order))->where('requester_id', $actor->id)->exists(), 403);
|
||||
}
|
||||
$old = OrderCancellation::query()->where('created_by', $actor->id)->where('operation_key', $data['operation_key'])->first();
|
||||
if ($old) {
|
||||
abort_unless($old->input_hash === $hash, 422, 'Chave utilizada com outro conteúdo.');
|
||||
@@ -143,36 +171,72 @@ class OrderCancellationWorkflow
|
||||
$award = PurchaseAward::query()->findOrFail($order->purchase_award_id);
|
||||
abort_if(in_array($actor->id, [$record->created_by, $request->requester_id, $award->created_by, $order->issued_by], true), 403);
|
||||
app(ConflictGuard::class)->assertProcess($request, $order->supplier_id, $actor);
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
||||
foreach (app(OrderPartsAccess::class)->origins($order) as $origin) {
|
||||
$source = Requisition::query()->whereKey($origin)->firstOrFail();
|
||||
$sourceAward = PurchaseAward::query()->where('requisition_id', $origin)->firstOrFail();
|
||||
abort_if(in_array($actor->id, [$source->requester_id, $sourceAward->created_by], true), 403);
|
||||
}
|
||||
}
|
||||
if ($record->status !== 'pending') {
|
||||
abort_unless($record->status === $decision && $record->review_reason === $reason && $record->reviewed_by === $actor->id, 409, 'Decisão imutável.');
|
||||
|
||||
return;
|
||||
}
|
||||
$entry = null;
|
||||
$partReversal = null;
|
||||
if ($decision === 'approved') {
|
||||
$this->source($order);
|
||||
abort_unless($record->basis_hash === $this->basis($order), 409, 'A base da ordem ou do compromisso mudou.');
|
||||
$policy = app(OrderCancellationPolicyWorkflow::class)->requireCurrent();
|
||||
abort_unless($policy->id === $record->policy_id, 409, 'Política alterada; rejeite o pedido para retomar o circuito.');
|
||||
abort_unless(DB::table('tenants')->where('id', $actor->tenant_id)->value('currency') === 'MZN', 422);
|
||||
if (! empty($order->snapshot['budget_control']) && ! DB::table('budget_entries')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->exists()) {
|
||||
throw ValidationException::withMessages(['budget' => 'A ordem indica controlo orçamental, mas o compromisso não está disponível.']);
|
||||
if (OrderPartsAccess::applies($order)) {
|
||||
$partReversal = $this->reverseParts($actor, $order, $record);
|
||||
} else {
|
||||
if (! empty($order->snapshot['budget_control']) && ! DB::table('budget_entries')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->exists()) {
|
||||
throw ValidationException::withMessages(['budget' => 'A ordem indica controlo orçamental, mas o compromisso não está disponível.']);
|
||||
}
|
||||
$path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
|
||||
abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
|
||||
require_once $path;
|
||||
try {
|
||||
$entry = (new CommitmentReversal)->reverse(DB::connection(), new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN'), $request->id, $order->id);
|
||||
} catch (\LogicException $error) {
|
||||
throw ValidationException::withMessages(['budget' => 'O compromisso não está integralmente disponível para reversão ou a sua base é inconsistente. Reveja o controlo orçamental.']);
|
||||
}
|
||||
$request->update(['status' => 'cancelled']);
|
||||
}
|
||||
$path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
|
||||
abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
|
||||
require_once $path;
|
||||
try {
|
||||
$entry = (new CommitmentReversal)->reverse(DB::connection(), new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN'), $request->id, $order->id);
|
||||
} catch (\LogicException $error) {
|
||||
throw ValidationException::withMessages(['budget' => 'O compromisso não está integralmente disponível para reversão ou a sua base é inconsistente. Reveja o controlo orçamental.']);
|
||||
}
|
||||
$request->update(['status' => 'cancelled']);
|
||||
}
|
||||
$record->update(['status' => $decision, 'reviewed_by' => $actor->id, 'review_reason' => $reason, 'reviewed_at' => now()]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'order_cancellation.'.$decision, $request, null, ['cancellation_id' => $record->id, 'order_id' => $order->id, 'budget_reversal_entry_id' => $entry]);
|
||||
app(RequisitionWorkflow::class)->audit($actor, 'order_cancellation.'.$decision, $request, null, ['cancellation_id' => $record->id, 'order_id' => $order->id, 'budget_reversal_entry_id' => $entry,
|
||||
...($partReversal === null ? [] : ['order_parts_reversal' => $partReversal])]);
|
||||
});
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private function reverseParts(User $actor, PurchaseOrder $order, OrderCancellation $record): array
|
||||
{
|
||||
abort_unless(app(OrderPartsWorkflow::class)->ready(), 503);
|
||||
$sources = $order->snapshot['order_parts']['budget_sources'];
|
||||
foreach ($sources as &$source) {
|
||||
$distribution = DB::table('budget_distributions')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $source['origin'])->lockForUpdate()->first();
|
||||
abort_unless($distribution !== null, 503, 'Preserve a origem do compromisso.');
|
||||
$source['version'] = DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count();
|
||||
$source['plan_hash'] = json_decode($distribution->snapshot, true, 64, JSON_THROW_ON_ERROR)['plan_hash'];
|
||||
}
|
||||
unset($source);
|
||||
$adapter = app(CommonBudget::class);
|
||||
$engine = $adapter->for($actor);
|
||||
$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.');
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function revise(User $actor, OrderCancellation $record, string $neededBy, string $reason): Requisition
|
||||
{
|
||||
$this->enabled();
|
||||
@@ -184,6 +248,7 @@ class OrderCancellationWorkflow
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
$record = OrderCancellation::query()->lockForUpdate()->findOrFail($record->id);
|
||||
$order = PurchaseOrder::query()->findOrFail($record->purchase_order_id);
|
||||
abort_if(OrderPartsAccess::applies($order), 422, 'Cancelar uma parcela não encerra a requisição nem autoriza uma nova requisição por arrasto.');
|
||||
$source = Requisition::query()->lockForUpdate()->findOrFail($order->requisition_id);
|
||||
abort_unless($actor->id === $source->requester_id && $actor->department_id === $source->department_id && $record->status === 'approved', 403);
|
||||
if ($record->revised_requisition_id) {
|
||||
|
||||
Reference in New Issue
Block a user