tellform/app/models/form.server.model.js

443 lines
11 KiB
JavaScript
Raw Normal View History

2015-06-29 22:51:29 +00:00
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
FieldSchema = require('./form_field.server.model.js'),
FormSubmissionSchema = require('./form_submission.server.model.js'),
2015-06-29 22:51:29 +00:00
Schema = mongoose.Schema,
2015-07-28 23:26:32 +00:00
pdfFiller = require('node-pdffiller'),
2015-06-29 22:51:29 +00:00
_ = require('lodash'),
config = require('../../config/config'),
path = require('path'),
2015-06-30 14:21:53 +00:00
fs = require('fs-extra'),
2015-07-27 18:11:43 +00:00
async = require('async'),
Field = mongoose.model('Field', FieldSchema),
2015-07-28 22:29:07 +00:00
FormSubmission = mongoose.model('FormSubmission', FormSubmissionSchema);
2015-06-29 22:51:29 +00:00
/**
* Form Schema
*/
var FormSchema = new Schema({
created: {
type: Date,
default: Date.now
},
2015-07-02 03:50:57 +00:00
lastModified: {
type: Date,
default: Date.now
},
2015-06-29 22:51:29 +00:00
title: {
type: String,
trim: true,
2015-07-28 22:29:07 +00:00
required: 'Form Title cannot be blank',
2015-06-29 22:51:29 +00:00
},
2015-07-07 01:21:43 +00:00
language: {
type: String,
enum: ['english', 'french', 'spanish'],
2015-07-13 19:00:10 +00:00
required: 'Form must have a language',
default: 'english'
2015-07-07 01:21:43 +00:00
},
2015-06-29 22:51:29 +00:00
description: {
type: String,
default: '',
},
form_fields: {
type: [FieldSchema],
},
2015-06-29 22:51:29 +00:00
2015-06-30 02:14:43 +00:00
submissions: [{
2015-06-29 22:51:29 +00:00
type: Schema.Types.ObjectId,
ref: 'FormSubmission'
}],
admin: {
type: Schema.Types.ObjectId,
ref: 'User',
required: 'Form must have an Admin'
2015-06-29 22:51:29 +00:00
},
pdf: {
type: Schema.Types.Mixed
},
pdfFieldMap: {
type: Schema.Types.Mixed
},
2015-06-30 11:05:44 +00:00
hideFooter: {
type: Boolean,
2015-07-07 01:21:43 +00:00
default: false,
2015-06-30 11:05:44 +00:00
},
2015-06-29 22:51:29 +00:00
isGenerated: {
type: Boolean,
default: false,
},
2015-07-02 02:49:35 +00:00
isLive: {
type: Boolean,
2015-07-07 01:21:43 +00:00
default: false,
2015-07-02 02:49:35 +00:00
},
2015-06-29 22:51:29 +00:00
autofillPDFs: {
type: Boolean,
default: false,
},
2015-07-28 22:29:07 +00:00
saveCount: {
type: Number,
default: 0,
},
design: {
colors:{
backgroundColor: String,
questionColor: String,
answerColor: String,
buttonColor: String,
},
font: String,
backgroundImage: { type: Schema.Types.Mixed }
2015-07-28 22:29:07 +00:00
}
2015-06-29 22:51:29 +00:00
});
2015-07-28 22:29:07 +00:00
2015-07-03 00:49:23 +00:00
//Delete template PDF of current Form
FormSchema.pre('remove', function (next) {
if(this.pdf && process.env.NODE_ENV === 'development'){
2015-07-03 00:49:23 +00:00
//Delete template form
fs.unlink(this.pdf.path, function(err){
if (err) throw err;
console.log('successfully deleted', this.pdf.path);
});
}
});
2015-07-28 22:29:07 +00:00
var _original;
// FormSchema.post( 'init', function() {
// _original = this.toObject();
// console.log(this);
// } );
// FormSchema.virtual('_original').get(function () {
// this.constructor // ≈ mongoose.model('…', FieldSchema).findById
// .findOne({_id: this._id}).exec(function(err, original){
// if(err) {
// console.log(err);
// throw err;
// } else {
// console.log(original);
// if(original) return original.toObject();
// else return null;
// }
// });
// });
2015-07-03 00:49:23 +00:00
2015-07-27 18:11:43 +00:00
//Set _original
FormSchema.pre('save', function (next) {
2015-07-28 22:29:07 +00:00
this.saveCount = this.saveCount++;
console.log('saveCount: '+this.saveCount);
// console.log(this.constructor.model);
// console.log(FormModel);
2015-07-27 18:11:43 +00:00
this.constructor // ≈ mongoose.model('…', FieldSchema).findById
2015-07-28 22:29:07 +00:00
.findOne({_id: this._id}).exec(function(err, original){
if(err) {
console.log(err);
next(err);
} else {
2015-07-27 18:11:43 +00:00
_original = original;
2015-07-28 22:29:07 +00:00
// console.log('_original');
// console.log(_original);
2015-07-27 18:11:43 +00:00
next();
}
2015-07-28 22:29:07 +00:00
});
2015-07-27 18:11:43 +00:00
});
2015-07-03 00:49:23 +00:00
//Update lastModified and created everytime we save
2015-07-02 03:50:57 +00:00
FormSchema.pre('save', function (next) {
2015-07-03 00:49:23 +00:00
var now = new Date();
this.lastModified = now;
if( !this.created ){
this.created = now;
}
2015-07-02 03:50:57 +00:00
next();
});
function getDeletedIndexes(needle, haystack){
var deletedIndexes = [];
if(haystack.length > 0){
for(var i = 0; i < needle.length; i++){
2015-07-27 18:11:43 +00:00
if(haystack.indexOf(needle[i]) === -1){
deletedIndexes.push(i);
}
}
}
return deletedIndexes;
}
2015-07-02 03:50:57 +00:00
//Move PDF to permanent location after new template is uploaded
2015-06-29 22:51:29 +00:00
FormSchema.pre('save', function (next) {
if(this.pdf){
2015-07-03 00:49:23 +00:00
var that = this;
async.series([
function(callback){
2015-07-27 18:11:43 +00:00
if(that.isModified('pdf') && that.pdf.path){
2015-07-03 00:49:23 +00:00
var new_filename = that.title.replace(/ /g,'')+'_template.pdf';
var newDestination = path.join(config.pdfUploadPath, that.admin.username.replace(/ /g,''), that.title.replace(/ /g,'')),
stat = null;
try {
stat = fs.statSync(newDestination);
} catch (err) {
fs.mkdirSync(newDestination);
}
if (stat && !stat.isDirectory()) {
2015-07-27 18:11:43 +00:00
return callback( new Error('Directory cannot be created because an inode of a different type exists at "' + config.pdfUploadPath + '"'), null);
2015-07-03 00:49:23 +00:00
}
2015-07-27 18:11:43 +00:00
var old_path = that.pdf.path;
fs.move(old_path, path.join(newDestination, new_filename), {clobber: true}, function (err) {
2015-07-03 00:49:23 +00:00
if (err) {
console.error(err);
2015-07-27 18:11:43 +00:00
callback( new Error(err.message), 'task1');
}else {
that.pdf.path = path.join(newDestination, new_filename);
that.pdf.name = new_filename;
2015-07-03 00:49:23 +00:00
2015-07-27 18:11:43 +00:00
callback(null,'task1');
}
2015-07-03 00:49:23 +00:00
});
2015-07-27 18:11:43 +00:00
}else {
callback(null,'task1');
2015-07-03 00:49:23 +00:00
}
2015-07-27 18:11:43 +00:00
2015-07-03 00:49:23 +00:00
},
function(callback){
if(that.isGenerated){
that.pdf.path = path.join(config.pdfUploadPath, that.admin.username.replace(/ /g,''), that.title.replace(/ /g,''), that.title.replace(/ /g,'')+'_template.pdf');
that.pdf.name = that.title.replace(/ /g,'')+'_template.pdf';
var _typeConvMap = {
'Multiline': 'textarea',
'Text': 'textfield',
'Button': 'checkbox',
'Choice': 'radio',
'Password': 'password',
'FileSelect': 'filefield',
'Radio': 'radio'
};
2015-07-27 18:11:43 +00:00
console.log('autogenerating form');
// console.log(that.pdf.path);
2015-07-03 00:49:23 +00:00
pdfFiller.generateFieldJson(that.pdf.path, function(err, _form_fields){
if(err){
callback( new Error(err.message), null);
}else if(!_form_fields.length || _form_fields === undefined || _form_fields === null){
callback( new Error('Generated formfields is empty'), null);
}
2015-07-27 18:11:43 +00:00
// console.log(_form_fields);
//Map PDF field names to FormField field names
for(var i = 0; i < _form_fields.length; i++){
var field = _form_fields[i];
//Convert types from FDF to 'FormField' types
if(_typeConvMap[ field.fieldType+'' ]){
field.fieldType = _typeConvMap[ field.fieldType+'' ];
2015-07-03 00:49:23 +00:00
}
field = new Field(field);
field.required = false;
_form_fields[i] = field;
}
// console.log('NEW FORM_FIELDS: ');
// console.log(_form_fields);
2015-07-03 00:49:23 +00:00
2015-07-27 18:11:43 +00:00
that.form_fields = that.form_fields.concat(_form_fields);
// console.log('\n\nOLD FORM_FIELDS: ');
// console.log(that.form_fields);
2015-07-27 18:11:43 +00:00
that.isGenerated = false;
callback(null, 'task2');
});
}else{
callback(null, 'task2');
}
2015-07-03 00:49:23 +00:00
}
], function(err, results) {
if(err){
next(new Error({
message: err.message
}));
}
console.log('ending form save');
next();
2015-07-02 02:49:35 +00:00
});
2015-07-27 18:11:43 +00:00
}else if(_original){
if(_original.pdf){
fs.remove(_original.pdf.path, function (err) {
if(err) next(err);
console.log('file at '+_original.pdf.path+' successfully deleted');
next();
});
}
2015-07-02 02:49:35 +00:00
}
2015-07-28 22:29:07 +00:00
next();
2015-07-02 02:49:35 +00:00
});
2015-07-27 18:11:43 +00:00
FormSchema.pre('save', function (next) {
2015-07-28 22:29:07 +00:00
// var _original = this._original;
// console.log('_original\n------------');
2015-07-27 18:11:43 +00:00
// console.log(_original);
2015-07-28 22:29:07 +00:00
// console.log('field has been deleted: ');
2015-07-27 18:11:43 +00:00
// console.log(this.isModified('form_fields') && !!this.form_fields && !!_original);
2015-07-27 18:36:44 +00:00
2015-07-28 22:29:07 +00:00
if(this.isModified('form_fields') && this.form_fields.length >= 0 && _original){
2015-07-27 18:11:43 +00:00
var old_form_fields = _original.form_fields,
new_ids = _.map(_.pluck(this.form_fields, '_id'), function(id){ return ''+id;}),
old_ids = _.map(_.pluck(old_form_fields, '_id'), function(id){ return ''+id;}),
deletedIds = getDeletedIndexes(old_ids, new_ids),
that = this;
2015-07-27 18:36:44 +00:00
console.log('deletedId Indexes\n--------');
2015-07-27 18:11:43 +00:00
// console.log(deletedIds);
// console.log('old_ids\n--------');
// console.log(old_ids);
// console.log('new_ids\n--------');
// console.log(new_ids);
//Preserve fields that have at least one submission
if( deletedIds.length > 0 ){
var modifiedSubmissions = [];
async.forEachOfSeries(deletedIds,
function (deletedIdIndex, key, callback) {
var deleted_id = old_ids[deletedIdIndex];
//Search for submissions with deleted form_field
// if(submissions.length){
// submissionsWithDeletedField = _.select(form.submissions, function(submission){
// var field = _(submission.form_fields).filter(function(field) { return field._id === deleted_id; })
// return !!field;
// });
// //Push old form_field to start of array
// if(submissionsWithDeletedField.length){
// that.form_fields.unshift(old_form_fields[deletedIdIndex]);
// modifiedSubmissions.push.apply(modifiedSubmissions, submissionsWithDeletedField);
// console.log(modifiedSubmissions);
// }
// callback(null, modifiedSubmissions);
// } else{
FormSubmission.
find({ form: that._id, admin: that.admin, form_fields: {$elemMatch: {_id: deleted_id} } }).
exec(function(err, submissions){
if(err){
console.error(err);
return callback(err);
}
// console.log(submissions);
2015-06-30 02:14:43 +00:00
2015-07-27 18:11:43 +00:00
//Delete field if there are no submission(s) found
if(submissions.length) {
//Push old form_field to start of array
// that.form_fields.unshift(old_form_fields[deletedIdIndex]);
modifiedSubmissions.push.apply(modifiedSubmissions, submissions);
}
callback(null);
});
// }
},
function (err) {
if(err){
console.error(err.message);
next(err);
}
// console.log('modifiedSubmissions\n---------\n\n');
// console.log(modifiedSubmissions);
2015-07-28 22:29:07 +00:00
console.log('preserved deleted fields');
2015-07-27 18:11:43 +00:00
// console.log(submissions);
async.forEachOfSeries(modifiedSubmissions, function (submission, key, callback) {
for(var i = 0; i < deletedIds.length; i++){
var index = _.findIndex(submission.form_fields, function(field) {
var tmp_id = field._id+'';
// console.log(tmp_id === old_ids[ deletedIds[i] ]);
return tmp_id === old_ids[ deletedIds[i] ];
});
// console.log('index: '+index);
var tmpField = submission.form_fields[index];
if(tmpField){
// console.log('tmpField\n-------\n\n');
// console.log(tmpField);
//Delete old form_field
submission.form_fields.splice(index, 1);
tmpField.deletePreserved = true;
//Move old form_field to start
submission.form_fields.unshift(tmpField);
that.form_fields.unshift(tmpField);
// console.log('form.form_fields\n--------\n\n');
// console.log(that.form_fields);
}
}
submission.save(function (err) {
if(err) callback(err);
else callback(null);
});
}, function (err) {
if(err){
console.error(err.message);
next(err);
}
// console.log('form.form_fields\n--------\n\n');
// console.log(that.form_fields);
next();
});
}
);
}else {
next();
}
}else {
next();
}
});
2015-06-29 22:51:29 +00:00
FormSchema.methods.generateFDFTemplate = function() {
2015-06-29 22:51:29 +00:00
var _keys = _.pluck(this.form_fields, 'title'),
_values = _.pluck(this.form_fields, 'fieldValue');
_values.forEach(function(val){
if(val === true){
val = 'Yes';
}else if(val === false) {
val = 'Off';
}
});
var jsonObj = _.zipObject(_keys, _values);
return jsonObj;
};
2015-07-28 22:29:07 +00:00
mongoose.model('Form', FormSchema);