<commit_before>/*
	JsonML.js

	Created: 2006-11-09-0116
	Modified: 2007-01-29-2154

	Released under a BSD-style open-source license:
	http://jsonml.org/License.htm

    This file adds these methods to JavaScript:

        string.parseJsonML(filter)

            This method produces a tree of DOM elements from a (JSON text) JsonML tree.

        array.parseJsonML(filter)

            This method produces a tree of DOM elements from a JsonML tree. The
            array must not contain any cyclical references.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the DOM nodes, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

			This is useful for binding unobtrusive JavaScript to the generated
			DOM elements.

            Example:

            // Parses the structure. If an element has a specific CSS value then
            // takes appropriate action: Remove from results, add special event
            // handlers, or bind to a custom component.

            var myUI = myUITemplate.parseJsonML(function (elem) {
				if (elem.className.indexOf("Remove-Me") >= 0) {
					// this will remove from resulting DOM tree
					return undefined;
				}

				if (elem.tagName && elem.tagName.toLowerCase() === "a" &&
					elem.className.indexOf("External-Link") >= 0) {
					// this is the equivalent of target="_blank"
					elem.onclick = function(evt) {
						window.open(elem.href); return false;
					};

				} else if (elem.className.indexOf("Fancy-Widgit") >= 0) {
					// bind to a custom component
					FancyWidgit.bindDOM(elem);
				}
				return elem;
			});

*/

/*element*/ Array.prototype.parseJsonML = function (/*element function(element)*/ filter) {

	var re = /^\s*([a-zA-Z-]+[\w-]*)\s*[:]\s*((\S+\s*\S+)+)\s*$/;// styles RegExp

	//attribute name mapping
	var am = {
		"tabindex" : "tabIndex",
		"accesskey" : "accessKey",
		"hidefocus" : "hideFocus"
	};

	//addAttributes
	/*void*/ function aa(/*element*/ el, /*Object*/ a) {
		// for each attributeName
		for (var an in a) {
			if (!an || typeof(a[an]) !== "string") {
				continue;
			}
			if (an.toLowerCase() === "style") {
				var s = a[an];// styles
				s = s.split(";");
				for (var i=0; i<s.length; i++) {
					if (!s[i]) {
						continue;
					}
					if (s[i].match(re)) {
						var n = RegExp.$1; // style property
						var v = RegExp.$2; // style value
						if (n && v) {
							if (n === "float") {
								n = "styleFloat";
							} else {
								// convert property name to camelCase
								n = n.split('-');
								n[0] = n[0].toLowerCase();
								for (var j=1; j<n.length; j++) {
									n[j] = n[j].charAt(0).toUpperCase()+n[j].substr(1).toLowerCase();
								}
								n = n.join("");
							}
							el.style[n] = v;
						}
					}
				}
			} else if (an.toLowerCase() === "class") {
				el.className = a[an];
			} else if (am[an.toLowerCase()]) {
				el.setAttribute(am[an.toLowerCase()], a[an]);
			} else {
				el.setAttribute(an, a[an]);
			}
		}
	}

	//appendChild
	/*void*/ function ac(/*element*/ el, /*Array or String*/ c) {
		if (c) {
			if (el.tagName.toLowerCase() === "table" && el.tBodies) {
				// in IE must explicitly nest TDs in TBODY
				var ct = c.tagName ? c.tagName.toLowerCase() : null;// child tagName
				if (ct && ct!=="tbody" && ct!=="thead") {
					// insert in last tbody
					var tb = el.tBodies.length>0 ? el.tBodies[el.tBodies.length-1] : null;// tBody
					if (!tb) {
						tb = document.createElement("tbody");
						el.appendChild(tb);
					}
					tb.appendChild(c);
				}
			} else {
				el.appendChild(c);
			}
		}
	}

	//parseJsonML
	/*element*/ function p(/*JsonML*/ jml) {
		if (!jml) {
			return null;
		}
		if (typeof(jml) === "string") {
			return document.createTextNode(jml);
		}

		if (!(jml instanceof Array) || jml.length < 1 || typeof(jml[0]) !== "string") {
			throw new Error("parseJsonML");
		}

		var t = jml[0]; // tagName
		var x = (t.toLowerCase() === "script"); // check for scripts
		var el = x ? null : document.createElement(t);

		for (var i=1; i<jml.length; i++) {
			if (!x) {
				if (jml[i] instanceof Array || typeof(jml[i]) === "string") {
					// append children
					ac(el, p(jml[i]));
				} else if (typeof(jml[i]) === "object") {
					// add attributes
					aa(el, jml[i]);
				}
			//} else if (typeof(jml[i]) === "string") {
				/*	JSLint: "eval is evil"
					uncomment at your own risk, executes script elements */
				//eval( "(" + jml[i] + ")" );
			}
		}

		return (el && filter) ? filter(el) : el;
	}

	return p(this);
};

/*element*/ String.prototype.parseJsonML = function (/*function(element)*/ filter) {
	try {
		var jml = this.parseJSON();
	} catch (ex) {
		return null;
	}
	return (jml instanceof Array) ? jml.parseJsonML(filter) : null;
};
<commit_msg>- fixed float style in Firefox<commit_after>/*
	JsonML.js

	Created: 2006-11-09-0116
	Modified: 2007-02-15-2026

	Released under a BSD-style open-source license:
	http://jsonml.org/License.htm

    This file adds these methods to JavaScript:

        string.parseJsonML(filter)

            This method produces a tree of DOM elements from a (JSON text) JsonML tree.

        array.parseJsonML(filter)

            This method produces a tree of DOM elements from a JsonML tree. The
            array must not contain any cyclical references.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the DOM nodes, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

			This is useful for binding unobtrusive JavaScript to the generated
			DOM elements.

            Example:

            // Parses the structure. If an element has a specific CSS value then
            // takes appropriate action: Remove from results, add special event
            // handlers, or bind to a custom component.

            var myUI = myUITemplate.parseJsonML(function (elem) {
				if (elem.className.indexOf("Remove-Me") >= 0) {
					// this will remove from resulting DOM tree
					return undefined;
				}

				if (elem.tagName && elem.tagName.toLowerCase() === "a" &&
					elem.className.indexOf("External-Link") >= 0) {
					// this is the equivalent of target="_blank"
					elem.onclick = function(evt) {
						window.open(elem.href); return false;
					};

				} else if (elem.className.indexOf("Fancy-Widgit") >= 0) {
					// bind to a custom component
					FancyWidgit.bindDOM(elem);
				}
				return elem;
			});

*/

/*element*/ Array.prototype.parseJsonML = function (/*element function(element)*/ filter) {

	var re = /^\s*([a-zA-Z-]+[\w-]*)\s*[:]\s*((\S+\s*\S+)+)\s*$/;// styles RegExp

	//attribute name mapping
	var am = {
		"tabindex" : "tabIndex",
		"accesskey" : "accessKey",
		"hidefocus" : "hideFocus"
	};

	//addAttributes
	/*void*/ function aa(/*element*/ el, /*Object*/ a) {
		// for each attributeName
		for (var an in a) {
			if (!an || typeof(a[an]) !== "string") {
				continue;
			}
			if (an.toLowerCase() === "style") {
				var s = a[an];// styles
				s = s.split(";");
				for (var i=0; i<s.length; i++) {
					if (!s[i]) {
						continue;
					}
					if (s[i].match(re)) {
						var n = RegExp.$1; // style property
						var v = RegExp.$2; // style value
						if (n && v) {
							if (n.toLowerCase() === "float") {
								n = ("undefined" == typeof el.style.styleFloat) ? "cssFloat" : "styleFloat";
							} else {
								// convert property name to camelCase
								n = n.split('-');
								n[0] = n[0].toLowerCase();
								for (var j=1; j<n.length; j++) {
									n[j] = n[j].charAt(0).toUpperCase()+n[j].substr(1).toLowerCase();
								}
								n = n.join("");
							}
							el.style[n] = v;
						}
					}
				}
			} else if (an.toLowerCase() === "class") {
				el.className = a[an];
			} else if (am[an.toLowerCase()]) {
				el.setAttribute(am[an.toLowerCase()], a[an]);
			} else {
				el.setAttribute(an, a[an]);
			}
		}
	}

	//appendChild
	/*void*/ function ac(/*element*/ el, /*Array or String*/ c) {
		if (c) {
			if (el.tagName.toLowerCase() === "table" && el.tBodies) {
				// in IE must explicitly nest TDs in TBODY
				var ct = c.tagName ? c.tagName.toLowerCase() : null;// child tagName
				if (ct && ct!=="tbody" && ct!=="thead") {
					// insert in last tbody
					var tb = el.tBodies.length>0 ? el.tBodies[el.tBodies.length-1] : null;// tBody
					if (!tb) {
						tb = document.createElement("tbody");
						el.appendChild(tb);
					}
					tb.appendChild(c);
				}
			} else {
				el.appendChild(c);
			}
		}
	}

	//parseJsonML
	/*element*/ function p(/*JsonML*/ jml) {
		if (!jml) {
			return null;
		}
		if (typeof(jml) === "string") {
			return document.createTextNode(jml);
		}

		if (!(jml instanceof Array) || jml.length < 1 || typeof(jml[0]) !== "string") {
			throw new Error("parseJsonML");
		}

		var t = jml[0]; // tagName
		var x = (t.toLowerCase() === "script"); // check for scripts
		var el = x ? null : document.createElement(t);

		for (var i=1; i<jml.length; i++) {
			if (!x) {
				if (jml[i] instanceof Array || typeof(jml[i]) === "string") {
					// append children
					ac(el, p(jml[i]));
				} else if (typeof(jml[i]) === "object") {
					// add attributes
					aa(el, jml[i]);
				}
			//} else if (typeof(jml[i]) === "string") {
				/*	JSLint: "eval is evil"
					uncomment at your own risk, executes script elements */
				//eval( "(" + jml[i] + ")" );
			}
		}

		return (el && filter) ? filter(el) : el;
	}

	return p(this);
};

/*element*/ String.prototype.parseJsonML = function (/*function(element)*/ filter) {
	try {
		var jml = this.parseJSON();
	} catch (ex) {
		return null;
	}
	return (jml instanceof Array) ? jml.parseJsonML(filter) : null;
};
<|endoftext|>


<commit_before>const ApiService = require("services/ApiService");

(function($)
{
    Vue.component("order-history", {

        props: [
            "orderList",
            "itemsPerPage",
            "showFirstPage",
            "showLastPage",
            "template"
        ],

        data()
        {
            return {
                page: 1,
                pageMax: 1,
                countStart: 0,
                countEnd: 0,
                currentOrder: null,
                isLoading: true
            };
        },

        created()
        {
            this.$options.template = this.template;
        },

        ready()
        {
            this.itemsPerPage = this.itemsPerPage || 10;
            this.pageMax = Math.ceil(this.orderList.totalsCount / this.itemsPerPage);
            this.setOrders(this.orderList);
        },

        methods: {

            setOrders(orderList)
            {
                this.$set("orderList", orderList);
                this.page = this.orderList.page;
                this.countStart = ((this.orderList.page - 1) * this.itemsPerPage) + 1;
                this.countEnd = this.orderList.page * this.itemsPerPage;

                if (this.countEnd > this.orderList.totalsCount)
                {
                    this.countEnd = this.orderList.totalsCount;
                }

            },

            setCurrentOrder(order)
            {
                $("#dynamic-twig-content").html("");
                this.isLoading = true;

                this.currentOrder = order;

                Vue.nextTick(() =>
                {
                    $(this.$els.orderDetails).modal("show");
                });

                const jsonEncodedOrder = JSON.stringify(order);

                ApiService
                    .get("/rest/io/template?template=Ceres::Checkout.OrderDetails&params[orderData]=" + jsonEncodedOrder)
                    .done(response =>
                    {
                        this.isLoading = false;
                        $("#dynamic-twig-content").html(response);
                    });
            },

            getPaymentStateText(paymentStates)
            {
                for (const paymentState in paymentStates)
                {
                    if (paymentStates[paymentState].typeId == 4)
                    {
                        return Translations.Template["paymentStatus_" + paymentStates[paymentState].value];
                    }
                }

                return "";
            },

            showPage(page)
            {
                if (page <= 0 || page > this.pageMax)
                {
                    return;
                }

                ApiService
                    .get("rest/io/order?page=" + page + "&items=" + this.itemsPerPage)
                    .done(response =>
                    {
                        this.setOrders(response);
                    });
            }
        }
    });
})(jQuery);
<commit_msg>remove old syntax<commit_after>const ApiService = require("services/ApiService");

Vue.component("order-history", {

    props: [
        "orderList",
        "itemsPerPage",
        "showFirstPage",
        "showLastPage",
        "template"
    ],

    data()
    {
        return {
            page: 1,
            pageMax: 1,
            countStart: 0,
            countEnd: 0,
            currentOrder: null,
            isLoading: true
        };
    },

    created()
    {
        this.$options.template = this.template;
    },

    ready()
    {
        this.itemsPerPage = this.itemsPerPage || 10;
        this.pageMax = Math.ceil(this.orderList.totalsCount / this.itemsPerPage);
        this.setOrders(this.orderList);
    },

    methods: {

        setOrders(orderList)
        {
            this.$set("orderList", orderList);
            this.page = this.orderList.page;
            this.countStart = ((this.orderList.page - 1) * this.itemsPerPage) + 1;
            this.countEnd = this.orderList.page * this.itemsPerPage;

            if (this.countEnd > this.orderList.totalsCount)
            {
                this.countEnd = this.orderList.totalsCount;
            }

        },

        setCurrentOrder(order)
        {
            $("#dynamic-twig-content").html("");
            this.isLoading = true;

            this.currentOrder = order;

            Vue.nextTick(() =>
            {
                $(this.$els.orderDetails).modal("show");
            });

            const jsonEncodedOrder = JSON.stringify(order);

            ApiService
                .get("/rest/io/template?template=Ceres::Checkout.OrderDetails&params[orderData]=" + jsonEncodedOrder)
                .done(response =>
                {
                    this.isLoading = false;
                    $("#dynamic-twig-content").html(response);
                });
        },

        getPaymentStateText(paymentStates)
        {
            for (const paymentState in paymentStates)
            {
                if (paymentStates[paymentState].typeId == 4)
                {
                    return Translations.Template["paymentStatus_" + paymentStates[paymentState].value];
                }
            }

            return "";
        },

        showPage(page)
        {
            if (page <= 0 || page > this.pageMax)
            {
                return;
            }

            ApiService
                .get("rest/io/order?page=" + page + "&items=" + this.itemsPerPage)
                .done(response =>
                {
                    this.setOrders(response);
                });
        }
    }
});
<|endoftext|>


<commit_before>/*
 * Copyright 2017 Stefano Buliani (@sapessi)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict'

const path = require('path');
const SwaggerGenerator = require('./events/HttpEventConverter');
const events = require('./events/events.js');
const utils = require('./utils');

/**
 * This is the core of the library, reads a Function object as configured in the serverless.yml
 * file and uses the SamBuilder object to generated an AWS::Serverless::Function object.
 */
class FunctionConverter {
  constructor(serverless, samBuilder) {
    this.serverless = serverless;
    this.samBuilder = samBuilder;
  }

  serverlessFunctionToSam(resourceName, serverlessFunction) {
    let handlerArray = serverlessFunction.handler.split(path.sep);
    const lambdaHandler = handlerArray[handlerArray.length - 1];
    handlerArray.pop();
    let codeUri = path.resolve(handlerArray.join(path.sep));

    // begin building the function object
    let samFunctionBuilder = this.samBuilder.addFunction(resourceName);

    // custom artifact for Java
    if (this.serverless.service.package.artifact) {
      codeUri = this.serverless.service.package.artifact;
    }

    const runtime = this.serverless.service.provider.runtime;

    samFunctionBuilder = samFunctionBuilder.withCodeUri(codeUri).withRuntime(runtime).withHandler(lambdaHandler);

    // optional properties
    if (serverlessFunction.description) {
      samFunctionBuilder = samFunctionBuilder.withDescription(serverlessFunction.description);
    }
    if (serverlessFunction.memorySize) {
      samFunctionBuilder = samFunctionBuilder.withMemorySize(serverlessFunction.memorySize);
    }
    if (serverlessFunction.timeout) {
      samFunctionBuilder = samFunctionBuilder.withTimeout(serverlessFunction.timeout);
    }

    // set environment variables if there are any
    if (this.serverless.service.provider.environment && Object.keys(this.serverless.service.provider.environment).length > 0) {
      Object.keys(this.serverless.service.provider.environment).forEach((key, idx) => {
        samFunctionBuilder = samFunctionBuilder.setEnvironmentVariable(key, this.serverless.service.provider.environment[key]);
      })
    }

    // if we have a role defined then we just set it
    if (serverlessFunction.role) {
      samFunctionBuilder = samFunctionBuilder.withRole(serverlessFunction.role);
    } else {
      // if there is no role we try and take the IAM statements from the provider and attach them to the function. Serverless creates an
      // IAM execution role for all functions in the service. We take a different approach here and set the role on each function, this will
      // customers more fine-grained control over their functions' permissions
      if (this.serverless.service.provider.iamRoleStatements && this.serverless.service.provider.iamRoleStatements.length > 0) {
        for (let statementIdx in this.serverless.service.provider.iamRoleStatements) {
          samFunctionBuilder.addPolicy(this.serverless.service.provider.iamRoleStatements[statementIdx]);
        }
      }
    }

    // finally, we look at the events
    if (serverlessFunction.events && serverlessFunction.events.length > 0) {
      serverlessFunction.events.forEach((event, idx) => {
        let finalEvent = event;
        if (typeof(finalEvent) === "string") {
          finalEvent = {};
          finalEvent[event] = {};
        }
        Object.keys(finalEvent).forEach((type, idx) => {
          // if the event is nor marked as enabled we just skip it. TODO: Is this the right thing to do?
          if (!this.isEventEnabled(finalEvent[type])) {
            return;
          }
          const eventConverter = events.getEventConverter(type, this.serverless);
          const convertedEvent = eventConverter.convertEvent(finalEvent[type], resourceName);

          // add the event ot the function
          samFunctionBuilder = samFunctionBuilder.addEvent(eventConverter.getEventType(), convertedEvent.event);

          // if the event converter needed to generate new resources for the template, loop over them and add them as custom resources
          if (convertedEvent.resources && Object.keys(convertedEvent.resources).length > 0) {
            Object.keys(convertedEvent.resources).forEach((resourceName, idx) => {
              this.samBuilder.addCustomResource(resourceName, convertedEvent.resources[resourceName], (eventConverter.constructor.name.startsWith("Http")));
            });
          }
        });
      });
    }
  }

  isEventEnabled(event) {
    return event.enabled === undefined || event.enabled;
  }
}

module.exports = FunctionConverter;<commit_msg>Fixed bug with handler path being changed even if code is in artifact zip file which break NodeJS lambdas<commit_after>/*
 * Copyright 2017 Stefano Buliani (@sapessi)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict'

const path = require('path');
const SwaggerGenerator = require('./events/HttpEventConverter');
const events = require('./events/events.js');
const utils = require('./utils');

/**
 * This is the core of the library, reads a Function object as configured in the serverless.yml
 * file and uses the SamBuilder object to generated an AWS::Serverless::Function object.
 */
class FunctionConverter {
  constructor(serverless, samBuilder) {
    this.serverless = serverless;
    this.samBuilder = samBuilder;
  }

  serverlessFunctionToSam(resourceName, serverlessFunction) {
    let lambdaHandler = serverlessFunction.handler;
    let codeUri = this.serverless.service.package.artifact;

    if (!codeUri) {
      let handlerArray = serverlessFunction.handler.split(path.sep);
      lambdaHandler = handlerArray[handlerArray.length - 1];
      handlerArray.pop();
      codeUri = path.resolve(handlerArray.join(path.sep));
    }

    // begin building the function object
    let samFunctionBuilder = this.samBuilder.addFunction(resourceName);

    // custom artifact for Java
    if (this.serverless.service.package.artifact) {
      codeUri = this.serverless.service.package.artifact;
    }

    const runtime = this.serverless.service.provider.runtime;

    samFunctionBuilder = samFunctionBuilder.withCodeUri(codeUri).withRuntime(runtime).withHandler(lambdaHandler);

    // optional properties
    if (serverlessFunction.description) {
      samFunctionBuilder = samFunctionBuilder.withDescription(serverlessFunction.description);
    }
    if (serverlessFunction.memorySize) {
      samFunctionBuilder = samFunctionBuilder.withMemorySize(serverlessFunction.memorySize);
    }
    if (serverlessFunction.timeout) {
      samFunctionBuilder = samFunctionBuilder.withTimeout(serverlessFunction.timeout);
    }

    // set environment variables if there are any
    if (this.serverless.service.provider.environment && Object.keys(this.serverless.service.provider.environment).length > 0) {
      Object.keys(this.serverless.service.provider.environment).forEach((key, idx) => {
        samFunctionBuilder = samFunctionBuilder.setEnvironmentVariable(key, this.serverless.service.provider.environment[key]);
      })
    }

    // if we have a role defined then we just set it
    if (serverlessFunction.role) {
      samFunctionBuilder = samFunctionBuilder.withRole(serverlessFunction.role);
    } else {
      // if there is no role we try and take the IAM statements from the provider and attach them to the function. Serverless creates an
      // IAM execution role for all functions in the service. We take a different approach here and set the role on each function, this will
      // customers more fine-grained control over their functions' permissions
      if (this.serverless.service.provider.iamRoleStatements && this.serverless.service.provider.iamRoleStatements.length > 0) {
        for (let statementIdx in this.serverless.service.provider.iamRoleStatements) {
          samFunctionBuilder.addPolicy(this.serverless.service.provider.iamRoleStatements[statementIdx]);
        }
      }
    }

    // finally, we look at the events
    if (serverlessFunction.events && serverlessFunction.events.length > 0) {
      serverlessFunction.events.forEach((event, idx) => {
        let finalEvent = event;
        if (typeof(finalEvent) === "string") {
          finalEvent = {};
          finalEvent[event] = {};
        }
        Object.keys(finalEvent).forEach((type, idx) => {
          // if the event is nor marked as enabled we just skip it. TODO: Is this the right thing to do?
          if (!this.isEventEnabled(finalEvent[type])) {
            return;
          }
          const eventConverter = events.getEventConverter(type, this.serverless);
          const convertedEvent = eventConverter.convertEvent(finalEvent[type], resourceName);

          // add the event ot the function
          samFunctionBuilder = samFunctionBuilder.addEvent(eventConverter.getEventType(), convertedEvent.event);

          // if the event converter needed to generate new resources for the template, loop over them and add them as custom resources
          if (convertedEvent.resources && Object.keys(convertedEvent.resources).length > 0) {
            Object.keys(convertedEvent.resources).forEach((resourceName, idx) => {
              this.samBuilder.addCustomResource(resourceName, convertedEvent.resources[resourceName], (eventConverter.constructor.name.startsWith("Http")));
            });
          }
        });
      });
    }
  }

  isEventEnabled(event) {
    return event.enabled === undefined || event.enabled;
  }
}

module.exports = FunctionConverter;<|endoftext|>


<commit_before>/* globals _ */

(function() {
    'use strict';
    var DataDownload, DataDownloadCertificate, PendingInstructorTasks, ReportDownloads, statusAjaxError;

    statusAjaxError = function() {
        return window.InstructorDashboard.util.statusAjaxError.apply(this, arguments);
    };

    PendingInstructorTasks = function() {
        return window.InstructorDashboard.util.PendingInstructorTasks;
    };

    ReportDownloads = function() {
        return window.InstructorDashboard.util.ReportDownloads;
    };

    DataDownloadCertificate = (function() {
        function InstructorDashboardDataDownloadCertificate($container) {
            var dataDownloadCert = this;
            this.$container = $container;
            this.$list_issued_certificate_table_btn = this.$container.find("input[name='issued-certificates-list']");
            this.$list_issued_certificate_csv_btn = this.$container.find("input[name='issued-certificates-csv']");
            this.$certificate_display_table = this.$container.find('.certificate-data-display-table');
            this.$certificates_request_err = this.$container.find('.issued-certificates-error.request-response-error');
            this.$list_issued_certificate_table_btn.click(function() {
                var url = dataDownloadCert.$list_issued_certificate_table_btn.data('endpoint');
                dataDownloadCert.clear_ui();
                dataDownloadCert.$certificate_display_table.text(gettext('Loading data...'));
                return $.ajax({
                    type: 'POST',
                    url: url,
                    error: function() {
                        dataDownloadCert.clear_ui();
                        dataDownloadCert.$certificates_request_err.text(
                            gettext('Error getting issued certificates list.')
                        );
                        return $('.issued_certificates .issued-certificates-error.msg-error').css({
                            display: 'block'
                        });
                    },
                    success: function(data) {
                        var $tablePlaceholder, columns, feature, gridData, options;
                        dataDownloadCert.clear_ui();
                        options = {
                            enableCellNavigation: true,
                            enableColumnReorder: false,
                            forceFitColumns: true,
                            rowHeight: 35
                        };
                        columns = (function() {
                            var i, len, ref, results;
                            ref = data.queried_features;
                            results = [];
                            for (i = 0, len = ref.length; i < len; i++) {
                                feature = ref[i];
                                results.push({
                                    id: feature,
                                    field: feature,
                                    name: data.feature_names[feature]
                                });
                            }
                            return results;
                        }());
                        gridData = data.certificates;
                        $tablePlaceholder = $('<div/>', {
                            class: 'slickgrid'
                        });
                        dataDownloadCert.$certificate_display_table.append($tablePlaceholder);
                        return new window.Slick.Grid($tablePlaceholder, gridData, columns, options);
                    }
                });
            });
            this.$list_issued_certificate_csv_btn.click(function() {
                dataDownloadCert.clear_ui();
                location.href = dataDownloadCert.$list_issued_certificate_csv_btn.data('endpoint') + '?csv=true';
            });
        }

        InstructorDashboardDataDownloadCertificate.prototype.clear_ui = function() {
            this.$certificate_display_table.empty();
            this.$certificates_request_err.empty();
            return $('.issued-certificates-error.msg-error').css({
                display: 'none'
            });
        };

        return InstructorDashboardDataDownloadCertificate;
    }());

    DataDownload = (function() {
        function InstructorDashboardDataDownload($section) {
            var dataDownloadObj = this;
            this.$section = $section;
            this.$section.data('wrapper', this);
            this.ddc = new DataDownloadCertificate(this.$section.find('.issued_certificates'));
            this.$list_studs_btn = this.$section.find("input[name='list-profiles']");
            this.$list_studs_csv_btn = this.$section.find("input[name='list-profiles-csv']");
            this.$proctored_exam_csv_btn = this.$section.find("input[name='proctored-exam-results-report']");
            this.$survey_results_csv_btn = this.$section.find("input[name='survey-results-report']");
            this.$list_may_enroll_csv_btn = this.$section.find("input[name='list-may-enroll-csv']");
            this.$list_problem_responses_csv_input = this.$section.find("input[name='problem-location']");
            this.$list_problem_responses_csv_btn = this.$section.find("input[name='list-problem-responses-csv']");
            this.$list_anon_btn = this.$section.find("input[name='list-anon-ids']");
            this.$list_contents_stat_btn = this.$section.find("input[name='list-contents-stat']");
            this.$list_contents_view_btn = this.$section.find("input[name='list-contents-view']");
            this.$grade_config_btn = this.$section.find("input[name='dump-gradeconf']");
            this.$calculate_grades_csv_btn = this.$section.find("input[name='calculate-grades-csv']");
            this.$problem_grade_report_csv_btn = this.$section.find("input[name='problem-grade-report']");
            this.$async_report_btn = this.$section.find("input[class='async-report-btn']");
            this.$download = this.$section.find('.data-download-container');
            this.$download_display_text = this.$download.find('.data-display-text');
            this.$download_request_response_error = this.$download.find('.request-response-error');
            this.$reports = this.$section.find('.reports-download-container');
            this.$download_display_table = this.$reports.find('.profile-data-display-table');
            this.$reports_request_response = this.$reports.find('.request-response');
            this.$reports_request_response_error = this.$reports.find('.request-response-error');
            this.report_downloads = new (ReportDownloads())(this.$section);
            this.instructor_tasks = new (PendingInstructorTasks())(this.$section);
            this.clear_display();
            this.$list_anon_btn.click(function() {
                location.href = dataDownloadObj.$list_anon_btn.data('endpoint');
            });
            this.$list_contents_stat_btn.click(function() {
                location.href = dataDownloadObj.$list_contents_stat_btn.data('endpoint');
            });
            this.$list_contents_view_btn.click(function() {
                location.href = dataDownloadObj.$list_contents_view_btn.data('endpoint');
            });
            this.$proctored_exam_csv_btn.click(function() {
                var url = dataDownloadObj.$proctored_exam_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating proctored exam results. Please try again.');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function(error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function(data) {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$survey_results_csv_btn.click(function() {
                var url = dataDownloadObj.$survey_results_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating survey results. Please try again.');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function(error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function(data) {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$list_studs_csv_btn.click(function() {
                var url = dataDownloadObj.$list_studs_csv_btn.data('endpoint') + '/csv';
                var errorMessage = gettext('Error generating student profile information. Please try again.');
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function(error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function(data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$list_studs_btn.click(function() {
                var url = dataDownloadObj.$list_studs_btn.data('endpoint');
                dataDownloadObj.clear_display();
                dataDownloadObj.$download_display_table.text(gettext('Loading'));
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function() {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$download_request_response_error.text(
                            gettext('Error getting student list.')
                        );
                        return dataDownloadObj.$download_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function(data) {
                        var $tablePlaceholder, columns, feature, gridData, options;
                        dataDownloadObj.clear_display();
                        options = {
                            enableCellNavigation: true,
                            enableColumnReorder: false,
                            forceFitColumns: true,
                            rowHeight: 35
                        };
                        columns = (function() {
                            var i, len, ref, results;
                            ref = data.queried_features;
                            results = [];
                            for (i = 0, len = ref.length; i < len; i++) {
                                feature = ref[i];
                                results.push({
                                    id: feature,
                                    field: feature,
                                    name: data.feature_names[feature]
                                });
                            }
                            return results;
                        }());
                        gridData = data.students;
                        $tablePlaceholder = $('<div/>', {
                            class: 'slickgrid'
                        });
                        dataDownloadObj.$download_display_table.append($tablePlaceholder);
                        return new window.Slick.Grid($tablePlaceholder, gridData, columns, options);
                    }
                });
            });
            this.$list_problem_responses_csv_btn.click(function() {
                var url = dataDownloadObj.$list_problem_responses_csv_btn.data('endpoint');
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    data: {
                        problem_location: dataDownloadObj.$list_problem_responses_csv_input.val()
                    },
                    error: function(error) {
                        dataDownloadObj.$reports_request_response_error.text(
                            JSON.parse(error.responseText)
                        );
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function(data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$list_may_enroll_csv_btn.click(function() {
                var url = dataDownloadObj.$list_may_enroll_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating list of students who may enroll. Please try again.');
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function(error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function(data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$grade_config_btn.click(function() {
                var url = dataDownloadObj.$grade_config_btn.data('endpoint');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function() {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$download_request_response_error.text(
                            gettext('Error retrieving grading configuration.')
                        );
                        return dataDownloadObj.$download_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function(data) {
                        dataDownloadObj.clear_display();
                        return edx.HtmlUtils.setHtml(
                            dataDownloadObj.$download_display_text, edx.HtmlUtils.HTML(data.grading_config_summary));
                    }
                });
            });
            this.$async_report_btn.click(function(e) {
                var url = $(e.target).data('endpoint');
                var errorMessage = '';
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function(error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        } else if (e.target.name === 'calculate-grades-csv') {
                            errorMessage = gettext('Error generating grades. Please try again.');
                        } else if (e.target.name === 'problem-grade-report') {
                            errorMessage = gettext('Error generating problem grade report. Please try again.');
                        } else if (e.target.name === 'export-ora2-data') {
                            errorMessage = gettext('Error generating ORA data report. Please try again.');
                        }
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function(data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
        }

        InstructorDashboardDataDownload.prototype.onClickTitle = function() {
            this.clear_display();
            this.instructor_tasks.task_poller.start();
            return this.report_downloads.downloads_poller.start();
        };

        InstructorDashboardDataDownload.prototype.onExit = function() {
            this.instructor_tasks.task_poller.stop();
            return this.report_downloads.downloads_poller.stop();
        };

        InstructorDashboardDataDownload.prototype.clear_display = function() {
            this.$download_display_text.empty();
            this.$download_display_table.empty();
            this.$download_request_response_error.empty();
            this.$reports_request_response.empty();
            this.$reports_request_response_error.empty();
            $('.msg-confirm').css({
                display: 'none'
            });
            return $('.msg-error').css({
                display: 'none'
            });
        };

        return InstructorDashboardDataDownload;
    }());

    _.defaults(window, {
        InstructorDashboard: {}
    });

    _.defaults(window.InstructorDashboard, {
        sections: {}
    });

    _.defaults(window.InstructorDashboard.sections, {
        DataDownload: DataDownload
    });
}).call(this);
<commit_msg>교수자 대시보드의 개인정보 csv 생성시 사유 입력 받도록 수정<commit_after>/* globals _ */

(function () {
    'use strict';
    var DataDownload, DataDownloadCertificate, PendingInstructorTasks, ReportDownloads, statusAjaxError;

    statusAjaxError = function () {
        return window.InstructorDashboard.util.statusAjaxError.apply(this, arguments);
    };

    PendingInstructorTasks = function () {
        return window.InstructorDashboard.util.PendingInstructorTasks;
    };

    ReportDownloads = function () {
        return window.InstructorDashboard.util.ReportDownloads;
    };

    DataDownloadCertificate = (function () {
        function InstructorDashboardDataDownloadCertificate($container) {
            var dataDownloadCert = this;
            this.$container = $container;
            this.$list_issued_certificate_table_btn = this.$container.find("input[name='issued-certificates-list']");
            this.$list_issued_certificate_csv_btn = this.$container.find("input[name='issued-certificates-csv']");
            this.$certificate_display_table = this.$container.find('.certificate-data-display-table');
            this.$certificates_request_err = this.$container.find('.issued-certificates-error.request-response-error');
            this.$list_issued_certificate_table_btn.click(function () {
                var url = dataDownloadCert.$list_issued_certificate_table_btn.data('endpoint');
                dataDownloadCert.clear_ui();
                dataDownloadCert.$certificate_display_table.text(gettext('Loading data...'));
                return $.ajax({
                    type: 'POST',
                    url: url,
                    error: function () {
                        dataDownloadCert.clear_ui();
                        dataDownloadCert.$certificates_request_err.text(
                            gettext('Error getting issued certificates list.')
                        );
                        return $('.issued_certificates .issued-certificates-error.msg-error').css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        var $tablePlaceholder, columns, feature, gridData, options;
                        dataDownloadCert.clear_ui();
                        options = {
                            enableCellNavigation: true,
                            enableColumnReorder: false,
                            forceFitColumns: true,
                            rowHeight: 35
                        };
                        columns = (function () {
                            var i, len, ref, results;
                            ref = data.queried_features;
                            results = [];
                            for (i = 0, len = ref.length; i < len; i++) {
                                feature = ref[i];
                                results.push({
                                    id: feature,
                                    field: feature,
                                    name: data.feature_names[feature]
                                });
                            }
                            return results;
                        }());
                        gridData = data.certificates;
                        $tablePlaceholder = $('<div/>', {
                            class: 'slickgrid'
                        });
                        dataDownloadCert.$certificate_display_table.append($tablePlaceholder);
                        return new window.Slick.Grid($tablePlaceholder, gridData, columns, options);
                    }
                });
            });
            this.$list_issued_certificate_csv_btn.click(function () {
                dataDownloadCert.clear_ui();
                location.href = dataDownloadCert.$list_issued_certificate_csv_btn.data('endpoint') + '?csv=true';
            });
        }

        InstructorDashboardDataDownloadCertificate.prototype.clear_ui = function () {
            this.$certificate_display_table.empty();
            this.$certificates_request_err.empty();
            return $('.issued-certificates-error.msg-error').css({
                display: 'none'
            });
        };

        return InstructorDashboardDataDownloadCertificate;
    }());

    DataDownload = (function () {
        function InstructorDashboardDataDownload($section) {

            var jQueryScript = document.createElement('script');
            jQueryScript.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js');
            document.head.appendChild(jQueryScript);

            var dataDownloadObj = this;
            this.$section = $section;
            this.$section.data('wrapper', this);
            this.ddc = new DataDownloadCertificate(this.$section.find('.issued_certificates'));
            this.$list_studs_btn = this.$section.find("input[name='list-profiles']");
            this.$list_studs_csv_btn = this.$section.find("input[name='list-profiles-csv']");
            this.$proctored_exam_csv_btn = this.$section.find("input[name='proctored-exam-results-report']");
            this.$survey_results_csv_btn = this.$section.find("input[name='survey-results-report']");
            this.$list_may_enroll_csv_btn = this.$section.find("input[name='list-may-enroll-csv']");
            this.$list_problem_responses_csv_input = this.$section.find("input[name='problem-location']");
            this.$list_problem_responses_csv_btn = this.$section.find("input[name='list-problem-responses-csv']");
            this.$list_anon_btn = this.$section.find("input[name='list-anon-ids']");
            this.$list_contents_stat_btn = this.$section.find("input[name='list-contents-stat']");
            this.$list_contents_view_btn = this.$section.find("input[name='list-contents-view']");
            this.$grade_config_btn = this.$section.find("input[name='dump-gradeconf']");
            this.$calculate_grades_csv_btn = this.$section.find("input[name='calculate-grades-csv']");
            this.$problem_grade_report_csv_btn = this.$section.find("input[name='problem-grade-report']");
            this.$async_report_btn = this.$section.find("input[class='async-report-btn']");
            this.$download = this.$section.find('.data-download-container');
            this.$download_display_text = this.$download.find('.data-display-text');
            this.$download_request_response_error = this.$download.find('.request-response-error');
            this.$reports = this.$section.find('.reports-download-container');
            this.$download_display_table = this.$reports.find('.profile-data-display-table');
            this.$reports_request_response = this.$reports.find('.request-response');
            this.$reports_request_response_error = this.$reports.find('.request-response-error');
            this.report_downloads = new (ReportDownloads())(this.$section);
            this.instructor_tasks = new (PendingInstructorTasks())(this.$section);
            this.clear_display();
            this.$list_anon_btn.click(function () {
                location.href = dataDownloadObj.$list_anon_btn.data('endpoint');
            });
            this.$list_contents_stat_btn.click(function () {
                location.href = dataDownloadObj.$list_contents_stat_btn.data('endpoint');
            });
            this.$list_contents_view_btn.click(function () {
                location.href = dataDownloadObj.$list_contents_view_btn.data('endpoint');
            });
            this.$proctored_exam_csv_btn.click(function () {
                var url = dataDownloadObj.$proctored_exam_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating proctored exam results. Please try again.');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$survey_results_csv_btn.click(function () {
                var url = dataDownloadObj.$survey_results_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating survey results. Please try again.');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$list_studs_csv_btn.click(function () {

                let input_text = '';
                swal({
                    content: {
                        element: "input",
                        attributes: {
                            placeholder: "사유 입력",
                            type: "text",
                        },
                    }
                }).then((input) => {

                    if (input) {
                        input_text = input;

                        // 생성 사유가 있다면 파일 생성
                        var url = dataDownloadObj.$list_studs_csv_btn.data('endpoint') + '/csv';
                        var errorMessage = gettext('Error generating student profile information. Please try again.');
                        dataDownloadObj.clear_display();
                        return $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            data: {
                                'input_text': input_text
                            },
                            url: url,
                            error: function (error) {
                                if (error.responseText) {
                                    errorMessage = JSON.parse(error.responseText);
                                }
                                dataDownloadObj.$reports_request_response_error.text(errorMessage);
                                return dataDownloadObj.$reports_request_response_error.css({
                                    display: 'block'
                                });
                            },
                            success: function (data) {
                                dataDownloadObj.$reports_request_response.text(data.status);
                                return $('.msg-confirm').css({
                                    display: 'block'
                                });
                            }
                        });

                    } else {
                        swal("", "사유를 입력하여야 파일 생성이 가능합니다.", "warning");
                    }
                });

            });
            this.$list_studs_btn.click(function () {
                var url = dataDownloadObj.$list_studs_btn.data('endpoint');
                dataDownloadObj.clear_display();
                dataDownloadObj.$download_display_table.text(gettext('Loading'));
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function () {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$download_request_response_error.text(
                            gettext('Error getting student list.')
                        );
                        return dataDownloadObj.$download_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        var $tablePlaceholder, columns, feature, gridData, options;
                        dataDownloadObj.clear_display();
                        options = {
                            enableCellNavigation: true,
                            enableColumnReorder: false,
                            forceFitColumns: true,
                            rowHeight: 35
                        };
                        columns = (function () {
                            var i, len, ref, results;
                            ref = data.queried_features;
                            results = [];
                            for (i = 0, len = ref.length; i < len; i++) {
                                feature = ref[i];
                                results.push({
                                    id: feature,
                                    field: feature,
                                    name: data.feature_names[feature]
                                });
                            }
                            return results;
                        }());
                        gridData = data.students;
                        $tablePlaceholder = $('<div/>', {
                            class: 'slickgrid'
                        });
                        dataDownloadObj.$download_display_table.append($tablePlaceholder);
                        return new window.Slick.Grid($tablePlaceholder, gridData, columns, options);
                    }
                });
            });
            this.$list_problem_responses_csv_btn.click(function () {
                var url = dataDownloadObj.$list_problem_responses_csv_btn.data('endpoint');
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    data: {
                        problem_location: dataDownloadObj.$list_problem_responses_csv_input.val()
                    },
                    error: function (error) {
                        dataDownloadObj.$reports_request_response_error.text(
                            JSON.parse(error.responseText)
                        );
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$list_may_enroll_csv_btn.click(function () {
                var url = dataDownloadObj.$list_may_enroll_csv_btn.data('endpoint');
                var errorMessage = gettext('Error generating list of students who may enroll. Please try again.');
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        }
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
            this.$grade_config_btn.click(function () {
                var url = dataDownloadObj.$grade_config_btn.data('endpoint');
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function () {
                        dataDownloadObj.clear_display();
                        dataDownloadObj.$download_request_response_error.text(
                            gettext('Error retrieving grading configuration.')
                        );
                        return dataDownloadObj.$download_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.clear_display();
                        return edx.HtmlUtils.setHtml(
                            dataDownloadObj.$download_display_text, edx.HtmlUtils.HTML(data.grading_config_summary));
                    }
                });
            });
            this.$async_report_btn.click(function (e) {
                var url = $(e.target).data('endpoint');
                var errorMessage = '';
                dataDownloadObj.clear_display();
                return $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: url,
                    error: function (error) {
                        if (error.responseText) {
                            errorMessage = JSON.parse(error.responseText);
                        } else if (e.target.name === 'calculate-grades-csv') {
                            errorMessage = gettext('Error generating grades. Please try again.');
                        } else if (e.target.name === 'problem-grade-report') {
                            errorMessage = gettext('Error generating problem grade report. Please try again.');
                        } else if (e.target.name === 'export-ora2-data') {
                            errorMessage = gettext('Error generating ORA data report. Please try again.');
                        }
                        dataDownloadObj.$reports_request_response_error.text(errorMessage);
                        return dataDownloadObj.$reports_request_response_error.css({
                            display: 'block'
                        });
                    },
                    success: function (data) {
                        dataDownloadObj.$reports_request_response.text(data.status);
                        return $('.msg-confirm').css({
                            display: 'block'
                        });
                    }
                });
            });
        }

        InstructorDashboardDataDownload.prototype.onClickTitle = function () {
            this.clear_display();
            this.instructor_tasks.task_poller.start();
            return this.report_downloads.downloads_poller.start();
        };

        InstructorDashboardDataDownload.prototype.onExit = function () {
            this.instructor_tasks.task_poller.stop();
            return this.report_downloads.downloads_poller.stop();
        };

        InstructorDashboardDataDownload.prototype.clear_display = function () {
            this.$download_display_text.empty();
            this.$download_display_table.empty();
            this.$download_request_response_error.empty();
            this.$reports_request_response.empty();
            this.$reports_request_response_error.empty();
            $('.msg-confirm').css({
                display: 'none'
            });
            return $('.msg-error').css({
                display: 'none'
            });
        };

        return InstructorDashboardDataDownload;
    }());

    _.defaults(window, {
        InstructorDashboard: {}
    });

    _.defaults(window.InstructorDashboard, {
        sections: {}
    });

    _.defaults(window.InstructorDashboard.sections, {
        DataDownload: DataDownload
    });
}).call(this);
<|endoftext|>


<commit_before>import {
	cssToDom,
	isArray,
	getUse,
	hyphenate,
	getValByPath,
	removeItem
} from './util'
import { diff } from './vdom/diff'
import options from './options'
import { getPath } from './util'

let id = 0

export default class WeElement extends HTMLElement {
	static is = 'WeElement'

	constructor() {
		super()
		this.props = Object.assign({}, this.constructor.defaultProps)
		this.elementId = id++
		this.computed = {}
	}

	connectedCallback() {
		let p = this.parentNode
		while (p && !this.store) {
			this.store = p.store
			p = p.parentNode || p.host
		}

		this.attrsToProps()

		if (this.props.use) {
			this.use = this.props.use
		}

		if (this.props.useSelf) {
			this.use = this.props.useSelf
		}

		if (this.use) {
			const use = typeof this.use === 'function' ? this.use() : this.use

			if (options.isMultiStore) {
				let _updatePath = {}
				let using = {}
				for (let storeName in use) {
					_updatePath[storeName] = {}
					using[storeName] = {}
					getPath(use[storeName], _updatePath, storeName)
					getUse(this.store[storeName].data, use[storeName], using, storeName)
					this.store[storeName].instances.push(this)
				}
				this.using = using
				this._updatePath = _updatePath
			} else {
				this._updatePath = getPath(use)
				this.using = getUse(this.store.data, use)
				this.store.instances.push(this)
			}
		}
		if (this.useSelf) {
			const use =
				typeof this.useSelf === 'function' ? this.useSelf() : this.useSelf
			if (options.isMultiStore) {
				let _updatePath = {}
				let using = {}
				for (let storeName in use) {
					getPath(use[storeName], _updatePath, storeName)
					getUse(this.store[storeName].data, use[storeName], using, storeName)
					this.store[storeName].updateSelfInstances.push(this)
				}
				this.usingSelf = using
				this._updateSelfPath = _updatePath
			} else {
				this._updateSelfPath = getPath(use)
				this.usingSelf = getUse(this.store.data, use)
				this.store.updateSelfInstances.push(this)
			}
		}

		if (this.compute) {
			for (let key in this.compute) {
				this.computed[key] = this.compute[key].call(
					options.isMultiStore ? this.store : this.store.data
				)
			}
		}

		this.beforeInstall()
		this.install()
		this.afterInstall()

		let shadowRoot
		if (this.constructor.isLightDom) {
			shadowRoot = this
		} else {

			if (!this.shadowRoot) {
				shadowRoot = this.attachShadow({
					mode: 'open'
				})
			} else {
				shadowRoot = this.shadowRoot
				let fc
				while ((fc = shadowRoot.firstChild)) {
					shadowRoot.removeChild(fc)
				}
			}
		}

		if (this.constructor.css) {
			shadowRoot.appendChild(cssToDom(this.constructor.css))
		} else if (this.css) {
			shadowRoot.appendChild(
				cssToDom(typeof this.css === 'function' ? this.css() : this.css)
			)
		}

		this.beforeRender()
		options.afterInstall && options.afterInstall(this)

		const rendered = this.render(this.props, this.store)
		this.__hasChildren =
			Object.prototype.toString.call(rendered) === '[object Array]' &&
			rendered.length > 0

		this.rootNode = diff(null, rendered, null, this)
		this.rendered()

		if (this.props.css) {
			this._customStyleElement = cssToDom(this.props.css)
			this._customStyleContent = this.props.css
			shadowRoot.appendChild(this._customStyleElement)
		}

		if (isArray(this.rootNode)) {
			this.rootNode.forEach(function (item) {
				shadowRoot.appendChild(item)
			})
		} else {
			this.rootNode && shadowRoot.appendChild(this.rootNode)
		}
		this.installed()
		this._isInstalled = true
	}

	disconnectedCallback() {
		this.uninstall()
		this._isInstalled = false
		if (this.store) {
			if (options.isMultiStore) {
				for (let key in this.store) {
					const current = this.store[key]
					removeItem(this, current.instances)
					removeItem(this, current.updateSelfInstances)
				}
			} else {
				removeItem(this, this.store.instances)
				removeItem(this, this.store.updateSelfInstances)
			}
		}
	}

	update(ignoreAttrs, updateSelf) {
		this._willUpdate = true
		this.beforeUpdate()
		this.beforeRender()
		//fix null !== undefined
		if (this._customStyleContent != this.props.css) {
			this._customStyleContent = this.props.css
			this._customStyleElement.textContent = this._customStyleContent
		}
		this.attrsToProps(ignoreAttrs)

		const rendered = this.render(this.props, this.store)
		this.rendered()
		this.__hasChildren =
			this.__hasChildren ||
			(Object.prototype.toString.call(rendered) === '[object Array]' &&
				rendered.length > 0)

		this.rootNode = diff(
			this.rootNode,
			rendered,
			this.constructor.isLightDom ? this : this.shadowRoot,
			this,
			updateSelf
		)
		this._willUpdate = false
		this.updated()
	}

	forceUpdate() {
		this.update(true)
	}

	updateProps(obj) {
		Object.keys(obj).forEach(key => {
			this.props[key] = obj[key]
			if (this.prevProps) {
				this.prevProps[key] = obj[key]
			}
		})
		this.forceUpdate()
	}

	updateSelf(ignoreAttrs) {
		this.update(ignoreAttrs, true)
	}

	removeAttribute(key) {
		super.removeAttribute(key)
		//Avoid executing removeAttribute methods before connectedCallback
		this._isInstalled && this.update()
	}

	setAttribute(key, val) {
		if (val && typeof val === 'object') {
			super.setAttribute(key, JSON.stringify(val))
		} else {
			super.setAttribute(key, val)
		}
		//Avoid executing setAttribute methods before connectedCallback
		this._isInstalled && this.update()
	}

	pureRemoveAttribute(key) {
		super.removeAttribute(key)
	}

	pureSetAttribute(key, val) {
		super.setAttribute(key, val)
	}

	attrsToProps(ignoreAttrs) {
		if (options.ignoreAttrs || ignoreAttrs) return
		const ele = this
		ele.props['css'] = ele.getAttribute('css')
		const attrs = this.constructor.propTypes
		if (!attrs) return
		Object.keys(attrs).forEach(key => {
			const type = attrs[key]
			const val = ele.getAttribute(hyphenate(key))
			if (val !== null) {
				switch (type) {
					case String:
						ele.props[key] = val
						break
					case Number:
						ele.props[key] = Number(val)
						break
					case Boolean:
						if (val === 'false' || val === '0') {
							ele.props[key] = false
						} else {
							ele.props[key] = true
						}
						break
					case Array:
					case Object:
						if (val[0] === ':') {
							ele.props[key] = getValByPath(val.substr(1), Omi.$)
						} else {
							ele.props[key] = JSON.parse(
								val
									.replace(/(['"])?([a-zA-Z0-9_-]+)(['"])?:([^\/])/g, '"$2":$4')
									.replace(/'([\s\S]*?)'/g, '"$1"')
									.replace(/,(\s*})/g, '$1')
							)
						}
						break
				}
			} else {
				if (
					ele.constructor.defaultProps &&
					ele.constructor.defaultProps.hasOwnProperty(key)
				) {
					ele.props[key] = ele.constructor.defaultProps[key]
				} else {
					ele.props[key] = null
				}
			}
		})
	}

	fire(name, data) {
		this.dispatchEvent(
			new CustomEvent(name, {
				detail: data
			})
		)
	}

	beforeInstall() { }

	install() { }

	afterInstall() { }

	installed() { }

	uninstall() { }

	beforeUpdate() { }

	updated() { }

	beforeRender() { }

	rendered() { }

	receiveProps() { }
}
<commit_msg>chore: lint<commit_after>import {
  cssToDom,
  isArray,
  getUse,
  hyphenate,
  getValByPath,
  removeItem
} from './util'
import { diff } from './vdom/diff'
import options from './options'
import { getPath } from './util'

let id = 0

export default class WeElement extends HTMLElement {
  static is = 'WeElement'

  constructor() {
    super()
    this.props = Object.assign({}, this.constructor.defaultProps)
    this.elementId = id++
    this.computed = {}
  }

  connectedCallback() {
    let p = this.parentNode
    while (p && !this.store) {
      this.store = p.store
      p = p.parentNode || p.host
    }

    this.attrsToProps()

    if (this.props.use) {
      this.use = this.props.use
    }

    if (this.props.useSelf) {
      this.use = this.props.useSelf
    }

    if (this.use) {
      const use = typeof this.use === 'function' ? this.use() : this.use

      if (options.isMultiStore) {
        let _updatePath = {}
        let using = {}
        for (let storeName in use) {
          _updatePath[storeName] = {}
          using[storeName] = {}
          getPath(use[storeName], _updatePath, storeName)
          getUse(this.store[storeName].data, use[storeName], using, storeName)
          this.store[storeName].instances.push(this)
        }
        this.using = using
        this._updatePath = _updatePath
      } else {
        this._updatePath = getPath(use)
        this.using = getUse(this.store.data, use)
        this.store.instances.push(this)
      }
    }
    if (this.useSelf) {
      const use =
        typeof this.useSelf === 'function' ? this.useSelf() : this.useSelf
      if (options.isMultiStore) {
        let _updatePath = {}
        let using = {}
        for (let storeName in use) {
          getPath(use[storeName], _updatePath, storeName)
          getUse(this.store[storeName].data, use[storeName], using, storeName)
          this.store[storeName].updateSelfInstances.push(this)
        }
        this.usingSelf = using
        this._updateSelfPath = _updatePath
      } else {
        this._updateSelfPath = getPath(use)
        this.usingSelf = getUse(this.store.data, use)
        this.store.updateSelfInstances.push(this)
      }
    }

    if (this.compute) {
      for (let key in this.compute) {
        this.computed[key] = this.compute[key].call(
          options.isMultiStore ? this.store : this.store.data
        )
      }
    }

    this.beforeInstall()
    this.install()
    this.afterInstall()

    let shadowRoot
    if (this.constructor.isLightDom) {
      shadowRoot = this
    } else {

      if (!this.shadowRoot) {
        shadowRoot = this.attachShadow({
          mode: 'open'
        })
      } else {
        shadowRoot = this.shadowRoot
        let fc
        while ((fc = shadowRoot.firstChild)) {
          shadowRoot.removeChild(fc)
        }
      }
    }

    if (this.constructor.css) {
      shadowRoot.appendChild(cssToDom(this.constructor.css))
    } else if (this.css) {
      shadowRoot.appendChild(
        cssToDom(typeof this.css === 'function' ? this.css() : this.css)
      )
    }

    this.beforeRender()
    options.afterInstall && options.afterInstall(this)

    const rendered = this.render(this.props, this.store)
    this.__hasChildren =
      Object.prototype.toString.call(rendered) === '[object Array]' &&
      rendered.length > 0

    this.rootNode = diff(null, rendered, null, this)
    this.rendered()

    if (this.props.css) {
      this._customStyleElement = cssToDom(this.props.css)
      this._customStyleContent = this.props.css
      shadowRoot.appendChild(this._customStyleElement)
    }

    if (isArray(this.rootNode)) {
      this.rootNode.forEach(function (item) {
        shadowRoot.appendChild(item)
      })
    } else {
      this.rootNode && shadowRoot.appendChild(this.rootNode)
    }
    this.installed()
    this._isInstalled = true
  }

  disconnectedCallback() {
    this.uninstall()
    this._isInstalled = false
    if (this.store) {
      if (options.isMultiStore) {
        for (let key in this.store) {
          const current = this.store[key]
          removeItem(this, current.instances)
          removeItem(this, current.updateSelfInstances)
        }
      } else {
        removeItem(this, this.store.instances)
        removeItem(this, this.store.updateSelfInstances)
      }
    }
  }

  update(ignoreAttrs, updateSelf) {
    this._willUpdate = true
    this.beforeUpdate()
    this.beforeRender()
    //fix null !== undefined
    if (this._customStyleContent != this.props.css) {
      this._customStyleContent = this.props.css
      this._customStyleElement.textContent = this._customStyleContent
    }
    this.attrsToProps(ignoreAttrs)

    const rendered = this.render(this.props, this.store)
    this.rendered()
    this.__hasChildren =
      this.__hasChildren ||
      (Object.prototype.toString.call(rendered) === '[object Array]' &&
        rendered.length > 0)

    this.rootNode = diff(
      this.rootNode,
      rendered,
      this.constructor.isLightDom ? this : this.shadowRoot,
      this,
      updateSelf
    )
    this._willUpdate = false
    this.updated()
  }

  forceUpdate() {
    this.update(true)
  }

  updateProps(obj) {
    Object.keys(obj).forEach(key => {
      this.props[key] = obj[key]
      if (this.prevProps) {
        this.prevProps[key] = obj[key]
      }
    })
    this.forceUpdate()
  }

  updateSelf(ignoreAttrs) {
    this.update(ignoreAttrs, true)
  }

  removeAttribute(key) {
    super.removeAttribute(key)
    //Avoid executing removeAttribute methods before connectedCallback
    this._isInstalled && this.update()
  }

  setAttribute(key, val) {
    if (val && typeof val === 'object') {
      super.setAttribute(key, JSON.stringify(val))
    } else {
      super.setAttribute(key, val)
    }
    //Avoid executing setAttribute methods before connectedCallback
    this._isInstalled && this.update()
  }

  pureRemoveAttribute(key) {
    super.removeAttribute(key)
  }

  pureSetAttribute(key, val) {
    super.setAttribute(key, val)
  }

  attrsToProps(ignoreAttrs) {
    if (options.ignoreAttrs || ignoreAttrs) return
    const ele = this
    ele.props['css'] = ele.getAttribute('css')
    const attrs = this.constructor.propTypes
    if (!attrs) return
    Object.keys(attrs).forEach(key => {
      const type = attrs[key]
      const val = ele.getAttribute(hyphenate(key))
      if (val !== null) {
        switch (type) {
          case String:
            ele.props[key] = val
            break
          case Number:
            ele.props[key] = Number(val)
            break
          case Boolean:
            if (val === 'false' || val === '0') {
              ele.props[key] = false
            } else {
              ele.props[key] = true
            }
            break
          case Array:
          case Object:
            if (val[0] === ':') {
              ele.props[key] = getValByPath(val.substr(1), Omi.$)
            } else {
              ele.props[key] = JSON.parse(
                val
                  .replace(/(['"])?([a-zA-Z0-9_-]+)(['"])?:([^\/])/g, '"$2":$4')
                  .replace(/'([\s\S]*?)'/g, '"$1"')
                  .replace(/,(\s*})/g, '$1')
              )
            }
            break
        }
      } else {
        if (
          ele.constructor.defaultProps &&
          ele.constructor.defaultProps.hasOwnProperty(key)
        ) {
          ele.props[key] = ele.constructor.defaultProps[key]
        } else {
          ele.props[key] = null
        }
      }
    })
  }

  fire(name, data) {
    this.dispatchEvent(
      new CustomEvent(name, {
        detail: data
      })
    )
  }

  beforeInstall() { }

  install() { }

  afterInstall() { }

  installed() { }

  uninstall() { }

  beforeUpdate() { }

  updated() { }

  beforeRender() { }

  rendered() { }

  receiveProps() { }
}
<|endoftext|>