<commit_before>import _ from 'underscore';
import s from 'underscore.string';

class ModelUsers extends RocketChat.models._Base {
	constructor() {
		super(...arguments);

		this.tryEnsureIndex({ 'roles': 1 }, { sparse: 1 });
		this.tryEnsureIndex({ 'name': 1 });
		this.tryEnsureIndex({ 'lastLogin': 1 });
		this.tryEnsureIndex({ 'status': 1 });
		this.tryEnsureIndex({ 'active': 1 }, { sparse: 1 });
		this.tryEnsureIndex({ 'statusConnection': 1 }, { sparse: 1 });
		this.tryEnsureIndex({ 'type': 1 });

		this.cache.ensureIndex('username', 'unique');
	}

	findOneByImportId(_id, options) {
		return this.findOne({ importIds: _id }, options);
	}

	findOneByUsername(username, options) {
		const query = {
			username: new RegExp(username, 'i')
		};

		return this.findOne(query, options);
	}

	findOneByEmailAddress(emailAddress, options) {
		const query =	{'emails.address': new RegExp(`^${ s.escapeRegExp(emailAddress) }$`, 'i')};

		return this.findOne(query, options);
	}

	findOneAdmin(admin, options) {
		const query =	{admin};

		return this.findOne(query, options);
	}

	findOneByIdAndLoginToken(_id, token, options) {
		const query = {
			_id,
			'services.resume.loginTokens.hashedToken' : Accounts._hashLoginToken(token)
		};

		return this.findOne(query, options);
	}

	// FIND
	findById(userId) {
		const query =	{_id: userId};

		return this.find(query);
	}

	findUsersNotOffline(options) {
		const query = {
			username: {
				$exists: 1
			},
			status: {
				$in: ['online', 'away', 'busy']
			}
		};

		return this.find(query, options);
	}

	findByUsername(username, options) {
		const query =	{username};

		return this.find(query, options);
	}

	findUsersByUsernamesWithHighlights(usernames, options) {
		if (this.useCache) {
			const result = {
				fetch() {
					return RocketChat.models.Users.getDynamicView('highlights').data().filter(record => usernames.indexOf(record.username) > -1);
				},
				count() {
					return result.fetch().length;
				},
				forEach(fn) {
					return result.fetch().forEach(fn);
				}
			};
			return result;
		}

		const query = {
			username: { $in: usernames },
			'settings.preferences.highlights.0': {
				$exists: true
			}
		};

		return this.find(query, options);
	}

	findActiveByUsernameOrNameRegexWithExceptions(searchTerm, exceptions, options) {
		if (exceptions == null) { exceptions = []; }
		if (options == null) { options = {}; }
		if (!_.isArray(exceptions)) {
			exceptions = [ exceptions ];
		}

		const termRegex = new RegExp(s.escapeRegExp(searchTerm), 'i');
		const query = {
			$or: [{
				username: termRegex
			}, {
				name: termRegex
			}],
			active: true,
			type: {
				$in: ['user', 'bot']
			},
			$and: [{
				username: {
					$exists: true
				}
			}, {
				username: {
					$nin: exceptions
				}
			}]
		};

		return this.find(query, options);
	}

	findByActiveUsersExcept(searchTerm, exceptions, options) {
		if (exceptions == null) { exceptions = []; }
		if (options == null) { options = {}; }
		if (!_.isArray(exceptions)) {
			exceptions = [ exceptions ];
		}

		const termRegex = new RegExp(s.escapeRegExp(searchTerm), 'i');

		const orStmt = _.reduce(RocketChat.settings.get('Accounts_SearchFields').trim().split(','), function(acc, el) {
			acc.push({ [el.trim()]: termRegex });
			return acc;
		}, []);
		const query = {
			$and: [
				{
					active: true,
					$or: orStmt
				},
				{
					username: { $exists: true, $nin: exceptions }
				}
			]
		};

		// do not use cache
		return this._db.find(query, options);
	}

	findUsersByNameOrUsername(nameOrUsername, options) {
		const query = {
			username: {
				$exists: 1
			},

			$or: [
				{name: nameOrUsername},
				{username: nameOrUsername}
			],

			type: {
				$in: ['user']
			}
		};

		return this.find(query, options);
	}

	findByUsernameNameOrEmailAddress(usernameNameOrEmailAddress, options) {
		const query = {
			$or: [
				{name: usernameNameOrEmailAddress},
				{username: usernameNameOrEmailAddress},
				{'emails.address': usernameNameOrEmailAddress}
			],
			type: {
				$in: ['user', 'bot']
			}
		};

		return this.find(query, options);
	}

	findLDAPUsers(options) {
		const query =	{ldap: true};

		return this.find(query, options);
	}

	findCrowdUsers(options) {
		const query =	{crowd: true};

		return this.find(query, options);
	}

	getLastLogin(options) {
		if (options == null) { options = {}; }
		const query = { lastLogin: { $exists: 1 } };
		options.sort = { lastLogin: -1 };
		options.limit = 1;
		const [user] = this.find(query, options).fetch();
		return user && user.lastLogin;
	}

	findUsersByUsernames(usernames, options) {
		const query = {
			username: {
				$in: usernames
			}
		};

		return this.find(query, options);
	}

	findUsersByIds(ids, options) {
		const query = {
			_id: {
				$in: ids
			}
		};
		return this.find(query, options);
	}

	// UPDATE
	addImportIds(_id, importIds) {
		importIds = [].concat(importIds);

		const query =	{_id};

		const update = {
			$addToSet: {
				importIds: {
					$each: importIds
				}
			}
		};

		return this.update(query, update);
	}

	updateLastLoginById(_id) {
		const update = {
			$set: {
				lastLogin: new Date
			}
		};

		return this.update(_id, update);
	}

	setServiceId(_id, serviceName, serviceId) {
		const update =
		{$set: {}};

		const serviceIdKey = `services.${ serviceName }.id`;
		update.$set[serviceIdKey] = serviceId;

		return this.update(_id, update);
	}

	setUsername(_id, username) {
		const update =
		{$set: {username}};

		return this.update(_id, update);
	}

	setEmail(_id, email) {
		const update = {
			$set: {
				emails: [{
					address: email,
					verified: false
				}
				]
			}
		};

		return this.update(_id, update);
	}

	setEmailVerified(_id, email) {
		const query = {
			_id,
			emails: {
				$elemMatch: {
					address: email,
					verified: false
				}
			}
		};

		const update = {
			$set: {
				'emails.$.verified': true
			}
		};

		return this.update(query, update);
	}

	setName(_id, name) {
		const update = {
			$set: {
				name
			}
		};

		return this.update(_id, update);
	}

	setCustomFields(_id, fields) {
		const values = {};
		Object.keys(fields).forEach(key => {
			values[`customFields.${ key }`] = fields[key];
		});

		const update = {$set: values};

		return this.update(_id, update);
	}

	setAvatarOrigin(_id, origin) {
		const update = {
			$set: {
				avatarOrigin: origin
			}
		};

		return this.update(_id, update);
	}

	unsetAvatarOrigin(_id) {
		const update = {
			$unset: {
				avatarOrigin: 1
			}
		};

		return this.update(_id, update);
	}

	setUserActive(_id, active) {
		if (active == null) { active = true; }
		const update = {
			$set: {
				active
			}
		};

		return this.update(_id, update);
	}

	setAllUsersActive(active) {
		const update = {
			$set: {
				active
			}
		};

		return this.update({}, update, { multi: true });
	}

	unsetLoginTokens(_id) {
		const update = {
			$set: {
				'services.resume.loginTokens' : []
			}
		};

		return this.update(_id, update);
	}

	unsetRequirePasswordChange(_id) {
		const update = {
			$unset: {
				'requirePasswordChange' : true,
				'requirePasswordChangeReason' : true
			}
		};

		return this.update(_id, update);
	}

	resetPasswordAndSetRequirePasswordChange(_id, requirePasswordChange, requirePasswordChangeReason) {
		const update = {
			$unset: {
				'services.password': 1
			},
			$set: {
				requirePasswordChange,
				requirePasswordChangeReason
			}
		};

		return this.update(_id, update);
	}

	setLanguage(_id, language) {
		const update = {
			$set: {
				language
			}
		};

		return this.update(_id, update);
	}

	setProfile(_id, profile) {
		const update = {
			$set: {
				'settings.profile': profile
			}
		};

		return this.update(_id, update);
	}

	setPreferences(_id, preferences) {
		const update = {
			$set: {
				'settings.preferences': preferences
			}
		};

		return this.update(_id, update);
	}

	setUtcOffset(_id, utcOffset) {
		const query = {
			_id,
			utcOffset: {
				$ne: utcOffset
			}
		};

		const update = {
			$set: {
				utcOffset
			}
		};

		return this.update(query, update);
	}

	saveUserById(_id, data) {
		const setData = {};
		const unsetData = {};

		if (data.name != null) {
			if (!_.isEmpty(s.trim(data.name))) {
				setData.name = s.trim(data.name);
			} else {
				unsetData.name = 1;
			}
		}

		if (data.email != null) {
			if (!_.isEmpty(s.trim(data.email))) {
				setData.emails = [{address: s.trim(data.email)}];
			} else {
				unsetData.emails = 1;
			}
		}

		if (data.phone != null) {
			if (!_.isEmpty(s.trim(data.phone))) {
				setData.phone = [{phoneNumber: s.trim(data.phone)}];
			} else {
				unsetData.phone = 1;
			}
		}

		const update = {};

		if (!_.isEmpty(setData)) {
			update.$set = setData;
		}

		if (!_.isEmpty(unsetData)) {
			update.$unset = unsetData;
		}

		if (_.isEmpty(update)) {
			return true;
		}

		return this.update({ _id }, update);
	}

	// INSERT
	create(data) {
		const user = {
			createdAt: new Date,
			avatarOrigin: 'none'
		};

		_.extend(user, data);

		return this.insert(user);
	}

	// REMOVE
	removeById(_id) {
		return this.remove(_id);
	}

	/*
Find users to send a message by email if:
- he is not online
- has a verified email
- has not disabled email notifications
- `active` is equal to true (false means they were deactivated and can't login)
*/
	getUsersToSendOfflineEmail(usersIds) {
		const query = {
			_id: {
				$in: usersIds
			},
			active: true,
			status: 'offline',
			statusConnection: {
				$ne: 'online'
			},
			'emails.verified': true
		};

		return this.find(query, { fields: { name: 1, username: 1, emails: 1, 'settings.preferences.emailNotificationMode': 1 } });
	}
}

RocketChat.models.Users = new ModelUsers(Meteor.users, true);
<commit_msg>Fix canse insesitive of Users.findOneByUsername<commit_after>import _ from 'underscore';
import s from 'underscore.string';

class ModelUsers extends RocketChat.models._Base {
	constructor() {
		super(...arguments);

		this.tryEnsureIndex({ 'roles': 1 }, { sparse: 1 });
		this.tryEnsureIndex({ 'name': 1 });
		this.tryEnsureIndex({ 'lastLogin': 1 });
		this.tryEnsureIndex({ 'status': 1 });
		this.tryEnsureIndex({ 'active': 1 }, { sparse: 1 });
		this.tryEnsureIndex({ 'statusConnection': 1 }, { sparse: 1 });
		this.tryEnsureIndex({ 'type': 1 });

		this.cache.ensureIndex('username', 'unique');
	}

	findOneByImportId(_id, options) {
		return this.findOne({ importIds: _id }, options);
	}

	findOneByUsername(username, options) {
		if (typeof username === 'string') {
			username = new RegExp(username, 'i')
		}

		const query = {username};

		return this.findOne(query, options);
	}

	findOneByEmailAddress(emailAddress, options) {
		const query =	{'emails.address': new RegExp(`^${ s.escapeRegExp(emailAddress) }$`, 'i')};

		return this.findOne(query, options);
	}

	findOneAdmin(admin, options) {
		const query =	{admin};

		return this.findOne(query, options);
	}

	findOneByIdAndLoginToken(_id, token, options) {
		const query = {
			_id,
			'services.resume.loginTokens.hashedToken' : Accounts._hashLoginToken(token)
		};

		return this.findOne(query, options);
	}

	// FIND
	findById(userId) {
		const query =	{_id: userId};

		return this.find(query);
	}

	findUsersNotOffline(options) {
		const query = {
			username: {
				$exists: 1
			},
			status: {
				$in: ['online', 'away', 'busy']
			}
		};

		return this.find(query, options);
	}

	findByUsername(username, options) {
		const query =	{username};

		return this.find(query, options);
	}

	findUsersByUsernamesWithHighlights(usernames, options) {
		if (this.useCache) {
			const result = {
				fetch() {
					return RocketChat.models.Users.getDynamicView('highlights').data().filter(record => usernames.indexOf(record.username) > -1);
				},
				count() {
					return result.fetch().length;
				},
				forEach(fn) {
					return result.fetch().forEach(fn);
				}
			};
			return result;
		}

		const query = {
			username: { $in: usernames },
			'settings.preferences.highlights.0': {
				$exists: true
			}
		};

		return this.find(query, options);
	}

	findActiveByUsernameOrNameRegexWithExceptions(searchTerm, exceptions, options) {
		if (exceptions == null) { exceptions = []; }
		if (options == null) { options = {}; }
		if (!_.isArray(exceptions)) {
			exceptions = [ exceptions ];
		}

		const termRegex = new RegExp(s.escapeRegExp(searchTerm), 'i');
		const query = {
			$or: [{
				username: termRegex
			}, {
				name: termRegex
			}],
			active: true,
			type: {
				$in: ['user', 'bot']
			},
			$and: [{
				username: {
					$exists: true
				}
			}, {
				username: {
					$nin: exceptions
				}
			}]
		};

		return this.find(query, options);
	}

	findByActiveUsersExcept(searchTerm, exceptions, options) {
		if (exceptions == null) { exceptions = []; }
		if (options == null) { options = {}; }
		if (!_.isArray(exceptions)) {
			exceptions = [ exceptions ];
		}

		const termRegex = new RegExp(s.escapeRegExp(searchTerm), 'i');

		const orStmt = _.reduce(RocketChat.settings.get('Accounts_SearchFields').trim().split(','), function(acc, el) {
			acc.push({ [el.trim()]: termRegex });
			return acc;
		}, []);
		const query = {
			$and: [
				{
					active: true,
					$or: orStmt
				},
				{
					username: { $exists: true, $nin: exceptions }
				}
			]
		};

		// do not use cache
		return this._db.find(query, options);
	}

	findUsersByNameOrUsername(nameOrUsername, options) {
		const query = {
			username: {
				$exists: 1
			},

			$or: [
				{name: nameOrUsername},
				{username: nameOrUsername}
			],

			type: {
				$in: ['user']
			}
		};

		return this.find(query, options);
	}

	findByUsernameNameOrEmailAddress(usernameNameOrEmailAddress, options) {
		const query = {
			$or: [
				{name: usernameNameOrEmailAddress},
				{username: usernameNameOrEmailAddress},
				{'emails.address': usernameNameOrEmailAddress}
			],
			type: {
				$in: ['user', 'bot']
			}
		};

		return this.find(query, options);
	}

	findLDAPUsers(options) {
		const query =	{ldap: true};

		return this.find(query, options);
	}

	findCrowdUsers(options) {
		const query =	{crowd: true};

		return this.find(query, options);
	}

	getLastLogin(options) {
		if (options == null) { options = {}; }
		const query = { lastLogin: { $exists: 1 } };
		options.sort = { lastLogin: -1 };
		options.limit = 1;
		const [user] = this.find(query, options).fetch();
		return user && user.lastLogin;
	}

	findUsersByUsernames(usernames, options) {
		const query = {
			username: {
				$in: usernames
			}
		};

		return this.find(query, options);
	}

	findUsersByIds(ids, options) {
		const query = {
			_id: {
				$in: ids
			}
		};
		return this.find(query, options);
	}

	// UPDATE
	addImportIds(_id, importIds) {
		importIds = [].concat(importIds);

		const query =	{_id};

		const update = {
			$addToSet: {
				importIds: {
					$each: importIds
				}
			}
		};

		return this.update(query, update);
	}

	updateLastLoginById(_id) {
		const update = {
			$set: {
				lastLogin: new Date
			}
		};

		return this.update(_id, update);
	}

	setServiceId(_id, serviceName, serviceId) {
		const update =
		{$set: {}};

		const serviceIdKey = `services.${ serviceName }.id`;
		update.$set[serviceIdKey] = serviceId;

		return this.update(_id, update);
	}

	setUsername(_id, username) {
		const update =
		{$set: {username}};

		return this.update(_id, update);
	}

	setEmail(_id, email) {
		const update = {
			$set: {
				emails: [{
					address: email,
					verified: false
				}
				]
			}
		};

		return this.update(_id, update);
	}

	setEmailVerified(_id, email) {
		const query = {
			_id,
			emails: {
				$elemMatch: {
					address: email,
					verified: false
				}
			}
		};

		const update = {
			$set: {
				'emails.$.verified': true
			}
		};

		return this.update(query, update);
	}

	setName(_id, name) {
		const update = {
			$set: {
				name
			}
		};

		return this.update(_id, update);
	}

	setCustomFields(_id, fields) {
		const values = {};
		Object.keys(fields).forEach(key => {
			values[`customFields.${ key }`] = fields[key];
		});

		const update = {$set: values};

		return this.update(_id, update);
	}

	setAvatarOrigin(_id, origin) {
		const update = {
			$set: {
				avatarOrigin: origin
			}
		};

		return this.update(_id, update);
	}

	unsetAvatarOrigin(_id) {
		const update = {
			$unset: {
				avatarOrigin: 1
			}
		};

		return this.update(_id, update);
	}

	setUserActive(_id, active) {
		if (active == null) { active = true; }
		const update = {
			$set: {
				active
			}
		};

		return this.update(_id, update);
	}

	setAllUsersActive(active) {
		const update = {
			$set: {
				active
			}
		};

		return this.update({}, update, { multi: true });
	}

	unsetLoginTokens(_id) {
		const update = {
			$set: {
				'services.resume.loginTokens' : []
			}
		};

		return this.update(_id, update);
	}

	unsetRequirePasswordChange(_id) {
		const update = {
			$unset: {
				'requirePasswordChange' : true,
				'requirePasswordChangeReason' : true
			}
		};

		return this.update(_id, update);
	}

	resetPasswordAndSetRequirePasswordChange(_id, requirePasswordChange, requirePasswordChangeReason) {
		const update = {
			$unset: {
				'services.password': 1
			},
			$set: {
				requirePasswordChange,
				requirePasswordChangeReason
			}
		};

		return this.update(_id, update);
	}

	setLanguage(_id, language) {
		const update = {
			$set: {
				language
			}
		};

		return this.update(_id, update);
	}

	setProfile(_id, profile) {
		const update = {
			$set: {
				'settings.profile': profile
			}
		};

		return this.update(_id, update);
	}

	setPreferences(_id, preferences) {
		const update = {
			$set: {
				'settings.preferences': preferences
			}
		};

		return this.update(_id, update);
	}

	setUtcOffset(_id, utcOffset) {
		const query = {
			_id,
			utcOffset: {
				$ne: utcOffset
			}
		};

		const update = {
			$set: {
				utcOffset
			}
		};

		return this.update(query, update);
	}

	saveUserById(_id, data) {
		const setData = {};
		const unsetData = {};

		if (data.name != null) {
			if (!_.isEmpty(s.trim(data.name))) {
				setData.name = s.trim(data.name);
			} else {
				unsetData.name = 1;
			}
		}

		if (data.email != null) {
			if (!_.isEmpty(s.trim(data.email))) {
				setData.emails = [{address: s.trim(data.email)}];
			} else {
				unsetData.emails = 1;
			}
		}

		if (data.phone != null) {
			if (!_.isEmpty(s.trim(data.phone))) {
				setData.phone = [{phoneNumber: s.trim(data.phone)}];
			} else {
				unsetData.phone = 1;
			}
		}

		const update = {};

		if (!_.isEmpty(setData)) {
			update.$set = setData;
		}

		if (!_.isEmpty(unsetData)) {
			update.$unset = unsetData;
		}

		if (_.isEmpty(update)) {
			return true;
		}

		return this.update({ _id }, update);
	}

	// INSERT
	create(data) {
		const user = {
			createdAt: new Date,
			avatarOrigin: 'none'
		};

		_.extend(user, data);

		return this.insert(user);
	}

	// REMOVE
	removeById(_id) {
		return this.remove(_id);
	}

	/*
Find users to send a message by email if:
- he is not online
- has a verified email
- has not disabled email notifications
- `active` is equal to true (false means they were deactivated and can't login)
*/
	getUsersToSendOfflineEmail(usersIds) {
		const query = {
			_id: {
				$in: usersIds
			},
			active: true,
			status: 'offline',
			statusConnection: {
				$ne: 'online'
			},
			'emails.verified': true
		};

		return this.find(query, { fields: { name: 1, username: 1, emails: 1, 'settings.preferences.emailNotificationMode': 1 } });
	}
}

RocketChat.models.Users = new ModelUsers(Meteor.users, true);
<|endoftext|>


<commit_before>// Hides Dashboard Views
$('.container').hide();

// Navbar button functions
$('.event').click(processEvent);
$('.init').click(processInit);
$('.speak').click(processSpeak);
$('.del-event').click(processDelEvent);
$('.del-init').click(processDelInit);
$('.del-speak').click(processDelSpeak);
$('.events').click(processEvents);
$('.speaker').click(processSpeaker);
$('.speakq').click(processSpeakq);
$('.proj').click(processProj);
$('.pledges').click(processPledges);

function processEvent(){
	$('.add-event').show();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processInit(){
	$('.add-event').hide();
	$('.add-initiative').show();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeak(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').show();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelEvent(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').show();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelInit(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').show();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelSpeak(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').show();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processEvents(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').show();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeaker(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').show();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeakq(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').show();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processProj(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').show();
	$('.view-pledge').hide();
}
function processPledges(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').show();
}

// Character Limit Function
function limitText(limitField, limitCount, limitNum) {
  if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
  } else {
    limitCount.value = limitNum - limitField.value.length;
  }
}

// Event Functions
$('.btn-send-event').click(sendEvent);
$('.btn-del-event').click(delEvent);

function delEvent(){
	document.getElementById("event-title").value="";
	document.getElementById("event-info").value="";
}

function sendEvent(){
	var title = $('#event-title').val();
	var event = $('#event-info').val();
	database.ref('event/'+ title).update({
  		Title: title,
  		Event: event
 	});
	//code to send event
	delEvent();
}

// Initiative Functions
$('.btn-send-initiative').click(sendInitiative);
$('.btn-del-initiative').click(delInitiative);

function delInitiative(){
	document.getElementById("initiative-title").value="";
	document.getElementById("initiative-info").value="";
}

function sendInitiative(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

		var title = $('#initiative-title').val();
		var initiative = $('#initiative-info').val();

		database.ref('event/'+ event +'/initiative/'+ title).update({
	  		Title: title,
	  		Initiative: initiative
	 	});
		//code to send initiative
		delInitiative();
	});
}

// Speaker Functions
$('.btn-send-speaker').click(sendSpeaker);
$('.btn-del-speaker').click(delSpeaker);

function delSpeaker(){
	document.getElementById("speaker-name").value="";
	document.getElementById("speaker-info").value="";
}

function sendSpeaker(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

		var name = $('#speaker-name').val();
		var info = $('#speaker-info').val();

		database.ref('event/'+ event +'/speaker/'+ name).update({
	  		Name: name,
	  		Info: info
	 	});
		//code to send speaker
		delSpeaker();
	});
}

// Delete Event Function
database.ref('event/').on('child_added', function(childSnapshot){
		var events = childSnapshot.key;
		deleteEvents(events);
		// console.log(speak);
});

function deleteEvents(events){
		$('.event-list').append('<option title="'+events+'">'+events+'</option');

}

$('.selectevents').click(processDelEvents);

function processDelEvents(){

	var events = $("#sel1 option:selected").text();

	database.ref('event/'+ events).remove();
	$("#sel1 option:selected").remove();
	alert(events + ' Removed!');
}

// Delete Initiative Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/initiative/').on('child_added', function(childSnapshot){
			var init = childSnapshot.key;
			delInit(init);
			// console.log(init);
	});
});

function delInit(init){
		$('.initiative-list').append('<option title="'+init+'">'+init+'</option');

}

$('.selecti').click(processSelecti);

function processSelecti(){
firebase.database().ref('chosen-event/').on('value', function(snapshot){

	var event = snapshot.val().Chosen;

	var init = $("#sel2 option:selected").text();

	database.ref('event/'+ event +'/initiative/' + init).remove();
	$("#sel2 option:selected").remove();
	alert(init + ' Removed!');
	});
}

// Delete Speaker Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/speaker/').on('child_added', function(childSnapshot){
			var speak = childSnapshot.key;
			delSpeak(speak);
			// console.log(speak);
	});
});

function delSpeak(speak){
		$('.speaker-list').append('<option title="'+speak+'">'+speak+'</option');

}

$('.selects').click(processSelects);

function processSelects(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	var speak = $("#sel3 option:selected").text();

	database.ref('event/'+ event +'/speaker/' + speak).remove();
	$("#sel3 option:selected").remove();
	alert(speak + ' Removed!');
	});
}

// Choose Event Function
database.ref('event/').on('child_added', function(childSnapshot){
		var event = childSnapshot.key;
		chooseEvent(event);
		// console.log(speak);
});

function chooseEvent(event){
		$('.event-choose').append('<option title="'+event+'">'+event+'</option');

}

$('.selectevent').click(processSelectEvent);

function processSelectEvent(){
	var event = $("#sel4 option:selected").text();

	database.ref('chosen-event/').update({
		Chosen: event
	});

	alert(event + ' Chosen');
};

// Choose Speaker Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/speaker/').on('child_added', function(childSnapshot){
			var speak = childSnapshot.key;
			chooseSpeak(speak);
			// console.log(speak);
	});
});

function chooseSpeak(speak){
		$('.speaker-choose').append('<option title="'+speak+'">'+speak+'</option');

}

$('.selectspeaker').click(processSelectSpeaker);

function processSelectSpeaker(){
	var speak = $("#sel5 option:selected").text();

	database.ref('chosen-speaker/').update({
		Chosen: speak
	});

	alert(speak + ' Chosen');
};

// Choose Question Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;
	var speaker = "";
	database.ref('chosen-speaker/').once('value', function(snapshot) {
		speaker = snapshot.val().Chosen;
		updateSpeakerQuestions(event, speaker);
	});
});

firebase.database().ref('chosen-speaker/').on('value', function(snapshot){
	var event = "";
	var speaker = snapshot.val().Chosen;
	database.ref('chosen-event/').once('value', function(snapshot) {
		event = snapshot.val().Chosen;
		updateSpeakerQuestions(event, speaker);
	});
});

function updateSpeakerQuestions(event, speaker) {
	removeAllQuestions($('.question-list'));
	firebase.database().ref('event/' + event + "/speaker-question/" + speaker).once('value', function(snapshot) {
		snapshot.forEach(function(childSnapshot) {
			childSnapshot.forEach(function(childSnapshot) {
				var question = childSnapshot.val();
				addQuestion(question, speaker);
			});
		});
	});
}

function removeAllQuestions(dropDown) {
	if (typeof dropDown != 'undefined' && typeof dropDown.options != 'undefined') {
	    while (dropDown.options.length > 0) {
	        dropDown.remove(0);
	    }
	}
}

function addQuestion(question,name){
		$('.question-list').append('<option title="'+question+'">'+question+' '+'('+'question for '+name+')'+'</option');

}

$('.selectq').click(processSelectq);

function processSelectq(){
	var question = $("#sel6 option:selected").text();

	database.ref('chosen-question/').update({
		Chosen: question
	});

	alert(question + " Chosen!")
}

// Change View Function
$('.select').click(processSelect);

function processSelect(){
	var view = $("#sel7 option:selected").text();

	database.ref('view/').update({
		currentView: view
	});

	alert("set view to " + view);
}

// View Pledge Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/' + event + '/pledges/').on('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			childSnapshot.forEach(function(childSnapshot){
			var title= childSnapshot.val().Title;
			var pledge= childSnapshot.val().Pledge;
			addPledge(title,pledge);
			console.log(title)
			});
		});
	});
});

function addPledge(title,pledge){
		$('.pledge-list').append('<option title="'+title+'">'+title+' '+'('+'Pledge: '+pledge+')'+'</option');

}

$('.selectp').click(processSelectP);

function processSelectP(){
	var question = $("#sel8 option:selected").text();
}<commit_msg>Added refresh when a list is selected, added arrays to question and pledges<commit_after>// Hides Dashboard Views
$('.container').hide();

// Navbar button functions
$('.event').click(processEvent);
$('.init').click(processInit);
$('.speak').click(processSpeak);
$('.del-event').click(processDelEvent);
$('.del-init').click(processDelInit);
$('.del-speak').click(processDelSpeak);
$('.events').click(processEvents);
$('.speaker').click(processSpeaker);
$('.speakq').click(processSpeakq);
$('.proj').click(processProj);
$('.pledges').click(processPledges);

function processEvent(){
	$('.add-event').show();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processInit(){
	$('.add-event').hide();
	$('.add-initiative').show();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeak(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').show();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelEvent(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').show();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelInit(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').show();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processDelSpeak(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').show();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processEvents(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').show();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeaker(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').show();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processSpeakq(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').show();
	$('.change-view').hide();
	$('.view-pledge').hide();
}
function processProj(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').show();
	$('.view-pledge').hide();
}
function processPledges(){
	$('.add-event').hide();
	$('.add-initiative').hide();
	$('.add-speaker').hide();
	$('.delete-event').hide();
	$('.delete-init').hide();
	$('.delete-speak').hide();
	$('.choose-event').hide();
	$('.choose-speak').hide();
	$('.choose-question').hide();
	$('.change-view').hide();
	$('.view-pledge').show();
}

// Character Limit Function
function limitText(limitField, limitCount, limitNum) {
  if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
  } else {
    limitCount.value = limitNum - limitField.value.length;
  }
}

// Event Functions
$('.btn-send-event').click(sendEvent);
$('.btn-del-event').click(delEvent);

function delEvent(){
	document.getElementById("event-title").value="";
	document.getElementById("event-info").value="";
}

function sendEvent(){
	var title = $('#event-title').val();
	var event = $('#event-info').val();
	database.ref('event/'+ title).update({
  		Title: title,
  		Event: event
 	});
	//code to send event
	delEvent();
}

// Initiative Functions
$('.btn-send-initiative').click(sendInitiative);
$('.btn-del-initiative').click(delInitiative);

function delInitiative(){
	document.getElementById("initiative-title").value="";
	document.getElementById("initiative-info").value="";
}

function sendInitiative(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

		var title = $('#initiative-title').val();
		var initiative = $('#initiative-info').val();

		database.ref('event/'+ event +'/initiative/'+ title).update({
	  		Title: title,
	  		Initiative: initiative
	 	});
		//code to send initiative
		delInitiative();
	});
}

// Speaker Functions
$('.btn-send-speaker').click(sendSpeaker);
$('.btn-del-speaker').click(delSpeaker);

function delSpeaker(){
	document.getElementById("speaker-name").value="";
	document.getElementById("speaker-info").value="";
}

function sendSpeaker(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

		var name = $('#speaker-name').val();
		var info = $('#speaker-info').val();

		database.ref('event/'+ event +'/speaker/'+ name).update({
	  		Name: name,
	  		Info: info
	 	});
		//code to send speaker
		delSpeaker();
	});
}

// Delete Event Function
database.ref('event/').on('child_added', function(childSnapshot){
		var events = childSnapshot.key;
		deleteEvents(events);
		// console.log(speak);
});

function deleteEvents(events){
		$('.event-list').append('<option title="'+events+'">'+events+'</option');

}

$('.selectevents').click(processDelEvents);

function processDelEvents(){

	var events = $("#sel1 option:selected").text();

	database.ref('event/'+ events).remove();
	$("#sel1 option:selected").remove();
	alert(events + ' Removed!');
	window.location.href = '/dashboard/index.html';
}

// Delete Initiative Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/initiative/').on('child_added', function(childSnapshot){
			var init = childSnapshot.key;
			delInit(init);
			// console.log(init);
	});
});

function delInit(init){
		$('.initiative-list').append('<option title="'+init+'">'+init+'</option');

}

$('.selecti').click(processSelecti);

function processSelecti(){
firebase.database().ref('chosen-event/').on('value', function(snapshot){

	var event = snapshot.val().Chosen;

	var init = $("#sel2 option:selected").text();

	database.ref('event/'+ event +'/initiative/' + init).remove();
	$("#sel2 option:selected").remove();
	alert(init + ' Removed!');
	window.location.href = '/dashboard/index.html';
	});
}

// Delete Speaker Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/speaker/').on('child_added', function(childSnapshot){
			var speak = childSnapshot.key;
			delSpeak(speak);
			// console.log(speak);
	});
});

function delSpeak(speak){
		$('.speaker-list').append('<option title="'+speak+'">'+speak+'</option');

}

$('.selects').click(processSelects);

function processSelects(){
	firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	var speak = $("#sel3 option:selected").text();

	database.ref('event/'+ event +'/speaker/' + speak).remove();
	$("#sel3 option:selected").remove();
	alert(speak + ' Removed!');
	window.location.href = '/dashboard/index.html';
	});
}

// Choose Event Function
database.ref('event/').on('child_added', function(childSnapshot){
		var event = childSnapshot.key;
		chooseEvent(event);
		// console.log(speak);
});

function chooseEvent(event){
		$('.event-choose').append('<option title="'+event+'">'+event+'</option');

}

$('.selectevent').click(processSelectEvent);

function processSelectEvent(){
	var event = $("#sel4 option:selected").text();

	database.ref('chosen-event/').update({
		Chosen: event
	});

	alert(event + ' Chosen');
	window.location.href = '/dashboard/index.html';
};

// Choose Speaker Function
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	database.ref('event/'+ event +'/speaker/').on('child_added', function(childSnapshot){
			var speak = childSnapshot.key;
			chooseSpeak(speak);
			// console.log(speak);
	});
});

function chooseSpeak(speak){
		$('.speaker-choose').append('<option title="'+speak+'">'+speak+'</option');

}

$('.selectspeaker').click(processSelectSpeaker);

function processSelectSpeaker(){
	var speak = $("#sel5 option:selected").text();

	database.ref('chosen-speaker/').update({
		Chosen: speak
	});

	alert(speak + ' Chosen');
	window.location.href = '/dashboard/index.html';
};

// Choose Question Function
var speakerquestion=[];
var nextQuestion=0;
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;
	var speaker = "";
	database.ref('chosen-speaker/').once('value', function(snapshot) {
		speaker = snapshot.val().Chosen;
		updateSpeakerQuestions(event, speaker);
	});
});

firebase.database().ref('chosen-speaker/').on('value', function(snapshot){
	var event = "";
	var speaker = snapshot.val().Chosen;
	database.ref('chosen-event/').once('value', function(snapshot) {
		event = snapshot.val().Chosen;
		updateSpeakerQuestions(event, speaker);
	});
});

function updateSpeakerQuestions(event, speaker) {
	// removeAllQuestions($('.question-list'));
	if (event == event) {
		speakerquestion=[];
	}

	firebase.database().ref('event/' + event + "/speaker-question/" + speaker).once('value', function(snapshot) {
		snapshot.forEach(function(childSnapshot) {
			childSnapshot.forEach(function(childSnapshot) {
				var question = childSnapshot.val();
				// addQuestion(question, speaker);
				speakerquestion.push([question,speaker]);
			});
		});
	});
}

setInterval(addQuestion,100);

function removeAllQuestions(dropDown) {
	if (typeof dropDown != 'undefined' && typeof dropDown.options != 'undefined') {
	    while (dropDown.options.length > 0) {
	        dropDown.remove(0);
	    }
	}
}

function addQuestion(){
		$('.question-list').append('<option title="'+speakerquestion[nextQuestion][0]+'">'+speakerquestion[nextQuestion][0]+' '+'('+'question for '+speakerquestion[nextQuestion][1]+')'+'</option');
		nextQuestion++;
		if(nextQuestion==speakerquestion.length){
		breakexception;
	}
}

$('.selectq').click(processSelectq);

function processSelectq(){
	var question = $("#sel6 option:selected").text();

	database.ref('chosen-question/').update({
		Chosen: question
	});

	alert(question + " Chosen!")
}

// Change View Function
$('.select').click(processSelect);

function processSelect(){
	var view = $("#sel7 option:selected").text();

	database.ref('view/').update({
		currentView: view
	});

	alert("set view to " + view);
}

// View Pledge Function
var pledges=[]
var nextPledge=0;
firebase.database().ref('chosen-event/').on('value', function(snapshot){
	var event = snapshot.val().Chosen;

	if (event == event) {
		pledges=[];
	}

	database.ref('event/' + event + '/pledges/').on('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			childSnapshot.forEach(function(childSnapshot){
			var title= childSnapshot.val().Title;
			var pledge= childSnapshot.val().Pledge;
			// addPledge(title,pledge);
			pledges.push([title,pledge]);
			console.log(title)
			});
		});
	});
});

setInterval(addPledge,100);
var breakexception ={}
function addPledge(){
		$('.pledge-list').append('<option title="'+pledges[nextPledge][0]+'">'+pledges[nextPledge][0]+' '+'('+'Pledge: '+pledges[nextPledge][1]+')'+'</option');
		nextPledge++;
		if(nextPledge==pledges.length){
		breakexception;
	}
}

$('.selectp').click(processSelectP);

function processSelectP(){
	var question = $("#sel8 option:selected").text();
}<|endoftext|>


<commit_before>import React, { Component } from "react";
import { connect } from "react-redux";

import {
	addComponent,
	removeComponent,
	watchComponent,
	updateQuery
} from "@appbaseio/reactivecore/lib/actions";
import {
	checkValueChange,
	checkPropChange
} from "@appbaseio/reactivecore/lib/utils/helper";
import types from "@appbaseio/reactivecore/lib/utils/types";

import Title from "../../styles/Title";
import Button, { numberBoxButtons } from "../../styles/Button";
import Flex from "../../styles/Flex";

class NumberBox extends Component {
	constructor(props) {
		super(props);

		this.type = "term";
		this.state = {
			currentValue: this.props.data.start
		};
	}

	componentWillMount() {
		this.props.addComponent(this.props.componentId);
		this.setReact(this.props);

		if (this.props.selectedValue) {
			this.setValue(this.props.selectedValue);
		} else if (this.props.defaultSelected) {
			this.setValue(this.props.defaultSelected);
		}
	}

	componentWillReceiveProps(nextProps) {
		checkPropChange(this.props.react, nextProps.react, () => {
			this.setReact(nextProps);
		});
		checkPropChange(this.props.defaultSelected, nextProps.defaultSelected, () => {
			this.setValue(nextProps.defaultSelected, nextProps);
		});
		checkPropChange(this.props.queryFormat, nextProps.queryFormat, () => {
			this.updateQuery(this.state.currentValue, nextProps);
		});
	}

	componentWillUnmount() {
		this.props.removeComponent(this.props.componentId);
	}

	defaultQuery = (value, props) => {
		switch (props.queryFormat) {
			case "exact":
				return {
					term: {
						[props.dataField]: value
					}
				};
			case "lte":
				return {
					range: {
						[props.dataField]: {
							lte: value,
							boost: 2.0
						}
					}
				};
			case "gte":
				return {
					range: {
						[props.dataField]: {
							gte: value,
							boost: 2.0
						}
					}
				};
			default:
				return null;
		}
	};

	setReact(props) {
		if (props.react) {
			props.watchComponent(props.componentId, props.react);
		}
	}

	incrementValue = () => {
		if (this.state.currentValue === this.props.data.end) {
			return;
		}
		const { currentValue } = this.state;
		this.setValue(currentValue + 1);
	};

	decrementValue = () => {
		if (this.state.currentValue === this.props.data.start) {
			return;
		}
		const { currentValue } = this.state;
		this.setValue(currentValue - 1);
	};

	setValue = (value, props = this.props) => {
		const performUpdate = () => {
			this.setState({
				currentValue: value
			}, () => {
				this.updateQuery(value, props);
			});
		};
		checkValueChange(
			props.componentId,
			value,
			props.beforeValueChange,
			props.onValueChange,
			performUpdate
		);
	};

	updateQuery = (value, props) => {
		const query = props.customQuery || this.defaultQuery;
		let onQueryChange = null;
		if (props.onQueryChange) {
			onQueryChange = props.onQueryChange;
		}
		props.updateQuery({
			componentId: props.componentId,
			query: query(value, props),
			value,
			onQueryChange,
			showFilter: false,	// we don't need filters for NumberBox
			URLParams: props.URLParams
		});
	};

	render() {
		return (

				{this.props.title && <Title>{this.props.title}</Title>}
				<Flex labelPosition={this.props.labelPosition} inline>
					{this.props.data.label}

						<Button
							onClick={this.decrementValue}
							disabled={this.state.currentValue === this.props.data.start}
						>
							-
						</Button>
						{this.state.currentValue}
						<Button
							onClick={this.incrementValue}
							disabled={this.state.currentValue === this.props.data.end}
						>
							+
						</Button>

				</Flex>

		);
	}
}

NumberBox.propTypes = {
	addComponent: types.addComponent,
	componentId: types.componentId,
	defaultSelected: types.number,
	data: types.dataNumberBox,
	react: types.react,
	removeComponent: types.removeComponent,
	title: types.title,
	queryFormat: types.queryFormatNumberBox,
	labelPosition: types.labelPosition,
	URLParams: types.URLParams,
	selectedValue: types.selectedValue
};

NumberBox.defaultProps = {
	queryFormat: "gte",
	labelPosition: "left",
	URLParams: false
};

const mapStateToProps = (state, props) => ({
	selectedValue: state.selectedValues[props.componentId] ? state.selectedValues[props.componentId].value : null
});

const mapDispatchtoProps = (dispatch, props) => ({
	addComponent: component => dispatch(addComponent(component)),
	removeComponent: component => dispatch(removeComponent(component)),
	watchComponent: (component, react) =>
		dispatch(watchComponent(component, react)),
	updateQuery: updateQueryObject => dispatch(updateQuery(updateQueryObject))
});

export default connect(mapStateToProps, mapDispatchtoProps)(NumberBox);
<commit_msg>Update NumberBox type definitions<commit_after>import React, { Component } from "react";
import { connect } from "react-redux";

import {
	addComponent,
	removeComponent,
	watchComponent,
	updateQuery
} from "@appbaseio/reactivecore/lib/actions";
import {
	checkValueChange,
	checkPropChange
} from "@appbaseio/reactivecore/lib/utils/helper";
import types from "@appbaseio/reactivecore/lib/utils/types";

import Title from "../../styles/Title";
import Button, { numberBoxButtons } from "../../styles/Button";
import Flex from "../../styles/Flex";

class NumberBox extends Component {
	constructor(props) {
		super(props);

		this.type = "term";
		this.state = {
			currentValue: this.props.data.start
		};
	}

	componentWillMount() {
		this.props.addComponent(this.props.componentId);
		this.setReact(this.props);

		if (this.props.selectedValue) {
			this.setValue(this.props.selectedValue);
		} else if (this.props.defaultSelected) {
			this.setValue(this.props.defaultSelected);
		}
	}

	componentWillReceiveProps(nextProps) {
		checkPropChange(this.props.react, nextProps.react, () => {
			this.setReact(nextProps);
		});
		checkPropChange(this.props.defaultSelected, nextProps.defaultSelected, () => {
			this.setValue(nextProps.defaultSelected, nextProps);
		});
		checkPropChange(this.props.queryFormat, nextProps.queryFormat, () => {
			this.updateQuery(this.state.currentValue, nextProps);
		});
	}

	componentWillUnmount() {
		this.props.removeComponent(this.props.componentId);
	}

	defaultQuery = (value, props) => {
		switch (props.queryFormat) {
			case "exact":
				return {
					term: {
						[props.dataField]: value
					}
				};
			case "lte":
				return {
					range: {
						[props.dataField]: {
							lte: value,
							boost: 2.0
						}
					}
				};
			case "gte":
				return {
					range: {
						[props.dataField]: {
							gte: value,
							boost: 2.0
						}
					}
				};
			default:
				return null;
		}
	};

	setReact(props) {
		if (props.react) {
			props.watchComponent(props.componentId, props.react);
		}
	}

	incrementValue = () => {
		if (this.state.currentValue === this.props.data.end) {
			return;
		}
		const { currentValue } = this.state;
		this.setValue(currentValue + 1);
	};

	decrementValue = () => {
		if (this.state.currentValue === this.props.data.start) {
			return;
		}
		const { currentValue } = this.state;
		this.setValue(currentValue - 1);
	};

	setValue = (value, props = this.props) => {
		const performUpdate = () => {
			this.setState({
				currentValue: value
			}, () => {
				this.updateQuery(value, props);
			});
		};
		checkValueChange(
			props.componentId,
			value,
			props.beforeValueChange,
			props.onValueChange,
			performUpdate
		);
	};

	updateQuery = (value, props) => {
		const query = props.customQuery || this.defaultQuery;
		let onQueryChange = null;
		if (props.onQueryChange) {
			onQueryChange = props.onQueryChange;
		}
		props.updateQuery({
			componentId: props.componentId,
			query: query(value, props),
			value,
			onQueryChange,
			showFilter: false,	// we don't need filters for NumberBox
			URLParams: props.URLParams
		});
	};

	render() {
		return (

				{this.props.title && <Title>{this.props.title}</Title>}
				<Flex labelPosition={this.props.labelPosition} inline>
					{this.props.data.label}

						<Button
							onClick={this.decrementValue}
							disabled={this.state.currentValue === this.props.data.start}
						>
							-
						</Button>
						{this.state.currentValue}
						<Button
							onClick={this.incrementValue}
							disabled={this.state.currentValue === this.props.data.end}
						>
							+
						</Button>

				</Flex>

		);
	}
}

NumberBox.propTypes = {
	addComponent: types.funcRequired,
	componentId: types.stringRequired,
	defaultSelected: types.number,
	data: types.dataNumberBox,
	react: types.react,
	removeComponent: types.funcRequired,
	title: types.title,
	queryFormat: types.queryFormatNumberBox,
	labelPosition: types.labelPosition,
	URLParams: types.boolRequired,
	selectedValue: types.selectedValue
};

NumberBox.defaultProps = {
	queryFormat: "gte",
	labelPosition: "left",
	URLParams: false
};

const mapStateToProps = (state, props) => ({
	selectedValue: state.selectedValues[props.componentId] ? state.selectedValues[props.componentId].value : null
});

const mapDispatchtoProps = (dispatch, props) => ({
	addComponent: component => dispatch(addComponent(component)),
	removeComponent: component => dispatch(removeComponent(component)),
	watchComponent: (component, react) =>
		dispatch(watchComponent(component, react)),
	updateQuery: updateQueryObject => dispatch(updateQuery(updateQueryObject))
});

export default connect(mapStateToProps, mapDispatchtoProps)(NumberBox);
<|endoftext|>


<commit_before>import forEach from 'lodash.foreach'
import moment from 'moment'

export const configurationSchema = {
  type: 'object',

  properties: {
    toMails: {
      type: 'array',
      title: 'mails',
      description: 'an array of recipients (mails)',

      items: {
        type: 'string'
      },
      minItems: 1
    },
    toXmpp: {
      type: 'array',
      title: 'xmpp address',
      description: 'an array of recipients (xmpp)',

      items: {
        type: 'string'
      },
      minItems: 1
    }
  }
}

// ===================================================================

class BackupReportsXoPlugin {
  constructor (xo) {
    this._xo = xo
    this._report = ::this._wrapper
  }

  configure ({ toMails, toXmpp }) {
    this._mailsReceivers = toMails
    this._xmppReceivers = toXmpp
  }

  load () {
    this._xo.on('job:terminated', this._report)
  }

  unload () {
    this._xo.removeListener('job:terminated', this._report)
  }

  async _wrapper (status) {
    try {
      await this._listener(status)
    } catch (e) {
      console.error('backup report error: ' + e)
    }
  }

  async _listener (status) {
    let nSuccess = 0
    let nCalls = 0

    const text = []

    forEach(status.calls, call => {
      // Ignore call if it's not a Backup a Snapshot or a Disaster Recovery.
      if (call.method !== 'vm.deltaCopy' &&
          call.method !== 'vm.rollingDeltaBackup') {
          call.method !== 'vm.rollingDrCopy' &&
          call.method !== 'vm.rollingSnapshot' &&
          call.method !== 'vm.rollingBackup')
        return
      }

      let vmStatus

      if (call.error) {
        vmStatus = 'Fail'
      } else {
        nSuccess++
        vmStatus = 'Success'
      }

      nCalls++

      let vm

      try {
        vm = this._xo.getObject(call.params.id)
      } catch (e) {}

      const start = moment(call.start)
      const end = moment(call.end)
      const duration = moment.duration(end - start).humanize()

      text.push([
        `### VM : ${vm ? vm.name_label : 'undefined'}`,
        `  - UUID: ${vm ? vm.uuid : 'undefined'}`,
        `  - Status: ${vmStatus}`,
        `  - Start time: ${String(start)}`,
        `  - End time: ${String(end)}`,
        `  - Duration: ${duration}`
      ].join('\n'))
    })

    // No backup calls.
    if (nCalls === 0) {
      return
    }

    const globalStatus = nSuccess === nCalls ? 'Success' : 'Fail'
    const start = moment(status.start)
    const end = moment(status.end)
    const duration = moment.duration(end - start).humanize()

    // Global status.
    text.unshift([
      `## Global status: ${globalStatus}`,
      `  - Start time: ${String(start)}`,
      `  - End time: ${String(end)}`,
      `  - Duration: ${duration}`,
      `  - Successful backed up VM number: ${nSuccess}`,
      `  - Failed backed up VM: ${nCalls - nSuccess}`
    ].join('\n'))

    const markdown = text.join('\n')

    // TODO : Handle errors when `sendEmail` isn't present. (Plugin dependencies)

    if (this._xo.sendEmail) {
      await this._xo.sendEmail({
        to: this._mailsReceivers,
        subject: 'Backup Reports (XenOrchestra)',
        markdown
      })
    }

    if (this._xo.sendToXmppClient) {
      this._xo.sendToXmppClient({
        to: this._xmppReceivers,
        message: markdown
      })
    }
  }
}

// ===================================================================

export default ({xo}) => new BackupReportsXoPlugin(xo)
<commit_msg>FIx my previous commit -_-".<commit_after>import forEach from 'lodash.foreach'
import moment from 'moment'

export const configurationSchema = {
  type: 'object',

  properties: {
    toMails: {
      type: 'array',
      title: 'mails',
      description: 'an array of recipients (mails)',

      items: {
        type: 'string'
      },
      minItems: 1
    },
    toXmpp: {
      type: 'array',
      title: 'xmpp address',
      description: 'an array of recipients (xmpp)',

      items: {
        type: 'string'
      },
      minItems: 1
    }
  }
}

// ===================================================================

class BackupReportsXoPlugin {
  constructor (xo) {
    this._xo = xo
    this._report = ::this._wrapper
  }

  configure ({ toMails, toXmpp }) {
    this._mailsReceivers = toMails
    this._xmppReceivers = toXmpp
  }

  load () {
    this._xo.on('job:terminated', this._report)
  }

  unload () {
    this._xo.removeListener('job:terminated', this._report)
  }

  async _wrapper (status) {
    try {
      await this._listener(status)
    } catch (e) {
      console.error('backup report error: ' + e)
    }
  }

  async _listener (status) {
    let nSuccess = 0
    let nCalls = 0

    const text = []

    forEach(status.calls, call => {
      // Ignore call if it's not a Backup a Snapshot or a Disaster Recovery.
      if (call.method !== 'vm.deltaCopy' &&
          call.method !== 'vm.rollingDeltaBackup' &&
          call.method !== 'vm.rollingDrCopy' &&
          call.method !== 'vm.rollingSnapshot' &&
          call.method !== 'vm.rollingBackup') {
        return
      }

      let vmStatus

      if (call.error) {
        vmStatus = 'Fail'
      } else {
        nSuccess++
        vmStatus = 'Success'
      }

      nCalls++

      let vm

      try {
        vm = this._xo.getObject(call.params.id)
      } catch (e) {}

      const start = moment(call.start)
      const end = moment(call.end)
      const duration = moment.duration(end - start).humanize()

      text.push([
        `### VM : ${vm ? vm.name_label : 'undefined'}`,
        `  - UUID: ${vm ? vm.uuid : 'undefined'}`,
        `  - Status: ${vmStatus}`,
        `  - Start time: ${String(start)}`,
        `  - End time: ${String(end)}`,
        `  - Duration: ${duration}`
      ].join('\n'))
    })

    // No backup calls.
    if (nCalls === 0) {
      return
    }

    const globalStatus = nSuccess === nCalls ? 'Success' : 'Fail'
    const start = moment(status.start)
    const end = moment(status.end)
    const duration = moment.duration(end - start).humanize()

    // Global status.
    text.unshift([
      `## Global status: ${globalStatus}`,
      `  - Start time: ${String(start)}`,
      `  - End time: ${String(end)}`,
      `  - Duration: ${duration}`,
      `  - Successful backed up VM number: ${nSuccess}`,
      `  - Failed backed up VM: ${nCalls - nSuccess}`
    ].join('\n'))

    const markdown = text.join('\n')

    // TODO : Handle errors when `sendEmail` isn't present. (Plugin dependencies)

    if (this._xo.sendEmail) {
      await this._xo.sendEmail({
        to: this._mailsReceivers,
        subject: 'Backup Reports (XenOrchestra)',
        markdown
      })
    }

    if (this._xo.sendToXmppClient) {
      this._xo.sendToXmppClient({
        to: this._xmppReceivers,
        message: markdown
      })
    }
  }
}

// ===================================================================

export default ({xo}) => new BackupReportsXoPlugin(xo)
<|endoftext|>


<commit_before>/**
 * Ajax.org Code Editor (ACE)
 *
 * @copyright 2010, Ajax.org Services B.V.
 * @license LGPLv3 <http://www.gnu.org/licenses/lgpl-3.0.txt>
 * @author Fabian Jakobs <fabian AT ajax DOT org>
 */
require.def("ace/mode/JavaScriptHighlightRules",
     [
         "ace/lib/oop",
         "ace/lib/lang",
         "ace/mode/DocCommentHighlightRules",
         "ace/mode/TextHighlightRules"
     ], function(oop, lang, DocCommentHighlightRules, TextHighlightRules) {

JavaScriptHighlightRules = function() {

    var docComment = new DocCommentHighlightRules();

    var keywords = lang.arrayToMap(
        ("break|case|catch|continue|default|delete|do|else|finally|for|function|\
        if|in|instanceof|new|return|switch|throw|try|typeof|var|while|with").split("|")
    );

    var buildinConstants = lang.arrayToMap(
        ("true|false|null|undefined|Infinity|NaN|undefined").split("|")
    );

    var futureReserved = lang.arrayToMap(
        ("class|enum|extends|super|const|export|import|implements|let|private|\
        public|yield|interface|package|protected|static").split("|")
    );

    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "\\/\\/.*$"
        },
        docComment.getStartRule("doc-start"),
        {
            token : "comment", // multi line comment
            regex : "\\/\\*",
            next : "comment"
        }, {
            token : "string", // single line
            regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
        }, {
            token : "string", // multi line string start
            regex : '["].*\\\\$',
            next : "qqstring"
        }, {
            token : "string", // single line
            regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
        }, {
            token : "string", // multi line string start
            regex : "['].*\\\\$",
            next : "qstring"
        }, {
            token : "number", // hex
            regex : "0[xX][0-9a-fA-F]+\\b"
        }, {
            token : "number", // float
            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
        }, {
            token : function(value) {
                if (value == "this")
                    return "variable";
                else if (keywords[value])
                    return "keyword";
                else if (buildinConstants[value])
                    return "buildin-constant";
                else if (futureReserved[value] || value == "debugger")
                    return "invalid";
                else
                    return "identifier";
            },
            regex : "[a-zA-Z_][a-zA-Z0-9_]*\\b"
        }, {
            token : "operator",
            regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(in|instanceof|new|delete|typeof|void)"
        }, {
            token : "lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "rparen",
            regex : "[\\]\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ],
        "comment" : [ {
            token : "comment", // closing comment
            regex : ".*?\\*\\/",
            next : "start"
        }, {
            token : "comment", // comment spanning whole line
            regex : ".+"
        } ],
        "qqstring" : [ {
            token : "string",
            regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
            next : "start"
        }, {
            token : "string",
            regex : '.+'
        } ],
        "qstring" : [ {
            token : "string",
            regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
            next : "start"
        }, {
            token : "string",
            regex : '.+'
        } ]
    };

    this.addRules(docComment.getRules(), "doc-");
    this.$rules["doc-start"][0].next = "start";
};

oop.inherits(JavaScriptHighlightRules, TextHighlightRules);

return JavaScriptHighlightRules;
});<commit_msg>also highlight "if"<commit_after>/**
 * Ajax.org Code Editor (ACE)
 *
 * @copyright 2010, Ajax.org Services B.V.
 * @license LGPLv3 <http://www.gnu.org/licenses/lgpl-3.0.txt>
 * @author Fabian Jakobs <fabian AT ajax DOT org>
 */
require.def("ace/mode/JavaScriptHighlightRules",
     [
         "ace/lib/oop",
         "ace/lib/lang",
         "ace/mode/DocCommentHighlightRules",
         "ace/mode/TextHighlightRules"
     ], function(oop, lang, DocCommentHighlightRules, TextHighlightRules) {

JavaScriptHighlightRules = function() {

    var docComment = new DocCommentHighlightRules();

    var keywords = lang.arrayToMap(
        ("break|case|catch|continue|default|delete|do|else|finally|for|function|" +
        "if|in|instanceof|new|return|switch|throw|try|typeof|var|while|with").split("|")
    );

    var buildinConstants = lang.arrayToMap(
        ("true|false|null|undefined|Infinity|NaN|undefined").split("|")
    );

    var futureReserved = lang.arrayToMap(
        ("class|enum|extends|super|const|export|import|implements|let|private|" +
        "public|yield|interface|package|protected|static").split("|")
    );

    // regexp must not have capturing parentheses. Use (?:) instead.
    // regexps are ordered -> the first match is used

    this.$rules = {
        "start" : [ {
            token : "comment",
            regex : "\\/\\/.*$"
        },
        docComment.getStartRule("doc-start"),
        {
            token : "comment", // multi line comment
            regex : "\\/\\*",
            next : "comment"
        }, {
            token : "string", // single line
            regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
        }, {
            token : "string", // multi line string start
            regex : '["].*\\\\$',
            next : "qqstring"
        }, {
            token : "string", // single line
            regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
        }, {
            token : "string", // multi line string start
            regex : "['].*\\\\$",
            next : "qstring"
        }, {
            token : "number", // hex
            regex : "0[xX][0-9a-fA-F]+\\b"
        }, {
            token : "number", // float
            regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
        }, {
            token : function(value) {
                if (value == "this")
                    return "variable";
                else if (keywords[value])
                    return "keyword";
                else if (buildinConstants[value])
                    return "buildin-constant";
                else if (futureReserved[value] || value == "debugger")
                    return "invalid";
                else
                    return "identifier";
            },
            regex : "[a-zA-Z_][a-zA-Z0-9_]*\\b"
        }, {
            token : "operator",
            regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(in|instanceof|new|delete|typeof|void)"
        }, {
            token : "lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "rparen",
            regex : "[\\]\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ],
        "comment" : [ {
            token : "comment", // closing comment
            regex : ".*?\\*\\/",
            next : "start"
        }, {
            token : "comment", // comment spanning whole line
            regex : ".+"
        } ],
        "qqstring" : [ {
            token : "string",
            regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
            next : "start"
        }, {
            token : "string",
            regex : '.+'
        } ],
        "qstring" : [ {
            token : "string",
            regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
            next : "start"
        }, {
            token : "string",
            regex : '.+'
        } ]
    };

    this.addRules(docComment.getRules(), "doc-");
    this.$rules["doc-start"][0].next = "start";
};

oop.inherits(JavaScriptHighlightRules, TextHighlightRules);

return JavaScriptHighlightRules;
});<|endoftext|>


<commit_before>// file: lib/mdlUpgrade.js
import { findDOMNode } from 'react-dom';
import CSSModules from 'react-css-modules';
import { mdl } from "exports?mdl=componentHandler!material-design-lite/material";

export default (WrappedComponent, styles = {}, options = {}) => {
  const CSSComponent = CSSModules(WrappedComponent, styles, options);
  return class extends CSSComponent {
    componentDidMount() {
      if(super.componentDidMount){
        super.componentDidMount();
      }
      mdl.upgradeElements(findDOMNode(this));
    }
    componentWillUnmount(){
      if(super.componentWillUnmount){
        super.componentWillUnmount();
      }
      mdl.downgradeElements(findDOMNode(this));
    }
  }
}
<commit_msg>Decouple mdlUpgrade from CSSModules for enhanced performance and flexibility<commit_after>// file: lib/mdlUpgrade.js
import { findDOMNode } from 'react-dom';
import { mdl } from "exports?mdl=componentHandler!material-design-lite/material";

export default (WrappedComponent) => {
  return class extends WrappedComponent {
    componentDidMount() {
      if(super.componentDidMount){
        super.componentDidMount();
      }
      mdl.upgradeElements(findDOMNode(this));
    }
    componentWillUnmount(){
      if(super.componentWillUnmount){
        super.componentWillUnmount();
      }
      mdl.downgradeElements(findDOMNode(this));
    }
  }
}
<|endoftext|>


<commit_before>/* @flow */
const { createAction } = require('redux-actions')
const { get_body, post, post_body } = require('app/http')

const
  { lensPath, over, not, indexBy, map, propOr, merge, zipWith, ifElse, gte
  , cond, where, objOf, zip, set, lift, assoc, dissoc, prop, converge, omit
  , sortBy, lensProp, reverse, compose: r_compose }
  = require('ramda')
const { pipe, compose } = require('sanctuary')

const { standing, lates, newsletter_alert, newsletter_reminder, subscription_due } =
  require('./bodies.js')

export const SEND_SUB_REMINDER =
  'SEND_SUB_REMINDER'
export const SEND_NEWSLETTER =
  'SEND_NEWSLETTER'
export const SEND_NEWSLETTER_REMINDER =
  'SEND_NEWSLETTER_REMINDER'
export const COMPOSE_CUSTOM =
  'COMPOSE_CUSTOM'
export const GET_BOUNCED =
  'GET_BOUNCED'
export const SUB_DUE_TAB =
  'SUB_DUE_TAB'
const SEND_WELCOME =
  'SEND_WELCOME'
const TOGGLE_LIST =
  'TOGGLE_LIST'
const TOGGLE_CONTENT =
  'TOGGLE_CONTENT'
const SUBMIT_EMAIL =
  'SUBMIT_EMAIL'
const SUBMIT_CUSTOM_EMAIL =
  'SUBMIT_CUSTOM_EMAIL'
const SEND_SUBSCRIPTION_DUE_EMAIL =
  'SEND_SUBSCRIPTION_DUE_EMAIL'
const PREVIEW_CUSTOM =
  'PREVIEW_CUSTOM'
const EDIT_CUSTOM =
  'EDIT_CUSTOM'

import type { Action, Reducer } from 'redux'

type State = { emails: { [key: string]: { overdue: number } }
             , custom_emails: { }
             }

const initialState = { emails: { }
                     , custom_emails: { }
                     }

const reducer : Reducer<State, Action>
  = (state = initialState, { type, payload }) => {
    const newState = omit(['custom_emails', 'email_sent', 'bounced'])(state)
    const update = lens => value => (set(lens, value, newState) : State)
    const emails = lensPath([ 'emails' ])
    const sent = lensPath([ 'email_sent' ])
    const list_hidden = lensPath([ 'list_hidden' ])
    const new_emails = template => shape =>
      update(emails)(map(compose(Email, template), shape(payload.results)))
    const change_tab = assoc('active_tab', type)
    switch (type) {
      case SEND_SUB_REMINDER:
        return change_tab(new_emails(template_subs)(primaries))
      case SEND_NEWSLETTER:
        return change_tab(new_emails(newsletter_alert)(shape_newsletters))
      case SEND_NEWSLETTER_REMINDER:
        return change_tab(new_emails(newsletter_reminder)(shape_newsletters))
      case COMPOSE_CUSTOM:
        return change_tab({ ...newState, custom_emails: { members: payload.results } })
      case TOGGLE_LIST:
        return (over(list_hidden, not, state): State)
      case TOGGLE_CONTENT:
        return toggle_show(payload)(state)
      case SEND_WELCOME:
        return update(sent)(true)
      case SUBMIT_EMAIL:
        return email_response(state)(payload)
      case GET_BOUNCED:
        return change_tab({ ...newState, bounced: sort_by_date(payload.results.items) })
      case SUBMIT_CUSTOM_EMAIL:
        return email_response(state)(payload)
      case SEND_SUBSCRIPTION_DUE_EMAIL:
        return new_emails(subscription_due)(shape_newsletters)
      case SUB_DUE_TAB:
        return change_tab({...newState, emails: {}})
      case PREVIEW_CUSTOM:
          return { ...state, custom_emails: { ...state.custom_emails, preview: payload, mode: type } }
      case EDIT_CUSTOM:
        return { ...state, custom_emails: { ...state.custom_emails, mode: type } }
      default:
        return state
    }
  }

export default reducer

const sort_by_date = pipe([map(over(lensProp('created_at'), Date.parse)), sortBy(prop('created_at')), reverse])

const Email = content => (
  { content: content.split('\n')
  , shown: false
  }
)

const email_response = state => res => (
  { ...state
  , email_sent: res.results ? 'success' : res.error.address
  }
)

const time_check = pipe([gte, objOf('overdue'), where])

const templating =
  compose(cond, zip(map(time_check, [60, 90, Infinity])))

const missing_standing_order = templating(standing)

const late_payment = templating(lates)

const template_subs = ifElse
  ( propOr(false, 'standing_order')
  , missing_standing_order
  , late_payment
  )

const indexByProp = compose(indexBy, propOr(''))

const greeting = member => assoc
  ( 'greeting'
  , member.first_name || member.title + ' ' + member.last_name
  , member
  )

const [ primaries, secondaries ] =
  map
    ( compose(map(map(map(greeting), dissoc('null'))), indexByProp)
    , [ 'primary_email', 'secondary_email' ]
    )

const shape_newsletters = lift(merge)(primaries, secondaries)

const toggle_show = (address: string) => (state: State): State => {
  const shown_lens = lensPath([ 'emails', address, 'shown' ])
  return over(shown_lens, not, state)
}

export const send_welcome =
  createAction(SEND_WELCOME, email => post({ email }, '/api/members/welcome'))

export const send_sub_reminder =
  createAction(SEND_SUB_REMINDER, () => get_body('api/reminders'))

export const send_newsletter =
  createAction(SEND_NEWSLETTER, () => get_body('api/newsletter-alert'))

export const send_newsletter_reminder =
  createAction(SEND_NEWSLETTER_REMINDER, () => get_body('api/newsletter-alert'))

export const send_subscription_due_email =
  createAction(SEND_SUBSCRIPTION_DUE_EMAIL, body => post_body({...body, news_type: 'online'}, 'api/subscription-due'))

export const compose_custom =
  createAction(COMPOSE_CUSTOM, () => get_body('api/custom-email'))

export const toggle_list =
  createAction(TOGGLE_LIST)

export const toggle_content =
  createAction(TOGGLE_CONTENT)

export const submit_email =
  createAction(SUBMIT_EMAIL, email => post_body({ email }, '/api/submit-email'))

export const get_bounced =
  createAction(GET_BOUNCED, () => get_body('/api/get-bounced'))

export const sub_due_tab =
  createAction(SUB_DUE_TAB)

export const preview_custom =
  createAction(PREVIEW_CUSTOM)

export const edit_custom =
  createAction(EDIT_CUSTOM)

export const submit_custom_email =
  createAction(SUBMIT_CUSTOM_EMAIL, (members, form) => {
    const format_message = form => member => (
      [ form[0]
      , 'Friends of Chichester Harbour'
      , `Dear ${member.first_name || member.title} ${member.last_name},`
      , form[1]
      ]
    )
    const template = format_message(form)
    const emailBodies = map(compose(objOf('content'), template), members)
    const emailsArr = zipWith(merge, members, emailBodies)
    const setEmailKey = map(compose(indexBy, prop), ['primary_email', 'secondary_email'])
    const shapedEmails = compose(dissoc('null'), converge(merge, setEmailKey))(emailsArr)
    return post_body({ email: shapedEmails }, '/api/submit-email')
  })
<commit_msg>remove unused compose function<commit_after>/* @flow */
const { createAction } = require('redux-actions')
const { get_body, post, post_body } = require('app/http')

const
  { lensPath, over, not, indexBy, map, propOr, merge, zipWith, ifElse, gte
  , cond, where, objOf, zip, set, lift, assoc, dissoc, prop, converge, omit
  , sortBy, lensProp, reverse}
  = require('ramda')
const { pipe, compose } = require('sanctuary')

const { standing, lates, newsletter_alert, newsletter_reminder, subscription_due } =
  require('./bodies.js')

export const SEND_SUB_REMINDER =
  'SEND_SUB_REMINDER'
export const SEND_NEWSLETTER =
  'SEND_NEWSLETTER'
export const SEND_NEWSLETTER_REMINDER =
  'SEND_NEWSLETTER_REMINDER'
export const COMPOSE_CUSTOM =
  'COMPOSE_CUSTOM'
export const GET_BOUNCED =
  'GET_BOUNCED'
export const SUB_DUE_TAB =
  'SUB_DUE_TAB'
const SEND_WELCOME =
  'SEND_WELCOME'
const TOGGLE_LIST =
  'TOGGLE_LIST'
const TOGGLE_CONTENT =
  'TOGGLE_CONTENT'
const SUBMIT_EMAIL =
  'SUBMIT_EMAIL'
const SUBMIT_CUSTOM_EMAIL =
  'SUBMIT_CUSTOM_EMAIL'
const SEND_SUBSCRIPTION_DUE_EMAIL =
  'SEND_SUBSCRIPTION_DUE_EMAIL'
const PREVIEW_CUSTOM =
  'PREVIEW_CUSTOM'
const EDIT_CUSTOM =
  'EDIT_CUSTOM'

import type { Action, Reducer } from 'redux'

type State = { emails: { [key: string]: { overdue: number } }
             , custom_emails: { }
             }

const initialState = { emails: { }
                     , custom_emails: { }
                     }

const reducer : Reducer<State, Action>
  = (state = initialState, { type, payload }) => {
    const newState = omit(['custom_emails', 'email_sent', 'bounced'])(state)
    const update = lens => value => (set(lens, value, newState) : State)
    const emails = lensPath([ 'emails' ])
    const sent = lensPath([ 'email_sent' ])
    const list_hidden = lensPath([ 'list_hidden' ])
    const new_emails = template => shape =>
      update(emails)(map(compose(Email, template), shape(payload.results)))
    const change_tab = assoc('active_tab', type)
    switch (type) {
      case SEND_SUB_REMINDER:
        return change_tab(new_emails(template_subs)(primaries))
      case SEND_NEWSLETTER:
        return change_tab(new_emails(newsletter_alert)(shape_newsletters))
      case SEND_NEWSLETTER_REMINDER:
        return change_tab(new_emails(newsletter_reminder)(shape_newsletters))
      case COMPOSE_CUSTOM:
        return change_tab({ ...newState, custom_emails: { members: payload.results } })
      case TOGGLE_LIST:
        return (over(list_hidden, not, state): State)
      case TOGGLE_CONTENT:
        return toggle_show(payload)(state)
      case SEND_WELCOME:
        return update(sent)(true)
      case SUBMIT_EMAIL:
        return email_response(state)(payload)
      case GET_BOUNCED:
        return change_tab({ ...newState, bounced: sort_by_date(payload.results.items) })
      case SUBMIT_CUSTOM_EMAIL:
        return email_response(state)(payload)
      case SEND_SUBSCRIPTION_DUE_EMAIL:
        return new_emails(subscription_due)(shape_newsletters)
      case SUB_DUE_TAB:
        return change_tab({...newState, emails: {}})
      case PREVIEW_CUSTOM:
          return { ...state, custom_emails: { ...state.custom_emails, preview: payload, mode: type } }
      case EDIT_CUSTOM:
        return { ...state, custom_emails: { ...state.custom_emails, mode: type } }
      default:
        return state
    }
  }

export default reducer

const sort_by_date = pipe([map(over(lensProp('created_at'), Date.parse)), sortBy(prop('created_at')), reverse])

const Email = content => (
  { content: content.split('\n')
  , shown: false
  }
)

const email_response = state => res => (
  { ...state
  , email_sent: res.results ? 'success' : res.error.address
  }
)

const time_check = pipe([gte, objOf('overdue'), where])

const templating =
  compose(cond, zip(map(time_check, [60, 90, Infinity])))

const missing_standing_order = templating(standing)

const late_payment = templating(lates)

const template_subs = ifElse
  ( propOr(false, 'standing_order')
  , missing_standing_order
  , late_payment
  )

const indexByProp = compose(indexBy, propOr(''))

const greeting = member => assoc
  ( 'greeting'
  , member.first_name || member.title + ' ' + member.last_name
  , member
  )

const [ primaries, secondaries ] =
  map
    ( compose(map(map(map(greeting), dissoc('null'))), indexByProp)
    , [ 'primary_email', 'secondary_email' ]
    )

const shape_newsletters = lift(merge)(primaries, secondaries)

const toggle_show = (address: string) => (state: State): State => {
  const shown_lens = lensPath([ 'emails', address, 'shown' ])
  return over(shown_lens, not, state)
}

export const send_welcome =
  createAction(SEND_WELCOME, email => post({ email }, '/api/members/welcome'))

export const send_sub_reminder =
  createAction(SEND_SUB_REMINDER, () => get_body('api/reminders'))

export const send_newsletter =
  createAction(SEND_NEWSLETTER, () => get_body('api/newsletter-alert'))

export const send_newsletter_reminder =
  createAction(SEND_NEWSLETTER_REMINDER, () => get_body('api/newsletter-alert'))

export const send_subscription_due_email =
  createAction(SEND_SUBSCRIPTION_DUE_EMAIL, body => post_body({...body, news_type: 'online'}, 'api/subscription-due'))

export const compose_custom =
  createAction(COMPOSE_CUSTOM, () => get_body('api/custom-email'))

export const toggle_list =
  createAction(TOGGLE_LIST)

export const toggle_content =
  createAction(TOGGLE_CONTENT)

export const submit_email =
  createAction(SUBMIT_EMAIL, email => post_body({ email }, '/api/submit-email'))

export const get_bounced =
  createAction(GET_BOUNCED, () => get_body('/api/get-bounced'))

export const sub_due_tab =
  createAction(SUB_DUE_TAB)

export const preview_custom =
  createAction(PREVIEW_CUSTOM)

export const edit_custom =
  createAction(EDIT_CUSTOM)

export const submit_custom_email =
  createAction(SUBMIT_CUSTOM_EMAIL, (members, form) => {
    const format_message = form => member => (
      [ form[0]
      , 'Friends of Chichester Harbour'
      , `Dear ${member.first_name || member.title} ${member.last_name},`
      , form[1]
      ]
    )
    const template = format_message(form)
    const emailBodies = map(compose(objOf('content'), template), members)
    const emailsArr = zipWith(merge, members, emailBodies)
    const setEmailKey = map(compose(indexBy, prop), ['primary_email', 'secondary_email'])
    const shapedEmails = compose(dissoc('null'), converge(merge, setEmailKey))(emailsArr)
    return post_body({ email: shapedEmails }, '/api/submit-email')
  })
<|endoftext|>


<commit_before>Jsonix.Model.PropertyInfo = Jsonix
		.Class({
			name : null,
			collection : false,
			defaultElementNamespaceURI : '',
			defaultAttributeNamespaceURI : '',
			built : false,
			initialize : function(options) {
				Jsonix.Util.Ensure.ensureObject(options);
				Jsonix.Util.Ensure.ensureString(options.name);
				this.name = options.name;
				if (Jsonix.Util.Type
						.isString(options.defaultElementNamespaceURI)) {
					this.defaultElementNamespaceURI = options.defaultElementNamespaceURI;
				}
				if (Jsonix.Util.Type
						.isString(options.defaultAttributeNamespaceURI)) {
					this.defaultAttributeNamespaceURI = options.defaultAttributeNamespaceURI;
				}
				if (Jsonix.Util.Type.isBoolean(options.collection)) {
					this.collection = options.collection;
				} else {
					this.collection = false;
				}
			},
			build : function(context, module) {
				if (!this.built) {
					this.doBuild(context, module);
					this.built = true;
				}
			},
			doBuild : function(context, module) {
				throw new Error("Abstract method [doBuild].");
			},
			buildStructure : function(context, structure) {
				throw new Error("Abstract method [buildStructure].");
			},
			setProperty : function(object, value) {
				if (Jsonix.Util.Type.exists(value)) {
					if (this.collection) {
						Jsonix.Util.Ensure.ensureArray(value,
								'Collection property requires an array value.');
						if (!Jsonix.Util.Type.exists(object[this.name])) {
							object[this.name] = [];
						}
						for ( var index = 0; index < value.length; index++) {
							object[this.name].push(value[index]);
						}

					} else {
						object[this.name] = value;
					}
				}
			},
			CLASS_NAME : 'Jsonix.Model.PropertyInfo'
		});<commit_msg>Compact naming.<commit_after>Jsonix.Model.PropertyInfo = Jsonix
		.Class({
			name : null,
			collection : false,
			defaultElementNamespaceURI : '',
			defaultAttributeNamespaceURI : '',
			built : false,
			initialize : function(mapping) {
				Jsonix.Util.Ensure.ensureObject(mapping);
				var n = mapping.name||mapping.n;
				Jsonix.Util.Ensure.ensureString(n);
				this.name = n;
				var dens = mapping.defaultElementNamespaceURI||mapping.dens;
				if (Jsonix.Util.Type.isString(dens)) {
					this.defaultElementNamespaceURI = dens;
				}
				var dans = mapping.defaultAttributeNamespaceURI||mapping.dans;
				if (Jsonix.Util.Type.isString(dans)) {
					this.defaultAttributeNamespaceURI = dans;
				}
				var col = mapping.collection||mapping.col;
				if (Jsonix.Util.Type.isBoolean(col)) {
					this.collection = col;
				}
			},
			build : function(context, module) {
				if (!this.built) {
					this.doBuild(context, module);
					this.built = true;
				}
			},
			doBuild : function(context, module) {
				throw new Error("Abstract method [doBuild].");
			},
			buildStructure : function(context, structure) {
				throw new Error("Abstract method [buildStructure].");
			},
			setProperty : function(object, value) {
				if (Jsonix.Util.Type.exists(value)) {
					if (this.collection) {
						Jsonix.Util.Ensure.ensureArray(value,
								'Collection property requires an array value.');
						if (!Jsonix.Util.Type.exists(object[this.name])) {
							object[this.name] = [];
						}
						for ( var index = 0; index < value.length; index++) {
							object[this.name].push(value[index]);
						}

					} else {
						object[this.name] = value;
					}
				}
			},
			CLASS_NAME : 'Jsonix.Model.PropertyInfo'
		});<|endoftext|>