diff --git a/app/Http/Controllers/Api/PendudukController.php b/app/Http/Controllers/Api/PendudukController.php index 84264a2558..6a1ac1a951 100644 --- a/app/Http/Controllers/Api/PendudukController.php +++ b/app/Http/Controllers/Api/PendudukController.php @@ -32,13 +32,13 @@ 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\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; -use Illuminate\Support\Str; use ZipArchive; class PendudukController extends Controller @@ -50,10 +50,16 @@ 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" * } + * @response 422 { + * "status": "danger", + * "message": "The hapus penduduk field must be present.", + * "errors": {"hapus_penduduk": ["The hapus penduduk field must be present."]} + * } */ public function store(PendudukRequest $request) { @@ -80,15 +86,25 @@ 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', - ]); + $zipPath = null; + $excellName = ''; try { // Upload file zip temporary using FileUploadService for security @@ -100,52 +116,68 @@ public function storedata(Request $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 + // Upload file securely to temp directory (disk public) + $zipPath = $fileUploadService->uploadSecure($file, 'temp', $allowedMimes, 5120); // 5MB max - // 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(Storage::disk('public')->path($zipPath)) !== true) { + throw new \RuntimeException('Gagal membuka file zip.'); + } - for ($i = 0; $i < $zip->numFiles; $i++) { + // 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); - $filename = $zip->getNameIndex($i); + if ($filename !== basename($filename)) { + continue; + } + + $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); - if (pathinfo($filename, PATHINFO_EXTENSION) === 'xlsx') { - $excellName = $filename; - break; - } + if ($extension === 'xlsx' && $excellName === '') { + $excellName = $filename; + $entries[] = $filename; + } elseif (in_array($extension, ['jpg', 'jpeg', 'png'], true)) { + $entries[] = $filename; } + } - $zip->extractTo($extract); + if ($excellName === '') { $zip->close(); + + throw new \RuntimeException('File xlsx tidak ditemukan di dalam zip.'); } + $zip->extractTo($extract, $entries); + $zip->close(); - // Proses impor excell - (new SinkronPenduduk()) - ->queue($extract . $excellName); - } catch (\Exception $e) { + // 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(), ]); - 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); + } 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/Api/SinkronPendudukRequest.php b/app/Http/Requests/Api/SinkronPendudukRequest.php new file mode 100644 index 0000000000..8563c9dcb5 --- /dev/null +++ b/app/Http/Requests/Api/SinkronPendudukRequest.php @@ -0,0 +1,55 @@ + 'required|file|mimes:zip' . $maxRule, + ]; + } +} diff --git a/app/Http/Requests/PendudukRequest.php b/app/Http/Requests/PendudukRequest.php index 33c7f72840..17f080a687 100644 --- a/app/Http/Requests/PendudukRequest.php +++ b/app/Http/Requests/PendudukRequest.php @@ -31,10 +31,13 @@ namespace App\Http\Requests; +use App\Traits\RespondsWithJsonValidationErrors; use Illuminate\Foundation\Http\FormRequest; class PendudukRequest extends FormRequest { + use RespondsWithJsonValidationErrors; + /** * Determine if the user is authorized to make this request. * @@ -53,10 +56,11 @@ public function authorize() public function rules() { return [ - // Batch delete validation - 'hapus_penduduk.*.id_pend_desa' => 'present|integer', + // 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' => 'present|string|exists:das_data_desa,desa_id', + 'hapus_penduduk.*.desa_id' => 'required|string|exists:das_data_desa,desa_id', ]; } } 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 89c888342e..be68d2b179 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) @@ -68,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); @@ -81,30 +82,26 @@ public function failed(\Exception $e) */ public function handle() { - DB::beginTransaction(); - - try { - // Batch delete penduduk - if (isset($this->request['hapus_penduduk'])) { - foreach ($this->request['hapus_penduduk'] as $item) { - $id_pend_desa[] = $item['id_pend_desa']; - $foto[] = $item['foto']; - $desa_id[] = $item['desa_id']; - } + if (empty($this->request['hapus_penduduk'])) { + return; + } - // Hapus data penduduk di database - Penduduk::whereIn('desa_id', $desa_id)->whereIn('id_pend_desa', $id_pend_desa)->delete(); + $hapus = collect($this->request['hapus_penduduk']); - // Hapus file foto di folder - foreach ($foto 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 (\Exception $e) { - report($e); - DB::rollBack(); + // 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 e4e3ebbfd2..e27a5fef65 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 must be present.' + errors: + hapus_penduduk: + - 'The hapus penduduk field must be present.' + properties: + status: + type: string + example: danger + message: + type: string + example: 'The hapus penduduk field must be present.' + errors: + type: object + properties: + hapus_penduduk: + type: array + example: + - 'The hapus penduduk field must be present.' + items: + type: string tags: - 'OpenSID Integration' requestBody: @@ -218,11 +246,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..f762206e37 --- /dev/null +++ b/tests/Feature/Api/SinkronPendudukApiTest.php @@ -0,0 +1,264 @@ + $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; $baris berupa satu baris atau daftar baris, + * tanpa $baris zip hanya berisi berkas teks. + */ +function zipPenduduk(?array $baris, array $tambahan = []): UploadedFile +{ + $dir = storage_path('framework/testing/sinkron-penduduk'); + File::ensureDirectoryExists($dir); + $zipPath = $dir.'/penduduk_'.uniqid().'.zip'; + + $zip = new ZipArchive(); + $zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE); + + if ($baris === null) { + $zip->addFromString('bukan_data.txt', 'kosong'); + } else { + $spreadsheet = new Spreadsheet(); + $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'); + } + + foreach ($tambahan as $nama => $isi) { + $zip->addFromString($nama, $isi); + } + + $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')); + File::delete(storage_path('app/public/penduduk/foto/foto_sinkron_test.jpg')); +}); + +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('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', []); + + $response->assertStatus(422) + ->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 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 new file mode 100644 index 0000000000..da506a5da7 --- /dev/null +++ b/tests/Unit/Jobs/PendudukQueueJobTest.php @@ -0,0 +1,127 @@ + []]))->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(); +}); + +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); +}); + +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'); +});