commit compras 2711
tests / ci (push) Waiting to run

This commit is contained in:
2026-11-27 13:49:31 +02:00
parent dc73540558
commit e709d900d1
81 changed files with 5352 additions and 107 deletions
@@ -0,0 +1,74 @@
<?php
namespace App\Services;
use App\Enums\PurchasingRole;
use App\Models\Invoice;
use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\User;
use Brick\Math\BigInteger;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
/** Read confirmed original payments, never sum imported financial copies. */
class ProcurementPaymentInsights
{
/** @param Builder<Requisition> $requests
* @return array<string,mixed>|null
*/
public function build(User $actor, Builder $requests, ?string $from, ?string $to): ?array
{
$adapter = app(SupplierPayables::class);
if (! $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) || ! $adapter->can($actor, 'view')) {
return null;
}
$adapter->readContext($actor);
$start = $from === null ? null : CarbonImmutable::parse($from, config('app.timezone'))->startOfDay();
$end = $to === null ? null : CarbonImmutable::parse($to, config('app.timezone'))->addDay()->startOfDay();
$orders = PurchaseOrder::query()->visibleTo($actor)->whereIn('requisition_id', (clone $requests)->reorder()->select('id'));
$invoices = Invoice::query()->where('tenant_id', $actor->tenant_id)->whereIn('purchase_order_id', $orders->select('id'));
$coverage = ['invoices' => 0, 'indeterminate' => 0, 'confirmed_payments' => 0];
$currencies = [];
foreach ($invoices->select('id')->lazyById(200) as $invoice) {
$coverage['invoices']++;
$rows = [];
try {
foreach ($adapter->readPaymentHistory($actor, $invoice->id) as $payment) {
if ($payment['status'] !== 'confirmed') {
continue;
}
if (! is_int($payment['amount_minor']) || $payment['amount_minor'] < 1
|| ! is_string($payment['currency']) || ! preg_match('/^[A-Z]{3}$/D', $payment['currency'])
|| ! is_string($payment['reviewed_at']) || trim($payment['reviewed_at']) === '') {
throw new \DomainException('Confirmação incompleta.');
}
try {
$date = CarbonImmutable::parse($payment['reviewed_at'], config('app.timezone'));
} catch (\Exception $error) {
throw new \DomainException('Data de confirmação indeterminada.', 0, $error);
}
if (($start !== null && $date < $start) || ($end !== null && $date >= $end)) {
continue;
}
$rows[] = $payment;
}
} catch (\DomainException) {
$coverage['indeterminate']++;
continue;
}
foreach ($rows as $payment) {
$currency = $payment['currency'];
$currencies[$currency] ??= ['currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
$currencies[$currency]['count']++;
$currencies[$currency]['amount_minor'] = (string) BigInteger::of($currencies[$currency]['amount_minor'])->plus($payment['amount_minor']);
$coverage['confirmed_payments']++;
}
}
ksort($currencies);
return ['method' => 'audited_original_confirmed_payments_v1', 'from' => $from, 'to' => $to,
'coverage' => $coverage, 'currencies' => array_values($currencies)];
}
}