Files
lpj/resources/views/surveyor/components/data-pembanding.blade.php
2025-03-07 10:46:24 +07:00

751 lines
32 KiB
PHP

@extends('layouts.main')
@section('breadcrumbs')
{{ Breadcrumbs::render(request()->route()->getName()) }}
@endsection
@section('content')
<div class="w-full grid gap-5 lg:gap-7.5">
<div class="grid gap-5">
<div class="card-grid min-w-full" data-datatable="false" data-datatable-page-size="10"
data-datatable-state-save="false" id="data-table" data-api-url="">
@php
$processedCategories = [];
$tanahBangunanTypes = ['KAPAL', 'PESAWAT', 'KENDARAAN', 'ALAT BERAT', 'MESIN'];
$dokumentName = null;
@endphp
<form id="dataPembandingForm" method="POST" enctype="multipart/form-data" class="grid gap-5">
@csrf
<input type="hidden" name="permohonan_id" value="{{ $permohonan->id }}">
<input type="hidden" name="type" value="tanah">
<input type="hidden" name="dokument_id" value="{{ request('dokument') }}">
<input type="hidden" name="nomor_registrasi" value="{{ $permohonan->nomor_registrasi }}">
<div class="card">
<div class="card-body">
@foreach ($permohonan->debiture->documents as $dokumen)
@if ($dokumen->jenisJaminan)
@php
$dokumentName = $dokumen->jenisJaminan->name;
$formKategori = json_decode($dokumen->jenisJaminan->form_kategori, true);
@endphp
<input type="hidden" name="action"
value="{{ is_array($formKategori) ? implode(',', $formKategori) : $formKategori }}">
@if (!in_array(strtoupper($dokumentName), $tanahBangunanTypes))
@include('lpj::surveyor.components.pembanding-tanah-bangunan-unit')
@else
@include('lpj::surveyor.components.pembanding-kendaraan')
@endif
@endif
@endforeach
</div>
</div>
<div class="card">
<div class="card-body ">
<div class="flex items-baseline flex-wrap lg:flex-nowrap gap-2.5" style="margin: 20px">
<label class="form-label lg:form-label max-w-56 ">Catatan yang Perlu Diperhatikan
</label>
<div class="w-full">
<div id="keterangan-container" class="flex items-baseline flex-wrap gap-2.5 w-full">
<div class="keterangan flex items-center gap-2 mt-2 textarea-group w-full">
<textarea name="keterangan" class="textarea mt-2" placeholder="Masukkan catatan penting" rows="10">{{ $comparisons['keterangan'] ?? old('keterangan') }}</textarea>
<em id="error-keterangan" class="alert text-danger text-sm"></em>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card-footer">
<div class="flex justify-end gap-2">
<button type="button" onclick="submitData()" class="btn btn-primary">
<i class="ki-duotone ki-save-2 fs-2"></i>
Simpan
</button>
</div>
</div>
</form>
</div>
</div>
</div>
@endsection
@push('scripts')
@include('lpj::surveyor.js.utils')
<script>
let columnCount = 1;
// Fungsi calculate prices yang diperbaiki
function calculatePrices(type = 'main', index = null) {
let hargaInput, diskonInput, totalInput, hargaDiskonInput;
// Tentukan input berdasarkan tipe (main atau pembanding)
if (type === 'main') {
// hargaPenawaranInput = document.querySelector('input[name="harga_penawaran"]');
hargaInput = document.querySelector('input[name="harga"]');
diskonInput = document.querySelector('input[name="diskon"]');
totalInput = document.querySelector('input[name="total"]');
} else {
const hargaInputs = document.getElementsByName('harga_pembanding[]');
const diskonInputs = document.getElementsByName('diskon_pembanding[]');
const totalInputs = document.getElementsByName('total_pembanding[]');
// Pastikan index valid
if (index !== null && index < hargaInputs.length) {
// hargaPenawaranInput = hargaPenawarans[index]
hargaInput = hargaInputs[index];
diskonInput = diskonInputs[index];
totalInput = totalInputs[index];
// hargaDiskonInput = hargaDiskonInputs[index];
} else {
return; // Keluar jika index tidak valid
}
}
// Validasi input
if (!hargaInput || !diskonInput || !totalInput) {
return;
}
const harga = parseFloat(hargaInput.value.replace(/[^\d]/g, '') || '0');
let diskonInput_value = diskonInput.value.replace(',', '.');
let diskon = parseFloat(diskonInput_value.replace(/[^\d.]/g, '') || '0');
// Batasi diskon maksimal 100%
diskon = Math.min(diskon, 100);
const total = harga;
const hargaPermeterSetelahDiskon = harga - (harga * (diskon / 100))
console.log(hargaPermeterSetelahDiskon);
// Update nilai dengan format currency
totalInput.value = formatCurrency(hargaPermeterSetelahDiskon.toString());
}
// Update fungsi fillPembandingData
function fillPembandingData(data, index) {
if (!data) return;
function setArrayInputValue(name, value, index) {
const element = document.getElementsByName(name)[index];
if (element) {
if (element.tagName === "SELECT") {
const options = Array.from(element.options);
const optionToSelect = options.find(option => option.value === value);
if (optionToSelect) {
optionToSelect.selected = true;
} else {
element.selectedIndex = 0;
}
} else {
// Format currency untuk input harga
if (name.includes('diskon')) {
element.value = value || '0';
} else {
element.value = value || '';
}
}
}
}
const arrayData = ['KAPAL', 'PESAWAT', 'KENDARAAN', 'ALAT BERAT', 'MESIN'];
const dk = @json($dokumentName);
const normalizedDk = dk.replace(/-/g, ' ').toUpperCase();
// Cek apakah arrayData berisi normalizedDk
const useFirstInputs = arrayData.includes(normalizedDk);
const currentData = Array.isArray(data) ? data[index] : data;
const inputs = useFirstInputs ? {
'nama_pembanding[]': currentData.nama,
'type_pembanding[]': currentData.type,
'warna_pembanding[]': currentData.warna,
'lokasi_pembanding[]': currentData.lokasi,
'sumber_data_pembanding[]': currentData.sumber_data,
'tahun_pembanding[]': currentData.tahun,
'transmisi_pembanding[]': currentData.transmisi,
'tahun_pembuatan_pembanding[]': currentData.tahun_pembuatan,
'merek_buatan_pembanding[]': currentData.merek_buatan,
'kapasitas_pembanding[]': currentData.kapasitas,
'power_pembanding[]': currentData.power,
'kondisi_pembanding[]': currentData.kondisi,
'kordinat_lat_pembanding[]': currentData.kordinat_lat,
'kordinat_lng_pembanding[]': currentData.kordinat_lng,
'address_pembanding[]': currentData.address,
'village_code_pembanding[]': currentData.village_code,
'district_code_pembanding[]': currentData.district_code,
'city_code_pembanding[]': currentData.city_code,
'province_code_pembanding[]': currentData.province_code,
'harga_pembanding[]': currentData.harga,
'harga_diskon_pembanding[]': currentData.harga_diskon,
'total_pembanding[]': currentData.total,
'diskon_pembanding[]': currentData.diskon,
'telepon_pembanding[]': currentData.telepon,
// 'penawaran_pembanding[]': currentData.penawaran
} : {
'jenis_aset_pembanding[]': currentData.jenis_aset,
'luas_tanah_pembanding[]': currentData.luas_tanah,
'luas_bangunan_pembanding[]': currentData.luas_bangunan,
'status_nara_sumber_pembanding[]': currentData.status_nara_sumber,
'nama_nara_sumber_pembanding[]': currentData.nama_nara_sumber,
'kordinat_lat_pembanding[]': currentData.kordinat_lat,
'kordinat_lng_pembanding[]': currentData.kordinat_lng,
'address_pembanding[]': currentData.address,
'village_code_pembanding[]': currentData.village_code,
'district_code_pembanding[]': currentData.district_code,
'city_code_pembanding[]': currentData.city_code,
'province_code_pembanding[]': currentData.province_code,
'harga_pembanding[]': currentData.harga,
'harga_diskon_pembanding[]': currentData.harga_diskon,
'total_pembanding[]': currentData.total,
'diskon_pembanding[]': currentData.diskon,
'hak_properti_pembanding[]': currentData.hak_properti,
'telepon_pembanding[]': currentData.telepon,
// 'penawaran_pembanding[]': currentData.penawaran,
'tanggal_pembanding[]': currentData.tanggal,
// 'harga_penawaran_pembanding[]':currentData.harga_penawaran
};
Object.entries(inputs).forEach(([name, value]) => {
setArrayInputValue(name, value, index);
});
// Handle foto objek
if (data.foto_objek) {
const imageId = `uploadedImage${index + 2}`;
const preview = document.getElementById(imageId);
if (preview) {
preview.src = `/storage/${data.foto_objek}`;
preview.classList.remove('hidden');
}
}
// Handle lokasi secara berurutan
if (data.province_code) {
setTimeout(() => {
getCity(data.province_code, index + 1).then(() => {
if (data.city_code) {
setArrayInputValue('city_code_pembanding[]', data.city_code, index);
getDistrict(data.city_code, index + 1).then(() => {
if (data.district_code) {
setArrayInputValue('district_code_pembanding[]', data
.district_code, index);
getVillage(data.district_code, index + 1).then(() => {
if (data.village_code) {
setArrayInputValue('village_code_pembanding[]',
data.village_code, index);
}
});
}
});
}
});
}, 100);
}
// Hitung harga setelah data terisi
setTimeout(() => calculatePrices(index), 200);
}
// Update event listener untuk input harga dan diskon
function initializePriceCalculation() {
// Event listener untuk input utama
const mainHargaInput = document.querySelector('input[name="harga"]');
// const mainHargaPenawaranInput = document.querySelector('input[name="harga_penawaran"]');
const mainDiskonInput = document.querySelector('input[name="diskon"]');
if (mainHargaInput) {
mainHargaInput.addEventListener('input', () => calculatePrices('main'));
}
// if (mainHargaPenawaranInput) {
// mainHargaPenawaranInput.addEventListener('input', () => calculatePrices('main'));
// }
if (mainDiskonInput) {
mainDiskonInput.addEventListener('input', () => calculatePrices('main'));
}
// Event listener untuk input pembanding
const pembandingHargaInputs = document.getElementsByName('harga_pembanding[]');
// const pembandingHargaPenawaranInput = document.getElementsByName('harga_penawaran_pembanding[]');
const pembandingDiskonInputs = document.getElementsByName('diskon_pembanding[]');
pembandingHargaInputs.forEach((input, index) => {
input.addEventListener('input', () => calculatePrices('pembanding', index));
});
// pembandingHargaPenawaranInput.forEach((input, index) => {
// input.addEventListener('input', () => calculatePrices('pembanding', index));
// });
pembandingDiskonInputs.forEach((input, index) => {
input.addEventListener('input', () => calculatePrices('pembanding', index));
});
}
document.addEventListener('DOMContentLoaded', function() {
try {
const inspectionData = {!! isset($inspectionData) ? json_encode($inspectionData) : 'null' !!};
const comparisons = {!! isset($comparisons) ? json_encode($comparisons) : 'null' !!};
console.log('inspectionData:', inspectionData);
console.log('comparisons:', comparisons);
initializeFirstPembandingListeners();
ensureLocationEventListeners();
initializePriceCalculation();
if (comparisons) {
comparisons.data_pembanding.forEach((comparison, index) => {
if (index > 0) {
addColumn();
}
fillPembandingData(comparison, index);
});
}
updateRemoveButtonVisibility();
initializeEventListeners();
} catch (error) {
console.error('Error initializing form:', error);
}
});
function addColumn() {
columnCount++;
const table = document.getElementById('dataTable');
const headerRow = table.querySelector('thead tr');
const bodyRows = table.querySelectorAll('tbody tr');
const newHeader = document.createElement('th');
newHeader.className = 'px-4 py-3 min-w-[250px]';
newHeader.textContent = `Data Pembanding ${columnCount}`;
headerRow.appendChild(newHeader);
bodyRows.forEach(row => {
const newCell = document.createElement('td');
newCell.className = 'px-4 py-2';
const firstInputCell = row.querySelector('td:last-child');
if (firstInputCell) {
const clonedContent = firstInputCell.innerHTML;
newCell.innerHTML = clonedContent;
const inputs = newCell.querySelectorAll('input, select, textarea');
inputs.forEach((input) => {
if (input.type === 'file') {
const newImageId = `uploadedImage${columnCount + 1}`;
const preview = newCell.querySelector('img');
if (preview) {
preview.id = newImageId;
preview.src = '';
preview.accept = ".jpg,.jpeg,.png";
preview.classList.add('hidden');
input.onchange = function() {
const file = this.files[0];
if (file) {
const validExtensions = ['image/jpeg', 'image/png', 'image/gif',
'image/webp'
];
if (validExtensions.includes(file.type)) {
previewImage(this, newImageId);
} else {
Swal.fire({
icon: 'error',
title: 'Format Tidak Didukung',
text: 'Hanya file gambar dengan format JPG, PNG, GIF, atau WEBP yang diperbolehkan.',
position: 'top-end',
toast: true,
showConfirmButton: false,
timer: 3000,
timerProgressBar: true
});
this.value = '';
}
}
};
}
}
if (input.tagName === 'SELECT') {
const baseId = input.id.replace(/_\d+$/, '').replace('_pembanding', '');
const newId = `${baseId}_pembanding_${columnCount}`;
input.id = newId;
if (input.name.includes('jenis_aset')) {
const originalOptions = document.querySelector(
'select[name="jenis_aset_pembanding[]"]').innerHTML;
input.innerHTML = originalOptions;
} else if (!input.id.includes('province')) {
// Reset opsi untuk select lokasi
input.innerHTML = `<option value="">Pilih ${
input.id.includes('city') ? 'Kota/Kabupaten' :
input.id.includes('district') ? 'Kecamatan' :
'Desa/Kelurahan'
}</option>`;
}
if (input.id.includes('province')) {
input.onchange = function() {
handleProvinceChange(this);
};
} else if (input.id.includes('city')) {
input.onchange = function() {
handleCityChange(this);
};
} else if (input.id.includes('district')) {
input.onchange = function() {
handleDistrictChange(this);
};
}
}
if (input.type !== 'file' && input.tagName !== 'SELECT') {
input.value = '';
}
if (input.classList.contains('currency-format')) {
input.addEventListener('input', function() {
handleCurrencyInput(this);
// Calculate prices if needed
if (input.name.includes('harga_pembanding') ||
input.name.includes('diskon_pembanding')) {
const inputs = document.getElementsByName(input.name);
const index = Array.from(inputs).indexOf(this);
calculatePrices('pembanding', index);
}
});
}
// Specific handling for discount to limit to 100%
if (input.name.includes('diskon_pembanding')) {
input.addEventListener('input', function() {
let value =
this.value = value.toString();
});
}
});
}
row.appendChild(newCell);
});
initializePriceCalculation();
updateRemoveButtonVisibility();
}
function handleCurrencyInput(input) {
const value = input.value.replace(/[^\d]/g, '');
input.value = formatCurrency(value);
}
function removeColumn() {
if (columnCount > 1) {
const table = document.getElementById('dataTable');
const rows = table.querySelectorAll('tr');
rows.forEach(row => {
row.deleteCell(-1);
});
columnCount--;
updateRemoveButtonVisibility();
}
}
function updateRemoveButtonVisibility() {
const removeBtn = document.getElementById('removeColumnBtn');
if (removeBtn) {
removeBtn.style.display = columnCount > 1 ? 'inline-flex' : 'none';
}
}
function initializeEventListeners() {
document.getElementById('addColumnBtn').addEventListener('click', addColumn);
document.getElementById('removeColumnBtn').addEventListener('click', removeColumn);
reinitializeEventListeners();
}
function reinitializeEventListeners() {
// Event listener yang sudah ada
document.querySelectorAll('.currency-format').forEach(input => {
input.addEventListener('input', function() {
formatCurrency(this);
});
});
document.querySelectorAll('.number-format').forEach(input => {
input.addEventListener('input', function() {
formatNumber(this);
});
});
// Tambahkan kalkulasi harga
initializePriceCalculation();
// Location event listeners
ensureLocationEventListeners();
}
function initializeCurrencyFormat() {
document.querySelectorAll('.currency-format').forEach(input => {
input.addEventListener('input', function() {
formatCurrency(this);
});
});
}
function initializeFirstPembandingListeners() {
const firstProvinceSelect = document.getElementById('province_code_pembanding');
if (firstProvinceSelect) {
firstProvinceSelect.addEventListener('change', function() {
const provinceId = this.value;
if (provinceId) {
getCity(provinceId, 1);
}
});
}
const firstCitySelect = document.getElementById('city_code_pembanding');
if (firstCitySelect) {
firstCitySelect.addEventListener('change', function() {
const cityId = this.value;
if (cityId) {
getDistrict(cityId, 1);
}
});
}
const firstDistrictSelect = document.getElementById('district_code_pembanding');
if (firstDistrictSelect) {
firstDistrictSelect.addEventListener('change', function() {
const districtId = this.value;
if (districtId) {
getVillage(districtId, 1);
}
});
}
}
function ensureLocationEventListeners() {
document.querySelectorAll('[id^="province_code_pembanding"]').forEach(select => {
select.onchange = function() {
handleProvinceChange(this);
};
});
document.querySelectorAll('[id^="city_code_pembanding"]').forEach(select => {
select.onchange = function() {
handleCityChange(this);
};
});
document.querySelectorAll('[id^="district_code_pembanding"]').forEach(select => {
select.onchange = function() {
handleDistrictChange(this);
};
});
}
function handleProvinceChange(provinceSelect) {
const provinceId = provinceSelect.value;
let columnIndex;
if (provinceSelect.id === 'province_code_pembanding') {
columnIndex = 1;
} else {
columnIndex = provinceSelect.id.split('_').pop();
}
if (provinceId) {
getCity(provinceId, columnIndex);
}
}
function handleCityChange(citySelect) {
const cityId = citySelect.value;
let columnIndex;
if (citySelect.id === 'city_code_pembanding') {
columnIndex = 1;
} else {
columnIndex = citySelect.id.split('_').pop();
}
if (cityId) {
getDistrict(cityId, columnIndex);
}
}
function handleDistrictChange(districtSelect) {
const districtId = districtSelect.value;
let columnIndex;
if (districtSelect.id === 'district_code_pembanding') {
columnIndex = 1;
} else {
columnIndex = districtSelect.id.split('_').pop();
}
if (districtId) {
getVillage(districtId, columnIndex);
}
}
async function getCity(provinceId, columnIndex) {
try {
const response = await fetch(`/locations/cities/province/${provinceId}`);
const data = await response.json();
const cityDropdown = columnIndex === 1 ?
document.getElementById('city_code_pembanding') :
document.getElementById(`city_code_pembanding_${columnIndex}`);
if (cityDropdown) {
cityDropdown.innerHTML = '<option value="">Pilih Kota/Kabupaten</option>';
data.forEach(city => {
cityDropdown.innerHTML += `<option value="${city.code}">${city.name}</option>`;
});
}
} catch (error) {
console.error('Error fetching cities:', error);
}
}
async function getDistrict(cityId, columnIndex) {
try {
const response = await fetch(`/locations/districts/city/${cityId}`);
const data = await response.json();
const districtDropdown = columnIndex === 1 ?
document.getElementById('district_code_pembanding') :
document.getElementById(`district_code_pembanding_${columnIndex}`);
if (districtDropdown) {
districtDropdown.innerHTML = '<option value="">Pilih Kecamatan</option>';
data.forEach(district => {
districtDropdown.innerHTML +=
`<option value="${district.code}">${district.name}</option>`;
});
}
} catch (error) {
console.error('Error fetching districts:', error);
}
}
async function getVillage(districtId, columnIndex) {
try {
const response = await fetch(`/locations/villages/district/${districtId}`);
const data = await response.json();
const villageDropdown = columnIndex === 1 ?
document.getElementById('village_code_pembanding') :
document.getElementById(`village_code_pembanding_${columnIndex}`);
if (villageDropdown) {
villageDropdown.innerHTML = '<option value="">Pilih Desa/Kelurahan</option>';
data.forEach(village => {
villageDropdown.innerHTML += `<option value="${village.code}">${village.name}</option>`;
});
}
} catch (error) {
console.error('Error fetching villages:', error);
}
}
function submitData() {
showLoadingSwal('Mengirim data ke server...');
const form = document.querySelector('form');
const formData = new FormData(form);
console.log('Form data entries:', Array.from(formData.entries()));
$.ajax({
url: '{{ route('surveyor.storeDataPembanding') }}',
type: 'POST',
data: formData,
processData: false,
contentType: false,
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
success: function(result) {
hideLoadingSwal();
console.log(result);
if (result.success) {
Swal.fire({
title: 'Berhasil!',
text: result.message,
icon: 'success',
confirmButtonText: 'OK'
}).then((result) => {
if (result.isConfirmed) {
if ("{{ Request::is('penilai/show-data-pembanding/*/edit') }}") {
console.log(
'Current route matches');
} else {
window.location.href =
"{{ route('surveyor.show', ['id' => $permohonan->id]) }}";
}
}
});
} else {
Swal.fire({
title: 'Error!',
text: result.message || 'Terjadi kesalahan',
icon: 'error',
confirmButtonText: 'OK'
});
}
},
error: function(xhr, status, error) {
hideLoadingSwal();
console.error('Error:', error);
Swal.fire({
title: 'Error!',
text: 'Terjadi kesalahan pada server',
icon: 'error',
confirmButtonText: 'OK'
});
}
});
}
document.addEventListener('DOMContentLoaded', function() {
// Initialize currency format for existing inputs
document.querySelectorAll('.currency-format').forEach(input => {
input.addEventListener('input', function() {
handleCurrencyInput(this);
});
// Format initial values if they exist
if (input.value) {
input.value = formatCurrency(input.value);
}
});
});
</script>
@endpush