<commit_before>var emr = (function($) {

    var accentMap = {
        "ä": "a", "á": "a", "à": "a", "â": "a", "ã": "a",
        "Ä": "A", "Á": "A", "À": "A", "Â": "A", "Ã": "A",
        "é": "e", "è": "e", "ê": "e", "ë": "e", "œ": "e","æ":"e",
        "É": "E", "È": "E", "Ê": "E", "Ë": "E",
        "ï": "i", "ì": "i", "í": "i", "î": "i",
        "Ï": "I", "Ì": "I", "Í": "I", "Î": "I",
        "ö": "o", "ó": "o", "ò": "o", "ô": "o", "õ": "o",
        "Ö": "O", "Ó": "O", "Ò": "O", "Ô": "O", "Õ": "O",
        "ü": "u", "ú": "u", "ù": "u", "û": "u",
        "Ü": "U", "Ú": "U", "Ù": "U", "Û": "U",
        "ÿ": "y", "Ÿ": "Y", "ñ": "n", "Ñ": "N",
        "ç": "c", "Ç": "C", "ß": "s"
    };

    var toQueryString = function(options) {
        var ret = "?";
        if (options) {
            for (key in options) {
                var val = options[key];
                if ($.isArray(val)) {
                    for (ind in val) {
                        ret += key + '=' + encodeURIComponent(val[ind]) + '&';
                    }
                } else {
                    ret += key + '=' + encodeURIComponent(val) + '&';
                }
            }
        }
        return ret;
    };

    var requireOptions = function() {
        var opts = arguments[0];
        for (var i = 1; i < arguments.length; ++i) {
            if (!opts[arguments[i]]) {
                throw "Missing option: " + arguments[i];
            }
        }
    };

    var jqObject = $();

    return {

        // just used in testing so we can replace the instance with a mock or spy as needed
        setJqObject: function(jqueryInstanceToSet)  {
            jqObject = jqueryInstanceToSet;
        },

        loadMessages: function(codes, callback) {
            if (!window.messages) {
                window.messages = {};
            }
            emr.getFragmentActionWithCallback("uicommons", "messages", "get", { codes: codes }, function(response) {
                for (var code in response) {
                    window.messages[code] = response[code];
                }
                if (callback) {
                    callback(window.messages);
                }
            });
        },

        loadGlobalProperties: function(properties, callback) {
            if (!window.globalProperties) {
                window.globalProperties = {};
            }
            emr.getFragmentActionWithCallback("uicommons", "globalProperties", "get", {properties: properties}, function(response) {
                for (var property in response) {
                    window.globalProperties[property] = response[property];
                }
                if (callback) {
                    callback(window.globalProperties);
                }
            });
        },

        message: function(code, defaultText) {
            if (window.messages) {
                var translated = window.messages[code];
                return translated ? translated : (defaultText ? defaultText : code);
            } else {
                return defaultText ? defaultText : code;
            }
        },

        serverValidationErrorMessage: function(response) {
            var errorMessages = [];
            if (response.data && response.data.error) {
                var errors = response.data.error;
                errorMessages.push(errors.message);
                if (errors.globalErrors) {
                    jq.each(errors.globalErrors, function(i, ele){
                        errorMessages.push(ele.message);
                    });
                }

                if (errors.fieldErrors) {
                    jq.map(errors.fieldErrors, function(fErrors, fName){
                        jq.each(fErrors, function(i, ele){
                            errorMessages.push(ele.message);
                        });
                    });
                }
            }

            var foundMessage = false;
            if(errorMessages.length > 0){
                jq.each(errorMessages, function(i, errMessage){
                    if(errMessage && jq.trim(errMessage) != ''){
                        if(foundMessage == false){
                            foundMessage = true;
                        }
                        emr.errorMessage(errMessage);
                    }
                });
            }

            if(foundMessage == false) {
                emr.errorMessage(this.message("uicommons.generalError.message", "An error has occurred"));
            }
        },

        serverGeneralErrorMessage: function() {
            emr.errorMessage(this.message("uicommons.generalError.message", "An error has occurred"));
        },

        navigateTo: function(opts) {
            var url = opts.url;
            if (opts.applicationUrl) {
                url = '/' + OPENMRS_CONTEXT_PATH
                    + (opts.applicationUrl.charAt(0) == '/' ? '' : '/')
                    + opts.applicationUrl;
            }
            if (opts.page) {
                var provider = opts.provider;
                if (provider == null) {
                    provider = "*"
                }
                url = this.pageLink(provider, opts.page, opts.query);
            }
            location.href = url;
        },

        pageLink: function(providerName, pageName, options) {
            var ret = '/' + OPENMRS_CONTEXT_PATH + '/' + providerName + '/' + pageName + '.page';
            return ret + toQueryString(options);
        },

        resourceLink: function(providerName, resourceName) {
            if (providerName == null)
                providerName = '*';
            return '/' + OPENMRS_CONTEXT_PATH + '/ms/uiframework/resource/' + providerName + '/' + resourceName;
        },

        fragmentActionLink: function(providerName, fragmentName, actionName, options) {
            var ret = '/' + OPENMRS_CONTEXT_PATH + '/' + providerName + '/' + fragmentName + '/' + actionName + '.action';
            return ret += toQueryString(options);
        },

        getFragmentActionWithCallback: function(providerName, fragmentName, actionName, options, callback, errorCallback) {
            if (!errorCallback) {
                errorCallback = function(xhr) {
                    emr.handleError(xhr);
                };
            }
            var url = this.fragmentActionLink(providerName, fragmentName, actionName, options);
            $.getJSON(url).success(callback).error(errorCallback);
        },

        /*
         * opts should contain:
         *   provider (defaults to '*')
         *   fragment
         *   action
         *   query, e.g. { q: "bob", checkedInAt: 5 }
         *   resultTarget e.g. '#search-results'
         *   resultTemplate (should be an underscore template)
         */
        ajaxSearch: function(opts) {
            var provider = opts.provider;
            if (!provider) {
                provider = '*';
            }
            var url = this.fragmentActionLink(provider, opts.fragment, opts.action);
            var target = $(opts.resultTarget);
            $.getJSON(url, opts.query)
                .success(function(data) {
                    target.html('');
                    jq.each(data, function(i, result) {
                        jq(opts.resultTemplate(result)).appendTo(target);
                    });
                })
                .error(function(err) {
                    emr.errorMessage(err);
                });
        },

        successMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'success',
                                              position: 'top-right',
                                              text:  emr.message(message) } );
        },

        errorMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'error',
                                              position: 'top-right',
                                              sticky: true,
                                              text:  emr.message(message) } );
        },

        alertMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'alert',
                                              position: 'top-right',
                                              text:  emr.message(message) } );
        },

        successAlert: function(message, options) {
            jqObject.toastmessage( 'showToast', { type: 'success',
                position: 'top-right',
                text:  emr.message(message),
                stayTime: 8000,
                close: options && options.close ? options.close : null } );
        },

        errorAlert: function(message, options) {
            jqObject.toastmessage( 'showToast', { type: 'error',
                position: 'top-right',
                text:  emr.message(message),
                stayTime: 8000,
                close: options && options.close ? options.close : null } )
        },

        handleError: function(xhr) {
            emr.handleParsedError(jq.parseJSON(xhr.responseText), xhr.status);
        },

        handleParsedError: function(data, status) {
            if (!emr.redirectOnAuthenticationFailure(status)) {
                if (data.globalErrors) {
                    emr.errorAlert(data.globalErrors[0]);
                } else if (data.error.message) {
                    emr.errorAlert(data.error.message);
                } else {
                    emr.errorAlert("Error!");
                }
            }
        },

        redirectOnAuthenticationFailure: function (status) {
            if (status == 403) {
                window.location = '/' + OPENMRS_CONTEXT_PATH;
                return true;
            }
            return false;
        },

        updateBreadcrumbs: function(extraBreadcrumbs) {
            if (!Array.isArray(breadcrumbs)) {
                // In case the page defines no JS var called breadcrumbs, but does have an html element with that id
                return;
            }
            var toUse = breadcrumbs;
            if (extraBreadcrumbs) {
                toUse = _.clone(breadcrumbs);
                if (extraBreadcrumbs == null || extraBreadcrumbs.length == 0) {
                    var index = toUse.length - 1;
                    var modified = _.clone(toUse[index]);
                    if(modified.link !=null){
                        modified.link = null;
                    }
                    toUse[index] = modified;
                }
                _.each(extraBreadcrumbs, function(item) {
                    toUse.push(item);
                })
            }
            $('#breadcrumbs').html(this.generateBreadcrumbHtml(toUse));
        },

        generateBreadcrumbHtml: function(breadcrumbs) {
            var breadcrumbTemplate = _.template($('#breadcrumb-template').html());
            var html = "";

            _.each(breadcrumbs, function(item, index) {
                html += breadcrumbTemplate({ breadcrumb: item, first: index == 0, last: index == breadcrumbs.length-1 });
            });
            return html;
        },

        /*
         * returns an object with show() and close() functions
         */
        setupConfirmationDialog: function(opts) {
            requireOptions(opts, 'selector');
            var element = $(opts.selector);
            element.hide();
            if (opts.actions) {
                if (opts.actions.confirm) {
                    element.find(".confirm").unbind('click');
                    element.find(".confirm").click(opts.actions.confirm);
                }
                if (opts.actions.cancel) {
                    element.find(".cancel").unbind('click');
                    element.find(".cancel").click(opts.actions.cancel);
                }
            }

            var dialogApi = {};
            var dialogOpts = {
                overlayClose: true,
                overlayId: "modal-overlay",
                opacity: 80,
                persist: true,
                closeClass: "cancel"
            };
            if (opts.dialogOpts) {
                $.extend(dialogOpts, opts.dialogOpts);
            }

            dialogApi.show = function() {
                $(opts.selector).modal(dialogOpts);
            };
            dialogApi.close = function() {
                $.modal.close();
            };

           return dialogApi;
        },

        stripAccents: function(term) {
            var ret = "";
            for ( var i = 0; i < term.length; i++ ) {
                ret += accentMap[ term.charAt(i) ] || term.charAt(i);
            }
            return ret;
        },

        formatAsHtml: function(str) {
            return str.replace(/\n/g,'<br/>')
        },

        isFeatureEnabled: function(key) {
            return featureToggles[key];
        },

        applyContextModel: function(input, contextModel) {
            if (contextModel) {
                $.each(contextModel, function(key, value) {
                    var pattern = new RegExp('{{\\s*' + key + '\\s*}}', 'g');
                    input = input.replace(pattern, value);
                });
            }
            return input;
        },

		getJSON: function(url, data, success) {
			var settings = {
				dataType: "json",
				url: url,
				data: data,
				success: success,
				beforeSend: function(xhr) {
					xhr.setRequestHeader('Disable-WWW-Authenticate', 'true');
				}
			};

			return jq.ajax(settings).fail(emr.handleNotLoggedIn);
		},

        handleNotLoggedIn: function(jqXHR) {
           if (jqXHR.status == 401 || jqXHR.status == 404) {
               if (confirm(emr.message("uicommons.notLoggedIn", "The operation cannot be completed, because you are no longer logged in. Do you want to go to login page?"))) {
                   window.location = "/" + OPENMRS_CONTEXT_PATH + "/login.htm";
               }
           }
        },

        domId: function(useIfNotNull, prefix, suffix) {
            if (useIfNotNull) {
                return useIfNotNull;
            }
            return (prefix ? prefix : 'id-') + Math.floor(Math.random() * 10000) + (suffix ? suffix : '');
        },

        isCompatibleWithSessionLocale: function(locale) {
            return window.sessionContext.locale.slice(0, locale.length) === locale ||
                locale.slice(0, window.sessionContext.locale.length) === window.sessionContext.locale;
        },

        focusNextElement: function(within, afterThisOne) {
            var fields = within.find('button,input,textarea,select');
            var index = fields.index(afterThisOne);
            if (index > -1 && (index + 1) < fields.length) {
                fields.eq(index + 1).focus();
            }
        },

        startsWithIgnoreCase: function(string, lookFor) {
            return string.toLowerCase().indexOf(lookFor.toLowerCase()) === 0;
        },

        hasMapping: function(concept, sourceName, code) {
            if (concept.mappings) {
                // this quick hack implementation presumes the concept mapping's display property is like "CIEL: 1513"
                var lookForDisplay = sourceName + ": " + code;
                return _.findWhere(concept.mappings, {display: lookForDisplay})
            }
            return null;
        },

        findConceptWithMapping: function(conceptArray, sourceName, code) {
            return _.find(conceptArray, function(concept) {
                return emr.hasMapping(concept, sourceName, code);
            });
        },

        // given a JS Date object, an existing Moment object, or ISO 8601 string,
        // returns a String properly formatted for a OpenMRS REST request
        // ** requires moment.js to be included on the page **
        formatDatetimeForREST: function(date) {
            return moment(date).format("YYYY-MM-DDTHH:mm:ss.SSSZZ");
        }

    };

})(jQuery);

var jq = jQuery;
_.templateSettings = {
    interpolate : /{{=(.+?)}}/g ,
    escape : /{{-(.+?)}}/g ,
    evaluate : /{{(.+?)}}/g
};
<commit_msg>RA-952: Unable to End Visit, Uncaught ReferenceError: Invalid left-hand side in assignment<commit_after>var emr = (function($) {

    var accentMap = {
        "ä": "a", "á": "a", "à": "a", "â": "a", "ã": "a",
        "Ä": "A", "Á": "A", "À": "A", "Â": "A", "Ã": "A",
        "é": "e", "è": "e", "ê": "e", "ë": "e", "œ": "e","æ":"e",
        "É": "E", "È": "E", "Ê": "E", "Ë": "E",
        "ï": "i", "ì": "i", "í": "i", "î": "i",
        "Ï": "I", "Ì": "I", "Í": "I", "Î": "I",
        "ö": "o", "ó": "o", "ò": "o", "ô": "o", "õ": "o",
        "Ö": "O", "Ó": "O", "Ò": "O", "Ô": "O", "Õ": "O",
        "ü": "u", "ú": "u", "ù": "u", "û": "u",
        "Ü": "U", "Ú": "U", "Ù": "U", "Û": "U",
        "ÿ": "y", "Ÿ": "Y", "ñ": "n", "Ñ": "N",
        "ç": "c", "Ç": "C", "ß": "s"
    };

    var toQueryString = function(options) {
        var ret = "?";
        if (options) {
            for (key in options) {
                var val = options[key];
                if ($.isArray(val)) {
                    for (ind in val) {
                        ret += key + '=' + encodeURIComponent(val[ind]) + '&';
                    }
                } else {
                    ret += key + '=' + encodeURIComponent(val) + '&';
                }
            }
        }
        return ret;
    };

    var requireOptions = function() {
        var opts = arguments[0];
        for (var i = 1; i < arguments.length; ++i) {
            if (!opts[arguments[i]]) {
                throw "Missing option: " + arguments[i];
            }
        }
    };

    var jqObject = $();

    return {

        // just used in testing so we can replace the instance with a mock or spy as needed
        setJqObject: function(jqueryInstanceToSet)  {
            jqObject = jqueryInstanceToSet;
        },

        loadMessages: function(codes, callback) {
            if (!window.messages) {
                window.messages = {};
            }
            emr.getFragmentActionWithCallback("uicommons", "messages", "get", { codes: codes }, function(response) {
                for (var code in response) {
                    window.messages[code] = response[code];
                }
                if (callback) {
                    callback(window.messages);
                }
            });
        },

        loadGlobalProperties: function(properties, callback) {
            if (!window.globalProperties) {
                window.globalProperties = {};
            }
            emr.getFragmentActionWithCallback("uicommons", "globalProperties", "get", {properties: properties}, function(response) {
                for (var property in response) {
                    window.globalProperties[property] = response[property];
                }
                if (callback) {
                    callback(window.globalProperties);
                }
            });
        },

        message: function(code, defaultText) {
            if (window.messages) {
                var translated = window.messages[code];
                return translated ? translated : (defaultText ? defaultText : code);
            } else {
                return defaultText ? defaultText : code;
            }
        },

        serverValidationErrorMessage: function(response) {
            var errorMessages = [];
            if (response.data && response.data.error) {
                var errors = response.data.error;
                errorMessages.push(errors.message);
                if (errors.globalErrors) {
                    jq.each(errors.globalErrors, function(i, ele){
                        errorMessages.push(ele.message);
                    });
                }

                if (errors.fieldErrors) {
                    jq.map(errors.fieldErrors, function(fErrors, fName){
                        jq.each(fErrors, function(i, ele){
                            errorMessages.push(ele.message);
                        });
                    });
                }
            }

            var foundMessage = false;
            if(errorMessages.length > 0){
                jq.each(errorMessages, function(i, errMessage){
                    if(errMessage && jq.trim(errMessage) != ''){
                        if(foundMessage == false){
                            foundMessage = true;
                        }
                        emr.errorMessage(errMessage);
                    }
                });
            }

            if(foundMessage == false) {
                emr.errorMessage(this.message("uicommons.generalError.message", "An error has occurred"));
            }
        },

        serverGeneralErrorMessage: function() {
            emr.errorMessage(this.message("uicommons.generalError.message", "An error has occurred"));
        },

        navigateTo: function(opts) {
            var url = opts.url;
            if (opts.applicationUrl) {
                url = '/' + OPENMRS_CONTEXT_PATH
                    + (opts.applicationUrl.charAt(0) == '/' ? '' : '/')
                    + opts.applicationUrl;
            }
            if (opts.page) {
                var provider = opts.provider;
                if (provider == null) {
                    provider = "*"
                }
                url = this.pageLink(provider, opts.page, opts.query);
            }
            location.href = url;
        },

        pageLink: function(providerName, pageName, options) {
            var ret = '/' + OPENMRS_CONTEXT_PATH + '/' + providerName + '/' + pageName + '.page';
            return ret + toQueryString(options);
        },

        resourceLink: function(providerName, resourceName) {
            if (providerName == null)
                providerName = '*';
            return '/' + OPENMRS_CONTEXT_PATH + '/ms/uiframework/resource/' + providerName + '/' + resourceName;
        },

        fragmentActionLink: function(providerName, fragmentName, actionName, options) {
            var ret = '/' + OPENMRS_CONTEXT_PATH + '/' + providerName + '/' + fragmentName + '/' + actionName + '.action';
            return ret += toQueryString(options);
        },

        getFragmentActionWithCallback: function(providerName, fragmentName, actionName, options, callback, errorCallback) {
            if (!errorCallback) {
                errorCallback = function(xhr) {
                    emr.handleError(xhr);
                };
            }
            var url = this.fragmentActionLink(providerName, fragmentName, actionName, options);
            $.getJSON(url).success(callback).error(errorCallback);
        },

        /*
         * opts should contain:
         *   provider (defaults to '*')
         *   fragment
         *   action
         *   query, e.g. { q: "bob", checkedInAt: 5 }
         *   resultTarget e.g. '#search-results'
         *   resultTemplate (should be an underscore template)
         */
        ajaxSearch: function(opts) {
            var provider = opts.provider;
            if (!provider) {
                provider = '*';
            }
            var url = this.fragmentActionLink(provider, opts.fragment, opts.action);
            var target = $(opts.resultTarget);
            $.getJSON(url, opts.query)
                .success(function(data) {
                    target.html('');
                    jq.each(data, function(i, result) {
                        jq(opts.resultTemplate(result)).appendTo(target);
                    });
                })
                .error(function(err) {
                    emr.errorMessage(err);
                });
        },

        successMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'success',
                                              position: 'top-right',
                                              text:  emr.message(message) } );
        },

        errorMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'error',
                                              position: 'top-right',
                                              sticky: true,
                                              text:  emr.message(message) } );
        },

        alertMessage: function(message) {
            jqObject.toastmessage( 'showToast', { type: 'alert',
                                              position: 'top-right',
                                              text:  emr.message(message) } );
        },

        successAlert: function(message, options) {
            jqObject.toastmessage( 'showToast', { type: 'success',
                position: 'top-right',
                text:  emr.message(message),
                stayTime: 8000,
                close: options && options.close ? options.close : null } );
        },

        errorAlert: function(message, options) {
            jqObject.toastmessage( 'showToast', { type: 'error',
                position: 'top-right',
                text:  emr.message(message),
                stayTime: 8000,
                close: options && options.close ? options.close : null } )
        },

        handleError: function(xhr) {
            emr.handleParsedError(jq.parseJSON(xhr.responseText), xhr.status);
        },

        handleParsedError: function(data, status) {
            if (!emr.redirectOnAuthenticationFailure(status)) {
                if (data.globalErrors) {
                    emr.errorAlert(data.globalErrors[0]);
                } else if (data.error.message) {
                    emr.errorAlert(data.error.message);
                } else {
                    emr.errorAlert("Error!");
                }
            }
        },

        redirectOnAuthenticationFailure: function (status) {
            if (status == 403) {
                window.location = '/' + OPENMRS_CONTEXT_PATH;
                return true;
            }
            return false;
        },

        updateBreadcrumbs: function(extraBreadcrumbs) {
            if (!Array.isArray(breadcrumbs)) {
                // In case the page defines no JS var called breadcrumbs, but does have an html element with that id
                return;
            }
            var toUse = breadcrumbs;
            if (extraBreadcrumbs) {
                toUse = _.clone(breadcrumbs);
                if (extraBreadcrumbs == null || extraBreadcrumbs.length == 0) {
                    var index = toUse.length - 1;
                    var modified = _.clone(toUse[index]);
                    if(modified.link !=null){
                        modified.link = null;
                    }
                    toUse[index] = modified;
                }
                _.each(extraBreadcrumbs, function(item) {
                    toUse.push(item);
                })
            }
            $('#breadcrumbs').html(this.generateBreadcrumbHtml(toUse));
        },

        generateBreadcrumbHtml: function(breadcrumbs) {
            var breadcrumbTemplate = _.template($('#breadcrumb-template').html());
            var html = "";

            _.each(breadcrumbs, function(item, index) {
                html += breadcrumbTemplate({ breadcrumb: item, first: index == 0, last: index == breadcrumbs.length-1 });
            });
            return html;
        },

        /*
         * returns an object with show() and close() functions
         */
        setupConfirmationDialog: function(opts) {
            requireOptions(opts, 'selector');
            var element = $(opts.selector);
            element.hide();
            if (opts.actions) {
                if (opts.actions.confirm) {
                    element.find(".confirm").unbind('click');
                    element.find(".confirm").click(opts.actions.confirm);
                }
                if (opts.actions.cancel) {
                    element.find(".cancel").unbind('click');
                    element.find(".cancel").click(opts.actions.cancel);
                }
            }

            var dialogApi = {};
            var dialogOpts = {
                overlayClose: true,
                overlayId: "modal-overlay",
                opacity: 80,
                persist: true,
                closeClass: "cancel"
            };
            if (opts.dialogOpts) {
                $.extend(dialogOpts, opts.dialogOpts);
            }

            dialogApi.show = function() {
                $(opts.selector).modal(dialogOpts);
            };
            dialogApi.close = function() {
                $.modal.close();
            };

           return dialogApi;
        },

        stripAccents: function(term) {
            var ret = "";
            for ( var i = 0; i < term.length; i++ ) {
                ret += accentMap[ term.charAt(i) ] || term.charAt(i);
            }
            return ret;
        },

        formatAsHtml: function(str) {
            return str.replace(/\n/g,'<br/>')
        },

        isFeatureEnabled: function(key) {
            return featureToggles[key];
        },

        applyContextModel: function(input, contextModel) {
            if (contextModel) {

                $.each(contextModel, function(key, value) {
                    var pattern = new RegExp('{{\\s*' + key + '\\s*}}', 'g');
                    input = input.replace(pattern, value);
                });

                // handle substitions for patterns that have already been escaped
                $.each(contextModel, function(key, value) {
                    var pattern = new RegExp('%7B%7Bs*' + key + 's*%7D%7D', 'g');
                    input = input.replace(pattern, value);
                });
            }
            return input;
        },

		getJSON: function(url, data, success) {
			var settings = {
				dataType: "json",
				url: url,
				data: data,
				success: success,
				beforeSend: function(xhr) {
					xhr.setRequestHeader('Disable-WWW-Authenticate', 'true');
				}
			};

			return jq.ajax(settings).fail(emr.handleNotLoggedIn);
		},

        handleNotLoggedIn: function(jqXHR) {
           if (jqXHR.status == 401 || jqXHR.status == 404) {
               if (confirm(emr.message("uicommons.notLoggedIn", "The operation cannot be completed, because you are no longer logged in. Do you want to go to login page?"))) {
                   window.location = "/" + OPENMRS_CONTEXT_PATH + "/login.htm";
               }
           }
        },

        domId: function(useIfNotNull, prefix, suffix) {
            if (useIfNotNull) {
                return useIfNotNull;
            }
            return (prefix ? prefix : 'id-') + Math.floor(Math.random() * 10000) + (suffix ? suffix : '');
        },

        isCompatibleWithSessionLocale: function(locale) {
            return window.sessionContext.locale.slice(0, locale.length) === locale ||
                locale.slice(0, window.sessionContext.locale.length) === window.sessionContext.locale;
        },

        focusNextElement: function(within, afterThisOne) {
            var fields = within.find('button,input,textarea,select');
            var index = fields.index(afterThisOne);
            if (index > -1 && (index + 1) < fields.length) {
                fields.eq(index + 1).focus();
            }
        },

        startsWithIgnoreCase: function(string, lookFor) {
            return string.toLowerCase().indexOf(lookFor.toLowerCase()) === 0;
        },

        hasMapping: function(concept, sourceName, code) {
            if (concept.mappings) {
                // this quick hack implementation presumes the concept mapping's display property is like "CIEL: 1513"
                var lookForDisplay = sourceName + ": " + code;
                return _.findWhere(concept.mappings, {display: lookForDisplay})
            }
            return null;
        },

        findConceptWithMapping: function(conceptArray, sourceName, code) {
            return _.find(conceptArray, function(concept) {
                return emr.hasMapping(concept, sourceName, code);
            });
        },

        // given a JS Date object, an existing Moment object, or ISO 8601 string,
        // returns a String properly formatted for a OpenMRS REST request
        // ** requires moment.js to be included on the page **
        formatDatetimeForREST: function(date) {
            return moment(date).format("YYYY-MM-DDTHH:mm:ss.SSSZZ");
        }

    };

})(jQuery);

var jq = jQuery;
_.templateSettings = {
    interpolate : /{{=(.+?)}}/g ,
    escape : /{{-(.+?)}}/g ,
    evaluate : /{{(.+?)}}/g
};
<|endoftext|>


<commit_before>"use strict";

var View = require("substance-application").View;

// Lens.Outline
// ==========================================================================
//
// Takes a surface, which is projected to a minimap

var Outline = function(surface) {
  View.call(this);

  this.surface = surface;

  // Initial view state, telling which node is selected and which are highlighted
  this.state = {
    selectedNode: null,
    highlightedNodes: []
  };

  this.$el.addClass('lens-outline');

  _.bindAll(this, 'mouseDown', 'mouseUp', 'mouseMove');

  // Mouse event handlers
  // --------

  this.$el.mousedown(this.mouseDown);
  this.$el.mousemove(this.mouseMove);
  this.$el.mouseup(this.mouseUp);
};

Outline.Prototype = function() {

  // Render Document Outline
  // -------------
  //
  // Renders outline and calculates bounds
  // Used for auto-selecting current heading

  this.render = function() {
    var that = this;
    var totalHeight = 0;

    // TODO: rather use recalibrate workflow
    this.$el.empty();
    this.$el.append('

');

    // Initial Calculations
    // --------

    var contentHeight = this.surface.$('.nodes').height();
    var panelHeight = this.surface.$el.height(); // this.$el.height();

    var factor = (contentHeight / panelHeight);
    this.factor = factor;

    // Render nodes
    // --------

    var nodes = this.surface.writer.getNodes();

    _.each(nodes, function(node) {
      var dn = this.surface.$('#'+node.id);
      var height = dn.outerHeight(true) / factor;

      // Outline node construction
      var $node = $('
')
        .attr({
          id: 'outline_'+node.id,
        })
        .addClass(node.type)
        .css({
          "position": "absolute",
          "height": height-1,
          "top": totalHeight
        }).append('
');

      this.$el.append($node);
      totalHeight += height;
    }, this);

    // Init scroll pos
    var scrollTop = that.surface.$el.scrollTop();

    this.$('.visible-area').css({
      "top": scrollTop / factor,
      "height": panelHeight / factor
    });

    // Listen for scroll changes update outline scroll pos accordingly
    // --------
    //

    this.surface.$el.unbind('scroll');
    this.surface.$el.scroll(function() {
      var scrollTop = that.surface.$el.scrollTop();

      // Update visible area
      that.$('.visible-area').css({
        "top": scrollTop / factor,
        "height": that.$el.height() / factor
      });
      //   that.markActiveHeading();
    });

    return this;
  };

  // Adjust
  // -------------
  //
  // Recalibrate (.e.g after resize)

  // thais.adjust = function() {

  //   // Current scrolltop
  //   var scrollTop = that.surface.$el.scrollTop();

  //   // Update visible area
  //   that.$('.visible-area').css({
  //     "top": scrollTop / factor,
  //     "height": that.$el.height() / factor
  //   });
  //     //   that.markActiveHeading();
  // };

  // Update Outline
  // -------------
  //
  // Usage:
  //
  // outline.update({
  //   selectedNode: "node_14",
  //   highlightNodes: []
  // })

  this.update = function(state) {
    this.state = state;

    // Reset
    this.$('.node').removeClass('selected').removeClass('highlighted');

    // 1. Mark selected node
    this.$('#outline_' + state.selectedNode).addClass('selected');

    // 2. Mark highlighted nodes
    _.each(state.highlightedNodes, function(n) {
      this.$('#outline_'+n).addClass('highlighted');
    }, this);
  };

  // Handle Mouse down event
  // -----------------
  //

  this.mouseDown = function(e) {
    this.mouseDown = true;
    var y = e.pageY;

    // Find offset to visible-area.top
    this.offset = y - $('.visible-area').position().top;
    return false;
  };

  // Handle Mouse Up
  // -----------------
  //
  // Mouse lifted, no scroll anymore

  this.mouseUp = function() {
    this.mouseDown = false;
  },

  // Handle Scroll
  // -----------------
  //
  // Handle scroll event
  // .visible-area handle

  this.mouseMove = function(e) {
    if (this.mouseDown) {
      var y = e.pageY;
      // find offset to visible-area.top
      var scroll = (y - this.offset)*this.factor;
      this.surface.$el.scrollTop(scroll);
    }
  };
};

Outline.Prototype.prototype = View.prototype;
Outline.prototype = new Outline.Prototype();

module.exports = Outline;
<commit_msg>Writer -> Controller.<commit_after>"use strict";

var View = require("substance-application").View;

// Lens.Outline
// ==========================================================================
//
// Takes a surface, which is projected to a minimap

var Outline = function(surface) {
  View.call(this);

  this.surface = surface;

  // Initial view state, telling which node is selected and which are highlighted
  this.state = {
    selectedNode: null,
    highlightedNodes: []
  };

  this.$el.addClass('lens-outline');

  _.bindAll(this, 'mouseDown', 'mouseUp', 'mouseMove');

  // Mouse event handlers
  // --------

  this.$el.mousedown(this.mouseDown);
  this.$el.mousemove(this.mouseMove);
  this.$el.mouseup(this.mouseUp);
};

Outline.Prototype = function() {

  // Render Document Outline
  // -------------
  //
  // Renders outline and calculates bounds
  // Used for auto-selecting current heading

  this.render = function() {
    var that = this;
    var totalHeight = 0;

    // TODO: rather use recalibrate workflow
    this.$el.empty();
    this.$el.append('

');

    // Initial Calculations
    // --------

    var contentHeight = this.surface.$('.nodes').height();
    var panelHeight = this.surface.$el.height(); // this.$el.height();

    var factor = (contentHeight / panelHeight);
    this.factor = factor;

    // Render nodes
    // --------

    var nodes = this.surface.doc.getNodes();

    _.each(nodes, function(node) {
      var dn = this.surface.$('#'+node.id);
      var height = dn.outerHeight(true) / factor;

      // Outline node construction
      var $node = $('
')
        .attr({
          id: 'outline_'+node.id,
        })
        .addClass(node.type)
        .css({
          "position": "absolute",
          "height": height-1,
          "top": totalHeight
        }).append('
');

      this.$el.append($node);
      totalHeight += height;
    }, this);

    // Init scroll pos
    var scrollTop = that.surface.$el.scrollTop();

    this.$('.visible-area').css({
      "top": scrollTop / factor,
      "height": panelHeight / factor
    });

    // Listen for scroll changes update outline scroll pos accordingly
    // --------
    //

    this.surface.$el.unbind('scroll');
    this.surface.$el.scroll(function() {
      var scrollTop = that.surface.$el.scrollTop();

      // Update visible area
      that.$('.visible-area').css({
        "top": scrollTop / factor,
        "height": that.$el.height() / factor
      });
      //   that.markActiveHeading();
    });

    return this;
  };

  // Adjust
  // -------------
  //
  // Recalibrate (.e.g after resize)

  // thais.adjust = function() {

  //   // Current scrolltop
  //   var scrollTop = that.surface.$el.scrollTop();

  //   // Update visible area
  //   that.$('.visible-area').css({
  //     "top": scrollTop / factor,
  //     "height": that.$el.height() / factor
  //   });
  //     //   that.markActiveHeading();
  // };

  // Update Outline
  // -------------
  //
  // Usage:
  //
  // outline.update({
  //   selectedNode: "node_14",
  //   highlightNodes: []
  // })

  this.update = function(state) {
    this.state = state;

    // Reset
    this.$('.node').removeClass('selected').removeClass('highlighted');

    // 1. Mark selected node
    this.$('#outline_' + state.selectedNode).addClass('selected');

    // 2. Mark highlighted nodes
    _.each(state.highlightedNodes, function(n) {
      this.$('#outline_'+n).addClass('highlighted');
    }, this);
  };

  // Handle Mouse down event
  // -----------------
  //

  this.mouseDown = function(e) {
    this.mouseDown = true;
    var y = e.pageY;

    // Find offset to visible-area.top
    this.offset = y - $('.visible-area').position().top;
    return false;
  };

  // Handle Mouse Up
  // -----------------
  //
  // Mouse lifted, no scroll anymore

  this.mouseUp = function() {
    this.mouseDown = false;
  },

  // Handle Scroll
  // -----------------
  //
  // Handle scroll event
  // .visible-area handle

  this.mouseMove = function(e) {
    if (this.mouseDown) {
      var y = e.pageY;
      // find offset to visible-area.top
      var scroll = (y - this.offset)*this.factor;
      this.surface.$el.scrollTop(scroll);
    }
  };
};

Outline.Prototype.prototype = View.prototype;
Outline.prototype = new Outline.Prototype();

module.exports = Outline;
<|endoftext|>


<commit_before>'use strict'

// Mongodb dependency
const ObjectId = require('mongodb').ObjectId;
require('mongodb-toolkit');
// Internal dependency
const BateeqModels = require('bateeq-models');
const map = BateeqModels.map;
// External dependency
const BaseManager = require('module-toolkit').BaseManager;
const moment = require('moment');

module.exports = class MonthlyStockManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.InventoryMovement);
    }

    // GET START AND END YEAR BASED ON INVENTORY MOVEMENT
    _getFirstInventoryMovement() {
        return this.collection.find().sort({ date: 1 }).limit(1).toArray();
    }

    _getYearMonthsList(firstYear, lastYear, firstMonth, lastMonth) {
        let yearMonths = [];
        for (let i = firstYear; i <= lastYear; i++) {
            let each = this.__pushMonthBasedOnYear(i, firstYear, lastYear, firstMonth, lastMonth);
            yearMonths.push(each);
        }
        yearMonths.sort(function (a, b) { return b.year - a.year });
        return yearMonths;
    }

    __pushMonthBasedOnYear(currentYear, firstYear, lastYear, firstMonth, lastMonth) {
        let currentYearList = { year: currentYear, months: [] };
        if (currentYear === firstYear) {
            if (currentYear === lastYear) {
                for (let j = firstMonth; j <= lastMonth; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
            else {
                for (let j = firstMonth; j <= 11; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
        }
        else {
            if (currentYear === lastYear) {
                for (let j = 0; j <= lastMonth; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
            else {
                for (let j = 0; j <= 11; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }

        }
        return currentYearList;
    }

    __getMonthName(monthNumber) {
        switch (monthNumber) {
            case 0:
                return { id: 0, name: "Januari" };
            case 1:
                return { id: 1, name: "Februari" };
            case 2:
                return { id: 2, name: "Maret" };
            case 3:
                return { id: 3, name: "April" };
            case 4:
                return { id: 4, name: "Mei" };
            case 5:
                return { id: 5, name: "Juni" };
            case 6:
                return { id: 6, name: "Juli" };
            case 7:
                return { id: 7, name: "Agustus" };
            case 8:
                return { id: 8, name: "September" };
            case 9:
                return { id: 9, name: "Oktober" };
            case 10:
                return { id: 10, name: "November" };
            case 11:
                return { id: 11, name: "Desember" };
        }
    }

    getYearMonthList() {
        let firstIM = this._getFirstInventoryMovement();
        let now = moment();
        return new Promise((resolve, reject) => {
            firstIM
                .then(results => {
                    let firstYear = results[0].date.getFullYear();
                    let firstMonth = results[0].date.getMonth();
                    let lastYear = parseInt(now.format('YYYY'));
                    let lastMonth = parseInt(now.format('MM')) - 1;
                    let yearMonthList = this._getYearMonthsList(firstYear, lastYear, firstMonth, lastMonth);
                    resolve(yearMonthList);
                })
        })
    }
    //

    // GET LOCALE TIME IN JAKARTA
    __getLocaleDateOfMonth(year, month, isStartOf) {
        let locale = isStartOf ? moment().month(month).year(year).startOf('month') : moment().month(month).year(year).endOf('month');
        return locale;
    }

    _setDateOfMonth(month, year) {
        let firstDay = this.__getLocaleDateOfMonth(year, month, true).format();
        let lastDay = this.__getLocaleDateOfMonth(year, month, false).format();
        return {
            firstDay: new Date(firstDay),
            lastDay: new Date(lastDay)
        }
    }
    //

    // GET INVENTORY ON PARTICULAR MONTH -> INVENTORY WITH MOVEMENT (END OF THE MONTH AND BEFORE EARLY OF THE MONTH)
    _getCurrentStocks(day) {
        let currentStocks = [
            { $match: { date: { $lte: day } } },
            { $sort: { date: -1 } },
            {
                $group: {
                    _id: { storageCode: "$storage.code", itemCode: "$item.code" },
                    storageName: { $first: "$storage.name" },
                    quantity: { $first: "$after" },
                    hpp: { $first: { $cond: { if: { $ne: ["$item.domesticCOGS", 0] }, then: "$item.domesticCOGS", else: "$item.internationalCOGS" } } },
                    sale: { $first: { $cond: { if: { $ne: ["$item.domesticSale", 0] }, then: "$item.domesticSale", else: "$item.internationalSale" } } }
                }
            },
            {
                $project: {
                    _id: 1,
                    storageName: "$storageName",
                    quantity: "$quantity",
                    hpp: { $multiply: ["$quantity", "$hpp"] },
                    sale: { $multiply: ["$quantity", "$sale"] }
                }
            },
            {
                $group: {
                    _id: { storageCode: "$_id.storageCode" },
                    storageName: { $first: "$storageName" },
                    quantity: { $sum: "$quantity" },
                    hpp: { $sum: "$hpp" },
                    sale: { $sum: "$sale" }
                }
            }
        ]
        let query = this.collection.aggregate(currentStocks).toArray();
        return query;
    }

    _combineStocks(earliest, latest) {
        let allStocks = [];
        latest.forEach(ls => {
            let stock = {
                code: ls._id.storageCode,
                name: ls.storageName,
                latestQuantity: ls.quantity,
                latestHPP: ls.hpp,
                latestSale: ls.sale
            };
            let found = earliest.find(es => { return es._id.storageCode === ls._id.storageCode });
            if (found) {
                stock.earliestQuantity = found.quantity;
                stock.earliestHPP = found.hpp;
                stock.earliestSale = found.sale;
            }
            else {
                stock.earliestQuantity = 0;
                stock.earliestHPP = 0;
                stock.earliestSale = 0;
            }
            allStocks.push(stock);
        })
        return allStocks;
    }

    getOverallStock(month, year) {
        let date = this._setDateOfMonth(month, year);
        let earliestStocksQuery = this._getCurrentStocks(date.firstDay);
        let latestStocksQuery = this._getCurrentStocks(date.lastDay);
        return new Promise((resolve, reject) => {
            return Promise.all([earliestStocksQuery, latestStocksQuery])
                .then(results => {
                    let earliestStocks = results[0];
                    let latestStocks = results[1];
                    let finalStocks = this._combineStocks(earliestStocks, latestStocks);
                    resolve(finalStocks);
                })
        })
    }
    //

    // GET LATEST ITEM WITH PARTICULAR MONTH AND STORAGE CODE
    _getCurrentItems(code, day) {
        let currentItems = [
            {
                $match: {
                    date: { $lte: day },
                    "storage.code": code
                }
            },
            { $sort: { date: -1 } },
            {
                $group: {
                    _id: { itemCode: "$item.code" },
                    itemName: { $first: "$item.name" },
                    quantity: { $first: "$after" },
                    hpp: { $first: { $cond: { if: { $ne: ["$item.domesticCOGS", 0] }, then: "$item.domesticCOGS", else: "$item.internationalCOGS" } } },
                    sale: { $first: { $cond: { if: { $ne: ["$item.domesticSale", 0] }, then: "$item.domesticSale", else: "$item.internationalSale" } } }
                }
            },
            {
                $project: {
                    itemCode: "$_id.itemCode",
                    itemName: "$itemName",
                    quantity: "$quantity",
                    totalHPP: { $multiply: ["$quantity", "$hpp"] },
                    totalSale: { $multiply: ["$quantity", "$sale"] }
                }
            },
            { $match: { quantity: { $ne: 0 } } }
        ]
        let query = this.collection.aggregate(currentItems).toArray();
        return query;
    }

    getStockInStorage(storageCode, month, year) {
        let date = this._setDateOfMonth(month, year);
        let latestItemsQuery = this._getCurrentItems(storageCode, date.lastDay);
        return new Promise((resolve, reject) => {
            return latestItemsQuery
                .then(latestItems => {
                    resolve(latestItems);
                })
        })
    }
    //
}<commit_msg>Add console log again<commit_after>'use strict'

// Mongodb dependency
const ObjectId = require('mongodb').ObjectId;
require('mongodb-toolkit');
// Internal dependency
const BateeqModels = require('bateeq-models');
const map = BateeqModels.map;
// External dependency
const BaseManager = require('module-toolkit').BaseManager;
const moment = require('moment');

module.exports = class MonthlyStockManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.InventoryMovement);
    }

    // GET START AND END YEAR BASED ON INVENTORY MOVEMENT
    _getFirstInventoryMovement() {
        return this.collection.find().sort({ date: 1 }).limit(1).toArray();
    }

    _getYearMonthsList(firstYear, lastYear, firstMonth, lastMonth) {
        let yearMonths = [];
        for (let i = firstYear; i <= lastYear; i++) {
            let each = this.__pushMonthBasedOnYear(i, firstYear, lastYear, firstMonth, lastMonth);
            yearMonths.push(each);
        }
        yearMonths.sort(function (a, b) { return b.year - a.year });
        return yearMonths;
    }

    __pushMonthBasedOnYear(currentYear, firstYear, lastYear, firstMonth, lastMonth) {
        let currentYearList = { year: currentYear, months: [] };
        if (currentYear === firstYear) {
            if (currentYear === lastYear) {
                for (let j = firstMonth; j <= lastMonth; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
            else {
                for (let j = firstMonth; j <= 11; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
        }
        else {
            if (currentYear === lastYear) {
                for (let j = 0; j <= lastMonth; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }
            else {
                for (let j = 0; j <= 11; j++) {
                    let currentMonth = this.__getMonthName(j);
                    currentYearList.months.push(currentMonth);
                }
            }

        }
        return currentYearList;
    }

    __getMonthName(monthNumber) {
        switch (monthNumber) {
            case 0:
                return { id: 0, name: "Januari" };
            case 1:
                return { id: 1, name: "Februari" };
            case 2:
                return { id: 2, name: "Maret" };
            case 3:
                return { id: 3, name: "April" };
            case 4:
                return { id: 4, name: "Mei" };
            case 5:
                return { id: 5, name: "Juni" };
            case 6:
                return { id: 6, name: "Juli" };
            case 7:
                return { id: 7, name: "Agustus" };
            case 8:
                return { id: 8, name: "September" };
            case 9:
                return { id: 9, name: "Oktober" };
            case 10:
                return { id: 10, name: "November" };
            case 11:
                return { id: 11, name: "Desember" };
        }
    }

    getYearMonthList() {
        let firstIM = this._getFirstInventoryMovement();
        let now = moment();
        return new Promise((resolve, reject) => {
            firstIM
                .then(results => {
                    let firstYear = results[0].date.getFullYear();
                    let firstMonth = results[0].date.getMonth();
                    let lastYear = parseInt(now.format('YYYY'));
                    let lastMonth = parseInt(now.format('MM')) - 1;
                    let yearMonthList = this._getYearMonthsList(firstYear, lastYear, firstMonth, lastMonth);
                    resolve(yearMonthList);
                })
        })
    }
    //

    // GET LOCALE TIME IN JAKARTA
    __getLocaleDateOfMonth(year, month, isStartOf) {
        let locale = isStartOf ? moment().month(month).year(year).startOf('month') : moment().month(month).year(year).endOf('month');
        return locale;
    }

    _setDateOfMonth(month, year) {
        let firstDay = this.__getLocaleDateOfMonth(year, month, true).format();
        let lastDay = this.__getLocaleDateOfMonth(year, month, false).format();
        return {
            firstDay: new Date(firstDay),
            lastDay: new Date(lastDay)
        }
    }
    //

    // GET INVENTORY ON PARTICULAR MONTH -> INVENTORY WITH MOVEMENT (END OF THE MONTH AND BEFORE EARLY OF THE MONTH)
    _getCurrentStocks(day) {
        let currentStocks = [
            { $match: { date: { $lte: day } } },
            { $sort: { date: -1 } },
            {
                $group: {
                    _id: { storageCode: "$storage.code", itemCode: "$item.code" },
                    storageName: { $first: "$storage.name" },
                    quantity: { $first: "$after" },
                    hpp: { $first: { $cond: { if: { $ne: ["$item.domesticCOGS", 0] }, then: "$item.domesticCOGS", else: "$item.internationalCOGS" } } },
                    sale: { $first: { $cond: { if: { $ne: ["$item.domesticSale", 0] }, then: "$item.domesticSale", else: "$item.internationalSale" } } }
                }
            },
            {
                $project: {
                    _id: 1,
                    storageName: "$storageName",
                    quantity: "$quantity",
                    hpp: { $multiply: ["$quantity", "$hpp"] },
                    sale: { $multiply: ["$quantity", "$sale"] }
                }
            },
            {
                $group: {
                    _id: { storageCode: "$_id.storageCode" },
                    storageName: { $first: "$storageName" },
                    quantity: { $sum: "$quantity" },
                    hpp: { $sum: "$hpp" },
                    sale: { $sum: "$sale" }
                }
            }
        ]
        let query = this.collection.aggregate(currentStocks).toArray();
        return query;
    }

    _combineStocks(earliest, latest) {
        let allStocks = [];
        console.log(earliest);
        console.log(latest);
        latest.forEach(ls => {
            let stock = {
                code: ls._id.storageCode,
                name: ls.storageName,
                latestQuantity: ls.quantity,
                latestHPP: ls.hpp,
                latestSale: ls.sale
            };
            let found = earliest.find(es => { return es._id.storageCode === ls._id.storageCode });
            if (found) {
                stock.earliestQuantity = found.quantity;
                stock.earliestHPP = found.hpp;
                stock.earliestSale = found.sale;
            }
            else {
                stock.earliestQuantity = 0;
                stock.earliestHPP = 0;
                stock.earliestSale = 0;
            }
            allStocks.push(stock);
        })
        return allStocks;
    }

    getOverallStock(month, year) {
        let date = this._setDateOfMonth(month, year);
        let earliestStocksQuery = this._getCurrentStocks(date.firstDay);
        let latestStocksQuery = this._getCurrentStocks(date.lastDay);
        return new Promise((resolve, reject) => {
            return Promise.all([earliestStocksQuery, latestStocksQuery])
                .then(results => {
                    let earliestStocks = results[0];
                    let latestStocks = results[1];
                    let finalStocks = this._combineStocks(earliestStocks, latestStocks);
                    resolve(finalStocks);
                })
        })
    }
    //

    // GET LATEST ITEM WITH PARTICULAR MONTH AND STORAGE CODE
    _getCurrentItems(code, day) {
        let currentItems = [
            {
                $match: {
                    date: { $lte: day },
                    "storage.code": code
                }
            },
            { $sort: { date: -1 } },
            {
                $group: {
                    _id: { itemCode: "$item.code" },
                    itemName: { $first: "$item.name" },
                    quantity: { $first: "$after" },
                    hpp: { $first: { $cond: { if: { $ne: ["$item.domesticCOGS", 0] }, then: "$item.domesticCOGS", else: "$item.internationalCOGS" } } },
                    sale: { $first: { $cond: { if: { $ne: ["$item.domesticSale", 0] }, then: "$item.domesticSale", else: "$item.internationalSale" } } }
                }
            },
            {
                $project: {
                    itemCode: "$_id.itemCode",
                    itemName: "$itemName",
                    quantity: "$quantity",
                    totalHPP: { $multiply: ["$quantity", "$hpp"] },
                    totalSale: { $multiply: ["$quantity", "$sale"] }
                }
            },
            { $match: { quantity: { $ne: 0 } } }
        ]
        let query = this.collection.aggregate(currentItems).toArray();
        return query;
    }

    getStockInStorage(storageCode, month, year) {
        let date = this._setDateOfMonth(month, year);
        let latestItemsQuery = this._getCurrentItems(storageCode, date.lastDay);
        return new Promise((resolve, reject) => {
            return latestItemsQuery
                .then(latestItems => {
                    resolve(latestItems);
                })
        })
    }
    //
}<|endoftext|>


<commit_before>import includePaths		from 'rollup-plugin-includepaths';
//import nodeResolve	from 'rollup-plugin-node-resolve';
//import nodent			from 'rollup-plugin-nodent';

export default {
	'output': {
		'format': 'es'
	},
	'plugins': [
		includePaths({
			'paths': [
				'.output',
				'.output/external',
				'.output/custom',
			],
//			'include': {
//				'preact':'output/external/preact/preact.o.js'
//			},
			'extensions': ['.es6.js'],
		}),

		// Sorry, we need to temporarily disable this, until nodent fully supports rest-spread
//		nodent({
//			'promises': true,
//			'noRuntime': true,
//			//'sourcemap': true,
//			//'es6target': true,
//		}),

//		nodeResolve({
//			'jsnext': true
//		}),
	]
};
<commit_msg>restore nodent support<commit_after>import includePaths		from 'rollup-plugin-includepaths';
//import nodeResolve	from 'rollup-plugin-node-resolve';
import nodent			from 'rollup-plugin-nodent';

export default {
	'output': {
		'format': 'es'
	},
	'plugins': [
		includePaths({
			'paths': [
				'.output',
				'.output/external',
				'.output/custom',
			],
//			'include': {
//				'preact':'output/external/preact/preact.o.js'
//			},
			'extensions': ['.es6.js'],
		}),

		// NOTE: nodent doesn't fully supports rest-spread (yet). Neither does Buble/Rollup though
		nodent({
			'promises': true,
			'noRuntime': true,
			//'sourcemap': true,
			//'es6target': true,
		}),

//		nodeResolve({
//			'jsnext': true
//		}),
	]
};
<|endoftext|>


<commit_before>
function Packet(id, p) {
  this.id = id;

  this.p = p;
}
<commit_msg>update packet<commit_after>
function Packet(sourceMAC, targetMAC, payload) {
  this.sourceMAC = sourceMAC;
  this.targetMac = targetMAC;
  this.payload = payload;
}
<|endoftext|>


<commit_before>var goods = [
    {'w':3,'v':4},
    {'w':4,'v':5},
    {'w':2,'v':3}
];
var num = goods.length;
var limit = 7;
var dp = [];
var i,j,k;
var defaultVal = 0;
var valIdName = function (i, j) {
    return 'v-' + i + '-' + j;
};
var goodsIdName = function (i) {
    return 'goods-' + i;
};

var explain = '入れる品物の
種類数＼重さ';
var dpTableHtml = '

' + explain + '	';
for (i = 0; i <= limit; i++){
    dpTableHtml += '' + i + '	';
}
dpTableHtml += '
';
for (i = 0; i <= num; i++){
    for(j = 0; j <= limit; j++){
        if (j === 0) dpTableHtml += '
' + i + '	';
        dpTableHtml += '' + defaultVal + '	';
        if (j === limit) dpTableHtml += '
';
    }
}
dpTableHtml += '
';
document.getElementById('dp').innerHTML = dpTableHtml;

var goodsTableBody = '';
for (i = 0; i < num; i++){
    goodsTableBody += '
';
    goodsTableBody += '' + (i + 1) + '	';
    goodsTableBody += '' + goods[i].v + '	';
    goodsTableBody += '' + goods[i].w + '	';
    goodsTableBody += '
';
}
document.querySelector('#goods tbody').innerHTML = goodsTableBody;

for (i = 0; i <= num; i++){
    dp[i] = [];
    for(j = 0; j <= limit; j++){
        dp[i][j] = defaultVal;
    }
}

var befValDom    = document.getElementById('bef-val');
var newValDom    = document.getElementById('new-val');
var addTotalWDom = document.getElementById('add-total-w');
var defaultColor = 'white';
var posDom       = null;
var reusePosDom  = null;
var befGoodsId   = -1;

var loopNum = 1;
var interval = 1000;
for (i = 0; i < num; i++) {
    for(j = 0; j <= limit; j++) {
        for(k = 0; k * goods[i].w <= j; k++) {
            setTimeout((function (i, j, k, loop) {
                return function () {
                    console.log('Loop[' + loop + ']i,j,k:' + i +',' + j + ',' + k);

                    if (befGoodsId !== i) {
                        var befGood = document.getElementById(goodsIdName(befGoodsId));
                        if (befGood) befGood.style.backgroundColor = defaultColor;
                        befGoodsId = i;
                        document.getElementById(goodsIdName(i)).style.backgroundColor = 'yellow';
                    }

                    if (posDom)     posDom.style.backgroundColor      = defaultColor;
                    if (reusePosDom)reusePosDom.style.backgroundColor = defaultColor;

                    var befPos    = i + 1;
                    var reusePos  = j - k * goods[i].w;
                    var reuseV    = dp[i][reusePos];
                    var befV      = dp[befPos][j];
                    var newV      = reuseV + k * goods[i].v;

                    posDom      = document.getElementById(valIdName(befPos, j));
                    reusePosDom = document.getElementById(valIdName(i, reusePos));
                    posDom.style.backgroundColor      = 'pink';
                    reusePosDom.style.backgroundColor = 'skyblue';

                    befValDom.innerHTML    = befV;
                    newValDom.innerHTML    = newV + '(' + reuseV + ' + '+ k + ' * ' + goods[i].v + ')';
                    addTotalWDom.innerHTML = k * goods[i].w + '(' + k + ' * ' + goods[i].w + ')';

                    dp[befPos][j] = Math.max(befV, newV);

                    document.getElementById(valIdName(befPos, j)).innerHTML = dp[i + 1][j];
                };
            })(i, j, k, loopNum), (loopNum++) * interval);
        }
    }
}

<commit_msg>無駄な計算を最適化した場合の可視化を実装した。<commit_after>var goods = [
    {'w':3,'v':4},
    {'w':4,'v':5},
    {'w':2,'v':3}
];
var num = goods.length;
var limit = 7;
var dp = [];
var i,j,k;
var defaultVal = 0;
var valIdName = function (i, j) {
    return 'v-' + i + '-' + j;
};
var goodsIdName = function (i) {
    return 'goods-' + i;
};

var explain = '入れる品物の
種類数＼重さ';
var dpTableHtml = '

' + explain + '	';
for (i = 0; i <= limit; i++){
    dpTableHtml += '' + i + '	';
}
dpTableHtml += '
';
for (i = 0; i <= num; i++){
    for(j = 0; j <= limit; j++){
        if (j === 0) dpTableHtml += '
' + i + '	';
        dpTableHtml += '' + defaultVal + '	';
        if (j === limit) dpTableHtml += '
';
    }
}
dpTableHtml += '
';
document.getElementById('dp').innerHTML = dpTableHtml;

var goodsTableBody = '';
for (i = 0; i < num; i++){
    goodsTableBody += '
';
    goodsTableBody += '' + (i + 1) + '	';
    goodsTableBody += '' + goods[i].v + '	';
    goodsTableBody += '' + goods[i].w + '	';
    goodsTableBody += '
';
}
document.querySelector('#goods tbody').innerHTML = goodsTableBody;

for (i = 0; i <= num; i++){
    dp[i] = [];
    for(j = 0; j <= limit; j++){
        dp[i][j] = defaultVal;
    }
}

var befValDom    = document.getElementById('bef-val');
var newValDom    = document.getElementById('new-val');
var addTotalWDom = document.getElementById('add-total-w');
var defaultColor = 'white';
var posDom       = null;
var reusePosDom  = null;
var befGoodsId   = -1;

var loopNum = 1;
var interval = 1000;
for (i = 0; i < num; i++) {
    for (j = 0; j <= limit; j++) {
        setTimeout((function (i, j, loop) {
            return function () {
                console.log('Loop[' + loop + ']i,j:' + i +',' + j);

                if (befGoodsId !== i) {
                    var befGood = document.getElementById(goodsIdName(befGoodsId));
                    if (befGood) befGood.style.backgroundColor = defaultColor;
                    befGoodsId = i;
                    document.getElementById(goodsIdName(i)).style.backgroundColor = 'yellow';
                }

                if (posDom)     posDom.style.backgroundColor      = defaultColor;
                if (reusePosDom)reusePosDom.style.backgroundColor = defaultColor;

                var nowPos    = i + 1;
                var reusePos  = j - goods[i].w;
                var reusable  = reusePos >= 0;
                var befV      = dp[i][j];
                var reuseV    = replasable ? dp[i + 1][reusePos] : befV;
                var newV      = replasable ? reuseV + goods[i].v : befV;

                posDom = document.getElementById(valIdName(nowPos, j));
                posDom.style.backgroundColor      = 'pink';
                if (replasable) {
                    reusePosDom = document.getElementById(valIdName(i + 1, reusePos));
                    reusePosDom.style.backgroundColor = 'skyblue';
                } else {
                    reusePosDom = document.getElementById(valIdName(i, j));
                    reusePosDom.style.backgroundColor = 'gray';
                }

                befValDom.innerHTML    = befV;
                newValDom.innerHTML    = !replasable ? '入れ替えられない' : newV + '(' + reuseV + ' + '+ goods[i].v + ')';
                addTotalWDom.innerHTML = !replasable ? '入れ替えられない' : goods[i].w : ;

                if (replasable) {
                    dp[nowPos][j] = Math.max(befV, newV);
                } else {
                    dp[nowPos][j] = dp[i][j];
                }

                document.getElementById(valIdName(nowPos, j)).innerHTML = dp[nowPos][j];
            };
        }(i, j, loopNum)), (loopNum++) * interval);
/*
        for(k = 0; k * goods[i].w <= j; k++) {
            setTimeout((function (i, j, k, loop) {
                return function () {
                    console.log('Loop[' + loop + ']i,j,k:' + i +',' + j + ',' + k);

                    if (befGoodsId !== i) {
                        var befGood = document.getElementById(goodsIdName(befGoodsId));
                        if (befGood) befGood.style.backgroundColor = defaultColor;
                        befGoodsId = i;
                        document.getElementById(goodsIdName(i)).style.backgroundColor = 'yellow';
                    }

                    if (posDom)     posDom.style.backgroundColor      = defaultColor;
                    if (reusePosDom)reusePosDom.style.backgroundColor = defaultColor;

                    var befPos    = i + 1;
                    var reusePos  = j - k * goods[i].w;
                    var reuseV    = dp[i][reusePos];
                    var befV      = dp[befPos][j];
                    var newV      = reuseV + k * goods[i].v;

                    posDom      = document.getElementById(valIdName(befPos, j));
                    reusePosDom = document.getElementById(valIdName(i, reusePos));
                    posDom.style.backgroundColor      = 'pink';
                    reusePosDom.style.backgroundColor = 'skyblue';

                    befValDom.innerHTML    = befV;
                    newValDom.innerHTML    = newV + '(' + reuseV + ' + '+ k + ' * ' + goods[i].v + ')';
                    addTotalWDom.innerHTML = k * goods[i].w + '(' + k + ' * ' + goods[i].w + ')';

                    dp[befPos][j] = Math.max(befV, newV);

                    document.getElementById(valIdName(befPos, j)).innerHTML = dp[i + 1][j];
                };
            })(i, j, k, loopNum), (loopNum++) * interval);
        }
*/
    }
}

<|endoftext|>


<commit_before>Package.describe({
    name: 'reywood:publish-composite',
    summary: 'Publish a set of related documents from multiple collections with a reactive join',
    version: '1.5.2',
    git: 'https://github.com/englue/meteor-publish-composite.git',
});

Package.onUse((api) => {
    api.versionsFrom('METEOR@1.4.3');
    api.use([
        'check',
        'ecmascript',
        'modules',
        'underscore',
    ], ['client', 'server']);
    api.mainModule('lib/publish_composite.js', 'server');
    api.addFiles([
        'lib/doc_ref_counter.js',
        'lib/logging.js',
        'lib/publication.js',
        'lib/subscription.js',
    ], 'server');

    api.export([
        'enableDebugLogging',
        'publishComposite',
    ], 'server');
});

Package.onTest((api) => {
    api.use([
        'ecmascript',
        'modules',
    ], ['client', 'server']);
    api.use([
        'practicalmeteor:mocha',
        'practicalmeteor:chai',
    ], 'client');
    api.use([
        'reywood:publish-composite',
        'mongo',
        'underscore',
    ], 'server');

    api.addFiles('tests/common.js', ['client', 'server']);
    api.addFiles('tests/client.js', 'client');
    api.addFiles('tests/server.js', 'server');
});
<commit_msg>Upgraded Meteor package versions to 1.6.1<commit_after>Package.describe({
    name: 'reywood:publish-composite',
    summary: 'Publish a set of related documents from multiple collections with a reactive join',
    version: '1.6.0',
    git: 'https://github.com/englue/meteor-publish-composite.git',
});

Package.onUse((api) => {
    api.versionsFrom('1.6.1');
    api.use([
        'check',
        'ecmascript',
        'modules',
        'underscore',
    ], ['client', 'server']);
    api.mainModule('lib/publish_composite.js', 'server');
    api.addFiles([
        'lib/doc_ref_counter.js',
        'lib/logging.js',
        'lib/publication.js',
        'lib/subscription.js',
    ], 'server');

    api.export([
        'enableDebugLogging',
        'publishComposite',
    ], 'server');
});

Package.onTest((api) => {
    api.use([
        'ecmascript',
        'modules',
    ], ['client', 'server']);
    api.use([
        'practicalmeteor:mocha',
        'practicalmeteor:chai',
    ], 'client');
    api.use([
        'reywood:publish-composite',
        'mongo',
        'underscore',
    ], 'server');

    api.addFiles('tests/common.js', ['client', 'server']);
    api.addFiles('tests/client.js', 'client');
    api.addFiles('tests/server.js', 'server');
});
<|endoftext|>


<commit_before>/*jshint -W117, -W097 */
'use strict';

Package.describe({
  name: 'velocity:core',
  summary: 'Velocity, a Meteor specific test-runner',
  version: '0.9.0',
  git: 'https://github.com/meteor-velocity/velocity.git',
  debugOnly: true
});

Npm.depends({
  'lodash': '2.4.1',
  'fs-extra': '0.18.0',
  'freeport':'1.0.4',
  'mongodb-uri': '0.9.7',
  'colors': '1.0.3',
  'tmp': '0.0.25'
});

Package.on_use(function (api) {

  var SERVER = 'server',
      CLIENT = 'client',
      BOTH = [CLIENT, SERVER];

  api.versionsFrom('METEOR@1.1.0.2');
  api.use('webapp');
  api.use('mongo');
  api.use('check');
  api.use('underscore'); // Used for the Function.bind polyfill
  api.use('velocity:chokidar@1.0.1_1', 'server');
  api.use('velocity:meteor-internals@1.1.0_7');
  api.use('velocity:source-map-support@0.3.2');
  api.use('sanjo:long-running-child-process@1.0.3', 'server');
  api.use('sanjo:meteor-files-helpers@1.1.0_4', 'server');

  api.export('Velocity', BOTH);
  api.export('VelocityTestFiles', BOTH);
  api.export('VelocityFixtureFiles', BOTH);
  api.export('VelocityTestReports', BOTH);
  api.export('VelocityAggregateReports', BOTH);
  api.export('VelocityLogs', BOTH);
  api.export('VelocityMirrors', BOTH);
  api.export('VelocityOptions', BOTH);

  api.add_files('src/source_map_support.js', BOTH);
  api.add_files('src/polyfills.js', BOTH);
  api.add_files('src/globals.js', BOTH);
  api.add_files('src/collections.js', BOTH);
  api.add_files('src/helpers.js', SERVER);
  api.add_files('src/core.js', SERVER);
  api.add_files('src/core-shared.js', BOTH);

  api.add_files('src/mirrors/Mirror.js', SERVER);
  api.add_files('src/mirrors/mirrorRegistrar.js', SERVER);

});
<commit_msg>Updates source-map-support to also install it on the server side<commit_after>/*jshint -W117, -W097 */
'use strict';

Package.describe({
  name: 'velocity:core',
  summary: 'Velocity, a Meteor specific test-runner',
  version: '0.9.0',
  git: 'https://github.com/meteor-velocity/velocity.git',
  debugOnly: true
});

Npm.depends({
  'lodash': '2.4.1',
  'fs-extra': '0.18.0',
  'freeport':'1.0.4',
  'mongodb-uri': '0.9.7',
  'colors': '1.0.3',
  'tmp': '0.0.25'
});

Package.on_use(function (api) {

  var SERVER = 'server',
      CLIENT = 'client',
      BOTH = [CLIENT, SERVER];

  api.versionsFrom('METEOR@1.1.0.2');
  api.use('webapp');
  api.use('mongo');
  api.use('check');
  api.use('underscore'); // Used for the Function.bind polyfill
  api.use('velocity:chokidar@1.0.1_1', 'server');
  api.use('velocity:meteor-internals@1.1.0_7');
  api.use('velocity:source-map-support@0.3.2_1');
  api.use('sanjo:long-running-child-process@1.0.3', 'server');
  api.use('sanjo:meteor-files-helpers@1.1.0_4', 'server');

  api.export('Velocity', BOTH);
  api.export('VelocityTestFiles', BOTH);
  api.export('VelocityFixtureFiles', BOTH);
  api.export('VelocityTestReports', BOTH);
  api.export('VelocityAggregateReports', BOTH);
  api.export('VelocityLogs', BOTH);
  api.export('VelocityMirrors', BOTH);
  api.export('VelocityOptions', BOTH);

  api.add_files('src/source_map_support.js', BOTH);
  api.add_files('src/polyfills.js', BOTH);
  api.add_files('src/globals.js', BOTH);
  api.add_files('src/collections.js', BOTH);
  api.add_files('src/helpers.js', SERVER);
  api.add_files('src/core.js', SERVER);
  api.add_files('src/core-shared.js', BOTH);

  api.add_files('src/mirrors/Mirror.js', SERVER);
  api.add_files('src/mirrors/mirrorRegistrar.js', SERVER);

});
<|endoftext|>


<commit_before>Package.describe({
  name: 'hubaaa:easy-meteor-settings',
  version: '0.1.0',
  // Brief, one-line summary of the package.
  summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use([
    'meteor',
    'underscore',
    'coffeescript',
    'practicalmeteor:loglevel@1.2.0_2',
    'practicalmeteor:chai@2.1.0_1',
    'practicalmeteor:underscore-deep@0.9.2'
  ]);

  api.addFiles('namespace.coffee');
  api.addFiles('EasyMeteorSettings.coffee');
});

Package.onTest(function(api) {
  api.use([
    'underscore',
    'coffeescript',
    'practicalmeteor:mocha@2.1.0_3'
  ]);

  api.use('hubaaa:easy-meteor-settings@0.1.0');

  api.addFiles('EasyMeteorSettingsTest.coffee');
});
<commit_msg>Update git url and bump version to 0.1.1<commit_after>Package.describe({
  name: 'hubaaa:easy-meteor-settings',
  version: '0.1.1',
  // Brief, one-line summary of the package.
  summary: "Easily read deep values from Meteor.settings using 'a.b.c'",
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/hubaaa/meteor-easy-meteor-settings',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use([
    'meteor',
    'underscore',
    'coffeescript',
    'practicalmeteor:loglevel@1.2.0_2',
    'practicalmeteor:chai@2.1.0_1',
    'practicalmeteor:underscore-deep@0.9.2'
  ]);

  api.addFiles('namespace.coffee');
  api.addFiles('EasyMeteorSettings.coffee');
});

Package.onTest(function(api) {
  api.use([
    'underscore',
    'coffeescript',
    'practicalmeteor:mocha@2.1.0_3'
  ]);

  api.use('hubaaa:easy-meteor-settings@0.1.1');

  api.addFiles('EasyMeteorSettingsTest.coffee');
});
<|endoftext|>


<commit_before>Package.describe({
  summary: "S3 signed uploads for meteorjs.",
  version: "0.0.1",
  git: "https://github.com/jimmiebtlr/s3-signed-upload.git"
});

Package.on_use(function(api){
  api.use(['mrt:aws-sdk@0.2.0'],'server');
  api.use(['aldeed:simple.schema']);
  api.export(['uploadFile'],'client');
  api.export(['S3SignedUploadTmp'],'server');

  api.add_files([
    'client.js'
  ], 'client');

  api.add_files([
    'server.js'
  ], 'server');
});
<commit_msg>Attach version to simple schema.<commit_after>Package.describe({
  summary: "S3 signed uploads for meteorjs.",
  version: "0.0.1",
  git: "https://github.com/jimmiebtlr/s3-signed-upload.git"
});

Package.on_use(function(api){
  api.use(['mrt:aws-sdk@0.2.0'],'server');
  api.use(['aldeed:simple-schema@0.7.0']);
  api.export(['uploadFile'],'client');
  api.export(['S3SignedUploadTmp'],'server');

  api.add_files([
    'client.js'
  ], 'client');

  api.add_files([
    'server.js'
  ], 'server');
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'aramk:collection-table',
  version: '0.4.0',
  summary: 'A CRUD table template for displaying collection items in Meteor.',
  git: 'https://github.com/aramk/meteor-collection-table.git'
});

Package.on_use(function(api) {
  api.versionsFrom('METEOR@0.9.0');
  api.use([
    'coffeescript',
    'templating',
    'underscore',
    'jquery',
    'less',
    'reactive-var@1.0.3',
    'aslagle:reactive-table@=0.8.1',
    'aramk:utility@0.6.0'
  ], 'client');
  api.use(['iron:router@1.0.7'], 'client', {weak: true});
  api.add_files([
    'src/collectionTable.html',
    'src/collectionTable.coffee',
    'src/collectionTable.less'
  ], 'client');
});
<commit_msg>Migrated to urbanetic:utility.<commit_after>Package.describe({
  name: 'aramk:collection-table',
  version: '0.4.0',
  summary: 'A CRUD table template for displaying collection items in Meteor.',
  git: 'https://github.com/aramk/meteor-collection-table.git'
});

Package.on_use(function(api) {
  api.versionsFrom('METEOR@0.9.0');
  api.use([
    'coffeescript',
    'templating',
    'underscore',
    'jquery',
    'less',
    'reactive-var@1.0.3',
    'aslagle:reactive-table@=0.8.1',
    'urbanetic:utility@1.0.0'
  ], 'client');
  api.use(['iron:router@1.0.7'], 'client', {weak: true});
  api.add_files([
    'src/collectionTable.html',
    'src/collectionTable.coffee',
    'src/collectionTable.less'
  ], 'client');
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'prosemeteor:prosemirror',
  version: '0.1.1',
  // Brief, one-line summary of the package.
  summary: 'Prosemirror integration for Meteor',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Npm.depends({
  //  using local version in imports/prosemirror for now because the latest publish was a month ago and collab module API has changed since then, we
  //  want the latest changes
  // prosemirror: '0.6.1'
});

Package.onUse(function(api) {
  api.versionsFrom('1.3');
  api.use('ecmascript');
  api.use('rocketchat:streamer@0.3.5');
  api.use('mdg:validated-method@1.1.0');
  api.use('didericis:callpromise-mixin@0.0.1');
  api.mainModule('lib/client/client-main.js', 'client');
  api.mainModule('lib/server/server-main.js', 'server');
});

Package.onTest(function(api) {
  api.use('ecmascript');
  api.use('tinytest');
  api.mainModule('lib/tests/prosemirror-tests.js');
});
<commit_msg>text format<commit_after>Package.describe({
  name: 'prosemeteor:prosemirror',
  version: '0.1.1',
  // Brief, one-line summary of the package.
  summary: 'Prosemirror integration for Meteor',
  // URL to the Git repository containing the source code for this package.
  git: '',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Npm.depends({
  //  using local version in imports/prosemirror for now because the latest publish was a month ago and collab module API has changed since then,
  // we want the latest changes
  // prosemirror: '0.6.1'
});

Package.onUse(function(api) {
  api.versionsFrom('1.3');
  api.use('ecmascript');
  api.use('rocketchat:streamer@0.3.5');
  api.use('mdg:validated-method@1.1.0');
  api.use('didericis:callpromise-mixin@0.0.1');
  api.mainModule('lib/client/client-main.js', 'client');
  api.mainModule('lib/server/server-main.js', 'server');
});

Package.onTest(function(api) {
  api.use('ecmascript');
  api.use('tinytest');
  api.mainModule('lib/tests/prosemirror-tests.js');
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'thepumpinglemma:flat',
  summary: 'Meteor package that wraps the flat NPM package. See https://github.com/hughsk/flat for more details.',
  version: '1.0.0',
  git: 'https://github.com/ThePumpingLemma/meteor-flat.git'
});

Npm.depends({
  'flat': '1.3.0'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0');
  api.export('Flat');
  api.addFiles('lib/fake-module.js', ['client']);
  api.addFiles('.npm/package/node_modules/flat/index.js', ['client']);
  api.addFiles('thepumpinglemma:flat.js');
});

<commit_msg>Update to flat 1.5.0.<commit_after>Package.describe({
  name: 'thepumpinglemma:flat',
  summary: 'Meteor package that wraps the flat NPM package. See https://github.com/hughsk/flat for more details.',
  version: '1.1.0',
  git: 'https://github.com/ThePumpingLemma/meteor-flat.git'
});

Npm.depends({
  'flat': '1.5.0'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0');
  api.export('Flat');
  api.addFiles('lib/fake-module.js', ['client']);
  api.addFiles('.npm/package/node_modules/flat/index.js', ['client']);
  api.addFiles('thepumpinglemma:flat.js');
});

<|endoftext|>


<commit_before>Package.describe({
  name: 'gbit:pagseguro',
  version: '0.0.1',
  summary: 'PagSeguro API for Meteor',
  git: '',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use('underscore@1.0.3');
  api.use('mongo@1.1.0');

  api.use('frozeman:persistent-minimongo@0.1.4');
  api.use('peerlibrary:xml2js@0.4.8_1');
  // api.use('meteorhacks:picker@1.0.3');
  api.use('iron:router@1.0.8');
  api.use('http@1.1.0');
  api.use('random');

  api.addFiles('lib/pagseguro.js', ['client', 'server']);
  api.addFiles('server/pagseguro.js', ['server']);
  api.addFiles('server/pagseguro-utils.js', ['server']);
  api.addFiles('server/config.js', ['server']);

  api.addFiles('client/pagseguro.js', ['client']);

  api.export('PagSeguro', ['client', 'server']);
  api.export('CartItems', ['server']);
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('gbit:faker@0.0.3');
  api.use('gbit:pagseguro');
  api.use('frozeman:persistent-minimongo');
  api.use('xolvio:http-interceptor@0.5.1');
  api.use('iron:router');
  api.use('random');

  api.addFiles('tests/_preps.js', ['client', 'server']);
  api.addFiles('tests/pagseguro-server.js', ['server']);
  api.addFiles('tests/pagseguro-client.js', ['client']);
});
<commit_msg>Add github url on packages.js<commit_after>Package.describe({
  name: 'gbit:pagseguro',
  version: '0.0.1',
  summary: 'PagSeguro API for Meteor',
  git: 'https://github.com/girassolbit/meteor-pagseguro',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');

  api.use('underscore@1.0.3');
  api.use('mongo@1.1.0');

  api.use('frozeman:persistent-minimongo@0.1.4');
  api.use('peerlibrary:xml2js@0.4.8_1');
  // api.use('meteorhacks:picker@1.0.3');
  api.use('iron:router@1.0.8');
  api.use('http@1.1.0');
  api.use('random');

  api.addFiles('lib/pagseguro.js', ['client', 'server']);
  api.addFiles('server/pagseguro.js', ['server']);
  api.addFiles('server/pagseguro-utils.js', ['server']);
  api.addFiles('server/config.js', ['server']);

  api.addFiles('client/pagseguro.js', ['client']);

  api.export('PagSeguro', ['client', 'server']);
  api.export('CartItems', ['server']);
});

Package.onTest(function(api) {
  api.use('tinytest');
  api.use('gbit:faker@0.0.3');
  api.use('gbit:pagseguro');
  api.use('frozeman:persistent-minimongo');
  api.use('xolvio:http-interceptor@0.5.1');
  api.use('iron:router');
  api.use('random');

  api.addFiles('tests/_preps.js', ['client', 'server']);
  api.addFiles('tests/pagseguro-server.js', ['server']);
  api.addFiles('tests/pagseguro-client.js', ['client']);
});
<|endoftext|>


<commit_before>Package.describe({
  summary: 'Accounts Templates for polymer',
  version: '1.13.1',
  name: 'useraccounts:polymer',
  git: 'https://github.com/meteor-useraccounts/polymer.git',
});

Package.on_use(function(api, where) {
  api.versionsFrom('METEOR@1.0');

  api.use([
    'templating',
    'underscore',
  ], 'client');

  api.use([
    'useraccounts:core',
  ], ['client', 'server']);

  // Requires all routing packages loads before this asking for weak dependencies.
  api.use('useraccounts:flow-routing@1.12.1', ['client', 'server'], {weak: true});
  api.use('useraccounts:iron-routing@1.12.1', ['client', 'server'], {weak: true});

  api.imply([
    'useraccounts:core@1.13.1',
  ], ['client', 'server']);

  api.add_files([
    'lib/at_error.html',
    'lib/at_error.js',
    'lib/at_form.html',
    'lib/at_form.js',
    'lib/at_input.html',
    'lib/at_input.js',
    'lib/at_message.html',
    'lib/at_message.js',
    'lib/at_nav_button.html',
    'lib/at_nav_button.js',
    'lib/at_oauth.html',
    'lib/at_oauth.js',
    'lib/at_pwd_form.html',
    'lib/at_pwd_form.js',
    'lib/at_pwd_form_btn.html',
    'lib/at_pwd_form_btn.js',
    'lib/at_pwd_link.html',
    'lib/at_pwd_link.js',
    'lib/at_reCaptcha.html',
    'lib/at_reCaptcha.js',
    'lib/at_result.html',
    'lib/at_result.js',
    'lib/at_sep.html',
    'lib/at_sep.js',
    'lib/at_signin_link.html',
    'lib/at_signin_link.js',
    'lib/at_signup_link.html',
    'lib/at_signup_link.js',
    'lib/at_social.html',
    'lib/at_social.js',
    'lib/at_terms_link.html',
    'lib/at_terms_link.js',
    'lib/at_resend_verification_email_link.html',
    'lib/at_resend_verification_email_link.js',
    'lib/at_title.html',
    'lib/at_title.js',
    'lib/full_page_at_form.html',
    'lib/at_polymer.css'
  ], ['client']);
});

Package.on_test(function(api) {
  api.use([
    'useraccounts:polymer',
    'useraccounts:core@1.13.1',
  ]);

  api.use([
    'accounts-password',
    'tinytest',
    'test-helpers'
  ], ['client', 'server']);

  api.add_files([
    'tests/tests.js'
  ], ['client', 'server']);
});
<commit_msg>fixed weak references<commit_after>Package.describe({
  summary: 'Accounts Templates for polymer',
  version: '1.13.1',
  name: 'useraccounts:polymer',
  git: 'https://github.com/meteor-useraccounts/polymer.git',
});

Package.on_use(function(api, where) {
  api.versionsFrom('METEOR@1.0');

  api.use([
    'templating',
    'underscore',
  ], 'client');

  api.use([
    'useraccounts:core',
  ], ['client', 'server']);

  // Requires all routing packages loads before this asking for weak dependencies.
  api.use('useraccounts:flow-routing@1.13.1', ['client', 'server'], {weak: true});
  api.use('useraccounts:iron-routing@1.13.1', ['client', 'server'], {weak: true});

  api.imply([
    'useraccounts:core@1.13.1',
  ], ['client', 'server']);

  api.add_files([
    'lib/at_error.html',
    'lib/at_error.js',
    'lib/at_form.html',
    'lib/at_form.js',
    'lib/at_input.html',
    'lib/at_input.js',
    'lib/at_message.html',
    'lib/at_message.js',
    'lib/at_nav_button.html',
    'lib/at_nav_button.js',
    'lib/at_oauth.html',
    'lib/at_oauth.js',
    'lib/at_pwd_form.html',
    'lib/at_pwd_form.js',
    'lib/at_pwd_form_btn.html',
    'lib/at_pwd_form_btn.js',
    'lib/at_pwd_link.html',
    'lib/at_pwd_link.js',
    'lib/at_reCaptcha.html',
    'lib/at_reCaptcha.js',
    'lib/at_result.html',
    'lib/at_result.js',
    'lib/at_sep.html',
    'lib/at_sep.js',
    'lib/at_signin_link.html',
    'lib/at_signin_link.js',
    'lib/at_signup_link.html',
    'lib/at_signup_link.js',
    'lib/at_social.html',
    'lib/at_social.js',
    'lib/at_terms_link.html',
    'lib/at_terms_link.js',
    'lib/at_resend_verification_email_link.html',
    'lib/at_resend_verification_email_link.js',
    'lib/at_title.html',
    'lib/at_title.js',
    'lib/full_page_at_form.html',
    'lib/at_polymer.css'
  ], ['client']);
});

Package.on_test(function(api) {
  api.use([
    'useraccounts:polymer',
    'useraccounts:core@1.13.1',
  ]);

  api.use([
    'accounts-password',
    'tinytest',
    'test-helpers'
  ], ['client', 'server']);

  api.add_files([
    'tests/tests.js'
  ], ['client', 'server']);
});
<|endoftext|>