got pdf generation to work

This commit is contained in:
David Baldwynn 2015-07-02 16:34:00 -07:00
parent 5bbac2963f
commit 0090c98ad2
9 changed files with 93 additions and 99 deletions

View file

@ -52,7 +52,6 @@ exports.uploadPDF = function(req, res, next) {
if(exists) { if(exists) {
var newDestination = config.tmpUploadPath+_user.username; var newDestination = config.tmpUploadPath+_user.username;
var newFilename = String(Date.now() % 987598 * 32 % (a - Date.now()))+'.pdf';
var stat = null; var stat = null;
try { try {
stat = fs.statSync(newDestination); stat = fs.statSync(newDestination);
@ -68,9 +67,8 @@ exports.uploadPDF = function(req, res, next) {
if (err) { if (err) {
next(new Error(err.message)); next(new Error(err.message));
} }
pdfFile.name = newFilename;
pdfFile.path = path.join(newDestination, pdfFile.name); 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); res.status(200).send(pdfFile);
}); });
@ -209,7 +207,8 @@ exports.listSubmissions = function(req, res) {
exports.update = function(req, res) { exports.update = function(req, res) {
var form = req.form; 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.admin = req.user;
form.save(function(err) { form.save(function(err) {

View file

@ -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 //Update lastModified everytime we save
FormSchema.pre('save', function (next) { FormSchema.pre('save', function (next) {
this.lastModified = Date.now(); this.lastModified = Date.now();
@ -82,12 +101,15 @@ FormSchema.pre('save', function (next) {
//Move PDF to permanent location after new template is uploaded //Move PDF to permanent location after new template is uploaded
FormSchema.pre('save', function (next) { FormSchema.pre('save', function (next) {
console.log(this.pdf);
console.log("isModified: "+this.isModified('pdf'));
var that = this;
if(this.pdf){ 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; stat = null;
try { try {
@ -96,23 +118,35 @@ FormSchema.pre('save', function (next) {
fs.mkdirSync(newDestination); fs.mkdirSync(newDestination);
} }
if (stat && !stat.isDirectory()) { 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 + '"') ); next( new Error('Directory cannot be created because an inode of a different type exists at "' + config.pdfUploadPath + '"') );
} }
console.log('about to move PDF'); console.log('about to move PDF');
//Move pdf to permanent location
fs.move(this.pdf.path, path.join(newDestination, new_filename), function (err) { fs.move(this.pdf.path, path.join(newDestination, new_filename), function (err) {
if (err) { // if (err) {
console.error(err); // console.error(err);
next( new Error(err.message) ); // next( new Error(err.message) );
} // }
this.pdf.path = path.join(newDestination, new_filename); // //Delete old pdf file
this.pdf.name = new_filename; // 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();
}); });
} }

View file

@ -9,21 +9,21 @@ var users = require('../../app/controllers/users.server.controller'),
module.exports = function(app) { module.exports = function(app) {
// Form Routes // Form Routes
app.route('/upload/pdf') app.route('/upload/pdf')
.all(forms.uploadPDF); .post(forms.uploadPDF);
app.route('/forms') app.route('/forms')
.get(users.requiresLogin, forms.list) .get(users.requiresLogin, forms.list)
.post(users.requiresLogin, forms.create); .post(users.requiresLogin, forms.create);
app.route('/forms/:formId/submissions') app.route('/forms/:formId([a-zA-Z0-9]+)')
.get(forms.listSubmissions);
app.route('/forms/:formId')
.get(forms.read) .get(forms.read)
.post(forms.createSubmission) // .post(forms.createSubmission)
.put(users.requiresLogin, forms.hasAuthorization, forms.update) .put(users.requiresLogin, forms.hasAuthorization, forms.update)
.delete(users.requiresLogin, forms.hasAuthorization, forms.delete); .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 // Finish by binding the form middleware
app.param('formId', forms.formByID); app.param('formId', forms.formByID);
}; };

View file

@ -14,7 +14,7 @@ angular.module('forms').run(['Menus',
return function(formObj){ return function(formObj){
//get keys //get keys
var formKeys = Object.keys(formObj); var formKeys = Object.keys(formObj);
// console.log(formKeys);
//we only care about things that don't start with $ //we only care about things that don't start with $
var fieldKeys = formKeys.filter(function(key){ var fieldKeys = formKeys.filter(function(key){
return key[0] !== '$'; return key[0] !== '$';

View file

@ -12,10 +12,6 @@ angular.module('forms').config(['$stateProvider',
state('createForm', { state('createForm', {
url: '/forms/create', url: '/forms/create',
templateUrl: 'modules/forms/views/create-form.client.view.html', templateUrl: 'modules/forms/views/create-form.client.view.html',
// parent: 'restricted',
// data: {
// roles: ['user', 'admin'],
// },
}). }).
state('viewForm', { state('viewForm', {
url: '/forms/:formId/admin', url: '/forms/:formId/admin',
@ -32,10 +28,6 @@ angular.module('forms').config(['$stateProvider',
state('editForm', { state('editForm', {
url: '/forms/:formId/edit', url: '/forms/:formId/edit',
templateUrl: 'modules/forms/views/create-form.client.view.html', templateUrl: 'modules/forms/views/create-form.client.view.html',
// parent: 'restricted',
// data: {
// roles: ['user', 'admin'],
// },
}); });
} }
]); ]);

View file

@ -1,25 +1,21 @@
'use strict'; 'use strict';
angular.module('forms').controller('EditFormController', ['$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) { function ($scope, $state, $rootScope, Upload, $stateParams, FormFields, Forms, CurrentForm, $modal, $location, $http) {
$scope.isNewForm = false; $scope.isNewForm = false;
$scope.pdfLoading = false; $scope.pdfLoading = false;
var _current_upload = null; var _current_upload = null;
$scope.log = ''; $scope.log = '';
$scope.form = {};
// Get current form if it exists, or create new one // Get current form if it exists, or create new one
if($stateParams.formId){ if($stateParams.formId){
$scope.form = {}; Forms.get({ formId: $stateParams.formId}, function(form){
var _form = Forms.get({ formId: $stateParams.formId}, function(form){ $scope.form = angular.fromJson(angular.toJson(form));
_form.pdf = form.pdf; console.log($scope.form);
_form.$save();
$scope.form = angular.fromJson(angular.toJson(_form));
console.log(JSON.stringify($scope.form.pdf));
}); });
} else { } else {
$scope.form = {};
$scope.form.form_fields = []; $scope.form.form_fields = [];
$scope.isNewForm = true; $scope.isNewForm = true;
} }
@ -56,13 +52,14 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$
evt.config.file.name + '\n' + $scope.log; evt.config.file.name + '\n' + $scope.log;
$scope.pdfLoading = true; $scope.pdfLoading = true;
}).success(function (data, status, headers, config) { }).success(function (data, status, headers, config) {
$scope.log = 'file ' + data.originalname + 'uploaded as '+ data.name +'. JSON: ' + JSON.stringify(data) + '\n' + $scope.log; $scope.log = 'file ' + data.originalname + ' uploaded as '+ data.name +'. JSON: ' + JSON.stringify(data) + '\n' + $scope.log;
$scope.form.pdf = data; console.log($scope.form.pdf);
$scope.form.pdf = angular.fromJson(angular.toJson(data));
$scope.pdfLoading = false; $scope.pdfLoading = false;
console.log($scope.log); console.log($scope.log);
console.log('$scope.pdf: '+$scope.form.pdf.name); console.log('$scope.pdf: '+$scope.form.pdf.name);
if(!$scope.$$phase) { if(!$scope.$$phase){
$scope.$apply(); $scope.$apply();
} }
}).error(function(err){ }).error(function(err){
@ -85,23 +82,19 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$
// Create new Form object // Create new Form object
var form = new Forms($scope.form); 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('form created');
// console.log(response.pdf);
// Clear form fields // Clear form fields
$scope.form = {}; $scope.form = {};
// Redirect after save // Redirect after save
$scope.goToWithId('viewForm', response._id); $scope.goToWithId('viewForm', response._id);
}).error(function(err){
}, function(errorResponse) {
console.log(errorResponse.data.message); console.log(errorResponse.data.message);
$scope.error = errorResponse.data.message; $scope.error = errorResponse.data.message;
}); });
} else{ } else{
console.log('update form');
$scope.update(); $scope.update();
} }
}; };
@ -109,14 +102,24 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$
// Update existing Form // Update existing Form
$scope.update = function() { $scope.update = function() {
var form = new Forms($scope.form); var form = new Forms($scope.form);
form.$update(function(response) { console.log('update form');
console.log('form updated'); console.log($scope.form);
$scope.goToWithId('viewForm', response._id);
// $location.path('forms/' + response._id + '/admin'); $http.put('/forms/'+$scope.form._id, {form: $scope.form})
}, function(errorResponse) { .success(function(data, status, headers){
console.log(errorResponse.data.message); console.log('form updated successfully');
$scope.error = errorResponse.data.message; $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 //Populate AddField with all available form field types
@ -153,7 +156,6 @@ angular.module('forms').controller('EditFormController', ['$scope', '$state', '$
// put newField into fields array // put newField into fields array
$scope.form.form_fields.push(newField); $scope.form.form_fields.push(newField);
// console.log($scope.form.form_fields);
}; };
// deletes particular field on button click // deletes particular field on button click

View file

@ -28,26 +28,14 @@ angular.module('forms').controller('ViewSubmissionController', ['$scope', '$stat
// Remove existing submission // Remove existing submission
$scope.remove = function(submission) { $scope.remove = function(submission) {
if (submission) { if (!submission) {
submission.$remove(); submission = $scope.submission;
$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..');
});
});
} }
$http.delete('/forms/'+$stateParams.formId+'/submissions/'+submission._id).
success(function(data, status, headers){
console.log('submission deleted successfully');
alert('submission deleted..');
});
}; };

View file

@ -6,8 +6,6 @@ angular.module('users').controller('AuthenticationController', ['$scope', '$loca
$scope = $rootScope; $scope = $rootScope;
$scope.credentials = {}; $scope.credentials = {};
// $scope.authentication = Principal;
// If user is signed in then redirect back home // If user is signed in then redirect back home
if ($scope.authentication.isAuthenticated()) $state.go('home'); if ($scope.authentication.isAuthenticated()) $state.go('home');

View file

@ -2,14 +2,10 @@
angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$state', 'User', angular.module('users').controller('PasswordController', ['$scope', '$stateParams', '$state', 'User',
function($scope, $stateParams, $state, User) { function($scope, $stateParams, $state, User) {
// $scope.authentication = Principal;
//If user is signed in then redirect back home //If user is signed in then redirect back home
if ($scope.authentication.isAuthenticated()) $state.go('home'); if ($scope.authentication.isAuthenticated()) $state.go('home');
// Principal.identity().then(function(response){
// $scope.authentication.user = response;
// Submit forgotten password account id // Submit forgotten password account id
$scope.askForPasswordReset = function() { $scope.askForPasswordReset = function() {
User.askForPasswordReset($scope.credentials).then( User.askForPasswordReset($scope.credentials).then(
@ -41,21 +37,6 @@ angular.module('users').controller('PasswordController', ['$scope', '$stateParam
$scope.passwordDetails = null; $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;
// });
}; };
// });
} }
]); ]);