Пример #1
0
exports = module.exports = function(req, res) {
	
	var view = new keystone.View(req, res);
	var locals = res.locals;
	
	// Set locals
	locals.section = 'txt';
	locals.formData = req.body || {};
	locals.validationErrors = {};
	locals.txtSubmitted = false;

	view.on('post', { action: 'txt' }, function(next) {
		// { ch_upload: 
		//    { fieldname: 'ch_upload',
		//      originalname: '25-1chi.txt',
		//      name: 'a0fc48e98481053c64011295611076c9.txt',
		//      encoding: '7bit',
		//      mimetype: 'text/plain',
		//      path: '/var/folders/08/vtvnl3d552x501k99llb1lk40000gp/T/a0fc48e98481053c64011295611076c9.txt',
		//      extension: 'txt',
		//      size: 3037,
		//      truncated: false,
		//      buffer: null },
		//   en_upload: 
		//    { fieldname: 'en_upload',
		//      originalname: '25-1eng.txt',
		//      name: '613c29f34c515ff6c5bd6ada97283254.txt',
		//      encoding: '7bit',
		//      mimetype: 'text/plain',
		//      path: '/var/folders/08/vtvnl3d552x501k99llb1lk40000gp/T/613c29f34c515ff6c5bd6ada97283254.txt',
		//      extension: 'txt',
		//      size: 3298,
		//      truncated: false,
		//      buffer: null } }
		var chPath = req.files.ch_upload.path;
		var ch = fs.readFileSync(chPath, 'utf8');
		fs.unlinkSync(chPath);
		var chArr = ch.toString().trim('\n').split('\n');

		var enPath = req.files.en_upload.path;
		var en = fs.readFileSync(enPath, 'utf8');
		fs.unlinkSync(enPath);
		var enArr = en.toString().trim('\n').split("\n");

		var newArr = [];

		if (chArr.length !== enArr.length) {
			locals.validationErrors = {
				server: '句子数量不一致:' + chArr.length + '行中文,' + enArr.length + '行英文',
			}
			return next();
		}
		var length = Math.max(chArr.length, enArr.length);
		for (var i = 0; i < length; i++) {
			newArr.push(enArr[i]);
			newArr.push(chArr[i]);
			newArr.push('');
		}
		var newData = newArr.join('\n');
		fs.writeFileSync(enPath, newData, 'utf8');
		var randomStr = randomstring.generate(12);
		var putPolicy = new qiniu.rs.PutPolicy('scott');
		var uptoken = putPolicy.token();
		var extra = new qiniu.io.PutExtra();
		var qiniuPath = randomStr + '.txt';
		qiniu.io.putFile(uptoken,
			qiniuPath,
			enPath,
			extra,
			function(err, ret) {
				//{ hash: 'FhfWba548IMqCZb1hi0E2OXTJ5-2',
				// key: 'wkfRxA/data/files/1_28@2_0.mp4' }
				if (err) {
					console.log('upload error: ', err);
					locals.validationErrors = {
						server: '上传错误:' + JSON.stringify(err),
					}
					return next();
				}
				locals.txtSubmitted = true;
				locals.link = qiniuHost + '/' + ret.key;
				console.log('uploaded: ', ret);
				// remove filePath
				fs.unlinkSync(enPath);
				next();
			}
		);
	});
	
	view.render('txt');
	
};
Пример #2
0
exports = module.exports = function (req, res) {
	var locals = res.locals,
		view = new keystone.View(req, res);

	view.render('index', locals);
};
Пример #3
0
exports = module.exports = function(req, res) {
	
	var view = new keystone.View(req, res);
	var locals = res.locals;
	
	// Set locals
	locals.section = 'blog';
	locals.filters = {
		post: req.params.post
	};
	locals.data = {
		emails: []
	};
	
	// Load the current post
	view.on('init', function(next) {
		
		var q = keystone.list('MailingList').model.findOne({
			state: 'published',
			slug: locals.filters.post
		}).populate('author categories');
		
		q.exec(function(err, result) {
			locals.data.email = result;
			next(err);
		});
		
	});
	
	// Load other posts
	view.on('init', function(next) {
		
		var q = keystone.list('MailingList').model.find();
		
		q.exec(function(err, results) {
			//console.log(err, results);
			locals.data.emails = results;
			next(err);
		});
		
	});
	
	
	// Load other posts
	view.on('post', function(next) {
		var newEmail = new MailingList.model({
			email: req.body.email,
			timestamp: Date.now()
		});
		
		newEmail.save(function(err) {
			if(err != null) next(err);
			else res.redirect('/mailinglist');
		});
	});
	
	
	
	// Render the view
	if(lib.check_login(req, res)){
		view.render('mailinglist');
	}
};
Пример #4
0
exports = module.exports = function(req, res) {

	var view = new keystone.View(req, res),
		locals = res.locals;

	// Init locals
	locals.section = 'blog';
	locals.filters = {
		post: req.params.post
	};

	view.on('init', function(next) {
		var q = Post.model.findOne({
			state: 'published',
			slug: locals.filters.post,
		}).populate('author categories');
		q.exec(function (err, result) {
			if (!result) return res.notfound("Blog", "Not Found oops");
			locals.post = result;
			locals.page.title = result.title + ' - Blog - Upscale';
			next(err);
		});

	});

	view.on('init', function (next) {

		var q = Post.model.find().where('state', 'published').sort('-publishedDate').populate('author').limit(parseInt(4));
		q.exec(function (err, results) {
			locals.posts = results;
			next(err);
		});

	});


//Load Comments on post
	view.on('init', function (next) {
			PostComment.model.find()
				.where('post', locals.post)
				.where('commentState', 'published')
				.where('author').ne(null)
				.populate('author', 'name photo')
				.sort('-publishedOn')
				.exec(function (err, comments) {
					if (err) return res.err(err);
					if (!comments) return res.notfound('Post comments not found');
					locals.comments = comments;
					next();
				});
		});
		// Create a Comment
	view.on('post', { action: 'comment.create' }, function (next) {

		var newComment = new PostComment.model({
			state: 'published',
			post: locals.post.id,
			author: locals.user.id,
		});

		var updater = newComment.getUpdateHandler(req);

		updater.process(req.body, {
			fields: 'content',
			flashErrors: true,
			logErrors: true,
		}, function (err) {
			if (err) {
				validationErrors = err.errors;
			} else {
				req.flash('success', 'Your comment was added.');
				return res.redirect('/blog/post/' + locals.post.slug + '#comment-id-' + newComment.id);
			}
			next();
		});

	});

	// Delete a Comment
	view.on('get', { remove: 'comment' }, function (next) {

		if (!req.user) {
			req.flash('error', 'You must be signed in to delete a comment.');
			return next();
		}

		PostComment.model.findOne({
				_id: req.query.comment,
				post: locals.post.id,
			})
			.exec(function (err, comment) {
				if (err) {
					if (err.name === 'CastError') {
						req.flash('error', 'The comment ' + req.query.comment + ' could not be found.');
						return next();
					}
					return res.err(err);
				}
				if (!comment) {
					req.flash('error', 'The comment ' + req.query.comment + ' could not be found.');
					return next();
				}
				if (comment.author != req.user.id) {
					req.flash('error', 'Sorry, you must be the author of a comment to delete it.');
					return next();
				}
				comment.commentState = 'archived';
				comment.save(function (err) {
					if (err) return res.err(err);
					req.flash('success', 'Your comment has been deleted.');
					return res.redirect('/blog/post/' + locals.post.slug);
				});
			});
	});

	// Render the view
	view.render('site/post');

}
Пример #5
0
 function renderView(){
   view.render( 'signin' );
 }
Пример #6
0
exports = module.exports = function(req, res) {
	
	var view = new keystone.View(req, res),
		locals = res.locals;
	
	locals.section = 'me';
	
	view.query('meetups.next',
		Meetup.model.findOne()
			.where('date').gte(moment().startOf('day').toDate())
			.where('state', 'published')
			.sort('date')
	, 'talks[who]');
	
	view.query('meetups.past',
		Meetup.model.find()
			.where('date').lt(moment().subtract('days', 1).endOf('day').toDate())
			.where('state', 'published')
			.sort('-date')
	, 'talks[who]');
	
	view.on('post', { action: 'profile.top' }, function(next) {
	
		req.user.getUpdateHandler(req).process(req.body, {
			fields: 'name,email,twitter,website,github',
			flashErrors: true
		}, function(err) {
		
			if (err) {
				return next();
			}
			
			req.flash('success', 'Your changes have been saved.');
			return next();
		
		});
	
	});
	
	view.on('post', { action: 'profile.bottom' }, function(next) {
	
		req.user.getUpdateHandler(req).process(req.body, {
			fields: 'isPublic,bio,photo,mentoring.available,mentoring.free,mentoring.paid,mentoring.swap,mentoring.have,mentoring.want',
			flashErrors: true
		}, function(err) {
		
			if (err) {
				return next();
			}
			
			req.flash('success', 'Your changes have been saved.');
			return next();
		
		});
	
	});
	
	view.on('post', { action: 'profile.password' }, function(next) {
	
		if (!req.body.password || !req.body.password_confirm) {
			req.flash('error', 'Please enter a password.');
			return next();
		}
	
		req.user.getUpdateHandler(req).process(req.body, {
			fields: 'password',
			flashErrors: true
		}, function(err) {
		
			if (err) {
				return next();
			}
			
			req.flash('success', 'Your changes have been saved.');
			return next();
		
		});
	
	});
	
	view.on('render', function(next) {
		
		if (locals.meetups && locals.meetups.next) {
			RSVP.model.findOne().where('meetup', locals.meetups.next.id).where('who', req.user.id).exec(function(err, rsvp) {
				locals.meetups.nextRSVP = rsvp;
				next(err);
			});
		} else {
			next();
		}
		
	});
	
	view.render('site/me');
	
}
Пример #7
0
exports.init = module.exports.init = function(req, res) {
	
	var locals = res.locals, view = new keystone.View(req, res);

	// locals.section is used to set the currently selected
	// item in the header navigation.
	locals.section = 'Missions';
	var outcome = {};
	
	// If the user is not allowed to see this mission, reroute him to the permissions page
	// else move on
	var getMissionInfo = function(callback) {
		keystone.list('Mission').model.findOne({
			'missionId' : req.params.mid
		}).exec(function(err, mission) {
			if (err) {
				return callback(err, null);
			}
			if (!(mission.authorizedUsers.indexOf(req.user._id) > -1)) {
				console.error(err);
				res.redirect('/permissions');
				outcome.mission = mission;
				return;
			} 
			outcome.mission = mission;
			return callback(null, 'done');
		});
	};

	// For the selected mission, get all TAP descriptors available 
	var getTAPDescriptors = function(callback) {
		// For the Mission
	  keystone.list('Mission').model.findOne({ missionId: req.params.mid}, '_id', function(err, mission) {
			// Find all of it's TAP descriptors
			keystone.list('TAP').model.where('missionId', mission._id).where('ID').regex(/TAP_\d+/).sort('ID')
				.select('name ID').exec(
						// If it fails
						function(err, taps) {
							if (err) {
								return callback(err, null);
							}
							// Sort by ID number
							taps.sort(function(a, b) {
								return a.toObject().ID.split('_')[1] - b.toObject().ID.split('_')[1];
							});
							// Clean up and store the data
							var tap_descs = {};
							for (var i = 0; i < taps.length; i++) {
								tap_descs[taps[i].ID] = taps[i].toObject();
							}
							outcome.tap_descs = tap_descs;
							return callback(null, 'done');
						});
					});
				
	}
	
	// For the selected mission, get all CAP descriptors available
	var getCAPDescriptors = function(callback) {
		// For the selected mission
		keystone.list('Mission').model.findOne({ missionId: req.params.mid}, '_id', function(err, mission) {
			// Find all of the CAP descriptors
			keystone.list('CAP').model.where('missionId', mission._id).where('ID').regex(/CAP_\d+/).sort('ID')
				.exec(
						// If there's an error
						function(err, caps) {
							if (err) {
								return callback(err, null);
							}
							// Sort by ID Number
							caps.sort(function(a, b) {
								return a.toObject().ID.split('_')[1] - b.toObject().ID.split('_')[1];
							});
							// Clean up and store the data
							for (var i = 0; i < caps.length; i++) {
								caps[i] = caps[i].toObject();
								caps[i].header = outcome.mission.CAPHeader;
							}
							outcome.cap_descs = caps;

							return callback(null, 'done');
						});
				});
	}

	// Once all the above has completed, render the page
	function asyncFinally(err, results) {
		view.render('view_mission', {
			data : outcome
		});
	}
	
	// Call all of the above functions in parallel
	async.parallel([getCAPDescriptors, getMissionInfo, getTAPDescriptors ], asyncFinally);
};
	return function (req, res) {
		var view = new keystone.View(req, res);
		var locals = res.locals;

		// Init locals
		locals.section = section;
		locals.movies = [];
		locals.filters = {
			category: req.params[cate_key_name]
		};
		locals.category = undefined;
		locals.categories = [];
		locals.title = title + ' - 興大多媒體中心';

		view.on('init', function (callback) {
			co(function*() {
				var results = yield {
					// Load categories
					categories: Category.model.find().sort('-startDate').exec(),

					// Load the current root_category filter
					category: (locals.filters.category ?
						Category.model.where({key: locals.filters.category}) :
						Category.model).findOne().sort('-startDate').exec(),
				};
				for (var attrname in results) {
					locals[attrname] = results[attrname];
				}

				var movie_paginated_query = Movie.paginate({
					page    : req.query.page || 1,
					perPage : 16,
					maxPages: 10,
				})
				.where('state', 'published')
				.sort('-publishedDate')
				.populate('author region_categories theme_categories classification_categories');
				var movie_counts_query = Movie.model.find().where('state', 'published');

				var cate_query = {};
				cate_query[cate_key_name] = results.category._id;
				movie_paginated_query.where(cate_query);
				movie_counts_query.where(cate_query);

				results = yield {
					// Load movies
					movies: new Promise(function(resolve, reject){
						movie_paginated_query.exec(function(err, ret) {
							if (err) {
								reject(err);
							}	else {
								resolve(ret);
							}
						})
					}),
					movies_vanilla_result: movie_counts_query.exec()
				};

				locals.movies =	fix_keystone_pagination(results.movies,	results.movies_vanilla_result.length, 16);
			}).then(
				function(){
					callback();
				},
				function(e){
					console.error(e, e.stack); callback(e);
				}
			);
		});

		// Render the view
		view.render('movie_cate');
	};
Пример #9
0
exports = module.exports = function(req, res) {

	const view = new keystone.View(req, res);
	const locals = res.locals;

	// Init locals
	locals.section = 'berichten';
	locals.filters = {
		category: req.params.category
	};
	locals.data = {
		posts: [],
		categories: []
	};

	// Load all categories
	view.on('init', (next) => {

		let q = keystone.list('PostCategory').model.find().sort('name');
		q.exec((err, results) => {

			if (err || !results.length) {
				return next(err);
			}

			locals.data.categories = results;

			// Load the counts for each category
			async.each(locals.data.categories, (category, next) => {

				let q = keystone.list('Post').model.count().where('categories').in([category.id]);
				q.exec((err, count) => {
					category.postCount = count;
					next(err);
				});

			}, (err) => {
				next(err);
			});

		});

	});

	// Load the current category filter
	view.on('init', (next) => {

		if (req.params.category) {
			let q = keystone.list('PostCategory').model.findOne({ key: locals.filters.category });
			q.exec((err, result) => {
				locals.data.category = result;
				next(err);
			});
		} else {
			next();
		}

	});

	// Load the posts
	view.on('init', (next) => {

		let q = keystone.list('Post').paginate({
				page: req.query.page || 1,
				perPage: 10,
				maxPages: 10
			})
			.where('state', 'published')
			.sort('-publishedDate')
			.populate('author categories');

		if (locals.data.category) {
			q.where('categories').in([locals.data.category]);
		}

		q.exec((err, results) => {
			locals.data.posts = results;
			next(err);
		});

	});

	// Render the view
	view.render('blog');

};
Пример #10
0
exports = module.exports = function (req, res) {

	var view = new keystone.View(req, res);
	var locals = res.locals;

	var eventsCategoryName = 'events';
	var weeklySeriesCategoryName = 'weekly-series';
	var newsCategoryName = 'blog';
	var servicesCategoryName = 'service'

	var numberOfNews = 2;

	// locals.section is used to set the currently selected
	// item in the header navigation.
	locals.section = 'home';

	locals.data = {
		event: null,
		weeklySeriesEvent: null,
		promoBanner: locals.promoBanner,
		news: [],
		servicesContent: []
	};

	// Load last event
	view.on('init', function (next) {
		keystone.list('Post').schema.methods.postsForCategory(eventsCategoryName, 'Event', locals.defaultYear, (function (posts, err) {
			if (err) next(err);
			if (typeof posts != "undefined") {
				var nextPost = posts[0];
				var today = new Date();
				posts.forEach(function (post) {
					if (post.startDate && post.startDate > today) {
						nextPost = post;
					}
				}, this);
				locals.data.event = nextPost;
				next();
			}
		}));
	});

	view.on('init', function (next) {
		keystone.list('Post').schema.methods.postsForCategory(weeklySeriesCategoryName, 'Event', locals.defaultYear, (function (posts, err) {
			if (err) next(err);
			if (typeof posts != "undefined") {
				var nextPost = posts[0];
				var today = new Date();
				posts.forEach(function (post) {
					if (post.startDate && post.startDate > today) {
						nextPost = post;
					}
				}, this);
				locals.data.weeklySeriesEvent = nextPost;
				next();
			}

		}));
	});

	view.on('init', function (next) {
		keystone.list('Post').schema.methods.postsForCategory(newsCategoryName, 'Post', locals.defaultYear, (function (posts, err) {
			if (err) next(err);
			if (typeof posts != "undefined") {
				locals.data.news = posts.slice(0, numberOfNews);
				next();
			}
		}));
	});

	//Load services content
	view.on('init', function (next) {
		keystone.list('Post').schema.methods.postsForCategory(servicesCategoryName, 'Post', null, (function (posts, err) {
			if (err) next(err);
			if (typeof posts != "undefined") {
				locals.data.servicesContent = posts;
				next();
			}

		}));
	});

	// Render the view
	view.render('index');

};
Пример #11
0
exports = module.exports = function(req, res) {
	var view = new keystone.View(req, res),
		locals = res.locals;

	// Init locals
		locals.section = 'lifestyleindustry';
		locals.data = [];

	// Load the current Lifestyleindustry
	view.on('init', function(next) {
		var q = Lifestyleindustry.model.find();
		q.exec(function(err, results) {
			locals.data.lifestyleindustrys = results;
			next(err);
		});
	});

	// Load the current Navbar
	view.on('init', function(next) {
		var q = Navbar.model.find();
		q.exec(function(err, results) {
			locals.data.navbars = results;
			next(err);
		});
	});

	// Load the current MenuList
	view.on('init', function(next) {
		var q = MenuList.model.find();
		q.exec(function(err, results) {
   			locals.data.menus = results;
			next(err);
		});
	});

	// Load the current FooterList
	view.on('init', function(next) {
		var q = FooterList.model.find();
		q.exec(function(err, results) {
   			locals.data.footers = results;
			next(err);
		});
	});

	// Load Current Footermenunavigation
	view.on('init', function(next) {
		var q = Footermenunavigation.model.find();
		q.exec(function(err, results) {
			locals.data.footermenunavigations = results;
			next(err);
		});
	});

	// Load the current Message
	// view.on('init', function(next) {
	// 	var q = Message.model.find();
	// 	q.exec(function(err, results) {
	// 		locals.data.messages = results;
	// 		console.log("hello");
	// 		next(err);
	// 	});
	// });
	// Render the view
	view.render('lifestyleindustry');
}
Пример #12
0
	q.exec(function(err, results) {
		locals.data.posts=results;
		view.render('mobile/services/households');
	});
Пример #13
0
exports = module.exports = function(req, res) {
	var view = new keystone.View(req, res),
		locals = res.locals;

	// Init locals
		locals.section = 'tibcospotfirecustom';
		locals.data = [];

	// Load the current tibcospotfirecustom
	view.on('init', function(next) {
		var q = Tibcospotfirecustom.model.find();
		q.exec(function(err, results) {
			locals.data.tibcospotfirecustoms = results;
			next(err);
		});
	});

	// Load the current Navbar
	view.on('init', function(next) {
		var q = Navbar.model.find();
		q.exec(function(err, results) {
			locals.data.navbars = results;
			next(err);
		});
	});

	// Load the current MenuList
	view.on('init', function(next) {
		var q = MenuList.model.find();
		q.exec(function(err, results) {
   			locals.data.menus = results;
			next(err);
		});
	});

	// Load the current FooterList
	view.on('init', function(next) {
		var q = FooterList.model.find();
		q.exec(function(err, results) {
   			locals.data.footers = results;
			next(err);
		});
	});

	// Load the current CompanyInfoListMenu
	view.on('init', function(next) {
		var q = CompanyInfoListMenu.model.find();
		q.exec(function(err, results) {
			locals.data.companyinfolistmenus = results;
			next(err);
		});
	});

	// Load the current Message
	// view.on('init', function(next) {
	// 	var q = Message.model.find();
	// 	q.exec(function(err, results) {
	// 		locals.data.messages = results;
	// 		next(err);
	// 	});
	// });
	
	// Render the view
	view.render('tibcospotfirecustom');
}
exports = module.exports = function (req, res) {

	var view = new keystone.View(req, res);
	var locals = res.locals;
	var asyncList = [];
	var page = (req.query.page || 1)-0;
	var catName = (req.query.cat || '');
	var sort = req.query.sort || 'sort';
	var tagId = req.query.tag || '';
	var perPage = 12;

	if(isNaN(page)){
		return res.status(400).end('invalid page');
	}

	// locals.section is used to set the currently selected
	// item in the header navigation.
	locals.section = 'blog_list';
	locals.data = {};


	//get side
	var defaultCat = '';
	var CatId= '';
	asyncList.push(function(callback){
		keystone.list('ProductCategory').model.find().sort({'sort':1}).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.catData = results;
			defaultCat = locals.data.catData[0].name;
			CatId = locals.data.catData[0]._id;

			//not catName
			if(!catName){
				catName = defaultCat
			}

			keystone.list('ProductTag').model.find().sort({'sort':1}).limit(1000).exec(function (err, resultsTag) {
				
				if (err) {
					return next(err);
				}

				//get cat count
				var catAsyncList = [];
				locals.data.catData.forEach(function(item, i){
					//console.log("========")
					item['tags'] = [];

					resultsTag.forEach(function(tagItem){
						if(item['_id'] && tagItem['categories'] && item['_id'].toString() == tagItem['categories'].toString()){
							//console.log("========", tagId, tagItem['_id'].toString())

							if(tagId == tagItem['_id'].toString()){
								tagItem.sel = true
							}else{
								tagItem.sel = false
							}
							item['tags'].push(tagItem)
						}
					})


					var sel = false;
					if(item.name == catName){
						sel = true;
						CatId = item._id;
						locals.selCatName = item.name;
					}

					// var q = {'state':'published'}
					// if(catName != 'all'){
					// 	q = {'state':'published', categories:{'$in':[item._id]}}
					// }

					var q = {'state':'published', categories:{'$in':[item._id]}}

					catAsyncList.push(function(asyncCb){
						keystone.list('Product').model.count(q).exec(function (err, results) {
							if(err) return asyncCb(err);
							locals.data.catData[i] = {
								'name':item.name,
								'tags':item.tags,
								'count':results,
								'sel':sel,
							}
							asyncCb();
						})
					})
				})

				//end get cat per count
				async.parallel(catAsyncList, function(err){
					if(err){
						callback(err);
						return
					}
					callback();
				})

			})

		});
	});


	//adv List 
	asyncList.push(function(callback){
		var skipNum = perPage * (page-1)
		keystone.list('Adv').model.find({'showOnProductList':'yes'}).sort({'sort':1}).limit(3).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.adv = results;

			//console.log(results)
			callback()
		})
	})


	//side product
	asyncList.push(function(callback){

		keystone.list('Product').model.find({'state':'published', 'putOnSide':'yes'}).sort({'sort':1}).limit(3).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.sideProduct = results;

			//console.log(results)
			callback()
		})
	})

	//count 
	asyncList.push(function(callback){

		var q = {'state':'published'}
		if(catName != 'all'){
			q = {'state':'published', categories:{'$in':[CatId]}}
		}

		var qObj = q
		if(tagId && tagId != ""){
			qObj['tag'] = tagId;
		}
		keystone.list('Product').model.count(qObj).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.countData = results;
			//console.log(results)
			callback();
		});
	});


	//side product
	asyncList.push(function(callback){

		var skipNum = perPage * (page-1);
		var sortObj = {};
		if(sort == 'sort'){
			sortObj[sort] = 1;
		}else{
			sortObj[sort] = -1;
		}

		var q = {'state':'published'}
		if(catName != 'all'){
			q = {'state':'published', categories:{'$in':[CatId]}}
		}
		
		var qObj = q
		//console.log(CatId)
		if(tagId && tagId != ""){
			qObj['tag'] = {'$all': tagId};
		}
		keystone.list('Product').model.find(qObj).sort(sortObj).limit(perPage).skip(skipNum).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.productData = results;

			//console.log(results)
			callback();
		})
	})


	async.series(asyncList, function(err){
		if(err){
			console.log('index.js| async.parallel error', err);
			return res.status(500).end();
		}

		locals.page = getPageObj(page, perPage, locals.data.countData, '/product/list?cat='+catName+'&sort='+sort);



		locals.sortObj = {
			'page':1,
			'cat':catName,
			'sort':sort,
		}

		locals.title = 'Products|BelleMa'
		// Render the view
		view.render('product_list');
	})


};
Пример #15
0
exports = module.exports = function(req, res) {
	const view = new keystone.View(req, res);
	let locals = res.locals;
	const supportWebP = isWebP(req);

	locals.section = 'product';
	locals.filters = {
		product: req.params.product,
		category: req.params.category
	};
	locals.data = {
		productImages: [],
		products: [],
		relatedproducts: [],
		awards: []
	};

	view.on('init', function(next) {
		const productQueryOptions = {
			dbCollection: keystone.list('Product'),
			populateBy: 'Manufacturer ProductType awards',
			slug: locals.filters.product,
			prefix: 'product-',
			callback: (product, err) => exec(product, err)
		};

		let categoryQueryOptions = {
			dbCollection: keystone.list('ProductCategory'),
			keyName: locals.filters.category,
			prefix: 'category-',
			callback: (result, err) => {
				if (err) throw err;
				else locals.data.category = result;
			}
		};
		findOneByKey(categoryQueryOptions);
		findItemBySlug(productQueryOptions);

		function exec(product, err = '') {
			if (product) {
				product.images.forEach(img => {
					if (supportWebP) img.secure_url = changeFormatToWebp(img.secure_url);

					locals.data.productImages.push({
						src: img.secure_url,
						w: img.width,
						h: img.height
					});
				});

				if (product.awards.length > 0) {
					product.awards.forEach(award => (award.CoverImage.secure_url = cropCloudlinaryImage(award.CoverImage, 150, 150, supportWebP)));
				}

				// Check if product doesn't have it's own discount and only then put the discount from productType
				if (!product.Discount) {
					if (product.ProductType[0].discount > 0) {
						const discount = setDiscountedPrice(product.ProductType[0].discount, product.price);
						product.Discount = discount;
					}
				}
				locals.data.product = product;
				next();
			} else {
				throw err;
			}
		}
	});

	// Related products
	view.on('init', function(next) {
		keystone
			.list('Product')
			.model.find()
			.lean()
			.where('ProductType')
			.in([locals.data.category])
			.where('slug')
			.ne([locals.filters.product])
			// .where('price').gt(locals.data.product.price-500).lt(locals.data.product.price+500)
			.populate('Manufacturer ProductType')
			.exec(function(err, result) {
				locals.data.relatedproducts = getRidOfMetadata(result, true, 250, 250, supportWebP);
				next(err);
			});
	});
	// Render the view
	view.render('product');
};
Пример #16
0
module.exports = function(req, res) {
	var view = new keystone.View(req, res),
		locals = res.locals;
	
	locals.section = 'profiles';

	view.on('post', { action: 'delete.account' }, function(next) {
		req.user._.password.compare(req.body.password, function(err, matched) {
			if (!matched) {
				locals.submitFail = true;
				return next();
			}

			async.parallel([
				function(done) {
					// DEACTIVATE Post Comments
					
					PostComment.model.find()
						.where('author', req.user)
						.exec(function(err, userPostComments) {
							if (err) return done(err);
							
							async.forEach(userPostComments, function(comment, commentRemoved) {
								comment.commentState = 'deactivated';
								comment.save(commentRemoved);
							}, done);
							
							log.info(req.user.id + ' deactivated all post comments');
						});
				},
				
				function(done) {
					// DEACTIVATE Event Comments
					
					EventComment.model.find()
						.where('author', req.user)
						.exec(function(err, userEventComments) {
							if (err) return done(err);
							
							async.forEach(userEventComments, function(comment, commentRemoved) {
								comment.commentState = 'deactivated';
								comment.save(commentRemoved);
							}, done);
							
							log.info(req.user.id + ' deactivated all event comments');
						});
				},
				
				function(done) {
					// DEACTIVATE Topics
					ForumTopic.model.find()
						.where('author', req.user)
						.exec(function(err, userForumTopics) {
							if (err) return done(err);
							
							async.forEach(userForumTopics, function(comment, topicRemoved) {
								comment.topicState = 'deactivated';
								comment.save(topicRemoved);
							}, done);
							
							log.info(req.user.id + ' deactivated all topics');
						});
				},
				
				function(done) {
					// DEACTIVATE Topic Replies
		
					ForumReply.model.find()
						.where('author', req.user)
						.exec(function(err, userForumReplies) {
							if (err) return done(err);
							
							async.forEach(userForumReplies, function(comment, replyRemoved) {
								comment.replyState = 'deactivated';
								comment.save(replyRemoved);
							}, done);
							
							log.info(req.user.id + ' deactivated all topic replies');
						});
				}
			], function(err) {
				if (err) return res.serverError(err);
				
				req.user.email = '-deactivated-' + Date.now() + '-' + req.user.email;
				req.user.userState = 'deactivated';
				req.user.save(function(err) {
					if (err) {
						res.serverError(err);
					} else {
						keystone.session.signout(req, res, function() {
							return res.redirect('/');
						});
					}
				});
			});
		});
	});
	
	view.render('profiles/delete');	
};
Пример #17
0
exports = module.exports = function (req, res) {

	var view = new keystone.View(req, res);
	var locals = res.locals;

	// Init locals
	locals.section = 'technology';
	locals.filters = {
		category: req.params.category,
	};
	locals.data = {
		posts: [],
		categories: [],
	};

	// Load all categories
	view.on('init', function (next) {

		keystone.list('TechnologyCategory').model.find().sort('name').exec(function (err, results) {

			if (err || !results.length) {
				return next(err);
			}

			locals.data.categories = results;

			// Load the counts for each category
			async.each(locals.data.categories, function (category, next) {

				keystone.list('Technology').model.count().where('categories').in([category.id]).exec(function (err, count) {
					category.postCount = count;
					next(err);
				});

			}, function (err) {
				next(err);
			});
		});
	});

	// Load the current category filter
	view.on('init', function (next) {

		if (req.params.category) {
			keystone.list('TechnologyCategory').model.findOne({ key: locals.filters.category }).exec(function (err, result) {
				locals.data.category = result;
				next(err);
			});
		} else {
			next();
		}
	});

	// Load the posts
	view.on('init', function (next) {

		var q = keystone.list('Technology').paginate({
				page: req.query.page || 1,
				perPage: 10,
				maxPages: 10,
				filters: {
					state: 'published',
				},
			})
			.sort('-publishedDate')
			.populate('author categories');

		if (locals.data.category) {
			q.where('categories').in([locals.data.category]);
		}

		q.exec(function (err, results) {
			locals.data.posts = results;
			console.log(JSON.stringify(locals.data))
			next(err);
		});
	});

	// Render the view
	view.render('technology');
};
Пример #18
0
exports = module.exports = function(req, res) {
	
	var view = new keystone.View(req, res),
		locals = res.locals;
	
	locals.section = 'profile';
	
	
	// LOAD User
	// ------------------------------
	
	view.on('init', function(next) {
		
		User.model.findOne()
			.where({ key: req.params.profile })
			.exec(function(err, profile) {
				if (err) return res.err(err);
				if (!profile) return res.notfound('Profile not found');
				locals.profile = profile;
				next();
			});
		
	});
	
	
	// LOAD Topics
	// ------------------------------
	
	view.on('init', function(next) {
		
		Topic.model.find()
			.where( 'state', 'published' )
			.where('author', locals.profile.id)
			.populate( 'author', 'name photo' )
			.populate( 'tags' )
			.sort('-createdAt')
			.exec(function(err, topics) {
				if (err) return res.err(err);
				locals.topics = topics;
				next();
			});
		
	});

	
	// LOAD replies
	view.on('init', function(next) {
		
		Reply.model.find()
			.where( 'state', 'published' )
			.where('author', locals.profile.id)
			.populate( 'author', 'name photo' )
			.sort('-createdAt')
			.exec(function(err, replies) {
				if (err) return res.err(err);
				locals.replies = replies;
				next();
			});
		
	});

	
	// Set page info
	// ------------------------------
	
	view.on('render', function(next) {
		locals.title = locals.profile.name.full;
		locals.metadescription = locals.profile.bio.md ? keystone.utils.cropString(keystone.utils.htmlToText(locals.profile.bio.html), 200, '...', true) : '';
		next();
	});
	
	
	view.render('site/profile');
	
}
Пример #19
0
exports = module.exports = function (req, res) {

    var view = new keystone.View(req, res);
    var locals = res.locals;
	var url = view.req.originalUrl;
	locals.tipo = url.substr(url.indexOf("?") + 1);
    locals.section = 'cadastroOportunidade';
    locals.tipoOfertas = Oportunidade.fields.tipoOferta.ops;
    locals.formData = req.body || {};
    locals.validationErrors = {};
    locals.compra = false;
    locals.venda = false;
	var emailConfigs;
	var emailConfig = EmailConfig.model.findOne().where('isAtivo', true);
	
	
// Register Empresa and Usuario
    view.on('post', {action: 'cadastroOportunidade'}, function (next) {
        var empresa = Empresa.model.findOne().where('usuario', locals.user.id);
        empresa.exec(function (err, resultE) {
            var oportunidade = new Oportunidade.model({
                isAtivo: true,
                empresa: resultE.id,
            });
            var updaterO = oportunidade.getUpdateHandler(req);
            updaterO.process(req.body, {
                flashErrors: true
            }, function (err) {
                if (err) {
                    locals.validationErrors = err.errors;
                } else {
                    locals.oportunidadeSubmitted = true;
                    oportunidade.isAtivo = true;
					oportunidade.controlData = res.locals.user.controlData;
                    oportunidade.save();
					oportunidade._doc.email = res.locals.user.email;
					
					//Matching vars
					var Mtipo;
					if(locals.tipo == "compra"){
						Mtipo = "Venda";
					}else{
						Mtipo = "Compra";
					};					
					var str = oportunidade.descricaoDetalhada;
					function clearSTR(str){
						var wordMatch = [" a "," A "," o ", " O "," no ", " e ", " de ", " os ", " com ", " de "];    
						for(i=0; i<wordMatch.length; i++){
						   str = str.replace(wordMatch[i], " ");
						}

						return str;
					}					
					var Mkeywords = clearSTR(str);
					queryKey ={
						
						
					}
					var busca = {"$text": Mkeywords};
					//Save oportunidade in cloudant queue 
					index.push({name: oportunidade.nome}, function (err) {
						db.insert({oportunidade}, oportunidade.id, function(err, body, header) {
							if (err) {
								return console.log("Insert Error: "+ err.message);
							}
							console.log('Oportunidade Salva');
						});
					});				
					//Matching queue
					query.push({name: oportunidade.nome}, function (err) {
						db.find({selector: {"$and":[{"$text": Mkeywords}, {"$text": Mtipo},{"$text": oportunidade.tipoOferta} ]}, use_index:"_design/32372935e14bed00cc6db4fc9efca0f1537d34a8"}, function(er, match) {
							if (er) {
								throw er;
							}
							if(match.docs.length <= 0){
								console.log("Nenhum matching encontrado")
							}else{
								var empresa =[];
								var autorizacao = null;	
								for (j = 0; j < match.docs.length ; j++){									
									if(match.docs[j].oportunidade.email != res.locals.user.email && match.docs[j].oportunidade.isAtivo == true){
										empresa = Empresa.model.findOne().where('controlData', match.docs[j].oportunidade.controlData).populate('usuario')
										empresa.exec(function (err, resultado){
											console.log("resultado");
											if(resultado){
												autorizacao = resultado.autorizacao;
												var emailBody = '<b>' + '<p>Saudações,</p><br />' +
												'<p>Foi encontrada uma oportunidade que voce talvez tenha interesse: </p>'; // html body
												if(autorizacao == true){
													emailBody = emailBody+ '<p> Nome da Oportunidade: ' + oportunidade.nome +'</p><br />'+
													'<p>Acesse aqui: <a href="http://*****:*****@smtp.gmail.com';
														var transporter = nodemailer.createTransport(smtps);
														var mailOptions = {
															from: emailConfigs.from, // sender address//
															subject: emailConfigs.subjectMatching, // Subject line
															html: emailBody
														};
														var emails = [];	
														mailOptions.to = resultado.usuario.email;
														{
															transporter.sendMail(mailOptions, function (error, info) {
																if (error) {
																	//queue of email not sent
																	return console.log(error);
																}
																console.log('Message sent AdeSampa: ' + info.response);
															});
														}
													});
												}
											}
										});
									}
								}
							}
						});
					});					
                }
                next();
            });
        });
    });

    //Define type of oportunidade
	if(locals.tipo == "compra"){
        locals.compra = true;
	}
	else if (locals.tipo == "venda"){
		locals.venda = true;
	}


    view.render('cadastroOportunidade');
}
Пример #20
0
exports = module.exports = function(req, res) {
	
	var view = new keystone.View(req, res),
		locals = res.locals;

  // Init locals
  locals.section = 'blog';
  locals.filters = {
    category: req.params.category,
    year: req.params.year,
    month: req.params.month
  };
  locals.data = {
    posts: [],
    categories: [],
    archives: []
  };
	
	// Load all categories
	view.on('init', function(next) {
		
		keystone.list('PostCategory').model.find().sort('name').exec(function(err, results) {
			
			if (err || !results.length) {
				return next(err);
			}
			
			locals.data.categories = results;
			
			// Load the counts for each category
			async.each(locals.data.categories, function(category, next) {
				
				keystone.list('Post').model.count().where('category').in([category.id]).exec(function(err, count) {
					category.postCount = count;
					next(err);
				});
				
			}, function(err) {
				next(err);
			});
			
		});
		
	});
	
	// Load the current category filter
	view.on('init', function(next) {
		
		if (req.params.category) {
			keystone.list('PostCategory').model.findOne({ key: locals.filters.category }).exec(function(err, result) {
				locals.data.category = result;
				next(err);
			});
		} else {
			next();
		}
		
	});

  // Load all archives in decscending order
  view.on('init', function(next) {
    keystone.list('PostArchive').model.find().sort({'date': -1}).exec(function(err, results) {

      if (err || !results.length) {
        return next(err);
      }

      var filteredResults = [];

      // Remove duplicate archives
      for(var i=0; i<results.length; i++) {
        if(i === 0) {
          filteredResults.push(results[i]);
        } else {
          var prevArchive = i - 1;
          if(results[i].name != results[prevArchive].name) {
            filteredResults.push(results[i]);
          }
        }
      }

      locals.data.archives = filteredResults;

      next(err);

    });
  });
	
	// Load the posts
	view.on('init', function(next) {
		
		var q = keystone.list('Post').paginate({
				page: req.query.page || 1,
				perPage: 10,
				maxPages: 10
			})
			.where('state', 'published')
			.sort('-publishedDate')
			.populate('author categories');
		
		if (locals.data.category) {
			q.where('categories').in([locals.data.category]);
		}

    if (locals.filters.year && locals.filters.month) {
      var postMonth = locals.filters.month - 1;
      var postYear = locals.filters.year;
      var start = new Date(postYear, postMonth, 1, 0);
      var end = new Date(postYear, postMonth + 1, 0, 23,59,59);
      q.find({publishedDate: { $gte: start, $lt: end }});
    }
		
		q.exec(function(err, results) {
			locals.data.posts = results;
			next(err);
		});
		
	});
	
	// Render the view
	view.render('blog');
	
};
Пример #21
0
	// Once all the above has completed, render the page
	function asyncFinally(err, results) {
		view.render('view_mission', {
			data : outcome
		});
	}
Пример #22
0
exports = module.exports = function(req, res) {
	var view = new keystone.View(req, res),
		locals = res.locals;

	// Init locals
		locals.section = 'businessintelligence';
		locals.data = [];

	// Load the current Businessintelligence
	view.on('init', function(next) {
		var q = Businessintelligence.model.find();
		q.exec(function(err, results) {
			locals.data.businessintelligences = results;
			next(err);
		});
	});

	// Load the current Navbar
	view.on('init', function(next) {
		var q = Navbar.model.find();
		q.exec(function(err, results) {
			locals.data.navbars = results;
			next(err);
		});
	});

	// Load the current MenuList
	view.on('init', function(next) {
		var q = MenuList.model.find();
		q.exec(function(err, results) {
   			locals.data.menus = results;
			next(err);
		});
	});

	// Load the current FooterList
	view.on('init', function(next) {
		var q = FooterList.model.find();
		q.exec(function(err, results) {
   			locals.data.footers = results;
			next(err);
		});
	});

		// Load the current ListingMenu
	view.on('init', function(next) {
		var q = Listingmenu.model.find();
		q.exec(function(err, results) {
			locals.data.listingmenus = results;
			next(err);
		});
	});
	// Load the current Message
	// view.on('init', function(next) {
	// 	var q = Message.model.find();
	// 	q.exec(function(err, results) {
	// 		locals.data.messages = results;
	// 		next(err);
	// 	});
	// });
	
	// Render the view
	view.render('businessintelligence');
}
exports = module.exports = function (req, res) {

	var view = new keystone.View(req, res);
	var locals = res.locals;
	var asyncList = [];
	var page = (req.query.page || 1)-0;
	var perPage = 10;

	if(isNaN(page)){
		return res.status(400).end('invalid page');
	}
	// locals.section is used to set the currently selected
	// item in the header navigation.
	locals.section = 'blog_list';
	locals.data = {};

	//get side
	asyncList.push(function(callback){
		keystone.list('InsuranceState').model.find({'status':'published'}).sort({'sort':1}).limit(10000).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.state = results //JSON.parse(JSON.stringify());
			// locals.data.sideData.map(function(item){
			// 	 item.publishedDate = moment(item.publishedDate).format('MM/DD/YYYY HH:SS')
			// 	 return item
			// })
			//console.log(results)
			callback();
		});
	});


	//recent post
	asyncList.push(function(callback){
		keystone.list('InsurancePlanList').model.find({'status':'published'}).sort({'sort':1}).limit(10000).exec(function (err, results) {

			if (err) {
				return callback(err);
			}


			locals.data.PlanList = results; //JSON.parse(JSON.stringify(results));;
			// locals.data.recentData.map(function(item){
			// 	 item.publishedDate = moment(item.publishedDate).format('MM/DD/YYYY HH:SS')
			// 	 return item
			// })
			//console.log(results)
			callback()
		});
	});

	//recent post
	asyncList.push(function(callback){
		keystone.list('InsurancePlanInfo').model.find({'status':'published'}).sort({'sort':1}).limit(10000).exec(function (err, results) {

			if (err) {
				return callback(err);
			}


			locals.data.PlanInfo = results; //JSON.parse(JSON.stringify(results));;
			// locals.data.recentData.map(function(item){
			// 	 item.publishedDate = moment(item.publishedDate).format('MM/DD/YYYY HH:SS')
			// 	 return item
			// })
			//console.log(results)
			callback()
		});
	});


	async.parallel(asyncList, function(err){
		if(err){
			console.log('insuranceList.js| async.parallel error', err);
			return res.status(500).end();
		}

		locals.title = 'Insurance|BelleMa'
		// Render the view
		view.render('insurance_list');
	})


	
};
Пример #24
0
 attendee.save(function (err) {
   locals.attendee = attendee;
   locals.status = 200;
   view.render('registration');
 });
Пример #25
0
exports = module.exports = function( req,
                                     res ){

  var locals = res.locals;
  locals.from = req.query.from
  locals.section = 'auth';
  locals.submitted = req.body || {};
  locals.brand = keystone.get( 'brand' );
  locals.title = locals.brand + ': signin';
  locals.logo = keystone.get( 'signin logo' );
  locals.csrf_token_key = keystone.security.csrf.TOKEN_KEY;
  locals.csrf_token_value = keystone.security.csrf.getToken( req, res );
  locals.sendResetLink = (User.schema.methods.sendResetPassword)
    ? keystone.get( 'resetpassword url' )
    : false;

  const view = new keystone.View( req, res );

  function renderView(){
    view.render( 'signin' );
  }

  // If a form was submitted, process the login attempt
  if( req.method === 'POST' ){

    if( !keystone.security.csrf.validate( req ) ){
      req.flash( 'error', 'There was an error with your request, please try again.' );
      return renderView();
    }

    if( !req.body.email || !req.body.password ){
      req.flash( 'error', 'Please enter your email address and password.' );
      return renderView();
    }

    var onSuccess = function( user ){

      if( req.query.from && req.query.from.match( /^(?!http|\/\/|javascript).+/ ) ){
        var parsed = url.parse( req.query.from );
        if( parsed.host || parsed.protocol || parsed.auth ){
          res.redirect( '/keystone' );
        } else {
          res.redirect( parsed.path );
        }
      } else if( 'string' === typeof keystone.get( 'signin redirect' ) ){
        res.redirect( keystone.get( 'signin redirect' ) );
      } else if( 'function' === typeof keystone.get( 'signin redirect' ) ){
        keystone.get( 'signin redirect' )( user, req, res );
      } else {
        res.redirect( '/keystone' );
      }

    };

    var onFail = function( err ){
      var message = (err && err.message)
        ? err.message
        : 'Sorry, that email and password combo are not valid.';
      req.flash( 'error', message );
      renderView();
    };

    keystone.session.signin( req.body, req, res, onSuccess, onFail );

  } else {
    renderView();
  }

};
Пример #26
0
exports = module.exports = function(req, res) {
	
	var view = new keystone.View(req, res);
	var locals = res.locals;
	
	// Set locals
	locals.section = 'products';
	locals.filters = {
		product: req.params.product
	};
	locals.data = {
		products: [],
		categories: []
	};
	locals.numeral = numeral;
	
	// Load all categories
	view.on('init', function(next) {
		
		keystone.list('ProductCategory').model.find().where('primary', true).sort('name').populate('categories').exec(function(err, results) {
			
			if (err || !results.length) {
				return next(err);
			}

			locals.data.categories = results;
			
			// Load the counts for each category
			async.each(locals.data.categories, function(category, next) {
				keystone.list('Product').model.count().where('categories').in([category.id]).exec(function(err, count) {
					category.productCount = count;
					next(err);
				});
				
			}, function(err) {
				next(err);
			});
			
		});
		
	});

	// Load the current product
	view.on('init', function(next) {
		
		var q = keystone.list('Product').model.findOne({
			slug: locals.filters.product
		})
		
		q.exec(function(err, result) {
			locals.data.product = result;
			locals.data.category = result.categories[0] || null;
			next(err);
		});
		
	});
	
	// Load other posts
	// view.on('init', function(next) {
		
	// 	var q = keystone.list('Product').model.find().where('state', 'published').sort('-publishedDate').populate('author').limit('4');
		
	// 	q.exec(function(err, results) {
	// 		locals.data.products = results;
	// 		next(err);
	// 	});
		
	// });
	
	// Render the view
	view.render('product');
	
};
Пример #27
0
exports = module.exports = function(req, res) {
	
	var view = new keystone.View(req, res),
		locals = res.locals;
	
	// Init locals
	locals.section = 'blog';
	locals.page.title = 'NYC Node - The NYC Node.js Meetup - Blog';
	locals.filters = {
		category: req.params.category
	};
	locals.data = {
		posts: [],
		categories: []
	};
	
	// Load all categories
	view.on('init', function(next) {
		
		keystone.list('PostCategory').model.find().sort('name').exec(function(err, results) {
			
			if (err || !results.length) {
				return next(err);
			}
			
			locals.data.categories = results;
			
			// Load the counts for each category
			async.each(locals.data.categories, function(category, next) {
				
				keystone.list('Post').model.count().where('category').in([category.id]).exec(function(err, count) {
					category.postCount = count;
					next(err);
				});
				
			}, function(err) {
				next(err);
			});
			
		});
		
	});
	
	// Load the current category filter
	view.on('init', function(next) {
		
		if (req.params.category) {
			keystone.list('PostCategory').model.findOne({ key: locals.filters.category }).exec(function(err, result) {
				locals.data.category = result;
				next(err);
			});
		} else {
			next();
		}
		
	});
	
	// Load the posts
	view.on('init', function(next) {
		
		var q = keystone.list('Post').model.find().where('state', 'published').sort('-publishedDate').populate('author categories');
		
		if (locals.data.category) {
			q.where('categories').in([locals.data.category]);
		}
		
		q.exec(function(err, results) {
			locals.data.posts = results;
			next(err);
		});
		
	});
	
	// Render the view
	view.render('site/blog');
	
}
Пример #28
0
exports = module.exports = function(req, res) {
	
	
	var disciplineWhere = {};
	if (res.locals.params.discipline) {
		disciplineWhere.slug = res.locals.params.discipline.slug;
	}else{
		disciplineWhere.slug = 'no-discipline';
	}

	
	var locals = res.locals;
	//console.log('params');
	//console.log(res.locals.params);
	if(res.locals.params.discipline){
		locals.discipline = res.locals.params.discipline.slug;
	}

	locals.data = {page:{title:'Kali Protectives'}};
	
	// locals.section is used to set the currently selected
	// item in the header navigation.
	locals.section = 'home';
	

	var view = new keystone.View(req, res);

	//popuplate Home page data.
	keystone.list('Discipline').model.find().where(disciplineWhere).exec(function (err, discipline) {
			
		var disciplineWhere = {};
		var homepageSlug = 'home';
		
		if (discipline.length > 0) {
			disciplineWhere = {disciplines: discipline[0]._id};
			if(discipline[0].slug === 'moto') {
				homepageSlug = 'moto-home';
			}else if(discipline[0].slug === 'bike') {
				homepageSlug = 'bike-home';
			}
		}

		keystone.list('BasePage').model.find().where({slug: homepageSlug}).exec(function (err, homePage) {
		
			//get Base Page == home Posts
			var postIds = [];
			
			if (homePage[0].posts.length) {
				homePage[0].posts.forEach(function (post) {
					postIds.push(post);
				});
			}
			
			var postWhere = {_id: {$in: postIds}};
			
			getPosts(postWhere, function(posts){
				//console.log('data:', posts.posts);

				orderPosts(postIds, posts.posts);
				res.locals.posts = [];
				async.forEachOf(posts.posts, function (post, i, cb) {

						populatePost(post, cb);
						//console.log(post);
						res.locals.posts.push(post);
						
					},
					function (err) {
						if (err) {
							console.log('error', err);
						}
					
						view.render('index');
						//next(err);
					}
				);

			});

		});
	});
};
Пример #29
0
exports = module.exports = function (req, res) {

	var view = new keystone.View(req, res);
	var locals = res.locals;
	// days of current month
	var today = new Date();
	function getLastDay(day) {
		var y = day.getFullYear();
		var FebLastDay = ((y % 4 === 0 && y % 100 != 0) || y % 400 === 0)?29:28;
		return [31,FebLastDay,31,30,31,30,31,31,30,31,30,31][day.getMonth()];	
	}	
	// 首页需要从数据库获取的数据有:所有本月的“今日新院”,三类新闻的分别最新2个,以及最新的10条公告
	locals.data={
		todays:[],
		ycl:[],
		collegeStu:[],
		graduateStu:[],
		notices:[],
		month:today.getMonth()+1,
		lastDay:getLastDay(today),
		dataEnough() {
			return this.todays.length === 10 && this.ycl.length === 2 && this.collegeStu.length === 2 && this.graduateStu.length === 2 && this.notices.length === 10;
		}
	};
	 // Load all posts
	view.on('init',function (next) {
		'use strict'
		keystone.list('Post').model.find().sort('-publishedDate').exec(function (err, result) {
			if (err || !result.length) {
				return next(err);
			}
			for (let i = 0; i < result.length; i++) {
				// 本月的“今日新院”新闻
				if (result[i].showInCalendar && result[i].publishedDate.getMonth() === today.getMonth()) {
					locals.data.todays.push(result[i]);
				}
				else {
					// notice
					if (result[i].category === '0' && locals.data.notices.length < 10) {
						locals.data.notices.push(result[i]);
					}
					// Youth Communist League	
					else if (result[i].category === '1' && locals.data.ycl.length < 2) {
						locals.data.ycl.push(result[i]);
					}
					// college students union
					else if (result[i].category === '2' && locals.data.collegeStu.length < 2) {
						locals.data.collegeStu.push(result[i]);
					}
					// graduate students union
					else if (result[i].category === '3' && locals.data.graduateStu.length < 2) {
						locals.data.graduateStu.push(result[i]);
					}
				}
				// 数据量已足够
				if (locals.data.dataEnough()) break;
			}
			// if there's no todays of current month yet, use todays of last month instead
			if(locals.data.todays.length === 0){
				locals.data.month = locals.data.month === 1 ? 12 : locals.data.month - 1;
				locals.data.lastDay = getLastDay(
					new Date(locals.data.month === 12?today.getFullYear()-1:today.getFullYear(), locals.data.month-1, 1)
					);
				for (let i = 0; i < result.length; i++) {
					if (result[i].showInCalendar && result[i].publishedDate.getMonth() === locals.data.month - 1) {
						locals.data.todays.push(result[i]);
					}
				}
			}
			next();
		});		
	});
	locals.section = 'home';
	view.render('home');
};
exports = module.exports = function (req, res) {

	var view = new keystone.View(req, res);
	var locals = res.locals;
	var asyncList = [];
	var page = (req.query.page || 1)-0;
	var perPage = 10;

	if(isNaN(page)){
		return res.status(400).end('invalid page');
	}
	// locals.section is used to set the currently selected
	// item in the header navigation.
	locals.section = 'blog_list';
	locals.data = {};

	var TroubleShooting = '123456789012345678901234';
	var TipSolution = '123456789012345678901234';
	var PressRealse = '123456789012345678901234';


	//get side
	asyncList.push(function(callback){
		keystone.list('BlogCategory').model.find().limit(1000).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			results.forEach(function(item){
				if(item.name == 'TroubleShooting'){
						TroubleShooting = item._id;
				}
				if(item.name == 'TipSolution'){
						TipSolution = item._id;
				}
				if(item.name == 'PressRealse'){
						PressRealse = item._id;
				}
			})

			// console.log(results)


			callback();
		});
	});


	//get side
	asyncList.push(function(callback){
		keystone.list('PressRealse').model.find({ 'state':'published', 'putOnSide':'yes'}).sort({'sort':1}).limit(3).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.sideData = JSON.parse(JSON.stringify(results));
			locals.data.sideData.map(function(item){
				 item.publishedDate = moment(item.publishedDate).format('MM/DD/YYYY HH:SS')
				 return item
			})
			//console.log(results)
			callback();
		});
	});


	//recent post
	asyncList.push(function(callback){
		keystone.list('PressRealse').model.find({'state':'published'}).sort({'publishedDate':-1}).limit(3).exec(function (err, results) {

			if (err) {
				return callback(err);
			}


			locals.data.recentData = JSON.parse(JSON.stringify(results));;
			locals.data.recentData.map(function(item){
				 item.publishedDate = moment(item.publishedDate).format('MM/DD/YYYY HH:SS')
				 return item
			})
			//console.log(results)
			callback()
		});
	});


	//count 
	asyncList.push(function(callback){
		var q = {'state':'published'};
		var keywords = (req.query.keywords || '').trim()

		if(keywords != ''){
			q['title'] = {"$regex":req.query.keywords}
		}


		keystone.list('PressRealse').model.find({}).count(q).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.countData = results;
			//console.log(results)
			callback()
		});
	});


	//data List 
	asyncList.push(function(callback){
		var skipNum = perPage * (page-1)
		var q = {'state':'published'};
		var keywords = (req.query.keywords || '').trim()

		if(keywords != ''){
			q['title'] = {"$regex":req.query.keywords}
		}

		keystone.list('PressRealse').model.find(q).sort({'sort':1}).limit(perPage).skip(skipNum).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.data = JSON.parse(JSON.stringify(results));
			locals.data.keywords = keywords

			locals.data.data.map(function(item){
				 item.publishedDate = moment(item.publishedDate).format('MM/DD/YYYY HH:SS')
				 return item
			})
			locals.keywords = keywords
			//console.log(results)
			callback()
		});
	});


	//data List 
	asyncList.push(function(callback){
		var skipNum = perPage * (page-1)
		keystone.list('Adv').model.find({'showOnBlog':'yes'}).sort({'sort':1}).limit(3).exec(function (err, results) {

			if (err) {
				return callback(err);
			}

			locals.data.adv = results;

			//console.log(results)
			callback()
		});
	});

	async.parallel(asyncList, function(err){
		if(err){
			console.log('index.js| async.parallel error', err);
			return res.status(500).end();
		}

		locals.page = getPageObj(page, perPage, locals.data.countData, '/blog/list');
		locals.title = 'Press Release|BelleMa'
		locals.NavTip = 'Press Release'
		locals.NavLink = '/breastfeeding/pressrealse/info'
		locals.bannberUrl = '/img/banner2-@2x.png'
		// Render the view
		view.render('blog_list');
	})


	
};