Files
lpj/resources/views/surveyor/js/utils.blade.php

342 lines
12 KiB
PHP

<script>
function showLoadingSwal(message) {
Swal.fire({
title: message,
allowOutsideClick: false,
didOpen: () => {
Swal.showLoading();
}
});
}
function hideLoadingSwal() {
Swal.close();
}
function previewImage(input, imageId) {
const preview = document.getElementById(imageId);
if (input.files && input.files[0]) {
const reader = new FileReader();
reader.onload = function(e) {
preview.src = e.target.result;
preview.classList.remove('hidden');
}
reader.readAsDataURL(input.files[0]);
}
}
function formatNumber(input) {
let value = input.value.replace(/[^\d.]/g, '');
input.value = value;
}
function formatCurrency(value, isDiskon = false) {
// Konversi value ke string, pastikan bukan null/undefined
let stringValue = value === null || value === undefined ? '' : String(value);
// Ganti koma dengan titik untuk memastikan parsing numerik
stringValue = stringValue.replace(/,/g, '.');
// Hapus karakter non-numerik kecuali titik
let numericValue = stringValue.replace(/[^\d.]/g, '');
// Parse nilai numerik
const parsedValue = parseFloat(numericValue);
if (isDiskon) {
// Format untuk diskon
return isNaN(parsedValue) ? '' : parsedValue.toLocaleString('id-ID', {
minimumFractionDigits: 0,
maximumFractionDigits: 2
});
} else {
// Format untuk mata uang tanpa desimal
return isNaN(parsedValue) ? '' : parsedValue.toLocaleString('id-ID', {
minimumFractionDigits: 0,
maximumFractionDigits: 0
});
}
}
function previewImage(input, previewId) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#' + previewId).attr('src', e.target.result).show();
}
reader.readAsDataURL(input.files[0]);
} else {
$('#' + previewId).hide();
}
}
function addClonableItem(containerId, itemClass) {
const container = document.getElementById(containerId);
if (!container) {
console.error(`Container with ID "${containerId}" not found.`);
return;
}
const template = container.querySelector(`.${itemClass}`);
if (!template) {
console.error(`Template with class "${itemClass}" not found in container "${containerId}".`);
return;
}
// Clone the template element
const newElement = template.cloneNode(true);
// Reset all input fields comprehensively
const inputs = newElement.querySelectorAll('input, select, textarea');
inputs.forEach(input => {
// Reset based on input type
switch (input.type) {
case 'text':
case 'number':
case 'email':
case 'tel':
case 'password':
case 'search':
case 'url':
case 'textarea':
input.value = '';
break;
case 'checkbox':
case 'radio':
input.checked = false;
break;
case 'select-one':
case 'select-multiple':
input.selectedIndex = 0;
break;
case 'file':
input.value = '';
break;
}
// Remove any error classes or validation states
input.classList.remove('is-invalid', 'error');
// Reset any custom attributes if needed
input.removeAttribute('data-previous-value');
});
// Reset select elements to their default state
const selects = newElement.querySelectorAll('select');
selects.forEach(select => {
select.selectedIndex = 0;
});
// Make the delete button visible and bind the click event
const deleteButton = newElement.querySelector('.remove-btn');
if (deleteButton) {
deleteButton.style.display = 'inline-block';
deleteButton.addEventListener('click', () => {
newElement.remove();
});
}
// Reset any custom data attributes
newElement.querySelectorAll('[data-clone-reset]').forEach(element => {
const resetValue = element.getAttribute('data-clone-reset');
if (resetValue) {
if (element.tagName === 'INPUT' || element.tagName === 'SELECT' || element.tagName ===
'TEXTAREA') {
element.value = resetValue;
} else {
element.textContent = resetValue;
}
}
});
// Optional: Regenerate unique IDs if needed
const elementsWithId = newElement.querySelectorAll('[id]');
elementsWithId.forEach(element => {
const originalId = element.id;
const newId = `${originalId}_${Date.now()}`;
element.id = newId;
// Update any labels or references
const labels = newElement.querySelectorAll(`label[for="${originalId}"]`);
labels.forEach(label => {
label.setAttribute('for', newId);
});
});
// Append the cloned element to the container
container.appendChild(newElement);
// Optional: Trigger any custom events or reinitialize plugins
const event = new Event('cloneAdded', {
bubbles: true
});
newElement.dispatchEvent(event);
}
async function loadSavedLocationData() {
const provinceCode = '{{ $cekAlamat['province_code'] ?? '' }}';
const cityCode = '{{ $cekAlamat['city_code'] ?? '' }}';
const districtCode = '{{ $cekAlamat['district_code'] ?? '' }}';
const villageCode = '{{ $cekAlamat['village_code'] ?? '' }}';
// Set province
const provinceSelect = document.getElementById('province_code');
if (provinceCode && provinceSelect) {
provinceSelect.value = provinceCode;
await getCity(provinceCode);
}
// Set city
const citySelect = document.getElementById('city_code');
if (cityCode && citySelect) {
citySelect.value = cityCode;
await getDistrict(cityCode);
}
// Set district
const districtSelect = document.getElementById('district_code');
if (districtCode && districtSelect) {
districtSelect.value = districtCode;
await getVillage(districtCode);
}
// Set village
const villageSelect = document.getElementById('village_code');
if (villageCode && villageSelect) {
villageSelect.value = villageCode;
}
}
// Modifikasi fungsi existing
async function getCity(provinceId) {
try {
const response = await fetch(`/locations/cities/province/${provinceId}`);
const data = await response.json();
const cityDropdown = document.getElementById('city_code');
if (cityDropdown) {
cityDropdown.innerHTML = '<option value="">Pilih Kota/Kabupaten</option>';
data.forEach(city => {
const option = document.createElement('option');
option.value = city.code;
option.textContent = city.name;
@if (isset($debitur->city_code))
if (city.code === '{{ $debitur->city_code }}') {
option.selected = true;
}
@endif
cityDropdown.appendChild(option);
});
// Reset dropdown kecamatan dan desa
document.getElementById('district_code').innerHTML = '<option value="">Pilih Kecamatan</option>';
document.getElementById('village_code').innerHTML = '<option value="">Pilih Kelurahan</option>';
}
} catch (error) {
console.error('Error fetching cities:', error);
}
}
// Lakukan hal serupa untuk getDistrict dan getVillage
async function getDistrict(cityId) {
try {
const response = await fetch(`/locations/districts/city/${cityId}`);
const data = await response.json();
const districtDropdown = document.getElementById('district_code');
if (districtDropdown) {
districtDropdown.innerHTML = '<option value="">Pilih Kecamatan</option>';
data.forEach(district => {
const option = document.createElement('option');
option.value = district.code;
option.textContent = district.name;
// Cek apakah ini adalah kecamatan yang sebelumnya dipilih
@if (isset($debitur->district_code))
if (district.code === '{{ $debitur->district_code }}') {
option.selected = true;
}
@endif
districtDropdown.appendChild(option);
});
// Reset dropdown desa
document.getElementById('village_code').innerHTML = '<option value="">Pilih Kelurahan</option>';
}
} catch (error) {
console.error('Error fetching districts:', error);
}
}
async function getVillage(districtId) {
try {
const response = await fetch(`/locations/villages/district/${districtId}`);
const data = await response.json();
const villageDropdown = document.getElementById('village_code');
if (villageDropdown) {
villageDropdown.innerHTML = '<option value="">Pilih Desa/Kelurahan</option>';
data.forEach(village => {
const option = document.createElement('option');
option.value = village.code;
option.textContent = village.name;
// Cek apakah ini adalah desa yang sebelumnya dipilih
@if (isset($debitur->village_code))
if (village.code === '{{ $debitur->village_code }}') {
option.selected = true;
}
@endif
villageDropdown.appendChild(option);
});
}
} catch (error) {
console.error('Error fetching villages:', error);
}
}
function checkLaporan(permohonanId, documentId, inspeksiId, jaminanId, statusLpj) {
// showLoadingSwal('Tunggu...');
fetch(
`{{ url('/penilai/check-laporan') }}?permohonanId=${permohonanId}&documentId=${documentId}&inspeksiId=${inspeksiId}`
)
.then(response => response.json())
.then(data => {
if (data.status) {
// Jika laporan ada, arahkan ke halaman cetak
window.location.href =
`{{ route('penilai.print-out') }}?permohonanId=${permohonanId}&documentId=${documentId}&inspeksiId=${inspeksiId}&jaminanId=${jaminanId}&statusLpj=${statusLpj}&type=${data.status}`;
} else {
// Jika laporan belum ada, tampilkan pesan peringatan
Swal.fire({
title: 'Laporan Belum Ada',
text: 'Silakan isi laporan terlebih dahulu sebelum mencetak.',
icon: 'warning',
confirmButtonText: 'OK',
confirmButtonColor: '#3085d6',
});
}
})
.catch(error => {
console.error('Error:', error);
Swal.fire({
title: 'Terjadi Kesalahan',
text: 'Tidak dapat memproses permintaan. Silakan coba lagi nanti.',
icon: 'error',
confirmButtonText: 'OK',
confirmButtonColor: '#d33',
});
});
}
</script>