Files
compras/app/Services/ExpenseAllocations.php
T
nala 7da8d6c87a
tests / ci (push) Canceled after 0s
commit compras2 2911
2026-11-29 10:48:22 +02:00

226 lines
13 KiB
PHP

<?php
namespace App\Services;
use App\Models\ExternalPayment;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\SupplyRecord;
use App\Models\User;
use Brick\Math\BigDecimal;
use Brick\Math\BigInteger;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
/** Explicit analytical attribution; never changes a payment, liability or financial journal. */
final class ExpenseAllocations
{
public function ready(): bool
{
$db = DB::connection();
if (app(StandaloneRuntime::class)->enabled()) {
return app(StandaloneRuntime::class)->feature('expense-allocations', $db)
&& $db->getSchemaBuilder()->hasTable('supply_records');
}
return config('expense-allocations.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())));
}
/** @return array<string,mixed> */
public function source(User $actor, int $id, string $sourceType = 'external_payment'): array
{
$this->validSource($sourceType);
$facts = null;
if ($sourceType === 'common_allocation') {
try {
$facts = app(CommonPaymentFacts::class)->source($actor, $id);
} catch (\DomainException $error) {
abort(409, $error->getMessage());
}
$invoiceId = $facts['invoice_id'];
} else {
$invoiceId = ExternalPayment::query()->whereKey($id)->firstOrFail()->invoice_id;
}
$invoice = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->whereKey($invoiceId)->firstOrFail();
if ($sourceType === 'external_payment') {
try {
$facts = collect(app(SupplierPayables::class)->readPaymentHistory($actor, $invoice->id))->firstWhere('id', $id);
} catch (\DomainException) {
abort(409, 'O histórico auditado do pagamento está indeterminado.');
}
}
abort_unless($facts !== null && $facts['status'] === 'confirmed', 409, 'A imputação exige um pagamento confirmado e o seu histórico auditado.');
abort_unless(is_int($facts['amount_minor']) && $facts['amount_minor'] > 0 && is_string($facts['currency'])
&& preg_match('/^[A-Z]{3}$/D', $facts['currency']) && is_string($facts['reviewed_at']) && trim($facts['reviewed_at']) !== ''
&& is_int($facts['reviewed_by']) && $facts['reviewed_by'] > 0, 409, 'A confirmação tem dados indeterminados; conserve os originais para conferência.');
$categories = [];
foreach ($invoice->items()->orderBy('id')->get() as $item) {
$line = DB::table('purchase_order_items')->where('tenant_id', $actor->tenant_id)->where('purchase_order_id', $invoice->purchase_order_id)
->where('id', $item->purchase_order_item_id)->first(['category']);
abort_unless($line !== null && is_string($line->category) && trim($line->category) !== '', 409,
'Há linhas da factura sem categoria documental determinada.');
$categories[$line->category] = $line->category;
}
$categories = array_values($categories);
sort($categories, SORT_STRING);
abort_unless($categories !== [], 409, 'A factura exige linhas com categorias documentais para esta imputação.');
$source = ['payment' => $facts, 'invoice_id' => $invoice->id, 'invoice_number' => $invoice->getAttribute('number'),
'purchase_order_id' => $invoice->purchase_order_id, 'categories' => $categories];
return [...$source, 'fingerprint' => hash('sha256', json_encode($source, JSON_THROW_ON_ERROR))];
}
private function actor(User $actor): User
{
abort_unless($this->ready(), 503);
app(ConflictGuard::class)->lockCompany($actor);
$actor = app(CurrentActor::class)->lock($actor);
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
abort_unless($actor->hasFunctions(['admin', 'finance']) && app(SupplierPayables::class)->can($actor, 'view'), 403);
return $actor;
}
private function validSource(string $sourceType): void
{
if (! in_array($sourceType, ['external_payment', 'common_allocation'], true)) {
throw new \InvalidArgumentException('Unknown expense attribution source.');
}
}
/** @return Builder<SupplyRecord> */
private function records(int $payment, string $sourceType): Builder
{
$this->validSource($sourceType);
return SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)
->when($sourceType === 'external_payment',
fn ($query) => $query->where(fn ($source) => $source->whereNull('data->source_type')->orWhere('data->source_type', 'external_payment')),
fn ($query) => $query->where('data->source_type', 'common_allocation'));
}
public function current(int $payment, string $sourceType = 'external_payment'): ?SupplyRecord
{
return $this->records($payment, $sourceType)->latest('version')->first();
}
/** @return array<string,mixed> */
public function projection(User $actor, int $payment, string $sourceType = 'external_payment'): array
{
$record = $this->current($payment, $sourceType);
if ($record === null) {
return ['state' => 'unallocated', 'allocations' => []];
}
if (! $this->ready()) {
return ['state' => 'indeterminate', 'allocations' => []];
}
try {
$source = $this->source($actor, $payment, $sourceType);
} catch (HttpExceptionInterface $error) {
if (! in_array($error->getStatusCode(), [404, 409], true)) {
throw $error;
}
return ['state' => 'indeterminate', 'allocations' => []];
}
if (($record->snapshot['fingerprint'] ?? '') !== $source['fingerprint']) {
return ['state' => 'indeterminate', 'allocations' => []];
}
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('user_id', $record->created_by)
->where('action', 'expense.allocation_recorded')->where('after->record->id', $record->id)->latest('id')->value('after');
$saved = is_string($audit) ? (json_decode($audit, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null) : null;
if (! 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) {
return ['state' => 'indeterminate', 'allocations' => []];
}
return ['state' => 'allocated', 'allocations' => $record->data['allocations']];
}
/** @return array<string,mixed> */
public function workspace(User $actor, int $payment, string $sourceType = 'external_payment'): array
{
return DB::transaction(function () use ($actor, $payment, $sourceType) {
$actor = $this->actor($actor);
$source = $this->source($actor, $payment, $sourceType);
$current = $this->current($payment, $sourceType);
$row = fn (SupplyRecord $record) => ['id' => $record->id, 'version' => $record->version, 'reason' => $record->reason,
'data' => ['allocations' => $record->data['allocations']]];
return ['payment' => ['id' => $payment, 'invoice_id' => $source['invoice_id'], 'invoice_number' => $source['invoice_number'],
'amount_minor' => (string) $source['payment']['amount_minor'], 'currency' => $source['payment']['currency']],
'categories' => $source['categories'], 'fingerprint' => $source['fingerprint'], 'current' => $current === null ? null : $row($current),
'history' => $this->records($payment, $sourceType)->latest('version')->paginate(15)->withQueryString()->through($row),
...($sourceType === 'common_allocation' ? ['sourceType' => 'common_allocation', 'submitUrl' => '/afectacoes-fornecedores/'.$payment.'/imputacao'] : []),
'canWrite' => $actor->hasFunctions(['finance']), 'actorId' => $actor->id, 'tenantId' => $actor->tenant_id];
});
}
/** @param array<string,mixed> $input */
public function save(User $actor, int $payment, array $input, string $sourceType = 'external_payment'): SupplyRecord
{
$data = Validator::make($input, ['operation_key' => 'required|uuid', 'version' => 'required|integer|min:0',
'fingerprint' => ['required', 'regex:/^[a-f0-9]{64}$/D'], 'reason' => 'required|string|min:10|max:4000',
'allocations' => 'required|array|list|min:1|max:100', 'allocations.*' => 'array:category,amount',
'allocations.*.category' => 'required|string|max:255|distinct:strict', 'allocations.*.amount' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D']])->validate();
$data['operation_key'] = strtolower($data['operation_key']);
$data['version'] = (int) $data['version'];
usort($data['allocations'], fn ($a, $b) => strcmp($a['category'], $b['category']));
$this->validSource($sourceType);
$hash = hash('sha256', json_encode($sourceType === 'external_payment' ? [$payment, $data] : [$sourceType, $payment, $data], JSON_THROW_ON_ERROR));
return DB::transaction(function () use ($actor, $payment, $data, $hash, $sourceType) {
$actor = $this->actor($actor);
abort_unless($actor->hasFunctions(['finance']), 403);
if ($sourceType === 'external_payment') {
ExternalPayment::query()->whereKey($payment)->lockForUpdate()->firstOrFail();
} else {
abort_unless(DB::table('ps_allocations')->where(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0])
->where('id', $payment)->lockForUpdate()->first() !== null, 404);
}
$source = $this->source($actor, $payment, $sourceType);
$order = PurchaseOrder::query()->whereKey($source['purchase_order_id'])->firstOrFail();
app(OrderPartsAccess::class)->assertProcess($actor, $order, true);
abort_unless(hash_equals($source['fingerprint'], $data['fingerprint']), 409, 'As origens mudaram. Reveja a factura e o pagamento.');
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
if ($retry !== null) {
abort_unless($retry->kind === 'expense_allocation' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
return $retry;
}
$old = $this->current($payment, $sourceType);
abort_unless(($old->version ?? 0) === $data['version'], 409, 'A imputação mudou. Reveja a versão actual.');
$total = BigInteger::zero();
$allocations = [];
foreach ($data['allocations'] as $row) {
if (! in_array($row['category'], $source['categories'], true)) {
throw ValidationException::withMessages(['allocations' => 'Seleccione apenas categorias das linhas desta factura.']);
}
$minor = BigDecimal::of($row['amount'])->multipliedBy(100)->toBigInteger();
$total = $total->plus($minor);
$allocations[] = ['category' => $row['category'], 'amount_minor' => (string) $minor];
}
if (! $total->isEqualTo($source['payment']['amount_minor'])) {
throw ValidationException::withMessages(['allocations' => 'A soma das imputações deve corresponder exactamente ao pagamento confirmado.']);
}
$record = SupplyRecord::query()->create(['tenant_id' => $actor->tenant_id, 'kind' => 'expense_allocation',
'record_key' => $old->record_key ?? (string) Str::uuid(), 'version' => ($old->version ?? 0) + 1, 'state' => 'allocated', 'created_by' => $actor->id,
'data' => [...($sourceType === 'common_allocation' ? ['source_type' => 'common_allocation'] : []),
'payment_id' => $payment, 'invoice_id' => $source['invoice_id'], 'currency' => $source['payment']['currency'],
'amount_minor' => (string) $total, 'allocations' => $allocations], 'snapshot' => $source,
'reason' => trim($data['reason']), 'operation_key' => $data['operation_key'], 'input_hash' => $hash, 'created_at' => now()]);
app(RequisitionWorkflow::class)->audit($actor, 'expense.allocation_recorded', null, $old?->toArray(), ['record' => $record->toArray()]);
return $record;
});
}
}