<commit_before>// ENV =============================================================================================
process.env.NODE_ENV = process.env.NODE_ENV || "development";
process.env.NODE_CONFIG_DIR = process.env.NODE_CONFIG_DIR || "./shared/config";

// IMPORTS =========================================================================================
let Path = require("path");
let Glob = require("glob");
let ChildProcess = require("child_process");
let Mkdirp = require("mkdirp");
let Config = require("config");
let RunSequence = require("run-sequence");
let Gulp = require("gulp");
let JshintStylish = require("jshint-stylish");
let GulpJshint = require("gulp-jshint");
let GulpCached = require("gulp-cached");
let GulpJsx = require("gulp-jsx");
let GulpSourcemaps = require("gulp-sourcemaps");
let GulpLess = require("gulp-less");
let GulpPlumber = require("gulp-plumber");
let frontendVendors = require("./package.json").frontendVendors;

// OPTIONS =========================================================================================
let exitOnError = false;

let jsxOptions = {
  ignoreDocblock: true,
  docblockUnknownTags: true,
  unknownTagsAsString: true,
  jsx: "h",
  renameAttrs: {
    "for": "htmlFor",
    "class": "className",
  }
};

require("events").EventEmitter.defaultMaxListeners = 999;

// HELPERS =========================================================================================
function interleaveWith(array, prefix) {
  return array.reduce((memo, val) => {
    return memo.concat([prefix]).concat([val]);
  }, []);
}

// TASKS ===========================================================================================
// TODO sourcemaps
Gulp.task("build", function () {
  return Gulp.src("frontend/**/*.js")
    .pipe(GulpPlumber({errorHandler: !exitOnError}))
    .pipe(GulpCached("build"))
    .pipe(GulpJsx(jsxOptions))
    .pipe(Gulp.dest("build"));
});

Gulp.task("dist-styles", function() {
  return Gulp.src(["./frontend/**/theme.css"])
    .pipe(GulpPlumber({errorHandler: !exitOnError}))
    //.pipe(GulpLess())
    .pipe(Gulp.dest("./static/"));
});

//Gulp.task("lint", function() {
//  return Gulp.src(["./frontend/**/*.js"])
//    .pipe(GulpPlumber({errorHandler: !exitOnError}))
//    .pipe(cached("lint-react"))
//    .pipe(GulpJshint())
//    .pipe(GulpJshint.reporter(JshintStylish));
//});

Gulp.task("dist-images", function () {
  return Gulp.src(["./images/**/*"])
    .pipe(Gulp.dest("./static/images"));
});

Gulp.task("dist-vendors", function () {
  // $ browserify -d -r cyclejs [-r ...] -o ./static/scripts/vendors.js
  Mkdirp.sync("./static/common/scripts");

  let args = ["-d"]
    .concat(interleaveWith(frontendVendors, "-r"))
    .concat(["-o", "./static/common/scripts/vendors.js"]);

  let bundler = ChildProcess.spawn("browserify", args);
  bundler.stdout.pipe(process.stdout);
  bundler.stderr.pipe(process.stderr);
  bundler.on("exit", function (code) {
    if (exitOnError && code) {
      process.exit(code);
    }
  });
});

function distFactory(appCode) { // , ["predist-app"]
  return function dist() {
    let folders = Glob.sync(`build/${appCode}*`);
    if (!folders) {
      throw Error(`wrong app code ${appCode}`);
    }

    let appName = Path.basename(folders[0]);

    Mkdirp.sync(`static/${appName}/scripts`);

    // $ browserify --delay 0 -d -x cyclejs [-x ...] ./build/{app}/scripts/app.js -o ./static/{app}/scripts/app.js
    let args = ["-d", "--delay 0"]
      .concat(interleaveWith(frontendVendors, "-x"))
      .concat([`./build/${appName}/scripts/app.js`])
      .concat(["-o", `./static/${appName}/scripts/app.js`]);

    let bundler = ChildProcess.spawn("browserify", args);
    bundler.stdout.pipe(process.stdout);
    bundler.stderr.pipe(process.stderr);
    bundler.on("exit", function (code) {
      if (exitOnError && code) {
        process.exit(code);
      }
    });
  }
}

function watchifyFactory(appCode) { // , ["predist-app"]
  return function dist() {
    let folders = Glob.sync(`build/${appCode}*`);
    if (!folders) {
      throw Error(`wrong app code ${appCode}`);
    }

    let appName = Path.basename(folders[0]);

    Mkdirp.sync(`static/${appName}/scripts`);

    // $ watchify --delay 0 -v -d -x cycle [-x ...] ./build/{app}/scripts/app.js -o ./static/{app}/scripts/app.js
    let args = ["-v", "-d", "--delay 0"]
      .concat(interleaveWith(frontendVendors, "-x"))
      .concat([`./build/${appName}/scripts/app.js`])
      .concat(["-o", `./static/${appName}/scripts/app.js`]);

    let watcher = ChildProcess.spawn("watchify", args);
    watcher.stdout.pipe(process.stdout);
    watcher.stderr.pipe(process.stderr);
  }
}

// All this mess is required because of dumb Gulp v3 architecture. TODO: reconsider at Gulp v4 release (undocumented yet!)
Gulp.task("dist-1.1", distFactory("1.1"));
Gulp.task("dist-1.2", distFactory("1.2"));
Gulp.task("dist-1.3", distFactory("1.3"));
Gulp.task("dist-2.1", distFactory("2.1"));
Gulp.task("dist-2.2", distFactory("2.2"));
Gulp.task("dist-3.1", distFactory("3.1"));
Gulp.task("dist-3.2", distFactory("3.2"));
Gulp.task("dist-3.3", distFactory("3.3"));
Gulp.task("dist-3.4", distFactory("3.4"));
Gulp.task("dist-4.1", distFactory("4.1"));
Gulp.task("dist-4.2", distFactory("4.2"));
Gulp.task("dist-4.3", distFactory("4.3"));
Gulp.task("dist-5.1", distFactory("5.1"));
Gulp.task("dist-6.1", distFactory("6.1"));
Gulp.task("dist-6.2", distFactory("6.2"));

Gulp.task("watchify-1.1", watchifyFactory("1.1"));
Gulp.task("watchify-1.2", watchifyFactory("1.2"));
Gulp.task("watchify-1.3", watchifyFactory("1.3"));
Gulp.task("watchify-2.1", watchifyFactory("2.1"));
Gulp.task("watchify-2.2", watchifyFactory("2.2"));
Gulp.task("watchify-3.1", watchifyFactory("3.1"));
Gulp.task("watchify-3.2", watchifyFactory("3.2"));
Gulp.task("watchify-3.3", watchifyFactory("3.3"));
Gulp.task("watchify-3.4", watchifyFactory("3.4"));
Gulp.task("watchify-4.1", watchifyFactory("4.1"));
Gulp.task("watchify-4.2", watchifyFactory("4.2"));
Gulp.task("watchify-4.3", watchifyFactory("4.3"));
Gulp.task("watchify-5.1", watchifyFactory("5.1"));
Gulp.task("watchify-6.1", watchifyFactory("6.1"));
Gulp.task("watchify-6.2", watchifyFactory("6.2"));

Gulp.task("dist-scripts", function() {
  RunSequence(
    "dist-1.1", "dist-1.2", "dist-1.3",
    "dist-2.1", "dist-2.2",
    "dist-3.1", "dist-3.2", "dist-3.3", "dist-3.4",
    "dist-4.1", "dist-4.2", "dist-4.3",
    "dist-5.1",
    "dist-6.1", "dist-6.2"
  )
});

Gulp.task("watch-build", function () {
  RunSequence(
    "watchify-1.1", "watchify-1.2", "watchify-1.3",
    "watchify-2.1", "watchify-2.2",
    "watchify-3.1", "watchify-3.2", "watchify-3.3", "watchify-3.4",
    "watchify-4.1", "watchify-4.2", "watchify-4.3",
    "watchify-5.1",
    "watchify-6.1", "watchify-6.2"
  )
});

Gulp.task("watch-src", function () {
  Gulp.watch("./frontend/**/*.js", ["build"]);
  Gulp.watch("./frontend/**/*.(jpg|png|gif)", ["dist-images"]);
  Gulp.watch("./frontend/**/*.css", ["dist-styles"]);
});

Gulp.task("dist", function () {
  exitOnError = true;
  return RunSequence(
    ["build"],
    ["dist-scripts", "dist-images", "dist-styles"]
  );
});

Gulp.task("watch", ["watch-src", "watch-build"]);<commit_msg>Enforce conventions<commit_after>// ENV =============================================================================================
process.env.NODE_ENV = process.env.NODE_ENV || "development";
process.env.NODE_CONFIG_DIR = process.env.NODE_CONFIG_DIR || "./shared/config";

// IMPORTS =========================================================================================
let Path = require("path");
let Glob = require("glob");
let ChildProcess = require("child_process");
let Mkdirp = require("mkdirp");
let Config = require("config");
let RunSequence = require("run-sequence");
let Gulp = require("gulp");
let JshintStylish = require("jshint-stylish");
let GulpJshint = require("gulp-jshint");
let GulpCached = require("gulp-cached");
let GulpJsx = require("gulp-jsx");
let GulpSourcemaps = require("gulp-sourcemaps");
let GulpLess = require("gulp-less");
let GulpPlumber = require("gulp-plumber");
let frontendVendors = require("./package.json").frontendVendors;

// OPTIONS =========================================================================================
let exitOnError = false;

let jsxOptions = {
  ignoreDocblock: true,
  docblockUnknownTags: true,
  unknownTagsAsString: true,
  jsx: "h",
  renameAttrs: {
    "for": "htmlFor",
    "class": "className",
  }
};

require("events").EventEmitter.defaultMaxListeners = 999;

// HELPERS =========================================================================================
function interleaveWith(array, prefix) {
  return array.reduce((memo, val) => {
    return memo.concat([prefix]).concat([val]);
  }, []);
}

// TASKS ===========================================================================================
// TODO sourcemaps
Gulp.task("build", function () {
  return Gulp.src("frontend/**/*.js")
    .pipe(GulpPlumber({errorHandler: !exitOnError}))
    .pipe(GulpCached("build"))
    .pipe(GulpJsx(jsxOptions))
    .pipe(Gulp.dest("build"));
});

Gulp.task("dist-styles", function () {
  return Gulp.src(["./frontend/**/theme.css"])
    .pipe(GulpPlumber({errorHandler: !exitOnError}))
    //.pipe(GulpLess())
    .pipe(Gulp.dest("./static/"));
});

//Gulp.task("lint", function () {
//  return Gulp.src(["./frontend/**/*.js"])
//    .pipe(GulpPlumber({errorHandler: !exitOnError}))
//    .pipe(cached("lint-react"))
//    .pipe(GulpJshint())
//    .pipe(GulpJshint.reporter(JshintStylish));
//});

Gulp.task("dist-images", function () {
  return Gulp.src(["./images/**/*"])
    .pipe(Gulp.dest("./static/images"));
});

Gulp.task("dist-vendors", function () {
  // $ browserify -d -r cyclejs [-r ...] -o ./static/scripts/vendors.js
  Mkdirp.sync("./static/common/scripts");

  let args = ["-d"]
    .concat(interleaveWith(frontendVendors, "-r"))
    .concat(["-o", "./static/common/scripts/vendors.js"]);

  let bundler = ChildProcess.spawn("browserify", args);
  bundler.stdout.pipe(process.stdout);
  bundler.stderr.pipe(process.stderr);
  bundler.on("exit", function (code) {
    if (exitOnError && code) {
      process.exit(code);
    }
  });
});

function distFactory(appCode) { // , ["predist-app"]
  return function dist() {
    let folders = Glob.sync(`build/${appCode}*`);
    if (!folders) {
      throw Error(`wrong app code ${appCode}`);
    }

    let appName = Path.basename(folders[0]);

    Mkdirp.sync(`static/${appName}/scripts`);

    // $ browserify --delay 0 -d -x cyclejs [-x ...] ./build/{app}/scripts/app.js -o ./static/{app}/scripts/app.js
    let args = ["-d", "--delay 0"]
      .concat(interleaveWith(frontendVendors, "-x"))
      .concat([`./build/${appName}/scripts/app.js`])
      .concat(["-o", `./static/${appName}/scripts/app.js`]);

    let bundler = ChildProcess.spawn("browserify", args);
    bundler.stdout.pipe(process.stdout);
    bundler.stderr.pipe(process.stderr);
    bundler.on("exit", function (code) {
      if (exitOnError && code) {
        process.exit(code);
      }
    });
  }
}

function watchifyFactory(appCode) { // , ["predist-app"]
  return function dist() {
    let folders = Glob.sync(`build/${appCode}*`);
    if (!folders) {
      throw Error(`wrong app code ${appCode}`);
    }

    let appName = Path.basename(folders[0]);

    Mkdirp.sync(`static/${appName}/scripts`);

    // $ watchify --delay 0 -v -d -x cycle [-x ...] ./build/{app}/scripts/app.js -o ./static/{app}/scripts/app.js
    let args = ["-v", "-d", "--delay 0"]
      .concat(interleaveWith(frontendVendors, "-x"))
      .concat([`./build/${appName}/scripts/app.js`])
      .concat(["-o", `./static/${appName}/scripts/app.js`]);

    let watcher = ChildProcess.spawn("watchify", args);
    watcher.stdout.pipe(process.stdout);
    watcher.stderr.pipe(process.stderr);
  }
}

// All this mess is required because of dumb Gulp v3 architecture. TODO: reconsider at Gulp v4 release (undocumented yet!)
Gulp.task("dist-1.1", distFactory("1.1"));
Gulp.task("dist-1.2", distFactory("1.2"));
Gulp.task("dist-1.3", distFactory("1.3"));
Gulp.task("dist-2.1", distFactory("2.1"));
Gulp.task("dist-2.2", distFactory("2.2"));
Gulp.task("dist-3.1", distFactory("3.1"));
Gulp.task("dist-3.2", distFactory("3.2"));
Gulp.task("dist-3.3", distFactory("3.3"));
Gulp.task("dist-3.4", distFactory("3.4"));
Gulp.task("dist-4.1", distFactory("4.1"));
Gulp.task("dist-4.2", distFactory("4.2"));
Gulp.task("dist-4.3", distFactory("4.3"));
Gulp.task("dist-5.1", distFactory("5.1"));
Gulp.task("dist-6.1", distFactory("6.1"));
Gulp.task("dist-6.2", distFactory("6.2"));

Gulp.task("watchify-1.1", watchifyFactory("1.1"));
Gulp.task("watchify-1.2", watchifyFactory("1.2"));
Gulp.task("watchify-1.3", watchifyFactory("1.3"));
Gulp.task("watchify-2.1", watchifyFactory("2.1"));
Gulp.task("watchify-2.2", watchifyFactory("2.2"));
Gulp.task("watchify-3.1", watchifyFactory("3.1"));
Gulp.task("watchify-3.2", watchifyFactory("3.2"));
Gulp.task("watchify-3.3", watchifyFactory("3.3"));
Gulp.task("watchify-3.4", watchifyFactory("3.4"));
Gulp.task("watchify-4.1", watchifyFactory("4.1"));
Gulp.task("watchify-4.2", watchifyFactory("4.2"));
Gulp.task("watchify-4.3", watchifyFactory("4.3"));
Gulp.task("watchify-5.1", watchifyFactory("5.1"));
Gulp.task("watchify-6.1", watchifyFactory("6.1"));
Gulp.task("watchify-6.2", watchifyFactory("6.2"));

Gulp.task("dist-scripts", function () {
  RunSequence(
    "dist-1.1", "dist-1.2", "dist-1.3",
    "dist-2.1", "dist-2.2",
    "dist-3.1", "dist-3.2", "dist-3.3", "dist-3.4",
    "dist-4.1", "dist-4.2", "dist-4.3",
    "dist-5.1",
    "dist-6.1", "dist-6.2"
  )
});

Gulp.task("watch-build", function () {
  RunSequence(
    "watchify-1.1", "watchify-1.2", "watchify-1.3",
    "watchify-2.1", "watchify-2.2",
    "watchify-3.1", "watchify-3.2", "watchify-3.3", "watchify-3.4",
    "watchify-4.1", "watchify-4.2", "watchify-4.3",
    "watchify-5.1",
    "watchify-6.1", "watchify-6.2"
  )
});

Gulp.task("watch-src", function () {
  Gulp.watch("./frontend/**/*.js", ["build"]);
  Gulp.watch("./frontend/**/*.(jpg|png|gif)", ["dist-images"]);
  Gulp.watch("./frontend/**/*.css", ["dist-styles"]);
});

Gulp.task("dist", function () {
  exitOnError = true;
  return RunSequence(
    ["build"],
    ["dist-scripts", "dist-images", "dist-styles"]
  );
});

Gulp.task("watch", ["watch-src", "watch-build"]);<|endoftext|>


<commit_before>(function () {
    'use strict';

    var gulp, minifyHTML, concat, stripDebug, uglify, jshint, changed, imagemin, autoprefix, sass, rjs, minifyCSS,
        browserSync, pngquant, del, paths, host, themes, fs, request, recursive, configs, FOUNDATION_URI,
        THEME_AS_DEFAULT, DEV_FOUNDATION_URI, DEFAULT_ROOT, DEFAULT_PASS;

    gulp = require('gulp');
    minifyHTML = require('gulp-minify-html');
    concat = require('gulp-concat');
    stripDebug = require('gulp-strip-debug');
    uglify = require('gulp-uglify');
    jshint = require('gulp-jshint');
    changed = require('gulp-changed');
    imagemin = require('gulp-imagemin');
    autoprefix = require('gulp-autoprefixer');
    sass = require('gulp-sass');
    rjs = require('gulp-requirejs');
    minifyCSS = require('gulp-minify-css');
    browserSync = require('browser-sync');
    pngquant = require('imagemin-pngquant');
    del = require('del');
    fs = require('fs');
    request = require('request');
    recursive = require('recursive-readdir');
    paths = {
        "app": require('./bower.json').appPath || 'app',
        "dist": 'dist',
        "themes": 'themes',
        "js": ['app/scripts/*.js', 'app/scripts/**/*.js'],
        "vendor": 'app/lib/**/*.js',
        "vendorTheme": 'app/themes/**/lib/**/*',
        "sass": 'app/styles/sass/**/*.scss',
        "css": 'app/themes/**/styles/**/*.css',
        "images": ['app/themes/**/images/**/*', 'app/themes/**/styles/**/*.{png,jpg,jpec,ico}'],
        "fonts": ['app/themes/**/styles/fonts/**/*', 'app/themes/**/fonts/**/*'],
        "html": 'app/**/*.html',
        "misc": 'app/*.{txt,htaccess,ico}',
        "themeDest": "dist/themes",
        "themesDir": "./app/themes"

    };
    host = {
        port: '8080',
        lrPort: '35729'
    };

    themes = [];
    DEV_FOUNDATION_URI = 'http://localhost:3000';
    DEFAULT_ROOT = 'admin';
    DEFAULT_PASS = 'admin';
    FOUNDATION_URI = 'http://dev.ottemo.io:3000';
    THEME_AS_DEFAULT = 'blitz';

    configs = [
        {
            "path": "general.app.foundation_url",
            "value": FOUNDATION_URI,
            "type": "varchar(255)",
            "editor": "text",
            "options": "",
            "label": "Foundation host URL",
            "description": "URL application will use to generate foundation resources links"
        },
        {
            "path": "themes",
            "value": "",
            "type": "group",
            "editor": "",
            "options": "",
            "label": "Themes",
            "description": ""
        },
        {
            "path": "themes.list",
            "value": "",
            "type": "group",
            "editor": "themes_manager",
            "options": "",
            "label": "Themes",
            "description": ""
        },
        {
            "path": "themes.list.active",
            "value": THEME_AS_DEFAULT,
            "type": "",
            "editor": "themes_manager",
            "options": "",
            "label": "Active theme",
            "description": "Active theme on storefront"
        },
        {
            "path": "general.app.login.facebook.appId",
            "value": "483159925160897",
            "type": "varchar(255)",
            "editor": "text",
            "options": "",
            "label": "Facebook: App ID",
            "description": "Facebook: Application ID"
        },
        {
            "path": "general.app.login.facebook.secretKey",
            "value": "9a362f8b5cd91dbdd908bff472468c7e",
            "type": "varchar(255)",
            "editor": "text",
            "options": "",
            "label": "Facebook: App Secret",
            "description": "Facebook: Application secret key"
        },
        {
            "path": "general.app.login.google.clientId",
            "value": "1074763412644-qq25glj3tb87bq7bk5m8793da11ddheh.apps.googleusercontent.com",
            "type": "varchar(255)",
            "editor": "text",
            "options": "",
            "label": "Google: Client ID",
            "description": ""
        },
        {
            "path": "general.app.category.itemsPerPage",
            "value": 10,
            "type": "int",
            "editor": "text",
            "options": "",
            "label": "Items on page",
            "description": ""
        }
    ];

    var setConfigValue = function (field, path, option) {
        for (var i = 0; i < configs.length; i += 1) {
            if (configs[i].path === path) {
                configs[i][field] = option;
                break;
            }
        }
    };

    var setConfig = function (serverURI, config) {
        request({
            uri: serverURI + '/config/unregister/' + config.path + '?auth=' + DEFAULT_ROOT + ':' + DEFAULT_PASS,
            method: 'DELETE'
        }, function () {
            var r = request.post(serverURI + '/config/register?auth=' + DEFAULT_ROOT + ':' + DEFAULT_PASS);
            var form = r.form();

            form.append('path', config.path);
            form.append('value', config.value);
            form.append('type', config.type);
            form.append('editor', config.editor);
            form.append('options', config.options);
            form.append('label', config.label);
            form.append('description', config.description);
        });
    };

    var initConfigs = function (serverURI) {
        for (var i = 0; i < configs.length; i += 1) {
            setConfig(serverURI, configs[i]);
        }
    };

    // Empties folders to start fresh
    gulp.task('clean', function (cb) {
        del(['dist/*', '!dist/media'], cb);
    });

    // Actions with js-files from theme
    gulp.task('vendorTheme', ['clean'], function () {
        /**
         * Minify and uglify the custom scripts in folder 'scripts' in each theme
         */
        gulp.src('app/themes/**/scripts/**/*.js')
            .pipe(stripDebug())
            .pipe(uglify({mangle: false}))
            .pipe(gulp.dest(paths.themeDest));

        /**
         * copy vendor js from theme folder
         */
        return gulp.src(paths.vendorTheme)
            .pipe(gulp.dest(paths.themeDest));
    });

    // copy vendor js
    gulp.task('vendor', ['clean', 'vendorTheme'], function () {
        return gulp.src(paths.vendor)
            .pipe(gulp.dest(paths.dist + '/lib'));
    });

    // copy misc assets
    gulp.task('misc', ['clean'], function () {
        return gulp.src(paths.misc)
            .pipe(gulp.dest(paths.dist));
    });

    // Run JSHint
    gulp.task('jshint', function () {
        gulp.src(paths.js)
            .pipe(jshint())
            .pipe(jshint.reporter(require('jshint-stylish')));
    });

    gulp.task('requirejs', ['clean', 'jshint'], function () {
        rjs({
            out: 'main.js',
            name: 'main',
            preserveLicenseComments: false, // remove all comments
            removeCombined: true,
            baseUrl: paths.app + '/scripts',
            mainConfigFile: 'app/scripts/main.js',
            "paths": {
                // Don't attempt to include dependencies whose path begins with webapp/
                "config": "config"
            },
            "shim": {
                "config": {exports: "config"}
            }
        })
            .pipe(stripDebug())
            .pipe(uglify({mangle: false}))
            .pipe(gulp.dest(paths.dist + '/scripts/'));
    });

    // Sass task, will run when any SCSS files change & BrowserSync
    // will auto-update browsers
    gulp.task('sass', function () {
        return gulp.src(paths.sass)
            .pipe(sass({imagePath: '../../images'}))
            .pipe(autoprefix('last 1 version'))
            .pipe(gulp.dest(paths.dist + '/styles'))
            .pipe(gulp.dest(paths.app + '/styles'));
    });

    // minify new images
    gulp.task('imagemin', ['clean'], function () {
        return gulp.src(paths.images)
            .pipe(changed(paths.themeDest))
            .pipe(imagemin())
            .pipe(gulp.dest(paths.themeDest));
    });

    // minify new or changed HTML pages
    gulp.task('html', ['clean'], function () {
        return gulp.src(paths.html)
            .pipe(changed(paths.dist))
            .pipe(minifyHTML({
                collapseWhitespace: true,
                collapseBooleanAttributes: true,
                removeCommentsFromCDATA: true,
                removeOptionalTags: true,
                conditionals: true,
                quotes: true,
                empty: true
            }))
            .pipe(gulp.dest(paths.dist));
    });

    // CSS auto-prefix and minify
    gulp.task('autoprefixer', ['clean', 'sass'], function () {
        gulp.src(paths.css)
            .pipe(autoprefix('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
            .pipe(minifyCSS())
            .pipe(gulp.dest(paths.themeDest));
        gulp.src(paths.fonts)
            .pipe(gulp.dest(paths.themeDest));
    });

    // Protractor tests
    // gulp.task('protractorUpdate', protractor.webdriverUpdate);
    // gulp.task('protractor', ['protractorUpdate'], function (cb) {
    //     gulp.src(['tests/e2e/**/*.js']).pipe(protractor.protractor({
    //         configFile: 'protractor.conf.js'
    //     })).on('error', function (e) {
    //         console.log(e);
    //     }).on('end', cb);
    // });
    //
    // // Jasmine test
    // gulp.task('jasmine', function() {
    //     gulp.src('spec/**/*.js')
    //         .pipe(jasmine({verbose:true, includeStackTrace: true}));
    // });
    //
    // gulp.task('test', ['protractor', 'jasmine'], function () {});

    // browser-sync task for starting server
    gulp.task('browser-sync', function () {
        browserSync({
            server: {
                baseDir: './app'
            },
            port: host.port
        });
    });

    gulp.task('bs-reload', function () {
        browserSync.reload();
    });

    // run in development mode with easy browser reloading
    gulp.task('dev', ['browser-sync'], function () {

        gulp.watch('app/views/**/*.html', [browserSync.reload]);
        gulp.watch('app/styles/**/*.css', [browserSync.reload]);
        gulp.watch('app/styles/**/*.scss', ['sass', browserSync.reload]);
        gulp.watch('app/scripts/**/*.js', ['jshint', browserSync.reload]);
    });

    gulp.task('serve', ['dev', 'retrieve-files']);

    gulp.task('build', function () {
        var jsCode, themesData;
        themesData = '';

        recursive(paths.themesDir, function (err, files) {
            var i, theme, filePath, parts, regExp;
            theme = null;
            regExp = new RegExp('app[/\\\\]themes[/\\\\](\\w+)[/\\\\](.+)', 'i');

            jsCode = '/* jshint ignore:start */\n' +
                '(function (define) {\n' +
                '"use strict";\n' +
                'define(function () {\n' +
                'return {\n';

            for (i = 0; i < files.length; i += 1) {
                filePath = files[i];
                parts = filePath.match(regExp);
                if (parts instanceof Array) {
                    if (theme !== parts[1] && theme === null) {
                        themes.push(parts[1]);
                        jsCode += '\'' + parts[1] + '\' : [\n';
                    }
                    if (theme !== parts[1] && theme !== null) {
                        themes.push(parts[1]);
                        jsCode += '],\n\'' + parts[1] + '\' : [\n';
                    }
                    jsCode += '\'/' + parts[2] + '\',\n';
                    theme = parts[1];
                }
            }

            jsCode += ']\n};\n' +
                '});\n' +
                '})(window.define);\n' +
                '/* jshint ignore:end */';

            fs.writeFile('./app/scripts/design/themeFiles.js', jsCode, function (err) {
                if (err) {
                    return console.log(err);
                }
            });

            themesData = '{';
            for (i = 0; i < themes.length; i += 1) {
                themesData += '"' + themes[i] + '":"' + themes[i] + '"';
                if (i < themes.length - 1) {
                    themesData += ',';
                }
            }
            themesData += '}';

            setConfigValue("options", "themes.list.active", themesData);
            setConfigValue("value", "general.app.foundation_url", FOUNDATION_URI);
            initConfigs(FOUNDATION_URI);

            gulp.start('requirejs');
            gulp.start('vendor');
            gulp.start('misc');
            gulp.start('html');
            gulp.start('autoprefixer');
            gulp.start('imagemin');
        });
    });

    gulp.task('default', ['build']);

    gulp.task('retrieve-files', function () {
        var jsCode, themesData;
        themesData = '';

        recursive(paths.themesDir, function (err, files) {
            var i, theme, filePath, parts, regExp;
            theme = null;
            regExp = new RegExp('app[/\\\\]themes[/\\\\](\\w+)[/\\\\](.+)', 'i');

            jsCode = '/* jshint ignore:start */\n' +
                '(function (define) {\n' +
                '"use strict";\n' +
                'define(function () {\n' +
                'return {\n';

            for (i = 0; i < files.length; i += 1) {
                filePath = files[i];
                parts = filePath.match(regExp);
                if (parts instanceof Array) {
                    if (theme !== parts[1] && theme === null) {
                        themes.push(parts[1]);
                        jsCode += '\'' + parts[1] + '\' : [\n';
                    }
                    if (theme !== parts[1] && theme !== null) {
                        themes.push(parts[1]);
                        jsCode += '],\n\'' + parts[1] + '\' : [\n';
                    }
                    jsCode += '\'/' + parts[2] + '\',\n';
                    theme = parts[1];
                }
            }

            jsCode += ']\n};\n' +
                '});\n' +
                '})(window.define);\n' +
                '/* jshint ignore:end */';

            fs.writeFile('./app/scripts/design/themeFiles.js', jsCode, function (err) {
                if (err) {
                    return console.log(err);
                }
            });
            themesData = '{';
            for (i = 0; i < themes.length; i += 1) {
                themesData += '"' + themes[i] + '":"' + themes[i] + '"';
                if (i < themes.length - 1) {
                    themesData += ',';
                }
            }
            themesData += '}';

            setConfigValue("options", "themes.list.active", themesData);
            setConfigValue("value", "general.app.foundation_url", DEV_FOUNDATION_URI);
            initConfigs(DEV_FOUNDATION_URI);
        });

    });

})();
<commit_msg>handle errors w/verbosity on pipe<commit_after>(function () {
    'use strict';

    var gulp, minifyHTML, concat, stripDebug, uglify, jshint, changed, imagemin, autoprefix, sass, rjs, minifyCSS,
        browserSync, pngquant, del, paths, host, themes, fs, request, recursive, configs, FOUNDATION_URI,
        THEME_AS_DEFAULT, DEV_FOUNDATION_URI, DEFAULT_ROOT, DEFAULT_PASS;

    gulp = require('gulp');
    minifyHTML = require('gulp-minify-html');
    concat = require('gulp-concat');
    stripDebug = require('gulp-strip-debug');
    uglify = require('gulp-uglify');
    jshint = require('gulp-jshint');
    changed = require('gulp-changed');
    imagemin = require('gulp-imagemin');
    autoprefix = require('gulp-autoprefixer');
    sass = require('gulp-sass');
    rjs = require('gulp-requirejs');
    minifyCSS = require('gulp-minify-css');
    browserSync = require('browser-sync');
    pngquant = require('imagemin-pngquant');
    del = require('del');
    fs = require('fs');
    request = require('request');
    recursive = require('recursive-readdir');
    paths = {
        "app": require('./bower.json').appPath || 'app',
        "dist": 'dist',
        "themes": 'themes',
        "js": ['app/scripts/*.js', 'app/scripts/**/*.js'],
        "vendor": 'app/lib/**/*.js',
        "vendorTheme": 'app/themes/**/lib/**/*',
        "sass": 'app/styles/sass/**/*.scss',
        "css": 'app/themes/**/styles/**/*.css',
        "images": ['app/themes/**/images/**/*', 'app/themes/**/styles/**/*.{png,jpg,jpec,ico}'],
        "fonts": ['app/themes/**/styles/fonts/**/*', 'app/themes/**/fonts/**/*'],
        "html": 'app/**/*.html',
        "misc": 'app/*.{txt,htaccess,ico}',
        "themeDest": "dist/themes",
        "themesDir": "./app/themes"

    };
    host = {
        port: '8080',
        lrPort: '35729'
    };

    themes = [];
    DEV_FOUNDATION_URI = 'http://localhost:3000';
    DEFAULT_ROOT = 'admin';
    DEFAULT_PASS = 'admin';
    FOUNDATION_URI = 'http://dev.ottemo.io:3000';
    THEME_AS_DEFAULT = 'blitz';

    configs = [
        {
            "path": "general.app.foundation_url",
            "value": FOUNDATION_URI,
            "type": "varchar(255)",
            "editor": "text",
            "options": "",
            "label": "Foundation host URL",
            "description": "URL application will use to generate foundation resources links"
        },
        {
            "path": "themes",
            "value": "",
            "type": "group",
            "editor": "",
            "options": "",
            "label": "Themes",
            "description": ""
        },
        {
            "path": "themes.list",
            "value": "",
            "type": "group",
            "editor": "themes_manager",
            "options": "",
            "label": "Themes",
            "description": ""
        },
        {
            "path": "themes.list.active",
            "value": THEME_AS_DEFAULT,
            "type": "",
            "editor": "themes_manager",
            "options": "",
            "label": "Active theme",
            "description": "Active theme on storefront"
        },
        {
            "path": "general.app.login.facebook.appId",
            "value": "483159925160897",
            "type": "varchar(255)",
            "editor": "text",
            "options": "",
            "label": "Facebook: App ID",
            "description": "Facebook: Application ID"
        },
        {
            "path": "general.app.login.facebook.secretKey",
            "value": "9a362f8b5cd91dbdd908bff472468c7e",
            "type": "varchar(255)",
            "editor": "text",
            "options": "",
            "label": "Facebook: App Secret",
            "description": "Facebook: Application secret key"
        },
        {
            "path": "general.app.login.google.clientId",
            "value": "1074763412644-qq25glj3tb87bq7bk5m8793da11ddheh.apps.googleusercontent.com",
            "type": "varchar(255)",
            "editor": "text",
            "options": "",
            "label": "Google: Client ID",
            "description": ""
        },
        {
            "path": "general.app.category.itemsPerPage",
            "value": 10,
            "type": "int",
            "editor": "text",
            "options": "",
            "label": "Items on page",
            "description": ""
        }
    ];

    var setConfigValue = function (field, path, option) {
        for (var i = 0; i < configs.length; i += 1) {
            if (configs[i].path === path) {
                configs[i][field] = option;
                break;
            }
        }
    };

    var setConfig = function (serverURI, config) {
        request({
            uri: serverURI + '/config/unregister/' + config.path + '?auth=' + DEFAULT_ROOT + ':' + DEFAULT_PASS,
            method: 'DELETE'
        }, function () {
            var r = request.post(serverURI + '/config/register?auth=' + DEFAULT_ROOT + ':' + DEFAULT_PASS);
            var form = r.form();

            form.append('path', config.path);
            form.append('value', config.value);
            form.append('type', config.type);
            form.append('editor', config.editor);
            form.append('options', config.options);
            form.append('label', config.label);
            form.append('description', config.description);
        });
    };

    var initConfigs = function (serverURI) {
        for (var i = 0; i < configs.length; i += 1) {
            setConfig(serverURI, configs[i]);
        }
    };

    // Empties folders to start fresh
    gulp.task('clean', function (cb) {
        del(['dist/*', '!dist/media'], cb);
    });

    // Actions with js-files from theme
    gulp.task('vendorTheme', ['clean'], function () {
        /**
         * Minify and uglify the custom scripts in folder 'scripts' in each theme
         */
        gulp.src('app/themes/**/scripts/**/*.js')
            .pipe(stripDebug())
            .on('error', console.log.bind(console))
            .pipe(uglify({mangle: false}))
            .pipe(gulp.dest(paths.themeDest));

        /**
         * copy vendor js from theme folder
         */
        return gulp.src(paths.vendorTheme)
            .pipe(gulp.dest(paths.themeDest));
    });

    // copy vendor js
    gulp.task('vendor', ['clean', 'vendorTheme'], function () {
        return gulp.src(paths.vendor)
            .pipe(gulp.dest(paths.dist + '/lib'));
    });

    // copy misc assets
    gulp.task('misc', ['clean'], function () {
        return gulp.src(paths.misc)
            .pipe(gulp.dest(paths.dist));
    });

    // Run JSHint
    gulp.task('jshint', function () {
        gulp.src(paths.js)
            .pipe(jshint())
            .pipe(jshint.reporter(require('jshint-stylish')));
    });

    gulp.task('requirejs', ['clean', 'jshint'], function () {
        rjs({
            out: 'main.js',
            name: 'main',
            preserveLicenseComments: false, // remove all comments
            removeCombined: true,
            baseUrl: paths.app + '/scripts',
            mainConfigFile: 'app/scripts/main.js',
            "paths": {
                // Don't attempt to include dependencies whose path begins with webapp/
                "config": "config"
            },
            "shim": {
                "config": {exports: "config"}
            }
        })
            .pipe(stripDebug())
            .on('error', console.error.bind(console))
            .pipe(uglify({mangle: false}))
            .pipe(gulp.dest(paths.dist + '/scripts/'));
    });

    // Sass task, will run when any SCSS files change & BrowserSync
    // will auto-update browsers
    gulp.task('sass', function () {
        return gulp.src(paths.sass)
            .pipe(sass({imagePath: '../../images'}))
            .pipe(autoprefix('last 1 version'))
            .pipe(gulp.dest(paths.dist + '/styles'))
            .pipe(gulp.dest(paths.app + '/styles'));
    });

    // minify new images
    gulp.task('imagemin', ['clean'], function () {
        return gulp.src(paths.images)
            .pipe(changed(paths.themeDest))
            .pipe(imagemin())
            .pipe(gulp.dest(paths.themeDest));
    });

    // minify new or changed HTML pages
    gulp.task('html', ['clean'], function () {
        return gulp.src(paths.html)
            .pipe(changed(paths.dist))
            .pipe(minifyHTML({
                collapseWhitespace: true,
                collapseBooleanAttributes: true,
                removeCommentsFromCDATA: true,
                removeOptionalTags: true,
                conditionals: true,
                quotes: true,
                empty: true
            }))
            .pipe(gulp.dest(paths.dist));
    });

    // CSS auto-prefix and minify
    gulp.task('autoprefixer', ['clean', 'sass'], function () {
        gulp.src(paths.css)
            .pipe(autoprefix('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
            .pipe(minifyCSS())
            .pipe(gulp.dest(paths.themeDest));
        gulp.src(paths.fonts)
            .pipe(gulp.dest(paths.themeDest));
    });

    // Protractor tests
    // gulp.task('protractorUpdate', protractor.webdriverUpdate);
    // gulp.task('protractor', ['protractorUpdate'], function (cb) {
    //     gulp.src(['tests/e2e/**/*.js']).pipe(protractor.protractor({
    //         configFile: 'protractor.conf.js'
    //     })).on('error', function (e) {
    //         console.log(e);
    //     }).on('end', cb);
    // });
    //
    // // Jasmine test
    // gulp.task('jasmine', function() {
    //     gulp.src('spec/**/*.js')
    //         .pipe(jasmine({verbose:true, includeStackTrace: true}));
    // });
    //
    // gulp.task('test', ['protractor', 'jasmine'], function () {});

    // browser-sync task for starting server
    gulp.task('browser-sync', function () {
        browserSync({
            server: {
                baseDir: './app'
            },
            port: host.port
        });
    });

    gulp.task('bs-reload', function () {
        browserSync.reload();
    });

    // run in development mode with easy browser reloading
    gulp.task('dev', ['browser-sync'], function () {

        gulp.watch('app/views/**/*.html', [browserSync.reload]);
        gulp.watch('app/styles/**/*.css', [browserSync.reload]);
        gulp.watch('app/styles/**/*.scss', ['sass', browserSync.reload]);
        gulp.watch('app/scripts/**/*.js', ['jshint', browserSync.reload]);
    });

    gulp.task('serve', ['dev', 'retrieve-files']);

    gulp.task('build', function () {
        var jsCode, themesData;
        themesData = '';

        recursive(paths.themesDir, function (err, files) {
            var i, theme, filePath, parts, regExp;
            theme = null;
            regExp = new RegExp('app[/\\\\]themes[/\\\\](\\w+)[/\\\\](.+)', 'i');

            jsCode = '/* jshint ignore:start */\n' +
                '(function (define) {\n' +
                '"use strict";\n' +
                'define(function () {\n' +
                'return {\n';

            for (i = 0; i < files.length; i += 1) {
                filePath = files[i];
                parts = filePath.match(regExp);
                if (parts instanceof Array) {
                    if (theme !== parts[1] && theme === null) {
                        themes.push(parts[1]);
                        jsCode += '\'' + parts[1] + '\' : [\n';
                    }
                    if (theme !== parts[1] && theme !== null) {
                        themes.push(parts[1]);
                        jsCode += '],\n\'' + parts[1] + '\' : [\n';
                    }
                    jsCode += '\'/' + parts[2] + '\',\n';
                    theme = parts[1];
                }
            }

            jsCode += ']\n};\n' +
                '});\n' +
                '})(window.define);\n' +
                '/* jshint ignore:end */';

            fs.writeFile('./app/scripts/design/themeFiles.js', jsCode, function (err) {
                if (err) {
                    return console.log(err);
                }
            });

            themesData = '{';
            for (i = 0; i < themes.length; i += 1) {
                themesData += '"' + themes[i] + '":"' + themes[i] + '"';
                if (i < themes.length - 1) {
                    themesData += ',';
                }
            }
            themesData += '}';

            setConfigValue("options", "themes.list.active", themesData);
            setConfigValue("value", "general.app.foundation_url", FOUNDATION_URI);
            initConfigs(FOUNDATION_URI);

            gulp.start('requirejs');
            gulp.start('vendor');
            gulp.start('misc');
            gulp.start('html');
            gulp.start('autoprefixer');
            gulp.start('imagemin');
        });
    });

    gulp.task('default', ['build']);

    gulp.task('retrieve-files', function () {
        var jsCode, themesData;
        themesData = '';

        recursive(paths.themesDir, function (err, files) {
            var i, theme, filePath, parts, regExp;
            theme = null;
            regExp = new RegExp('app[/\\\\]themes[/\\\\](\\w+)[/\\\\](.+)', 'i');

            jsCode = '/* jshint ignore:start */\n' +
                '(function (define) {\n' +
                '"use strict";\n' +
                'define(function () {\n' +
                'return {\n';

            for (i = 0; i < files.length; i += 1) {
                filePath = files[i];
                parts = filePath.match(regExp);
                if (parts instanceof Array) {
                    if (theme !== parts[1] && theme === null) {
                        themes.push(parts[1]);
                        jsCode += '\'' + parts[1] + '\' : [\n';
                    }
                    if (theme !== parts[1] && theme !== null) {
                        themes.push(parts[1]);
                        jsCode += '],\n\'' + parts[1] + '\' : [\n';
                    }
                    jsCode += '\'/' + parts[2] + '\',\n';
                    theme = parts[1];
                }
            }

            jsCode += ']\n};\n' +
                '});\n' +
                '})(window.define);\n' +
                '/* jshint ignore:end */';

            fs.writeFile('./app/scripts/design/themeFiles.js', jsCode, function (err) {
                if (err) {
                    return console.log(err);
                }
            });
            themesData = '{';
            for (i = 0; i < themes.length; i += 1) {
                themesData += '"' + themes[i] + '":"' + themes[i] + '"';
                if (i < themes.length - 1) {
                    themesData += ',';
                }
            }
            themesData += '}';

            setConfigValue("options", "themes.list.active", themesData);
            setConfigValue("value", "general.app.foundation_url", DEV_FOUNDATION_URI);
            initConfigs(DEV_FOUNDATION_URI);
        });

    });

})();
<|endoftext|>


<commit_before>var gulp = require("gulp");

require("../gulp-ps-tasks/tasks")(gulp);<commit_msg>Changed gulp-ps-tasks import path<commit_after>var gulp = require("gulp");

require("../tasks")(gulp);<|endoftext|>


<commit_before>'use strict';

var config = require('../../config/environment');
var User = require('./user.model');
var userService = require('./user.service');
var mongoose = require('mongoose');
var authService = require('../auth/auth.service');

var validationError = function (res, err) {
  return res.status(422).json(err);
};

exports.create = function (req, res) {
  if (req.body.userId) {
    req.body.createdBy = req.body.userId;
    var isValidGender = userService.validateGenderSync(req.body.gender);
    if (!isValidGender) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "Gender is not accepted"
      });
    }
  }

  if (req.body.isParent === false) {
    req.body.roles = [];
    req.body.roles.push('coach');
  }
  var user = new User(req.body);
  if (!config.isLoanUser) {
    var isValidBirthDate = userService.validateBirthDateSync(req.body.birthDate);
    if (!isValidBirthDate) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "Birth date is not accepted"
      });
    };
  } else {
    if (!req.body.ssn || !userService.verifySSN(user.ssn)) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "SSN is not valid"
      });
    }
    user.ssn = userService.encryptSSN(req.body.ssn);
  }

  var isValidFirstName = userService.validateFirstNameSync(req.body.firstName);
  if (!isValidFirstName) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "First name is not accepted"
    });
  }
  var isValidLastName = userService.validateLastNameSync(req.body.lastName);
  if (!isValidLastName) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "Last name is not accepted"
    });
  }
  userService.save(user, function (err, data) {

    if (err) return validationError(res, err);
    return res.status(200).json({ userId: data._id });
  });
};

exports.createAll = function (req, res) {
  var body = req.body;
  if (!body) {
    return res.status(422).json({ message: 'request can`t be empty' });
  }
  if (!body.firstName) {
    return res.status(422).json({ message: 'firstName is require' });
  }
  if (!body.lastName) {
    return res.status(422).json({ message: 'lastName is require' });
  }
  if (!body.email) {
    return res.status(422).json({ message: 'email is require' });
  }
  if (!body.password) {
    return res.status(422).json({ message: 'password is require' });
  }
  if (!body.address) {
    return res.status(422).json({ message: 'address is require' });
  }
  if (!body.city) {
    return res.status(422).json({ message: 'city is require' });
  }
  if (!body.state) {
    return res.status(422).json({ message: 'state is require' });
  }
  if (!body.country) {
    return res.status(422).json({ message: 'country is require' });
  }
  if (!body.zipCode) {
    return res.status(422).json({ message: 'zipCode is require' });
  }
  if (!body.phone) {
    return res.status(422).json({ message: 'phone is require' });
  }
  if (!body.getFrom) {
    return res.status(422).json({ message: 'getFrom is require' });
  }

  userService.createAll(body, function (err, data) {
    if (err) {
      return res.status(500).json(err);
    }
    return res.status(200).json(data);
  })

}

exports.me = function (req, res, next) {
  authService.decryptToken(req.query.token, function (err, id) {
    if (err) {
      return res.status(401).json({
        code: "AuthFailed",
        message: "Authentication token is invalid"
      });
    }
    userService.findOne({
      _id: id
    }, '-salt -hashedPassword -verify.token -verify.updatedAt -role -updateAt -createAt -resetPassword', function (err, user) { // don't ever give out the password or salt
      if (err) return next(err);
      if (!user) return res.status(401).json({
        code: "AuthFailed",
        message: "Couldn't find a user with the given token"
      });
      res.status(200).json(user);
    });

  });
};

exports.update = function (req, res, next) {
  var userId = req.params.userId;
  var userUpdate = req.body.userId;
  var isValidFirstName = userService.validateFirstNameSync(req.body.firstName);
  if (!isValidFirstName) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "First name is not accepted"
    });
  }

  var isValidLastName = userService.validateLastNameSync(req.body.lastName);
  if (!isValidLastName) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "Last name is not accepted"
    });
  }
  var filter = { _id: userId };
  if (userUpdate != userId) {//Here - validate if user is parent or athlete.
    var isValidGender = userService.validateGenderSync(req.body.gender);
    if (!isValidGender) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "Gender is not accepted"
      });
    }
    var isValidBirthDate = userService.validateBirthDateSync(req.body.birthDate);
    if (!isValidBirthDate) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "Birthdate is not accepted"
      });
    }
    filter = { _id: userUpdate };

  }
  userService.findOne(filter, '', function (err, userFind) {
    if (err) return res.status(409).json(res, err);
    if (!userFind) {
      return res.status(404).json({
        "code": "AuthCredentialNotExists",
        "message": "User Id does not exist"
      });
    }
    userFind.firstName = req.body.firstName;
    userFind.lastName = req.body.lastName;
    if (userUpdate != userId) {//move to user.service
      userFind.gender = req.body.gender;
      userFind.birthDate = req.body.birthDate;
    }
    userService.save(userFind, function (err, userSave) {
      if (err) return validationError(res, err);
      res.status(200).json({});
    });
  });
};

exports.find = function (req, res, next) {
  var filter = req.body;
  userService.find(filter, '', function (err, users) {
    if (err) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "filter incorrect."
      });
    }
    if (!users) return res.status(403).json({
      "code": "User permission error",
      "message": "You don't have permission for this operation"
    });
    if (config.isLoanUser && (users.length = 1)) {
      users[0].ssn = userService.getlast4ssn(users[0].ssn);
    }
    res.status(200).json(users);
  });
};

exports.save = function (req, res, next) {
  var filter = { _id: req.body._id };
  userService.update(filter, req.body, function (err, userUpd) {
    if (err) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "filter incorrect update."
      });
    }
    if (!userUpd) {
      return res.status(403).json({
        "code": "User permission error",
        "message": "You don't have permission for this operation"
      });
    }
    userService.findOne(filter, '', function (err, user) {
      if (err) {
        return res.status(400).json({
          "code": "ValidationError",
          "message": "filter incorrect find."
        });
      }
      if (!user) {
        return res.status(403).json({
          "code": "User permission error",
          "message": "You don't have permission for this operation"
        });
      }
      res.status(200).json(user);
    });
  });
}

exports.validateSign = function (req, res, next) {
  if (!req.body.userId || !req.body.firstName || !req.body.lastName || !req.body.ssn) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "sign is incorrect"
    });
  }
  userService.findById(req.body.userId, function (err, user) {
    if (err) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "user is incorrect"
      });
    }
    var ssnDecypt = userService.getlast4ssn(user.ssn);
    if (user.firstName === req.body.firstName && user.lastName === req.body.lastName && ssnDecypt === req.body.ssn) {
      return res.status(200).json({ isCorrect: true });
    } else {
      return res.status(200).json({ isCorrect: false });
    }
  });
}

exports.updateProductsSuggested = function (req, res, next) {
  var id = req.params.userId;
  var productsSuggested = req.body;
  if (!id) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "User id is required."
    });
  }

  if (!productsSuggested) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "productsSuggested obj is required."
    });
  }

  userService.productsSuggested(id, productsSuggested, function (err, user) {
    if (err) {
      return res.status(500).json(err);
    } else {
      return res.status(200).json(user);
    }
  });
};
/**
 * Authentication callback
 */
exports.authCallback = function (req, res, next) {
  res.redirect('/');
};
<commit_msg>PU-266<commit_after>'use strict';

var config = require('../../config/environment');
var User = require('./user.model');
var userService = require('./user.service');
var mongoose = require('mongoose');
var authService = require('../auth/auth.service');

var validationError = function (res, err) {
  return res.status(422).json(err);
};

exports.create = function (req, res) {
  if (req.body.userId) {
    req.body.createdBy = req.body.userId;
    var isValidGender = userService.validateGenderSync(req.body.gender);
    if (!isValidGender) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "Gender is not accepted"
      });
    }
  }

  if (req.body.isParent === false) {
    req.body.roles = [];
    req.body.roles.push('coach');
  }
  var user = new User(req.body);
  if (!config.isLoanUser) {
    var isValidBirthDate = userService.validateBirthDateSync(req.body.birthDate);
    if (!isValidBirthDate) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "Birth date is not accepted"
      });
    };
  } else {
    if (!req.body.ssn || !userService.verifySSN(user.ssn)) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "SSN is not valid"
      });
    }
    user.ssn = userService.encryptSSN(req.body.ssn);
  }

  var isValidFirstName = userService.validateFirstNameSync(req.body.firstName);
  if (!isValidFirstName) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "First name is not accepted"
    });
  }
  var isValidLastName = userService.validateLastNameSync(req.body.lastName);
  if (!isValidLastName) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "Last name is not accepted"
    });
  }
  userService.save(user, function (err, data) {

    if (err) return validationError(res, err);
    return res.status(200).json({ userId: data._id });
  });
};

exports.createAll = function (req, res) {
  var body = req.body;
  if (!body) {
    return res.status(422).json({ message: 'request can`t be empty' });
  }
  if (!body.firstName) {
    return res.status(422).json({ message: 'firstName is require' });
  }
  if (!body.lastName) {
    return res.status(422).json({ message: 'lastName is require' });
  }
  if (!body.email) {
    return res.status(422).json({ message: 'email is require' });
  }
  if (!body.password) {
    return res.status(422).json({ message: 'password is require' });
  }
  if (!body.address) {
    return res.status(422).json({ message: 'address is require' });
  }
  if (!body.city) {
    return res.status(422).json({ message: 'city is require' });
  }
  if (!body.state) {
    return res.status(422).json({ message: 'state is require' });
  }
  if (!body.country) {
    return res.status(422).json({ message: 'country is require' });
  }
  if (!body.zipCode) {
    return res.status(422).json({ message: 'zipCode is require' });
  }
  if (!body.phone) {
    return res.status(422).json({ message: 'phone is require' });
  }
  if (!body.getFrom) {
    return res.status(422).json({ message: 'getFrom is require' });
  }

  userService.createAll(body, function (err, data) {
    if (err) {
      return res.status(500).json(err);
    }
    body.id = data._id
    return res.status(200).json(body);
  })

}

exports.me = function (req, res, next) {
  authService.decryptToken(req.query.token, function (err, id) {
    if (err) {
      return res.status(401).json({
        code: "AuthFailed",
        message: "Authentication token is invalid"
      });
    }
    userService.findOne({
      _id: id
    }, '-salt -hashedPassword -verify.token -verify.updatedAt -role -updateAt -createAt -resetPassword', function (err, user) { // don't ever give out the password or salt
      if (err) return next(err);
      if (!user) return res.status(401).json({
        code: "AuthFailed",
        message: "Couldn't find a user with the given token"
      });
      res.status(200).json(user);
    });

  });
};

exports.update = function (req, res, next) {
  var userId = req.params.userId;
  var userUpdate = req.body.userId;
  var isValidFirstName = userService.validateFirstNameSync(req.body.firstName);
  if (!isValidFirstName) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "First name is not accepted"
    });
  }

  var isValidLastName = userService.validateLastNameSync(req.body.lastName);
  if (!isValidLastName) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "Last name is not accepted"
    });
  }
  var filter = { _id: userId };
  if (userUpdate != userId) {//Here - validate if user is parent or athlete.
    var isValidGender = userService.validateGenderSync(req.body.gender);
    if (!isValidGender) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "Gender is not accepted"
      });
    }
    var isValidBirthDate = userService.validateBirthDateSync(req.body.birthDate);
    if (!isValidBirthDate) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "Birthdate is not accepted"
      });
    }
    filter = { _id: userUpdate };

  }
  userService.findOne(filter, '', function (err, userFind) {
    if (err) return res.status(409).json(res, err);
    if (!userFind) {
      return res.status(404).json({
        "code": "AuthCredentialNotExists",
        "message": "User Id does not exist"
      });
    }
    userFind.firstName = req.body.firstName;
    userFind.lastName = req.body.lastName;
    if (userUpdate != userId) {//move to user.service
      userFind.gender = req.body.gender;
      userFind.birthDate = req.body.birthDate;
    }
    userService.save(userFind, function (err, userSave) {
      if (err) return validationError(res, err);
      res.status(200).json({});
    });
  });
};

exports.find = function (req, res, next) {
  var filter = req.body;
  userService.find(filter, '', function (err, users) {
    if (err) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "filter incorrect."
      });
    }
    if (!users) return res.status(403).json({
      "code": "User permission error",
      "message": "You don't have permission for this operation"
    });
    if (config.isLoanUser && (users.length = 1)) {
      users[0].ssn = userService.getlast4ssn(users[0].ssn);
    }
    res.status(200).json(users);
  });
};

exports.save = function (req, res, next) {
  var filter = { _id: req.body._id };
  userService.update(filter, req.body, function (err, userUpd) {
    if (err) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "filter incorrect update."
      });
    }
    if (!userUpd) {
      return res.status(403).json({
        "code": "User permission error",
        "message": "You don't have permission for this operation"
      });
    }
    userService.findOne(filter, '', function (err, user) {
      if (err) {
        return res.status(400).json({
          "code": "ValidationError",
          "message": "filter incorrect find."
        });
      }
      if (!user) {
        return res.status(403).json({
          "code": "User permission error",
          "message": "You don't have permission for this operation"
        });
      }
      res.status(200).json(user);
    });
  });
}

exports.validateSign = function (req, res, next) {
  if (!req.body.userId || !req.body.firstName || !req.body.lastName || !req.body.ssn) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "sign is incorrect"
    });
  }
  userService.findById(req.body.userId, function (err, user) {
    if (err) {
      return res.status(400).json({
        "code": "ValidationError",
        "message": "user is incorrect"
      });
    }
    var ssnDecypt = userService.getlast4ssn(user.ssn);
    if (user.firstName === req.body.firstName && user.lastName === req.body.lastName && ssnDecypt === req.body.ssn) {
      return res.status(200).json({ isCorrect: true });
    } else {
      return res.status(200).json({ isCorrect: false });
    }
  });
}

exports.updateProductsSuggested = function (req, res, next) {
  var id = req.params.userId;
  var productsSuggested = req.body;
  if (!id) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "User id is required."
    });
  }

  if (!productsSuggested) {
    return res.status(400).json({
      "code": "ValidationError",
      "message": "productsSuggested obj is required."
    });
  }

  userService.productsSuggested(id, productsSuggested, function (err, user) {
    if (err) {
      return res.status(500).json(err);
    } else {
      return res.status(200).json(user);
    }
  });
};
/**
 * Authentication callback
 */
exports.authCallback = function (req, res, next) {
  res.redirect('/');
};
<|endoftext|>


<commit_before>'use strict';

var User = require('./user.model');
var passport = require('passport');
var config = require('../../config/environment');

/**
 * Creates a new user
 */ exports.create = function (req, res, next) {
  var newUser = new User(req.body);
  newUser.save(function(err, user) {
    if (err) return next(err);
    res.json(user);
  });
};

/**
 * Get a single user
 */
exports.show = function (req, res, next) {
  User.findOne({token: req.headers.token}, function (err, user) {
    if (err) return next(err);
    if (!user) return res.send(404, "No user found");
    res.json(user);
  });
};

/**
 * Update start_date
 */
exports.update = function (req, res, next) {
  User.findOne({token: req.headers.token}, function (err, user) {
    if (err) return next(err);
    if (!user) return res.send(404, "No user found");
    if (!req.body.start_date) return res.send(422, "Please provide a start date");
    user.start_date = req.body.start_date;
    user.save(function(err, user) {
      res.json(user);
    });
  });
};
<commit_msg>log req<commit_after>'use strict';

var User = require('./user.model');
var passport = require('passport');
var config = require('../../config/environment');

/**
 * Creates a new user
 */ exports.create = function (req, res, next) {
  var newUser = new User(req.body);
  newUser.save(function(err, user) {
    if (err) return next(err);
    res.json(user);
  });
};

/**
 * Get a single user
 */
exports.show = function (req, res, next) {
  User.findOne({token: req.headers.token}, function (err, user) {
    if (err) return next(err);
    if (!user) return res.send(404, "No user found");
    res.json(user);
  });
};

/**
 * Update start_date
 */
exports.update = function (req, res, next) {
  User.findOne({token: req.headers.token}, function (err, user) {
    if (err) return next(err);
    if (!user) return res.send(404, "No user found");
    if (!req.body.start_date) return res.send(422, "Please provide a start date");
    user.start_date = req.body.start_date;
    console.log(req.body);
    user.save(function(err, user) {
      res.json(user);
    });
  });
};
<|endoftext|>


<commit_before>var fs = require('fs'),
    gulp = require('gulp'),
    debug = require('gulp-debug'),
    cache = require('gulp-cached'),
    exec = require('child_process').exec,
    rename = require('gulp-rename'),
    browserify = require('gulp-browserify'),
    header = require('gulp-header'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    ts = require('gulp-typescript');

console.log(fs.readFileSync('./LICENSE', 'utf8'));

var tsProject = ts.createProject('tsconfig.json');

gulp.task('browserify', function() {
    var tsResult = gulp.src('**/*.ts')
      .pipe(tsProject())
      .js.pipe(browserify({
        })).
        pipe(rename(function(path) {
            path.basename = 'neuralnetwork0';
        })).
        pipe(header(
            '/**' + fs.readFileSync('./LICENSE', 'utf8') + '*/\n\n'
        )).
        pipe(gulp.dest('./dist')).
        pipe(rename(function(path) {
            path.basename = 'neuralnetwork0.min';
        })).
        pipe(uglify()).
        pipe(header(
            '/**' + fs.readFileSync('./LICENSE', 'utf8') + '*/\n\n'
        )).
        pipe(gulp.dest('./dist'));
});

// gulp.task('licensify', function() {
//     return gulp.src(['./LICENSE', './dist/neuralNet.js']).
//         pipe(concat('all.js')).
//         pipe(gulp.dest('./dist'))
// });

gulp.task('build', function() {
    console.log('Performing incremental build...');

    var tsResult = tsProject.src().pipe(cache('build'))
        .pipe(debug({title: 'files'}))
        .pipe(tsProject()).pipe(gulp.dest('./build'));
});

gulp.task('test', function() {
    //var spawnSync = require("child_process").spawnSync;
    //spawnSync('npm', ['run', 'mocha', 'build/test/neurons.spec.js', '--colors'], { stdio: "inherit" });
    exec('npm run mocha "build/test/neurons.spec.js"', (err, stdout, stderr) => {
        if (err) {
            console.error(err);
            return;
        }
            console.log(stdout);
        }
    );
});

gulp.task('watch', function() {
    gulp.watch('**/*.ts', ['build', 'test']);
});

gulp.task('default', ['build']);
<commit_msg>Updated test task with globs since test files are typescripted.<commit_after>var fs = require('fs'),
    gulp = require('gulp'),
    debug = require('gulp-debug'),
    cache = require('gulp-cached'),
    exec = require('child_process').exec,
    rename = require('gulp-rename'),
    browserify = require('gulp-browserify'),
    header = require('gulp-header'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    ts = require('gulp-typescript');

console.log(fs.readFileSync('./LICENSE', 'utf8'));

var tsProject = ts.createProject('tsconfig.json');

gulp.task('browserify', function() {
    var tsResult = gulp.src('**/*.ts')
      .pipe(tsProject())
      .js.pipe(browserify({
        })).
        pipe(rename(function(path) {
            path.basename = 'neuralnetwork0';
        })).
        pipe(header(
            '/**' + fs.readFileSync('./LICENSE', 'utf8') + '*/\n\n'
        )).
        pipe(gulp.dest('./dist')).
        pipe(rename(function(path) {
            path.basename = 'neuralnetwork0.min';
        })).
        pipe(uglify()).
        pipe(header(
            '/**' + fs.readFileSync('./LICENSE', 'utf8') + '*/\n\n'
        )).
        pipe(gulp.dest('./dist'));
});

// gulp.task('licensify', function() {
//     return gulp.src(['./LICENSE', './dist/neuralNet.js']).
//         pipe(concat('all.js')).
//         pipe(gulp.dest('./dist'))
// });

gulp.task('build', function() {
    console.log('Performing incremental build...');

    var tsResult = tsProject.src().pipe(cache('build'))
        .pipe(debug({title: 'files'}))
        .pipe(tsProject()).pipe(gulp.dest('./build'));
});

gulp.task('test', function() {
    //var spawnSync = require("child_process").spawnSync;
    //spawnSync('npm', ['run', 'mocha', 'build/test/**/*.spec.js', '--colors'], { stdio: "inherit" });
    exec('npm run mocha "build/test/**/*.spec.js"', (err, stdout, stderr) => {
        if (err) {
            console.error(err);
            return;
        }
            console.log(stdout);
        }
    );
});

gulp.task('watch', function() {
    gulp.watch('**/*.ts', ['build', 'test']);
});

gulp.task('default', ['build']);
<|endoftext|>


<commit_before>/*
 Copyright [2016] [Relevance Lab]

 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.
 */

var logger = require('_pr/logger')(module);
var taskDao = require('_pr/model/classes/tasks/tasks.js');
var masterUtil = require('_pr/lib/utils/masterUtil.js');
var d4dModelNew = require('_pr/model/d4dmasters/d4dmastersmodelnew.js');
var TaskHistory = require('_pr/model/classes/tasks/taskHistory');
var instancesDao = require('_pr/model/classes/instance/instance');

const errorType = 'taskService';

var taskService = module.exports = {};

taskService.getChefTasksByOrgBgProjectAndEnvId = function getChefTasksByOrgBgProjectAndEnvId(jsonData, callback) {
    //jsonData["taskType"] = { $in: ["chef", "composite"] };
    jsonData["taskType"] = "chef";
    taskDao.getChefTasksByOrgBgProjectAndEnvId(jsonData, function(err, chefTasks) {
        if (err) {
            logger.debug("Failed to fetch  Chef Tasks");
            callback(err, null);
            return;
        }
        if (chefTasks.length === 0) {
            logger.debug("There is no chef Tasks Configured");
            callback(null, []);
            return;
        } else {
            /*var chefTaskList = [];
            var count = 0;
            var compositeObj = {};
            for (var i = 0; i < chefTasks.length; i++) {
                (function(aTask) {
                    if (aTask.taskType === 'chef') {
                        count++;
                        chefTaskList.push(aTask);
                    } else {
                        taskDao.getDistinctTaskTypeByIds(aTask.taskConfig.assignTasks,function(err,distinctTaskType){
                            if(err){
                               logger.debug("Failed to fetch  Distinct Tasks");
                               callback(err,null);
                               return;
                            }
                            count++;
                            if (distinctTaskType.length === 0)
                                logger.debug("There is no composite Tasks Configured");
                            if (distinctTaskType.length === 1 && distinctTaskType[0] === 'chef')
                                chefTaskList.push(aTask);
                            else
                                logger.debug("There is composite Tasks Configured with chef and others also");
                            if (chefTasks.length === count) {
                                callback(null, chefTaskList);
                                return;
                            }
                        });
                    }
                    if (chefTasks.length === count) {
                        callback(null, chefTaskList);
                        return;
                    }
                })(chefTasks[i]);
            }*/
            callback(null, chefTasks);
        }
    });
};

taskService.executeTask = function executeTask(taskId, user, hostProtocol, choiceParam, appData, callback) {
    if (appData) {
        appData['taskId'] = taskId;
    }
    taskDao.getTaskById(taskId, function(err, task) {
        if (err) {
            var error = new Error('Failed to fetch Task.');
            error.status = 500;
            return callback(error, null);
        }
        if (task) {
            var blueprintIds = [];
            if (task.blueprintIds && task.blueprintIds.length) {
                blueprintIds = task.blueprintIds;
            }
            task.execute(user, hostProtocol, choiceParam, appData, blueprintIds, task.envId, function(err, taskRes, historyData) {
                if (err) {
                    var error = new Error('Failed to execute task.');
                    error.status = 500;
                    return callback(error, null);
                }
                if (historyData) {
                    taskRes.historyId = historyData.id;
                }
                callback(null, taskRes);
                return;
            });
        } else {
            var error1 = new Error('Task Not Found.');
            error1.status = 404;
            return callback(error1, null);
        }
    });
};

taskService.getTaskActionList = function getTaskActionList(jsonData, callback) {
    TaskHistory.listHistoryWithPagination(jsonData, function(err, histories) {
        if (err) {
            logger.error("Failed to fetch TaskActions: ", err);
            return callback(err, null);
        }
        var count = 0;
        if (histories && histories.docs && histories.docs.length) {
            for (var i = 0; i < histories.docs.length; i++) {
                (function(i) {
                    if (histories.docs[i] && histories.docs[i].taskType == "jenkins") {
                        histories.docs[i] = JSON.parse(JSON.stringify(histories.docs[i]));
                        histories.docs[i].jenkinsLog = "/jenkins/" + histories.docs[i].jenkinsServerId + "/jobs/" + histories.docs[i].jobName + "/builds/" + histories.docs[i].buildNumber + "/output";
                    } else if (histories.docs[i] && histories.docs[i].taskType == "chef") {
                        for (var p = 0; p < histories.docs[i].executionResults.length; p++) {
                            (function(p) {
                                instancesDao.getInstanceById(histories.docs[i].executionResults[p].instanceId, function(err, instance) {
                                    if (err) {
                                        logger.error("Failed to fetch instance: ", err);
                                    }
                                    if (instance && instance.length) {
                                        histories.docs[i].executionResults[p].instanceName = instance[0].name;
                                    }
                                });
                            })(p);
                        }
                        if (histories.docs[i] && histories.docs[i].blueprintExecutionResults && histories.docs[i].blueprintExecutionResults.length) {
                            instancesDao.getInstanceById(histories.docs[i].blueprintExecutionResults[0].result[0].instanceId, function(err, instance) {
                                if (err) {
                                    logger.error("Failed to fetch instance: ", err);
                                }
                                if (instance && instance.length) {
                                    histories.docs[i].blueprintExecutionResults[0].result[0].instanceName = instance[0].name;
                                    histories.docs[i].blueprintExecutionResults[0].result[0].actionId = histories.docs[i].blueprintExecutionResults[0].result[0].actionLogId;
                                    histories.docs[i].executionResults = histories.docs[i].blueprintExecutionResults[0].result;
                                }
                            });
                        }
                    }
                    if (histories.docs[i] && histories.docs[i].taskType == "composite") {
                        if (histories.docs[i].taskHistoryIds && histories.docs[i].taskHistoryIds.length) {
                            for (var j = 0; j < histories.docs[i].taskHistoryIds.length; j++) {
                                (function(j) {
                                    TaskHistory.getHistoryByTaskIdAndHistoryId(histories.docs[i].taskHistoryIds[j].taskId, histories.docs[i].taskHistoryIds[j].historyId, function(err, data) {
                                        if (err) {
                                            logger.error("Failed to fetch history: ", err);
                                        }
                                        if (data) {
                                            if (data.taskType == "jenkins") {
                                                data = JSON.parse(JSON.stringify(data));
                                                data.jenkinsLog = "/jenkins/" + data.jenkinsServerId + "/jobs/" + data.jobName + "/builds/" + data.buildNumber + "/output";
                                                histories.docs[i].executionResults.push(data);
                                            } else {
                                                var c = 0;
                                                for (var k = 0; k < data.executionResults.length; k++) {
                                                    (function(k) {
                                                        instancesDao.getInstanceById(data.executionResults[k].instanceId, function(err, instance) {
                                                            c++;
                                                            if (err) {
                                                                logger.error("Failed to fetch instance: ", err);
                                                            }
                                                            if (instance && instance.length) {
                                                                data.executionResults[k].instanceName = instance[0].name;
                                                                //histories.docs[i].executionResults.push(data);
                                                            }
                                                            if (data.executionResults.length == c) {
                                                                histories.docs[i].executionResults.push(data);
                                                            }
                                                        });
                                                    })(k);
                                                }
                                            }
                                        }
                                        //if (histories.docs[i] && histories.docs[i].executionResults)
                                        //histories.docs[i].executionResults.push(data);
                                    });
                                })(j);
                            }
                        }
                    }
                    count++;

                    if (count == histories.docs.length) {
                        setTimeout(function() {
                            return callback(null, histories);
                        }, 2000);
                    }
                })(i);
            }
        } else {
            return callback(null, histories);
        }
    });
};
<commit_msg>Modified response for composite task<commit_after>/*
 Copyright [2016] [Relevance Lab]

 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.
 */

var logger = require('_pr/logger')(module);
var taskDao = require('_pr/model/classes/tasks/tasks.js');
var masterUtil = require('_pr/lib/utils/masterUtil.js');
var d4dModelNew = require('_pr/model/d4dmasters/d4dmastersmodelnew.js');
var TaskHistory = require('_pr/model/classes/tasks/taskHistory');
var instancesDao = require('_pr/model/classes/instance/instance');

const errorType = 'taskService';

var taskService = module.exports = {};

taskService.getChefTasksByOrgBgProjectAndEnvId = function getChefTasksByOrgBgProjectAndEnvId(jsonData, callback) {
    //jsonData["taskType"] = { $in: ["chef", "composite"] };
    jsonData["taskType"] = "chef";
    taskDao.getChefTasksByOrgBgProjectAndEnvId(jsonData, function(err, chefTasks) {
        if (err) {
            logger.debug("Failed to fetch  Chef Tasks");
            callback(err, null);
            return;
        }
        if (chefTasks.length === 0) {
            logger.debug("There is no chef Tasks Configured");
            callback(null, []);
            return;
        } else {
            /*var chefTaskList = [];
            var count = 0;
            var compositeObj = {};
            for (var i = 0; i < chefTasks.length; i++) {
                (function(aTask) {
                    if (aTask.taskType === 'chef') {
                        count++;
                        chefTaskList.push(aTask);
                    } else {
                        taskDao.getDistinctTaskTypeByIds(aTask.taskConfig.assignTasks,function(err,distinctTaskType){
                            if(err){
                               logger.debug("Failed to fetch  Distinct Tasks");
                               callback(err,null);
                               return;
                            }
                            count++;
                            if (distinctTaskType.length === 0)
                                logger.debug("There is no composite Tasks Configured");
                            if (distinctTaskType.length === 1 && distinctTaskType[0] === 'chef')
                                chefTaskList.push(aTask);
                            else
                                logger.debug("There is composite Tasks Configured with chef and others also");
                            if (chefTasks.length === count) {
                                callback(null, chefTaskList);
                                return;
                            }
                        });
                    }
                    if (chefTasks.length === count) {
                        callback(null, chefTaskList);
                        return;
                    }
                })(chefTasks[i]);
            }*/
            callback(null, chefTasks);
        }
    });
};

taskService.executeTask = function executeTask(taskId, user, hostProtocol, choiceParam, appData, callback) {
    if (appData) {
        appData['taskId'] = taskId;
    }
    taskDao.getTaskById(taskId, function(err, task) {
        if (err) {
            var error = new Error('Failed to fetch Task.');
            error.status = 500;
            return callback(error, null);
        }
        if (task) {
            var blueprintIds = [];
            if (task.blueprintIds && task.blueprintIds.length) {
                blueprintIds = task.blueprintIds;
            }
            task.execute(user, hostProtocol, choiceParam, appData, blueprintIds, task.envId, function(err, taskRes, historyData) {
                if (err) {
                    var error = new Error('Failed to execute task.');
                    error.status = 500;
                    return callback(error, null);
                }
                if (historyData) {
                    taskRes.historyId = historyData.id;
                }
                callback(null, taskRes);
                return;
            });
        } else {
            var error1 = new Error('Task Not Found.');
            error1.status = 404;
            return callback(error1, null);
        }
    });
};

taskService.getTaskActionList = function getTaskActionList(jsonData, callback) {
    TaskHistory.listHistoryWithPagination(jsonData, function(err, histories) {
        if (err) {
            logger.error("Failed to fetch TaskActions: ", err);
            return callback(err, null);
        }
        var count = 0;
        if (histories && histories.docs && histories.docs.length) {
            for (var i = 0; i < histories.docs.length; i++) {
                (function(i) {
                    if (histories.docs[i] && histories.docs[i].taskType == "jenkins") {
                        histories.docs[i] = JSON.parse(JSON.stringify(histories.docs[i]));
                        histories.docs[i].jenkinsLog = "/jenkins/" + histories.docs[i].jenkinsServerId + "/jobs/" + histories.docs[i].jobName + "/builds/" + histories.docs[i].buildNumber + "/output";
                    } else if (histories.docs[i] && histories.docs[i].taskType == "chef") {
                        for (var p = 0; p < histories.docs[i].executionResults.length; p++) {
                            (function(p) {
                                instancesDao.getInstanceById(histories.docs[i].executionResults[p].instanceId, function(err, instance) {
                                    if (err) {
                                        logger.error("Failed to fetch instance: ", err);
                                    }
                                    if (instance && instance.length) {
                                        histories.docs[i].executionResults[p].instanceName = instance[0].name;
                                    }
                                });
                            })(p);
                        }
                        if (histories.docs[i] && histories.docs[i].blueprintExecutionResults && histories.docs[i].blueprintExecutionResults.length) {
                            instancesDao.getInstanceById(histories.docs[i].blueprintExecutionResults[0].result[0].instanceId, function(err, instance) {
                                if (err) {
                                    logger.error("Failed to fetch instance: ", err);
                                }
                                if (instance && instance.length) {
                                    histories.docs[i].blueprintExecutionResults[0].result[0].instanceName = instance[0].name;
                                    histories.docs[i].blueprintExecutionResults[0].result[0].actionId = histories.docs[i].blueprintExecutionResults[0].result[0].actionLogId;
                                    histories.docs[i].executionResults = histories.docs[i].blueprintExecutionResults[0].result;
                                }
                            });
                        }
                    }
                    if (histories.docs[i] && histories.docs[i].taskType == "composite") {
                        if (histories.docs[i].taskHistoryIds && histories.docs[i].taskHistoryIds.length) {
                            for (var j = 0; j < histories.docs[i].taskHistoryIds.length; j++) {
                                (function(j) {
                                    TaskHistory.getHistoryByTaskIdAndHistoryId(histories.docs[i].taskHistoryIds[j].taskId, histories.docs[i].taskHistoryIds[j].historyId, function(err, data) {
                                        if (err) {
                                            logger.error("Failed to fetch history: ", err);
                                        }
                                        if (data) {
                                            if (data.taskType == "jenkins") {
                                                data = JSON.parse(JSON.stringify(data));
                                                data.jenkinsLog = "/jenkins/" + data.jenkinsServerId + "/jobs/" + data.jobName + "/builds/" + data.buildNumber + "/output";
                                                histories.docs[i].executionResults.push(data);
                                            } else {
                                                if(data.blueprintExecutionResults && data.blueprintExecutionResults.length){
                                                    data.blueprintExecutionResults[0].result[0].actionId = data.blueprintExecutionResults[0].result[0].actionLogId;
                                                    data.executionResults = data.blueprintExecutionResults[0].result;

                                                }
                                                var c = 0;
                                                for (var k = 0; k < data.executionResults.length; k++) {
                                                    (function(k) {
                                                        instancesDao.getInstanceById(data.executionResults[k].instanceId, function(err, instance) {
                                                            c++;
                                                            if (err) {
                                                                logger.error("Failed to fetch instance: ", err);
                                                            }
                                                            if (instance && instance.length) {
                                                                data.executionResults[k].instanceName = instance[0].name;
                                                                //histories.docs[i].executionResults.push(data);
                                                            }
                                                            if (data.executionResults.length == c) {
                                                                histories.docs[i].executionResults.push(data);
                                                            }
                                                        });
                                                    })(k);
                                                }
                                            }
                                        }
                                        //if (histories.docs[i] && histories.docs[i].executionResults)
                                        //histories.docs[i].executionResults.push(data);
                                    });
                                })(j);
                            }
                        }
                    }
                    count++;

                    if (count == histories.docs.length) {
                        setTimeout(function() {
                            return callback(null, histories);
                        }, 2000);
                    }
                })(i);
            }
        } else {
            return callback(null, histories);
        }
    });
};
<|endoftext|>