<commit_before>var db = require('mongoose');
var numeral = require('numeral');
var moment = require('moment');

/**
 * get
 *
 * Returns a list of all transactions
 * optionally filtering by category
 * or date.
 */

var get = function get(req, res, next) {
  var t = db.model('transactions').find();
  var category = req.params.category;
  var year = req.params.year;
  var month = req.params.month;

  if (category) t = t.where({ category: category });
  // if (year) {
  //   t = t.where({  });
  // }

  t.exec(function(err, list) {
    if (err) next(err);
    res.send(list);
  });
};

/**
 * post
 *
 * Creates a new transaction given
 * some data.
 */

var post = function post(req, res, next) {
  var description = req.body.description || 'Transaction';
  var amount = req.body.amount || 0;
  var category = req.body.category || 'Default';
  var date = req.body.date || new Date();

  db.model('transactions').create({
    description: description,
    amount: amount,
    category: category,
    date: date
  }, function(err) {
    if (err) next(err);
    res.redirect('/');
  });
};

/**
 * put
 *
 * Updates a specific transaction
 * given some data and an id.
 */

var put = function put(req, res, next) {
  var id = req.body.id;
  var description = req.body.description;
  var amount = req.body.amount;
  var category = req.body.category;
  var date = req.body.date;

  db.model('transactions').findById(id, function(err, tr) {
    if (err) next(err);

    if (description) tr.description = description.trim();
    if (amount) tr.amount = parseFloat(amount.replace('$', ''));
    if (category) tr.category = category.trim();
    if (date) tr.date = new Date(date);

    tr.save(function(err) {
      if (err) next(err);
      tr.amount = numeral(tr.amount).format('$0,0.00');
      res.send(tr);
    });
  });
};

/**
 * remove
 *
 * Deletes a specific transaction
 * given an id.
 */

var remove = function remove(req, res, next) {
  db.model('transactions').findByIdAndRemove(req.body.id, function(err) {
    if (err) next(err);
  });
};

/**
 * categories
 *
 * Returns a list of all distinct
 * categories of transactions.
 */

var categories = function categories(cb, next) {
  var t = db.model('transactions').find();
  t.distinct('category');
  t.exec(function(err, list) {
    if (err) next(err);
    cb(list);
  });
};

/**
 * render
 *
 * Renders the view for transactions.
 * By default, renders transactions for current month.
 * Can also render by category and/or year + month.
 */

var render = function render(req, res, next) {
  var category = req.params.category;
  var year = req.params.year;
  var month = req.params.month;

  var date = month ? moment().set({ year: year, month: month }) : moment();
  var dateMin = date.clone().date(1);
  var dateMax = date.clone().endOf('month');

  var transactions = db.model('transactions')
    .find()
    .where('date')
      .gt(dateMin.toDate())
      .lt(dateMax.toDate());

  if (category) {
    transactions = transactions
      .where('category')
      .equals(category);
  }

  transactions.exec(function(err, list) {
    if (err) next(err);

    // sort by date
    var sorted = list.sort(function(a, b) {
      if (a.date < b.date) return -1;
      if (a.date > b.date) return 1;
      return 0;
    }).reverse();

    // total all amounts
    var total = list.reduce(function(sum, t) {
      return sum += t.amount;
    }, 0);

    // total income
    var totalIn = list.reduce(function(sum, t) {
      if (t.amount > 0) return sum += t.amount;
      return sum;
    }, 0);

    // total expenses
    var totalOut = list.reduce(function(sum, t) {
      if (t.amount < 0) return sum += t.amount;
      return sum;
    }, 0);

    res.render('index', {
      transactions: sorted,
      totals: {
        all: total,
        income: totalIn,
        expenses: totalOut
      },
      category: category || '',
      date: date.format('MMMM YYYY')
    });
  });
};

module.exports = {
  get: get,
  post: post,
  put: put,
  remove: remove,
  categories: categories,
  render: render
};
<commit_msg>comparison should be gte/lte, dateMin should be startOf('month')<commit_after>var db = require('mongoose');
var numeral = require('numeral');
var moment = require('moment');

/**
 * get
 *
 * Returns a list of all transactions
 * optionally filtering by category
 * or date.
 */

var get = function get(req, res, next) {
  var t = db.model('transactions').find();
  var category = req.params.category;
  var year = req.params.year;
  var month = req.params.month;

  if (category) t = t.where({ category: category });
  // if (year) {
  //   t = t.where({  });
  // }

  t.exec(function(err, list) {
    if (err) next(err);
    res.send(list);
  });
};

/**
 * post
 *
 * Creates a new transaction given
 * some data.
 */

var post = function post(req, res, next) {
  var description = req.body.description || 'Transaction';
  var amount = req.body.amount || 0;
  var category = req.body.category || 'Default';
  var date = req.body.date || new Date();

  db.model('transactions').create({
    description: description,
    amount: amount,
    category: category,
    date: date
  }, function(err) {
    if (err) next(err);
    res.redirect('/');
  });
};

/**
 * put
 *
 * Updates a specific transaction
 * given some data and an id.
 */

var put = function put(req, res, next) {
  var id = req.body.id;
  var description = req.body.description;
  var amount = req.body.amount;
  var category = req.body.category;
  var date = req.body.date;

  db.model('transactions').findById(id, function(err, tr) {
    if (err) next(err);

    if (description) tr.description = description.trim();
    if (amount) tr.amount = parseFloat(amount.replace('$', ''));
    if (category) tr.category = category.trim();
    if (date) tr.date = new Date(date);

    tr.save(function(err) {
      if (err) next(err);
      tr.amount = numeral(tr.amount).format('$0,0.00');
      res.send(tr);
    });
  });
};

/**
 * remove
 *
 * Deletes a specific transaction
 * given an id.
 */

var remove = function remove(req, res, next) {
  db.model('transactions').findByIdAndRemove(req.body.id, function(err) {
    if (err) next(err);
  });
};

/**
 * categories
 *
 * Returns a list of all distinct
 * categories of transactions.
 */

var categories = function categories(cb, next) {
  var t = db.model('transactions').find();
  t.distinct('category');
  t.exec(function(err, list) {
    if (err) next(err);
    cb(list);
  });
};

/**
 * render
 *
 * Renders the view for transactions.
 * By default, renders transactions for current month.
 * Can also render by category and/or year + month.
 */

var render = function render(req, res, next) {
  var category = req.params.category;
  var year = req.params.year;
  var month = req.params.month;

  var date = month ? moment().set({ year: year, month: month }) : moment();
  var dateMin = date.clone().startOf('month');
  var dateMax = date.clone().endOf('month');

  var transactions = db.model('transactions')
    .find()
    .where('date')
      .gte(dateMin.toDate())
      .lte(dateMax.toDate());

  if (category) {
    transactions = transactions
      .where('category')
      .equals(category);
  }

  transactions.exec(function(err, list) {
    if (err) next(err);

    // sort by date
    var sorted = list.sort(function(a, b) {
      if (a.date < b.date) return -1;
      if (a.date > b.date) return 1;
      return 0;
    }).reverse();

    // total all amounts
    var total = list.reduce(function(sum, t) {
      return sum += t.amount;
    }, 0);

    // total income
    var totalIn = list.reduce(function(sum, t) {
      if (t.amount > 0) return sum += t.amount;
      return sum;
    }, 0);

    // total expenses
    var totalOut = list.reduce(function(sum, t) {
      if (t.amount < 0) return sum += t.amount;
      return sum;
    }, 0);

    res.render('index', {
      transactions: sorted,
      totals: {
        all: total,
        income: totalIn,
        expenses: totalOut
      },
      category: category || '',
      date: date.format('MMMM YYYY')
    });
  });
};

module.exports = {
  get: get,
  post: post,
  put: put,
  remove: remove,
  categories: categories,
  render: render
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var glob = require('glob');
var dox = require('dox');
var each = require('lodash/collection/each');
var processFile = require('./processFile');

function collectNodes(config) {

  // collect all js files
  var jsFiles = [];
  var folders = config.folders || [];

  var patterns = [];
  each(folders, function(folder) {
    patterns.push(folder + "/**/*.js")
  })

  // EXPERIMENTAL
  // patterns = ["util/oo.js"];

  each(patterns, function(pattern) {
    jsFiles = jsFiles.concat(glob.sync(pattern));
  });
  // console.log(jsFiles);

  // run dox on every js file
  var files = {};
  each(jsFiles, function(jsFile) {
    var js = fs.readFileSync(jsFile, 'utf8');
    var folder = path.dirname(jsFile);
    var name = path.basename(jsFile, '.js');
    var id = jsFile.slice(0,-3);
    files[id] = {
      id: id,
      folder: folder,
      name: name,
      dox: dox.parseComments(js)
    };
  });
  // console.log('Doxified:', doxified);

  // expand and aggregate
  // Methods and properties and added to their container
  // Each file is classified either as Class, Object, or Function depending on export tags.
  // If no export tags are found, the one entity is assumed as default export which has the same name as the file
  var nodes = [];
  each(files, function(file) {
    nodes = nodes.concat(processFile(file));
  });

  // TODO: add namespace nodes derived from found nodes.

  return nodes;
}

module.exports = collectNodes;
<commit_msg>Added workaround for jsdoctypeparser problem.<commit_after>var fs = require('fs');
var path = require('path');
var glob = require('glob');
var dox = require('dox');
var each = require('lodash/collection/each');
var processFile = require('./processFile');

// HACK: overriding the type parser entry point
// to workaround a syntax error thrown by jsdoctypeparser for
// when using paths in type strings `{model/Document}` without `module:` prefix.
var _parseTagTypes = dox.parseTagTypes;
dox.parseTagTypes = function(str, tag) {
  if (/\{\w+(\/\w+)\}/.exec(str)) {
    str = str.replace('/', '_SEP_');
    var types = _parseTagTypes(str, tag);
    for (var i = 0; i < types.length; i++) {
      types[i] = types[i].replace('_SEP_', '/');
    }
  } else {
    return _parseTagTypes(str, tag);
  }
};

function collectNodes(config) {

  // collect all js files
  var jsFiles = [];
  var folders = config.folders || [];

  var patterns = [];
  each(folders, function(folder) {
    patterns.push(folder + "/**/*.js")
  })

  // EXPERIMENTAL
  // patterns = ["util/oo.js"];

  each(patterns, function(pattern) {
    jsFiles = jsFiles.concat(glob.sync(pattern));
  });
  // console.log(jsFiles);

  // run dox on every js file
  var files = {};
  each(jsFiles, function(jsFile) {
    var js = fs.readFileSync(jsFile, 'utf8');
    var folder = path.dirname(jsFile);
    var name = path.basename(jsFile, '.js');
    var id = jsFile.slice(0,-3);
    files[id] = {
      id: id,
      folder: folder,
      name: name,
      dox: dox.parseComments(js)
    };
  });
  // console.log('Doxified:', doxified);

  // expand and aggregate
  // Methods and properties and added to their container
  // Each file is classified either as Class, Object, or Function depending on export tags.
  // If no export tags are found, the one entity is assumed as default export which has the same name as the file
  var nodes = [];
  each(files, function(file) {
    nodes = nodes.concat(processFile(file));
  });

  // TODO: add namespace nodes derived from found nodes.

  return nodes;
}

module.exports = collectNodes;
<|endoftext|>


<commit_before>/**
 * controller that gets instantiated for all editable components
 * @class
 */

function ComponentEdit() {
  var dom = require('../services/dom'),
    events = require('../services/events'),
    references = require('../services/references'),
    decorate = require('../services/decorators'),
    editableAttr = references.editableAttribute,
    placeholderAttr = references.placeholderAttribute;

  /**
   * get a path to decorate
   * @param {Element} el
   * @returns {string|undefined}
   */
  function getDecoratorPath(el) {
    return el && (el.getAttribute(editableAttr) || el.getAttribute(placeholderAttr));
  }

  /**
   * recursively decorate nodes with click events, placeholders, and other decorators
   * @param {Element} node
   * @param {TreeWalker} walker
   * @param {string} ref
   * @param {array} promises    hold onto promises so that they can be returned.
   */
  function decorateNodes(node, walker, ref, promises) {
    var path = getDecoratorPath(node); // only assign a path if node exists

    if (path) {
      // this element is editable, decorate it!
      promises.push(decorate(node, ref, path));
    }

    if (node) {
      // keep walking through the nodes
      decorateNodes(walker.nextNode(), walker, ref, promises);
    }
  }

  /**
   * find out if component is editable or contains editable children
   * @param  {Element}  el component element
   * @return {Boolean}
   */
  function isComponentEditable(el) {
    return el.hasAttribute(editableAttr) ||
      el.hasAttribute(placeholderAttr) ||
      !!dom.find(el, '[' + editableAttr + ']') ||
      !!dom.find(el, '[' + placeholderAttr + ']');
  }

  /**
   * @constructs
   * @param {Element} el
   * @returns {Promise}
   */
  function constructor(el) {
    var ref = el.getAttribute(references.referenceAttribute),
      componentHasPath = ref && !!getDecoratorPath(el),
      walker, path, promises = [];

    if (isComponentEditable(el)) {
      walker = document.createTreeWalker(el, NodeFilter.SHOW_ELEMENT, {
        acceptNode: function (currentNode) {
          if (!currentNode.hasAttribute(references.referenceAttribute)) {
            return NodeFilter.FILTER_ACCEPT;
          } else {
            return NodeFilter.FILTER_REJECT;
          }
        }
      });

      // add click events to children with [name], but NOT children inside child components
      decorateNodes(walker.nextNode(), walker, ref, promises);

      // special case when editable path is in the component's root element.
      if (componentHasPath) {
        path = getDecoratorPath(el);
        promises.push(decorate(el, ref, path));
      }
    }

    events.add(el, {
      'a click': 'killLinks'
    }, this);

    return Promise.all(promises);
  }

  constructor.prototype = {

    killLinks: function (e) {
      // prevent all links in this component from being clicked
      // allows us to attach click handlers to open things like tags, author, sources (lists of links)
      // users can still right-click + open in new tab on links they want to actually go to
      if (e) {
        e.preventDefault();
        e.stopPropagation();
      }
    }
  };
  return constructor;
}

module.exports = ComponentEdit;
<commit_msg>don't stop propegation on killLinks<commit_after>/**
 * controller that gets instantiated for all editable components
 * @class
 */

function ComponentEdit() {
  var dom = require('../services/dom'),
    events = require('../services/events'),
    references = require('../services/references'),
    decorate = require('../services/decorators'),
    editableAttr = references.editableAttribute,
    placeholderAttr = references.placeholderAttribute;

  /**
   * get a path to decorate
   * @param {Element} el
   * @returns {string|undefined}
   */
  function getDecoratorPath(el) {
    return el && (el.getAttribute(editableAttr) || el.getAttribute(placeholderAttr));
  }

  /**
   * recursively decorate nodes with click events, placeholders, and other decorators
   * @param {Element} node
   * @param {TreeWalker} walker
   * @param {string} ref
   * @param {array} promises    hold onto promises so that they can be returned.
   */
  function decorateNodes(node, walker, ref, promises) {
    var path = getDecoratorPath(node); // only assign a path if node exists

    if (path) {
      // this element is editable, decorate it!
      promises.push(decorate(node, ref, path));
    }

    if (node) {
      // keep walking through the nodes
      decorateNodes(walker.nextNode(), walker, ref, promises);
    }
  }

  /**
   * find out if component is editable or contains editable children
   * @param  {Element}  el component element
   * @return {Boolean}
   */
  function isComponentEditable(el) {
    return el.hasAttribute(editableAttr) ||
      el.hasAttribute(placeholderAttr) ||
      !!dom.find(el, '[' + editableAttr + ']') ||
      !!dom.find(el, '[' + placeholderAttr + ']');
  }

  /**
   * @constructs
   * @param {Element} el
   * @returns {Promise}
   */
  function constructor(el) {
    var ref = el.getAttribute(references.referenceAttribute),
      componentHasPath = ref && !!getDecoratorPath(el),
      walker, path, promises = [];

    if (isComponentEditable(el)) {
      walker = document.createTreeWalker(el, NodeFilter.SHOW_ELEMENT, {
        acceptNode: function (currentNode) {
          if (!currentNode.hasAttribute(references.referenceAttribute)) {
            return NodeFilter.FILTER_ACCEPT;
          } else {
            return NodeFilter.FILTER_REJECT;
          }
        }
      });

      // add click events to children with [name], but NOT children inside child components
      decorateNodes(walker.nextNode(), walker, ref, promises);

      // special case when editable path is in the component's root element.
      if (componentHasPath) {
        path = getDecoratorPath(el);
        promises.push(decorate(el, ref, path));
      }
    }

    events.add(el, {
      'a click': 'killLinks'
    }, this);

    return Promise.all(promises);
  }

  constructor.prototype = {

    killLinks: function (e) {
      // prevent all links in this component from being clicked
      // allows us to attach click handlers to open things like tags, author, sources (lists of links)
      // users can still right-click + open in new tab on links they want to actually go to
      if (e) {
        e.preventDefault();
      }
    }
  };
  return constructor;
}

module.exports = ComponentEdit;
<|endoftext|>


<commit_before><commit_msg>Change MongoDB provider to MongoLab<commit_after><|endoftext|>


<commit_before>var moment = require('moment-timezone')
var sherlock = require('./other_modules/sherlock/sherlock')

function createDateFromText (inputText) {
  var convertedToUTC = moment.tz(inputText, 'America/Chicago').tz('UTC')
  var utcDate = new Date(convertedToUTC.format())
  console.log('Converted to ' + utcDate)
  return utcDate
}

function processDateAndTitleFromText (inputText, callback) {
  var now = new Date()
  var nowLocal = moment.tz(now, 'America/Chicago')
  var nowLocalString = nowLocal.format()
  var nowLocalTrimmed = nowLocalString.substring(0, nowLocalString.length - 6)
  var nowLocalDate = new Date(nowLocalTrimmed)
  console.log('NOW:' + now + ' nowLocal:' + nowLocal.format() + ' nowLocalDate:' + nowLocalDate)
  sherlock._setNow(nowLocalDate)
  var sherlocked = sherlock.parse(inputText)
  var startDateString = '' + sherlocked.startDate
  var startDateReported = startDateString.substring(0, startDateString.length - 15)
  var startDateTrimmed =  startDateReported + ' GMT-06:00 (UTC)'
  var startDateLocal = moment(startDateTrimmed)
  var startDateGMT = new Date(startDateLocal)
  console.log('startDateTrimmed:' + startDateTrimmed + ' startDateLocal:' + startDateLocal.format() + ' startDateGMT:' + startDateGMT)
  if (sherlocked.startDate == null) {
    callback("Couldn't work out that time sorry. 😕", null, null)
  }
  callback(null, startDateGMT, startDateReported + sherlocked.eventTitle)
}

module.exports = {
  createDateFromText,
  processDateAndTitleFromText
}
<commit_msg>scheduler<commit_after>var moment = require('moment-timezone')
var sherlock = require('./other_modules/sherlock/sherlock')

function createDateFromText (inputText) {
  var convertedToUTC = moment.tz(inputText, 'America/Chicago').tz('UTC')
  var utcDate = new Date(convertedToUTC.format())
  console.log('Converted to ' + utcDate)
  return utcDate
}

function processDateAndTitleFromText (inputText, callback) {
  var now = new Date()
  var nowLocal = moment.tz(now, 'America/Chicago')
  var nowLocalString = nowLocal.format()
  var nowLocalTrimmed = nowLocalString.substring(0, nowLocalString.length - 6)
  var nowLocalDate = new Date(nowLocalTrimmed)
  console.log('NOW:' + now + ' nowLocal:' + nowLocal.format() + ' nowLocalDate:' + nowLocalDate)
  sherlock._setNow(nowLocalDate)
  var sherlocked = sherlock.parse(inputText)
  var startDateString = '' + sherlocked.startDate
  var startDateReported = startDateString.substring(0, startDateString.length - 15)
  var startDateTrimmed =  startDateReported + ' GMT-06:00 (UTC)'
  var startDateLocal = moment(startDateTrimmed)
  var startDateGMT = new Date(startDateLocal)
  console.log('startDateTrimmed:' + startDateTrimmed + ' startDateLocal:' + startDateLocal.format() + ' startDateGMT:' + startDateGMT)
  if (sherlocked.startDate == null) {
    callback("Couldn't work out that time sorry. 😕", null, null)
  }
  callback(null, startDateGMT, startDateReported + ' ' + sherlocked.eventTitle)
}

module.exports = {
  createDateFromText,
  processDateAndTitleFromText
}
<|endoftext|>


<commit_before>// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
import React from 'react';
import SelectField from 'material-ui/lib/select-field';
import MenuItem from 'material-ui/lib/menus/menu-item';
import RaisedButton from 'material-ui/lib/raised-button';
import LoadingGif from '../../../LoadingGif';
import * as RecordActions from '../../../../actions/record';
import * as Colors from 'material-ui/lib/styles/colors';

import { connect } from 'react-redux';

class NewRecordLabelSelect extends React.Component {

  constructor(props) {
    super(props);
    this.handleRecordLabelSelect = this.handleRecordLabelSelect.bind(this);
    this.handleNewRecordClick = this.handleNewRecordClick.bind(this);
    this.handleCloseClick = this.handleCloseClick.bind(this);
  }

  handleRecordLabelSelect(e, index, value) {
    const { dispatch } = this.props;
    dispatch(RecordActions.setSelectedLabel(value));
  }

  handleNewRecordClick() {
    const { dispatch } = this.props;
    if (this.props.selectedLabel === null) {
      dispatch(RecordActions.setRecordError('Please select a record label.'));
      return;
    }
    dispatch(RecordActions.createRecordRequest());
    const url = `/dataentry/protocoldatasource/${this.props.pds.id}/subject/` +
      `${this.props.subject.id}/create/?label_id=${this.props.selectedLabel}`;
    window.location.href = url;
  }

  handleCloseClick() {
    const { dispatch } = this.props;
    dispatch(RecordActions.setAddRecordMode(false));
  }

  render() {
    const labels = this.props.pds.driver_configuration.labels;
    const modalStyle = {
      left: '45%',
      top: '20%',
      marginLeft: '-5em',
      marginBottom: '3em',
      position: 'fixed',
      zIndex: '1000',
    };
    const cardStyle = {
      padding: '15px',
      boxShadow: '3px 3px 14px rgba(204, 197, 185, 0.5)',
      backgroundColor: 'white',
    };
    const backdropStyle = {
      position: 'fixed',
      top: '0px',
      left: '0px',
      width: '100%',
      height: '100%',
      zIndex: 99,
      display: 'block',
      backgroundColor: 'rgba(0, 0, 0, 0.298039)',
    };
    return (
      this.props.isCreating && this.props.pds.id == this.props.activePDS.id ?

                Please wait. This action may take several seconds...

              <LoadingGif />

 :
          this.props.addRecordMode && this.props.pds.id == this.props.activePDS.id ?

Select label for {this.props.pds.display_label} Record

                    <SelectField
                      onChange={this.handleRecordLabelSelect}
                      style={{ width: '100%' }}
                      value={this.props.selectedLabel}
                    >
                      {labels.map((label, i) => (
                        <MenuItem key={i} value={label[0]} primaryText={label[1]} />
                      ))}
                    </SelectField>

                  <RaisedButton
                    onMouseUp={this.handleNewRecordClick}
                    label={'Create New'}
                    labelColor={'#7AC29A'}
                    type="submit"
                    style={{ width: '100%' }}
                  />
                  <RaisedButton
                    style={{ width: '100%' }}
                    labelColor={Colors.red400}
                    label="Cancel"
                    onMouseUp={this.handleCloseClick}
                  />
                  {this.props.newRecordError != null ?

{this.props.newRecordError}

                  : null}

          : null

    );
  }
}

NewRecordLabelSelect.propTypes = {
  dispatch: React.PropTypes.func,
  subject: React.PropTypes.object,
  selectedLabel: React.PropTypes.number,
  pds: React.PropTypes.object,
  isCreating: React.PropTypes.bool,
  newRecordError: React.PropTypes.string,
};

function mapStateToProps(state) {
  return {
    activePDS: state.pds.activePDS,
    subject: state.subject.activeSubject,
    selectedLabel: state.record.selectedLabel,
    isCreating: state.record.isCreating,
    newRecordError: state.record.newRecordError,
    addRecordMode: state.record.addRecordMode,
  };
}

export default connect(mapStateToProps)(NewRecordLabelSelect);
<commit_msg>adding 'select label' to the add a new record form to make it clear that user needs to select a label<commit_after>// jscs:disable requireCamelCaseOrUpperCaseIdentifiers
import React from 'react';
import SelectField from 'material-ui/lib/select-field';
import MenuItem from 'material-ui/lib/menus/menu-item';
import RaisedButton from 'material-ui/lib/raised-button';
import LoadingGif from '../../../LoadingGif';
import * as RecordActions from '../../../../actions/record';
import * as Colors from 'material-ui/lib/styles/colors';

import { connect } from 'react-redux';

class NewRecordLabelSelect extends React.Component {

  constructor(props) {
    super(props);
    this.handleRecordLabelSelect = this.handleRecordLabelSelect.bind(this);
    this.handleNewRecordClick = this.handleNewRecordClick.bind(this);
    this.handleCloseClick = this.handleCloseClick.bind(this);
  }

  handleRecordLabelSelect(e, index, value) {
    const { dispatch } = this.props;
    dispatch(RecordActions.setSelectedLabel(value));
  }

  handleNewRecordClick() {
    const { dispatch } = this.props;
    if (this.props.selectedLabel === null) {
      dispatch(RecordActions.setRecordError('Please select a record label.'));
      return;
    }
    dispatch(RecordActions.createRecordRequest());
    const url = `/dataentry/protocoldatasource/${this.props.pds.id}/subject/` +
      `${this.props.subject.id}/create/?label_id=${this.props.selectedLabel}`;
    window.location.href = url;
  }

  handleCloseClick() {
    const { dispatch } = this.props;
    dispatch(RecordActions.setAddRecordMode(false));
  }

  render() {
    const labels = this.props.pds.driver_configuration.labels;
    const modalStyle = {
      left: '45%',
      top: '20%',
      marginLeft: '-5em',
      marginBottom: '3em',
      position: 'fixed',
      zIndex: '1000',
    };
    const cardStyle = {
      padding: '15px',
      boxShadow: '3px 3px 14px rgba(204, 197, 185, 0.5)',
      backgroundColor: 'white',
    };
    const backdropStyle = {
      position: 'fixed',
      top: '0px',
      left: '0px',
      width: '100%',
      height: '100%',
      zIndex: 99,
      display: 'block',
      backgroundColor: 'rgba(0, 0, 0, 0.298039)',
    };
    return (
      this.props.isCreating && this.props.pds.id == this.props.activePDS.id ?

                Please wait. This action may take several seconds...

              <LoadingGif />

 :
          this.props.addRecordMode && this.props.pds.id == this.props.activePDS.id ?

Select label for {this.props.pds.display_label} Record

                    <SelectField
                      onChange={this.handleRecordLabelSelect}
                      style={{ width: '100%' }}
                      value={this.props.selectedLabel}
                      floatingLabelText={'Select Label'}
                    >
                      {labels.map((label, i) => (
                        <MenuItem key={i} value={label[0]} primaryText={label[1]} />
                      ))}
                    </SelectField>

                  <RaisedButton
                    onMouseUp={this.handleNewRecordClick}
                    label={'Create New'}
                    labelColor={'#7AC29A'}
                    type="submit"
                    style={{ width: '100%' }}
                  />
                  <RaisedButton
                    style={{ width: '100%' }}
                    labelColor={Colors.red400}
                    label="Cancel"
                    onMouseUp={this.handleCloseClick}
                  />
                  {this.props.newRecordError != null ?

{this.props.newRecordError}

                  : null}

          : null

    );
  }
}

NewRecordLabelSelect.propTypes = {
  dispatch: React.PropTypes.func,
  subject: React.PropTypes.object,
  selectedLabel: React.PropTypes.number,
  pds: React.PropTypes.object,
  isCreating: React.PropTypes.bool,
  newRecordError: React.PropTypes.string,
};

function mapStateToProps(state) {
  return {
    activePDS: state.pds.activePDS,
    subject: state.subject.activeSubject,
    selectedLabel: state.record.selectedLabel,
    isCreating: state.record.isCreating,
    newRecordError: state.record.newRecordError,
    addRecordMode: state.record.addRecordMode,
  };
}

export default connect(mapStateToProps)(NewRecordLabelSelect);
<|endoftext|>


<commit_before>(function(HTML) {
  /*
    ======== A Handy Little QUnit Reference ========
    http://api.qunitjs.com/

    Test methods:
      module(name, {[setup][ ,teardown]})
      test(name, callback)
      expect(numberOfAssertions)
      stop(increment)
      start(decrement)
    Test assertions:
      ok(value, [message])
      equal(actual, expected, [message])
      notEqual(actual, expected, [message])
      deepEqual(actual, expected, [message])
      notDeepEqual(actual, expected, [message])
      strictEqual(actual, expected, [message])
      notStrictEqual(actual, expected, [message])
      throws(block, [expected], [message])
  */

	module("HTML element creation");

	test("basic", function() {
		ok(!HTML.body.a, "no A to begin with");
		equal(HTML.body.add('a').tagName, "A", "Tag created.");
		ok(HTML.body.a, 'Tag found.');
		HTML.body.a.remove();
	});

	test("add node", function() {
		var node = document.createElement('article');
		equal(HTML.body.add(node), node, "added node and got it back");
		ok(HTML.body.article && 'each' in node, 'added node has been assimilated');
		node.remove();
	});

	test("add list", function() {
		var list = ['nav', document.createElement('nav'), ['nav']];
		equal(HTML.body.add(list).length, 3, 'added three nav elements');
		HTML.find('nav').remove();
	});

  //TODO: test add(el, ref);

  module("HTML element removal");

  test("single", 4, function() {
    var el = HTML.body.add('doomed');
    ok(el, 'have element');
    equal(el.remove(), el, 'remove returns self');
    ok(!el.parentNode, 'no parent after removal');
    ok(!HTML.body.doomed.length, 'child property is empty array');
  });

  test("list", 8, function() {
    var list = HTML.body.add('doa*5');
    ok(list && list.forEach, 'have array');
    strictEqual(list.remove(), list, 'remove returns self');
    list.each(function(doa) {
      ok(!doa.parentNode, 'no parents after removal');
    });
    ok(!HTML.body.doa.length, 'child property is empty array');
  });

  test("keep active chain", function() {
    var el = HTML.body.add('doomed');
    ok(el, 'have element');
    equal(el.remove(true), HTML.body, 'remove(true) returns parent');
  });

  test("keep chain for list", function() {
    var list = HTML.body.add('doa*5');
    ok(list && list.forEach, 'have array');
    strictEqual(list.remove(true), HTML.body, 'remove returns parent(s)');
  });

}(HTML));
<commit_msg>gave up on chainable remove<commit_after>(function(HTML) {
  /*
    ======== A Handy Little QUnit Reference ========
    http://api.qunitjs.com/

    Test methods:
      module(name, {[setup][ ,teardown]})
      test(name, callback)
      expect(numberOfAssertions)
      stop(increment)
      start(decrement)
    Test assertions:
      ok(value, [message])
      equal(actual, expected, [message])
      notEqual(actual, expected, [message])
      deepEqual(actual, expected, [message])
      notDeepEqual(actual, expected, [message])
      strictEqual(actual, expected, [message])
      notStrictEqual(actual, expected, [message])
      throws(block, [expected], [message])
  */

	module("HTML element creation");

	test("basic", function() {
		ok(!HTML.body.a, "no A to begin with");
		equal(HTML.body.add('a').tagName, "A", "Tag created.");
		ok(HTML.body.a, 'Tag found.');
		HTML.body.a.remove();
	});

	test("add node", function() {
		var node = document.createElement('article');
		equal(HTML.body.add(node), node, "added node and got it back");
		ok(HTML.body.article && 'each' in node, 'added node has been assimilated');
		node.remove();
	});

	test("add list", function() {
		var list = ['nav', document.createElement('nav'), ['nav']];
		equal(HTML.body.add(list).length, 3, 'added three nav elements');
		HTML.find('nav').remove();
	});

  //TODO: test add(el, ref);

  module("HTML element removal");

  test("single", 4, function() {
    var el = HTML.body.add('doomed');
    ok(el, 'have element');
    equal(el.remove(), el, 'remove returns self');
    ok(!el.parentNode, 'no parent after removal');
    ok(!HTML.body.doomed.length, 'child property is empty array');
  });

  test("list", 8, function() {
    var list = HTML.body.add('doa*5');
    ok(list && list.forEach, 'have array');
    strictEqual(list.remove(), list, 'remove returns self');
    list.each(function(doa) {
      ok(!doa.parentNode, 'no parents after removal');
    });
    ok(!HTML.body.doa.length, 'child property is empty array');
  });

}(HTML));
<|endoftext|>


<commit_before>/**
 * Backbone-Nested 1.1.2 - An extension of Backbone.js that keeps track of nested attributes
 *
 * http://afeld.github.com/backbone-nested/
 *
 * Copyright (c) 2011-2012 Aidan Feldman
 * MIT Licensed (LICENSE)
 */
/*global $, _, Backbone */
(function(){
  'use strict';

  var _delayedTriggers = [];

  Backbone.NestedModel = Backbone.Model.extend({

    get: function(attrStrOrPath){
      var attrPath = Backbone.NestedModel.attrPath(attrStrOrPath),
        result;

      Backbone.NestedModel.walkPath(this.attributes, attrPath, function(val, path){
        var attr = _.last(path);
        if (path.length === attrPath.length){
          // attribute found
          result = val[attr];
        }
      });

      return result;
    },

    has: function(attr){
      // for some reason this is not how Backbone.Model is implemented - it accesses the attributes object directly
      var result = this.get(attr);
      return !(result === null || _.isUndefined(result));
    },

    set: function(key, value, opts){
      var newAttrs = Backbone.NestedModel.deepClone(this.attributes),
        chgs = {},
        attrPath;

      if (_.isString(key)){
        // Backbone 0.9.0+ syntax: `model.set(key, val)` - convert the key to an attribute path
        attrPath = Backbone.NestedModel.attrPath(key);
      } else if (_.isArray(key)){
        // attribute path
        attrPath = key;
      }

      if (attrPath){
        opts = opts || {};
        this._setAttr(newAttrs, attrPath, value, chgs, opts);
      } else { // it's an Object
        opts = value || {};
        var attrs = key;
        for (var attrStr in attrs){
          if (attrs.hasOwnProperty(attrStr)){
            attrPath = Backbone.NestedModel.attrPath(attrStr);
            this._setAttr(newAttrs, attrPath, attrs[attrStr], chgs, opts);
          }
        }
      }

      if (!this._validate(newAttrs, opts)) return false;

      for (var changedAttr in chgs) {
        this._delayedTrigger('change:' + changedAttr, this, chgs[changedAttr]);
        this.changed[changedAttr] = chgs[changedAttr];
      }

      var setReturn;
      if (opts.unset && attrPath.length === 1){ // assume it is a singular attribute being unset
        // unsetting top-level attribute
        var unsetObj = {};
        unsetObj[key] = null;
        setReturn = Backbone.NestedModel.__super__.set.call(this, unsetObj, opts);
      } else {
        // normal set(), or an unset of nested attribute
        if (opts.unset){
          // make sure Backbone.Model won't unset the top-level attribute
          opts = _.extend({}, opts);
          delete opts.unset;
        }

        setReturn = Backbone.NestedModel.__super__.set.call(this, newAttrs, opts);
      }

      this._runDelayedTriggers();
      return setReturn;
    },

    unset: function(attrStr, opts){
      opts = _.extend({}, opts, {unset: true});
      this.set(attrStr, null, opts);

      return this;
    },

    add: function(attrStr, value, opts){
      var current = this.get(attrStr);
      if (!_.isArray(current)) throw new Error('current value is not an array');
      return this.set(attrStr + '[' + current.length + ']', value, opts);
    },

    remove: function(attrStr, opts){
      opts = opts || {};

      var attrPath = Backbone.NestedModel.attrPath(attrStr),
        aryPath = _.initial(attrPath),
        val = this.get(aryPath),
        i = _.last(attrPath);

      if (!_.isArray(val)){
        throw new Error("remove() must be called on a nested array");
      }

      // only trigger if an element is actually being removed
      var trigger = !opts.silent && (val.length >= i + 1),
        oldEl = val[i];

      // remove the element from the array
      val.splice(i, 1);
      opts.silent = true; // Triggers should only be fired in trigger section below
      this.set(aryPath, val, opts);

      if (trigger){
        attrStr = Backbone.NestedModel.createAttrStr(aryPath);
        this.trigger('remove:' + attrStr, this, oldEl);
        for (var aryCount = aryPath.length; aryCount >= 1; aryCount--) {
          attrStr = Backbone.NestedModel.createAttrStr(_.first(aryPath, aryCount));
          this.trigger('change:' + attrStr, this, oldEl);
        }
        this.trigger('change', this, oldEl);
      }

      return this;
    },

    toJSON: function(){
      return Backbone.NestedModel.deepClone(this.attributes);
    },

    // private
    _delayedTrigger: function(/* the trigger args */){
      _delayedTriggers.push(arguments);
    },

    _runDelayedTriggers: function(){
      while (_delayedTriggers.length > 0){
        this.trigger.apply(this, _delayedTriggers.shift());
      }
    },

    // note: modifies `newAttrs`
    _setAttr: function(newAttrs, attrPath, value, chgs, opts){
      opts = opts || {};

      var fullPathLength = attrPath.length;
      var model = this;

      Backbone.NestedModel.walkPath(newAttrs, attrPath, function(val, path){
        var attr = _.last(path);
        var attrStr = Backbone.NestedModel.createAttrStr(path);

        // See if this is a new value being set
        var isNewValue = !_.isEqual(val[attr], value);

        if (path.length === fullPathLength){
          // reached the attribute to be set

          if (opts.unset){
            // unset the value
            delete val[attr];
            delete model._escapedAttributes[attrStr];
          } else {
            // Set the new value
            val[attr] = value;
          }

          // Trigger Change Event if new values are being set
          if (_.isObject(value) && isNewValue){
            for (var a in value){
              if (value.hasOwnProperty(a)){
                model._delayedTrigger('change:' + attrStr + '.' + a, model, val[attr]);
                model.changed[attrStr] = value;
              }
            }
          }

          // Trigger Remove Event if array being set to null
          if (value === null){
            var parentPath = Backbone.NestedModel.createAttrStr(_.initial(attrPath));
            model._delayedTrigger('remove:' + parentPath, model, val[attr]);
          }

        } else if (!val[attr]){
          if (_.isNumber(attr)){
            val[attr] = [];
          } else {
            val[attr] = {};
          }
        }

        if (!opts.silent){
          // let the superclass handle change events for top-level attributes
          if (path.length > 1 && isNewValue){
            chgs[attrStr] = val[attr];
          }

          if (_.isArray(val[attr])){
            model._delayedTrigger('add:' + attrStr, model, val[attr]);
          }
        }
      });
    }

  }, {
    // class methods

    attrPath: function(attrStrOrPath){
      var path;

      if (_.isString(attrStrOrPath)){
        // TODO this parsing can probably be more efficient
        path = (attrStrOrPath === '') ? [''] : attrStrOrPath.match(/[^\.\[\]]+/g);
        path = _.map(path, function(val){
          // convert array accessors to numbers
          return val.match(/^\d+$/) ? parseInt(val, 10) : val;
        });
      } else {
        path = attrStrOrPath;
      }

      return path;
    },

    createAttrStr: function(attrPath){
      var attrStr = attrPath[0];
      _.each(_.rest(attrPath), function(attr){
        attrStr += _.isNumber(attr) ? ('[' + attr + ']') : ('.' + attr);
      });

      return attrStr;
    },

    deepClone: function(obj){
      return $.extend(true, {}, obj);
    },

    walkPath: function(obj, attrPath, callback, scope){
      var val = obj,
        childAttr;

      // walk through the child attributes
      for (var i = 0; i < attrPath.length; i++){
        callback.call(scope || this, val, attrPath.slice(0, i + 1));

        childAttr = attrPath[i];
        val = val[childAttr];
        if (!val) break; // at the leaf
      }
    }

  });

})();
<commit_msg>simplify delay of change events<commit_after>/**
 * Backbone-Nested 1.1.2 - An extension of Backbone.js that keeps track of nested attributes
 *
 * http://afeld.github.com/backbone-nested/
 *
 * Copyright (c) 2011-2012 Aidan Feldman
 * MIT Licensed (LICENSE)
 */
/*global $, _, Backbone */
(function(){
  'use strict';

  var _delayedTriggers = [];

  Backbone.NestedModel = Backbone.Model.extend({

    get: function(attrStrOrPath){
      var attrPath = Backbone.NestedModel.attrPath(attrStrOrPath),
        result;

      Backbone.NestedModel.walkPath(this.attributes, attrPath, function(val, path){
        var attr = _.last(path);
        if (path.length === attrPath.length){
          // attribute found
          result = val[attr];
        }
      });

      return result;
    },

    has: function(attr){
      // for some reason this is not how Backbone.Model is implemented - it accesses the attributes object directly
      var result = this.get(attr);
      return !(result === null || _.isUndefined(result));
    },

    set: function(key, value, opts){
      var newAttrs = Backbone.NestedModel.deepClone(this.attributes),
        attrPath;

      if (_.isString(key)){
        // Backbone 0.9.0+ syntax: `model.set(key, val)` - convert the key to an attribute path
        attrPath = Backbone.NestedModel.attrPath(key);
      } else if (_.isArray(key)){
        // attribute path
        attrPath = key;
      }

      if (attrPath){
        opts = opts || {};
        this._setAttr(newAttrs, attrPath, value, opts);
      } else { // it's an Object
        opts = value || {};
        var attrs = key;
        for (var attrStr in attrs){
          if (attrs.hasOwnProperty(attrStr)){
            attrPath = Backbone.NestedModel.attrPath(attrStr);
            this._setAttr(newAttrs, attrPath, attrs[attrStr], opts);
          }
        }
      }

      if (!this._validate(newAttrs, opts)){
        // reset changed attributes
        this.changed = {};
        return false;
      }

      var setReturn;
      if (opts.unset && attrPath.length === 1){ // assume it is a singular attribute being unset
        // unsetting top-level attribute
        var unsetObj = {};
        unsetObj[key] = null;
        setReturn = Backbone.NestedModel.__super__.set.call(this, unsetObj, opts);
      } else {
        // normal set(), or an unset of nested attribute
        if (opts.unset){
          // make sure Backbone.Model won't unset the top-level attribute
          opts = _.extend({}, opts);
          delete opts.unset;
        }

        setReturn = Backbone.NestedModel.__super__.set.call(this, newAttrs, opts);
      }

      this._runDelayedTriggers();
      return setReturn;
    },

    unset: function(attrStr, opts){
      opts = _.extend({}, opts, {unset: true});
      this.set(attrStr, null, opts);

      return this;
    },

    add: function(attrStr, value, opts){
      var current = this.get(attrStr);
      if (!_.isArray(current)) throw new Error('current value is not an array');
      return this.set(attrStr + '[' + current.length + ']', value, opts);
    },

    remove: function(attrStr, opts){
      opts = opts || {};

      var attrPath = Backbone.NestedModel.attrPath(attrStr),
        aryPath = _.initial(attrPath),
        val = this.get(aryPath),
        i = _.last(attrPath);

      if (!_.isArray(val)){
        throw new Error("remove() must be called on a nested array");
      }

      // only trigger if an element is actually being removed
      var trigger = !opts.silent && (val.length >= i + 1),
        oldEl = val[i];

      // remove the element from the array
      val.splice(i, 1);
      opts.silent = true; // Triggers should only be fired in trigger section below
      this.set(aryPath, val, opts);

      if (trigger){
        attrStr = Backbone.NestedModel.createAttrStr(aryPath);
        this.trigger('remove:' + attrStr, this, oldEl);
        for (var aryCount = aryPath.length; aryCount >= 1; aryCount--) {
          attrStr = Backbone.NestedModel.createAttrStr(_.first(aryPath, aryCount));
          this.trigger('change:' + attrStr, this, oldEl);
        }
        this.trigger('change', this, oldEl);
      }

      return this;
    },

    toJSON: function(){
      return Backbone.NestedModel.deepClone(this.attributes);
    },

    // private
    _delayedTrigger: function(/* the trigger args */){
      _delayedTriggers.push(arguments);
    },

    _delayedChange: function(attrStr, newVal){
      this._delayedTrigger('change:' + attrStr, this, newVal);
      this.changed[attrStr] = newVal;
    },

    _runDelayedTriggers: function(){
      while (_delayedTriggers.length > 0){
        this.trigger.apply(this, _delayedTriggers.shift());
      }
    },

    // note: modifies `newAttrs`
    _setAttr: function(newAttrs, attrPath, value, opts){
      opts = opts || {};

      var fullPathLength = attrPath.length;
      var model = this;

      Backbone.NestedModel.walkPath(newAttrs, attrPath, function(val, path){
        var attr = _.last(path);
        var attrStr = Backbone.NestedModel.createAttrStr(path);

        // See if this is a new value being set
        var isNewValue = !_.isEqual(val[attr], value);

        if (path.length === fullPathLength){
          // reached the attribute to be set

          if (opts.unset){
            // unset the value
            delete val[attr];
            delete model._escapedAttributes[attrStr];
          } else {
            // Set the new value
            val[attr] = value;
          }

          // Trigger Change Event if new values are being set
          if (_.isObject(value) && isNewValue){
            for (var a in value){
              if (value.hasOwnProperty(a)){
                model._delayedChange(attrStr + '.' + a, val[attr]);
              }
            }
          }

          // Trigger Remove Event if array being set to null
          if (value === null){
            var parentPath = Backbone.NestedModel.createAttrStr(_.initial(attrPath));
            model._delayedTrigger('remove:' + parentPath, model, val[attr]);
          }

        } else if (!val[attr]){
          if (_.isNumber(attr)){
            val[attr] = [];
          } else {
            val[attr] = {};
          }
        }

        if (!opts.silent){
          // let the superclass handle change events for top-level attributes
          if (path.length > 1 && isNewValue){
            model._delayedChange(attrStr, val[attr]);
          }

          if (_.isArray(val[attr])){
            model._delayedTrigger('add:' + attrStr, model, val[attr]);
          }
        }
      });
    }

  }, {
    // class methods

    attrPath: function(attrStrOrPath){
      var path;

      if (_.isString(attrStrOrPath)){
        // TODO this parsing can probably be more efficient
        path = (attrStrOrPath === '') ? [''] : attrStrOrPath.match(/[^\.\[\]]+/g);
        path = _.map(path, function(val){
          // convert array accessors to numbers
          return val.match(/^\d+$/) ? parseInt(val, 10) : val;
        });
      } else {
        path = attrStrOrPath;
      }

      return path;
    },

    createAttrStr: function(attrPath){
      var attrStr = attrPath[0];
      _.each(_.rest(attrPath), function(attr){
        attrStr += _.isNumber(attr) ? ('[' + attr + ']') : ('.' + attr);
      });

      return attrStr;
    },

    deepClone: function(obj){
      return $.extend(true, {}, obj);
    },

    walkPath: function(obj, attrPath, callback, scope){
      var val = obj,
        childAttr;

      // walk through the child attributes
      for (var i = 0; i < attrPath.length; i++){
        callback.call(scope || this, val, attrPath.slice(0, i + 1));

        childAttr = attrPath[i];
        val = val[childAttr];
        if (!val) break; // at the leaf
      }
    }

  });

})();
<|endoftext|>


<commit_before>var Strategy   = require('passport-linkedin-oauth2').Strategy;

module.exports = function(Controller, AuthController, UserService, Exceptions, cleverAuthLinkedin, injector, passport, underscore) {
  var state    = +new Date() + ''
    , qs       = require('qs');

  return Controller.extend({
    route          : '[GET,POST] /auth/linkedIn/:action/?',
    restfulRouting : false,

    setup: function() {
      injector.instance('LinkedInStrategy', Strategy);
      passport.use(new Strategy(underscore.extend({state: state}, cleverAuthLinkedin.config), this.callback('linkedinLogin')));

      return this._super.apply(this, arguments);
    },

    linkedinLogin: function(accessToken, refreshToken, profile, done) {
      UserService.findOrCreate({
        linkedinId  : profile._json.id,
        email       : profile._json.emailAddress,
        lastName    : profile._json.lastName,
        firstName   : profile._json.firstName,
        // link        : profile._json.publicProfileUrl,
        // picture     : profile._json.pictureUrl || null,
        // locale      : !!profile._json.location && typeof profile._json.location === 'object' ? profile._json.location.name : null,
        // token       : accessToken || null
      })
      .then(done)
      .catch(function(error) {
        done(new Exceptions.AuthenticationError('Unable to authenticate linkedin user due to: ' + error));
      });
    }
  },
  {
    signInAction: function () {
      var params = {
        state           : state,
        scope           : cleverAuthLinkedin.config.scope,
        'client_id'     : cleverAuthLinkedin.config.AppKey,
        'redirect_uri'  : cleverAuthLinkedin.config.redirectURIs,
        'response_type' : 'code',
      };

      this.send({url: 'https://www.linkedin.com/uas/oauth2/authorization?' + qs.stringify(params)}, 200);
    },

    returnAction: function () {
      passport.authenticate('linkedin', this.proxy(AuthController.authenticate, null))(this.req, this.res, this.next);
    }
  });
};
<commit_msg>refactor(config): Reference config directly<commit_after>var Strategy   = require('passport-linkedin-oauth2').Strategy;

module.exports = function(Controller, AuthController, UserService, Exceptions, config, injector, passport, underscore) {
  var state    = +new Date() + ''
    , qs       = require('qs');

  return Controller.extend({
    route          : '[GET,POST] /auth/linkedIn/:action/?',
    restfulRouting : false,

    setup: function() {
      injector.instance('LinkedInStrategy', Strategy);
      passport.use(new Strategy(underscore.extend({state: state}, config['clever-auth-linkedin']), this.callback('linkedinLogin')));

      return this._super.apply(this, arguments);
    },

    linkedinLogin: function(accessToken, refreshToken, profile, done) {
      UserService.findOrCreate({
        linkedinId  : profile._json.id,
        email       : profile._json.emailAddress,
        lastName    : profile._json.lastName,
        firstName   : profile._json.firstName,
        // link        : profile._json.publicProfileUrl,
        // picture     : profile._json.pictureUrl || null,
        // locale      : !!profile._json.location && typeof profile._json.location === 'object' ? profile._json.location.name : null,
        // token       : accessToken || null
      })
      .then(done)
      .catch(function(error) {
        done(new Exceptions.AuthenticationError('Unable to authenticate linkedin user due to: ' + error));
      });
    }
  },
  {
    signInAction: function () {
      var params = {
        state           : state,
        scope           : config['clever-auth-linkedin'].scope,
        'client_id'     : config['clever-auth-linkedin'].AppKey,
        'redirect_uri'  : config['clever-auth-linkedin'].redirectURIs,
        'response_type' : 'code',
      };

      this.send({url: 'https://www.linkedin.com/uas/oauth2/authorization?' + qs.stringify(params)}, 200);
    },

    returnAction: function () {
      passport.authenticate('linkedin', this.proxy(AuthController.authenticate, null))(this.req, this.res, this.next);
    }
  });
};
<|endoftext|>


<commit_before>(function(tree) {

tree.Variable = function Variable(name, index, filename) {
    this.name = name;
    this.index = index;
    this.filename = filename;
};
tree.Variable.prototype = {
    eval: function(env) {
        var variable,
            v,
            that = this,
            name = this.name;

        if (this._css) return this._css;

        var thisframe = env.frames.filter(function(f) {
            return f.name == this.name;
        });
        if (thisframe.length) {
            return thisframe[0].value.eval(env);
        } else {
            env.error({
                message: 'variable ' + this.name + ' is undefined',
                index: this.index,
                type: 'runtime',
                filename: this.filename,
            });
            return {
                is: 'undefined',
                value: 'undefined'
            };
        }
    }
};

})(require('../tree'));
<commit_msg>Fixing variable interpretation with frames<commit_after>(function(tree) {

tree.Variable = function Variable(name, index, filename) {
    this.name = name;
    this.index = index;
    this.filename = filename;
};
tree.Variable.prototype = {
    eval: function(env) {
        var variable,
            v,
            that = this,
            name = this.name;

        if (this._css) return this._css;

        var thisframe = env.frames.filter(function(f) {
            return f.name == that.name;
        });
        if (thisframe.length) {
            return thisframe[0].value.eval(env);
        } else {
            env.error({
                message: 'variable ' + this.name + ' is undefined',
                index: this.index,
                type: 'runtime',
                filename: this.filename,
            });
            return {
                is: 'undefined',
                value: 'undefined'
            };
        }
    }
};

})(require('../tree'));
<|endoftext|>


<commit_before>'use strict';

/*
 * Defining the Package
 */
var Module = require('meanio').Module;

var Articles = new Module('articles');

/*
 * All MEAN packages require registration
 * Dependency injection is used to define required modules
 */
Articles.register(function(app, auth, database) {

  //We enable routing. By default the Package Object is passed to the routes
  Articles.routes(app, auth, database);

  //We are adding a link to the main menu for all authenticated users
  Articles.menus.add({
    title: 'Beer Maps',
    link: 'map',
    roles: [
      'anonymous',
      'authenticated'
    ]
  });
  Articles.menus.add({
    title: 'Beer News',
    link: 'latest feed',
    roles: [
      'anonymous',
      'authenticated'
    ]
  });
  /*
  Articles.menus.add({
    'roles': ['authenticated'],
    'title': 'Create New Article',
    'link': 'create article'
  });

  //Articles.aggregateAsset('js','/packages/system/public/services/menus.js', {group:'footer', absolute:true, weight:-9999});
  //Articles.aggregateAsset('js', 'test.js', {group: 'footer', weight: -1});

  /*
    //Uncomment to use. Requires meanio@0.3.7 or above
    // Save settings with callback
    // Use this for saving data from administration pages
    Articles.settings({'someSetting':'some value'},function (err, settings) {
      //you now have the settings object
    });

    // Another save settings example this time with no callback
    // This writes over the last settings.
    Articles.settings({'anotherSettings':'some value'});

    // Get settings. Retrieves latest saved settings
    Articles.settings(function (err, settings) {
      //you now have the settings object
    });
    */
  Articles.aggregateAsset('css', 'articles.css');
  //Articles.aggregateAsset('js', 'map.styles.js');

  return Articles;
});
<commit_msg>clean up top var declaration 2 lines<commit_after>'use strict';

/*
 * Defining the Package
 */
var Module = require('meanio').Module,
  Articles = new Module('articles');

/*
 * All MEAN packages require registration
 * Dependency injection is used to define required modules
 */
Articles.register(function(app, auth, database) {

  //We enable routing. By default the Package Object is passed to the routes
  Articles.routes(app, auth, database);

  //We are adding a link to the main menu for all authenticated users
  Articles.menus.add({
    title: 'Beer Maps',
    link: 'map',
    roles: [
      'anonymous',
      'authenticated'
    ]
  });
  Articles.menus.add({
    title: 'Beer News',
    link: 'latest feed',
    roles: [
      'anonymous',
      'authenticated'
    ]
  });
  /*
  Articles.menus.add({
    'roles': ['authenticated'],
    'title': 'Create New Article',
    'link': 'create article'
  });

  //Articles.aggregateAsset('js','/packages/system/public/services/menus.js', {group:'footer', absolute:true, weight:-9999});
  //Articles.aggregateAsset('js', 'test.js', {group: 'footer', weight: -1});

  /*
    //Uncomment to use. Requires meanio@0.3.7 or above
    // Save settings with callback
    // Use this for saving data from administration pages
    Articles.settings({'someSetting':'some value'},function (err, settings) {
      //you now have the settings object
    });

    // Another save settings example this time with no callback
    // This writes over the last settings.
    Articles.settings({'anotherSettings':'some value'});

    // Get settings. Retrieves latest saved settings
    Articles.settings(function (err, settings) {
      //you now have the settings object
    });
    */
  Articles.aggregateAsset('css', 'articles.css');
  //Articles.aggregateAsset('js', 'map.styles.js');

  return Articles;
});
<|endoftext|>


<commit_before>let models = require('../models')

module.exports = {
  usersWithRoles: function(req, res, next){
    let mongo = req.app.get('mongo')
    models.User.findAll()
    .then(users=>{
      let allUsers = []
      mongo.collection("users").find({}).toArray((err, userRoles)=>{
        for (var i in users) {
          let someone = {
            name: users[i].name,
            username: users[i].username,
            hasRole: false,
            roles: []
          }
          for (var j in userRoles) {
            if (userRoles[j].key == users[i].id) {
              someone.hasRole = true
              someone.roles.push(Object.keys(userRoles[j]).slice(2))
            }
          }
          allUsers.push(someone)
        }
        res.json({
          success: true,
          users: allUsers
        })
      })
    })
  },

  // Detail data user
  userDetail: function(req, res, next){
    models.User.find({
      where: {
        username: req.params.username
      }
    })
    .then(user=>{
      if (user) {
        // let acl = req.app.get('acl')
        res.json({
          success: true,
          user: {
            id: user.id,
            name: user.name,
            username: user.username,
            email: user.email,
            identityNumber: user.identityNumber,
          }
        })
      }
      else {
        res.json({
          success: false,
          message: "User " + req.params.username + " not found"
        })
      }
    })
  },

  // tambah role
  addRole: function(req, res, next){
    let acl = req.app.get('acl')
    if (req.body.rolename && req.body.permissions) {
      acl.whatResources(req.body.rolename.toUpperCase(), (err, resources)=>{
        console.log(resources);
        if (!Object.keys(resources).length) {
          console.log("yes, the role not exist yet");
          let newAcl = {
            roles: req.body.rolename.toUpperCase(),
          }
          try {
            newAcl.allows = JSON.parse(req.body.permissions)
          } catch (e) {
            res.json({
              success: false,
              message: "Invalid JSON for permissions"
            })
          }
          console.log(JSON.stringify(newAcl));
          acl.allow([newAcl], err=>{
            if (err) {
              res.json({
                success: false,
                message: err
              })
            }
            else {
              res.json({
                success: true,
                message: "berhasil menambahkan role",
                permissions: newAcl
              })
            }
          })
        }
        else {
          res.json({
            success: false,
            message: "role already exist"
          })
        }
      })

    }
    else {
      res.json({
        success: false,
        message: "missing parameter(s)"
      })
    }
  },

  // menghapus role dari ACL
  removeRole: function(req, res, next){
    let acl = req.app.get('acl')
    if (req.body.role) {
      acl.removeRole(req.body.role, err=>{

      })
    }
    else {
      res.json({
        success: false,
        message: "missing parameter(s)"
      })
    }
  },

  // assign role ke user
  addRoleToUser: function(req, res, next){
    let acl = req.app.get('acl')
    if (req.body.role && req.body.userId) {
      models.User.findById(req.body.userId).then(user=>{
        if (user) {
          acl.addUserRoles(req.body.userId, req.body.role, err=>{
            if (err) {
              res.json({
                success: false,
                errors: err
              })
            }
            else {
              res.json({
                success: true,
                message: "role successfully assigned to user",
                user: {
                  username: user.username,
                  name: user.name
                }
              })
            }
          })
        }
        else {
          res.json({
            success: false,
            message: "User not found",
          })
        }
      })

    }
    else {
      res.json({
        success: false,
        message: "missing parameter(s)",
      })
    }
  },

  // hapus role dari user
  removeRoleFromUser: function(req, res, next){
    let acl = req.app.get('acl')
    if (req.body.role && req. body.userId) {
      models.User.findById(req.body.userId).then(user=>{
        if (user) {
          acl.removeUserRoles(req.body.userId, req.body.role, err=>{
            if (err) {
              res.json({
                success: false,
                errors: err
              })
            }
            else {
              res.json({
                success: true,
                message: "role successfully removed from user"
              })
            }
          })
        }
        else {
          res.json({
            success: false,
            message: "User not found"
          })
        }
      })
    }
    else {
      res.json({
        success: false,
        message: "missing parameter(s)",
      })
    }
  },

}
<commit_msg>tambah role di detail user<commit_after>let models = require('../models')

module.exports = {
  usersWithRoles: function(req, res, next){
    let mongo = req.app.get('mongo')
    models.User.findAll()
    .then(users=>{
      let allUsers = []
      mongo.collection("users").find({}).toArray((err, userRoles)=>{
        for (var i in users) {
          let someone = {
            name: users[i].name,
            username: users[i].username,
            hasRole: false,
            roles: []
          }
          for (var j in userRoles) {
            if (userRoles[j].key == users[i].id) {
              someone.hasRole = true
              someone.roles.push(Object.keys(userRoles[j]).slice(2))
            }
          }
          allUsers.push(someone)
        }
        res.json({
          success: true,
          users: allUsers
        })
      })
    })
  },

  // Detail data user
  userDetail: function(req, res, next){
    models.User.find({
      where: {
        username: req.params.username
      }
    })
    .then(user=>{
      if (user) {
        let mongo = req.app.get('mongo')
        mongo.collection("users").find({key: user.id.toString()}).toArray((err, userRoles)=>{
          console.log(userRoles);
          let someone = {
            success: true,
            user: {
              id: user.id,
              name: user.name,
              username: user.username,
              email: user.email,
              identityNumber: user.identityNumber,
              roles: Object.keys(userRoles[0]).slice(2)
            }
          }
          res.json(someone)
        })
      }
      else {
        res.json({
          success: false,
          message: "User " + req.params.username + " not found"
        })
      }
    })
  },

  // tambah role
  addRole: function(req, res, next){
    let acl = req.app.get('acl')
    if (req.body.rolename && req.body.permissions) {
      acl.whatResources(req.body.rolename.toUpperCase(), (err, resources)=>{
        console.log(resources);
        if (!Object.keys(resources).length) {
          console.log("yes, the role not exist yet");
          let newAcl = {
            roles: req.body.rolename.toUpperCase(),
          }
          try {
            newAcl.allows = JSON.parse(req.body.permissions)
          } catch (e) {
            res.json({
              success: false,
              message: "Invalid JSON for permissions"
            })
          }
          console.log(JSON.stringify(newAcl));
          acl.allow([newAcl], err=>{
            if (err) {
              res.json({
                success: false,
                message: err
              })
            }
            else {
              res.json({
                success: true,
                message: "berhasil menambahkan role",
                permissions: newAcl
              })
            }
          })
        }
        else {
          res.json({
            success: false,
            message: "role already exist"
          })
        }
      })

    }
    else {
      res.json({
        success: false,
        message: "missing parameter(s)"
      })
    }
  },

  // menghapus role dari ACL
  removeRole: function(req, res, next){
    let acl = req.app.get('acl')
    if (req.body.role) {
      acl.removeRole(req.body.role, err=>{

      })
    }
    else {
      res.json({
        success: false,
        message: "missing parameter(s)"
      })
    }
  },

  // assign role ke user
  addRoleToUser: function(req, res, next){
    let acl = req.app.get('acl')
    if (req.body.role && req.body.userId) {
      models.User.findById(req.body.userId).then(user=>{
        if (user) {
          acl.addUserRoles(req.body.userId, req.body.role, err=>{
            if (err) {
              res.json({
                success: false,
                errors: err
              })
            }
            else {
              res.json({
                success: true,
                message: "role successfully assigned to user",
                user: {
                  username: user.username,
                  name: user.name
                }
              })
            }
          })
        }
        else {
          res.json({
            success: false,
            message: "User not found",
          })
        }
      })

    }
    else {
      res.json({
        success: false,
        message: "missing parameter(s)",
      })
    }
  },

  // hapus role dari user
  removeRoleFromUser: function(req, res, next){
    let acl = req.app.get('acl')
    if (req.body.role && req. body.userId) {
      models.User.findById(req.body.userId).then(user=>{
        if (user) {
          acl.removeUserRoles(req.body.userId, req.body.role, err=>{
            if (err) {
              res.json({
                success: false,
                errors: err
              })
            }
            else {
              res.json({
                success: true,
                message: "role successfully removed from user"
              })
            }
          })
        }
        else {
          res.json({
            success: false,
            message: "User not found"
          })
        }
      })
    }
    else {
      res.json({
        success: false,
        message: "missing parameter(s)",
      })
    }
  },

}
<|endoftext|>


<commit_before>/*jshint esversion: 6, loopfunc: true */
let fs = require('../core/fs.js');
let async = require('async');
//var Plugins = require('../core/plugins.js');
var utils = require('../utils/utils.js');
//var Npm = require('../pipeline/npm.js');
//let currentWeb3Version = require('../../package.json').dependencies.web3.replace("^","");
const webpack = require("webpack");

class Pipeline {

  constructor(options) {
    this.buildDir = options.buildDir;
    this.contractsFiles = options.contractsFiles;
    this.assetFiles = options.assetFiles;
    this.events = options.events;
    this.logger = options.logger;
    this.plugins = options.plugins;
  }

  build(abi, contractsJSON, path, callback) {
    let self = this;

    this.buildContracts(contractsJSON);

    self.buildWeb3JS(function() {

    // limit:1 due to issues when downloading required files such as web3.js
    async.eachOfLimit(self.assetFiles, 1, function (files, targetFile, cb) {
      // limit:1 due to issues when downloading required files such as web3.js
      async.mapLimit(files, 1,
        function(file, fileCb) {
          self.logger.trace("reading " + file.filename);

          if (file.filename.indexOf('.js') >= 0) {
              let importsList = {};

              //importsList["Embark/EmbarkJS"] = fs.embarkPath("js/embark.js");
              importsList["Embark/EmbarkJS"] = utils.joinPath(fs.dappPath(), ".embark", 'embark.js');
              importsList["Embark/web3"] = utils.joinPath(fs.dappPath(), ".embark", 'web3_instance.js');
              //importsList["Embark/libs/IpfsApi"] = fs.embarkPath('js/ipfs.js');

              async.waterfall([
                function findImports(next) {
                  webpack({
                    entry: utils.joinPath(fs.dappPath(), file.filename),
                    output: {
                      libraryTarget: 'umd',
                      path: utils.joinPath(fs.dappPath(), '.embark'),
                      filename: file.filename
                    },
                    externals: function(context, request, callback) {
                      if (request === utils.joinPath(fs.dappPath(), file.filename)) {
                        callback();
                      } else {
                        console.log("request " + request);
                        if (request.indexOf('Embark/contracts/') === 0) {
                          let contractName = request.split('/')[2];
                          let contractCode = self.buildContractJS(contractName);
                          let filePath = utils.joinPath(fs.dappPath(), ".embark", contractName + '.js');
                          fs.writeFileSync(filePath, contractCode);
                          importsList[request] = filePath;
                        }
                        callback(null, "amd " + Math.random());
                      }
                    },
                    module: {
                      rules: [
                        {
                          test: /\.css$/,
                          use: [
                            {loader: "style-loader"},
                            {loader: "css-loader"}
                          ]
                        }
                      ]
                    }
                  }).run((_err, _stats) => {
                    next();
                  });
                },

                function runWebpack(next) {
                  webpack({
                    entry: utils.joinPath(fs.dappPath(), file.filename),
                    output: {
                      libraryTarget: 'umd',
                      path: utils.joinPath(fs.dappPath(), '.embark'),
                      filename: file.filename
                    },
                    resolve: {
                      alias: importsList
                    },
                    externals: function(context, request, callback) {
                        if (request === "Embark/contracts/all") {
                          return callback(null, fs.readFileSync(utils.joinPath(fs.dappPath(), '.embark', 'embark.js')));
                          // should be .toString() ?
                        }
                        callback();
                    },
                    module: {
                      rules: [
                        {
                          test: /\.css$/,
                          use: [
                            {loader: "style-loader"},
                            {loader: "css-loader"}
                          ]
                        },
                        {
                          test: /\.scss$/,
                          use: [
                            {loader: "style-loader"},
                            {loader: "css-loader"}
                          ]
                        },
                        {
                          test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                          loader: 'url-loader?limit=100000'
                        }
                      ]
                    }
                  }).run((_err, _stats) => {
                    next();
                  });

                }

              ], function(_err, _result) {
                let fileContent = fs.readFileSync('./.embark/' + file.filename).toString();
                fileCb(null, {content: fileContent, filename: file.filename, path: file.path, modified: true});
              });

          } else {
            file.content(function(fileContent) {
              return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, modified: true});
            });
          }

        },
        function (err, contentFiles) {
          let dir = targetFile.split('/').slice(0, -1).join('/');
          self.logger.trace("creating dir " + self.buildDir + dir);
          fs.mkdirpSync(self.buildDir + dir);

          // if it's a directory
          if (targetFile.slice(-1) === '/' || targetFile.indexOf('.') === -1) {
            let targetDir = targetFile;

            if (targetDir.slice(-1) !== '/') {
              targetDir = targetDir + '/';
            }

            contentFiles.map(function (file) {
              let filename = file.filename.replace('app/', '');
              filename = filename.replace(targetDir, '');
              self.logger.info("writing file " + (self.buildDir + targetDir + filename).bold.dim);

              fs.copySync(self.buildDir + targetDir + filename, file.path, {overwrite: true});
            });
          } else {
            let content = contentFiles.map(function (file) {
              if (file === undefined) {
                return "";
              }
              return file.content;
            }).join("\n");

            self.logger.info("writing file " + (self.buildDir + targetFile).bold.dim);
            fs.writeFileSync(self.buildDir + targetFile, content);
          }
          cb();
        }
      );
    },
    function (_err, _results) {
      callback();
    });
  });
  }

  buildContracts(contractsJSON) {
    fs.mkdirpSync(this.buildDir + 'contracts');

    for (let className in contractsJSON) {
      let contract = contractsJSON[className];
      fs.writeJSONSync(this.buildDir + 'contracts/' + className + ".json", contract, {spaces: 2});
    }
  }

  buildContractJS(contractName) {
    let contractJSON = fs.readFileSync('dist/contracts/' + contractName + '.json').toString();

    let contractCode = "";
    contractCode += "import web3 from 'Embark/web3';\n";
    contractCode += "import EmbarkJS from 'Embark/EmbarkJS';\n";
    contractCode += "let " + contractName + "JSONConfig = " + contractJSON + ";\n";
    contractCode += "let " + contractName + " = new EmbarkJS.Contract(" + contractName + "JSONConfig);\n";

    contractCode += "\n__embarkContext.execWhenReady(function() {\n";
    contractCode += "\nconsole.log('ready to set provider');\n";
    contractCode += "\n" + contractName + ".setProvider(web3.currentProvider);\n";
    contractCode += "\n});\n";

    contractCode += "export default " + contractName + ";\n";

    return contractCode;
  }

  buildWeb3JS(cb) {
    console.log("--> web3");
    this.events.request('provider-code', function(providerCode)  {
      let code = "";
      code += "\nimport Web3 from '" + utils.joinPath(fs.embarkPath("js/web3-1.0.min.js")) + "'\n";

      code += "\n if (typeof web3 !== 'undefined') {";
      code += "\n } else {";
      code += "\n var web3 = new Web3();\n";
      code += "\n }";

      code += providerCode;
      code += "\nglobal.__embarkContext = __mainContext.__loadManagerInstance;\n";
      code += "\nconsole.log('web3');\n";
      code += "\nconsole.log(web3);\n";
      code += "\nwindow.web3 = web3;\n";
      code += "\nexport default web3;\n";
      let filePath = utils.joinPath(fs.dappPath(), ".embark", 'web3_instance.js');
      fs.mkdirpSync(utils.joinPath(fs.dappPath(), ".embark"));
      fs.writeFileSync(filePath, code);
      cb();
    });
  }

}

module.exports = Pipeline;
<commit_msg>cleanup<commit_after>/*jshint esversion: 6, loopfunc: true */
let fs = require('../core/fs.js');
let async = require('async');
//var Plugins = require('../core/plugins.js');
var utils = require('../utils/utils.js');
//var Npm = require('../pipeline/npm.js');
//let currentWeb3Version = require('../../package.json').dependencies.web3.replace("^","");
const webpack = require("webpack");

class Pipeline {

  constructor(options) {
    this.buildDir = options.buildDir;
    this.contractsFiles = options.contractsFiles;
    this.assetFiles = options.assetFiles;
    this.events = options.events;
    this.logger = options.logger;
    this.plugins = options.plugins;
  }

  build(abi, contractsJSON, path, callback) {
    let self = this;

    this.buildContracts(contractsJSON);

    self.buildWeb3JS(function() {

    // limit:1 due to issues when downloading required files such as web3.js
    async.eachOfLimit(self.assetFiles, 1, function (files, targetFile, cb) {
      // limit:1 due to issues when downloading required files such as web3.js
      async.mapLimit(files, 1,
        function(file, fileCb) {
          self.logger.trace("reading " + file.filename);

          if (file.filename.indexOf('.js') >= 0) {
              let importsList = {};

              //importsList["Embark/EmbarkJS"] = fs.embarkPath("js/embark.js");
              importsList["Embark/EmbarkJS"] = utils.joinPath(fs.dappPath(), ".embark", 'embark.js');
              importsList["Embark/web3"] = utils.joinPath(fs.dappPath(), ".embark", 'web3_instance.js');
              //importsList["Embark/libs/IpfsApi"] = fs.embarkPath('js/ipfs.js');

              async.waterfall([
                function findImports(next) {
                  webpack({
                    entry: utils.joinPath(fs.dappPath(), file.filename),
                    output: {
                      libraryTarget: 'umd',
                      path: utils.joinPath(fs.dappPath(), '.embark'),
                      filename: file.filename
                    },
                    externals: function(context, request, callback) {
                      if (request === utils.joinPath(fs.dappPath(), file.filename)) {
                        callback();
                      } else {
                        if (request.indexOf('Embark/contracts/') === 0) {
                          let contractName = request.split('/')[2];
                          let contractCode = self.buildContractJS(contractName);
                          let filePath = utils.joinPath(fs.dappPath(), ".embark", contractName + '.js');
                          fs.writeFileSync(filePath, contractCode);
                          importsList[request] = filePath;
                        }
                        callback(null, "amd " + Math.random());
                      }
                    },
                    module: {
                      rules: [
                        {
                          test: /\.css$/,
                          use: [
                            {loader: "style-loader"},
                            {loader: "css-loader"}
                          ]
                        }
                      ]
                    }
                  }).run((_err, _stats) => {
                    next();
                  });
                },

                function runWebpack(next) {
                  webpack({
                    entry: utils.joinPath(fs.dappPath(), file.filename),
                    output: {
                      libraryTarget: 'umd',
                      path: utils.joinPath(fs.dappPath(), '.embark'),
                      filename: file.filename
                    },
                    resolve: {
                      alias: importsList
                    },
                    externals: function(context, request, callback) {
                        if (request === "Embark/contracts/all") {
                          return callback(null, fs.readFileSync(utils.joinPath(fs.dappPath(), '.embark', 'embark.js')));
                          // should be .toString() ?
                        }
                        callback();
                    },
                    module: {
                      rules: [
                        {
                          test: /\.css$/,
                          use: [
                            {loader: "style-loader"},
                            {loader: "css-loader"}
                          ]
                        },
                        {
                          test: /\.scss$/,
                          use: [
                            {loader: "style-loader"},
                            {loader: "css-loader"}
                          ]
                        },
                        {
                          test: /\.(png|woff|woff2|eot|ttf|svg)$/,
                          loader: 'url-loader?limit=100000'
                        }
                      ]
                    }
                  }).run((_err, _stats) => {
                    next();
                  });

                }

              ], function(_err, _result) {
                let fileContent = fs.readFileSync('./.embark/' + file.filename).toString();
                fileCb(null, {content: fileContent, filename: file.filename, path: file.path, modified: true});
              });

          } else {
            file.content(function(fileContent) {
              return fileCb(null, {content: fileContent, filename: file.filename, path: file.path, modified: true});
            });
          }

        },
        function (err, contentFiles) {
          let dir = targetFile.split('/').slice(0, -1).join('/');
          self.logger.trace("creating dir " + self.buildDir + dir);
          fs.mkdirpSync(self.buildDir + dir);

          // if it's a directory
          if (targetFile.slice(-1) === '/' || targetFile.indexOf('.') === -1) {
            let targetDir = targetFile;

            if (targetDir.slice(-1) !== '/') {
              targetDir = targetDir + '/';
            }

            contentFiles.map(function (file) {
              let filename = file.filename.replace('app/', '');
              filename = filename.replace(targetDir, '');
              self.logger.info("writing file " + (self.buildDir + targetDir + filename).bold.dim);

              fs.copySync(self.buildDir + targetDir + filename, file.path, {overwrite: true});
            });
          } else {
            let content = contentFiles.map(function (file) {
              if (file === undefined) {
                return "";
              }
              return file.content;
            }).join("\n");

            self.logger.info("writing file " + (self.buildDir + targetFile).bold.dim);
            fs.writeFileSync(self.buildDir + targetFile, content);
          }
          cb();
        }
      );
    },
    function (_err, _results) {
      callback();
    });
  });
  }

  buildContracts(contractsJSON) {
    fs.mkdirpSync(this.buildDir + 'contracts');

    for (let className in contractsJSON) {
      let contract = contractsJSON[className];
      fs.writeJSONSync(this.buildDir + 'contracts/' + className + ".json", contract, {spaces: 2});
    }
  }

  buildContractJS(contractName) {
    let contractJSON = fs.readFileSync('dist/contracts/' + contractName + '.json').toString();

    let contractCode = "";
    contractCode += "import web3 from 'Embark/web3';\n";
    contractCode += "import EmbarkJS from 'Embark/EmbarkJS';\n";
    contractCode += "let " + contractName + "JSONConfig = " + contractJSON + ";\n";
    contractCode += "let " + contractName + " = new EmbarkJS.Contract(" + contractName + "JSONConfig);\n";

    contractCode += "\n__embarkContext.execWhenReady(function() {\n";
    contractCode += "\n" + contractName + ".setProvider(web3.currentProvider);\n";
    contractCode += "\n});\n";

    contractCode += "export default " + contractName + ";\n";

    return contractCode;
  }

  buildWeb3JS(cb) {
    this.events.request('provider-code', function(providerCode)  {
      let code = "";
      code += "\nimport Web3 from '" + utils.joinPath(fs.embarkPath("js/web3-1.0.min.js")) + "'\n";

      code += "\n if (typeof web3 !== 'undefined') {";
      code += "\n } else {";
      code += "\n var web3 = new Web3();\n";
      code += "\n }";

      code += providerCode;
      code += "\nglobal.__embarkContext = __mainContext.__loadManagerInstance;\n";
      code += "\nwindow.web3 = web3;\n";
      code += "\nexport default web3;\n";
      let filePath = utils.joinPath(fs.dappPath(), ".embark", 'web3_instance.js');
      fs.mkdirpSync(utils.joinPath(fs.dappPath(), ".embark"));
      fs.writeFileSync(filePath, code);
      cb();
    });
  }

}

module.exports = Pipeline;
<|endoftext|>