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/buyercall/assets/components/widgets/new_widget_page.js
/* jshint esversion: 6 */

(function () {
    "use strict";

    var $ = require('jquery');
    var _ = require('underscore');
    var Backbone = require('backbone');
    var { CallWidgetView, CallWidgetPreView } = require('./call_widget');
    var utils = require('../utils');
    var comp = require('./components');

    const defaultSettings = require('./default_settings');

    const wizardTemplate = require('./templates/new_widget_page.tpl');

    const API_ROOT = '/api/outbound';

    var WidgetModel = require('./models');

    var PageView = Backbone.View.extend({
        events: {
            'click a[data-gotostep]': 'handleNavigation',
            'click #install-instructions': 'handleInstallInstructions',
            'click #skip-button': 'handleSkip',
            'click #next-button': 'handleSkip',
            'click #save-button': 'handleSave',
            'click #exit-button': 'handleExit'
        },

        $id: function (id) {
          return this.el.querySelector('#' + id);
        },

        initialize: function () {
            // A list of all sub-views (wizard pages and toolbar)
            var renderSettings = () => {
                // Initialize the sub-components and the widget preview
                this.render();

                this.createModals();
            };

            // Are we creating a new view, or editing an existing one?
            this.widgetId = utils.getIdFromUrl(location.href) || 0;
            this.widgets = [];

            this.model = new WidgetModel(defaultSettings);
            this.listenTo(this.model, 'change', this.handleSettingsChange);
            this.listenTo(
                this.model,
                'change:transparentBackground',
                (model, val) => {
                    console.log(val);
                    this.$('.widget-preview-background').setClass('hide', !val);
                }
            );
            this.listenTo(this.model, 'change:typeButton change:typeLink', (model, val) => {
                var [ typeButton, typeLink ] = [ model.get('typeButton'), model.get('typeLink') ];

                this.$('#widget-button-container').setClass('hide', !typeButton);
                this.$('#widget-link-container').setClass('hide', !typeLink);
                this.$('h4').parent().setClass('hide', typeLink || typeButton);
            });

            this.listenTo(this.model, 'change:widgetType', this.enableStepsBasedOnType);

            if (this.widgetId) {
                let data = JSON.parse($('#widget-data').html());
                this.model.set(
                    _.extend({}, defaultSettings, data),
                    { silent: true }
                );
                renderSettings();
                this.showNextPage();
                this.enableStep(1, false);
                this.dirty = false;
            } else {
                renderSettings();
                for (let i = 2; i <= 6; i++) {
                    this.enableStep(i, false);
                }
                this.dirty = true;
            }
        },

        render: function () {
            this.$el.html(wizardTemplate(this.model.toJSON()));
            this.enableStepsBasedOnType();

            this.widgets = [];
            this.$('.widget-preview').each((i, el) => {
                let widget = new CallWidgetPreView({
                    settings: this.model,
                    state: el.getAttribute('data-widget-state')
                });
                widget.$el.appendTo(el);
                this.widgets.push(widget);
            });

            var views = [
                comp.SelectTypeView,
                comp.BeforeCallView,
                comp.StartingCallView,
                comp.CallSettingsView,
                comp.UnavailabilityView,
                comp.TriggerView,
            ];

            for (let i = 0; i < views.length; i++) {
                new views[i]({
                    model: this.model,
                    widgetId: this.widgetId
                }).$el.prependTo(this.$(`#step-${i + 1}`));
            }

            if (this.widgetId && this.model.get("widgetType") === "adf") {
                this.$('a[data-gotostep=step-2], a[data-gotostep=step-3], a[data-gotostep=step-5], a[data-gotostep=step-6]').attr('disabled', 'disabled');
            }
        },

        createModals: function () {
            this.$exitModal = $('<div></div>')
                .html($('#exit-modal-template').html())
                .children();
            $(document.body).append(this.$exitModal);
            this.$exitModal.find('.widget-btn-yes')
                .on('click', this.exit);
        },

        activeStep: function () {
            return parseInt($('.widget-steps-nav li.active a').attr('data-gotostep')[5]);
        },

        enableStep: function (n, enable) {
            if (typeof(enable) === 'undefined') {
                enable = true;
            }
            var $step = this.$('a[data-gotostep=step-' + n + ']');
            if (enable) {
                $step.removeAttr('disabled');
            } else {
                $step.attr('disabled', 'disabled')
            }
        },

        enableStepsBasedOnType: function () {
            if (this.model.get('widgetType') === 'adf') {
                this.enableStep(2, false);
                this.enableStep(3, false);
                this.enableStep(4, true);
                this.enableStep(5, false);
                this.enableStep(6, false);
            } else {
                for (let i = 2; i <= 6; i++) {
                    this.enableStep(i);
                }
            }
        },

        showNextPage: function () {
            var thisStep = this.activeStep(),
                i;

            for (let i = thisStep + 1; i < 7; i++) {
                let $nextTab = this.$('a[data-gotostep=step-' + i + ']');
                if ($nextTab && !$nextTab.attr('disabled')) {
                    $nextTab.click();
                    break;
                }
            }
        },

        /**
         * Saves the widget currently being edited. Returns a $.Deferred object
         * (https://api.jquery.com/category/deferred-object/)
         */
        saveWidget: function () {
            var url = API_ROOT,
                method = 'POST',
                promise;

            if (this.widgetId) {
                url = `${API_ROOT}/${this.widgetId}`;
                method = 'PUT';
            }

            return $.ajax(url, {
                contentType: 'application/json',
                method: method,
                data: JSON.stringify(this.model.toJSON())
            });


        },

        exit: function () {
            document.location.href = '/outbound';
        },

        handleInstallInstructions: function (event) {
            if (this.widgetId && !this.dirty) {
                window.location.href = '/outbound/install-instructions/' + this.widgetId;
                return;
            }

            if (window.confirm('Your widget is not saved. Do you want to save it now?')) {
                this.saveWidget().done((data) => {
                    this.widgetId = data.id;
                    history.pushState({}, document.title, `/outbound/${this.widgetId}`);
                    window.location.href = '/outbound/install-instructions/' + this.widgetId;
                });
            }
        },

        handleNavigation: function (event) {
            // Do not navigate to disabled steps
            var $clicked = $(event.currentTarget);
            if ($clicked.attr('disabled'))
                return;

            this.$('.wizard-nav li').removeClass('active');
            $clicked.parent().addClass('active');

            this.$('.widget-configure').not('.hide').addClass('hide');
            this.$('#' + $clicked.attr('data-gotostep')).removeClass('hide');
            if (this.activeStep() === 1) {
                this.$('#install-instructions').hide();
                this.$('#skip-button, #save-button').hide();
                this.$('#next-button').show();
            } else {
                this.$('#install-instructions').show();
                this.$('#skip-button, #save-button').show();
                this.$('#next-button').hide();
            }

            for (let i = 0; i < this.widgets.length; i++) {
                this.widgets[i].updateSettings(this.model.toJSON());
            }
        },

        handleSkip: function (event) {
            // utils.flash('');

            // Are we on the last page?
            if (this.$('.widget-steps-nav li:nth-child(7)').hasClass('active')) {
                this.saveWidget().done(() => {
                    this.handleInstallInstructions();
                });
            } else {
                this.showNextPage();
            }
        },

        handleSave: function (event) {
            // utils.flash('');

            this.saveWidget().done((data) => {
                // Update the URL to reflect that we've saved the widget
                if (!this.widgetId) {
                    history.pushState({}, document.title, `/outbound/${data.id}`);
                }

                this.widgetId = data.id;
                this.model.name = data.name;
                this.dirty = false;

                // Are we on the last page?
                var lastPage = this.activeStep() == 6 || (this.model.get('widgetType') == 'adf' && this.activeStep() == 4);
                if (lastPage) {
                    this.handleInstallInstructions();
                } else {
                    this.showNextPage();
                }
            }).fail((xhr, status, error) => {
                console.log(status, error);
            });
        },

        handleExit: function (event) {
            if (this.dirty) {
                this.$exitModal.modal();
            } else {
                this.exit();
            }

            return false;
        },

        // Called every time the user types in a text field
        handleSettingsChange: function (event) {
            console.log('Settings changed!!!');
            this.dirty = true;
        }
    });

    $.fn.extend({
        setClass: function (class_, condition) {
            if (condition) {
                this.addClass(class_);
            } else {
                this.removeClass(class_);
            }
        }
    });

    module.exports = {
        init: function () {
            var pageView = new PageView({ el: '#body-container' });
        }
    };
}());