Untitled

 avatar
unknown
plain_text
a year ago
14 kB
6
Indexable
    <script defer>
        let CreditCalc = function ($) {
           'use strict';


           const numberWithCommas = (x) => {
              return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
           }

           let year_rate = parseFloat("{{ year_rate}}".replace(',', '.')).toFixed(1)
           let tax_per_month = parseFloat("{{ tax_per_month}}".replace(',', '.')).toFixed(1);
           let onetimeTax = parseFloat("{{ onetime_tax}}".replace(',', '.')).toFixed(1);
           let today = new Date();
           let firstPaymentDate;
           let formattedDate;


           let calc = function (productId, year_rate, tax_per_month, onetimeTax) {  
            let summFormat, comission;
            let kk = 0;
            let newSum = 0;
            let sumMou = 0;
            let cresitSummFormat = 0;
            let persent = 0;
            let today = new Date();
            let firstPaymentDate = new Date(today.getTime() + (14 * 24 * 60 * 60 * 1000)); // Adding 14 days
            let formattedDate = new Intl.DateTimeFormat('en-GB', {
                day: '2-digit',
                month: '2-digit',
                year: 'numeric'
            }).format(firstPaymentDate);
            formattedDate = formattedDate.replace(/\//g, '.');
            productId = Number(productId);
            if (productId == 10) { 
              console.log(year_rate, tax_per_month, onetimeTax);
              kk = 0;
              newSum = 0;
              sumMou = 0;
              cresitSummFormat = 0;
              persent = 0;
              firstPaymentDate = new Date(today.getTime() + (14 * 24 * 60 * 60 * 1000)); // Adding 14 days
              let summFormat = $('#summ').val(); 
              let summ = Number.parseInt(
                  summFormat.replace(/\s/g, '')
              );
              let term = parseFloat($('#term').val()) / 2;
              comission = onetimeTax / 100;
              let stawkaYear = year_rate / 100;
              let stawkaMou = (stawkaYear.toFixed(3) / 12) + (tax_per_month / 100);
              let znam = stawkaMou * ((stawkaMou) ** term);
              let chisl = ((stawkaMou) ** term);
              kk = znam / chisl;
              newSum = summ + summ * (onetimeTax / 100);
              sumMou =  ((newSum * kk) + (newSum / term));
              sumMou = sumMou / 2;
              cresitSummFormat = numberWithCommas(sumMou.toFixed(2));
              persent = tax_per_month / 30;
             } else if ([20, 19, 18, 17, 15, 14, 13, 11, 9, 8, 6].includes(productId)) {
                console.log(year_rate, tax_per_month, onetimeTax);
                let summ = Number.parseInt($('#summ').val().replace(/\s/g, ''));
                let term = parseFloat($('#term').val());
                let onetimeComission = (summ * onetimeTax) / 100;
                let totalLoan = summ + onetimeComission;
                let monthlyRate = (year_rate / 100) / 12;
                let pvif = Math.pow(1 + monthlyRate, term);
                let monthlyPayment = (monthlyRate * totalLoan * pvif) / (pvif - 1);
                firstPaymentDate = new Date(today.getTime() + (30 * 24 * 60 * 60 * 1000)); // Adding 30 days
                cresitSummFormat = numberWithCommas(monthlyPayment.toFixed(2));
                persent = year_rate / 360;
            }
              formattedDate = new Intl.DateTimeFormat('en-GB', {
              day: '2-digit',
              month: '2-digit',
              year: 'numeric'
              }).format(firstPaymentDate);
              formattedDate = formattedDate.replace(/\//g, '.');

              $('.get__sum').text(summFormat);
              $('.comission__sum').text(comission);
              $('.return__sum').text(cresitSummFormat);
              $('.rate__sum').text(persent.toFixed(2) + '%');
              $('.first-payment-date__value').text(formattedDate);
              let left__pos = term * 0.7 + '%';
              let persent__block = $('.info__percent');
              let day__block = $('.quantity__center');
              let day__inp = term * 0.3;
              let day__inner = (Math.round(day__inp));
                let termo = Number($('#term').val().replace(',', ''));
                let currentDate = new Date();
                let termoMonths;
                let returnSum = Number($('.return__sum').text().replace(',', '').replace(/\s/g, ''));
                let summ = Number($('#summ').val().replace(/,/g, '').replace(/\s/g, ''));

                if (productId == '10') {
                    termoMonths = termo / 2;  // Convert twice-monthly payments to months
                } else {
                    termoMonths = termo;
                }
                currentDate.setMonth(currentDate.getMonth() + termoMonths);
                let data_povernennya = currentDate;
                let zagalna_vartist = returnSum * termo;
                let zagalni_vitrati = zagalna_vartist - summ;
                let richna_stavka = (zagalni_vitrati / summ / termo) * 365;
                console.log('termo:', termo);  // Add this line
                console.log('returnSum:', returnSum);  // Add this line
                console.log('summ:', summ);  // Add this line
              persent__block.css({
                 left: left__pos,
              })
              day__block.css({
                 left: left__pos,
              })
              if (day__inner == 3 || day__inner == 4) {
                 day__block.html(day__inner + ' {% trans "дня" %}');
              } else {
                 day__block.html(day__inner + ' {% trans "дней" %}');
              }
            return {
                suma_kredity: summ,
                issue_date: new Date().toLocaleDateString(),
                periodichnist: (productId == '10') ? '14 днів' : 'щомісяця',
                suma_plateju: returnSum,
                strok_kredity: termo,
                data_povernennya: data_povernennya,
                zagalna_vartist: zagalna_vartist,
                zagalni_vitrati: zagalni_vitrati,
                richna_stavka: richna_stavka
            };
            };
            
            function updateValues(values) {
                // Use the values from the calc function
                $('.suma_kredity').text(values.suma_kredity);
                $('.issue_date').text(values.issue_date);
                $('.periodichnist').text(values.periodichnist);
                $('.suma_plateju').text(values.suma_plateju);
                $('.strok_kredity').text(values.strok_kredity);
                $('.data_povernennya').text(new Date(values.data_povernennya).toLocaleDateString());
                $('.zagalna_vartist').text(values.zagalna_vartist.toFixed(2));
                $('.zagalni_vitrati').text(values.zagalni_vitrati.toFixed(2));
                $('.richna_stavka').text(values.richna_stavka.toFixed(2) + '%');
            }

           let slide = function (obj) {
              let input = obj.find('input'),
                 k = parseInt(input.attr('data-k')),
                 min = parseFloat(input.attr('data-min')) * k,
                 max = parseFloat(input.attr('data-max')) * k,
                 step = parseFloat(input.attr('data-step')) * k,
                 val = parseFloat(input.val()) * k,
                 minEvemt = input.attr('data-min-event');

              input.val(numberWithCommas(input.val()));
              input.keyup(function () {
                 var val = $(this).val();
                 val = val.replace(/\s+/g, "");
                 val = val.replace(/,/g, ".");

                 $(this).val(numberWithCommas(val));
                 if (val == '')
                    val = 0;
                 else
                    val = parseFloat(val) * k;

                 $(this).closest('.range').find('.slider').slider({ value: val });
              });
              obj.find(".slider").slider({
                 min: min,
                 max: max,
                 step: step,
                 range: "min",
                 value: val,
                 slide: function (event, ui) {
                    var k = parseInt(input.attr('data-k'));
                    var val = parseFloat(ui.value) / k;
                    if (minEvemt && ui.value < minEvemt)
                       return false;
                    if (val)
                       input.val(numberWithCommas(val));
                       if (input.attr('id') === 'summ') {  // Check if the 'summ' slider is being moved
                            $('.get__sum').text(numberWithCommas(val) + ' грн');  // Update the sum display
                       }
                 },
                 change: function (event, ui) {
                    let productId = $('#product').val();
                    let values = calc(productId, year_rate, tax_per_month, onetimeTax);
                    updateValues(values);
                    var k = parseInt(input.attr('data-k'));
                    var val = parseFloat(ui.value) / k;
                    if (input.attr('id') === 'summ') {  // Check if the 'summ' slider is being moved
                        $('.get__sum').text(numberWithCommas(val) + ' грн');  // Update the sum display
                    }
                 }
              });
           }

    let initialisation = function () {
        $('.range').each(function (obj, i) {
            slide($(this));
        });
        $('.range').on('input', function() {
            // Update the value of suma_kredity
            var suma_kredity = parseFloat($('#summ').val().replace(/,/g, '').replace(/\s/g, ''));
            $('.suma_kredity').text(suma_kredity);

            // Get the current product ID
            let productId = $('#product').val();

            // Call the calc function to update the values
                let values = calc(productId, year_rate, tax_per_month, onetimeTax);
                updateValues(values);
        });
        // Handle product selection change
        $('#product').change(function() {
            let productId = $(this).val();

            // Make an AJAX request to the server to get the product data
            $.get('/product_data/' + productId + '/', function(data) {
                console.log(data);
                // Update the calculator variables with the data returned from the server
                year_rate = parseFloat(data.year_rate)
                tax_per_month = parseFloat(data.tax_per_month)
                onetimeTax = parseFloat(data.onetime_tax)
                console.log('robert', year_rate, tax_per_month, onetimeTax);
                
                // Modify term values for productId == 10
                if (productId == '10') {
                    data.term_min_value *= 2;
                    data.term_max_value *= 2;
                }

                // Update the data-min and data-max attributes
                $('#summ').attr('data-min', data.summ_min_value);
                $('#summ').attr('data-max', data.summ_max_value);
                $('#term').attr('data-min', data.term_min_value);
                $('#term').attr('data-max', data.term_max_value);
                $('.quantity__left').html(data.term_min_value + ' <span>платежу</span>');
                $('.quantity__right').html(data.term_max_value + ' <span>платежів</span>');
                $('.sum_left').html(data.summ_min_value + ' <span>грн</span>');
                $('.sum_right').html(data.summ_max_value + ' <span>грн</span>');
                if (productId == '10') {
                    $('.periodicity__value').text('14 днів');
                } else {
                    $('.periodicity__value').text('щомісяця');
                }
                

                // Update the slider
                slide($('#summ').closest('.range'));
                slide($('#term').closest('.range'));
                // Show the modal when the details button is clicked
                $('#details-button').on('click', function() {
                    $('#calcDetailsModalLongTerm, #modal-background').css('display', 'block');
                    $('body').css('overflow', 'hidden');
                });

                // Close the modal when the close button is clicked
                $('.close').on('click', function() {
                    $('#calcDetailsModalLongTerm, #modal-background').css('display', 'none');
                    $('body').css('overflow', 'auto');
                });

                // Close the modal when the user clicks outside of it
                $(window).on('click', function(event) {
                    if ($(event.target).is('#calcDetailsModalLongTerm')) {
                        $('#calcDetailsModalLongTerm, #modal-background').css('display', 'none');
                        $('body').css('overflow', 'auto');
                    }
                });
                // Recalculate the values
                let values = calc(productId, year_rate, tax_per_month, onetimeTax);
                updateValues(values);
            });
        });

        $('#product').trigger('change');
    };

    return {
        init: function () {
            initialisation();
        },
    }
}(jQuery);

jQuery(document).ready(function ($) {
    CreditCalc.init();
});
Editor is loading...
Leave a Comment