Files
compras/app/Http/Controllers/ProcurementReportController.php
T
nala d58b75c87a
tests / ci (push) Waiting to run
commit compras5 2711
2026-11-27 20:19:21 +02:00

356 lines
21 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Enums\PurchasingRole;
use App\Models\Department;
use App\Models\PurchaseOrder;
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;
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;
class ProcurementReportController extends Controller
{
private function actor(Request $request): User
{
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
return $actor;
}
private function snapshot(\Closure $read): mixed
{
if (DB::connection()->getDriverName() === 'pgsql' && DB::transactionLevel() !== 0) {
throw new \LogicException('O relatório exige uma transacção própria de leitura.');
}
return DB::transaction(function () use ($read) {
if (DB::connection()->getDriverName() === 'pgsql') {
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY');
}
return $read();
});
}
/** @return array<string,mixed> */
private function filters(Request $request): array
{
$current = $request->user('web');
abort_unless($current instanceof User, 403);
$actor = User::query()->where('tenant_id', $current->tenant_id)->findOrFail($current->id);
abort_unless(! app(OrganizationAccess::class)->maintenanceOnly($actor) && $actor->hasFunctions([PurchasingRole::Admin, PurchasingRole::Procurement, PurchasingRole::Finance, PurchasingRole::DepartmentHead]), 403);
$request->setUserResolver(fn () => $actor);
$filters = $request->validate([
'search' => 'nullable|string|max:100',
'status' => 'nullable|in:draft,pending,approved,rejected,cancelled',
'from' => 'nullable|date_format:Y-m-d',
'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.']);
}
return $filters;
}
/** @return Builder<Quotation> */
private function registeredQuotes(): Builder
{
return Quotation::query()->whereColumn('quotations.requisition_id', 'requisitions.id');
}
/** @return Builder<PurchaseOrder> */
private function visibleOrders(User $actor): Builder
{
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
* @return Builder<Requisition>
*/
private function query(User $actor, array $filters, string $today): Builder
{
$query = Requisition::query()->where('tenant_id', $actor->tenant_id)->visibleTo($actor);
if (isset($filters['search']) && $filters['search'] !== '') {
$query->where('number', 'like', '%'.$filters['search'].'%');
}
foreach (['status', 'department_id'] as $field) {
if (! empty($filters[$field])) {
$query->where($field, $filters[$field]);
}
}
if (($filters['attention'] ?? '') === 'unapproved_needed') {
$query->whereIn('status', ['draft', 'pending'])->whereDate('needed_by', '<', $today);
}
if (($filters['attention'] ?? '') === 'approved_without_quotes') {
$query->where('status', 'approved')->whereNotExists($this->registeredQuotes()->selectRaw('1'));
}
if (($filters['attention'] ?? '') === 'approved_without_order') {
$query->where('status', 'approved')->whereNotExists($this->visibleOrders($actor)->selectRaw('1'));
}
if (! empty($filters['from'])) {
$query->where('created_at', '>=', $filters['from'].' 00:00:00');
}
if (! empty($filters['to'])) {
$query->where('created_at', '<', (new \DateTimeImmutable($filters['to']))->modify('+1 day')->format('Y-m-d').' 00:00:00');
}
return $query;
}
/** @param Builder<Requisition> $query
* @return Builder<Requisition>
*/
private function records(Builder $query, User $actor): Builder
{
return $query->select('requisitions.*')->with(['department:id,name', 'requester:id,name'])->addSelect([
'quotations_count' => $this->registeredQuotes()->selectRaw('COUNT(*)'),
'order_number' => $this->visibleOrders($actor)->select('number')->orderBy('id')->limit(1),
]);
}
/** @return array<string,mixed> */
private function row(Requisition $record): array
{
return [
'id' => $record->id, 'number' => $record->number, 'status' => $record->status,
'created_at' => $record->created_at?->toIso8601String(),
'needed_by' => $record->needed_by?->toDateString(),
'department' => $record->department?->name, 'requester' => $record->requester?->name,
'total_minor' => $record->total_minor === null ? null : (string) $record->total_minor,
'quotations_count' => (int) $record->getAttribute('quotations_count'),
'order_number' => $record->getAttribute('order_number'),
];
}
public function index(Request $request): Response
{
$props = $this->snapshot(function () use ($request): array {
$instant = CarbonImmutable::now(config('app.timezone'));
$filters = $this->filters($request);
$actor = $this->actor($request);
$query = $this->query($actor, $filters, $instant->toDateString());
$counts = (clone $query)->selectRaw('status, COUNT(*) AS count')->groupBy('status')->pluck('count', 'status')->map(fn ($value) => (int) $value);
$records = $this->records(clone $query, $actor)->orderByDesc('id')->paginate(25)->withQueryString()->through(fn (Requisition $record) => $this->row($record));
$departments = Department::query()->when($actor->departmentScoped(), fn ($q) => $q->whereKey($actor->department_id))->orderBy('name')->get(['id', 'name']);
$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, (int) ($filters['supplier_page'] ?? 1), (int) ($filters['category_page'] ?? 1))];
});
Inertia::encryptHistory();
$response = Inertia::render('reports/procurement', $props)->toResponse($request);
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
return $response;
}
public function exportPositions(Request $request): Response
{
$data = $this->snapshot(function () use ($request): array {
$instant = CarbonImmutable::now(config('app.timezone'));
$filters = $this->filters($request);
$actor = $this->actor($request);
$positions = app(ProcurementPayableInsights::class)->build($actor, $this->query($actor, $filters, $instant->toDateString()));
abort_unless($positions !== null, 403);
return ['positions' => $positions, 'filters' => $filters, 'generated_at' => $instant->toIso8601String()];
});
return response()->streamDownload(function () use ($data) {
$output = fopen('php://output', 'w');
if ($output === false) {
throw new \RuntimeException('Não foi possível gerar a posição financeira.');
}
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']], ';', '"', '');
fputcsv($output, ['Moeda', 'Obrigações determinadas', 'Principal (centavos)', 'Histórico conferido (centavos)', 'Liquidações imputadas (centavos)', 'Saldo actual (centavos)'], ';', '"', '');
foreach ($data['positions']['currencies'] as $row) {
fputcsv($output, [$row['currency'], $row['count'], $row['principal_minor'], $row['confirmed_payments_minor'], $row['allocated_payments_minor'], $row['balance_minor']], ';', '"', '');
}
fclose($output);
}, 'posicao-obrigacoes-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
}
public function exportPayments(Request $request): Response
{
$data = $this->snapshot(function () use ($request): array {
$instant = CarbonImmutable::now(config('app.timezone'));
$filters = $this->filters($request);
$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, null, null);
abort_unless($payments !== null, 403);
return ['payments' => $payments, 'generated_at' => $instant->toIso8601String()];
});
return response()->streamDownload(function () use ($data) {
$output = fopen('php://output', 'w');
if ($output === false) {
throw new \RuntimeException('Não foi possível exportar a despesa.');
}
fwrite($output, "\xEF\xBB\xBF");
$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);
$text = fn (?string $value) => preg_match('/^[\s]*[=+\-@]|^[\t\r\n]/u', $value ?? '') ? "'".$value : ($value ?? '');
return response()->streamDownload(fn () => $this->snapshot(function () use ($request, $text) {
$instant = CarbonImmutable::now(config('app.timezone'));
$filters = $this->filters($request);
$actor = $this->actor($request);
$query = $this->records($this->query($actor, $filters, $instant->toDateString()), $actor);
$output = fopen('php://output', 'w');
if ($output === false) {
throw new \RuntimeException('Não foi possível gerar o ficheiro.');
}
fwrite($output, "\xEF\xBB\xBF");
fputcsv($output, ['Relatório de compras', 'Criado em', $instant->toIso8601String()], ';', '"', '');
fputcsv($output, ['Filtros', $text(json_encode($filters, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR))], ';', '"', '');
fputcsv($output, ['Requisição', 'Criada em', 'Departamento', 'Solicitante', 'Estado da requisição', 'Estimativa total (centavos MZN)', 'Propostas registadas', 'Ordem de compra', 'Processo', 'Relatório de conferência', 'Data de necessidade'], ';', '"', '');
foreach ($query->lazyById(200) as $record) {
$row = $this->row($record);
$base = url('/requisicoes/'.$record->id);
fputcsv($output, [$text($record->number), $row['created_at'], $text($row['department']), $text($row['requester']), $record->status, $row['total_minor'] ?? 'Por completar', $row['quotations_count'], $text($row['order_number']), $base.'/processo', $base.'/relatorio', $row['needed_by']], ';', '"', '');
}
fclose($output);
}), 'relatorio-compras-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'private, no-store, max-age=0']);
}
}