@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Services\AgreementFollowup;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Inertia\Inertia;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
final class AgreementFollowupController extends Controller
|
||||
{
|
||||
public function index(Request $request, AgreementFollowup $read): Response
|
||||
{
|
||||
return $this->respond($request, $read, false);
|
||||
}
|
||||
|
||||
public function csv(Request $request, AgreementFollowup $read): Response
|
||||
{
|
||||
return $this->respond($request, $read, true);
|
||||
}
|
||||
|
||||
private function respond(Request $request, AgreementFollowup $read, bool $csv): Response
|
||||
{
|
||||
$actor = $this->staffIdentity($request);
|
||||
|
||||
return DB::transaction(function () use ($request, $read, $csv, $actor) {
|
||||
if (DB::getDriverName() === 'pgsql' && DB::transactionLevel() === 1) {
|
||||
DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
}
|
||||
$actor = $read->authorize($actor);
|
||||
$filters = $read->filters($request);
|
||||
$kind = $request->validate(['kind' => 'nullable|in:agreement,contract'])['kind'] ?? 'agreement';
|
||||
$today = today()->toDateString();
|
||||
$query = $read->query($actor, $filters, $today, $kind)->orderBy('id');
|
||||
if (! $csv) {
|
||||
$page = $query->paginate(25)->withQueryString();
|
||||
Inertia::encryptHistory();
|
||||
$response = Inertia::render('supply/agreement-followup', ['kind' => $kind, 'asOf' => $today, 'filters' => $filters, 'records' => [
|
||||
'data' => $read->rows($page->getCollection(), $today), 'total' => $page->total(), 'current_page' => $page->currentPage(),
|
||||
'last_page' => $page->lastPage(), 'prev_page_url' => $page->previousPageUrl(), 'next_page_url' => $page->nextPageUrl(),
|
||||
]])->toResponse($request);
|
||||
$response->headers->set('Cache-Control', 'private, no-store, max-age=0');
|
||||
$response->headers->set('X-Content-Type-Options', 'nosniff');
|
||||
|
||||
return $response;
|
||||
}
|
||||
$file = fopen('php://temp', 'w+');
|
||||
if ($file === false) {
|
||||
throw new \RuntimeException('Não foi possível preparar o CSV.');
|
||||
}
|
||||
try {
|
||||
fwrite($file, "\xEF\xBB\xBF");
|
||||
$write = static function (array $cells) use ($file): void {
|
||||
fputcsv($file, array_map(static function (mixed $value): string {
|
||||
$text = $value === null ? 'Não disponível' : (string) $value;
|
||||
|
||||
return preg_match('/^[\s\x00-\x1F]*[=+@-]/u', $text) ? "'".$text : $text;
|
||||
}, $cells), ';', '"', '');
|
||||
};
|
||||
$write([$kind === 'contract' ? 'Vigência de contratos globais aprovados' : 'Vigência de acordos aprovados', 'Data de consulta', $today]);
|
||||
$write(['Pesquisa', $filters['search'], 'Situação', $filters['validity'], 'Termina até', $filters['expires_by']]);
|
||||
$write(['Registo', 'Versão', 'Referência', 'Fornecedor preservado', 'Código do artigo', 'Artigo preservado', 'Armazém preservado', 'Início', 'Fim', 'Situação de vigência', 'Políticas aprovadas ligadas', 'Acordo', 'Políticas',
|
||||
...($kind === 'contract' ? ['Moeda', 'Limite global por ordem (centavos)', 'Periodicidade prevista (dias)', 'Artigos aprovados', 'Artigos ligados'] : [])]);
|
||||
$query->chunk(100, function ($batch) use ($read, $today, $write, $kind) {
|
||||
foreach ($read->rows($batch, $today) as $row) {
|
||||
$write([$row['record_key'], $row['version'], $row['reference'], $row['supplier'], $kind === 'contract' ? 'Não aplicável' : $row['item_code'], $kind === 'contract' ? 'Não aplicável' : $row['item'], $kind === 'contract' ? 'Não aplicável' : $row['warehouse'],
|
||||
$row['valid_from'], $row['valid_until'], match ($row['validity']) {
|
||||
'current' => 'Vigente','expired' => 'Expirado','future' => 'Por iniciar',default => 'Datas indeterminadas'
|
||||
}, $kind === 'contract' ? 'Não aplicável' : $row['approved_policies'], $row['href'], $kind === 'contract' ? 'Não aplicável' : $row['policies_href'],
|
||||
...($kind === 'contract' ? [$row['currency'], $row['max_order_value_minor'] ?? 'Não definido', $row['periodicity_days'], $row['approved_articles'], $row['articles_href']] : [])]);
|
||||
}
|
||||
});
|
||||
rewind($file);
|
||||
$body = stream_get_contents($file);
|
||||
if ($body === false) {
|
||||
throw new \RuntimeException('Não foi possível ler o CSV preparado.');
|
||||
}
|
||||
} finally {
|
||||
fclose($file);
|
||||
}
|
||||
|
||||
return response($body, 200, ['Content-Type' => 'text/csv; charset=UTF-8', 'Content-Disposition' => 'attachment; filename="vigencia-'.($kind === 'contract' ? 'contratos' : 'acordos').'-'.$today.'.csv"',
|
||||
'Cache-Control' => 'private, no-store, max-age=0', 'X-Content-Type-Options' => 'nosniff']);
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user