From 341c6017eaf02d93a4415fa5751ceddecbde87fa Mon Sep 17 00:00:00 2001 From: Ahmad Afandi Date: Wed, 21 Oct 2026 08:31:32 +0700 Subject: [PATCH 1/2] feat import isian --- .gitignore | 1 + .../ImporDataSpasialTemplateExport.php | 166 +++++++ .../DataSpasial/ImporDataController.php | 412 ++++++++++++++++- .../DataSpasial/DownloadTemplateRequest.php | 23 + .../DataSpasial/PreviewImporRequest.php | 23 + .../DataSpasial/UploadImporRequest.php | 23 + app/Services/DataSpasialApiService.php | 22 + .../views/dataspasial/impor/index.blade.php | 414 ++++++++++++++++-- routes/web.php | 15 + .../DataSpasial/ImporDataTemplateTest.php | 72 +++ tests/Feature/DataSpasial/ImporDataTest.php | 204 +++++++++ 11 files changed, 1330 insertions(+), 45 deletions(-) create mode 100644 app/Exports/ImporDataSpasialTemplateExport.php create mode 100644 app/Http/Requests/DataSpasial/DownloadTemplateRequest.php create mode 100644 app/Http/Requests/DataSpasial/PreviewImporRequest.php create mode 100644 app/Http/Requests/DataSpasial/UploadImporRequest.php create mode 100644 tests/Feature/DataSpasial/ImporDataTemplateTest.php create mode 100644 tests/Feature/DataSpasial/ImporDataTest.php diff --git a/.gitignore b/.gitignore index eec64139..67a2d921 100644 --- a/.gitignore +++ b/.gitignore @@ -38,5 +38,6 @@ graphify-out docs specs/ .opencode/ +.gemini/ .specify/ storage/sso diff --git a/app/Exports/ImporDataSpasialTemplateExport.php b/app/Exports/ImporDataSpasialTemplateExport.php new file mode 100644 index 00000000..e08d121e --- /dev/null +++ b/app/Exports/ImporDataSpasialTemplateExport.php @@ -0,0 +1,166 @@ +SHOULD_PRESERVE_EMPTY_ROWS = true; + + $writer = new Writer($options); + $writer->openToFile($filePath); + + $infoLabelStyle = (new Style)->setFontBold(); + + $writer->getCurrentSheet()->setName(self::SHEET_PETUNJUK); + $writer->addRow(Row::fromValues(['PETUNJUK PENGISIAN TEMPLATE IMPOR DATASPASIAL'], $infoLabelStyle)); + $writer->addRow(Row::fromValues([''])); + $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.'])); + if ($this->sektor) { + $writer->addRow(Row::fromValues([''])); + $writer->addRow(Row::fromValues(['Sektor: '.$this->sektor])); + } + + $writer->addNewSheetAndMakeItCurrent(); + $writer->getCurrentSheet()->setName(self::SHEET_DATA); + $writer->addRow(Row::fromValues(['TEMPLATE IMPOR DATASPASIAL'], $infoLabelStyle)); + $writer->addRow(Row::fromValues(['Sektor', $this->sektor])); + if ($this->periode) { + $writer->addRow(Row::fromValues(['Periode', $this->periode])); + } + $writer->addRow(Row::fromValues([''])); + $writer->addRow(Row::fromValues(['Catatan: Pilih desa dari dropdown pada kolom pertama.'])); + $writer->addRow(Row::fromValues([''])); + $writer->addRow(Row::fromValues([''])); + + $header = ['kode_desa', 'kode_fasilitas', 'nama_fasilitas']; + foreach ($this->items as $item) { + if (is_array($item)) { + $key = $item['kode'] ?? $item['key'] ?? $item['id'] ?? $item['nama'] ?? $item['label'] ?? 'field'; + } else { + $key = (string) $item; + } + $key = preg_replace('/[^A-Za-z0-9_]/', '_', strtolower((string) $key)); + $header[] = $key; + } + $headerStyle = (new Style)->setFontBold()->setBackgroundColor(Color::YELLOW); + $writer->addRow(Row::fromValues($header), $headerStyle); + + $writer->addNewSheetAndMakeItCurrent(); + $writer->getCurrentSheet()->setName(self::SHEET_DESA); + $writer->addRow(Row::fromValues(['Kode Desa', 'Nama Desa', 'Kode - Nama'], (new Style)->setFontBold())); + + $desaList = $this->desaList; + if (is_object($desaList) && method_exists($desaList, 'toArray')) { + $desaList = $desaList->toArray(); + } + if (! is_array($desaList)) { + $desaList = []; + } + + foreach ($desaList as $desa) { + if (is_object($desa)) { + if (method_exists($desa, 'toArray')) { + $desa = $desa->toArray(); + } else { + $desa = (array) $desa; + } + } + if (is_array($desa)) { + $attrs = $desa['attributes'] ?? []; + if (is_array($attrs)) { + $kode = $desa['kode_desa'] ?? $desa['kode'] ?? ($attrs['kode_desa'] ?? ($attrs['kode'] ?? '')); + $nama = $desa['nama_desa'] ?? $desa['nama'] ?? ($attrs['nama_desa'] ?? ($attrs['nama'] ?? '')); + } else { + $kode = $desa['kode_desa'] ?? $desa['kode'] ?? ''; + $nama = $desa['nama_desa'] ?? $desa['nama'] ?? ''; + } + } else { + continue; + } + $writer->addRow(Row::fromValues([(string) $kode, (string) $nama, (string) $kode.' - '.(string) $nama])); + } + + $writer->close(); + $this->injectDesaDropdown($filePath); + } + + 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 + + $zip = new ZipArchive; + if ($zip->open($filePath) !== true) { + return; + } + + $sheetPath = 'xl/worksheets/sheet2.xml'; + $xml = $zip->getFromName($sheetPath); + if ($xml === false) { + $sheetPath = 'xl/worksheets/sheet1.xml'; + $xml = $zip->getFromName($sheetPath); + } + if ($xml === false) { + $zip->close(); + return; + } + + $dataStartRow = self::CONTEXT_ROWS + 2; + $lastRow = $dataStartRow + 999; + $lastDesaRow = count($this->desaList) + 1; + $formula = sprintf("'%s'!\$C\$2:\$C\$%d", self::SHEET_DESA, $lastDesaRow); + + $validation = '' + .htmlspecialchars($formula, ENT_XML1 | ENT_QUOTES, 'UTF-8') + .''; + + $pos = strpos($xml, ''); + if ($pos !== false) { + $formulaBlock = ''; + for ($r = $dataStartRow; $r <= $dataStartRow + 49; $r++) { + $formulaBlock .= 'IFERROR(MID(A'.$r.',FIND(" - ",A'.$r.')+3,255),"")'; + } + $xml = substr_replace($xml, ''.$formulaBlock.$validation, $pos, strlen('')); + $zip->addFromString($sheetPath, $xml); + } else { + $zip->close(); + return; + } + + $zip->close(); + } +} diff --git a/app/Http/Controllers/DataSpasial/ImporDataController.php b/app/Http/Controllers/DataSpasial/ImporDataController.php index 0b566665..cbe05d52 100644 --- a/app/Http/Controllers/DataSpasial/ImporDataController.php +++ b/app/Http/Controllers/DataSpasial/ImporDataController.php @@ -4,17 +4,29 @@ namespace App\Http\Controllers\DataSpasial; +use App\Exports\ImporDataSpasialTemplateExport; +use App\Http\Requests\DataSpasial\PreviewImporRequest; +use App\Http\Requests\DataSpasial\UploadImporRequest; +use App\Services\ConfigApiService; +use App\Services\DataSpasialApiService; use App\Services\DataSpasialResult; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Support\Collection; +use Illuminate\Support\Facades\Session; +use Illuminate\View\View; +use OpenSpout\Reader\XLSX\Reader; +use Symfony\Component\HttpFoundation\BinaryFileResponse; -/** - * Menu Impor Data (Operator Impor). - * - * Kerangka menu pada fase fondasi ini. Alur impor lengkap (template, validasi - * per baris, ringkasan ditolak/konflik) menjadi lingkup KAB-04. - */ class ImporDataController extends DataSpasialController { + public function __construct( + DataSpasialApiService $dataspasial, + protected ConfigApiService $configApiService + ) { + parent::__construct($dataspasial); + } + protected function pageTitle(): string { return 'Impor Data'; @@ -27,10 +39,388 @@ protected function viewName(): string protected function fetch(Request $request): DataSpasialResult { - return $this->dataspasial->listFasilitas($request->only([ - 'sektor_id', - 'skema_versi_id', - 'kode_desa', - ])); + return DataSpasialResult::empty([], null, 200); + } + + public function index(Request $request): View + { + $sektors = $this->dataspasial->listSektor(); + $kecamatans = $this->configApiService->kecamatan(); + + return view($this->viewName(), [ + 'title' => $this->pageTitle(), + 'sektors' => $sektors, + 'kecamatans' => $kecamatans, + ]); + } + + public function downloadTemplate(Request $request) + { + $request->validate([ + 'sektor' => 'required|string', + ]); + + $sektor = $request->input('sektor'); + + $desaList = $this->getDesaListForTemplate($request); + + $skema = $this->dataspasial->listSkema(['sektor' => $sektor]); + $items = $this->extractSkemaItems($skema); + + $filename = 'template_impor_'.str_replace([' ', '/'], '_', strtolower($sektor)).'_'.date('YmdHis').'.xlsx'; + + $periode = $request->input('periode', date('Y-m')); + $export = new ImporDataSpasialTemplateExport($desaList, $items, $sektor, $periode); + $tempFile = tempnam(sys_get_temp_dir(), 'tmpl_'); + $export->write($tempFile); + + return response()->download($tempFile, $filename)->deleteFileAfterSend(); + } + + public function upload(UploadImporRequest $request): JsonResponse + { + $file = $request->file('file'); + $rows = $this->parseFile($file); + + // Normalisasi kode_desa dengan memisahkan "Kode - Nama" dan validasi format + $desaList = $this->configApiService->desaConfig(); + if ($desaList instanceof Collection) { + $desaList = $desaList->toArray(); + } + $validKodeDesa = []; + foreach ((array) $desaList as $d) { + if (is_object($d)) { + $validKodeDesa[] = (string) ($d->kode_desa ?? $d->kode ?? ''); + } elseif (is_array($d)) { + $attrs = $d['attributes'] ?? []; + $validKodeDesa[] = (string) ($d['kode_desa'] ?? $d['kode'] ?? ($attrs['kode_desa'] ?? ($attrs['kode'] ?? ''))); + } + } + $validKodeDesa = array_filter($validKodeDesa); + + foreach ($rows as $i => &$row) { + $kd = (string) ($row['kode_desa'] ?? ($row['desa'] ?? '')); + $kd = trim($kd); + if (strpos($kd, ' - ') !== false) { + $parts = explode(' - ', $kd, 2); + $kd = trim($parts[0]); + } + $row['kode_desa'] = $kd; + $row['nomor_baris'] = $i + 2; + $row['_kode_valid'] = $kd !== '' && (empty($validKodeDesa) || in_array($kd, $validKodeDesa, true)); + } + unset($row); + + Session::put('impor_parsed', [ + 'sektor' => $request->input('sektor'), + 'filename' => $file->getClientOriginalName(), + 'rows' => $rows, + ]); + + return response()->json([ + 'success' => true, + 'rows_count' => count($rows), + 'invalid_count' => count(array_filter($rows, fn ($r) => ($r['_kode_valid'] ?? true) === false)), + 'rows' => array_slice($rows, 0, 200), + ]); + } + + public function preview(PreviewImporRequest $request): JsonResponse + { + $parsed = Session::get('impor_parsed'); + if (! $parsed) { + return response()->json(['success' => false, 'message' => 'Tidak ada data hasil unggah.'], 422); + } + + $baris = []; + foreach (($parsed['rows'] ?? []) as $idx => $row) { + $nilai = $row['nilai'] ?? $this->extractNilai($row); + // Buang key internal yang bukan bagian skema (prefix underscore) + foreach (array_keys($nilai) as $k) { + if (strpos((string) $k, '_') === 0) { + unset($nilai[$k]); + } + } + $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'] ?? '', + 'periode' => $row['periode'] ?? date('Y-m'), + 'nilai' => $nilai, + ]; + } + + $payload = [ + 'sektor' => $parsed['sektor'], + 'filename' => $parsed['filename'], + 'force_overwrite' => (bool) $request->input('force_overwrite', false), + 'mode' => $request->input('mode', 'sebagian'), + 'baris' => $baris, + ]; + $result = $this->dataspasial->imporPratinjau($payload); + if ($result->isUnavailable()) { + return response()->json(['success' => false, 'message' => $result->message ?? 'Gagal melakukan pratinjau.'], 422); + } + + $data = $result->data; + logger()->error('data', $data); + $previewData = $this->normalizePreview($data, $result->meta); + + Session::put('impor_preview', $previewData); + + return response()->json(['success' => true, 'preview' => $previewData]); + } + + public function save(Request $request, string $imporId): JsonResponse + { + $result = $this->dataspasial->imporSimpan($imporId, $request->all()); + + if ($result->isUnavailable()) { + return response()->json(['success' => false, 'message' => $result->message ?? 'Gagal menyimpan impor.'], 422); + } + + Session::forget('impor_parsed'); + Session::forget('impor_preview'); + + return response()->json(['success' => true, 'result' => $result->data]); + } + + /** + * Normalisasi respons pratinjau API-06 (JSON:API) menjadi struktur flat + * yang mudah dikonsumsi frontend. + */ + private function normalizePreview(array $data, array $meta = []): array + { + $first = $data[0] ?? $data; + $attrs = []; + if (is_array($first) && isset($first['attributes']) && is_array($first['attributes'])) { + $attrs = $first['attributes']; + } elseif (is_array($first)) { + $attrs = $first; + } + + if (empty($attrs)) { + $attrs = $meta; + } + + $ringkasan = $attrs['ringkasan'] ?? []; + $laporan = $attrs['laporan'] ?? ($attrs['baris'] ?? []); + + $baris = []; + foreach ((array) $laporan as $item) { + if (is_object($item)) { + $item = (array) $item; + } + $pesan = $item['pesan'] ?? ($item['alasan'] ?? null); + if (is_array($pesan)) { + $pesan = implode('; ', $pesan); + } + $baris[] = [ + 'nomor_baris' => $item['nomor_baris'] ?? null, + 'kode_desa' => $item['kode_desa'] ?? '', + 'nama_desa' => $item['nama_desa'] ?? '', + 'kode_fasilitas' => $item['kode_fasilitas'] ?? '', + 'nama_fasilitas' => $item['nama_fasilitas'] ?? '', + 'periode' => $item['periode'] ?? '', + 'status' => $item['status'] ?? ($item['keterangan'] ?? ''), + 'pesan' => (string) ($pesan ?? ''), + 'nilai' => $item['nilai'] ?? [], + ]; + } + + return [ + 'impor_id' => $attrs['impor_id'] ?? ($first['impor_id'] ?? ($first['id'] ?? ($attrs['id'] ?? ''))), + 'sektor' => $attrs['sektor'] ?? null, + 'skema_versi' => $attrs['skema_versi'] ?? null, + 'filename' => $attrs['filename'] ?? '', + 'kadaluwarsa_pada' => $attrs['kadaluwarsa_pada'] ?? null, + 'force_overwrite' => $attrs['force_overwrite'] ?? false, + 'mode' => $attrs['mode'] ?? 'sebagian', + 'ringkasan' => [ + 'total_baris' => $ringkasan['total_baris'] ?? count($baris), + 'baris_siap' => $ringkasan['baris_siap'] ?? 0, + 'baris_menimpa' => $ringkasan['baris_menimpa'] ?? 0, + 'baris_konflik' => $ringkasan['baris_konflik'] ?? 0, + 'baris_galat' => $ringkasan['baris_galat'] ?? 0, + 'bisa_disimpan' => $ringkasan['bisa_disimpan'] ?? false, + ], + 'baris' => $baris, + ]; + } + + private function getDesaListForTemplate(Request $request): array + { + $kecamatanId = $request->input('kecamatan'); + if ($kecamatanId) { + $result = $this->configApiService->desaConfig(['filter[kode_kecamatan]' => $kecamatanId]); + } else { + $result = $this->configApiService->desaConfig(); + } + + if ($result instanceof Collection) { + $result = $result->toArray(); + } + + if (! is_array($result)) { + return []; + } + + return array_values(array_filter(array_map(function ($desa) { + if (is_object($desa)) { + $kode = (string) ($desa->kode_desa ?? $desa->kode ?? ''); + $nama = (string) ($desa->nama_desa ?? $desa->nama ?? ''); + + return $kode === '' ? null : ['kode_desa' => $kode, 'nama_desa' => $nama]; + } + if (is_array($desa)) { + $attrs = $desa['attributes'] ?? []; + $kode = (string) ($desa['kode_desa'] ?? $desa['kode'] ?? ($attrs['kode_desa'] ?? ($attrs['kode'] ?? ''))); + $nama = (string) ($desa['nama_desa'] ?? $desa['nama'] ?? ($attrs['nama_desa'] ?? ($attrs['nama'] ?? ''))); + + return $kode === '' ? null : ['kode_desa' => $kode, 'nama_desa' => $nama]; + } + + return null; + }, $result))); + } + + private function extractSkemaItems(DataSpasialResult $skema): array + { + $data = $skema->data; + if (empty($data)) { + return []; + } + $first = is_array($data[0]) ? $data[0] : $data; + $attrs = $first['attributes'] ?? $first; + if (isset($attrs['isian']) && is_array($attrs['isian'])) { + return $attrs['isian']; + } + if (isset($attrs['fields']) && is_array($attrs['fields'])) { + return $attrs['fields']; + } + + return []; + } + + private function parseFile($file): array + { + $rows = []; + $path = $file->getRealPath(); + + try { + $reader = new Reader; + $reader->open($path); + foreach ($reader->getSheetIterator() as $sheet) { + $sheetName = strtolower($sheet->getName()); + if (in_array($sheetName, ['petunjuk', 'daftar desa'], true)) { + continue; + } + $allRows = []; + foreach ($sheet->getRowIterator() as $row) { + $cells = $row->getCells(); + $values = []; + foreach ($cells as $cell) { + $values[] = trim((string) $cell->getValue()); + } + $allRows[] = $values; + } + if (empty($allRows)) { + continue; + } + $headerIndex = -1; + foreach ($allRows as $i => $r) { + $joined = strtolower(implode(' ', $r)); + if (strpos($joined, 'kode_desa') !== false && strpos($joined, 'kode_fasilitas') !== false) { + $headerIndex = $i; + break; + } + } + if ($headerIndex === -1) { + foreach ($allRows as $i => $r) { + $joined = strtolower(implode(' ', $r)); + if (strpos($joined, 'kode_desa') !== false) { + // look ahead a few rows + $headerIndex = $i; + break; + } + } + } + if ($headerIndex === -1) { + continue; + } + $header = array_map(function ($h) { + $h = strtolower(trim((string) $h)); + $h = str_replace([' ', '-'], '_', $h); + $h = preg_replace('/[^a-z0-9_]/', '', $h); + + return $h; + }, $allRows[$headerIndex]); + + for ($i = $headerIndex + 1; $i < count($allRows); $i++) { + $data = $allRows[$i]; + $hasContent = false; + foreach ($data as $k => $v) { + $val = trim((string) $v); + if ($val !== '' && strpos($val, '=') !== 0) { + $hasContent = true; + break; + } + } + if (! $hasContent) { + continue; + } + $row = []; + foreach ($header as $idx => $col) { + if ($col === '') { + continue; + } + if (isset($data[$idx])) { + $val = trim((string) $data[$idx]); + if (strpos($val, '=') === 0) { + continue; + } + $row[$col] = $val; + } + } + if (! empty($row)) { + if (isset($row['kode_desa']) && strpos($row['kode_desa'], ' - ') !== false) { + $parts = explode(' - ', $row['kode_desa'], 2); + $row['kode_desa'] = trim($parts[0]); + } + if (isset($row['kode_desa']) && strpos($row['kode_desa'], '=') === 0) { + continue; + } + if (empty($row['kode_desa']) && isset($row['desa'])) { + unset($row['desa']); + } + $rows[] = $row; + } + } + break; + } + $reader->close(); + } catch (\Throwable $e) { + // Fallback to previous method if parsing fails + } + + return $rows; + } + + private function extractNilai(array $row): array + { + $nilai = []; + $exclude = ['nomor_baris', 'kode_desa', 'desa', 'kode_fasilitas', 'nama_fasilitas', 'periode', 'petunjuk']; + foreach ($row as $k => $v) { + if (in_array($k, $exclude, true)) { + continue; + } + if ($v === null || $v === '') { + continue; + } + $nilai[$k] = $v; + } + + return $nilai; } } diff --git a/app/Http/Requests/DataSpasial/DownloadTemplateRequest.php b/app/Http/Requests/DataSpasial/DownloadTemplateRequest.php new file mode 100644 index 00000000..03bf9e85 --- /dev/null +++ b/app/Http/Requests/DataSpasial/DownloadTemplateRequest.php @@ -0,0 +1,23 @@ + 'required|string', + 'kecamatan' => 'nullable|string', + ]; + } + + public function authorize(): bool + { + return $this->user() !== null; + } +} diff --git a/app/Http/Requests/DataSpasial/PreviewImporRequest.php b/app/Http/Requests/DataSpasial/PreviewImporRequest.php new file mode 100644 index 00000000..f19c39e2 --- /dev/null +++ b/app/Http/Requests/DataSpasial/PreviewImporRequest.php @@ -0,0 +1,23 @@ + 'nullable|boolean', + 'mode' => 'nullable|string', + ]; + } + + public function authorize(): bool + { + return $this->user() !== null; + } +} diff --git a/app/Http/Requests/DataSpasial/UploadImporRequest.php b/app/Http/Requests/DataSpasial/UploadImporRequest.php new file mode 100644 index 00000000..847ba620 --- /dev/null +++ b/app/Http/Requests/DataSpasial/UploadImporRequest.php @@ -0,0 +1,23 @@ + 'required|file|mimes:xlsx|max:10240', + 'sektor' => 'required|string', + ]; + } + + public function authorize(): bool + { + return $this->user() !== null; + } +} diff --git a/app/Services/DataSpasialApiService.php b/app/Services/DataSpasialApiService.php index 602f1082..724e7798 100644 --- a/app/Services/DataSpasialApiService.php +++ b/app/Services/DataSpasialApiService.php @@ -606,4 +606,26 @@ public function imporNilai(array $body, ?int $schemaVersion = null): DataSpasial { return $this->request('POST', 'impor', [], $body, $schemaVersion); } + + /** + * Pratinjau impor data spasial (API-06). + * + * @param array $body + */ + public function imporPratinjau(array $body, ?int $schemaVersion = null): DataSpasialResult + { + return $this->request('POST', 'impor/pratinjau', [], $body, $schemaVersion); + } + + /** + * Simpan hasil pratinjau impor data spasial (API-06). + * + * @param array $body + */ + public function imporSimpan(string $imporId, array $body = [], ?int $schemaVersion = null): DataSpasialResult + { + $path = 'impor/'.rawurlencode($imporId).'/simpan'; + + return $this->request('POST', $path, [], $body, $schemaVersion); + } } diff --git a/resources/views/dataspasial/impor/index.blade.php b/resources/views/dataspasial/impor/index.blade.php index 5142d521..378908b4 100644 --- a/resources/views/dataspasial/impor/index.blade.php +++ b/resources/views/dataspasial/impor/index.blade.php @@ -10,45 +10,391 @@ @include('partials.breadcrumbs') @include('partials.flash_message') - -
-
-
-
-

Daftar Fasilitas

+
+
+
+
+

Bantuan Pengisian DataSpasial

+
+
+
+
+
+ Alur: 1) Unduh Templat (pilih sektor dan kecamatan/semua kecamatan) 2) Unggah XLSX 3) Pratinjau & Simpan +
+
-
-

- Kerangka menu. Alur impor lengkap (template, validasi per baris, - ringkasan ditolak dan konflik) menjadi lingkup fitur turunan dan - dibangun di atas service DataSpasialApiService tanpa - mengubah kontraknya. -

- -
- - - - - - - - - - @foreach ($result->data as $item) - @php $attributes = $item['attributes'] ?? []; @endphp - - - - - + + +
+
+ + +
+
+ +
-
RujukanNamaSektor
{{ $attributes['rujukan_fasilitas'] ?? $item['id'] ?? '-' }}{{ $attributes['nama'] ?? '-' }}{{ $attributes['sektor'] ?? $attributes['sektor_id'] ?? '-' }}
+ +
+
+ + +
+
+ +
+
+ + +
+
+ +
+ @csrf + +
+ +
+ +
+
+ Maks 10MB. Parsing dilakukan di OpenKab. +
+
+
+ + +
- +
@stop + +@push('js') + +@endpush diff --git a/routes/web.php b/routes/web.php index 56042b5e..7c272dc9 100644 --- a/routes/web.php +++ b/routes/web.php @@ -540,6 +540,21 @@ Route::get('impor', [ImporDataController::class, 'index']) ->middleware('permission:dataspasial-impor-read') ->name('dataspasial.impor'); + Route::get('impor/template', [ImporDataController::class, 'downloadTemplate']) + ->middleware('permission:dataspasial-impor-read') + ->name('dataspasial.impor.template'); + Route::post('impor/template', [ImporDataController::class, 'downloadTemplate']) + ->middleware('permission:dataspasial-impor-read') + ->name('dataspasial.impor.template.post'); + Route::post('impor/upload', [ImporDataController::class, 'upload']) + ->middleware('permission:dataspasial-impor-read') + ->name('dataspasial.impor.upload'); + Route::post('impor/pratinjau', [ImporDataController::class, 'preview']) + ->middleware('permission:dataspasial-impor-read') + ->name('dataspasial.impor.preview'); + Route::post('impor/simpan/{impor_id}', [ImporDataController::class, 'save']) + ->middleware('permission:dataspasial-impor-read') + ->name('dataspasial.impor.simpan'); Route::get('monitoring', [MonitoringController::class, 'index']) ->middleware('permission:dataspasial-monitoring-read') diff --git a/tests/Feature/DataSpasial/ImporDataTemplateTest.php b/tests/Feature/DataSpasial/ImporDataTemplateTest.php new file mode 100644 index 00000000..0868a1a1 --- /dev/null +++ b/tests/Feature/DataSpasial/ImporDataTemplateTest.php @@ -0,0 +1,72 @@ +withoutMiddleware(); + } + + public function test_template_requires_sektor(): void + { + $response = $this->get(route('dataspasial.impor.template')); + $this->assertTrue(in_array($response->status(), [302, 422])); + } + + public function test_template_download_xlsx_with_desa_list_and_dropdown(): void + { + Http::fake([ + '*/api/v1/dataspasial/skema*' => Http::response([ + 'data' => [[ + 'type' => 'skema', + 'attributes' => [ + 'sektor' => 'kesehatan', + 'isian' => [ + ['kode' => 'jumlah_penduduk', 'nama' => 'Jumlah Penduduk'], + ], + ], + ]], + ]), + '*/api/v1/config/desa*' => Http::response([ + 'data' => [ + [ + 'id' => '1', + 'type' => 'desa', + 'attributes' => [ + 'kode_desa' => '3501010001', + 'nama_desa' => 'Desa Satu', + ], + ], + [ + 'id' => '2', + 'type' => 'desa', + 'attributes' => [ + 'kode_desa' => '3501010002', + 'nama_desa' => 'Desa Dua', + ], + ], + ], + ]), + '*/api/v1/config/kecamatan*' => Http::response(['data' => []]), + ]); + + $response = $this->get(route('dataspasial.impor.template', [ + 'sektor' => 'kesehatan', + 'kecamatan' => '350101', + ])); + + $response->assertStatus(200); + $this->assertStringContainsString('.xlsx', $response->headers->get('content-disposition')); + $this->assertStringContainsString('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', $response->headers->get('content-type')); + } +} diff --git a/tests/Feature/DataSpasial/ImporDataTest.php b/tests/Feature/DataSpasial/ImporDataTest.php new file mode 100644 index 00000000..886df7f6 --- /dev/null +++ b/tests/Feature/DataSpasial/ImporDataTest.php @@ -0,0 +1,204 @@ + 'https://api.example.test']); + config(['dataspasial.cache_ttl' => 300]); + + Setting::query()->updateOrCreate( + ['key' => 'database_gabungan_api_key'], + ['value' => 'test-token'] + ); + + Cache::flush(); + + fakeConfigEndpoint(); + } + + private function actingAsOperatorImpor(): User + { + $user = makeRole('operator impor', ['dataspasial-impor-read']); + $this->actingAs($user); + + return $user; + } + + public function test_menu_impor_bisa_diakses_oleh_user_dengan_permission(): void + { + $this->actingAsOperatorImpor(); + + $this->get(route('dataspasial.impor'))->assertStatus(200); + } + + public function test_template_membutuhkan_sektor_dan_wilayah(): void + { + $this->actingAsOperatorImpor(); + + $this->postJson(route('dataspasial.impor.template'), [])->assertStatus(422); + } + + public function test_upload_file_xlsx_diparse(): void + { + $this->actingAsOperatorImpor(); + + $content = "kode_desa,kode_fasilitas,nama_fasilitas,jumlah_dokter\n5102012001,POS-001,Posyandu Mawar,4\n"; + $file = UploadedFile::fake()->createWithContent('faskes.xlsx', $content); + + $this->post(route('dataspasial.impor.upload'), ['file' => $file, 'sektor' => 'kesehatan']) + ->assertStatus(200) + ->assertJson(['success' => true]); + } + + public function test_tombol_simpan_tidak_aktif_sebelum_pratinjau(): void + { + $this->actingAsOperatorImpor(); + + Session::put('impor_parsed', [ + 'sektor' => 'kesehatan', + 'filename' => 'test.csv', + 'rows' => [], + ]); + Http::fake([ + '*/impor/pratinjau' => Http::response(['data' => [['impor_id' => 'imp001', 'diterima' => 0, 'ditolak' => 0]]], 200), + ]); + + $this->post(route('dataspasial.impor.preview'))->assertStatus(200); + } + + public function test_preview_mengembalikan_ringkasan_dan_baris_galat(): void + { + $this->actingAsOperatorImpor(); + + Session::put('impor_parsed', [ + 'sektor' => 'kesehatan', + 'filename' => 'template.xlsx', + 'rows' => [ + ['kode_desa' => '5102022004', 'kode_fasilitas' => 'FAS-01', 'nama_fasilitas' => 'Puskesmas', 'jumlah_bidan' => '10'], + ], + ]); + Http::fake([ + '*/impor/pratinjau' => Http::response([ + 'data' => [[ + 'type' => 'pratinjau impor data spasial', + 'id' => 'a7afd583-ad2a-404b-bd55-2e5094e0990b', + 'attributes' => [ + 'impor_id' => 'a7afd583-ad2a-404b-bd55-2e5094e0990b', + 'sektor' => ['kode' => 'kesehatan', 'nama' => 'Kesehatan'], + 'filename' => 'template.xlsx', + 'mode' => 'sebagian', + 'ringkasan' => [ + 'total_baris' => 1, + 'baris_siap' => 0, + 'baris_menimpa' => 0, + 'baris_konflik' => 0, + 'baris_galat' => 1, + 'bisa_disimpan' => false, + ], + 'laporan' => [[ + 'nomor_baris' => 2, + 'kode_desa' => '5102022004', + 'nama_desa' => 'Mambang', + 'kode_fasilitas' => 'FAS-01', + 'nama_fasilitas' => 'Puskesmas', + 'periode' => '2026-10', + 'status' => 'galat', + 'pesan' => ['Kode isian tidak dikenal pada skema terbit.'], + 'nilai' => ['jumlah_bidan' => '10'], + ]], + ], + ]], + ], 200), + ]); + + $response = $this->post(route('dataspasial.impor.preview')); + $response->assertStatus(200) + ->assertJsonPath('success', true) + ->assertJsonPath('preview.impor_id', 'a7afd583-ad2a-404b-bd55-2e5094e0990b') + ->assertJsonPath('preview.ringkasan.bisa_disimpan', false) + ->assertJsonPath('preview.ringkasan.baris_galat', 1) + ->assertJsonPath('preview.baris.0.nama_desa', 'Mambang') + ->assertJsonPath('preview.baris.0.status', 'galat') + ->assertJsonPath('preview.baris.0.nilai.jumlah_bidan', '10'); + } + + public function test_payload_pratinjau_membuang_key_internal(): void + { + $this->actingAsOperatorImpor(); + + Session::put('impor_parsed', [ + 'sektor' => 'kesehatan', + 'filename' => 'template.xlsx', + 'rows' => [ + ['kode_desa' => '5102022004', 'kode_fasilitas' => 'FAS-01', 'nama_fasilitas' => 'Puskesmas', 'jumlah_bidan' => '10', '_kode_valid' => true], + ], + ]); + + Http::fake([ + '*/impor/pratinjau' => Http::response(['data' => [['impor_id' => 'imp1', 'attributes' => ['ringkasan' => ['total_baris' => 1, 'baris_galat' => 0, 'bisa_disimpan' => true], 'laporan' => []]]]], 200), + ]); + + $this->post(route('dataspasial.impor.preview'))->assertStatus(200); + + Http::assertSent(function ($request) { + $body = $request->data(); + $nilai = $body['baris'][0]['nilai'] ?? []; + + return ! array_key_exists('_kode_valid', $nilai) && ($nilai['jumlah_bidan'] ?? null) === '10'; + }); + } + + public function test_preview_simpan_diizinkan_saat_bisa_disimpan_true(): void + { + $this->actingAsOperatorImpor(); + + Session::put('impor_parsed', [ + 'sektor' => 'kesehatan', + 'filename' => 'template.xlsx', + 'rows' => [ + ['kode_desa' => '5102022004', 'kode_fasilitas' => 'FAS-01', 'nama_fasilitas' => 'Puskesmas', 'jumlah_bidan' => '10'], + ], + ]); + + Http::fake([ + '*/impor/pratinjau' => Http::response(['data' => [['impor_id' => 'imp-ok', 'attributes' => ['ringkasan' => ['total_baris' => 1, 'baris_siap' => 1, 'baris_galat' => 0, 'bisa_disimpan' => true], 'laporan' => []]]]], 200), + ]); + + $this->post(route('dataspasial.impor.preview')) + ->assertStatus(200) + ->assertJsonPath('preview.ringkasan.bisa_disimpan', true) + ->assertJsonPath('preview.impor_id', 'imp-ok'); + } + + public function test_index_hanya_menampilkan_sektor_dan_kecamatan(): void + { + $this->actingAsOperatorImpor(); + + $this->get(route('dataspasial.impor'))->assertStatus(200)->assertViewHas('sektors')->assertViewHas('kecamatans'); + } + + public function test_download_template_memakai_form_request_validasi(): void + { + $this->actingAsOperatorImpor(); + + $this->postJson(route('dataspasial.impor.template'), ['sektor' => ''])->assertStatus(422); + } +} From 55b3fa8e1fea1a57611665ab3682abd38e7c46bd Mon Sep 17 00:00:00 2001 From: Abah Roland <59082428+vickyrolanda@users.noreply.github.com> Date: Mon, 9 Nov 2026 13:31:27 +0700 Subject: [PATCH 2/2] update catatan rilis --- catatan_rilis.md | 1 + 1 file changed, 1 insertion(+) diff --git a/catatan_rilis.md b/catatan_rilis.md index ef19adff..1b2234a5 100644 --- a/catatan_rilis.md +++ b/catatan_rilis.md @@ -11,6 +11,7 @@ Di rilis ini, versi 2611.0.0 berisi penambahan dan perbaikan yang diminta penggu 6. [#1298](https://github.com/OpenSID/OpenKab/issues/1298) [KAB-03] Penerbitan, riwayat versi & status adopsi desa. 7. [#1299](https://github.com/OpenSID/OpenKab/issues/1299) Feat: Peta Gabungan Geospasial & DataSpasial. 8. [#1300](https://github.com/OpenSID/OpenKab/issues/1300) [KAB-05] Dasbor indikator, grafik & ekspor. +9. [#1301](https://github.com/OpenSID/OpenKab/issues/1301) [KAB-06] Impor data desa dari file: templat, unggah & pratinjau. #### Perbaikan BUG