<commit_before>var DNT = window.DNT || {};

(function (ns) {
    "use strict";

    ns.PicturesView = Backbone.View.extend({

        el: '#route-images',

        uploadUrl: '/upload/picture',

        events: {
            'sortstop #route-images-all-container': 'picturePositionUpdated',
            'updatePictureIndexes': 'updateIndexes'
        },

        $errorContainer: null,
        $errorMsg: null,

        initialize: function (options) {

            this.user = options.model.get('user');

            this.pictureCollection = this.model.get('pictureCollection');
            this.setupFileupload();

            this.pictureCollection.on('change:deleted', function () {
                // Render view when all pictures are removed
                if (this.pictureCollection.countPictures() === 0) {
                    this.render();
                }
            }, this);

            this.$('#route-images-all-container').sortable({
                items: '.picture-sortable',
                placeholder: 'sortable-placeholder col-sm-4'
            });

            this.$('#route-images-all-container').disableSelection();

            this.user = this.model.get('user');

            _.bindAll(this, 'picturePositionUpdated');
        },

        setupFileupload: function () {
            var ended = false;

            var that = this;
            var fileUpload = this.$('#fileupload').fileupload({
                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                sequentialUploads: true,
                url: this.uploadUrl,
                dataType: 'json',
                maxFileSize: 6000000,

                // Before sending file
                submit: function (e, data) {
                    ended = false;
                    that.endProcessBar();

                    return true;
                },

                // Current file upload progress
                progress: function (e, data) {
                    if (data.loaded === data.total) {
                        that.startProcessBar();
                    }
                },

                // Total upload progress
                progressall: function (e, data) {
                    if (data.loaded === data.total) {
                        ended = true;
                    }
                    that.renderProgressBar(data);
                },

                // On response from server
                done: function (e, data) {
                    that.endProcessBar();

                    if (ended) {
                        setTimeout(that.hideAndResetProgressBar, 1500);
                    }

                    $.each(data.result.files, function (index, file) {
                        that.addNewFile(file);
                    });
                },

                // On error
                fail: function (e, data) {
                    console.error(e, data)

                    that.endProcessBar();
                    that.hideAndResetProgressBar();
                    that.addUploadError('En feil oppstod ved bildeopplasting. Du kan prøve igjen med et annet bilde.');
                }
            });

            fileUpload.prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');

            fileUpload.on('fileuploadadd', function (e, data) {
                that.resetUploadErrors();
            });

            fileUpload.on('fileuploadprocessfail', function (e, data) {
                var errorMsg = '';

                if ((data.files.length > 0) && (data.files.length === data.originalFiles.length)) {
                    if (data.files.length === 1) {
                        errorMsg = 'Bildet du forsøkte å laste opp var for stort eller feil format, og ble ikke lastet opp. Hvert bilde må være mindre enn 6 MB og av typen gif, jpg eller png.';
                    } else {
                        errorMsg = 'Bildene du forsøkte å laste opp var for store eller feil format, og ble ikke lastet opp. Hvert bilde må være mindre enn 6 MB og av typen gif, jpg eller png.';
                    }

                } else {
                    errorMsg = 'Et eller flere av bildene var for store eller feil format, og ble ikke lastet opp. Hvert bilde må være mindre enn 6 MB og av typen gif, jpg eller png.. Bildene som ikke overstiger denne grensen blir lastet opp.';
                }

                that.addUploadError(errorMsg);
            });

        },

        startProcessBar: function (data) {
            this.$("#progress").addClass("progress-striped active");
            this.$("#progress .progress-bar").html('Behandler bilde...');
        },

        endProcessBar: function (data) {
            this.$("#progress .progress-bar").html('');
            this.$($("#progress").removeClass("progress-striped active hidden"));
        },

        renderProgressBar: function (data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            this.$("#progress .progress-bar").css('width', progress + '%');
        },

        hideAndResetProgressBar: function () {
            this.$($("#progress").addClass("hidden"));
            this.$("#progress .progress-bar").css('width', 0);
        },

        picturePositionUpdated: function (event, ui) {
            // Trig event on ui-item so that the correct picture item listener is trigged.
            // (In correct pictureView.js instance, which contains the model)
            ui.item.trigger('pictureDropped', ui.item.index());
        },

        updateIndexes: function (event, picture, index) {
            this.pictureCollection.reIndex(picture, index);
        },

        addNewFile: function (file) {
            file.ordinal = this.pictureCollection.getNextOrdinal();
            file.fotograf = {navn: this.user.get('navn'), epost: this.user.get('epost')};
            file.privat = {
                opprettet_av: {
                    id: this.user.get('id'),
                    navn: this.user.get('navn'),
                    epost: this.user.get('epost')
                }
            };
            var picture = new ns.Picture(file);
            this.pictureCollection.add(picture);
            this.appendPicture(picture);
            this.$("#noPictures").addClass("hidden");
            this.$("#hintInfo").removeClass("hidden");
            //setTimeout(this.hideAndResetProgressBar, 1500);
        },

        addUploadError: function (err) {
            var $error = $('

').text(err);
            this.$errorContainer.append($error);
        },

        resetUploadErrors: function () {
            this.$errorContainer.html('');
        },

        appendPicture: function (picture) {
            var view = new DNT.PictureView({model: picture, app: this.model});

            this.$("#route-images-all-container").append(view.render().el);
        },

        render: function () {

            if (this.pictureCollection.countPictures() === 0) {
                this.$("#noPictures").removeClass("hidden");
                this.$("#hintInfo").addClass("hidden");
            } else {
                this.$("#noPictures").addClass("hidden");
                this.$("#hintInfo").removeClass("hidden");
            }

            this.pictureCollection.each(this.appendPicture, this);

            this.$errorContainer = this.$el.find('[data-container-for="picture-upload-error"]');

            return this;
        }
    });
}(DNT));
<commit_msg>Removed variable not in use<commit_after>var DNT = window.DNT || {};

(function (ns) {
    "use strict";

    ns.PicturesView = Backbone.View.extend({

        el: '#route-images',

        uploadUrl: '/upload/picture',

        events: {
            'sortstop #route-images-all-container': 'picturePositionUpdated',
            'updatePictureIndexes': 'updateIndexes'
        },

        $errorContainer: null,

        initialize: function (options) {

            this.user = options.model.get('user');

            this.pictureCollection = this.model.get('pictureCollection');
            this.setupFileupload();

            this.pictureCollection.on('change:deleted', function () {
                // Render view when all pictures are removed
                if (this.pictureCollection.countPictures() === 0) {
                    this.render();
                }
            }, this);

            this.$('#route-images-all-container').sortable({
                items: '.picture-sortable',
                placeholder: 'sortable-placeholder col-sm-4'
            });

            this.$('#route-images-all-container').disableSelection();

            this.user = this.model.get('user');

            _.bindAll(this, 'picturePositionUpdated');
        },

        setupFileupload: function () {
            var ended = false;

            var that = this;
            var fileUpload = this.$('#fileupload').fileupload({
                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                sequentialUploads: true,
                url: this.uploadUrl,
                dataType: 'json',
                maxFileSize: 6000000,

                // Before sending file
                submit: function (e, data) {
                    ended = false;
                    that.endProcessBar();

                    return true;
                },

                // Current file upload progress
                progress: function (e, data) {
                    if (data.loaded === data.total) {
                        that.startProcessBar();
                    }
                },

                // Total upload progress
                progressall: function (e, data) {
                    if (data.loaded === data.total) {
                        ended = true;
                    }
                    that.renderProgressBar(data);
                },

                // On response from server
                done: function (e, data) {
                    that.endProcessBar();

                    if (ended) {
                        setTimeout(that.hideAndResetProgressBar, 1500);
                    }

                    $.each(data.result.files, function (index, file) {
                        that.addNewFile(file);
                    });
                },

                // On error
                fail: function (e, data) {
                    console.error(e, data)

                    that.endProcessBar();
                    that.hideAndResetProgressBar();
                    that.addUploadError('En feil oppstod ved bildeopplasting. Du kan prøve igjen med et annet bilde.');
                }
            });

            fileUpload.prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');

            fileUpload.on('fileuploadadd', function (e, data) {
                that.resetUploadErrors();
            });

            fileUpload.on('fileuploadprocessfail', function (e, data) {
                var errorMsg = '';

                if ((data.files.length > 0) && (data.files.length === data.originalFiles.length)) {
                    if (data.files.length === 1) {
                        errorMsg = 'Bildet du forsøkte å laste opp var for stort eller feil format, og ble ikke lastet opp. Hvert bilde må være mindre enn 6 MB og av typen gif, jpg eller png.';
                    } else {
                        errorMsg = 'Bildene du forsøkte å laste opp var for store eller feil format, og ble ikke lastet opp. Hvert bilde må være mindre enn 6 MB og av typen gif, jpg eller png.';
                    }

                } else {
                    errorMsg = 'Et eller flere av bildene var for store eller feil format, og ble ikke lastet opp. Hvert bilde må være mindre enn 6 MB og av typen gif, jpg eller png.. Bildene som ikke overstiger denne grensen blir lastet opp.';
                }

                that.addUploadError(errorMsg);
            });

        },

        startProcessBar: function (data) {
            this.$("#progress").addClass("progress-striped active");
            this.$("#progress .progress-bar").html('Behandler bilde...');
        },

        endProcessBar: function (data) {
            this.$("#progress .progress-bar").html('');
            this.$($("#progress").removeClass("progress-striped active hidden"));
        },

        renderProgressBar: function (data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            this.$("#progress .progress-bar").css('width', progress + '%');
        },

        hideAndResetProgressBar: function () {
            this.$($("#progress").addClass("hidden"));
            this.$("#progress .progress-bar").css('width', 0);
        },

        picturePositionUpdated: function (event, ui) {
            // Trig event on ui-item so that the correct picture item listener is trigged.
            // (In correct pictureView.js instance, which contains the model)
            ui.item.trigger('pictureDropped', ui.item.index());
        },

        updateIndexes: function (event, picture, index) {
            this.pictureCollection.reIndex(picture, index);
        },

        addNewFile: function (file) {
            file.ordinal = this.pictureCollection.getNextOrdinal();
            file.fotograf = {navn: this.user.get('navn'), epost: this.user.get('epost')};
            file.privat = {
                opprettet_av: {
                    id: this.user.get('id'),
                    navn: this.user.get('navn'),
                    epost: this.user.get('epost')
                }
            };
            var picture = new ns.Picture(file);
            this.pictureCollection.add(picture);
            this.appendPicture(picture);
            this.$("#noPictures").addClass("hidden");
            this.$("#hintInfo").removeClass("hidden");
            //setTimeout(this.hideAndResetProgressBar, 1500);
        },

        addUploadError: function (err) {
            var $error = $('

').text(err);
            this.$errorContainer.append($error);
        },

        resetUploadErrors: function () {
            this.$errorContainer.html('');
        },

        appendPicture: function (picture) {
            var view = new DNT.PictureView({model: picture, app: this.model});

            this.$("#route-images-all-container").append(view.render().el);
        },

        render: function () {

            if (this.pictureCollection.countPictures() === 0) {
                this.$("#noPictures").removeClass("hidden");
                this.$("#hintInfo").addClass("hidden");
            } else {
                this.$("#noPictures").addClass("hidden");
                this.$("#hintInfo").removeClass("hidden");
            }

            this.pictureCollection.each(this.appendPicture, this);

            this.$errorContainer = this.$el.find('[data-container-for="picture-upload-error"]');

            return this;
        }
    });
}(DNT));
<|endoftext|>


<commit_before>/*
 * grunt-war
 * https://github.com/wibobm/grunt-war
 *
 * Copyright (c) 2013 Morriscoding LLC
 * Licensed under the MIT license.
 */

module.exports = function (grunt) {

    'use strict';

    var path = require('path');
    var fs = require('fs');

    grunt.registerMultiTask('war', 'grunt-war generating war.', function () {

        var zip = require('node-zip')();
        var options = this.options({
            war_dist_folder: 'test',
            war_name: 'grunt',
            war_compression: 'DEFLATE',
            war_verbose: false,
            war_extras: [],
            webxml: webXML,
            webxml_welcome: 'index.html',
            webxml_display_name: 'Grunt WAR',
            webxml_webapp_version: '3.0',
            webxml_webapp_xmlns: 'http://java.sun.com/xml/ns/javaee',
            webxml_webapp_xmlns_xsi: 'http://www.w3.org/2001/XMLSchema-instance',
            webxml_webapp_xsi_schema_location: 'http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd',
            webxml_mime_mapping: [],
            webxml_webapp_extras: []
        });

        try {
            if (fs.existsSync(warName(options))) {
                fs.renameSync(warName(options ),warName(options) + '.old');
                fs.unlinkSync(warName(options) + '.old');
            }
        } catch (err) {
            grunt.log.error('Unable remove old ' + warName(options) + '  ' + err);
        }

        war(zip, options, [
            {filename: 'WEB-INF/web.xml', data: webXML},
            {filename: 'META-INF'}
        ]);

        war(zip, options, options.war_extras);

        this.files.forEach(function (each) {
            try {
                var file_name = each.src[0];
                if (!grunt.file.isDir(file_name)) {
                    var src_folder_length = 1 + Math.max(indexOfRegEx(file_name,(/\//)),indexOfRegEx(file_name,(/\\/)));

                    war(zip, options, {
                        filename: (file_name).substring(src_folder_length),
                        data: fs.readFileSync(file_name, 'binary')
                    });
                }
            } catch (err) {
                grunt.log.error('Unable to read file: (' + each.src + ') error: ' + err);
                throw err;
            }
        });

        try {
            log(options, 'Generating ' + warName(options));
            var data = zip.generate({type: 'nodebuffer', compression: options.war_compression});
            fs.writeFileSync(warName(options), data, 'binary');
        } catch (err) {
            grunt.log.error('Error creating war: ' + err);
            throw err;
        }
    });

    var webXML = function (opts) {
        var xml;

        xml = '<web-app';
        xml += ' version="' + opts.webxml_webapp_version + '"';
        xml += ' xmlns="' + opts.webxml_webapp_xmlns + '"';
        xml += ' xmlns:xsi="' + opts.webxml_webapp_xmlns_xsi + '"';
        xml += ' xsi:schemaLocation="' + opts.webxml_webapp_xsi_schema_location + '"';
        xml += '>\n';

        xml += '<display-name>' + opts.webxml_display_name + '</display-name>\n';
        xml += '<welcome-file-list>';
        xml += '<welcome-file>' + opts.webxml_welcome + '</welcome-file>';
        xml += '</welcome-file-list>\n';

        if (opts.webxml_mime_mapping) {
            opts.webxml_mime_mapping.forEach(function (mime_map) {
                xml += '<mime-mapping>';
                xml += '<extension>' + mime_map.extension + '</extension>';
                xml += '<mime-type>' + mime_map.mime_type + '</mime-type>';
                xml += '</mime-mapping>\n';
            });
        }

        if (Array.isArray(opts.webxml_webapp_extras)) {
            opts.webxml_webapp_extras.forEach(function (each) {
                if (typeof each === 'function') {
                    xml += each(opts);
                } else if (typeof each === 'string') {
                    xml += each;
                } else {
                    grunt.log.error('options.webxml_webapp_extras invalid: ' + each);
                }
            });
        }

        xml += '</web-app>\n';

        return xml;
    };

    var war = function (target, opts, extras) {
        if (extras === undefined) {
            return;
        }

        var addEntry = function (each) {
            try {
                if (typeof each.data === 'function') {
                    target.file(each.filename, each.data(opts), {binary:true});
                } else {
                    if (each.data === undefined) {
                        target.folder(each.filename);
                    } else {
                        target.file(each.filename, each.data, {binary:true});
                    }
                }
                log(opts, 'adding ' + each.filename);
            } catch (err) {
                grunt.log.error('Error adding: ' + each + ' to war: ' + err);
                throw err;
            }
        };

        if (Array.isArray(extras)) {
            extras.forEach(addEntry);
        } else if (extras.hasOwnProperty('filename')) {
            addEntry(extras);
        } else {
            grunt.log.error('Invalid format of war_extras element: ' + extras);
        }
    };

    var warName = function (opts) {
        return normalize(opts.war_dist_folder) + opts.war_name + ((/\.war$/).test(opts.war_name) ? '' : '.war');
    };

    var normalize = function (folder) {
        if ((/\/$/).test(folder) || (/\\$/).test(folder)) {
            return folder.substr(0, folder.length - 1) + path.sep;
        }
        return folder + path.sep;
    };

    var log = function (opts, msg) {
        if (opts.war_verbose) {
            grunt.log.writeln(msg);
        } else {
            grunt.log.debug(msg);
        }
    };

    var indexOfRegEx = function(str, regex) {
        var indexOf = str.search(regex);
        return (indexOf >= 0) ? (indexOf + (0)) : indexOf;
    };
};
<commit_msg>Test pull request<commit_after>/*
 * grunt-war
 * https://github.com/wibobm/grunt-war
 *
 * Copyright (c) 2013 Morriscoding LLC
 * Licensed under the MIT license.
 */

module.exports = function (grunt) {

    'use strict';

    var path = require('path');
    var fs = require('fs');

    grunt.registerMultiTask('war', 'grunt-war generating war.', function () {

        var zip = require('node-zip')();
        var options = this.options({
            war_dist_folder: 'test',
            war_name: 'grunt',
            war_compression: 'DEFLATE',
            war_verbose: false,
            war_extras: [],
            webxml: webXML,
            webxml_welcome: 'index.html',
            webxml_display_name: 'Grunt WAR',
            webxml_webapp_version: '3.0',
            webxml_webapp_xmlns: 'http://java.sun.com/xml/ns/javaee',
            webxml_webapp_xmlns_xsi: 'http://www.w3.org/2001/XMLSchema-instance',
            webxml_webapp_xsi_schema_location: 'http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd',
            webxml_mime_mapping: [],
            webxml_webapp_extras: []
        });

        try {
            if (fs.existsSync(warName(options))) {
                fs.renameSync(warName(options ),warName(options) + '.old');
                fs.unlinkSync(warName(options) + '.old');
            }
        } catch (err) {
            grunt.log.error('Unable remove old ' + warName(options) + '  ' + err);
        }

        war(zip, options, [
            {filename: 'WEB-INF/web.xml', data: webXML},
            {filename: 'META-INF'}
        ]);

        war(zip, options, options.war_extras);

        this.files.forEach(function (each) {
            try {
                var file_name = each.src[0];
                if (!grunt.file.isDir(file_name)) {
                    var src_folder_length = 1 + Math.max(indexOfRegEx(file_name,(/\//)),indexOfRegEx(file_name,(/\\/)));

                    grunt.log.writeln('old: ' + (file_name).substring(src_folder_length) + '  new: ' + each.dest);

                    war(zip, options, {
                        filename: (file_name).substring(src_folder_length),
                        data: fs.readFileSync(file_name, 'binary')
                    });
                }
            } catch (err) {
                grunt.log.error('Unable to read file: (' + each.src + ') error: ' + err);
                throw err;
            }
        });

        try {
            log(options, 'Generating ' + warName(options));
            var data = zip.generate({type: 'nodebuffer', compression: options.war_compression});
            fs.writeFileSync(warName(options), data, 'binary');
        } catch (err) {
            grunt.log.error('Error creating war: ' + err);
            throw err;
        }
    });

    var webXML = function (opts) {
        var xml;

        xml = '<web-app';
        xml += ' version="' + opts.webxml_webapp_version + '"';
        xml += ' xmlns="' + opts.webxml_webapp_xmlns + '"';
        xml += ' xmlns:xsi="' + opts.webxml_webapp_xmlns_xsi + '"';
        xml += ' xsi:schemaLocation="' + opts.webxml_webapp_xsi_schema_location + '"';
        xml += '>\n';

        xml += '<display-name>' + opts.webxml_display_name + '</display-name>\n';
        xml += '<welcome-file-list>';
        xml += '<welcome-file>' + opts.webxml_welcome + '</welcome-file>';
        xml += '</welcome-file-list>\n';

        if (opts.webxml_mime_mapping) {
            opts.webxml_mime_mapping.forEach(function (mime_map) {
                xml += '<mime-mapping>';
                xml += '<extension>' + mime_map.extension + '</extension>';
                xml += '<mime-type>' + mime_map.mime_type + '</mime-type>';
                xml += '</mime-mapping>\n';
            });
        }

        if (Array.isArray(opts.webxml_webapp_extras)) {
            opts.webxml_webapp_extras.forEach(function (each) {
                if (typeof each === 'function') {
                    xml += each(opts);
                } else if (typeof each === 'string') {
                    xml += each;
                } else {
                    grunt.log.error('options.webxml_webapp_extras invalid: ' + each);
                }
            });
        }

        xml += '</web-app>\n';

        return xml;
    };

    var war = function (target, opts, extras) {
        if (extras === undefined) {
            return;
        }

        var addEntry = function (each) {
            try {
                if (typeof each.data === 'function') {
                    target.file(each.filename, each.data(opts), {binary:true});
                } else {
                    if (each.data === undefined) {
                        target.folder(each.filename);
                    } else {
                        target.file(each.filename, each.data, {binary:true});
                    }
                }
                log(opts, 'adding ' + each.filename);
            } catch (err) {
                grunt.log.error('Error adding: ' + each + ' to war: ' + err);
                throw err;
            }
        };

        if (Array.isArray(extras)) {
            extras.forEach(addEntry);
        } else if (extras.hasOwnProperty('filename')) {
            addEntry(extras);
        } else {
            grunt.log.error('Invalid format of war_extras element: ' + extras);
        }
    };

    var warName = function (opts) {
        return normalize(opts.war_dist_folder) + opts.war_name + ((/\.war$/).test(opts.war_name) ? '' : '.war');
    };

    var normalize = function (folder) {
        if ((/\/$/).test(folder) || (/\\$/).test(folder)) {
            return folder.substr(0, folder.length - 1) + path.sep;
        }
        return folder + path.sep;
    };

    var log = function (opts, msg) {
        if (opts.war_verbose) {
            grunt.log.writeln(msg);
        } else {
            grunt.log.debug(msg);
        }
    };

    var indexOfRegEx = function(str, regex) {
        var indexOf = str.search(regex);
        return (indexOf >= 0) ? (indexOf + (0)) : indexOf;
    };
};
<|endoftext|>


<commit_before>module.exports = function ( grunt ) {

	// load NPM tasks
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-cssmin');

	var packages = [];
	var admin = grunt.file.readJSON( 'admin.json' );
	var cp = require( 'child_process' );
	var pathInfo = {
		source: '../src/',
		lib: '../lib/',
		dist: '../grunt-dist/',
		repo: 'http://j4f.jnw.io/repository'
	};

	grunt.initConfig( {
		path: pathInfo,
		pkg: grunt.file.readJSON( 'package.json' ),
		clean: {
			options: {
				force: true
			},
			build: [ '<%= path.dist %>' ]
		},
		copy: {
			lib: {
				files: [ {
					expand: true,
					src: [ '<%= path.lib %>**' ],
					dest: '<%= path.dist %>lib'
				} ]
			},
			src: {
				files: [
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>src/style/bootstrap/docs/assets/js/bootstrap*.js' ],
						dest: '<%= path.dist %>lib/bootstrap'
					},
					{
						expand: true,
						src: [
							'<%= path.source %>**',
							'!<%= path.source %>style/**',
							'<%= path.source %>style/**/package.json',
							'!<%= path.source %>style/bootstrap3/package.json'
						],
						dest: '<%= path.dist %>src'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-dark/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-white/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-wireframe/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-cerulean/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-flatly/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-united/images'
					}
				]
			}
		},
		uglify: {
			options: {
				banner: grunt.file.read( './copyright.txt', { encoding: 'UTF-8' } )
			},
			minify: {
				files: [ {
					expand: true,
					src: [ '<%= path.dist %>src/**/*.js', '!<%= path.dist %>src/style/**/*.js' ]
				} ]
			}
		},
		less: {
			compile: {
				files: [
					{
						'<%= path.dist %>src/style/theme-dark/cornerstone.css': '<%= path.source %>style/theme-dark/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/theme-white/cornerstone.css': '<%= path.source %>style/theme-white/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/theme-wireframe/cornerstone.css': '<%= path.source %>style/theme-wireframe/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/skin-cerulean/cerulean.css': '<%= path.source %>style/skin-cerulean/cerulean.less'
					},
					{
						'<%= path.dist %>src/style/skin-flatly/flatly.css': '<%= path.source %>style/skin-flatly/flatly.less'
					},
					{
						'<%= path.dist %>src/style/skin-united/united.css': '<%= path.source %>style/skin-united/united.less'
					}
				]
			}
		},
		cssmin: {
			options: {
				banner: grunt.file.read( './copyright.txt', { encoding: 'UTF-8' } )
			},
			minify: {
				files: [
					{
						'<%= path.dist %>src/style/theme-dark/cornerstone.css': '<%= path.dist %>src/style/theme-dark/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/theme-white/cornerstone.css': '<%= path.dist %>src/style/theme-white/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/theme-wireframe/cornerstone.css': '<%= path.dist %>src/style/theme-wireframe/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/skin-cerulean/cerulean.css': '<%= path.dist %>src/style/skin-cerulean/cerulean.css'
					},
					{
						'<%= path.dist %>src/style/skin-flatly/flatly.css': '<%= path.dist %>src/style/skin-flatly/flatly.css'
					},
					{
						'<%= path.dist %>src/style/skin-united/united.css': '<%= path.dist %>src/style/skin-united/united.css'
					}
				]
			}
		}
	} );

	grunt.registerTask( 'findPackages', function () {
		grunt.file.recurse( pathInfo.dist, function callback( abspath, rootdir, subdir, filename ) {
			if ( filename == 'package.json' ) packages.push( rootdir + subdir );
		} );
	} );

	grunt.registerTask( 'upload', function () {
		var done = this.async();
		var count = 0;

		grunt.util.async.whilst(
		    function () {
		    	return count < packages.length;
		    },
		    function ( callback ) {
		    	var child = cp.exec( 'jam publish ' + packages[ count ] + ' --force --repository ' + pathInfo.repo );

				child.stdin.setEncoding( 'utf-8' );
				child.stdout.pipe( process.stdout );

				child.stdout.on( 'data', function( chunk ) {
					if ( chunk.substr( -10 ) == 'Username: ' )
						child.stdin.write( admin.id + '\n' );
					else if ( chunk.substr( -10 ) == 'Password: ' )
						child.stdin.write( admin.pass + '\n' );
				} );
		        count++;
		        setTimeout( callback, 700 );
		    },
		    function ( err ) {
		    	if ( err ) {
		    		console.log( err );
		    		throw err;
		    	}
		        done();
		    }
		);
	} );

	grunt.registerTask( 'publish', [ 'findPackages', 'upload' ] );
	grunt.registerTask( 'build', [ 'clean', 'copy', 'uglify', 'less', 'cssmin' ] );
	grunt.registerTask( 'default', [ 'build', 'publish' ] );
}<commit_msg>skin less 빌드 후 파일이름을 cornerstone.css로 변경<commit_after>module.exports = function ( grunt ) {

	// load NPM tasks
	grunt.loadNpmTasks('grunt-contrib-uglify');
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-copy');
	grunt.loadNpmTasks('grunt-contrib-less');
	grunt.loadNpmTasks('grunt-contrib-cssmin');

	var packages = [];
	var admin = grunt.file.readJSON( 'admin.json' );
	var cp = require( 'child_process' );
	var pathInfo = {
		source: '../src/',
		lib: '../lib/',
		dist: '../grunt-dist/',
		repo: 'http://j4f.jnw.io/repository'
	};

	grunt.initConfig( {
		path: pathInfo,
		pkg: grunt.file.readJSON( 'package.json' ),
		clean: {
			options: {
				force: true
			},
			build: [ '<%= path.dist %>' ]
		},
		copy: {
			lib: {
				files: [ {
					expand: true,
					src: [ '<%= path.lib %>**' ],
					dest: '<%= path.dist %>lib'
				} ]
			},
			src: {
				files: [
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>src/style/bootstrap/docs/assets/js/bootstrap*.js' ],
						dest: '<%= path.dist %>lib/bootstrap'
					},
					{
						expand: true,
						src: [
							'<%= path.source %>**',
							'!<%= path.source %>style/**',
							'<%= path.source %>style/**/package.json',
							'!<%= path.source %>style/bootstrap3/package.json'
						],
						dest: '<%= path.dist %>src'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-dark/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-white/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/theme-wireframe/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-cerulean/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-flatly/images'
					},
					{
						expand: true,
						flatten: true,
						filter: 'isFile',
						src: [ '<%= path.source %>style/images/**' ],
						dest: '<%= path.dist %>src/style/skin-united/images'
					}
				]
			}
		},
		uglify: {
			options: {
				banner: grunt.file.read( './copyright.txt', { encoding: 'UTF-8' } )
			},
			minify: {
				files: [ {
					expand: true,
					src: [ '<%= path.dist %>src/**/*.js', '!<%= path.dist %>src/style/**/*.js' ]
				} ]
			}
		},
		less: {
			compile: {
				files: [
					{
						'<%= path.dist %>src/style/theme-dark/cornerstone.css': '<%= path.source %>style/theme-dark/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/theme-white/cornerstone.css': '<%= path.source %>style/theme-white/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/theme-wireframe/cornerstone.css': '<%= path.source %>style/theme-wireframe/cornerstone.less'
					},
					{
						'<%= path.dist %>src/style/skin-cerulean/cornerstone.css': '<%= path.source %>style/skin-cerulean/cerulean.less'
					},
					{
						'<%= path.dist %>src/style/skin-flatly/cornerstone.css': '<%= path.source %>style/skin-flatly/flatly.less'
					},
					{
						'<%= path.dist %>src/style/skin-united/cornerstone.css': '<%= path.source %>style/skin-united/united.less'
					}
				]
			}
		},
		cssmin: {
			options: {
				banner: grunt.file.read( './copyright.txt', { encoding: 'UTF-8' } )
			},
			minify: {
				files: [
					{
						'<%= path.dist %>src/style/theme-dark/cornerstone.css': '<%= path.dist %>src/style/theme-dark/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/theme-white/cornerstone.css': '<%= path.dist %>src/style/theme-white/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/theme-wireframe/cornerstone.css': '<%= path.dist %>src/style/theme-wireframe/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/skin-cerulean/cornerstone.css': '<%= path.dist %>src/style/skin-cerulean/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/skin-flatly/cornerstone.css': '<%= path.dist %>src/style/skin-flatly/cornerstone.css'
					},
					{
						'<%= path.dist %>src/style/skin-united/cornerstone.css': '<%= path.dist %>src/style/skin-united/cornerstone.css'
					}
				]
			}
		}
	} );

	grunt.registerTask( 'findPackages', function () {
		grunt.file.recurse( pathInfo.dist, function callback( abspath, rootdir, subdir, filename ) {
			if ( filename == 'package.json' ) packages.push( rootdir + subdir );
		} );
	} );

	grunt.registerTask( 'upload', function () {
		var done = this.async();
		var count = 0;

		grunt.util.async.whilst(
		    function () {
		    	return count < packages.length;
		    },
		    function ( callback ) {
		    	var child = cp.exec( 'jam publish ' + packages[ count ] + ' --force --repository ' + pathInfo.repo );

				child.stdin.setEncoding( 'utf-8' );
				child.stdout.pipe( process.stdout );

				child.stdout.on( 'data', function( chunk ) {
					if ( chunk.substr( -10 ) == 'Username: ' )
						child.stdin.write( admin.id + '\n' );
					else if ( chunk.substr( -10 ) == 'Password: ' )
						child.stdin.write( admin.pass + '\n' );
				} );
		        count++;
		        setTimeout( callback, 700 );
		    },
		    function ( err ) {
		    	if ( err ) {
		    		console.log( err );
		    		throw err;
		    	}
		        done();
		    }
		);
	} );

	grunt.registerTask( 'publish', [ 'findPackages', 'upload' ] );
	grunt.registerTask( 'build', [ 'clean', 'copy', 'uglify', 'less', 'cssmin' ] );
	grunt.registerTask( 'default', [ 'build', 'publish' ] );
}<|endoftext|>


<commit_before>/** @jsx React.DOM */
//= require jquery
//= require react

var TestUtils = React.addons.TestUtils;
var testRef = {
      "sections": {
        "Introduction": 1
      },
      "mentions": 1,
      "median_co_citations": 0.0,
      "citation_groups": [
        {
          "word_position": 21,
          "section": "Introduction",
          "context": "Bacon ipsum dolor sit amet jerky pork loin pariatur pork chop, salami do aliqua fatback. [1] Venison filet mignon exercitation adipisicing meatloaf veniam. \u2026",
          "references": [
            "pone.0000000-Doe1"
          ],
          "count": 1
        },
      ],
      "info": {
        "author": [
          {
            "given": "J",
            "family": "Doe"
          }
        ],
        "page": "79-95",
        "issued": {
          "date-parts": [
            [
              2007
            ]
          ]
        },
        "volume": "2",
        "title": "The best ever",
        "container-title": "Journal of Silly Studies",
        "container-type": "journal",
        "text": "Doe J ( 2007 ) The best ever. Journal of Silly Studies 2: 79\u201395."
      },
      "index": 1,
      "id": "pone.0000000-Doe1"
    };

var testRefWithDoi = $.extend(true, {}, testRef, {"info": {"doi": "10.12345/67890"}});

test("jquery quote id", function() {
    equal(jq("hello.world"), "#hello\\.world");
    equal(jq("hello:world"), "#hello\\:world");
    equal(jq("hello_world"), "#hello_world");
});

test("arraySorter", function () {
    equal(0, arraySorter({sort: ["a"]}, {sort: ["a"]}));
    equal(0, arraySorter({sort: [null]}, {sort: ["a"]}));
    equal(0, arraySorter({sort: ["a"]}, {sort: [null]}));
    equal(-1, arraySorter({sort: ["a"]}, {sort: ["b"]}));
    equal(0, arraySorter({sort: ["a", 1]}, {sort: ["a", 1]}));
    equal(-1, arraySorter({sort: ["a", 1]}, {sort: ["a", 2]}));
    equal(1, arraySorter({sort: ["a", 1]}, {sort: ["a", 0]}));
    var alpha = {sort: ["a", 0, 2, 3]};
    var beta =  {sort: ["a", 1, 1, 1]};
    equal([beta, alpha].sort(arraySorter)[0], alpha);
});

test("mkSortString", function () {
    strictEqual(mkSortString("Hello, world"), "hello world");
    strictEqual(mkSortString("the standard hello world of computing"), "standard hello world of computing");
});

test("mkSortField", function () {
    stop();
    $.getJSON("/papers/10.1371/journal.pone.0067380?format=json").
        done(function (fixture) {
            var ref = fixture.references["pone.0067380-Lowry1"];
            strictEqual("relative importance of growth and behaviour to elasmobranch suction-feeding performance over early ontogeny", mkSortField(ref, "title"));
            strictEqual(1, mkSortField(ref, "mentions"));
            strictEqual(6487, mkSortField(ref, "appearance"));
            strictEqual("lowry d", mkSortField(ref, "author"));
            strictEqual(2008, mkSortField(ref, "year"));
            strictEqual(55, mkSortField(ref, "index"));
            strictEqual("journal of royal society interface", mkSortField(ref, "journal"));

            /* reference with no info */
            var refNoInfo = {id: "pone.0067380-Wahnbaeck1",
                             info: {}};
            strictEqual(null, mkSortField(refNoInfo, "author"));
            strictEqual(null, mkSortField(refNoInfo, "year"));
            strictEqual(null, mkSortField(refNoInfo, "title"));
            strictEqual(null, mkSortField(refNoInfo, "journal"));

            /* anything else should return null */
            strictEqual(null, mkSortField(ref, "foobar"));
            start();
        });
});

test("mkSearchResultsFilter", function () {
    stop();
    $.getJSON("/papers/10.1371/journal.pone.0067380?format=json").
        done(function (fixture) {
            var filter = mkSearchResultsFilter(buildIndex(fixture.references), "odontodactylus");
            var results = _.filter(fixture.references, filter);
            strictEqual(results.length, 1);
            strictEqual(results[0].id, "pone.0067380-Patek1");
            start();
        });
});

test("buildIndex", function () {
    stop();
    $.getJSON("/papers/10.1371/journal.pone.0067380?format=json").
        done(function (fixture) {
            var idx = buildIndex(fixture.references);
            var results = idx.search("odontodactylus");
            strictEqual(results.length, 1);
            strictEqual(results[0].ref, "pone.0067380-Patek1");
            start();
        });
});

test("sortReferences", function () {
    stop();
    $.getJSON("/papers/10.1371/journal.pone.0067380?format=json").
        done(function (fixture) {
            _.each([{by: "appearance",
                     first: "pone.0067380-Clua1",
                     last: "pone.0067380-Lowry1",
                     sortableCount: 55,
                     unsortableCount: 0},
                    {by: "appearance+repeated",
                     first: "pone.0067380-Clua1",
                     last: "pone.0067380-Heithaus1",
                     sortableCount: 91,
                     unsortableCount: 0},
                    {by: "title",
                     first: "pone.0067380-Simon1",
                     last: "pone.0067380-Whitehead1",
                     sortableCount: 55,
                     unsortableCount: 0}],
                   function (d) {
                       var refs = fixture.references;
                       var results = sortReferences(refs, d.by);
                       strictEqual(results.unsortable.length, d.unsortableCount);
                       strictEqual(results.sorted.length, d.sortableCount);
                       strictEqual(results.sorted[0].data.id, d.first);
                       strictEqual(results.sorted[results.sorted.length-1].data.id, d.last);
                   }.bind(this));
            start();
        });
});

test("guid generator", function() {
    var guid1 = guid();
    var guid2 = guid();
    notEqual(guid1, guid2);

    ok(guid2.match("^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$"));
});

test("extract and generated citation reference ids", function() {
    var id = "pone.0067380-Sperone2";
    strictEqual(extractCitationReferenceInfo("pone.0067380-Sperone2"), null);
    strictEqual(extractCitationReferenceInfo(generateCitationReferenceId(id, 0)).id, id);
    strictEqual(extractCitationReferenceInfo(generateCitationReferenceId(id, 0)).count, 0);
    strictEqual(generateCitationReferenceId("pone.0067380-Sperone2", 0), "ref_" + id + "_0");
});

test("formatAuthorNameInvertedInitials", function() {
    strictEqual(formatAuthorNameInvertedInitials({given: "Jane", family: "Roe"}), "Roe J");
    strictEqual(formatAuthorNameInvertedInitials({given: "Mary Jane", family: "Roe"}), "Roe MJ");
    strictEqual(formatAuthorNameInvertedInitials({given: "Jane", family: "Roe Doe"}), "Roe Doe J");
    strictEqual(formatAuthorNameInvertedInitials({given: "Jane", family: "Roe-Doe"}), "Roe-Doe J");
});

test("ordinalStr", function() {
    strictEqual(ordinalStr(1), "1st");
    strictEqual(ordinalStr(2), "2nd");
    strictEqual(ordinalStr(3), "3rd");
    strictEqual(ordinalStr(1000), "1000th");
    strictEqual(ordinalStr(1011), "1011th");
    strictEqual(ordinalStr(1021), "1021st");
});

test("author list", function() {
    var a = {given: "Jane", family: "Roe"};
    var b = {given: "Joan", family: "Roe"};
    var c = {given: "John", family: "Doe"};
    var d = {given: "James", family: "Doe"};
    var e = {given: "Jennifer", family: "Roe"};
    /* can't make JSX transform work at the moment */
    var authorList4 = ReferenceAuthorList({authors: [a, b, c, d]});
    var authorList5 = ReferenceAuthorList({authors: [a, b, c, d, e]});
    TestUtils.renderIntoDocument(authorList4);
    TestUtils.renderIntoDocument(authorList5);
    var span4 = TestUtils.findRenderedDOMComponentWithClass(authorList4, 'reference-authors');
    var span5 = TestUtils.findRenderedDOMComponentWithClass(authorList5, 'reference-authors');
    /* all four names should display */
    strictEqual(span4.getDOMNode().textContent, "Roe J, Roe J, Doe J, Doe J");
    /* 2 refs of 5 should be hidden */
    strictEqual(span5.getDOMNode().textContent, "Roe J, Roe J, Doe J, (and 2 more)");
    /* should expand on click */
    var input = TestUtils.findRenderedDOMComponentWithTag(span5, 'a');
    TestUtils.Simulate.click(input);
    strictEqual(span5.getDOMNode().textContent, "Roe J, Roe J, Doe J, Doe J, Roe J");
});

test("abstract display", function() {
    var abs = ReferenceAbstract({ text: "foo bar baz" });
    TestUtils.renderIntoDocument(abs);
    var div = TestUtils.findRenderedDOMComponentWithTag(abs, "div");
    strictEqual(div.getDOMNode().textContent, "▶ Show abstract");
    var input = TestUtils.findRenderedDOMComponentWithTag(abs, 'button');
    TestUtils.Simulate.click(input);
    strictEqual(div.getDOMNode().textContent, "▼ Show abstractfoo bar baz");
});

test("search bar", function() {
    /* test that updating search text will call function with changed text */
    var text = "";
    var f = function(foo) { text = foo; };
    var sb = SearchBar({ filterText: text, onSearchUpdate: f});
    TestUtils.renderIntoDocument(sb);
    var input = TestUtils.findRenderedDOMComponentWithTag(sb, "input");
    TestUtils.Simulate.change(input, {target : { value: "foo" }});
    strictEqual(text, "foo");
});

test("reference with DOI has link", function() {
    var r = ReferenceCore({reference: testRefWithDoi});
    TestUtils.renderIntoDocument(r);
    var title = TestUtils.findRenderedDOMComponentWithClass(r, "reference-link");
    strictEqual(title.getDOMNode().getAttribute("href"), "http://dx.doi.org/10.12345/67890");
});

test("reference without DOI has no link", function() {
    var r = ReferenceCore({reference: testRef});
    TestUtils.renderIntoDocument(r);
    throws(
        function() {
            TestUtils.findRenderedDOMComponentWithClass(r, "reference-link");
        });
});

test("full reference", function() {
    var r = Reference({reference: testRefWithDoi});
    TestUtils.renderIntoDocument(r);
    equal(r.getDOMNode().textContent, "Doe J (2007)The best everJournal of Silly Studies10.12345/67890▶ 1 appearance in this article.");
});

test("withReferenceData", function() {
    stop();
    withReferenceData("10.1371/journal.pone.0097164", function (data) {
        strictEqual(data.references["pone.0097164-Ptz7"].info.author[0].family, "Pütz");
        start();

test("ReferenceUpdated", function() {
    var r = ReferenceUpdated({updated_by: [{"type": "retraction"}]});
    TestUtils.renderIntoDocument(r);
    strictEqual(r.getDOMNode().textContent, "RETRACTED");

    var u = ReferenceUpdated({updated_by: [{"type": "update"}]});
    TestUtils.renderIntoDocument(u);
    strictEqual(u.getDOMNode().textContent, "UPDATED");

    var n = ReferenceUpdated({updated_by: {}});
    TestUtils.renderIntoDocument(n);
    strictEqual(n.getDOMNode().textContent, "");
});
    });
});

test("ReferenceAppearanceListRevealable with 1 mention in reference list", function() {
    var l = ReferenceAppearanceListRevealable({ reference: testRef });
    var x = TestUtils.renderIntoDocument(l);
    strictEqual(x.getDOMNode().textContent, "▶ 1 appearance in this article.");
});

test("ReferenceAppearanceListRevealable with 1 mention in popover", function() {
    var l = ReferenceAppearanceListRevealable({ reference: testRef, currentMention: 0 });
    var x = TestUtils.renderIntoDocument(l);
    strictEqual(x.getDOMNode().textContent, "Appears once in this article.");
});

test("ReferenceAppearanceList", function() {
    var l = ReferenceAppearanceList({ reference: testRef, currentMention: 0 });
    var x = TestUtils.renderIntoDocument(l);
    strictEqual(x.getDOMNode().textContent, "Introduction☛Bacon ipsum dolor sit amet jerky pork loin pariatur pork chop, salami do aliqua fatback. [1] Venison filet mignon exercitation adipisicing meatloaf veniam. …");
});

test("Revealable", function() {
    var r = Revealable({revealText: "foo", children: ["baz"]});
    TestUtils.renderIntoDocument(r);
    strictEqual(r.getDOMNode().textContent, "▶ foo");
    var input = TestUtils.findRenderedDOMComponentWithTag(r, 'button');
    TestUtils.Simulate.click(input);
    strictEqual(r.getDOMNode().textContent, "▼ foobaz");
});

test("Maybe", function() {
    var t = Maybe({test: true, children: ["foo"]});
    TestUtils.renderIntoDocument(t);
    strictEqual(t.getDOMNode().textContent, "foo");

    var f = Maybe({test: false, children: ["foo"]});
    TestUtils.renderIntoDocument(f);
    strictEqual(f.getDOMNode().textContent, "");
});
<commit_msg>fix test for corrected action list<commit_after>/** @jsx React.DOM */
//= require jquery
//= require react

var TestUtils = React.addons.TestUtils;
var testRef = {
      "sections": {
        "Introduction": 1
      },
      "mentions": 1,
      "median_co_citations": 0.0,
      "citation_groups": [
        {
          "word_position": 21,
          "section": "Introduction",
          "context": "Bacon ipsum dolor sit amet jerky pork loin pariatur pork chop, salami do aliqua fatback. [1] Venison filet mignon exercitation adipisicing meatloaf veniam. \u2026",
          "references": [
            "pone.0000000-Doe1"
          ],
          "count": 1
        },
      ],
      "info": {
        "author": [
          {
            "given": "J",
            "family": "Doe"
          }
        ],
        "page": "79-95",
        "issued": {
          "date-parts": [
            [
              2007
            ]
          ]
        },
        "volume": "2",
        "title": "The best ever",
        "container-title": "Journal of Silly Studies",
        "container-type": "journal",
        "text": "Doe J ( 2007 ) The best ever. Journal of Silly Studies 2: 79\u201395."
      },
      "index": 1,
      "id": "pone.0000000-Doe1"
    };

var testRefWithDoi = $.extend(true, {}, testRef, {"info": {"doi": "10.12345/67890"}});

test("jquery quote id", function() {
    equal(jq("hello.world"), "#hello\\.world");
    equal(jq("hello:world"), "#hello\\:world");
    equal(jq("hello_world"), "#hello_world");
});

test("arraySorter", function () {
    equal(0, arraySorter({sort: ["a"]}, {sort: ["a"]}));
    equal(0, arraySorter({sort: [null]}, {sort: ["a"]}));
    equal(0, arraySorter({sort: ["a"]}, {sort: [null]}));
    equal(-1, arraySorter({sort: ["a"]}, {sort: ["b"]}));
    equal(0, arraySorter({sort: ["a", 1]}, {sort: ["a", 1]}));
    equal(-1, arraySorter({sort: ["a", 1]}, {sort: ["a", 2]}));
    equal(1, arraySorter({sort: ["a", 1]}, {sort: ["a", 0]}));
    var alpha = {sort: ["a", 0, 2, 3]};
    var beta =  {sort: ["a", 1, 1, 1]};
    equal([beta, alpha].sort(arraySorter)[0], alpha);
});

test("mkSortString", function () {
    strictEqual(mkSortString("Hello, world"), "hello world");
    strictEqual(mkSortString("the standard hello world of computing"), "standard hello world of computing");
});

test("mkSortField", function () {
    stop();
    $.getJSON("/papers/10.1371/journal.pone.0067380?format=json").
        done(function (fixture) {
            var ref = fixture.references["pone.0067380-Lowry1"];
            strictEqual("relative importance of growth and behaviour to elasmobranch suction-feeding performance over early ontogeny", mkSortField(ref, "title"));
            strictEqual(1, mkSortField(ref, "mentions"));
            strictEqual(6487, mkSortField(ref, "appearance"));
            strictEqual("lowry d", mkSortField(ref, "author"));
            strictEqual(2008, mkSortField(ref, "year"));
            strictEqual(55, mkSortField(ref, "index"));
            strictEqual("journal of royal society interface", mkSortField(ref, "journal"));

            /* reference with no info */
            var refNoInfo = {id: "pone.0067380-Wahnbaeck1",
                             info: {}};
            strictEqual(null, mkSortField(refNoInfo, "author"));
            strictEqual(null, mkSortField(refNoInfo, "year"));
            strictEqual(null, mkSortField(refNoInfo, "title"));
            strictEqual(null, mkSortField(refNoInfo, "journal"));

            /* anything else should return null */
            strictEqual(null, mkSortField(ref, "foobar"));
            start();
        });
});

test("mkSearchResultsFilter", function () {
    stop();
    $.getJSON("/papers/10.1371/journal.pone.0067380?format=json").
        done(function (fixture) {
            var filter = mkSearchResultsFilter(buildIndex(fixture.references), "odontodactylus");
            var results = _.filter(fixture.references, filter);
            strictEqual(results.length, 1);
            strictEqual(results[0].id, "pone.0067380-Patek1");
            start();
        });
});

test("buildIndex", function () {
    stop();
    $.getJSON("/papers/10.1371/journal.pone.0067380?format=json").
        done(function (fixture) {
            var idx = buildIndex(fixture.references);
            var results = idx.search("odontodactylus");
            strictEqual(results.length, 1);
            strictEqual(results[0].ref, "pone.0067380-Patek1");
            start();
        });
});

test("sortReferences", function () {
    stop();
    $.getJSON("/papers/10.1371/journal.pone.0067380?format=json").
        done(function (fixture) {
            _.each([{by: "appearance",
                     first: "pone.0067380-Clua1",
                     last: "pone.0067380-Lowry1",
                     sortableCount: 55,
                     unsortableCount: 0},
                    {by: "appearance+repeated",
                     first: "pone.0067380-Clua1",
                     last: "pone.0067380-Heithaus1",
                     sortableCount: 91,
                     unsortableCount: 0},
                    {by: "title",
                     first: "pone.0067380-Simon1",
                     last: "pone.0067380-Whitehead1",
                     sortableCount: 55,
                     unsortableCount: 0}],
                   function (d) {
                       var refs = fixture.references;
                       var results = sortReferences(refs, d.by);
                       strictEqual(results.unsortable.length, d.unsortableCount);
                       strictEqual(results.sorted.length, d.sortableCount);
                       strictEqual(results.sorted[0].data.id, d.first);
                       strictEqual(results.sorted[results.sorted.length-1].data.id, d.last);
                   }.bind(this));
            start();
        });
});

test("guid generator", function() {
    var guid1 = guid();
    var guid2 = guid();
    notEqual(guid1, guid2);

    ok(guid2.match("^[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}$"));
});

test("extract and generated citation reference ids", function() {
    var id = "pone.0067380-Sperone2";
    strictEqual(extractCitationReferenceInfo("pone.0067380-Sperone2"), null);
    strictEqual(extractCitationReferenceInfo(generateCitationReferenceId(id, 0)).id, id);
    strictEqual(extractCitationReferenceInfo(generateCitationReferenceId(id, 0)).count, 0);
    strictEqual(generateCitationReferenceId("pone.0067380-Sperone2", 0), "ref_" + id + "_0");
});

test("formatAuthorNameInvertedInitials", function() {
    strictEqual(formatAuthorNameInvertedInitials({given: "Jane", family: "Roe"}), "Roe J");
    strictEqual(formatAuthorNameInvertedInitials({given: "Mary Jane", family: "Roe"}), "Roe MJ");
    strictEqual(formatAuthorNameInvertedInitials({given: "Jane", family: "Roe Doe"}), "Roe Doe J");
    strictEqual(formatAuthorNameInvertedInitials({given: "Jane", family: "Roe-Doe"}), "Roe-Doe J");
});

test("ordinalStr", function() {
    strictEqual(ordinalStr(1), "1st");
    strictEqual(ordinalStr(2), "2nd");
    strictEqual(ordinalStr(3), "3rd");
    strictEqual(ordinalStr(1000), "1000th");
    strictEqual(ordinalStr(1011), "1011th");
    strictEqual(ordinalStr(1021), "1021st");
});

test("author list", function() {
    var a = {given: "Jane", family: "Roe"};
    var b = {given: "Joan", family: "Roe"};
    var c = {given: "John", family: "Doe"};
    var d = {given: "James", family: "Doe"};
    var e = {given: "Jennifer", family: "Roe"};
    /* can't make JSX transform work at the moment */
    var authorList4 = ReferenceAuthorList({authors: [a, b, c, d]});
    var authorList5 = ReferenceAuthorList({authors: [a, b, c, d, e]});
    TestUtils.renderIntoDocument(authorList4);
    TestUtils.renderIntoDocument(authorList5);
    var span4 = TestUtils.findRenderedDOMComponentWithClass(authorList4, 'reference-authors');
    var span5 = TestUtils.findRenderedDOMComponentWithClass(authorList5, 'reference-authors');
    /* all four names should display */
    strictEqual(span4.getDOMNode().textContent, "Roe J, Roe J, Doe J, Doe J");
    /* 2 refs of 5 should be hidden */
    strictEqual(span5.getDOMNode().textContent, "Roe J, Roe J, Doe J, (and 2 more)");
    /* should expand on click */
    var input = TestUtils.findRenderedDOMComponentWithTag(span5, 'a');
    TestUtils.Simulate.click(input);
    strictEqual(span5.getDOMNode().textContent, "Roe J, Roe J, Doe J, Doe J, Roe J");
});

test("abstract display", function() {
    var abs = ReferenceAbstract({ text: "foo bar baz" });
    TestUtils.renderIntoDocument(abs);
    var div = TestUtils.findRenderedDOMComponentWithTag(abs, "div");
    strictEqual(div.getDOMNode().textContent, "▶ Show abstract");
    var input = TestUtils.findRenderedDOMComponentWithTag(abs, 'button');
    TestUtils.Simulate.click(input);
    strictEqual(div.getDOMNode().textContent, "▼ Show abstractfoo bar baz");
});

test("search bar", function() {
    /* test that updating search text will call function with changed text */
    var text = "";
    var f = function(foo) { text = foo; };
    var sb = SearchBar({ filterText: text, onSearchUpdate: f});
    TestUtils.renderIntoDocument(sb);
    var input = TestUtils.findRenderedDOMComponentWithTag(sb, "input");
    TestUtils.Simulate.change(input, {target : { value: "foo" }});
    strictEqual(text, "foo");
});

test("reference with DOI has link", function() {
    var r = ReferenceCore({reference: testRefWithDoi});
    TestUtils.renderIntoDocument(r);
    var title = TestUtils.findRenderedDOMComponentWithClass(r, "reference-link");
    strictEqual(title.getDOMNode().getAttribute("href"), "http://dx.doi.org/10.12345/67890");
});

test("reference without DOI has no link", function() {
    var r = ReferenceCore({reference: testRef});
    TestUtils.renderIntoDocument(r);
    throws(
        function() {
            TestUtils.findRenderedDOMComponentWithClass(r, "reference-link");
        });
});

test("full reference", function() {
    var r = Reference({reference: testRefWithDoi});
    TestUtils.renderIntoDocument(r);
    equal(r.getDOMNode().textContent, "Doe J (2007)The best everJournal of Silly Studies10.12345/67890Download reference (BibTeX) (RIS)▶ 1 appearance in this article.");
});

test("withReferenceData", function() {
    stop();
    withReferenceData("10.1371/journal.pone.0097164", function (data) {
        strictEqual(data.references["pone.0097164-Ptz7"].info.author[0].family, "Pütz");
        start();

test("ReferenceUpdated", function() {
    var r = ReferenceUpdated({updated_by: [{"type": "retraction"}]});
    TestUtils.renderIntoDocument(r);
    strictEqual(r.getDOMNode().textContent, "RETRACTED");

    var u = ReferenceUpdated({updated_by: [{"type": "update"}]});
    TestUtils.renderIntoDocument(u);
    strictEqual(u.getDOMNode().textContent, "UPDATED");

    var n = ReferenceUpdated({updated_by: {}});
    TestUtils.renderIntoDocument(n);
    strictEqual(n.getDOMNode().textContent, "");
});
    });
});

test("ReferenceAppearanceListRevealable with 1 mention in reference list", function() {
    var l = ReferenceAppearanceListRevealable({ reference: testRef });
    var x = TestUtils.renderIntoDocument(l);
    strictEqual(x.getDOMNode().textContent, "▶ 1 appearance in this article.");
});

test("ReferenceAppearanceListRevealable with 1 mention in popover", function() {
    var l = ReferenceAppearanceListRevealable({ reference: testRef, currentMention: 0 });
    var x = TestUtils.renderIntoDocument(l);
    strictEqual(x.getDOMNode().textContent, "Appears once in this article.");
});

test("ReferenceAppearanceList", function() {
    var l = ReferenceAppearanceList({ reference: testRef, currentMention: 0 });
    var x = TestUtils.renderIntoDocument(l);
    strictEqual(x.getDOMNode().textContent, "Introduction☛Bacon ipsum dolor sit amet jerky pork loin pariatur pork chop, salami do aliqua fatback. [1] Venison filet mignon exercitation adipisicing meatloaf veniam. …");
});

test("Revealable", function() {
    var r = Revealable({revealText: "foo", children: ["baz"]});
    TestUtils.renderIntoDocument(r);
    strictEqual(r.getDOMNode().textContent, "▶ foo");
    var input = TestUtils.findRenderedDOMComponentWithTag(r, 'button');
    TestUtils.Simulate.click(input);
    strictEqual(r.getDOMNode().textContent, "▼ foobaz");
});

test("Maybe", function() {
    var t = Maybe({test: true, children: ["foo"]});
    TestUtils.renderIntoDocument(t);
    strictEqual(t.getDOMNode().textContent, "foo");

    var f = Maybe({test: false, children: ["foo"]});
    TestUtils.renderIntoDocument(f);
    strictEqual(f.getDOMNode().textContent, "");
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types'
import React, { Component } from 'react'
import _isEmpty from 'lodash/isEmpty'
import { showLoading, hideLoading } from 'react-redux-loading-bar'
import './LoaderHOC.css'

export const mapDispatchToProps = (dispatch, ownProps) => ({
    showLoading: () => dispatch(showLoading()),
    hideLoading: () => dispatch(hideLoading()),
})

const LoaderHOC = (isLoading) => (dataPropName) => (WrappedComponent) => {
    return class LoaderHOC extends Component {

        isLoadingData(prop) {
            return (
                prop ||
                prop === undefined
            )
        }

        render() {
            const dataIsEmpty = _isEmpty(this.props[dataPropName])
            const showLoader =  dataIsEmpty && this.isLoadingData(this.props[isLoading])

            if (showLoader) {
                return

            } else if (dataIsEmpty) {
                return
No data

            }
            else {
                return <WrappedComponent {...this.props} />
            }
        }
    }
}

export default LoaderHOC
<commit_msg>NCI-Agency/anet#255: Allow custom error message in LoaderHOC<commit_after>import PropTypes from 'prop-types'
import React, { Component } from 'react'
import _isEmpty from 'lodash/isEmpty'
import { showLoading, hideLoading } from 'react-redux-loading-bar'
import './LoaderHOC.css'

export const mapDispatchToProps = (dispatch, ownProps) => ({
    showLoading: () => dispatch(showLoading()),
    hideLoading: () => dispatch(hideLoading()),
})

const LoaderHOC = (isLoading) => (dataPropName) => (WrappedComponent) => {
    return class LoaderHOC extends Component {

        isLoadingData(prop) {
            return (
                prop ||
                prop === undefined
            )
        }

        render() {
            const dataIsEmpty = _isEmpty(this.props[dataPropName])
            const showLoader =  dataIsEmpty && this.isLoadingData(this.props[isLoading])
            const loaderMessage = this.props.loaderMessage
            const defaultMessage =
No data

            if (showLoader) {
                return

            } else if (dataIsEmpty) {
                return _isEmpty(loaderMessage) ? defaultMessage : loaderMessage
            }
            else {
                return <WrappedComponent {...this.props} />
            }
        }
    }
}

export default LoaderHOC
<|endoftext|>


<commit_before>/*!
 * Copyright 2015 mifort.org
 *
 * 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.
 *
 * @author Andrew Voitov
 */

var moment = require('moment');

var db = require('./libs/mongodb_settings');
var users = require('./user');
var utils = require('./libs/utils');
var registration = require('./libs/registration');
var log = require('./libs/logger');
var authorization = require('./libs/authorization');
var mail = require('./libs/mail');
var constants = require('./libs/config_constants');

//Rest API
exports.restFindById = function(req, res, next) {
    var companyId = utils.getCompanyId(req);
    log.debug('-REST call: Find company by id. Company id: %s', companyId.toHexString());

    findById(companyId, function(err, company, next) {
        if(err) {
            err.code = 400;
            next(err);
        } else {
            res.json(company);
            log.debug('-REST result: Finded company id. Company id: %s',
                company._id.toHexString());
        }
    });
};

exports.restCreateCompany = function(req, res, next) {
    var company = req.body;
    log.debug('-REST call: Create company. Company name: %s', company.name);

    var defaultCompany = exports.generateDefaultCompany();
    company.template = defaultCompany.template;
    company.periods = defaultCompany.periods;
    company.dayTypes = defaultCompany.dayTypes;
    company.defaultValues = defaultCompany.defaultValues;
    company.availablePositions = defaultCompany.availablePositions;
    if(req.user) {
        company.ownerId = req.user._id;
    }

    save(company, function(err, savedCompany) {
        if(err) {
            next(err);
        } else {
            //Warning: asynchronous operations!!!
            registration.createDefaultProject(savedCompany, req.user);
            createUsersByEmails(savedCompany);
            res.json(savedCompany);
            log.debug('-REST result: Create company. Company id: %s',
                savedCompany._id.toHexString());
        }
    });
};

exports.restUpdateCompany = function(req, res, next) {
    var company = req.body;
    log.debug('-REST call: Update company. Company id: %s', company._id.toHexString());
    save(company, function(err, savedCompany) {
        if(err) {
            next(err);
        } else {
            //update all projects
            var projects = db.projectCollection();
            projects.update(
                    {companyId: savedCompany._id},
                    {$set: {template: savedCompany.template,
                            periods: savedCompany.periods,
                            defaultValues: savedCompany.defaultValues,
                            dayTypes: savedCompany.dayTypes,
                            availablePositions: savedCompany.availablePositions}},
                    {multi: true},
                function(err, result){
                    log.info('Company projects are updated!')
                });
            createUsersByEmails(savedCompany);
            res.json(savedCompany);
            log.debug('-REST result: Update company. Company id: %s',
                savedCompany._id.toHexString());
        }
    });
};

//Public API
exports.save = save;

exports.defaultPositions = constants.DEFAULT_AVAILABLE_POSITIONS.slice();

//dayTypes
var Weekend = {
    id: 1,
    name: 'Weekend',
    time: 0,
    color: '#c5e9fb'
};
var Corporate = {
    id: 2,
    name: 'Corporate',
    time: 0,
    color: '#f3cce1'
};
var Holiday = {
    id: 3,
    name: 'Holiday',
    time: 0,
    color: '#fff9a1'
};

exports.generateDefaultCompany = function() {
    var periods = generateDefaultPeriods();
    var defaultValues = generateDefaultValues(periods);

    var company = constructCompany(periods, defaultValues);
    return company;
};

exports.findById = findById;

//private part
function findById(id, callback) {
    var companies = db.companyCollection();
    companies.findOne({_id: id}, function(err, company){
        callback(err, company);
    });
}

function createUsersByEmails(company) {
    var emails = company.emails;
    if(emails) {
        emails.forEach(function(email) {
            var user = {email: email,
                        companyId: company._id};

            users.findByExample(user, function(err, dbUser) {
                if(err) {
                    log.warn('Cannot find user by email for new company.', {error: err});
                } else if(!dbUser) {
                    user.displayName = email;
                    user.role = authorization.EMPLOYEE_ROLE;
                    users.save(user, function(err, savedUser) {
                        if(err) {
                            log.error('Cannot save user by email for new company.', {error: err});
                        } else {
                            log.info('User saved with e-mail %s', savedUser.email);
                            mail.sendInvite(email, company.name);
                        }
                    });
                }
            });

        })
    }
}

function save(company, callback) {
    var companies = db.companyCollection();
    companies.save(company, {safe:true}, function (err, result) {
        if(result.ops) {
            callback(err, result.ops[0]);
        } else {
            callback(err, company);
        }
    });
}

function constructCompany(periods, defaultValues) {
    return {
        template : {
            date: '',
            role: '',
            time: 8,
            comment: ''
        },
        periods: periods,
        dayTypes: [
            Weekend, Corporate, Holiday
        ],
        defaultValues: defaultValues,
        availablePositions: constants.DEFAULT_AVAILABLE_POSITIONS
    };
}

function generateDefaultPeriods() {
    var periods = [];

    var firstPeriod = {
        start: moment.utc().toDate(),
        end: moment.utc().endOf('week').toDate()
    };
    periods.push(firstPeriod);

    //generate 53 weeks (1 year)
    var startDate = moment.utc(firstPeriod.end).add(1,'day').toDate();
    var endDate = moment.utc(startDate).endOf('week').toDate();
    for (var i = 0; i < 53; i++) {
        periods.push({
            start: startDate,
            end: endDate
        });
        startDate = moment.utc(endDate).add(1,'day').toDate();
        endDate = moment.utc(startDate).endOf('week').toDate();
    };

    return periods;
}

function generateDefaultValues(periods) {
    var defaultValues = [];

    periods.forEach(function(period) {
        if(isWeekend(period.start)) {
            defaultValues.push({date: period.start, dayId: Weekend.id});
        }
        if(isWeekend(period.end)) {
            defaultValues.push({date: period.end, dayId: Weekend.id});
        }
    });

    return defaultValues;
}

function isWeekend(date) {
    return moment.utc(date).day() % 6 == 0;
}
<commit_msg>Fix #79 No "availablePositions" for new projects<commit_after>/*!
 * Copyright 2015 mifort.org
 *
 * 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.
 *
 * @author Andrew Voitov
 */

var moment = require('moment');

var db = require('./libs/mongodb_settings');
var users = require('./user');
var utils = require('./libs/utils');
var registration = require('./libs/registration');
var log = require('./libs/logger');
var authorization = require('./libs/authorization');
var mail = require('./libs/mail');
var constants = require('./libs/config_constants');

//Rest API
exports.restFindById = function(req, res, next) {
    var companyId = utils.getCompanyId(req);
    log.debug('-REST call: Find company by id. Company id: %s', companyId.toHexString());

    findById(companyId, function(err, company, next) {
        if(err) {
            err.code = 400;
            next(err);
        } else {
            res.json(company);
            log.debug('-REST result: Finded company id. Company id: %s',
                company._id.toHexString());
        }
    });
};

exports.restCreateCompany = function(req, res, next) {
    var company = req.body;
    log.debug('-REST call: Create company. Company name: %s', company.name);

    var defaultCompany = exports.generateDefaultCompany();
    company.template = defaultCompany.template;
    company.periods = defaultCompany.periods;
    company.dayTypes = defaultCompany.dayTypes;
    company.defaultValues = defaultCompany.defaultValues;
    company.availablePositions = defaultCompany.availablePositions;
    if(req.user) {
        company.ownerId = req.user._id;
    }

    save(company, function(err, savedCompany) {
        if(err) {
            next(err);
        } else {
            //Warning: asynchronous operations!!!
            registration.createDefaultProject(savedCompany, req.user);
            createUsersByEmails(savedCompany);
            res.json(savedCompany);
            log.debug('-REST result: Create company. Company id: %s',
                savedCompany._id.toHexString());
        }
    });
};

exports.restUpdateCompany = function(req, res, next) {
    var company = req.body;
    log.debug('-REST call: Update company. Company id: %s', company._id.toHexString());
    if(!company.availablePositions) {
        company.availablePositions = constants.DEFAULT_AVAILABLE_POSITIONS;
    }
    save(company, function(err, savedCompany) {
        if(err) {
            next(err);
        } else {
            //update all projects
            var projects = db.projectCollection();
            projects.update(
                    {companyId: savedCompany._id},
                    {$set: {template: savedCompany.template,
                            periods: savedCompany.periods,
                            defaultValues: savedCompany.defaultValues,
                            dayTypes: savedCompany.dayTypes,
                            availablePositions: savedCompany.availablePositions}},
                    {multi: true},
                function(err, result){
                    log.info('Company projects are updated!')
                });
            createUsersByEmails(savedCompany);
            res.json(savedCompany);
            log.debug('-REST result: Update company. Company id: %s',
                savedCompany._id.toHexString());
        }
    });
};

//Public API
exports.save = save;

exports.defaultPositions = constants.DEFAULT_AVAILABLE_POSITIONS.slice();

//dayTypes
var Weekend = {
    id: 1,
    name: 'Weekend',
    time: 0,
    color: '#c5e9fb'
};
var Corporate = {
    id: 2,
    name: 'Corporate',
    time: 0,
    color: '#f3cce1'
};
var Holiday = {
    id: 3,
    name: 'Holiday',
    time: 0,
    color: '#fff9a1'
};

exports.generateDefaultCompany = function() {
    var periods = generateDefaultPeriods();
    var defaultValues = generateDefaultValues(periods);

    var company = constructCompany(periods, defaultValues);
    return company;
};

exports.findById = findById;

//private part
function findById(id, callback) {
    var companies = db.companyCollection();
    companies.findOne({_id: id}, function(err, company){
        callback(err, company);
    });
}

function createUsersByEmails(company) {
    var emails = company.emails;
    if(emails) {
        emails.forEach(function(email) {
            var user = {email: email,
                        companyId: company._id};

            users.findByExample(user, function(err, dbUser) {
                if(err) {
                    log.warn('Cannot find user by email for new company.', {error: err});
                } else if(!dbUser) {
                    user.displayName = email;
                    user.role = authorization.EMPLOYEE_ROLE;
                    users.save(user, function(err, savedUser) {
                        if(err) {
                            log.error('Cannot save user by email for new company.', {error: err});
                        } else {
                            log.info('User saved with e-mail %s', savedUser.email);
                            mail.sendInvite(email, company.name);
                        }
                    });
                }
            });

        })
    }
}

function save(company, callback) {
    var companies = db.companyCollection();
    companies.save(company, {safe:true}, function (err, result) {
        if(result.ops) {
            callback(err, result.ops[0]);
        } else {
            callback(err, company);
        }
    });
}

function constructCompany(periods, defaultValues) {
    return {
        template : {
            date: '',
            role: '',
            time: 8,
            comment: ''
        },
        periods: periods,
        dayTypes: [
            Weekend, Corporate, Holiday
        ],
        defaultValues: defaultValues,
        availablePositions: constants.DEFAULT_AVAILABLE_POSITIONS
    };
}

function generateDefaultPeriods() {
    var periods = [];

    var firstPeriod = {
        start: moment.utc().toDate(),
        end: moment.utc().endOf('week').toDate()
    };
    periods.push(firstPeriod);

    //generate 53 weeks (1 year)
    var startDate = moment.utc(firstPeriod.end).add(1,'day').toDate();
    var endDate = moment.utc(startDate).endOf('week').toDate();
    for (var i = 0; i < 53; i++) {
        periods.push({
            start: startDate,
            end: endDate
        });
        startDate = moment.utc(endDate).add(1,'day').toDate();
        endDate = moment.utc(startDate).endOf('week').toDate();
    };

    return periods;
}

function generateDefaultValues(periods) {
    var defaultValues = [];

    periods.forEach(function(period) {
        if(isWeekend(period.start)) {
            defaultValues.push({date: period.start, dayId: Weekend.id});
        }
        if(isWeekend(period.end)) {
            defaultValues.push({date: period.end, dayId: Weekend.id});
        }
    });

    return defaultValues;
}

function isWeekend(date) {
    return moment.utc(date).day() % 6 == 0;
}
<|endoftext|>