From 9345e56a9cac3ce07c09d166d7c6a7d1e76184aa Mon Sep 17 00:00:00 2001 From: Habibie Date: Mon, 26 Oct 2026 22:48:13 +0700 Subject: [PATCH 1/8] Sinkronisasi Penduduk dari OpenSID Database Gabungan Gagal Diam-diam --- .../Controllers/Api/PendudukController.php | 54 ++++-- .../Requests/Api/SinkronPendudukRequest.php | 64 +++++++ app/Jobs/PendudukQueueJob.php | 9 +- openapi/openapi.yaml | 48 +++++ tests/Feature/Api/SinkronPendudukApiTest.php | 173 ++++++++++++++++++ tests/Unit/Jobs/PendudukQueueJobTest.php | 61 ++++++ 6 files changed, 387 insertions(+), 22 deletions(-) create mode 100644 app/Http/Requests/Api/SinkronPendudukRequest.php create mode 100644 tests/Feature/Api/SinkronPendudukApiTest.php create mode 100644 tests/Unit/Jobs/PendudukQueueJobTest.php diff --git a/app/Http/Controllers/Api/PendudukController.php b/app/Http/Controllers/Api/PendudukController.php index 84264a2558..99fbf5e6a4 100644 --- a/app/Http/Controllers/Api/PendudukController.php +++ b/app/Http/Controllers/Api/PendudukController.php @@ -32,13 +32,12 @@ namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; +use App\Http\Requests\Api\SinkronPendudukRequest; use App\Http\Requests\PendudukRequest; use App\Imports\SinkronPenduduk; use App\Jobs\PendudukQueueJob; -use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; -use Illuminate\Support\Str; use ZipArchive; class PendudukController extends Controller @@ -50,6 +49,7 @@ class PendudukController extends Controller * * @bodyParam desa_id string required Kode desa. Example: 3201012001 * @bodyParam hapus_penduduk array required Array objek penduduk yang akan dihapus. Setiap objek berisi: id_pend_desa (int), foto (string/null), desa_id (string). + * * @response { * "status": "success", * "message": "Proses sync Data Penduduk OpenSID sedang berjalan" @@ -80,16 +80,23 @@ public function store(PendudukRequest $request) * rw, rt, status_dasar, status_rekam. * * @bodyParam file file required File ZIP (max 5MB) berisi data penduduk + foto. Example: null + * * @response { + * "status": "success", * "message": "Data Foto Telah Berhasil di Sinkronkan" * } + * @response 422 { + * "status": "danger", + * "message": "The file field is required.", + * "errors": {"file": ["The file field is required."]} + * } + * @response 500 { + * "status": "danger", + * "message": "Import data penduduk gagal. Periksa log OpenDK untuk detail kesalahan." + * } */ - public function storedata(Request $request) + public function storedata(SinkronPendudukRequest $request) { - $this->validate($request, [ - 'file' => 'file|mimes:zip|max:5120', - ]); - try { // Upload file zip temporary using FileUploadService for security $file = $request->file('file'); @@ -105,29 +112,33 @@ public function storedata(Request $request) // Extract filename from path $name = basename($path); - + // Temporary path file $path = storage_path("app/public/temp/{$name}"); $extract = storage_path('app/public/penduduk/foto/'); $excellName = ''; // Ekstrak file $zip = new ZipArchive(); - if ($zip->open($path) === TRUE) { + if ($zip->open($path) !== true) { + throw new \RuntimeException('Gagal membuka file zip.'); + } - for ($i = 0; $i < $zip->numFiles; $i++) { + for ($i = 0; $i < $zip->numFiles; $i++) { - $filename = $zip->getNameIndex($i); + $filename = $zip->getNameIndex($i); - if (pathinfo($filename, PATHINFO_EXTENSION) === 'xlsx') { - $excellName = $filename; - break; - } + if (pathinfo($filename, PATHINFO_EXTENSION) === 'xlsx') { + $excellName = $filename; + break; } - - $zip->extractTo($extract); - $zip->close(); } + $zip->extractTo($extract); + $zip->close(); + + if ($excellName === '') { + throw new \RuntimeException('File xlsx tidak ditemukan di dalam zip.'); + } // Proses impor excell (new SinkronPenduduk()) @@ -137,7 +148,11 @@ public function storedata(Request $request) 'error' => $e->getMessage(), ]); - return back()->with('error', 'Import data gagal.'); + // HTTP 500 agar OpenSID (Guzzle) mendeteksi kegagalan; detail exception hanya di log + return response()->json([ + 'status' => 'danger', + 'message' => 'Import data penduduk gagal. Periksa log OpenDK untuk detail kesalahan.', + ], 500); } // Hapus folder temp ketika sudah selesai @@ -146,6 +161,7 @@ public function storedata(Request $request) Storage::disk('public')->delete('penduduk/foto/' . $excellName); return response()->json([ + 'status' => 'success', 'message' => 'Data Foto Telah Berhasil di Sinkronkan', ]); } diff --git a/app/Http/Requests/Api/SinkronPendudukRequest.php b/app/Http/Requests/Api/SinkronPendudukRequest.php new file mode 100644 index 0000000000..96b17cc2c0 --- /dev/null +++ b/app/Http/Requests/Api/SinkronPendudukRequest.php @@ -0,0 +1,64 @@ + 'required|file|mimes:zip|max:5120', + ]; + } + + /** + * Endpoint dipanggil OpenSID tanpa header Accept JSON; tanpa ini validasi gagal + * dibalas redirect 302 yang dianggap sukses oleh OpenSID. + */ + protected function failedValidation(Validator $validator) + { + throw new HttpResponseException(response()->json([ + 'status' => 'danger', + 'message' => $validator->errors()->first(), + 'errors' => $validator->errors(), + ], 422)); + } +} diff --git a/app/Jobs/PendudukQueueJob.php b/app/Jobs/PendudukQueueJob.php index 89c888342e..b422024612 100644 --- a/app/Jobs/PendudukQueueJob.php +++ b/app/Jobs/PendudukQueueJob.php @@ -56,6 +56,7 @@ class PendudukQueueJob implements ShouldQueue * Create a new job instance. * * @param array $request + * * @return void */ public function __construct($request) @@ -85,10 +86,12 @@ public function handle() try { // Batch delete penduduk - if (isset($this->request['hapus_penduduk'])) { + if (! empty($this->request['hapus_penduduk'])) { + $id_pend_desa = $foto = $desa_id = []; + foreach ($this->request['hapus_penduduk'] as $item) { $id_pend_desa[] = $item['id_pend_desa']; - $foto[] = $item['foto']; + $foto[] = $item['foto'] ?? null; $desa_id[] = $item['desa_id']; } @@ -96,7 +99,7 @@ public function handle() Penduduk::whereIn('desa_id', $desa_id)->whereIn('id_pend_desa', $id_pend_desa)->delete(); // Hapus file foto di folder - foreach ($foto as $hapusfoto) { + foreach (array_filter($foto) as $hapusfoto) { Storage::disk('public')->delete('penduduk/foto/'.'kecil_'.$hapusfoto); } } diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index e4e3ebbfd2..ea7bd79308 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -218,11 +218,59 @@ paths: schema: type: object example: + status: success message: 'Data Foto Telah Berhasil di Sinkronkan' properties: + status: + type: string + example: success message: type: string example: 'Data Foto Telah Berhasil di Sinkronkan' + 422: + description: '' + content: + application/json: + schema: + type: object + example: + status: danger + message: 'The file field is required.' + errors: + file: + - 'The file field is required.' + properties: + status: + type: string + example: danger + message: + type: string + example: 'The file field is required.' + errors: + type: object + properties: + file: + type: array + example: + - 'The file field is required.' + items: + type: string + 500: + description: '' + content: + application/json: + schema: + type: object + example: + status: danger + message: 'Import data penduduk gagal. Periksa log OpenDK untuk detail kesalahan.' + properties: + status: + type: string + example: danger + message: + type: string + example: 'Import data penduduk gagal. Periksa log OpenDK untuk detail kesalahan.' tags: - 'OpenSID Integration' requestBody: diff --git a/tests/Feature/Api/SinkronPendudukApiTest.php b/tests/Feature/Api/SinkronPendudukApiTest.php new file mode 100644 index 0000000000..3579138f6e --- /dev/null +++ b/tests/Feature/Api/SinkronPendudukApiTest.php @@ -0,0 +1,173 @@ + $desaId, + 'id' => $idPendDesa, + 'nomor_nik' => '3324030101900001', + 'nama' => 'Penduduk Sinkron', + 'nomor_kk' => '3324030101900002', + 'jenis_kelamin' => 1, + 'tempat_lahir' => 'Kendal', + 'tanggal_lahir' => '1990-01-01', + 'agama' => 1, + 'pendidikan_dlm_kk' => 3, + 'pendidikan_sdg_ditempuh' => 1, + 'pekerjaan' => 1, + 'kawin' => 1, + 'hubungan_keluarga' => 1, + 'kewarganegaraan' => 1, + 'nama_ibu' => 'Ibu', + 'nama_ayah' => 'Ayah', + 'gol_darah' => 1, + 'hamil' => 0, + 'alamat' => 'Jl. Desa', + 'dusun' => 'Dusun 1', + 'rw' => '001', + 'rt' => '001', + 'status_dasar' => 1, + 'status_rekam' => 1, + 'created_at' => '2026-01-01 00:00:00', + 'updated_at' => '2026-01-01 00:00:00', + ]); +} + +/** + * Buat zip seperti kiriman OpenSID; tanpa $baris zip hanya berisi berkas teks. + */ +function zipPenduduk(?array $baris): UploadedFile +{ + $dir = storage_path('framework/testing/sinkron-penduduk'); + File::ensureDirectoryExists($dir); + $zipPath = $dir.'/penduduk.zip'; + + $zip = new ZipArchive(); + $zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE); + + if ($baris === null) { + $zip->addFromString('bukan_data.txt', 'kosong'); + } else { + $spreadsheet = new Spreadsheet(); + $spreadsheet->getActiveSheet()->fromArray([KOLOM_XLSX_PENDUDUK, array_values($baris)]); + $xlsxPath = $dir.'/penduduk_opendk.xlsx'; + (new Xlsx($spreadsheet))->save($xlsxPath); + $zip->addFile($xlsxPath, 'penduduk_opendk.xlsx'); + } + + $zip->close(); + + return new UploadedFile($zipPath, 'penduduk.zip', 'application/zip', null, true); +} + +beforeEach(function () { + $this->desa = DataDesa::factory()->create(['desa_id' => '33.24.03.2008']); + + $this->token = auth('api')->login(User::factory()->create()); + SettingAplikasi::updateOrCreate( + ['key' => 'api_key_opendk'], + ['value' => $this->token, 'type' => 'input', 'description' => 'API Key OpenDK', 'kategori' => 'aplikasi', 'option' => '[]'] + ); + + $this->berkasTempAwal = File::glob(storage_path('app/public/temp/*')); +}); + +afterEach(function () { + // storedata meninggalkan zip di disk public/temp; bersihkan hanya berkas hasil test ini + File::delete(array_diff(File::glob(storage_path('app/public/temp/*')), $this->berkasTempAwal)); + File::deleteDirectory(storage_path('framework/testing/sinkron-penduduk')); +}); + +describe('POST /api/v1/penduduk/storedata', function () { + test('berhasil mengimpor penduduk dengan id_pend_desa di atas batas int', function () { + $idBesar = 2499099148; + + $response = withToken($this->token)->post('/api/v1/penduduk/storedata', [ + 'file' => zipPenduduk(barisPenduduk($this->desa->desa_id, $idBesar)), + ]); + + $response->assertOk()->assertJson(['status' => 'success']); + + expect(Penduduk::where('desa_id', $this->desa->desa_id)->where('id_pend_desa', $idBesar)->exists()) + ->toBeTrue(); + }); + + test('membalas json 500 bila zip tidak berisi xlsx', function () { + $response = withToken($this->token)->post('/api/v1/penduduk/storedata', [ + 'file' => zipPenduduk(null), + ]); + + $response->assertStatus(500) + ->assertExactJson([ + 'status' => 'danger', + 'message' => 'Import data penduduk gagal. Periksa log OpenDK untuk detail kesalahan.', + ]); + }); + + test('membalas json 500 bila desa pada xlsx tidak terdaftar', function () { + $response = withToken($this->token)->post('/api/v1/penduduk/storedata', [ + 'file' => zipPenduduk(barisPenduduk('99.99.99.9999', 1)), + ]); + + $response->assertStatus(500)->assertJson(['status' => 'danger']); + }); + + test('membalas json 422 tanpa redirect bila file tidak dikirim', function () { + // OpenSID tidak mengirim header Accept: application/json + $response = withToken($this->token)->post('/api/v1/penduduk/storedata', []); + + $response->assertStatus(422) + ->assertJson(['status' => 'danger']) + ->assertJsonValidationErrors('file'); + }); +}); diff --git a/tests/Unit/Jobs/PendudukQueueJobTest.php b/tests/Unit/Jobs/PendudukQueueJobTest.php new file mode 100644 index 0000000000..5734ef35a1 --- /dev/null +++ b/tests/Unit/Jobs/PendudukQueueJobTest.php @@ -0,0 +1,61 @@ + []]))->handle(); + + Exceptions::assertNothingReported(); +}); + +test('menghapus penduduk sesuai desa dan id_pend_desa', function () { + $desa = DataDesa::factory()->create(['desa_id' => '33.24.03.2008']); + $desaLain = DataDesa::factory()->create(['desa_id' => '33.24.03.2009']); + + $dihapus = Penduduk::factory()->create(['desa_id' => $desa->desa_id, 'id_pend_desa' => 2499099148]); + $tetap = Penduduk::factory()->create(['desa_id' => $desaLain->desa_id, 'id_pend_desa' => 2499099148]); + + (new PendudukQueueJob(['hapus_penduduk' => [ + ['id_pend_desa' => 2499099148, 'desa_id' => $desa->desa_id], + ]]))->handle(); + + Exceptions::assertNothingReported(); + expect(Penduduk::find($dihapus->id))->toBeNull() + ->and(Penduduk::find($tetap->id))->not->toBeNull(); +}); From db0e733f9ca1df7dcfb06055fe9cd24e0d9d5bd8 Mon Sep 17 00:00:00 2001 From: Habibie Date: Wed, 28 Oct 2026 13:10:16 +0700 Subject: [PATCH 2/8] sesuaikan limit upload penduduk sinkronisasi --- app/Http/Controllers/Api/PendudukController.php | 2 +- app/Http/Requests/Api/SinkronPendudukRequest.php | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/app/Http/Controllers/Api/PendudukController.php b/app/Http/Controllers/Api/PendudukController.php index 99fbf5e6a4..ec9de080a7 100644 --- a/app/Http/Controllers/Api/PendudukController.php +++ b/app/Http/Controllers/Api/PendudukController.php @@ -143,7 +143,7 @@ public function storedata(SinkronPendudukRequest $request) // Proses impor excell (new SinkronPenduduk()) ->queue($extract . $excellName); - } catch (\Exception $e) { + } catch (\Throwable $e) { Log::error('Penduduk storedata failed', [ 'error' => $e->getMessage(), ]); diff --git a/app/Http/Requests/Api/SinkronPendudukRequest.php b/app/Http/Requests/Api/SinkronPendudukRequest.php index 96b17cc2c0..d370dc2aed 100644 --- a/app/Http/Requests/Api/SinkronPendudukRequest.php +++ b/app/Http/Requests/Api/SinkronPendudukRequest.php @@ -31,6 +31,7 @@ namespace App\Http\Requests\Api; +use App\Services\FileUploadService; use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Exceptions\HttpResponseException; @@ -44,8 +45,10 @@ public function authorize(): bool public function rules(): array { + $maxRule = FileUploadService::isLimitEnabled() ? '|max:5120' : ''; + return [ - 'file' => 'required|file|mimes:zip|max:5120', + 'file' => 'required|file|mimes:zip' . $maxRule, ]; } From 7adc55b15fabbef8160a72fb6ec16fe3d12329b4 Mon Sep 17 00:00:00 2001 From: Habibie Date: Fri, 30 Oct 2026 13:17:54 +0700 Subject: [PATCH 3/8] sesuaikan permintaan review --- .../Controllers/Api/PendudukController.php | 62 +++++++++++------- app/Http/Requests/PendudukRequest.php | 20 +++++- app/Imports/SinkronPenduduk.php | 12 ++-- app/Jobs/PendudukQueueJob.php | 24 +++---- tests/Feature/Api/SinkronPendudukApiTest.php | 65 ++++++++++++++++++- tests/Unit/Jobs/PendudukQueueJobTest.php | 29 +++++++++ 6 files changed, 166 insertions(+), 46 deletions(-) diff --git a/app/Http/Controllers/Api/PendudukController.php b/app/Http/Controllers/Api/PendudukController.php index ec9de080a7..ad7f2623cd 100644 --- a/app/Http/Controllers/Api/PendudukController.php +++ b/app/Http/Controllers/Api/PendudukController.php @@ -54,6 +54,11 @@ class PendudukController extends Controller * "status": "success", * "message": "Proses sync Data Penduduk OpenSID sedang berjalan" * } + * @response 422 { + * "status": "danger", + * "message": "The hapus penduduk field is required.", + * "errors": {"hapus_penduduk": ["The hapus penduduk field is required."]} + * } */ public function store(PendudukRequest $request) { @@ -97,6 +102,9 @@ public function store(PendudukRequest $request) */ public function storedata(SinkronPendudukRequest $request) { + $zipPath = null; + $excellName = ''; + try { // Upload file zip temporary using FileUploadService for security $file = $request->file('file'); @@ -107,42 +115,45 @@ public function storedata(SinkronPendudukRequest $request) // Define allowed MIME types for zip files $allowedMimes = \App\Services\FileUploadService::getAllowedMimes('archive'); - // Upload file securely to temp directory - $path = $fileUploadService->uploadSecure($file, 'temp', $allowedMimes, 5120); // 5MB max - - // Extract filename from path - $name = basename($path); + // Upload file securely to temp directory (disk public) + $zipPath = $fileUploadService->uploadSecure($file, 'temp', $allowedMimes, 5120); // 5MB max - // Temporary path file - $path = storage_path("app/public/temp/{$name}"); $extract = storage_path('app/public/penduduk/foto/'); - $excellName = ''; - // Ekstrak file $zip = new ZipArchive(); - if ($zip->open($path) !== true) { + if ($zip->open(Storage::disk('public')->path($zipPath)) !== true) { throw new \RuntimeException('Gagal membuka file zip.'); } + // Hanya ekstrak xlsx dan foto di root zip; entri lain (subfolder, tipe lain) diabaikan + $entries = []; for ($i = 0; $i < $zip->numFiles; $i++) { - $filename = $zip->getNameIndex($i); - if (pathinfo($filename, PATHINFO_EXTENSION) === 'xlsx') { + if ($filename !== basename($filename)) { + continue; + } + + $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); + + if ($extension === 'xlsx' && $excellName === '') { $excellName = $filename; - break; + $entries[] = $filename; + } elseif (in_array($extension, ['jpg', 'jpeg', 'png'], true)) { + $entries[] = $filename; } } - $zip->extractTo($extract); - $zip->close(); - if ($excellName === '') { + $zip->close(); + throw new \RuntimeException('File xlsx tidak ditemukan di dalam zip.'); } - // Proses impor excell - (new SinkronPenduduk()) - ->queue($extract . $excellName); + $zip->extractTo($extract, $entries); + $zip->close(); + + // Impor sinkron agar kegagalan langsung dibalas ke OpenSID + (new SinkronPenduduk())->import($extract . $excellName); } catch (\Throwable $e) { Log::error('Penduduk storedata failed', [ 'error' => $e->getMessage(), @@ -153,13 +164,16 @@ public function storedata(SinkronPendudukRequest $request) 'status' => 'danger', 'message' => 'Import data penduduk gagal. Periksa log OpenDK untuk detail kesalahan.', ], 500); + } finally { + // Hapus zip dan xlsx temp, baik impor berhasil maupun gagal + if ($zipPath) { + Storage::disk('public')->delete($zipPath); + } + if ($excellName !== '') { + Storage::disk('public')->delete('penduduk/foto/' . $excellName); + } } - // Hapus folder temp ketika sudah selesai - Storage::deleteDirectory('temp'); - // Hapus file excell temp ketika sudah selesai - Storage::disk('public')->delete('penduduk/foto/' . $excellName); - return response()->json([ 'status' => 'success', 'message' => 'Data Foto Telah Berhasil di Sinkronkan', diff --git a/app/Http/Requests/PendudukRequest.php b/app/Http/Requests/PendudukRequest.php index 33c7f72840..ec42af28ec 100644 --- a/app/Http/Requests/PendudukRequest.php +++ b/app/Http/Requests/PendudukRequest.php @@ -31,7 +31,9 @@ namespace App\Http\Requests; +use Illuminate\Contracts\Validation\Validator; use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Http\Exceptions\HttpResponseException; class PendudukRequest extends FormRequest { @@ -54,9 +56,23 @@ public function rules() { return [ // Batch delete validation - 'hapus_penduduk.*.id_pend_desa' => 'present|integer', + 'hapus_penduduk' => 'required|array|min:1', + 'hapus_penduduk.*.id_pend_desa' => 'required|integer', 'hapus_penduduk.*.foto' => 'nullable', - 'hapus_penduduk.*.desa_id' => 'present|string|exists:das_data_desa,desa_id', + 'hapus_penduduk.*.desa_id' => 'required|string|exists:das_data_desa,desa_id', ]; } + + /** + * Endpoint dipanggil OpenSID tanpa header Accept JSON; tanpa ini validasi gagal + * dibalas redirect 302 yang dianggap sukses oleh OpenSID. + */ + protected function failedValidation(Validator $validator) + { + throw new HttpResponseException(response()->json([ + 'status' => 'danger', + 'message' => $validator->errors()->first(), + 'errors' => $validator->errors(), + ], 422)); + } } diff --git a/app/Imports/SinkronPenduduk.php b/app/Imports/SinkronPenduduk.php index 4176983170..ba827138cf 100644 --- a/app/Imports/SinkronPenduduk.php +++ b/app/Imports/SinkronPenduduk.php @@ -35,18 +35,19 @@ use App\Models\Penduduk; use App\Models\TingkatPendidikan; use Exception; -use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Arr; use Illuminate\Support\Collection; -use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; -use Illuminate\Support\Facades\Storage; use Maatwebsite\Excel\Concerns\Importable; use Maatwebsite\Excel\Concerns\ToCollection; use Maatwebsite\Excel\Concerns\WithChunkReading; use Maatwebsite\Excel\Concerns\WithHeadingRow; -class SinkronPenduduk implements ToCollection, WithHeadingRow, WithChunkReading, ShouldQueue +/** + * Sengaja tidak ShouldQueue: impor dijalankan sinkron agar kegagalan (mis. desa tidak terdaftar) + * langsung dibalas HTTP 500 ke OpenSID, bukan muncul di worker setelah respons 200. + */ +class SinkronPenduduk implements ToCollection, WithHeadingRow, WithChunkReading { use Importable; @@ -69,8 +70,7 @@ public function collection(Collection $collection) if (! in_array($value['desa_id'], $kode_desa)) { Log::debug('Desa tidak terdaftar'); - DB::rollBack(); // rollback data yang sudah masuk karena ada data yang bermasalah - Storage::deleteDirectory('temp'); // Hapus folder temp ketika gagal + // Rollback chunk ditangani transaction handler maatwebsite (config excel.transactions) throw new Exception('kode Desa pada baris ke-'.$index + 2 .' tidak terdaftar . kode desa yang bermasalah : '.$value['desa_id']); } diff --git a/app/Jobs/PendudukQueueJob.php b/app/Jobs/PendudukQueueJob.php index b422024612..3430c35527 100644 --- a/app/Jobs/PendudukQueueJob.php +++ b/app/Jobs/PendudukQueueJob.php @@ -69,7 +69,7 @@ public function __construct($request) * * @return void */ - public function failed(\Exception $e) + public function failed(\Throwable $e) { // TODO: Send notification when job failure. report($e); @@ -87,27 +87,27 @@ public function handle() try { // Batch delete penduduk if (! empty($this->request['hapus_penduduk'])) { - $id_pend_desa = $foto = $desa_id = []; + $hapus = collect($this->request['hapus_penduduk']); - foreach ($this->request['hapus_penduduk'] as $item) { - $id_pend_desa[] = $item['id_pend_desa']; - $foto[] = $item['foto'] ?? null; - $desa_id[] = $item['desa_id']; + // Hapus per desa agar id_pend_desa milik desa lain dalam batch yang sama tidak ikut terhapus + foreach ($hapus->groupBy('desa_id') as $desa_id => $items) { + Penduduk::where('desa_id', $desa_id) + ->whereIn('id_pend_desa', $items->pluck('id_pend_desa')) + ->delete(); } - // Hapus data penduduk di database - Penduduk::whereIn('desa_id', $desa_id)->whereIn('id_pend_desa', $id_pend_desa)->delete(); - // Hapus file foto di folder - foreach (array_filter($foto) as $hapusfoto) { + foreach ($hapus->pluck('foto')->filter() as $hapusfoto) { Storage::disk('public')->delete('penduduk/foto/'.'kecil_'.$hapusfoto); } } DB::commit(); - } catch (\Exception $e) { - report($e); + } catch (\Throwable $e) { DB::rollBack(); + + // Lempar ulang agar job tercatat gagal dan failed() terpanggil + throw $e; } } } diff --git a/tests/Feature/Api/SinkronPendudukApiTest.php b/tests/Feature/Api/SinkronPendudukApiTest.php index 3579138f6e..45b23c546d 100644 --- a/tests/Feature/Api/SinkronPendudukApiTest.php +++ b/tests/Feature/Api/SinkronPendudukApiTest.php @@ -35,6 +35,7 @@ use App\Models\User; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\File; +use Illuminate\Support\Facades\Queue; use function Pest\Laravel\withToken; use PhpOffice\PhpSpreadsheet\Spreadsheet; @@ -86,11 +87,11 @@ function barisPenduduk(string $desaId, int $idPendDesa): array /** * Buat zip seperti kiriman OpenSID; tanpa $baris zip hanya berisi berkas teks. */ -function zipPenduduk(?array $baris): UploadedFile +function zipPenduduk(?array $baris, array $tambahan = []): UploadedFile { $dir = storage_path('framework/testing/sinkron-penduduk'); File::ensureDirectoryExists($dir); - $zipPath = $dir.'/penduduk.zip'; + $zipPath = $dir.'/penduduk_'.uniqid().'.zip'; $zip = new ZipArchive(); $zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE); @@ -105,6 +106,10 @@ function zipPenduduk(?array $baris): UploadedFile $zip->addFile($xlsxPath, 'penduduk_opendk.xlsx'); } + foreach ($tambahan as $nama => $isi) { + $zip->addFromString($nama, $isi); + } + $zip->close(); return new UploadedFile($zipPath, 'penduduk.zip', 'application/zip', null, true); @@ -126,6 +131,7 @@ function zipPenduduk(?array $baris): UploadedFile // storedata meninggalkan zip di disk public/temp; bersihkan hanya berkas hasil test ini File::delete(array_diff(File::glob(storage_path('app/public/temp/*')), $this->berkasTempAwal)); File::deleteDirectory(storage_path('framework/testing/sinkron-penduduk')); + File::delete(storage_path('app/public/penduduk/foto/foto_sinkron_test.jpg')); }); describe('POST /api/v1/penduduk/storedata', function () { @@ -170,4 +176,59 @@ function zipPenduduk(?array $baris): UploadedFile ->assertJson(['status' => 'danger']) ->assertJsonValidationErrors('file'); }); + + test('impor tidak bergantung pada queue async', function () { + // Simulasi produksi dengan worker queue: tidak boleh ada job impor yang ditunda + Queue::fake(); + + $berhasil = withToken($this->token)->post('/api/v1/penduduk/storedata', [ + 'file' => zipPenduduk(barisPenduduk($this->desa->desa_id, 10)), + ]); + $gagal = withToken($this->token)->post('/api/v1/penduduk/storedata', [ + 'file' => zipPenduduk(barisPenduduk('99.99.99.9999', 11)), + ]); + + $berhasil->assertOk(); + $gagal->assertStatus(500)->assertJson(['status' => 'danger']); + Queue::assertNothingPushed(); + expect(Penduduk::where('desa_id', $this->desa->desa_id)->where('id_pend_desa', 10)->exists())->toBeTrue(); + }); + + test('menghapus zip dan xlsx temp setelah impor berhasil maupun gagal', function (string $desaId, int $status) { + $response = withToken($this->token)->post('/api/v1/penduduk/storedata', [ + 'file' => zipPenduduk(barisPenduduk($desaId, 12)), + ]); + + $response->assertStatus($status); + expect(array_diff(File::glob(storage_path('app/public/temp/*')), $this->berkasTempAwal))->toBeEmpty() + ->and(File::exists(storage_path('app/public/penduduk/foto/penduduk_opendk.xlsx')))->toBeFalse(); + })->with([ + 'berhasil' => ['33.24.03.2008', 200], + 'desa tidak terdaftar' => ['99.99.99.9999', 500], + ]); + + test('hanya mengekstrak foto di root zip', function () { + $response = withToken($this->token)->post('/api/v1/penduduk/storedata', [ + 'file' => zipPenduduk(barisPenduduk($this->desa->desa_id, 13), [ + 'foto_sinkron_test.jpg' => 'foto', + 'skrip_sinkron_test.php' => ' 'foto', + ]), + ]); + + $response->assertOk(); + expect(File::exists(storage_path('app/public/penduduk/foto/foto_sinkron_test.jpg')))->toBeTrue() + ->and(File::exists(storage_path('app/public/penduduk/foto/skrip_sinkron_test.php')))->toBeFalse() + ->and(File::exists(storage_path('app/public/penduduk/foto/sub')))->toBeFalse(); + }); +}); + +describe('POST /api/v1/penduduk', function () { + test('membalas json 422 bila hapus_penduduk kosong', function () { + $response = withToken($this->token)->post('/api/v1/penduduk', []); + + $response->assertStatus(422) + ->assertJson(['status' => 'danger']) + ->assertJsonValidationErrors('hapus_penduduk'); + }); }); diff --git a/tests/Unit/Jobs/PendudukQueueJobTest.php b/tests/Unit/Jobs/PendudukQueueJobTest.php index 5734ef35a1..ebcb1d254d 100644 --- a/tests/Unit/Jobs/PendudukQueueJobTest.php +++ b/tests/Unit/Jobs/PendudukQueueJobTest.php @@ -59,3 +59,32 @@ expect(Penduduk::find($dihapus->id))->toBeNull() ->and(Penduduk::find($tetap->id))->not->toBeNull(); }); + +test('hanya menghapus pasangan desa dan id_pend_desa dalam batch lintas desa', function () { + $desaA = DataDesa::factory()->create(['desa_id' => '33.24.03.2008']); + $desaB = DataDesa::factory()->create(['desa_id' => '33.24.03.2009']); + + $a1 = Penduduk::factory()->create(['desa_id' => $desaA->desa_id, 'id_pend_desa' => 1]); + $a2 = Penduduk::factory()->create(['desa_id' => $desaA->desa_id, 'id_pend_desa' => 2]); + $b1 = Penduduk::factory()->create(['desa_id' => $desaB->desa_id, 'id_pend_desa' => 1]); + $b2 = Penduduk::factory()->create(['desa_id' => $desaB->desa_id, 'id_pend_desa' => 2]); + + (new PendudukQueueJob(['hapus_penduduk' => [ + ['id_pend_desa' => 1, 'desa_id' => $desaA->desa_id], + ['id_pend_desa' => 2, 'desa_id' => $desaB->desa_id], + ]]))->handle(); + + expect(Penduduk::find($a1->id))->toBeNull() + ->and(Penduduk::find($b2->id))->toBeNull() + ->and(Penduduk::find($a2->id))->not->toBeNull() + ->and(Penduduk::find($b1->id))->not->toBeNull(); +}); + +test('melempar ulang exception agar job tercatat gagal', function () { + // Nilai bersarang ditolak whereIn sehingga query delete gagal + $job = new PendudukQueueJob(['hapus_penduduk' => [ + ['desa_id' => '33.24.03.2008', 'id_pend_desa' => ['bukan', 'skalar']], + ]]); + + expect(fn () => $job->handle())->toThrow(InvalidArgumentException::class); +}); From 13ec5b35159fe5b8a8519941a13381384f92e315 Mon Sep 17 00:00:00 2001 From: Habibie Date: Fri, 30 Oct 2026 13:42:51 +0700 Subject: [PATCH 4/8] sesuaikan respon openapi --- openapi/openapi.yaml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index ea7bd79308..8b0cf23b83 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -181,6 +181,34 @@ paths: message: type: string example: 'Proses sync Data Penduduk OpenSID sedang berjalan' + 422: + description: '' + content: + application/json: + schema: + type: object + example: + status: danger + message: 'The hapus penduduk field is required.' + errors: + hapus_penduduk: + - 'The hapus penduduk field is required.' + properties: + status: + type: string + example: danger + message: + type: string + example: 'The hapus penduduk field is required.' + errors: + type: object + properties: + hapus_penduduk: + type: array + example: + - 'The hapus penduduk field is required.' + items: + type: string tags: - 'OpenSID Integration' requestBody: From 2c1659cbf05c72f59ffea7eda7ce487c0ab9e464 Mon Sep 17 00:00:00 2001 From: Habibie Date: Fri, 30 Oct 2026 13:52:55 +0700 Subject: [PATCH 5/8] ignore claude --- .gitignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index a4e724e526..4694c5626b 100644 --- a/.gitignore +++ b/.gitignore @@ -62,6 +62,8 @@ mcp.json /.opencode /vendor-backup +/public/themes/ + .env.testing nul @@ -74,4 +76,5 @@ graphify-out specs/ .specify/ -AGENTS.md \ No newline at end of file +AGENTS.md +CLAUDE.md \ No newline at end of file From 33982eaf71af5ec067ba05d4bea9cf9c88b88c60 Mon Sep 17 00:00:00 2001 From: Habibie Date: Fri, 30 Oct 2026 14:02:02 +0700 Subject: [PATCH 6/8] sesuaikan test --- tests/Browser/SyncFlowTest.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/Browser/SyncFlowTest.php b/tests/Browser/SyncFlowTest.php index efba72c607..4d63380766 100644 --- a/tests/Browser/SyncFlowTest.php +++ b/tests/Browser/SyncFlowTest.php @@ -118,7 +118,10 @@ function sendSyncRequest(string $endpoint, array $payload, string $token): \Illu })->group('browser', 'e2e', 'sync-flow', 'negative'); test('request with unregistered (revoked) token is rejected with 401', function () { - sendSyncRequest('/api/v1/penduduk', ['hapus_penduduk' => []], $this->registeredToken) + // Payload harus valid: hapus_penduduk kosong ditolak 422 oleh PendudukRequest + $payload = ['hapus_penduduk' => [['id_pend_desa' => 99999, 'desa_id' => '1234567890']]]; + + sendSyncRequest('/api/v1/penduduk', $payload, $this->registeredToken) ->assertStatus(200); $newToken = app(\Tymon\JWTAuth\JWT::class)->fromUser($this->user); @@ -127,11 +130,11 @@ function sendSyncRequest(string $endpoint, array $payload, string $token): \Illu ['value' => $newToken, 'type' => 'textarea'] ); - sendSyncRequest('/api/v1/penduduk', ['hapus_penduduk' => []], $this->registeredToken) + sendSyncRequest('/api/v1/penduduk', $payload, $this->registeredToken) ->assertStatus(401) ->assertJson(['error' => 'Token not registered']); - sendSyncRequest('/api/v1/penduduk', ['hapus_penduduk' => []], $newToken) + sendSyncRequest('/api/v1/penduduk', $payload, $newToken) ->assertStatus(200); })->group('browser', 'e2e', 'sync-flow', 'negative'); From 82cd25b713e15d756f6c9685c84ed1bf89f60766 Mon Sep 17 00:00:00 2001 From: Habibie Date: Wed, 18 Nov 2026 11:37:15 +0700 Subject: [PATCH 7/8] sesuaikan permintaan review --- .../Controllers/Api/PendudukController.php | 10 ++-- .../Requests/Api/SinkronPendudukRequest.php | 18 ++----- app/Http/Requests/PendudukRequest.php | 22 ++------ app/Jobs/PendudukQueueJob.php | 38 ++++++-------- .../RespondsWithJsonValidationErrors.php | 51 +++++++++++++++++++ openapi/openapi.yaml | 8 +-- tests/Browser/SyncFlowTest.php | 9 ++-- tests/Feature/Api/SinkronPendudukApiTest.php | 40 +++++++++++++-- tests/Unit/Jobs/PendudukQueueJobTest.php | 37 ++++++++++++++ 9 files changed, 160 insertions(+), 73 deletions(-) create mode 100644 app/Traits/RespondsWithJsonValidationErrors.php diff --git a/app/Http/Controllers/Api/PendudukController.php b/app/Http/Controllers/Api/PendudukController.php index ad7f2623cd..6a1ac1a951 100644 --- a/app/Http/Controllers/Api/PendudukController.php +++ b/app/Http/Controllers/Api/PendudukController.php @@ -36,6 +36,7 @@ use App\Http\Requests\PendudukRequest; use App\Imports\SinkronPenduduk; use App\Jobs\PendudukQueueJob; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use ZipArchive; @@ -56,8 +57,8 @@ class PendudukController extends Controller * } * @response 422 { * "status": "danger", - * "message": "The hapus penduduk field is required.", - * "errors": {"hapus_penduduk": ["The hapus penduduk field is required."]} + * "message": "The hapus penduduk field must be present.", + * "errors": {"hapus_penduduk": ["The hapus penduduk field must be present."]} * } */ public function store(PendudukRequest $request) @@ -152,8 +153,9 @@ public function storedata(SinkronPendudukRequest $request) $zip->extractTo($extract, $entries); $zip->close(); - // Impor sinkron agar kegagalan langsung dibalas ke OpenSID - (new SinkronPenduduk())->import($extract . $excellName); + // Impor sinkron agar kegagalan langsung dibalas ke OpenSID. Transaksi per chunk dari + // maatwebsite menjadi savepoint di sini, sehingga satu berkas tersimpan utuh atau tidak sama sekali. + DB::transaction(fn () => (new SinkronPenduduk())->import($extract . $excellName)); } catch (\Throwable $e) { Log::error('Penduduk storedata failed', [ 'error' => $e->getMessage(), diff --git a/app/Http/Requests/Api/SinkronPendudukRequest.php b/app/Http/Requests/Api/SinkronPendudukRequest.php index d370dc2aed..8563c9dcb5 100644 --- a/app/Http/Requests/Api/SinkronPendudukRequest.php +++ b/app/Http/Requests/Api/SinkronPendudukRequest.php @@ -32,12 +32,13 @@ namespace App\Http\Requests\Api; use App\Services\FileUploadService; -use Illuminate\Contracts\Validation\Validator; +use App\Traits\RespondsWithJsonValidationErrors; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Http\Exceptions\HttpResponseException; class SinkronPendudukRequest extends FormRequest { + use RespondsWithJsonValidationErrors; + public function authorize(): bool { return true; @@ -51,17 +52,4 @@ public function rules(): array 'file' => 'required|file|mimes:zip' . $maxRule, ]; } - - /** - * Endpoint dipanggil OpenSID tanpa header Accept JSON; tanpa ini validasi gagal - * dibalas redirect 302 yang dianggap sukses oleh OpenSID. - */ - protected function failedValidation(Validator $validator) - { - throw new HttpResponseException(response()->json([ - 'status' => 'danger', - 'message' => $validator->errors()->first(), - 'errors' => $validator->errors(), - ], 422)); - } } diff --git a/app/Http/Requests/PendudukRequest.php b/app/Http/Requests/PendudukRequest.php index ec42af28ec..17f080a687 100644 --- a/app/Http/Requests/PendudukRequest.php +++ b/app/Http/Requests/PendudukRequest.php @@ -31,12 +31,13 @@ namespace App\Http\Requests; -use Illuminate\Contracts\Validation\Validator; +use App\Traits\RespondsWithJsonValidationErrors; use Illuminate\Foundation\Http\FormRequest; -use Illuminate\Http\Exceptions\HttpResponseException; class PendudukRequest extends FormRequest { + use RespondsWithJsonValidationErrors; + /** * Determine if the user is authorized to make this request. * @@ -55,24 +56,11 @@ public function authorize() public function rules() { return [ - // Batch delete validation - 'hapus_penduduk' => 'required|array|min:1', + // OpenSID selalu mengirim kunci ini setelah storedata, berisi [] bila tidak ada yang dihapus + 'hapus_penduduk' => 'present|array', 'hapus_penduduk.*.id_pend_desa' => 'required|integer', 'hapus_penduduk.*.foto' => 'nullable', 'hapus_penduduk.*.desa_id' => 'required|string|exists:das_data_desa,desa_id', ]; } - - /** - * Endpoint dipanggil OpenSID tanpa header Accept JSON; tanpa ini validasi gagal - * dibalas redirect 302 yang dianggap sukses oleh OpenSID. - */ - protected function failedValidation(Validator $validator) - { - throw new HttpResponseException(response()->json([ - 'status' => 'danger', - 'message' => $validator->errors()->first(), - 'errors' => $validator->errors(), - ], 422)); - } } diff --git a/app/Jobs/PendudukQueueJob.php b/app/Jobs/PendudukQueueJob.php index 3430c35527..be68d2b179 100644 --- a/app/Jobs/PendudukQueueJob.php +++ b/app/Jobs/PendudukQueueJob.php @@ -82,32 +82,26 @@ public function failed(\Throwable $e) */ public function handle() { - DB::beginTransaction(); - - try { - // Batch delete penduduk - if (! empty($this->request['hapus_penduduk'])) { - $hapus = collect($this->request['hapus_penduduk']); + if (empty($this->request['hapus_penduduk'])) { + return; + } - // Hapus per desa agar id_pend_desa milik desa lain dalam batch yang sama tidak ikut terhapus - foreach ($hapus->groupBy('desa_id') as $desa_id => $items) { - Penduduk::where('desa_id', $desa_id) - ->whereIn('id_pend_desa', $items->pluck('id_pend_desa')) - ->delete(); - } + $hapus = collect($this->request['hapus_penduduk']); - // Hapus file foto di folder - foreach ($hapus->pluck('foto')->filter() as $hapusfoto) { - Storage::disk('public')->delete('penduduk/foto/'.'kecil_'.$hapusfoto); - } + // Exception dilempar ulang oleh DB::transaction agar job tercatat gagal dan failed() terpanggil + DB::transaction(function () use ($hapus) { + // Hapus per desa agar id_pend_desa milik desa lain dalam batch yang sama tidak ikut terhapus + foreach ($hapus->groupBy('desa_id') as $desa_id => $items) { + Penduduk::where('desa_id', $desa_id) + ->whereIn('id_pend_desa', $items->pluck('id_pend_desa')) + ->delete(); } + }); - DB::commit(); - } catch (\Throwable $e) { - DB::rollBack(); - - // Lempar ulang agar job tercatat gagal dan failed() terpanggil - throw $e; + // Foto dihapus setelah commit agar tidak hilang bila penghapusan data dibatalkan. + // basename() mencegah path traversal dari nilai foto kiriman klien. + foreach ($hapus->pluck('foto')->filter() as $hapusfoto) { + Storage::disk('public')->delete('penduduk/foto/kecil_'.basename((string) $hapusfoto)); } } } diff --git a/app/Traits/RespondsWithJsonValidationErrors.php b/app/Traits/RespondsWithJsonValidationErrors.php new file mode 100644 index 0000000000..b20597a3d8 --- /dev/null +++ b/app/Traits/RespondsWithJsonValidationErrors.php @@ -0,0 +1,51 @@ +json([ + 'status' => 'danger', + 'message' => $validator->errors()->first(), + 'errors' => $validator->errors(), + ], 422)); + } +} diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml index 8b0cf23b83..e27a5fef65 100644 --- a/openapi/openapi.yaml +++ b/openapi/openapi.yaml @@ -189,24 +189,24 @@ paths: type: object example: status: danger - message: 'The hapus penduduk field is required.' + message: 'The hapus penduduk field must be present.' errors: hapus_penduduk: - - 'The hapus penduduk field is required.' + - 'The hapus penduduk field must be present.' properties: status: type: string example: danger message: type: string - example: 'The hapus penduduk field is required.' + example: 'The hapus penduduk field must be present.' errors: type: object properties: hapus_penduduk: type: array example: - - 'The hapus penduduk field is required.' + - 'The hapus penduduk field must be present.' items: type: string tags: diff --git a/tests/Browser/SyncFlowTest.php b/tests/Browser/SyncFlowTest.php index 4d63380766..efba72c607 100644 --- a/tests/Browser/SyncFlowTest.php +++ b/tests/Browser/SyncFlowTest.php @@ -118,10 +118,7 @@ function sendSyncRequest(string $endpoint, array $payload, string $token): \Illu })->group('browser', 'e2e', 'sync-flow', 'negative'); test('request with unregistered (revoked) token is rejected with 401', function () { - // Payload harus valid: hapus_penduduk kosong ditolak 422 oleh PendudukRequest - $payload = ['hapus_penduduk' => [['id_pend_desa' => 99999, 'desa_id' => '1234567890']]]; - - sendSyncRequest('/api/v1/penduduk', $payload, $this->registeredToken) + sendSyncRequest('/api/v1/penduduk', ['hapus_penduduk' => []], $this->registeredToken) ->assertStatus(200); $newToken = app(\Tymon\JWTAuth\JWT::class)->fromUser($this->user); @@ -130,11 +127,11 @@ function sendSyncRequest(string $endpoint, array $payload, string $token): \Illu ['value' => $newToken, 'type' => 'textarea'] ); - sendSyncRequest('/api/v1/penduduk', $payload, $this->registeredToken) + sendSyncRequest('/api/v1/penduduk', ['hapus_penduduk' => []], $this->registeredToken) ->assertStatus(401) ->assertJson(['error' => 'Token not registered']); - sendSyncRequest('/api/v1/penduduk', $payload, $newToken) + sendSyncRequest('/api/v1/penduduk', ['hapus_penduduk' => []], $newToken) ->assertStatus(200); })->group('browser', 'e2e', 'sync-flow', 'negative'); diff --git a/tests/Feature/Api/SinkronPendudukApiTest.php b/tests/Feature/Api/SinkronPendudukApiTest.php index 45b23c546d..f762206e37 100644 --- a/tests/Feature/Api/SinkronPendudukApiTest.php +++ b/tests/Feature/Api/SinkronPendudukApiTest.php @@ -29,6 +29,7 @@ * @link https://github.com/OpenSID/opendk */ +use App\Jobs\PendudukQueueJob; use App\Models\DataDesa; use App\Models\Penduduk; use App\Models\SettingAplikasi; @@ -85,7 +86,8 @@ function barisPenduduk(string $desaId, int $idPendDesa): array } /** - * Buat zip seperti kiriman OpenSID; tanpa $baris zip hanya berisi berkas teks. + * Buat zip seperti kiriman OpenSID; $baris berupa satu baris atau daftar baris, + * tanpa $baris zip hanya berisi berkas teks. */ function zipPenduduk(?array $baris, array $tambahan = []): UploadedFile { @@ -100,7 +102,8 @@ function zipPenduduk(?array $baris, array $tambahan = []): UploadedFile $zip->addFromString('bukan_data.txt', 'kosong'); } else { $spreadsheet = new Spreadsheet(); - $spreadsheet->getActiveSheet()->fromArray([KOLOM_XLSX_PENDUDUK, array_values($baris)]); + $daftarBaris = array_is_list($baris) ? $baris : [$baris]; + $spreadsheet->getActiveSheet()->fromArray([KOLOM_XLSX_PENDUDUK, ...array_map('array_values', $daftarBaris)]); $xlsxPath = $dir.'/penduduk_opendk.xlsx'; (new Xlsx($spreadsheet))->save($xlsxPath); $zip->addFile($xlsxPath, 'penduduk_opendk.xlsx'); @@ -168,6 +171,19 @@ function zipPenduduk(?array $baris, array $tambahan = []): UploadedFile $response->assertStatus(500)->assertJson(['status' => 'danger']); }); + test('tidak menyimpan baris apa pun bila impor gagal di chunk berikutnya', function () { + // chunkSize 1000: baris 1-1000 valid (chunk pertama), baris 1001 desanya tidak terdaftar + $daftarBaris = array_map(fn ($id) => barisPenduduk($this->desa->desa_id, $id), range(1, 1000)); + $daftarBaris[] = barisPenduduk('99.99.99.9999', 1001); + + $response = withToken($this->token)->post('/api/v1/penduduk/storedata', [ + 'file' => zipPenduduk($daftarBaris), + ]); + + $response->assertStatus(500)->assertJson(['status' => 'danger']); + expect(Penduduk::where('desa_id', $this->desa->desa_id)->count())->toBe(0); + }); + test('membalas json 422 tanpa redirect bila file tidak dikirim', function () { // OpenSID tidak mengirim header Accept: application/json $response = withToken($this->token)->post('/api/v1/penduduk/storedata', []); @@ -224,11 +240,25 @@ function zipPenduduk(?array $baris, array $tambahan = []): UploadedFile }); describe('POST /api/v1/penduduk', function () { - test('membalas json 422 bila hapus_penduduk kosong', function () { - $response = withToken($this->token)->post('/api/v1/penduduk', []); + test('membalas sukses bila hapus_penduduk berupa array kosong', function () { + // Payload yang selalu dikirim OpenSID setelah storedata bila tidak ada penduduk yang dihapus + Queue::fake(); + + $response = withToken($this->token)->postJson('/api/v1/penduduk', ['hapus_penduduk' => []]); + + $response->assertOk()->assertJson(['status' => 'success']); + Queue::assertPushed(PendudukQueueJob::class); + }); + + test('membalas json 422 bila hapus_penduduk tidak dikirim atau bukan array', function (array $payload) { + $response = withToken($this->token)->postJson('/api/v1/penduduk', $payload); $response->assertStatus(422) ->assertJson(['status' => 'danger']) ->assertJsonValidationErrors('hapus_penduduk'); - }); + })->with([ + 'kunci tidak ada' => [[]], + 'string' => [['hapus_penduduk' => 'semua']], + 'null' => [['hapus_penduduk' => null]], + ]); }); diff --git a/tests/Unit/Jobs/PendudukQueueJobTest.php b/tests/Unit/Jobs/PendudukQueueJobTest.php index ebcb1d254d..da506a5da7 100644 --- a/tests/Unit/Jobs/PendudukQueueJobTest.php +++ b/tests/Unit/Jobs/PendudukQueueJobTest.php @@ -33,6 +33,7 @@ use App\Models\DataDesa; use App\Models\Penduduk; use Illuminate\Support\Facades\Exceptions; +use Illuminate\Support\Facades\Storage; beforeEach(function () { Exceptions::fake(); @@ -88,3 +89,39 @@ expect(fn () => $job->handle())->toThrow(InvalidArgumentException::class); }); + +test('menghapus foto kecil penduduk setelah data terhapus', function () { + Storage::fake('public'); + Storage::disk('public')->put('penduduk/foto/kecil_foto_a.jpg', 'foto'); + $desa = DataDesa::factory()->create(['desa_id' => '33.24.03.2008']); + Penduduk::factory()->create(['desa_id' => $desa->desa_id, 'id_pend_desa' => 5]); + + (new PendudukQueueJob(['hapus_penduduk' => [ + ['id_pend_desa' => 5, 'desa_id' => $desa->desa_id, 'foto' => 'foto_a.jpg'], + ]]))->handle(); + + Storage::disk('public')->assertMissing('penduduk/foto/kecil_foto_a.jpg'); +}); + +test('tidak menghapus foto bila penghapusan data gagal', function () { + Storage::fake('public'); + Storage::disk('public')->put('penduduk/foto/kecil_foto_a.jpg', 'foto'); + + $job = new PendudukQueueJob(['hapus_penduduk' => [ + ['desa_id' => '33.24.03.2008', 'id_pend_desa' => ['bukan', 'skalar'], 'foto' => 'foto_a.jpg'], + ]]); + + expect(fn () => $job->handle())->toThrow(InvalidArgumentException::class); + Storage::disk('public')->assertExists('penduduk/foto/kecil_foto_a.jpg'); +}); + +test('nama foto dengan path traversal tidak menghapus berkas di luar folder foto', function () { + Storage::fake('public'); + Storage::disk('public')->put('penduduk/sasaran.txt', 'jangan dihapus'); + + (new PendudukQueueJob(['hapus_penduduk' => [ + ['id_pend_desa' => 6, 'desa_id' => '33.24.03.2008', 'foto' => '../../../sasaran.txt'], + ]]))->handle(); + + Storage::disk('public')->assertExists('penduduk/sasaran.txt'); +}); From cb8b6b955ed2c0b5d3c995d67edc16a0d8df4a0f Mon Sep 17 00:00:00 2001 From: Habibie Date: Wed, 18 Nov 2026 14:52:49 +0700 Subject: [PATCH 8/8] update ignore --- .gitignore | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 4694c5626b..a4e724e526 100644 --- a/.gitignore +++ b/.gitignore @@ -62,8 +62,6 @@ mcp.json /.opencode /vendor-backup -/public/themes/ - .env.testing nul @@ -76,5 +74,4 @@ graphify-out specs/ .specify/ -AGENTS.md -CLAUDE.md \ No newline at end of file +AGENTS.md \ No newline at end of file