From 5bbac2963f8722fc1811cdb4a8f3d5f33037002f Mon Sep 17 00:00:00 2001 From: David Baldwynn Date: Thu, 2 Jul 2015 14:49:21 -0700 Subject: [PATCH 1/3] got pdf upload to work --- app/controllers/forms.server.controller.js | 124 ++++++++++++------ app/routes/forms.server.routes.js | 2 +- config/express.js | 32 +++-- .../directives/table.client.directive.js | 31 +++++ 4 files changed, 137 insertions(+), 52 deletions(-) create mode 100644 public/modules/forms/directives/table.client.directive.js diff --git a/app/controllers/forms.server.controller.js b/app/controllers/forms.server.controller.js index 6350409a..a0aaadc4 100644 --- a/app/controllers/forms.server.controller.js +++ b/app/controllers/forms.server.controller.js @@ -36,55 +36,99 @@ exports.create = function(req, res) { /** * Upload PDF */ -exports.uploadPDF = function(files, user, cb) { - var _user = JSON.parse(''+user); - console.log(_user.username); - console.log(config.tmpUploadPath); +exports.uploadPDF = function(req, res, next) { - if(files) { + console.log('inside uploadPDF'); + if(req.files){ + var pdfFile = req.files.file; + var _user = req.user; + if (req.files.size === 0) { + next(new Error('File uploaded is EMPTY')); + }else if(req.files.size > 200000000){ + next(new Error('File uploaded exceeds MAX SIZE of 200MB')); + }else { + fs.exists(pdfFile.path, function(exists) { + //If file exists move to user's tmp directory + if(exists) { - console.log('inside uploadPDF'); - console.log(files.file[0]); - var pdfFile = files.file[0]; + var newDestination = config.tmpUploadPath+_user.username; + var newFilename = String(Date.now() % 987598 * 32 % (a - Date.now()))+'.pdf'; + var stat = null; + try { + stat = fs.statSync(newDestination); + } catch (err) { + fs.mkdirSync(newDestination); + } + if (stat && !stat.isDirectory()) { + console.log('Directory cannot be created'); + next(new Error('Directory cannot be created because an inode of a different type exists at "' + newDestination + '"')); + } + + fs.move(pdfFile.path, path.join(newDestination, pdfFile.name), function (err) { + if (err) { + next(new Error(err.message)); + } + pdfFile.name = newFilename; + pdfFile.path = path.join(newDestination, pdfFile.name); + console.log(pdfFile.name + ' uploaded to ' + pdfFile.path); + res.status(200).send(pdfFile); + }); - if (pdfFile.size === 0) { - throw new Error('Files uploaded are EMPTY'); + } else { + next(new Error('Did NOT get your file!')); + } + }); } - fs.exists(pdfFile.path, function(exists) { - //If file exists move to user's tmp directory - if(exists) { - - var newDestination = path.join(config.tmpUploadPath, _user.username); - var stat = null; - try { - stat = fs.statSync(newDestination); - } catch (err) { - fs.mkdirSync(newDestination); - } - if (stat && !stat.isDirectory()) { - console.log('Directory cannot be created'); - throw new Error('Directory cannot be created because an inode of a different type exists at "' + newDestination + '"'); - } - - fs.move(pdfFile.path, path.join(newDestination, pdfFile.name), function (err) { - if (err) { - throw new Error(err.message); - } - pdfFile.path = path.join(newDestination, pdfFile.name); - - return cb(pdfFile); - }); - - } else { - throw new Error('Did NOT get your file!'); - } - }); }else { - throw new Error('File NOT uploaded'); + next(new Error('Uploaded files were NOT detected')); } }; +// exports.uploadPDF = function(pdfFile, _user, cb) { +// // console.log(_user.username); +// // console.log(config.tmpUploadPath); + + +// console.log('inside uploadPDF'); +// // console.log(pdfFile); + +// if (pdfFile.size === 0) { +// cb(new Error('Files uploaded are EMPTY'), null); +// }else { +// fs.exists(pdfFile.path, function(exists) { +// //If file exists move to user's tmp directory +// if(exists) { + +// var newDestination = config.tmpUploadPath+""+_user.username; +// var stat = null; +// try { +// stat = fs.statSync(newDestination); +// } catch (err) { +// fs.mkdirSync(newDestination); +// } +// if (stat && !stat.isDirectory()) { +// console.log('Directory cannot be created'); +// cb(new Error('Directory cannot be created because an inode of a different type exists at "' + newDestination + '"'), null); +// } + +// fs.move(pdfFile.path, path.join(newDestination, pdfFile.name), function (err) { +// if (err) { +// return cb(new Error(err.message), null); +// } +// pdfFile.path = path.join(newDestination, pdfFile.name); + +// return cb(null, pdfFile); +// }); + +// } else { +// cb(new Error('Did NOT get your file!'), null); +// } +// }); +// } + +// }; + /** * Show the current form */ diff --git a/app/routes/forms.server.routes.js b/app/routes/forms.server.routes.js index d5340659..a49b79b8 100644 --- a/app/routes/forms.server.routes.js +++ b/app/routes/forms.server.routes.js @@ -9,7 +9,7 @@ var users = require('../../app/controllers/users.server.controller'), module.exports = function(app) { // Form Routes app.route('/upload/pdf') - .post(forms.uploadPDF); + .all(forms.uploadPDF); app.route('/forms') .get(users.requiresLogin, forms.list) diff --git a/config/express.js b/config/express.js index f36c9863..a0e65785 100755 --- a/config/express.js +++ b/config/express.js @@ -106,19 +106,29 @@ module.exports = function(db) { console.log(file.originalname + ' is starting ...'); }, onFileUploadComplete: function (file, req, res) { + console.log(file.originalname + ' uploaded to ' + file.path); // console.log('\n\nheadersSent in onFileUploadComplete: ', res.headersSent); - console.log(req.body.user); - try{ - formCtrl.uploadPDF(req.files, req.body.user, function(_file){ - console.log(_file.filename + ' uploaded to ' + _file.path); - res.status(200).send(_file); - }); - }catch(err) { - res.status(500).send({ - message: err.message - }); - } + // res.status(200).send(file); } + // console.log('\n\nheadersSent in onFileUploadComplete: ', res.headersSent); + // console.log(req.body.user); + // console.log(req.user); + // var _user = JSON.parse(req.body.user); + // console.log(file) + + // formCtrl.uploadPDF(file, _user, function(err, _file){ + // if(err){ + // console.log('\n\n ERROR: '+err.message) + // res.status(500).send({ + // message: err.message + // }); + // }else { + // console.log(_file.filename + ' uploaded to ' + _file.path); + // res.status(200).send(_file); + // } + + // }); + // } })); // CookieParser should be above session diff --git a/public/modules/forms/directives/table.client.directive.js b/public/modules/forms/directives/table.client.directive.js new file mode 100644 index 00000000..745db428 --- /dev/null +++ b/public/modules/forms/directives/table.client.directive.js @@ -0,0 +1,31 @@ +'use strict'; + +angular.module('forms').directive('tableDirective', ['$http', '$timeout', 'Auth', + function ($http, $timeout, Auth) { + return { + controller: function($scope){ + + $scope.toggleChecker = function(checked) { + var rows = $scope.gridOptions.$gridScope.renderedRows, + allChecked = true; + + for (var r = 0; r < rows.length; r++) { + if (rows[r].entity.checker !== true) { + allChecked = false; + break; + } + } + + $scope.gridOptions.$gridScope.checker = allChecked; + }; + + }, + templateUrl: './modules/forms/views/directiveViews/table/table.html', + restrict: 'E', + scope: { + rows:'=', + extras:'=', + } + }; + } +]); \ No newline at end of file From 0090c98ad244cacacc08964cb39ff343ef47ee92 Mon Sep 17 00:00:00 2001 From: David Baldwynn Date: Thu, 2 Jul 2015 16:34:00 -0700 Subject: [PATCH 2/3] got pdf generation to work --- app/controllers/forms.server.controller.js | 7 +-- app/models/form.server.model.js | 58 +++++++++++++++---- app/routes/forms.server.routes.js | 12 ++-- .../forms/config/forms.client.config.js | 2 +- .../forms/config/forms.client.routes.js | 8 --- .../create-form.client.controller.js | 58 ++++++++++--------- .../view-form-submission.client.controller.js | 26 +++------ .../authentication.client.controller.js | 2 - .../controllers/password.client.controller.js | 19 ------ 9 files changed, 93 insertions(+), 99 deletions(-) diff --git a/app/controllers/forms.server.controller.js b/app/controllers/forms.server.controller.js index a0aaadc4..dc247a93 100644 --- a/app/controllers/forms.server.controller.js +++ b/app/controllers/forms.server.controller.js @@ -52,7 +52,6 @@ exports.uploadPDF = function(req, res, next) { if(exists) { var newDestination = config.tmpUploadPath+_user.username; - var newFilename = String(Date.now() % 987598 * 32 % (a - Date.now()))+'.pdf'; var stat = null; try { stat = fs.statSync(newDestination); @@ -68,9 +67,8 @@ exports.uploadPDF = function(req, res, next) { if (err) { next(new Error(err.message)); } - pdfFile.name = newFilename; pdfFile.path = path.join(newDestination, pdfFile.name); - console.log(pdfFile.name + ' uploaded to ' + pdfFile.path); + console.log(pdfFile.name + ' uploaded to ' + pdfFile.path); res.status(200).send(pdfFile); }); @@ -209,7 +207,8 @@ exports.listSubmissions = function(req, res) { exports.update = function(req, res) { var form = req.form; - form = _.extend(form, req.body); + console.log(req.body.form); + form = _.extend(form, req.body.form); form.admin = req.user; form.save(function(err) { diff --git a/app/models/form.server.model.js b/app/models/form.server.model.js index e0ff4a85..86212e07 100644 --- a/app/models/form.server.model.js +++ b/app/models/form.server.model.js @@ -73,6 +73,25 @@ var FormSchema = new Schema({ }, }); +//Create folder for user's pdfs +FormSchema.pre('save', function (next) { + var newDestination = path.join(config.pdfUploadPath, this.admin.username.trim()), + stat = null; + + try { + stat = fs.statSync(newDestination); + } catch (err) { + fs.mkdirSync(newDestination); + } + if (stat && !stat.isDirectory()) { + console.log('Directory cannot be created'); + next( new Error('Directory cannot be created because an inode of a different type exists at "' + newDestination + '"') ); + }else{ + next(); + } +}); + + //Update lastModified everytime we save FormSchema.pre('save', function (next) { this.lastModified = Date.now(); @@ -82,12 +101,15 @@ FormSchema.pre('save', function (next) { //Move PDF to permanent location after new template is uploaded FormSchema.pre('save', function (next) { + console.log(this.pdf); + console.log("isModified: "+this.isModified('pdf')); + var that = this; if(this.pdf){ - if(this.pdf.modified){ + if(this.isModified('pdf')){ - var new_filename = this.pdf.title.trim()+'_template.pdf'; + var new_filename = this.title.trim()+'_template.pdf'; - var newDestination = path.join(config.pdfUploadPath, this.pdf.title.trim()), + var newDestination = path.join(config.pdfUploadPath, this.admin.username.trim(), this.title.trim()), stat = null; try { @@ -96,23 +118,35 @@ FormSchema.pre('save', function (next) { fs.mkdirSync(newDestination); } if (stat && !stat.isDirectory()) { - console.log('Directory cannot be created'); + console.log('Directory '+newDestination+' cannot be created'); next( new Error('Directory cannot be created because an inode of a different type exists at "' + config.pdfUploadPath + '"') ); } console.log('about to move PDF'); + //Move pdf to permanent location fs.move(this.pdf.path, path.join(newDestination, new_filename), function (err) { - if (err) { - console.error(err); - next( new Error(err.message) ); - } + // if (err) { + // console.error(err); + // next( new Error(err.message) ); + // } - this.pdf.path = path.join(newDestination, new_filename); - this.pdf.name = new_filename; + // //Delete old pdf file + // fs.unlink(that.pdf.path, function(err){ + if (err) { + console.error(err); + next( new Error(err.message) ); + } - console.log('PDF file:'+this.pdf.name+' successfully moved to: '+this.pdf.path); + // console.log('successfully deleted', that.pdf.path); + + that.pdf.path = path.join(newDestination, new_filename); + that.pdf.name = new_filename; + + console.log('\n\n PDF file:'+that.pdf.name+' successfully moved to: '+that.pdf.path); + + next(); + // }); - next(); }); } diff --git a/app/routes/forms.server.routes.js b/app/routes/forms.server.routes.js index a49b79b8..9974b631 100644 --- a/app/routes/forms.server.routes.js +++ b/app/routes/forms.server.routes.js @@ -9,21 +9,21 @@ var users = require('../../app/controllers/users.server.controller'), module.exports = function(app) { // Form Routes app.route('/upload/pdf') - .all(forms.uploadPDF); + .post(forms.uploadPDF); app.route('/forms') .get(users.requiresLogin, forms.list) .post(users.requiresLogin, forms.create); - app.route('/forms/:formId/submissions') - .get(forms.listSubmissions); - - app.route('/forms/:formId') + app.route('/forms/:formId([a-zA-Z0-9]+)') .get(forms.read) - .post(forms.createSubmission) + // .post(forms.createSubmission) .put(users.requiresLogin, forms.hasAuthorization, forms.update) .delete(users.requiresLogin, forms.hasAuthorization, forms.delete); + app.route('/forms/:formId([a-zA-Z0-9]+)/submissions') + .get(forms.listSubmissions); + // Finish by binding the form middleware app.param('formId', forms.formByID); }; diff --git a/public/modules/forms/config/forms.client.config.js b/public/modules/forms/config/forms.client.config.js index d57ecbc1..e1d242ac 100644 --- a/public/modules/forms/config/forms.client.config.js +++ b/public/modules/forms/config/forms.client.config.js @@ -14,7 +14,7 @@ angular.module('forms').run(['Menus', return function(formObj){ //get keys var formKeys = Object.keys(formObj); - // console.log(formKeys); + //we only care about things that don't start with $ var fieldKeys = formKeys.filter(function(key){ return key[0] !== '$'; diff --git a/public/modules/forms/config/forms.client.routes.js b/public/modules/forms/config/forms.client.routes.js index b0425431..c8811803 100644 --- a/public/modules/forms/config/forms.client.routes.js +++ b/public/modules/forms/config/forms.client.routes.js @@ -12,10 +12,6 @@ angular.module('forms').config(['$stateProvider', state('createForm', { url: '/forms/create', templateUrl: 'modules/forms/views/create-form.client.view.html', - // parent: 'restricted', - // data: { - // roles: ['user', 'admin'], - // }, }). state('viewForm', { url: '/forms/:formId/admin', @@ -32,10 +28,6 @@ angular.module('forms').config(['$stateProvider', state('editForm', { url: '/forms/:formId/edit', templateUrl: 'modules/forms/views/create-form.client.view.html', - // parent: 'restricted', - // data: { - // roles: ['user', 'admin'], - // }, }); } ]); \ No newline at end of file diff --git a/public/modules/forms/controllers/create-form.client.controller.js b/public/modules/forms/controllers/create-form.client.controller.js index 8769606f..91126c54 100644 --- a/public/modules/forms/controllers/create-form.client.controller.js +++ b/public/modules/forms/controllers/create-form.client.controller.js @@ -1,25 +1,21 @@ 'use strict'; -angular.module('forms').controller('EditFormController', ['$scope', '$state', '$rootScope', 'Upload', '$stateParams', 'FormFields', 'Forms', 'CurrentForm', '$modal', '$location', - function ($scope, $state, $rootScope, Upload, $stateParams, FormFields, Forms, CurrentForm, $modal, $location) { +angular.module('forms').controller('EditFormController', ['$scope', '$state', '$rootScope', 'Upload', '$stateParams', 'FormFields', 'Forms', 'CurrentForm', '$modal', '$location', '$http', + function ($scope, $state, $rootScope, Upload, $stateParams, FormFields, Forms, CurrentForm, $modal, $location, $http) { $scope.isNewForm = false; $scope.pdfLoading = false; var _current_upload = null; $scope.log = ''; + $scope.form = {}; // Get current form if it exists, or create new one if($stateParams.formId){ - $scope.form = {}; - var _form = Forms.get({ formId: $stateParams.formId}, function(form){ - _form.pdf = form.pdf; - _form.$save(); - - $scope.form = angular.fromJson(angular.toJson(_form)); - console.log(JSON.stringify($scope.form.pdf)); + Forms.get({ formId: $stateParams.formId}, function(form){ + $scope.form = angular.fromJson(angular.toJson(form)); + console.log($scope.form); }); } else { - $scope.form = {}; $scope.form.form_fields = []; $scope.isNewForm = true; } @@ -56,13 +52,14 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$ evt.config.file.name + '\n' + $scope.log; $scope.pdfLoading = true; }).success(function (data, status, headers, config) { - $scope.log = 'file ' + data.originalname + 'uploaded as '+ data.name +'. JSON: ' + JSON.stringify(data) + '\n' + $scope.log; - $scope.form.pdf = data; + $scope.log = 'file ' + data.originalname + ' uploaded as '+ data.name +'. JSON: ' + JSON.stringify(data) + '\n' + $scope.log; + console.log($scope.form.pdf); + $scope.form.pdf = angular.fromJson(angular.toJson(data)); $scope.pdfLoading = false; console.log($scope.log); console.log('$scope.pdf: '+$scope.form.pdf.name); - if(!$scope.$$phase) { + if(!$scope.$$phase){ $scope.$apply(); } }).error(function(err){ @@ -85,23 +82,19 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$ // Create new Form object var form = new Forms($scope.form); - form.$save(function(response) { - + $http.post('/forms', {form: $scope.form}) + .success(function(data, status, headers){ console.log('form created'); - // console.log(response.pdf); // Clear form fields $scope.form = {}; - // Redirect after save $scope.goToWithId('viewForm', response._id); - - }, function(errorResponse) { + }).error(function(err){ console.log(errorResponse.data.message); $scope.error = errorResponse.data.message; }); } else{ - console.log('update form'); $scope.update(); } }; @@ -109,14 +102,24 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$ // Update existing Form $scope.update = function() { var form = new Forms($scope.form); - form.$update(function(response) { - console.log('form updated'); - $scope.goToWithId('viewForm', response._id); - // $location.path('forms/' + response._id + '/admin'); - }, function(errorResponse) { - console.log(errorResponse.data.message); - $scope.error = errorResponse.data.message; + console.log('update form'); + console.log($scope.form); + + $http.put('/forms/'+$scope.form._id, {form: $scope.form}) + .success(function(data, status, headers){ + console.log('form updated successfully'); + $scope.goToWithId('viewForm', $scope.form._id); + }).error(function(err){ + console.log('Error occured during form UPDATE.\n'); + console.log(err); }); + // form.$update({formId: $scope.form._id}, function(response) { + // console.log('form successfully updated'); + // $scope.goToWithId('viewForm', response._id); + // }, function(errorResponse) { + // console.log(errorResponse.data.message); + // $scope.error = errorResponse.data.message; + // }); }; //Populate AddField with all available form field types @@ -153,7 +156,6 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$ // put newField into fields array $scope.form.form_fields.push(newField); - // console.log($scope.form.form_fields); }; // deletes particular field on button click diff --git a/public/modules/forms/controllers/view-form-submission.client.controller.js b/public/modules/forms/controllers/view-form-submission.client.controller.js index c87a0ff2..fc45e136 100644 --- a/public/modules/forms/controllers/view-form-submission.client.controller.js +++ b/public/modules/forms/controllers/view-form-submission.client.controller.js @@ -28,26 +28,14 @@ angular.module('forms').controller('ViewSubmissionController', ['$scope', '$stat // Remove existing submission $scope.remove = function(submission) { - if (submission) { - submission.$remove(); - - $http.delete('/forms/'+$stateParams.formId+'submissions/'+$scope.submission._id). - success(function(data, status, headers){ - console.log('submission deleted successfully'); - alert('submission deleted..'); - }); - - } else { - $scope.submission.$remove(function() { - console.log('remove'); - $state.path('submissions'); - $http.delete('/forms/'+$stateParams.formId+'/submissions/'+$scope.submission._id). - success(function(data, status, headers){ - console.log('submission deleted successfully'); - alert('submission deleted..'); - }); - }); + if (!submission) { + submission = $scope.submission; } + $http.delete('/forms/'+$stateParams.formId+'/submissions/'+submission._id). + success(function(data, status, headers){ + console.log('submission deleted successfully'); + alert('submission deleted..'); + }); }; diff --git a/public/modules/users/controllers/authentication.client.controller.js b/public/modules/users/controllers/authentication.client.controller.js index 04de32af..36c9a292 100755 --- a/public/modules/users/controllers/authentication.client.controller.js +++ b/public/modules/users/controllers/authentication.client.controller.js @@ -6,8 +6,6 @@ angular.module('users').controller('AuthenticationController', ['$scope', '$loca $scope = $rootScope; $scope.credentials = {}; - // $scope.authentication = Principal; - // If user is signed in then redirect back home if ($scope.authentication.isAuthenticated()) $state.go('home'); diff --git a/public/modules/users/controllers/password.client.controller.js b/public/modules/users/controllers/password.client.controller.js index 99f5deac..817977f2 100755 --- a/public/modules/users/controllers/password.client.controller.js +++ b/public/modules/users/controllers/password.client.controller.js @@ -2,14 +2,10 @@ angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$state', 'User', function($scope, $stateParams, $state, User) { - // $scope.authentication = Principal; //If user is signed in then redirect back home if ($scope.authentication.isAuthenticated()) $state.go('home'); - // Principal.identity().then(function(response){ - // $scope.authentication.user = response; - // Submit forgotten password account id $scope.askForPasswordReset = function() { User.askForPasswordReset($scope.credentials).then( @@ -41,21 +37,6 @@ angular.module('users').controller('PasswordController', ['$scope', '$stateParam $scope.passwordDetails = null; } ); - // $scope.success = $scope.error = null; - - // $http.post('/auth/reset/' + $stateParams.token, $scope.passwordDetails).success(function(response) { - // // If successful show success message and clear form - // $scope.passwordDetails = null; - - // // Attach user profile - // // Principal.user() = response; - - // // And redirect to the index page - // $state.go('reset-success'); - // }).error(function(response) { - // $scope.error = response.message; - // }); }; - // }); } ]); \ No newline at end of file From 71d315a2d01a968a11b75811e8f619ca36e15e80 Mon Sep 17 00:00:00 2001 From: David Baldwynn Date: Thu, 2 Jul 2015 17:49:23 -0700 Subject: [PATCH 3/3] got pdf generation working --- app/controllers/forms.server.controller.js | 5 +- app/models/form.server.model.js | 311 +++++++++++------- app/models/form_submission.server.model.js | 5 +- .../create-form.client.controller.js | 10 +- 4 files changed, 198 insertions(+), 133 deletions(-) diff --git a/app/controllers/forms.server.controller.js b/app/controllers/forms.server.controller.js index dc247a93..01351ffd 100644 --- a/app/controllers/forms.server.controller.js +++ b/app/controllers/forms.server.controller.js @@ -205,9 +205,10 @@ exports.listSubmissions = function(req, res) { * Update a form */ exports.update = function(req, res) { - + console.log('in form.update()'); + var form = req.form; - console.log(req.body.form); + // console.log(req.body.form); form = _.extend(form, req.body.form); form.admin = req.user; diff --git a/app/models/form.server.model.js b/app/models/form.server.model.js index 86212e07..ad637fff 100644 --- a/app/models/form.server.model.js +++ b/app/models/form.server.model.js @@ -11,6 +11,7 @@ var mongoose = require('mongoose'), config = require('../../config/config'), path = require('path'), fs = require('fs-extra'), + async = require('async'), Field = mongoose.model('Field', FieldSchema); @@ -73,9 +74,20 @@ var FormSchema = new Schema({ }, }); +//Delete template PDF of current Form +FormSchema.pre('remove', function (next) { + if(this.pdf){ + //Delete template form + fs.unlink(this.pdf.path, function(err){ + if (err) throw err; + console.log('successfully deleted', this.pdf.path); + }); + } +}); + //Create folder for user's pdfs FormSchema.pre('save', function (next) { - var newDestination = path.join(config.pdfUploadPath, this.admin.username.trim()), + var newDestination = path.join(config.pdfUploadPath, this.admin.username.replace(/ /g,'')), stat = null; try { @@ -91,149 +103,200 @@ FormSchema.pre('save', function (next) { } }); - -//Update lastModified everytime we save +//Update lastModified and created everytime we save FormSchema.pre('save', function (next) { - this.lastModified = Date.now(); + var now = new Date(); + this.lastModified = now; + if( !this.created ){ + this.created = now; + } next(); }); //Move PDF to permanent location after new template is uploaded FormSchema.pre('save', function (next) { - console.log(this.pdf); - console.log("isModified: "+this.isModified('pdf')); - var that = this; if(this.pdf){ - if(this.isModified('pdf')){ + var that = this; + async.series([ + function(callback){ + if(that.isModified('pdf')){ + console.log('about to move PDF'); - var new_filename = this.title.trim()+'_template.pdf'; + var new_filename = that.title.replace(/ /g,'')+'_template.pdf'; - var newDestination = path.join(config.pdfUploadPath, this.admin.username.trim(), this.title.trim()), - stat = null; + 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()) { - console.log('Directory '+newDestination+' cannot be created'); - next( new Error('Directory cannot be created because an inode of a different type exists at "' + config.pdfUploadPath + '"') ); - } + try { + stat = fs.statSync(newDestination); + } catch (err) { + fs.mkdirSync(newDestination); + } + if (stat && !stat.isDirectory()) { + console.log('Directory '+newDestination+' cannot be created'); + callback( new Error('Directory cannot be created because an inode of a different type exists at "' + config.pdfUploadPath + '"') ); + } - console.log('about to move PDF'); - //Move pdf to permanent location - fs.move(this.pdf.path, path.join(newDestination, new_filename), function (err) { - // if (err) { - // console.error(err); - // next( new Error(err.message) ); - // } + console.log('about to move PDF'); - // //Delete old pdf file - // fs.unlink(that.pdf.path, function(err){ - if (err) { - console.error(err); + fs.move(that.pdf.path, path.join(newDestination, new_filename), function (err) { + if (err) { + console.error(err); + callback( new Error(err.message) ); + } + that.pdf.path = path.join(newDestination, new_filename); + that.pdf.name = new_filename; + + console.log('\n\n PDF file:'+that.pdf.name+' successfully moved to: '+that.pdf.path); + + callback(null,null); + }); + } + callback(null,null); + }, + 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' + }; + + console.log('autogenerating form'); + console.log(that.pdf.path); + + try { + pdfFiller.generateFieldJson(that.pdf.path, function(_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+'' ]; + } + + field.fieldValue = ''; + field.created = Date.now(); + field.required = true; + field.disabled = false; + + // field = new Field(field); + // field.save(function(err) { + // if (err) { + // console.error(err.message); + // throw new Error(err.message); + // }); + // } else { + // _form_fields[i] = that; + // } + // }); + _form_fields[i] = field; + } + + console.log('NEW FORM_FIELDS: '); + console.log(_form_fields); + + console.log('\n\nOLD FORM_FIELDS: '); + console.log(that.form_fields); + + that.form_fields = _form_fields; + callback(); + }); + } catch(err){ next( new Error(err.message) ); } - - // console.log('successfully deleted', that.pdf.path); - - that.pdf.path = path.join(newDestination, new_filename); - that.pdf.name = new_filename; - - console.log('\n\n PDF file:'+that.pdf.name+' successfully moved to: '+that.pdf.path); - - next(); - // }); - - }); - - } - }else { - next(); - } -}); - -//Delete template PDF of current Form -FormSchema.pre('remove', function (next) { - if(this.pdf){ - //Delete template form - fs.unlink(this.pdf.path, function(err){ - if (err) throw err; - console.log('successfully deleted', this.pdf.path); + } + callback(null,null); + } + ], function(err, results) { + if(err){ + next(new Error({ + message: err.message + })); + } + next(); }); } -}); - -//Autogenerate FORM from PDF if 'isGenerated' flag is 'true' -FormSchema.pre('save', function (next) { - var field, _form_fields; - - if(this.isGenerated && this.pdf){ - - var _typeConvMap = { - 'Multiline': 'textarea', - 'Text': 'textfield', - 'Button': 'checkbox', - 'Choice': 'radio', - 'Password': 'password', - 'FileSelect': 'filefield', - 'Radio': 'radio' - }; - - var that = this; - console.log('autogenerating form'); - - try { - pdfFiller.generateFieldJson(this.pdf.path, function(_form_fields){ - - //Map PDF field names to FormField field names - for(var i = 0; i < _form_fields.length; i++){ - field = _form_fields[i]; - - //Convert types from FDF to 'FormField' types - if(_typeConvMap[ field.fieldType+'' ]){ - field.fieldType = _typeConvMap[ field.fieldType+'' ]; - } - - field.fieldValue = ''; - field.created = Date.now(); - field.required = true; - field.disabled = false; - - // field = new Field(field); - // field.save(function(err) { - // if (err) { - // console.error(err.message); - // throw new Error(err.message); - // }); - // } else { - // _form_fields[i] = this; - // } - // }); - _form_fields[i] = field; - } - - console.log('NEW FORM_FIELDS: '); - console.log(_form_fields); - - console.log('\n\nOLD FORM_FIELDS: '); - console.log(that.form_fields); - - that.form_fields = _form_fields; - next(); - }); - } catch(err){ - next( new Error(err.message) ); - } - - } - - //Throw error if we encounter form with invalid type next(); }); +//Autogenerate Form_fields from PDF if 'isGenerated' flag is set +// FormSchema.pre('save', function (next) { +// var field, _form_fields; + +// if(this.pdf){ +// if(this.isGenerated){ + +// var _typeConvMap = { +// 'Multiline': 'textarea', +// 'Text': 'textfield', +// 'Button': 'checkbox', +// 'Choice': 'radio', +// 'Password': 'password', +// 'FileSelect': 'filefield', +// 'Radio': 'radio' +// }; + +// var that = this; +// console.log('autogenerating form'); + +// try { +// pdfFiller.generateFieldJson(this.pdf.path, function(_form_fields){ + +// //Map PDF field names to FormField field names +// for(var i = 0; i < _form_fields.length; i++){ +// field = _form_fields[i]; + +// //Convert types from FDF to 'FormField' types +// if(_typeConvMap[ field.fieldType+'' ]){ +// field.fieldType = _typeConvMap[ field.fieldType+'' ]; +// } + +// field.fieldValue = ''; +// field.created = Date.now(); +// field.required = true; +// field.disabled = false; + +// // field = new Field(field); +// // field.save(function(err) { +// // if (err) { +// // console.error(err.message); +// // throw new Error(err.message); +// // }); +// // } else { +// // _form_fields[i] = this; +// // } +// // }); +// _form_fields[i] = field; +// } + +// console.log('NEW FORM_FIELDS: '); +// console.log(_form_fields); + +// console.log('\n\nOLD FORM_FIELDS: '); +// console.log(that.form_fields); + +// that.form_fields = _form_fields; +// next(); +// }); +// } catch(err){ +// next( new Error(err.message) ); +// } +// } +// } + +// next(); +// }); + FormSchema.methods.convertToFDF = function (cb) { var _keys = _.pluck(this.form_fields, 'title'), _values = _.pluck(this.form_fields, 'fieldValue'); diff --git a/app/models/form_submission.server.model.js b/app/models/form_submission.server.model.js index c4b6c7fb..40fe049e 100644 --- a/app/models/form_submission.server.model.js +++ b/app/models/form_submission.server.model.js @@ -90,12 +90,11 @@ FormSubmissionSchema.pre('save', function (next) { if(_form.autofillPDFs){ - dest_filename = _form.title.trim()+'_submission_'+Date.now()+'.pdf'; + dest_filename = _form.title.replace(/ /g,'')+'_submission_'+Date.now()+'.pdf'; dest_path = path.join(config.pdfUploadPath, dest_filename); this.pdfFilePath = dest_path; - // console.log('autofillPDFs check'); pdfFiller.fillForm(_form.pdf.path, dest_path, this.fdfData, function(err){ console.log('fdfData: \n'); @@ -108,7 +107,7 @@ FormSubmissionSchema.pre('save', function (next) { console.log('\n err.message: '+err.message); next( new Error(err.message) ); } - console.log('Field data from Form: '+_form.title.trim()+' outputed to new PDF: '+dest_path); + console.log('Field data from Form: '+_form.title.replace(/ /g,'')+' outputed to new PDF: '+dest_path); next(); }); } else { diff --git a/public/modules/forms/controllers/create-form.client.controller.js b/public/modules/forms/controllers/create-form.client.controller.js index 91126c54..6c20f804 100644 --- a/public/modules/forms/controllers/create-form.client.controller.js +++ b/public/modules/forms/controllers/create-form.client.controller.js @@ -5,9 +5,10 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$ $scope.isNewForm = false; $scope.pdfLoading = false; - var _current_upload = null; - $scope.log = ''; + $scope.form = {}; + $scope.log = ''; + var _current_upload = null; // Get current form if it exists, or create new one if($stateParams.formId){ @@ -24,12 +25,13 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$ $scope.cancelUpload = function(){ _current_upload.abort(); $scope.pdfLoading = false; + $scope.removePDF(); }; $scope.removePDF = function(){ $scope.form.pdf = null; - $scope.isGenerated = false; - $scope.autofillPDFs = false; + $scope.form.isGenerated = false; + $scope.form.autofillPDFs = false; console.log('form.pdf: '+$scope.form.pdf+' REMOVED'); };