119 lines
7.0 KiB
PHP
119 lines
7.0 KiB
PHP
<?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, ?int $supplierPage = 1, ?int $categoryPage = 1): ?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)->forRequisitions($requests);
|
|
$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 = [];
|
|
$suppliers = [];
|
|
$categoryCoverage = ['allocated' => 0, 'unallocated' => 0, 'indeterminate' => 0];
|
|
$categories = [];
|
|
$unassigned = [];
|
|
foreach ($invoices->select(['id', 'supplier_id', 'snapshot'])->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']);
|
|
$key = $invoice->getAttribute('supplier_id').':'.$currency;
|
|
$name = $invoice->snapshot['supplier']['name'] ?? null;
|
|
$suppliers[$key] ??= ['supplier_id' => (int) $invoice->getAttribute('supplier_id'),
|
|
'supplier_name' => is_string($name) && trim($name) !== '' ? $name : 'Fornecedor #'.$invoice->getAttribute('supplier_id'),
|
|
'currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
|
|
$suppliers[$key]['count']++;
|
|
$suppliers[$key]['amount_minor'] = (string) BigInteger::of($suppliers[$key]['amount_minor'])->plus($payment['amount_minor']);
|
|
$attribution = app(ExpenseAllocations::class)->projection($actor, $payment['id']);
|
|
$categoryCoverage[$attribution['state']]++;
|
|
if ($attribution['state'] === 'allocated') {
|
|
foreach ($attribution['allocations'] as $allocation) {
|
|
if ($allocation['amount_minor'] === '0') {
|
|
continue;
|
|
}
|
|
$categoryKey = json_encode([$allocation['category'], $currency], JSON_THROW_ON_ERROR);
|
|
$categories[$categoryKey] ??= ['category' => $allocation['category'], 'currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
|
|
$categories[$categoryKey]['count']++;
|
|
$categories[$categoryKey]['amount_minor'] = (string) BigInteger::of($categories[$categoryKey]['amount_minor'])->plus($allocation['amount_minor']);
|
|
}
|
|
} else {
|
|
$unassignedKey = $currency.':'.$attribution['state'];
|
|
$unassigned[$unassignedKey] ??= ['state' => $attribution['state'], 'currency' => $currency, 'count' => 0, 'amount_minor' => '0'];
|
|
$unassigned[$unassignedKey]['count']++;
|
|
$unassigned[$unassignedKey]['amount_minor'] = (string) BigInteger::of($unassigned[$unassignedKey]['amount_minor'])->plus($payment['amount_minor']);
|
|
}
|
|
$coverage['confirmed_payments']++;
|
|
}
|
|
}
|
|
ksort($currencies);
|
|
$suppliers = array_values($suppliers);
|
|
usort($suppliers, fn ($a, $b) => ($a['supplier_id'] <=> $b['supplier_id']) ?: strcmp($a['currency'], $b['currency']));
|
|
$supplierGroups = count($suppliers);
|
|
$lastPage = max(1, (int) ceil($supplierGroups / 20));
|
|
$page = $supplierPage === null ? 1 : max(1, min($lastPage, $supplierPage));
|
|
$categories = array_values($categories);
|
|
usort($categories, fn ($a, $b) => strcmp($a['category'], $b['category']) ?: strcmp($a['currency'], $b['currency']));
|
|
$lastCategoryPage = max(1, (int) ceil(count($categories) / 20));
|
|
$currentCategoryPage = $categoryPage === null ? 1 : max(1, min($lastCategoryPage, $categoryPage));
|
|
ksort($unassigned);
|
|
|
|
return ['method' => 'audited_original_confirmed_payments_v1', 'from' => $from, 'to' => $to,
|
|
'coverage' => $coverage, 'currencies' => array_values($currencies),
|
|
'suppliers' => ['data' => $supplierPage === null ? $suppliers : array_slice($suppliers, ($page - 1) * 20, 20),
|
|
'total' => $supplierGroups, 'current_page' => $page, 'last_page' => $lastPage],
|
|
'category_attribution' => ['coverage' => $categoryCoverage, 'unassigned' => array_values($unassigned),
|
|
'groups' => ['data' => $categoryPage === null ? $categories : array_slice($categories, ($currentCategoryPage - 1) * 20, 20),
|
|
'total' => count($categories), 'current_page' => $currentCategoryPage, 'last_page' => $lastCategoryPage]]];
|
|
}
|
|
}
|