190 lines
11 KiB
PHP
190 lines
11 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Enums\PurchasingRole;
|
|
use App\Models\Invoice;
|
|
use App\Models\PurchaseOrder;
|
|
use App\Models\User;
|
|
use Brick\Math\BigDecimal;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
/** Finance's explicit native invoice imputations, with one common consumption command. */
|
|
final class OrderPartsInvoices
|
|
{
|
|
/** @return list<array<string,mixed>>|null */
|
|
public function options(User $actor, PurchaseOrder $order): ?array
|
|
{
|
|
if (! app(OrderPartsWorkflow::class)->ready() || ! $actor->hasFunctions([PurchasingRole::Finance])
|
|
|| app(OrganizationAccess::class)->maintenanceOnly($actor)) {
|
|
return null;
|
|
}
|
|
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();
|
|
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');
|
|
foreach ($snapshot['allocations'] as $allocation) {
|
|
if (! isset($nativeLines[$allocation['line_id']]) || ! DB::table('budget_order_allocations')->where('tenant_id', $actor->tenant_id)
|
|
->where('order_key', $order->getAttribute('order_key'))->where('distribution_id', $distribution->id)->where('allocation_key', $allocation['allocation_key'])->where('kind', 'commit')->exists()) {
|
|
continue;
|
|
}
|
|
$rows[] = ['origin' => $source['requisition_id'], 'allocation_key' => $allocation['allocation_key'], 'line_id' => $allocation['line_id'],
|
|
'centre_id' => $allocation['centre_id'], 'description' => $nativeLines[$allocation['line_id']]['description']];
|
|
}
|
|
}
|
|
|
|
return $rows;
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function rules(): array
|
|
{
|
|
$money = ['required', 'string', 'regex:/^\d{1,12}(?:\.\d{1,2})?$/D'];
|
|
|
|
return ['order_part_allocations' => 'required|array|min:1|max:500',
|
|
'order_part_allocations.*' => 'required|array:origin,allocation_key,subtotal,total',
|
|
'order_part_allocations.*.origin' => 'required|integer|min:1',
|
|
'order_part_allocations.*.allocation_key' => 'required|string|max:120',
|
|
'order_part_allocations.*.subtotal' => $money, 'order_part_allocations.*.total' => $money,
|
|
'reason' => 'required|string|min:10|max:4000'];
|
|
}
|
|
|
|
/** @param array<string,mixed> $input
|
|
* @param list<array<string,mixed>> $nativeLines
|
|
* @return array<string,mixed>
|
|
*/
|
|
public function prepare(User $actor, Invoice $invoice, PurchaseOrder $order, array $input, array $nativeLines): array
|
|
{
|
|
abort_unless(app(OrderPartsWorkflow::class)->ready() && DB::transactionLevel() > 0 && OrderPartsAccess::applies($order), 503);
|
|
abort_unless(auth()->id() === $actor->id && $actor->hasFunctions([PurchasingRole::Finance])
|
|
&& $invoice->tenant_id === $actor->tenant_id && $order->tenant_id === $actor->tenant_id && $invoice->purchase_order_id === $order->id, 403);
|
|
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
|
abort_unless($order->currency === 'MZN', 503, 'A imputação multimoeda por origem ainda está em preparação.');
|
|
$data = Validator::make($input, $this->rules())->validate();
|
|
$rows = [];
|
|
$seen = [];
|
|
foreach ($data['order_part_allocations'] as $row) {
|
|
$origin = BigDecimal::of($row['origin'])->toInt();
|
|
$key = $origin.':'.$row['allocation_key'];
|
|
if (isset($seen[$key])) {
|
|
throw ValidationException::withMessages(['order_part_allocations' => 'Cada atribuição é indicada uma única vez por origem.']);
|
|
}
|
|
$seen[$key] = true;
|
|
$rows[] = ['origin' => $origin, 'allocation_key' => $row['allocation_key'],
|
|
'subtotal_minor' => BigDecimal::of($row['subtotal'])->multipliedBy(100)->toInt(),
|
|
'total_minor' => BigDecimal::of($row['total'])->multipliedBy(100)->toInt()];
|
|
}
|
|
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);
|
|
$adapter->execute(fn () => (new \ReflectionMethod($engine, 'checkOrderPartsConsumption'))->invoke($engine, $sources));
|
|
|
|
return ['allocations' => $rows, 'source_versions_at_preparation' => array_column($sources, 'version', 'origin'),
|
|
'revision' => $this->revision($invoice, $order, $nativeLines), 'operation_key' => (string) Str::uuid(),
|
|
'prepared_by' => $actor->id, 'reason' => trim($data['reason'])];
|
|
}
|
|
|
|
/** @param list<array<string,mixed>> $rows
|
|
* @param list<array<string,mixed>> $nativeLines
|
|
* @return list<array<string,mixed>>
|
|
*/
|
|
private function bindings(User $actor, PurchaseOrder $order, array $rows, array $nativeLines): array
|
|
{
|
|
$orderKey = $order->getAttribute('order_key');
|
|
abort_unless(is_string($orderKey) && $orderKey === ($order->snapshot['order_parts']['order_key'] ?? null), 503,
|
|
'Preserve o identificador nativo da ordem por parcelas.');
|
|
$origins = app(OrderPartsAccess::class)->origins($order);
|
|
$orderLines = $order->items()->get()->keyBy('id');
|
|
$lineOrigins = [];
|
|
foreach ($order->snapshot['order_parts']['sources'] as $source) {
|
|
foreach ($source['items'] as $line) {
|
|
$lineOrigins[$line['requisition_item_id']] = $source['requisition_id'];
|
|
}
|
|
}
|
|
$expected = [];
|
|
foreach ($nativeLines as $line) {
|
|
$native = $orderLines->get($line['purchase_order_item_id']);
|
|
abort_unless($native !== null && isset($lineOrigins[$native->requisition_item_id]), 409);
|
|
$expected[$native->requisition_item_id] = ['origin' => $lineOrigins[$native->requisition_item_id],
|
|
'subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['subtotal_minor'] + $line['tax_minor']];
|
|
}
|
|
$sources = $sums = [];
|
|
foreach ($rows as $row) {
|
|
if (! in_array($row['origin'], $origins, true)) {
|
|
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();
|
|
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(),
|
|
'plan_hash' => $snapshot['plan_hash'], 'allocations' => [], 'frozen' => array_column($snapshot['allocations'], null, 'allocation_key')];
|
|
}
|
|
$binding = $sources[$row['origin']]['frozen'][$row['allocation_key']] ?? null;
|
|
$id = $binding['line_id'] ?? null;
|
|
if ($id === null || ! isset($expected[$id]) || $expected[$id]['origin'] !== $row['origin']) {
|
|
throw ValidationException::withMessages(['order_part_allocations' => 'Distribua apenas as linhas e origens efectivamente facturadas.']);
|
|
}
|
|
$sums[$id] ??= ['subtotal_minor' => 0, 'total_minor' => 0];
|
|
$sums[$id]['subtotal_minor'] += $row['subtotal_minor'];
|
|
$sums[$id]['total_minor'] += $row['total_minor'];
|
|
$sources[$row['origin']]['allocations'][] = ['order_key' => $orderKey, 'allocation_key' => $row['allocation_key'],
|
|
'subtotal_minor' => $row['subtotal_minor'], 'total_minor' => $row['total_minor']];
|
|
}
|
|
foreach ($expected as $id => $line) {
|
|
if (($sums[$id] ?? null) !== ['subtotal_minor' => $line['subtotal_minor'], 'total_minor' => $line['total_minor']]) {
|
|
throw ValidationException::withMessages(['order_part_allocations' => 'As imputações devem coincidir exactamente com cada linha nativa da factura.']);
|
|
}
|
|
}
|
|
foreach ($sources as &$source) {
|
|
unset($source['frozen']);
|
|
}
|
|
unset($source);
|
|
ksort($sources, SORT_NUMERIC);
|
|
|
|
return array_values($sources);
|
|
}
|
|
|
|
/** @param list<array<string,mixed>> $lines */
|
|
private function revision(Invoice $invoice, PurchaseOrder $order, array $lines): string
|
|
{
|
|
$items = array_map(fn ($line) => array_intersect_key($line, array_flip(['purchase_order_item_id', 'quantity_milli', 'subtotal_minor', 'tax_minor'])), $lines);
|
|
usort($items, fn ($a, $b) => $a['purchase_order_item_id'] <=> $b['purchase_order_item_id']);
|
|
foreach ($items as &$item) {
|
|
ksort($item);
|
|
}
|
|
unset($item);
|
|
|
|
return hash('sha256', json_encode([$invoice->only(['tenant_id', 'purchase_order_id', 'number', 'subtotal_minor', 'tax_minor', 'total_minor']),
|
|
$order->only(['id', 'order_key', 'currency', 'snapshot']), $items], JSON_THROW_ON_ERROR));
|
|
}
|
|
|
|
/** @return array<string,mixed> */
|
|
public function consume(User $actor, Invoice $invoice, PurchaseOrder $order): array
|
|
{
|
|
abort_unless(app(OrderPartsWorkflow::class)->ready() && DB::transactionLevel() > 0, 503);
|
|
app(OrderPartsAccess::class)->assertProcess($actor, $order);
|
|
$plan = $invoice->snapshot['budget_distribution'] ?? null;
|
|
$lines = array_values($invoice->items()->orderBy('purchase_order_item_id')->get()->map(fn ($item) => $item->only(['purchase_order_item_id', 'quantity_milli', 'subtotal_minor', 'tax_minor']))->all());
|
|
if (! is_array($plan) || ($plan['revision'] ?? null) !== $this->revision($invoice, $order, $lines)) {
|
|
throw ValidationException::withMessages(['order_part_allocations' => 'Preserve a imputação nativa confirmada para esta factura.']);
|
|
}
|
|
$sources = $this->bindings($actor, $order, $plan['allocations'], $lines);
|
|
$adapter = app(CommonBudget::class);
|
|
$engine = $adapter->for($actor);
|
|
$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.');
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
}
|