// HTML include another HTML // <------------------- Time Zone FUNCTION ---------------------- > function convertToPreferredTimezone(dateString, format = "YYYY-MM-DD hh:mm:ss A") { if (!dateString) return ""; const tzMapping = { "IST": "Asia/Kolkata", "CST": "America/Chicago" }; let preferredTZ = localStorage.getItem("preferredTimezone"); if (!preferredTZ || !tzMapping[preferredTZ]) { preferredTZ = "CST"; } const backendTime = moment.tz(dateString, "America/Chicago"); return backendTime.clone().tz(tzMapping[preferredTZ]).format(format); } // function showBothTimezones(dateString, format = "YYYY-MM-DD hh:mm:ss A") { // if (!dateString) return ""; // const tzMapping = { // "IST": "Asia/Kolkata", // "CST": "America/Chicago" // }; // let preferredTZ = localStorage.getItem("preferredTimezone"); // if (!preferredTZ || !tzMapping[preferredTZ]) { // preferredTZ = "CST"; // default agar kuch select nahi kiya // } // // Backend time is always in CST // const cstTime = moment.tz(dateString, tzMapping["CST"]); // const istTime = cstTime.clone().tz(tzMapping["IST"]); // let firstLine = ""; // let secondLine = ""; // if (preferredTZ === "IST") { // firstLine = `${cstTime.format(format)} (CST)`; // secondLine = `${istTime.format(format)} (IST)`; // } else if (preferredTZ === "CST") { // firstLine = `${istTime.format(format)} (IST)`; // secondLine = `${cstTime.format(format)} (CST)`; // } // return `${firstLine}
${secondLine}`; // } // <---------------------- Time Zone Code END --------------------> let vendorIdLeads; function includeHTML() { var z, i, elmnt, file, xhttp; /*loop through a collection of all HTML elements:*/ z = document.getElementsByTagName("*"); for (i = 0; i < z.length; i++) { elmnt = z[i]; /*search for elements with a certain attribute:*/ file = elmnt.getAttribute("w3-include-html"); if (file) { /*make an HTTP request using the attribute value as the file name:*/ xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200) { elmnt.innerHTML = this.responseText; } if (this.status == 404) { elmnt.innerHTML = "Page not found."; } /*remove the attribute, and call this function once more:*/ elmnt.removeAttribute("w3-include-html"); includeHTML(); } } xhttp.open("GET", file, true); xhttp.send(); /*exit the function:*/ return; } } }; function myIP() { if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest(); else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); xmlhttp.open("GET", "http://api.hostip.info/get_html.php", false); xmlhttp.send(); hostipInfo = xmlhttp.responseText.split("\n"); for (i = 0; hostipInfo.length >= i; i++) { ipAddress = hostipInfo[i].split(":"); if (ipAddress[0] == "IP") return ipAddress[1]; } return false; } // this ajax works on submit button in rental application form(Unsecured page) function submitApplicationForm(baseurl, appID, status) { //for property var propertyID = $("#propertyId").val(); var type = $("#type").val(); var squareFeet = $("#squareFeet").val(); var bedrooms = $("#bedrooms").val(); var bathrooms = $("#bathrooms").val(); var rentAmount = $("#rentAmount").val(); var streetAddress = $("#streetAddress").val(); var houseNo = $("#houseNo").val(); var city = $("#city").val(); var state = $("#state").val(); var zip = $("#zip").val(); var country = $("#country").val(); var pets = $("#pets").val(); var carParking = $("#carParking").val(); var carParkingType = $("#carParkingType").val(); var rentalRate = $("#rentalRate").val(); var furnishing = $("#furnishing").val(); var ip = $("#ipaddress").val(); //for applicant details var fullName = $("#fullName").val(); var dob = $("#dob").val(); var email = $("#mail").val(); var phoneNo = $("#phone_no").val(); var ssn = $("#ssn").val(); var emergencyContact = $("#emergencyContact").val(); var verification = $("#verify").val(); var emergencyContactName = $("#emergencyContact_name").val(); var emergencyContactRelationship = $("#emergencyContact_relationship").val(); //for applicant vehicle details var vehicleNumber = document.querySelectorAll('[id^="vehicleFields_"]').length; var veh_arr = []; for (var i = 1; i <= vehicleNumber; i++) { var vehicleRegistrationNumber = $("#vehicleRegistrationNumber_" + i).val(); var vehicleType = $("#vehicleType_" + i).val(); var vehicleModel = $("#vehicleModel_" + i).val(); var vehicleColor = $("#vehicleColor_" + i).val(); var vehicle = { "model": vehicleModel, "registration_number": vehicleRegistrationNumber, "vehicle_color": vehicleColor, "vehicle_type": vehicleType }; veh_arr.push(vehicle); } // For Lease Details var startDate = $("#startDate").val(); var endDate = $("#endDate").val(); //for current employment details var currentcompany = $("#current_company").val(); var currentoccupation = $("#current_occupation").val(); var currentduration = $("#current_duration").val(); var currentincome = $("#current_income").val(); var currentsupervisor = $("#current_supervisor").val(); var currentofficeaddress = $("#current_office_address").val(); var currentcompanyphone = $("#current_company_phoneNo").val(); var currentcompanymail = $("#current_company_mail").val(); var currentcompanycity = $("#current_company_city").val(); var currentcompanystate = $("#current_company_state").val(); var currentzip = $("#current_zip").val(); var currentcompanycountry = $("#current_company_country").val(); //for previous employment details var previouscompany = $("#previous_company").val(); var previousoccupation = $("#previous_occupation").val(); var previousduration = $("#previous_duration").val(); var previousincome = $("#previous_income").val(); var previoussupervisor = $("#previous_supervisor").val(); var previousofficeaddress = $("#previous_office_address").val(); var previouscompanyphone = $("#previous_company_contact").val(); var previouscompanymail = $("#previous_company_mail").val(); var previouscompanycity = $("#previous_company_city").val(); var previouscompanystate = $("#previous_company_state").val(); var previouszip = $("#previous_zip").val(); var previouscompanycountry = $("#previous_company_country").val(); // for personal reference var personalreferencename = $("#personalref_fullname").val(); var personalreferencerelationship = $("#personalref_relationship").val(); var personalreferencephone = $("#personalref_phone").val(); var personalreferencemail = $("#personalref_mail").val(); //for current landlord var currentlandlordname = $("#current_landlord_name").val(); var currentlandlordaddress = $("#current_landlord_address").val(); var currentlandlordphone = $("#current_landlord_phoneNo").val(); var currentlandlordmail = $("#current_landlord_mail").val(); // for previous landlord-1 var prevLandlordname = $("#previous_landlord1_name").val(); var prevLandlordaddress = $("#previous_landlord1_address").val(); var prevLandlordphone = $("#previous_landlord1_phone").val(); var prevLandlordmail = $("#previous_landlord1_mail").val(); // for previous landlord-2 var previousLandlordname = $("#previous_landlord_name").val(); var previousLandlordaddress = $("#previous_landlord_address").val(); var previousLandlordphone = $("#previous_landlord_phone").val(); var previousLandlordmail = $("#previous_landlord_mail").val(); //for current residence var currentresidencetype = $("#current_residence_type").val(); var currentresidencesqFeet = $("#current_residence_sqFeet").val(); var currentresidencebedrooms = $("#current_residence_bedrooms").val(); var currentresidencerentamount = $("#current_residence_rent").val(); var currentresidenceaddress = $("#current_residence_houseNo").val(); var currentresidencestreet = $("#current_residence_street").val(); var currentresidencecity = $("#current_residence_city").val(); var currentresidencestate = $("#current_residence_state").val(); var currentresidencezip = $("#current_residence_zip").val() var currentresidencecountry = $("#current_residence_country").val(); var currentresidenceduration = $("#current_residence_duration").val(); var currentleaseExpiry = $("#current_lease_expiry").val(); var reasonformoving = $("#reason_for_moving").val(); //for previous residence-1 var previousresidencetype = $("#previous_residence_type").val(); var previousresidencesqFeet = $("#previous_residence_sqFeet").val(); var previousresidencebedrooms = $("#previous_residence_bedrooms").val(); var previousresidencerentamount = $("#previous_residence_rent").val(); var previousresidenceaddress = $("#previous_residence_houseNo").val(); var previousresidencestreet = $("#previous_residence_address").val(); var previousresidencecity = $("#previous_residence_city").val(); var previousresidencestate = $("#previous_residence_state").val(); var previousresidencezip = $("#previous_residence_zip").val(); var previousresidencecountry = $("#previous_residence_country").val(); var previousresidenceduration = $("#previous_residence_duration").val(); var previousresidenceStartDate = $("#previous_residence_startDate").val(); var previousresidenceEndDate = $("#previous_residence_endDate").val(); //for previous residence-2 var previousresidence2type = $("#previous_residence2_type").val(); var previousresidences2sqFeet = $("#previous_residence2_sqFeet").val(); var previousresidence2bedrooms = $("#previous_residence2_bedrooms").val(); var previousresidence2rentamount = $("#previous_residence2_rent").val(); var previousresidence2address = $("#previous_residence2_houseNo").val(); var previousresidence2street = $("#previous_residence2_street").val(); var previousresidence2city = $("#previous_residence2_city").val(); var previousresidence2state = $("#previous_residence2_state").val(); var previousresidence2zip = $("#previous_residence2_zip").val(); var previousresidence2country = $("#previous_residence2_country").val(); var previousresidence2StartDate = $("#previous_residence2_startDate").val(); var previousresidence2EndDate = $("#previous_residence2_endDate").val(); var idInput = document.getElementById('identityDoc'); var input = document.getElementById('employmentDoc'); if (!idInput) { var fileSize = idInput.files[0].size; // CHECKING FOR FILE SIZE if (fileSize > 2097152) { document.getElementById('identityDoc').focus(); $('#id_error').html("File size shoud be less than 2MB"); return false; } var file = idInput.files[0]; // CHECKING FOR FILE EXTENSION if (/\.(pdf)$/i.test(file.name) === false) { document.getElementById('identityDoc').focus(); $('#id_error').html("Only PDF is allowed"); return false; } } if (!input) { // CHECKING FOR FILE SIZE if (input.files[0].size > 2097152) { document.getElementById('employmentDoc').focus(); $('#letter_error').html("File size shoud be less than 2MB"); return false; } // CHECKING FOR FILE EXTENSION var file = input.files[0]; if (/\.(pdf)$/i.test(file.name) === false) { document.getElementById('employmentDoc').focus(); $('#letter_error').html("Only PDF is allowed"); return false; } } document.getElementById('letter_error').innerHTML = ''; document.getElementById('id_error').innerHTML = ''; document.getElementById('pre_residence_endDate_error').innerHTML = ''; document.getElementById('pre_residence2_endDate_error').innerHTML = ''; if (previousresidenceStartDate != null && previousresidenceStartDate != "" && previousresidenceEndDate != null && previousresidenceEndDate != "") { if (previousresidenceStartDate >= previousresidenceEndDate) { document.getElementById("pre_residence_endDate_error").innerHTML = "Date should be less than End Date"; document.getElementById("previous_residence_endDate").focus(); return false; } } // console.log(previousresidenceEndDate); if (previousresidence2StartDate != null && previousresidence2StartDate != "" && previousresidence2EndDate != null && previousresidence2EndDate != "") { if (previousresidence2StartDate >= previousresidence2EndDate) { document.getElementById("pre_residence2_endDate_error").innerHTML = "Date should be less than End Date"; document.getElementById("previous_residence2_endDate").focus(); return false; } } if (!fullName) { var error = document.getElementById("name_applicants"); error.innerHTML = "This field is mandatory"; document.getElementById('fullName').focus(); return false; } else { document.getElementById("name_applicants").innerHTML = ""; } if (!emergencyContact) { var error = document.getElementById("error_emergencyContact"); error.innerHTML = "This field is mandatory"; document.getElementById('emergencyContact').focus(); return false; } else { document.getElementById("error_emergencyContact").innerHTML = ""; } if (!emergencyContactName) { var error = document.getElementById("emergencyContact_name_error"); error.innerHTML = "This field is mandatory"; document.getElementById('emergencyContact_name').focus(); return false; } else { document.getElementById("emergencyContact_name_error").innerHTML = ""; } if (startDate == "" || startDate == null) { document.getElementById("applicantStartDate").innerHTML = "This Field is Mandatory"; document.getElementById("startDate").focus(); return false; } else { document.getElementById("applicantStartDate").innerHTML = ""; } if (endDate) { if (endDate <= startDate) { document.getElementById("applicantEndDate").innerHTML = "Invalid Date"; document.getElementById("endDate").focus(); return false; } } var termsCheckBox = document.getElementById("more"); var termsLabel = document.getElementById("term_label"); if (!termsCheckBox.checked) { document.getElementById("term_label").focus(); document.getElementById("check_box_error").innerHTML = "Please select the checkbox if you want to submit form " termsLabel.style.backgroundColor = "yellow"; $('#errorModal').modal('show'); return false; } if (document.getElementById("vehicleYes").checked) { var registrationNumber = document.getElementById("vehicleRegistrationNumber_1").value; var vehicleType = document.getElementById("vehicleType_1").value; var vehicleModel = document.getElementById("vehicleModel_1").value; var errorSpan = document.getElementById("vehicles_error"); if (registrationNumber === '' || vehicleType === '' || vehicleModel === '') { errorSpan.textContent = "Please fill in the mandatory fields."; if (registrationNumber === '' && vehicleType === '' && vehicleModel === '') { document.getElementById("vehicleRegistrationNumber_1").focus(); } else if (vehicleType === '' && vehicleModel === '') { document.getElementById("vehicleType_1").focus(); } else if (vehicleModel === '' && registrationNumber === '') { document.getElementById("vehicleRegistrationNumber_1").focus(); } else if (registrationNumber === '') { document.getElementById("vehicleRegistrationNumber_1").focus(); } else if (vehicleType === '') { document.getElementById("vehicleType_1").focus(); } else { document.getElementById("vehicleModel_1").focus(); } return false; } else { errorSpan.textContent = ""; } } var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } var path; // console.log(status); if (!status) { path = "/rentalunsecured/submitapplication?appID=" + appID + "&ip=" + ip; } else { path = "/rentalunsecured/saveapplication?appID=" + appID; } xmlhttp1.open("POST", baseurl + path, false); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "" && this.readyState == 4) { var res = JSON.parse(this.responseText); var loginRes = res.response; // console.log(res.rspnsMsg); var s = res.rspnsMsg; var s = s.replace(/[{}]/g, ""); let pairs = s.split(', ') let obj = pairs.reduce((obj, data) => { let [k, v] = data.split('=') obj[k] = v return obj }, {}) // this is to clear errors below fields once the user inputs correct values document.getElementById('name_applicants').innerHTML = ''; document.getElementById('phone_applicants').innerHTML = ''; document.getElementById('dob_applicants').innerHTML = ''; document.getElementById('email_applicants').innerHTML = ''; document.getElementById('ssn_applicants').innerHTML = ''; document.getElementById('error_emergencyContact').innerHTML = ''; document.getElementById('emergencyContact_name_error').innerHTML = ''; document.getElementById('emergencyContact_error_rel').innerHTML = ''; document.getElementById('curr_company').innerHTML = ''; document.getElementById('curr_occupation').innerHTML = ''; document.getElementById('curr_income').innerHTML = ''; document.getElementById('curr_supervisor').innerHTML = ''; document.getElementById('curr_office_address').innerHTML = ''; document.getElementById('curr_company_phoneNo').innerHTML = ''; document.getElementById('curr_company_mail').innerHTML = ''; document.getElementById('curr_company_city').innerHTML = ''; document.getElementById('curr_company_state').innerHTML = ''; document.getElementById('curr_zip').innerHTML = ''; document.getElementById('curr_company_country').innerHTML = ''; // document.getElementById('curr_duration').innerHTML=''; document.getElementById('pre_company').innerHTML = ''; document.getElementById('pre_occupation').innerHTML = ''; document.getElementById('pre_income').innerHTML = ''; document.getElementById('pre_supervisor').innerHTML = ''; document.getElementById('pre_office_address').innerHTML = ''; document.getElementById('pre_company_contact').innerHTML = ''; document.getElementById('pre_company_mail').innerHTML = ''; document.getElementById('pre_company_city').innerHTML = ''; document.getElementById('pre_company_state').innerHTML = ''; document.getElementById('pre_company_country').innerHTML = ''; // document.getElementById('pre_duration').innerHTML=''; document.getElementById('curr_landlord_name').innerHTML = ''; document.getElementById('curr_landlord_address').innerHTML = ''; document.getElementById('curr_landlord_phoneNo').innerHTML = ''; document.getElementById('curr_landlord_mail').innerHTML = ''; document.getElementById('pre_landlord-1_name').innerHTML = ''; document.getElementById('pre_landlord-1_address').innerHTML = ''; document.getElementById('pre_zip').innerHTML = ''; document.getElementById('pre_landlord-1_phone').innerHTML = ''; document.getElementById('pre_landlord-1_mail').innerHTML = ''; document.getElementById('pre_landlord_name').innerHTML = ''; document.getElementById('pre_landlord_address').innerHTML = ''; document.getElementById('pre_landlord_phoneNo').innerHTML = ''; document.getElementById('pre_landlord_mail').innerHTML = ''; document.getElementById('personal_fullname').innerHTML = ''; document.getElementById('personal_relationship').innerHTML = ''; document.getElementById('personal_phone').innerHTML = ''; document.getElementById('personal_mail').innerHTML = ''; document.getElementById('pre_residence-1_zip').innerHTML = ''; document.getElementById('pre_residence-1_city').innerHTML = ''; document.getElementById('pre_residence-1_sqFeet').innerHTML = ''; document.getElementById('pre_residence-1_rent').innerHTML = ''; document.getElementById('pre_residence-1_houseNo').innerHTML = ''; document.getElementById('pre_residence-1_street').innerHTML = ''; document.getElementById('pre_residence-1_state').innerHTML = ''; document.getElementById('pre_residence-1_country').innerHTML = ''; document.getElementById('pre_residence_zip').innerHTML = ''; document.getElementById('pre_residence_city').innerHTML = ''; document.getElementById('pre_residence_sqFeet').innerHTML = ''; document.getElementById('pre_residence_rent').innerHTML = ''; document.getElementById('pre_residence_houseNo').innerHTML = ''; document.getElementById('pre_residence_address').innerHTML = ''; document.getElementById('pre_residence_state').innerHTML = ''; document.getElementById('pre_residence_country').innerHTML = ''; document.getElementById('curr_residence_zip').innerHTML = ''; document.getElementById('curr_residence_city').innerHTML = ''; document.getElementById('curr_residence_sqFeet').innerHTML = ''; document.getElementById('curr_residence_rent').innerHTML = ''; document.getElementById('curr_residence_houseNo').innerHTML = ''; document.getElementById('curr_residence_address').innerHTML = ''; document.getElementById('curr_residence_state').innerHTML = ''; document.getElementById('curr_residence_country').innerHTML = ''; // APPLICANTS DETAILS document.getElementById("fullName").addEventListener("input", myFunction); function myFunction() { document.getElementById("name_applicants").style.visibility = "hidden"; } if (fullName == null || fullName == "") { document.getElementById("name_applicants").style.visibility = "visible"; var error = document.getElementById("name_applicants"); error.innerHTML = "This field is mandatory"; document.getElementById('fullName').focus(); return false; } else if (obj["applicant.fullName"] == "Invalid Name!!") { var error = document.getElementById("name_applicants"); error.innerHTML = obj["applicant.fullName"]; document.getElementById('fullName').focus(); return false; } // if (dob == null || dob == "") { // var error = document.getElementById("dob_applicants"); // error.innerHTML = "This field is mandatory"; // document.getElementById('dob').focus(); // return false; // } if (obj["applicant.DOB"] == "Invalid DOB!!") { var error = document.getElementById("dob_applicants"); error.innerHTML = obj["applicant.DOB"]; document.getElementById('dob').focus(); return false; } if (email == null || email == "") { var error = document.getElementById("email_applicants"); error.innerHTML = "This field is mandatory"; document.getElementById('mail').focus(); return false; } else if (obj["applicant.emailID"] == "Invalid email!!") { var error = document.getElementById("email_applicants"); error.innerHTML = obj["applicant.emailID"]; return false; } // if (phoneNo == null || phoneNo == "") { // var error = document.getElementById("phone_applicants"); // error.innerHTML = "This field is mandatory"; // document.getElementById('phone_no').focus(); // return false; // } if (obj["applicant.phone"] == "Invalid Phone Number!!") { var error = document.getElementById("phone_applicants"); error.innerHTML = obj["applicant.phone"]; document.getElementById('phone_no').focus(); return false; } if (obj["applicant.SSN"] == "Invalid Social Security Number!!") { var error = document.getElementById("ssn_applicants"); error.innerHTML = obj["applicant.SSN"]; document.getElementById('mail').focus(); return false; } if (obj["contactInfo.contactNumber"] == "Invalid Phone Number!!") { var error = document.getElementById("error_emergencyContact"); error.innerHTML = obj["contactInfo.contactNumber"]; document.getElementById('emergencyContact').focus(); return false; } if (obj["contactInfo.contactName"] == "Invalid Name!!") { var error = document.getElementById("emergencyContact_name_error"); error.innerHTML = obj["contactInfo.contactName"]; document.getElementById('emergencyContact_name').focus(); return false; } if (obj["contactInfo.contactPersonRelationship"] == "Invalid!!") { var error = document.getElementById("emergencyContact_rel_error"); error.innerHTML = obj["contactInfo.contactPersonRelationship"]; document.getElementById('emergencyContact_relationship').focus(); return false; } //current company details if (obj["employmentHistory[0].company"] == "Invalid company!!") { document.getElementById("curr_company").innerHTML = obj["employmentHistory[0].company"]; document.getElementById('current_company').focus(); return false; } if (obj["employmentHistory[0].occupation"] == "Invalid occupation!!") { document.getElementById("curr_occupation").innerHTML = obj["employmentHistory[0].occupation"]; document.getElementById('current_occupation').focus(); return false; } if (obj["employmentHistory[0].income"] == "Invalid income!!") { document.getElementById("curr_income").innerHTML = obj["employmentHistory[0].income"]; document.getElementById('current_income').focus(); return false; } if (obj["employmentHistory[0].supervisor"] == "Please enter a valid name") { document.getElementById("curr_supervisor").innerHTML = obj["employmentHistory[0].supervisor"]; document.getElementById('current_supervisor').focus(); return false; } if (obj["employmentHistory[0].address"] == "Invalid Address!!") { document.getElementById("curr_office_address").innerHTML = obj["employmentHistory[0].address"]; document.getElementById('current_office_address').focus(); return false; } if (obj["employmentHistory[0].companyPhoneNo"] == "Invalid Company Contact Number!!") { document.getElementById("curr_company_phoneNo").innerHTML = obj["employmentHistory[0].companyPhoneNo"]; document.getElementById('current_company_phoneNo').focus(); return false; } if (obj["employmentHistory[0].companyEmail"] == "Invalid Company email!!") { document.getElementById("curr_company_mail").innerHTML = obj["employmentHistory[0].companyEmail"]; document.getElementById('current_company_mail').focus(); return false; } if (obj["employmentHistory[0].city"] == "Invalid city!!") { document.getElementById("curr_company_city").innerHTML = obj["employmentHistory[0].city"]; document.getElementById('current_company_city').focus(); return false; } if (obj["employmentHistory[0].state"] == "Invalid state!!") { document.getElementById("curr_company_state").innerHTML = obj["employmentHistory[0].state"]; document.getElementById('current_company_state').focus(); return false; } if (obj["employmentHistory[0].zip"] == "Invalid zip!!") { document.getElementById("curr_zip").innerHTML = obj["employmentHistory[0].zip"]; document.getElementById('current_zip').focus(); return false; } if (obj["employmentHistory[0].country"] == "Invalid country!!") { document.getElementById("curr_company_country").innerHTML = obj["employmentHistory[0].country"]; document.getElementById('current_company_country').focus(); return false; } if (obj["employmentHistory[0].duration"] == "Invalid duration!!") { document.getElementById("curr_duration").innerHTML = obj["employmentHistory[0].duration"]; document.getElementById('current_duration').focus(); return false; } //previous company details if (obj["employmentHistory[1].company"] == "Invalid company!!") { document.getElementById("pre_company").innerHTML = obj["employmentHistory[1].company"]; document.getElementById('previous_company').focus(); return false; } if (obj["employmentHistory[1].occupation"] == "Invalid occupation!!") { document.getElementById("pre_occupation").innerHTML = obj["employmentHistory[1].occupation"]; document.getElementById('previous_occupation').focus(); return false; } if (obj["employmentHistory[1].income"] == "Invalid income!!") { document.getElementById("pre_income").innerHTML = obj["employmentHistory[1].income"]; document.getElementById('previous_income').focus(); return false; } if (obj["employmentHistory[1].supervisor"] == "Please enter a valid name") { document.getElementById("pre_supervisor").innerHTML = obj["employmentHistory[1].supervisor"]; document.getElementById('previous_supervisor').focus(); return false; } if (obj["employmentHistory[1].address"] == "Invalid Address!!") { document.getElementById("pre_office_address").innerHTML = obj["employmentHistory[1].address"]; document.getElementById('previous_office_address').focus(); return false; } if (obj["employmentHistory[1].companyPhoneNo"] == "Invalid Company Contact Number!!") { document.getElementById("pre_company_contact").innerHTML = obj["employmentHistory[1].companyPhoneNo"]; document.getElementById('previous_company_contact').focus(); return false; } if (obj["employmentHistory[1].companyEmail"] == "Invalid Company email!!") { document.getElementById("pre_company_mail").innerHTML = obj["employmentHistory[1].companyEmail"]; document.getElementById('previous_company_mail').focus(); return false; } if (obj["employmentHistory[1].city"] == "Invalid city!!") { document.getElementById("pre_company_city").innerHTML = obj["employmentHistory[1].city"]; document.getElementById('previous_company_city').focus(); return false; } if (obj["employmentHistory[1].state"] == "Invalid state!!") { document.getElementById("pre_company_state").innerHTML = obj["employmentHistory[1].state"]; document.getElementById('previous_company_state').focus(); return false; } if (obj["employmentHistory[1].zip"] == "Invalid zip!!") { document.getElementById("pre_zip").innerHTML = obj["employmentHistory[1].zip"]; document.getElementById('previous_zip').focus(); return false; } if (obj["employmentHistory[1].country"] == "Invalid country!!") { document.getElementById("pre_company_country").innerHTML = obj["employmentHistory[1].country"]; document.getElementById('previous_company_country').focus(); return false; } if (obj["employmentHistory[1].duration"] == "Invalid duration!!") { document.getElementById("pre_duration").innerHTML = obj["employmentHistory[1].duration"]; document.getElementById('previous_duration').focus(); return false; } //current landlord if (obj["landlordHistory[0].name"] == "Invalid Name!!") { document.getElementById("curr_landlord_name").innerHTML = obj["landlordHistory[0].name"]; document.getElementById('current_landlord_name').focus(); return false; } if (obj["landlordHistory[0].rentalAddress"] == "Invalid Rental Address!!") { document.getElementById("curr_landlord_address").innerHTML = obj["landlordHistory[0].rentalAddress"]; document.getElementById('current_landlord_address').focus(); return false; } if (obj["landlordHistory[0].phone"] == "Invalid Phone Number!!") { document.getElementById("curr_landlord_phoneNo").innerHTML = obj["landlordHistory[0].phone"]; document.getElementById('current_landlord_phoneNo').focus(); return false; } if (obj["landlordHistory[0].email"] == "Invalid email!!") { document.getElementById("curr_landlord_mail").innerHTML = obj["landlordHistory[0].email"]; document.getElementById('current_landlord_mail').focus(); return false; } //previous landlord-1 if (obj["landlordHistory[1].name"] == "Invalid Name!!") { document.getElementById("pre_landlord-1_name").innerHTML = obj["landlordHistory[1].name"]; document.getElementById('previous_landlord1_name').focus(); return false; } if (obj["landlordHistory[1].rentalAddress"] == "Invalid Rental Address!!") { document.getElementById("pre_landlord-1_address").innerHTML = obj["landlordHistory[1].rentalAddress"]; document.getElementById('previous_landlord1_address').focus(); return false; } if (obj["landlordHistory[1].phone"] == "Invalid Phone Number!!") { document.getElementById("pre_landlord-1_phone").innerHTML = obj["landlordHistory[1].phone"]; document.getElementById('previous_landlord1_phone').focus(); return false; } if (obj["landlordHistory[1].email"] == "Invalid email!!") { document.getElementById("pre_landlord-1_mail").innerHTML = obj["landlordHistory[1].email"]; document.getElementById('previous_landlord1_mail').focus(); return false; } // previous landlord-2 if (obj["landlordHistory[2].name"] == "Invalid Name!!") { document.getElementById("pre_landlord_name").innerHTML = obj["landlordHistory[2].name"]; document.getElementById('previous_landlord_name').focus(); return false; } if (obj["landlordHistory[2].rentalAddress"] == "Invalid Rental Address!!") { document.getElementById("pre_landlord_address").innerHTML = obj["landlordHistory[2].rentalAddress"]; document.getElementById('previous_landlord_address').focus(); return false; } if (obj["landlordHistory[2].phone"] == "Invalid Phone Number!!") { document.getElementById("pre_landlord_phoneNo").innerHTML = obj["landlordHistory[2].phone"]; document.getElementById('previous_landlord_phone').focus(); return false; } if (obj["landlordHistory[2].email"] == "Invalid email!!") { document.getElementById("pre_landlord_mail").innerHTML = obj["landlordHistory[2].email"]; document.getElementById('previous_landlord_mail').focus(); return false; } //personal references if (obj["personalReferencesVO.fullName"] == "Invalid Name!!") { document.getElementById("personal_fullname").innerHTML = obj["personalReferencesVO.fullName"]; document.getElementById('personalref_fullname').focus(); return false; } if (obj["personalReferencesVO.relationship"] == "Invalid!!") { document.getElementById("personal_relationship").innerHTML = obj["personalReferencesVO.relationship"]; document.getElementById('personalref_relationship').focus(); return false; } if (obj["personalReferencesVO.phoneNo"] == "Invalid Phone Number!!") { document.getElementById("personal_phone").innerHTML = obj["personalReferencesVO.phoneNo"]; document.getElementById('personalref_phone').focus(); return false; } if (obj["personalReferencesVO.email"] == "Invalid email!!") { document.getElementById("personal_mail").innerHTML = obj["personalReferencesVO.email"]; document.getElementById('personalref_mail').focus(); return false; } //previous residence-2 if (obj["residenceHistory[2].zip"] == "Invalid Zip!!") { document.getElementById("pre_residence-1_zip").innerHTML = obj["residenceHistory[2].zip"]; document.getElementById('previous_residence2_zip').focus(); return false; } if (obj["residenceHistory[2].city"] == "Invalid City!!") { document.getElementById("pre_residence-1_city").innerHTML = obj["residenceHistory[2].city"]; document.getElementById('previous_residence2_city').focus(); return false; } if (obj["residenceHistory[2].squareFeet"] == "Invalid Square Feet!!") { document.getElementById("pre_residence-1_sqFeet").innerHTML = obj["residenceHistory[2].squareFeet"]; document.getElementById('previous_residence2_sqFeet').focus(); return false; } if (obj["residenceHistory[2].rent"] == "Invalid Rent Amount!!") { document.getElementById("pre_residence-1_rent").innerHTML = obj["residenceHistory[2].rent"]; document.getElementById('previous_residence2_rent').focus(); return false; } if (obj["residenceHistory[2].houseNo"] == "Invalid House Number!!") { document.getElementById("pre_residence-1_houseNo").innerHTML = obj["residenceHistory[2].houseAddress"]; document.getElementById('previous_residence2_houseNo').focus(); return false; } if (obj["residenceHistory[2].streetAddress"] == "Invalid Street Address!!") { document.getElementById("pre_residence-1_street").innerHTML = obj["residenceHistory[2].streetAddress"]; document.getElementById('previous_residence2_street').focus(); return false; } if (obj["residenceHistory[2].state"] == "Invalid State!!") { document.getElementById("pre_residence-1_state").innerHTML = obj["residenceHistory[2].state"]; document.getElementById('previous_residence2_state').focus(); return false; } if (obj["residenceHistory[2].country"] == "Invalid Country!!") { document.getElementById("pre_residence-1_country").innerHTML = obj["residenceHistory[2].country"]; document.getElementById('previous_residence2_country').focus(); return false; } //previous residence-1 if (obj["residenceHistory[1].zip"] == "Invalid Zip!!") { document.getElementById("pre_residence_zip").innerHTML = obj["residenceHistory[1].zip"]; document.getElementById('previous_residence_zip').focus(); return false; } if (obj["residenceHistory[1].city"] == "Invalid City!!") { document.getElementById("pre_residence_city").innerHTML = obj["residenceHistory[1].city"]; document.getElementById('previous_residence_city').focus(); return false; } if (obj["residenceHistory[1].squareFeet"] == "Invalid Square Feet!!") { document.getElementById("pre_residence_sqFeet").innerHTML = obj["residenceHistory[1].squareFeet"]; document.getElementById('previous_residence_sqFeet').focus(); return false; } if (obj["residenceHistory[1].rent"] == "Invalid Rent Amount!!") { document.getElementById("pre_residence_rent").innerHTML = obj["residenceHistory[1].rent"]; document.getElementById('previous_residence_rent').focus(); return false; } if (obj["residenceHistory[1].houseNo"] == "Invalid House Number!!") { document.getElementById("pre_residence_houseNo").innerHTML = obj["residenceHistory[1].houseNo"]; document.getElementById('previous_residence_houseNo').focus(); return false; } if (obj["residenceHistory[1].streetAddress"] == "Invalid Street Address!!") { document.getElementById("pre_residence_address").innerHTML = obj["residenceHistory[1].streetAddress"] document.getElementById('previous_residence_address').focus(); return false; } if (obj["residenceHistory[1].state"] == "Invalid State!!") { document.getElementById("pre_residence_state").innerHTML = obj["residenceHistory[1].state"]; document.getElementById('previous_residence_state').focus(); return false; } if (obj["residenceHistory[1].country"] == "Invalid Country!!") { document.getElementById("pre_residence_country").innerHTML = obj["residenceHistory[1].country"]; document.getElementById('previous_residence_country').focus(); return false; } // current residence if (obj["residenceHistory[1].zip"] == "Invalid Zip!!") { document.getElementById("curr_residence_zip").innerHTML = obj["residenceHistory[0].zip"]; document.getElementById('current_residence_zip').focus(); return false; } if (obj["residenceHistory[0].city"] == "Invalid City!!") { document.getElementById("curr_residence_city").innerHTML = obj["residenceHistory[0].city"]; document.getElementById('current_residence_city').focus(); return false; } if (obj["residenceHistory[0].squareFeet"] == "Invalid Square Feet!!") { document.getElementById("curr_residence_sqFeet").innerHTML = obj["residenceHistory[0].squareFeet"]; document.getElementById('current_residence_sqFeet').focus(); return false; } if (obj["residenceHistory[0].rent"] == "Invalid Rent Amount!!") { document.getElementById("curr_residence_rent").innerHTML = obj["residenceHistory[0].rent"]; document.getElementById('current_residence_rent').focus(); return false; } if (obj["residenceHistory[0].houseNo"] == "Invalid House Number!!") { document.getElementById("curr_residence_houseNo").innerHTML = obj["residenceHistory[0].houseNo"]; document.getElementById('current_residence_houseNo').focus(); return false; } if (obj["residenceHistory[0].streetAddress"] == "Invalid Street Address!!") { document.getElementById("curr_residence_address").innerHTML = obj["residenceHistory[0].streetAddress"] document.getElementById('current_residence_street').focus(); return false; } if (obj["residenceHistory[0].state"] == "Invalid State!!") { document.getElementById("curr_residence_state").innerHTML = obj["residenceHistory[0].state"]; document.getElementById('current_residence_state').focus(); return false; } if (obj["residenceHistory[0].country"] == "Invalid Country!!") { document.getElementById("curr_residence_country").innerHTML = obj["residenceHistory[0].country"]; document.getElementById('current_residence_country').focus(); return false; } if (res.rspnsMsg == "GOOD") { if (!status) { window.location.href = window.location.protocol + "//" + window.location.host + "/submitted.html" } else { $('#basicModal').modal("show"); $("#modal_message").html("

The application has been saved temporarily. Please make sure to submit it after providing the necessary details.

"); $("#modal_title").html("SUCCESS!!"); } } } else if (this.status == 500) { window.location.href = window.location.protocol + "//" + window.location.host + "/error.html"; } }; xmlhttp1.send(JSON.stringify({ "applicant": { "DOB": dob, "SSN": ssn, "dob": dob, "emailID": email, "fullName": fullName, "phone": phoneNo, "ssn": ssn, "verification": verification, "startDate": startDate, "endDate": endDate, "emergencyContactName": emergencyContactName, "emergencyContactRelation": emergencyContactRelationship }, "contactInfo": { "contactNumber": emergencyContact, "contactName": emergencyContactName, "contactPersonRelationship": emergencyContactRelationship }, "employmentHistory": [{ "address": currentofficeaddress, "city": currentcompanycity, "company": currentcompany, "companyEmail": currentcompanymail, "companyPhoneNo": currentcompanyphone, "country": currentcompanycountry, "duration": currentduration, "income": currentincome, "occupation": currentoccupation, "state": currentcompanystate, "supervisor": currentsupervisor, "zip": currentzip, }, { "address": previousofficeaddress, "city": previouscompanycity, "company": previouscompany, "companyEmail": previouscompanymail, "companyPhoneNo": previouscompanyphone, "country": previouscompanycountry, "duration": previousduration, "income": previousincome, "occupation": previousoccupation, "state": previouscompanystate, "supervisor": previoussupervisor, "zip": previouszip, } ], "landlordHistory": [{ "email": currentlandlordmail, "name": currentlandlordname, "phone": currentlandlordphone, "rentalAddress": currentlandlordaddress }, { "email": prevLandlordmail, "name": prevLandlordname, "phone": prevLandlordphone, "rentalAddress": prevLandlordaddress }, { "email": previousLandlordmail, "name": previousLandlordname, "phone": previousLandlordphone, "rentalAddress": previousLandlordaddress } ], "personalReferencesVO": { "email": personalreferencemail, "fullName": personalreferencename, "phoneNo": personalreferencephone, "relationship": personalreferencerelationship }, "propertyId": propertyID, "propertyInfo": { "type": type, "bedrooms": bedrooms, "zip": zip, "furnishing": furnishing, "squareFeet": squareFeet, "carParking": carParking, "rentAmount": rentAmount, "houseNo": houseNo, "streetAddress": streetAddress, "city": city, "state": state, "country": country, "bathrooms": bathrooms, "carParkingType": carParkingType, "rentalRate": rentalRate, }, "residenceHistory": [{ "bedrooms": currentresidencebedrooms, "city": currentresidencecity, "country": currentresidencecountry, "currLeaseExpDate": currentleaseExpiry, "duration": currentresidenceduration, "houseAddress": currentresidenceaddress, "reasonForMoving": reasonformoving, "rent": currentresidencerentamount, "squareFeet": currentresidencesqFeet, "state": currentresidencestate, "streetAddress": currentresidencestreet, "type": currentresidencetype, "zip": currentresidencezip }, { "bedrooms": previousresidencebedrooms, "city": previousresidencecity, "country": previousresidencecountry, // "currLeaseExpDate": previousleaseExpiry, "duration": previousresidenceduration, "houseAddress": previousresidenceaddress, // "reasonForMoving": reasonformoving, "rent": previousresidencerentamount, "squareFeet": previousresidencesqFeet, "state": previousresidencestate, "streetAddress": previousresidencestreet, "type": previousresidencetype, "zip": previousresidencezip, "startDate": previousresidenceStartDate, "endDate": previousresidenceEndDate }, { "bedrooms": previousresidence2bedrooms, "city": previousresidence2city, "country": previousresidence2country, // "currLeaseExpDate": previousleaseExpiry, "duration": previousresidenceduration, "houseAddress": previousresidence2address, // "reasonForMoving": reasonformoving, "rent": previousresidence2rentamount, "squareFeet": previousresidences2sqFeet, "state": previousresidence2state, "streetAddress": previousresidence2street, "type": previousresidence2type, "zip": previousresidence2zip, "startDate": previousresidence2StartDate, "endDate": previousresidence2EndDate } ], "vehicles": { "vehicle": veh_arr }, })); console.log("waiting for server response...."); } // this is for getting auto filled values in property section of application form function getApplicationData(baseurl, appID) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentalunsecured/getapplication?appID=" + appID, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); var response = JSON.parse(res['response']); if (response == null) { window.location.href = window.location.protocol + "//" + window.location.host + "/error.html"; } else if (response != null) { // console.log(response.propertyId); document.getElementById('type').value = response.propertyInfo['type']; document.getElementById('squareFeet').value = response.propertyInfo['squareFeet']; document.getElementById('bedrooms').value = response.propertyInfo['bedrooms']; document.getElementById('rentAmount').value = response.propertyInfo['rentAmount']; document.getElementById("streetAddress").value = response.propertyInfo["streetAddress"]; document.getElementById("houseNo").value = response.propertyInfo["houseNo"]; document.getElementById("city").value = response.propertyInfo["city"]; document.getElementById("state").value = response.propertyInfo["state"]; document.getElementById("zip").value = response.propertyInfo["zip"]; document.getElementById("country").value = response.propertyInfo["country"]; document.getElementById("bathrooms").value = response.propertyInfo["bathrooms"]; document.getElementById("carParking").value = response.propertyInfo["carParking"]; document.getElementById("furnishing").value = response.propertyInfo["furnishing"]; document.getElementById("carParkingType").value = response.propertyInfo["carParkingType"]; document.getElementById("rentalRate").value = response.propertyInfo["rentalRate"]; document.getElementById("propertyId").value = response.propertyId; document.getElementById("app_id").innerHTML = appID; document.getElementById("mail").value = response.applicant['emailID']; // document.getElementById("inlineRadio2").value = response.propertyInfo["pets"]; } } else if (this.status == 500) { window.location.href = window.location.protocol + "//" + window.location.host + "/error.html"; } }; xmlhttp1.send(); } // for getting user information on each page function getUserInfo() { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/getuserinfo", true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); var response = JSON.parse(res['response']); // console.log(response); var user = document.getElementById("profile_name"); user.innerHTML = response.firstName; if (response.preferredTimezone) { localStorage.setItem("preferredTimezone", response.preferredTimezone); } // alert("Timezone stored: " + response.preferredTimezone); var logoName = document.getElementById("logoName"); switch (response.clientID) { case "RM000001": logoName.innerText = "Rents4Me - PM"; break; case "RM000E11": logoName.innerText = "Rents4Me - Intern"; break; case "RM000E21": logoName.innerText = "Rents4Me - Lead"; break; case "RM000E31": logoName.innerText = "Rents4Me - Manager"; break; default: logoName.innerText = "Rents4Me"; } } else if ((this.status == 403 || this.status == 401) && this.readyState == 4) { window.location.href = window.location.protocol + "//" + window.location.host + "/admin/login.html" } else if (this.status == 500) { var res = JSON.parse(this.responseText); if (res.response === "403 FORBIDDEN") { window.location.href = window.location.protocol + "//" + window.location.host + "/admin/login.html" } } }; xmlhttp1.send(); } // this ajax is for getting overview in user profile function getUserDetails() { var xmlhttp1; var adminFullName = document.getElementById("adminFullName"); var adminEmail = document.getElementById("adminEmail"); var adminPhone = document.getElementById("adminPhone"); var adminTimeZone = document.getElementById("adminTimeZone"); try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/getuserinfo", true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); var response = JSON.parse(res['response']); console.log(response); // var user = document.getElementById("profile_name"); // user.innerHTML = response.firstName; adminFullName.innerHTML = response.firstName + " " + response.lastName; adminEmail.innerHTML = response.emailID; adminPhone.innerHTML = response.phoneNumber; adminTimeZone.innerHTML = response.preferredTimezone; document.getElementById("FirstName").value = response.firstName; document.getElementById("LastName").value = response.lastName; document.getElementById("Email").value = response.emailID; document.getElementById("Phone1").value = response.phoneNumber; document.getElementById("TimeZone").value = response.preferredTimezone; } else if ((this.status == 403 || this.status == 401) && this.readyState == 4) { window.location.href = window.location.protocol + "//" + window.location.host + "/admin/login.html" } else if (this.status == 500) { var res = JSON.parse(this.responseText); if (res.response === "403 FORBIDDEN") { window.location.href = window.location.protocol + "//" + window.location.host + "/admin/login.html" } } }; xmlhttp1.send(); } // login function var loginBtn = document.querySelector("#login_form_submit") function delay() { $("#login_form_submit").prop("disabled", true) // this function will disable the button after click until the response comes from backend } function initLogin() { var email = $("#username").val(); var pass = $("#password").val(); var xmlhttpAuth; try { xmlhttpAuth = new XMLHttpRequest(); } catch (e) { try { xmlhttpAuth = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttpAuth = new ActiveXObject( "Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttpAuth.open("POST", baseurl + "/authentication/getGenericJWTToken", true); xmlhttpAuth.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttpAuth.setRequestHeader('clientID', clientId); xmlhttpAuth.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "" && this.readyState == 4) { $("#login_form_submit").prop("disabled", false) var res = JSON.parse(this.responseText); if (res.token != "Invalid User or Password / Or Account Locked") { localStorage.setItem('token', res.token); window.location.href = window.location.protocol + "//" + window.location.host + "/admin/index.html"; } else { $("#error_message").show(); $("#error_message").html("Invalid User or Password / Or Account Locked"); } } } xmlhttpAuth.send(JSON.stringify({ "username": email, "password": pass })); } // this is for list of properties page -- for delete button function deleteProperty(propertyID) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("POST", baseurl + "/rentaladmin/deleteproperty?propertyID=" + propertyID, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); if (confirm('Are you sure you want to delete this property?')) { xmlhttp1.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200 && this.responseText) { var res = JSON.parse(this.responseText); var resp = res.response; $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

" + resp + "

"); $("#employee_modal_title").html("Response"); // Optional: redirect only if deletion was successful if (resp === "PROPERTY DELETED") { setTimeout(function () { window.location.href = window.location.protocol + "//" + window.location.host + "/admin/list-of-properties.html"; }, 2000); } } else { var res; try { res = JSON.parse(this.responseText); } catch (err) { res = { response: "Unknown Error" }; } $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

" + res.response + "

"); $("#employee_modal_title").html("OOPS!!"); } } }; xmlhttp1.send(JSON.stringify({})); // no need to send propertyInfo if not required } } // this is for list of properties page-- for getting auto filled values on form when edit button is clicked function getProperty(propertyID) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/getproperty?propertyID=" + propertyID, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); document.getElementById('type').value = response.type; document.getElementById('squareFeet').value = response.squareFeet; document.getElementById('bedrooms').value = response.bedrooms; document.getElementById('rentAmount').value = response.rentAmount; document.getElementById("streetAddress").value = response.streetAddress; document.getElementById("houseNo").value = response.houseNo; document.getElementById("city").value = response.city; populateStates(); document.getElementById("state").value = response.state; document.getElementById("zip").value = response.zip; document.getElementById("country").value = response.country; document.getElementById("bathrooms").value = response.bathrooms; document.getElementById("carParking").value = response.carParking; document.getElementById("furnishing").value = response.furnishing; document.getElementById("carParkingType").value = response.carParkingType; document.getElementById("rentalRate").value = response.rentalRate; document.getElementById("termsAndConditions").value = response.termsAndConditions; document.getElementById("propertyDesc").value = response.propertyDesc; document.getElementById("number").value = response.number; if (response.otherBookingPlatform) { document.getElementById("otherBookingPlatform").value = response.otherBookingPlatform; } document.getElementById("endDate").value = response.endDate; document.getElementById("startDate").value = response.startDate; } } }; xmlhttp1.send(); } // this is for list of properties page details button function viewProperty(propertyID) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/getproperty?propertyID=" + propertyID, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); document.getElementById('type').innerHTML = response.type; document.getElementById('squareFeet').innerHTML = response.squareFeet; document.getElementById('bedrooms').innerHTML = response.bedrooms; document.getElementById('rentAmount').innerHTML = response.rentAmount; document.getElementById("streetAddress").innerHTML = response.streetAddress; document.getElementById("houseNo").innerHTML = response.houseNo; document.getElementById("city").innerHTML = response.city; document.getElementById("state").innerHTML = response.state; document.getElementById("zip").innerHTML = response.zip; document.getElementById("country").innerHTML = response.country; document.getElementById("bathrooms").innerHTML = response.bathrooms; document.getElementById("carParking").innerHTML = response.carParking; document.getElementById("furnishing").innerHTML = response.furnishing; document.getElementById("carParkingType").innerHTML = response.carParkingType; document.getElementById("rentalRate").innerHTML = response.rentalRate; } } }; xmlhttp1.send(); } // for get property details page-- unsecured page(getProperty.html) function getPropertyUnsecured(propertyID) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentalunsecured/getproperty?propertyID=" + propertyID, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); // console.log(res) if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); if (response == null) { window.location.href = window.location.protocol + "//" + window.location.host + "/error.html"; } else { // console.log(response) document.getElementById('type').innerHTML = response.type; document.getElementById('squareFeet').innerHTML = response.squareFeet; document.getElementById('bedrooms').innerHTML = response.bedrooms; document.getElementById('rentAmount').innerHTML = response.rentAmount; document.getElementById("streetAddress").innerHTML = response.streetAddress; document.getElementById("houseNo").innerHTML = response.houseNo; document.getElementById("city").innerHTML = response.city; document.getElementById("state").innerHTML = response.state; document.getElementById("termsAndCondition").innerHTML = response.termsAndConditions; document.getElementById("number").innerHTML = response.number; // var state = getStateName(response.state); var country = response.country; // $('#gmap_canvas').attr('src', // 'https://maps.google.com/maps?q=' + state + ","+ country + '&t=k&z=10&ie=UTF8&iwloc=&output=embed'); document.getElementById("zip").innerHTML = response.zip; document.getElementById("country").innerHTML = response.country; document.getElementById("bathrooms").innerHTML = response.bathrooms; document.getElementById("carParking").innerHTML = response.carParking; document.getElementById("furnishing").innerHTML = response.furnishing; document.getElementById("carParkingType").innerHTML = response.carParkingType; document.getElementById("rentalRate").innerHTML = response.rentalRate; document.getElementById("number").innerHTML = response.number; if (response.propertyDesc == null || response.propertyDesc == "") { document.getElementById("propertyDesc").innerHTML = "Description Not Available"; } else { document.getElementById("propertyDesc").innerHTML = response.propertyDesc; } } } } else if (this.status == 500) { window.location.href = window.location.protocol + "//" + window.location.host + "/admin/pages-error-404.html"; } }; xmlhttp1.send(); } // this is for add property page function addproperties() { return new Promise(function (resolve, reject) { var landlord_email = $("#landlord_email").val(); var number = $("#number").val(); var type = $("#type").val(); var bedrooms = $("#bedrooms").val(); var zip = $("#zip").val(); var furnishing = $("#furnishing").val(); var squareFeet = $("#squareFeet").val(); var rentAmount = $("#rentAmount").val(); var houseNo = $("#houseNo").val(); var streetAddress = $("#streetAddress").val(); var city = $("#city").val(); var state = $("#state").val(); var country = $("#country").val(); var carParking = $("#carParking").val(); var bathrooms = $("#bathrooms").val(); var carParkingType = $("#carParkingType").val(); var rentalRate = $("#rentalRate").val(); var termsAndConditions = $('#termsAndConditions').val(); var propertyDesc = $('#propertyDesc').val(); var otherBookingPlatform = $("#otherBookingPlatform").val(); var endDate = $("#endDate").val(); var startDate = $("#startDate").val(); $(".add_properties strong").html(""); if (otherBookingPlatform) { if (!startDate) { // Check if startDate is empty $("#startDate_error").html('This field is required'); document.getElementById("startDate").focus(); return; // Stop the function if validation fails } } if (otherBookingPlatform) { $("endDate_error").html('This field is required'); document.getElementById("endDate").focus(); } // Empty field errors var email_pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (landlord_email !== "" && !email_pattern.test(landlord_email)) { document.getElementById("landlord_email_error").innerHTML = "Please enter a valid email address"; document.getElementById("landlord_email").focus(); return false; } if (type == "" || type == null) { var error = document.getElementById("type_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("type").focus(); return false; } if (bedrooms == "" || bedrooms == null) { var error = document.getElementById("bedrooms_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("bedrooms").focus(); return false; } if (bathrooms == "" || bathrooms == null) { var error = document.getElementById("bathrooms_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("bathrooms").focus(); return false; } if (furnishing == "" || furnishing == null) { var error = document.getElementById("furnishing_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("furnishing").focus(); return false; } if (squareFeet == "" || squareFeet == null) { var error = document.getElementById("squareFeet_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("squareFeet").focus(); return false; } if (carParking == "" || carParking == null) { var error = document.getElementById("carParking_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("carParking").focus(); return false; } if (carParkingType == "" || carParkingType == null) { var error = document.getElementById("carParkingType_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("carParkingType").focus(); return false; } if (rentAmount == "" || rentAmount == null) { var error = document.getElementById("rentAmount_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("rentAmount").focus(); return false; } if (state == "" || state == null) { var error = document.getElementById("state_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("state").focus(); return false; } if (zip == "" || zip == null) { var message = "This field is required"; var error = document.getElementById("zip_error"); document.getElementById("zip").focus(); error.innerHTML = message; return false; } if (country == "" || country == null) { var error = document.getElementById("country_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("country").focus(); return false; } if (rentalRate == "" || rentalRate == null) { var error = document.getElementById("rentalRate_error"); error.innerHTML = obj.rentalRate; document.getElementById("rentalRate").focus(); return false; } if (houseNo == "" || houseNo == null) { var error = document.getElementById("houseNo_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("houseNo").focus(); return false; } if (city == "" || city == null) { var message = "This field is required"; var error = document.getElementById("city_error"); error.innerHTML = message; document.getElementById("city").focus(); return false; } if (streetAddress == "" || streetAddress == null) { var error = document.getElementById("streetAddress_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("streetAddress").focus(); return false; } //console.log(termsAndConditions); var id = ""; var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } $("#form_submit").prop("disabled", true) xmlhttp1.open("POST", baseurl + "/rentaladmin/addproperty?landlordEmail=" + landlord_email, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "" && this.readyState == 4) { var res = JSON.parse(this.responseText); var loginRes = res.response; $("#form_submit").prop("disabled", false) var s = res.rspnsMsg; console.log(s); var s = s.replace(/[{}]/g, ""); let pairs = s.split(', ') let obj = pairs.reduce((obj, data) => { let [k, v] = data.split('=') obj[k] = v return obj }, {}) console.log(obj) // this is to clear error after user puts fills valid values $(".add_properties strong").html(""); // this is to populate error below each field in add properties form if (obj.type == "Please select an item") { var error = document.getElementById("type_error"); error.innerHTML = obj.type; document.getElementById("type").focus(); return false; } if (obj.bedrooms == "Please select an item") { var error = document.getElementById("bedrooms_error"); error.innerHTML = obj.bedrooms; document.getElementById("bedrooms").focus(); return false; } if (obj.bathrooms == "Please select an item") { var error = document.getElementById("bathrooms_error"); error.innerHTML = obj.bathrooms; document.getElementById("bathrooms").focus(); return false; } if (obj.furnishing == "Please select an item") { var error = document.getElementById("furnishing_error"); error.innerHTML = obj.furnishing; document.getElementById("furnishing").focus(); return false; } if (obj.squareFeet == "Invalid Square Feet!!") { // console.log("npt ") var error = document.getElementById("squareFeet_error"); error.innerHTML = obj.squareFeet; document.getElementById("squareFeet").focus(); return false; } if (obj.carParking == "Please select an item") { var error = document.getElementById("carParking_error"); error.innerHTML = obj.carParking; document.getElementById("carParking").focus(); return false; } if (obj.carParkingType == "Please select an item") { var error = document.getElementById("carParkingType_error"); error.innerHTML = obj.carParkingType; document.getElementById("carParkingType").focus(); return false; } if (obj.rentAmount == "Invalid Amount!!") { var error = document.getElementById("rentAmount_error"); error.innerHTML = obj.rentAmount; document.getElementById("rentAmount").focus(); return false; } if (obj.rentalRate == "Please select an item") { var error = document.getElementById("rentalRate_error"); error.innerHTML = obj.rentalRate; document.getElementById("rentalRate").focus(); return false; } if (obj.houseNo == "Invalid House Number!!") { var error = document.getElementById("houseNo_error"); error.innerHTML = obj.houseNo; document.getElementById("houseNo").focus(); return false; } if (obj.streetAddress == "Invalid Street Address!!") { var error = document.getElementById("streetAddress_error"); error.innerHTML = obj.streetAddress; document.getElementById("streetAddress").focus(); return false; } if (obj.city == "Invalid City!!") { var error = document.getElementById("city_error"); error.innerHTML = obj.city; document.getElementById("city").focus(); return false; } if (obj.zip == "Invalid Zip!!") { var error = document.getElementById("zip_error"); document.getElementById("zip").focus(); error.innerHTML = obj.zip; return false; } if (obj.state == "Invalid State!!") { var error = document.getElementById("state_error"); error.innerHTML = obj.state; document.getElementById("state").focus(); return false; } if (obj.country == "Invalid Country!!") { var error = document.getElementById("country_error"); error.innerHTML = obj.country; document.getElementById("country").focus(); return false; } if (res.rspnsMsg == "GOOD") { // window.location.href = window.location.protocol + "//" + window.location.host + "/admin/list-of-properties.html" var s = res.response; // console.log(s); var s = s.replace(/[{}]/g, ""); const obj = Object.fromEntries([s.split(":")]); console.log(obj["Added Property"]); id = obj["Added Property"]; // console.log(id); resolve(id); window.location.href = window.location.protocol + "//" + window.location.host + "/admin/list-of-properties.html" } if (termsAndConditions = "" || termsAndConditions == null) { var error = document.getElementById("#term_error"); var message = "This field is required"; error.innerHTML = message; document.getElementById("termsAndConditions").focus(); return false; } } else { var res = JSON.parse(this.responseText); console.log(res.response); if (res.response === "401 UNAUTHORIZED") { $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

You are not authorised for this action

"); $("#employee_modal_title").html("OOPS!!"); } } }; xmlhttp1.send(JSON.stringify({ "landlordEmail": landlord_email, "type": type, "bedrooms": bedrooms, "zip": zip, "furnishing": furnishing, "squareFeet": squareFeet, "carParking": carParking, "rentAmount": rentAmount, "houseNo": houseNo, "streetAddress": streetAddress, "city": city, "state": state, "country": country, "bathrooms": bathrooms, "rentalRate": rentalRate, "carParkingType": carParkingType, "termsAndConditions": termsAndConditions, "propertyDesc": propertyDesc, "number": number, "otherBookingPlatform": otherBookingPlatform, "endDate": endDate })); //console.log("waiting for server response...."); }); } // this is for populating list of properties page function getProperties(status, searchVal) { var xmlhttp1; var webBaseURL = window.location.protocol + "//" + window.location.host; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } if ((searchVal == null || searchVal == "")) { xmlhttp1.open("GET", baseurl + "/rentaladmin/getproperties", true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "" && this.readyState == 4) { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); var dynamicCard = document.querySelector('.container_card'); console.log(response); dynamicCard.innerHTML = ''; for (var i = 0; i < response.length; i++) { var s = JSON.parse(response[i].imageList); var firstImage = s != null ? s[0].imageLink : "assets/img/img for card.jpg"; if (status == "non-rented") { // console.log(response[i].isPropertyUnderMaintenance) if (response[i].deleteFlag == '0' && !response[i].isPropertyRented && !response[i].isPropertyUnderMaintenance) { var copyLink = webBaseURL + "" + "/propertydetails.html?propertyID=" + "" + response[i].propertyId; var fetch = document.querySelector('.container_card').innerHTML; var tempHtml = ""; var propertyID = response[i].propertyId; // console.log(response[i]); // console.log("l"); tempHtml = `
Image Title

${response[i].propertyInfo["type"]}

$${response[i].propertyInfo["rentAmount"]}/${response[i].propertyInfo["rentalRate"]}

${response[i].propertyInfo["houseNo"]} ${response[i].propertyInfo["streetAddress"]} ${response[i].propertyInfo["city"]} ${response[i].propertyInfo["state"]} - ${response[i].propertyInfo["zip"]} ${response[i].propertyInfo["country"]}

${response[i].propertyInfo["squareFeet"]} Sq Ft ${response[i].propertyInfo["bedrooms"]} Bedrooms ${response[i].propertyInfo["bathrooms"]} Bathrooms ${response[i].propertyInfo["furnishing"]} ${response[i].propertyInfo["carParking"]} ${response[i].propertyInfo["carParkingType"]}

`; dynamicCard.innerHTML += tempHtml; } } else { // console.log(response[i]); var propertyID = response[i].propertyId; if (response[i].deleteFlag == '0') { var copyLink = webBaseURL + "" + "/propertydetails.html?propertyID=" + "" + response[i].propertyId; var fetch = document.querySelector('.container_card').innerHTML; var tempHtml = ""; tempHtml = `
Image Title

${response[i].propertyInfo["type"]}

$${response[i].propertyInfo["rentAmount"]}/${response[i].propertyInfo["rentalRate"]}

${response[i].propertyInfo["houseNo"]} ${response[i].propertyInfo["streetAddress"]} ${response[i].propertyInfo["city"]} ${response[i].propertyInfo["state"]} - ${response[i].propertyInfo["zip"]} ${response[i].propertyInfo["country"]}

${response[i].propertyInfo["squareFeet"]} Sq Ft ${response[i].propertyInfo["bedrooms"]} Bedrooms ${response[i].propertyInfo["bathrooms"]} Bathrooms ${response[i].propertyInfo["furnishing"]} ${response[i].propertyInfo["carParking"]} ${response[i].propertyInfo["carParkingType"]}

`; dynamicCard.innerHTML += tempHtml; disableDeleteButtons(); } } } if (response.length <= 0) { dynamicCard.innerHTML = "No Properties Listed"; } } else { window.location.href = window.location.protocol + "//" + window.location.host + "/error.html"; } } }; xmlhttp1.send(); } else if (searchVal != null) { searchVal = searchVal.replace(/,/g, "%"); searchVal = searchVal.replace(/-/g, "%"); searchVal = searchVal.replace(/ /g, "%"); xmlhttp1.open("GET", baseurl + "/rentaladmin/getproperties?keyword=" + searchVal, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "" && this.readyState == 4) { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); var dynamicCard = document.querySelector('.container_card'); // console.log(response); dynamicCard.innerHTML = ''; if (response.length > 0) { for (var i = 0; i < response.length; i++) { var s = JSON.parse(response[i].imageList); var firstImage = s != null ? s[0].imageLink : "assets/img/img for card.jpg"; if (status == "non-rented") { if (response[i].deleteFlag == '0' && !response[i].isPropertyRented) { var copyLink = webBaseURL + "" + "/propertydetails.html?propertyID=" + "" + response[i].propertyId; var fetch = document.querySelector('.container_card').innerHTML; var tempHtml = ""; var propertyID = response[i].propertyId; // console.log(s); tempHtml = `
Image Title

${response[i].propertyInfo["type"]}

$${response[i].propertyInfo["rentAmount"]}/${response[i].propertyInfo["rentalRate"]}

${response[i].propertyInfo["houseNo"]} ${response[i].propertyInfo["streetAddress"]} ${response[i].propertyInfo["city"]} ${response[i].propertyInfo["state"]} - ${response[i].propertyInfo["zip"]} ${response[i].propertyInfo["country"]}

${response[i].propertyInfo["squareFeet"]} Sq Ft ${response[i].propertyInfo["bedrooms"]} Bedrooms ${response[i].propertyInfo["bathrooms"]} Bathrooms ${response[i].propertyInfo["furnishing"]} ${response[i].propertyInfo["carParking"]} ${response[i].propertyInfo["carParkingType"]}

`; dynamicCard.innerHTML += tempHtml; disableDeleteButtons(); } } else { var propertyID = response[i].propertyId; if (response[i].deleteFlag == '0') { var copyLink = webBaseURL + "" + "/propertydetails.html?propertyID=" + "" + response[i].propertyId; var fetch = document.querySelector('.container_card').innerHTML; var tempHtml = ""; tempHtml = `
Image Title

${response[i].propertyInfo["type"]}

$${response[i].propertyInfo["rentAmount"]}/${response[i].propertyInfo["rentalRate"]}

${response[i].propertyInfo["houseNo"]} ${response[i].propertyInfo["streetAddress"]} ${response[i].propertyInfo["city"]} ${response[i].propertyInfo["state"]} - ${response[i].propertyInfo["zip"]} ${response[i].propertyInfo["country"]}

${response[i].propertyInfo["squareFeet"]} Sq Ft ${response[i].propertyInfo["bedrooms"]} Bedrooms ${response[i].propertyInfo["bathrooms"]} Bathrooms ${response[i].propertyInfo["furnishing"]} ${response[i].propertyInfo["carParking"]} ${response[i].propertyInfo["carParkingType"]}

`; dynamicCard.innerHTML += tempHtml; disableDeleteButtons(); } } } } else { dynamicCard.innerHTML = 'No results found for the specified keyword'; } } else { window.location.href = window.location.protocol + "//" + window.location.host + "/error.html"; } } }; xmlhttp1.send(); } } // this is for list of properties page-- edit button function updateProperty() { var type = $("#type").val(); var bedrooms = $("#bedrooms").val(); var zip = $("#zip").val(); var furnishing = $("#furnishing").val(); var squareFeet = $("#squareFeet").val(); var rentAmount = $("#rentAmount").val(); var houseNo = $("#houseNo").val(); var streetAddress = $("#streetAddress").val(); var city = $("#city").val(); var state = $("#state").val(); var country = $("#country").val(); var carParking = $("#carParking").val(); var bathrooms = $("#bathrooms").val(); var carParkingType = $("#carParkingType").val(); var rentalRate = $("#rentalRate").val(); var termsAndConditions = $('#termsAndConditions').val(); var propertyDesc = $('#propertyDesc').val(); var landlordEmail = $('#landlord_email').val(); var number = $('#number').val(); var otherBookingPlatform = $("#otherBookingPlatform").val(); var endDate = $("#endDate").val(); var startDate = $("#startDate").val(); $(".add_properties strong").html(""); if (otherBookingPlatform) { if (!startDate) { // Check if startDate is empty $("#startDate_error").html('This field is required'); document.getElementById("startDate").focus(); return; // Stop the function if validation fails } } if (otherBookingPlatform) { $("endDate_error").html('This field is required'); document.getElementById("endDate").focus(); } var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("POST", baseurl + "/rentaladmin/updateproperty?propertyID=" + propertyID + "&landlordEmail=" + landlordEmail, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "" && this.readyState == 4) { var res = JSON.parse(this.responseText); var loginRes = res.response; // console.log(loginRes); var s = res.rspnsMsg; // console.log(s); var s = s.replace(/[{}]/g, ""); let pairs = s.split(', ') let obj = pairs.reduce((obj, data) => { let [k, v] = data.split('=') obj[k] = v return obj }, {}) // console.log(obj) // this is to clear error after user puts fills valid values $(".add_properties strong").html(""); // this is to populate error below each field in add properties form if (obj.zip == "Invalid Zip!!") { var error = document.getElementById("zip_error"); error.innerHTML = obj.zip; } if (obj.city == "Invalid City!!") { var error = document.getElementById("city_error"); error.innerHTML = obj.city; } if (obj.squareFeet == "Invalid Square Feet!!") { var error = document.getElementById("squareFeet_error"); error.innerHTML = obj.squareFeet; } if (obj.rentAmount == "Invalid Amount!!") { var error = document.getElementById("rentAmount_error"); error.innerHTML = obj.rentAmount; } if (obj.houseNo == "Invalid House Number!!") { var error = document.getElementById("houseNo_error"); error.innerHTML = obj.houseNo; } if (obj.streetAddress == "Invalid Street Address!!") { var error = document.getElementById("streetAddress_error"); error.innerHTML = obj.streetAddress; } if (obj.state == "Invalid State!!") { var error = document.getElementById("state_error"); error.innerHTML = obj.state; } if (obj.country == "Invalid Country!!") { var error = document.getElementById("country_error"); error.innerHTML = obj.country; } if (obj.type == "Please select an item") { var error = document.getElementById("type_error"); error.innerHTML = obj.type; } if (obj.bedrooms == "Please select an item") { var error = document.getElementById("bedrooms_error"); error.innerHTML = obj.bedrooms; } if (obj.bathrooms == "Please select an item") { var error = document.getElementById("bathrooms_error"); error.innerHTML = obj.bathrooms; } if (obj.furnishing == "Please select an item") { var error = document.getElementById("furnishing_error"); error.innerHTML = obj.furnishing; } if (obj.carParking == "Please select an item") { var error = document.getElementById("carParking_error"); error.innerHTML = obj.carParking; } if (obj.carParkingType == "Please select an item") { var error = document.getElementById("carParkingType_error"); error.innerHTML = obj.carParkingType; } if (obj.rentalRate == "Please select an item") { var error = document.getElementById("rentalRate_error"); error.innerHTML = obj.rentalRate; } if (res.rspnsMsg == "GOOD") { location.reload(); // window.location.href = window.location.protocol + "//" + window.location.host + "/admin/list-of-properties.html" } } else { var res = JSON.parse(this.responseText); console.log(res.response); if (res.response === "401 UNAUTHORIZED") { $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

You are not authorised for this action

"); $("#employee_modal_title").html("OOPS!!"); } } }; xmlhttp1.send(JSON.stringify({ "type": type, "bedrooms": bedrooms, "zip": zip, "furnishing": furnishing, "squareFeet": squareFeet, "carParking": carParking, "rentAmount": rentAmount, "houseNo": houseNo, "streetAddress": streetAddress, "city": city, "state": state, "country": country, "bathrooms": bathrooms, "rentalRate": rentalRate, "carParkingType": carParkingType, "termsAndConditions": termsAndConditions, "propertyDesc": propertyDesc, "number": number, "otherBookingPlatform": otherBookingPlatform, "startDate": startDate, "endDate": endDate })); console.log("waiting for server response...."); } //this is for invite applicant page-- property dropdown function loadAllProperties() { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/getproperties", true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); var dropdown = ''; for (var i = 0; i < response.length; i++) { if (response[i].deleteFlag == '0') { dropdown += ''; } } $("#propertyDropdown").html(dropdown); } } }; xmlhttp1.send(); } // this sends mail for inviting application function initInviteApplication() { var email = $("#customer_email").val(); var webBaseURL = window.location.protocol + "//" + window.location.host; var propertyID = $('#propertyDropdown').val(); if (propertyID == -1) { $("#error_propertyId").html("Please Select Required Property"); } if (!email || email.trim() === "") { $("#error_nullMail").html("Please fill Mail Id"); return; } // Validate proper email format var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!emailPattern.test(email)) { $("#error_nullMail").html("Please fill a valid Mail Id"); return; } var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("POST", baseurl + "/rentaladmin/inviteapplication?email=" + email + "&propertyID=" + propertyID + "&webBaseURL=" + webBaseURL, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "" && this.readyState == 4) { var res = JSON.parse(this.responseText); var loginRes = res.response; var s = res.rspnsMsg; // console.log(s); var s = s.replace(/[{}]/g, ""); const obj = Object.fromEntries([s.split("=")]) // console.log(obj) // console.log(obj.error); document.getElementById("error_nullMail").innerHTML = ""; document.getElementById("invite_email").innerHTML = ""; document.getElementById("error_propertyId").innerHTML = ""; if (propertyID == -1) { $("#error_propertyId").html("Please Select Required Property"); } if (email == "") { $("#error_nullMail").html("Please fill Mail Id"); return false; } if (obj.error == "Invalid Mail Id!!") { var error = document.getElementById("invite_email"); error.innerHTML = obj.error; } if (res.response == "SUCCESS") { $('#basicModal').modal("show"); $("#modal_message").html("

Email sent to applicant

"); $("#modal_title").html("SUCCESS!!"); // window.location.href = window.location.protocol + "//" + window.location.host + "/admin/invite-applicant.html" } } else if ((this.status == 403 || this.status == 401) && this.readyState == 4) { window.location.href = window.location.protocol + "//" + window.location.host + "/admin/pages-error-404.html" } else if (this.status == 500) { var res = JSON.parse(this.responseText); if (res.response === "401 UNAUTHORIZED") { $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

You are not authorised for this action

"); $("#employee_modal_title").html("OOPS!!"); } else { $('#basicModal').modal("show"); $("#modal_message").html("

Error sending mail....Please try again later

"); $("#modal_title").html("OOPS!!"); } } }; xmlhttp1.send(JSON.stringify({ "customer_email": email, "propertyID": propertyID, "webBaseURL": webBaseURL })); console.log("waiting for server response...."); } // this is for populating table of unsubmitted application(invite-applicant.html) function inviteapplicationwithoutproperty() { var email = $("#cust_user_email").val(); // console.log(email); var webBaseURL = window.location.protocol + "//" + window.location.host; var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("POST", baseurl + "/rentaladmin/inviteapplicationwithoutproperty?email=" + email + "&webBaseURL=" + webBaseURL, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "" && this.readyState == 4) { var res = JSON.parse(this.responseText); var loginRes = res.response; var s = res.rspnsMsg; // console.log(s); var s = s.replace(/[{}]/g, ""); const obj = Object.fromEntries([s.split("=")]) // console.log(obj) // console.log(obj.error); document.getElementById("user_nullMail").innerHTML = ""; document.getElementById("invite_email").innerHTML = ""; if (email == "") { $("#user_nullMail").html("Please fill Mail Id"); return false; } if (obj.error == "Invalid Mail Id!!") { var error = document.getElementById("user_invite_email"); error.innerHTML = obj.error; } if (res.response == "SUCCESS") { $('#basicModal').modal("show"); $("#modal_message").html("

Email sent to applicant

"); $("#modal_title").html("SUCCESS!!"); } } else if ((this.status == 403 || this.status == 401) && this.readyState == 4) { window.location.href = window.location.protocol + "//" + window.location.host + "/admin/pages-error-404.html" } else if (this.status == 500) { var res = JSON.parse(this.responseText); if (res.response === "401 UNAUTHORIZED") { $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

You are not authorised for this action

"); $("#employee_modal_title").html("OOPS!!"); } else { $('#basicModal').modal("show"); $("#modal_message").html("

Error sending mail....Please try again later

"); $("#modal_title").html("OOPS!!"); } } }; xmlhttp1.send(JSON.stringify({ "email": email, "webBaseURL": webBaseURL })); console.log("waiting for server response...."); } function getApplicantNumbers(navLinkId, status) { return new Promise(function (resolve, reject) { var xmlhttp1 = new XMLHttpRequest(); var apiUrl = baseurl + "/rentaladmin/unsubmittedapplication"; if (status && status.trim() !== "") { apiUrl += "?status=" + encodeURIComponent(status); } xmlhttp1.open("GET", apiUrl, true); xmlhttp1.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xmlhttp1.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("token")); xmlhttp1.onreadystatechange = function () { if (xmlhttp1.readyState === 4) { if (xmlhttp1.status === 200 && xmlhttp1.responseText) { try { var res = JSON.parse(xmlhttp1.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res.response); var count = Array.isArray(response) ? response.length : 0; if (document.getElementById("applicant_number")) { document.getElementById("applicant_number").innerHTML = count; } resolve(count); } else { resolve(0); } } catch (err) { console.error("Error parsing count:", err); reject(err); } } else { console.error("Error fetching applicant count:", xmlhttp1.status); reject(xmlhttp1.status); } } }; xmlhttp1.send(); }); } function getUnsubmitApplication(pageNumber) { var status = $('#statusFilter').val(); var pageSize = $('#pageSize').val(); var webBaseURL = window.location.protocol + "//" + window.location.host; var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } var apiUrl = baseurl + "/rentaladmin/unsubmittedapplication?pageNumber=" + pageNumber + "&pageSize=" + pageSize; if (status && status.trim() !== "") { apiUrl += "&status=" + encodeURIComponent(status); } xmlhttp1.open("GET", apiUrl, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); tableData = ''; if (response.length > 0) { for (i = 0; i < response.length; i++) { var phone = (response[i].rentProperty.applicant.phone); // console.log(response[i]); // debugTimeZones(response); if (response[i].status == "INIT") { var propertyInfo = response[i].rentProperty.propertyInfo; var propertyAddress = ""; if (propertyInfo["houseNo"] !== null && propertyInfo["streetAddress"] !== null && propertyInfo["city"] !== null && propertyInfo["zip"] !== null && propertyInfo["state"] !== null && propertyInfo["country"] !== null) { propertyAddress = propertyInfo["houseNo"] + ", " + propertyInfo["streetAddress"] + ", " + propertyInfo["city"] + ", " + propertyInfo["zip"] + ", " + propertyInfo["state"] + ", " + propertyInfo["country"]; } var copyLink = webBaseURL + "" + "/applicationform.html?appID=" + "" + response[i].applicationID; tableData += ''; tableData += '' + ((pageNumber - 1) * pageSize + (i + 1)) + ''; tableData += '' + response[i].email + ''; tableData += '' + ((phone) ? phone : "-") + ''; tableData += '' + propertyAddress + ''; tableData += '' + "Unsubmitted" + ''; // var propertyAddress = response[i].rentProperty.propertyAddress || ""; // tableData += '' + (propertyAddress !== "" ? propertyAddress : "") + ''; // tableData += '' + (propertyAddress !== "" ? "Unsubmitted" : "") + ''; tableData += '' + ' ' + '' + ' ' + ''; tableData += '' + convertToPreferredTimezone(response[i].createTimeStamp) + ''; tableData += '' + convertToPreferredTimezone(response[i].updateTimeStamp) + ''; } else if (response[i].status == "REQUEST") { var propertyInfo = response[i].rentProperty.propertyInfo; var propertyAddress = ""; if (propertyInfo["houseNo"] !== null && propertyInfo["streetAddress"] !== null && propertyInfo["city"] !== null && propertyInfo["zip"] !== null && propertyInfo["state"] !== null && propertyInfo["country"] !== null) { propertyAddress = propertyInfo["houseNo"] + ", " + propertyInfo["streetAddress"] + ", " + propertyInfo["city"] + ", " + propertyInfo["zip"] + ", " + propertyInfo["state"] + ", " + propertyInfo["country"]; } // var propertyAddress = response[i].rentProperty.propertyInfo["houseNo"] + ", " + response[i].rentProperty.propertyInfo["streetAddress"] + ", " + // response[i].rentProperty.propertyInfo["city"] + ", " + response[i].rentProperty.propertyInfo["zip"] + ", " + response[i].rentProperty.propertyInfo["state"] + ", " + response[i].rentProperty.propertyInfo["country"]; var copyLink = webBaseURL + "" + "/applicationform.html?appID=" + "" + response[i].applicationID; tableData += ''; tableData += '' + ((pageNumber - 1) * pageSize + (i + 1)) + ''; tableData += '' + response[i].email + ''; tableData += '' + ((phone) ? phone : "-") + ''; tableData += '' + propertyAddress + ''; tableData += '' + "Requested to Apply" + ''; tableData += '' + '' + ' ' + ''; tableData += '' + convertToPreferredTimezone(response[i].createTimeStamp) + ''; tableData += '' + convertToPreferredTimezone(response[i].updateTimeStamp) + ''; } else if (response[i].status == "PARTIAL") { var propertyInfo = response[i].rentProperty.propertyInfo; var propertyAddress = ""; if (propertyInfo["houseNo"] !== null && propertyInfo["streetAddress"] !== null && propertyInfo["city"] !== null && propertyInfo["zip"] !== null && propertyInfo["state"] !== null && propertyInfo["country"] !== null) { propertyAddress = propertyInfo["houseNo"] + ", " + propertyInfo["streetAddress"] + ", " + propertyInfo["city"] + ", " + propertyInfo["zip"] + ", " + propertyInfo["state"] + ", " + propertyInfo["country"]; } // var propertyAddress = response[i].rentProperty.propertyInfo["houseNo"] + ", " + response[i].rentProperty.propertyInfo["streetAddress"] + ", " + // response[i].rentProperty.propertyInfo["city"] + ", " + response[i].rentProperty.propertyInfo["zip"] + ", " + response[i].rentProperty.propertyInfo["state"] + ", " + response[i].rentProperty.propertyInfo["country"]; var copyLink = webBaseURL + "" + "/applicationform.html?appID=" + "" + response[i].applicationID + "&status=PARTIAL"; tableData += ''; tableData += '' + ((pageNumber - 1) * pageSize + (i + 1)) + ''; tableData += '' + response[i].email + ''; tableData += '' + ((phone) ? phone : "-") + ''; tableData += '' + propertyAddress + ''; tableData += '' + "Partial" + ''; tableData += '' + ' ' + '' + ' ' + ''; tableData += '' + convertToPreferredTimezone(response[i].createTimeStamp) + ''; tableData += '' + convertToPreferredTimezone(response[i].updateTimeStamp) + ''; } else if (response[i].status == "SAVE") { var propertyInfo = response[i].rentProperty.propertyInfo; var propertyAddress = ""; if (propertyInfo["houseNo"] !== null && propertyInfo["streetAddress"] !== null && propertyInfo["city"] !== null && propertyInfo["zip"] !== null && propertyInfo["state"] !== null && propertyInfo["country"] !== null) { propertyAddress = propertyInfo["houseNo"] + ", " + propertyInfo["streetAddress"] + ", " + propertyInfo["city"] + ", " + propertyInfo["zip"] + ", " + propertyInfo["state"] + ", " + propertyInfo["country"]; } var copyLink = webBaseURL + "" + "/applicationform.html?appID=" + "" + response[i].applicationID; tableData += ''; tableData += '' + ((pageNumber - 1) * pageSize + (i + 1)) + ''; tableData += '' + response[i].email + ''; tableData += '' + ((phone) ? phone : "-") + ''; tableData += '' + propertyAddress + ''; tableData += '' + "Saved" + ''; tableData += '' + ' ' + '' + ' ' + ''; tableData += '' + convertToPreferredTimezone(response[i].createTimeStamp) + ''; tableData += '' + convertToPreferredTimezone(response[i].updateTimeStamp) + ''; } } } else { tableData = "No Applicants for now" } } document.getElementById('unsubmitapp').innerHTML = tableData; } }; xmlhttp1.send(); } // this is for copy link to clipboard for tables function copyText(copyLink) { var body = $(window.document.body); var textarea = $(' `); // Format notes: "YYYY-MM-DD HH:MM - text" let formattedNotes = notes .filter(note => (note.datetime || note.text)) .map(note => { let dt = note.datetime ? new Date(note.datetime).toLocaleString('sv-SE').replace('T', ' ') : ''; return `${dt} - ${note.text || ''}`.trim(); }) .join('\n'); document.getElementById('lead_notes').value = formattedNotes; // --- Schedule Section --- try { const scheduleObj = JSON.parse(lead.schedule || "{}"); scheduleDatetimeInput.value = scheduleObj.datetime || ""; schedulePlaceInput.value = scheduleObj.place || ""; } catch (e) { console.warn("Invalid schedule JSON"); scheduleDatetimeInput.value = ""; schedulePlaceInput.value = ""; } } } } else { alert("Service not opening"); } } else if (this.readyState === 4) { console.log("Request failed with status: " + xmlhttp1.status); } }; xmlhttp1.send(); } // End the code function showOfferDetails(offerID) { let offered_By = document.getElementById("issued_by"); let Offer_Start = document.getElementById("startedOnDate"); let offer_End = document.getElementById("endByDate"); let offer_Detail = document.getElementById("offer_details"); let tenant = document.getElementById("tenant"); let status = 'ALL'; var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/getOffers?status=" + status, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { // console.log( Offer_Start); if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res.response); for (var i = 0; i < response.length; i++) { console.log(response); if (response[i].offerID == offerID) { Offer_Start.innerHTML = convertToPreferredTimezone(response[i].validfromDate, "MM-DD-YY"); offer_End.innerHTML = convertToPreferredTimezone(response[i].validuptoDate, "MM-DD-YY"); offered_By.innerHTML = response[i].issuedBy; offer_Detail.innerHTML = response[i].details; tenant.innerHTML = response[i].tenant_name; } } } else { alert("Service not opening"); } } else { console.log("Request failed with status: " + xmlhttp1.status); } }; xmlhttp1.send(); } function getOffersNumbers(navLinkId) { const status = sessionStorage.getItem("selectedStatus") || "ALL"; if (navLinkId == null) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } const url = baseurl + "/rentaladmin/getOffers?status=" + status; // alert("Request URL get offers: " + url); xmlhttp1.open("GET", url, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 && this.responseText != null && this.responseText !== "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); var count = response.length; document.getElementById('task_offer').innerHTML = count; } } }; xmlhttp1.send(); } else { return new Promise(function (resolve, reject) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } const url = baseurl + "/rentaladmin/getOffers?status=" + status; // alert("Request URL: " + url); xmlhttp1.open("GET", url, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 && this.responseText != null && this.responseText !== "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); var count = response.length; // alert(count); resolve(count); } } }; xmlhttp1.send(); }); } } function deleteLeads(leadID) { var confirmDelete = confirm("Are you sure you want to delete this lead?"); if (!confirmDelete) { return; } var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("POST", baseurl + "/rentaladmin/deletelead?id=" + leadID, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onload = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { console.log(res); console.log("lead Deleted"); } else { alert("lead not Deleted"); } } else { var res = JSON.parse(this.responseText); console.log(res.response); if (res.response === "401 UNAUTHORIZED") { $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

You are not authorised for this action

"); $("#employee_modal_title").html("OOPS!!"); } } }; xmlhttp1.send(); // location.reload(); setTimeout(() => { window.location.href = window.location.protocol + "//" + window.location.host + "/admin/leads.html"; }, 1000); } // <---------------- SHORT TEMR LEASE FUNCTIONS ---------------- > short_term_page = () => { window.location.href = "/admin/short-term.html"; // Replace "short term" with the actual filename } // SHORT TERM LEASE ::: ??? function getshortterm(navLinkId) { function fetchShortTermFilteredCount() { return new Promise(function (resolve, reject) { var xhr; try { xhr = new XMLHttpRequest(); } catch (e) { try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return reject(e); } } } xhr.open("GET", baseurl + "/rentaladmin/shortterm?type=ACTIVE", true); xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("token")); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200 && xhr.responseText) { try { var res = JSON.parse(xhr.responseText); if (res.rspnsCode !== 1000) return resolve(0); let response = []; try { response = JSON.parse(res.response); } catch (e) { response = []; } let filteredCount = 0; for (let lease of response) { const currentLeaseEnd = lease.currentLeaseEnd || null; const nextLeaseStart = lease.nextLeaseStart || null; const maintenanceEnd = lease.maintenanceEndDate || null; // Skip: currentLeaseEnd == nextLeaseStart if (currentLeaseEnd && nextLeaseStart && currentLeaseEnd.substring(0, 10) === nextLeaseStart.substring(0, 10)) { continue; } // Skip: maintenanceEnd == nextLeaseStart if (maintenanceEnd && nextLeaseStart && maintenanceEnd.substring(0, 10) === nextLeaseStart.substring(0, 10)) { continue; } filteredCount++; } resolve(filteredCount); } catch (e) { resolve(0); } } }; xhr.send(); }); } if (navLinkId == null) { fetchShortTermFilteredCount().then(count => { document.getElementById("short_term_no").innerHTML = count; }); } else { return fetchShortTermFilteredCount(); } } // Date format function (6-Sep-2025 jaisa format ke liye) function formatDate(date) { const options = { day: "2-digit", month: "short", year: "numeric" }; return new Date(date).toLocaleDateString("en-GB", options).replace(/ /g, "-"); } // Function to show Short term lease data function listshortterm(pageNumber) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE: " + e.message); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/shortterm?type=ACTIVE", true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200 && this.responseText) { try { var res = JSON.parse(this.responseText); if (res.rspnsCode !== 1000) { document.getElementById('short_term_lease').innerHTML = 'Error loading data'; return; } var response = []; try { response = JSON.parse(res.response); } catch (e) { response = []; } var tableData = ''; if (response.length > 0) { let sequenceNumber = (pageNumber - 1) * pageSize + 1; const webBaseURL = window.location.protocol + "//" + window.location.host; for (let lease of response) { const currentLeaseEnd = lease.currentLeaseEnd || null; const nextLeaseStart = lease.nextLeaseStart || null; const maintenanceEnd = lease.maintenanceEndDate || null; // skip if currentLeaseEnd == nextLeaseStart if (currentLeaseEnd && nextLeaseStart && currentLeaseEnd.substring(0, 10) === nextLeaseStart.substring(0, 10)) { continue; } // skip if maintenanceEndDate == nextLeaseStart if (maintenanceEnd && nextLeaseStart && maintenanceEnd.substring(0, 10) === nextLeaseStart.substring(0, 10)) { continue; } const propertyvo = lease.propertyvo || {}; const addressParts = [ propertyvo.houseNo, propertyvo.streetAddress, propertyvo.city, propertyvo.state, propertyvo.country ].filter(Boolean); const fullAddress = addressParts.join(" , ") || "N/A"; const propertyId = lease.propertyId || ""; const copyLinks = propertyId ? `${webBaseURL}/propertydetails.html?propertyID=${propertyId}` : "#"; let availableFrom = "N/A"; let iconHTML = ""; if (maintenanceEnd) { availableFrom = formatDate(maintenanceEnd); iconHTML = ``; } else if (currentLeaseEnd) { const leaseEnd = new Date(currentLeaseEnd); const today = new Date(); if (leaseEnd <= today) { availableFrom = formatDate(today); } else { availableFrom = formatDate(leaseEnd); } } const nextLeaseStartFormatted = nextLeaseStart ? formatDate(nextLeaseStart) : "N/A"; tableData += ` ${sequenceNumber} ${fullAddress} ${availableFrom} ${iconHTML} ${nextLeaseStartFormatted} `; sequenceNumber++; } } else { tableData = 'No short-term leases for now'; } document.getElementById('short_term_lease').innerHTML = tableData; } catch (e) { document.getElementById('short_term_lease').innerHTML = 'Failed to parse server response.'; } } } }; xmlhttp1.send(); } function copyTexts(text) { if (!text || text === "#") { alert("❌ Invalid property link!"); return; } // Secure context (https ya localhost) if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(text).then(() => { alert("✅ Property link copied! Paste it in browser to open."); }).catch(() => { fallbackCopy(text); // agar reject hua toh fallback }); } else { // Agar dev http hai toh sidha fallback fallbackCopy(text); } } function fallbackCopy(text) { const textarea = document.createElement("textarea"); textarea.value = text; textarea.style.position = "fixed"; // screen ke corner pe textarea.style.opacity = "0"; // invisible document.body.appendChild(textarea); textarea.focus(); textarea.select(); try { document.execCommand("copy"); alert("✅ Property link copied !"); } catch (err) { alert("❌ Failed to copy: " + err.message); } document.body.removeChild(textarea); } // this is for populating list of properties for bulk transaction purpose function getSelectedProperties(searchVal, inputElement) { const container = inputElement.closest('.transaction-line'); const suggestionBox = container.querySelector(".propertySuggestions"); const propertyIdInput = container.querySelector(".propertyIdInput"); suggestionBox.innerHTML = ""; // Clear suggestions if (!searchVal) return; const processedSearch = searchVal.replace(/[, -]/g, "%"); let xmlhttp; try { xmlhttp = new XMLHttpRequest(); } catch (e) { alert("Browser not supported"); return; } xmlhttp.open("GET", baseurl + "/rentaladmin/getproperties?keyword=" + encodeURIComponent(processedSearch), true); xmlhttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200 && this.responseText) { const result = JSON.parse(this.responseText); if (result.rspnsCode === 1000) { const properties = JSON.parse(result.response); const labels = []; properties.forEach(function (property) { if (property.deleteFlag === '0') { const info = property.propertyInfo; const label = info.houseNo + ", " + info.streetAddress + ", " + info.city + ", " + info.state + " - " + info.zip + ", " + info.country; if (labels.includes(label)) return; labels.push(label); const item = document.createElement("a"); item.classList.add("list-group-item", "list-group-item-action"); item.textContent = label; item.onclick = function () { inputElement.value = label; suggestionBox.innerHTML = ""; propertyIdInput.value = property.propertyId; loadBulkAllLeases(property.propertyId, container); }; suggestionBox.appendChild(item); } }); if (!suggestionBox.hasChildNodes()) { suggestionBox.innerHTML = '
No matching properties
'; } } else { alert("Server responded with rspnsCode: " + result.rspnsCode); } } else { alert("Request failed."); } } }; xmlhttp.send(); } function loadBulkAllLeases(propertyID, container) { let xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/listleasesforproperty?propertyID=" + propertyID, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 && this.responseText) { const res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { const response = JSON.parse(res.response); let dropdownHTML = ''; for (let i = 0; i < response.length; i++) { if (response[i].status === "DEFAULT") { dropdownHTML += ``; } else { dropdownHTML += ``; } } // Update only the lease dropdown in the current row const leaseDropdown = container.querySelector(".leaseDropdown"); if (leaseDropdown) { leaseDropdown.innerHTML = dropdownHTML; } } } }; xmlhttp1.send(); } function listBulkTransactionType(container) { let xmlhttp; try { xmlhttp = new XMLHttpRequest(); } catch (e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp.open("GET", baseurl + "/rentaladmin/listtransactiontypeandsub?key=type", true); xmlhttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 && this.responseText) { const res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { const response = JSON.parse(res.response); const obj = Object.entries(response); let dropdown = ''; for (let i = 0; i < obj.length; i++) { dropdown += ``; } const typeDropdown = container.querySelector(".transaction_type"); if (typeDropdown) typeDropdown.innerHTML = dropdown; } } }; xmlhttp.send(); } function listBulkTransactionSubType(container) { let xmlhttp; try { xmlhttp = new XMLHttpRequest(); } catch (e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp.open("GET", baseurl + "/rentaladmin/listtransactiontypeandsub?key=subtype", true); xmlhttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 && this.responseText) { const res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { const response = JSON.parse(res.response); const obj = Object.entries(response); let dropdown = ''; for (let i = 0; i < obj.length; i++) { dropdown += ``; } const subTypeDropdown = container.querySelector(".transaction_sub_type"); if (subTypeDropdown) subTypeDropdown.innerHTML = dropdown; } } }; xmlhttp.send(); } // this is ajax for add bulk transaction (submit button) function bulkAddTransaction() { var transactions = []; var isValid = true; // Clear previous errors $('.property_error, .tenant_error, .date_error, .type_error, .sub_type_error, .details_error, .amount_error').html(''); // Collect all transaction line data $('.transaction-line').each(function () { var $row = $(this); var rowIsValid = true; var propertyID = $row.find('.propertyIdInput').val(); var leaseID = $row.find('.leaseDropdown').val(); var paymentDate = $row.find(".payment_date").val(); var transaction_type = $row.find('.transaction_type').val(); var transaction_sub_type = $row.find('.transaction_sub_type').val(); var details = $row.find(".trans_details").val(); var amount = $row.find('.trans_amount').val(); var account = $row.find('.account').val(); // ensure you have this input var referenceID = $row.find('.transaction_reference_id').val(); // ensure you have this input var outsideAccount = $row.find('.outside_account').is(":checked"); // checkbox if (!propertyID) { $row.find('.property_error').text('Please select a property.'); rowIsValid = false; } if (!leaseID) { $row.find('.leaseDropdown').next('.text-danger').text('Please select a tenant.'); rowIsValid = false; } if (!paymentDate) { $row.find('.payment_date').next('.text-danger').text('Please select a date.'); rowIsValid = false; } if (!transaction_type) { $row.find('.transaction_type').next('.text-danger').text('Please select a transaction type.'); rowIsValid = false; } if (!transaction_sub_type) { $row.find('.transaction_sub_type').next('.text-danger').text('Please select a transaction sub-type.'); rowIsValid = false; } if (!amount || isNaN(amount) || parseFloat(amount) <= 0) { $row.find('.trans_amount').next('.text-danger').text('Please enter a valid amount.'); rowIsValid = false; } if (rowIsValid) { transactions.push({ propertyID, leaseID, paymentDate, transactionType: transaction_type, transactionSubType: transaction_sub_type, details, amount: parseFloat(amount), account, referenceID, outsideAccount }); } else { isValid = false; } }); if (!isValid || transactions.length === 0) { return false; } $(".transactSubmit").css("display", "none"); let success = 0; let failure = 0; transactions.forEach((txn, index) => { var xmlhttp; try { xmlhttp = new XMLHttpRequest(); } catch (e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp.onreadystatechange = function () { if (this.readyState === 4) { $(".transactSubmit").css("display", "inline-block"); if (this.status === 200 && this.responseText) { var res = JSON.parse(this.responseText); var s = res.rspnsMsg.replace(/[{}]/g, ""); let pairs = s.split(', '); let obj = pairs.reduce((acc, pair) => { let [k, v] = pair.split('='); acc[k] = v; return acc; }, {}); if (obj.amount === "Please fill a valid amount") { alert(`Transaction ${index + 1} failed: Invalid amount.`); failure++; } else if (res.rspnsMsg === "GOOD") { success++; } } else { failure++; if (this.status === 401) { $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

You are not authorised for this action

"); $("#employee_modal_title").html("OOPS!!"); } } if (success + failure === transactions.length) { if (success === transactions.length) { alert("All transactions added successfully!"); window.location.href = window.location.protocol + "//" + window.location.host + "/admin/transactions.html"; } else if (success > 0) { alert(`${success} transactions succeeded, ${failure} failed. Please review.`); } else { alert("All transactions failed."); } } } }; xmlhttp.open("POST", baseurl + `/rentaladmin/addtransaction?leaseID=${txn.leaseID}&propertyID=${txn.propertyID}`, true); xmlhttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.send(JSON.stringify({ account: txn.account, transactionType: txn.transactionType, transactionSubType: txn.transactionSubType, referenceID: txn.referenceID, amount: txn.amount, payDate: txn.paymentDate, details: txn.details, outsideAccount: txn.outsideAccount })); }); } function generateOfferCode() { const prefixLength = Math.floor(Math.random() * 3) + 4; const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; let prefix = ""; for (let i = 0; i < prefixLength; i++) { prefix += letters[Math.floor(Math.random() * letters.length)]; } const number = Math.floor(1000 + Math.random() * 9000); const code = `${prefix}${number}`; document.getElementById('unique_code').value = code; } // <-----------------------Schedule Card ----------------------> schedule_card = () => { window.location.href = "/admin/schedule.html"; } // <--------- Schedule card Count ------------------> function getScheduleNumbers(navLinkId) { const type = "ACTIVE"; if (navLinkId == null) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/leadshedule?type=ACTIVE", true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); // console.log(response); var count = 0; for (var i = 0; i < response.length; i++) { count++; } console.log(count); document.getElementById('schedule_count').innerHTML = count; } } }; xmlhttp1.send(); } else { return new Promise(function (resolve, reject) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/leadshedule?type=ACTIVE", true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); // console.log(response); var count = 0; for (var i = 0; i < response.length; i++) { count++; } // document.getElementById('applicant_number').innerHTML = response.length; resolve(count); } } }; xmlhttp1.send(); }); } } // Function To Show Data function listschedule(pageNumber) { let xhr = new XMLHttpRequest(); const pageSize = document.getElementById('pageSize') ? parseInt(document.getElementById('pageSize').value) : 10; xhr.open("GET", baseurl + "/rentaladmin/leadshedule?type=ACTIVE", true); xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xhr.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200 && this.responseText) { try { let leads = JSON.parse(this.responseText); if (leads && leads.rspnsCode === 1000 && leads.response) leads = JSON.parse(leads.response); if (!Array.isArray(leads)) leads = [leads]; const start = (pageNumber - 1) * pageSize; const rows = leads.slice(start, start + pageSize).map((lead, i) => { let schedule = {}; try { schedule = lead.schedule ? JSON.parse(lead.schedule) : {}; } catch { } return ` ${start + i + 1} ${lead.full_name || "N/A"} ${lead.email || "N/A"} ${lead.contact_number || "N/A"} ${schedule.datetime ? convertToPreferredTimezone(schedule.datetime, "YYYY-MM-DD hh:mm:ss A") : "N/A"} ${schedule.place || "N/A"} `; }).join(""); document.getElementById('schedule_data').innerHTML = rows || 'No leads to display for now'; } catch (e) { console.error("Parsing error:", e, this.responseText); document.getElementById('schedule_data').innerHTML = 'Failed to parse server response.'; } } else { console.error("AJAX Error:", this.status, this.responseText); document.getElementById('schedule_data').innerHTML = 'Error fetching data.'; } } }; xhr.send(); } // <--------------- Function to show schedule details ------------------> function showScheduledetails(scheduleID) { let schedule_name = document.getElementById("schedule_name"); let schedule_email = document.getElementById("schedule_email"); let schedule_Cnumber = document.getElementById("schedule_Cnumber"); let schedule_address = document.getElementById("schedule_address"); let schedule_date = document.getElementById("schedule_date"); let schedule_place = document.getElementById("schedule_place"); if (schedule_name) schedule_name.innerHTML = 'Loading...'; if (schedule_email) schedule_email.innerHTML = 'Loading...'; if (schedule_Cnumber) schedule_Cnumber.innerHTML = 'Loading...'; if (schedule_address) schedule_address.innerHTML = 'Loading...'; if (schedule_date) schedule_date.innerHTML = 'Loading...'; if (schedule_place) schedule_place.innerHTML = 'Loading...'; var xmlhttp1 = new XMLHttpRequest(); xmlhttp1.open("GET", baseurl + "/rentaladmin/leadshedule?type=ACTIVE", true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200 && this.responseText) { try { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response; try { response = JSON.parse(res.response); } catch (eInner) { console.error("Error parsing inner 'response' JSON:", eInner); if (schedule_name) schedule_name.innerHTML = 'Invalid API Data Format'; return; } if (!Array.isArray(response)) { response = [response]; } let leadFound = false; for (var i = 0; i < response.length; i++) { if (response[i].id == scheduleID) { const currentLead = response[i]; leadFound = true; // Populate basic details if (schedule_name) schedule_name.innerHTML = currentLead.full_name || 'N/A'; if (schedule_email) schedule_email.innerHTML = currentLead.email || 'N/A'; if (schedule_Cnumber) schedule_Cnumber.innerHTML = currentLead.contact_number || 'N/A'; if (schedule_address) schedule_address.innerHTML = currentLead.preferred_address || 'N/A'; let displayScheduleDate = 'N/A'; let displaySchedulePlace = 'N/A'; if (currentLead.schedule) { try { const schedule = JSON.parse(currentLead.schedule); if (schedule.datetime) { displayScheduleDate = convertToPreferredTimezone(schedule.datetime, "YYYY-MM-DD hh:mm:ss A"); } displaySchedulePlace = schedule.place || 'N/A'; } catch (e) { console.error("Error parsing 'schedule' field for lead ID " + scheduleID + ":", e, "Raw schedule string:", currentLead.schedule); displayScheduleDate = "Error Parsing Schedule"; displaySchedulePlace = "Error Parsing Schedule"; } } if (schedule_date) schedule_date.innerHTML = displayScheduleDate; if (schedule_place) schedule_place.innerHTML = displaySchedulePlace; break; } } if (!leadFound) { if (schedule_name) schedule_name.innerHTML = 'Lead not found with ID: ' + scheduleID; if (schedule_email) schedule_email.innerHTML = 'N/A'; if (schedule_Cnumber) schedule_Cnumber.innerHTML = 'N/A'; if (schedule_address) schedule_address.innerHTML = 'N/A'; if (schedule_date) schedule_date.innerHTML = 'N/A'; if (schedule_place) schedule_place.innerHTML = 'N/A'; } } else { alert("Service not opening: " + (res.rspnsMsg || "Unknown API error")); if (schedule_name) schedule_name.innerHTML = 'API Error: ' + (res.rspnsMsg || 'Unknown'); } } catch (eOuter) { console.error("Error parsing initial API response JSON or processing data:", eOuter); console.error("Raw responseText from server:", this.responseText); if (schedule_name) schedule_name.innerHTML = 'Error Processing Data'; alert("An error occurred while processing data. Check console."); } } else { console.error("AJAX Request Failed. Status:", this.status, "Response Text:", this.responseText); if (schedule_name) schedule_name.innerHTML = 'Failed to Fetch Data. Status: ' + this.status; alert("Failed to fetch data from the server."); } } }; xmlhttp1.send(); } function downloadOfferCsv() { const fileName = "offer" + ".csv"; const xhr = new XMLHttpRequest(); xhr.open("GET", baseurl + "/rentaladmin/csvfiledownloadoffers", true); xhr.responseType = "blob"; xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xhr.onload = function () { if (xhr.status === 200) { const blob = new Blob([xhr.response], { type: "text/csv" }); const link = document.createElement("a"); link.href = window.URL.createObjectURL(blob); link.download = fileName; link.click(); } }; xhr.send(); } function downloadTransactionPdf(property, leaseID) { let propertyDropdown = document.getElementById("propertyDropdownForLease"); let selectedText = propertyDropdown.options[propertyDropdown.selectedIndex].text; let trimmedPropertyText = selectedText.split(",").slice(0, 3).join(","); trimmedPropertyText = trimmedPropertyText.trim(); let leaseDropdown = document.getElementById("leaseDropdown"); let tenantNameText = leaseDropdown.options[leaseDropdown.selectedIndex].text; let trimmedTenantName = tenantNameText.split(" - ")[0].trim(); let filename = trimmedTenantName + "_" + trimmedPropertyText + ".pdf"; // Create AJAX request let xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } let url = baseurl + "/rentaladmin/downloadpdftransaction?propertyID=" + property + "&leaseID=" + leaseID; xmlhttp1.open("GET", url, true); xmlhttp1.responseType = 'arraybuffer'; xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (xmlhttp1.readyState === 4) { if (xmlhttp1.status === 200) { if (xmlhttp1.response.byteLength === 0) { alert("Empty PDF file received."); window.location.href = window.location.protocol + "//" + window.location.host + "/error.html"; } else { const blob = new Blob([xmlhttp1.response], { type: "application/pdf" }); const link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = filename; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } else { alert("Failed to download PDF. Status: " + xmlhttp1.status); } } }; xmlhttp1.send(); } function loadAllPropertiesTask() { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/getproperties", true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); var dropdown = ''; for (var i = 0; i < response.length; i++) { if (response[i].deleteFlag == '0') { dropdown += ''; } } dropdown += ''; $("#propertyDropdown").html(dropdown); } } }; xmlhttp1.send(); } //This function is used on the maintenance task page for searching properties. function getPropertiesTask(searchVal) { const suggestionBox = document.getElementById("propertySuggestions"); const propertyIdInput = document.getElementById("propertyId"); suggestionBox.innerHTML = ""; if (!searchVal || searchVal.trim().length < 1) return; const keyword = searchVal.trim().toLowerCase(); const otherWords = ["other", "others", "oth", "othe", "other property", "custom", "custom property"]; // If user is typing "other" → show custom option if (otherWords.some(w => keyword.includes(w))) { const item = document.createElement("a"); item.className = "list-group-item list-group-item-action"; item.textContent = "Other (Custom Property)"; item.onclick = () => { document.getElementById("propertyDropdown").value = "Other (Custom Property)"; // Set propertyId = -1 propertyIdInput.value = "-1"; // Show custom text field customPropertyInput.style.display = "block"; customPropertyInput.placeholder = "Enter property here"; suggestionBox.innerHTML = ""; listMaintenanceTasks(); }; suggestionBox.appendChild(item); return; } // Normal flow: call API when not typing "other" const xhr = new XMLHttpRequest(); xhr.open("GET", baseurl + "/rentaladmin/getproperties?keyword=" + encodeURIComponent(keyword), true); xhr.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("token")); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { const result = JSON.parse(xhr.responseText); if (result.rspnsCode === 1000 && result.response) { const properties = JSON.parse(result.response); const matched = []; properties.forEach(p => { const info = p.propertyInfo || {}; const text = `${info.type || ""} ${info.houseNo || ""} ${info.streetAddress || ""} ${info.city || ""} ${info.state || ""} ${info.zip || ""} ${info.country || ""}` .toLowerCase(); if (text.includes(keyword)) { matched.push({ id: p.propertyId, label: `${info.type} - ${info.houseNo}, ${info.streetAddress}, ${info.city}, ${info.state} - ${info.zip}, ${info.country}` }); } }); matched.forEach(m => { const item = document.createElement("a"); item.className = "list-group-item list-group-item-action"; item.textContent = m.label; item.onclick = () => { document.getElementById("propertyDropdown").value = m.label; suggestionBox.innerHTML = ""; propertyIdInput.value = m.id; listMaintenanceTasks(); }; suggestionBox.appendChild(item); }); } } }; xhr.send(); } function listBlockedProperties(keyword) { var xmlhttp; var webBaseURL = window.location.protocol + "//" + window.location.host; try { xmlhttp = new XMLHttpRequest(); } catch (e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } if (keyword) { keyword = keyword.replace(/,/g, "%"); keyword = keyword.replace(/-/g, "%"); keyword = keyword.replace(/ /g, "%"); } var path = "/rentaladmin/showdeletedproperty"; if (keyword) { path = "/rentaladmin/showdeletedproperty?keyword=" + keyword; } xmlhttp.open("GET", baseurl + path, true); xmlhttp.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "" && this.readyState == 4) { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res['response']); var dynamicCard = document.querySelector('.container_card'); dynamicCard.innerHTML = ''; if (response.length > 0) { for (var i = 0; i < response.length; i++) { console.log(response); var s = JSON.parse(response[i].imageList); var firstImage = s != null ? s[0].imageLink : "assets/img/img for card.jpg"; var copyLink = webBaseURL + "" + "/propertydetails.html?propertyID=" + "" + response[i].propertyId; var tempHtml = ""; var propertyID = response[i].propertyId; tempHtml = `
Image Title

${response[i].propertyInfo["type"]}

$${response[i].propertyInfo["rentAmount"]}/${response[i].propertyInfo["rentalRate"]}

${response[i].propertyInfo["houseNo"]} ${response[i].propertyInfo["streetAddress"]} ${response[i].propertyInfo["city"]} ${response[i].propertyInfo["state"]} - ${response[i].propertyInfo["zip"]} ${response[i].propertyInfo["country"]}

${response[i].propertyInfo["squareFeet"]} Sq Ft ${response[i].propertyInfo["bedrooms"]} Bedrooms ${response[i].propertyInfo["bathrooms"]} Bathrooms ${response[i].propertyInfo["furnishing"]} ${response[i].propertyInfo["carParking"]} ${response[i].propertyInfo["carParkingType"]}

`; dynamicCard.innerHTML += tempHtml; disableDeleteButtons() } } else { dynamicCard.innerHTML = "No Blocked properties for now"; } } } } xmlhttp.send(); } function unblockProperty(propertyID) { var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject( "Microsoft.XMLHTTP") } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("POST", baseurl + "/rentaladmin/unblockdeletedproperty?propertyID=" + propertyID, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); if (confirm('Are you sure you want to unblock this property')) { xmlhttp1.onreadystatechange = function () { if (this.status == 200 && this.responseText != null && this.responseText != "") { var res = JSON.parse(this.responseText); var resp = res.response; // console.log(resp); window.location.href = window.location.protocol + "//" + window.location.host + "/admin/list-of-properties.html"; } else { var res = JSON.parse(this.responseText); console.log(res.response); if (res.response === "401 UNAUTHORIZED") { $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

You are not authorised for this action

"); $("#employee_modal_title").html("OOPS!!"); } } }; xmlhttp1.send(JSON.stringify({ "propertyInfo": { // "bedrooms": bedrooms, "city": city, "country": country, "houseNo": houseNo, // "pets": pets, // "rentAmount": rentamount, // "squareFeet": squareFeet, "state": state, // "streetAddress": streetaddress, // "type": type, "zip": zip }, })); } } // Called when the "Rent Paid" button is clicked.It fetches the list of approved leases from the backend and dynamically populates. function handleRentPaid(pageNumber, searchVal) { document.getElementById("rentDueContainer").innerHTML = ""; const type = "ACTIVE"; var pageSize = $('#pageSize').val(); var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/listapprovedlease?type=" + type, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 && this.responseText) { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res.response); console.log(response); let container = document.getElementById("rentPaidContainer"); container.innerHTML = ""; // clear old rows for (let i = 0; i < response.length; i++) { let lease = response[i].lease; // Format property address let propertyAddress = ""; if (lease) { propertyAddress = (lease.houseNo ? lease.houseNo + ", " : "") + (lease.streetAddress ? lease.streetAddress + ", " : "") + (lease.city ? lease.city + ", " : "") + (lease.state ? lease.state + " - " : "") + (lease.zip ? lease.zip + ", " : "") + (lease.country ? lease.country : ""); } let rentAmount = lease && lease.rentAmount ? lease.rentAmount : ""; let now = new Date(); let firstDay = new Date(now.getFullYear(), now.getMonth(), 1); let year = firstDay.getFullYear(); let month = String(firstDay.getMonth() + 1).padStart(2, '0'); // month is 0-based let day = String(firstDay.getDate()).padStart(2, '0'); let firstDayStr = `${year}-${month}-${day}`; const monthAbbr = firstDay.toLocaleString('default', { month: 'short' }); let defaultDetails = `${monthAbbr} Rent Paid`; let rowHTML = `
`; container.insertAdjacentHTML("beforeend", rowHTML); let newRow = container.lastElementChild; // Populate subtype/type dropdowns listBulkTransactionType(newRow); listBulkTransactionSubType(newRow); document.querySelectorAll(".transactSubmit").forEach(btn => { btn.classList.remove("d-none"); btn.style.display = "inline-block"; }); document.querySelectorAll(".addlinebulktransaction").forEach(btn => { btn.classList.remove("d-none"); btn.style.display = "inline-block"; }); const typeSelect = newRow.querySelector(".transaction_type"); const subTypeSelect = newRow.querySelector(".transaction_sub_type"); if (typeSelect) { const observer = new MutationObserver(() => { if (typeSelect.options.length > 1) { typeSelect.value = "T_0"; // Dues observer.disconnect(); } }); observer.observe(typeSelect, { childList: true }); } if (subTypeSelect) { const observer2 = new MutationObserver(() => { if (subTypeSelect.options.length > 1) { subTypeSelect.value = "S_7"; // Tenant Rent observer2.disconnect(); } }); observer2.observe(subTypeSelect, { childList: true }); } } } } }; xmlhttp1.send(); } // Called when the "Rent Due" button is clicked.It fetches the list of approved leases from the backend and dynamically populates the transaction form with property, tenant, date, rent amount, etc. function handleRentDue(pageNumber, searchVal) { document.getElementById("rentPaidContainer").innerHTML = ""; const type = "ACTIVE"; var pageSize = $('#pageSize').val(); var xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("BROWSER BROKE"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/listapprovedlease?type=" + type, true); xmlhttp1.setRequestHeader('Content-type', 'application/json;charset=UTF-8'); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200 && this.responseText) { var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { var response = JSON.parse(res.response); console.log(response); let container = document.getElementById("rentDueContainer"); container.innerHTML = ""; // clear old rows for (let i = 0; i < response.length; i++) { let lease = response[i].lease; // Format property address let propertyAddress = ""; if (lease) { propertyAddress = (lease.houseNo ? lease.houseNo + ", " : "") + (lease.streetAddress ? lease.streetAddress + ", " : "") + (lease.city ? lease.city + ", " : "") + (lease.state ? lease.state + " - " : "") + (lease.zip ? lease.zip + ", " : "") + (lease.country ? lease.country : ""); } let rentAmount = lease && lease.rentAmount ? lease.rentAmount : ""; let now = new Date(); let firstDay = new Date(now.getFullYear(), now.getMonth(), 1); let year = firstDay.getFullYear(); let month = String(firstDay.getMonth() + 1).padStart(2, '0'); // month is 0-based let day = String(firstDay.getDate()).padStart(2, '0'); let firstDayStr = `${year}-${month}-${day}`; const monthAbbr = firstDay.toLocaleString('default', { month: 'short' }); let defaultDetails = `${monthAbbr} Rent Due`; let rowHTML = `
`; container.insertAdjacentHTML("beforeend", rowHTML); let newRow = container.lastElementChild; // Populate subtype/type dropdowns listBulkTransactionType(newRow); listBulkTransactionSubType(newRow); document.querySelectorAll(".transactSubmit").forEach(btn => { btn.classList.remove("d-none"); btn.style.display = "inline-block"; }); document.querySelectorAll(".addlinebulktransaction").forEach(btn => { btn.classList.remove("d-none"); btn.style.display = "inline-block"; }); const typeSelect = newRow.querySelector(".transaction_type"); const subTypeSelect = newRow.querySelector(".transaction_sub_type"); if (typeSelect) { const observer = new MutationObserver(() => { if (typeSelect.options.length > 1) { typeSelect.value = "T_3"; // Dues observer.disconnect(); } }); observer.observe(typeSelect, { childList: true }); } if (subTypeSelect) { const observer2 = new MutationObserver(() => { if (subTypeSelect.options.length > 1) { subTypeSelect.value = "S_7"; // Tenant Rent observer2.disconnect(); } }); observer2.observe(subTypeSelect, { childList: true }); } } } } }; xmlhttp1.send(); } // Called when the user clicks the "Submit All Transactions" button If any row is incomplete, submission is stopped and user is alerted. function submitBulkTransactions() { let allTransactions = []; let valid = true; document.querySelectorAll('.transaction-line').forEach(row => { let propertyId = row.querySelector('.propertyIdInput').value.trim(); let leaseId = row.querySelector('.leaseIdInput').value.trim(); let tenantName = row.querySelector('.leaseDropdown').value.trim(); let payDate = row.querySelector('.payment_date').value.trim(); let details = row.querySelector('.trans_details').value.trim(); let transactionType = row.querySelector('.transaction_type').value.trim(); let transactionSubType = row.querySelector('.transaction_sub_type').value.trim(); let amount = row.querySelector('.trans_amount').value.trim(); let propertyAddress = row.querySelector('.propertySearch').value.trim(); if (!propertyId || !leaseId || !payDate || !transactionType || !transactionSubType || !amount) { valid = false; row.classList.add("border", "border-danger"); } else { row.classList.remove("border", "border-danger"); } allTransactions.push({ propertyID: propertyId, leaseID: leaseId, payDate: payDate, details: details, transactionType: transactionType, transactionSubType: transactionSubType, amount: parseFloat(amount), address: propertyAddress, name: tenantName }); }); if (!valid) { alert("Please fill all required fields."); return; } console.log("Sending transactions:", allTransactions); if (!confirm("Are you sure you want to submit all transactions?")) return; let xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } } xmlhttp1.open("POST", baseurl + "/rentaladmin/addbulktransaction", true); xmlhttp1.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xmlhttp1.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("token")); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { const res = JSON.parse(this.responseText); console.log("Response:", res); if (res.rspnsCode === 1000) { alert("All transactions added successfully!"); location.reload(); } else { alert("Failed: " + res.rspnsMsg + "\nNo data was saved."); } } else if (this.status === 401) { $('#employee_modal_message').modal("show"); $("#modal_message_content").html("

You are not authorised for this action.

"); $("#employee_modal_title").html("OOPS!!"); } else { console.error("Error:", this.status, this.responseText); alert("Something went wrong. No data was saved."); } } }; xmlhttp1.send(JSON.stringify(allTransactions)); } function showRefundAmount(leaseID) { let xmlhttp1; try { xmlhttp1 = new XMLHttpRequest(); } catch (e) { try { xmlhttp1 = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Browser not supported!"); return false; } } } xmlhttp1.open("GET", baseurl + "/rentaladmin/getrefundamountnotes?leaseID=" + leaseID, true); xmlhttp1.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xmlhttp1.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("token")); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4) { $("#refundModal").modal("show"); const viewDiv = document.getElementById("refundViewContent"); const container = document.getElementById("refundLinesContainer"); const refundLeaseInput = document.getElementById("refund_lease_id"); refundLeaseInput.value = leaseID; viewDiv.innerHTML = "Loading refund info..."; container.innerHTML = ""; if (this.status === 200 && this.responseText) { try { const res = JSON.parse(this.responseText); console.log("Refund fetch response:", res); let refundData = res.response; if (typeof refundData === "string") { try { refundData = JSON.parse(refundData); } catch (e) { console.warn("Refund response is not JSON:", refundData); refundData = null; } } if (!refundData) refundData = []; if (!Array.isArray(refundData)) refundData = [refundData]; if (refundData.length === 0) { viewDiv.innerHTML = "

No refund history found.

"; addRefundLine(); return; } let viewHTML = ""; refundData.forEach((item, index) => { viewHTML += `
Refund #${index + 1}
Refund Amount:
${item.refundAmount ?? "-"}
Refund Note:
${item.refundNote ?? "-"}
`; }); viewDiv.innerHTML = viewHTML; refundData.forEach(item => { const newLine = document.createElement("div"); newLine.classList.add("refund-line", "mb-3", "border", "rounded", "p-3"); newLine.innerHTML = ` `; container.appendChild(newLine); }); } catch (err) { console.error("Error parsing refund response:", err); viewDiv.innerHTML = "

Error loading refund details.

"; } } else { viewDiv.innerHTML = "

No refund history found.

"; addRefundLine(); } } }; xmlhttp1.send(); } // Saving all refund data in the refund_info column of the lease_details table function saveRefund() { const leaseID = document.getElementById('refund_lease_id').value.trim(); if (!leaseID) { alert("Lease ID missing!"); return; } const refundLines = document.querySelectorAll('.refund-line'); const refundList = []; refundLines.forEach(line => { const amount = line.querySelector('.refundAmount').value.trim(); const note = line.querySelector('.refundNote').value.trim(); if (amount) { refundList.push({ refundAmount: parseFloat(amount), refundNote: note || "" }); } }); if (refundList.length === 0) { alert("Please enter at least one refund amount"); return; } const refundData = { refunds: refundList }; let xmlhttp; try { xmlhttp = new XMLHttpRequest(); } catch (e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Browser not supported!"); return; } } } xmlhttp.open("POST", baseurl + "/rentaladmin/addrefundamountnotes?leaseID=" + leaseID, true); xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200 && this.responseText) { const res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { alert("Refunds saved successfully!"); $('#refundModal').modal('hide'); } else { alert("Failed: " + (res.response || "Unknown error")); } } else { alert("Error saving refund info. Status: " + this.status); } } }; xmlhttp.send(JSON.stringify(refundData)); } function addLandlordinfo() { let firstName = document.getElementById('landlord-first-name').value.trim(); let lastName = document.getElementById('landlord-last-name').value.trim(); let email = document.getElementById('landlord-email').value.trim(); let contactNumber = document.getElementById('landlord-contact-number').value.trim(); let address = document.getElementById('landlord-address').value.trim(); let city = document.getElementById('landlord-city').value.trim(); let state = document.getElementById('landlord-state').value.trim(); let zipcode = document.getElementById('landlord-zipcode').value.trim(); let country = document.getElementById('landlord-country').value.trim(); // ---------------- VALIDATION ---------------- // if (!firstName) { alert("Please enter First Name"); return; } if (!lastName) { alert("Please enter Last Name"); return; } // Email Validation let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!email || !emailPattern.test(email)) { alert("Please enter a valid Email"); return; } // Data Object let landlordData = { firstName: firstName, lastName: lastName, emailId: email, contact: contactNumber, address: address, city: city, state: state, zipCode: zipcode, country: country }; let xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", baseurl + "/rentaladmin/insertlandlordinfo", true); xmlhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { const res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { if (typeof res.response === "string") { if (res.response.startsWith("LANDLORD_EXISTS:")) { let landlordId = res.response.split(":")[1]; alert("Landlord already exists. Redirecting..."); setTimeout(function () { window.location.href = "/admin/landlord-info.html?landlordId=" + landlordId; }, 1000); return; } if (res.response.startsWith("LANDLORD_CREATED:")) { window.location.href = "/admin/landlord-records"; return; } } window.location.href = "/admin/landlord-records.html"; } } else { alert("Error: " + this.status); } } }; xmlhttp.send(JSON.stringify(landlordData)); } function getAllLandlords() { let xmlhttp; try { xmlhttp = new XMLHttpRequest(); } catch (e) { alert("Browser not supported!"); return; } xmlhttp.open("GET", baseurl + "/rentaladmin/getalllandlords", true); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200 && this.responseText) { const res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { let landlords = JSON.parse(res.response); let tbody = document.getElementById("landlordTableBody"); document.getElementById("name").onkeyup = function () { let key = this.value.toLowerCase().trim(); let filtered = landlords.filter(ll => (ll.firstName && ll.firstName.toLowerCase().startsWith(key)) || (ll.lastName && ll.lastName.toLowerCase().startsWith(key)) || (ll.emailId && ll.emailId.toLowerCase().startsWith(key)) ); loadTable(filtered); }; loadTable(landlords); function loadTable(data) { tbody.innerHTML = ""; data.forEach((ll, index) => { let row = ` ${index + 1} ${ll.firstName || "N/A"} ${ll.lastName || "N/A"} ${ll.emailId || "N/A"} ${ll.address || "N/A"} ${ll.contact || "N/A"} `; tbody.innerHTML += row; }); } } else { console.log("Failed: " + (res.response || "Unknown error")); } } else { console.log("Error fetching landlord list. Status: " + this.status); } } }; xmlhttp.send(); } function editLandlordinfo(landlordId) { // Collect Input Values let firstName = document.getElementById('landlord-first-name').value.trim(); let lastName = document.getElementById('landlord-last-name').value.trim(); let email = document.getElementById('landlord-email').value.trim(); let contactNumber = document.getElementById('landlord-contact-number').value.trim(); let address = document.getElementById('landlord-address').value.trim(); let city = document.getElementById('landlord-city').value.trim(); let state = document.getElementById('landlord-state').value.trim(); let zipcode = document.getElementById('landlord-zipcode').value.trim(); let country = document.getElementById('landlord-country').value.trim(); // SAME KEYS AS ADD API (VERY IMPORTANT) let landlordData = { firstName: firstName, lastName: lastName, emailId: email, contact: contactNumber, address: address, city: city, state: state, zipCode: zipcode, country: country }; let xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST", baseurl + "/rentaladmin/editlandlordinfo?landlordId=" + landlordId, true); xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xmlhttp.setRequestHeader("Authorization", "Bearer " + localStorage.getItem("token")); xmlhttp.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { let res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { alert("Landlord info updated successfully!"); // Redirect like add function window.location.href = "/admin/landlord-records.html"; } else { alert("Failed: " + (res.response || "Unknown error")); } } else { alert("Error updating landlord info. Status: " + this.status); } } }; xmlhttp.send(JSON.stringify(landlordData)); } function getLandlordById(landlordId) { let xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", baseurl + "/rentaladmin/getlandlordbyid?landlordId=" + landlordId, true); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200 && this.responseText) { const res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { // Parse the string to object const landlord = JSON.parse(res.response); console.log(landlord); // Fill form fields (match backend field names) document.getElementById('landlord-first-name').value = landlord.firstName || ""; document.getElementById('landlord-last-name').value = landlord.lastName || ""; document.getElementById('landlord-email').value = landlord.emailId || ""; document.getElementById('landlord-contact-number').value = landlord.contact || ""; document.getElementById('landlord-address').value = landlord.address || ""; document.getElementById('landlord-city').value = landlord.city || ""; document.getElementById('landlord-state').value = landlord.state || ""; document.getElementById('landlord-zipcode').value = landlord.zipCode || ""; document.getElementById('landlord-country').value = landlord.country || ""; } else { alert("Failed: " + (res.response || "Unknown error")); } } else { alert("Error fetching landlord info. Status: " + this.status); } } }; xmlhttp.send(); } function getReceivablePayableonPM(email, propertyID) { const xmlhttp = new XMLHttpRequest(); const url = baseurl + "/landlord/getlandlordtransationbyemail" + "?emailID=" + encodeURIComponent(email) + "&propertyID=" + encodeURIComponent(propertyID); xmlhttp.open("GET", url, true); xmlhttp.setRequestHeader( "Authorization", "Bearer " + localStorage.getItem("token") ); xmlhttp.onreadystatechange = function () { if (this.readyState !== 4) return; const container = document.getElementById("landlordTransactionsContainer"); if (this.status !== 200) { console.error("AJAX Error:", this.status); container.innerHTML = "

Failed to load transactions

"; return; } try { const res = JSON.parse(this.responseText); if (res.rspnsCode !== 1000 || !res.response) { container.innerHTML = "

No Transactions Found

"; return; } const transactions = JSON.parse(res.response); console.log("Transactions:", transactions); if (!Array.isArray(transactions) || transactions.length === 0) { container.innerHTML = "

No Transactions Available

"; return; } let tableHtml = `
Transaction History
`; transactions.forEach((txn, index) => { tableHtml += ` `; }); tableHtml += `
S.No Date Reference ID Details Type Sub Type Amount Property
${index + 1} ${txn.payDate ? new Date(txn.payDate).toLocaleDateString() : "-"} ${txn.referenceID || "-"} ${txn.details || "-"} ${txn.transactionType || "-"} ${txn.transactionSubType || "-"} ${txn.amount || "-"} ${(() => { try { const p = typeof txn.property === "string" ? JSON.parse(txn.property) : txn.property; return [ p.number, p.type, p.city, p.zip, p.state, p.country ].filter(Boolean).join(", "); } catch (e) { return "-"; } })() }
`; container.innerHTML = tableHtml; } catch (err) { console.error("JSON Parse Error:", err); container.innerHTML = "

Invalid response format

"; } }; xmlhttp.send(); } function listLandlordTransactionYearOnPM() { var xmlhttp1 = new XMLHttpRequest(); xmlhttp1.open("GET", baseurl + "/rentaladmin/getlandlordtransactionyearforpm", true); xmlhttp1.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp1.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { try { // Parse outer response var res = JSON.parse(this.responseText); if (res.rspnsCode === 1000) { // Parse inner JSON string var years = JSON.parse(res.response); // console.log("Transaction Years:", years); var dropdown = document.getElementById("yearFilter"); // Clear existing options dropdown.innerHTML = ''; // Add year options years.forEach(function (year) { var option = document.createElement("option"); option.value = year; option.textContent = year; dropdown.appendChild(option); }); } else { console.error("API Error: " + res.rspnsMsg); } } catch (err) { console.error("JSON Parsing Error:", err); } } else { console.error("AJAX request failed, Status:", this.status); } } }; xmlhttp1.send(); } function listLandlordTransactioneEmailOnPM(keyword) { const suggestionBox = document.getElementById("emailSuggestions"); const emailInput = document.getElementById("landlord_email"); if (!keyword || keyword.length < 4) { suggestionBox.classList.add("d-none"); suggestionBox.innerHTML = ""; return; } const xhr = new XMLHttpRequest(); let url = baseurl + "/rentaladmin/getlandlordtransactionemailforpm?keyword=" + encodeURIComponent(keyword); xhr.open("GET", url, true); xhr.setRequestHeader( "Authorization", "Bearer " + localStorage.getItem("token") ); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { try { const res = JSON.parse(xhr.responseText); if (res.rspnsCode !== 1000) { suggestionBox.classList.add("d-none"); return; } const landlordList = JSON.parse(res.response); suggestionBox.innerHTML = ""; if (!landlordList || landlordList.length === 0) { suggestionBox.classList.add("d-none"); return; } // SHOW suggestion box suggestionBox.classList.remove("d-none"); landlordList.forEach(item => { const div = document.createElement("div"); div.className = "list-group-item list-group-item-action"; div.style.cursor = "pointer"; div.innerHTML = ` ${item.firstName} ${item.lastName}
${item.emailId} `; div.onclick = function () { emailInput.value = item.emailId; suggestionBox.classList.add("d-none"); suggestionBox.innerHTML = ""; }; suggestionBox.appendChild(div); }); } catch (e) { console.error("Error parsing response", e); suggestionBox.classList.add("d-none"); } } }; xhr.send(); } // post ajax for adding landlord service ... function addlandlordService() { let landlordName = $("#landlord_name").val().trim(); let serviceName = $("#service_name").val().trim(); if (!landlordName) { alert("Landlord Name is required"); $("#landlord_name").focus(); return; } if (!serviceName) { alert("Service Name is required"); $("#service_name").focus(); return; } let paymentType = $("#payment_type").val(); if (!paymentType) { paymentType = "FREE"; } let amountVal = $("#amount").val(); if (paymentType === "PAID" && (!amountVal || isNaN(amountVal))) { alert("Please enter amount for Paid service"); $("#amount").focus(); return; } let serviceData = { email: $("#landlord_email").val(), landlordName: landlordName, serviceName: serviceName, property: $("#property option:selected").text(), serviceProvider: $("#service_provider").val()?.trim() || null, serviceProviderDetails: $("#service_provider_details").val()?.trim() || null, startedOnDate: $("#started_on_date").val() || null, endByDate: $("#end_by_date").val() || null, paymentScheduleType: paymentType, amount: paymentType === "PAID" ? parseFloat(amountVal) : null }; $.ajax({ url: baseurl + "/landlord/addlandlordservice", type: "POST", contentType: "application/json", headers: { Authorization: "Bearer " + localStorage.getItem("token") }, data: JSON.stringify(serviceData), success: function () { console.log("✅ Insert success"); window.location.href = "/admin/services-landlord.html"; }, error: function (xhr) { console.error("❌ Insert failed:", xhr.responseText); alert("Insert failed"); } }); } function loadLandlordServices(pageNo = 1) { currentPage = pageNo; pageSize = parseInt($("#pageSize").val(), 10); $.ajax({ url: baseurl + "/landlord/landlordservice", type: "GET", headers: { Authorization: "Bearer " + localStorage.getItem("token") }, success: function (res) { console.log(res); allLandlordServices = Array.isArray(res) ? res : res.response; // store for edit page usage localStorage.setItem( "landlordServices", JSON.stringify(allLandlordServices) ); let totalRecords = allLandlordServices.length; let totalPages = Math.ceil(totalRecords / pageSize); if (!paginationInitialized) { addPagination(loadLandlordServices, "service_landlord", totalPages); paginationInitialized = true; } let start = (currentPage - 1) * pageSize; let end = start + pageSize; let pageData = allLandlordServices.slice(start, end); renderLandlordTable(pageData, start); } }); } function renderLandlordTable(data, offset = 0) { let tbody = $("#service_landlord"); tbody.empty(); if (!data || data.length === 0) { tbody.html(` No Data Found `); return; } $.each(data, function (index, service) { let paymentType = (service.paymentScheduleType || "").toUpperCase(); let amountDisplay = paymentType === "PAID" ? (service.amount ?? "-") : "Free"; let row = ` ${offset + index + 1} ${service.email ?? "-"} ${service.landlordName ?? "-"} ${service.serviceName ?? "-"} ${service.property ?? "-"} ${service.serviceProvider ?? "-"} ${service.startedOnDate ?? "-"} ${service.endByDate ?? "-"} ${paymentType} ${amountDisplay} `; tbody.append(row); }); } function loadServiceById(serviceId) { const services = JSON.parse(localStorage.getItem("landlordServices")) || []; const service = services.find( s => String(s.serviceId) === String(serviceId) ); if (!service) { alert("Service not found"); return; } $("#service_id").val(service.serviceId); $("#landlord_email").val(service.email); $("#landlord_email").prop("disabled", true); $("#landlord_name").val(service.landlordName); $("#service_name").val(service.serviceName); selectedProperty = service.property; selectedProperty = service.property; getLandlordProperty(service.email); $("#service_provider").val(service.serviceProvider); $("#service_provider_details").val(service.serviceProviderDetails); $("#started_on_date").val(service.startedOnDate); $("#end_by_date").val(service.endByDate); $("#payment_type") .val((service.paymentScheduleType || "").toUpperCase()); toggleAmount(); if ((service.paymentScheduleType || "").toUpperCase() === "PAID") { $("#amount").val(service.amount); } } function updatelandlordService() { let paymentType = $("#payment_type").val() || "FREE"; let amountVal = $("#amount").val(); if (paymentType === "PAID" && (!amountVal || isNaN(amountVal))) { alert("Please enter valid amount"); return; } let serviceData = { serviceId: $("#service_id").val(), email: $("#landlord_email").val(), landlordName: $("#landlord_name").val(), serviceName: $("#service_name").val(), property: $("#property option:selected").text(), serviceProvider: $("#service_provider").val(), serviceProviderDetails: $("#service_provider_details").val(), startedOnDate: $("#started_on_date").val(), endByDate: $("#end_by_date").val(), paymentScheduleType: paymentType, amount: paymentType === "PAID" ? parseFloat(amountVal) : null }; console.log("UPDATE PAYLOAD =>", serviceData); $.ajax({ url: baseurl + "/landlord/editlandlordservice", type: "POST", contentType: "application/json", headers: { Authorization: "Bearer " + localStorage.getItem("token") }, data: JSON.stringify(serviceData), success: function () { alert("Service updated successfully"); window.location.href = "/admin/services-landlord.html"; }, error: function (xhr) { console.error(xhr.responseText); alert("Update failed"); } }); } // this is ajax for add landlord transaction (submit button) function addLandlordTransaction() { var payload = { transactionId: $('#transaction_reference_id').val().trim(), payDate: $('#payment_date').val(), property: $('#property').val(), emailId: $('#landlord_email').val().trim(), transactionType: $('#transaction_type').val(), transactionSubType: $('#transaction_sub_type').val(), referenceID: $('#transaction_reference_id').val().trim(), details: $('#details').val().trim(), amount: $('#amount').val().trim(), account: $('#account').val().trim() }; // Clear previous errors $(".add_transactions strong").html(""); if (!payload.payDate) { $('#date_error').html("Date is mandatory"); $('#payment_date').focus(); return; } if (!payload.emailId) { $('#email_error').html("Email is mandatory"); $('#landlord_email').focus(); return; } if (!payload.property) { $('#property_error').html("Property is mandatory"); $('#property').focus(); return; } if (!payload.transactionType || payload.transactionType === "" || payload.transactionType === "-1") { $('#type_error').html("Transaction type is mandatory"); $('#transaction_type').focus(); return; } if (!payload.transactionSubType || payload.transactionSubType === "" || payload.transactionSubType === "-1") { $('#sub_type_error').html("Transaction sub-type is mandatory"); $('#transaction_sub_type').focus(); return; } if (!payload.details) { $('#details_error').html("Details are mandatory"); $('#details').focus(); return; } if (!payload.amount || isNaN(payload.amount) || Number(payload.amount) <= 0) { $('#amount_error').html("Valid amount is mandatory"); $('#amount').focus(); return; } $(".transactSubmit") .prop("disabled", true) .text("Submitting..."); console.log("Add Landlord Transaction Payload:", payload); $.ajax({ url: baseurl + "/landlord/addlandlordtransaction", type: "POST", contentType: "application/json", data: JSON.stringify(payload), headers: { Authorization: "Bearer " + localStorage.getItem("token") }, success: function () { alert("Transaction added successfully"); $(".transactSubmit") .prop("disabled", false) .text("Submit"); }, error: function (xhr) { console.error("Insert failed:", xhr.responseText); $(".transactSubmit") .prop("disabled", false) .text("Submit"); } }); } let selectedProperty = null; function getLandlordProperty(email) { if (!email) { alert("Email is empty, cannot load properties"); return; } let xmlhttp = new XMLHttpRequest(); const url = baseurl + "/landlord/getlandlordpropertybyemail" + "?emailID=" + encodeURIComponent(email); xmlhttp.open("GET", url, true); xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token')); xmlhttp.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { try { const res = JSON.parse(this.responseText); if (res.rspnsCode === 1000 && res.response) { const propertyList = JSON.parse(res.response); const propertySelect = document.getElementById("property"); propertySelect.innerHTML = ''; propertyList.forEach(p => { let dataObj = {}; try { dataObj = JSON.parse(p.data); } catch (e) { console.warn("Invalid JSON for property", p.property_id); } const parts = [ dataObj.number, dataObj.type, dataObj.city, dataObj.zip, dataObj.state, dataObj.country ].filter(Boolean); const option = document.createElement("option"); option.value = p.property_id; option.text = parts.join(", "); propertySelect.appendChild(option); }); if (selectedProperty) { Array.from(propertySelect.options).forEach(opt => { if (opt.text.trim() === selectedProperty.trim()) { opt.selected = true; } }); } } else { console.error("Invalid response structure", res); } } catch (err) { console.error("JSON Parse Error:", err); } } else { console.error("AJAX Error:", this.status, this.responseText); } } }; xmlhttp.send(); } function getLandlordTransactiononPM(email, year) { let xmlhttp = new XMLHttpRequest(); const url = baseurl + "/rentaladmin/getlandlordtransactiononforpm" + "?emailID=" + encodeURIComponent(email) + "&year=" + encodeURIComponent(year); xmlhttp.open("GET", url, true); xmlhttp.setRequestHeader( "Authorization", "Bearer " + localStorage.getItem("token") ); xmlhttp.onreadystatechange = function () { if (this.readyState !== 4) return; if (this.status === 200) { try { const res = JSON.parse(this.responseText); if (res.rspnsCode === 1000 && res.response) { const parsedResponse = JSON.parse(res.response); console.log(parsedResponse); let allTablesHtml = ""; for (const bucketId in parsedResponse) { const transactions = parsedResponse[bucketId]; if (!transactions || !transactions.length) continue; let tableHtml = `
${transactions[0].bucket_name.replace(/^.* - /, '')}
`; transactions.forEach((txn, index) => { tableHtml += ` `; }); tableHtml += `
S.No Date Description Debit Credit Running Balance
${index + 1} ${new Date(txn.date).toLocaleDateString()} ${txn.description || ''} ${txn.debit || ''} ${txn.credit || ''} ${txn.running_balance || ''}
`; allTablesHtml += tableHtml; } document.getElementById("landlordTransactionsContainer").innerHTML = allTablesHtml || "

No Transactions Available

"; document.getElementById("downloadCSVBtn").style.display = "inline-block"; } else { console.error("Invalid response structure", res); } } catch (err) { console.error("JSON Parse Error:", err); } } else { console.error("AJAX Error:", this.status, this.responseText); } }; xmlhttp.send(); } function getPaymentOverDues0to10() { let xmlhttp = new XMLHttpRequest(); const url = baseurl + "/rentaladmin/listofpaymentoverdues0to10"; xmlhttp.open("GET", url, true); xmlhttp.setRequestHeader( "Authorization", "Bearer " + localStorage.getItem("token") ); xmlhttp.onreadystatechange = function () { if (this.readyState !== 4) return; if (this.status === 200) { try { const res = JSON.parse(this.responseText); // console.log("Raw response:", res); let count = 0; let list = []; if (res.response) { list = JSON.parse(res.response); if (Array.isArray(list)) { count = list.length; } } const overdueEl = document.getElementById("overdue_0_10"); if (overdueEl) { console.log("1"); overdueEl.innerText = count; } const tableBody = document.getElementById("fine_table"); if (!tableBody || !Array.isArray(list)) { return; } tableBody.innerHTML = ""; list.forEach((item, index) => { let addressText = "-"; if (item.address) { try { const addr = JSON.parse(item.address); addressText = `${addr.houseNo || ""}, ${addr.streetAddress || ""}, ${addr.city || ""}, ${addr.zip || ""}, ${addr.state || ""}`; } catch (e) {} } const amount = (item.accountBalance ?? 0).toFixed(2); let row = ` ${index + 1} ${addressText} ${item.name || "-"} $ ${amount} `; tableBody.insertAdjacentHTML("beforeend", row); }); } catch (err) { console.error("JSON Parse Error:", err); const overdueEl = document.getElementById("overdue_0_10"); if (overdueEl) overdueEl.innerText = 0; } } else { console.error("AJAX Error:", this.status); const overdueEl = document.getElementById("overdue_0_10"); if (overdueEl) overdueEl.innerText = 0; } }; xmlhttp.send(); } function getPaymentOverDues10to100() { let xmlhttp = new XMLHttpRequest(); const url = baseurl + "/rentaladmin/listofpaymentoverdues10to100"; xmlhttp.open("GET", url, true); xmlhttp.setRequestHeader( "Authorization", "Bearer " + localStorage.getItem("token") ); xmlhttp.onreadystatechange = function () { if (this.readyState !== 4) return; if (this.status === 200) { try { const res = JSON.parse(this.responseText); // console.log("Raw response:", res); let count = 0; let list = []; if (res.response) { list = JSON.parse(res.response); if (Array.isArray(list)) { count = list.length; } } const overdueEl = document.getElementById("overdue_10_100"); if (overdueEl) { overdueEl.innerText = count; } const tableBody = document.getElementById("fine_table"); if (!tableBody || !Array.isArray(list)) { return; } tableBody.innerHTML = ""; list.forEach((item, index) => { let addressText = "-"; if (item.address) { try { const addr = JSON.parse(item.address); addressText = `${addr.houseNo || ""}, ${addr.streetAddress || ""}, ${addr.city || ""}, ${addr.zip || ""}, ${addr.state || ""}`; } catch (e) {} } const amount = (item.accountBalance ?? 0).toFixed(2); let row = ` ${index + 1} ${addressText} ${item.name || "-"} $ ${amount} `; tableBody.insertAdjacentHTML("beforeend", row); }); } catch (err) { console.error("JSON Parse Error:", err); const overdueEl = document.getElementById("overdue_10_100"); if (overdueEl) overdueEl.innerText = 0; } } else { console.error("AJAX Error:", this.status); const overdueEl = document.getElementById("overdue_10_100"); if (overdueEl) overdueEl.innerText = 0; } }; xmlhttp.send(); } function getPaymentOverDues100to1000() { let xmlhttp = new XMLHttpRequest(); const url = baseurl + "/rentaladmin/listofpaymentoverdues100to1000"; xmlhttp.open("GET", url, true); xmlhttp.setRequestHeader( "Authorization", "Bearer " + localStorage.getItem("token") ); xmlhttp.onreadystatechange = function () { if (this.readyState !== 4) return; if (this.status === 200) { try { const res = JSON.parse(this.responseText); // console.log("Raw response:", res); let count = 0; let list = []; if (res.response) { list = JSON.parse(res.response); if (Array.isArray(list)) { count = list.length; } } const overdueEl = document.getElementById("overdue_100_1000"); if (overdueEl) { overdueEl.innerText = count; } const tableBody = document.getElementById("fine_table"); if (!tableBody || !Array.isArray(list)) { return; } tableBody.innerHTML = ""; list.forEach((item, index) => { let addressText = "-"; if (item.address) { try { const addr = JSON.parse(item.address); addressText = `${addr.houseNo || ""}, ${addr.streetAddress || ""}, ${addr.city || ""}, ${addr.zip || ""}, ${addr.state || ""}`; } catch (e) {} } const amount = (item.accountBalance ?? 0).toFixed(2); let row = ` ${index + 1} ${addressText} ${item.name || "-"} $ ${amount} `; tableBody.insertAdjacentHTML("beforeend", row); }); } catch (err) { console.error("JSON Parse Error:", err); const overdueEl = document.getElementById("overdue_100_1000"); if (overdueEl) overdueEl.innerText = 0; } } else { console.error("AJAX Error:", this.status); const overdueEl = document.getElementById("overdue_100_1000"); if (overdueEl) overdueEl.innerText = 0; } }; xmlhttp.send(); } function getPaymentOverDues1000toMore() { let xmlhttp = new XMLHttpRequest(); const url = baseurl + "/rentaladmin/listofpaymentoverdues1000tomore"; xmlhttp.open("GET", url, true); xmlhttp.setRequestHeader( "Authorization", "Bearer " + localStorage.getItem("token") ); xmlhttp.onreadystatechange = function () { if (this.readyState !== 4) return; if (this.status === 200) { try { const res = JSON.parse(this.responseText); // console.log("Raw response:", res); let count = 0; let list = []; if (res.response) { list = JSON.parse(res.response); if (Array.isArray(list)) { count = list.length; } } const overdueEl = document.getElementById("overdue_1000_plus"); if (overdueEl) { overdueEl.innerText = count; } const tableBody = document.getElementById("fine_table"); if (!tableBody || !Array.isArray(list)) { return; } tableBody.innerHTML = ""; list.forEach((item, index) => { let addressText = "-"; if (item.address) { try { const addr = JSON.parse(item.address); addressText = `${addr.houseNo || ""}, ${addr.streetAddress || ""}, ${addr.city || ""}, ${addr.zip || ""}, ${addr.state || ""}`; } catch (e) {} } const amount = (item.accountBalance ?? 0).toFixed(2); let row = ` ${index + 1} ${addressText} ${item.name || "-"} $ ${amount} `; tableBody.insertAdjacentHTML("beforeend", row); }); } catch (err) { console.error("JSON Parse Error:", err); const overdueEl = document.getElementById("overdue_1000_plus"); if (overdueEl) overdueEl.innerText = 0; } } else { console.error("AJAX Error:", this.status); const overdueEl = document.getElementById("overdue_1000_plus"); if (overdueEl) overdueEl.innerText = 0; } }; xmlhttp.send(); } function loadRefundCount() { const type = "EXPIRED"; var sixMonthsAgo = new Date(); sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6); var xhr = new XMLHttpRequest(); xhr.open( "GET", `${baseurl}/rentaladmin/listapprovedlease?pageNumber=1&pageSize=10000&type=${type}`, true ); xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xhr.setRequestHeader("Authorization", `Bearer ${localStorage.getItem("token")}`); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var res = JSON.parse(xhr.responseText); if (res.rspnsCode !== 1000) return; var response = JSON.parse(res.response); var count = 0; for (var i = 0; i < response.length; i++) { let hasRefund = response[i].tenantRefund && response[i].tenantRefund.refunds && response[i].tenantRefund.refunds.length > 0; let leaseEndRaw = response[i].lease.leaseEndDate; let leaseEndObj = leaseEndRaw ? new Date(leaseEndRaw) : null; if (hasRefund) continue; if (!leaseEndObj) continue; if (leaseEndObj < sixMonthsAgo) continue; count++; } document.getElementById("refund_card_dashboard").innerText = count; } }; xhr.send(); } function listRefundLeases(pageNumber) { var pageSize = $('#pageSize').val(); const type = "EXPIRED"; // last 6 months date var sixMonthsAgo = new Date(); sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6); var xmlhttp = new XMLHttpRequest(); // 🔥 IMPORTANT: // Refund page ke liye hum ek baar me saara data la rahe hain xmlhttp.open( "GET", `${baseurl}/rentaladmin/listapprovedlease?pageNumber=1&pageSize=10000&type=${type}`, true ); xmlhttp.setRequestHeader("Content-type", "application/json;charset=UTF-8"); xmlhttp.setRequestHeader("Authorization", `Bearer ${localStorage.getItem("token")}`); xmlhttp.onreadystatechange = function () { if (this.readyState === 4 && this.status === 200) { var res = JSON.parse(this.responseText); if (res.rspnsCode !== 1000) return; var response = JSON.parse(res.response); // ===== STEP 1: FILTER ONLY PENDING + LAST 6 MONTHS ===== var filtered = []; for (var i = 0; i < response.length; i++) { let hasRefund = response[i].tenantRefund && response[i].tenantRefund.refunds && response[i].tenantRefund.refunds.length > 0; let leaseEndRaw = response[i].lease.leaseEndDate; let leaseEndObj = leaseEndRaw ? new Date(leaseEndRaw) : null; if (hasRefund) continue; if (!leaseEndObj) continue; if (leaseEndObj < sixMonthsAgo) continue; filtered.push(response[i]); } // ===== STEP 2: FRONTEND PAGINATION ===== var start = (pageNumber - 1) * pageSize; var end = start + pageSize; var pageData = filtered.slice(start, end); var tableData = ""; if (pageData.length > 0) { for (var j = 0; j < pageData.length; j++) { let row = pageData[j]; let leaseStartDate = formatDateOnly(row.lease.leaseStartDate); let leaseEndDate = formatDateOnly(row.lease.leaseEndDate); let propertyAddress = `${row.lease.houseNo}, ${row.lease.streetAddress}, ${row.lease.city}, ${row.lease.zip}, ${row.lease.state}`; tableData += ""; tableData += `${start + j + 1}`; tableData += `${row.name}`; tableData += `${propertyAddress}`; tableData += ` `; tableData += `${leaseStartDate}`; tableData += `${leaseEndDate}`; tableData += `${row.lease.leaseTermType}`; tableData += ` `; tableData += ""; } } else { tableData = `No Pending Refunds`; } document.getElementById("approvedLease").innerHTML = tableData; var totalPages = Math.ceil(filtered.length / pageSize); addPagination(listRefundLeases, "approvedLease", totalPages); } }; xmlhttp.send(); }