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

100 lines
5.7 KiB
PHP

<?php
namespace App\Services;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\User;
use Brick\Math\BigInteger;
use DomainException;
use Illuminate\Support\Facades\DB;
/** Original confirmed common allocations, not copies of native payment history. No bank references. */
final class CommonPaymentFacts
{
/** @return array<string,mixed> */
public function source(User $actor, int $allocation): array
{
$adapter = app(SupplierPayables::class);
$context = $adapter->readContext($actor);
$scope = $context['scope'];
abort_unless(app(StandaloneRuntime::class)->enabled() && DB::getSchemaBuilder()->hasTable('ps_allocations'), 503);
$q = fn (string $table) => DB::table($table)->where($scope);
$row = $q('ps_allocations')->where('id', $allocation)->first();
abort_unless($row !== null, 404);
if ($q('ps_reversals')->where('allocation_id', $allocation)->exists()) {
throw new DomainException('Afectação revertida; conserve a imputação histórica.');
}
$obligation = $q('pa_obligations')->where('id', $row->obligation_id)->first();
$origin = $obligation === null ? null : $q('pa_sources')->where('id', $obligation->source_id)->first();
if ($origin === null) {
throw new DomainException('Origem da afectação incompleta.');
}
$invoice = Invoice::query()->whereIn('purchase_order_id', PurchaseOrder::query()->visibleTo($actor)->select('id'))
->whereKey($origin->local_source_id)->firstOrFail();
$position = $adapter->readEngine($actor)->positionForSource($invoice->id);
$payment = $q('ps_payments')->where('id', $row->payment_id)->first();
$decision = $q('ps_allocation_decisions')->where('id', $row->decision_id)->first();
$proposal = $decision === null ? null : $q('ps_proposals')->where('id', $decision->proposal_id)->first();
$confirmation = $q('ps_payment_decisions')->where('payment_id', $row->payment_id)->where('decision', 'confirmed')->first();
if ($position === null || $position['source_conflict'] || (int) $position['id'] !== (int) $row->obligation_id
|| $position['source_revision'] !== $row->source_revision || $payment === null || $decision === null || $proposal === null || $confirmation === null
|| $decision->decision !== 'confirmed' || (int) $proposal->payment_id !== (int) $row->payment_id
|| $decision->actor_id === $proposal->prepared_by || $decision->person === $proposal->prepared_person
|| $confirmation->actor_id === $payment->prepared_by || $confirmation->person === $payment->prepared_person
|| (int) $row->amount_minor <= 0 || $payment->currency !== 'MZN') {
throw new DomainException('Confirmação ou revisão da afectação indeterminada.');
}
$events = [];
foreach (['supplier_payment.confirmed' => $confirmation, 'supplier_allocation.confirmed' => $decision] as $kind => $evidence) {
$event = $q('ps_events')->where('kind', $kind)->where('actor_id', $evidence->actor_id)
->where('payload->decision_id', $evidence->id)->first(['id']);
if ($event === null) {
throw new DomainException('Confirmação sem evento financeiro compatível.');
}
$events[] = (int) $event->id;
}
return ['id' => $allocation, 'source_type' => 'common_allocation', 'common_payment_id' => (int) $row->payment_id,
'invoice_id' => $invoice->id, 'status' => 'confirmed', 'amount_minor' => (int) $row->amount_minor,
'currency' => 'MZN', 'reviewed_at' => $confirmation->created_at, 'reviewed_by' => (int) $confirmation->actor_id,
'source_revision' => $row->source_revision, 'allocation_decision_id' => (int) $decision->id,
'allocation_confirmed_at' => $decision->created_at, 'confirmation_id' => (int) $confirmation->id, 'event_ids' => $events];
}
/** @return list<array<string,mixed>> */
public function forInvoice(User $actor, int $invoice): array
{
if (! app(StandaloneRuntime::class)->enabled() || ! DB::getSchemaBuilder()->hasTable('ps_allocations')) {
return [];
}
$adapter = app(SupplierPayables::class);
$context = $adapter->readContext($actor);
$scope = $context['scope'];
$position = $adapter->readEngine($actor)->positionForSource($invoice);
if ($position === null) {
return [];
}
if ($position['source_conflict']) {
throw new DomainException('Origem financeira alterada; despesa indeterminada.');
}
$payments = DB::table('ps_payments')->where($scope)->where('obligation_id', $position['id'])
->whereIn('id', DB::table('ps_payment_decisions')->where($scope)->where('decision', 'confirmed')->select('payment_id'))->get();
foreach ($payments as $payment) {
$assigned = DB::table('ps_allocations')->where($scope)->where('payment_id', $payment->id)
->whereNotIn('id', DB::table('ps_reversals')->where($scope)->select('allocation_id'))->sum('amount_minor');
if (! BigInteger::of((string) $assigned)->isEqualTo((string) $payment->amount_minor)) {
throw new DomainException('Pagamento confirmado com afectação documental incompleta; despesa por factura indeterminada.');
}
}
$rows = DB::table('ps_allocations')->where($scope)->where('obligation_id', $position['id'])
->whereNotIn('id', DB::table('ps_reversals')->where($scope)->select('allocation_id'))->orderBy('id')->get(['id']);
$facts = [];
foreach ($rows as $row) {
$facts[] = $this->source($actor, (int) $row->id);
}
return $facts;
}
}