64 lines
2.5 KiB
PHP
64 lines
2.5 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 Illuminate\Database\Eloquent\Builder;
|
|
|
|
/** Aggregate positions supplied by the common financial engine, never calculate a ledger. */
|
|
class ProcurementPayableInsights
|
|
{
|
|
/** @param Builder<Requisition> $requests
|
|
* @return array<string,mixed>|null
|
|
*/
|
|
public function build(User $actor, Builder $requests): ?array
|
|
{
|
|
$adapter = app(SupplierPayables::class);
|
|
if (! $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]) || ! $adapter->can($actor, 'view')) {
|
|
return null;
|
|
}
|
|
$engine = $adapter->readEngine($actor);
|
|
$orders = PurchaseOrder::query()->visibleTo($actor)->whereIn('requisition_id', (clone $requests)->reorder()->select('id'));
|
|
$invoices = Invoice::query()->whereIn('purchase_order_id', $orders->select('id'));
|
|
$counts = ['invoices' => 0, 'recognised' => 0, 'unrecognised' => 0, 'indeterminate' => 0];
|
|
$currencies = [];
|
|
$fields = ['principal_minor', 'confirmed_payments_minor', 'allocated_payments_minor', 'balance_minor'];
|
|
foreach ($invoices->select('id')->lazyById(200) as $invoice) {
|
|
$counts['invoices']++;
|
|
try {
|
|
$position = $engine->positionForSource($invoice->id);
|
|
} catch (\DomainException) {
|
|
$counts['indeterminate']++;
|
|
|
|
continue;
|
|
}
|
|
if ($position === null) {
|
|
$counts['unrecognised']++;
|
|
|
|
continue;
|
|
}
|
|
$currency = $position['currency'] ?? null;
|
|
if (($position['source_conflict'] ?? true) !== false || ($position['balance_minor'] ?? null) === null
|
|
|| ! is_string($currency) || ! preg_match('/^[A-Z]{3}$/D', $currency)) {
|
|
$counts['indeterminate']++;
|
|
|
|
continue;
|
|
}
|
|
$counts['recognised']++;
|
|
$currencies[$currency] ??= ['currency' => $currency, 'count' => 0, ...array_fill_keys($fields, '0')];
|
|
$currencies[$currency]['count']++;
|
|
foreach ($fields as $field) {
|
|
$currencies[$currency][$field] = (string) BigInteger::of($currencies[$currency][$field])->plus($position[$field]);
|
|
}
|
|
}
|
|
ksort($currencies);
|
|
|
|
return ['method' => 'native_payable_positions_v1', 'coverage' => $counts, 'currencies' => array_values($currencies)];
|
|
}
|
|
}
|