diff --git a/.gitignore b/.gitignore index b3c8ae49..07706888 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,4 @@ specs/ .specify/ storage/sso .claude/ +CLAUDE.md \ No newline at end of file diff --git a/app/Enums/Modul.php b/app/Enums/Modul.php index ca9e61ca..b237e7a3 100644 --- a/app/Enums/Modul.php +++ b/app/Enums/Modul.php @@ -333,6 +333,12 @@ final class Modul extends Enum 'url' => 'dataspasial/audit', 'permission' => 'dataspasial-audit', ], + [ + 'icon' => 'far fa-fw fa-circle', + 'text' => 'Status Desa', + 'url' => 'dataspasial/desa', + 'permission' => 'dataspasial-desa', + ], ], ], [ diff --git a/app/Http/Controllers/DataSpasial/StatusDesaController.php b/app/Http/Controllers/DataSpasial/StatusDesaController.php new file mode 100644 index 00000000..7c494872 --- /dev/null +++ b/app/Http/Controllers/DataSpasial/StatusDesaController.php @@ -0,0 +1,136 @@ +statusDesa->dataspasial); + } + + protected function pageTitle(): string + { + return 'Status Desa'; + } + + protected function viewName(): string + { + return 'dataspasial.desa.index'; + } + + protected function fetch(Request $request): DataSpasialResult + { + // Kerangka halaman tidak membaca data (dimuat lewat AJAX). + return DataSpasialResult::empty(); + } + + public function index(Request $request): View + { + return view($this->viewName(), [ + 'title' => $this->pageTitle(), + 'result' => $this->fetch($request), + 'pilihanStatus' => $this->statusDesa->pilihanStatus(), + // Tombol aksi hanya tampil bagi pemilik izin tulis; route-nya tetap dijaga middleware permission. + 'bolehUbah' => (bool) $request->user()?->can('dataspasial-desa-write'), + ]); + } + + /** + * Tabel desa + paginasi (AJAX). + */ + public function data(Request $request): JsonResponse + { + $hasil = $this->statusDesa->daftar($request->only(['kode_kecamatan', 'status', 'page'])); + + return response()->json([ + 'meta' => [ + 'unavailable' => ! $hasil['tersedia'], + 'empty' => $hasil['tersedia'] && $hasil['baris'] === [], + 'message' => $hasil['tersedia'] ? null : (string) config('dataspasial.unavailable_message'), + 'page' => $hasil['halaman'], + 'total_pages' => $hasil['total_halaman'], + 'total' => $hasil['total'], + 'per_page' => $hasil['per_halaman'], + ], + 'ringkasan' => $hasil['ringkasan'], + // Jumlah per status pada cakupan filter (seluruh halaman) untuk tombol & modal aksi massal + 'ringkasan_status' => $hasil['ringkasan_status'], + 'baris' => $hasil['baris'], + ]); + } + + /** + * Nonaktifkan atau aktifkan kembali seluruh desa pada cakupan filter kecamatan + * (tanpa filter = seluruh desa kabupaten). + */ + public function ubahStatusMassal(UbahStatusDesaMassalRequest $request): RedirectResponse|JsonResponse + { + $aktif = $request->aktif(); + $result = $this->statusDesa->ubahStatusMassal($aktif, $request->alasan(), $request->kodeKecamatan()); + $kembali = redirect()->route('dataspasial.desa', $request->only(['kode_kecamatan', 'status'])); + + if ($result->isUnavailable()) { + $pesan = $result->httpStatus === 404 + ? 'Tidak ada desa pada cakupan yang dipilih.' + : (string) config('dataspasial.unavailable_message'); + + return $request->wantsJson() + ? response()->json(['success' => false, 'message' => $pesan], $result->httpStatus === 404 ? 404 : 503) + : $kembali->with('error', $pesan); + } + + $pesan = $this->statusDesa->pesanMassal($result, $aktif, $request->namaKecamatan()); + + return $request->wantsJson() + ? response()->json(['success' => true, 'message' => $pesan, 'hasil' => $result->first()['attributes'] ?? null]) + : $kembali->with('success', $pesan); + } + + /** + * Nonaktifkan atau aktifkan kembali pengisian satu desa. + */ + public function ubahStatus(UbahStatusDesaRequest $request, int $config_id): RedirectResponse|JsonResponse + { + $aktif = $request->aktif(); + $result = $this->statusDesa->ubahStatus($config_id, $aktif, $request->alasan()); + + if ($result->isUnavailable()) { + $pesan = $result->httpStatus === 404 + ? 'Desa tidak ditemukan atau berada di luar kabupaten Anda.' + : (string) config('dataspasial.unavailable_message'); + + return $request->wantsJson() + ? response()->json(['success' => false, 'message' => $pesan], $result->httpStatus === 404 ? 404 : 503) + : redirect()->route('dataspasial.desa', $request->only(['kode_kecamatan', 'status']))->with('error', $pesan); + } + + $pesan = $this->statusDesa->pesanBerhasil($result, $aktif); + + return $request->wantsJson() + ? response()->json(['success' => true, 'message' => $pesan, 'desa' => $result->first()]) + : redirect()->route('dataspasial.desa', $request->only(['kode_kecamatan', 'status']))->with('success', $pesan); + } +} diff --git a/app/Http/Requests/DataSpasial/UbahStatusDesaMassalRequest.php b/app/Http/Requests/DataSpasial/UbahStatusDesaMassalRequest.php new file mode 100644 index 00000000..f0278d2b --- /dev/null +++ b/app/Http/Requests/DataSpasial/UbahStatusDesaMassalRequest.php @@ -0,0 +1,58 @@ +> + */ + public function rules(): array + { + return array_merge(parent::rules(), [ + 'kode_kecamatan' => ['nullable', 'string', 'max:20', 'regex:/^[0-9.]+$/'], + 'nama_kecamatan' => ['nullable', 'string', 'max:150'], + 'konfirmasi' => ['accepted'], + ]); + } + + /** + * @return array + */ + public function messages(): array + { + return array_merge(parent::messages(), [ + 'kode_kecamatan.regex' => 'Kode kecamatan harus berupa angka.', + 'konfirmasi.accepted' => 'Centang konfirmasi untuk mengubah status banyak desa sekaligus.', + ]); + } + + public function kodeKecamatan(): ?string + { + $kode = $this->validated('kode_kecamatan'); + + return is_string($kode) && trim($kode) !== '' ? trim($kode) : null; + } + + /** + * Nama kecamatan untuk pesan flash (hanya tampilan; cakupan ditentukan kode_kecamatan). + */ + public function namaKecamatan(): ?string + { + if ($this->kodeKecamatan() === null) { + return null; + } + + $nama = $this->validated('nama_kecamatan'); + + return is_string($nama) && trim($nama) !== '' ? trim($nama) : $this->kodeKecamatan(); + } +} diff --git a/app/Http/Requests/DataSpasial/UbahStatusDesaRequest.php b/app/Http/Requests/DataSpasial/UbahStatusDesaRequest.php new file mode 100644 index 00000000..abef48f5 --- /dev/null +++ b/app/Http/Requests/DataSpasial/UbahStatusDesaRequest.php @@ -0,0 +1,62 @@ +> + */ + public function rules(): array + { + $aturanAlasan = $this->has('aktif') && $this->boolean('aktif') + ? ['nullable', 'string', 'max:'.self::PANJANG_ALASAN] + : ['required', 'string', 'max:'.self::PANJANG_ALASAN]; + + return [ + 'aktif' => ['required', 'boolean'], + 'alasan' => $aturanAlasan, + ]; + } + + /** + * @return array + */ + public function messages(): array + { + return [ + 'aktif.required' => 'Status yang diminta tidak dikenal.', + 'alasan.required' => 'Alasan wajib diisi saat menonaktifkan pengisian desa.', + 'alasan.max' => 'Alasan maksimal '.self::PANJANG_ALASAN.' karakter.', + ]; + } + + public function aktif(): bool + { + return $this->boolean('aktif'); + } + + public function alasan(): ?string + { + $alasan = $this->validated('alasan'); + + return is_string($alasan) && trim($alasan) !== '' ? trim($alasan) : null; + } +} diff --git a/app/Services/AdopsiDesaService.php b/app/Services/AdopsiDesaService.php index 7ee81a6b..094050b0 100644 --- a/app/Services/AdopsiDesaService.php +++ b/app/Services/AdopsiDesaService.php @@ -120,6 +120,8 @@ private function normalisasiBaris(array $item): ?array : null, 'status_api' => is_string($statusApi) ? $statusApi : null, 'terakhir_ada_data' => is_string($terakhir) && $terakhir !== '' ? $terakhir : null, + // API-09: false bila kabupaten menonaktifkan pengisian desa. API lama tanpa field ini = aktif. + 'isian_aktif' => ! array_key_exists('isian_aktif', $atribut) || (bool) $atribut['isian_aktif'], ]; } diff --git a/app/Services/DataSpasialApiService.php b/app/Services/DataSpasialApiService.php index e7e42233..d3c1c88c 100644 --- a/app/Services/DataSpasialApiService.php +++ b/app/Services/DataSpasialApiService.php @@ -328,6 +328,8 @@ protected function extractMeta(mixed $payload): array return array_filter([ 'pagination' => is_array($payload['meta']['pagination'] ?? null) ? $payload['meta']['pagination'] : null, 'links' => is_array($payload['links'] ?? null) ? $payload['links'] : null, + // API-09: jumlah desa per status pada cakupan filter (GET /dataspasial/desa) + 'ringkasan_status' => is_array($payload['meta']['ringkasan_status'] ?? null) ? $payload['meta']['ringkasan_status'] : null, ], static fn ($value) => $value !== null); } @@ -690,4 +692,53 @@ public function auditRingkasan(array $filters = []): DataSpasialResult { return $this->request('GET', 'audit/ringkasan', $filters, null, null, true); } + + // ----------------------------------------------------------------------- + // Status isian desa (API-09 / KAB-09) + // ----------------------------------------------------------------------- + + /** + * Daftar desa kabupaten beserta status pengisian Data Spasialnya. + * + * ⚠️ **TIDAK di-cache** — status menentukan apakah operator desa boleh + * mengisi, sehingga halaman harus selalu menampilkan keadaan terbaru. + * + * @param array $filters kode_kecamatan, kode_desa, config_id, status (aktif|nonaktif), page + */ + public function listDesa(array $filters = []): DataSpasialResult + { + return $this->request('GET', 'desa', $filters, null, null, true); + } + + /** + * Nonaktifkan (`$aktif=false`, alasan wajib) atau aktifkan kembali pengisian satu desa. + * Penulisan sukses menginvalidasi seluruh cache baca (adopsi ikut berubah). + */ + public function ubahStatusDesa(int $configId, bool $aktif, ?string $alasan = null): DataSpasialResult + { + return $this->request( + 'PUT', + 'desa/'.$configId.'/status', + [], + array_filter(['aktif' => $aktif, 'alasan' => $alasan], static fn ($v) => $v !== null) + ); + } + + /** + * Nonaktifkan / aktifkan seluruh desa kabupaten sekaligus, dipersempit `$kodeKecamatan` bila diberikan. + * Satu transaksi di sisi API; penulisan sukses menginvalidasi seluruh cache baca. + */ + public function ubahStatusDesaMassal(bool $aktif, ?string $alasan = null, ?string $kodeKecamatan = null): DataSpasialResult + { + return $this->request( + 'PUT', + 'desa/status', + [], + array_filter([ + 'aktif' => $aktif, + 'alasan' => $alasan, + 'kode_kecamatan' => $kodeKecamatan, + ], static fn ($v) => $v !== null) + ); + } } diff --git a/app/Services/ImporBerkasService.php b/app/Services/ImporBerkasService.php index 62ab7d70..cc4af995 100644 --- a/app/Services/ImporBerkasService.php +++ b/app/Services/ImporBerkasService.php @@ -155,6 +155,11 @@ public function normalisasiPratinjau(array $data, array $meta = []): array if (is_array($pesan)) { $pesan = implode('; ', $pesan); } + // API-09: peringatan non-blokir, mis. desa yang pengisiannya dinonaktifkan kabupaten + $peringatan = $item['peringatan'] ?? null; + if (is_array($peringatan)) { + $peringatan = implode('; ', $peringatan); + } $baris[] = [ 'nomor_baris' => $item['nomor_baris'] ?? null, 'kode_desa' => $item['kode_desa'] ?? '', @@ -165,6 +170,7 @@ public function normalisasiPratinjau(array $data, array $meta = []): array 'periode' => $item['periode'] ?? '', 'status' => $item['status'] ?? ($item['keterangan'] ?? ''), 'pesan' => (string) ($pesan ?? ''), + 'peringatan' => (string) ($peringatan ?? ''), 'nilai' => $item['nilai'] ?? [], ]; } diff --git a/app/Services/MonitoringDataSpasialService.php b/app/Services/MonitoringDataSpasialService.php index 323b8ef1..b894f2b2 100644 --- a/app/Services/MonitoringDataSpasialService.php +++ b/app/Services/MonitoringDataSpasialService.php @@ -189,9 +189,12 @@ public function buildMonitoring(array $query): array // Kartu atas SELURUH hasil (FR-010). "Perlu diperiksa" kini = desa // dengan versi tertinggal (tanda data dihapus 2026-10-21). + // KAB-09: desa yang pengisiannya dinonaktifkan kabupaten tidak dihitung + // "belum pernah mengirim" maupun "perlu diperiksa" — desa itu memang dikunci. $sudah = count(array_filter($terfilter, static fn (array $b): bool => $b['status_pengisian'] === 'sudah_mengisi')); - $belum = count(array_filter($terfilter, static fn (array $b): bool => $b['status_pengisian'] === 'belum_pernah_mengirim')); + $belum = count(array_filter($terfilter, static fn (array $b): bool => $b['status_pengisian'] === 'belum_pernah_mengirim' && $b['isian_aktif'])); $perlu = count(array_filter($terfilter, static fn (array $b): bool => $b['perlu_tindakan'])); + $nonaktif = count(array_filter($terfilter, static fn (array $b): bool => ! $b['isian_aktif'])); $kartu = [ 'sudah_mengisi' => $sudah, @@ -199,6 +202,7 @@ public function buildMonitoring(array $query): array 'perlu_diperiksa' => $perlu, 'total_desa' => count($terfilter), 'sudah_mengisi_label' => $sudah.'/'.count($terfilter), + 'isian_nonaktif' => $nonaktif, ]; $total = count($terfilter); @@ -444,6 +448,7 @@ public function barisAdopsiSektor(array $baris, ?int $sektorId): array 'versi_terpakai' => $b['nomor_versi'], 'terakhir_ada_data' => $b['terakhir_ada_data'], 'ada_adopsi' => true, + 'isian_aktif' => $b['isian_aktif'] ?? true, ]; } @@ -477,6 +482,7 @@ public function susunBarisDasar(array $barisAdopsi, string $kodeKecamatan): arra 'versi_terpakai' => null, 'terakhir_ada_data' => null, 'ada_adopsi' => false, + 'isian_aktif' => true, ]; } @@ -606,6 +612,7 @@ public function hitungBaris( ): array { $kodeDesa = (string) $dasar['kode_desa']; $versiTerpakai = $dasar['versi_terpakai']; + $isianAktif = (bool) ($dasar['isian_aktif'] ?? true); // Status versi (FR-022): anomali bila nomor versi > terbit terbaru. if ($versiTerbit === null || $versiTerpakai === null) { @@ -698,7 +705,9 @@ public function hitungBaris( 'tanda_impor' => $sumber === 'impor', 'kelengkapan_persen' => $kelengkapan, 'skor_kualitas' => null, - 'perlu_tindakan' => (! $berdata) || $statusVersi === 'tertinggal', + // KAB-09: desa yang dinonaktifkan kabupaten tidak perlu ditindaklanjuti operatornya. + 'isian_aktif' => $isianAktif, + 'perlu_tindakan' => $isianAktif && ((! $berdata) || $statusVersi === 'tertinggal'), 'periode' => $periode, ]; } @@ -728,7 +737,7 @@ public function payloadTidakTersedia(array $filter): array 'total' => 0, 'total_pages' => 1, ], - 'kartu' => ['sudah_mengisi' => 0, 'belum_pernah_mengirim' => 0, 'perlu_diperiksa' => 0], + 'kartu' => ['sudah_mengisi' => 0, 'belum_pernah_mengirim' => 0, 'perlu_diperiksa' => 0, 'isian_nonaktif' => 0], 'tabel' => ['columns' => ['desa', 'kecamatan', 'kelengkapan', 'status', 'kualitas'], 'rows' => []], 'semua_baris' => [], ]; diff --git a/app/Services/StatusDesaService.php b/app/Services/StatusDesaService.php new file mode 100644 index 00000000..6ae74307 --- /dev/null +++ b/app/Services/StatusDesaService.php @@ -0,0 +1,204 @@ + $filter kode_kecamatan, status (aktif|nonaktif), page + * @return array{tersedia: bool, baris: array>, halaman: int, total_halaman: int, total: int, per_halaman: int, ringkasan: array, ringkasan_status: array{total: int, aktif: int, nonaktif: int}|null} + */ + public function daftar(array $filter): array + { + $halaman = max(1, (int) ($filter['page'] ?? 1)); + $query = array_filter([ + 'kode_kecamatan' => $this->teks($filter['kode_kecamatan'] ?? null), + 'status' => in_array($filter['status'] ?? null, ['aktif', 'nonaktif'], true) ? $filter['status'] : null, + 'page' => ['number' => $halaman, 'size' => self::PER_HALAMAN], + ], static fn ($v) => $v !== null); + + $result = $this->dataspasial->listDesa($query); + + if ($result->isUnavailable()) { + return [ + 'tersedia' => false, + 'baris' => [], + 'halaman' => $halaman, + 'total_halaman' => 1, + 'total' => 0, + 'per_halaman' => self::PER_HALAMAN, + 'ringkasan' => ['total' => 0, 'nonaktif' => 0], + 'ringkasan_status' => null, + ]; + } + + $baris = array_values(array_filter(array_map( + fn (array $item): ?array => $this->normalisasiBaris($item), + $result->data + ))); + $pagination = $result->pagination(); + + return [ + 'tersedia' => true, + 'baris' => $baris, + 'halaman' => (int) ($pagination['current_page'] ?? $halaman), + 'total_halaman' => max(1, (int) ($pagination['total_pages'] ?? 1)), + 'total' => (int) ($pagination['total'] ?? count($baris)), + 'per_halaman' => (int) ($pagination['per_page'] ?? self::PER_HALAMAN), + 'ringkasan' => [ + 'total' => count($baris), + 'nonaktif' => count(array_filter($baris, static fn (array $b): bool => ! $b['isian_aktif'])), + ], + 'ringkasan_status' => $this->ringkasanStatus($result->meta['ringkasan_status'] ?? null), + ]; + } + + /** + * Nonaktifkan / aktifkan seluruh desa pada cakupan (kabupaten, dipersempit kecamatan bila diberikan). + */ + public function ubahStatusMassal(bool $aktif, ?string $alasan, ?string $kodeKecamatan): DataSpasialResult + { + return $this->dataspasial->ubahStatusDesaMassal($aktif, $alasan, $kodeKecamatan); + } + + /** + * Pesan flash setelah aksi massal; angka diambil dari respons API, bukan dari modal. + */ + public function pesanMassal(DataSpasialResult $result, bool $aktif, ?string $namaKecamatan): string + { + $item = is_array($result->first()) ? $result->first() : []; + $atribut = is_array($item['attributes'] ?? null) ? $item['attributes'] : []; + $diubah = (int) ($atribut['jumlah_diubah'] ?? 0); + $tetap = (int) ($atribut['jumlah_tidak_berubah'] ?? 0); + $cakupan = $namaKecamatan !== null ? "di Kecamatan {$namaKecamatan}" : 'se-kabupaten'; + + if ($aktif) { + $pesan = "Pengisian Data Spasial {$diubah} desa {$cakupan} telah diaktifkan kembali."; + + return $tetap > 0 ? "{$pesan} {$tetap} desa sudah aktif sebelumnya." : $pesan; + } + + $pesan = "Pengisian Data Spasial {$diubah} desa {$cakupan} telah dinonaktifkan."; + + return $tetap > 0 ? "{$pesan} {$tetap} desa sudah nonaktif sebelumnya dan alasannya tidak diubah." : $pesan; + } + + /** + * Nonaktifkan (`$aktif=false`, alasan wajib) atau aktifkan kembali pengisian satu desa. + */ + public function ubahStatus(int $configId, bool $aktif, ?string $alasan): DataSpasialResult + { + return $this->dataspasial->ubahStatusDesa($configId, $aktif, $alasan); + } + + /** + * Pesan untuk flash setelah ubah status berhasil. + */ + public function pesanBerhasil(DataSpasialResult $result, bool $aktif): string + { + $item = is_array($result->first()) ? $result->first() : []; + $atribut = is_array($item['attributes'] ?? null) ? $item['attributes'] : []; + $nama = (string) ($atribut['nama_desa'] ?? 'Desa'); + + return $aktif + ? "Pengisian Data Spasial {$nama} telah diaktifkan kembali." + : "Pengisian Data Spasial {$nama} telah dinonaktifkan. Operator desa tidak dapat mengubah data sampai diaktifkan kembali."; + } + + /** + * @return array> + */ + public function pilihanStatus(): array + { + return [ + ['value' => '', 'label' => 'Semua Status'], + ['value' => 'aktif', 'label' => 'Aktif'], + ['value' => 'nonaktif', 'label' => 'Nonaktif'], + ]; + } + + /** + * @param array $item + * @return array|null + */ + private function normalisasiBaris(array $item): ?array + { + $atribut = is_array($item['attributes'] ?? null) ? $item['attributes'] : $item; + + if ($atribut === [] || ! isset($atribut['config_id'])) { + return null; + } + + $aktif = (bool) ($atribut['isian_aktif'] ?? true); + + return [ + 'config_id' => (int) $atribut['config_id'], + 'kode_desa' => (string) ($atribut['kode_desa'] ?? ''), + 'nama_desa' => (string) ($atribut['nama_desa'] ?? ''), + 'kode_kecamatan' => (string) ($atribut['kode_kecamatan'] ?? ''), + 'nama_kecamatan' => (string) ($atribut['nama_kecamatan'] ?? ($atribut['kode_kecamatan'] ?? '')), + 'isian_aktif' => $aktif, + 'status_label' => $aktif ? 'Aktif' : 'Nonaktif', + 'warna_lencana' => $aktif ? 'success' : 'danger', + 'alasan_nonaktif' => $this->teks($atribut['alasan_nonaktif'] ?? null), + 'dinonaktifkan_oleh' => $this->teks($atribut['dinonaktifkan_oleh'] ?? null), + 'dinonaktifkan_pada' => $this->teks($atribut['dinonaktifkan_pada'] ?? null), + 'dinonaktifkan_pada_label' => $this->formatTanggal($atribut['dinonaktifkan_pada'] ?? null), + ]; + } + + /** + * `meta.ringkasan_status` API; null bila API versi lama belum mengirimnya. + * + * @return array{total: int, aktif: int, nonaktif: int}|null + */ + private function ringkasanStatus(mixed $ringkasan): ?array + { + if (! is_array($ringkasan) || ! isset($ringkasan['total'], $ringkasan['aktif'], $ringkasan['nonaktif'])) { + return null; + } + + return [ + 'total' => (int) $ringkasan['total'], + 'aktif' => (int) $ringkasan['aktif'], + 'nonaktif' => (int) $ringkasan['nonaktif'], + ]; + } + + private function teks(mixed $nilai): ?string + { + return is_string($nilai) && trim($nilai) !== '' ? trim($nilai) : null; + } + + private function formatTanggal(mixed $nilai): string + { + if (! is_string($nilai) || trim($nilai) === '') { + return '—'; + } + + try { + return Carbon::parse($nilai)->translatedFormat('d M Y H:i'); + } catch (\Throwable) { + return '—'; + } + } +} diff --git a/catatan_rilis.md b/catatan_rilis.md index 8f4fa013..485e4e6d 100644 --- a/catatan_rilis.md +++ b/catatan_rilis.md @@ -4,6 +4,7 @@ Di rilis ini, versi 2611.0.1 berisi penambahan dan perbaikan yang diminta penggu 1. [#1320](https://github.com/OpenSID/OpenKab/issues/1320) Tambahkan user akses khusus mengelola data tertentu dari dataspasial. 2. [#1324](https://github.com/OpenSID/OpenKab/issues/1324) Tambahkan fungsi reset password pada pengguna. +3. [#1326](https://github.com/OpenSID/OpenKab/issues/1326) Halaman "Status Desa": nonaktifkan/aktifkan pengisian Data Spasial per desa. #### Perbaikan BUG diff --git a/database/migrations/2026_11_17_000001_add_dataspasial_desa_permission_and_menu.php b/database/migrations/2026_11_17_000001_add_dataspasial_desa_permission_and_menu.php new file mode 100644 index 00000000..4e07db8b --- /dev/null +++ b/database/migrations/2026_11_17_000001_add_dataspasial_desa_permission_and_menu.php @@ -0,0 +1,231 @@ +> + */ + private const ROLES = [ + 'admin skema' => ['read', 'write'], + 'operator impor' => ['read'], + 'analis opd' => ['read'], + ]; + + public function up(): void + { + Permission::findOrCreate(self::PARENT_PERMISSION, 'web'); + Permission::findOrCreate(self::PERMISSION.'-read', 'web'); + Permission::findOrCreate(self::PERMISSION.'-write', 'web'); + + $submenu = $this->submenuStatusDesa(); + + if ($submenu === null) { + // Menu belum terdaftar di `App\Enums\Modul::Menu` (kode & menu harus sinkron). + return; + } + + foreach (self::ROLES as $roleName => $abilities) { + $this->applyToRole($roleName, $this->withAbilityFlags($submenu, $abilities), $abilities); + } + + if (Team::where('name', 'administrator')->exists()) { + Artisan::call('admin:menu-update'); + } + } + + public function down(): void + { + foreach (array_keys(self::ROLES) as $roleName) { + $team = Team::where('name', $roleName)->first(); + + if (! $team) { + continue; + } + + $menu = $this->hapusSubmenu($team->menu); + + if ($menu !== null) { + $team->update(['menu' => $menu]); + } + + setPermissionsTeamId($team->id); + + $role = Role::where('team_id', $team->id)->where('name', $roleName)->first(); + + $role?->revokePermissionTo([self::PERMISSION.'-read', self::PERMISSION.'-write']); + } + + setPermissionsTeamId(null); + + if (Team::where('name', 'administrator')->exists()) { + Artisan::call('admin:menu-update'); + } + + Permission::whereIn('name', [self::PERMISSION.'-read', self::PERMISSION.'-write'])->delete(); + } + + // ----------------------------------------------------------------------- + + /** + * @param array $submenu + * @param array $abilities + */ + private function applyToRole(string $roleName, array $submenu, array $abilities): void + { + $team = Team::where('name', $roleName)->first(); + + if (! $team) { + return; + } + + $menu = $this->tambahSubmenu($team->menu, $submenu, $abilities); + + if ($menu !== null) { + $team->update(['menu' => $menu]); + } + + setPermissionsTeamId($team->id); + + $role = Role::firstOrCreate([ + 'name' => $roleName, + 'team_id' => $team->id, + 'guard_name' => 'web', + ]); + + $permissions = array_map(fn (string $a) => self::PERMISSION.'-'.$a, $abilities); + + // Gabungkan (bukan ganti) supaya izin lain yang ditambahkan admin secara lokal tidak hilang. + $role->syncPermissions(array_values(array_unique(array_merge( + $role->permissions->pluck('name')->all(), + $permissions + )))); + } + + /** + * @return array|null + */ + private function submenuStatusDesa(): ?array + { + foreach (Modul::Menu as $group) { + if (($group['text'] ?? null) !== 'DataSpasial') { + continue; + } + + foreach ($group['submenu'] ?? [] as $item) { + if (($item['permission'] ?? null) === self::PERMISSION) { + return $item; + } + } + } + + return null; + } + + /** + * @param mixed $menu + * @param array $submenu + * @param array $abilities + * @return array>|null + */ + private function tambahSubmenu(mixed $menu, array $submenu, array $abilities): ?array + { + $menu = is_array($menu) ? $menu : []; + + foreach ($menu as $index => $group) { + if (($group['text'] ?? null) !== 'DataSpasial') { + continue; + } + + $submenus = array_values(array_filter( + $group['submenu'] ?? [], + static fn ($item): bool => ($item['permission'] ?? null) !== self::PERMISSION + )); + $submenus[] = $submenu; + + $group['submenu'] = $submenus; + foreach ($abilities as $ability) { + $group[self::PERMISSION.'-'.$ability] = true; + } + + $menu[$index] = $group; + + return $menu; + } + + return null; + } + + /** + * @param mixed $menu + * @return array>|null + */ + private function hapusSubmenu(mixed $menu): ?array + { + if (! is_array($menu)) { + return null; + } + + foreach ($menu as $index => $group) { + if (($group['text'] ?? null) !== 'DataSpasial') { + continue; + } + + $group['submenu'] = array_values(array_filter( + $group['submenu'] ?? [], + static fn ($item): bool => ($item['permission'] ?? null) !== self::PERMISSION + )); + unset($group[self::PERMISSION.'-read'], $group[self::PERMISSION.'-write']); + + $menu[$index] = $group; + + return $menu; + } + + return null; + } + + /** + * @param array $item + * @param array $abilities + * @return array + */ + private function withAbilityFlags(array $item, array $abilities): array + { + $permission = (string) ($item['permission'] ?? ''); + + foreach (['read', 'write', 'edit', 'delete'] as $ability) { + $item[$permission.'-'.$ability] = in_array($ability, $abilities, true); + } + + $item['selected'] = true; + + return $item; + } +}; diff --git a/public/js/dataspasial/monitoring.js b/public/js/dataspasial/monitoring.js index 87cdfe5c..954cbdbf 100644 --- a/public/js/dataspasial/monitoring.js +++ b/public/js/dataspasial/monitoring.js @@ -106,8 +106,12 @@ return; } tb.innerHTML = rows.map(function (r) { + // KAB-09: desa yang pengisiannya dinonaktifkan kabupaten diberi lencana + var lencanaNonaktif = r.isian_aktif === false + ? ' Nonaktif' + : ''; return '' + - '' + esc(r.nama_desa) + '
' + esc(r.kode_desa) + '' + + '' + esc(r.nama_desa) + '' + lencanaNonaktif + '
' + esc(r.kode_desa) + '' + '' + esc(r.nama_kecamatan || r.kode_kecamatan || '—') + '' + '' + barKelengkapan(r.kelengkapan_persen) + '' + '' + (r.skor_kualitas === null ? '—' : r.skor_kualitas diff --git a/public/js/dataspasial/status-desa.js b/public/js/dataspasial/status-desa.js new file mode 100644 index 00000000..53a1b762 --- /dev/null +++ b/public/js/dataspasial/status-desa.js @@ -0,0 +1,268 @@ +/** + * Halaman Status Desa DataSpasial (KAB-09 / API-09). + * + * Tabel desa dimuat lewat AJAX (filter kecamatan + status, paginasi); tombol + * Nonaktifkan/Aktifkan membuka modal konfirmasi yang mengirim form POST biasa + * (CSRF dari @csrf) sehingga hasilnya tampil sebagai flash message. + * + * Tombol massal "Nonaktifkan/Aktifkan Semua Desa" memakai cakupan filter kecamatan + * (tanpa filter = se-kabupaten) dan jumlah terdampak dari `ringkasan_status` + * (seluruh cakupan, bukan hanya halaman yang tampil). + */ +(function () { + 'use strict'; + + var opts = {}; + var state = { kode_kecamatan: '', status: '', page: 1 }; + var ringkasanStatus = null; + var lastToken = 0; + + function qs(sel) { return document.querySelector(sel); } + + function esc(s) { + return String(s === null || s === undefined ? '' : s) + .replace(/&/g, '&').replace(//g, '>') + .replace(/"/g, '"').replace(/'/g, '''); + } + + function show(id, on) { + var el = qs(id); + if (el) el.style.display = on ? '' : 'none'; + } + + function kolom() { return opts.bolehUbah ? 6 : 5; } + + function readUrl() { + var p = new URLSearchParams(window.location.search); + state.kode_kecamatan = p.get('kode_kecamatan') || ''; + state.status = p.get('status') || ''; + state.page = Math.max(1, parseInt(p.get('page') || '1', 10) || 1); + } + + function syncUrl() { + var p = new URLSearchParams(); + if (state.kode_kecamatan) p.set('kode_kecamatan', state.kode_kecamatan); + if (state.status) p.set('status', state.status); + if (state.page > 1) p.set('page', String(state.page)); + window.history.replaceState(null, '', window.location.pathname + (p.toString() ? '?' + p.toString() : '')); + } + + function lencana(r) { + return '' + esc(r.status_label) + ''; + } + + function tombolAksi(r) { + if (!opts.bolehUbah) return ''; + var label = r.isian_aktif ? 'Nonaktifkan' : 'Aktifkan'; + var kelas = r.isian_aktif ? 'btn-outline-danger' : 'btn-outline-success'; + var ikon = r.isian_aktif ? 'fa-lock' : 'fa-lock-open'; + return ''; + } + + function renderTabel(baris) { + var tb = qs('#status-desa-tbody'); + if (!baris.length) { + tb.innerHTML = 'Tidak ada desa untuk pilihan ini.'; + return; + } + tb.innerHTML = baris.map(function (r) { + var oleh = r.dinonaktifkan_oleh ? '
oleh ' + esc(r.dinonaktifkan_oleh) + '' : ''; + return '' + + '' + esc(r.nama_desa) + '
' + esc(r.kode_desa) + '' + + '' + esc(r.nama_kecamatan || '—') + '' + + '' + lencana(r) + '' + + '' + esc(r.alasan_nonaktif || '—') + '' + + '' + (r.isian_aktif ? '—' : esc(r.dinonaktifkan_pada_label) + oleh) + '' + + tombolAksi(r) + + ''; + }).join(''); + } + + // ------------------------------------------------------------- massal + + function namaKecamatanTerpilih() { + var kec = qs('#filter_kecamatan_status'); + if (!kec || !state.kode_kecamatan || kec.selectedIndex < 0) return ''; + return (kec.options[kec.selectedIndex].text || '').trim(); + } + + function teksCakupan() { + return state.kode_kecamatan ? 'di Kecamatan ' + (namaKecamatanTerpilih() || state.kode_kecamatan) : 'se-kabupaten'; + } + + /** Jumlah desa yang akan berubah: nonaktifkan → desa aktif, aktifkan → desa nonaktif. */ + function jumlahTerdampak(aktifkan) { + if (!ringkasanStatus) return 0; + return aktifkan ? (ringkasanStatus.nonaktif || 0) : (ringkasanStatus.aktif || 0); + } + + /** + * Label tombol tetap pendek ("Nonaktifkan Semua" / "Aktifkan Semua"); jumlah desa dan cakupan + * hanya ditampilkan di modal. Cakupan tetap terlihat lewat tooltip. + */ + function renderTombolMassal() { + document.querySelectorAll('.tombol-status-massal').forEach(function (tombol) { + var aktifkan = tombol.getAttribute('data-aktif') === '1'; + var n = jumlahTerdampak(aktifkan); + tombol.disabled = !ringkasanStatus || n === 0; + tombol.title = !ringkasanStatus + ? 'Jumlah desa belum dapat dihitung' + : (n === 0 + ? 'Tidak ada desa yang perlu diubah pada cakupan ini' + : (aktifkan ? 'Aktifkan' : 'Nonaktifkan') + ' semua desa ' + teksCakupan()); + }); + } + + function bukaModalMassal(aktifkan) { + var form = qs('#form-status-massal'); + if (!form) return; + var n = jumlahTerdampak(aktifkan); + var total = ringkasanStatus ? ringkasanStatus.total : 0; + + qs('#massal-aktif').value = aktifkan ? '1' : '0'; + qs('#massal-kode-kecamatan').value = state.kode_kecamatan; + qs('#massal-nama-kecamatan').value = state.kode_kecamatan ? namaKecamatanTerpilih() : ''; + qs('#massal-status-filter').value = state.status; + qs('#judul-modal-massal').textContent = aktifkan ? 'Aktifkan Semua Desa' : 'Nonaktifkan Semua Desa'; + qs('#teks-modal-massal').textContent = aktifkan + ? n + ' dari ' + total + ' desa ' + teksCakupan() + ' akan dapat kembali mengisi data spasial.' + : n + ' dari ' + total + ' desa ' + teksCakupan() + ' tidak akan dapat menambah, mengubah, atau mengisi data spasial sampai diaktifkan kembali.'; + + var alasan = qs('#massal-alasan'); + alasan.value = ''; + alasan.required = !aktifkan; + show('#grup-alasan-massal', !aktifkan); + show('#catatan-desa-baru', !aktifkan); + + var konfirmasi = qs('#massal-konfirmasi'); + konfirmasi.checked = false; + var simpan = qs('#tombol-simpan-massal'); + simpan.disabled = true; + simpan.textContent = aktifkan ? 'Aktifkan Semua' : 'Nonaktifkan Semua'; + simpan.className = 'btn ' + (aktifkan ? 'btn-success' : 'btn-danger'); + + if (window.jQuery) window.jQuery('#modal-status-massal').modal('show'); + } + + function renderPaginasi(meta) { + var nav = qs('#status-desa-paginasi'); + if (!nav) return; + if (!meta || meta.total_pages <= 1) { nav.innerHTML = ''; return; } + var html = '
    '; + for (var i = 1; i <= meta.total_pages; i++) { + html += '
  • ' + + '' + i + '
  • '; + } + nav.innerHTML = html + '
'; + } + + function muat() { + var token = ++lastToken; + syncUrl(); + show('#status-desa-loading', true); + show('#status-desa-empty', false); + show('#status-desa-unavailable', false); + + var p = new URLSearchParams(); + if (state.kode_kecamatan) p.set('kode_kecamatan', state.kode_kecamatan); + if (state.status) p.set('status', state.status); + p.set('page', String(state.page)); + + fetch(opts.dataUrl + '?' + p.toString(), { headers: { 'Accept': 'application/json' }, credentials: 'same-origin' }) + .then(function (res) { return res.json(); }) + .then(function (body) { + if (token !== lastToken) return; + show('#status-desa-loading', false); + var meta = body.meta || {}; + ringkasanStatus = body.ringkasan_status || null; + renderTombolMassal(); + if (meta.unavailable) { + show('#status-desa-unavailable', true); + renderTabel([]); + renderPaginasi(null); + return; + } + show('#status-desa-empty', !!meta.empty); + renderTabel(body.baris || []); + renderPaginasi(meta); + var ringkas = qs('#ringkasan-nonaktif'); + if (ringkas) { + var n = (body.ringkasan || {}).nonaktif || 0; + ringkas.textContent = n + ' desa nonaktif di halaman ini'; + ringkas.style.display = n > 0 ? '' : 'none'; + } + }) + .catch(function () { + if (token !== lastToken) return; + show('#status-desa-loading', false); + show('#status-desa-unavailable', true); + ringkasanStatus = null; + renderTombolMassal(); + }); + } + + function bukaModal(id, nama, aktifSekarang) { + var form = qs('#form-status-desa'); + if (!form) return; + var menonaktifkan = aktifSekarang; + form.setAttribute('action', form.getAttribute('data-action').replace('__ID__', encodeURIComponent(id))); + qs('#input-aktif').value = menonaktifkan ? '0' : '1'; + qs('#input-kode-kecamatan').value = state.kode_kecamatan; + qs('#input-status-filter').value = state.status; + qs('#judul-modal-status').textContent = menonaktifkan ? 'Nonaktifkan Pengisian Desa' : 'Aktifkan Kembali Pengisian Desa'; + qs('#teks-modal-status').textContent = menonaktifkan + ? 'Operator ' + nama + ' tidak akan dapat menambah, mengubah, atau mengisi data spasial sampai diaktifkan kembali.' + : 'Operator ' + nama + ' akan dapat kembali mengisi data spasial.'; + var alasan = qs('#input-alasan'); + alasan.value = ''; + alasan.required = menonaktifkan; + show('#grup-alasan', menonaktifkan); + var tombol = qs('#tombol-simpan-status'); + tombol.textContent = menonaktifkan ? 'Nonaktifkan' : 'Aktifkan'; + tombol.className = 'btn ' + (menonaktifkan ? 'btn-danger' : 'btn-success'); + if (window.jQuery) window.jQuery('#modal-status-desa').modal('show'); + } + + function init(o) { + opts = o || {}; + readUrl(); + + var kec = qs('#filter_kecamatan_status'); + var status = qs('#filter_status_desa'); + if (kec) { kec.value = state.kode_kecamatan; kec.addEventListener('change', function () { state.kode_kecamatan = kec.value; state.page = 1; muat(); }); } + if (status) { status.value = state.status; status.addEventListener('change', function () { state.status = status.value; state.page = 1; muat(); }); } + + document.addEventListener('click', function (e) { + var halaman = e.target.closest('#status-desa-paginasi [data-page]'); + if (halaman) { + e.preventDefault(); + state.page = parseInt(halaman.getAttribute('data-page'), 10) || 1; + muat(); + return; + } + var tombol = e.target.closest('.tombol-ubah-status'); + if (tombol) { + bukaModal(tombol.getAttribute('data-id'), tombol.getAttribute('data-nama'), tombol.getAttribute('data-aktif') === '1'); + return; + } + var massal = e.target.closest('.tombol-status-massal'); + if (massal && !massal.disabled) { + bukaModalMassal(massal.getAttribute('data-aktif') === '1'); + } + }); + + // Tombol simpan massal hanya aktif setelah konfirmasi dicentang + var konfirmasi = qs('#massal-konfirmasi'); + if (konfirmasi) { + konfirmasi.addEventListener('change', function () { + qs('#tombol-simpan-massal').disabled = !konfirmasi.checked; + }); + } + + muat(); + } + + window.StatusDesaDataSpasial = { init: init }; +})(); diff --git a/resources/views/dataspasial/desa/index.blade.php b/resources/views/dataspasial/desa/index.blade.php new file mode 100644 index 00000000..ab6033ef --- /dev/null +++ b/resources/views/dataspasial/desa/index.blade.php @@ -0,0 +1,236 @@ +{{-- + Halaman Status Desa (KAB-09 / API-09 / SID-11). + + Pemerintah Kabupaten menonaktifkan atau mengaktifkan kembali pengisian Data Spasial + per desa. Desa nonaktif tidak dapat menambah/mengubah fasilitas maupun mengisi isian + dinamis di OpenSID (mode Terpusat); data lama tetap tampil di peta dan dasbor. + Tabel dimuat lewat AJAX; ubah status memakai form POST dengan flash message. +--}} +@extends('layouts.index') + +@section('title', $title) + +@section('content_header') +

{{ $title }}

+@stop + +@section('content') + @include('partials.breadcrumbs') + @include('partials.flash_message') + +
+
+
+

+ Desa yang dinonaktifkan tidak dapat menambah fasilitas, mengubah fasilitas, + maupun mengisi isian dinamis Data Spasial di OpenSID. Data yang sudah ada tetap tampil di + Peta Gabungan dan Dasbor, dan Impor Data dari OpenKab tetap dapat dilakukan. +

+
+
+
+ + {{-- Blok Filter --}} +
+
+
+

Filter

+
+
+
+
+ +
+
+ + +
+ @if ($bolehUbah) + {{-- Aksi massal: cakupan mengikuti filter kecamatan (tanpa filter = se-kabupaten). + Tombol aktif setelah jumlah desa per status dimuat (ringkasan_status); + angka & cakupan ditampilkan di modal, bukan di tombol. --}} +
+ {{-- Label kosong hanya untuk meratakan tombol dengan dropdown filter di sebelahnya --}} + +
+ + +
+
+ @endif +
+
+
+
+
+
+ + {{-- Tabel desa --}} +
+
+
+
+

Daftar Desa

+
+ +
+
+
+ + + +
+ + + + + + + + + @if ($bolehUbah) + + @endif + + + + + + + +
DesaKecamatanStatusAlasanDinonaktifkanAksi
Memuat…
+
+
+ +
+
+
+ + @if ($bolehUbah) + {{-- Modal konfirmasi ubah status --}} + + + {{-- Modal konfirmasi aksi massal --}} + + @endif +@stop + +@push('js') + {{-- ?v=filemtime: browser selalu memuat versi terbaru setelah berkas berubah (tanpa ini JS lama dari cache + tidak mengenal tombol massal sehingga tombol tetap disabled) --}} + + +@endpush diff --git a/resources/views/dataspasial/impor/index.blade.php b/resources/views/dataspasial/impor/index.blade.php index b689c5cb..0270271b 100644 --- a/resources/views/dataspasial/impor/index.blade.php +++ b/resources/views/dataspasial/impor/index.blade.php @@ -291,6 +291,15 @@ function renderPreviewTable(rows){ } else { td.textContent = v; } + // API-09: peringatan non-blokir (mis. pengisian desa dinonaktifkan kabupaten) tampil di kolom pesan + if(c === 'pesan' && r.peringatan){ + var warn = document.createElement('div'); + warn.className = 'text-warning small'; + warn.setAttribute('data-testid', 'peringatan-baris'); + warn.textContent = '⚠ ' + r.peringatan; + if(v === '-'){ td.textContent = ''; } + td.appendChild(warn); + } tr.appendChild(td); }); tbody.appendChild(tr); diff --git a/routes/web.php b/routes/web.php index b4c0ef20..9a3e5ef6 100644 --- a/routes/web.php +++ b/routes/web.php @@ -33,6 +33,7 @@ use App\Http\Controllers\DataSpasial\MonitoringController; use App\Http\Controllers\DataSpasial\PetaGabunganController; use App\Http\Controllers\DataSpasial\SkemaDataSpasialController; +use App\Http\Controllers\DataSpasial\StatusDesaController; use App\Http\Controllers\DDKPanganController; use App\Http\Controllers\DepartmentController; use App\Http\Controllers\DesaController; @@ -614,6 +615,21 @@ Route::get('audit/ekspor', [AuditDataSpasialController::class, 'ekspor']) ->middleware('permission:dataspasial-audit-read') ->name('dataspasial.audit.ekspor'); + + // KAB-09 — Status Desa: nonaktifkan/aktifkan pengisian Data Spasial per desa (API-09). + Route::get('desa', [StatusDesaController::class, 'index']) + ->middleware('permission:dataspasial-desa-read') + ->name('dataspasial.desa'); + Route::get('desa/data', [StatusDesaController::class, 'data']) + ->middleware('permission:dataspasial-desa-read') + ->name('dataspasial.desa.data'); + Route::post('desa/status-massal', [StatusDesaController::class, 'ubahStatusMassal']) + ->middleware('permission:dataspasial-desa-write') + ->name('dataspasial.desa.status-massal'); + Route::post('desa/{config_id}/status', [StatusDesaController::class, 'ubahStatus']) + ->whereNumber('config_id') + ->middleware('permission:dataspasial-desa-write') + ->name('dataspasial.desa.status'); }); }); diff --git a/tests/Feature/DataSpasial/DataSpasialDesaPermissionMigrationTest.php b/tests/Feature/DataSpasial/DataSpasialDesaPermissionMigrationTest.php new file mode 100644 index 00000000..78403090 --- /dev/null +++ b/tests/Feature/DataSpasial/DataSpasialDesaPermissionMigrationTest.php @@ -0,0 +1,108 @@ +{$arah}(); +} + +function permissionsDesa(string $teamName): array +{ + $team = Team::where('name', $teamName)->firstOrFail(); + setPermissionsTeamId($team->id); + + return Role::where('team_id', $team->id)->where('name', $teamName)->firstOrFail() + ->permissions->pluck('name')->all(); +} + +function submenuStatusDesa(string $teamName): ?array +{ + foreach (Team::where('name', $teamName)->firstOrFail()->menu ?? [] as $group) { + if (($group['text'] ?? null) !== 'DataSpasial') { + continue; + } + + foreach ($group['submenu'] ?? [] as $item) { + if (($item['permission'] ?? null) === 'dataspasial-desa') { + return $item; + } + } + } + + return null; +} + +beforeEach(function () { + Cache::flush(); + setPermissionsTeamId(Team::where('name', 'administrator')->first()->id); + Artisan::call('admin:menu-update'); + + (require database_path('migrations/2026_10_14_000001_create_dataspasial_roles.php'))->up(); + runDataSpasialDesaMigration(); +}); + +it('memberikan izin baca status desa ke ketiga peran dan izin tulis hanya ke Admin Skema', function () { + expect(permissionsDesa('admin skema'))->toContain('dataspasial-desa-read', 'dataspasial-desa-write'); + + foreach (['operator impor', 'analis opd'] as $peran) { + expect(permissionsDesa($peran))->toContain('dataspasial-desa-read') + ->not->toContain('dataspasial-desa-write'); + } +}); + +it('menambahkan submenu Status Desa beserta flag hak akses', function () { + $admin = submenuStatusDesa('admin skema'); + $analis = submenuStatusDesa('analis opd'); + + expect($admin)->not->toBeNull() + ->and($admin['url'])->toBe('dataspasial/desa') + ->and($admin['dataspasial-desa-read'])->toBeTrue() + ->and($admin['dataspasial-desa-write'])->toBeTrue() + ->and($analis['dataspasial-desa-write'])->toBeFalse(); +}); + +it('memberikan role administrator akses menu Status Desa lewat Modul::Menu', function () { + $team = Team::where('name', 'administrator')->firstOrFail(); + setPermissionsTeamId($team->id); + $permissions = Role::where('team_id', $team->id)->where('name', 'administrator')->firstOrFail() + ->permissions->pluck('name')->all(); + + expect($permissions)->toContain('dataspasial-desa-read', 'dataspasial-desa-write'); +}); + +it('aman dijalankan berulang tanpa menggandakan submenu maupun permission', function () { + runDataSpasialDesaMigration(); + + $jumlah = 0; + foreach (Team::where('name', 'admin skema')->firstOrFail()->menu as $group) { + if (($group['text'] ?? null) === 'DataSpasial') { + $jumlah = count(array_filter($group['submenu'], fn ($i) => ($i['permission'] ?? null) === 'dataspasial-desa')); + } + } + + expect($jumlah)->toBe(1) + ->and(Permission::where('name', 'dataspasial-desa-write')->where('guard_name', 'web')->count())->toBe(1); +}); + +it('rollback mencabut submenu dan izin status desa', function () { + runDataSpasialDesaMigration('down'); + + expect(submenuStatusDesa('admin skema'))->toBeNull() + ->and(Permission::where('name', 'dataspasial-desa-read')->exists())->toBeFalse(); +}); diff --git a/tests/Feature/DataSpasial/MonitoringDataTest.php b/tests/Feature/DataSpasial/MonitoringDataTest.php index 593816b3..e2a3f252 100644 --- a/tests/Feature/DataSpasial/MonitoringDataTest.php +++ b/tests/Feature/DataSpasial/MonitoringDataTest.php @@ -118,7 +118,7 @@ public function test_cards_and_row_semantics_match_fixtures(): void // Kartu dasar (aturan tanda dihapus): sudah=4, belum=1, perlu_diperiksa = tertinggal + belum (perlu tindakan). $this->assertSame( - ['sudah_mengisi' => 4, 'belum_pernah_mengirim' => 1, 'perlu_diperiksa' => 2, 'total_desa' => 5, 'sudah_mengisi_label' => '4/5'], + ['sudah_mengisi' => 4, 'belum_pernah_mengirim' => 1, 'perlu_diperiksa' => 2, 'total_desa' => 5, 'sudah_mengisi_label' => '4/5', 'isian_nonaktif' => 0], $resp->json('kartu') ); @@ -243,4 +243,39 @@ public function test_row_order_puts_action_needed_first(): void // Perlu tindakan: tertinggal (Bantas) & belum (Cekatak) lebih dulu — lalu nama menaik. $this->assertSame(['5102022003', '5102022004', '5102012001', '5102012005', '5102012006'], $kode); } + + public function test_desa_nonaktif_tidak_dihitung_belum_mengirim_maupun_perlu_diperiksa(): void + { + $this->actingAsPembaca(); + + // KAB-09: Cekatak (belum pernah mengirim) dinonaktifkan kabupaten lewat API-09. + $adopsi = fxMonitoringAdopsi(); + foreach ($adopsi['data'] as $i => $baris) { + $adopsi['data'][$i]['attributes']['isian_aktif'] = $baris['attributes']['kode_desa'] !== '5102022004'; + } + fakeEndpointMonitoring($adopsi); + + $resp = $this->getJson('/dataspasial/monitoring/data?sektor=SK0&kode_kecamatan=SEMUA&periode=2025-06') + ->assertOk(); + + $this->assertSame(0, $resp->json('kartu.belum_pernah_mengirim')); + $this->assertSame(1, $resp->json('kartu.perlu_diperiksa'), 'Hanya Bantas (tertinggal) yang perlu diperiksa'); + $this->assertSame(1, $resp->json('kartu.isian_nonaktif')); + + $cekatak = collect($resp->json('tabel.rows'))->firstWhere('kode_desa', '5102022004'); + $this->assertFalse($cekatak['isian_aktif']); + $this->assertFalse($cekatak['perlu_tindakan']); + $this->assertSame('belum_pernah_mengirim', $cekatak['status_pengisian']); + } + + public function test_respons_adopsi_lama_tanpa_isian_aktif_dianggap_aktif(): void + { + $this->actingAsPembaca(); + fakeEndpointMonitoring(); + + $rows = collect($this->getJson('/dataspasial/monitoring/data?sektor=SK0&kode_kecamatan=SEMUA&periode=2025-06') + ->assertOk()->json('tabel.rows')); + + $this->assertTrue($rows->every(fn (array $r) => $r['isian_aktif'] === true)); + } } diff --git a/tests/Feature/DataSpasial/StatusDesaTest.php b/tests/Feature/DataSpasial/StatusDesaTest.php new file mode 100644 index 00000000..d8574b7e --- /dev/null +++ b/tests/Feature/DataSpasial/StatusDesaTest.php @@ -0,0 +1,441 @@ + 'https://api.example.test', 'dataspasial.cache_ttl' => 300]); + Setting::query()->updateOrCreate(['key' => 'database_gabungan_api_key'], ['value' => 'test-token']); + Cache::flush(); + } + + private function actingAsPembaca(): void + { + $this->actingAs(makeRole('pembaca status desa uji k09', ['dataspasial-desa-read'])); + } + + private function actingAsPengelola(): void + { + $this->actingAs(makeRole('pengelola status desa uji k09', ['dataspasial-desa-read', 'dataspasial-desa-write'])); + } + + /** + * @return array + */ + private function barisDesa(int $configId, string $nama, bool $aktif, ?string $alasan = null): array + { + return [ + 'type' => 'status isian desa', + 'id' => (string) $configId, + 'attributes' => [ + 'config_id' => $configId, + 'kode_desa' => '510201200'.$configId, + 'nama_desa' => $nama, + 'kode_kecamatan' => '510201', + 'nama_kecamatan' => 'Kediri', + 'kode_kabupaten' => '5102', + 'isian_aktif' => $aktif, + 'alasan_nonaktif' => $aktif ? null : $alasan, + 'dinonaktifkan_oleh' => $aktif ? null : 'Budi Santoso', + 'dinonaktifkan_pada' => $aktif ? null : '2026-11-17 09:00:00', + ], + ]; + } + + private function fakeDaftar(): void + { + Http::fake([ + '*/api/v1/config/*' => Http::response(fakeConfigEndpoint(), 200), + '*/api/v1/dataspasial/desa*' => Http::response([ + 'data' => [ + $this->barisDesa(1, 'Bajera', true), + $this->barisDesa(2, 'Bantas', false, 'Data belum diverifikasi'), + ], + 'meta' => [ + 'ringkasan_status' => ['total' => 12, 'aktif' => 11, 'nonaktif' => 1], + 'pagination' => ['total' => 2, 'count' => 2, 'per_page' => 25, 'current_page' => 1, 'total_pages' => 1], + ], + ], 200), + '*' => Http::response(['data' => []], 200), + ]); + } + + /** + * Respons `PUT /dataspasial/desa/status` (massal) sesuai DesaController::ubahStatusMassal. + * + * @return array + */ + private function hasilMassal(bool $aktif, int $diubah, int $tetap, ?string $kodeKecamatan = null): array + { + return [ + 'data' => [ + 'type' => 'status isian desa massal', + 'attributes' => [ + 'aktif' => $aktif, + 'kode_kabupaten' => '5102', + 'kode_kecamatan' => $kodeKecamatan, + 'jumlah_desa' => $diubah + $tetap, + 'jumlah_diubah' => $diubah, + 'jumlah_tidak_berubah' => $tetap, + ], + ], + ]; + } + + // ----------------------------------------------------------------------- + // Akses + // ----------------------------------------------------------------------- + + public function test_guest_is_redirected(): void + { + $this->get('/dataspasial/desa')->assertRedirect('/login'); + } + + public function test_user_without_permission_is_rejected(): void + { + $tanpaIzin = makeRole('tanpa status desa uji k09', []); + + $this->actingAs($tanpaIzin)->get('/dataspasial/desa')->assertForbidden(); + $this->actingAs($tanpaIzin)->getJson('/dataspasial/desa/data')->assertForbidden(); + } + + public function test_pembaca_tidak_boleh_mengubah_status(): void + { + Http::fake(); + $this->actingAsPembaca(); + + $this->post('/dataspasial/desa/1/status', ['aktif' => 0, 'alasan' => 'Coba'])->assertForbidden(); + + Http::assertNothingSent(); + } + + // ----------------------------------------------------------------------- + // Halaman & data + // ----------------------------------------------------------------------- + + public function test_pembaca_melihat_halaman_tanpa_kolom_aksi(): void + { + $this->fakeDaftar(); + $this->actingAsPembaca(); + + $this->get('/dataspasial/desa') + ->assertOk() + ->assertSee('data-testid="status-desa-filter"', false) + ->assertSee('data-testid="tabel-status-desa"', false) + ->assertDontSee('data-testid="modal-status-desa"', false); + } + + public function test_pengelola_melihat_modal_ubah_status(): void + { + $this->fakeDaftar(); + $this->actingAsPengelola(); + + $this->get('/dataspasial/desa') + ->assertOk() + ->assertSee('data-testid="modal-status-desa"', false) + ->assertSee('data-testid="input-alasan"', false); + } + + public function test_data_menormalkan_baris_api(): void + { + $this->fakeDaftar(); + $this->actingAsPembaca(); + + $resp = $this->getJson('/dataspasial/desa/data?status=nonaktif&kode_kecamatan=510201')->assertOk(); + + $this->assertFalse($resp->json('meta.unavailable')); + $this->assertSame(['total' => 2, 'nonaktif' => 1], $resp->json('ringkasan')); + + $bantas = collect($resp->json('baris'))->firstWhere('config_id', 2); + $this->assertFalse($bantas['isian_aktif']); + $this->assertSame('Nonaktif', $bantas['status_label']); + $this->assertSame('danger', $bantas['warna_lencana']); + $this->assertSame('Data belum diverifikasi', $bantas['alasan_nonaktif']); + $this->assertSame('Budi Santoso', $bantas['dinonaktifkan_oleh']); + $this->assertNotSame('—', $bantas['dinonaktifkan_pada_label']); + + Http::assertSent(fn (Request $r) => str_contains($r->url(), '/api/v1/dataspasial/desa') + && str_contains(urldecode($r->url()), 'status=nonaktif') + && str_contains($r->url(), 'kode_kecamatan=510201')); + } + + public function test_data_tidak_tersedia_tanpa_pesan_teknis(): void + { + Http::fake(['*/api/v1/dataspasial/desa*' => Http::response(['message' => 'SQLSTATE rahasia'], 500)]); + $this->actingAsPembaca(); + + $resp = $this->getJson('/dataspasial/desa/data')->assertOk(); + + $this->assertTrue($resp->json('meta.unavailable')); + $this->assertSame([], $resp->json('baris')); + $this->assertStringNotContainsString('SQLSTATE', $resp->getContent()); + } + + // ----------------------------------------------------------------------- + // Ubah status + // ----------------------------------------------------------------------- + + public function test_nonaktifkan_mengirim_put_ke_api_dan_menginvalidasi_cache(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa/2/status' => Http::response(['data' => $this->barisDesa(2, 'Bantas', false, 'Sedang diaudit')], 200), + ]); + $this->actingAsPengelola(); + $generasiAwal = app(DataSpasialApiService::class)->cacheGeneration(); + + $this->post('/dataspasial/desa/2/status', ['aktif' => 0, 'alasan' => 'Sedang diaudit', 'kode_kecamatan' => '510201']) + ->assertRedirect(route('dataspasial.desa', ['kode_kecamatan' => '510201'])) + ->assertSessionHas('success', fn (string $pesan) => str_contains($pesan, 'Bantas') && str_contains($pesan, 'dinonaktifkan')); + + Http::assertSent(function (Request $r) { + return $r->method() === 'PUT' + && str_ends_with($r->url(), '/api/v1/dataspasial/desa/2/status') + && $r['aktif'] === false + && $r['alasan'] === 'Sedang diaudit' + && $r->hasHeader('X-OpenKab-User-Name'); + }); + $this->assertGreaterThan($generasiAwal, app(DataSpasialApiService::class)->cacheGeneration()); + } + + public function test_aktifkan_tidak_wajib_alasan(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa/2/status' => Http::response(['data' => $this->barisDesa(2, 'Bantas', true)], 200), + ]); + $this->actingAsPengelola(); + + $this->post('/dataspasial/desa/2/status', ['aktif' => 1]) + ->assertRedirect() + ->assertSessionHas('success', fn (string $pesan) => str_contains($pesan, 'diaktifkan kembali')); + + Http::assertSent(fn (Request $r) => $r->method() === 'PUT' && $r['aktif'] === true && ! isset($r['alasan'])); + } + + public function test_nonaktifkan_tanpa_alasan_ditolak_sebelum_memanggil_api(): void + { + Http::fake(); + $this->actingAsPengelola(); + + $this->post('/dataspasial/desa/2/status', ['aktif' => 0]) + ->assertSessionHasErrors(['alasan']); + + Http::assertNothingSent(); + } + + public function test_desa_di_luar_kabupaten_ditampilkan_sebagai_galat(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa/999/status' => Http::response(['message' => 'Desa dengan config_id 999 tidak ditemukan.'], 404), + ]); + $this->actingAsPengelola(); + + $this->post('/dataspasial/desa/999/status', ['aktif' => 0, 'alasan' => 'Coba']) + ->assertRedirect() + ->assertSessionHas('error', 'Desa tidak ditemukan atau berada di luar kabupaten Anda.'); + } + + public function test_api_gagal_tidak_membocorkan_pesan_teknis(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa/2/status' => Http::response(['message' => 'SQLSTATE rahasia'], 500), + ]); + $this->actingAsPengelola(); + + $this->postJson('/dataspasial/desa/2/status', ['aktif' => 0, 'alasan' => 'Coba']) + ->assertStatus(503) + ->assertJsonMissing(['message' => 'SQLSTATE rahasia']) + ->assertJsonPath('success', false); + } + + // ----------------------------------------------------------------------- + // Aksi massal (nonaktifkan / aktifkan semua desa) + // ----------------------------------------------------------------------- + + public function test_tombol_massal_hanya_tampil_untuk_pengelola(): void + { + $this->fakeDaftar(); + + $this->actingAsPembaca(); + $this->get('/dataspasial/desa') + ->assertOk() + ->assertDontSee('data-testid="tombol-nonaktifkan-semua"', false) + ->assertDontSee('data-testid="modal-status-massal"', false); + + $this->actingAsPengelola(); + $html = $this->get('/dataspasial/desa') + ->assertOk() + ->assertSee('data-testid="tombol-nonaktifkan-semua"', false) + ->assertSee('data-testid="tombol-aktifkan-semua"', false) + ->assertSee('data-testid="modal-status-massal"', false) + ->assertSee('data-testid="konfirmasi-massal"', false) + ->getContent(); + + // Tombol berada di card Filter, sesudah filter Status Pengisian, dan sebelum tabel desa + $posStatus = strpos($html, 'data-testid="filter-status"'); + $posAksi = strpos($html, 'data-testid="aksi-massal"'); + $posFormSelesai = strpos($html, '', (int) $posStatus); + $posTabel = strpos($html, 'data-testid="tabel-status-desa"'); + $this->assertNotFalse($posAksi); + $this->assertTrue($posStatus < $posAksi && $posAksi < $posFormSelesai && $posFormSelesai < $posTabel); + + // Script ber-versi agar browser tidak memakai status-desa.js lama dari cache + $this->assertMatchesRegularExpression('#js/dataspasial/status-desa\.js\?v=\d+#', $html); + + // Label tombol pendek, tanpa label kolom; style tombol biasa (bukan outline). Angka hanya di modal. + $this->assertMatchesRegularExpression('#class="btn btn-sm btn-danger tombol-status-massal"[^>]*>\s* Nonaktifkan Semua\s*#', $html); + $this->assertMatchesRegularExpression('#class="btn btn-sm btn-success tombol-status-massal"[^>]*>\s* Aktifkan Semua\s*#', $html); + $this->assertStringNotContainsString('Aksi Semua Desa', $html); + $this->assertStringNotContainsString('btn-outline-danger tombol-status-massal', $html); + } + + public function test_pembaca_tidak_boleh_menjalankan_aksi_massal(): void + { + Http::fake(); + $this->actingAsPembaca(); + + $this->post('/dataspasial/desa/status-massal', ['aktif' => 0, 'alasan' => 'Coba', 'konfirmasi' => 1])->assertForbidden(); + + Http::assertNothingSent(); + } + + public function test_data_meneruskan_ringkasan_status_seluruh_cakupan(): void + { + $this->fakeDaftar(); + $this->actingAsPembaca(); + + $this->getJson('/dataspasial/desa/data?kode_kecamatan=510201') + ->assertOk() + ->assertJsonPath('ringkasan_status', ['total' => 12, 'aktif' => 11, 'nonaktif' => 1]); + } + + public function test_api_lama_tanpa_ringkasan_status_menghasilkan_null(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa*' => Http::response(['data' => [$this->barisDesa(1, 'Bajera', true)]], 200), + ]); + $this->actingAsPembaca(); + + $this->getJson('/dataspasial/desa/data')->assertOk()->assertJsonPath('ringkasan_status', null); + } + + public function test_nonaktifkan_semua_per_kecamatan_mengirim_kode_kecamatan(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa/status' => Http::response($this->hasilMassal(false, 10, 2, '510201'), 200), + ]); + $this->actingAsPengelola(); + $generasiAwal = app(DataSpasialApiService::class)->cacheGeneration(); + + $this->post('/dataspasial/desa/status-massal', [ + 'aktif' => 0, + 'alasan' => 'Verifikasi tahunan', + 'kode_kecamatan' => '510201', + 'nama_kecamatan' => 'Kediri', + 'status' => 'aktif', + 'konfirmasi' => 1, + ]) + ->assertRedirect(route('dataspasial.desa', ['kode_kecamatan' => '510201', 'status' => 'aktif'])) + ->assertSessionHas('success', fn (string $pesan) => str_contains($pesan, '10 desa di Kecamatan Kediri') + && str_contains($pesan, 'dinonaktifkan') + && str_contains($pesan, '2 desa sudah nonaktif')); + + Http::assertSent(function (Request $r) { + return $r->method() === 'PUT' + && str_ends_with($r->url(), '/api/v1/dataspasial/desa/status') + && $r['aktif'] === false + && $r['alasan'] === 'Verifikasi tahunan' + && $r['kode_kecamatan'] === '510201' + && $r->hasHeader('X-OpenKab-User-Name'); + }); + $this->assertGreaterThan($generasiAwal, app(DataSpasialApiService::class)->cacheGeneration()); + } + + public function test_tanpa_filter_kecamatan_berlaku_se_kabupaten(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa/status' => Http::response($this->hasilMassal(false, 133, 0), 200), + ]); + $this->actingAsPengelola(); + + $this->post('/dataspasial/desa/status-massal', ['aktif' => 0, 'alasan' => 'Kunci semua', 'konfirmasi' => 1]) + ->assertRedirect(route('dataspasial.desa')) + ->assertSessionHas('success', fn (string $pesan) => str_contains($pesan, '133 desa se-kabupaten')); + + Http::assertSent(fn (Request $r) => $r->method() === 'PUT' && ! isset($r['kode_kecamatan'])); + } + + public function test_aktifkan_semua_tidak_wajib_alasan(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa/status' => Http::response($this->hasilMassal(true, 5, 0, '510201'), 200), + ]); + $this->actingAsPengelola(); + + $this->post('/dataspasial/desa/status-massal', ['aktif' => 1, 'kode_kecamatan' => '510201', 'nama_kecamatan' => 'Kediri', 'konfirmasi' => 1]) + ->assertRedirect() + ->assertSessionHas('success', fn (string $pesan) => str_contains($pesan, '5 desa di Kecamatan Kediri telah diaktifkan kembali')); + + Http::assertSent(fn (Request $r) => $r->method() === 'PUT' && $r['aktif'] === true && ! isset($r['alasan'])); + } + + public function test_aksi_massal_tanpa_alasan_atau_konfirmasi_ditolak_sebelum_memanggil_api(): void + { + Http::fake(); + $this->actingAsPengelola(); + + $this->post('/dataspasial/desa/status-massal', ['aktif' => 0, 'konfirmasi' => 1]) + ->assertSessionHasErrors(['alasan']); + $this->post('/dataspasial/desa/status-massal', ['aktif' => 0, 'alasan' => 'Coba']) + ->assertSessionHasErrors(['konfirmasi']); + $this->post('/dataspasial/desa/status-massal', ['aktif' => 1, 'kode_kecamatan' => "51'02", 'konfirmasi' => 1]) + ->assertSessionHasErrors(['kode_kecamatan']); + + Http::assertNothingSent(); + } + + public function test_cakupan_kosong_ditampilkan_sebagai_galat(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa/status' => Http::response(['message' => 'Tidak ada desa pada cakupan yang dipilih.'], 404), + ]); + $this->actingAsPengelola(); + + $this->post('/dataspasial/desa/status-massal', ['aktif' => 0, 'alasan' => 'Coba', 'kode_kecamatan' => '999999', 'konfirmasi' => 1]) + ->assertRedirect() + ->assertSessionHas('error', 'Tidak ada desa pada cakupan yang dipilih.'); + } + + public function test_aksi_massal_api_gagal_tidak_membocorkan_pesan_teknis(): void + { + Http::fake([ + '*/api/v1/dataspasial/desa/status' => Http::response(['message' => 'SQLSTATE rahasia'], 500), + ]); + $this->actingAsPengelola(); + + $this->postJson('/dataspasial/desa/status-massal', ['aktif' => 0, 'alasan' => 'Coba', 'konfirmasi' => 1]) + ->assertStatus(503) + ->assertJsonMissing(['message' => 'SQLSTATE rahasia']) + ->assertJsonPath('success', false); + } +}