commit compras2 2911
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-11-29 10:48:22 +02:00
parent 448948a487
commit 7da8d6c87a
64 changed files with 2538 additions and 288 deletions
+69 -24
View File
@@ -9,6 +9,7 @@ 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;
@@ -22,6 +23,11 @@ final class ExpenseAllocations
{
$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'
@@ -29,14 +35,27 @@ final class ExpenseAllocations
}
/** @return array<string,mixed> */
public function source(User $actor, int $id): array
public function source(User $actor, int $id, string $sourceType = 'external_payment'): array
{
$payment = ExternalPayment::query()->whereKey($id)->firstOrFail();
$invoice = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))->whereKey($payment->invoice_id)->firstOrFail();
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.');
$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'])
@@ -70,15 +89,33 @@ final class ExpenseAllocations
return $actor;
}
public function current(int $payment): ?SupplyRecord
private function validSource(string $sourceType): void
{
return SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)->latest('version')->first();
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): array
public function projection(User $actor, int $payment, string $sourceType = 'external_payment'): array
{
$record = $this->current($payment);
$record = $this->current($payment, $sourceType);
if ($record === null) {
return ['state' => 'unallocated', 'allocations' => []];
}
@@ -86,7 +123,7 @@ final class ExpenseAllocations
return ['state' => 'indeterminate', 'allocations' => []];
}
try {
$source = $this->source($actor, $payment);
$source = $this->source($actor, $payment, $sourceType);
} catch (HttpExceptionInterface $error) {
if (! in_array($error->getStatusCode(), [404, 409], true)) {
throw $error;
@@ -109,25 +146,26 @@ final class ExpenseAllocations
}
/** @return array<string,mixed> */
public function workspace(User $actor, int $payment): array
public function workspace(User $actor, int $payment, string $sourceType = 'external_payment'): array
{
return DB::transaction(function () use ($actor, $payment) {
return DB::transaction(function () use ($actor, $payment, $sourceType) {
$actor = $this->actor($actor);
$source = $this->source($actor, $payment);
$current = $this->current($payment);
$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' => SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)->latest('version')->paginate(15)->withQueryString()->through($row),
'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): SupplyRecord
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',
@@ -136,13 +174,19 @@ final class ExpenseAllocations
$data['operation_key'] = strtolower($data['operation_key']);
$data['version'] = (int) $data['version'];
usort($data['allocations'], fn ($a, $b) => strcmp($a['category'], $b['category']));
$hash = hash('sha256', json_encode([$payment, $data], JSON_THROW_ON_ERROR));
$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) {
return DB::transaction(function () use ($actor, $payment, $data, $hash, $sourceType) {
$actor = $this->actor($actor);
abort_unless($actor->hasFunctions(['finance']), 403);
ExternalPayment::query()->whereKey($payment)->lockForUpdate()->firstOrFail();
$source = $this->source($actor, $payment);
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.');
@@ -152,7 +196,7 @@ final class ExpenseAllocations
return $retry;
}
$old = $this->current($payment);
$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 = [];
@@ -169,7 +213,8 @@ final class ExpenseAllocations
}
$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' => ['payment_id' => $payment, 'invoice_id' => $source['invoice_id'], 'currency' => $source['payment']['currency'],
'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()]);