Files
siakad/app/Http/Controllers/Operator/LaporanController.php
T
2026-11-12 16:10:18 +07:00

401 lines
18 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Http\Controllers\Operator;
use App\Http\Controllers\Controller;
use App\Models\Legacy\Account;
use App\Support\Legacy\AcademicOverview;
use App\Support\Legacy\PortalException;
use App\Support\Legacy\Reports\ReportContext;
use App\Support\Legacy\Reports\ReportRegistry;
use App\Support\Legacy\Reports\ReportResult;
use App\Support\Legacy\Reports\ReportSource;
use App\Support\Prototype\Satu\Catalog;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;
/**
* Menu Laporan operator untuk akun DB lama: formulir parameter yang menjalankan laporan otomatis lewat JSON
* (tabel berhalaman), unduh CSV, dan halaman cetak. Hanya baca. Sumber laporan (ReportSource) hanya mengenal
* limit, jadi halaman N diambil dengan limit N × per halaman lalu dipotong (dibatasi CAP baris pertama).
*/
class LaporanController extends Controller
{
/** Pilihan jumlah baris per halaman; bawaan yang kedua. */
public const array PER_PAGE = [10, 25, 50, 100];
/** Baris pertama yang bisa dilihat berhalaman; selebihnya lewat Unduh atau filter yang lebih sempit. */
private const int CAP = 5000;
private const int PRINT = 2000;
private const int DOWNLOAD = 50000;
public function __construct(private readonly AcademicOverview $overview) {}
public function __invoke(Request $request, string $slug): View
{
[$source, $context, $page, $definition] = $this->prepare($request, $slug);
[$values] = $this->parse($request, $definition['params'], $request->query() !== []);
// Semua laporan tampil sebagai daftar biasa (bilah filter + tabel); 'list' => false mengembalikan formulir parameter.
if ($definition['list'] ?? true) {
return $this->listPage($request, $slug, $source, $context, $page, $definition, $values);
}
return view('operator.satu.legacy-report', [
'page' => $page,
'crumbs' => ['Beranda' => route(auth()->user()->role->dashboardRoute())] + array_fill_keys(Catalog::trail($slug), null) + [$page['title'] => null],
'slug' => $slug,
'definition' => $definition,
'values' => $values,
'config' => [
'url' => route('operator.laporan.data', $slug),
'downloadUrl' => route('operator.laporan.unduh', $slug),
'printUrl' => route('operator.laporan.cetak', $slug),
'params' => array_map(fn (array $p): array => ['name' => $p['name'], 'type' => $p['type'], 'required' => (bool) ($p['required'] ?? false), 'reload' => $p['name'] !== 'kop'], $definition['params']),
'values' => $this->clientValues($definition['params'], $values),
'perPage' => self::PER_PAGE,
'per' => self::PER_PAGE[1],
],
]);
}
/** JSON satu halaman hasil: kolom, baris halaman ini, keterangan, dan penomoran. */
public function data(Request $request, string $slug): JsonResponse
{
[$source, $context, , $definition] = $this->prepare($request, $slug);
[$values, $errors] = $this->parse($request, $definition['params'], true);
if ($errors !== []) {
return response()->json(['message' => implode(' ', $errors), 'errors' => $errors], 422);
}
$list = (bool) ($definition['list'] ?? true);
$raw = $request->input('q');
$q = is_string($raw) ? mb_substr(trim($raw), 0, 100) : '';
$filterQ = null;
if ($list && $q !== '') {
if ($definition['search'] ?? false) {
// Sumber mengenal kata cari: diteruskan sebagai parameter q.
$values['q'] = $q;
} elseif (! self::hasParam($definition, 'q')) {
// Sumber tidak mengenal kata cari: hasil disaring di sini atas semua kolom (sampai batas CAP baris).
$filterQ = $q;
}
}
$per = in_array($request->integer('per'), self::PER_PAGE, true) ? $request->integer('per') : self::PER_PAGE[1];
try {
return response()->json($this->pageOf($source, $slug, $values, $context, $per, $request->integer('page', 1), $list, $filterQ));
} catch (PortalException $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
}
/** Laporan punya parameter bernama {name}? */
private static function hasParam(array $definition, string $name): bool
{
return in_array($name, array_column($definition['params'], 'name'), true);
}
/**
* Satu halaman hasil laporan: kolom, baris halaman ini, keterangan, dan penomoran (baris diberi id urut bila daftar).
*
* @param array<string, mixed> $values
* @return array<string, mixed>
*/
private function pageOf(ReportSource $source, string $slug, array $values, ReportContext $context, int $per, int $page, bool $list = false, ?string $filterQ = null): array
{
$maxPage = intdiv(self::CAP + $per - 1, $per);
$page = min(max(1, $page), $maxPage);
if ($filterQ !== null) {
// Kata cari generik: ambil sampai batas CAP lalu saring baris yang salah satu kolomnya memuat kata itu.
$result = $source->run($slug, $values, $context, self::CAP + 1);
$needle = mb_strtolower($filterQ);
$rows = array_values(array_filter($result->rows, function (array $row) use ($needle): bool {
foreach ($row as $value) {
if (is_scalar($value) && str_contains(mb_strtolower((string) $value), $needle)) {
return true;
}
}
return false;
}));
$result = new ReportResult($result->columns, $rows, count($rows), $result->summary, $result->note);
} else {
// +1 agar terlihat bila masih ada baris sesudah halaman ini saat sumber tidak mengisi total
$result = $source->run($slug, $values, $context, $page * $per + 1);
}
$total = $result->total ?? count($result->rows);
$lastPage = max(1, min($maxPage, intdiv($total + $per - 1, $per)));
$page = min($page, $lastPage);
$from = ($page - 1) * $per + 1;
$rows = array_values(array_slice($result->rows, $from - 1, $per));
$columns = $result->columns;
if ($list) {
$rows = array_map(fn (array $row, int $i): array => ['id' => $from + $i] + $row, $rows, array_keys($rows));
// Kolom tabel daftar: tanpa kolom 'hidden' (hanya untuk CSV); 'meter' = tampil sebagai bar persen.
$columns = array_values(array_map(
fn (array $c): array => ['key' => $c['key'], 'label' => $c['label'], 'num' => (bool) ($c['num'] ?? false), 'meter' => (bool) ($c['meter'] ?? false)],
array_filter($columns, fn (array $c): bool => ! ($c['hidden'] ?? false)),
));
}
return [
'columns' => $columns,
'rows' => $rows,
'summary' => $result->summary,
'note' => $result->note,
'total' => $total,
'page' => $page,
'last_page' => $lastPage,
'per_page' => $per,
'from' => $from,
'capped' => $total > self::CAP,
'cap' => self::CAP,
];
}
/**
* Laporan bergaya daftar biasa (remote-list): bilah filter dari parameter laporan (tanpa KOP), tabel dengan kotak cari
* dan halaman, tautan Unduh CSV di bilah. Kolom diambil dari hasil halaman pertama.
*
* @param array<string, mixed> $page
* @param array<string, mixed> $definition
* @param array<string, mixed> $values
*/
private function listPage(Request $request, string $slug, ReportSource $source, ReportContext $context, array $page, array $definition, array $values): View
{
// Parameter laporan menjadi filter daftar: select/check/text/number/date (KOP hanya untuk cetak, dibuang).
$params = array_values(array_filter($definition['params'], fn (array $p): bool => $p['name'] !== 'kop'));
$filters = array_map(function (array $p) use ($values): array {
$filter = ['name' => $p['name'], 'label' => $p['label'].(($p['required'] ?? false) ? '' : '')];
if ($p['type'] === 'check') {
return $filter + ['type' => 'check', 'value' => (bool) ($values[$p['name']] ?? false)];
}
if ($p['type'] === 'select') {
return $filter + ['options' => $p['options'] ?? [], 'value' => $values[$p['name']] ?? null];
}
return $filter + ['type' => $p['type'], 'value' => $values[$p['name']] ?? null, 'placeholder' => $p['placeholder'] ?? null, 'hint' => $p['hint'] ?? null];
}, $params);
// Halaman pertama; parameter wajib yang belum terisi atau kesalahan sumber = tabel kosong dengan kolom dinamis dari JSON.
[, $errors] = $this->parse($request, $definition['params'], true);
$data = ['columns' => [], 'rows' => [], 'total' => 0, 'page' => 1, 'last_page' => 1, 'per_page' => self::PER_PAGE[0]];
if ($errors === []) {
try {
$data = $this->pageOf($source, $slug, $values, $context, self::PER_PAGE[0], 1, true);
} catch (PortalException) {
// biarkan kosong; pesan tampil saat filter diubah
}
}
// Laporan dengan 'detail' (kolom modal Lihat) mendapat kolom Aksi berisi tombol Lihat per baris.
$detail = $definition['detail'] ?? [];
return view('operator.satu.remote-list', [
// Kolom katalog laporan kosong; diisi label kolom hasil (+ 'Aksi' bila ada modal rincian) untuk remote-list.
'page' => ['columns' => [...array_column($data['columns'], 'label'), ...($detail !== [] ? ['Aksi'] : [])]] + $page,
'viewable' => $detail !== [],
'detailColumns' => $detail,
'crumbs' => ['Beranda' => route(auth()->user()->role->dashboardRoute())] + array_fill_keys(Catalog::trail($slug), null) + [$page['title'] => null],
'note' => trim(($definition['note'] ?? '').($errors === [] ? '' : ' Lengkapi filter yang wajib diisi ('.implode(', ', array_map(fn (array $p): string => $p['label'], array_filter($params, fn (array $p): bool => isset($errors[$p['name']])))).') untuk menampilkan data.')) ?: null,
'empty' => ['icon' => 'document-chart-bar', 'title' => 'Belum ada data', 'description' => 'Data tampil setelah tabel sumbernya terisi.'],
'url' => route('operator.laporan.data', $slug),
'filters' => $filters,
// Kolom dinamis: kepala tabel mengikuti kolom hasil (JSON) agar laporan tanpa data awal tetap menampilkan kolom begitu filter terisi.
'columns' => [],
'perPage' => self::PER_PAGE,
'selectable' => false,
// Kotak cari: ke sumber bila mengenal q, selain itu saringan generik atas kolom hasil; disembunyikan hanya bila laporan
// punya parameter lain bernama q.
'searchable' => (bool) ($definition['search'] ?? false) || ! self::hasParam($definition, 'q'),
'barLinks' => [['label' => 'Unduh (CSV)', 'href' => route('operator.laporan.unduh', $slug), 'icon' => 'arrow-down-tray', 'withFilters' => true]],
'data' => $data,
]);
}
public function download(Request $request, string $slug): StreamedResponse|RedirectResponse
{
[$source, $context, , $definition] = $this->prepare($request, $slug);
[$values, $errors] = $this->parse($request, $definition['params'], true);
if ($errors !== []) {
return redirect()->route('operator.halaman', [$slug] + $this->queryString($request));
}
try {
$result = $source->run($slug, $values, $context, self::DOWNLOAD);
} catch (PortalException $e) {
return redirect()->route('operator.halaman', [$slug] + $this->queryString($request));
}
return response()->streamDownload(function () use ($result): void {
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF"); // BOM agar Excel membaca UTF-8
fputcsv($out, array_column($result->columns, 'label'), ',', '"', '\\');
foreach ($result->rows as $row) {
fputcsv($out, array_map(fn (array $c): mixed => $row[$c['key']] ?? '', $result->columns), ',', '"', '\\');
}
fclose($out);
}, $slug.'-'.now()->format('Ymd-His').'.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
}
public function print(Request $request, string $slug): View|RedirectResponse
{
[$source, $context, $page, $definition] = $this->prepare($request, $slug);
[$values, $errors] = $this->parse($request, $definition['params'], true);
if ($errors !== []) {
return redirect()->route('operator.halaman', [$slug] + $this->queryString($request));
}
try {
$result = $source->run($slug, $values, $context, self::PRINT);
} catch (PortalException $e) {
return redirect()->route('operator.halaman', [$slug] + $this->queryString($request));
}
return view('operator.laporan-cetak', [
'title' => $page['title'],
'result' => $result,
'kop' => (bool) ($values['kop'] ?? true),
'parameters' => $this->describe($definition['params'], $values),
'operator' => $request->user()->username,
]);
}
/**
* Penjaga akun dan definisi: akun DB lama dan slug terdaftar; kop (Gunakan KOP) ditambahkan di akhir parameter.
*
* @return array{0: ReportSource, 1: ReportContext, 2: array<string, mixed>, 3: array<string, mixed>}
*/
private function prepare(Request $request, string $slug): array
{
abort_unless($request->user() instanceof Account, 404);
$source = ReportRegistry::sourceFor($slug) ?? abort(404);
$page = Catalog::page($slug) ?? abort(404);
$programs = $this->overview->programs((int) $request->user()->getKey());
$context = new ReportContext((int) $request->user()->getKey(), (string) $request->user()->username, $programs->keys()->all(), $programs->all());
$definition = $source->definition($slug, $context);
$definition['params'][] = ['name' => 'kop', 'label' => 'Gunakan KOP', 'type' => 'check', 'default' => true];
return [$source, $context, $page, $definition];
}
/**
* Baca parameter dari query: pilihan dicocokkan ke opsi, teks dipangkas, angka dan tanggal diperiksa.
* Kotak centang yang tidak dikirim berarti salah; sebelum ada query nilai awalnya dipakai.
*
* @param list<array<string, mixed>> $params
* @return array{0: array<string, mixed>, 1: array<string, string>}
*/
private function parse(Request $request, array $params, bool $submitted): array
{
$values = [];
$errors = [];
foreach ($params as $p) {
$name = $p['name'];
$label = $p['label'];
$raw = $request->query($name);
$raw = is_string($raw) ? trim($raw) : null;
if ($p['type'] === 'check') {
$values[$name] = $submitted ? ($raw !== null && $raw !== '' && $raw !== '0') : (bool) ($p['default'] ?? false);
continue;
}
if (($raw === null || $raw === '') && ! $submitted && isset($p['default'])) {
$raw = (string) $p['default'];
}
if ($raw === null || $raw === '') {
$values[$name] = null;
if ($p['required'] ?? false) {
$errors[$name] = "{$label} wajib diisi.";
}
continue;
}
$values[$name] = match ($p['type']) {
'select' => $this->matchOption($p['options'] ?? [], $raw),
'number' => preg_match('/^-?\d{1,9}$/', $raw) ? (int) $raw : null,
'date' => ($d = \DateTimeImmutable::createFromFormat('!Y-m-d', $raw)) && $d->format('Y-m-d') === $raw ? $raw : null,
default => mb_substr($raw, 0, 100),
};
if ($values[$name] === null) {
$errors[$name] = "{$label} tidak valid.";
}
}
return [$values, $errors];
}
/** @param array<int|string, string> $options */
private function matchOption(array $options, string $raw): int|string|null
{
foreach ($options as $key => $label) {
if ((string) $key === $raw) {
return $key;
}
}
return null;
}
/**
* Nilai awal formulir untuk klien: teks/angka/pilihan sebagai string ('' bila kosong), kotak centang sebagai bool.
*
* @param list<array<string, mixed>> $params
* @param array<string, mixed> $values
* @return array<string, string|bool>
*/
private function clientValues(array $params, array $values): array
{
$out = [];
foreach ($params as $p) {
$value = $values[$p['name']] ?? null;
$out[$p['name']] = $p['type'] === 'check' ? (bool) $value : ($value === null ? '' : (string) $value);
}
return $out;
}
/**
* Ringkasan parameter yang terisi untuk halaman cetak: label => nilai tampil.
*
* @param list<array<string, mixed>> $params
* @param array<string, mixed> $values
* @return array<string, string>
*/
private function describe(array $params, array $values): array
{
$out = [];
foreach ($params as $p) {
$value = $values[$p['name']] ?? null;
if ($p['type'] === 'check' || $value === null || $value === '') {
continue;
}
$out[$p['label']] = $p['type'] === 'select' ? (string) ($p['options'][$value] ?? $value) : (string) $value;
}
return $out;
}
/** Query laporan (string saja), untuk pengalihan kembali ke halaman. @return array<string, string> */
private function queryString(Request $request): array
{
return collect($request->query())->filter(fn (mixed $v): bool => is_string($v))->all();
}
}