Files
compras/app/Services/OrderPartsAmendments.php
T
nala 9cf9764710
tests / ci (push) Waiting to run
commit compras3 2711
2026-11-27 18:56:24 +02:00

81 lines
5.2 KiB
PHP

<?php
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;
use Illuminate\Support\Facades\Validator;
/** Native Finance authority and projection; the common writer alone reallocates commitments. */
final class OrderPartsAmendments
{
/** @return list<array<string,mixed>> */
public function sources(User $actor, PurchaseOrder $order): array
{
abort_unless(app(OrderPartsWorkflow::class)->ready() && OrderPartsAccess::applies($order), 503);
abort_unless(auth()->id() === $actor->id && $actor->hasFunctions([PurchasingRole::Finance])
&& ! app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
app(OrderPartsAccess::class)->assertProcess($actor, $order);
app(OrderCancellationWorkflow::class)->assertOperational($order);
$sources = [];
foreach ($order->snapshot['order_parts']['budget_sources'] as $original) {
$origin = $original['origin'];
$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');
$rows = [];
foreach ($original['allocations'] as $row) {
$allocation = $frozen[$row['allocation_key']] ?? null;
abort_unless($allocation !== null, 503, 'Preserve as atribuições originais.');
$current = DB::table('budget_order_allocations')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)
->where('order_key', $order->getAttribute('order_key'))->where('allocation_key', $row['allocation_key'])->whereIn('kind', ['commit', 'amend']);
$rows[] = ['allocation_key' => $row['allocation_key'], 'line_id' => $allocation['line_id'], 'centre_id' => $allocation['centre_id'],
'subtotal' => (string) BigDecimal::of((int) (clone $current)->sum('subtotal_minor'))->dividedBy(100, 2),
'total' => (string) BigDecimal::of((int) (clone $current)->sum('total_minor'))->dividedBy(100, 2)];
}
$sources[] = ['origin' => $origin, 'version' => DB::table('budget_order_bindings')->where('tenant_id', $actor->tenant_id)->where('distribution_id', $distribution->id)->count(),
'plan_hash' => $snapshot['plan_hash'], 'allocations' => $rows];
}
return $sources;
}
/** @param array<string,mixed> $input */
public function amend(User $actor, PurchaseOrder $order, array $input): void
{
DB::transaction(function () use ($actor, $order, $input): void {
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor, [PurchasingRole::Finance]);
$order = PurchaseOrder::query()->whereKey($order->id)->lockForUpdate()->firstOrFail();
$this->sources($actor, $order);
app(QuotationExchange::class)->orderAmounts($order, $order->subtotal_minor, $order->tax_minor);
$data = Validator::make($input, [
'operation_key' => 'required|uuid', 'reason' => 'required|string|min:10|max:4000',
'sources' => 'required|array|list|min:1|max:100',
'sources.*' => 'required|array:origin,version,plan_hash,allocations',
'sources.*.origin' => 'required|integer|min:1|distinct', 'sources.*.version' => 'required|integer|min:0',
'sources.*.plan_hash' => 'required|regex:/^[a-f0-9]{64}$/D',
'sources.*.allocations' => 'required|array|list|min:1|max:500',
'sources.*.allocations.*' => 'required|array:allocation_key,subtotal,total',
'sources.*.allocations.*.allocation_key' => 'required|string|max:120',
'sources.*.allocations.*.subtotal' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/D'],
'sources.*.allocations.*.total' => ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/D'],
])->validate();
$sources = array_map(fn ($source) => ['origin' => BigDecimal::of($source['origin'])->toInt(), 'version' => BigDecimal::of($source['version'])->toInt(),
'plan_hash' => $source['plan_hash'], 'allocations' => array_map(fn ($row) => ['allocation_key' => $row['allocation_key'],
'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, RequisitionExpiry::orderCycles($order));
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'amendOrderParts'))->invoke($engine,
$order->getAttribute('order_key'), $sources, $data['reason'], strtolower($data['operation_key'])));
});
}
}