HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/buyercall_new/buyercall/buyercall/assets/scripts/forms_backend_edit.js
var utils = require('../components/utils');
var moment = require('moment');
var App = require('./app');

const CONDITION_DATA = `//${appConfig.server_url}/forms`;

var forms_backend_edit = {

    error: false,

    conditionalNotification: false,

    currentCondition: {},

    currentForm: 0,

    okSubjectLine: '',

    okEmailRecipients: '',

    okAdfEmailRecipients: '',

    nokSubjectLine: '',

    nokEmailRecipients: '',

    nokAdfEmailRecipients: '',

    tableApi: null,

    criteriaTable: [],

    formFields: [],

    init: function() {
        var loThat = this;
        var pageURL = $(location).attr("href");

        loThat.criteriaTable = [];

        if ($('#standard_notification_type').attr('checked')) {
            $('.standard-form-notification').show();
            $('.conditional-form-notification').hide();
            loThat.conditionalNotification = false;
        } else {
            $('.standard-form-notification').hide();
            $('.conditional-form-notification').show();
            loThat.conditionalNotification = true;
        }

        loThat.currentForm = $('.current_form').attr('id');
        loThat.loadConditionalData();
        loThat.setEvents();
        loThat.setDataTable();

        if (pageURL.indexOf("?tab=logs") >= 0) {
            //$('#form-properties-li').removeClass('active');
            $('.form-properties-link').trigger( "click" );
            $('.form-logs-link').trigger( "click" );
        }
    },

	loadStyles: function() {
		$('#logs-datatable_length label, #logs-datatable_filter label').addClass("form-group");
	},

	loadConditionalData: function() {
	    var loThat = this;

        $.ajax({
           url: `${CONDITION_DATA}` + '\\' + loThat.currentForm + '\\notification_criteria',
           type: 'GET',
           dataType: 'json',
           success: function(response) {
                const loConditions = response.conditions;

                if (loConditions.criteria) {
                    loThat.criteriaTable = loConditions.criteria;
                }

                if (loConditions.okSubjectLine != '') {
                    $("#txtThenEmailSubject").val(loConditions.okSubjectLine);
                    $("#txtThenEmailSubject").closest('.label-floating').removeClass('is-empty');
                } else {
                    $("#txtThenEmailSubject").val('Lead Notification');
                    $("#txtThenEmailSubject").closest('.label-floating').removeClass('is-empty');
                }

                if (loConditions.okEmailRecipients != '') {
                    $("#txtThenEmailRecipients").val(loConditions.okEmailRecipients);
                    $("#txtThenEmailRecipients").closest('.label-floating').removeClass('is-empty');
                }

                if (loConditions.okAdfEmailRecipients != '') {
                    $("#txtThenADFRecipients").val(loConditions.okAdfEmailRecipients);
                    $("#txtThenADFRecipients").closest('.label-floating').removeClass('is-empty');
                }

                if (loConditions.nokSubjectLine != '') {
                    $("#txtElseEmailSubject").val(loConditions.nokSubjectLine);
                    $("#txtElseEmailSubject").closest('.label-floating').removeClass('is-empty');
                } else {
                    $("#txtElseEmailSubject").val('Lead Notification');
                    $("#txtElseEmailSubject").closest('.label-floating').removeClass('is-empty');
                }

                if (loConditions.nokEmailRecipients != '') {
                    $("#txtElseEmailRecipients").val(loConditions.nokEmailRecipients);
                    $("#txtElseEmailRecipients").closest('.label-floating').removeClass('is-empty');
                }

                if (loConditions.nokAdfEmailRecipients != '') {
                    $("#txtElseADFRecipients").val(loConditions.nokAdfEmailRecipients);
                    $("#txtElseADFRecipients").closest('.label-floating').removeClass('is-empty');
                }
                loThat.generateConditionalTable();
           }
        });
	},

    setDataTable: function() {
		var loThat = this;

		App.datatables();

		loThat.tableApi = $("#logs-datatable").DataTable({
		    buttons: [],
			dom: "<'row'<'col-sm-2 col-lg-2'l>>" +
				 "<'row'<'col-sm-12't>>" +
				 "<'row'<'col-sm-5'i><'col-sm-7'rp>>",
			columns: [
				// No
				{
					data: null,
					render: function (data, type, row, meta) {
						return loThat.tableApi.page.info().start + meta.row + 1;
					},
					searchable: false,
					orderable: false,
					width: "5%"
				},
				// Date
				{
					data: 1,
					searchable: false,
					render: function (date) {
						return `<time datetime='${date}'>${moment(new Date(date)).fromNow()}</time>`;
					},
					width: "10%"
				},
				// Description
				{
					data: 2,
					searchable: false,
					width: "45%"
				},
                // Service Provider
				{
					data: 3,
					searchable: false,
					width: "20%"
				},
				// Status
				{
					data: 4,
					searchable: false,
					className: "text-center text-capitalize",
					render: function (status) {
						var classes = {
							"success": "label-success",
							"failed": "label-danger",
							"other": "label-default"
						};
						if (!(status in classes)) {
							status = "other";
						}
						return `<span class="label ${classes[status]}" title="">${status}</span>`;
					},
					width: "10%"
				},
				// Actions
				{
					data: 5,
					searchable: false,
					orderable: false,
					className: "text-center",
					render: function (id) {
						return '<div class="btn-group">' +
						'<a href="/form_leads/' + id +'" class="btn btn-xs btn-success btn-table-action" data-original-title="Edit form lead" title="Edit form lead" data-toggle="tooltip">' +
						'<i class="material-icons">mode_edit</i>' +
						'</a>' +
						'</div>';
					},
					width: "10%"
				}
			],
			"initComplete": function(settings, json) {

			},
			"order": [[ 1, "desc" ]],
			"language": {
				"lengthMenu": 'Display <select class="form-control dataTables-records-length-select">'+
				'<option value="30"> 30</option>'+
				'<option value="40"> 40</option>'+
				'<option value="50"> 50</option>'+
				'<option value="100"> 100</option>'+
				'</select> records'
			},
			"autoWidth": false,
			"pageLength": 50,
			"processing": true,
			"serverSide": true,
			"searching": false,
			"ajax": '/forms/' + loThat.currentForm + '/form_logs/data'
		});

		loThat.loadStyles();
    },

    setEvents: function() {
        const standardNotification = 'standard-notification-type';
        const conditionalNotification = 'conditional-notification-type';
        var loThat = this;

        $('input.email-account').on('change', function() {
            $('input.email-account').not(this).prop('checked', false);
        });

        $('#standard_notification_type').change(function() {
            $('.standard-form-notification').show();
            $('.conditional-form-notification').hide();
            loThat.conditionalNotification = false;
            $('#is_conditional').val(false);
            loThat.generateConditionalTable();
        });

        $('#conditional_notification_type').change(function() {
            $('.standard-form-notification').hide();
            $('.conditional-form-notification').show();
            loThat.conditionalNotification = true;
            $('#is_conditional').val(true);
            loThat.generateConditionalTable();
        });

        $(".smsText").keyup(function () {
            var maxLength = 500;
            var smsText = $(".smsText").val().length;
            $("#smsCharCount").text(500 - smsText + "/" + maxLength);
            var smsText = maxLength - smsText;

            $(".smsText").text(smsText);

            if ($(".smsText").val().length > 5) {
                var loItem = $('.routing-number').val();

                if (loItem != "-1") {
                    $('.btn-sms').removeAttr('disabled');
                }
            } else {
                $('.btn-sms').attr('disabled', 'disabled');
            }
        });

        $('.field-pos').change(function (e) {
            var fieldList = $('.field-pos'),
                oldVal = parseInt(this.getAttribute('data-oldvalue'), 10),
                newVal = parseInt(this.value, 10),
                that = this,
                counter, value;

            fieldList.sort(function (a, b) {
                return parseInt(a.value, 10) - parseInt(b.value, 10);
            });

            if (parseInt(oldVal) < parseInt(newVal)) {
                counter = oldVal;
                for (var i = 0; i < fieldList.length; i++) {
                    if (fieldList[i] == that)
                        continue;
                    value = parseInt(fieldList[i].value, 10);
                    if (oldVal < value && value <= newVal) {
                        fieldList[i].value = counter++;
                        fieldList[i].setAttribute('data-oldvalue', fieldList[i].value);
                    }
                }
            } else {
                counter = newVal + 1;
                for (var i = 0; i < fieldList.length; i++) {
                    if (fieldList[i] == that)
                        continue;
                    value = parseInt(fieldList[i].value, 10);
                    if (newVal <= value && value < oldVal) {
                        fieldList[i].value = counter++;
                        fieldList[i].setAttribute('data-oldvalue', fieldList[i].value);
                    }
                }
            }

            this.setAttribute('data-oldvalue', newVal);
        });

        $('.btn-add-condition').on('click', function() {
            if (!loThat.validateConditionRow(false)) {
                var loOperation = 'or';

                if (loThat.criteriaTable.length == 0) {
                    loOperation = 'initial';
                }

                var condition = {
                        operation: loOperation, //initial, and, or
                        type: 'form_field', // submit, form_field
                        value: '', // form field value or all/partial/full
                        form_field: '', //form field name/type
                        pos: loThat.criteriaTable.length
                };
                loThat.generateConditionalTable();
                loThat.currentCondition = {
                    pos: loThat.criteriaTable.length,
                    operation: 'and',
                    type: 'form_field',
                    form_field: '',
                    value: ''
                };
                loThat.addContionalTableRow(true, loThat.criteriaTable.length, condition);
                loThat.criteriaTable.push(loThat.currentCondition);
            }
        });

        $('#btnSubmitFormChanges').on('click', function() {
            if (loThat.conditionalNotification) {
                if (!loThat.validateConditionRow(true)) {
                    loThat.saveCriteria();
                    $('#formEditForm').submit();
                }
            } else {
                if (!loThat.validateConditionRow(true)) {
                    loThat.saveCriteria();
                    $('#formEditForm').submit();
                } else {
                    $("#conditional_notification_type").click();
                }
            }
        });
    },

    saveCriteria: function() {
        var loThat = this;

        for (var i = 0; i < loThat.criteriaTable.length; i++) {
            var currentRow = loThat.criteriaTable[i];
            currentRow['pos'] = i;
        }
        var loOkSubjectLine = $("#txtThenEmailSubject").val();
        var loOkEmailRecipients = $("#txtThenEmailRecipients").val();
        var loOkAdfEmailRecipients = $("#txtThenADFRecipients").val();
        var loNokSubjectLine = $("#txtElseEmailSubject").val();
        var loNokEmailRecipients = $("#txtElseEmailRecipients").val();
        var loNokAdfEmailRecipients = $("#txtElseADFRecipients").val();
        var data = {
            'okSubjectLine': loOkSubjectLine,
            'okEmailRecipients': loOkEmailRecipients,
            'okAdfEmailRecipients': loOkAdfEmailRecipients,
            'nokSubjectLine': loNokSubjectLine,
            'nokEmailRecipients': loNokEmailRecipients,
            'nokAdfEmailRecipients': loNokAdfEmailRecipients,
            'criteria': loThat.criteriaTable
        };

        $('#condition_criteria').val(JSON.stringify(data));
    },

    showError: function(message) {
        $('.conditional-form-notification .error-message').html(message).show();
    },

    hideError: function() {
        $('.conditional-form-notification .error-message').html('').hide();
    },

    validateConditionRow: function(submissionCheck) {
        var loThat = this;
        var loValue = '';
        var loError = false;
        var loErrorMessage = 'No value entered.';

        if (submissionCheck && loThat.conditionalNotification && loThat.criteriaTable.length == 0) {
            loErrorMessage = 'No condition set. Please add a condition.';
            loError = true;
        } else {
            if (loThat.currentCondition.type == "form_field") {
                loValue = $('#txt-form-value-' + loThat.currentCondition.pos).val();

                if (loValue == '' || loValue == undefined) {
                    loErrorMessage = 'No value entered.';
                    loError = true;
                } else {
                    loThat.currentCondition.value = loValue;
                }

                if (loThat.currentCondition.form_field == '') {
                    loErrorMessage = 'No form field selected.';
                    loError = true;
                }
            } else {
                loValue = $('#condition-form-values-' + loThat.currentCondition.pos).val();

                if (loValue == '') {
                    loErrorMessage = 'No value selected.';
                    loError = true;
                } else {
                    loThat.currentCondition.value = $('#condition-form-values-' + loThat.currentCondition.pos).val();
                }
            }
        }

        if (loError) {
            loThat.showError(loErrorMessage);
        } else {
            loThat.hideError();
        }

        return loError;
    },

    addContionalTableRow: function(current, id, condition) {
        var loThat = this;
        var loFirstColumn = '<div class="col-md-1 conditional-text default-conditional-operation">IF</div>'
        var loDisabled = 'disabled';

        if (current) {
            loThat.currentCondition = condition;
            loDisabled = '';
        }

        if (condition.type == "form_field") {
            loSixthColumn = '<div class="col-md-3 remove-condition"><div class="btn btn-primary btn-delete-condition" style="float:right;">Remove Condition</div></div>';
        } else {
            loSixthColumn = '<div class="col-md-6 remove-condition"><div class="btn btn-primary btn-delete-condition" style="float:right;">Remove Condition</div></div>';
        }

        if (condition.operation != "initial" && id != 0) {
            loFirstColumn =
                                '<div class="col-md-1 form-group label-floating default-conditional-operation">' +
                                    '<select id="condition-operation-' + id + '" class="form-control" style="text-align:center;" ' + loDisabled + '>' +
                                    '    <option value="or">OR</option>' +
                                    '    <option value="and">AND</option>' +
                                    '</select>' +
                                '</div>';
        }

        var loFieldSelection = $('.defaultConditionFormFields').html();
        var loHtml = '<div class="row row-' + id + '" data-row-id="' + id + '"> ' +
                        loFirstColumn +
                        '<div class="col-md-2 form-group label-floating">' +
                            '<label for="condition-type-' + id + '" class="control-label">Select Condition Type</label>' +
                            '<select id="condition-type-' + id + '" class="form-control" ' + loDisabled + '>' +
                            '    <option value="form_field">Form Field</option>' +
                            '    <option value="submit">Submit Type</option>' +
                            '</select>' +
                        '</div>' +
                        '<div class="col-md-3 form-group label-floating default-condition-fields">' +
                            '<label for="condition-form-fields-' + id + '" class="control-label">Select Form Field</label>' +
                        '</div>' +
                        '<div class="col-md-1 conditional-text">EQUALS</div>' +
                        '<div class="col-md-2 form-group label-floating conditional-text-value" >' +
                            '<label for="txt-form-value-' + id + '" class="control-label">Enter Form Field Value</label>' +
                            '<input type="text" id="txt-form-value-' + id + '" class="form-control" ' + loDisabled + ' />' +
                        '</div>' +
                        '<div class="col-md-2 form-group label-floating conditional-select-value" style="display:none">' +
                            '<label for="condition-form-values-' + id + '" class="control-label">Select Submit Type</label>' +
                            '<select id="condition-form-values-' + id + '" class="form-control" ' + loDisabled + '>' +
                            '    <option value="all">all submits</option>' +
                            '    <option value="partial">partial submits</option>' +
                            '    <option value="full">full submits</option>' +
                            '</select>' +
                        '</div>' +
                        loSixthColumn +
                    '</div>';

        $('.form-field-sec').append(loHtml);
        var row = $(".row-" + id);
        row.find('.default-condition-fields').append('<select id="' + 'condition-form-fields-' + id + '" class="form-control" ' + loDisabled + '>' + loFieldSelection + '</select>');

        // Setting the values of the row
         if (condition.operation == "and") {
            $('#condition-operation-' + id).val("and");
         } else
         if (condition.operation == "or") {
            $('#condition-operation-' + id).val("or");
         }

         if (condition.type == "form_field") {
            $('#condition-type-' + id).val("form_field");
            $('#condition-form-fields-' + id).val(condition.form_field);
            $('#txt-form-value-' + id).val(condition.value);
            row.find('.default-condition-fields').show();
            row.find('.conditional-text-value').show();
            row.find('.conditional-select-value').hide();
         } else
         if (condition.type == "submit") {
            $('#condition-type-' + id).val("submit");
            $('#condition-form-values-' + id).val(condition.value);
            row.find('.default-condition-fields').hide();
            row.find('.conditional-text-value').hide();
            row.find('.conditional-select-value').show();
         }

        if (current) {
            $('#condition-form-fields-' + id).off().on('change', function() {
                var selected = $(this).find(":selected").val();

                if (selected != "none-selected") {
                    loThat.currentCondition['form_field'] = selected;
                } else {
                    loThat.currentCondition['form_field'] = '';
                }
            });

            $('#condition-type-' + id).off().on('change', function() {
                var row = $(this).closest('.row');
                var loDeleteCell = row.find('.remove-condition');
                var selected = $(this).find(":selected").val();

                if (selected == "form_field") {
                    loDeleteCell.removeClass('col-md-6').addClass('col-md-3');
                    row.find('.default-condition-fields').show();
                    row.find('.conditional-text-value').show();
                    row.find('.conditional-select-value').hide();
                    loThat.currentCondition['type'] = 'form_field';
                } else {
                    loDeleteCell.removeClass('col-md-3').addClass('col-md-6');
                    row.find('.default-condition-fields').hide();
                    row.find('.conditional-text-value').hide();
                    row.find('.conditional-select-value').show();
                    loThat.currentCondition['type'] = 'submit';
                }
            });

            $('#condition-form-values-' + id).off().on('change', function() {
                var selected = $(this).find(":selected").val();

                loThat.currentCondition['value'] = selected;
            });

            $('#condition-operation-' + id).off().on('change', function() {
                var selected = $(this).find(":selected").val();

                loThat.currentCondition['operation'] = selected;
            });
        }

        $('.btn-delete-condition').off().on('click', function() {
            const rowId = $(this).closest('.row').attr('data-row-id');

            loThat.removeConditionalTableRow(rowId);
        });
    },

    removeConditionalTableRow: function(id) {
        var loThat = this;

        loThat.criteriaTable.splice(id, 1);
        loThat.saveCriteria();
        loThat.generateConditionalTable();

        if (loThat.currentCondition.pos == id) {
            loThat.currentCondition = {};
        }
    },

    generateConditionalTable: function(withCurrentActive = false) {
        var loThat = this;

        $('.form-field-sec').html('');

        if (loThat.criteriaTable.length != 0) {
            for(var i=0; i < loThat.criteriaTable.length; i++) {
                var condition = loThat.criteriaTable[i];

                loThat.addContionalTableRow(withCurrentActive, i, condition);
            }
        }
    }
};

$(document).ready(function() {
    forms_backend_edit.init();
});