Created
March 23, 2014 06:39
-
-
Save DrMoriarty/9719581 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var keystone = require('keystone'), | |
Types = keystone.Field.Types; | |
var SingleMail = new keystone.List('SingleMail', { | |
map: { name: 'title' }, | |
autokey: {path: 'key', from: 'title' }, | |
defaultSort: '-sendAt' | |
}); | |
SingleMail.add({ | |
title: { type: String, required: true, label: 'Заголовок' }, | |
image: { type: Types.CloudinaryImage, label: 'Изображение' }, | |
state: { type: Types.Select, options: [{value: 'draft', label: 'Черновик'}, {value: 'active', label: 'Активно'}], | |
default: 'draft', index: true, label: 'Состояние' }, | |
groups: { type: Types.Relationship, ref: 'UserGroup', many: true, label: 'Группы' }, | |
message: { type: Types.Html, wysiwyg: true, height: 200, label: 'Сообщение' }, | |
link: {type: Types.Url, label: 'Ссылка'}, | |
template: { type: Types.Select, options: [{value: 'email-default', label: 'Обычное письмо'}], | |
default: 'email-default', label: 'Шаблон'}, | |
fromName: { type: String, default: 'MobilAp', label: 'От кого'}, | |
fromEmail: { type: Types.Email, default: '[email protected]', label: 'Откуда'}, | |
sendAt: { type: Types.Datetime, default: Date.now, label: 'Дата отправления' }, | |
complete: {type: Boolean, noedit: true, label: 'Выполнено'}, | |
sendCounter: {type: Number, noedit: true, label: 'Отправлено'}, | |
openCounter: {type: Number, noedit: true, label: 'Открыто'}, | |
}); | |
SingleMail.schema.pre('save', function(next) { | |
//this.wasNew = this.isNew; | |
if (this.complete && this.state == 'active' && this.sendAt > new Date()) { | |
this.complete = false; | |
} | |
next(); | |
}) | |
SingleMail.schema.methods.sendEmail = function(callback) { | |
var singleMail = this; | |
keystone.list('User').model.find() | |
.where('groups').in(singleMail.groups) | |
.where('subscribed', true) | |
.exec(function(err, users) { | |
if (err) return callback(err); | |
SingleMail.model.update({_id: email.id}, {$set: {complete: true}, $inc: {sendCounter: users.length}}, function(err) { | |
if(err) console.log(err); | |
}); | |
new keystone.Email(singleMail.template).send({ | |
to: users, | |
from: { | |
name: singleMail.fromName, | |
email: singleMail.fromEmail | |
}, | |
subject: singleMail.title, | |
mail: singleMail, | |
web_view_url: 'http://mobilap.biz/email/'+singleMail.id, | |
unsubscribe_url: 'http://mobilap.biz/unsubscribe' | |
}, callback); | |
}); | |
} | |
SingleMail.defaultColumns = 'title, state, groups, sendAt, complete|10%, sendCounter|10%, openCounter|10%'; | |
SingleMail.register(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment