Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 65 additions & 33 deletions app/Http/Controllers/Api/PendudukController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
{
Expand All @@ -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
Expand All @@ -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',
]);
}
Expand Down
55 changes: 55 additions & 0 deletions app/Http/Requests/Api/SinkronPendudukRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

/*
* File ini bagian dari:
*
* OpenDK
*
* Aplikasi dan source code ini dirilis berdasarkan lisensi GPL V3
*
* Hak Cipta 2017 - 2024 Perkumpulan Desa Digital Terbuka (https://opendesa.id)
*
* Dengan ini diberikan izin, secara gratis, kepada siapa pun yang mendapatkan salinan
* dari perangkat lunak ini dan file dokumentasi terkait ("Aplikasi Ini"), untuk diperlakukan
* tanpa batasan, termasuk hak untuk menggunakan, menyalin, mengubah dan/atau mendistribusikan,
* asal tunduk pada syarat berikut:
*
* Pemberitahuan hak cipta di atas dan pemberitahuan izin ini harus disertakan dalam
* setiap salinan atau bagian penting Aplikasi Ini. Barang siapa yang menghapus atau menghilangkan
* pemberitahuan ini melanggar ketentuan lisensi Aplikasi Ini.
*
* PERANGKAT LUNAK INI DISEDIAKAN "SEBAGAIMANA ADANYA", TANPA JAMINAN APA PUN, BAIK TERSURAT MAUPUN
* TERSIRAT. PENULIS ATAU PEMEGANG HAK CIPTA SAMA SEKALI TIDAK BERTANGGUNG JAWAB ATAS KLAIM, KERUSAKAN ATAU
* KEWAJIBAN APAPUN ATAS PENGGUNAAN ATAU LAINNYA TERKAIT APLIKASI INI.
*
* @package OpenDK
* @author Tim Pengembang OpenDesa
* @copyright Hak Cipta 2017 - 2024 Perkumpulan Desa Digital Terbuka (https://opendesa.id)
* @license http://www.gnu.org/licenses/gpl.html GPL V3
* @link https://github.com/OpenSID/opendk
*/

namespace App\Http\Requests\Api;

use App\Services\FileUploadService;
use App\Traits\RespondsWithJsonValidationErrors;
use Illuminate\Foundation\Http\FormRequest;

class SinkronPendudukRequest extends FormRequest
{
use RespondsWithJsonValidationErrors;

public function authorize(): bool
{
return true;
}

public function rules(): array
{
$maxRule = FileUploadService::isLimitEnabled() ? '|max:5120' : '';

return [
'file' => 'required|file|mimes:zip' . $maxRule,
];
}
}
10 changes: 7 additions & 3 deletions app/Http/Requests/PendudukRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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',
];
}
}
12 changes: 6 additions & 6 deletions app/Imports/SinkronPenduduk.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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']);
}

Expand Down
39 changes: 18 additions & 21 deletions app/Jobs/PendudukQueueJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ class PendudukQueueJob implements ShouldQueue
* Create a new job instance.
*
* @param array $request
*
* @return void
*/
public function __construct($request)
Expand All @@ -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);
Expand All @@ -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));
}
}
}
51 changes: 51 additions & 0 deletions app/Traits/RespondsWithJsonValidationErrors.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?php

/*
* File ini bagian dari:
*
* OpenDK
*
* Aplikasi dan source code ini dirilis berdasarkan lisensi GPL V3
*
* Hak Cipta 2017 - 2024 Perkumpulan Desa Digital Terbuka (https://opendesa.id)
*
* Dengan ini diberikan izin, secara gratis, kepada siapa pun yang mendapatkan salinan
* dari perangkat lunak ini dan file dokumentasi terkait ("Aplikasi Ini"), untuk diperlakukan
* tanpa batasan, termasuk hak untuk menggunakan, menyalin, mengubah dan/atau mendistribusikan,
* asal tunduk pada syarat berikut:
*
* Pemberitahuan hak cipta di atas dan pemberitahuan izin ini harus disertakan dalam
* setiap salinan atau bagian penting Aplikasi Ini. Barang siapa yang menghapus atau menghilangkan
* pemberitahuan ini melanggar ketentuan lisensi Aplikasi Ini.
*
* PERANGKAT LUNAK INI DISEDIAKAN "SEBAGAIMANA ADANYA", TANPA JAMINAN APA PUN, BAIK TERSURAT MAUPUN
* TERSIRAT. PENULIS ATAU PEMEGANG HAK CIPTA SAMA SEKALI TIDAK BERTANGGUNG JAWAB ATAS KLAIM, KERUSAKAN ATAU
* KEWAJIBAN APAPUN ATAS PENGGUNAAN ATAU LAINNYA TERKAIT APLIKASI INI.
*
* @package OpenDK
* @author Tim Pengembang OpenDesa
* @copyright Hak Cipta 2017 - 2024 Perkumpulan Desa Digital Terbuka (https://opendesa.id)
* @license http://www.gnu.org/licenses/gpl.html GPL V3
* @link https://github.com/OpenSID/opendk
*/

namespace App\Traits;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

/**
* Untuk FormRequest endpoint sinkronisasi OpenSID: galat validasi selalu dibalas JSON 422
* dengan field `status` seperti respons API lain, apa pun header Accept dari klien.
*/
trait RespondsWithJsonValidationErrors
{
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json([
'status' => 'danger',
'message' => $validator->errors()->first(),
'errors' => $validator->errors(),
], 422));
}
}
Loading
Loading