Compare commits

20 Commits

Author SHA1 Message Date
Daeng Deni Mardaeni
f402c0831a 🚀 feat(preview-laporan): Optimasi tampilan gambar dengan resize otomatis dan peningkatan DPI PDF
Perubahan pada PreviewLaporanService:
- Menambahkan set_option('dpi', '96') untuk meningkatkan kualitas render PDF

Perubahan pada foto-jaminan blade template:
- Implementasi helper function `resize_image()` untuk resize gambar jaminan
- Mengubah gambar asli menjadi versi yang sudah di-resize (800x400px, quality 25%)
- Mengoptimalkan ukuran file gambar untuk preview laporan
- Menjaga aspect ratio gambar tetap proporsional
- Meningkatkan performa loading gambar di PDF preview

Optimasi ini bertujuan untuk:
- Mengurangi ukuran file PDF hasil preview
- Meningkatkan kecepatan loading gambar
- Menjaga kualitas visual yang tetap baik
- Mengurangi memory usage saat generate PDF
2025-12-24 11:15:39 +07:00
Daeng Deni Mardaeni
ceca0aa5e8 feat(helper): Tambahkan helper function resize_image untuk integrasi ImageResizeService
Menambahkan helper function `resize_image()` di app/Helpers/Lpj.php untuk:
- Menyediakan interface yang lebih mudah digunakan untuk resize gambar
- Menerima parameter: path gambar, width, height (opsional), dan quality
- Menggunakan ImageResizeService untuk proses resize yang sudah ada
- Memudahkan developer untuk resize gambar secara on-the-fly
- Mengembalikan path gambar yang sudah di-resize

Function ini mengabstraksi ImageResizeService agar bisa dipanggil dengan
lebih sederhana tanpa perlu dependency injection manual.
2025-12-24 11:14:35 +07:00
Daeng Deni Mardaeni
43361f81e7 🎨 feat(ImageResizeService): Tambahkan service resize gambar dengan fitur kualitas dan aspect ratio
Menambahkan ImageResizeService untuk mengelola proses resize gambar dengan fitur:
- Resize gambar dengan menjaga aspect ratio atau force resize
- Support resize berdasarkan width saja, height saja, atau keduanya
- Kustomisasi kualitas kompresi gambar (default 80%)
- Penyimpanan hasil resize di folder terpisah ('resized')
- Nama file yang deskriptif dengan format: {filename}_{width}x{height}_{quality}.{extension}
- Error handling dengan fallback ke gambar original
- Logging untuk monitoring proses resize

Service ini menggunakan Intervention Image Laravel untuk manipulasi gambar dan
Laravel Storage untuk manajemen file. Cocok untuk optimasi gambar di aplikasi
LPJ module.
2025-12-24 11:13:28 +07:00
Daeng Deni Mardaeni
58b53a0284 feat(daftar-pustaka): 💄 Tingkatkan Tampilan Tombol dan Kartu
Perubahan ini mencakup beberapa penyesuaian pada tata letak dan gaya untuk meningkatkan pengalaman pengguna di halaman daftar pustaka.

- **Tombol Lebar Penuh**: Tombol "Hapus" dan "Edit" sekarang memiliki lebar penuh (`w-full`) untuk konsistensi dan kemudahan penggunaan.
- **Tata Letak Tombol**: Tombol-tombol diatur dalam tata letak kolom (`flex-col`) dengan jarak (`gap-2`) untuk tampilan yang lebih rapi.
- **Posisi Tombol**: Tombol-tombol sekarang selalu berada di bagian bawah kartu, terlepas dari panjang konten, dengan menggunakan `mt-auto`.
- **Struktur Kartu**: Struktur kartu diubah menjadi `flex flex-col` untuk memungkinkan penataan posisi tombol yang lebih baik.
2025-12-18 17:48:57 +07:00
Daeng Deni Mardaeni
bb0da7626b fix(model): 🐛 Perbaiki Foreign Key pada Relasi Daftar Pustaka
Memperbaiki relasi `hasMany` pada model `CategoryDaftarPustaka` untuk mereferensikan `DaftarPustaka` dengan benar.

- **Perbaikan Relasi**: Mengubah relasi `daftarPustaka` untuk secara eksplisit mendefinisikan foreign key sebagai `category_id`.
- **Pencegahan Error**: Perubahan ini mengatasi error `SQLSTATE[42S22]: Column not found` yang terjadi karena Eloquent mencoba mencari kolom `category_daftar_pustaka_id` yang tidak ada.
- **Konsistensi Skema**: Memastikan bahwa relasi model sekarang sesuai dengan skema database yang sebenarnya, di mana tabel `daftar_pustaka` menggunakan `category_id` untuk relasi ke kategori.
2025-12-18 17:46:24 +07:00
Daeng Deni Mardaeni
8a6ab059f5 feat(controller): Tambahkan Error Handling pada Pemuatan Kategori
Menambahkan mekanisme penanganan error yang tangguh pada metode `index` di `DaftarPustakaController` untuk memastikan halaman tetap berfungsi meskipun terjadi kegagalan pada query database.

- **Implementasi Try-Catch**: Membungkus query `CategoryDaftarPustaka::withCount('daftarPustaka')` di dalam blok `try-catch`.
- **Pencatatan Error**: Jika terjadi `Exception` (misalnya, tabel relasi belum ada atau terjadi error SQL), pesan error akan dicatat menggunakan `Log::warning()` untuk kemudahan debugging.
- **Mekanisme Fallback**: Apabila query `withCount` gagal, controller akan menjalankan query alternatif `CategoryDaftarPustaka::get()` yang mengambil data kategori tanpa jumlah relasi. Ini memastikan bahwa halaman daftar pustaka tetap dapat ditampilkan kepada pengguna.
- **Penambahan Dependensi**: Menambahkan `use Exception;` dan `use Illuminate\Support\Facades\Log;` untuk mendukung fungsionalitas ini.
2025-12-18 17:46:13 +07:00
Daeng Deni Mardaeni
6cf4432642 📝 fix(linguistic): perbaiki label teks dan fallback variable
- Tambahkan fallback variable alamat untuk mencegah undefined error
- Gunakan null coalescing sebagai default value yang aman
- Perbaiki label tampilan dari "Jalan Lingkungan" menjadi "Jalan Utama"
- Tingkatkan kejelasan dan konsistensi istilah pada UI
- Pertahankan key data 'jalan_linkungan' untuk backward compatibility
- Tidak ada perubahan struktur data atau logic backend
- Perubahan terbatas pada layer tampilan (UI)
- Meningkatkan UX dan stabilitas pada edge case
2025-12-15 16:33:30 +07:00
Daeng Deni Mardaeni
7c5202021f 🐛 fix(currency): perbaiki thousand separator pada input currency dinamis
- Gunakan nilai mentah dari DB pada template JS (hapus number_format di JS)
- Inisialisasi IMask untuk nilai existing saat loadSavedNPW()
- Terapkan IMask pada class .currency dan .currency-format
- Tambahkan event blur untuk menjaga format saat edit ulang
- Perbaiki parsing nilai luas dengan parseFloat + regex cleaning
- Pastikan perhitungan total NPW tetap akurat
- Hapus fungsi formatCurrencyValue yang tidak terpakai
- Pastikan thousand separator muncul saat load dan input baru
2025-12-15 16:29:31 +07:00
Daeng Deni Mardaeni
e8a735e977 feat(lpj-print-out): perbaiki format currency dan parsing data NPW
- Standarisasi format currency menggunakan number_format() di seluruh print-out
- Hapus penggunaan formatRupiah() yang tidak konsisten
- Bersihkan data currency dengan str_replace() sebelum diproses
- Tangani karakter Rp, titik, dan koma agar parsing aman
- Perbaiki perhitungan total NPW dari data numerik murni
- Tambahkan null safety dengan default nilai 0
- Cegah error parsing akibat string currency
- Pastikan tampilan angka konsisten (contoh: 1.500.000)
2025-12-15 11:13:37 +07:00
Daeng Deni Mardaeni
1c5b48ff1b feat(lpj-form-penilai): gunakan IMask untuk formatting currency dinamis
- Ganti formatter manual formatCurrency dengan library IMask pada input class currency
- Terapkan thousand separator titik (.) dan radix koma (,) sesuai format lokal
- Gunakan mask Number tanpa desimal (scale 0) untuk nilai harga
- Pindahkan trigger event dari input ke change untuk efisiensi performa
- IMask otomatis menolak karakter non-numerik dan menormalkan nilai
- Thousand separator muncul otomatis saat input nilai besar
- Format angka menjadi konsisten dan standar di seluruh form penilaian
- Kurangi potensi error input akibat formatting manual
2025-12-15 11:08:42 +07:00
Daeng Deni Mardaeni
6378ba0f98 ⚙️ feat(LpjServiceProvider): Konfigurasi scheduling otomatis untuk cleanup inspeksi
Menambahkan registrasi commands dan scheduling untuk cleanup data inspeksi dengan konfigurasi multi-server dan logging

- Register 3 command cleanup: CleanupInspeksiDataCommand, CleanupSingleInspeksiCommand, dan CleanupInspeksiStatusCommand
- Daily cleanup scheduling setiap jam 02:00 dengan opsi --force dan withoutOverlapping()
- Weekly backup cleanup setiap minggu pukul 03:00 pada hari minggu
- Multi-server support dengan onOneServer() untuk environment clustered
- Background execution dengan runInBackground() untuk performa optimal
- Dedicated logging ke storage/logs/cleanup-inspeksi.log dan cleanup-inspeksi-weekly.log
- Service binding untuk BankDataService dengan dependency injection
- Modular structure dengan namespace dan module path yang terorganisir
2025-12-09 15:42:43 +07:00
Daeng Deni Mardaeni
2c8136dcf3 🔧 feat(SurveyorController): Tambahkan cleanup inspeksi otomatis pada method show
Menambahkan fungsi cleanupInspeksiData() untuk membersihkan data inspeksi lama secara otomatis saat menampilkan detail permohonan

- Method cleanupInspeksiData() dipanggil otomatis di method show() line 112
- Implementasi cleanup berbasis created_by dengan grouping data
- Soft delete data inspeksi tanpa dokument_id jika ada data lengkap dengan dokument_id
- Transaction handling dengan DB::beginTransaction() dan DB::rollback() untuk konsistensi data
- Comprehensive logging untuk audit trail setiap operasi cleanup
- Error handling individual per data dengan continue pada exception
- Validasi mutual exclusion antara data dengan dan tanpa dokument_id
- Integrasi dengan Auth::id() untuk tracking user yang melakukan akses
2025-12-09 15:40:33 +07:00
Daeng Deni Mardaeni
3315e1d4b6 📚 docs(Console README): Tambahkan dokumentasi lengkap untuk console commands cleanup inspeksi
Membuat dokumentasi komprehensif untuk semua command cleanup dengan contoh penggunaan dan troubleshooting guide

- Dokumentasi untuk 3 command utama: lpj:cleanup-inspeksi, lpj:cleanup-single-inspeksi, dan lpj:cleanup-inspeksi-status
- Usage examples untuk setiap command dengan berbagai opsi (--sync, --force, --dry-run, --detailed)
- Penjelasan alur kerja cleanup (identifikasi → proses → logging → transaction)
- Informasi scheduling otomatis (setiap hari jam 2 pagi dan mingguan)
- Lokasi log files untuk monitoring dan troubleshooting
- Troubleshooting guide untuk command tidak muncul, data tidak ter-cleanup, dan performance issues
- Best practices untuk data besar dengan mode queue vs sync
2025-12-09 15:38:35 +07:00
Daeng Deni Mardaeni
37fb5c90d5 🧹 feat(CleanupInspeksiDataCommand): Implementasi command utama untuk batch cleanup data inspeksi
Membuat artisan command utama untuk cleanup data inspeksi secara batch dengan fitur preview, filter, dan progress tracking

- Command signature: `lpj:cleanup-inspeksi` dengan opsi --permohonan-id, --sync, --dry-run, dan --force
- Method getCleanupData() untuk query data yang memenuhi kriteria cleanup menggunakan DB::table
- Method displayPreview() untuk menampilkan tabel preview data yang akan di-cleanup
- Method runCleanup() dengan progress bar untuk tracking progress batch processing
- Validasi mutual exclusion antara --dry-run dan --sync untuk mencegah konflik
- Konfirmasi interaktif sebelum proses (dapat di-skip dengan --force)
- Support mode sync (direct execution) dan async (queue dispatch)
- Error handling per permohonan dengan continue pada exception
- Comprehensive logging dengan context options dan error details
- Hitungan total data yang dihapus dan jumlah error untuk reporting
2025-12-09 15:38:28 +07:00
Daeng Deni Mardaeni
ff994a7c95 🧹 feat(CleanupSingleInspeksiCommand): Tambahkan command untuk cleanup inspeksi per permohonan
Membuat artisan command untuk cleanup data inspeksi secara spesifik untuk 1 permohonan dan user tertentu dengan opsi sync/async

- Command signature: `lpj:cleanup-single-inspeksi` dengan required arguments permohonan-id dan created-by
- Opsi --sync untuk eksekusi synchronous dan --force untuk skip konfirmasi
- Validasi input permohonanId dan createdBy harus angka positif
- Integrasi dengan InspeksiCleanupService untuk cleanupSync() dan cleanupAsync()
- Konfirmasi interaktif sebelum proses (dapat di-skip dengan --force)
- Comprehensive logging dengan context permohonan_id dan created_by
- Error handling dengan try-catch dan return Command::SUCCESS/FAILURE
- Informasi mode eksekusi (Synchronous vs Queue) ditampilkan ke user
- Pesan sukses yang jelas untuk monitoring progress di log
2025-12-09 15:35:52 +07:00
Daeng Deni Mardaeni
a2275758b1 🔍 feat(CleanupInspeksiStatusCommand): Tambahkan command untuk monitoring status data inspeksi
Membuat artisan command untuk cek status data yang memerlukan cleanup dengan opsi filter dan detail view

- Command signature: `lpj:cleanup-inspeksi-status` dengan opsi --permohonan-id, --created-by, dan --detailed
- Method showGeneralStats() untuk statistik umum data (total, aktif, terhapus, dengan/tanpa dokument_id)
- Method showCleanupStats() untuk identifikasi data yang perlu cleanup berdasarkan permohonan_id dan created_by
- Method showDetailedData() untuk menampilkan 20 data terbaru dengan relasi permohonan dan dokument
- Query optimization dengan DB::table dan raw SQL untuk performa optimal
- Error handling dengan try-catch dan logging ke Laravel Log
- Tampilan tabel yang informatif dengan format number_format untuk angka besar
- Support filter berdasarkan permohonan_id dan created_by untuk analisis spesifik
- Limit 20 data untuk mencegah overload memory pada dataset besar
2025-12-09 15:34:47 +07:00
Daeng Deni Mardaeni
783250d99a 🧪 test(CleanupInspeksiDataJobTest): Implementasi unit test lengkap untuk cleanup job
Membuat suite test yang mencakup semua skenario penting untuk CleanupInspeksiDataJob dengan RefreshDatabase trait

- 6 test cases yang mencakup success dan failure scenarios
- Penggunaan RefreshDatabase trait untuk isolasi data test
- Penggunaan factory models untuk pembuatan data test otomatis
- Validasi soft delete pada data inspeksi lama tanpa dokument_id
- Pencegahan penghapusan data dengan created_by berbeda
- Handling exception dan rollback transaction
- Logging error pada method failed
- PHPDoc dokumentasi untuk setiap test case
- Integrasi dengan model Permohonan, DokumenJaminan, dan Inspeksi
2025-12-09 15:32:35 +07:00
Daeng Deni Mardaeni
19057c7e81 🎮 controller(InspeksiController): Implementasi controller dengan integrasi cleanup service
Membuat controller contoh yang menunjukkan best practices penggunaan InspeksiCleanupService dengan automatic cleanup trigger pada create dan update operations

- Dependency injection InspeksiCleanupService melalui constructor
- Method store() dengan automatic cleanup trigger saat dokument_id tersedia
- Method update() dengan cleanup trigger hanya saat dokument_id berubah dari null
- Method cleanup() untuk eksekusi manual cleanup dengan pilihan sync/async
- Validasi request yang komprehensif untuk semua method
- Database transaction handling dengan proper rollback pada error
- Logging informatif untuk audit trail setiap operasi
- Error handling dengan try-catch dan response JSON yang konsisten
- Response format yang standar dengan status code HTTP yang tepat
- PHPDoc dokumentasi untuk setiap method dengan parameter dan return type
2025-12-09 15:27:48 +07:00
Daeng Deni Mardaeni
9dfb8727dc 🔧 service(InspeksiCleanupService): Implementasi service layer untuk manajemen cleanup data inspeksi
Membuat service layer yang menyediakan interface fleksibel untuk menjalankan cleanup data inspeksi secara async/sync dengan error handling dan logging komprehensif

- Implementasi pattern service layer untuk separation of concerns
- Method utama cleanupInspeksiData dengan parameter sync untuk fleksibilitas eksekusi
- Method wrapper cleanupAsync() untuk eksekusi asynchronous default
- Method wrapper cleanupSync() untuk eksekusi synchronous langsung
- Error handling dengan try-catch dan re-throw exception untuk propagasi error
- Logging informatif untuk setiap proses cleanup (mulai, selesai, error)
- Integrasi dengan CleanupInspeksiDataJob untuk delegasi proses bisnis
- Parameter lengkap: permohonanId, createdBy, dokumentId, dan sync mode
- Dokumentasi PHPDoc yang komprehensif untuk setiap method
- Menggunakan Laravel dispatch() untuk queue management yang optimal
2025-12-09 15:24:44 +07:00
Daeng Deni Mardaeni
bef7bcfa8f 🗑️ job(CleanupInspeksiDataJob): Menambahkan fungsi untuk cleanup data inspeksi dengan queueable retry dan transaction aman
Menambahkan exponential backoff (60, 120, 300 detik), timeout 5 menit, dan logging rinci untuk audit cleanup data inspeksi tanpa dokument_id

- Implementasi job queue dengan retry otomatis menggunakan exponential backoff strategy
- Tambahkan timeout 5 menit untuk mencegah hanging jobs
- Gunakan database transaction untuk memastikan atomicity operasi soft delete
- Logging komprehensif untuk audit trail proses cleanup
- Validasi data lengkap (dengan dokument_id) sebelum proses cleanup
- Soft delete data lama tanpa dokument_id hanya jika data baru tersedia
- Pencegahan penghapusan data yang baru saja ditemukan dengan kondisi where('id', '!=', $newInspeksi->id)
- Error handling dengan rollback transaction dan re-throw exception untuk retry mechanism
- Dokumentasi kode yang jelas dengan PHPDoc untuk setiap method
- Menggunakan Laravel best practices dengan ShouldQueue, Dispatchable, InteractsWithQueue, Queueable, SerializesModels traits
2025-12-09 15:22:37 +07:00
23 changed files with 1878 additions and 101 deletions

View File

@@ -0,0 +1,228 @@
<?php
namespace Modules\Lpj\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Lpj\Jobs\CleanupInspeksiDataJob;
use Modules\Lpj\Models\Inspeksi;
use Modules\Lpj\Services\InspeksiCleanupService;
class CleanupInspeksiDataCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'lpj:cleanup-inspeksi
{--permohonan-id= : ID permohonan yang akan di-cleanup (opsional)}
{--sync : Jalankan secara synchronous}
{--dry-run : Tampilkan preview tanpa menjalankan cleanup}
{--force : Jalankan tanpa konfirmasi}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Cleanup data inspeksi lama yang tidak memiliki dokument_id';
/**
* Execute the console command.
*/
public function handle(): int
{
Log::info('CleanupInspeksiDataCommand: Memulai proses cleanup data inspeksi', [
'options' => $this->options()
]);
try {
$permohonanId = $this->option('permohonan-id');
$sync = $this->option('sync');
$dryRun = $this->option('dry-run');
$force = $this->option('force');
// Validasi opsi
if ($dryRun && $sync) {
$this->error('Opsi --dry-run dan --sync tidak dapat digunakan bersamaan.');
return Command::FAILURE;
}
// Tampilkan header
$this->info('=== Cleanup Data Inspeksi ===');
$this->newLine();
// Ambil data yang akan di-cleanup
$cleanupData = $this->getCleanupData($permohonanId);
if ($cleanupData->isEmpty()) {
$this->info('Tidak ada data yang perlu di-cleanup.');
return Command::SUCCESS;
}
// Tampilkan preview data
$this->displayPreview($cleanupData);
if ($dryRun) {
$this->info('Mode dry-run: Tidak ada perubahan yang dilakukan.');
return Command::SUCCESS;
}
// Konfirmasi jika tidak force
if (!$force && !$this->confirm('Lanjutkan dengan cleanup?')) {
$this->info('Cleanup dibatalkan.');
return Command::SUCCESS;
}
// Jalankan cleanup
$this->runCleanup($cleanupData, $sync);
$this->info('Proses cleanup selesai.');
return Command::SUCCESS;
} catch (\Exception $e) {
Log::error('CleanupInspeksiDataCommand: Terjadi error saat proses cleanup', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
$this->error('Terjadi kesalahan: ' . $e->getMessage());
return Command::FAILURE;
}
}
/**
* Ambil data yang akan di-cleanup
*/
private function getCleanupData(?int $permohonanId = null)
{
$this->info('Mencari data yang akan di-cleanup...');
$query = DB::table('inspeksi as i')
->select(
'i.permohonan_id',
'i.created_by',
DB::raw('COUNT(CASE WHEN i.dokument_id IS NOT NULL AND i.deleted_at IS NULL THEN 1 END) as new_data_count'),
DB::raw('COUNT(CASE WHEN i.dokument_id IS NULL AND i.deleted_at IS NULL THEN 1 END) as old_data_count')
)
->whereNull('i.deleted_at')
->groupBy('i.permohonan_id', 'i.created_by');
if ($permohonanId) {
$query->where('i.permohonan_id', $permohonanId);
}
$results = $query->havingRaw('new_data_count > 0 AND old_data_count > 0')
->get();
return $results;
}
/**
* Tampilkan preview data
*/
private function displayPreview($cleanupData): void
{
$this->info('Data yang akan di-cleanup:');
$this->table(
['Permohonan ID', 'Created By', 'Data Baru', 'Data Lama'],
$cleanupData->map(function ($item) {
return [
$item->permohonan_id,
$item->created_by,
$item->new_data_count,
$item->old_data_count
];
})->toArray()
);
$totalPermohonan = $cleanupData->count();
$totalOldData = $cleanupData->sum('old_data_count');
$this->info("Total permohonan: {$totalPermohonan}");
$this->info("Total data lama yang akan dihapus: {$totalOldData}");
$this->newLine();
}
/**
* Jalankan cleanup
*/
private function runCleanup($cleanupData, bool $sync): void
{
$this->info('Memulai proses cleanup...');
$this->newLine();
$progressBar = $this->output->createProgressBar($cleanupData->count());
$progressBar->setFormat('Processing: %current%/%max% [%bar%] %percent:3s%% %message%');
$progressBar->start();
$totalDeleted = 0;
$totalErrors = 0;
foreach ($cleanupData as $data) {
try {
$progressBar->setMessage("Permohonan ID: {$data->permohonan_id}");
// Ambil data baru untuk mendapatkan dokument_id
$newInspeksi = Inspeksi::where('permohonan_id', $data->permohonan_id)
->where('created_by', $data->created_by)
->whereNotNull('dokument_id')
->whereNull('deleted_at')
->first();
if (!$newInspeksi) {
$this->warn("Tidak ditemukan data baru untuk permohonan {$data->permohonan_id}");
$progressBar->advance();
continue;
}
// Jalankan cleanup
if ($sync) {
// Jalankan sync
$job = new CleanupInspeksiDataJob(
$data->permohonan_id,
$data->created_by,
$newInspeksi->dokument_id
);
$job->handle();
} else {
// Dispatch ke queue
CleanupInspeksiDataJob::dispatch(
$data->permohonan_id,
$data->created_by,
$newInspeksi->dokument_id
);
}
$totalDeleted += $data->old_data_count;
} catch (\Exception $e) {
Log::error('CleanupInspeksiDataCommand: Error pada permohonan', [
'permohonan_id' => $data->permohonan_id,
'created_by' => $data->created_by,
'error' => $e->getMessage()
]);
$this->error("Error pada permohonan {$data->permohonan_id}: {$e->getMessage()}");
$totalErrors++;
}
$progressBar->advance();
}
$progressBar->finish();
$this->newLine();
$this->newLine();
// Tampilkan hasil
$this->info('=== Hasil Cleanup ===');
$this->info("Data lama yang dihapus: {$totalDeleted}");
$this->info("Error: {$totalErrors}");
if (!$sync) {
$this->info('Job telah di-dispatch ke queue. Monitor progress di log.');
}
}
}

View File

@@ -0,0 +1,192 @@
<?php
namespace Modules\Lpj\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Lpj\Models\Inspeksi;
class CleanupInspeksiStatusCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'lpj:cleanup-inspeksi-status
{--permohonan-id= : Filter berdasarkan permohonan ID}
{--created-by= : Filter berdasarkan user ID}
{--detailed : Tampilkan detail data}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Cek status data inspeksi yang memerlukan cleanup';
/**
* Execute the console command.
*/
public function handle(): int
{
try {
$permohonanId = $this->option('permohonan-id');
$createdBy = $this->option('created-by');
$detailed = $this->option('detailed');
$this->info('=== Status Data Inspeksi ===');
$this->newLine();
// Ambil statistik umum
$this->showGeneralStats();
// Ambil data yang memerlukan cleanup
$this->showCleanupStats($permohonanId, $createdBy);
if ($detailed) {
$this->showDetailedData($permohonanId, $createdBy);
}
return Command::SUCCESS;
} catch (\Exception $e) {
Log::error('CleanupInspeksiStatusCommand: Terjadi error', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
$this->error('Terjadi kesalahan: ' . $e->getMessage());
return Command::FAILURE;
}
}
/**
* Tampilkan statistik umum
*/
private function showGeneralStats(): void
{
$this->info('Statistik Umum:');
$totalData = Inspeksi::count();
$activeData = Inspeksi::whereNull('deleted_at')->count();
$deletedData = Inspeksi::whereNotNull('deleted_at')->count();
$dataWithDokument = Inspeksi::whereNotNull('dokument_id')->count();
$dataWithoutDokument = Inspeksi::whereNull('dokument_id')->count();
$this->table(
['Metrik', 'Jumlah'],
[
['Total Data', number_format($totalData)],
['Data Aktif', number_format($activeData)],
['Data Terhapus (Soft)', number_format($deletedData)],
['Data dengan Dokument ID', number_format($dataWithDokument)],
['Data tanpa Dokument ID', number_format($dataWithoutDokument)],
]
);
$this->newLine();
}
/**
* Tampilkan statistik cleanup
*/
private function showCleanupStats(?int $permohonanId = null, ?int $createdBy = null): void
{
$this->info('Data yang Memerlukan Cleanup:');
$query = DB::table('inspeksi as i')
->select(
'i.permohonan_id',
'i.created_by',
DB::raw('COUNT(CASE WHEN i.dokument_id IS NOT NULL AND i.deleted_at IS NULL THEN 1 END) as new_data_count'),
DB::raw('COUNT(CASE WHEN i.dokument_id IS NULL AND i.deleted_at IS NULL THEN 1 END) as old_data_count'),
DB::raw('MIN(i.created_at) as oldest_data'),
DB::raw('MAX(i.created_at) as newest_data')
)
->whereNull('i.deleted_at')
->groupBy('i.permohonan_id', 'i.created_by');
if ($permohonanId) {
$query->where('i.permohonan_id', $permohonanId);
}
if ($createdBy) {
$query->where('i.created_by', $createdBy);
}
$results = $query->havingRaw('new_data_count > 0 AND old_data_count > 0')
->orderBy('old_data_count', 'desc')
->limit(20)
->get();
if ($results->isEmpty()) {
$this->info('Tidak ada data yang memerlukan cleanup.');
return;
}
$this->table(
['Permohonan ID', 'Created By', 'Data Baru', 'Data Lama', 'Data Terlama', 'Data Terbaru'],
$results->map(function ($item) {
return [
$item->permohonan_id,
$item->created_by,
$item->new_data_count,
$item->old_data_count,
$item->oldest_data,
$item->newest_data,
];
})->toArray()
);
$totalPermohonan = $results->count();
$totalOldData = $results->sum('old_data_count');
$this->info("Total permohonan yang perlu cleanup: {$totalPermohonan}");
$this->info("Total data lama yang akan dihapus: {$totalOldData}");
$this->newLine();
}
/**
* Tampilkan detail data
*/
private function showDetailedData(?int $permohonanId = null, ?int $createdBy = null): void
{
$this->info('Detail Data (20 data terbaru):');
$query = Inspeksi::with(['permohonan', 'dokument'])
->whereNull('deleted_at');
if ($permohonanId) {
$query->where('permohonan_id', $permohonanId);
}
if ($createdBy) {
$query->where('created_by', $createdBy);
}
$data = $query->orderBy('created_at', 'desc')
->limit(20)
->get();
if ($data->isEmpty()) {
$this->info('Tidak ada data untuk ditampilkan.');
return;
}
$this->table(
['ID', 'Permohonan ID', 'Created By', 'Dokument ID', 'Status', 'Created At'],
$data->map(function ($item) {
return [
$item->id,
$item->permohonan_id,
$item->created_by,
$item->dokument_id ?? '-',
$item->status,
$item->created_at,
];
})->toArray()
);
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace Modules\Lpj\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Modules\Lpj\Jobs\CleanupInspeksiDataJob;
use Modules\Lpj\Services\InspeksiCleanupService;
class CleanupSingleInspeksiCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'lpj:cleanup-single-inspeksi
{permohonan-id : ID permohonan yang akan di-cleanup}
{created-by : ID user yang membuat data}
{--sync : Jalankan secara synchronous}
{--force : Jalankan tanpa konfirmasi}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Cleanup data inspeksi untuk 1 permohonan dan user tertentu';
/**
* Execute the console command.
*/
public function handle(): int
{
Log::info('CleanupSingleInspeksiCommand: Memulai proses cleanup', [
'permohonan_id' => $this->argument('permohonan-id'),
'created_by' => $this->argument('created-by'),
'sync' => $this->option('sync')
]);
try {
$permohonanId = (int) $this->argument('permohonan-id');
$createdBy = (int) $this->argument('created-by');
$sync = $this->option('sync');
$force = $this->option('force');
// Validasi input
if ($permohonanId <= 0) {
$this->error('Permohonan ID harus angka positif.');
return Command::FAILURE;
}
if ($createdBy <= 0) {
$this->error('Created By harus angka positif.');
return Command::FAILURE;
}
// Tampilkan info
$this->info('=== Cleanup Single Inspeksi ===');
$this->info("Permohonan ID: {$permohonanId}");
$this->info("Created By: {$createdBy}");
$this->info("Mode: " . ($sync ? 'Synchronous' : 'Queue'));
$this->newLine();
// Konfirmasi jika tidak force
if (!$force && !$this->confirm('Lanjutkan dengan cleanup?')) {
$this->info('Cleanup dibatalkan.');
return Command::SUCCESS;
}
// Jalankan cleanup
$cleanupService = new InspeksiCleanupService();
if ($sync) {
$this->info('Menjalankan cleanup secara synchronous...');
$cleanupService->cleanupSync($permohonanId, $createdBy);
$this->info('Cleanup selesai.');
} else {
$this->info('Mengirim job ke queue...');
$cleanupService->cleanupAsync($permohonanId, $createdBy);
$this->info('Job telah di-dispatch ke queue.');
$this->info('Monitor progress di log.');
}
return Command::SUCCESS;
} catch (\Exception $e) {
Log::error('CleanupSingleInspeksiCommand: Terjadi error saat proses cleanup', [
'permohonan_id' => $this->argument('permohonan-id'),
'created_by' => $this->argument('created-by'),
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
$this->error('Terjadi kesalahan: ' . $e->getMessage());
return Command::FAILURE;
}
}
}

123
app/Console/README.md Normal file
View File

@@ -0,0 +1,123 @@
# Console Commands untuk Cleanup Data Inspeksi
## Daftar Command
### 1. `lpj:cleanup-inspeksi`
Command utama untuk cleanup data inspeksi secara batch.
**Usage:**
```bash
php artisan lpj:cleanup-inspeksi [options]
```
**Options:**
- `--permohonan-id=ID` - Filter berdasarkan permohonan ID (opsional)
- `--sync` - Jalankan secara synchronous
- `--dry-run` - Tampilkan preview tanpa menjalankan cleanup
- `--force` - Jalankan tanpa konfirmasi
**Contoh Penggunaan:**
```bash
# Preview data yang akan di-cleanup
php artisan lpj:cleanup-inspeksi --dry-run
# Cleanup semua data (dengan konfirmasi)
php artisan lpj:cleanup-inspeksi
# Cleanup untuk permohonan tertentu
php artisan lpj:cleanup-inspeksi --permohonan-id=123 --force
# Jalankan secara sync
php artisan lpj:cleanup-inspeksi --sync --force
```
### 2. `lpj:cleanup-single-inspeksi`
Command untuk cleanup 1 permohonan dan user tertentu.
**Usage:**
```bash
php artisan lpj:cleanup-single-inspeksi <permohonan-id> <created-by> [options]
```
**Arguments:**
- `permohonan-id` - ID permohonan yang akan di-cleanup (required)
- `created-by` - ID user yang membuat data (required)
**Options:**
- `--sync` - Jalankan secara synchronous
- `--force` - Jalankan tanpa konfirmasi
**Contoh Penggunaan:**
```bash
# Cleanup untuk permohonan 123 oleh user 456
php artisan lpj:cleanup-single-inspeksi 123 456
# Jalankan secara sync tanpa konfirmasi
php artisan lpj:cleanup-single-inspeksi 123 456 --sync --force
```
### 3. `lpj:cleanup-inspeksi-status`
Command untuk mengecek status data inspeksi dan melihat statistik cleanup.
**Usage:**
```bash
php artisan lpj:cleanup-inspeksi-status [options]
```
**Options:**
- `--permohonan-id=ID` - Filter berdasarkan permohonan ID
- `--created-by=ID` - Filter berdasarkan user ID
- `--detailed` - Tampilkan detail data
**Contoh Penggunaan:**
```bash
# Lihat statistik umum
php artisan lpj:cleanup-inspeksi-status
# Filter berdasarkan permohonan
php artisan lpj:cleanup-inspeksi-status --permohonan-id=123
# Tampilkan detail data
php artisan lpj:cleanup-inspeksi-status --detailed
```
## Scheduling
Command cleanup otomatis dijalankan setiap hari jam 2 pagi dan setiap minggu. Konfigurasi scheduling ada di `LpjServiceProvider.php`.
## Monitoring
Semua aktivitas cleanup dicatat di log file:
- `storage/logs/laravel.log` - Log umum
- `storage/logs/cleanup-inspeksi.log` - Log cleanup harian
- `storage/logs/cleanup-inspeksi-weekly.log` - Log cleanup mingguan
## Alur Kerja Cleanup
1. **Identifikasi**: Cari data inspeksi yang memiliki:
- Data baru dengan `dokument_id` (tidak null)
- Data lama tanpa `dokument_id` (null)
- Sama `permohonan_id` dan `created_by`
2. **Proses**: Soft delete data lama menggunakan Laravel SoftDeletes
3. **Logging**: Catat setiap operasi untuk audit trail
4. **Transaction**: Gunakan DB transaction untuk konsistensi data
## Troubleshooting
### Command tidak muncul
Pastikan service provider sudah diregister dengan benar:
```bash
php artisan list | grep lpj
```
### Data tidak ter-cleanup
- Cek log untuk error
- Pastikan ada data yang memenuhi kriteria
- Gunakan `--dry-run` untuk preview
- Gunakan `--detailed` untuk melihat detail data
### Performance
Untuk data besar, gunakan mode queue (default) daripada `--sync`

View File

@@ -20,6 +20,7 @@
use Modules\Usermanagement\Models\User;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Modules\Lpj\Services\ImageResizeService;
/**
* Format tanggal ke dalam format Bahasa Indonesia
@@ -775,3 +776,20 @@
Log::error('Tidak dapat memparsing timestamp dengan format apapun: "' . $timestamp . '"');
return null;
}
if (!function_exists('resize_image')) {
/**
* Merubah ukuran gambar secara on-the-fly dan mengembalikan path-nya.
*
* @param string $path Path asli gambar.
* @param int|null $width Lebar yang diinginkan.
* @param int|null $height Tinggi yang diinginkan (opsional, akan menjaga rasio aspek jika null).
* @param int $quality Kualitas gambar (1-100).
* @return string Path gambar yang sudah di-resize.
*/
function resize_image(string $path, ?int $width, ?int $height = null, int $quality = 80): string
{
return app(ImageResizeService::class)->resize($path, $width, $height, $quality);
}
}

View File

@@ -7,6 +7,8 @@ use Illuminate\Http\Request;
use Modules\Lpj\Models\CategoryDaftarPustaka;
use Modules\Lpj\Services\DaftarPustakaService;
use Modules\Lpj\Http\Requests\DaftarPustakaRequest;
use Exception;
use Illuminate\Support\Facades\Log;
class DaftarPustakaController extends Controller
{
@@ -22,7 +24,15 @@ class DaftarPustakaController extends Controller
*/
public function index(Request $request)
{
$categories = CategoryDaftarPustaka::all();
// Get categories with count of daftar pustaka
try {
$categories = CategoryDaftarPustaka::withCount('daftarPustaka')->get();
} catch (\Exception $e) {
// Handle jika tabel belum ada atau error lainnya
Log::warning('Error loading categories with count: ' . $e->getMessage());
$categories = CategoryDaftarPustaka::get(); // Fallback tanpa count
}
$daftar_pustaka = $this->daftarPustaka->getAllDaftarPustaka($request);
return view('lpj::daftar-pustaka.index', [

View File

@@ -0,0 +1,239 @@
<?php
namespace Modules\Lpj\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Lpj\Models\Inspeksi;
use Modules\Lpj\Services\InspeksiCleanupService;
/**
* Controller contoh untuk menunjukkan penggunaan InspeksiCleanupService
*
* Controller ini berisi contoh method untuk membuat dan update data inspeksi
* dengan otomatis menjalankan cleanup data lama yang tidak memiliki dokument_id
*/
class InspeksiController extends Controller
{
protected InspeksiCleanupService $cleanupService;
public function __construct(InspeksiCleanupService $cleanupService)
{
$this->cleanupService = $cleanupService;
}
/**
* Contoh method untuk membuat data inspeksi baru
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
{
$validated = $request->validate([
'permohonan_id' => 'required|integer|exists:permohonan,id',
'dokument_id' => 'nullable|integer|exists:dokumen_jaminan,id',
'data_form' => 'required|json',
'foto_form' => 'nullable|json',
'denah_form' => 'nullable|json',
'name' => 'required|string|max:255',
'status' => 'required|string|max:50',
]);
DB::beginTransaction();
try {
// Buat data inspeksi baru
$inspeksi = Inspeksi::create(array_merge($validated, [
'created_by' => Auth::id(),
'updated_by' => Auth::id(),
]));
Log::info('InspeksiController: Data inspeksi berhasil dibuat', [
'inspeksi_id' => $inspeksi->id,
'permohonan_id' => $inspeksi->permohonan_id,
'dokument_id' => $inspeksi->dokument_id,
'created_by' => $inspeksi->created_by
]);
// Commit transaksi utama
DB::commit();
// Jalankan cleanup secara async jika ada dokument_id
// Ini akan menghapus data lama yang tidak memiliki dokument_id
if ($inspeksi->dokument_id) {
Log::info('InspeksiController: Memulai cleanup data lama', [
'permohonan_id' => $inspeksi->permohonan_id,
'created_by' => $inspeksi->created_by,
'dokument_id' => $inspeksi->dokument_id
]);
// Dispatch job cleanup secara async
$this->cleanupService->cleanupAsync(
$inspeksi->permohonan_id,
$inspeksi->created_by,
$inspeksi->dokument_id
);
}
return response()->json([
'success' => true,
'message' => 'Data inspeksi berhasil dibuat',
'data' => $inspeksi->load(['permohonan', 'dokument'])
], 201);
} catch (\Exception $e) {
DB::rollBack();
Log::error('InspeksiController: Gagal membuat data inspeksi', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return response()->json([
'success' => false,
'message' => 'Gagal membuat data inspeksi: ' . $e->getMessage()
], 500);
}
}
/**
* Contoh method untuk update data inspeksi
*
* @param Request $request
* @param int $id
* @return \Illuminate\Http\JsonResponse
*/
public function update(Request $request, $id)
{
$validated = $request->validate([
'dokument_id' => 'nullable|integer|exists:dokumen_jaminan,id',
'data_form' => 'required|json',
'foto_form' => 'nullable|json',
'denah_form' => 'nullable|json',
'name' => 'required|string|max:255',
'status' => 'required|string|max:50',
]);
DB::beginTransaction();
try {
$inspeksi = Inspeksi::findOrFail($id);
// Simpan data lama untuk logging
$oldDokumentId = $inspeksi->dokument_id;
// Update data
$inspeksi->update(array_merge($validated, [
'updated_by' => Auth::id(),
]));
Log::info('InspeksiController: Data inspeksi berhasil diupdate', [
'inspeksi_id' => $inspeksi->id,
'permohonan_id' => $inspeksi->permohonan_id,
'old_dokument_id' => $oldDokumentId,
'new_dokument_id' => $inspeksi->dokument_id,
'updated_by' => $inspeksi->updated_by
]);
// Commit transaksi utama
DB::commit();
// Jalankan cleanup jika dokument_id berubah dari null ke ada nilai
if (!$oldDokumentId && $inspeksi->dokument_id) {
Log::info('InspeksiController: Dokument ID berubah dari null, memulai cleanup', [
'inspeksi_id' => $inspeksi->id,
'permohonan_id' => $inspeksi->permohonan_id,
'created_by' => $inspeksi->created_by,
'new_dokument_id' => $inspeksi->dokument_id
]);
// Dispatch job cleanup secara async
$this->cleanupService->cleanupAsync(
$inspeksi->permohonan_id,
$inspeksi->created_by,
$inspeksi->dokument_id
);
}
return response()->json([
'success' => true,
'message' => 'Data inspeksi berhasil diupdate',
'data' => $inspeksi->load(['permohonan', 'dokument'])
]);
} catch (\Exception $e) {
DB::rollBack();
Log::error('InspeksiController: Gagal update data inspeksi', [
'inspeksi_id' => $id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return response()->json([
'success' => false,
'message' => 'Gagal update data inspeksi: ' . $e->getMessage()
], 500);
}
}
/**
* Contoh method untuk menjalankan cleanup secara manual
*
* @param Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function cleanup(Request $request)
{
$validated = $request->validate([
'permohonan_id' => 'required|integer|exists:permohonan,id',
'created_by' => 'required|integer|exists:users,id',
'sync' => 'boolean', // Opsional, default false (async)
]);
try {
$permohonanId = $validated['permohonan_id'];
$createdBy = $validated['created_by'];
$sync = $validated['sync'] ?? false;
Log::info('InspeksiController: Menjalankan cleanup manual', [
'permohonan_id' => $permohonanId,
'created_by' => $createdBy,
'sync' => $sync
]);
if ($sync) {
// Jalankan secara sync
$this->cleanupService->cleanupSync($permohonanId, $createdBy);
return response()->json([
'success' => true,
'message' => 'Cleanup selesai dijalankan secara synchronous'
]);
} else {
// Dispatch ke queue
$this->cleanupService->cleanupAsync($permohonanId, $createdBy);
return response()->json([
'success' => true,
'message' => 'Cleanup job berhasil di-dispatch ke queue'
]);
}
} catch (\Exception $e) {
Log::error('InspeksiController: Gagal menjalankan cleanup manual', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
return response()->json([
'success' => false,
'message' => 'Gagal menjalankan cleanup: ' . $e->getMessage()
], 500);
}
}
}

View File

@@ -9,9 +9,11 @@ use Maatwebsite\Excel\Facades\Excel;
use Modules\Lpj\Exports\BasicDataSurveyorExport;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Carbon;
use Exception;
use Modules\Lpj\Models\Debiture;
use Modules\Lpj\Models\LaporanExternal;
use Modules\Lpj\Models\Permohonan;
@@ -106,6 +108,9 @@ class SurveyorController extends Controller
$provinces = Province::all();
$bentukTanah = BentukTanah::all();
// Jalankan cleanup inspeksi otomatis untuk permohonan ini
$this->cleanupInspeksiData($id);
// Get all inspeksi data for this permohonan
if (strtolower($permohonan->tujuanPenilaian->name) == 'rap') {
$inspeksiData = Inspeksi::where('permohonan_id', $id)
@@ -237,7 +242,7 @@ class SurveyorController extends Controller
], 200);
} catch (\Exception $e) {
\Log::error('Denah Store Error: ' . $e->getMessage());
Log::error('Denah Store Error: ' . $e->getMessage());
return response()->json([
'success' => false,
'message' => 'Gagal menyimpan data: ' . $e->getMessage()
@@ -1063,7 +1068,7 @@ class SurveyorController extends Controller
return null;
} catch (\Exception $e) {
\Log::error('File upload error: ' . $e->getMessage());
Log::error('File upload error: ' . $e->getMessage());
throw new \Exception("Gagal mengupload file: " . $e->getMessage());
}
}
@@ -2893,5 +2898,99 @@ class SurveyorController extends Controller
]);
}
/**
* Fungsi untuk cleanup data inspeksi otomatis
* Menghapus data inspeksi tanpa dokument_id jika ada data lain dengan dokument_id yang sama
*/
private function cleanupInspeksiData($permohonanId)
{
try {
Log::info('SurveyorController: Memulai cleanup inspeksi otomatis', [
'permohonan_id' => $permohonanId,
'user_id' => Auth::id()
]);
// Ambil data inspeksi yang memiliki dokument_id (data lengkap)
$dataWithDokument = Inspeksi::where('permohonan_id', $permohonanId)
->whereNotNull('dokument_id')
->whereNull('deleted_at')
->get();
// Ambil data inspeksi yang tidak memiliki dokument_id (data yang akan di-cleanup)
$dataWithoutDokument = Inspeksi::where('permohonan_id', $permohonanId)
->whereNull('dokument_id')
->whereNull('deleted_at')
->get();
// Jika ada data tanpa dokument_id, cek apakah ada data dengan dokument_id yang sama
if ($dataWithoutDokument->isNotEmpty() && $dataWithDokument->isNotEmpty()) {
// Group data dengan dokument_id by created_by
$groupedDataWithDokument = $dataWithDokument->groupBy('created_by');
// Group data tanpa dokument_id by created_by
$groupedDataWithoutDokument = $dataWithoutDokument->groupBy('created_by');
// Proses cleanup untuk setiap user
foreach ($groupedDataWithDokument as $userId => $userDataWithDokument) {
// Cek apakah user ini juga memiliki data tanpa dokument_id
if (isset($groupedDataWithoutDokument[$userId])) {
// Ambil salah satu data dengan dokument_id sebagai referensi untuk logging
$referenceData = $userDataWithDokument->first();
Log::info('SurveyorController: Menemukan data lengkap untuk user, akan menghapus data tidak lengkap', [
'user_id' => $userId,
'permohonan_id' => $permohonanId,
'reference_dokument_id' => $referenceData->dokument_id,
'data_count_to_delete' => $groupedDataWithoutDokument[$userId]->count()
]);
// Ambil semua data tanpa dokument_id untuk user ini
$userDataWithoutDokument = $groupedDataWithoutDokument[$userId];
// Soft delete data tanpa dokument_id
foreach ($userDataWithoutDokument as $dataToDelete) {
DB::beginTransaction();
try {
// Soft delete data
$dataToDelete->delete();
Log::info('SurveyorController: Data inspeksi berhasil di-soft delete', [
'id' => $dataToDelete->id,
'permohonan_id' => $dataToDelete->permohonan_id,
'dokument_id' => $dataToDelete->dokument_id,
'created_by' => $dataToDelete->created_by,
'deleted_at' => now()
]);
DB::commit();
} catch (\Exception $e) {
DB::rollback();
Log::error('SurveyorController: Gagal menghapus data inspeksi', [
'id' => $dataToDelete->id,
'error' => $e->getMessage()
]);
}
}
}
}
}
Log::info('SurveyorController: Cleanup inspeksi otomatis selesai', [
'permohonan_id' => $permohonanId,
'data_with_dokument' => $dataWithDokument->count(),
'data_without_dokument' => $dataWithoutDokument->count()
]);
} catch (\Exception $e) {
Log::error('SurveyorController: Error saat cleanup inspeksi otomatis', [
'permohonan_id' => $permohonanId,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
}
}
}

View File

@@ -0,0 +1,156 @@
<?php
namespace Modules\Lpj\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Lpj\Models\Inspeksi;
/**
* Job untuk membersihkan data inspeksi yang tidak memiliki dokument_id
*
* Case: Jika ada data inspeksi yang masuk dengan permohonan_id yang sama
* tetapi memiliki dokument_id dan user created_by yang sama, maka
* data lama (tanpa dokument_id) akan di-soft delete
*/
class CleanupInspeksiDataJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 300; // 5 menit
public $tries = 3;
public $maxExceptions = 3;
public $backoff = [60, 120, 300]; // Exponential backoff dalam detik
protected int $permohonanId;
protected int $createdBy;
protected ?int $dokumentId;
/**
* Create a new job instance.
*
* @param int $permohonanId
* @param int $createdBy
* @param int|null $dokumentId
*/
public function __construct(int $permohonanId, int $createdBy, ?int $dokumentId = null)
{
$this->permohonanId = $permohonanId;
$this->createdBy = $createdBy;
$this->dokumentId = $dokumentId;
}
/**
* Execute the job.
*
* @return void
* @throws \Exception
*/
public function handle(): void
{
Log::info('CleanupInspeksiDataJob: Memulai proses cleanup data inspeksi', [
'permohonan_id' => $this->permohonanId,
'created_by' => $this->createdBy,
'dokument_id' => $this->dokumentId
]);
DB::beginTransaction();
try {
// Cari data inspeksi yang memiliki dokument_id (data baru)
$newInspeksi = Inspeksi::where('permohonan_id', $this->permohonanId)
->where('created_by', $this->createdBy)
->whereNotNull('dokument_id')
->whereNull('deleted_at')
->first();
if (!$newInspeksi) {
Log::warning('CleanupInspeksiDataJob: Tidak ditemukan data inspeksi baru dengan dokument_id', [
'permohonan_id' => $this->permohonanId,
'created_by' => $this->createdBy
]);
DB::rollBack();
return;
}
Log::info('CleanupInspeksiDataJob: Data inspeksi baru ditemukan', [
'inspeksi_id' => $newInspeksi->id,
'dokument_id' => $newInspeksi->dokument_id
]);
// Cari data inspeksi lama yang tidak memiliki dokument_id
$oldInspeksiList = Inspeksi::where('permohonan_id', $this->permohonanId)
->where('created_by', $this->createdBy)
->whereNull('dokument_id')
->whereNull('deleted_at')
->where('id', '!=', $newInspeksi->id) // Jangan hapus data yang baru saja ditemukan
->get();
if ($oldInspeksiList->isEmpty()) {
Log::info('CleanupInspeksiDataJob: Tidak ditemukan data inspeksi lama tanpa dokument_id', [
'permohonan_id' => $this->permohonanId,
'created_by' => $this->createdBy
]);
DB::commit();
return;
}
$deletedCount = 0;
foreach ($oldInspeksiList as $oldInspeksi) {
// Soft delete data lama
$oldInspeksi->delete(); // Menggunakan soft delete karena model menggunakan SoftDeletes trait
Log::info('CleanupInspeksiDataJob: Data inspeksi lama berhasil di-soft delete', [
'old_inspeksi_id' => $oldInspeksi->id,
'permohonan_id' => $oldInspeksi->permohonan_id,
'created_by' => $oldInspeksi->created_by,
'deleted_at' => now()->toDateTimeString()
]);
$deletedCount++;
}
DB::commit();
Log::info('CleanupInspeksiDataJob: Proses cleanup selesai', [
'permohonan_id' => $this->permohonanId,
'created_by' => $this->createdBy,
'deleted_count' => $deletedCount,
'new_inspeksi_id' => $newInspeksi->id
]);
} catch (\Exception $e) {
DB::rollBack();
Log::error('CleanupInspeksiDataJob: Terjadi error saat proses cleanup', [
'permohonan_id' => $this->permohonanId,
'created_by' => $this->createdBy,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
throw $e;
}
}
/**
* Handle a job failure.
*
* @param \Throwable $exception
* @return void
*/
public function failed(\Throwable $exception): void
{
Log::error('CleanupInspeksiDataJob: Job gagal dieksekusi', [
'permohonan_id' => $this->permohonanId,
'created_by' => $this->createdBy,
'error' => $exception->getMessage(),
'trace' => $exception->getTraceAsString()
]);
}
}

View File

@@ -21,7 +21,7 @@ class CategoryDaftarPustaka extends Model
];
public function daftarPustaka(){
return $this->hasMany(DaftarPustaka::class);
return $this->hasMany(DaftarPustaka::class, 'category_id');
}
}

View File

@@ -32,25 +32,46 @@
}
/**
* Register commands in the format of Command::class
*/
protected function registerCommands()
: void
{
// $this->commands([]);
}
* Register commands in the format of Command::class
*/
protected function registerCommands()
: void
{
$this->commands([
\Modules\Lpj\Console\Commands\CleanupInspeksiDataCommand::class,
\Modules\Lpj\Console\Commands\CleanupSingleInspeksiCommand::class,
\Modules\Lpj\Console\Commands\CleanupInspeksiStatusCommand::class,
]);
}
/**
* Register command Schedules.
*/
protected function registerCommandSchedules()
: void
{
// $this->app->booted(function () {
// $schedule = $this->app->make(Schedule::class);
// $schedule->command('inspire')->hourly();
// });
}
* Register command Schedules.
*/
protected function registerCommandSchedules()
: void
{
$this->app->booted(function () {
$schedule = $this->app->make(\Illuminate\Console\Scheduling\Schedule::class);
// Jalankan cleanup inspeksi setiap hari jam 2 pagi
$schedule->command('lpj:cleanup-inspeksi --force')
->dailyAt('02:00')
->withoutOverlapping()
->onOneServer()
->runInBackground()
->appendOutputTo(storage_path('logs/cleanup-inspeksi.log'));
// Backup cleanup setiap minggu
$schedule->command('lpj:cleanup-inspeksi --force')
->weekly()
->sundays()
->at('03:00')
->withoutOverlapping()
->onOneServer()
->runInBackground()
->appendOutputTo(storage_path('logs/cleanup-inspeksi-weekly.log'));
});
}
/**
* Register translations.

View File

@@ -0,0 +1,73 @@
<?php
namespace Modules\Lpj\Services;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Laravel\Facades\Image;
class ImageResizeService
{
/**
* Resize an image and store it.
*
* @param string $originalPath
* @param int $width
* @param int|null $height
* @param int $quality
* @return string
*/
public function resize(string $originalPath, ?int $width, ?int $height = null, int $quality = 80): string
{
if (empty($originalPath) || !Storage::disk('public')->exists($originalPath)) {
Log::warning("Image Service: Original path is empty or does not exist: {$originalPath}");
return '';
}
$height = null;
$pathinfo = pathinfo($originalPath);
// Kembali menggunakan direktori 'resized' dan menyertakan dimensi di nama file
$resizedPath = "{$pathinfo['dirname']}/resized/{$pathinfo['filename']}_{$width}x{$height}_{$quality}.{$pathinfo['extension']}";
if (Storage::disk('public')->exists($resizedPath)) {
return $resizedPath;
}
try {
$originalFullPath = Storage::disk('public')->path($originalPath);
$newFullPath = Storage::disk('public')->path($resizedPath);
$image = Image::read($originalFullPath);
// Resize dengan menjaga aspek rasio jika height null
if ($width && $height) {
// Paksa resize ke dimensi yang ditentukan, abaikan aspek rasio
$image->resize($width, $height);
} elseif ($width && !$height) {
// Resize hanya berdasarkan width, tinggi menyesuaikan aspek rasio
$image->scale(width: $width);
} elseif (!$width && $height) {
// Resize hanya berdasarkan height, lebar menyesuaikan aspek rasio
$image->scale(height: $height);
}
if (!Storage::disk('public')->exists(dirname($resizedPath))) {
Storage::disk('public')->makeDirectory(dirname($resizedPath));
}
// Simpan dengan kualitas yang ditentukan
$image->save($newFullPath, $quality);
Log::info("Image Service: Successfully resized {$originalPath} to {$resizedPath} with quality {$quality}%.");
return $resizedPath;
} catch (\Exception $e) {
Log::error("Image Service: Resize failed for {$originalPath}. Error: " . $e->getMessage());
return $originalPath; // Fallback ke gambar asli jika gagal
}
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace Modules\Lpj\Services;
use Illuminate\Support\Facades\Log;
use Modules\Lpj\Jobs\CleanupInspeksiDataJob;
/**
* Service untuk membersihkan data inspeksi yang tidak memiliki dokument_id
*
* Class ini menyediakan method untuk menjalankan cleanup data inspeksi
* ketika ada data baru dengan dokument_id yang sama
*/
class InspeksiCleanupService
{
/**
* Dispatch job untuk cleanup data inspeksi
*
* @param int $permohonanId
* @param int $createdBy
* @param int|null $dokumentId
* @param bool $sync
* @return void
*/
public function cleanupInspeksiData(int $permohonanId, int $createdBy, ?int $dokumentId = null, bool $sync = false): void
{
Log::info('InspeksiCleanupService: Memulai cleanup data inspeksi', [
'permohonan_id' => $permohonanId,
'created_by' => $createdBy,
'dokument_id' => $dokumentId,
'sync' => $sync
]);
try {
$job = new CleanupInspeksiDataJob($permohonanId, $createdBy, $dokumentId);
if ($sync) {
// Jalankan secara synchronous (langsung)
$job->handle();
Log::info('InspeksiCleanupService: Cleanup selesai dijalankan secara sync');
} else {
// Dispatch ke queue
dispatch($job);
Log::info('InspeksiCleanupService: Cleanup job berhasil di-dispatch ke queue');
}
} catch (\Exception $e) {
Log::error('InspeksiCleanupService: Gagal menjalankan cleanup', [
'permohonan_id' => $permohonanId,
'created_by' => $createdBy,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString()
]);
throw $e;
}
}
/**
* Dispatch job untuk cleanup data inspeksi secara async (default)
*
* @param int $permohonanId
* @param int $createdBy
* @param int|null $dokumentId
* @return void
*/
public function cleanupAsync(int $permohonanId, int $createdBy, ?int $dokumentId = null): void
{
$this->cleanupInspeksiData($permohonanId, $createdBy, $dokumentId, false);
}
/**
* Jalankan cleanup data inspeksi secara sync
*
* @param int $permohonanId
* @param int $createdBy
* @param int|null $dokumentId
* @return void
*/
public function cleanupSync(int $permohonanId, int $createdBy, ?int $dokumentId = null): void
{
$this->cleanupInspeksiData($permohonanId, $createdBy, $dokumentId, true);
}
}

View File

@@ -347,6 +347,7 @@ class PreviewLaporanService
$pdf->setPaper('A4', 'portrait');
$pdf->set_option('isHtml5ParserEnabled', true);
$pdf->set_option('isPhpEnabled', true);
$pdf->set_option('dpi', '96');
return $pdf;
}

View File

@@ -22,6 +22,7 @@
"permission": "",
"roles": [
"administrator",
"admin",
"pemohon-ao",
"pemohon-eo",
"DD Appraisal",

View File

@@ -302,9 +302,20 @@
});
// Tambahkan event listener untuk currency format
newNPWRow.querySelectorAll('.currency-format').forEach(input => {
input.addEventListener('input', function() {
formatCurrency(this);
newNPWRow.querySelectorAll('.currency').forEach(input => {
input.addEventListener('change', function() {
window.IMask(this, {
mask: Number, // enable number mask
// other options are optional with defaults below
scale: 0, // digits after point, 0 for integers
thousandsSeparator: ".", // any single char
padFractionalZeros: false, // if true, then pads zeros at end to the length of scale
normalizeZeros: true, // appends or removes zeros at ends
radix: ",", // fractional delimiter
mapToRadix: ["."], // symbols to process as radix
autofix: true,
});
});
});
@@ -355,7 +366,7 @@
class="w-full currency"
name="nilai_npw_${npwCounter}_1"
placeholder="Harga per meter"
value="${npw.nilai_1 || ''}"
value="${npw.nilai_1 || '0'}"
oninput="calculateTotal()">
</label>
</div>
@@ -387,10 +398,36 @@
calculateTotal();
});
// Tambahkan event listener untuk currency format
newNPWRow.querySelectorAll('.currency-format').forEach(input => {
input.addEventListener('input', function() {
formatCurrency(this);
// Initialize currency formatting for existing values
newNPWRow.querySelectorAll('.currency').forEach(input => {
// Apply IMask immediately for existing values
if (input.value && input.value !== '0') {
window.IMask(input, {
mask: Number,
scale: 0,
thousandsSeparator: ".",
padFractionalZeros: false,
normalizeZeros: true,
radix: ",",
mapToRadix: ["."],
autofix: true,
});
}
// Also add blur event for future editing
input.addEventListener('blur', function() {
if (!this.imask) {
window.IMask(this, {
mask: Number,
scale: 0,
thousandsSeparator: ".",
padFractionalZeros: false,
normalizeZeros: true,
radix: ",",
mapToRadix: ["."],
autofix: true,
});
}
});
});
@@ -406,7 +443,7 @@
// Panggil fungsi load NPW saat halaman dimuat
loadSavedNPW();
document.querySelectorAll('.currency-format').forEach(input => {
document.querySelectorAll('.currency').forEach(input => {
input.addEventListener('input', function() {
formatCurrency(this);
});
@@ -492,7 +529,7 @@
const outputElement = row.querySelector('input[id^="nilai_npw_"][id$="_2"]');
if (luasInput && nilaiInput && outputElement) {
const luas = parseInput(luasInput.value);
const luas = parseFloat(luasInput.value.replace(/[^0-9.]/g, '')) || 0;
const nilai = parseInput(nilaiInput.value);
const hasil = luas * nilai;

View File

@@ -6,6 +6,78 @@
@section('content')
<style>
/* Styling untuk sidebar kategori */
.category-sidebar {
background: #f8fafc;
border-radius: 8px;
padding: 1.5rem;
height: fit-content;
}
.category-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem 1rem;
margin: 0.25rem 0;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s ease;
border: 1px solid transparent;
}
.category-item:hover {
background: #e2e8f0;
border-color: #cbd5e1;
}
.category-item.active {
background: #3b82f6;
color: white;
border-color: #2563eb;
}
.category-count {
background: #e2e8f0;
color: #64748b;
padding: 0.25rem 0.5rem;
border-radius: 9999px;
font-size: 0.75rem;
font-weight: 500;
}
.category-item.active .category-count {
background: rgba(255, 255, 255, 0.2);
color: white;
}
.sidebar-title {
font-size: 1.125rem;
font-weight: 600;
margin-bottom: 1rem;
color: #1e293b;
}
/* Loading state */
body.loading {
cursor: wait;
}
body.loading * {
pointer-events: none;
}
@media (max-width: 768px) {
.category-sidebar {
margin-bottom: 1.5rem;
}
.category-item {
padding: 0.5rem 0.75rem;
font-size: 0.875rem;
}
}
@media (max-width: 768px) {
#previewContent {
height: 400px;
@@ -15,7 +87,34 @@
</style>
<div class="flex flex-col gap-7 items-stretch">
<div class="flex flex-col gap-7 lg:flex-row">
<!-- Sidebar Kategori -->
<div class="w-full lg:w-80">
<div class="category-sidebar">
<h3 class="sidebar-title">
<i class="mr-2 ki-filled ki-category"></i>
Kategori
</h3>
<!-- Semua Kategori -->
<div class="category-item {{ !request('category') ? 'active' : '' }}" onclick="filterByCategory('', 'Semua Kategori')">
<span>Semua Kategori</span>
<span class="category-count">{{ $total ?? 0 }}</span>
</div>
<!-- Daftar Kategori -->
@foreach ($categories as $category)
<div class="category-item {{ request('category') == $category->id ? 'active' : '' }}" onclick="filterByCategory({{ $category->id }}, '{{ $category->name }}')">
<span>{{ $category->name }}</span>
<span class="category-count">{{ $category->daftarPustaka_count ?? 0 }}</span>
</div>
@endforeach
</div>
</div>
<!-- Konten Utama -->
<div class="flex-1">
<div class="flex flex-col gap-7 items-stretch">
<div class="flex gap-3 items-center w-full">
<div class="w-full input">
<i class="ki-filled ki-magnifier">
@@ -43,12 +142,6 @@
{{ $total }} items.
</h3>
<div class="flex gap-2.5">
<select id="category_id" name="category_id" class="select tomselect w-[300px]" multiple>
<option value="" selected disabled>Filter by Category</option>
@foreach ($categories as $item)
<option value="{{ $item->id }}">{{ $item->name }}</option>
@endforeach
</select>
<div class="flex toggle-group" data-kt-tabs="true" data-kt-tabs-initialized="true">
<a class="btn btn-icon active selected" data-kt-tab-toggle="#daftar_pustaka_grid" onclick="showGrid()"
href="javascript:void(0)">
@@ -74,8 +167,8 @@
<div class="grid grid-cols-1 gap-4 md:grid-cols-3 lg:grid-cols-4" id="daftar_pustaka_grid">
@if (isset($daftar_pustaka))
@foreach ($daftar_pustaka as $item)
<div class="border shadow-none card">
<a class="show-pustaka h-[300px] bg-gray-200 w-full block" href="{{ route('daftar-pustaka.show', $item->id) }}"
<div class="flex flex-col border shadow-none card">
<a class="show-pustaka h-[150px] bg-gray-200 w-full block" href="{{ route('daftar-pustaka.show', $item->id) }}"
data-url="{{ $item->attachment }}">
<div class="flex overflow-hidden justify-center items-center p-4 w-full h-full">
<div class="flex justify-center items-center text-red-500 rounded">
@@ -84,39 +177,33 @@
</div>
</a>
<div class="card-body">
<a href="{{ route('daftar-pustaka.show', $item->id) }}">
<h3 class="font-medium text-gray-900 cursor-pointer text-md hover:text-primary">
{{ $item->judul }}</h3>
<p class="text-gray-700 text-2sm">
{{-- batasi panjang deskripsi 50 --}}
{{ substr($item->deskripsi, 0, 50) }}
</p>
</a>
<div class="flex gap-2.5 justify-between items-center mt-2">
<p class="text-xs text-gray-700 rounded-full badge badge-xs badge-outline badge-success">
# {{ $item->category->name }}</p>
@auth
@if (auth()->user()->hasRole(['administrator', 'admin']))
<div>
<a class="btn btn-xs btn-danger" onclick="deleteData({{ $item->id }})">
<i class="ki-filled ki-trash">
</i>
Hapus
</a>
<a class="btn btn-xs btn-info"
href="{{ route('daftar-pustaka.edit', $item->id) }}">
<i class="ki-filled ki-pencil">
</i>
Edit
</a>
</div>
@endif
@endauth
<div class="flex flex-col flex-grow p-4 card-body">
<div>
<p class="text-xs text-gray-700 badge badge-xs badge-outline badge-success">
# {{ $item->category->name }}</p>
</div>
<div class="flex-grow mt-2">
<a href="{{ route('daftar-pustaka.show', $item->id) }}">
<h3 class="text-sm font-bold text-gray-900 hover:text-primary">
{{ $item->judul }}</h3>
<p class="text-xs text-gray-700">
{{-- batasi panjang deskripsi 50 --}}
{{ substr($item->deskripsi, 0, 50) }}
</p>
</a>
</div>
@if (auth()->user()->hasRole(['administrator', 'admin']))
<div class="flex gap-2 items-center mt-5">
<a class="w-full text-center btn btn-xs btn-danger" onclick="deleteData({{ $item->id }})">
<i class="ki-filled ki-trash"></i>
Hapus
</a>
<a class="w-full text-center btn btn-xs btn-primary" href="{{ route('daftar-pustaka.edit', $item->id) }}">
<i class="ki-filled ki-pencil"></i>
Edit
</a>
</div>
@endif
</div>
</div>
@endforeach
@@ -143,9 +230,11 @@
</a>
</div>
<a href="{{ route('daftar-pustaka.show', $item->id) }}">
<div class="flex flex-col gap-2 cursor-pointer">
<div class="flex items-center mt-1">
<a class="text-sm font-medium hover:text-primary text-mono leading-5.5">
<div class="flex flex-col cursor-pointer">
<p class="text-xs text-gray-700 badge badge-xs badge-outline badge-success">
# {{ $item->category->name }}</p>
<div class="flex items-center">
<a class="text-sm font-bold hover:text-primary text-mono leading-5.5">
{{ $item->judul }}
</div>
</a>
@@ -161,8 +250,6 @@
</a>
</div>
<div class="flex gap-1.5 items-center">
<p class="text-xs text-gray-700 rounded-full badge badge-sm badge-outline badge-success">
# {{ $item->category->name }}</p>
@auth
@if (auth()->user()->hasRole(['administrator', 'admin']))
<div>
@@ -277,14 +364,18 @@
function filterSearch() {
const search = document.getElementById('search')?.value || '';
const select = document.getElementById('category_id');
const selectedCategories = Array.from(select.selectedOptions).map(option => option.value);
const params = new URLSearchParams(window.location.search);
const categoryParam = selectedCategories.join(',');
if (search) {
params.set('search', search);
} else {
params.delete('search');
}
const url = "{{ route('daftar-pustaka.index') }}?search=" + encodeURIComponent(search) + "&category=" +
encodeURIComponent(categoryParam);
window.location.href = url;
// Reset to first page when searching
params.set('page', '1');
window.location.href = `{{ route('daftar-pustaka.index') }}?${params.toString()}`;
}
@@ -292,5 +383,37 @@
const url = "{{ route('daftar-pustaka.index') }}";
window.location.href = url;
}
function filterByCategory(categoryId, categoryName) {
// Add loading state
document.body.classList.add('loading');
// Update active state
document.querySelectorAll('.category-item').forEach(item => {
item.classList.remove('active');
});
event.currentTarget.classList.add('active');
// Get current search parameter
const search = document.getElementById('search')?.value || '';
// Build URL with category parameter
const params = new URLSearchParams(window.location.search);
if (search) {
params.set('search', search);
}
if (categoryId) {
params.set('category', categoryId);
} else {
params.delete('category');
}
// Reset to first page when filtering
params.set('page', '1');
window.location.href = `{{ route('daftar-pustaka.index') }}?${params.toString()}`;
}
</script>
@endpush

View File

@@ -20,7 +20,7 @@
<td style="padding: 2px; vertical-align: top;">{{ $lingkungan['jarak_jalan_utama'] ?? '-' }}</td>
</tr>
<tr>
<td style="padding: 2px; vertical-align: top;">Jalan Lingkungan</td>
<td style="padding: 2px; vertical-align: top;">Jalan Utama</td>
<td style="padding: 2px; vertical-align: top;">:</td>
<td style="padding: 2px; vertical-align: top;">{{ $lingkungan['jalan_linkungan'] ?? '-' }}</td>

View File

@@ -154,10 +154,12 @@
? $fallbackPath
: $originalPath;
$resizedPath = resize_image($pathToUse, 800, 400, 25);
$filePath =
$statusLpj == 1
? storage_path('app/public/' . $pathToUse)
: asset('storage/' . $pathToUse);
? storage_path('app/public/' . $resizedPath)
: asset('storage/' . $resizedPath);
$extension = strtolower(pathinfo($pathToUse, PATHINFO_EXTENSION));
$isImage = in_array($extension, [
@@ -248,12 +250,16 @@
style="align-content: center; text-align: center; margin-bottom: 20px">
@foreach ($chunkedPhotos as $item)
@php
$originalPath = $item['path'];
$resizedPath = resize_image($originalPath, 800, 400, 25);
$filePath =
$statusLpj == 1
? storage_path('app/public/' . $item['path'])
: asset('storage/' . $item['path']);
? storage_path('app/public/' . $resizedPath)
: asset('storage/' . $resizedPath);
$extension = strtolower(pathinfo($item['path'], PATHINFO_EXTENSION));
$extension = strtolower(pathinfo($originalPath, PATHINFO_EXTENSION));
$isImage = in_array($extension, [
'jpg',
'jpeg',

View File

@@ -582,16 +582,14 @@
</td>
<td width="5%" style="padding: 3px; text-align: center;">X</td>
<td width="25%" style="padding: 3px; text-align:right">
{{ formatRupiah($npw['nilai_1'] ?? 0, 0, false) ?? '' }}
</td>
<td width="5" style="padding: 3px; text-align: center;">
=
{{ number_format((float) str_replace(['Rp', '.', ','], '', $npw['nilai_1'] ?? 0), 0, ',', '.') }}
</td>
<td width="5" style="padding: 3px; text-align: center;">=</td>
<td width="25%" style="padding: 3px; text-align: left; text-align: right;">
{{ formatRupiah($npw['nilai_2'] ?? 0, 0, false) ?? '' }}
{{ number_format((float) str_replace(['Rp', '.', ','], '', $npw['nilai_2'] ?? 0), 0, ',', '.') }}
</td>
</tr>
@php $totalNilaiPasarWajar += str_replace(['Rp', '.'], '', $npw['nilai_2']); @endphp
@php $totalNilaiPasarWajar += str_replace(['Rp', '.', ','], '', $npw['nilai_2'] ?? 0); @endphp
@endforeach
@endif
<tr>

View File

@@ -370,7 +370,6 @@
@endif
@endforeach
@endif
@if (isset($lpjData['npw_tambahan']))
@foreach ($lpjData['npw_tambahan'] as $npw)
<tr>
@@ -382,15 +381,14 @@
</td>
<td width="5%" style="padding: 3px; text-align: center;">X</td>
<td width="25%" style="padding: 3px; text-align:right">
{{ number_format($npw['nilai_1'], 0, ',', '.') ?? '' }}
{{ number_format((float) str_replace(['Rp', '.', ','], '', $npw['nilai_1'] ?? 0), 0, ',', '.') }}
</td>
<td width="5" style="padding: 3px; text-align: center;">=</td>
<td width="25%" style="padding: 3px; text-align: left; text-align: right;">
{{ number_format($npw['nilai_2'], 0, ',', '.') ?? '' }}
{{ number_format((float) str_replace(['Rp', '.', ','], '', $npw['nilai_2'] ?? 0), 0, ',', '.') }}
</td>
</tr>
@php $totalNilaiPasarWajar += $npw['nilai_2']; @endphp
@php $totalNilaiPasarWajar += str_replace(['Rp', '.', ','], '', $npw['nilai_2'] ?? 0); @endphp
@endforeach
@endif

View File

@@ -235,7 +235,7 @@
@php
$statusKey = isset($forminspeksi['asset']['alamat']['sesuai']) ? 'sesuai' : 'tidak sesuai';
$address = $forminspeksi['asset']['alamat'][$statusKey] ?? null;
$cekAlamat = $address ?? '';
@endphp
<div id="alamat_form" class="grid gap-2 mt-5" style="display: none;">

View File

@@ -0,0 +1,272 @@
<?php
namespace Modules\Lpj\Tests\Jobs;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Log;
use Modules\Lpj\Jobs\CleanupInspeksiDataJob;
use Modules\Lpj\Models\Inspeksi;
use Modules\Lpj\Models\Permohonan;
use Modules\Lpj\Models\DokumenJaminan;
use Tests\TestCase;
/**
* Unit test untuk CleanupInspeksiDataJob
*/
class CleanupInspeksiDataJobTest extends TestCase
{
use RefreshDatabase;
protected $permohonan;
protected $dokumenJaminan;
protected $userId = 1;
protected function setUp(): void
{
parent::setUp();
// Setup data test
$this->permohonan = Permohonan::factory()->create();
$this->dokumenJaminan = DokumenJaminan::factory()->create([
'permohonan_id' => $this->permohonan->id
]);
}
/**
* Test cleanup berhasil menghapus data lama tanpa dokument_id
*/
public function test_cleanup_successfully_deletes_old_data_without_dokument_id()
{
// Buat data lama tanpa dokument_id
$oldInspeksi1 = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => null,
'created_by' => $this->userId,
'deleted_at' => null
]);
$oldInspeksi2 = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => null,
'created_by' => $this->userId,
'deleted_at' => null
]);
// Buat data baru dengan dokument_id
$newInspeksi = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => $this->dokumenJaminan->id,
'created_by' => $this->userId,
'deleted_at' => null
]);
// Pastikan data awal ada
$this->assertDatabaseHas('inspeksi', [
'id' => $oldInspeksi1->id,
'deleted_at' => null
]);
$this->assertDatabaseHas('inspeksi', [
'id' => $oldInspeksi2->id,
'deleted_at' => null
]);
$this->assertDatabaseHas('inspeksi', [
'id' => $newInspeksi->id,
'deleted_at' => null
]);
// Jalankan job
$job = new CleanupInspeksiDataJob(
$this->permohonan->id,
$this->userId,
$this->dokumenJaminan->id
);
$job->handle();
// Cek hasil: data lama harus soft deleted
$this->assertSoftDeleted('inspeksi', [
'id' => $oldInspeksi1->id
]);
$this->assertSoftDeleted('inspeksi', [
'id' => $oldInspeksi2->id
]);
// Data baru tetap ada
$this->assertDatabaseHas('inspeksi', [
'id' => $newInspeksi->id,
'deleted_at' => null
]);
}
/**
* Test cleanup tidak menghapus data jika tidak ada data baru dengan dokument_id
*/
public function test_cleanup_does_not_delete_if_no_new_data_with_dokument_id()
{
// Buat data lama tanpa dokument_id
$oldInspeksi = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => null,
'created_by' => $this->userId,
'deleted_at' => null
]);
// Jangan buat data baru dengan dokument_id
// Jalankan job
$job = new CleanupInspeksiDataJob(
$this->permohonan->id,
$this->userId,
null
);
$job->handle();
// Data lama tetap ada (tidak dihapus)
$this->assertDatabaseHas('inspeksi', [
'id' => $oldInspeksi->id,
'deleted_at' => null
]);
}
/**
* Test cleanup tidak menghapus data dengan created_by berbeda
*/
public function test_cleanup_does_not_delete_data_with_different_created_by()
{
$otherUserId = 2;
// Buat data lama dengan created_by berbeda
$oldInspeksi = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => null,
'created_by' => $otherUserId, // User berbeda
'deleted_at' => null
]);
// Buat data baru dengan created_by yang sama dengan job
$newInspeksi = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => $this->dokumenJaminan->id,
'created_by' => $this->userId, // User sama dengan job
'deleted_at' => null
]);
// Jalankan job
$job = new CleanupInspeksiDataJob(
$this->permohonan->id,
$this->userId,
$this->dokumenJaminan->id
);
$job->handle();
// Data lama dengan created_by berbeda tetap ada
$this->assertDatabaseHas('inspeksi', [
'id' => $oldInspeksi->id,
'deleted_at' => null
]);
// Data baru tetap ada
$this->assertDatabaseHas('inspeksi', [
'id' => $newInspeksi->id,
'deleted_at' => null
]);
}
/**
* Test cleanup tidak menghapus data yang sudah di-soft delete
*/
public function test_cleanup_does_not_delete_already_soft_deleted_data()
{
// Buat data lama yang sudah di-soft delete
$oldInspeksi = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => null,
'created_by' => $this->userId,
'deleted_at' => now() // Sudah di-soft delete
]);
// Buat data baru dengan dokument_id
$newInspeksi = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => $this->dokumenJaminan->id,
'created_by' => $this->userId,
'deleted_at' => null
]);
// Jalankan job
$job = new CleanupInspeksiDataJob(
$this->permohonan->id,
$this->userId,
$this->dokumenJaminan->id
);
$job->handle();
// Data lama tetap soft deleted (tidak berubah)
$this->assertSoftDeleted('inspeksi', [
'id' => $oldInspeksi->id
]);
// Data baru tetap ada
$this->assertDatabaseHas('inspeksi', [
'id' => $newInspeksi->id,
'deleted_at' => null
]);
}
/**
* Test job handle exception properly
*/
public function test_job_handles_exception_and_rolls_back()
{
// Buat data lama tanpa dokument_id
$oldInspeksi = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => null,
'created_by' => $this->userId,
'deleted_at' => null
]);
// Buat data baru dengan dokument_id
$newInspeksi = Inspeksi::factory()->create([
'permohonan_id' => $this->permohonan->id,
'dokument_id' => $this->dokumenJaminan->id,
'created_by' => $this->userId,
'deleted_at' => null
]);
// Jalankan job dengan data yang valid
$job = new CleanupInspeksiDataJob(
$this->permohonan->id,
$this->userId,
$this->dokumenJaminan->id
);
// Job seharusnya berhasil dijalankan tanpa exception
$job->handle();
// Cek hasil: data lama harus soft deleted
$this->assertSoftDeleted('inspeksi', [
'id' => $oldInspeksi->id
]);
}
/**
* Test failed method logs error properly
*/
public function test_failed_method_logs_error()
{
// Test bahwa method failed dapat dijalankan tanpa error
$job = new CleanupInspeksiDataJob(
$this->permohonan->id,
$this->userId,
$this->dokumenJaminan->id
);
$exception = new \Exception('Test failure');
// Method failed seharusnya dapat dijalankan
$job->failed($exception);
// Jika tidak ada exception yang di-throw, test dianggap berhasil
$this->assertTrue(true);
}
}