/* * Licensed Materials - Property of IBM * * IBM Cognos Products: SHARE * * (C) Copyright IBM Corp. 2015, 2018 * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. */ define([ 'bi/glass/app/ContentView', 'bi/commons/utils/BidiUtil', 'bi/schedule/app/appControler', 'jquery', 'bi/sharecommon/utils/translator', 'q', 'bi/sharecommon/utils/simpledoT', 'text!bi/schedule/templates/SubscriptionView.html', 'underscore', 'bi/commons/ui/widgets/TimePicker', 'bi/schedule/views/WeeklyCadencePickerView', 'bi/commons/utils/Utils', 'bi/schedule/views/FormatPickerView', 'bi/schedule/views/ScheduleDeliveryPickerView', 'ca_portal/features/mypreferences/MyPreferences', 'bi/content_apps/utils/ContentStoreObject', 'caglass/ajax/CAAuthentication', 'bi/commons/utils/DateTimeUtils', 'moment' ], function (View, BidiUtil, controler, $, t, Q, dot, template, _, TimePicker, WeeklyCadencePicker, Utils, FormatPicker, ScheduleDeliveryPickerView, MyPreferences, ContentStoreObject, CAAuthentication, DateTimeUtils, moment) { 'use strict'; var subscriptionView = View.extend({ /** * Constructor / initialization function for view * * @param options Options that are apart of this view. options.descriptor is required and inside * the descriptor object name and reportId are both required. * descriptor { * name: 'some-report-name', * reportId: 'some-report-id' * } */ init: function (options) { subscriptionView.inherited('init', this, arguments); this.timezone = options.glassContext.services.userProfile.preferences.timeZoneID; this.locale = options.glassContext.services.userProfile.preferences.contentLocale; this._initVariables(); $.extend(this, options); if (typeof this.descriptor !== 'undefined' && this.descriptor.name && this.descriptor.reportId) { this.id = this.descriptor.id; if (this.id) { this.isEditMode = true; } if (this.isEditMode) { this.name = this.descriptor.name; } else { this.name = t.translate("subscription_name", { param: this.descriptor.name }); } this.reportId = this.descriptor.reportId; this.type = this.descriptor.type; for (var key in this.descriptor.scheduleInfo) { this.scheduleInfo[key] = this.descriptor.scheduleInfo[key]; } for (key in this.descriptor.options) { this.options[key] = this.descriptor.options[key]; } if (this.descriptor.parameters) { this.parameterValues = this.descriptor.parameters; } } else { throw "Error: No descriptor was given."; } }, /** * Render function */ render: function () { var deferred = Q.defer(); var parameterValues = this.parameterValues || []; this.showPrompts = parameterValues.length > 0; var htmlGenerator = dot.simpleTemplate(template); var attributes = { report_name: _.escape(BidiUtil.enforceTextDirection(this.name)), subscription_header_region: t.translate("subscription_header_region"), subscription_panel_title: t.translate("subscription_panel_title"), schedule_timepicker_label: t.translate("schedule_time_label"), schedule_output_label: t.translate("schedule_output_label"), schedule_select_text: t.translate("schedule_select_text"), schedule_prompts_label: t.translate("schedule_prompts_label"), schedule_create_btn: this.isEditMode ? t.translate("schedule_update_btn_label") : t.translate("schedule_create_btn_label"), schedule_cancel_btn: t.translate("schedule_cancel_btn_label"), subs_delivery_message: t.translate("subs_delivery_message"), schedule_delivery_label: t.translate("schedule_delivery_label"), schedule_prompts_text: t.translate("schedule_prompts_text"), isUpdate: this.isEditMode, uniqueid: _.uniqueId(), output_format_select_text: t.translate('output_format_select_text'), showPrompts: this.showPrompts }; attributes.subscription_controls_description = t.translate('subscription_controls_description', { action1: attributes.schedule_create_btn, action2: attributes.schedule_cancel_btn }); this.$el.html(htmlGenerator(attributes)); // Render the 'widgets' that this subscription view has this._setIcons(); this.renderCadencePicker(); this.renderTimePicker(); this.renderOutputFormatPicker(); this.renderDeliveryPicker(); if (this.showPrompts) { this.renderPromptRow(); } this._setEvents(); deferred.resolve(this); return deferred.promise; }, setFocus: function () { this.$el.find('.schedule_button_groups').children().first().focus(); }, renderCadencePicker: function () { this.cadencePicker = new WeeklyCadencePicker({ $el: this.$el.find(".schedule_cadence_picker"), glassContext: this.glassContext, objectInformation: { showRunEvery: false, showDailyInterval: false, descriptor: { scheduleInfo: this.scheduleInfo } } }); this.cadencePicker.render(); }, renderTimePicker: function () { this.timePicker = new TimePicker({ $el: this.$el.find(".schedule_time_picker_container"), timezone: this.timezone, attributes: { minuteStep: 1, showMeridian: !DateTimeUtils.is24HrFormat(this.locale), defaultTime: this.scheduleInfo.startDate } }); this.timePicker.render(); }, renderOutputFormatPicker: function () { try { var showHtmlOnly = this.type === 'interactiveReport'; var showPdfOnly = this.type === 'powerPlay8Report' || this.type === 'powerPlay8ReportView'; this.outputFormatPicker = new FormatPicker({ $el: this.$el.find('.output_format_list'), $toggler: this.$el.find('.output_format_picker'), outputFormats: this.options.outputFormat.slice(), glassContext: this.glassContext, slideoutparent: this.slideout, overlay: true, showHTML: !showPdfOnly, showPDF: !showHtmlOnly && this.glassContext.hasCapability("canGeneratePDFOutput"), showExcel: !showHtmlOnly && !showPdfOnly && this.glassContext.hasCapability("canGenerateXLSOutput"), showCSV: !showHtmlOnly && !showPdfOnly && this.glassContext.hasCapability("canGenerateCSVOutput"), showXML: !showHtmlOnly && !showPdfOnly && this.glassContext.hasCapability("canGenerateXMLOutput") }); this.outputFormatPicker.render(); } catch (e) { console.log('There was an error initializing the FormatPicker.', e); } }, renderDeliveryPicker: function () { try { this.deliveryPicker = new ScheduleDeliveryPickerView({ $el: this.$el.find('.schedule_delivery_picker'), $toggler: this.$el.find('.schedule_delivery_picker'), $activeOptionsContainer: this.$el.find('.delivery_list.clearfix'), reportName: this.name, deliveryOptions: this.options.delivery, isEditMode: this.isEditMode, glassContext: this.glassContext, slideoutparent: this.slideout, showMobile: this.glassContext.hasCapability("canUseMobileService") && this.type === "interactiveReport", showSaveToFileSystem: false, overlay: true }); this.deliveryPicker.render(); } catch (e) { console.log('There was an error initializing the DeliveryPicker.', e); } }, renderPromptRow: function () { var _self = this; // Provide bare minimum objectInfo var _objectInfo = { id: this.reportId }; this.objectInfo = _objectInfo; // Slide out is to the left of parent and is an overlay this.$promptTarget = this.$el.find('.prompt_picker_target'); this.$promptTarget.on('clicktap', function () { _self.glassContext.appController.showSlideOut({ 'position': _self.slideout ? null : 'left', 'parent': _self.slideout, 'overlay': true, 'enableTabLooping': true, 'label': t.translate("schedule_prompt_picker_name"), 'content': { 'module': 'bi/content_apps/PromptValuesView', 'parentView': _self, 'glassContext': _self.glassContext, 'promptDisplayValues': ContentStoreObject.getPromptsDisplayValues(_self.parameterValues), 'parameters': _self.parameterValues, 'isEditMode': _self.isEditMode, 'clearCallback': function () { if (_self.parameterValues.length > 0) { _self._updatePromptValueLabel(); } }, 'editCallback': function (parameters) { _self._updatePromptValueLabel(parameters); } } }); }); this._updatePromptValueLabel(this.parameterValues); }, _updatePromptValueLabel: function (prompts) { // Reset the parameterValues to empty on Clear callback this.parameterValues = prompts ? prompts : []; var $promptValueLabel = this.$el.find('.currentPromptValues'); $promptValueLabel.text(this._getPromptValueLabel()); }, _getPromptValueLabel: function () { var label = t.translate("schedule_prompt_value_label_default"); if (this.parameterValues && this.parameterValues.length > 0) { if (this.parameterValues.length == 1) { label = t.translate("schedule_prompt_value_label_single"); } else { label = t.translate("schedule_prompt_value_label_multiple", { 'number': this.parameterValues.length }); } } return label; }, close: function () { var _self = this; this.slideout.hide().then(function () { _self._runCallback(); }); }, /** * Mark the pane as in progress with a semi-transparent overlay */ setWorking: function () { this.$overlay = this.$el.find(".progress-overlay"); this.$overlay.show(); }, /** * Show the view if hidden */ setDone: function () { if (!this.$overlay) return; this.$overlay.hide(); }, _setIcons: function () { var icons = this.$el.find('.common_schedule_icon'); for (var i = 0; i < icons.length; i++) { var $icon = $(icons[i]); Utils.setIcon($icon, 'common-' + $icon.data('icon'), t.translate('svg_expand_icon')); } }, _setEvents: function () { this.$el.find('.schedule_primary_button').on('clicktap', function () { this.setWorking(); // hide time warning message if any present on create button click // if the user input time is still invalid it will show again // the message will disappear with a successful creation of schedule this.hideWarningMessage(); if (this.validate()) { // if a startDate exists (we are in edit mode), re-use it. var localDate; if (this.scheduleInfo.startDate !== 'current') { localDate = moment.utc(this.scheduleInfo.startDate).toDate(); } else { localDate = new Date(); } this.scheduleInfo.startDate = this.timePicker.getDateTimeUTC(localDate); if (this.outputFormatPicker !== null) { this.options.outputFormat = this.outputFormatPicker.getOutputFormats(); } if (this.deliveryPicker !== null) { this.options.delivery = this.deliveryPicker.getDeliveryOptions(); } // set default content locale this.options.outputLocale = [this.glassContext.services.userProfile.preferences.contentLocale]; // grab cadencePicker info this.scheduleInfo = this.cadencePicker.toDescriptor(this.scheduleInfo); var subscriptionDesc = { name: this.name, reportId: this.reportId, scheduleInfo: this.scheduleInfo, options: this.options }; if (this.id) { subscriptionDesc.id = this.id; } if (this.showPrompts) { subscriptionDesc.parameters = this.parameterValues; } // Check user credentials in tandem when creating subscription controler.getUserCredential(this.glassContext).then(function () { this._createOrUpdateSubscription(subscriptionDesc); }.bind(this)).fail(function () { // Credentials need to be renewed this.glassContext.appController.showToast(t.translate('sub_credentials_expired_msg'), { 'type': 'warning', 'preventDuplicates': true, 'btnLabel': t.translate('sub_renew_credentials_button'), 'callback': function () { this._caAuthentication = new CAAuthentication(); return this._caAuthentication.storeCredentials(this.glassContext).then(function () { this._createOrUpdateSubscription(subscriptionDesc); }.bind(this)).fail(function (error) { if (error && error.displayObjects) { this._myPreferences = new MyPreferences({ glassContext: this.glassContext }); return this._myPreferences.openCreateCredentialDialog(error.displayObjects).then(function () { this._createOrUpdateSubscription(subscriptionDesc); }.bind(this)); } }.bind(this)).fail(function () { this.setDone; }.bind(this)); }.bind(this) }); }.bind(this)); } else { // show the invalid time warning message this.showWarningMessage(); // unlock ui this.setDone(); } }.bind(this)); this.$el.find('.schedule_secondary_button').on('clicktap', function () { // Because the callback is (currently) only used for updates just delete it // if the user clicks cancel so that when in edit mode the view doesn't get refreshed // with the same data. delete this.callback; this.close(); }.bind(this)); }, _createOrUpdateSubscription: function (subscriptionDesc) { var _self = this; if (this.isEditMode) { controler.updateSubscription(subscriptionDesc, this.glassContext).then(function () { _self.glassContext.appController.showToast(t.translate('sub_update_success_msg'), { 'preventDuplicates': false }); _self.setDone(); _self.close(); }, function () { _self.setDone(); }); } else { controler.createSubscription(subscriptionDesc, this.glassContext).then(function (data) { _self.glassContext.appController.showToast(t.translate('sub_create_success_msg'), { 'preventDuplicates': false }); _self.setDone(); _self.close(); }, function () { _self.setDone(); }); } }, _runCallback: function () { // Check to see if there is a callback function to run if (this.callback) { if (this.callback.onUpdate && typeof this.callback.onUpdate === 'function') { this.callback.onUpdate(); } } }, validate: function () { // Starting from the cadence pickers this.msgs = []; var $startTimeDiv = this.$el.find(".schedule_time_picker_container"); $startTimeDiv.removeAttr('aria-invalid aria-describedby'); if (!this.timePicker.isValidTime()) { this.msgs.push(t.translate("schedule_invalid_start_time")); $startTimeDiv.attr({ 'aria-invalid': 'true', 'aria-describedby': this.msgs[0] }); // One message at a time return false; } // Check delivery Options var deliveryOptions = this.deliveryPicker.getDeliveryOptions(); var $deliveryListDiv = this.$el.find('.delivery_list'); $deliveryListDiv.removeAttr('aria-invalid aria-describedby'); if (deliveryOptions.email) { if (!deliveryOptions.email.emailAsAttachment && !deliveryOptions.email.emailAsURL) { this.msgs.push(t.translate('schedule_delivery_email_require_include')); $deliveryListDiv.attr({ 'aria-invalid': 'true', 'aria-describedby': this.msgs[0] }); return false; } } if (deliveryOptions.print && $.trim(deliveryOptions.print.name) === '') { this.msgs.push(t.translate('schedule_delivery_printer_empty_error')); $deliveryListDiv.attr({ 'aria-invalid': 'true', 'aria-describedby': this.msgs[0] }); return false; } return this.msgs.length === 0; }, /** * Show warning message for invalid time input by user */ showWarningMessage: function () { this.$warningMessage = this.$el.find(".invalid_input_warning_message").text(this.msgs[0]); if (!this.$warningMessage) { return; } else { this.$warningMessage.show(); } }, /** * Hide the warning message */ hideWarningMessage: function () { if (!this.$warningMessage) return; this.$warningMessage.hide(); }, _initVariables: function () { this.descriptor = null; this.id = ''; this.name = ''; this.reportId = ''; this.scheduleInfo = { type: 'weekly', active: true, startDate: 'current', endDate: '', endType: 'indefinite', everyNPeriods: 0, timezone: this.timezone, weekly: { weeklySunday: false, weeklyMonday: false, weeklyTuesday: false, weeklyWednesday: false, weeklyThursday: false, weeklyFriday: false, weeklySaturday: false } }; this.options = { delivery: { save: { notify: true } }, outputFormat: [] }; this.parameterValues = null; this.cadencePicker = null; this.timePicker = null; this.outputFormatPicker = null; this.deliveryPicker = null; this.isEditMode = false; this.showPrompts = false; this.callback = {}; } }); return subscriptionView; });