diff --git a/app/Exports/ImporDataSpasialTemplateExport.php b/app/Exports/ImporDataSpasialTemplateExport.php index d64c4445f..acc25bdb3 100644 --- a/app/Exports/ImporDataSpasialTemplateExport.php +++ b/app/Exports/ImporDataSpasialTemplateExport.php @@ -15,6 +15,7 @@ class ImporDataSpasialTemplateExport public const SHEET_DATA = 'Data Impor'; public const SHEET_DESA = 'Daftar Desa'; public const SHEET_PETUNJUK = 'Petunjuk'; + public const SHEET_LOKASI = 'Daftar Lokasi'; private const DATA_START_ROW = 9; @@ -29,6 +30,7 @@ public function __construct( private string $sektor = '', private string $periode = '', private array $fasilitas = [], + private array $lokasi = [], ) {} /** @@ -62,8 +64,10 @@ public function write(string $filePath): void $writer->addRow(Row::fromValues(['1. Isi kolom sesuai dengan data yang dimiliki.'])); $writer->addRow(Row::fromValues(['2. Pilih desa pada kolom pertama dari daftar dropdown (jika tersedia).'])); $writer->addRow(Row::fromValues(['3. Isi kode_fasilitas dan nama_fasilitas sesuai data.'])); - $writer->addRow(Row::fromValues(['4. Kolom lainnya diisi sesuai skema terbit untuk sektor yang dipilih.'])); - $writer->addRow(Row::fromValues(['5. Jangan mengubah nama sheet atau header kolom.'])); + $writer->addRow(Row::fromValues(['4. Pilih lokasi pada kolom lokasi_id dari daftar lokasi di desa yang sama.'])); + $writer->addRow(Row::fromValues(['5. Kolom lainnya diisi sesuai skema terbit untuk sektor yang dipilih.'])); + $writer->addRow(Row::fromValues(['6. Jangan mengubah nama sheet atau header kolom.'])); + $writer->addRow(Row::fromValues(['Jika lokasi belum tersedia, daftarkan lokasi beserta koordinatnya di peta terlebih dahulu.'])); if ($this->sektor) { $writer->addRow(Row::fromValues([''])); $writer->addRow(Row::fromValues(['Sektor: '.$this->sektor])); @@ -81,7 +85,7 @@ public function write(string $filePath): void $writer->addRow(Row::fromValues([''])); $writer->addRow(Row::fromValues([''])); - $header = ['kode_desa', 'kode_fasilitas', 'nama_fasilitas']; + $header = ['kode_desa', 'kode_fasilitas', 'nama_fasilitas', 'lokasi_id']; foreach ($this->items as $item) { $header[] = self::headerKey($item); } @@ -89,12 +93,17 @@ public function write(string $filePath): void $writer->addRow(Row::fromValues($header), $headerStyle); // Baris data fasilitas yang sudah ada: pengguna cukup mengedit atau menambah baris. - $isianColumns = array_slice($header, 3); + $isianColumns = array_slice($header, 4); + $lokasiLabels = []; + foreach ($this->lokasi as $lokasi) { + $lokasiLabels[$lokasi['id']] = $this->labelLokasi($lokasi); + } foreach ($this->fasilitas as $fasilitas) { $values = [ (string) $fasilitas['kode_desa'], (string) $fasilitas['kode_fasilitas'], (string) $fasilitas['nama_fasilitas'], + $lokasiLabels[$fasilitas['lokasi_id'] ?? ''] ?? (string) ($fasilitas['lokasi_id'] ?? ''), ]; foreach ($isianColumns as $column) { $values[] = $fasilitas['nilai'][$column] ?? ''; @@ -137,20 +146,31 @@ public function write(string $filePath): void $writer->addRow(Row::fromValues([(string) $kode, (string) $nama, (string) $kode.' - '.(string) $nama])); } + $writer->addNewSheetAndMakeItCurrent(); + $writer->getCurrentSheet()->setName(self::SHEET_LOKASI); + $writer->addRow(Row::fromValues(['Lokasi', 'Kode Desa', 'Desa', 'Jenis Peta'], (new Style)->setFontBold())); + foreach ($this->lokasi as $lokasi) { + $writer->addRow(Row::fromValues([ + $this->labelLokasi($lokasi), $lokasi['kode_desa'], $lokasi['nama_desa'], $lokasi['kategori'], + ])); + } + $writer->close(); $this->injectDesaDropdown($filePath); } + private function labelLokasi(array $lokasi): string + { + return $lokasi['id'].' - '.$lokasi['nama'].' ('.$lokasi['nama_desa'].')'; + } + protected function injectDesaDropdown(string $filePath): void { $desaList = $this->desaList; if (is_object($desaList) && method_exists($desaList, 'toArray')) { $desaList = $desaList->toArray(); } - if (! is_array($desaList) || $desaList === []) { - return; - } - $this->desaList = $desaList; // normalize for count below + $desaList = is_array($desaList) ? $desaList : []; $zip = new ZipArchive; if ($zip->open($filePath) !== true) { @@ -171,12 +191,23 @@ protected function injectDesaDropdown(string $filePath): void // Baris header berada di baris 8 pada sheet Data Impor; data mulai di baris 9. $dataStartRow = self::DATA_START_ROW; $lastRow = $dataStartRow + 999; - $lastDesaRow = count($this->desaList) + 1; - $formula = sprintf("'%s'!\$C\$2:\$C\$%d", self::SHEET_DESA, $lastDesaRow); + $validations = []; + if ($desaList !== []) { + $formula = sprintf("'%s'!\$C\$2:\$C\$%d", self::SHEET_DESA, count($desaList) + 1); + $validations[] = '' + .htmlspecialchars($formula, ENT_XML1 | ENT_QUOTES, 'UTF-8').''; + } + if ($this->lokasi !== []) { + $formula = sprintf("INDIRECT(\"'%s'!\$A\$2:\$A\$%d\")", self::SHEET_LOKASI, count($this->lokasi) + 1); + $validations[] = '' + .htmlspecialchars($formula, ENT_XML1 | ENT_QUOTES, 'UTF-8').''; + } + if ($validations === []) { + $zip->close(); - $validation = '' - .htmlspecialchars($formula, ENT_XML1 | ENT_QUOTES, 'UTF-8') - .''; + return; + } + $validation = ''.implode('', $validations).''; // dataValidations wajib berada setelah ; baris tidak boleh ditambahkan di luar sheetData. $pos = strpos($xml, ''); diff --git a/app/Http/Controllers/DataSpasial/ImporDataController.php b/app/Http/Controllers/DataSpasial/ImporDataController.php index cdad8884b..87a148ad7 100644 --- a/app/Http/Controllers/DataSpasial/ImporDataController.php +++ b/app/Http/Controllers/DataSpasial/ImporDataController.php @@ -14,8 +14,11 @@ use App\Services\ImporTemplateService; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Http\Client\ConnectionException; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Session; use Illuminate\View\View; +use RuntimeException; class ImporDataController extends DataSpasialController { @@ -57,7 +60,13 @@ public function downloadTemplate(DownloadTemplateRequest $request) $sektor = $request->validated('sektor'); $periode = $request->validated('periode') ?? date('Y'); - $tempFile = $this->templateService->bangun($sektor, $request->validated('kecamatan'), $periode); + try { + $tempFile = $this->templateService->bangun($sektor, $request->validated('kecamatan'), $periode); + } catch (RuntimeException|ConnectionException $exception) { + Log::warning('DataSpasial: daftar lokasi untuk templat tidak tersedia', ['message' => $exception->getMessage()]); + + return back()->with('error', 'Templat tidak dapat dibuat karena daftar lokasi tidak tersedia. Silakan coba lagi.'); + } $filename = 'template_impor_'.str_replace([' ', '/'], '_', strtolower($sektor)).'_'.date('YmdHis').'.xlsx'; @@ -66,6 +75,7 @@ public function downloadTemplate(DownloadTemplateRequest $request) public function upload(UploadImporRequest $request): JsonResponse { + Session::forget(['impor_parsed', 'impor_preview']); $file = $request->file('file'); $rows = $this->berkasService->baca($file->getRealPath()); @@ -87,19 +97,48 @@ public function upload(UploadImporRequest $request): JsonResponse public function preview(PreviewImporRequest $request): JsonResponse { + Session::forget('impor_preview'); $parsed = Session::get('impor_parsed'); if (! $parsed) { return response()->json(['success' => false, 'message' => 'Tidak ada data hasil unggah.'], 422); } $forceOverwrite = (bool) $request->input('force_overwrite', false); + $baris = $this->berkasService->bangunBarisPratinjau($parsed['rows'] ?? []); + if ($baris === []) { + return response()->json(['success' => false, 'message' => 'Tidak ada baris data untuk dipratinjau.'], 422); + } + + foreach ($baris as &$row) { + $id = filter_var($row['lokasi_id'], FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); + if ($id === false) { + return response()->json(['success' => false, 'message' => 'Baris '.$row['nomor_baris'].': pilih lokasi yang valid pada kolom lokasi_id.'], 422); + } + $row['lokasi_id'] = $id; + } + unset($row); + + try { + $desa = array_map(static fn (array $row): array => ['kode_desa' => (string) $row['kode_desa'], 'nama_desa' => ''], $baris); + $lokasi = array_column($this->templateService->daftarLokasi($desa), null, 'id'); + } catch (RuntimeException|ConnectionException $exception) { + Log::warning('DataSpasial: validasi lokasi impor tidak tersedia', ['message' => $exception->getMessage()]); + + return response()->json(['success' => false, 'message' => 'Daftar lokasi tidak tersedia. Silakan coba lagi.'], 503); + } + foreach ($baris as $row) { + $pilihan = $lokasi[$row['lokasi_id']] ?? null; + if ($pilihan === null || $pilihan['kode_desa'] !== (string) $row['kode_desa']) { + return response()->json(['success' => false, 'message' => 'Baris '.$row['nomor_baris'].': lokasi tidak ditemukan, tidak memiliki koordinat, atau tidak berada di desa yang dipilih.'], 422); + } + } $payload = [ 'sektor' => $parsed['sektor'], 'filename' => $parsed['filename'], 'force_overwrite' => $forceOverwrite, 'mode' => $request->input('mode', 'sebagian'), - 'baris' => $this->berkasService->bangunBarisPratinjau($parsed['rows'] ?? []), + 'baris' => $baris, ]; if ($forceOverwrite) { $payload['alasan_override'] = $request->validated('alasan_override'); @@ -113,6 +152,17 @@ public function preview(PreviewImporRequest $request): JsonResponse $previewData = $this->berkasService->normalisasiPratinjau($result->data, $result->meta); + if (count($previewData['baris']) !== count($baris)) { + return response()->json(['success' => false, 'message' => 'API belum mengonfirmasi lokasi untuk seluruh baris. Perbarui API DataSpasial sebelum menyimpan impor.'], 503); + } + foreach ($baris as $index => $row) { + $confirmed = $previewData['baris'][$index]; + if ((string) ($confirmed['nomor_baris'] ?? '') !== (string) $row['nomor_baris'] + || (string) ($confirmed['lokasi_id'] ?? '') !== (string) $row['lokasi_id']) { + return response()->json(['success' => false, 'message' => 'API belum mengonfirmasi lokasi untuk seluruh baris. Perbarui API DataSpasial sebelum menyimpan impor.'], 503); + } + } + Session::put('impor_preview', $previewData); return response()->json(['success' => true, 'preview' => $previewData]); @@ -120,6 +170,11 @@ public function preview(PreviewImporRequest $request): JsonResponse public function save(Request $request, string $imporId): JsonResponse { + $preview = Session::get('impor_preview'); + if (! is_array($preview) || ($preview['impor_id'] ?? null) !== $imporId + || ! ($preview['ringkasan']['bisa_disimpan'] ?? false)) { + return response()->json(['success' => false, 'message' => 'Lakukan pratinjau lokasi yang valid sebelum menyimpan impor.'], 422); + } $result = $this->dataspasial->imporSimpan($imporId, $request->all()); if ($result->isUnavailable()) { diff --git a/app/Http/Controllers/DataSpasial/PetaGabunganController.php b/app/Http/Controllers/DataSpasial/PetaGabunganController.php index 778d9d65a..f8bb11411 100644 --- a/app/Http/Controllers/DataSpasial/PetaGabunganController.php +++ b/app/Http/Controllers/DataSpasial/PetaGabunganController.php @@ -5,6 +5,7 @@ namespace App\Http\Controllers\DataSpasial; use App\Services\DataSpasialResult; +use App\Services\PetaSkemaPopupService; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\View\View; @@ -47,7 +48,7 @@ public function index(Request $request): View * Selalu HTTP 200; kegagalan ditandai pada `meta.unavailable`/`meta.empty` * agar UI menampilkan pesan generik (tanpa stack trace). */ - public function data(Request $request): JsonResponse + public function data(Request $request, PetaSkemaPopupService $popup): JsonResponse { $sektor = $this->stringInput($request, 'sektor'); $result = $this->dataspasial->geojsonGabungan($this->filters($request)); @@ -80,6 +81,49 @@ public function data(Request $request): JsonResponse $features = $this->applyIsianFilters($features, (array) $request->input('filter', [])); $features = $this->withPopupIsian($features, $sektor); + $periode = $this->stringInput($request, 'periode'); + $features = $popup->susun($features, $periode)['features']; + if ($sektor !== null || $periode !== null) { + $filters = $this->filters($request); + unset($filters['sektor'], $filters['periode']); + $semua = $this->dataspasial->geojsonGabungan($filters); + if ($semua->isUnavailable()) { + foreach ($features as $i => $feature) { + $features[$i]['properties']['popup_skema_unavailable'] = true; + } + } else { + $collection = $semua->first(); + $referensi = is_array($collection['features'] ?? null) ? $collection['features'] : []; + $rincian = $popup->susun($referensi, $periode); + $lokasi = $rincian['lokasi']; + $fasilitas = []; + foreach ($rincian['features'] as $feature) { + $props = $feature['properties'] ?? []; + $id = $props['id'] ?? null; + $kode = $props['sektor_kode'] ?? null; + if (is_scalar($id) && is_string($kode) && $kode !== '' && isset($props['popup_skema'])) { + $fasilitas[$kode][(string) $id] = [ + 'skema' => $props['popup_skema'], + 'unavailable' => $props['popup_skema_unavailable'], + ]; + } + } + foreach ($features as $i => $feature) { + $props = $feature['properties'] ?? []; + $id = $props['lokasi_id'] ?? null; + $detail = null; + if (is_scalar($id) && isset($lokasi[(string) $id])) { + $detail = $lokasi[(string) $id]; + } elseif (is_scalar($props['id'] ?? null) && is_string($props['sektor_kode'] ?? null)) { + $detail = $fasilitas[$props['sektor_kode']][(string) $props['id']] ?? null; + } + if ($detail !== null) { + $features[$i]['properties']['popup_skema'] = $detail['skema']; + $features[$i]['properties']['popup_skema_unavailable'] = $detail['unavailable']; + } + } + } + } $payload['features'] = $features; $payload['meta'] = array_merge( diff --git a/app/Http/Controllers/DataSpasial/SkemaDataSpasialController.php b/app/Http/Controllers/DataSpasial/SkemaDataSpasialController.php index 4897f6474..9baaf0d59 100644 --- a/app/Http/Controllers/DataSpasial/SkemaDataSpasialController.php +++ b/app/Http/Controllers/DataSpasial/SkemaDataSpasialController.php @@ -125,6 +125,64 @@ public function index(Request $request): View ]); } + public function ubahNamaSektor(Request $request): JsonResponse + { + $data = $request->validate([ + 'sektor' => ['required', 'string', 'max:50'], + 'sektor_nama' => ['required', 'string', 'max:100'], + ]); + + $nama = trim($data['sektor_nama']); + if ($nama === '') { + return response()->json(['message' => 'Nama sektor wajib diisi.'], 422); + } + + $result = $this->dataspasial->ubahNamaSektor($data['sektor'], $nama); + $item = $result->first(); + if ($result->isUnavailable() || ($item['type'] ?? null) !== 'ds_sektor' + || ($item['attributes']['kode'] ?? null) !== $data['sektor'] + || ($item['attributes']['nama'] ?? null) !== $nama) { + Log::warning('DataSpasial: perubahan nama sektor gagal atau tidak dikonfirmasi', [ + 'sektor' => $data['sektor'], + 'http_status' => $result->httpStatus, + ]); + + return response()->json(['success' => false, 'message' => 'Nama sektor belum dapat disimpan. Silakan coba lagi nanti.'], 503); + } + + return response()->json(['success' => true, 'sektor' => $data['sektor']]); + } + + public function batalkanDraf(Request $request): JsonResponse + { + $data = $request->validate([ + 'sektor' => ['required', 'string', 'max:50'], + 'nomor_draf' => ['required', 'integer', 'min:1'], + 'nomor_terbit' => ['required', 'integer', 'min:1'], + ]); + $nomorDraf = (int) $data['nomor_draf']; + $nomorTerbit = (int) $data['nomor_terbit']; + $result = $this->dataspasial->batalkanDrafTanpaPerubahan($data['sektor'], $nomorDraf, $nomorTerbit); + $item = $result->first(); + $atribut = $item['attributes'] ?? []; + + if ($result->isUnavailable() || ($item['type'] ?? null) !== 'pembatalan_draf' + || ($atribut['sektor'] ?? null) !== $data['sektor'] + || ($atribut['nomor_draf'] ?? null) !== $nomorDraf + || ($atribut['nomor_terbit'] ?? null) !== $nomorTerbit) { + Log::warning('DataSpasial: pembatalan draf gagal atau tidak dikonfirmasi', [ + 'sektor' => $data['sektor'], 'http_status' => $result->httpStatus, + ]); + $pesan = $result->httpStatus === 422 && $result->message + ? $result->message + : 'Draf belum dapat dibatalkan. Silakan coba lagi nanti.'; + + return response()->json(['success' => false, 'message' => $pesan], 422); + } + + return response()->json(['success' => true]); + } + /** * Simpan draf skema (FR-029 … FR-033, Q18/Q19/Q20/Q23). * @@ -253,7 +311,9 @@ public function previewTerbit(Request $request): JsonResponse return response()->json([ 'success' => false, 'tanpa_perubahan' => true, - 'message' => 'Tidak ada perubahan untuk diterbitkan pada draf ini.', + 'message' => 'Draf tidak memiliki perubahan. Versi terbit sebelumnya tetap berlaku.', + 'nomor_draf' => $nomorDraf, + 'nomor_terbit' => $versiTerbit['nomor_versi'] ?? null, ], 422); } diff --git a/app/Http/Controllers/Web/PresisiController.php b/app/Http/Controllers/Web/PresisiController.php index 176ea996b..351b3eedb 100644 --- a/app/Http/Controllers/Web/PresisiController.php +++ b/app/Http/Controllers/Web/PresisiController.php @@ -7,8 +7,14 @@ use App\Http\Controllers\Controller; use App\Models\Enums\StatistikPendudukEnum; use App\Models\Enums\StatistikRtmEnum; +use App\Services\DataSpasialApiService; use App\Services\KesehatanApiService; +use App\Services\PetaSkemaPopupService; use App\Services\PemetaanService; +use Illuminate\Http\Client\ConnectionException; +use Illuminate\Http\JsonResponse; +use Illuminate\Support\Facades\Log; +use RuntimeException; class PresisiController extends Controller { @@ -193,4 +199,36 @@ public function geoSpasial() return view('presisi.geo_spasial.index', compact('categoriesItems', 'listKecamatan', 'listDesa', 'kategori')); } + + public function geoSpasialSkema(DataSpasialApiService $dataspasial, PetaSkemaPopupService $popup, PemetaanService $pemetaan): JsonResponse + { + $result = $dataspasial->geojsonGabungan(); + if ($result->isUnavailable()) { + return response()->json(['message' => $result->userMessage()], 503); + } + + $collection = $result->first(); + $features = is_array($collection['features'] ?? null) ? $collection['features'] : []; + try { + $coordinates = $pemetaan->getCoordinates(); + } catch (RuntimeException|ConnectionException $exception) { + Log::warning('DataSpasial: lokasi peta Presisi tidak tersedia', ['message' => $exception->getMessage()]); + + return response()->json(['message' => 'Data sementara tidak tersedia. Silakan coba lagi nanti.'], 503); + } + + $ids = []; + foreach ($coordinates as $coordinate) { + if (is_array($coordinate) && isset($coordinate['id']) && is_scalar($coordinate['id'])) { + $ids[(string) $coordinate['id']] = true; + } + } + $features = array_values(array_filter($features, static function ($feature) use ($ids): bool { + $id = is_array($feature) ? ($feature['properties']['lokasi_id'] ?? null) : null; + + return is_scalar($id) && isset($ids[(string) $id]); + })); + + return response()->json(['lokasi' => $popup->susun($features)['lokasi']]); + } } diff --git a/app/Services/DataSpasialApiService.php b/app/Services/DataSpasialApiService.php index 846e1dcf9..e7e422338 100644 --- a/app/Services/DataSpasialApiService.php +++ b/app/Services/DataSpasialApiService.php @@ -568,6 +568,25 @@ public function buatDrafSkema(array $body, ?int $schemaVersion = null): DataSpas return $this->request('POST', 'skema', [], $body, $schemaVersion); } + public function ubahNamaSektor(string $sektor, string $nama): DataSpasialResult + { + return $this->request('POST', 'skema', [], [ + 'aksi' => 'ubah_nama_sektor', + 'sektor' => $sektor, + 'sektor_nama' => $nama, + ]); + } + + public function batalkanDrafTanpaPerubahan(string $sektor, int $nomorDraf, int $nomorTerbit): DataSpasialResult + { + return $this->request('POST', 'skema', [], [ + 'aksi' => 'batalkan_draf_tanpa_perubahan', + 'sektor' => $sektor, + 'nomor_draf' => $nomorDraf, + 'nomor_terbit' => $nomorTerbit, + ]); + } + /** * Terbitkan draf skema menjadi versi `terbit` yang immutable. * diff --git a/app/Services/ImporBerkasService.php b/app/Services/ImporBerkasService.php index 5baac7d2b..62ab7d704 100644 --- a/app/Services/ImporBerkasService.php +++ b/app/Services/ImporBerkasService.php @@ -29,7 +29,7 @@ public function baca(string $path): array $reader->open($path); foreach ($reader->getSheetIterator() as $sheet) { - if (in_array(strtolower($sheet->getName()), ['petunjuk', 'daftar desa'], true)) { + if (in_array(strtolower($sheet->getName()), ['petunjuk', 'daftar desa', 'daftar lokasi'], true)) { continue; } @@ -103,11 +103,17 @@ public function bangunBarisPratinjau(array $rows): array ARRAY_FILTER_USE_BOTH ); + $lokasi = trim((string) ($row['lokasi_id'] ?? '')); + if (str_contains($lokasi, ' - ')) { + $lokasi = trim(explode(' - ', $lokasi, 2)[0]); + } + $baris[] = [ 'nomor_baris' => $row['nomor_baris'] ?? ($idx + 2), 'kode_desa' => $row['kode_desa'] ?? ($row['desa'] ?? ''), 'kode_fasilitas' => $row['kode_fasilitas'] ?? '', 'nama_fasilitas' => $row['nama_fasilitas'] ?? '', + 'lokasi_id' => $lokasi, 'periode' => $row['periode'] ?? date('Y'), 'nilai' => $nilai, ]; @@ -155,6 +161,7 @@ public function normalisasiPratinjau(array $data, array $meta = []): array 'nama_desa' => $item['nama_desa'] ?? '', 'kode_fasilitas' => $item['kode_fasilitas'] ?? '', 'nama_fasilitas' => $item['nama_fasilitas'] ?? '', + 'lokasi_id' => $item['lokasi_id'] ?? null, 'periode' => $item['periode'] ?? '', 'status' => $item['status'] ?? ($item['keterangan'] ?? ''), 'pesan' => (string) ($pesan ?? ''), @@ -305,7 +312,7 @@ private function kodeDesaValid(mixed $desaList): array */ private function ambilNilai(array $row): array { - $exclude = ['nomor_baris', 'kode_desa', 'desa', 'kode_fasilitas', 'nama_fasilitas', 'periode', 'petunjuk']; + $exclude = ['nomor_baris', 'kode_desa', 'desa', 'kode_fasilitas', 'nama_fasilitas', 'lokasi_id', 'periode', 'petunjuk']; $nilai = []; foreach ($row as $k => $v) { diff --git a/app/Services/ImporTemplateService.php b/app/Services/ImporTemplateService.php index 798677889..3db55c930 100644 --- a/app/Services/ImporTemplateService.php +++ b/app/Services/ImporTemplateService.php @@ -7,6 +7,7 @@ use App\Exports\ImporDataSpasialTemplateExport; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Log; +use Illuminate\Validation\ValidationException; /** * Menyusun berkas templat impor DataSpasial (XLSX) beserta data fasilitas @@ -22,6 +23,7 @@ class ImporTemplateService public function __construct( private DataSpasialApiService $dataspasial, private ConfigApiService $configApiService, + private PemetaanService $pemetaan, ) {} /** @@ -31,14 +33,52 @@ public function bangun(string $sektor, ?string $kecamatan, string $periode): str { $desaList = $this->daftarDesa($kecamatan); $items = $this->itemIsian($sektor); + foreach ($items as $item) { + if (ImporDataSpasialTemplateExport::headerKey($item) === 'lokasi_id') { + throw ValidationException::withMessages(['sektor' => 'Kode isian lokasi_id digunakan untuk hubungan lokasi dan tidak dapat digunakan sebagai kode isian skema.']); + } + } $fasilitas = $this->fasilitasBerjalan($sektor, $kecamatan, $periode, $desaList); + $lokasi = $this->daftarLokasi($desaList); $tempFile = tempnam(sys_get_temp_dir(), 'tmpl_'); - (new ImporDataSpasialTemplateExport($desaList, $items, $sektor, $periode, $fasilitas))->write($tempFile); + (new ImporDataSpasialTemplateExport($desaList, $items, $sektor, $periode, $fasilitas, $lokasi))->write($tempFile); return $tempFile; } + /** + * @param array $desaList + * @return array + */ + public function daftarLokasi(array $desaList): array + { + $cakupan = array_fill_keys(array_column($desaList, 'kode_desa'), true); + $hasil = []; + foreach ($this->pemetaan->getCoordinates() as $item) { + $id = $item['id'] ?? null; + $desa = (string) ($item['config']['kode_desa'] ?? ''); + $lat = $item['lat'] ?? null; + $lng = $item['lng'] ?? null; + if (! is_scalar($id) || ! ctype_digit((string) $id) || (int) $id < 1 + || ! isset($cakupan[$desa]) || ! is_numeric($lat) || ! is_numeric($lng) + || (float) $lat === 0.0 || (float) $lng === 0.0 + || abs((float) $lat) > 90 || abs((float) $lng) > 180) { + continue; + } + + $hasil[] = [ + 'id' => (string) $id, + 'nama' => (string) ($item['nama'] ?? ''), + 'kode_desa' => $desa, + 'nama_desa' => (string) ($item['config']['nama_desa'] ?? ''), + 'kategori' => (string) ($item['point']['nama'] ?? ''), + ]; + } + + return $hasil; + } + /** * @return array */ @@ -205,11 +245,13 @@ private function petaFasilitas(array $daftarFasilitas, string $sektor, array $ca $namaDesa = (string) $cakupan[$kodeDesa]; $kodeFasilitas = (string) ($atribut['kode_fasilitas'] ?? ''); + $rujukan = (string) ($atribut['rujukan_fasilitas'] ?? ''); $peta[$id] = [ // Format "kode - nama" sama dengan daftar dropdown pada sheet Daftar Desa. 'kode_desa' => $namaDesa !== '' ? $kodeDesa.' - '.$namaDesa : $kodeDesa, 'kode_fasilitas' => $kodeFasilitas !== '' ? $kodeFasilitas : $id, 'nama_fasilitas' => (string) ($atribut['nama'] ?? ''), + 'lokasi_id' => preg_match('/^point:([1-9][0-9]*)$/', $rujukan, $matches) ? $matches[1] : '', 'nilai' => [], ]; } diff --git a/app/Services/PemetaanService.php b/app/Services/PemetaanService.php index 66a22608e..61e8420c8 100644 --- a/app/Services/PemetaanService.php +++ b/app/Services/PemetaanService.php @@ -31,6 +31,16 @@ public function getAllPlan(array $query = []): ?array return is_array($data) ? $data : null; } + public function getCoordinates(): array + { + $data = $this->apiGet('/api/v1/plan/get-list-coordinate'); + if (! is_array($data) || ! array_is_list($data)) { + throw new \UnexpectedValueException('Respons koordinat peta tidak valid.'); + } + + return $data; + } + public function planStore(array $data): ?array { return $this->apiPost('/api/v1/plan/store', $data); diff --git a/app/Services/PetaSkemaPopupService.php b/app/Services/PetaSkemaPopupService.php new file mode 100644 index 000000000..93c338021 --- /dev/null +++ b/app/Services/PetaSkemaPopupService.php @@ -0,0 +1,238 @@ +> $features + * @return array{features: array>, lokasi: array} + */ + public function susun(array $features, ?string $periode = null): array + { + $skemaPerSektor = []; + $lokasi = []; + $perFitur = []; + $versiPerSektor = []; + + foreach ($features as $feature) { + $props = is_array($feature['properties'] ?? null) ? $feature['properties'] : []; + $kode = $props['sektor_kode'] ?? null; + if (! is_string($kode) || $kode === '') { + continue; + } + foreach ($this->entries($props) as $entry) { + if (isset($entry['skema_versi_id']) && is_scalar($entry['skema_versi_id'])) { + $versiPerSektor[$kode][(string) $entry['skema_versi_id']] = true; + } + } + } + + foreach ($features as $index => $feature) { + $props = is_array($feature['properties'] ?? null) ? $feature['properties'] : []; + $kode = $props['sektor_kode'] ?? null; + if (! is_string($kode) || $kode === '') { + continue; + } + + if (! array_key_exists($kode, $skemaPerSektor)) { + $skemaPerSektor[$kode] = $this->skemaTerbit($kode, array_keys($versiPerSektor[$kode] ?? [])); + } + + $skema = $skemaPerSektor[$kode]; + $groups = []; + $versiFitur = []; + foreach ($this->entries($props) as $entry) { + if (isset($entry['skema_versi_id']) && is_scalar($entry['skema_versi_id'])) { + $versiFitur[(string) $entry['skema_versi_id']] = true; + } + } + foreach ($skema['versi'] as $id => $versi) { + if ($versi['isian'] !== [] && ((string) $id === $skema['terbaru'] || isset($versiFitur[(string) $id]))) { + $groups[] = $this->kelompok($props, $versi, $periode); + } + } + + $detail = ['skema' => $groups, 'unavailable' => $skema['unavailable']]; + $perFitur[$index] = $detail; + $lokasiId = $props['lokasi_id'] ?? null; + if (! is_scalar($lokasiId) || (string) $lokasiId === '') { + continue; + } + + $key = (string) $lokasiId; + $lokasi[$key] ??= ['skema' => [], 'unavailable' => false]; + array_push($lokasi[$key]['skema'], ...$groups); + $lokasi[$key]['unavailable'] = $lokasi[$key]['unavailable'] || $detail['unavailable']; + } + + foreach ($features as $index => $feature) { + $props = is_array($feature['properties'] ?? null) ? $feature['properties'] : []; + $lokasiId = $props['lokasi_id'] ?? null; + $detail = is_scalar($lokasiId) && (string) $lokasiId !== '' + ? ($lokasi[(string) $lokasiId] ?? null) + : ($perFitur[$index] ?? null); + if ($detail !== null) { + $features[$index]['properties']['popup_skema'] = $detail['skema']; + $features[$index]['properties']['popup_skema_unavailable'] = $detail['unavailable']; + } + } + + return ['features' => $features, 'lokasi' => $lokasi]; + } + + /** + * @param array $ids + * @return array{versi: array, terbaru: string|null, unavailable: bool} + */ + private function skemaTerbit(string $kode, array $ids): array + { + $result = $this->dataspasial->listSkema(['sektor' => $kode]); + $hasil = ['versi' => [], 'terbaru' => null, 'unavailable' => $result->isUnavailable()]; + if ($result->isUnavailable()) { + return $hasil; + } + $terbaru = $this->bacaSkema($result); + if ($terbaru !== null) { + $id = (string) $terbaru['versi']['id']; + $hasil['versi'][$id] = $terbaru; + $hasil['terbaru'] = $id; + } + + $lainnya = array_diff(array_map('strval', $ids), array_keys($hasil['versi'])); + if ($lainnya === []) { + return $hasil; + } + + $riwayat = $this->dataspasial->riwayatSkema(['sektor' => $kode]); + $hasil['unavailable'] = $hasil['unavailable'] || $riwayat->isUnavailable(); + foreach ($riwayat->data as $item) { + $atribut = is_array($item['attributes'] ?? null) ? $item['attributes'] : []; + $id = (string) ($item['id'] ?? $atribut['id'] ?? ''); + $nomor = $atribut['nomor_versi'] ?? null; + if (! in_array($id, $lainnya, true) || ($atribut['status'] ?? null) !== 'terbit' + || ! is_numeric($nomor) || (int) $nomor < 1) { + continue; + } + $resultVersi = $this->dataspasial->listSkema(['sektor' => $kode, 'versi' => (int) $nomor]); + $hasil['unavailable'] = $hasil['unavailable'] || $resultVersi->isUnavailable(); + $versi = $this->bacaSkema($resultVersi); + if ($versi !== null && (string) $versi['versi']['id'] === $id) { + $hasil['versi'][$id] = $versi; + } + } + + return $hasil; + } + + /** + * @return array{versi: array, isian: array>}|null + */ + private function bacaSkema(DataSpasialResult $result): ?array + { + $item = $result->first(); + $atribut = is_array($item['attributes'] ?? null) ? $item['attributes'] : []; + $versi = is_array($atribut['versi_skema'] ?? null) ? $atribut['versi_skema'] : null; + + if (($versi['status'] ?? null) !== 'terbit' || ! isset($versi['id']) || ! is_scalar($versi['id'])) { + return null; + } + + $isian = is_array($atribut['isian'] ?? null) ? $atribut['isian'] : []; + + return [ + 'versi' => $versi, + 'isian' => array_values(array_filter($isian, static fn ($item): bool => is_array($item) + && ($item['tampil_popup'] ?? null) === true + && empty($item['diarsipkan']) + && is_string($item['kode'] ?? null) + && $item['kode'] !== '')), + ]; + } + + /** + * @param array $props + * @return array> + */ + private function entries(array $props): array + { + $entries = $props['dataspasial'] ?? []; + if (! is_array($entries)) { + return []; + } + + return array_values(array_filter(array_is_list($entries) ? $entries : [$entries], 'is_array')); + } + + /** + * @param array $props + * @param array{versi: array, isian: array>} $skema + * @return array + */ + private function kelompok(array $props, array $skema, ?string $periode): array + { + $nilai = []; + $periodeTersedia = []; + $isianPublik = array_fill_keys(array_column($skema['isian'], 'kode'), true); + + foreach ($this->entries($props) as $entry) { + if (! isset($entry['skema_versi_id']) || ! is_scalar($entry['skema_versi_id']) + || (string) $entry['skema_versi_id'] !== (string) $skema['versi']['id']) { + continue; + } + + $kode = $entry['isian_kode'] ?? null; + if (! is_string($kode) || ! isset($isianPublik[$kode])) { + continue; + } + $periodeNilai = $entry['periode'] ?? null; + if ($periodeNilai !== null && ! is_scalar($periodeNilai)) { + continue; + } + $periodeNilai = (string) ($periodeNilai ?? ''); + $periodeTersedia[$periodeNilai] = true; + $nilai[$kode][$periodeNilai] ??= $entry; + } + + if ($periode !== null && $periode !== '') { + $periodeTersedia[$periode] = true; + } + $periodeTersedia = array_map('strval', array_keys($periodeTersedia)); + rsort($periodeTersedia, SORT_STRING); + $periodeAktif = $periode !== null && $periode !== '' ? $periode : ($periodeTersedia[0] ?? null); + + $isian = []; + foreach ($skema['isian'] as $item) { + $entry = $periodeAktif !== null ? ($nilai[$item['kode']][$periodeAktif] ?? []) : []; + $value = $entry['nilai'] ?? null; + $perPeriode = []; + foreach ($nilai[$item['kode']] ?? [] as $key => $data) { + $nilaiPeriode = $data['nilai'] ?? null; + $perPeriode[] = [ + 'periode' => (string) $key, + 'nilai' => is_scalar($nilaiPeriode) || $nilaiPeriode === null ? $nilaiPeriode : json_encode($nilaiPeriode, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'sumber' => is_scalar($data['sumber'] ?? null) ? (string) $data['sumber'] : null, + ]; + } + $isian[] = [ + 'label' => $item['label'] ?? $item['kode'], + 'nilai' => is_scalar($value) || $value === null ? $value : json_encode($value, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), + 'satuan' => $item['satuan'] ?? null, + 'nilai_periode' => $perPeriode, + ]; + } + + return [ + 'sektor' => $props['sektor_nama'] ?? $props['sektor_kode'], + 'fasilitas' => $props['nama'] ?? null, + 'versi' => $skema['versi']['nomor_versi'] ?? null, + 'periode' => $periodeTersedia, + 'periode_aktif' => $periodeAktif, + 'isian' => $isian, + ]; + } +} diff --git a/public/css/dataspasial/popup-skema.css b/public/css/dataspasial/popup-skema.css new file mode 100644 index 000000000..b53863998 --- /dev/null +++ b/public/css/dataspasial/popup-skema.css @@ -0,0 +1,247 @@ +.dataspasial-leaflet-popup .leaflet-popup-content-wrapper { + padding: 0; + border-radius: 12px; + box-shadow: 0 8px 28px rgba(15, 23, 42, .2); +} + +.dataspasial-leaflet-popup .leaflet-popup-content { + width: 360px; + max-width: calc(100vw - 64px); + margin: 0; + overflow-y: auto; +} + +.dataspasial-leaflet-popup a.leaflet-popup-close-button { + top: 10px; + right: 11px; + color: #64748b; + font-size: 21px; +} + +.peta-popup { + box-sizing: border-box; + padding: 18px; + color: #253449; + font-size: 13px; + line-height: 1.5; + overflow-wrap: anywhere; +} + +.dataspasial-popup-header { + padding-right: 22px; +} + +.dataspasial-popup-eyebrow, +.dataspasial-popup-section-title { + color: #52657b; + font-size: 11px; + font-weight: 700; + letter-spacing: .06em; + text-transform: uppercase; +} + +.dataspasial-popup-title { + margin: 4px 0 0; + color: #162a42; + font-size: 17px; + font-weight: 700; + line-height: 1.3; +} + +.dataspasial-popup-description { + margin: 6px 0 0 !important; + color: #52657b; + line-height: 1.45; +} + +.dataspasial-popup-tags { + display: flex; + flex-wrap: wrap; + gap: 5px; + margin-top: 9px; +} + +.dataspasial-popup-tag { + padding: 3px 8px; + border-radius: 5px; + background: #eaf3fb; + color: #205a88; + font-size: 11px; + font-weight: 600; +} + +.dataspasial-popup-tag-sector { + background: #edf6f1; + color: #28664d; +} + +.dataspasial-popup-location, +.dataspasial-popup-fields { + margin: 0; +} + +.dataspasial-popup-location { + margin-top: 13px; + padding: 9px 11px; + border-radius: 7px; + background: #f5f8fb; +} + +.dataspasial-popup-location-row, +.dataspasial-popup-field { + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1.2fr); + gap: 12px; +} + +.dataspasial-popup-location-row + .dataspasial-popup-location-row { + margin-top: 4px; +} + +.dataspasial-popup-location dt, +.dataspasial-popup-location dd, +.dataspasial-popup-fields dt, +.dataspasial-popup-fields dd { + margin: 0; + overflow-wrap: anywhere; +} + +.dataspasial-popup-location dt, +.dataspasial-popup-fields dt { + color: #52657b; + font-weight: 400; +} + +.dataspasial-popup-location dd, +.dataspasial-popup-fields dd { + color: #162a42; + font-weight: 600; + text-align: right; +} + +.dataspasial-popup-skema { + margin-top: 16px; + overflow-wrap: anywhere; +} + +.dataspasial-popup-section-title { + margin: 0 0 8px; +} + +.dataspasial-popup-notice { + padding: 10px 12px; + border-radius: 7px; + background: #f5f8fb; + color: #52657b; + font-size: 12px; +} + +.peta-popup > .dataspasial-popup-notice { + margin-top: 16px; +} + +.dataspasial-popup-notice + .dataspasial-popup-group { + margin-top: 8px; +} + +.dataspasial-popup-group { + overflow: hidden; + border: 1px solid #dce5ed; + border-radius: 8px; + background: #fff; +} + +.dataspasial-popup-group + .dataspasial-popup-group { + margin-top: 8px; +} + +.dataspasial-popup-group summary { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 10px 12px; + color: #205a88; + font-size: 12px; + font-weight: 700; + cursor: pointer; + list-style: none; +} + +.dataspasial-popup-group summary::-webkit-details-marker { + display: none; +} + +.dataspasial-popup-group summary::after { + width: 7px; + height: 7px; + flex: none; + border-right: 1.5px solid currentColor; + border-bottom: 1.5px solid currentColor; + content: ""; + transform: rotate(45deg); +} + +.dataspasial-popup-group[open] summary::after { + transform: rotate(225deg); +} + +.dataspasial-popup-group summary:focus-visible, +.dataspasial-popup-period:focus-visible { + outline: 2px solid #277bc0; + outline-offset: -2px; +} + +.dataspasial-popup-group-body { + padding: 0 12px 12px; +} + +.dataspasial-popup-facility { + margin-bottom: 8px; + color: #52657b; + font-size: 12px; +} + +.dataspasial-popup-period-label { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + margin: 0 0 8px; + color: #52657b; + font-size: 12px; + font-weight: 600; +} + +.dataspasial-popup-period { + width: auto; + max-width: 60%; + min-height: 32px; + padding: 4px 8px; + border: 1px solid #cbd7e2; + border-radius: 6px; + background: #fff; + color: #253449; + font: inherit; +} + +.dataspasial-popup-field { + padding: 7px 0; + border-top: 1px solid #edf1f5; +} + +.dataspasial-popup-fields dd.dataspasial-popup-field-empty { + color: #64748b; + font-size: 12px; + font-weight: 400; +} + +.dataspasial-popup-source { + margin-top: 8px; + color: #64748b; + font-size: 11px; +} + +.dataspasial-popup-group [data-popup-period][hidden] { + display: none !important; +} diff --git a/public/js/dataspasial/dasbor.js b/public/js/dataspasial/dasbor.js index 04bbf5649..77cabafee 100644 --- a/public/js/dataspasial/dasbor.js +++ b/public/js/dataspasial/dasbor.js @@ -184,16 +184,65 @@ history.replaceState(null, null, s ? '?' + s : window.location.pathname); } + function loadMap(rid) { + var peta = window.PetaGabungan; + if (!peta) { + var alert = document.getElementById('map-unavailable'); + if (alert) alert.style.display = ''; + console.error('Peta DataSpasial tidak dapat dimuat.'); + return; + } + + var params = new URLSearchParams(); + if (state.kecamatan) params.set('kode_kecamatan', state.kecamatan); + if (state.desa) params.set('kode_desa', state.desa); + if (state.sektor) params.set('sektor', state.sektor); + if (state.periode) params.set('periode', state.periode); + + try { + peta.init({ mapId: 'map' }); + } catch (error) { + console.error('Peta DataSpasial tidak dapat diinisialisasi.', error); + peta.unavailable(); + return; + } + + fetch(window.DasborDataSpasial.opts.petaUrl + '?' + params.toString(), { + headers: { 'Accept': 'application/json' }, credentials: 'same-origin' + }) + .then(function (response) { + if (!response.ok) throw new Error('HTTP ' + response.status); + return response.json(); + }) + .then(function (data) { + if (rid !== state.last) return; + if (data.meta && data.meta.unavailable) { + peta.unavailable(data.meta.message); + return; + } + peta.render(data, data.meta); + }) + .catch(function (error) { + if (rid !== state.last) return; + console.error('Data peta tidak dapat dimuat.', error); + peta.unavailable(); + }); + } + function load() { var rid = ++state.last; var params = new URLSearchParams(); FILTER_KEYS.forEach(function (k) { if (state[k]) params.set(k, state[k]); }); if (state.kecamatan) params.set('kode_kecamatan', state.kecamatan); if (state.desa) params.set('kode_desa', state.desa); + loadMap(rid); fetch(window.DasborDataSpasial.opts.dataUrl + '?' + params.toString(), { headers: { 'Accept': 'application/json' }, credentials: 'same-origin' }) - .then(function (r) { return r.json(); }) + .then(function (r) { + if (!r.ok) throw new Error('HTTP ' + r.status); + return r.json(); + }) .then(function (j) { if (rid !== state.last) return; setText('dasbor-kartu', cardHtml(j.kartu || [])); @@ -232,30 +281,14 @@ } } syncUrl(); - - if (window.PetaGabungan) { - var petaParams = new URLSearchParams(); - if (state.kecamatan) petaParams.set('kode_kecamatan', state.kecamatan); - if (state.desa) petaParams.set('kode_desa', state.desa); - if (state.sektor) petaParams.set('sektor', state.sektor); - if (state.periode) petaParams.set('periode', state.periode); - fetch(window.DasborDataSpasial.opts.petaUrl + '?' + petaParams.toString(), { credentials: 'same-origin' }) - .then(function (x) { return x.json(); }) - .then(function (p) { - if (p.meta && p.meta.unavailable) { - if (typeof window.PetaGabungan.unavailable === 'function') window.PetaGabungan.unavailable(p.meta.message); - return; - } - if (typeof window.PetaGabungan.init === 'function' && !window._dasborPetaInit) { - try { window.PetaGabungan.init({ mapId: 'map' }); window._dasborPetaInit = true; } catch (e) { /* noop */ } - } - if (typeof window.PetaGabungan.render === 'function') window.PetaGabungan.render(p, p.meta); - if (p.meta && p.meta.empty && typeof window.PetaGabungan.empty === 'function') window.PetaGabungan.empty(); - }) - .catch(function () { if (typeof window.PetaGabungan.unavailable === 'function') window.PetaGabungan.unavailable(); }); - } }) - .catch(function () { }); + .catch(function (error) { + if (rid !== state.last) return; + console.error('Data dasbor tidak dapat dimuat.', error); + setText('dasbor-kartu', '
Data dasbor sementara tidak tersedia.
'); + setText('dasbor-tabel-baris', ''); + renderChartsHint('Data dasbor sementara tidak tersedia.'); + }); } function clearDashboard() { @@ -266,8 +299,6 @@ renderChartsHint('Pilih filter dan klik Tampilkan untuk melihat data.'); if (window.PetaGabungan && typeof window.PetaGabungan.clear === 'function') { try { window.PetaGabungan.clear(); } catch (e) { /* noop */ } - } else if (window.PetaGabungan && typeof window.PetaGabungan.unavailable === 'function') { - try { window.PetaGabungan.unavailable('Pilih filter dan klik Tampilkan untuk melihat data.'); } catch (e) { /* noop */ } } } @@ -287,12 +318,13 @@ var r = qs('#peta-reset'); if (r) r.onclick = function () { - state = { kecamatan: '', desa: '', sektor: '', periode: '', indikator: '', page: 1, last: state.last }; + state = { kecamatan: '', desa: '', sektor: '', periode: '', indikator: '', page: 1, last: state.last + 1 }; FILTER_KEYS.forEach(function (k) { var el = qs('#filter_' + k); if (el) { el.value = ''; if (k === 'indikator') { el.disabled = true; fillSelect(el, [], '', 'Pilih sektor terlebih dahulu'); } } }); var selInd = qs('#filter_indikator'); if (selInd) { selInd.disabled = true; fillSelect(selInd, [], '', 'Pilih sektor terlebih dahulu'); } loadDesa(false); clearDashboard(); + loadMap(state.last); history.replaceState(null, null, window.location.pathname); }; @@ -382,6 +414,8 @@ if (hasQuery) { state.page = 1; load(); + } else { + loadMap(++state.last); } } }; diff --git a/public/js/dataspasial/peta-gabungan.js b/public/js/dataspasial/peta-gabungan.js index 74e1e2144..e9be74589 100644 --- a/public/js/dataspasial/peta-gabungan.js +++ b/public/js/dataspasial/peta-gabungan.js @@ -73,6 +73,7 @@ var mapId = options.mapId || 'map'; map = L.map(mapId).setView(DEFAULT_CENTER, DEFAULT_ZOOM); + if (window.PopupSkema) window.PopupSkema.ikutiUkuranPeta(map); if (window.PETA_GABUNGAN_ICON && window.PETA_GABUNGAN_ICON.iconUrl) { markerIcon = new L.Icon({ @@ -114,92 +115,32 @@ return layerGroups[key]; } - function dsEntries(ds) { - if (!ds) { - return []; - } - if (Array.isArray(ds)) { - return ds.filter(function (e) { return e && typeof e === 'object'; }); - } - - return [ds]; - } - - function featureValue(props, kode) { - if (!props || !props.dataspasial) { - return null; - } - - var entries = dsEntries(props.dataspasial); - for (var i = 0; i < entries.length; i++) { - var ds = entries[i]; - if (ds.nilai_map && Object.prototype.hasOwnProperty.call(ds.nilai_map, kode)) { - return ds.nilai_map[kode]; - } - if (ds.isian_kode === kode) { - return ds.nilai; - } - } - - return null; - } - - function firstEntryValue(entries, keys) { - for (var i = 0; i < entries.length; i++) { - for (var j = 0; j < keys.length; j++) { - if (entries[i][keys[j]]) { - return entries[i][keys[j]]; - } - } - } - - return null; - } - - function popupContent(props) { + function popupContent(props, coordinates) { props = props || {}; var html = '
'; - if (props.nama) { - html += '' + esc(props.nama) + '
'; - } - - if (props.sektor_nama || props.sektor_kode) { - html += 'Sektor: ' + esc(props.sektor_nama || props.sektor_kode) + '
'; - } else if (props.kategori) { - html += '' + esc(props.kategori) + '
'; - } - - if (props.nama_desa || props.kode_desa) { - html += '' + esc(props.nama_desa || props.kode_desa) + '
'; - } else if (props.kode_kecamatan) { - html += 'Kec. ' + esc(props.kode_kecamatan) + '
'; - } - - var popupIsian = props.dataspasial ? (props.popup_isian || []) : []; - for (var i = 0; i < popupIsian.length; i++) { - var item = popupIsian[i]; - var value = featureValue(props, item.kode); - var display = (value === null || value === undefined || value === '') - ? 'Belum ada data untuk periode ini' - : value; - var satuan = item.satuan ? ' ' + esc(item.satuan) : ''; - - html += '
' + esc(item.label || item.kode) + ': ' + esc(display) + '' + satuan + '
'; - } - - var entries = dsEntries(props.dataspasial); - var sumber = firstEntryValue(entries, ['sumber', 'sumber_data']) || (props.source === 'presisi' ? 'Data Presisi' : null); - var diperbarui = firstEntryValue(entries, ['waktu_input', 'tanggal_pembaruan']); - var periode = firstEntryValue(entries, ['periode']); - if (sumber) { - html += 'Sumber: ' + esc(sumber) + '
'; - } - if (diperbarui) { - html += 'Diperbarui: ' + esc(diperbarui) + '
'; - } - if (periode) { - html += 'Periode: ' + esc(periode) + ''; + if (window.PopupSkema) { + html += window.PopupSkema.renderLokasi({ + nama: props.nama, + deskripsi: props.deskripsi || props.desk, + kategori: props.kategori, + sektor: props.sektor_nama || props.sektor_kode, + provinsi: props.nama_propinsi || props.kode_propinsi, + kabupaten: props.nama_kabupaten || props.kode_kabupaten, + kecamatan: props.nama_kecamatan || props.kode_kecamatan, + desa: props.nama_desa || props.kode_desa, + koordinat: Array.isArray(coordinates) && coordinates.length >= 2 ? coordinates[1] + ', ' + coordinates[0] : null + }); + html += window.PopupSkema.render(props.popup_skema, props.popup_skema_unavailable); + } else { + html += '' + esc(props.nama || 'Lokasi') + ''; + if (props.deskripsi || props.desk) html += '
' + esc(props.deskripsi || props.desk) + '
'; + if (props.kategori) html += '
Jenis peta: ' + esc(props.kategori) + '
'; + if (props.sektor_nama || props.sektor_kode) html += '
Sektor: ' + esc(props.sektor_nama || props.sektor_kode) + '
'; + if (props.nama_desa || props.kode_desa) html += '
Desa: ' + esc(props.nama_desa || props.kode_desa) + '
'; + if (props.nama_kecamatan || props.kode_kecamatan) html += '
Kecamatan: ' + esc(props.nama_kecamatan || props.kode_kecamatan) + '
'; + if (Array.isArray(coordinates) && coordinates.length >= 2) html += '
Koordinat: ' + esc(coordinates[1]) + ', ' + esc(coordinates[0]) + '
'; + html += '
Informasi skema tidak dapat dimuat.
'; } html += '
'; @@ -217,11 +158,8 @@ markerBounds[key].extend([coords[1], coords[0]]); var marker = L.marker([coords[1], coords[0]], markerIcon ? {icon: markerIcon} : {}); - marker.bindPopup(popupContent(feature.properties || {}), {closeButton: true, autoPan: true}); - - marker.on('mouseover', function () { - this.openPopup(); - }); + marker.bindPopup(popupContent(feature.properties || {}, coords), window.PopupSkema + ? window.PopupSkema.opsiPeta(map) : {maxWidth: 360, maxHeight: 300}); clusterFor(key).addLayer(marker); } diff --git a/public/js/dataspasial/popup-skema.js b/public/js/dataspasial/popup-skema.js new file mode 100644 index 000000000..c57b36438 --- /dev/null +++ b/public/js/dataspasial/popup-skema.js @@ -0,0 +1,166 @@ +(function (window) { + 'use strict'; + + var popupNumber = 0; + + function escape(value) { + return String(value === null || value === undefined ? '' : value) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + function renderLokasi(info) { + info = info || {}; + var html = '
' + + '
Informasi lokasi
' + + '

' + escape(info.nama || 'Lokasi') + '

'; + if (info.deskripsi) { + html += '

' + escape(info.deskripsi) + '

'; + } + if (info.kategori || info.sektor) { + html += '
'; + if (info.kategori) html += '' + escape(info.kategori) + ''; + if (info.sektor) html += '' + escape(info.sektor) + ''; + html += '
'; + } + html += '
'; + + var rows = [ + ['Provinsi', info.provinsi], + ['Kota / Kabupaten', info.kabupaten], + ['Kecamatan', info.kecamatan], + ['Desa', info.desa], + ['Koordinat', info.koordinat], + ].filter(function (row) { return row[1] !== null && row[1] !== undefined && row[1] !== ''; }); + if (rows.length) { + html += '
'; + rows.forEach(function (row) { + html += '
' + escape(row[0]) + + '
' + escape(row[1]) + '
'; + }); + html += '
'; + } + return html; + } + + function opsiPeta(map) { + var size = map.getSize(); + return { + className: 'dataspasial-leaflet-popup', + maxWidth: Math.max(80, Math.min(360, size.x - 48)), + minWidth: 0, + maxHeight: Math.max(80, Math.min(420, size.y - 60)) + }; + } + + function ikutiUkuranPeta(map) { + var popupAktif = null; + function sesuaikan() { + if (!popupAktif) return; + var options = opsiPeta(map); + popupAktif.options.maxWidth = options.maxWidth; + popupAktif.options.maxHeight = options.maxHeight; + popupAktif.update(); + } + map.on('popupopen', function (event) { + popupAktif = event.popup.options.className === 'dataspasial-leaflet-popup' ? event.popup : null; + sesuaikan(); + }); + map.on('popupclose', function (event) { + if (popupAktif === event.popup) popupAktif = null; + }); + map.on('resize', sesuaikan); + } + + function renderIsian(items, periode, adaPeriode) { + var sumber = []; + var html = '
'; + (items || []).forEach(function (item) { + var entry = adaPeriode && Array.isArray(item.nilai_periode) + ? item.nilai_periode.find(function (data) { return String(data.periode) === periode; }) + : null; + var value = adaPeriode ? (entry ? entry.nilai : null) : item.nilai; + var display = value === null || value === undefined || value === '' + ? 'Belum ada data untuk periode ini' + : (value === true ? 'Ya' : (value === false ? 'Tidak' : value)); + var kosong = value === null || value === undefined || value === ''; + html += '
' + escape(item.label) + '
' + + '' + escape(display); + if (item.satuan && value !== null && value !== undefined && value !== '') { + html += ' ' + escape(item.satuan); + } + html += '
'; + if (entry && entry.sumber && sumber.indexOf(String(entry.sumber)) === -1) { + sumber.push(String(entry.sumber)); + } + }); + html += '
'; + if (sumber.length) { + html += '
Sumber: ' + sumber.map(escape).join(', ') + '
'; + } + return html; + } + + function render(groups, unavailable) { + groups = Array.isArray(groups) ? groups : []; + var accordionName = 'popup-skema-' + (++popupNumber); + var html = '

Skema DataSpasial

'; + + if (unavailable) { + html += '
Sebagian informasi skema sementara tidak tersedia.
'; + } + if (!groups.length && !unavailable) { + html += '
Belum ada informasi skema terbit untuk lokasi ini.
'; + } + + groups.forEach(function (group, index) { + var title = escape(group.sektor || 'DataSpasial'); + var periods = Array.isArray(group.periode) ? group.periode.map(String) : []; + var selected = group.periode_aktif === null || group.periode_aktif === undefined + ? (periods[0] || '') : String(group.periode_aktif); + if (group.versi !== null && group.versi !== undefined) { + title += ' · v' + escape(group.versi); + } + html += '
' + + '' + title + '
'; + if (group.fasilitas) { + html += '
' + escape(group.fasilitas) + '
'; + } + html += ''; + if (periods.length) { + periods.forEach(function (period) { + html += '
' + + renderIsian(group.isian, period, true) + '
'; + }); + } else { + html += renderIsian(group.isian, '', false); + } + html += '
'; + }); + + return html + '
'; + } + + document.addEventListener('change', function (event) { + var select = event.target; + if (!select.matches || !select.matches('.dataspasial-popup-period')) return; + var group = select.closest('.dataspasial-popup-group'); + if (!group) return; + group.querySelectorAll('[data-popup-period]').forEach(function (panel) { + panel.hidden = panel.getAttribute('data-popup-period') !== select.value; + }); + }); + + window.PopupSkema = { render: render, renderLokasi: renderLokasi, opsiPeta: opsiPeta, ikutiUkuranPeta: ikutiUkuranPeta, escape: escape }; +}(window)); diff --git a/public/js/dataspasial/schema-editor.js b/public/js/dataspasial/schema-editor.js index 94e65f984..6f321497e 100644 --- a/public/js/dataspasial/schema-editor.js +++ b/public/js/dataspasial/schema-editor.js @@ -209,9 +209,7 @@ function rujukanDari(tr, sel) { /** * Baca opsi satu baris isian. * - * ⚠️ Kolom "Pilihan" tidak lagi ada di tabel editor (tidak dipakai), sehingga - * nilai opsi diambil dari atribut `data-opsi`. Bila atribut tidak tersedia, - * kembalikan array kosong. + * Nilai opsi disimpan di atribut `data-opsi` dan disunting melalui dialog. * * @param {HTMLElement} tr * @returns {Array} @@ -246,9 +244,6 @@ function bacaDariDom(tbody) { tipe: nilai('.input-tipe')?.value ?? 'teks', wajib: Boolean(nilai('.input-wajib')?.checked), satuan: nilai('.input-satuan')?.value?.trim() ?? '', - // ⚠️ Kolom Pilihan (opsi) TIDAK lagi ditampilkan pada tabel - // editor. Nilainya dibaca dari atribut `data-opsi` pada baris - // supaya opsi yang tersimpan di API tidak hilang saat Simpan draf. opsi: bacaOpsiBaris(tr), urutan: index + 1, popupPeta: Boolean(nilai('.input-popup-peta')?.checked), @@ -265,6 +260,11 @@ function bacaDariDom(tbody) { }); } +function jenisPenyimpanan(modeSektorBaru, namaAwal, nama, isianAwal, isian) { + if (modeSektorBaru || JSON.stringify(isianAwal) !== JSON.stringify(isian)) return 'draf'; + return nama.trim() !== namaAwal.trim() ? 'nama' : 'tidak-berubah'; +} + /** * Terapkan aturan kolom tipe (FR-010). * @@ -274,11 +274,18 @@ function terapkanAturanTipe(tbody) { tbody.querySelectorAll('tr').forEach((tr) => { const tipe = tr.querySelector('.input-tipe')?.value ?? 'teks'; const satuan = tr.querySelector('.input-satuan'); + const tombolOpsi = tr.querySelector('.btn-atur-opsi'); const bolehUbah = tbody.dataset.bolehUbah === '1'; if (satuan) { satuan.disabled = !bolehUbah || tipe !== TIPE_SATUAN; } + if (tombolOpsi) { + tombolOpsi.classList.toggle('d-none', tipe !== TIPE_PILIHAN); + tombolOpsi.disabled = !bolehUbah; + const jumlah = bacaOpsiBaris(tr).length; + tombolOpsi.textContent = jumlah ? `Atur pilihan (${jumlah})` : 'Atur pilihan'; + } }); } @@ -312,11 +319,11 @@ function renderPratinjau(wadah, isian) { kontrol = '
' + '' - + 'Diisi dari sumber: ' + (baris.sumber || 'pemetaan') + '
'; + + 'Diisi dari sumber: ' + escapeHtml(baris.sumber || 'pemetaan') + ''; } else if (baris.tipe === TIPE_PILIHAN) { kontrol = ''; } else if (baris.tipe === 'ya_tidak') { kontrol = ''; + + escapeHtml(baris.satuan || 'isi nilai') + '">'; } const catatanTersembunyi = terkunci && !baris.rujukan @@ -339,7 +346,7 @@ function renderPratinjau(wadah, isian) { if (baris.sebagaiIndikator) { penanda.push('Indikator'); } return '
' - + '