<commit_before>define([
	'knockout',
	'text!./death.html',
	'd3',
	'utils/CommonUtils',
	'utils/ChartUtils',
	'const',
	'pages/data-sources/classes/Report',
	'components/Component',
	'components/heading',
	'components/charts/donut',
	'components/charts/line',
	'components/charts/boxplot',
	'components/charts/trellisline',
], function (
	ko,
	view,
	d3,
	commonUtils,
	ChartUtils,
	constants,
	Report,
	Component
) {
	class Death extends Report {
		constructor(params) {
			super(params);

			this.prevalenceByGenderAgeYearData = ko.observable();
			this.byMonthSeriesLineData = ko.observable();
			this.prevalenceByTypeDonutData = ko.observable();
			this.ageBoxplotData = ko.observable();

			this.chartFormats = {
				prevalenceByGenderAgeYear: {
					trellisSet: null,
					trellisLabel: "Age Decile",
					seriesLabel: "Year of Observation",
					yLabel: "Prevalence Per 1000 People",
					xFormat: d3.timeFormat("%Y"),
					yFormat: d3.format("0.2f"),
					tickPadding: 20,
					colors: d3.scaleOrdinal()
						.domain(['MALE', 'FEMALE', 'UNKNOWN'])
						.range(["#1F78B4", "#FB9A99", "#33A02C"])
				},
				byMonthSeriesLine: {
					xScale: null,
					xFormat: d3.timeFormat("%m/%Y"),
					tickFormat: d3.timeFormat("%Y"),
					xLabel: "Date",
					yLabel: "Prevalence per 1000 People"
				},
				prevalenceByTypeDonut: {
					margin: {
						top: 5,
						left: 5,
						right: 200,
						bottom: 5
					}
				},
				ageBoxplot: {
					yLabel: 'Age at first occurence',
					xLabel: 'Gender',
					yFormat: d3.format(',.1s'),
				},
			};
			this.loadData();

		}

		parseData({ data }) {
			this.prevalenceByGenderAgeYear(data.prevalenceByGenderAgeYear);
			this.prevalenceByMonth(data.prevalenceByMonth);
			this.prevalenceByType(data.deathByType);
			this.ageBoxplot(data.ageAtDeath);
		}

		prevalenceByGenderAgeYear(data) {
			this.chartFormats.prevalenceByGenderAgeYear.trellisSet = constants.defaultDeciles;
			this.prevalenceByGenderAgeYearData(data);
		}

		prevalenceByMonth(data) {
			const prevData = ChartUtils.normalizeArray(data);
			if (!prevData.empty) {
				const byMonthSeries = ChartUtils.mapMonthYearDataToSeries(prevData, {
					dateField: 'xCalendarMonth',
					yValue: 'yPrevalence1000Pp',
					yPercent: 'yPrevalence1000Pp'
				});
				this.byMonthSeriesLineData(byMonthSeries);
				this.chartFormats.byMonthSeriesLine.xScale = d3.scaleTime()
					.domain(d3.extent(byMonthSeries[0].values, d => d.xValue));
			}
		}

		prevalenceByType(data) {
			if (!!data && data.length > 0) {
				this.prevalenceByTypeDonutData(ChartUtils.mapConceptData(data));
			}
		}

		ageBoxplot(data) {
			const bpseries = [];
			const bpdata = ChartUtils.normalizeArray(data);
			if (!bpdata.empty) {
				for (let i = 0; i < bpdata.category.length; i++) {
					bpseries.push({
						Category: bpdata.category[i],
						min: bpdata.minValue[i],
						max: bpdata.maxValue[i],
						median: bpdata.medianValue[i],
						LIF: bpdata.p10Value[i],
						q1: bpdata.p25Value[i],
						q3: bpdata.p75Value[i],
						UIF: bpdata.p90Value[i]
					});
				}
				this.ageBoxplotData(bpseries);
			}
		}
	}

	return commonUtils.build('report-death', Death, view);
});
<commit_msg>Fixed month precision in Achilles - Death prevalence report (#1333)<commit_after>define([
	'knockout',
	'text!./death.html',
	'd3',
	'utils/CommonUtils',
	'utils/ChartUtils',
	'const',
	'pages/data-sources/classes/Report',
	'components/Component',
	'components/heading',
	'components/charts/donut',
	'components/charts/line',
	'components/charts/boxplot',
	'components/charts/trellisline',
], function (
	ko,
	view,
	d3,
	commonUtils,
	ChartUtils,
	constants,
	Report,
	Component
) {
	class Death extends Report {
		constructor(params) {
			super(params);

			this.prevalenceByGenderAgeYearData = ko.observable();
			this.byMonthSeriesLineData = ko.observable();
			this.prevalenceByTypeDonutData = ko.observable();
			this.ageBoxplotData = ko.observable();

			this.chartFormats = {
				prevalenceByGenderAgeYear: {
					trellisSet: null,
					trellisLabel: "Age Decile",
					seriesLabel: "Year of Observation",
					yLabel: "Prevalence Per 1000 People",
					xFormat: d3.timeFormat("%Y"),
					yFormat: d3.format("0.2f"),
					tickPadding: 20,
					colors: d3.scaleOrdinal()
						.domain(['MALE', 'FEMALE', 'UNKNOWN'])
						.range(["#1F78B4", "#FB9A99", "#33A02C"])
				},
				byMonthSeriesLine: {
					xScale: null,
					xFormat: d3.timeFormat("%m/%Y"),
					tickFormat: d3.timeFormat("%Y"),
					xLabel: "Date",
					yLabel: "Prevalence per 1000 People",
					yFormat: d3.format("0.2f"),
					getTooltipBuilder: options => {
						return d => {
							const format = d3.format("0.5f");
							return `
								${options.xLabel}: ${options.xFormat(d.xValue)}<br/>
								${options.yLabel}: ${format(d.yValue)}
							`;
						}
					}
				},
				prevalenceByTypeDonut: {
					margin: {
						top: 5,
						left: 5,
						right: 200,
						bottom: 5
					}
				},
				ageBoxplot: {
					yLabel: 'Age at first occurence',
					xLabel: 'Gender',
					yFormat: d3.format(',.1s'),
				},
			};
			this.loadData();

		}

		parseData({ data }) {
			this.prevalenceByGenderAgeYear(data.prevalenceByGenderAgeYear);
			this.prevalenceByMonth(data.prevalenceByMonth);
			this.prevalenceByType(data.deathByType);
			this.ageBoxplot(data.ageAtDeath);
		}

		prevalenceByGenderAgeYear(data) {
			this.chartFormats.prevalenceByGenderAgeYear.trellisSet = constants.defaultDeciles;
			this.prevalenceByGenderAgeYearData(data);
		}

		prevalenceByMonth(data) {
			const prevData = ChartUtils.normalizeArray(data);
			if (!prevData.empty) {
				const byMonthSeries = ChartUtils.mapMonthYearDataToSeries(prevData, {
					dateField: 'xCalendarMonth',
					yValue: 'yPrevalence1000Pp',
					yPercent: 'yPrevalence1000Pp'
				});
				this.byMonthSeriesLineData(byMonthSeries);
				this.chartFormats.byMonthSeriesLine.xScale = d3.scaleTime()
					.domain(d3.extent(byMonthSeries[0].values, d => d.xValue));
			}
		}

		prevalenceByType(data) {
			if (!!data && data.length > 0) {
				this.prevalenceByTypeDonutData(ChartUtils.mapConceptData(data));
			}
		}

		ageBoxplot(data) {
			const bpseries = [];
			const bpdata = ChartUtils.normalizeArray(data);
			if (!bpdata.empty) {
				for (let i = 0; i < bpdata.category.length; i++) {
					bpseries.push({
						Category: bpdata.category[i],
						min: bpdata.minValue[i],
						max: bpdata.maxValue[i],
						median: bpdata.medianValue[i],
						LIF: bpdata.p10Value[i],
						q1: bpdata.p25Value[i],
						q3: bpdata.p75Value[i],
						UIF: bpdata.p90Value[i]
					});
				}
				this.ageBoxplotData(bpseries);
			}
		}
	}

	return commonUtils.build('report-death', Death, view);
});
<|endoftext|>


<commit_before>describe('templates', function () {
  beforeEach(module('templates', function ($provide) {
    $provide.decorator('$templateCache', function ($delegate) {
      var put = $delegate.put;
      $delegate.toTest = [];
      $delegate.put = function (uri) {
        this.toTest.push(uri);
        return put.apply(this, [].slice.call(arguments));
      };
      return $delegate;
    });
  }), 'prx');

  it ('can compile all templates', inject(function ($rootScope, $compile, $templateCache) {
    var scope = $rootScope.$new();
    angular.forEach($templateCache.toTest, function (uri) {
      $compile($templateCache.get(uri))(scope);
    });
  }));
});<commit_msg>load prx first<commit_after>describe('templates', function () {
  beforeEach(module('prx', 'templates', function ($provide) {
    $provide.decorator('$templateCache', function ($delegate) {
      var put = $delegate.put;
      $delegate.toTest = [];
      $delegate.put = function (uri) {
        this.toTest.push(uri);
        return put.apply(this, [].slice.call(arguments));
      };
      return $delegate;
    });
  }));

  it ('can compile all templates', inject(function ($rootScope, $compile, $templateCache) {
    var scope = $rootScope.$new();
    angular.forEach($templateCache.toTest, function (uri) {
      $compile($templateCache.get(uri))(scope);
    });
  }));
});<|endoftext|>


<commit_before>/**
 * Sleepy Modal
 *
 * Highly customizable modals
 *
 */

;(function ($, window, document) {

  var

    // Set some defaults
    defaults = {
      escKey : true,
      forceShow : false,
      preventDefault : true,
      showOverlay : true,
      overlaySelector : '#overlay',
      modalSelector : '#modal',
      modalContentSelector : '#modal-content',
      closeSelector : '.close-modal',
      transitionIn : {
        effect : 'fadeIn', // fadeIn, ...
        duration : 'fast' // fast, slow, int, ...
      },
      transitionOut : {
        effect : 'fadeOut', // fadeOut, ...
        duration : 'fast' // fast, slow, int, ...
      },
      height : 'auto',
      width : 'auto',
      remote : {
        url : false,
        type : 'get',
        data : {}
      },
      event : 'click',
      xPos : 'center', // left, center, right, int, ...
      yPos : 'center', // top, center, bottom, int, ...
      content : false,
      onCloseNavTo : false,
      onBeforeShow : false,
      onAfterShow : false,
      onBeforeHide : false,
      onAfterHide : false
    },

    // Set the name of the plugin
    pluginName = 'sleepyModal';

  /**
   * Constructor
   */

  function SleepyModal (element, options) {

    if ( element ) {

      // Set the current DOM node being acted upon
      this.element = element;

      // Set the current jQuery object being acted upon
      this.$element = $(element);

      // Set the current DOM node tag name being acted upon (e.g. "select" or "a")
      if ( this.$element.prop('tagName') && typeof( this.$element.prop('tagName') ) == 'string' ) {
        this.htmlTag = this.$element.prop('tagName').toLowerCase();
      };

    };

    // Set allowed events
    this.allowedEvents = [
      'keydown', 'keypress', 'keyup',
      'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'hover', 'click', 'dblclick',
      'focus', 'blur', 'focusin', 'focusout', 'change', 'select'
    ];

    // Set allowed transitions in
    this.allowedTransitionIn = []

    // Set allowed transitions out
    this.allowedTransitionOut = []

    // Merge the options into the defaults
    this.options = $.extend( true, {}, defaults, options );

    // Set a reference to the original, un-merged defaults
    this._defaults = defaults;

    // Set a reference to the name of the plugin
    this._name = pluginName;

    // If no "modalContentSelector" option is given
    // (since it's optional), use the "modalSelector"
    // instead (since it's required)
    this.options.modalContentSelector = (this.options.modalContentSelector && this.options.modalContentSelector != '') ? this.options.modalContentSelector : this.options.modalSelector;

    // Away we go!
    this.init();

  };

  /**
   * Public methods
   */

  SleepyModal.prototype.init = function () {
    var self = this;

    this.showOverlay = function () {
      if ( !$(this.options.overlaySelector).is(':visible') ) {
        if ( this.options.overlaySelector ) {
          if ( this.options.transitionIn ) {
            switch ( this.options.transitionIn.effect ) {
              case 'fadeIn':
                $(this.options.overlaySelector).fadeIn( this.options.transitionIn.duration );
                break;
              default:
                $(this.options.overlaySelector).show();
            };
          };
        };
      };
    };

    this.focusFirstFormField = function () {
      $firstFormField = $(this.options.modalContentSelector + ' input[type=submit],' + this.options.modalContentSelector + ' input[type=password],' + this.options.modalContentSelector + ' input[type=email],' + this.options.modalContentSelector + ' input[type=text],' + this.options.modalContentSelector + ' select,' + this.options.modalContentSelector + ' textarea').not('.no-auto-focus').first();
      if ( $firstFormField.parent().hasClass('custom-select') || $firstFormField.parent().hasClass('custom-checkbox') ) {
        $firstFormField.parent('.custom-select, .custom-checkbox').addClass('focus');
      };
      $firstFormField.focus();
    },

    this.hideOverlay = function () {
      if ( this.options.overlaySelector ) {
        if ( this.options.transitionOut ) {
          switch ( this.options.transitionOut.effect ) {
            case 'fadeOut':
              $(this.options.overlaySelector).fadeOut( this.options.transitionOut.duration );
              break;
            default:
              $(this.options.overlaySelector).hide();
          };
        };
      };
    };

    this.showModal = function () {
      this.showOverlay();
      this.onBeforeShow();
      if ( !$(this.options.modalSelector).is(':visible') ) {
        if ( this.options.transitionIn ) {
          switch ( this.options.transitionIn.effect ) {
            case 'fadeIn':
              this.injectContent();
              this.sizeModal();
              this.positionModal();
              $(this.options.modalSelector).fadeIn( this.options.transitionIn.duration, function () {
                self.focusFirstFormField();
                self.onAfterShow();
              });
              break;
            default:
              $(this.options.modalSelector).show( function () {
                self.injectContent();
                self.sizeModal();
                self.positionModal();
                self.focusFirstFormField();
                self.onAfterShow();
              });
          };
        };
      } else {
        this.hideModal( true );
      };
    };

    this.hideModal = function (showAfterHide) {
      this.onBeforeHide();
      if ( this.options.transitionOut ) {
        switch ( this.options.transitionOut.effect ) {
          case 'fadeOut':
            $(this.options.modalSelector).fadeOut( this.options.transitionOut.duration, function () {
              self.removeContent();
              if (showAfterHide) {
                self.showModal();
              };
            });
            break;
          default:
            $(this.options.modalSelector).hide( function () {
              self.removeContent();
              if (showAfterHide) {
                self.showModal();
              };
            });
        };
      };
      this.onAfterHide();
      ESO.app.focusFirstFormField();
    };

    this.injectContent = function () {
      $(this.options.modalContentSelector).html( this.content );
    };

    this.removeContent = function () {
      $(self.options.modalContentSelector).empty();
    };

    this.positionModal = function () {
      // Horizontal position
      switch ( this.options.xPos ) {
        case 'left':
          $(this.options.modalSelector).css({
            left : 0
          });
          break;
        case 'center':
          $(this.options.modalSelector).css({
            left : ( $(window).width() - $(this.options.modalSelector).outerWidth() ) / 2
          });
          break;
        case 'right':
          $(this.options.modalSelector).css({
            right : 0
          });
          break;
        default:
          $(this.options.modalSelector).css({
            left : ( $(window).width() - $(this.options.modalSelector).outerWidth() ) / 2
          });
      };
      // Vertical position
      switch ( this.options.yPos ) {
        case 'top':
          $(this.options.modalSelector).css({
            top : 0
          });
          break;
        case 'center':
          $(this.options.modalSelector).css({
            top : ( $(window).height() - $(this.options.modalSelector).outerHeight() ) / 2
          });
          break;
        case 'bottom':
          $(this.options.modalSelector).css({
            bottom : 0
          });
          break;
        default:
          $(this.options.modalSelector).css({
            top : ( $(window).height() - $(this.options.modalSelector).outerHeight() ) / 2
          });
      };
    };

    this.sizeModal = function () {
      $(this.options.modalSelector).css({
        height : this.options.height,
        width : this.options.width,
      });
    };

    this.bindModalClose = function () {
      if ( this.options.closeSelector ) {
        $(document).on('click', this.options.closeSelector, function (event) {
          self.hideOverlay();
          self.hideModal();
          self.onCloseNavigateTo();
        });
      };
      if ( this.options.overlaySelector ) {
        $(document).on('click', this.options.overlaySelector, function (event) {
          self.hideOverlay();
          self.hideModal();
          self.onCloseNavigateTo();
        });
      };
      if ( this.options.escKey ) {
        $(document).on('keyup', function (event) {
          if ( event.which == 27 ) {
            self.hideOverlay();
            self.hideModal();
            self.onCloseNavigateTo();
          };
        });
      };
    };

    this.onCloseNavigateTo = function () {
      if ( this.options.onCloseNavTo && typeof( this.options.onCloseNavTo ) == 'string' ) {
        window.location = this.options.onCloseNavTo;
      };
    };

    this.bindModalOpen = function () {
      if ( this.options.forceShow || !this.element ) {
        this.getContent();
      } else {
        this.$element.on( this.options.event, function (event) {
          self.getContent();
        });
      };
    };

    this.getContent = function () {
      if ( this.options.remote.url && this.options.remote.url != '' ) {
        $.ajax({
          url : this.options.remote.url,
          type : this.options.remote.type,
          data : this.options.remote.data,
          success : function ( response ) {
            self.content = response;
            self.showModal();
          },
          error : function ( jqXHR, textStatus, errorThrown ) {
            ESO.app.handleAjaxError(jqXHR, textStatus, errorThrown);
          }
        });
      } else {
        this.content = this.options.content;
        this.showModal();
      };
    };

    this.bindPreventDefault = function () {
      if ( this.options.preventDefault ) {
        $(document).on('click', this.$element, function (event) {
          // event.preventDefault();
        });
      };
    };

    this.bindWindowResize = function () {
      $(window).on('resize', function (event) {
        self.positionModal();
      });
    };

    this.bindEvents = function () {
      this.bindModalOpen();
      this.bindPreventDefault();
      this.bindModalClose();
      this.bindWindowResize();
    };

    this.destroyModal = function () {
      // Destroy modal
    };

    this.onBeforeShow = function () {
      if (this.options.onBeforeShow && typeof(this.options.onBeforeShow) == 'function' ) {
        this.options.onBeforeShow();
      };
    };

    this.onAfterShow = function () {
      if (this.options.onAfterShow && typeof(this.options.onAfterShow) == 'function' ) {
        this.options.onAfterShow();
      };
    };

    this.onBeforeHide = function () {
      if (this.options.onBeforeHide && typeof(this.options.onBeforeHide) == 'function' ) {
        this.options.onBeforeHide();
      };
    };

    this.onAfterHide = function () {
      if (this.options.onAfterHide && typeof(this.options.onAfterHide) == 'function' ) {
        this.options.onAfterHide();
      };
    };

    this.checkValidBindEvents = function () {
      if ( $.isArray( this.options.event ) ) {
        var validEvents = [];
        for ( var e in this.options.event ) {
          if ( $.inArray( e, self.allowedEvents ) > -1 ) {
            validEvents.push(e);
          };
        };
        this.options.event = validEvents.join(' ');
        this.bindEvents();
      } else if ( $.inArray( this.options.event, this.allowedEvents ) > -1 ) {
        this.bindEvents();
      };
    };

    this.exec = function () {
      this.checkValidBindEvents();
    };

    this.exec();

  };

  /*
   * Plugin wrapper
   */

$.sleepyModal = $.fn[pluginName] = function (options) {

    // If using the $.sleepyModal() format (i.e., sans-selector)...
    if ( !this.selector ) {

      return new SleepyModal( false, options );

    // Otherwise, if a selector is provided...
    } else {

      // For every matched selector found...
      return this.each( function () {

        // Set some jQuery data if it doesn't already exist
        if ( !$.data( this, 'plugin_' + pluginName ) || options.forceShow ) {
          $.data( this, 'plugin_' + pluginName, new SleepyModal( this, options ) );
        };

      });

    };

  };

})(jQuery, window, document);
<commit_msg>Remove ESO references<commit_after>/**
 * Sleepy Modal
 *
 * Highly customizable modals
 *
 */

;(function ($, window, document) {

  var

    // Set some defaults
    defaults = {
      escKey : true,
      forceShow : false,
      preventDefault : true,
      showOverlay : true,
      overlaySelector : '#overlay',
      modalSelector : '#modal',
      modalContentSelector : '#modal-content',
      closeSelector : '.close-modal',
      transitionIn : {
        effect : 'fadeIn', // fadeIn, ...
        duration : 'fast' // fast, slow, int, ...
      },
      transitionOut : {
        effect : 'fadeOut', // fadeOut, ...
        duration : 'fast' // fast, slow, int, ...
      },
      height : 'auto',
      width : 'auto',
      remote : {
        url : false,
        type : 'get',
        data : {}
      },
      event : 'click',
      xPos : 'center', // left, center, right, int, ...
      yPos : 'center', // top, center, bottom, int, ...
      content : false,
      onCloseNavTo : false,
      onBeforeShow : false,
      onAfterShow : false,
      onBeforeHide : false,
      onAfterHide : false
    },

    // Set the name of the plugin
    pluginName = 'sleepyModal';

  /**
   * Constructor
   */

  function SleepyModal (element, options) {

    if ( element ) {

      // Set the current DOM node being acted upon
      this.element = element;

      // Set the current jQuery object being acted upon
      this.$element = $(element);

      // Set the current DOM node tag name being acted upon (e.g. "select" or "a")
      if ( this.$element.prop('tagName') && typeof( this.$element.prop('tagName') ) == 'string' ) {
        this.htmlTag = this.$element.prop('tagName').toLowerCase();
      };

    };

    // Set allowed events
    this.allowedEvents = [
      'keydown', 'keypress', 'keyup',
      'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'hover', 'click', 'dblclick',
      'focus', 'blur', 'focusin', 'focusout', 'change', 'select'
    ];

    // Set allowed transitions in
    this.allowedTransitionIn = []

    // Set allowed transitions out
    this.allowedTransitionOut = []

    // Merge the options into the defaults
    this.options = $.extend( true, {}, defaults, options );

    // Set a reference to the original, un-merged defaults
    this._defaults = defaults;

    // Set a reference to the name of the plugin
    this._name = pluginName;

    // If no "modalContentSelector" option is given
    // (since it's optional), use the "modalSelector"
    // instead (since it's required)
    this.options.modalContentSelector = (this.options.modalContentSelector && this.options.modalContentSelector != '') ? this.options.modalContentSelector : this.options.modalSelector;

    // Away we go!
    this.init();

  };

  /**
   * Public methods
   */

  SleepyModal.prototype.init = function () {
    var self = this;

    this.showOverlay = function () {
      if ( !$(this.options.overlaySelector).is(':visible') ) {
        if ( this.options.overlaySelector ) {
          if ( this.options.transitionIn ) {
            switch ( this.options.transitionIn.effect ) {
              case 'fadeIn':
                $(this.options.overlaySelector).fadeIn( this.options.transitionIn.duration );
                break;
              default:
                $(this.options.overlaySelector).show();
            };
          };
        };
      };
    };

    this.focusFirstFormField = function () {
      $firstFormField = $(this.options.modalContentSelector + ' input[type=submit],' + this.options.modalContentSelector + ' input[type=password],' + this.options.modalContentSelector + ' input[type=email],' + this.options.modalContentSelector + ' input[type=text],' + this.options.modalContentSelector + ' select,' + this.options.modalContentSelector + ' textarea').not('.no-auto-focus').first();
      if ( $firstFormField.parent().hasClass('custom-select') || $firstFormField.parent().hasClass('custom-checkbox') ) {
        $firstFormField.parent('.custom-select, .custom-checkbox').addClass('focus');
      };
      $firstFormField.focus();
    },

    this.hideOverlay = function () {
      if ( this.options.overlaySelector ) {
        if ( this.options.transitionOut ) {
          switch ( this.options.transitionOut.effect ) {
            case 'fadeOut':
              $(this.options.overlaySelector).fadeOut( this.options.transitionOut.duration );
              break;
            default:
              $(this.options.overlaySelector).hide();
          };
        };
      };
    };

    this.showModal = function () {
      this.showOverlay();
      this.onBeforeShow();
      if ( !$(this.options.modalSelector).is(':visible') ) {
        if ( this.options.transitionIn ) {
          switch ( this.options.transitionIn.effect ) {
            case 'fadeIn':
              this.injectContent();
              this.sizeModal();
              this.positionModal();
              $(this.options.modalSelector).fadeIn( this.options.transitionIn.duration, function () {
                self.focusFirstFormField();
                self.onAfterShow();
              });
              break;
            default:
              $(this.options.modalSelector).show( function () {
                self.injectContent();
                self.sizeModal();
                self.positionModal();
                self.focusFirstFormField();
                self.onAfterShow();
              });
          };
        };
      } else {
        this.hideModal( true );
      };
    };

    this.hideModal = function (showAfterHide) {
      this.onBeforeHide();
      if ( this.options.transitionOut ) {
        switch ( this.options.transitionOut.effect ) {
          case 'fadeOut':
            $(this.options.modalSelector).fadeOut( this.options.transitionOut.duration, function () {
              self.removeContent();
              if (showAfterHide) {
                self.showModal();
              };
            });
            break;
          default:
            $(this.options.modalSelector).hide( function () {
              self.removeContent();
              if (showAfterHide) {
                self.showModal();
              };
            });
        };
      };
      this.onAfterHide();
    };

    this.injectContent = function () {
      $(this.options.modalContentSelector).html( this.content );
    };

    this.removeContent = function () {
      $(self.options.modalContentSelector).empty();
    };

    this.positionModal = function () {
      // Horizontal position
      switch ( this.options.xPos ) {
        case 'left':
          $(this.options.modalSelector).css({
            left : 0
          });
          break;
        case 'center':
          $(this.options.modalSelector).css({
            left : ( $(window).width() - $(this.options.modalSelector).outerWidth() ) / 2
          });
          break;
        case 'right':
          $(this.options.modalSelector).css({
            right : 0
          });
          break;
        default:
          $(this.options.modalSelector).css({
            left : ( $(window).width() - $(this.options.modalSelector).outerWidth() ) / 2
          });
      };
      // Vertical position
      switch ( this.options.yPos ) {
        case 'top':
          $(this.options.modalSelector).css({
            top : 0
          });
          break;
        case 'center':
          $(this.options.modalSelector).css({
            top : ( $(window).height() - $(this.options.modalSelector).outerHeight() ) / 2
          });
          break;
        case 'bottom':
          $(this.options.modalSelector).css({
            bottom : 0
          });
          break;
        default:
          $(this.options.modalSelector).css({
            top : ( $(window).height() - $(this.options.modalSelector).outerHeight() ) / 2
          });
      };
    };

    this.sizeModal = function () {
      $(this.options.modalSelector).css({
        height : this.options.height,
        width : this.options.width,
      });
    };

    this.bindModalClose = function () {
      if ( this.options.closeSelector ) {
        $(document).on('click', this.options.closeSelector, function (event) {
          self.hideOverlay();
          self.hideModal();
          self.onCloseNavigateTo();
        });
      };
      if ( this.options.overlaySelector ) {
        $(document).on('click', this.options.overlaySelector, function (event) {
          self.hideOverlay();
          self.hideModal();
          self.onCloseNavigateTo();
        });
      };
      if ( this.options.escKey ) {
        $(document).on('keyup', function (event) {
          if ( event.which == 27 ) {
            self.hideOverlay();
            self.hideModal();
            self.onCloseNavigateTo();
          };
        });
      };
    };

    this.onCloseNavigateTo = function () {
      if ( this.options.onCloseNavTo && typeof( this.options.onCloseNavTo ) == 'string' ) {
        window.location = this.options.onCloseNavTo;
      };
    };

    this.bindModalOpen = function () {
      if ( this.options.forceShow || !this.element ) {
        this.getContent();
      } else {
        this.$element.on( this.options.event, function (event) {
          self.getContent();
        });
      };
    };

    this.getContent = function () {
      if ( this.options.remote.url && this.options.remote.url != '' ) {
        $.ajax({
          url : this.options.remote.url,
          type : this.options.remote.type,
          data : this.options.remote.data,
          success : function ( response ) {
            self.content = response;
            self.showModal();
          },
          error : function ( jqXHR, textStatus, errorThrown ) {
            // TODO
          }
        });
      } else {
        this.content = this.options.content;
        this.showModal();
      };
    };

    this.bindPreventDefault = function () {
      if ( this.options.preventDefault ) {
        $(document).on('click', this.$element, function (event) {
          // event.preventDefault();
        });
      };
    };

    this.bindWindowResize = function () {
      $(window).on('resize', function (event) {
        self.positionModal();
      });
    };

    this.bindEvents = function () {
      this.bindModalOpen();
      this.bindPreventDefault();
      this.bindModalClose();
      this.bindWindowResize();
    };

    this.destroyModal = function () {
      // Destroy modal
    };

    this.onBeforeShow = function () {
      if (this.options.onBeforeShow && typeof(this.options.onBeforeShow) == 'function' ) {
        this.options.onBeforeShow();
      };
    };

    this.onAfterShow = function () {
      if (this.options.onAfterShow && typeof(this.options.onAfterShow) == 'function' ) {
        this.options.onAfterShow();
      };
    };

    this.onBeforeHide = function () {
      if (this.options.onBeforeHide && typeof(this.options.onBeforeHide) == 'function' ) {
        this.options.onBeforeHide();
      };
    };

    this.onAfterHide = function () {
      if (this.options.onAfterHide && typeof(this.options.onAfterHide) == 'function' ) {
        this.options.onAfterHide();
      };
    };

    this.checkValidBindEvents = function () {
      if ( $.isArray( this.options.event ) ) {
        var validEvents = [];
        for ( var e in this.options.event ) {
          if ( $.inArray( e, self.allowedEvents ) > -1 ) {
            validEvents.push(e);
          };
        };
        this.options.event = validEvents.join(' ');
        this.bindEvents();
      } else if ( $.inArray( this.options.event, this.allowedEvents ) > -1 ) {
        this.bindEvents();
      };
    };

    this.exec = function () {
      this.checkValidBindEvents();
    };

    this.exec();

  };

  /*
   * Plugin wrapper
   */

$.sleepyModal = $.fn[pluginName] = function (options) {

    // If using the $.sleepyModal() format (i.e., sans-selector)...
    if ( !this.selector ) {

      return new SleepyModal( false, options );

    // Otherwise, if a selector is provided...
    } else {

      // For every matched selector found...
      return this.each( function () {

        // Set some jQuery data if it doesn't already exist
        if ( !$.data( this, 'plugin_' + pluginName ) || options.forceShow ) {
          $.data( this, 'plugin_' + pluginName, new SleepyModal( this, options ) );
        };

      });

    };

  };

})(jQuery, window, document);
<|endoftext|>


<commit_before><commit_msg>Lint compliance<commit_after><|endoftext|>


<commit_before>// Copyright (c) Jupyter-Contrib Team.
// Distributed under the terms of the Modified BSD License.

define(function(require, exports, module) {
    'use strict';

    var Jupyter = require('base/js/namespace');
    var keyboard = require('base/js/keyboard');
    var utils = require('base/js/utils');
    var configmod = require('services/config');
    var Cell = require('notebook/js/cell').Cell;
    var CodeCell = require('notebook/js/codecell').CodeCell;

    var add_edit_shortcuts = {};
    var replace_in_cell = false; //bool to enable/disable replacements
    var exec_code_verbose = true;
    var kName; // name of current kernel
    var kernelLanguage; // language associated with kernel

    var cfg = {
        code_format_hotkey: 'Ctrl-L',
    }

    // list of availables kernels
    var userKernels;

    var kMap = { // map of parameters for supported kernels
        python: {
            library: 'from yapf.yapflib.yapf_api import FormatCode',
            exec: yapf_format,
            post_exec: ''
        },
        r: { // intentionally in lower case
            library: 'library(formatR)',
            exec: autoR_format,
            post_exec: ''
        },
        javascript: {
            library: String('var beautify' + ' = require' + '("js-beautify").js_beautify'),
            exec: js_beautify,
            post_exec: ''
        },
    }

    function initialize() {
        // create config object to load parameters
        var base_url = utils.get_body_data("baseUrl");
        var config = new configmod.ConfigSection('notebook', { base_url: base_url });
        config.load();
        config.loaded.then(function config_loaded_callback() {
            for (var key in cfg) {
                if (config.data.hasOwnProperty(key)) {
                    cfg[key] = config.data[key];
                }
            }
            code_format_hotkey(); //initialize hotkey
        })
    }

    function code_exec_callback(msg) {

        if (msg.msg_type == "error") {
            if (exec_code_verbose) alert("CODE prettify extension\n Error: " + msg.content.ename + "\n" + msg.content.evalue)
            return
        }
        if (replace_in_cell) {
            if (kernelLanguage == "python") {
                var ret = msg.content.data['text/plain'];
                //console.log("RETURNED code", ret)
                var quote = String(ret[ret.length - 1])
                var reg = RegExp(quote + '[\\S\\s]*' + quote)
                var ret = String(ret).match(reg)[0] // extract text between quotes
                ret = ret.substr(1, ret.length - 2) //suppress quotes
                ret = ret.replace(/([^\\])\\n/g, "$1\n").replace(/([^\\])\\n/g, "$1\n")
                        // replace \n if not escaped (two times beacause of recovering subsequences)
                .replace(/([^\\])\\\\\\n/g, "$1\\\n") // [continuation line] replace \ at eol (but no conversion)
                    .replace(/\\'/g, "'") // replace simple quotes
                    .replace(/\\\\/g, "\\") // unescape
            }

            if (kernelLanguage == "r") {
                var ret = msg.content['text'];
                var ret = String(ret).replace(/\\"/gm, "'").replace(/\\n/gm, '\n').replace(/\$\!\$/gm, "\\n")
            }
            if (kernelLanguage == "javascript") {
                var ret = msg.content.data['text/plain'];
                var ret = String(ret).substr(1, ret.length - 1)
                    .replace(/\\'/gm, "'").replace(/\\n/gm, '\n').replace(/\$\!\$/gm, "\\n")
            }
            //yapf/formatR - cell (file) ends with a blank line. Here, still remove the last blank line
            var ret = ret.substr(0, ret.length - 1) //last blank line/quote char for javascript kernel
            var selected_cell = Jupyter.notebook.get_selected_cell();
            selected_cell.set_text(String(ret));
        }
    }

    function exec_code(code_input) {
        Jupyter.notebook.kernel.execute(code_input, { iopub: { output: code_exec_callback } }, { silent: false });
    }

    function js_beautify() {
        var selected_cell = Jupyter.notebook.get_selected_cell();
        if (selected_cell instanceof CodeCell) {
            var text = selected_cell.get_text().replace(/\\n/gm, "$!$")
                .replace(/\n/gm, "\\n")
                .replace(/\'/gm, "\\'")
            var code_input = "beautify(text='" + text + "')"
            exec_code(code_input)
        }
    }

    function autoR_format() {
        var selected_cell = Jupyter.notebook.get_selected_cell();
        if (selected_cell instanceof CodeCell) {
            var text = selected_cell.get_text().replace(/\\n/gm, "$!$")
                .replace(/\'/gm, "\\'").replace(/\\"/gm, "\\'")
            var code_input = "tidy_source(text='" + text + "')"
            exec_code(code_input)
        }
    }

    function yapf_format(index) {
        //var selected_cell = Jupyter.notebook.get_selected_cell();
        index = index;
        Jupyter.notebook.select(index);
        var selected_cell = Jupyter.notebook.get_selected_cell();
        if (selected_cell instanceof CodeCell) {
            var text = selected_cell.get_text()
                .replace(/\\n/gm, "$!$") // Replace escaped \n by $!$
                .replace(/\"/gm, '\\"'); // Escape double quote
            var text = selected_cell.get_text()
            text = JSON.stringify(text)
                .replace(/([^\\])\\\\\\n/g, "$1") // [continuation line] replace \ at eol (but result will be on a single line)
            var code_input = 'FormatCode(' + text + ')[0]'
            //console.log("INPUT",code_input)
            exec_code(code_input, index)
        }
    }

    function autoFormat() {
        replace_in_cell = true;
        kMap[kernelLanguage].exec()
    }

    function code_format_button() {
        if ($('#code_format_button').length == 0) {
            Jupyter.toolbar.add_buttons_group([{
                'label': 'Code formatting',
                'icon': 'fa-legal',
                'callback': autoFormat,
                'id': 'code_format_button'
            }]);
        }
    }

    function code_format_hotkey() {
        add_edit_shortcuts[cfg['code_format_hotkey']] = {
            help: "code formatting",
            help_index: 'yf',
            handler: autoFormat
        };
    }

    function getKernelInfos() {
        //console.log("--->kernel_ready.Kernel")
        kName = Jupyter.notebook.kernel.name;
        kernelLanguage = Jupyter.notebook.metadata.kernelspec.language.toLowerCase()
        var knownKernel = kMap[kernelLanguage]
        if (!knownKernel) {
            $('#code_format_button').remove()
            alert("Sorry; code prettify nbextension only works with a Python, R or javascript kernel");

        } else {
            code_format_button();
            Jupyter.keyboard_manager.edit_shortcuts.add_shortcuts(add_edit_shortcuts);
            replace_in_cell = false;
            exec_code(kMap[kernelLanguage].library)
        }
    }

    function load_notebook_extension() {

        initialize();

        if (typeof Jupyter.notebook.kernel !== "undefined" && Jupyter.notebook.kernel != null) {
            getKernelInfos();
        }

        // only if kernel_ready (but kernel may be loaded before)
        $([Jupyter.events]).on("kernel_ready.Kernel", function() {
            console.log("code_prettify: restarting")
            getKernelInfos();
        });
    }

    return {
        load_ipython_extension: load_notebook_extension
    };
});
<commit_msg>Update code_prettify to address #767<commit_after>// Copyright (c) Jupyter-Contrib Team.
// Distributed under the terms of the Modified BSD License.

define(function(require, exports, module) {
    'use strict';

    var Jupyter = require('base/js/namespace');
    var keyboard = require('base/js/keyboard');
    var utils = require('base/js/utils');
    var configmod = require('services/config');
    var Cell = require('notebook/js/cell').Cell;
    var CodeCell = require('notebook/js/codecell').CodeCell;

    var add_edit_shortcuts = {};
    var replace_in_cell = false; //bool to enable/disable replacements
    var exec_code_verbose = true;
    var kName; // name of current kernel
    var kernelLanguage; // language associated with kernel

    var cfg = {
        code_format_hotkey: 'Ctrl-L',
    }

    // list of availables kernels
    var userKernels;

    var kMap = { // map of parameters for supported kernels
        python: {
            library: 'from yapf.yapflib.yapf_api import FormatCode',
            exec: yapf_format,
            post_exec: ''
        },
        r: { // intentionally in lower case
            library: 'library(formatR)',
            exec: autoR_format,
            post_exec: ''
        },
        javascript: {
            library: String('var beautify' + ' = require' + '("js-beautify").js_beautify'),
            exec: js_beautify,
            post_exec: ''
        },
    }

    function initialize() {
        // create config object to load parameters
        var base_url = utils.get_body_data("baseUrl");
        var config = new configmod.ConfigSection('notebook', { base_url: base_url });
        config.load();
        config.loaded.then(function config_loaded_callback() {
            for (var key in cfg) {
                if (config.data.hasOwnProperty(key)) {
                    cfg[key] = config.data[key];
                }
            }
            code_format_hotkey(); //initialize hotkey
        })
    }

    function code_exec_callback(msg) {

        if (msg.msg_type == "error") {
            if (exec_code_verbose) alert("CODE prettify extension\n Error: " + msg.content.ename + "\n" + msg.content.evalue)
            return
        }
        if (replace_in_cell) {
            if (kernelLanguage == "python") {
                var ret = msg.content.data['text/plain'];
                //console.log("RETURNED code", ret)
                var quote = String(ret[ret.length - 1])
                var reg = RegExp(quote + '[\\S\\s]*' + quote)
                var ret = String(ret).match(reg)[0] // extract text between quotes
                ret = ret.substr(1, ret.length - 2) //suppress quotes
                ret = ret.replace(/([^\\])\\n/g, "$1\n").replace(/([^\\])\\n/g, "$1\n")
                        // replace \n if not escaped (two times beacause of recovering subsequences)
                .replace(/([^\\])\\\\\\n/g, "$1\\\n") // [continuation line] replace \ at eol (but no conversion)
                    .replace(/\\'/g, "'") // replace simple quotes
                    .replace(/\\\\/g, "\\") // unescape
            }

            if (kernelLanguage == "r") {
                var ret = msg.content['text'];
                var ret = String(ret).replace(/\\"/gm, "'").replace(/\\n/gm, '\n').replace(/\$\!\$/gm, "\\n")
            }
            if (kernelLanguage == "javascript") {
                var ret = msg.content.data['text/plain'];
                var ret = String(ret).substr(1, ret.length - 1)
                    .replace(/\\'/gm, "'").replace(/\\n/gm, '\n').replace(/\$\!\$/gm, "\\n")
            }
            //yapf/formatR - cell (file) ends with a blank line. Here, still remove the last blank line
            var ret = ret.substr(0, ret.length - 1) //last blank line/quote char for javascript kernel
            var selected_cell = Jupyter.notebook.get_selected_cell();
            selected_cell.set_text(String(ret));
        }
    }

    function exec_code(code_input) {
        Jupyter.notebook.kernel.execute(code_input, { iopub: { output: code_exec_callback } }, { silent: false });
    }

    function js_beautify() {
        var selected_cell = Jupyter.notebook.get_selected_cell();
        if (selected_cell instanceof CodeCell) {
            var text = selected_cell.get_text().replace(/\\n/gm, "$!$")
                .replace(/\n/gm, "\\n")
                .replace(/\'/gm, "\\'")
            var code_input = "beautify(text='" + text + "')"
            exec_code(code_input)
        }
    }

    function autoR_format() {
        var selected_cell = Jupyter.notebook.get_selected_cell();
        if (selected_cell instanceof CodeCell) {
            var text = selected_cell.get_text().replace(/\\n/gm, "$!$")
                .replace(/\'/gm, "\\'").replace(/\\"/gm, "\\'")
            var code_input = "tidy_source(text='" + text + "')"
            exec_code(code_input)
        }
    }

    function yapf_format() {
        var selected_cell = Jupyter.notebook.get_selected_cell();
        if (selected_cell instanceof CodeCell) {
            var text = selected_cell.get_text()
                .replace(/\\n/gm, "$!$") // Replace escaped \n by $!$
                .replace(/\"/gm, '\\"'); // Escape double quote
            var text = selected_cell.get_text()
            text = JSON.stringify(text)
                .replace(/([^\\])\\\\\\n/g, "$1") // [continuation line] replace \ at eol (but result will be on a single line)
            var code_input = 'FormatCode(' + text + ')[0]'
            //console.log("INPUT",code_input)
            exec_code(code_input)
        }
    }

    function autoFormat() {
        replace_in_cell = true;
        kMap[kernelLanguage].exec()
    }

    function code_format_button() {
        if ($('#code_format_button').length == 0) {
            Jupyter.toolbar.add_buttons_group([{
                'label': 'Code formatting',
                'icon': 'fa-legal',
                'callback': autoFormat,
                'id': 'code_format_button'
            }]);
        }
    }

    function code_format_hotkey() {
        add_edit_shortcuts[cfg['code_format_hotkey']] = {
            help: "code formatting",
            help_index: 'yf',
            handler: autoFormat
        };
    }

    function getKernelInfos() {
        //console.log("--->kernel_ready.Kernel")
        kName = Jupyter.notebook.kernel.name;
        kernelLanguage = Jupyter.notebook.metadata.kernelspec.language.toLowerCase()
        var knownKernel = kMap[kernelLanguage]
        if (!knownKernel) {
            $('#code_format_button').remove()
            alert("Sorry; code prettify nbextension only works with a Python, R or javascript kernel");

        } else {
            code_format_button();
            Jupyter.keyboard_manager.edit_shortcuts.add_shortcuts(add_edit_shortcuts);
            replace_in_cell = false;
            exec_code(kMap[kernelLanguage].library)
        }
    }

    function load_notebook_extension() {

        initialize();

        if (typeof Jupyter.notebook.kernel !== "undefined" && Jupyter.notebook.kernel != null) {
            getKernelInfos();
        }

        // only if kernel_ready (but kernel may be loaded before)
        $([Jupyter.events]).on("kernel_ready.Kernel", function() {
            console.log("code_prettify: restarting")
            getKernelInfos();
        });
    }

    return {
        load_ipython_extension: load_notebook_extension
    };
});
<|endoftext|>


<commit_before>// Roughly based on http://jqueryui.com/demos/autocomplete/#combobox
(function( $ ) {
  $.widget( "ui.chooser", {
    options: {
      choiceClass: 'ui-widget ui-widget-content ui-corner-left inlineblock ui-chooser-choice',
      inputClass:  'ui-widget ui-widget-content ui-corner-left inlineblock ui-chooser-input',
      buttonClass: 'ui-corner-right ui-chooser-button ui-button-icon inlineblock',
      queryParam: 'term'
    },
    _create: function() {
      var self = this,
          source = this.options.source,
          collectionUrl = this.options.collectionUrl,
          cache = {},
          defaultSources = this.options.defaultSources || $.parseJSON($(this.element).attr('data-chooser-default-sources') || null)
      if (!collectionUrl && typeof(this.options.source) == 'string') {
        collectionUrl = this.options.collectionUrl = this.options.source
      }
      this.defaultSources = defaultSources = this.recordsToItems(defaultSources)
      this.options.chosen = this.options.chosen || $.parseJSON($(this.element).attr('data-chooser-chosen') || null)
      this.options.source = this.options.source || defaultSources
      var markup = this.setupMarkup()
      this.selectDefault()
      if (!this.options.collectionUrl && this.options.source.length == 0 || typeof(this.options.source[0]) == 'string') {
        var that = this
        $(this.markup.input).blur(function() {
          if ($(that.markup.input).is(':visible')) {
            that.selectItem($(that.markup.input).val())
          }
        })
      }
      markup.input.autocomplete({
        html: true,
        minLength: 0,
        select: function(ui, event) {
          if (event.item.forceRemote) {
            cache[request.term] = null
            self.options.source = collectionUrl
            $(ui.target).autocomplete('search', ui.target.value)
          } else if (event.item.clear) {
            $(self).data('previous', null)
            self.clear()
          } else {
            self.selectItem(event.item)
          }
          return false
        },
        source: function(request, response) {
          var source = self.options.source
          if (request.term == '' && typeof(source) == 'string') {
            source = self.options.source = self.defaultSources
          }
          if (typeof(source) != 'string') {
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
            var selected = $.map(source, function(src) {
              if (src.forceRemote || matcher.test(src.label)) { return src }
            })
            if (selected.length != 0) {
              if (collectionUrl && request.term != '') {
                selected.push({label: ''+I18n.t('search_remote')+'', value: request.term, forceRemote: true})
              }
              selected.push({label: ''+I18n.t('clear')+'', value: request.term, clear: true})
              response(selected)
              return
            } else {
              response([])
            }
          }
          if (cache[request.term]) {
            response(cache[request.term])
            return
          }

          if (!collectionUrl) { return };

          markup.chooseButton.hide()
          markup.loadingButton.showInlineBlock()

          if (self.request) {
            self.request.abort()
          }
          self.request = $.getJSON(collectionUrl, self.options.queryParam+"="+request.term, function(json) {
            markup.chooseButton.showInlineBlock()
            markup.loadingButton.hide()
            json = self.recordsToItems(json)
            json.push({label: ''+I18n.t('clear')+'', value: request.term, clear: true})
            cache[request.term] = json
            response(json)
          })
        }
      })

      // bind button behaviors
      markup.clearButton.click(function() {
        self.clear()
      })

      markup.input.bind('autocompleteclose', function(e, ui) {
        if (!markup.input.is(':focus') && $(self).data('previous')) {
          self.selectItem($(self).data('previous'), {blurring: true})
        }
      })
      markup.input.bind('autocompleteopen', function(e, ui) {
        // lame hack aaround weird display bug
        if (!$(e.currentTarget).is(':visible')) {
          markup.input.autocomplete( "close" )
          return
        }
      })

      markup.chooseButton.click(function() {
        // close if already visible
        if (markup.input.autocomplete( "widget" ).is( ":visible" )) {
          markup.input.autocomplete( "close" )
          return
        }

        // work around a bug (likely same cause as #5265)
        $( this ).blur()

        $(self).data('previous', $(self).data('selected'))
        self.open()

        // pass empty string as value to search for, displaying all results
        markup.input.autocomplete( "search", "" )
        markup.input.focus()
      })

      // Bind ENTER in search field
      $(markup.input).keypress(function(e) {
        if (e.which == 13) {
          return false
        }
      })
    },

    selectDefault: function() {
      var self = this, markup = this.markup
      if (this.options.chosen) {
        var item = this.options.chosen
        if (typeof(item) != 'string') {
          item = self.recordsToItems([item])[0]
        }
        $(this).data('previous', item)
        this.selectItem(item)
      } else if ($(this.element).val() != '' && this.options.resourceUrl) {
        this.selectId($(this.element).val())
      }
    },

    selectId: function(id) {
      var self = this, markup = this.markup
      markup.chooseButton.hide()
      markup.loadingButton.showInlineBlock()
      var resourceUrl = this.options.resourceUrl.replace(/\{\{id\}\}/, id)
      $.getJSON(resourceUrl, function(json) {
        var item = self.recordsToItems([json])[0]
        markup.loadingButton.hide()
        self.selectItem(item)
      })
    },

    recordsToItems: function(records) {
      var items = [], records = records || []
      for (var i=0; i < records.length; i++) {
        if (!records[i]) { continue }
        items.push(
          $.extend(records[i], {
            label: records[i].label || records[i].html || records[i].title || records[i].name,
            value: records[i].value || records[i].title || records[i].name || records[i].id,
            recordId: records[i].id
          })
        )
      }
      return items
    },

    selectItem: function(item, options) {
      options = options || this.options || {}
      if (!item) {
        this.clear()
      } else {
        if (typeof(item) == 'object') {
          if (!item.label) {
            item = this.recordsToItems([item])[0]
          }
          var itemLabel = item.label || item.html,
              itemValue = item.recordId || item.value || item.id
        } else {
          var itemLabel = item,
              itemValue = item
        }
        $(this).data('selected', item)
        $(this.markup.input).hide()
        $(this.markup.choice).html(itemLabel).showInlineBlock().width(this.markup.input.width())
        $(this.markup.chooseButton).showInlineBlock()
        $(this.markup.clearButton)
          .height(this.markup.choice.outerHeight()-2)
        $(this.markup.chooseButton)
          .height(this.markup.choice.outerHeight()-2)
        $('.ui-icon', this.markup.clearButton)
          .css('margin-top', '-' + Math.round((this.markup.choice.outerHeight() / 2) - 6) + 'px')
        $('.ui-icon', this.markup.chooseButton)
          .css('margin-top', '-' + Math.round((this.markup.choice.outerHeight() / 2) - 6) + 'px')
        $(this.markup.originalInput).val(itemValue).change()
      }
      var changed = true
      if (($(this).data('previous') && $(this).data('previous').id === item.id) || (!$(this).data('previous') && !item)) {
        changed = false
      }
      if (!options.blurring && typeof(this.options.afterSelect) == 'function' && changed) {
        this.options.afterSelect.apply(this, [item])
      }
      $(this).data('previous', null)
    },

    open: function(opts) {
      var options = this.options || {},
          opts = opts || {},
          bubble = opts.bubble == false ? false : true
      $(this).data('selected', null)
      $(this.markup.originalInput).val('')
      if (!$(this).data('previous') && bubble) {
        $(this.markup.originalInput).change()
      }
      $(this.markup.input).val('').showInlineBlock()
      $(this.markup.choice).html('').hide()

      $(this.markup.chooseButton).height(this.markup.input.outerHeight())
      $('.ui-icon', this.markup.chooseButton)
        .css('margin-top', '-' + Math.round((this.markup.input.outerHeight() / 2) - 6) + 'px')
    },

    clear: function(clearOpts) {
      var options = this.options || {}
      this.open(clearOpts)
      if (!options.blurring && typeof(this.options.afterClear) == 'function') {
        this.options.afterClear.apply(this)
      }
    },

    setupMarkup: function() {
      var originalInput = this.element.hide()
      this.markup = {
        originalInput: originalInput,
        wrapper: $('

').attr('id', originalInput.attr('id') + '_chooser'),
        input: $('<input type="text"/>')
          .addClass(this.options.inputClass)
          .attr('placeholder', originalInput.attr('placeholder'))
          .blur( function( ) {
            $(this).val( "" );
          }),
        choice: $('

')
          .addClass(this.options.choiceClass)
          .hide(),
        chooseButton: $('<button type="button" class="choosebutton"> </button>')
          .button({
            icons: {
              primary: "ui-icon-triangle-1-s"
            },
            text: false
          })
          .removeClass( "ui-corner-all" )
          .addClass(this.options.buttonClass),
        clearButton: $('<button type="button"> </button>')
          .button({
            icons: {
              primary: "ui-icon-cancel"
            },
            text: false
          })
          .removeClass( "ui-corner-all" )
          .addClass(this.options.buttonClass)
          .hide(),
        loadingButton: $('<button type="button" disabled="disabled"> </button>')
          .button({
            text: false,
            disabled: true
          })
          .removeClass( "ui-corner-all" )
          .addClass(this.options.buttonClass + ' ui-icon-loading')
          .hide()
      }
      $(this.markup.originalInput).wrap(this.markup.wrapper)
      this.markup.originalInput.after(
        this.markup.input,
        this.markup.choice,
        this.markup.chooseButton,
        this.markup.loadingButton,
        this.markup.clearButton)
      this.markup.input.width(originalInput.outerWidth() - this.markup.chooseButton.width() - 20)
      this.markup.choice.width(originalInput.outerWidth())
      return this.markup
    },
    destroy: function() {
      this.markup.input.remove()
      this.markup.choice.remove()
      this.markup.chooseButton.remove()
      this.markup.loadingButton.remove()
      this.markup.clearButton.remove()

      this.element.show();
      $.Widget.prototype.destroy.call( this );
    },

    getOptions: function() {
      return this.options
    },

    getSources: function() {
      return this.options.source
    },

    getItemById: function(id) {
      for (var i = this.options.source.length - 1; i >= 0; i--){
        if (this.options.source[i].id == id) { return this.options.source[i] }
      }
      return null
    },

    selected: function() {
      var selected = $(this).data('selected')
      return typeof(selected) == 'undefined' ? null : selected
    }
  })
})( jQuery )
<commit_msg>Attempt to fix chooser issue, part deux.<commit_after>// Roughly based on http://jqueryui.com/demos/autocomplete/#combobox
(function( $ ) {
  $.widget( "ui.chooser", {
    options: {
      choiceClass: 'ui-widget ui-widget-content ui-corner-left inlineblock ui-chooser-choice',
      inputClass:  'ui-widget ui-widget-content ui-corner-left inlineblock ui-chooser-input',
      buttonClass: 'ui-corner-right ui-chooser-button ui-button-icon inlineblock',
      queryParam: 'term'
    },
    _create: function() {
      var self = this,
          source = this.options.source,
          collectionUrl = this.options.collectionUrl,
          cache = {},
          defaultSources = this.options.defaultSources || $.parseJSON($(this.element).attr('data-chooser-default-sources') || null)
      if (!collectionUrl && typeof(this.options.source) == 'string') {
        collectionUrl = this.options.collectionUrl = this.options.source
      }
      this.defaultSources = defaultSources = this.recordsToItems(defaultSources)
      this.options.chosen = this.options.chosen || $.parseJSON($(this.element).attr('data-chooser-chosen') || null)
      this.options.source = this.options.source || defaultSources
      var markup = this.setupMarkup()
      this.selectDefault()
      if (!this.options.collectionUrl && this.options.source.length == 0 || typeof(this.options.source[0]) == 'string') {
        var that = this
        $(this.markup.input).blur(function() {
          if ($(that.markup.input).is(':visible')) {
            that.selectItem($(that.markup.input).val())
          }
        })
      }
      markup.input.autocomplete({
        html: true,
        minLength: 0,
        select: function(ui, event) {
          if (event.item.forceRemote) {
            cache = {}
            self.options.source = collectionUrl
            $(ui.target).autocomplete('search', ui.target.value)
          } else if (event.item.clear) {
            $(self).data('previous', null)
            self.clear()
          } else {
            self.selectItem(event.item)
          }
          return false
        },
        source: function(request, response) {
          var source = self.options.source
          if (request.term == '' && typeof(source) == 'string') {
            source = self.options.source = self.defaultSources
          }
          if (typeof(source) != 'string') {
            var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
            var selected = $.map(source, function(src) {
              if (src.forceRemote || matcher.test(src.label)) { return src }
            })
            if (selected.length != 0) {
              if (collectionUrl && request.term != '') {
                selected.push({label: ''+I18n.t('search_remote')+'', value: request.term, forceRemote: true})
              }
              selected.push({label: ''+I18n.t('clear')+'', value: request.term, clear: true})
              response(selected)
              return
            } else {
              response([])
            }
          }
          if (cache[request.term]) {
            response(cache[request.term])
            return
          }

          if (!collectionUrl) { return };

          markup.chooseButton.hide()
          markup.loadingButton.showInlineBlock()

          if (self.request) {
            self.request.abort()
          }
          self.request = $.getJSON(collectionUrl, self.options.queryParam+"="+request.term, function(json) {
            markup.chooseButton.showInlineBlock()
            markup.loadingButton.hide()
            json = self.recordsToItems(json)
            json.push({label: ''+I18n.t('clear')+'', value: request.term, clear: true})
            cache[request.term] = json
            response(json)
          })
        }
      })

      // bind button behaviors
      markup.clearButton.click(function() {
        self.clear()
      })

      markup.input.bind('autocompleteclose', function(e, ui) {
        if (!markup.input.is(':focus') && $(self).data('previous')) {
          self.selectItem($(self).data('previous'), {blurring: true})
        }
      })
      markup.input.bind('autocompleteopen', function(e, ui) {
        // lame hack aaround weird display bug
        if (!$(e.currentTarget).is(':visible')) {
          markup.input.autocomplete( "close" )
          return
        }
      })

      markup.chooseButton.click(function() {
        // close if already visible
        if (markup.input.autocomplete( "widget" ).is( ":visible" )) {
          markup.input.autocomplete( "close" )
          return
        }

        // work around a bug (likely same cause as #5265)
        $( this ).blur()

        $(self).data('previous', $(self).data('selected'))
        self.open()

        // pass empty string as value to search for, displaying all results
        markup.input.autocomplete( "search", "" )
        markup.input.focus()
      })

      // Bind ENTER in search field
      $(markup.input).keypress(function(e) {
        if (e.which == 13) {
          return false
        }
      })
    },

    selectDefault: function() {
      var self = this, markup = this.markup
      if (this.options.chosen) {
        var item = this.options.chosen
        if (typeof(item) != 'string') {
          item = self.recordsToItems([item])[0]
        }
        $(this).data('previous', item)
        this.selectItem(item)
      } else if ($(this.element).val() != '' && this.options.resourceUrl) {
        this.selectId($(this.element).val())
      }
    },

    selectId: function(id) {
      var self = this, markup = this.markup
      markup.chooseButton.hide()
      markup.loadingButton.showInlineBlock()
      var resourceUrl = this.options.resourceUrl.replace(/\{\{id\}\}/, id)
      $.getJSON(resourceUrl, function(json) {
        var item = self.recordsToItems([json])[0]
        markup.loadingButton.hide()
        self.selectItem(item)
      })
    },

    recordsToItems: function(records) {
      var items = [], records = records || []
      for (var i=0; i < records.length; i++) {
        if (!records[i]) { continue }
        items.push(
          $.extend(records[i], {
            label: records[i].label || records[i].html || records[i].title || records[i].name,
            value: records[i].value || records[i].title || records[i].name || records[i].id,
            recordId: records[i].id
          })
        )
      }
      return items
    },

    selectItem: function(item, options) {
      options = options || this.options || {}
      if (!item) {
        this.clear()
      } else {
        if (typeof(item) == 'object') {
          if (!item.label) {
            item = this.recordsToItems([item])[0]
          }
          var itemLabel = item.label || item.html,
              itemValue = item.recordId || item.value || item.id
        } else {
          var itemLabel = item,
              itemValue = item
        }
        $(this).data('selected', item)
        $(this.markup.input).hide()
        $(this.markup.choice).html(itemLabel).showInlineBlock().width(this.markup.input.width())
        $(this.markup.chooseButton).showInlineBlock()
        $(this.markup.clearButton)
          .height(this.markup.choice.outerHeight()-2)
        $(this.markup.chooseButton)
          .height(this.markup.choice.outerHeight()-2)
        $('.ui-icon', this.markup.clearButton)
          .css('margin-top', '-' + Math.round((this.markup.choice.outerHeight() / 2) - 6) + 'px')
        $('.ui-icon', this.markup.chooseButton)
          .css('margin-top', '-' + Math.round((this.markup.choice.outerHeight() / 2) - 6) + 'px')
        $(this.markup.originalInput).val(itemValue).change()
      }
      var changed = true
      if (($(this).data('previous') && $(this).data('previous').id === item.id) || (!$(this).data('previous') && !item)) {
        changed = false
      }
      if (!options.blurring && typeof(this.options.afterSelect) == 'function' && changed) {
        this.options.afterSelect.apply(this, [item])
      }
      $(this).data('previous', null)
    },

    open: function(opts) {
      var options = this.options || {},
          opts = opts || {},
          bubble = opts.bubble == false ? false : true
      $(this).data('selected', null)
      $(this.markup.originalInput).val('')
      if (!$(this).data('previous') && bubble) {
        $(this.markup.originalInput).change()
      }
      $(this.markup.input).val('').showInlineBlock()
      $(this.markup.choice).html('').hide()

      $(this.markup.chooseButton).height(this.markup.input.outerHeight())
      $('.ui-icon', this.markup.chooseButton)
        .css('margin-top', '-' + Math.round((this.markup.input.outerHeight() / 2) - 6) + 'px')
    },

    clear: function(clearOpts) {
      var options = this.options || {}
      this.open(clearOpts)
      if (!options.blurring && typeof(this.options.afterClear) == 'function') {
        this.options.afterClear.apply(this)
      }
    },

    setupMarkup: function() {
      var originalInput = this.element.hide()
      this.markup = {
        originalInput: originalInput,
        wrapper: $('

').attr('id', originalInput.attr('id') + '_chooser'),
        input: $('<input type="text"/>')
          .addClass(this.options.inputClass)
          .attr('placeholder', originalInput.attr('placeholder'))
          .blur( function( ) {
            $(this).val( "" );
          }),
        choice: $('

')
          .addClass(this.options.choiceClass)
          .hide(),
        chooseButton: $('<button type="button" class="choosebutton"> </button>')
          .button({
            icons: {
              primary: "ui-icon-triangle-1-s"
            },
            text: false
          })
          .removeClass( "ui-corner-all" )
          .addClass(this.options.buttonClass),
        clearButton: $('<button type="button"> </button>')
          .button({
            icons: {
              primary: "ui-icon-cancel"
            },
            text: false
          })
          .removeClass( "ui-corner-all" )
          .addClass(this.options.buttonClass)
          .hide(),
        loadingButton: $('<button type="button" disabled="disabled"> </button>')
          .button({
            text: false,
            disabled: true
          })
          .removeClass( "ui-corner-all" )
          .addClass(this.options.buttonClass + ' ui-icon-loading')
          .hide()
      }
      $(this.markup.originalInput).wrap(this.markup.wrapper)
      this.markup.originalInput.after(
        this.markup.input,
        this.markup.choice,
        this.markup.chooseButton,
        this.markup.loadingButton,
        this.markup.clearButton)
      this.markup.input.width(originalInput.outerWidth() - this.markup.chooseButton.width() - 20)
      this.markup.choice.width(originalInput.outerWidth())
      return this.markup
    },
    destroy: function() {
      this.markup.input.remove()
      this.markup.choice.remove()
      this.markup.chooseButton.remove()
      this.markup.loadingButton.remove()
      this.markup.clearButton.remove()

      this.element.show();
      $.Widget.prototype.destroy.call( this );
    },

    getOptions: function() {
      return this.options
    },

    getSources: function() {
      return this.options.source
    },

    getItemById: function(id) {
      for (var i = this.options.source.length - 1; i >= 0; i--){
        if (this.options.source[i].id == id) { return this.options.source[i] }
      }
      return null
    },

    selected: function() {
      var selected = $(this).data('selected')
      return typeof(selected) == 'undefined' ? null : selected
    }
  })
})( jQuery )
<|endoftext|>


<commit_before>import Q from 'q';
import Request from './sessionSuperagent';

import StoreSingleton from '../redux/storeSingleton';

import { kGlobalConstants } from '../GlobalConstants';
import * as uploadActions from '../redux/actions/uploadActions';

const prepareFilesNewSub = (fileDict) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_files/')
        .attach('appropriations', fileDict.appropriations)
        .attach('program_activity', fileDict.program_activity)
        .attach('award_financial', fileDict.award_financial)
        .field('cgac_code', fileDict.cgac_code)
        .field('frec_code', fileDict.frec_code)
        .field('reporting_period_start_date', fileDict.reporting_period_start_date)
        .field('reporting_period_end_date', fileDict.reporting_period_end_date)
        .field('is_quarter', fileDict.is_quarter)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareFilesExistingSub = (fileDict) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_files/')
        .attach('appropriations', fileDict.appropriations)
        .attach('program_activity', fileDict.program_activity)
        .attach('award_financial', fileDict.award_financial)
        .field('existing_submission_id', fileDict.existing_submission_id)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareMetadata = (metadata, request) => {
    const tmpRequest = Object.assign({}, request);
    // add the metadata to the request
    tmpRequest.cgac_code = metadata.codeType === 'cgac_code' ? metadata.agency : null;
    tmpRequest.frec_code = metadata.codeType === 'frec_code' ? metadata.agency : null;
    tmpRequest.reporting_period_start_date = metadata.startDate;
    tmpRequest.reporting_period_end_date = metadata.endDate;
    tmpRequest.is_quarter = false;
    if (metadata.dateType === "quarter") {
        tmpRequest.is_quarter = true;
    }

    return tmpRequest;
};

export const submitFabs = (submissionId) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_detached_file/')
        .send(submissionId)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareFabsFile = (fileDict) => {
    const deferred = Q.defer();

    let fieldType = '';

    if (fileDict.hasOwnProperty('agency_code')) {
        fieldType = 'agency_code';
    }
    else if (fileDict.hasOwnProperty('existing_submission_id')) {
        fieldType = 'existing_submission_id';
    }

    Request.post(kGlobalConstants.API + 'upload_detached_file/')
        .attach('fabs', fileDict.fabs)
        .field(fieldType, fileDict[fieldType])
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

export const performRemoteUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    let request = {};

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            const file = submission.files[fileType].file;
            request[fileType] = file.name;
        }
    }

    request = prepareMetadata(submission.meta, request);

    prepareFilesNewSub(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performRemoteCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };
    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            const file = submission.files[fileType].file;
            request[fileType] = file.name;
        }
    }

    prepareFilesExistingSub(request)
        .then(() => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(submission.id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performLocalUpload = (submission) => {
    const deferred = Q.defer();

    let request = {};

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    request = prepareMetadata(submission.meta, request);

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesNewSub(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch(() => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject();
        });

    return deferred.promise;
};

export const performLocalCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesExistingSub(request)
        .then(() => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(submission.id);
        })
        .catch(() => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject();
        });

    return deferred.promise;
};

export const performFabsFileUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        agency_code: submission.meta.subTierAgency
    };

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsFileCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsLocalUpload = (submission) => {
    const deferred = Q.defer();

    const request = {
        agency_code: submission.meta.subTierAgency
    };

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsLocalCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const request = {
        existing_submission_id: submission.id
    };

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};
<commit_msg>Fixing what we send to the backend<commit_after>import Q from 'q';
import Request from './sessionSuperagent';

import StoreSingleton from '../redux/storeSingleton';

import { kGlobalConstants } from '../GlobalConstants';
import * as uploadActions from '../redux/actions/uploadActions';

const prepareFilesNewSub = (fileDict) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_files/')
        .attach('appropriations', fileDict.appropriations)
        .attach('program_activity', fileDict.program_activity)
        .attach('award_financial', fileDict.award_financial)
        .field('cgac_code', fileDict.cgac_code)
        .field('frec_code', fileDict.frec_code)
        .field('reporting_period_start_date', fileDict.reporting_period_start_date)
        .field('reporting_period_end_date', fileDict.reporting_period_end_date)
        .field('is_quarter', fileDict.is_quarter)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareFilesExistingSub = (fileDict) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_files/')
        .attach('appropriations', fileDict.appropriations)
        .attach('program_activity', fileDict.program_activity)
        .attach('award_financial', fileDict.award_financial)
        .field('existing_submission_id', fileDict.existing_submission_id)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareMetadata = (metadata, request) => {
    const tmpRequest = Object.assign({}, request);
    // add the metadata to the request
    tmpRequest.cgac_code = metadata.codeType === 'cgac_code' ? metadata.agency : null;
    tmpRequest.frec_code = metadata.codeType === 'frec_code' ? metadata.agency : null;
    tmpRequest.reporting_period_start_date = metadata.startDate;
    tmpRequest.reporting_period_end_date = metadata.endDate;
    tmpRequest.is_quarter = false;
    if (metadata.dateType === "quarter") {
        tmpRequest.is_quarter = true;
    }

    return tmpRequest;
};

export const submitFabs = (submissionId) => {
    const deferred = Q.defer();

    Request.post(kGlobalConstants.API + 'submit_detached_file/')
        .send(submissionId)
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

const prepareFabsFile = (fileDict) => {
    const deferred = Q.defer();

    let fieldType = '';

    if (fileDict.hasOwnProperty('agency_code')) {
        fieldType = 'agency_code';
    }
    else if (fileDict.hasOwnProperty('existing_submission_id')) {
        fieldType = 'existing_submission_id';
    }

    Request.post(kGlobalConstants.API + 'upload_detached_file/')
        .attach('fabs', fileDict.fabs)
        .field(fieldType, fileDict[fieldType])
        .end((err, res) => {
            if (err) {
                const response = Object.assign({}, res.body);
                response.httpStatus = res.status;
                deferred.reject(response);
            }
            else {
                deferred.resolve(res);
            }
        });

    return deferred.promise;
};

export const performRemoteUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    let request = {};

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    request = prepareMetadata(submission.meta, request);

    prepareFilesNewSub(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performRemoteCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };
    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesExistingSub(request)
        .then(() => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(submission.id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performLocalUpload = (submission) => {
    const deferred = Q.defer();

    let request = {};

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    request = prepareMetadata(submission.meta, request);

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesNewSub(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch(() => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject();
        });

    return deferred.promise;
};

export const performLocalCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };

    for (const fileType in submission.files) {
        if (submission.files.hasOwnProperty(fileType)) {
            request[fileType] = submission.files[fileType].file;
        }
    }

    prepareFilesExistingSub(request)
        .then(() => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(submission.id);
        })
        .catch(() => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject();
        });

    return deferred.promise;
};

export const performFabsFileUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        agency_code: submission.meta.subTierAgency
    };

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsFileCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    const request = {
        existing_submission_id: submission.id
    };

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsLocalUpload = (submission) => {
    const deferred = Q.defer();

    const request = {
        agency_code: submission.meta.subTierAgency
    };

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};

export const performFabsLocalCorrectedUpload = (submission) => {
    const deferred = Q.defer();

    const request = {
        existing_submission_id: submission.id
    };

    const store = new StoreSingleton().store;
    store.dispatch(uploadActions.setSubmissionState('uploading'));

    if (submission.files.hasOwnProperty('fabs')) {
        request.fabs = submission.files.fabs.file;
    }

    prepareFabsFile(request)
        .then((res) => {
            store.dispatch(uploadActions.setSubmissionState('prepare'));
            deferred.resolve(res.body.submission_id);
        })
        .catch((err) => {
            store.dispatch(uploadActions.setSubmissionState('failed'));
            deferred.reject(err);
        });

    return deferred.promise;
};
<|endoftext|>