<commit_before>/**
 * Created by preciousr on 11/04/2016.
 */
var Model = require('../app/model/models.js'),
    common = require('./common.js'),
    moment = require('moment'),
    envVariables = common.config();

var jobs ={
    accountExpiryCheck: function(){
    console.log("[ACCOUNT CHECK JOB] STARTING");
        var now = new Date(),
        gracePeriod = new Date(now);
        gracePeriod.setDate(now.getDate()+envVariables.userAccountSettings.gracePeriod);
        Model.User.findAll({
            where: {
                accountExpiry: {
                    $lte: gracePeriod
                }
            }
        }).then(function(users){
            console.log('[ACCOUNT CHECK JOB] ACCOUNTS TO CHECK: ' + users.length);

                for(var u=0; u<users.length; u++){
                    setTimeout(function(u){

                            var user = users[u],
                                expired = user.accountExpiry < now,
                                expiringSoon = user.accountExpiry < gracePeriod,
                                warningSent = user.warningSent,
                                expiryConfirmationSent = user.expiryConfirmationSent,
                                accountExpiryDateText = moment(user.accountExpiry).format('Do MMMM YYYY'),
                                dayAndMonthText = moment(user.accountExpiry).format('Do MMMM');

                            console.log('[ACCOUNT CHECK JOB] PROCESSING USER ' + user.id);

                            if (!expired && expiringSoon && !warningSent) {
                                console.log('[ACCOUNT CHECK JOB] SENDING WARNING EMAIL FOR USER ' + user.id);

                                Model.User.update({warningSent: true}, {where: {email: user.email}}).then(function () {

                                    emailService.expiryWarning(user.email,accountExpiryDateText,dayAndMonthText, user.id);

                                });

                            }
                            else if (expired && !expiryConfirmationSent) {
                                console.log('[ACCOUNT CHECK JOB] SENDING EXPIRY EMAIL AND DELETE ACCOUNT FOR USER ' + user.id);

                                Model.User.update({expiryConfirmationSent: true}, {where: {email: user.email}}).then(function () {

                                    emailService.expiryConfirmation(user.email, user.id);

                                    Model.AccountDetails.destroy({where: {user_id: user.id}}).then(function () {
                                        Model.SavedAddress.destroy({where: {user_id: user.id}}).then(function () {
                                            Model.User.destroy({where: {email: user.email}}).then(function(){
                                                console.log('[ACCOUNT CHECK JOB] ACCOUNT DELETED SUCCESSFULLY FOR USER ' + user.id);
                                            });
                                        });
                                    });
                                });
                            } else {
                                console.log('[ACCOUNT CHECK JOB] NO ACTION REQUIRED FOR USER ' + user.id);
                            }

                    }, 1000 * u, u);
                }
            }
        )
    }
};
module.exports = jobs;<commit_msg>fixing some errors in the query steming from the sequelize package update<commit_after>/**
 * Created by preciousr on 11/04/2016.
 */
var Model = require('../app/model/models.js'),
    common = require('./common.js'),
    moment = require('moment'),
    envVariables = common.config();

var jobs ={
    accountExpiryCheck: function(){
    console.log("[ACCOUNT CHECK JOB] STARTING");
        var now = new Date(),
        gracePeriod = new Date(now);
        gracePeriod.setDate(now.getDate()+envVariables.userAccountSettings.gracePeriod);

        const { Op } = require("sequelize");

        Model.User.findAll({
            where: {
                accountExpiry: {
                    [Op.lte]: gracePeriod
                }
            }
        }).then(function(users){
            console.log('[ACCOUNT CHECK JOB] ACCOUNTS TO CHECK: ' + users.length);

                for(var u=0; u<users.length; u++){
                    setTimeout(function(u){

                            var user = users[u],
                                expired = user.accountExpiry < now,
                                expiringSoon = user.accountExpiry < gracePeriod,
                                warningSent = user.warningSent,
                                expiryConfirmationSent = user.expiryConfirmationSent,
                                accountExpiryDateText = moment(user.accountExpiry).format('Do MMMM YYYY'),
                                dayAndMonthText = moment(user.accountExpiry).format('Do MMMM');

                            console.log('[ACCOUNT CHECK JOB] PROCESSING USER ' + user.id);

                            if (!expired && expiringSoon && !warningSent) {
                                console.log('[ACCOUNT CHECK JOB] SENDING WARNING EMAIL FOR USER ' + user.id);

                                Model.User.update({warningSent: true}, {where: {email: user.email}}).then(function () {

                                    emailService.expiryWarning(user.email,accountExpiryDateText,dayAndMonthText, user.id);

                                });

                            }
                            else if (expired && !expiryConfirmationSent) {
                                console.log('[ACCOUNT CHECK JOB] SENDING EXPIRY EMAIL AND DELETE ACCOUNT FOR USER ' + user.id);

                                Model.User.update({expiryConfirmationSent: true}, {where: {email: user.email}}).then(function () {

                                    emailService.expiryConfirmation(user.email, user.id);

                                    Model.AccountDetails.destroy({where: {user_id: user.id}}).then(function () {
                                        Model.SavedAddress.destroy({where: {user_id: user.id}}).then(function () {
                                            Model.User.destroy({where: {email: user.email}}).then(function(){
                                                console.log('[ACCOUNT CHECK JOB] ACCOUNT DELETED SUCCESSFULLY FOR USER ' + user.id);
                                            });
                                        });
                                    });
                                });
                            } else {
                                console.log('[ACCOUNT CHECK JOB] NO ACTION REQUIRED FOR USER ' + user.id);
                            }

                    }, 1000 * u, u);
                }
            }
        )
    }
};
module.exports = jobs;
<|endoftext|>


<commit_before>//
// Parsers Suite
//
/*eslint-env node, mocha */
var
  path = require('path'),
  fs = require('fs')
var
  basedir = __dirname,
  jsdir = path.join(basedir, 'js')

function have(mod, req) {
  if (compiler.parsers._req(mod, req))
    return true
  console.error('\tnot installed locally: ' + (req || mod) + ' alias "' + mod + '"')
  return false
}

function cat(dir, filename) {
  return fs.readFileSync(path.join(dir, filename), 'utf8')
}

function normalize(str) {
  var
    n = str.search(/[^\n]/)
  if (n < 0) return ''
  if (n > 0) str = str.slice(n)
  n = str.search(/\n+$/)
  return ~n ? str.slice(0, n) : str
}

function testParser(name, opts) {
  var
    file = name + (opts.type ? '.' + opts.type : ''),
    str1 = cat(basedir, file + '.tag'),
    str2 = cat(jsdir, file + '.js')

  expect(normalize(compiler.compile(str1, opts || {}))).to.be(normalize(str2))
}

describe('HTML parsers', function () {

  this.timeout(12000)

  function testStr(str, resStr, opts) {
    expect(compiler.html(str, opts || {})).to.be(resStr)
  }

  // test.jade.tag & slide.jade.tag
  it('jade', function () {
    if (have('jade') && have('coffee')) {
      testParser('test.jade', { template: 'jade' })
      testParser('slide.jade', { template: 'jade' })
    }
  })

  describe('Custom parser in expressions', function () {
    var opts = {
      parser: function (str) { return '@' + str },
      expr: true
    }

    it('don\'t touch format before run parser, compact & trim after (2.3.0)', function () {
      testStr('', '', opts)
      testStr('{\tb\n }', '{@\tb}', opts)
    })

    it('plays with the custom parser', function () {
      testStr('', '', opts)
      testStr('{ b }', '{@ b}', opts)
    })

    it('plays with quoted values', function () {
      testStr('', '', opts)
      testStr('{"b"}', '{@"b"}', opts)
    })

    it('remove the last semi-colon', function () {
      testStr('', '', opts)
      testStr('{ b ;}', '{@ b}', opts)
    })

    it('prefixing the expression with "^" prevents the parser (2.3.0)', function () {
      testStr('', '', opts)
      testStr('{^ b }', '{b}', opts)
    })

  })

})

describe('JavaScript parsers', function () {

  function _custom(js) {
    return 'var foo'
  }

  this.timeout(25000) // first call to babel-core is slooooow!

  // complex.tag
  it('complex tag structure', function () {
    if (have('none')) {   // testing none, for coverage too
      testParser('complex', {})
    }
    else expect().fail('parsers.js must have a "none" property')
  })

  // test.tag
  it('javascript (root container)', function () {
    testParser('test', { expr: true })
  })

  // test-alt.tag
  it('javascript (comment hack)', function () {
    testParser('test-alt', { expr: true })
  })

  it('mixed riotjs and javascript types', function () {
    if (have('javascript')) {   // for js, for coverage too
      testParser('mixed-js', {})
    }
    else expect().fail('parsers.js must have a "javascript" property')
  })

  // test.coffee.tag
  it('coffeescript', function () {
    if (have('coffee')) {
      testParser('test', { type: 'coffee', expr: true })
    }
  })

  // test.livescript.tag
  it('livescript', function () {
    if (have('livescript')) {
      testParser('test', { type: 'livescript' })
    }
  })

  // test.livescript.tag
  it('typescript', function () {
    if (have('typescript')) {
      testParser('test', { type: 'typescript' })
    }
  })

  // test.es6.tag
  it('es6', function () {
    if (have('es6')) {
      testParser('test', { type: 'es6' })
    }
  })

  // test.babel.tag
  it('babel', function () {
    if (have('babel')) {
      testParser('test', { type: 'babel' })
    }
  })

  // test-attr.babel.tag
  it('coffee with shorthands (fix #1090)', function () {
    if (have('coffee')) {
      testParser('test-attr', { type: 'coffee', expr: true })
    }
  })

  // test.random.tag
  it('custom js parser', function () {

    compiler.parsers.js.custom = _custom
    testParser('test', { type: 'custom' })

  })

})

describe('Style parsers', function () {

  this.timeout(12000)

  // custom parser
  compiler.parsers.css.postcss = function(tag, css, opts) {
    return require('postcss')([require('autoprefixer')]).process(css).css
  }

  // style.tag
  it('default style', function () {
    testParser('style', {})
  })

  // style.escoped.tag
  it('scoped styles', function () {
    var str = compiler.compile(cat(basedir, 'style.scoped.tag'))
    fs.writeFileSync('out_.js', str)
    testParser('style.scoped', {})
  })

  // stylus.tag
  it('stylus', function () {
    if (have('stylus')) {
      testParser('stylus', {})
    }
  })

  // sass.tag
  it('sass, indented 2, margin 0', function () {
    if (have('sass')) {
      testParser('sass', {})
    }
  })

  // scss.tag
  it('scss, indented 2, margin 0', function () {
    if (have('scss', 'node-sass')) {
      testParser('scss', {})
    }
  })

  // testing the options attribute on the style tag
  it('custom style options', function () {
    if (have('sass', 'node-sass')) {
      testParser('sass.options', {})
    }
  })

  // scss.tag
  it('custom parser using postcss + autoprefixer', function () {
    if (have('postcss', 'postcss')) {
      testParser('postcss', {})
    }
  })

  // less.tag
  it('less', function () {
    if (have('less')) {
      testParser('less', {})
    }
  })

  it('Mixing CSS blocks with different type', function () {
    testParser('mixed-css', {})
  })

})

describe('Other', function () {

  it('Unknown HTML template parser throws an error', function () {
    var
      str1 = cat(basedir, 'test.tag')

    expect(compiler.compile).withArgs(str1, {template: 'unknown'}).to.throwError()
  })

  it('Unknown JS & CSS parsers throws an error', function () {
    var
      str1 = cat(basedir, 'test.tag'),
      str2 = [
        '<error>',
        "",
        '</error>'
      ].join('\n')

    expect(compiler.compile).withArgs(str1, {type: 'unknown'}).to.throwError()
    expect(compiler.compile).withArgs(str2).to.throwError()
    expect(have('unknown')).to.be(false)
  })

  // brackets.tag
  it('using different brackets', function () {
    testParser('brackets', { brackets: '${ }' })
  })

})
<commit_msg>Fixes to indentation<commit_after>//
// Parsers Suite
//
/*eslint-env node, mocha */
var
  path = require('path'),
  fs = require('fs')
var
  basedir = __dirname,
  jsdir = path.join(basedir, 'js')

function have(mod, req) {
  if (compiler.parsers._req(mod, req))
    return true
  console.error('\tnot installed locally: ' + (req || mod) + ' alias "' + mod + '"')
  return false
}

function cat(dir, filename) {
  return fs.readFileSync(path.join(dir, filename), 'utf8')
}

function normalize(str) {
  var
    n = str.search(/[^\n]/)
  if (n < 0) return ''
  if (n > 0) str = str.slice(n)
  n = str.search(/\n+$/)
  return ~n ? str.slice(0, n) : str
}

function testParser(name, opts) {
  var
    file = name + (opts.type ? '.' + opts.type : ''),
    str1 = cat(basedir, file + '.tag'),
    str2 = cat(jsdir, file + '.js')

  expect(normalize(compiler.compile(str1, opts || {}))).to.be(normalize(str2))
}

describe('HTML parsers', function () {

  this.timeout(12000)

  function testStr(str, resStr, opts) {
    expect(compiler.html(str, opts || {})).to.be(resStr)
  }

  // test.jade.tag & slide.jade.tag
  it('jade', function () {
    if (have('jade') && have('coffee')) {
      testParser('test.jade', { template: 'jade' })
      testParser('slide.jade', { template: 'jade' })
    }
  })

  describe('Custom parser in expressions', function () {
    var opts = {
      parser: function (str) { return '@' + str },
      expr: true
    }

    it('don\'t touch format before run parser, compact & trim after (2.3.0)', function () {
      testStr('', '', opts)
      testStr('{\tb\n }', '{@\tb}', opts)
    })

    it('plays with the custom parser', function () {
      testStr('', '', opts)
      testStr('{ b }', '{@ b}', opts)
    })

    it('plays with quoted values', function () {
      testStr('', '', opts)
      testStr('{"b"}', '{@"b"}', opts)
    })

    it('remove the last semi-colon', function () {
      testStr('', '', opts)
      testStr('{ b ;}', '{@ b}', opts)
    })

    it('prefixing the expression with "^" prevents the parser (2.3.0)', function () {
      testStr('', '', opts)
      testStr('{^ b }', '{b}', opts)
    })

  })

})

describe('JavaScript parsers', function () {

  function _custom(js) {
    return 'var foo'
  }

  this.timeout(25000) // first call to babel-core is slooooow!

  // complex.tag
  it('complex tag structure', function () {
    if (have('none')) {   // testing none, for coverage too
      testParser('complex', {})
    }
    else expect().fail('parsers.js must have a "none" property')
  })

  // test.tag
  it('javascript (root container)', function () {
    testParser('test', { expr: true })
  })

  // test-alt.tag
  it('javascript (comment hack)', function () {
    testParser('test-alt', { expr: true })
  })

  it('mixed riotjs and javascript types', function () {
    if (have('javascript')) {   // for js, for coverage too
      testParser('mixed-js', {})
    }
    else expect().fail('parsers.js must have a "javascript" property')
  })

  // test.coffee.tag
  it('coffeescript', function () {
    if (have('coffee')) {
      testParser('test', { type: 'coffee', expr: true })
    }
  })

  // test.livescript.tag
  it('livescript', function () {
    if (have('livescript')) {
      testParser('test', { type: 'livescript' })
    }
  })

  // test.livescript.tag
  it('typescript', function () {
    if (have('typescript')) {
      testParser('test', { type: 'typescript' })
    }
  })

  // test.es6.tag
  it('es6', function () {
    if (have('es6')) {
      testParser('test', { type: 'es6' })
    }
  })

  // test.babel.tag
  it('babel', function () {
    if (have('babel')) {
      testParser('test', { type: 'babel' })
    }
  })

  // test-attr.babel.tag
  it('coffee with shorthands (fix #1090)', function () {
    if (have('coffee')) {
      testParser('test-attr', { type: 'coffee', expr: true })
    }
  })

  // test.random.tag
  it('custom js parser', function () {

    compiler.parsers.js.custom = _custom
    testParser('test', { type: 'custom' })

  })

})

describe('Style parsers', function () {

  this.timeout(12000)

  // custom parser
  compiler.parsers.css.postcss = function(tag, css, opts) {
    return require('postcss')([require('autoprefixer')]).process(css).css
  }

  // style.tag
  it('default style', function () {
    testParser('style', {})
  })

  // style.escoped.tag
  it('scoped styles', function () {
    testParser('style.scoped', {})
  })

  // stylus.tag
  it('stylus', function () {
    if (have('stylus')) {
      testParser('stylus', {})
    }
  })

  // sass.tag
  it('sass, indented 2, margin 0', function () {
    if (have('sass')) {
      testParser('sass', {})
    }
  })

  // scss.tag
  it('scss, indented 2, margin 0', function () {
    if (have('scss', 'node-sass')) {
      testParser('scss', {})
    }
  })

  // testing the options attribute on the style tag
  it('custom style options', function () {
    if (have('sass', 'node-sass')) {
      testParser('sass.options', {})
    }
  })

  // scss.tag
  it('custom parser using postcss + autoprefixer', function () {
    if (have('postcss', 'postcss')) {
      testParser('postcss', {})
    }
  })

  // less.tag
  it('less', function () {
    if (have('less')) {
      testParser('less', {})
    }
  })

  it('Mixing CSS blocks with different type', function () {
    testParser('mixed-css', {})
  })

})

describe('Other', function () {

  it('Unknown HTML template parser throws an error', function () {
    var
      str1 = cat(basedir, 'test.tag')

    expect(compiler.compile).withArgs(str1, {template: 'unknown'}).to.throwError()
  })

  it('Unknown JS & CSS parsers throws an error', function () {
    var
      str1 = cat(basedir, 'test.tag'),
      str2 = [
        '<error>',
        "",
        '</error>'
      ].join('\n')

    expect(compiler.compile).withArgs(str1, {type: 'unknown'}).to.throwError()
    expect(compiler.compile).withArgs(str2).to.throwError()
    expect(have('unknown')).to.be(false)
  })

  // brackets.tag
  it('using different brackets', function () {
    testParser('brackets', { brackets: '${ }' })
  })

})
<|endoftext|>


<commit_before>(function ($) {
    $.fn.folderless_change_list = function () {
        this.each(function () {
            var _self = $(this);
            var upload_button = _self.find(".folderless_uploader");
            var upload_info = _self.find(".folderless_upload_info");
            var upload_errors_link = _self.find(".upload_errors");
            var upload_errors_info = _self.find(".error_info");
            var files_total = 0;
            var files_uploaded = 0;
            var files_upload_error = 0;
            var file_input = _self.find(".folderless_fileinput");

            var reload = function() {
                document.location.reload();
            };

            var check_finished = function() {
                if (files_uploaded + files_upload_error == files_total) {
                    if (files_uploaded == files_total) {
                      reload();
                    } else {
                      alert(upload_errors_info.html());
                      reload();
                    }
                }
            }

            var init = function () {
                // uploader instead of classic "add"
                upload_errors_link.click(function (e) {
                    e.preventDefault();
                    alert(upload_errors_info.html());
                });
                upload_button.click(function (e) {
                    e.preventDefault();
                    file_input.click();
                });
                file_input.fileupload({
                      dataType: 'json',
                      replaceFileInput: false,
                      sequentialUploads: true,
                      add: function (e, data) {
                          upload_info.show(0);
                          files_total += 1;
                          upload_info.find(".total").html(files_total);
                          data.submit();
                      },
                      send: function (e, data) {

                      },
                      done: function (e, data) {
                          files_uploaded += 1;
                          upload_info.find(".uploaded").html(files_uploaded);
                          check_finished();
                      },
                      fail: function (e, data) {
                          files_upload_error += 1;
                          var info = jQuery.parseJSON(data.jqXHR.responseText);
                          upload_errors_link.show(0).find("span").html(files_upload_error);
                          upload_errors_info.append(info.message + "\n\n");
                          check_finished();
                      },
                      progressall: function (e, data) {
                          var progress = parseInt(data.loaded / data.total * 100, 10);
                          upload_info.find(".percent").html(progress + "%");
                          if (data.loaded / data.total == 1) {
                              upload_info.find(".status").html("processing...");
                          }
                      }
                });
            };

            init();

        });
    }
})(jQuery);
<commit_msg>prototyping dismisspopup code for django later than 1.9!<commit_after>(function ($) {
    $.fn.folderless_change_list = function () {
        this.each(function () {
            var _self = $(this);
            var upload_button = _self.find(".folderless_uploader");
            var upload_info = _self.find(".folderless_upload_info");
            var upload_errors_link = _self.find(".upload_errors");
            var upload_errors_info = _self.find(".error_info");
            var files_total = 0;
            var files_uploaded = 0;
            var files_upload_error = 0;
            var file_input = _self.find(".folderless_fileinput");
            var file_result_list = _self.find(".results");
            var popup_candidates = file_result_list.find('a[data-popup-opener], a[onclick]');

            var reload = function() {
                document.location.reload();
            };

            var check_finished = function() {
                if (files_uploaded + files_upload_error == files_total) {
                    if (files_uploaded == files_total) {
                      reload();
                    } else {
                      alert(upload_errors_info.html());
                      reload();
                    }
                }
            }

            var callDissmissPopup = function(win, chosen_id) {

            }

            var init = function () {
                // uploader instead of classic "add"
                upload_errors_link.click(function (e) {
                    e.preventDefault();
                    alert(upload_errors_info.html());
                });
                upload_button.click(function (e) {
                    e.preventDefault();
                    file_input.click();
                });
                // init fileuploader
                file_input.fileupload({
                      dataType: 'json',
                      replaceFileInput: false,
                      sequentialUploads: true,
                      add: function (e, data) {
                          upload_info.show(0);
                          files_total += 1;
                          upload_info.find(".total").html(files_total);
                          data.submit();
                      },
                      send: function (e, data) {

                      },
                      done: function (e, data) {
                          files_uploaded += 1;
                          upload_info.find(".uploaded").html(files_uploaded);
                          check_finished();
                      },
                      fail: function (e, data) {
                          files_upload_error += 1;
                          var info = jQuery.parseJSON(data.jqXHR.responseText);
                          upload_errors_link.show(0).find("span").html(files_upload_error);
                          upload_errors_info.append(info.message + "\n\n");
                          check_finished();
                      },
                      progressall: function (e, data) {
                          var progress = parseInt(data.loaded / data.total * 100, 10);
                          upload_info.find(".percent").html(progress + "%");
                          if (data.loaded / data.total == 1) {
                              upload_info.find(".status").html("processing...");
                          }
                      }
                });
                // manage dismiss popup code here!
                $.each(popup_candidates, function(index, item) {
                   var $item = $(item);
                   console.log($item.attr('data-popup-opener'));
                   console.log($item.closest('.field-thumb_list'));
                   // $item.unbind('click');
                   // $item.click(callDissmissPopup);
                });
            };

            init();

        });
    }
})(jQuery);
<|endoftext|>


<commit_before>var path        = require('path');
var _           = require('underscore');
var fs          = require('fs');
var io          = require('indian-ocean');
var execSync    = require('child_process').execSync;
var sh_commands = require('../src/sh-commands.js');
var moment      = require('moment-timezone');
var Promise     = require('promise');

var home_dir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var config_path = path.join(home_dir, '.conf', 'kestrel-config.json');
var config = require(config_path);

var PROJECT_PATH = path.resolve('.');
var LOCAL_FOLDER = path.basename(PROJECT_PATH);

function readDeploySettings(){
  var file_path_and_name = path.join(PROJECT_PATH, '.kestrel', 'deploy-settings.json'),
      settings = {};
  if (io.existsSync(file_path_and_name)){
    settings = require(file_path_and_name);
  }
  return settings;
}

function getDirectories(srcpath, opts) {
  return fs.readdirSync(srcpath).filter(function(file) {
    var is_directory = fs.statSync(path.join(srcpath, file)).isDirectory()
    // Test for folders that start with a dot
    if (is_directory && opts.excludeHidden) {
      is_directory = !/^\./.test(file)
    }
    return is_directory;
  });
}

function getLocalDeployDirChoices(){
  var dirs = getDirectories(PROJECT_PATH, {excludeHidden: true})

  // Add repo-name
  var dirs_with_basename = dirs.map(function(dir){
    return ['.', dir].join('/'); // Kestrel server will run with `/` file paths for Linux
  })
  var all_dirs = ['./'].concat(dirs_with_basename);
  // If we have a dir that we deployed to that isn't in our list, then it was a sub-dir, so give that as the first choice
  if (!_.contains(dirs_with_basename, default_deploy.local_path) ) {
    all_dirs = [default_deploy.local_path.replace(LOCAL_FOLDER, '.')].concat(all_dirs)
  }
  return all_dirs

}

function getConfigRemotePath(){
  var remote_path = config.publishing.remote_path
  if (config.publishing.is_moment_template) {
    remote_path = moment().format(remote_path)
  }
  return remote_path
}

var default_deploy = {
  bucket_environment: 'staging',
  trigger_type: 'sync',
  local_path: './',
  remote_path: getConfigRemotePath() + '/' + LOCAL_FOLDER,
  when: 'now'
};

_.extend(default_deploy, readDeploySettings());

var local_deploy_dir_choices = getLocalDeployDirChoices()

var questions = [
  {
    type: 'list',
    name: 'bucket_environment',
    message: 'Deploy to which environment?',
    choices: ['staging', 'prod'],
    default: default_deploy.bucket_environment
  },{
    type: 'list',
    name: 'trigger_type',
    message: 'Deploy method?',
    choices: function(){
      var choices = ['sync']
      if (config.server.hard_deploy.enabled) {
        choices.push('hard')
      }
      return choices
    },
    default: default_deploy.trigger_type
  },{
    type: 'list-input',
    name: 'local_path',
    message: 'Deploy from directory:',
    choices: local_deploy_dir_choices,
    default: local_deploy_dir_choices[0],
    filter: function(input){
      if (input == './') {
        return LOCAL_FOLDER
      } else {
        return input.replace('.', LOCAL_FOLDER)
      }
    }
  },{
    type: 'input',
    name: 'remote_path',
    message: 'Deploy to:',
    default: default_deploy.remote_path,
    filter: function(val){
      return val.trim()
    }
  },{
    type: 'input',
    name: 'when',
    message: 'When? e.g. 2015-01-01 14:00',
    default: default_deploy.when,
    filter: function(val){
      return val.trim()
    }
  },{
    type: 'password',
    name: 'trigger',
    message: 'Enter the trigger:'
  }
]

module.exports = questions;<commit_msg>remember deploy output; better display dir changing<commit_after>var path        = require('path');
var _           = require('underscore');
var fs          = require('fs');
var io          = require('indian-ocean');
var execSync    = require('child_process').execSync;
var sh_commands = require('../src/sh-commands.js');
var moment      = require('moment-timezone');
var Promise     = require('promise');

var home_dir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
var config_path = path.join(home_dir, '.conf', 'kestrel-config.json');
var config = require(config_path);

var PROJECT_PATH = path.resolve('.');
var LOCAL_FOLDER = path.basename(PROJECT_PATH);

function readDeploySettings(){
  var file_path_and_name = path.join(PROJECT_PATH, '.kestrel', 'deploy-settings.json'),
      settings = {};
  if (io.existsSync(file_path_and_name)){
    settings = require(file_path_and_name);
  }
  return settings;
}

function getDirectories(srcpath, opts) {
  return fs.readdirSync(srcpath).filter(function(file) {
    var is_directory = fs.statSync(path.join(srcpath, file)).isDirectory()
    // Test for folders that start with a dot
    if (is_directory && opts.excludeHidden) {
      is_directory = !/^\./.test(file)
    }
    return is_directory;
  });
}

function getLocalDeployDirChoices(){
  var dirs = getDirectories(PROJECT_PATH, {excludeHidden: true})

  // Add repo-name
  var dirs_with_basename = dirs.map(function(dir){
    return ['.', dir].join('/'); // Kestrel server will run with `/` file paths for Linux
  })
  var all_dirs = ['./'].concat(dirs_with_basename);
  // If we have a dir that we deployed to that isn't in our list, then it was a sub-dir, so give that as the first choice
  if (!_.contains(dirs_with_basename, default_deploy.local_path) ) {
    all_dirs = [default_deploy.local_path.replace(LOCAL_FOLDER, '.')].concat(all_dirs)
  }
  return all_dirs.map(function(dir){ return {name: dir, value: dir.replace('.', LOCAL_FOLDER), short: dir} })

}

function getConfigRemotePath(){
  var remote_path = config.publishing.remote_path
  if (config.publishing.is_moment_template) {
    remote_path = moment().format(remote_path)
  }
  return remote_path
}

var default_deploy = {
  bucket_environment: 'staging',
  trigger_type: 'sync',
  local_path: './',
  remote_path: getConfigRemotePath() + '/' + LOCAL_FOLDER,
  when: 'now'
};

_.extend(default_deploy, readDeploySettings());

var local_deploy_dir_choices = getLocalDeployDirChoices()

var questions = [
  {
    type: 'list',
    name: 'bucket_environment',
    message: 'Deploy to which environment?',
    choices: ['staging', 'prod'],
    default: default_deploy.bucket_environment
  },{
    type: 'list',
    name: 'trigger_type',
    message: 'Deploy method?',
    choices: function(){
      var choices = ['sync']
      if (config.server.hard_deploy.enabled) {
        choices.push('hard')
      }
      return choices
    },
    default: default_deploy.trigger_type
  },{
    type: 'list-input',
    name: 'local_path',
    message: 'Deploy from directory:',
    choices: local_deploy_dir_choices,
    default: default_deploy.local_path
  },{
    type: 'input',
    name: 'remote_path',
    message: 'Deploy to:',
    default: default_deploy.remote_path,
    filter: function(val){
      return val.trim()
    }
  },{
    type: 'input',
    name: 'when',
    message: 'When? e.g. 2015-01-01 14:00',
    default: default_deploy.when,
    filter: function(val){
      return val.trim()
    }
  },{
    type: 'password',
    name: 'trigger',
    message: 'Enter the trigger:'
  }
]

module.exports = questions;<|endoftext|>


<commit_before>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		var $selectAll = $('.spl-field-cko-select-all');
		var $selectItem = $('.spl-field-cko-select-item');

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { token: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		this.initHoldsPending();

	} // initHolds()

, initHoldsPending: function() {
		var $form = $('#spl-form-holds-pending');

		var $selectAll = $('.spl-field-holds-pending-select-all');
		var $selectItem = $('.spl-field-holds-pending-select-item');

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	} // initHoldsPending()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

};
<commit_msg>holds pending<commit_after>// account.js

var org = {

	// added on script load
	config: {
						endpoint: { hzws: 'http://api.spokanelibrary.org/v2/hzws/' }
					 }

	// added on authentication
	,user: {}

	// called on script load
	,init: function() {
		_self = this;

		// setup variables
		this.user = $('#spl-account-summary').data('account');
		//console.log(this.user);

		// init ui
		this.initMyAccount();

	} // init()

, initMyAccount: function() {

		this.initTabs();

		this.initCko();

		this.initProfile();

  } // initMyAccount()

, initTabs: function() {
		// apply hash onload
		if ( window.location.hash ) {
			$('a[href="'+window.location.hash+'"]').tab('show')
		}

		// apply hashchange on tab event
		//$('body').on('click', '[data-toggle="tab"]', function(e) {
		$('[data-toggle="tab"]').click(function(e) {
			window.location.hash = $(this).attr('href');
		});

	} // initTabs()

, initCko: function() {
		var $form = $('#spl-form-cko');

		var $selectAll = $('.spl-field-cko-select-all');
		var $selectItem = $('.spl-field-cko-select-item');

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});

		$form.on('submit', function(e) {
			if ( 'ajax' == $(this).data('process') ) {
				e.preventDefault();

				var barcodes = new Array;
				$('.spl-field-cko-select-item:checked').each(function() {
					barcodes.push( $(this).data('barcode') );
				});

				if ( barcodes.length > 0 ) {
					_self.ckoRenew(barcodes);
				} else {
					alert('Please select item(s) to renew.');
				}
			}

		});

	} // initCko()

, ckoRenew: function(barcodes) {
		var $form = $('#spl-form-cko');
		var $submit = $('.spl-submit-cko');
		var $hidden = $('#spl-field-cko-renewal');

		$submit.button('loading'); //$submit.button('reset');
		$.ajax({
	    url: this.config.endpoint.hzws+'renew' //'renew' //'trace'
    , data: { params: { token: this.user.sessionToken
    									,	barcodes: barcodes
    									}
    				}
	  })
	  .done(function(obj) {
	  	// pass results through
			$hidden.val(JSON.stringify(obj));
			$form.data('process', 'http').submit();
	  })
	  .fail(function() {
	  })
	  .always(function() {
	  });

	} // ckoRenew()

, initHolds: function() {
		this.initHoldsPending();

		console.log('holds pending'):
	} // initHolds()

, initHoldsPending: function() {
		var $form = $('#spl-form-holds-pending');

		var $selectAll = $('.spl-field-holds-pending-select-all');
		var $selectItem = $('.spl-field-holds-pending-select-item');

		$selectAll.on('change', function(e) {
			if ( $(this).is(':checked') ) {
				$selectAll.prop('checked', true);
				$selectItem.prop('checked', true);
			} else {
				$selectAll.prop('checked', false);
				$selectItem.prop('checked', false);
			}
		});
	} // initHoldsPending()

, initProfile: function() {
		this.initProfileEmail();
		this.initProfilePin();

	} // initProfile()

, initProfileEmail: function() {
		// it turns out hzws has no methods for updating email
		// will need addres ord? or maybe just select on old address?
		var $form = $('#spl-form-profile-email');
		var $email = $('#spl-field-profile-email');
		var $submit = $('#spl-submit-profile-email');

		$form.validate();

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

	} // initProfileEmail()

, initProfilePin: function() {
	// note: we will need a new session token here (loginUserResetMyPin)
	var $form = $('#spl-form-profile-pin');

	var $submit = $('#spl-submit-profile-pin');

	$form.validate({
		rules: {
			pinConfirm: {
	      equalTo: "#spl-field-profile-pin-new"
	    }
  	}
	});

		$form.on('submit', function(e) {
			e.preventDefault();
			if ( $form.valid() ) {
				/*
				console.log( _self.user.borrower );
				console.log( _self.user.sessionToken );
				console.log( $email.val() );
				$submit.button('loading');
				*/
			}
		});

} // initProfilePin()

};
<|endoftext|>


<commit_before>import '../Assets/styleSheets/base.scss';
import React,{Component} from 'react';

class urlShort extends Component{
    render(){
        return(

                    Supercalifragilistic API  url shortener microservice

                    Example shortener creation usage:

                    https://freecodecampapichallenges.herokuapp.com/api/newurl/http://www.google.com

                    Example result output:

                    "original_url":"http://www.google.com, "shortened_url":"https://freecodecampapichallenges.herokuapp.com/api/short/8888"

                    To get a list of the urls introduced use the following url:

                    https://freecodecampapichallenges.herokuapp.com/api/listurls

                    Usage of the microservice:

                        https://freecodecampapichallenges.herokuapp.com/api/short/8888

        );
    }
};
export default urlShort;<commit_msg>trying commits to check the heroku sync<commit_after>import '../Assets/styleSheets/base.scss';
import React,{Component} from 'react';

class urlShort extends Component{
    render(){
        return(

                    Supercalifragilistic API  url shortener microservice

                    Example shortener creation usage:

                    https://freecodecampapichallenges.herokuapp.com/api/newurl/http://www.google.com

                    Example result output:

                    "original_url":"http://www.google.com, "shortened_url":"https://freecodecampapichallenges.herokuapp.com/api/short/8888"

                    To get a list of the urls introduced use the following url:

                    https://freecodecampapichallenges.herokuapp.com/api/listurls

                    Usage of the microservice:

                        https://freecodecampapichallenges.herokuapp.com/api/short/8888

        );
    }
};
export default urlShort;<|endoftext|>


<commit_before>import { createAction } from 'redux-actions';
import { createThunkAction } from 'utils/redux';
import isEmpty from 'lodash/isEmpty';

/* @tmpfix: remove usage of indcTransform */
import indcTransform from 'utils/indctransform';

const fetchLTSInit = createAction('fetchLTSInit');
const fetchLTSReady = createAction('fetchLTSReady');
const fetchLTSFail = createAction('fetchLTSFail');

const fetchLTS = createThunkAction('fetchLTS', () => (dispatch, state) => {
  const { ndcs } = state();
  if (
    ndcs &&
    (isEmpty(ndcs.data) || isEmpty(ndcs.data.indicators)) &&
    !ndcs.loading
  ) {
    dispatch(fetchLTSInit());
    fetch('/api/v1/ndcs?source=LTS&filter=map')
      .then(response => {
        if (response.ok) return response.json();
        throw Error(response.statusText);
      })
      .then(data => indcTransform(data))
      .then(data => {
        dispatch(fetchLTSReady(data));
      })
      .catch(error => {
        console.warn(error);
        dispatch(fetchLTSFail());
      });
  }
});

export default {
  fetchLTS,
  fetchLTSInit,
  fetchLTSReady,
  fetchLTSFail
};
<commit_msg>Fix lts explore fetching<commit_after>import { createAction } from 'redux-actions';
import { createThunkAction } from 'utils/redux';
import isEmpty from 'lodash/isEmpty';

/* @tmpfix: remove usage of indcTransform */
import indcTransform from 'utils/indctransform';

const fetchLTSInit = createAction('fetchLTSInit');
const fetchLTSReady = createAction('fetchLTSReady');
const fetchLTSFail = createAction('fetchLTSFail');

const fetchLTS = createThunkAction('fetchLTS', () => (dispatch, state) => {
  const { LTS } = state();
  if (
    LTS &&
    (isEmpty(LTS.data) || isEmpty(LTS.data.indicators)) &&
    !LTS.loading
  ) {
    dispatch(fetchLTSInit());
    fetch('/api/v1/ndcs?source=LTS&filter=map')
      .then(response => {
        if (response.ok) return response.json();
        throw Error(response.statusText);
      })
      .then(data => indcTransform(data))
      .then(data => {
        dispatch(fetchLTSReady(data));
      })
      .catch(error => {
        console.warn(error);
        dispatch(fetchLTSFail());
      });
  }
});

export default {
  fetchLTS,
  fetchLTSInit,
  fetchLTSReady,
  fetchLTSFail
};
<|endoftext|>


<commit_before>/* eslint-disable prettier/prettier */
/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import { COLUMN_TYPES } from './constants';
import { UIDatabase, createRecord } from '../../database';

const COLUMN_INDICATOR = {
  width: 1,
  sortable: false,
};

const COLUMN_INDICATOR_IMMUTABLE = {
  type: COLUMN_TYPES.STRING,
  editable: false,
  ...COLUMN_INDICATOR,
};

const COLUMN_INDICATOR_MUTABLE = {
  type: COLUMN_TYPES.EDITABLE_STRING,
  editable: true,
  ...COLUMN_INDICATOR,
};

const COLUMNS = {
  DESCRIPTION: {
    ...COLUMN_INDICATOR_IMMUTABLE,
    title: 'Description',
    key: 'description',
  },
  CODE: {
    ...COLUMN_INDICATOR_IMMUTABLE,
    title: 'Code',
    key: 'code',
  },
};

/**
 * Returns a filter method for finding a subset of an array of IndicatorAttribute objects by period.
 * @param {Array.<IndicatorAttribute>} filterPeriod
 * @return {Func}
 */
const filterByPeriod = filterPeriod => ({ period }) => period.id === filterPeriod.id;

/**
 * Returns a find method for querying an array of indicatorValue for the index of a given object.
 * @param {IndicatorValue} findValue
 * @return {Func}
 */
const findByValue = findValue => value => findValue.id === value.id;

/**
 * Query if an IndicatorValue array contains a given object.
 * @param {Array.<IndicatorValue>} values
 * @param {IndicatorValue} value
 */
const includesValue = (values, value) => {
  const result = values.findIndex(findByValue(value)) > 0;
  return result;
};

/**
 * Returns a filter method for getting the intersection of two arrays of IndicatorValue objects.
 * @param {Array.<IndicatorValue>} values
 * @return {Func}
 */
const filterByValues = values => value => includesValue(values, value);

/**
 * Intialise a new indicator value.
 *
 * @param {IndicatorAttribute} row
 * @param {IndicatorAttribute} column
 * @param {Period} period
 */
const initialiseRowColumnValue = (row, column, period) => {
  let record;
  UIDatabase.write(() => {
    record = createRecord(UIDatabase, 'IndicatorValue', row, column, period);
  });
  return record;
};

/**
 * Get indicator column by code.
 * @param {ProgramIndicator} indicator
 * @param {string} code
 * @return {Array.<IndicatorAttribute>}
 */
const getIndicatorColumns = (indicator, code) =>
    indicator?.columns?.filter(({ code: columnCode }) => columnCode === code);

/**
 * Get indicator rows by id.
 * @param {ProgramIndicator} indicator
 * @param {string} id
 * @return {Array.<IndicatorAttribute>}
 */
const getIndicatorRows = (indicator, id) =>
    indicator?.rows?.filter(({ id: rowId }) => rowId === id);

/**
 * Get value for indicator row, column attribute pair.
 *
 * @param {IndicatorAttribute} row
 * @param {IndicatorAttribute} column
 * @param {Period} period
 * @return {IndicatorValue}
 */
const getIndicatorRowColumnValue = (row, column, period) => {
  const rowValues = row.values.filter(filterByPeriod(period));
  const columnValues = column.values.filter(filterByPeriod(period));
  const rowColumnValues = rowValues?.filter(filterByValues(columnValues));
  const [rowColumnValue] = rowColumnValues;
  return rowColumnValue || initialiseRowColumnValue(row, column, period);
};

const getIndicatorData = indicator => ({
  rows: getIndicatorRows(indicator),
  columns: getIndicatorColumns(indicator),
});

/**
 * Get data table column for indicator column attribute.
 * @param {IndicatorAttribute} column
 * @return {object}
 */
const getIndicatorTableColumn = column => {
  const { description: title, code: key } = column;
  return {
    ...COLUMN_INDICATOR_MUTABLE,
    title,
    key,
  };
};

/**
 * Get data table columns for given indicator.
 * @param {ProgramIndicator} indicator
 * @returns {Array.<object>}
 */
const getIndicatorTableColumns = indicator => {
  if (!indicator) return [];
  const valueColumns = indicator.columns.map(column => getIndicatorTableColumn(column));
  return [COLUMNS.DESCRIPTION, COLUMNS.CODE, ...valueColumns];
};

/**
 * Get data table row for indicator row attribute.
 * @param {IndicatorAttribute} row
 * @param {ProgramIndicator} indicator
 * @param {Period} period
 */
const getIndicatorTableRow = (row, indicator, period) => {
  const [rowObject] = indicator.rows.filter(({ id: rowId }) => rowId === row.id);
  const { id, description, code } = rowObject;
  const values = indicator.columns.reduce((acc, column) => {
    const { code: key } = column;
    const value = getIndicatorRowColumnValue(rowObject, column, period);
    return { ...acc, [key]: value.value };
  }, {});
  return { id, description, code, ...values };
};

/**
 * Get indicator data table rows.
 *
 * @param {ProgramIndicator} indicator
 * @param {Period} period
 * @returns {Array.<object>}
 */
const getIndicatorTableRows = (indicator, period) => {
  if (!indicator) return [];
  return indicator.rows.map(row => getIndicatorTableRow(row, indicator, period));
};

/**
 * Get indicator data table rows and columns.
 *
 * @param {ProgramIndicator} indicator
 * @param {Period} period
 * @returns {object}
 */
const getIndicatorTableData = (indicator, period) => {
  const columns = getIndicatorTableColumns(indicator, period);
  const rows = getIndicatorTableRows(indicator, period);
  return { columns, rows };
};

export {
  getIndicatorRows,
  getIndicatorColumns,
  getIndicatorRowColumnValue,
  getIndicatorData,
  getIndicatorTableRow,
  getIndicatorTableRows,
  getIndicatorTableColumns,
  getIndicatorTableData,
};
<commit_msg>Remove prettier disable<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import { COLUMN_TYPES } from './constants';
import { UIDatabase, createRecord } from '../../database';

const COLUMN_INDICATOR = {
  width: 1,
  sortable: false,
};

const COLUMN_INDICATOR_IMMUTABLE = {
  type: COLUMN_TYPES.STRING,
  editable: false,
  ...COLUMN_INDICATOR,
};

const COLUMN_INDICATOR_MUTABLE = {
  type: COLUMN_TYPES.EDITABLE_STRING,
  editable: true,
  ...COLUMN_INDICATOR,
};

const COLUMNS = {
  DESCRIPTION: {
    ...COLUMN_INDICATOR_IMMUTABLE,
    title: 'Description',
    key: 'description',
  },
  CODE: {
    ...COLUMN_INDICATOR_IMMUTABLE,
    title: 'Code',
    key: 'code',
  },
};

/**
 * Returns a filter method for finding a subset of an array of IndicatorAttribute objects by period.
 * @param {Array.<IndicatorAttribute>} filterPeriod
 * @return {Func}
 */
const filterByPeriod = filterPeriod => ({ period }) => period.id === filterPeriod.id;

/**
 * Returns a find method for querying an array of indicatorValue for the index of a given object.
 * @param {IndicatorValue} findValue
 * @return {Func}
 */
const findByValue = findValue => value => findValue.id === value.id;

/**
 * Query if an IndicatorValue array contains a given object.
 * @param {Array.<IndicatorValue>} values
 * @param {IndicatorValue} value
 */
const includesValue = (values, value) => {
  const result = values.findIndex(findByValue(value)) > 0;
  return result;
};

/**
 * Returns a filter method for getting the intersection of two arrays of IndicatorValue objects.
 * @param {Array.<IndicatorValue>} values
 * @return {Func}
 */
const filterByValues = values => value => includesValue(values, value);

/**
 * Intialise a new indicator value.
 *
 * @param {IndicatorAttribute} row
 * @param {IndicatorAttribute} column
 * @param {Period} period
 */
const initialiseRowColumnValue = (row, column, period) => {
  let record;
  UIDatabase.write(() => {
    record = createRecord(UIDatabase, 'IndicatorValue', row, column, period);
  });
  return record;
};

/**
 * Get indicator column by code.
 * @param {ProgramIndicator} indicator
 * @param {string} code
 * @return {Array.<IndicatorAttribute>}
 */
const getIndicatorColumns = (indicator, code) =>
  indicator?.columns?.filter(({ code: columnCode }) => columnCode === code);

/**
 * Get indicator rows by id.
 * @param {ProgramIndicator} indicator
 * @param {string} id
 * @return {Array.<IndicatorAttribute>}
 */
const getIndicatorRows = (indicator, id) =>
  indicator?.rows?.filter(({ id: rowId }) => rowId === id);

/**
 * Get value for indicator row, column attribute pair.
 *
 * @param {IndicatorAttribute} row
 * @param {IndicatorAttribute} column
 * @param {Period} period
 * @return {IndicatorValue}
 */
const getIndicatorRowColumnValue = (row, column, period) => {
  const rowValues = row.values.filter(filterByPeriod(period));
  const columnValues = column.values.filter(filterByPeriod(period));
  const rowColumnValues = rowValues?.filter(filterByValues(columnValues));
  const [rowColumnValue] = rowColumnValues;
  return rowColumnValue || initialiseRowColumnValue(row, column, period);
};

const getIndicatorData = indicator => ({
  rows: getIndicatorRows(indicator),
  columns: getIndicatorColumns(indicator),
});

/**
 * Get data table column for indicator column attribute.
 * @param {IndicatorAttribute} column
 * @return {object}
 */
const getIndicatorTableColumn = column => {
  const { description: title, code: key } = column;
  return {
    ...COLUMN_INDICATOR_MUTABLE,
    title,
    key,
  };
};

/**
 * Get data table columns for given indicator.
 * @param {ProgramIndicator} indicator
 * @returns {Array.<object>}
 */
const getIndicatorTableColumns = indicator => {
  if (!indicator) return [];
  const valueColumns = indicator.columns.map(column => getIndicatorTableColumn(column));
  return [COLUMNS.DESCRIPTION, COLUMNS.CODE, ...valueColumns];
};

/**
 * Get data table row for indicator row attribute.
 * @param {IndicatorAttribute} row
 * @param {ProgramIndicator} indicator
 * @param {Period} period
 */
const getIndicatorTableRow = (row, indicator, period) => {
  const [rowObject] = indicator.rows.filter(({ id: rowId }) => rowId === row.id);
  const { id, description, code } = rowObject;
  const values = indicator.columns.reduce((acc, column) => {
    const { code: key } = column;
    const value = getIndicatorRowColumnValue(rowObject, column, period);
    return { ...acc, [key]: value.value };
  }, {});
  return { id, description, code, ...values };
};

/**
 * Get indicator data table rows.
 *
 * @param {ProgramIndicator} indicator
 * @param {Period} period
 * @returns {Array.<object>}
 */
const getIndicatorTableRows = (indicator, period) => {
  if (!indicator) return [];
  return indicator.rows.map(row => getIndicatorTableRow(row, indicator, period));
};

/**
 * Get indicator data table rows and columns.
 *
 * @param {ProgramIndicator} indicator
 * @param {Period} period
 * @returns {object}
 */
const getIndicatorTableData = (indicator, period) => {
  const columns = getIndicatorTableColumns(indicator, period);
  const rows = getIndicatorTableRows(indicator, period);
  return { columns, rows };
};

export {
  getIndicatorRows,
  getIndicatorColumns,
  getIndicatorRowColumnValue,
  getIndicatorData,
  getIndicatorTableRow,
  getIndicatorTableRows,
  getIndicatorTableColumns,
  getIndicatorTableData,
};
<|endoftext|>


<commit_before>"use strict";

var chai = require("chai");
var expect = chai.expect;

var yaioc = require("../yaioc.js");

describe("yaioc test", function () {

    function TargetFunction(dependencyOne, dependencyTwo) {
        this.args = arguments;
        this.dependencyOne = dependencyOne;
        this.dependencyTwo = dependencyTwo;
    }

    var container;

    beforeEach(function () {
        container = yaioc.container();
    });

    describe("register and resolve", function () {

        it("should return simple value objects", function () {
            var dependencyOne = {};
            container.registerValue("dependencyOne", dependencyOne);

            var resolved = container.get("dependencyOne");

            expect(resolved).to.be.equal(dependencyOne);
        });

        it("should return simple value objects registered via general method", function () {
            var dependencyOne = {};
            container.register("dependencyOne", dependencyOne);

            var resolved = container.get("dependencyOne");

            expect(resolved).to.be.equal(dependencyOne);
        });

        it("should instantiate object with dependencies", function () {
            var dependencyOne = {};
            container.register("dependencyOne", dependencyOne);
            var dependencyTwo = {};
            container.register("dependencyTwo", dependencyTwo);

            container.registerConstructor("TargetFunction", TargetFunction);

            var instance = container.get("TargetFunction");

            expect(instance.args.length).to.be.eql(2);
            expect(instance.dependencyOne).to.be.eql(dependencyOne);
            expect(instance.dependencyTwo).to.be.eql(dependencyTwo);
            expect(instance).to.be.instanceof(TargetFunction);
        });

        it("should instantiate object with dependencies via general method", function () {
            container.register("dependencyOne", {});
            container.register("dependencyTwo", {});
            container.register("TargetFunction", TargetFunction);

            var instance = container.get("TargetFunction");

            expect(instance.args.length).to.be.eql(2);
            expect(instance).to.be.instanceof(TargetFunction);
        });

        it("should throw if dependency cannot be resolved", function () {
            var container = yaioc.container();
            container.register(TargetFunction);

            var action = container.get.bind(container, "targetFunction");

            expect(action).to.throw(/Could not satisfy dependency/);
        });

        it("should include name of missing dependency", function () {
            var container = yaioc.container();
            container.register(TargetFunction);

            var action = container.get.bind(container, "targetFunction");

            expect(action).to.throw(/dependencyOne/);
        });

        it("should include traget name of missing dependency", function () {
            var container = yaioc.container();
            container.register(TargetFunction);

            var action = container.get.bind(container, "targetFunction");

            expect(action).to.throw(/TargetFunction/);
        });

        it("should resolve types which end in upper case", function () {
            function TypeAB() { TargetFunction.call(this); }

            container.register(TypeAB);

            var instance = container.get("typeAB");
            expect(instance).to.be.instanceof(TypeAB);
        });

    });

    describe("get", function () {

        it("should instanciate registered constructor function as dependency", function () {
            function Dependency() {}
            function Target(dependency) { this.dependency = dependency; }
            container.register(Dependency);
            container.register(Target);

            var targetInstance = container.get("Target");

            expect(targetInstance.dependency).to.be.instanceof(Dependency);
        });

    });

    describe("register", function () {

        it("should use name of function if present", function () {

            container.register(TargetFunction);

            expect("TargetFunction" in container.registry.factories).to.be.eql(true);
        });

        it("should throw if no name is present and cannot be resolver", function () {

            var callRegister = container.register.bind(container, {});

            expect(callRegister).to.throw(/no name provided for dependency/);
        });

    });

    describe("cache", function () {

        it("should resolve to new instance on every call", function () {
            container.register("dependencyOne", {});
            container.register("dependencyTwo", {});
            container.register(TargetFunction);

            var instanceA = container.get("targetFunction");
            var instanceB = container.get("targetFunction");

            expect(instanceA).to.be.instanceof(TargetFunction);
            expect(instanceB).to.be.instanceof(TargetFunction);
            expect(instanceA === instanceB).to.be.eql(false);
        });

        it("should resolve to same instance on every call, when registered in cache", function () {
            container.register("dependencyOne", {});
            container.register("dependencyTwo", {});
            container.cache().register(TargetFunction);

            var instanceA = container.get("targetFunction");
            var instanceB = container.get("targetFunction");

            expect(instanceA).to.be.instanceof(TargetFunction);
            expect(instanceB).to.be.instanceof(TargetFunction);
            expect(instanceA === instanceB).to.be.eql(true);
        });

    });

    describe("registerFactory", function () {

        it("should resolve to result of given function", function () {
            var result = {};
            container.registerFactory("factoryThing", function () {
                return result;
            });

            var actualResult = container.get("factoryThing");

            expect(actualResult).to.be.eql(result);
        });

        it("should resolve and provide dependencies of given function", function () {
            var dependencyOne = {};
            container.register("dependencyOne", dependencyOne);
            container.registerFactory("factoryThing", function (dependencyOne) {
                return dependencyOne;
            });

            var actualResult = container.get("factoryThing");

            expect(actualResult).to.be.equal(dependencyOne);
        });

    });

    describe("getDependencyNames", function () {

        it("should return empty list if no dependencies found", function () {

            var names = container.registry.getDependencyNames(function () {
            });

            expect(names).to.be.an("array");
            expect(names.length).to.be.eql(0);
        });

        it("should return names of dependencies found", function () {

            var names = container.registry.getDependencyNames(TargetFunction);

            expect(names).to.be.eql(["dependencyOne", "dependencyTwo"]);
        });

    });

    describe("ease of use", function () {

        it("yaioc() should return a Container instance", function () {
            var container = yaioc();

            expect(container).to.be.instanceof(yaioc.Container);
        });

        it("yaioc() should return always the same Container instance", function () {
            var container1 = yaioc();
            var container2 = yaioc();

            expect(container1 === container2).to.be.eql(true);
        });

    });

    describe("child containers", function () {

        it("should optionally take a container in constructor, which is used for dependency resolving", function () {
            var wrappedContainer = yaioc.container();
            var container = yaioc.container(wrappedContainer);

            var foo = {};
            wrappedContainer.register("foo", foo);

            var resolvedFoo = container.get("foo");

            expect(resolvedFoo === foo).to.be.eql(true);
        });

        it("should not resolve dependencies in outer container", function () {
            var wrappedContainer = yaioc.container();
            var container = yaioc.container(wrappedContainer);

            var foo = {};
            container.register("foo", foo);

            var resolvedFoo = wrappedContainer.get("foo");

            expect(resolvedFoo).to.be.eql(void 0);
        });

        it("should resolve constructors in wrapped container", function () {
            var wrappedContainer = yaioc.container();
            var container = yaioc.container(wrappedContainer);
            wrappedContainer.register(TargetFunction);
            wrappedContainer.register("dependencyOne", {});
            wrappedContainer.register("dependencyTwo", {});

            var targetFunction = container.get("targetFunction");

            expect(targetFunction).to.be.a.instanceof(TargetFunction);
        });

    });

});
<commit_msg>cleanup tests<commit_after>"use strict";

var chai = require("chai");
var expect = chai.expect;

var yaioc = require("../yaioc.js");

describe("yaioc test", function () {

    function TargetFunction(dependencyOne, dependencyTwo) {
        this.args = arguments;
        this.dependencyOne = dependencyOne;
        this.dependencyTwo = dependencyTwo;
    }

    var container;

    beforeEach(function () {
        container = yaioc.container();
    });

    describe("register and resolve", function () {

        it("should return simple value objects", function () {
            var dependencyOne = {};
            container.registerValue("dependencyOne", dependencyOne);

            var resolved = container.get("dependencyOne");

            expect(resolved).to.be.equal(dependencyOne);
        });

        it("should return simple value objects registered via general method", function () {
            var dependencyOne = {};
            container.register("dependencyOne", dependencyOne);

            var resolved = container.get("dependencyOne");

            expect(resolved).to.be.equal(dependencyOne);
        });

        it("should instantiate object with dependencies", function () {
            var dependencyOne = {};
            container.register("dependencyOne", dependencyOne);
            var dependencyTwo = {};
            container.register("dependencyTwo", dependencyTwo);

            container.registerConstructor("TargetFunction", TargetFunction);

            var instance = container.get("TargetFunction");

            expect(instance.args.length).to.be.eql(2);
            expect(instance.dependencyOne).to.be.eql(dependencyOne);
            expect(instance.dependencyTwo).to.be.eql(dependencyTwo);
            expect(instance).to.be.instanceof(TargetFunction);
        });

        it("should instantiate object with dependencies via general method", function () {
            container.register("dependencyOne", {});
            container.register("dependencyTwo", {});
            container.register("TargetFunction", TargetFunction);

            var instance = container.get("TargetFunction");

            expect(instance.args.length).to.be.eql(2);
            expect(instance).to.be.instanceof(TargetFunction);
        });

        it("should throw if dependency cannot be resolved", function () {
            var container = yaioc.container();
            container.register(TargetFunction);

            var action = container.get.bind(container, "targetFunction");

            expect(action).to.throw(/Could not satisfy dependency/);
        });

        it("should include name of missing dependency", function () {
            var container = yaioc.container();
            container.register(TargetFunction);

            var action = container.get.bind(container, "targetFunction");

            expect(action).to.throw(/dependencyOne/);
        });

        it("should include traget name of missing dependency", function () {
            var container = yaioc.container();
            container.register(TargetFunction);

            var action = container.get.bind(container, "targetFunction");

            expect(action).to.throw(/TargetFunction/);
        });

        it("should resolve types which end in upper case", function () {
            function TypeAB() { TargetFunction.call(this); }

            container.register(TypeAB);

            var instance = container.get("typeAB");
            expect(instance).to.be.instanceof(TypeAB);
        });

        it("should use name of function if present", function () {

            container.register(TargetFunction);

            expect("TargetFunction" in container.registry.factories).to.be.eql(true);
        });

        it("should throw if no name is present and cannot be resolved", function () {

            var callRegister = container.register.bind(container, {});

            expect(callRegister).to.throw(/no name provided for dependency/);
        });

    });

    describe("get", function () {

        it("should instantiate registered constructor function as dependency", function () {
            function Dependency() {}
            function Target(dependency) { this.dependency = dependency; }
            container.register(Dependency);
            container.register(Target);

            var targetInstance = container.get("Target");

            expect(targetInstance.dependency).to.be.instanceof(Dependency);
        });

    });

    describe("cache", function () {

        it("should resolve to new instance on every call", function () {
            container.register("dependencyOne", {});
            container.register("dependencyTwo", {});
            container.register(TargetFunction);

            var instanceA = container.get("targetFunction");
            var instanceB = container.get("targetFunction");

            expect(instanceA).to.be.instanceof(TargetFunction);
            expect(instanceB).to.be.instanceof(TargetFunction);
            expect(instanceA === instanceB).to.be.eql(false);
        });

        it("should resolve to same instance on every call, when registered in cache", function () {
            container.register("dependencyOne", {});
            container.register("dependencyTwo", {});
            container.cache().register(TargetFunction);

            var instanceA = container.get("targetFunction");
            var instanceB = container.get("targetFunction");

            expect(instanceA).to.be.instanceof(TargetFunction);
            expect(instanceB).to.be.instanceof(TargetFunction);
            expect(instanceA === instanceB).to.be.eql(true);
        });

    });

    describe("registerFactory", function () {

        it("should resolve to result of given function", function () {
            var result = {};
            container.registerFactory("factoryThing", function () {
                return result;
            });

            var actualResult = container.get("factoryThing");

            expect(actualResult).to.be.eql(result);
        });

        it("should resolve and provide dependencies of given function", function () {
            var dependencyOne = {};
            container.register("dependencyOne", dependencyOne);
            container.registerFactory("factoryThing", function (dependencyOne) {
                return dependencyOne;
            });

            var actualResult = container.get("factoryThing");

            expect(actualResult).to.be.equal(dependencyOne);
        });

    });

    describe("getDependencyNames", function () {

        it("should return empty list if no dependencies found", function () {

            var names = container.registry.getDependencyNames(function () {
            });

            expect(names).to.be.an("array");
            expect(names.length).to.be.eql(0);
        });

        it("should return names of dependencies found", function () {

            var names = container.registry.getDependencyNames(TargetFunction);

            expect(names).to.be.eql(["dependencyOne", "dependencyTwo"]);
        });

    });

    describe("ease of use", function () {

        it("yaioc() should return a Container instance", function () {
            var container = yaioc();

            expect(container).to.be.instanceof(yaioc.Container);
        });

        it("yaioc() should return always the same Container instance", function () {
            var container1 = yaioc();
            var container2 = yaioc();

            expect(container1 === container2).to.be.eql(true);
        });

    });

    describe("child containers", function () {

        it("should optionally take a container in constructor, which is used for dependency resolving", function () {
            var wrappedContainer = yaioc.container();
            var container = yaioc.container(wrappedContainer);

            var foo = {};
            wrappedContainer.register("foo", foo);

            var resolvedFoo = container.get("foo");

            expect(resolvedFoo === foo).to.be.eql(true);
        });

        it("should not resolve dependencies in outer container", function () {
            var wrappedContainer = yaioc.container();
            var container = yaioc.container(wrappedContainer);

            var foo = {};
            container.register("foo", foo);

            var resolvedFoo = wrappedContainer.get("foo");

            expect(resolvedFoo).to.be.eql(void 0);
        });

        it("should resolve constructors in wrapped container", function () {
            var wrappedContainer = yaioc.container();
            var container = yaioc.container(wrappedContainer);
            wrappedContainer.register(TargetFunction);
            wrappedContainer.register("dependencyOne", {});
            wrappedContainer.register("dependencyTwo", {});

            var targetFunction = container.get("targetFunction");

            expect(targetFunction).to.be.a.instanceof(TargetFunction);
        });

    });

});
<|endoftext|>