<commit_before>export function getCookie (cookieName) {
  if (document.cookie.length > 0) {
    var cookieStart = document.cookie.indexOf(cookieName + '=');
    if (cookieStart !== -1) {
      cookieStart = cookieStart + cookieName.length + 1;
      var cookieEnd = document.cookie.indexOf(';', cookieStart);
      if (cookieEnd === -1) cookieEnd = document.cookie.length;
      return decodeURIComponent(document.cookie.substring(cookieStart, cookieEnd));
    }
  }
  return '';
}

export function getXsrfToken () {
  return getCookie('XSRF-TOKEN');
}

export function BuildHttpRequestPayload (object) {
  let formData = new FormData();
  let normalData = {};

  for (let key in object) {
    if (object.hasOwnProperty(key)) {
      if (object[key] && object[key].constructor === File) {
        formData.append(key, object[key]);
      }
      else {
        normalData[key] = object[key];
      }
    }
  }

  formData.append('_data', JSON.stringify(normalData));

  return formData;
}

/**
 * @return {string}
 */
export function BuildAutoSearchQuery (columns, term) {
  if (columns.constructor !== Array) {
    columns = [columns];
  }
  columns.push('id');
  let query = 'draw=' + new Date().getTime() + '&start=0&length=25';
  query += '&search[regex]=false&search[value]=' + encodeURIComponent(term);

  for (let i = 0; i < columns.length; i++) {
    query += '&columns[' + i + '][name]=' + columns[i] + '&columns[' + i + '][searchable]=true';
  }
  return query;
}

export function RegisterStore (vue, storeName, store) {
  if (!vue.$store._modules.get([storeName])) {
    return vue.$store.registerModule(storeName, store);
  }
}

/**
 * @return {string}
 */
export function ShowDeleteConfirmDialog (vue, url, data, confirmText, messageText) {
  data = data ? data : {}
  data._method = 'delete'
  confirmText = confirmText ? confirmText : vue.$i18n.t('global.delete_confirm.confirm_text')
  messageText = messageText ? messageText : vue.$i18n.t('global.delete_confirm.complete_text')
  return vue.$confirm(confirmText, vue.$i18n.t('global.terms.alert'), {
    confirmButtonText: vue.$i18n.t('global.terms.confirm'),
    cancelButtonText: vue.$i18n.t('global.terms.cancel'),
    type: 'warning'
  }).then(() => {
    return axios.post(url, data)
  }).then(result => {
    vue.$message({
      type: 'success',
      message: messageText
    })
    return result.data
  }, ({response}) => {
    vue.$message({
      type: 'error',
      message: response.data.message
    })
  })
}<commit_msg>enhance BuildAutoSearchQuery<commit_after>export function getCookie (cookieName) {
  if (document.cookie.length > 0) {
    var cookieStart = document.cookie.indexOf(cookieName + '=');
    if (cookieStart !== -1) {
      cookieStart = cookieStart + cookieName.length + 1;
      var cookieEnd = document.cookie.indexOf(';', cookieStart);
      if (cookieEnd === -1) cookieEnd = document.cookie.length;
      return decodeURIComponent(document.cookie.substring(cookieStart, cookieEnd));
    }
  }
  return '';
}

export function getXsrfToken () {
  return getCookie('XSRF-TOKEN');
}

export function BuildHttpRequestPayload (object) {
  let formData = new FormData();
  let normalData = {};

  for (let key in object) {
    if (object.hasOwnProperty(key)) {
      if (object[key] && object[key].constructor === File) {
        formData.append(key, object[key]);
      }
      else {
        normalData[key] = object[key];
      }
    }
  }

  formData.append('_data', JSON.stringify(normalData));

  return formData;
}

/**
 * @return {string}
 */
export function BuildAutoSearchQuery (columns, term) {
  if (columns.constructor !== Array) {
    columns = [columns]
  }
  columns.push('id')
  let query = 'draw=' + new Date().getTime() + '&start=0&length=25'
  if (term) {
    query += '&search[regex]=false&search[value]=' + encodeURIComponent(term)
  }

  for (let i = 0; i < columns.length; i++) {
    query += '&columns[' + i + '][name]=' + columns[i] + '&columns[' + i + '][searchable]=true'
  }
  return query
}

export function RegisterStore (vue, storeName, store) {
  if (!vue.$store._modules.get([storeName])) {
    return vue.$store.registerModule(storeName, store);
  }
}

/**
 * @return {string}
 */
export function ShowDeleteConfirmDialog (vue, url, data, confirmText, messageText) {
  data = data ? data : {}
  data._method = 'delete'
  confirmText = confirmText ? confirmText : vue.$i18n.t('global.delete_confirm.confirm_text')
  messageText = messageText ? messageText : vue.$i18n.t('global.delete_confirm.complete_text')
  return vue.$confirm(confirmText, vue.$i18n.t('global.terms.alert'), {
    confirmButtonText: vue.$i18n.t('global.terms.confirm'),
    cancelButtonText: vue.$i18n.t('global.terms.cancel'),
    type: 'warning'
  }).then(() => {
    return axios.post(url, data)
  }).then(result => {
    vue.$message({
      type: 'success',
      message: messageText
    })
    return result.data
  }, ({response}) => {
    vue.$message({
      type: 'error',
      message: response.data.message
    })
  })
}<|endoftext|>


<commit_before>"use strict";
const moduleId = "M-DISC";
const moment = require('moment');
var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var BateeqModels = require("bateeq-models");
var map = BateeqModels.map;
var generateCode = require('../../../utils/code-generator');
var BaseManager = require('module-toolkit').BaseManager;
var Discount = BateeqModels.inventory.master.Discount;
var StoreManager = require('../../master/store-manager');

module.exports = class DiscountManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.master.Discount);
        this.storeManager = new StoreManager(db, user);
    }

    _getQuery(paging) {

        var _default = {
            _deleted: false
        },
            pagingFilter = paging.filter || {},
            keywordFilter = {},
            query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterDiscountOne = {
                "discountOne": {
                    "$regex": regex
                }
            };

            var filterDiscountTwo = {
                "discountTwo": {
                    "$regex": regex
                }
            };

            var filterStoreCategory = {
                "storeCategory": {
                    "$regex": regex
                }
            };

            var filterItem = {
                "items.item.code": {
                    "$regex": regex
                }
            }
            keywordFilter['$or'] = [filterDiscountOne, filterDiscountTwo, filterStoreCategory, filterItem];
        }

        query["$and"] = [_default];
        return query;
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.inventory.master.Discount}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        return this.collection.createIndexes([dateIndex]);
    }

    _beforeInsert(discount) {
        discount.code = generateCode(moduleId);
        return Promise.resolve(discount);
    };

    _validate(discount) {
        var valid = discount;
        var errors = {};
        var getStores = [];
        var getAvailableDiscount = {};

        if (valid.discountOne && valid.discountTwo) {

            if (valid.storeCategory === "ALL") {
                getStores = this.storeManager.getStore();
            } else if (valid.stores.name === "ALL") {
                var storeName = { 'storeCategory': valid.storeCategory, '_deleted': false };
                getStores = this.storeManager.getStore(storeName);
            } else {
                if (valid.stores) {
                    var storeName = { 'name': valid.stores.name, '_deleted': false };
                    getStores = this.storeManager.getSingleByQuery(storeName);
                }
            }

            getAvailableDiscount = this.getDiscountByFilter({ 'discountOne': valid.discountOne, 'discountTwo': valid.discountTwo, '_deleted': false });

        }

        return Promise.all([getStores, getAvailableDiscount])
            .then(result => {
                var todaySdate = moment(new Date).startOf('date');
                var validListDiscount = [];
                valid.stores = result[0];

                // Get Discount where is still available until today
                if (result[1].length > 0) {
                    result[1].forEach(item => {
                        var startDiscount = moment(item.startDate).startOf('day');
                        var endDiscount = moment(item.endDate).endOf('day');

                        if (todaySdate >= startDiscount && !valid._id || todaySdate <= endDiscount && valid._id) {
                            validListDiscount.push(item);
                        }
                    });
                }

                if (!valid.startDate || valid.startDate == '') {
                    errors["startDate"] = "Masukkan Mulai Berlaku Diskon";
                }

                if (!valid.endDate || valid.endDate == '') {
                    errors["endDate"] = "Masukkan Mulai Berakhir Diskon";
                }

                if (validListDiscount.length > 0 && !valid._id) {
                    validListDiscount.forEach(item => {
                        var validStartDiscount = moment(valid.startDate).startOf('day');
                        var validEndDiscount = moment(valid.endDate).endOf('day');
                        var itemStartDiscount = moment(item.startDate).startOf('day');
                        var itemEndDiscount = moment(item.endDate).endOf('day');

                        if (validStartDiscount >= itemStartDiscount && validStartDiscount <= itemEndDiscount ||
                            itemStartDiscount >= validStartDiscount && itemStartDiscount <= validEndDiscount) {
                                errors["discountOne"] = "Diskon 1 Sudah dipakai & Masih Berlaku";
                                errors["discountTwo"] = "Diskon 2 Sudah dipakai & Masih Berlaku";
                        }
                    });
                }

                if (!valid.stamp) {
                    valid = new Discount(valid);
                }

                valid.stamp(this.user.username, "manager");

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require('module-toolkit').ValidationError;
                    return Promise.reject(new ValidationError('data does not pass validation', errors));
                }

                return Promise.resolve(valid);
            })
    }

    getDiscountByFilter(filter) {
        return this._createIndexes()
            .then((createIndexResults) => {
                return new Promise((resolve, reject) => {
                    this.collection.where(filter).execute()
                        .then((results) => {
                            resolve(results.data);
                        })
                        .catch(e => {
                            reject(e);
                        });
                });
            });
    }
};<commit_msg>update master discount  validation<commit_after>"use strict";
const moduleId = "M-DISC";
const moment = require('moment');
var ObjectId = require("mongodb").ObjectId;
require("mongodb-toolkit");
var BateeqModels = require("bateeq-models");
var map = BateeqModels.map;
var generateCode = require('../../../utils/code-generator');
var BaseManager = require('module-toolkit').BaseManager;
var Discount = BateeqModels.inventory.master.Discount;
var StoreManager = require('../../master/store-manager');

module.exports = class DiscountManager extends BaseManager {
    constructor(db, user) {
        super(db, user);
        this.collection = this.db.use(map.inventory.master.Discount);
        this.storeManager = new StoreManager(db, user);
    }

    _getQuery(paging) {

        var _default = {
            _deleted: false
        },
            pagingFilter = paging.filter || {},
            keywordFilter = {},
            query = {};

        if (paging.keyword) {
            var regex = new RegExp(paging.keyword, "i");
            var filterDiscountOne = {
                "discountOne": {
                    "$regex": regex
                }
            };

            var filterDiscountTwo = {
                "discountTwo": {
                    "$regex": regex
                }
            };

            var filterStoreCategory = {
                "storeCategory": {
                    "$regex": regex
                }
            };

            var filterItem = {
                "items.item.code": {
                    "$regex": regex
                }
            }
            keywordFilter['$or'] = [filterDiscountOne, filterDiscountTwo, filterStoreCategory, filterItem];
        }

        query["$and"] = [_default];
        return query;
    }

    _createIndexes() {
        var dateIndex = {
            name: `ix_${map.inventory.master.Discount}__updatedDate`,
            key: {
                _updatedDate: -1
            }
        };

        return this.collection.createIndexes([dateIndex]);
    }

    _beforeInsert(discount) {
        discount.code = generateCode(moduleId);
        return Promise.resolve(discount);
    };

    _validate(discount) {
        var valid = discount;
        var errors = {};
        var getStores = [];
        var getAvailableDiscount = {};

        if (valid.discountOne && valid.discountTwo) {

            if (valid.storeCategory === "ALL") {
                getStores = this.storeManager.getStore();
            } else if (valid.stores.name === "ALL") {
                var storeName = { 'storeCategory': valid.storeCategory, '_deleted': false };
                getStores = this.storeManager.getStore(storeName);
            } else {
                if (valid.stores) {
                    var storeName = { 'name': valid.stores.name, '_deleted': false };
                    getStores = this.storeManager.getSingleByQuery(storeName);
                }
            }

            getAvailableDiscount = this.getDiscountByFilter({ 'discountOne': valid.discountOne, 'discountTwo': valid.discountTwo, '_deleted': false });

        }

        return Promise.all([getStores, getAvailableDiscount])
            .then(result => {
                var todaySdate = moment(new Date).startOf('date');
                var validListDiscount = [];
                valid.stores = result[0];

                // Get Discount where is still available until today
                if (result[1].length > 0 && !valid._id) {
                    result[1].forEach(item => {
                        var startDiscount = moment(item.startDate).startOf('day');
                        var endDiscount = moment(item.endDate).endOf('day');

                        if (todaySdate >= startDiscount && !valid._id || todaySdate <= endDiscount && valid._id) {
                            validListDiscount.push(item);
                        }
                    });
                }

                if (!valid.startDate || valid.startDate == '') {
                    errors["startDate"] = "Masukkan Mulai Berlaku Diskon";
                }

                if (!valid.endDate || valid.endDate == '') {
                    errors["endDate"] = "Masukkan Mulai Berakhir Diskon";
                }

                if (validListDiscount.length > 0) {
                    validListDiscount.forEach(item => {
                        var validStartDiscount = moment(valid.startDate).startOf('day');
                        var validEndDiscount = moment(valid.endDate).endOf('day');
                        var itemStartDiscount = moment(item.startDate).startOf('day');
                        var itemEndDiscount = moment(item.endDate).endOf('day');

                        if (validStartDiscount >= itemStartDiscount && validStartDiscount <= itemEndDiscount ||
                            itemStartDiscount >= validStartDiscount && itemStartDiscount <= validEndDiscount) {
                                errors["discountOne"] = "Diskon 1 Sudah dipakai & Masih Berlaku";
                                errors["discountTwo"] = "Diskon 2 Sudah dipakai & Masih Berlaku";
                        }
                    });
                }

                if (!valid.stamp) {
                    valid = new Discount(valid);
                }

                valid.stamp(this.user.username, "manager");

                if (Object.getOwnPropertyNames(errors).length > 0) {
                    var ValidationError = require('module-toolkit').ValidationError;
                    return Promise.reject(new ValidationError('data does not pass validation', errors));
                }

                return Promise.resolve(valid);
            })
    }

    getDiscountByFilter(filter) {
        return this._createIndexes()
            .then((createIndexResults) => {
                return new Promise((resolve, reject) => {
                    this.collection.where(filter).execute()
                        .then((results) => {
                            resolve(results.data);
                        })
                        .catch(e => {
                            reject(e);
                        });
                });
            });
    }
};<|endoftext|>


<commit_before>'use strict';

import { async } from 'metal';
import dom from './dom';

/**
 * Utility functions for running styles.
 */
class globalEvalStyles {
	/**
	 * Evaluates the given style.
	 * @param {string} text
	 * @return {Element} style
	 */
	static run(text) {
		var style = document.createElement('style');
		style.innerHTML = text;
		document.head.appendChild(style);
		return style;
	}

	/**
	 * Evaluates the given style file.
	 * @param {string} href The file's path.
	 * @param {function()=} opt_callback Optional function to be called
	 *   when the styles has been run.
	 * @return {Element} style
	 */
	static runFile(href, opt_callback) {
		var link = document.createElement('link');
		link.rel = 'stylesheet';
		link.href = href;
		globalEvalStyles.runStyle(link, opt_callback);
		return link;
	}

	/**
	 * Evaluates the code referenced by the given style/link element.
	 * @param {!Element} style
	 * @param {function()=} opt_callback Optional function to be called
	 *   when the script has been run.
	 *  @return {Element} style
	 */
	static runStyle(style, opt_callback) {
		var callback = function() {
			opt_callback && opt_callback();
		};
		if (style.rel && style.rel !== 'stylesheet') {
			async.nextTick(callback);
			return;
		}
		dom.on(style, 'load', callback);
		dom.on(style, 'error', callback);
		document.head.appendChild(style);
		return style;
	}

	/**
	 * Evaluates any style present in the given element.
	 * TODO: Evaluates running styles in parallel instead of in order.
	 * @params {!Element} element
	 * @param {function()=} opt_callback Optional function to be called
	 *   when the style has been run.
	 */
	static runStylesInElement(element, opt_callback) {
		var styles = element.querySelectorAll('style,link');
		if (styles.length) {
			globalEvalStyles.runStylesInOrder(styles, 0, opt_callback);
		} else if (opt_callback) {
			async.nextTick(opt_callback);
		}
	}

	/**
	 * Runs the given styles elements in the order that they appear.
	 * @param {!NodeList} styles
	 * @param {number} index
	 * @param {function()=} opt_callback Optional function to be called
	 *   when the script has been run.
	 */
	static runStylesInOrder(styles, index, opt_callback) {
		globalEvalStyles.runStyle(styles.item(index), function() {
			if (index < styles.length - 1) {
				globalEvalStyles.runStylesInOrder(styles, index + 1, opt_callback);
			} else if (opt_callback) {
				async.nextTick(opt_callback);
			}
		});
	}
}

export default globalEvalStyles;
<commit_msg>Allows style tags to be loaded in parallel<commit_after>'use strict';

import { async } from 'metal';
import dom from './dom';

/**
 * Utility functions for running styles.
 */
class globalEvalStyles {
	/**
	 * Evaluates the given style.
	 * @param {string} text
	 * @return {Element} style
	 */
	static run(text) {
		var style = document.createElement('style');
		style.innerHTML = text;
		document.head.appendChild(style);
		return style;
	}

	/**
	 * Evaluates the given style file.
	 * @param {string} href The file's path.
	 * @param {function()=} opt_callback Optional function to be called
	 *   when the styles has been run.
	 * @return {Element} style
	 */
	static runFile(href, opt_callback) {
		var link = document.createElement('link');
		link.rel = 'stylesheet';
		link.href = href;
		globalEvalStyles.runStyle(link, opt_callback);
		return link;
	}

	/**
	 * Evaluates the code referenced by the given style/link element.
	 * @param {!Element} style
	 * @param {function()=} opt_callback Optional function to be called
	 *   when the script has been run.
	 *  @return {Element} style
	 */
	static runStyle(style, opt_callback) {
		var callback = function() {
			opt_callback && opt_callback();
		};
		if (style.rel && style.rel !== 'stylesheet') {
			async.nextTick(callback);
			return;
		}
		dom.on(style, 'load', callback);
		dom.on(style, 'error', callback);
		document.head.appendChild(style);
		return style;
	}

	/**
	 * Evaluates any style present in the given element.
	 * TODO: Evaluates running styles in parallel instead of in order.
	 * @params {!Element} element
	 * @param {function()=} opt_callback Optional function to be called
	 *   when the style has been run.
	 */
	static runStylesInElement(element, opt_callback) {
		var styles = element.querySelectorAll('style,link');
		if (styles.length === 0 && opt_callback) {
			async.nextTick(opt_callback);
			return;
		}

		var loadCount = 0;
		var callback = function() {
			if (opt_callback && ++loadCount === styles.length) {
				async.nextTick(opt_callback);
			}
		};
		for (var i = 0; i < styles.length; i++) {
			globalEvalStyles.runStyle(styles[i], callback);
		}
	}
}

export default globalEvalStyles;
<|endoftext|>


<commit_before>/*
  Import React
*/
import React from 'react';

/*
  Import Components
*/
import {
  MarkedPreview,
  MarkedInput
} from '../components';

/*
  MarkedArea Container Class
*/
export class LiveMarkedArea extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      value: props.defaultValue ? props.defaultValue : ''
    };
  }
  static defaultProps = {
    id: 'mmc-marked-area',
    label: '',
    classNames: {
      root: 'marked-area',
      header: 'marked-area-header',
      activeButton: 'marked-area-button active',
      defaultButton: 'marked-area-button',
      helpLink: 'marked-area-help-link',
      textContainer: 'marked-area-text-container',
      liveDivider: 'marked-area-live-divider'
    }
  };
  handleTextChange = (e) => {
    this.setState({value: e.target.value});
  };
  render() {
    let {id, label, classNames, placeholder} = this.props;
    let {value} = this.state;
    return (

        {label}

        <MarkedInput
          placeholder={placeholder}
          classNames={classNames}
          onChange={this.handleTextChange}
          value={value} />

        <MarkedPreview classNames={classNames}
          value={value} />

    );
  }
}
<commit_msg>update LiveMarkedArea props value change handler<commit_after>/*
  Import React
*/
import React from 'react';

/*
  Import Components
*/
import {
  MarkedPreview,
  MarkedInput
} from '../components';

/*
  MarkedArea Container Class
*/
export class LiveMarkedArea extends React.Component {
    constructor(props) {
    super(props);
    this.state = {
      value: props.defaultValue ? props.defaultValue : ''
    };
  }
  static defaultProps = {
    id: 'mmc-marked-area',
    label: '',
    classNames: {
      root: 'marked-area',
      header: 'marked-area-header',
      activeButton: 'marked-area-button active',
      defaultButton: 'marked-area-button',
      helpLink: 'marked-area-help-link',
      textContainer: 'marked-area-text-container',
      liveDivider: 'marked-area-live-divider'
    }
  };
  componentWillReceiveProps(props) {
      this.setState({value: props.value});
  };
  handleTextChange = (e) => {
    this.setState({value: e.target.value});
  };
  render() {
    let {id, label, classNames, placeholder} = this.props;
    let {value} = this.state;
    return (

        {label}

        <MarkedInput
          placeholder={placeholder}
          classNames={classNames}
          onChange={this.handleTextChange}
          value={value} />

        <MarkedPreview classNames={classNames}
          value={value} />

    );
  }
}
<|endoftext|>


<commit_before>import webpack from 'webpack';
import path from 'path';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import DashboardPlugin from 'webpack-dashboard/plugin';

export default {
  devtool: 'cheap-module-eval-source-map',

  entry: [
    'react-hot-loader/patch',
    'webpack-dev-server/client?http://0.0.0.0:8080',
    'webpack/hot/only-dev-server',
    path.resolve(__dirname, 'src/index.js'),
  ],

  output: {
    path: path.resolve(__dirname, 'build'),
    pathinfo: true,
    filename: 'bundle.js',
    publicPath: '/',
  },

  devServer: {
    hot: true,
    contentBase: path.resolve(__dirname, 'app'),
    publicPath: '/',
  },

  resolveLoader: {
    moduleExtensions: ['-loader'],
  },

  module: {
    rules: [
      {
        exclude: [
          /\.html$/,
          /\.jsx?$/,
          /\.css$/,
          /\.json$/,
          /\.svg$/,
        ],
        use: [
          {
            loader: 'url',
            options: {
              limit: 10000,
              name: '[name].[hash:8].[ext]',
            },
          },
        ],
      },
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, 'src'),
        ],
        use: [
          { loader: 'babel' },
        ],
      },
      {
        test: /\.scss$/,
        use: [
          { loader: 'style' },
          { loader: 'css' },
          { loader: 'sass' },
        ],
      },
      {
        test: /\.css$/,
        use: [
          { loader: 'style' },
          { loader: 'css' },
        ],
      },
      {
        test: /\.svg$/,
        use: [
          { loader: 'file' },
        ],
      },
    ],
  },

  plugins: [
    new DashboardPlugin(),
    new HtmlWebpackPlugin({
      inject: true,
      template: path.resolve(__dirname, 'app/index.html'),
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development'),
      },
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.NoErrorsPlugin(),
  ],

  target: 'electron',
};
<commit_msg>Fixed webpack-dev-server error<commit_after>import webpack from 'webpack';
import path from 'path';
import DashboardPlugin from 'webpack-dashboard/plugin';

export default {
  devtool: 'cheap-eval-source-map',

  entry: [
    'react-hot-loader/patch',
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/only-dev-server',
    path.resolve(__dirname, 'src/index.js'),
  ],

  output: {
    path: path.resolve(__dirname, 'app'),
    pathinfo: true,
    filename: 'bundle.js',
    publicPath: '/',
  },

  devServer: {
    contentBase: path.resolve(__dirname, 'app'),
    hot: true,
    inline: true,
    publicPath: 'http://localhost:8080/',
    watchContentBase: true,
  },

  resolveLoader: {
    moduleExtensions: ['-loader'],
  },

  module: {
    rules: [
      {
        exclude: [
          /\.html$/,
          /\.jsx?$/,
          /\.css$/,
          /\.json$/,
          /\.svg$/,
        ],
        use: [
          {
            loader: 'url',
            options: {
              limit: 10000,
              name: '[name].[hash:8].[ext]',
            },
          },
        ],
      },
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, 'src'),
        ],
        use: [
          { loader: 'babel' },
        ],
      },
      {
        test: /\.scss$/,
        use: [
          { loader: 'style' },
          { loader: 'css' },
          { loader: 'sass' },
        ],
      },
      {
        test: /\.css$/,
        use: [
          { loader: 'style' },
          { loader: 'css' },
        ],
      },
      {
        test: /\.svg$/,
        use: [
          { loader: 'file' },
        ],
      },
    ],
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development'),
      },
    }),
    new DashboardPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.NoErrorsPlugin(),
  ],

  target: 'electron-renderer',
};
<|endoftext|>


<commit_before>// Vogue - Client
// Copyright (c) 2011 Andrew Davey (andrew@equin.co.uk)
//
// Note that all occurances of {port} in this script will be replaced with the port of the
// HTTP server hosted by Node.

(function() {

loadScripts({
  jQuery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js',
  io: 'http://localhost:{port}/socket.io/socket.io.js'
}, vogue);

function vogue() {
  var stylesheets = getLocalStylesheets();
  var socket = new io.Socket('localhost', { port: {port} });
  socket.on('connect', watchAllStylesheets);
  socket.on('message', handleMessage);
  socket.connect();

  function watchAllStylesheets() {
    var origin = document.location.protocol + '//' + document.location.host;
    var skipPrefixLength = origin.length;
    for (var href in stylesheets) {
      // linkElement.href is resolved by the browser to the full URL.
      // (unlike reading the actual attribute value.)
      // Very handy; we can easily get the full path segment of the URL
      // by skipping the current document's location origin length.
      var path = stylesheets[href].href.substr(skipPrefixLength);
      socket.send('watch ' + path);
    }
  }

  function handleMessage(message) {
    var match = message.match(/^update (.*)$/);
    if (match) {
      var href = match[1];
      reloadStylesheet(href);
    }
  }

  function reloadStylesheet(href) {
    var newHref = href
      + (href.indexOf('?') >= 0 ? '&' : '?')
      + '_vogue_nocache='
      + (new Date()).getTime();
    $(stylesheets[href]).attr('href', newHref);
  }

  function getLocalStylesheets() {
    var links = $('link[type=text/css][href]').filter(isLocal);
    var origin = document.location.protocol + '//' + document.location.host;
    var stylesheets = {};
    links.each(function() {
      var href = this.href.substr(origin.length)
      stylesheets[href] = this;
    });
    return stylesheets;

    function isLocal() {
      var href = $(this).attr('href');
      return !href.match(/^https?:/);
    }
  }
}

function loadScripts(scripts, loadedCallback) {
  var srcs = [];
  for (var property in scripts) {
    if (!(property in window)) srcs.push(scripts[property]);
  }

  var count = srcs.length;
  if (count == 0) loadedCallback();
  for (var i = 0; i < srcs.length; i++) {
    var src = srcs[i];
    loadScript(src, function() {
      count--;
      if (count == 0) loadedCallback();
    });
  }
}

function loadScript(src, loadedCallback) {
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.setAttribute('src', src);
  script.onload = loadedCallback; // Chrome
  script.onreadystatechange = function () { // IE?
    if (this.readyState == 'complete' || this.readyState == 'loaded') loadedCallback();
  }
  document.getElementsByTagName('head')[0].appendChild(script);
}

})();
<commit_msg>Set full URL for socket.io SWF shim.<commit_after>// Vogue - Client
// Copyright (c) 2011 Andrew Davey (andrew@equin.co.uk)
//
// Note that all occurances of {port} in this script will be replaced with the port of the
// HTTP server hosted by Node.

(function() {

loadScripts({
  jQuery: 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js',
  io: 'http://localhost:{port}/socket.io/socket.io.js'
}, vogue);

function vogue() {
  var stylesheets = getLocalStylesheets();
  WEB_SOCKET_SWF_LOCATION = 'http://localhost:{port}/socket.io/lib/vendor/web-socket-js/WebSocketMain.swf';
  var socket = new io.Socket('localhost', { port: {port} });
  socket.on('connect', watchAllStylesheets);
  socket.on('message', handleMessage);
  socket.connect();

  function watchAllStylesheets() {
    var origin = document.location.protocol + '//' + document.location.host;
    var skipPrefixLength = origin.length;
    for (var href in stylesheets) {
      // linkElement.href is resolved by the browser to the full URL.
      // (unlike reading the actual attribute value.)
      // Very handy; we can easily get the full path segment of the URL
      // by skipping the current document's location origin length.
      var path = stylesheets[href].href.substr(skipPrefixLength);
      socket.send('watch ' + path);
    }
  }

  function handleMessage(message) {
    var match = message.match(/^update (.*)$/);
    if (match) {
      var href = match[1];
      reloadStylesheet(href);
    }
  }

  function reloadStylesheet(href) {
    var newHref = href
      + (href.indexOf('?') >= 0 ? '&' : '?')
      + '_vogue_nocache='
      + (new Date()).getTime();
    $(stylesheets[href]).attr('href', newHref);
  }

  function getLocalStylesheets() {
    var links = $('link[type=text/css][href]').filter(isLocal);
    var origin = document.location.protocol + '//' + document.location.host;
    var stylesheets = {};
    links.each(function() {
      var href = this.href.substr(origin.length)
      stylesheets[href] = this;
    });
    return stylesheets;

    function isLocal() {
      var href = $(this).attr('href');
      return !href.match(/^https?:/);
    }
  }
}

function loadScripts(scripts, loadedCallback) {
  var srcs = [];
  for (var property in scripts) {
    if (!(property in window)) srcs.push(scripts[property]);
  }

  var count = srcs.length;
  if (count == 0) loadedCallback();
  for (var i = 0; i < srcs.length; i++) {
    var src = srcs[i];
    loadScript(src, function() {
      count--;
      if (count == 0) loadedCallback();
    });
  }
}

function loadScript(src, loadedCallback) {
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.setAttribute('src', src);
  script.onload = loadedCallback; // Chrome
  script.onreadystatechange = function () { // IE?
    if (this.readyState == 'complete' || this.readyState == 'loaded') loadedCallback();
  }
  document.getElementsByTagName('head')[0].appendChild(script);
}

})();
<|endoftext|>


<commit_before>/*global define, $j, psData*/

define(['service', 'underscore', 'config'], function (service, _, config) {
    'use strict';
    return {
        main: function () {
            this.loadContacts();
        },

        /**
         *
         * @param contacts {Array}
         * @param stagingContacts {Array}
         */
        getArrayOfContactIds: function (contacts, stagingContacts) {
            var contactTableName = contacts.name.toLowerCase();
            var stagingContactsTableName = stagingContacts.name.toLowerCase();
            var allContacts = contacts;
            allContacts.concat(stagingContacts);
            var contactIds = [];
            _.each(allContacts, function(contact) {

            });
        },

        /**
         * @param stagingContacts {Object}
         * @param contactId {String}
         * @private
         * @returns {Object|Boolean}
         */
        _getStagingContactById: function (stagingContacts, contactId) {
            var contactsStagingTableName = config.studentContactsStagingTable.toLowerCase();
            var idMatches = _.filter(stagingContacts, function(contact) {
                return contact.tables[contactsStagingTableName].contact_id === contactId;
            });
            if (idMatches.length === 1) {
                return idMatches[0];
            } else {
                return false;
            }
        },

        loadContacts: function () {
            var options = {
                studentsdcid: psData.studentfrn.slice(3)
            };
            var parGuarContactsAjax = service.getParGuars(options);
            var parGuarContactsStagingAjax = service.getParGuarsStaging(options);

            var emergContactsAjax = service.getEmergConts(options);
            var emergContactsStagingAjax = service.getEmergContsStaging(options);

            var deferredObjects = [];
            deferredObjects.push(parGuarContactsAjax);
            deferredObjects.push(parGuarContactsStagingAjax);
            deferredObjects.push(emergContactsAjax);
            deferredObjects.push(emergContactsStagingAjax);
            var _this = this;
            $j.when.apply($j, deferredObjects).done(function (parGuarContacts, parGuarContactsStaging, emergContacts, emergContactsStaging) {
                var contactsTableName = parGuarContacts[0].name.toLowerCase();
                var contactsStagingTableName = parGuarContactsStaging[0].name.toLowerCase();

                var parGuarContactRecords = parGuarContacts[0].record;
                var parGuarContactStagingRecords = parGuarContactsStaging[0].record;

                var emergContactRecords = emergContacts[0].record;
                var emergContactStagingRecords = emergContactsStaging[0].record;
                $j.each(parGuarContactRecords, function (index, contact) {
                    var contactId = contact.tables[contactsTableName].contact_id;
                    var stagingContact = _this._getStagingContactById(parGuarContactStagingRecords, contactId);
                    var contactData;
                    if (stagingContact) {
                        contactData = stagingContact.tables[contactsStagingTableName];
                        _this.renderContact(contactData, null, true, true);
                    } else {
                        contactData = contact.tables[contactsTableName];
                        _this.renderContact(contactData, null, false, false);
                    }
                });

                $j.each(emergContactRecords, function (index, contact) {
                    var contactId = contact.tables[contactsTableName].contact_id;
                    var stagingContact = _this._getStagingContactById(emergContactStagingRecords, contactId);
                    var contactData;
                    if (stagingContact) {
                        contactData = stagingContact.tables[contactsStagingTableName];
                        _this.renderContact(contactData, null, true, false);
                    } else {
                        contactData = contact.tables[contactsTableName];
                        _this.renderContact(contactData, null, false, false);
                    }
                });
            });
        },

        /**
         * @param contactData {Object}
         * @param [row] {jQuery} - Row that will have its content replaced with the contact template.
         * Leaving this param empty will insert the row at the end of the table.
         * @param [showUpdateMsg] {Boolean} - If true, prepend the updated contact information.
         * @param isParGuar {Boolean} - Which contacts table should this contact be rendered into?
         */
        renderContact: function (contactData, row, showUpdateMsg, isParGuar) {
            var contactTemplate = $j('#contact-template').html();
            var renderedTemplate = _.template(contactTemplate, {'contact': contactData});
            var rowSelector;

            if (!row) {
                row = $j('
' + renderedTemplate + '
');
                if (isParGuar) {
                    $j('#parents-guardians-table tbody').append(row);
                } else {
                    $j('#emergency-contacts-table tbody').append(row);
                }
            } else {
                row.html('').html(renderedTemplate);
            }

            var prevElem = row.prev();
            if (prevElem) {
                var prevClass = prevElem.attr('class');
            }
            if (showUpdateMsg && prevClass !== 'contact-update-msg') {
                var updatedTemplate = $j($j('#contact-updated-template').html());
                updatedTemplate.insertBefore(row);
            }
            //var newRow = $j('#parents-guardians-table tr').last();
            row.data({'contactData': contactData});
        },

        /**
         *
         * @param contactData {Object}
         * @param row {jQuery}
         */
        editContact: function (contactData, row, isParGuar) {
            var numSelector = isParGuar ? '#parents-guardians-table' : '#emergency-contacts-table';
            var numOfContacts = $j(numSelector).find('tr').not('.inforow').length;
            var editContactTemplate = $j('#edit-contact-template').html();
            var context = {
                'numOfContacts': numOfContacts,
                'contact': contactData
            };
            var renderedTemplate = _.template(editContactTemplate, context);
            $j(row).html('').html(renderedTemplate);

            // Set the correct option in the priority dropdown to be selected.
            _.each($j('#priority option'), function (option) {
                var $option = $j(option);
                if ($option.val() === contactData.priority) {
                    $option.attr({'selected': 'selected'});
                }
            });

            // Set the correct option in the relationship dropdown to be selected.
            _.each($j('#relationship option'), function (option) {
                var $option = $j(option);
                if ($option.val() === contactData.relationship) {
                    $option.attr({'selected': 'selected'});
                }
            });

            // Set the correct option in the residence state drop down to be selected.
            _.each($j('#residence-state option'), function (option) {
                var $option = $j(option);
                if ($option.val() === contactData.relationship) {
                    $option.attr({'selected': 'selected'});
                }
            });

            // Set the correct option in the mailing state drop down to be selected.
            _.each($j('#mailing-state option'), function (option) {
                var $option = $j(option);
                if ($option.val() === contactData.relationship) {
                    $option.attr({'selected': 'selected'});
                }
            });
        },

        /**
         * Create an object with the data in the edit contact form
         * @param row {jQuery}
         */
        deserializeContact: function (row) {
            return {
                email: row.find('#email').val(),
                employer: row.find('#employer').val(),
                first_name: row.find('#first-name').val(),
                last_name: row.find('#last-name').val(),
                mailing_city: row.find('#mailing-city').val(),
                mailing_state: row.find('#mailing-state').val(),
                mailing_street: row.find('#mailing-street').val(),
                mailing_zip: row.find('#mailing-zip').val(),
                phone1: row.find('#phone1').val(),
                phone1type: row.find('#phone1type').val(),
                phone2: row.find('#phone2').val(),
                phone2type: row.find('#phone2type').val(),
                phone3: row.find('#phone1').val(),
                phone3type: row.find('#phone3type').val(),
                priority: row.find('#priority').val(),
                relationship: row.find('#relationship').val(),
                residence_city: row.find('#residence-city').val(),
                residence_state: row.find('#residence-state').val(),
                residence_street: row.find('#residence-street').val(),
                residence_zip: row.find('#residence-zip').val()
            };
        },

        addContact: function(row, isParGuar) {
            var numSelector = isParGuar ? '#parents-guardians-table' : '#emergency-contacts-table';
            var numOfContacts = $j(numSelector).find('tr').not('.inforow').length;
            var newContactTemplate = $j('#new-contact-template').html();
            var renderedTemplate = _.template(newContactTemplate, {numOfContacts: numOfContacts});
            $j(row).html('').html(renderedTemplate);
        },

        /**
         * @param contactData {Object}
         * @param contactRecordId {Number} Back-end id of the contact that is being edited
         */
        updateStagingContact: function (contactData, contactRecordId) {
            var studentContactsStagingTable = config.studentContactsStagingTable;
            var requestObj = {
                name: config.studentContactsStagingTable,
                tables: {}
            };
            requestObj.tables[studentContactsStagingTable] = contactData;
            var jsonContactData = JSON.stringify(requestObj);
            return service.updateStagingContact(jsonContactData, contactRecordId);
        },

        /**
         *
         * @param contactData {Object}
         * @param studentsDcid {Number}
         * @param legalGuardian {Boolean}
         * @param contactId {String}
         */
        newStagingContact: function (contactData, studentsDcid, legalGuardian, contactId) {
            contactData.legal_guardian = legalGuardian ? "1" : "0";
            contactData.studentsdcid = studentsDcid;
            contactData.contact_id = contactId;
            var studentContactsStagingTable = config.studentContactsStagingTable;
            var requestObj = {
                tables: {}
            };
            requestObj.tables[studentContactsStagingTable] = contactData;
            var jsonContactData = JSON.stringify(requestObj);
            return service.newStagingContact(jsonContactData);
        }
    };
});<commit_msg>Added dynamic priority option generation when displaying the add/edit contact form<commit_after>/*global define, $j, psData*/

define(['service', 'underscore', 'config'], function (service, _, config) {
    'use strict';
    return {
        main: function () {
            this.loadContacts();
        },

        /**
         * @param stagingContacts {Object}
         * @param contactId {String}
         * @private
         * @returns {Object|Boolean}
         */
        _getStagingContactById: function (stagingContacts, contactId) {
            var contactsStagingTableName = config.studentContactsStagingTable.toLowerCase();
            var idMatches = _.filter(stagingContacts, function(contact) {
                return contact.tables[contactsStagingTableName].contact_id === contactId;
            });
            if (idMatches.length === 1) {
                return idMatches[0];
            } else {
                return false;
            }
        },

        _addRowColorClasses: function () {
            var oddRows = $j('tr.contact:odd');
            oddRows.addClass('oddRow');
            _.each(oddRows, function (row) {
                var $row = $j(row);
                if ($row.prev().attr('class') === 'contact-update-msg') {
                    $row.prev().addClass('oddRow');
                }
            });
        },

        /**
         * @return {Array}
         */
        loadContacts: function () {
            this.contacts = {};
            this.contacts.live = [];
            this.contacts.staging = [];

            var options = {
                studentsdcid: psData.studentfrn.slice(3)
            };
            var parGuarContactsAjax = service.getParGuars(options);
            var parGuarContactsStagingAjax = service.getParGuarsStaging(options);

            var emergContactsAjax = service.getEmergConts(options);
            var emergContactsStagingAjax = service.getEmergContsStaging(options);

            var deferredObjects = [];
            deferredObjects.push(parGuarContactsAjax);
            deferredObjects.push(parGuarContactsStagingAjax);
            deferredObjects.push(emergContactsAjax);
            deferredObjects.push(emergContactsStagingAjax);
            var _this = this;
            $j.when.apply($j, deferredObjects).done(function (parGuarContacts, parGuarContactsStaging, emergContacts, emergContactsStaging) {

                // This probably doesn't need to be separated by parGuar/emerg contact.
                // In the future, separate this just by staging/live table.
                var contactsTableName = parGuarContacts[0].name.toLowerCase();
                var contactsStagingTableName = parGuarContactsStaging[0].name.toLowerCase();

                var parGuarContactRecords = parGuarContacts[0].record;
                var parGuarContactStagingRecords = parGuarContactsStaging[0].record;

                var emergContactRecords = emergContacts[0].record;
                var emergContactStagingRecords = emergContactsStaging[0].record;

                $j.each(parGuarContactRecords, function (index, contact) {
                    var contactId = contact.tables[contactsTableName].contact_id;
                    _this.contacts.live.push(contact.tables[contactsTableName]);
                    var stagingContact = _this._getStagingContactById(parGuarContactStagingRecords, contactId);
                    var contactData;
                    if (stagingContact) {
                        contactData = stagingContact.tables[contactsStagingTableName];
                        _this.renderContact(contactData, null, true, true);
                    } else {
                        contactData = contact.tables[contactsTableName];
                        _this.renderContact(contactData, null, false, true);
                    }
                });

                $j.each(emergContactRecords, function (index, contact) {
                    var contactId = contact.tables[contactsTableName].contact_id;
                    _this.contacts.live.push(contact.tables[contactsTableName]);
                    var stagingContact = _this._getStagingContactById(emergContactStagingRecords, contactId);
                    var contactData;
                    if (stagingContact) {
                        contactData = stagingContact.tables[contactsStagingTableName];
                        _this.renderContact(contactData, null, true, false);
                    } else {
                        contactData = contact.tables[contactsTableName];
                        _this.renderContact(contactData, null, false, false);
                    }
                });

                // Look for new staging records that have no corresponding live records
                $j.each(emergContactStagingRecords, function (index, contact) {
                    var contactId = contact.tables[contactsStagingTableName].contact_id;

                    // Does this staging record have a corresponding live-table record?
                    var stagingHasLive = _.filter(_this.contacts.live, function (liveContact) {
                        return liveContact.contact_id === contactId;
                    });

                    // If there were no matches, this is a new contact that is still in the staging table
                    if (stagingHasLive.length === 0) {
                        var contactData = contact.tables[contactsStagingTableName];
                        _this.renderContact(contactData, null, true, false);
                    }
                });

                $j.each(parGuarContactStagingRecords, function (index, contact) {
                    _this.contacts.staging.push(contact.tables[contactsStagingTableName]);
                });

                $j.each(emergContactStagingRecords, function (index, contact) {
                    _this.contacts.staging.push(contact.tables[contactsStagingTableName]);
                });

                _this._addRowColorClasses();
            });
        },

        /**
         * @param contactData {Object}
         * @param [row] {jQuery} - Row that will have its content replaced with the contact template.
         * Leaving this param empty will insert the row at the end of the table.
         * @param [showUpdateMsg] {Boolean} - If true, prepend the updated contact information.
         * @param isParGuar {Boolean} - Which contacts table should this contact be rendered into?
         */
        renderContact: function (contactData, row, showUpdateMsg, isParGuar) {
            var contactTemplate = $j('#contact-template').html();
            var renderedTemplate = _.template(contactTemplate, {'contact': contactData});

            if (!row) {
                row = $j('
' + renderedTemplate + '
');
                if (isParGuar) {
                    $j('#parents-guardians-table tbody').append(row);
                } else {
                    $j('#emergency-contacts-table tbody').append(row);
                }
            } else {
                row.html('').html(renderedTemplate);
            }

            var prevElem = row.prev();
            if (prevElem) {
                var prevClass = prevElem.attr('class');
            }
            if (showUpdateMsg && prevClass.indexOf('contact-update-msg') === -1) {
                var updatedTemplate = $j($j('#contact-updated-template').html());
                updatedTemplate.insertBefore(row);
            }
            //var newRow = $j('#parents-guardians-table tr').last();
            row.data({'contactData': contactData});
        },

        /**
         *
         * @param contactData {Object}
         * @param row {jQuery}
         */
        editContact: function (contactData, row, isParGuar) {
            var numSelector = isParGuar ? '#parents-guardians-table' : '#emergency-contacts-table';
            var numOfContacts = $j(numSelector).find('tr').not('.inforow').length;
            var editContactTemplate = $j('#edit-contact-template').html();
            var context = {
                'numOfContacts': numOfContacts,
                'contact': contactData
            };
            var renderedTemplate = _.template(editContactTemplate, context);
            $j(row).html('').html(renderedTemplate);

            // Set the correct option in the priority dropdown to be selected.
            _.each($j('#priority option'), function (option) {
                var $option = $j(option);
                if ($option.val() === contactData.priority) {
                    $option.attr({'selected': 'selected'});
                }
            });

            // Set the correct option in the relationship dropdown to be selected.
            _.each($j('#relationship option'), function (option) {
                var $option = $j(option);
                if ($option.val() === contactData.relationship) {
                    $option.attr({'selected': 'selected'});
                }
            });

            // Set the correct option in the residence state drop down to be selected.
            _.each($j('#residence-state option'), function (option) {
                var $option = $j(option);
                if ($option.val() === contactData.relationship) {
                    $option.attr({'selected': 'selected'});
                }
            });

            // Set the correct option in the mailing state drop down to be selected.
            _.each($j('#mailing-state option'), function (option) {
                var $option = $j(option);
                if ($option.val() === contactData.relationship) {
                    $option.attr({'selected': 'selected'});
                }
            });
        },

        /**
         * Create an object with the data in the edit contact form
         * @param row {jQuery}
         */
        deserializeContact: function (row) {
            return {
                email: row.find('#email').val(),
                employer: row.find('#employer').val(),
                first_name: row.find('#first-name').val(),
                last_name: row.find('#last-name').val(),
                mailing_city: row.find('#mailing-city').val(),
                mailing_state: row.find('#mailing-state').val(),
                mailing_street: row.find('#mailing-street').val(),
                mailing_zip: row.find('#mailing-zip').val(),
                phone1: row.find('#phone1').val(),
                phone1type: row.find('#phone1type').val(),
                phone2: row.find('#phone2').val(),
                phone2type: row.find('#phone2type').val(),
                phone3: row.find('#phone1').val(),
                phone3type: row.find('#phone3type').val(),
                priority: row.find('#priority').val(),
                relationship: row.find('#relationship').val(),
                residence_city: row.find('#residence-city').val(),
                residence_state: row.find('#residence-state').val(),
                residence_street: row.find('#residence-street').val(),
                residence_zip: row.find('#residence-zip').val()
            };
        },

        addContact: function(row, isParGuar, allPriorities) {
            var numSelector = isParGuar ? '#parents-guardians-table' : '#emergency-contacts-table';

            // Add 1 to the length to account for the new contact
            var numOfContacts = $j(numSelector).find('tr').not('.inforow').length + 1;

            // Add 1 to stop int so the last number is included in the array.
            var numRange = _.range(1, numOfContacts + 1);
            var unusedPriorities = _.difference(numRange, allPriorities);
            var newContactTemplate = $j('#new-contact-template').html();
            var renderedTemplate = _.template(newContactTemplate, {unusedPriorities: unusedPriorities});
            $j(row).html('').html(renderedTemplate);
        },

        /**
         * @param contactData {Object}
         * @param contactRecordId {Number} Back-end id of the contact that is being edited
         */
        updateStagingContact: function (contactData, contactRecordId) {
            var studentContactsStagingTable = config.studentContactsStagingTable;
            var requestObj = {
                name: config.studentContactsStagingTable,
                tables: {}
            };
            requestObj.tables[studentContactsStagingTable] = contactData;
            var jsonContactData = JSON.stringify(requestObj);
            return service.updateStagingContact(jsonContactData, contactRecordId);
        },

        /**
         *
         * @param contactData {Object}
         * @param studentsDcid {Number}
         * @param legalGuardian {Boolean}
         * @param contactId {String}
         */
        newStagingContact: function (contactData, studentsDcid, legalGuardian, contactId) {
            contactData.legal_guardian = legalGuardian ? "1" : "0";
            contactData.studentsdcid = studentsDcid;
            contactData.contact_id = contactId;
            var studentContactsStagingTable = config.studentContactsStagingTable;
            var requestObj = {
                tables: {}
            };
            requestObj.tables[studentContactsStagingTable] = contactData;
            var jsonContactData = JSON.stringify(requestObj);
            return service.newStagingContact(jsonContactData);
        }
    };
});<|endoftext|>


<commit_before>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

define([
    'angular',
    'lodash',
    'liveblog-edit/unread.posts.service',
    'ng-sir-trevor',
    'ng-sir-trevor-blocks',
    'angular-embed'
], function(angular, _) {
    'use strict';
    var BlogSettingsController = function($scope, blog, api, blogService, $location, notify,
        gettext, modal, $q, upload, datetimeHelper, moment, config, blogSecurityService) {

        // set view's model
        var vm = this;

        angular.extend(vm, {
            mailto: 'mail:upgrade@liveblog.pro?subject='+
                encodeURIComponent(location.hostname) +
                ' ' +
                config.subscriptionLevel,
            blog: blog,
            newBlog: angular.copy(blog),
            deactivateTheme: (config.subscriptionLevel == 'solo') ? true : false,
            blogPreferences: angular.copy(blog.blog_preferences),
            availableLanguages: [],
            original_creator: {},
            availableThemes: [],
            availableCategories: [
                '',
                'Breaking News',
                'Entertainment',
                'Business and Finance',
                'Sport',
                'Technology'
            ],
            //used as an aux var to be able to change members and safely cancel the changes
            blogMembers: [],
            //users to remove from the pending queue once the changes are saved
            acceptedMembers: [],
            memberRequests: [],
            //concat of blogMembers and membership requested members
            posibleMembers: [],
            isSaved: true,
            editTeamModal: false,
            forms: {},
            preview: {},
            progress: {width: 0},
            tab: false,
            // by default themes are not accepting embed multi height and code.
            embedMultiHight: false,
            userNotInMembers:function(user) {
                for (var i = 0; i < vm.members.length; i ++) {
                    if (user._id === vm.members[i]._id) {
                        return false;
                    }
                }
                return true;
            },
            openUploadModal: function() {
                vm.uploadModal = true;
            },
            closeUploadModal: function() {
                vm.uploadModal = false;
                vm.preview = {};
                vm.progress = {width: 0};
            },
            changeTab: function(tab) {
                if (vm.tab) {
                    vm.forms.dirty = vm.forms.dirty || vm.forms[vm.tab].$dirty;
                }
                vm.tab = tab;
            },
            setFormsPristine: function() {
                if (vm.forms.dirty) {
                    vm.forms.dirty = false;
                }
                angular.forEach(vm.forms, function(value, key) {
                    if (vm.forms[key] && vm.forms[key].$dirty) {
                        vm.forms[key].$setPristine();
                    }
                });
            },
            removeImage: function() {
                modal.confirm(gettext('Are you sure you want to remove the blog image?')).then(function() {
                    deregisterPreventer();
                    vm.newBlog.picture_url = null;
                    vm.forms.dirty = true;
                });
            },
            upload: function(config) {
                var form = {};
                if (config.img) {
                    form.media = config.img;
                } else if (config.url) {
                    form.URL = config.url;
                } else {
                    return;
                }
                // return a promise of upload which will call the success/error callback
                return api.archive.getUrl().then(function(url) {
                    return upload.start({
                        method: 'POST',
                        url: url,
                        data: form
                    })
                    .then(function(response) {
                        if (response.data._status === 'ERR'){
                            return;
                        }
                        var picture_url = response.data.renditions.viewImage.href;
                        vm.newBlog.picture_url = picture_url;
                        vm.newBlog.picture = response.data._id;
                        vm.uploadModal = false;
                        vm.preview = {};
                        vm.progress = {width: 0};
                        vm.forms.dirty = true;
                    }, null, function(progress) {
                        vm.progress.width = Math.round(progress.loaded / progress.total * 100.0);
                    });
                });
            },
            saveAndClose: function() {
                vm.save().then(function() {
                    vm.close();
                });
            },
            editTeam: function() {
                vm.blogMembers = _.clone(vm.members);
                vm.posibleMembers = vm.blogMembers.concat(vm.memberRequests);
                //close the change owner dropdown if open
                if (vm.openOwner === true) {
                    vm.openOwner = false;
                }
                vm.editTeamModal = true;
            },
            cancelTeamEdit: function() {
                vm.editTeamModal = false;
            },
            doneTeamEdit: function() {
                vm.members = _.clone(vm.blogMembers);
                vm.forms.dirty = true;
                vm.cancelTeamEdit();
            },
            addMember: function(user) {
                vm.blogMembers.push(user);
            },
            acceptMember: function(user) {
                vm.members.push(user);
                vm.forms.dirty = true;
                vm.memberRequests.splice(vm.memberRequests.indexOf(user), 1);
                vm.acceptedMembers.push(user);
            },
            hasReachedMembersLimit: function() {
              if (!config.assignableUsers.hasOwnProperty(config.subscriptionLevel))
                return false;

              return vm.blogMembers.length >= config.assignableUsers[config.subscriptionLevel];
            },
            removeMember: function(user) {
                vm.blogMembers.splice(vm.blogMembers.indexOf(user), 1);
            },
            save: function() {
                // save on backend
                var deferred = $q.defer();
                var members = _.map(vm.members, function(member) {
                    return ({user: member._id});
                });
                notify.info(gettext('saving blog settings'));
                var changedBlog = {
                    blog_preferences: vm.blogPreferences,
                    original_creator: vm.original_creator._id,
                    blog_status: vm.blog_switch === true? 'open': 'closed',
                    syndication_enabled: vm.syndication_enabled,
                    market_enabled: vm.market_enabled,
                    category: vm.category,
                    start_date: datetimeHelper.mergeDateTime(vm.start_date, vm.start_time),
                    members: members
                };
                angular.extend(vm.newBlog, changedBlog);
                delete vm.newBlog._latest_version;
                delete vm.newBlog._current_version;
                delete vm.newBlog._version;
                delete vm.newBlog.marked_for_not_publication;
                blogService.update(vm.blog, vm.newBlog).then(function(blog) {
                    vm.isSaved = true;
                    vm.blog = blog;
                    vm.newBlog = angular.copy(blog);
                    vm.blogPreferences = angular.copy(blog.blog_preferences);
                    //remove accepted users from the queue
                    if (vm.acceptedMembers.length) {
                        _.each(vm.acceptedMembers, function(member) {
                            api('request_membership').getById(member.request_id).then(function(item) {
                                api('request_membership').remove(item).then(function() {}, function() {
                                    notify.pop();
                                    notify.error(gettext('Something went wrong'));
                                    deferred.reject();
                                });
                            });
                        });
                    }
                    notify.pop();
                    notify.info(gettext('blog settings saved'));
                    vm.setFormsPristine();
                    deferred.resolve();
                });
                return deferred.promise;
            },
            askRemoveBlog: function() {
                modal.confirm(gettext('Are you sure you want to delete the blog?'))
                .then(function() {
                    vm.removeBlog();
                });
            },
            removeBlog: function() {
                api.blogs.remove(angular.copy(vm.blog)).then(function(message) {
                    notify.pop();
                    notify.info(gettext('Blog removed'));
                    $location.path('/liveblog');
                }, function () {
                    notify.pop();
                    notify.error(gettext('Something went wrong'));
                    $location.path('/liveblog/edit/' + vm.blog._id);
                    });
            },
            close: function() {
                // return to blog edit page
                $location.path('/liveblog/edit/' + vm.blog._id);
            },
            buildOwner: function(userID) {
                api('users').getById(userID).then(function(data) {
                    //temp_selected_owner is used handle the selection of users in the change owner autocomplete box
                    //without automatically changing the owner that is displayed
                    vm.temp_selected_owner = vm.original_creator = data;
                });
            },
            getUsers: function(details, ids) {
                _.each(ids, function(user) {
                    api('users').getById(user.user).then(function(data) {
                        if (user.request_id) {
                            data.request_id = user.request_id;
                        }
                        details.push(data);
                    });
                });
            }

        });
        // retieve the blog's public url
        var qPublicUrl = blogService.getPublicUrl(blog).then(function(url) {
            vm.publicUrl = url;
        });
        // load available languages
        api('languages').query().then(function(data) {
            vm.availableLanguages = data._items;
        });
        // load available themes
        var qTheme = api('themes').query().then(function(data) {
            // filter theme with label (without label are `generic` from inheritance)
            vm.angularTheme = data._items.find(function(theme) {return theme.name == 'angular'});
            vm.availableThemes = data._items.filter(function(theme) {return !theme['abstract'];});
            vm.selectedTheme = _.find(vm.availableThemes, function(theme) {
                return theme.name === vm.blogPreferences.theme;
            });
        });

        // after publicUrl and theme is on `vm` object we can compute embeds code.
        $q.all([qPublicUrl, qTheme]).then(function() {
            vm.embedMultiHight = true;
            // devel link
            var parentIframe = 'http://localhost:5000/themes_assets/angular/';
            if (vm.angularTheme.public_url) {
                // production link
                parentIframe = vm.angularTheme.public_url.replace(/\/[0-9\.]+\/themes_assets\//, '/themes_assets/');
            }
            // loading mechanism, and load parent-iframe.js with callback.
            var loadingScript = '';
            // compute embeds code with the injected publicUrl
            vm.embeds = {
                normal: '',
                resizeing: loadingScript + ''
            };
        });

        api('users').getById(blog.original_creator).then(function(data) {
            vm.original_creator = data;
        });
        api('users').query().then(function(data) {
            vm.avUsers = data._items;
        });
        vm.buildOwner(blog.original_creator);

        //get details for the users that have requested blog membership
        vm.memberRequests = [];
        api('blogs/<regex("[a-f0-9]{24}"):blog_id>/request_membership', {_id: vm.blog._id}).query().then(function(data) {
            vm.getUsers(vm.memberRequests, _.map(data._items, function(request) {
                return {user: request.original_creator, request_id: request._id};
            }));
        });

        //get team members details
        vm.members = [];
        vm.getUsers(vm.members, blog.members);

        //check if form is dirty before leaving the page
        var deregisterPreventer = $scope.$on('$locationChangeStart', routeChange);
        function routeChange (event, next, current) {
            //check if one of the forms is dirty
            var dirty = false;
            if (vm.forms.dirty) {
                dirty = true;
            } else {
                angular.forEach(vm.forms, function(value, key) {
                    if (vm.forms[key] && vm.forms[key].$dirty) {
                        dirty = true;
                        return;
                    }
                });
            }
            if (dirty) {
                event.preventDefault();
                modal.confirm(gettext('You have unsaved settings. Are you sure you want to leave the page?')).then(function() {
                    deregisterPreventer();
                    $location.url($location.url(next).hash());
                });
            }
        }

        var splitDate = moment.tz(vm.newBlog.start_date, config.defaultTimezone);
        vm.start_date = splitDate.format();
        vm.start_time = splitDate.format(config.model.timeformat);

        vm.changeTab('general');
        vm.blog_switch = vm.newBlog.blog_status === 'open'? true: false;
        vm.syndication_enabled = vm.newBlog.syndication_enabled;
        vm.market_enabled = vm.newBlog.market_enabled;
        vm.category = vm.newBlog.category;

        // Deactivate status input, when too many blogs are active
        blogSecurityService.showUpgradeModal().then(function(showUpgradeModal) {
            vm.deactivateStatus = vm.blog_switch ? false : showUpgradeModal;
        });

    }

    BlogSettingsController.$inject = [
        '$scope',
        'blog',
        'api',
        'blogService',
        '$location',
        'notify',
        'gettext',
        'modal',
        '$q',
        'upload',
        'datetimeHelper',
        'moment',
        'config',
        'blogSecurityService'
    ];

    return BlogSettingsController;
});
<commit_msg>Does not instantiate blogs with invalid dates<commit_after>/**
 * This file is part of Superdesk.
 *
 * Copyright 2013, 2014 Sourcefabric z.u. and contributors.
 *
 * For the full copyright and license information, please see the
 * AUTHORS and LICENSE files distributed with this source code, or
 * at https://www.sourcefabric.org/superdesk/license
 */

define([
    'angular',
    'lodash',
    'liveblog-edit/unread.posts.service',
    'ng-sir-trevor',
    'ng-sir-trevor-blocks',
    'angular-embed'
], function(angular, _) {
    'use strict';
    var BlogSettingsController = function($scope, blog, api, blogService, $location, notify,
        gettext, modal, $q, upload, datetimeHelper, moment, config, blogSecurityService) {

        // set view's model
        var vm = this;

        angular.extend(vm, {
            mailto: 'mail:upgrade@liveblog.pro?subject='+
                encodeURIComponent(location.hostname) +
                ' ' +
                config.subscriptionLevel,
            blog: blog,
            newBlog: angular.copy(blog),
            deactivateTheme: (config.subscriptionLevel == 'solo') ? true : false,
            blogPreferences: angular.copy(blog.blog_preferences),
            availableLanguages: [],
            original_creator: {},
            availableThemes: [],
            availableCategories: [
                '',
                'Breaking News',
                'Entertainment',
                'Business and Finance',
                'Sport',
                'Technology'
            ],
            //used as an aux var to be able to change members and safely cancel the changes
            blogMembers: [],
            //users to remove from the pending queue once the changes are saved
            acceptedMembers: [],
            memberRequests: [],
            //concat of blogMembers and membership requested members
            posibleMembers: [],
            isSaved: true,
            editTeamModal: false,
            forms: {},
            preview: {},
            progress: {width: 0},
            tab: false,
            // by default themes are not accepting embed multi height and code.
            embedMultiHight: false,
            userNotInMembers:function(user) {
                for (var i = 0; i < vm.members.length; i ++) {
                    if (user._id === vm.members[i]._id) {
                        return false;
                    }
                }
                return true;
            },
            openUploadModal: function() {
                vm.uploadModal = true;
            },
            closeUploadModal: function() {
                vm.uploadModal = false;
                vm.preview = {};
                vm.progress = {width: 0};
            },
            changeTab: function(tab) {
                if (vm.tab) {
                    vm.forms.dirty = vm.forms.dirty || vm.forms[vm.tab].$dirty;
                }
                vm.tab = tab;
            },
            setFormsPristine: function() {
                if (vm.forms.dirty) {
                    vm.forms.dirty = false;
                }
                angular.forEach(vm.forms, function(value, key) {
                    if (vm.forms[key] && vm.forms[key].$dirty) {
                        vm.forms[key].$setPristine();
                    }
                });
            },
            removeImage: function() {
                modal.confirm(gettext('Are you sure you want to remove the blog image?')).then(function() {
                    deregisterPreventer();
                    vm.newBlog.picture_url = null;
                    vm.forms.dirty = true;
                });
            },
            upload: function(config) {
                var form = {};
                if (config.img) {
                    form.media = config.img;
                } else if (config.url) {
                    form.URL = config.url;
                } else {
                    return;
                }
                // return a promise of upload which will call the success/error callback
                return api.archive.getUrl().then(function(url) {
                    return upload.start({
                        method: 'POST',
                        url: url,
                        data: form
                    })
                    .then(function(response) {
                        if (response.data._status === 'ERR'){
                            return;
                        }
                        var picture_url = response.data.renditions.viewImage.href;
                        vm.newBlog.picture_url = picture_url;
                        vm.newBlog.picture = response.data._id;
                        vm.uploadModal = false;
                        vm.preview = {};
                        vm.progress = {width: 0};
                        vm.forms.dirty = true;
                    }, null, function(progress) {
                        vm.progress.width = Math.round(progress.loaded / progress.total * 100.0);
                    });
                });
            },
            saveAndClose: function() {
                vm.save().then(function() {
                    vm.close();
                });
            },
            editTeam: function() {
                vm.blogMembers = _.clone(vm.members);
                vm.posibleMembers = vm.blogMembers.concat(vm.memberRequests);
                //close the change owner dropdown if open
                if (vm.openOwner === true) {
                    vm.openOwner = false;
                }
                vm.editTeamModal = true;
            },
            cancelTeamEdit: function() {
                vm.editTeamModal = false;
            },
            doneTeamEdit: function() {
                vm.members = _.clone(vm.blogMembers);
                vm.forms.dirty = true;
                vm.cancelTeamEdit();
            },
            addMember: function(user) {
                vm.blogMembers.push(user);
            },
            acceptMember: function(user) {
                vm.members.push(user);
                vm.forms.dirty = true;
                vm.memberRequests.splice(vm.memberRequests.indexOf(user), 1);
                vm.acceptedMembers.push(user);
            },
            hasReachedMembersLimit: function() {
              if (!config.assignableUsers.hasOwnProperty(config.subscriptionLevel))
                return false;

              return vm.blogMembers.length >= config.assignableUsers[config.subscriptionLevel];
            },
            removeMember: function(user) {
                vm.blogMembers.splice(vm.blogMembers.indexOf(user), 1);
            },
            save: function() {
                // save on backend
                var deferred = $q.defer();
                var members = _.map(vm.members, function(member) {
                    return ({user: member._id});
                });
                notify.info(gettext('saving blog settings'));
                var changedBlog = {
                    blog_preferences: vm.blogPreferences,
                    original_creator: vm.original_creator._id,
                    blog_status: vm.blog_switch === true? 'open': 'closed',
                    syndication_enabled: vm.syndication_enabled,
                    market_enabled: vm.market_enabled,
                    category: vm.category,
                    start_date: datetimeHelper.mergeDateTime(vm.start_date, vm.start_time),
                    members: members
                };
                angular.extend(vm.newBlog, changedBlog);
                delete vm.newBlog._latest_version;
                delete vm.newBlog._current_version;
                delete vm.newBlog._version;
                delete vm.newBlog.marked_for_not_publication;
                blogService.update(vm.blog, vm.newBlog).then(function(blog) {
                    vm.isSaved = true;
                    vm.blog = blog;
                    vm.newBlog = angular.copy(blog);
                    vm.blogPreferences = angular.copy(blog.blog_preferences);
                    //remove accepted users from the queue
                    if (vm.acceptedMembers.length) {
                        _.each(vm.acceptedMembers, function(member) {
                            api('request_membership').getById(member.request_id).then(function(item) {
                                api('request_membership').remove(item).then(function() {}, function() {
                                    notify.pop();
                                    notify.error(gettext('Something went wrong'));
                                    deferred.reject();
                                });
                            });
                        });
                    }
                    notify.pop();
                    notify.info(gettext('blog settings saved'));
                    vm.setFormsPristine();
                    deferred.resolve();
                });
                return deferred.promise;
            },
            askRemoveBlog: function() {
                modal.confirm(gettext('Are you sure you want to delete the blog?'))
                .then(function() {
                    vm.removeBlog();
                });
            },
            removeBlog: function() {
                api.blogs.remove(angular.copy(vm.blog)).then(function(message) {
                    notify.pop();
                    notify.info(gettext('Blog removed'));
                    $location.path('/liveblog');
                }, function () {
                    notify.pop();
                    notify.error(gettext('Something went wrong'));
                    $location.path('/liveblog/edit/' + vm.blog._id);
                    });
            },
            close: function() {
                // return to blog edit page
                $location.path('/liveblog/edit/' + vm.blog._id);
            },
            buildOwner: function(userID) {
                api('users').getById(userID).then(function(data) {
                    //temp_selected_owner is used handle the selection of users in the change owner autocomplete box
                    //without automatically changing the owner that is displayed
                    vm.temp_selected_owner = vm.original_creator = data;
                });
            },
            getUsers: function(details, ids) {
                _.each(ids, function(user) {
                    api('users').getById(user.user).then(function(data) {
                        if (user.request_id) {
                            data.request_id = user.request_id;
                        }
                        details.push(data);
                    });
                });
            }

        });
        // retieve the blog's public url
        var qPublicUrl = blogService.getPublicUrl(blog).then(function(url) {
            vm.publicUrl = url;
        });
        // load available languages
        api('languages').query().then(function(data) {
            vm.availableLanguages = data._items;
        });
        // load available themes
        var qTheme = api('themes').query().then(function(data) {
            // filter theme with label (without label are `generic` from inheritance)
            vm.angularTheme = data._items.find(function(theme) {return theme.name == 'angular'});
            vm.availableThemes = data._items.filter(function(theme) {return !theme['abstract'];});
            vm.selectedTheme = _.find(vm.availableThemes, function(theme) {
                return theme.name === vm.blogPreferences.theme;
            });
        });

        // after publicUrl and theme is on `vm` object we can compute embeds code.
        $q.all([qPublicUrl, qTheme]).then(function() {
            vm.embedMultiHight = true;
            // devel link
            var parentIframe = 'http://localhost:5000/themes_assets/angular/';
            if (vm.angularTheme.public_url) {
                // production link
                parentIframe = vm.angularTheme.public_url.replace(/\/[0-9\.]+\/themes_assets\//, '/themes_assets/');
            }
            // loading mechanism, and load parent-iframe.js with callback.
            var loadingScript = '';
            // compute embeds code with the injected publicUrl
            vm.embeds = {
                normal: '',
                resizeing: loadingScript + ''
            };
        });

        api('users').getById(blog.original_creator).then(function(data) {
            vm.original_creator = data;
        });
        api('users').query().then(function(data) {
            vm.avUsers = data._items;
        });
        vm.buildOwner(blog.original_creator);

        //get details for the users that have requested blog membership
        vm.memberRequests = [];
        api('blogs/<regex("[a-f0-9]{24}"):blog_id>/request_membership', {_id: vm.blog._id}).query().then(function(data) {
            vm.getUsers(vm.memberRequests, _.map(data._items, function(request) {
                return {user: request.original_creator, request_id: request._id};
            }));
        });

        //get team members details
        vm.members = [];
        vm.getUsers(vm.members, blog.members);

        //check if form is dirty before leaving the page
        var deregisterPreventer = $scope.$on('$locationChangeStart', routeChange);
        function routeChange (event, next, current) {
            //check if one of the forms is dirty
            var dirty = false;
            if (vm.forms.dirty) {
                dirty = true;
            } else {
                angular.forEach(vm.forms, function(value, key) {
                    if (vm.forms[key] && vm.forms[key].$dirty) {
                        dirty = true;
                        return;
                    }
                });
            }
            if (dirty) {
                event.preventDefault();
                modal.confirm(gettext('You have unsaved settings. Are you sure you want to leave the page?')).then(function() {
                    deregisterPreventer();
                    $location.url($location.url(next).hash());
                });
            }
        }

        if (vm.newBlog.start_date) {
            var splitDate = moment.tz(vm.newBlog.start_date, config.defaultTimezone);
            vm.start_date = splitDate.format();
            vm.start_time = splitDate.format(config.model.timeformat);
        }

        vm.changeTab('general');
        vm.blog_switch = vm.newBlog.blog_status === 'open'? true: false;
        vm.syndication_enabled = vm.newBlog.syndication_enabled;
        vm.market_enabled = vm.newBlog.market_enabled;
        vm.category = vm.newBlog.category;

        // Deactivate status input, when too many blogs are active
        blogSecurityService.showUpgradeModal().then(function(showUpgradeModal) {
            vm.deactivateStatus = vm.blog_switch ? false : showUpgradeModal;
        });

    }

    BlogSettingsController.$inject = [
        '$scope',
        'blog',
        'api',
        'blogService',
        '$location',
        'notify',
        'gettext',
        'modal',
        '$q',
        'upload',
        'datetimeHelper',
        'moment',
        'config',
        'blogSecurityService'
    ];

    return BlogSettingsController;
});
<|endoftext|>