Integrasi Menu Laporan Operator
This commit is contained in:
@@ -0,0 +1,276 @@
|
||||
<?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\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
|
||||
{
|
||||
[, , $page, $definition] = $this->prepare($request, $slug);
|
||||
[$values] = $this->parse($request, $definition['params'], $request->query() !== []);
|
||||
|
||||
return view('operator.satu.legacy-report', [
|
||||
'page' => $page,
|
||||
'crumbs' => ['Beranda' => route('operator.dashboard')] + 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);
|
||||
}
|
||||
|
||||
$per = in_array($request->integer('per'), self::PER_PAGE, true) ? $request->integer('per') : self::PER_PAGE[1];
|
||||
$maxPage = intdiv(self::CAP + $per - 1, $per);
|
||||
$page = min(max(1, $request->integer('page', 1)), $maxPage);
|
||||
|
||||
try {
|
||||
// +1 agar terlihat bila masih ada baris sesudah halaman ini saat sumber tidak mengisi total
|
||||
$result = $source->run($slug, $values, $context, $page * $per + 1);
|
||||
} catch (PortalException $e) {
|
||||
return response()->json(['message' => $e->getMessage()], 422);
|
||||
}
|
||||
|
||||
$total = $result->total ?? count($result->rows);
|
||||
$lastPage = max(1, min($maxPage, intdiv($total + $per - 1, $per)));
|
||||
$page = min($page, $lastPage);
|
||||
|
||||
return response()->json([
|
||||
'columns' => $result->columns,
|
||||
'rows' => array_values(array_slice($result->rows, ($page - 1) * $per, $per)),
|
||||
'summary' => $result->summary,
|
||||
'note' => $result->note,
|
||||
'total' => $total,
|
||||
'page' => $page,
|
||||
'last_page' => $lastPage,
|
||||
'per_page' => $per,
|
||||
'from' => ($page - 1) * $per + 1,
|
||||
'capped' => $total > self::CAP,
|
||||
'cap' => self::CAP,
|
||||
]);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user