@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\ExternalPayment;
|
||||
use App\Models\User;
|
||||
use App\Services\ExpenseAllocations;
|
||||
use Illuminate\Http\Request;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class ExpenseAllocationController extends Controller
|
||||
{
|
||||
public function show(Request $request, ExternalPayment $payment, ExpenseAllocations $service): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$request->validate(['page' => 'nullable|integer|min:1|max:1000000']);
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('payments/expense-allocation', $service->workspace($actor, $payment->id))->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
public function store(Request $request, ExternalPayment $payment, ExpenseAllocations $service): Response
|
||||
{
|
||||
$actor = $request->user('web');
|
||||
abort_unless($actor instanceof User, 403);
|
||||
$service->save($actor, $payment->id, $request->all());
|
||||
|
||||
return back()->with('success', 'Imputação da despesa por categoria preservada.');
|
||||
}
|
||||
}
|
||||
@@ -9,10 +9,12 @@ use App\Models\PurchaseOrder;
|
||||
use App\Models\Supplier;
|
||||
use App\Models\SupplierBankDetail;
|
||||
use App\Models\User;
|
||||
use App\Services\ExpenseAllocations;
|
||||
use App\Services\ExternalPaymentWorkflow;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\RequisitionWorkflow;
|
||||
use App\Services\SupplierBankWorkflow;
|
||||
use App\Services\SupplierPayables;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Validation\Rule;
|
||||
@@ -51,7 +53,8 @@ class ExternalPaymentController extends Controller
|
||||
'bank_id' => $bank['id'] ?? 0, 'bank_revision' => $bank['revision'] ?? 0, 'bank_state' => $approved->isNotEmpty() ? 'approved' : ($banks->first()['state'] ?? 'missing'), 'banks' => $canManage ? $banks->all() : []];
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('payments/index', ['focusPaymentId' => $focus, 'focusInvoiceId' => $focusInvoice, 'invoices' => $invoices, 'payments' => $payments, 'canManage' => $canManage])->toResponse($request);
|
||||
$response = Inertia::render('payments/index', ['focusPaymentId' => $focus, 'focusInvoiceId' => $focusInvoice, 'invoices' => $invoices, 'payments' => $payments, 'canManage' => $canManage,
|
||||
'expenseAllocationsReady' => app(ExpenseAllocations::class)->ready() && app(SupplierPayables::class)->can($actor, 'view')])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
|
||||
return $response;
|
||||
|
||||
@@ -9,6 +9,8 @@ use App\Models\Quotation;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use App\Services\OrganizationAccess;
|
||||
use App\Services\ProcurementContractInsights;
|
||||
use App\Services\ProcurementDeliveryInsights;
|
||||
use App\Services\ProcurementOperationalInsights;
|
||||
use App\Services\ProcurementPayableInsights;
|
||||
use App\Services\ProcurementPaymentInsights;
|
||||
@@ -16,6 +18,7 @@ use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
@@ -61,6 +64,10 @@ class ProcurementReportController extends Controller
|
||||
'to' => 'nullable|date_format:Y-m-d',
|
||||
'department_id' => 'nullable|integer|min:1',
|
||||
'attention' => 'nullable|in:unapproved_needed,approved_without_quotes,approved_without_order',
|
||||
'supplier_page' => 'nullable|integer|min:1|max:1000000',
|
||||
'category_page' => 'nullable|integer|min:1|max:1000000',
|
||||
'delivery_page' => 'nullable|integer|min:1|max:1000000',
|
||||
'delivery_state' => 'nullable|in:attention,all,pending_late,pending,partial_late,completed_late,completed_on_time,unknown',
|
||||
]);
|
||||
if (! empty($filters['from']) && ! empty($filters['to']) && $filters['from'] > $filters['to']) {
|
||||
throw ValidationException::withMessages(['to' => 'A data final deve ser igual ou posterior à data inicial.']);
|
||||
@@ -78,7 +85,16 @@ class ProcurementReportController extends Controller
|
||||
/** @return Builder<PurchaseOrder> */
|
||||
private function visibleOrders(User $actor): Builder
|
||||
{
|
||||
return PurchaseOrder::query()->visibleTo($actor)->whereColumn('purchase_orders.requisition_id', 'requisitions.id');
|
||||
return PurchaseOrder::query()->visibleTo($actor)->where(function ($orders) {
|
||||
$orders->whereColumn('purchase_orders.requisition_id', 'requisitions.id');
|
||||
if (Schema::hasTable('purchase_order_sources') && Schema::hasColumn('purchase_orders', 'order_key')) {
|
||||
$orders->orWhere(function ($parts) {
|
||||
$parts->whereNotNull('purchase_orders.order_key')->whereExists(fn ($source) => $source->selectRaw('1')
|
||||
->from('purchase_order_sources as report_origin')->whereColumn('report_origin.purchase_order_id', 'purchase_orders.id')
|
||||
->whereColumn('report_origin.tenant_id', 'purchase_orders.tenant_id')->whereColumn('report_origin.requisition_id', 'requisitions.id'));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $filters
|
||||
@@ -153,10 +169,13 @@ class ProcurementReportController extends Controller
|
||||
$insights = app(ProcurementOperationalInsights::class)->build($this->records(clone $query, $actor), $instant);
|
||||
|
||||
return ['records' => $records, 'counts' => $counts, 'filters' => $filters, 'departments' => $departments, 'generatedAt' => $instant->toIso8601String(), 'insights' => $insights,
|
||||
'contractInsights' => app(ProcurementContractInsights::class)->build($actor, clone $query),
|
||||
'deliveryInsights' => app(ProcurementDeliveryInsights::class)->build($actor, clone $query, $instant,
|
||||
(int) ($filters['delivery_page'] ?? 1), $filters['delivery_state'] ?? 'attention'),
|
||||
'payableInsights' => app(ProcurementPayableInsights::class)->build($actor, clone $query),
|
||||
'paymentInsights' => app(ProcurementPaymentInsights::class)->build($actor,
|
||||
$this->query($actor, array_diff_key($filters, array_flip(['from', 'to'])), $instant->toDateString()),
|
||||
$filters['from'] ?? null, $filters['to'] ?? null)];
|
||||
$filters['from'] ?? null, $filters['to'] ?? null, (int) ($filters['supplier_page'] ?? 1), (int) ($filters['category_page'] ?? 1))];
|
||||
});
|
||||
Inertia::encryptHistory();
|
||||
|
||||
@@ -186,6 +205,7 @@ class ProcurementReportController extends Controller
|
||||
fwrite($output, "\xEF\xBB\xBF");
|
||||
fputcsv($output, ['Posição actual das obrigações', 'Gerado em', $data['generated_at']], ';', '"', '');
|
||||
fputcsv($output, ['Filtros dos pedidos (data de criação)', json_encode($data['filters'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)], ';', '"', '');
|
||||
fputcsv($output, ['Âmbito documental', 'Cada factura conta uma vez se alguma origem corresponder aos filtros; posição integral sem repartição por pedido.'], ';', '"', '');
|
||||
fputcsv($output, ['Facturas autorizadas', 'Reconhecidas e determinadas', 'Por reconhecer', 'Posição indeterminada'], ';', '"', '');
|
||||
$coverage = $data['positions']['coverage'];
|
||||
fputcsv($output, [$coverage['invoices'], $coverage['recognised'], $coverage['unrecognised'], $coverage['indeterminate']], ';', '"', '');
|
||||
@@ -205,7 +225,7 @@ class ProcurementReportController extends Controller
|
||||
$actor = $this->actor($request);
|
||||
$payments = app(ProcurementPaymentInsights::class)->build($actor,
|
||||
$this->query($actor, array_diff_key($filters, array_flip(['from', 'to'])), $instant->toDateString()),
|
||||
$filters['from'] ?? null, $filters['to'] ?? null);
|
||||
$filters['from'] ?? null, $filters['to'] ?? null, null, null);
|
||||
abort_unless($payments !== null, 403);
|
||||
|
||||
return ['payments' => $payments, 'generated_at' => $instant->toIso8601String()];
|
||||
@@ -220,16 +240,92 @@ class ProcurementReportController extends Controller
|
||||
$payments = $data['payments'];
|
||||
fputcsv($output, ['Pagamentos externos confirmados pela data de confirmação', 'Gerado em', $data['generated_at']], ';', '"', '');
|
||||
fputcsv($output, ['Confirmação desde', $payments['from'] ?? '', 'Até (inclusive)', $payments['to'] ?? ''], ';', '"', '');
|
||||
fputcsv($output, ['Âmbito documental', 'Cada factura conta uma vez se alguma origem corresponder aos filtros; pagamentos integrais sem repartição por pedido.'], ';', '"', '');
|
||||
fputcsv($output, ['Facturas no âmbito', 'Históricos indeterminados excluídos', 'Pagamentos confirmados determinados'], ';', '"', '');
|
||||
fputcsv($output, array_values($payments['coverage']), ';', '"', '');
|
||||
fputcsv($output, ['Moeda', 'Pagamentos', 'Despesa (centavos)'], ';', '"', '');
|
||||
foreach ($payments['currencies'] as $row) {
|
||||
fputcsv($output, [$row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
|
||||
}
|
||||
fputcsv($output, ['Fornecedor (identificador)', 'Nome conservado na factura', 'Moeda', 'Pagamentos', 'Despesa (centavos)'], ';', '"', '');
|
||||
foreach ($payments['suppliers']['data'] as $row) {
|
||||
$name = preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $row['supplier_name']) ? "'".$row['supplier_name'] : $row['supplier_name'];
|
||||
fputcsv($output, [$row['supplier_id'], $name, $row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
|
||||
}
|
||||
fputcsv($output, ['Categoria (imputação explícita de Finanças)', 'Moeda', 'Imputações', 'Despesa (centavos)'], ';', '"', '');
|
||||
foreach ($payments['category_attribution']['groups']['data'] as $row) {
|
||||
$category = preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $row['category']) ? "'".$row['category'] : $row['category'];
|
||||
fputcsv($output, [$category, $row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
|
||||
}
|
||||
fputcsv($output, ['Imputação pendente', 'Moeda', 'Pagamentos', 'Montante (centavos)'], ';', '"', '');
|
||||
foreach ($payments['category_attribution']['unassigned'] as $row) {
|
||||
fputcsv($output, [$row['state'] === 'unallocated' ? 'Não imputada' : 'Imputação indeterminada', $row['currency'], $row['count'], $row['amount_minor']], ';', '"', '');
|
||||
}
|
||||
fclose($output);
|
||||
}, 'despesa-confirmada-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||
}
|
||||
|
||||
public function exportContracts(Request $request): Response
|
||||
{
|
||||
$data = $this->snapshot(function () use ($request): array {
|
||||
$instant = CarbonImmutable::now(config('app.timezone'));
|
||||
$filters = $this->filters($request);
|
||||
|
||||
return ['generated_at' => $instant->toIso8601String(), 'filters' => $filters,
|
||||
'contracts' => app(ProcurementContractInsights::class)->build($this->actor($request), $this->query($this->actor($request), $filters, $instant->toDateString()))];
|
||||
});
|
||||
|
||||
return response()->streamDownload(function () use ($data) {
|
||||
$output = fopen('php://output', 'w');
|
||||
if ($output === false) {
|
||||
throw new \RuntimeException('Não foi possível exportar as associações contratuais.');
|
||||
}
|
||||
fwrite($output, "\xEF\xBB\xBF");
|
||||
fputcsv($output, ['Associação contratual conservada na emissão', 'Gerado em', $data['generated_at']], ';', '"', '');
|
||||
fputcsv($output, ['Base', 'Ordens operacionais visíveis; montantes integrais das ordens, não pagamentos; não certifica conformidade.'], ';', '"', '');
|
||||
fputcsv($output, ['Filtros dos pedidos (data de criação)', json_encode($data['filters'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)], ';', '"', '');
|
||||
fputcsv($output, ['Classificação', 'Moeda', 'Ordens', 'Montante (centavos)'], ';', '"', '');
|
||||
foreach ($data['contracts']['currencies'] as $row) {
|
||||
fputcsv($output, [ProcurementContractInsights::LABELS[$row['classification']], $row['currency'] ?? 'Indeterminada', $row['count'], $row['amount_minor'] ?? 'Indeterminado'], ';', '"', '');
|
||||
}
|
||||
fclose($output);
|
||||
}, 'associacoes-contratuais-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||
}
|
||||
|
||||
public function exportDeliveries(Request $request): Response
|
||||
{
|
||||
$data = $this->snapshot(function () use ($request): array {
|
||||
$instant = CarbonImmutable::now(config('app.timezone'));
|
||||
$filters = $this->filters($request);
|
||||
|
||||
return ['filters' => $filters, 'deliveries' => app(ProcurementDeliveryInsights::class)->build($this->actor($request),
|
||||
$this->query($this->actor($request), $filters, $instant->toDateString()), $instant, null, $filters['delivery_state'] ?? 'attention')];
|
||||
});
|
||||
|
||||
return response()->streamDownload(function () use ($data) {
|
||||
$output = fopen('php://output', 'w');
|
||||
if ($output === false) {
|
||||
throw new \RuntimeException('Não foi possível exportar o acompanhamento de entregas.');
|
||||
}
|
||||
fwrite($output, "\xEF\xBB\xBF");
|
||||
$write = static function (array $cells) use ($output): void {
|
||||
fputcsv($output, array_map(fn ($cell) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', (string) $cell) ? "'".$cell : $cell, $cells), ';', '"', '');
|
||||
};
|
||||
$write(['Entregas documentadas face às datas acordadas na ordem', 'Gerado em', $data['deliveries']['generated_at']]);
|
||||
$write(['Filtros dos pedidos (data de criação)', json_encode($data['filters'], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR)]);
|
||||
$write(['Base', 'Recepções nativas não estornadas, por origem; datas desconhecidas ficam por determinar; não certifica qualidade ou culpa do fornecedor.']);
|
||||
$write(['Ordem', 'Situação', 'Linhas por receber', 'Linhas indeterminadas', 'Maior atraso documentado (dias)']);
|
||||
foreach ($data['deliveries']['records']['data'] as $row) {
|
||||
$write([$row['number'], ProcurementDeliveryInsights::LABELS[$row['state']], $row['pending_lines'], $row['unknown_lines'], $row['late_days'] ?? 'Indeterminado']);
|
||||
foreach ($row['late_lines'] as $line) {
|
||||
$write(['Linha', $line['description'], 'Data acordada', $line['promised_on'], 'Recepção integral documentada', $line['completed_on'] ?? 'Por completar',
|
||||
'Quantidade por receber', $line['pending_quantity'], $line['unit']]);
|
||||
}
|
||||
}
|
||||
fclose($output);
|
||||
}, 'entregas-compras-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
|
||||
}
|
||||
|
||||
public function export(Request $request): Response
|
||||
{
|
||||
$this->filters($request);
|
||||
|
||||
@@ -69,6 +69,24 @@ class PurchaseOrder extends Model
|
||||
}
|
||||
}
|
||||
|
||||
/** @param Builder<PurchaseOrder> $query
|
||||
* @param Builder<Requisition> $requests
|
||||
*/
|
||||
public function scopeForRequisitions(Builder $query, Builder $requests): void
|
||||
{
|
||||
$query->where(function ($orders) use ($requests) {
|
||||
$orders->whereIn('purchase_orders.requisition_id', (clone $requests)->reorder()->select('requisitions.id'));
|
||||
if (Schema::hasTable('purchase_order_sources') && Schema::hasColumn('purchase_orders', 'order_key')) {
|
||||
$orders->orWhere(function ($parts) use ($requests) {
|
||||
$parts->whereNotNull('purchase_orders.order_key')->whereExists(fn ($source) => $source->selectRaw('1')
|
||||
->from('purchase_order_sources as report_origin')->whereColumn('report_origin.purchase_order_id', 'purchase_orders.id')
|
||||
->whereColumn('report_origin.tenant_id', 'purchase_orders.tenant_id')
|
||||
->whereIn('report_origin.requisition_id', (clone $requests)->reorder()->select('requisitions.id')));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** @param Builder<PurchaseOrder> $query */
|
||||
public function scopeOperational(Builder $query): void
|
||||
{
|
||||
|
||||
@@ -115,7 +115,7 @@ final class AgreementOrderLimits
|
||||
public function freeze(User $actor, Quotation $quote, Requisition $request, array $lines, array $bindings, array $additionalRequests = []): array
|
||||
{
|
||||
if ($bindings === []) {
|
||||
return [];
|
||||
return ['agreement_order_input_hash' => hash('sha256', json_encode([], JSON_THROW_ON_ERROR)), 'agreement_bindings' => []];
|
||||
}
|
||||
abort_unless($this->ready() && Schema::hasTable('supply_records'), 503, 'Limites por ordem preparados apenas em QA isolada.');
|
||||
abort_unless($this->canRead($actor), 403);
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ExternalPayment;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\SupplyRecord;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Brick\Math\BigInteger;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
|
||||
|
||||
/** Explicit analytical attribution; never changes a payment, liability or financial journal. */
|
||||
final class ExpenseAllocations
|
||||
{
|
||||
public function ready(): bool
|
||||
{
|
||||
$db = DB::connection();
|
||||
|
||||
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'
|
||||
&& preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $db->getDatabaseName())));
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function source(User $actor, int $id): 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.');
|
||||
}
|
||||
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'])
|
||||
&& preg_match('/^[A-Z]{3}$/D', $facts['currency']) && is_string($facts['reviewed_at']) && trim($facts['reviewed_at']) !== ''
|
||||
&& is_int($facts['reviewed_by']) && $facts['reviewed_by'] > 0, 409, 'A confirmação tem dados indeterminados; conserve os originais para conferência.');
|
||||
$categories = [];
|
||||
foreach ($invoice->items()->orderBy('id')->get() as $item) {
|
||||
$line = DB::table('purchase_order_items')->where('tenant_id', $actor->tenant_id)->where('purchase_order_id', $invoice->purchase_order_id)
|
||||
->where('id', $item->purchase_order_item_id)->first(['category']);
|
||||
abort_unless($line !== null && is_string($line->category) && trim($line->category) !== '', 409,
|
||||
'Há linhas da factura sem categoria documental determinada.');
|
||||
$categories[$line->category] = $line->category;
|
||||
}
|
||||
$categories = array_values($categories);
|
||||
sort($categories, SORT_STRING);
|
||||
abort_unless($categories !== [], 409, 'A factura exige linhas com categorias documentais para esta imputação.');
|
||||
$source = ['payment' => $facts, 'invoice_id' => $invoice->id, 'invoice_number' => $invoice->getAttribute('number'),
|
||||
'purchase_order_id' => $invoice->purchase_order_id, 'categories' => $categories];
|
||||
|
||||
return [...$source, 'fingerprint' => hash('sha256', json_encode($source, JSON_THROW_ON_ERROR))];
|
||||
}
|
||||
|
||||
private function actor(User $actor): User
|
||||
{
|
||||
abort_unless($this->ready(), 503);
|
||||
app(ConflictGuard::class)->lockCompany($actor);
|
||||
$actor = app(CurrentActor::class)->lock($actor);
|
||||
abort_if(app(OrganizationAccess::class)->maintenanceOnly($actor), 403);
|
||||
abort_unless($actor->hasFunctions(['admin', 'finance']) && app(SupplierPayables::class)->can($actor, 'view'), 403);
|
||||
|
||||
return $actor;
|
||||
}
|
||||
|
||||
public function current(int $payment): ?SupplyRecord
|
||||
{
|
||||
return SupplyRecord::query()->where('kind', 'expense_allocation')->where('data->payment_id', $payment)->latest('version')->first();
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function projection(User $actor, int $payment): array
|
||||
{
|
||||
$record = $this->current($payment);
|
||||
if ($record === null) {
|
||||
return ['state' => 'unallocated', 'allocations' => []];
|
||||
}
|
||||
if (! $this->ready()) {
|
||||
return ['state' => 'indeterminate', 'allocations' => []];
|
||||
}
|
||||
try {
|
||||
$source = $this->source($actor, $payment);
|
||||
} catch (HttpExceptionInterface $error) {
|
||||
if (! in_array($error->getStatusCode(), [404, 409], true)) {
|
||||
throw $error;
|
||||
}
|
||||
|
||||
return ['state' => 'indeterminate', 'allocations' => []];
|
||||
}
|
||||
if (($record->snapshot['fingerprint'] ?? '') !== $source['fingerprint']) {
|
||||
return ['state' => 'indeterminate', 'allocations' => []];
|
||||
}
|
||||
$audit = DB::table('audit_logs')->where('tenant_id', $actor->tenant_id)->where('user_id', $record->created_by)
|
||||
->where('action', 'expense.allocation_recorded')->where('after->record->id', $record->id)->latest('id')->value('after');
|
||||
$saved = is_string($audit) ? (json_decode($audit, true, 64, JSON_THROW_ON_ERROR)['record'] ?? null) : null;
|
||||
if (! is_array($saved) || ($saved['data'] ?? null) !== $record->data || ($saved['snapshot'] ?? null) !== $record->snapshot
|
||||
|| ($saved['version'] ?? null) !== $record->version || ($saved['input_hash'] ?? null) !== $record->input_hash) {
|
||||
return ['state' => 'indeterminate', 'allocations' => []];
|
||||
}
|
||||
|
||||
return ['state' => 'allocated', 'allocations' => $record->data['allocations']];
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
public function workspace(User $actor, int $payment): array
|
||||
{
|
||||
return DB::transaction(function () use ($actor, $payment) {
|
||||
$actor = $this->actor($actor);
|
||||
$source = $this->source($actor, $payment);
|
||||
$current = $this->current($payment);
|
||||
$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),
|
||||
'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
|
||||
{
|
||||
$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',
|
||||
'allocations' => 'required|array|list|min:1|max:100', 'allocations.*' => 'array:category,amount',
|
||||
'allocations.*.category' => 'required|string|max:255|distinct:strict', 'allocations.*.amount' => ['required', 'string', 'regex:/^\d{1,12}(\.\d{1,2})?$/D']])->validate();
|
||||
$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));
|
||||
|
||||
return DB::transaction(function () use ($actor, $payment, $data, $hash) {
|
||||
$actor = $this->actor($actor);
|
||||
abort_unless($actor->hasFunctions(['finance']), 403);
|
||||
ExternalPayment::query()->whereKey($payment)->lockForUpdate()->firstOrFail();
|
||||
$source = $this->source($actor, $payment);
|
||||
$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.');
|
||||
$retry = SupplyRecord::query()->where('operation_key', $data['operation_key'])->first();
|
||||
if ($retry !== null) {
|
||||
abort_unless($retry->kind === 'expense_allocation' && $retry->created_by === $actor->id && hash_equals($retry->input_hash, $hash), 409);
|
||||
|
||||
return $retry;
|
||||
}
|
||||
$old = $this->current($payment);
|
||||
abort_unless(($old->version ?? 0) === $data['version'], 409, 'A imputação mudou. Reveja a versão actual.');
|
||||
$total = BigInteger::zero();
|
||||
$allocations = [];
|
||||
foreach ($data['allocations'] as $row) {
|
||||
if (! in_array($row['category'], $source['categories'], true)) {
|
||||
throw ValidationException::withMessages(['allocations' => 'Seleccione apenas categorias das linhas desta factura.']);
|
||||
}
|
||||
$minor = BigDecimal::of($row['amount'])->multipliedBy(100)->toBigInteger();
|
||||
$total = $total->plus($minor);
|
||||
$allocations[] = ['category' => $row['category'], 'amount_minor' => (string) $minor];
|
||||
}
|
||||
if (! $total->isEqualTo($source['payment']['amount_minor'])) {
|
||||
throw ValidationException::withMessages(['allocations' => 'A soma das imputações deve corresponder exactamente ao pagamento confirmado.']);
|
||||
}
|
||||
$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'],
|
||||
'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()]);
|
||||
|
||||
return $record;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigInteger;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
/** Documentary association at issuance, never a retrospective legal compliance decision. */
|
||||
final class ProcurementContractInsights
|
||||
{
|
||||
public const LABELS = ['contract' => 'Todas as linhas com contrato associado', 'partial' => 'Parte das linhas com contrato associado',
|
||||
'without_contract' => 'Sem contrato associado na emissão', 'unknown' => 'Associação por determinar'];
|
||||
|
||||
/** @param Builder<Requisition> $requests
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function build(User $actor, Builder $requests): array
|
||||
{
|
||||
$coverage = array_fill_keys(['contract', 'partial', 'without_contract', 'unknown'], 0);
|
||||
$currencies = [];
|
||||
$orders = PurchaseOrder::query()->visibleTo($actor)->operational()->forRequisitions($requests)
|
||||
->with('items:id,purchase_order_id,requisition_item_id');
|
||||
foreach ($orders->lazyById(200) as $order) {
|
||||
$state = $this->classification($order);
|
||||
$coverage[$state]++;
|
||||
$currency = $order->getAttribute('currency');
|
||||
$minor = $order->getAttribute('total_minor');
|
||||
if (! is_string($currency) || ! preg_match('/^[A-Z]{3}$/D', $currency) || ! preg_match('/^\d+$/D', (string) $minor)) {
|
||||
// Missing amounts are not converted to a zero-valued order.
|
||||
$currencies['unknown:'.$state] ??= ['currency' => null, 'classification' => $state, 'count' => 0, 'amount_minor' => null];
|
||||
$currencies['unknown:'.$state]['count']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
$key = $currency.':'.$state;
|
||||
$currencies[$key] ??= ['currency' => $currency, 'classification' => $state, 'count' => 0, 'amount_minor' => '0'];
|
||||
$currencies[$key]['count']++;
|
||||
$currencies[$key]['amount_minor'] = (string) BigInteger::of($currencies[$key]['amount_minor'])->plus($minor);
|
||||
}
|
||||
ksort($currencies);
|
||||
|
||||
return ['method' => 'frozen_order_contract_association_v1', 'coverage' => $coverage, 'currencies' => array_values($currencies)];
|
||||
}
|
||||
|
||||
private function classification(PurchaseOrder $order): string
|
||||
{
|
||||
$snapshot = $order->snapshot;
|
||||
if (! is_string($snapshot['agreement_order_input_hash'] ?? null) || ! preg_match('/^[a-f0-9]{64}$/D', $snapshot['agreement_order_input_hash'])
|
||||
|| ! is_array($snapshot['agreement_bindings'] ?? null) || $order->items->isEmpty()) {
|
||||
return 'unknown';
|
||||
}
|
||||
$contracts = 0;
|
||||
foreach ($order->items as $line) {
|
||||
$binding = $snapshot['agreement_bindings'][$line->getAttribute('requisition_item_id')] ?? null;
|
||||
if ($binding !== null && ! is_array($binding)) {
|
||||
return 'unknown';
|
||||
}
|
||||
if ($binding === null || ! isset($binding['contract_id'])) {
|
||||
continue;
|
||||
}
|
||||
if (($binding['schema'] ?? null) !== 'sgc.agreement.order_limit.v1'
|
||||
|| ! is_int($binding['contract_id']) || $binding['contract_id'] < 1
|
||||
|| ($binding['contract']['id'] ?? null) !== $binding['contract_id']
|
||||
|| ! is_int($binding['contract']['version'] ?? null) || $binding['contract']['version'] < 1) {
|
||||
return 'unknown';
|
||||
}
|
||||
$contracts++;
|
||||
}
|
||||
|
||||
return $contracts === 0 ? 'without_contract' : ($contracts === $order->items->count() ? 'contract' : 'partial');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\GoodsReceiptItem;
|
||||
use App\Models\PurchaseOrder;
|
||||
use App\Models\Requisition;
|
||||
use App\Models\User;
|
||||
use Brick\Math\BigDecimal;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
/** Native documentary receipt dates against each origin's frozen promised date. */
|
||||
final class ProcurementDeliveryInsights
|
||||
{
|
||||
public const LABELS = ['pending_late' => 'Por receber depois da data acordada', 'pending' => 'Por receber, dentro da data acordada',
|
||||
'partial_late' => 'Recepção parcial tardia; restante em prazo', 'completed_late' => 'Recepção integral depois da data acordada',
|
||||
'completed_on_time' => 'Recepção integral no prazo acordado', 'unknown' => 'Datas ou quantidades por determinar'];
|
||||
|
||||
private function date(mixed $value): ?string
|
||||
{
|
||||
if (! is_string($value) || ! preg_match('/^\d{4}-\d{2}-\d{2}$/D', $value)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$date = CarbonImmutable::createFromFormat('!Y-m-d', $value, config('app.timezone'));
|
||||
} catch (\InvalidArgumentException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $date !== null && $date->format('Y-m-d') === $value ? $value : null;
|
||||
}
|
||||
|
||||
private function promised(PurchaseOrder $order, int $item): ?string
|
||||
{
|
||||
if (! OrderPartsAccess::applies($order)) {
|
||||
return $this->date($order->snapshot['award']['delivery_date'] ?? null);
|
||||
}
|
||||
$dates = [];
|
||||
foreach ($order->snapshot['order_parts']['sources'] ?? [] as $source) {
|
||||
foreach ($source['items'] ?? [] as $line) {
|
||||
if (($line['requisition_item_id'] ?? null) === $item) {
|
||||
$dates[] = $this->date($source['award_terms']['delivery_date'] ?? null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count($dates) === 1 ? $dates[0] : null;
|
||||
}
|
||||
|
||||
/** @param Builder<Requisition> $requests
|
||||
* @return array<string,mixed>
|
||||
*/
|
||||
public function build(User $actor, Builder $requests, CarbonImmutable $instant, ?int $page = 1, string $view = 'attention'): array
|
||||
{
|
||||
$today = $instant->setTimezone(config('app.timezone'))->toDateString();
|
||||
$coverage = array_fill_keys(array_keys(self::LABELS), 0);
|
||||
$records = [];
|
||||
$pendingLines = $unknownLines = 0;
|
||||
$reversed = array_keys(app(InventoryReversals::class)->corrections('receipt'));
|
||||
foreach (PurchaseOrder::query()->visibleTo($actor)->operational()->forRequisitions($requests)->with('items')->lazyById(100) as $order) {
|
||||
app(OrderPartsAccess::class)->origins($order);
|
||||
$progress = app(ReceiptWorkflow::class)->progress($order);
|
||||
$items = $order->items->keyBy('id');
|
||||
$receipts = GoodsReceiptItem::query()->join('goods_receipts as gr', 'gr.id', '=', 'goods_receipt_items.goods_receipt_id')
|
||||
->where('gr.tenant_id', $actor->tenant_id)->where('gr.purchase_order_id', $order->id)->whereNotIn('goods_receipt_items.id', $reversed)
|
||||
->orderBy('gr.received_on')->orderBy('gr.id')->orderBy('goods_receipt_items.id')
|
||||
->get(['goods_receipt_items.id', 'goods_receipt_items.purchase_order_item_id', 'goods_receipt_items.received_milli', 'gr.received_on'])->groupBy('purchase_order_item_id');
|
||||
$pending = $unknown = $latePending = $lateCompleted = $maxDays = 0;
|
||||
$details = [];
|
||||
foreach ($progress['lines'] as $line) {
|
||||
$item = $items->get($line['id']);
|
||||
$due = $item === null ? null : $this->promised($order, (int) $item->requisition_item_id);
|
||||
$quantity = 0;
|
||||
$completed = null;
|
||||
$verified = $line['ordered_milli'] > 0 && $line['received_milli'] >= 0 && $line['received_milli'] <= $line['ordered_milli'];
|
||||
foreach ($receipts->get($line['id'], collect()) as $receipt) {
|
||||
$received = $this->date($receipt->getAttribute('received_on'));
|
||||
if ($received === null || $received > $today || (int) $receipt->received_milli < 1) {
|
||||
$verified = false;
|
||||
}
|
||||
$quantity += (int) $receipt->received_milli;
|
||||
if ($quantity >= $line['ordered_milli'] && $completed === null) {
|
||||
$completed = $received;
|
||||
}
|
||||
}
|
||||
$verified = $verified && $quantity === $line['received_milli'];
|
||||
$waiting = $line['received_milli'] < $line['ordered_milli'];
|
||||
$pending += $waiting ? 1 : 0;
|
||||
if (! $verified || $due === null || (! $waiting && $completed === null)) {
|
||||
$unknown++;
|
||||
continue;
|
||||
}
|
||||
$end = $waiting ? $today : $completed;
|
||||
if ($end > $due) {
|
||||
$waiting ? $latePending++ : $lateCompleted++;
|
||||
$days = (int) CarbonImmutable::parse($due, config('app.timezone'))->diffInDays(CarbonImmutable::parse($end, config('app.timezone')));
|
||||
$maxDays = max($maxDays, $days);
|
||||
$details[] = ['id' => $line['id'], 'description' => $line['description'], 'unit' => $line['unit'], 'promised_on' => $due,
|
||||
'completed_on' => $completed, 'pending_quantity' => (string) BigDecimal::of($line['delivery_pending_milli'])->dividedBy(1000, 3)];
|
||||
}
|
||||
}
|
||||
$state = $latePending > 0 ? 'pending_late' : ($unknown > 0 || $items->isEmpty() ? 'unknown'
|
||||
: ($pending > 0 ? ($lateCompleted > 0 ? 'partial_late' : 'pending') : ($lateCompleted > 0 ? 'completed_late' : 'completed_on_time')));
|
||||
$coverage[$state]++;
|
||||
$pendingLines += $pending;
|
||||
$unknownLines += $unknown;
|
||||
$records[] = ['id' => $order->id, 'number' => $order->number, 'state' => $state, 'pending_lines' => $pending, 'unknown_lines' => $unknown,
|
||||
'late_days' => $state === 'unknown' && $maxDays === 0 ? null : $maxDays,
|
||||
'quality_pending' => $progress['state'] === 'quality_pending', 'late_lines' => $details, 'href' => '/ordens/'.$order->id];
|
||||
}
|
||||
$filtered = array_values(array_filter($records, fn ($row) => $view === 'all' || ($view === 'attention'
|
||||
? in_array($row['state'], ['pending_late', 'partial_late', 'completed_late', 'unknown'], true) : $row['state'] === $view)));
|
||||
usort($filtered, fn ($a, $b) => (($b['late_days'] ?? -1) <=> ($a['late_days'] ?? -1)) ?: ($a['id'] <=> $b['id']));
|
||||
$last = max(1, (int) ceil(count($filtered) / 20));
|
||||
$current = $page === null ? 1 : max(1, min($page, $last));
|
||||
|
||||
return ['method' => 'frozen_promised_dates_native_receipts_v1', 'generated_at' => $instant->toIso8601String(), 'view' => $view,
|
||||
'coverage' => $coverage, 'pending_lines' => $pendingLines, 'unknown_lines' => $unknownLines,
|
||||
'records' => ['data' => $page === null ? $filtered : array_slice($filtered, ($current - 1) * 20, 20),
|
||||
'total' => count($filtered), 'current_page' => $current, 'last_page' => $last]];
|
||||
}
|
||||
}
|
||||
@@ -32,8 +32,10 @@ class ProcurementEvidenceBrief
|
||||
$opening = $report['opening'];
|
||||
$add('opening', $opening === null ? 'Não consta acta de abertura neste módulo opcional.' : 'Acta de abertura na revisão '.$opening['revision'].'. '.($opening['source_changed'] ? 'Há diferenças face à base actual; a acta conserva a base original.' : 'A base coincide com os dados actuais.'),
|
||||
'records', 'Registos do processo', 'opening', $opening);
|
||||
$add('order', $report['order'] === null ? 'Não consta ordem emitida nesta consulta.' : 'Consta uma ordem emitida; a existência da ordem não comprova entrega nem pagamento.',
|
||||
'records', 'Registos do processo', 'order', $report['order']);
|
||||
$orders = $report['orders'] ?? ($report['order'] === null ? [] : [$report['order']]);
|
||||
$add('order', count($orders) > 1 ? count($orders).' ordens emitidas constam da consulta; a existência das ordens não comprova entrega nem pagamento.'
|
||||
: ($report['order'] === null ? 'Não consta ordem emitida nesta consulta.' : 'Consta uma ordem emitida; a existência da ordem não comprova entrega nem pagamento.'),
|
||||
'records', 'Registos do processo', count($orders) > 1 ? 'orders' : 'order', count($orders) > 1 ? $orders : $report['order']);
|
||||
$fulfilment = $report['fulfilment'];
|
||||
$add('receipts', count($fulfilment['receipts']).' registos de recepção constam da consulta; esta contagem não comprova execução integral.',
|
||||
'fulfilment', 'Recepção, facturas e registos de pagamento', 'fulfilment.receipts', $fulfilment['receipts']);
|
||||
|
||||
@@ -23,7 +23,7 @@ class ProcurementPayableInsights
|
||||
return null;
|
||||
}
|
||||
$engine = $adapter->readEngine($actor);
|
||||
$orders = PurchaseOrder::query()->visibleTo($actor)->whereIn('requisition_id', (clone $requests)->reorder()->select('id'));
|
||||
$orders = PurchaseOrder::query()->visibleTo($actor)->forRequisitions($requests);
|
||||
$invoices = Invoice::query()->whereIn('purchase_order_id', $orders->select('id'));
|
||||
$counts = ['invoices' => 0, 'recognised' => 0, 'unrecognised' => 0, 'indeterminate' => 0];
|
||||
$currencies = [];
|
||||
|
||||
@@ -17,7 +17,7 @@ class ProcurementPaymentInsights
|
||||
/** @param Builder<Requisition> $requests
|
||||
* @return array<string,mixed>|null
|
||||
*/
|
||||
public function build(User $actor, Builder $requests, ?string $from, ?string $to): ?array
|
||||
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')) {
|
||||
@@ -26,11 +26,15 @@ class ProcurementPaymentInsights
|
||||
$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'));
|
||||
$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 = [];
|
||||
foreach ($invoices->select('id')->lazyById(200) as $invoice) {
|
||||
$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 {
|
||||
@@ -63,12 +67,52 @@ class ProcurementPaymentInsights
|
||||
$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)];
|
||||
'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]]];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,45 +102,60 @@ class ProcurementReviewCsv
|
||||
}
|
||||
}
|
||||
$fulfilment = $report['fulfilment'];
|
||||
$limits = $report['agreement_limits'] ?? [];
|
||||
if (! is_array($limits)) {
|
||||
throw new \UnexpectedValueException('A projecção de acordos deve ser uma lista ou mapa de bases preservadas.');
|
||||
$documentOrders = $report['orders'] ?? ($report['order'] === null ? [] : [$report['order']]);
|
||||
$write(['Ordens', '', 'Registos disponíveis', count($documentOrders)]);
|
||||
foreach ($documentOrders as $documentOrder) {
|
||||
if ($documentOrder['id'] !== ($report['order']['id'] ?? null)) {
|
||||
$fields('Ordem', (string) $documentOrder['id'], $documentOrder,
|
||||
['number' => 'Referência', 'currency' => 'Moeda', 'total_minor' => 'Total (centavos)']);
|
||||
}
|
||||
if (isset($documentOrder['origins'])) {
|
||||
$fields('Ordem', (string) $documentOrder['id'], ['origins' => implode(', ', array_column($documentOrder['origins'], 'number'))], ['origins' => 'Requisições de origem']);
|
||||
}
|
||||
}
|
||||
$seen = [];
|
||||
$seenContracts = [];
|
||||
foreach ($limits as $binding) {
|
||||
if (! is_array($binding) || ! isset($binding['agreement_id']) || ! is_int($binding['agreement_id']) || $binding['agreement_id'] < 1) {
|
||||
throw new \UnexpectedValueException('Base contratual sem identidade válida.');
|
||||
$orderContexts = $report['orders'] ?? [['number' => $report['order']['number'] ?? '', 'agreement_limits' => $report['agreement_limits'] ?? []]];
|
||||
foreach ($orderContexts as $documentOrder) {
|
||||
$limits = $documentOrder['agreement_limits'] ?? [];
|
||||
if (! is_array($limits)) {
|
||||
throw new \UnexpectedValueException('A projecção de acordos deve ser uma lista ou mapa de bases preservadas.');
|
||||
}
|
||||
if (isset($seen[$binding['agreement_id']])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$binding['agreement_id']] = true;
|
||||
if (isset($binding['contract']) && is_array($binding['contract'])) {
|
||||
$contract = $binding['contract'];
|
||||
if (! isset($contract['id']) || ! is_int($contract['id']) || $contract['id'] < 1) {
|
||||
throw new \UnexpectedValueException('Contrato global sem identidade válida.');
|
||||
$seen = [];
|
||||
$seenContracts = [];
|
||||
foreach ($limits as $binding) {
|
||||
if (! is_array($binding) || ! isset($binding['agreement_id']) || ! is_int($binding['agreement_id']) || $binding['agreement_id'] < 1) {
|
||||
throw new \UnexpectedValueException('Base contratual sem identidade válida.');
|
||||
}
|
||||
if (! isset($seenContracts[$contract['id']])) {
|
||||
$seenContracts[$contract['id']] = true;
|
||||
$fields('Contrato global por ordem', (string) $contract['id'], [...$contract, 'max_order_value_minor' => $contract['max_order_value_minor'] ?? 'Não definido'], [
|
||||
'record_key' => 'Identidade do contrato', 'reference' => 'Referência', 'version' => 'Versão preservada', 'currency' => 'Moeda',
|
||||
'max_order_value_minor' => 'Limite global por ordem (centavos)', 'checked_order_value_minor' => 'Total conferido nesta ordem (centavos)',
|
||||
if (isset($seen[$binding['agreement_id']])) {
|
||||
continue;
|
||||
}
|
||||
$seen[$binding['agreement_id']] = true;
|
||||
$write(['Acordo por ordem', (string) $binding['agreement_id'], 'Ordem de origem', $documentOrder['number'] ?? '']);
|
||||
if (isset($binding['contract']) && is_array($binding['contract'])) {
|
||||
$contract = $binding['contract'];
|
||||
if (! isset($contract['id']) || ! is_int($contract['id']) || $contract['id'] < 1) {
|
||||
throw new \UnexpectedValueException('Contrato global sem identidade válida.');
|
||||
}
|
||||
if (! isset($seenContracts[$contract['id']])) {
|
||||
$seenContracts[$contract['id']] = true;
|
||||
$fields('Contrato global por ordem', (string) $contract['id'], [...$contract, 'max_order_value_minor' => $contract['max_order_value_minor'] ?? 'Não definido'], [
|
||||
'record_key' => 'Identidade do contrato', 'reference' => 'Referência', 'version' => 'Versão preservada', 'currency' => 'Moeda',
|
||||
'max_order_value_minor' => 'Limite global por ordem (centavos)', 'checked_order_value_minor' => 'Total conferido nesta ordem (centavos)',
|
||||
]);
|
||||
}
|
||||
}
|
||||
$fields('Acordo por ordem', (string) $binding['agreement_id'], [...$binding,
|
||||
'basis' => 'Por ordem', 'max_order_value_minor' => $binding['max_order_value_minor'] ?? 'Não definido',
|
||||
'max_order_quantity_milli' => $binding['max_order_quantity_milli'] ?? 'Não definido'], [
|
||||
'record_key' => 'Identidade do acordo', 'version' => 'Versão preservada', 'reference' => 'Referência', 'basis' => 'Aplicação do limite',
|
||||
'currency' => 'Moeda', 'unit' => 'Unidade contratual', 'includes_tax' => 'Inclui impostos',
|
||||
'max_order_value_minor' => 'Limite por ordem (centavos)', 'max_order_quantity_milli' => 'Limite por ordem (milésimos)',
|
||||
'checked_order_value_minor' => 'Total conferido nesta ordem (centavos)', 'checked_order_quantity_milli' => 'Quantidade conferida nesta ordem (milésimos)',
|
||||
]);
|
||||
}
|
||||
}
|
||||
$fields('Acordo por ordem', (string) $binding['agreement_id'], [...$binding,
|
||||
'basis' => 'Por ordem', 'max_order_value_minor' => $binding['max_order_value_minor'] ?? 'Não definido',
|
||||
'max_order_quantity_milli' => $binding['max_order_quantity_milli'] ?? 'Não definido'], [
|
||||
'record_key' => 'Identidade do acordo', 'version' => 'Versão preservada', 'reference' => 'Referência', 'basis' => 'Aplicação do limite',
|
||||
'currency' => 'Moeda', 'unit' => 'Unidade contratual', 'includes_tax' => 'Inclui impostos',
|
||||
'max_order_value_minor' => 'Limite por ordem (centavos)', 'max_order_quantity_milli' => 'Limite por ordem (milésimos)',
|
||||
'checked_order_value_minor' => 'Total conferido nesta ordem (centavos)', 'checked_order_quantity_milli' => 'Quantidade conferida nesta ordem (milésimos)',
|
||||
]);
|
||||
}
|
||||
$write(['Recepções', '', 'Registos disponíveis', count($fulfilment['receipts'])]);
|
||||
foreach ($fulfilment['receipts'] as $receipt) {
|
||||
$fields('Recepção', (string) $receipt['id'], $receipt, ['received_on' => 'Recebida em', 'delivery_note' => 'Guia']);
|
||||
$fields('Recepção', (string) $receipt['id'], $receipt, ['received_on' => 'Recebida em', 'delivery_note' => 'Guia', 'order_number' => 'Ordem de origem']);
|
||||
}
|
||||
$write(['Execução financeira', '', 'Consulta autorizada', $fulfilment['finance_visible']]);
|
||||
if ($fulfilment['finance_visible']) {
|
||||
@@ -148,7 +163,7 @@ class ProcurementReviewCsv
|
||||
$write([$section, '', 'Registos disponíveis', count($fulfilment[$key])]);
|
||||
foreach ($fulfilment[$key] as $record) {
|
||||
$fields($section, (string) $record['id'], $record, $key === 'invoices'
|
||||
? ['number' => 'Referência', 'status' => 'Estado', 'issued_on' => 'Emitida em', 'total_minor' => 'Total (centavos)', 'currency' => 'Moeda']
|
||||
? ['number' => 'Referência', 'status' => 'Estado', 'issued_on' => 'Emitida em', 'total_minor' => 'Total (centavos)', 'currency' => 'Moeda', 'order_number' => 'Ordem de origem']
|
||||
: ['invoice_id' => 'Factura de origem', 'status' => 'Estado', 'paid_on' => 'Data informada', 'amount_minor' => 'Montante (centavos)', 'currency' => 'Moeda']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,8 @@ class ProcurementReviewReport
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
|
||||
}
|
||||
$actor = User::query()->where('tenant_id', $actor->tenant_id)->findOrFail($actor->id);
|
||||
abort_unless($actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||
abort_unless(! app(OrganizationAccess::class)->maintenanceOnly($actor)
|
||||
&& $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
|
||||
$request = Requisition::query()->visibleTo($actor)->with(['department:id,name', 'requester:id,name'])->findOrFail($requisitionId);
|
||||
$comparison = app(ProposalComparison::class)->inspect($request);
|
||||
$rows = [];
|
||||
@@ -62,12 +63,15 @@ class ProcurementReviewReport
|
||||
}
|
||||
$opening = ProposalOpening::query()->where('requisition_id', $request->id)->latest('revision')->first();
|
||||
$award = PurchaseAward::query()->where('requisition_id', $request->id)->first();
|
||||
$order = PurchaseOrder::query()->visibleTo($actor)->where('requisition_id', $request->id)->first();
|
||||
$receipts = $order ? GoodsReceipt::query()->where('purchase_order_id', $order->id)->orderBy('id')->get(['id', 'received_on', 'delivery_note'])->map(fn (GoodsReceipt $receipt) => [
|
||||
'id' => $receipt->id, 'received_on' => $receipt->received_on->format('Y-m-d'), 'delivery_note' => $receipt->delivery_note,
|
||||
])->all() : [];
|
||||
$orders = PurchaseOrder::query()->visibleTo($actor)->forRequisitions(Requisition::query()->whereKey($request->id))->orderBy('id')->get();
|
||||
$order = $orders->first(); // Retain the earlier singular projection for existing consumers.
|
||||
$orderNumbers = $orders->pluck('number', 'id');
|
||||
$receipts = GoodsReceipt::query()->whereIn('purchase_order_id', $orders->modelKeys())->orderBy('id')->get(['id', 'purchase_order_id', 'received_on', 'delivery_note'])->map(fn (GoodsReceipt $receipt) => [
|
||||
'id' => $receipt->id, 'purchase_order_id' => $receipt->purchase_order_id, 'order_number' => $orderNumbers[$receipt->purchase_order_id],
|
||||
'received_on' => $receipt->received_on->format('Y-m-d'), 'delivery_note' => $receipt->delivery_note,
|
||||
])->all();
|
||||
$financeVisible = $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Finance]);
|
||||
$invoices = $financeVisible && $order ? Invoice::query()->where('purchase_order_id', $order->id)->orderBy('id')->get(['id', 'number', 'status', 'issued_on', 'total_minor', 'snapshot']) : collect();
|
||||
$invoices = $financeVisible ? Invoice::query()->whereIn('purchase_order_id', $orders->modelKeys())->orderBy('id')->get(['id', 'purchase_order_id', 'number', 'status', 'issued_on', 'total_minor', 'snapshot']) : collect();
|
||||
$payments = $financeVisible ? ExternalPayment::query()->whereIn('invoice_id', $invoices->pluck('id'))->orderBy('id')->get(['id', 'invoice_id', 'status', 'amount_minor', 'currency', 'paid_on'])->map(fn ($payment) => [
|
||||
'id' => $payment->id, 'invoice_id' => $payment->invoice_id, 'status' => $payment->status, 'amount_minor' => (string) $payment->amount_minor, 'currency' => $payment->currency, 'paid_on' => $payment->paid_on,
|
||||
])->all() : null;
|
||||
@@ -83,10 +87,15 @@ class ProcurementReviewReport
|
||||
'opening' => $opening ? [...$opening->only(['id', 'revision', 'reference']), 'source_changed' => $opening->basis_hash !== $basis] : null,
|
||||
'award' => $award?->only(['id', 'status', 'total_minor']),
|
||||
'order' => $order?->only(['id', 'number', 'currency', 'total_minor']),
|
||||
'orders' => $orders->map(fn (PurchaseOrder $document) => [...$document->only(['id', 'number', 'currency', 'total_minor']),
|
||||
'agreement_limits' => $document->snapshot['agreement_bindings'] ?? [],
|
||||
'origins' => Requisition::query()->whereIn('id', app(OrderPartsAccess::class)->origins($document))->orderBy('id')->get(['id', 'number'])->toArray()])->all(),
|
||||
'agreement_limits' => $order?->snapshot['agreement_bindings'] ?? [],
|
||||
'fulfilment' => [
|
||||
'receipts' => $receipts, 'finance_visible' => $financeVisible,
|
||||
'invoices' => $financeVisible ? $invoices->map(fn (Invoice $invoice) => ['id' => $invoice->id, 'number' => $invoice->number, 'status' => $invoice->status, 'issued_on' => $invoice->issued_on, 'total_minor' => (string) $invoice->total_minor, 'currency' => $invoice->snapshot['currency'] ?? null])->all() : null,
|
||||
'invoices' => $financeVisible ? $invoices->map(fn (Invoice $invoice) => ['id' => $invoice->id, 'purchase_order_id' => $invoice->purchase_order_id,
|
||||
'order_number' => $orderNumbers[$invoice->purchase_order_id], 'number' => $invoice->number, 'status' => $invoice->status, 'issued_on' => $invoice->issued_on,
|
||||
'total_minor' => (string) $invoice->total_minor, 'currency' => $invoice->snapshot['currency'] ?? null])->all() : null,
|
||||
'payments' => $payments,
|
||||
],
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user