fixed autosaving

This commit is contained in:
David Baldwynn 2015-07-28 15:29:07 -07:00
parent c499a7edf5
commit 5abbebb117
43 changed files with 498 additions and 549 deletions

View file

@ -290,24 +290,25 @@ exports.formByID = function(req, res, next, id) {
}); });
} }
Form.findById(id).populate('admin', 'submissions').exec(function(err, form) { Form.findById(id).populate('admin').exec(function(err, form) {
if (err) { if (err) {
return next(err); return next(err);
} else if (!form || form === null) { } else if (form === undefined || form === null) {
res.status(404).send({ res.status(400).send({
message: 'Form not found' message: 'Form not found'
}); });
} }
else { else {
if(!form.username){ if(!form.admin.username){
form.admin = req.user; form.admin = req.user;
} }
// console.log(creaform.admin); console.log(form.admin);
//Remove sensitive information from User object //Remove sensitive information from User object
form.admin.password = null; form.admin.password = null;
form.admin.created = null; form.admin.created = null;
form.admin.salt = null; form.admin.salt = null;
form.provider = null;
req.form = form; req.form = form;
next(); next();

View file

@ -20,7 +20,7 @@ var smtpTransport = nodemailer.createTransport(config.mailer.options);
// NEV configuration ===================== // NEV configuration =====================
nev.configure({ nev.configure({
persistentUserModel: User, persistentUserModel: User,
expirationTime: 600, // 10 minutes expirationTime: 1800, // 30 minutes
verificationURL: config.baseUrl+'/#!/verify/${URL}', verificationURL: config.baseUrl+'/#!/verify/${URL}',
transportOptions: config.mailer.options, transportOptions: config.mailer.options,
@ -56,7 +56,7 @@ exports.signup = function(req, res) {
// Add missing user fields // Add missing user fields
user.provider = 'local'; user.provider = 'local';
user.username = user.email; user.username = user.email;
user.displayName = user.firstName + ' ' + user.lastName; // user.displayName = user.firstName + ' ' + user.lastName;
// Then save the temporary user // Then save the temporary user
nev.createTempUser(user, function(newTempUser) { nev.createTempUser(user, function(newTempUser) {

View file

@ -24,7 +24,7 @@ exports.update = function(req, res) {
// Merge existing user // Merge existing user
user = _.extend(user, req.body); user = _.extend(user, req.body);
user.updated = Date.now(); user.updated = Date.now();
user.displayName = user.firstName + ' ' + user.lastName; // user.displayName = user.firstName + ' ' + user.lastName;
user.save(function(err) { user.save(function(err) {
if (err) { if (err) {

View file

@ -14,8 +14,7 @@ var mongoose = require('mongoose'),
fs = require('fs-extra'), fs = require('fs-extra'),
async = require('async'), async = require('async'),
Field = mongoose.model('Field', FieldSchema), Field = mongoose.model('Field', FieldSchema),
FormSubmission = mongoose.model('FormSubmission', FormSubmissionSchema), FormSubmission = mongoose.model('FormSubmission', FormSubmissionSchema);
_original;
/** /**
@ -33,8 +32,7 @@ var FormSchema = new Schema({
title: { title: {
type: String, type: String,
trim: true, trim: true,
unique: true, required: 'Form Title cannot be blank',
required: 'Title cannot be blank',
}, },
language: { language: {
type: String, type: String,
@ -84,8 +82,13 @@ var FormSchema = new Schema({
type: Boolean, type: Boolean,
default: false, default: false,
}, },
saveCount: {
type: Number,
default: 0,
}
}); });
//Delete template PDF of current Form //Delete template PDF of current Form
FormSchema.pre('remove', function (next) { FormSchema.pre('remove', function (next) {
if(this.pdf){ if(this.pdf){
@ -96,20 +99,45 @@ FormSchema.pre('remove', function (next) {
}); });
} }
}); });
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;
// }
// });
// });
//Set _original //Set _original
FormSchema.pre('save', function (next) { FormSchema.pre('save', function (next) {
console.log(this.constructor.modelName); this.saveCount = this.saveCount++;
console.log('saveCount: '+this.saveCount);
// console.log(this.constructor.model);
// console.log(FormModel);
this.constructor // ≈ mongoose.model('…', FieldSchema).findById this.constructor // ≈ mongoose.model('…', FieldSchema).findById
.findOne({title: this.title}, function(err, original){ .findOne({_id: this._id}).exec(function(err, original){
if(err) next(err); if(err) {
else { console.log(err);
console.log(original); next(err);
} else {
_original = original; _original = original;
// console.log('_original');
// console.log(_original);
next(); next();
} }
});
});
}); });
//Update lastModified and created everytime we save //Update lastModified and created everytime we save
@ -137,7 +165,6 @@ function getDeletedIndexes(needle, haystack){
//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) {
if(this.pdf){ if(this.pdf){
var that = this; var that = this;
async.series([ async.series([
@ -246,20 +273,18 @@ FormSchema.pre('save', function (next) {
next(); next();
}); });
} }
}else{
next();
} }
next();
}); });
FormSchema.pre('save', function (next) { FormSchema.pre('save', function (next) {
// console.log(this.form_fields); // var _original = this._original;
// console.log('_original\n------------');
// console.log('_original\n------------\n\n');
// console.log(_original); // console.log(_original);
// console.log('field has been deleted: ');
// console.log(this.isModified('form_fields') && !!this.form_fields && !!_original); // console.log(this.isModified('form_fields') && !!this.form_fields && !!_original);
console.log(_original) if(this.isModified('form_fields') && this.form_fields.length >= 0 && _original){
if(this.isModified('form_fields') && this.form_fields && _original){
var old_form_fields = _original.form_fields, var old_form_fields = _original.form_fields,
new_ids = _.map(_.pluck(this.form_fields, '_id'), function(id){ return ''+id;}), new_ids = _.map(_.pluck(this.form_fields, '_id'), function(id){ return ''+id;}),
@ -330,7 +355,7 @@ FormSchema.pre('save', function (next) {
// console.log('modifiedSubmissions\n---------\n\n'); // console.log('modifiedSubmissions\n---------\n\n');
// console.log(modifiedSubmissions); // console.log(modifiedSubmissions);
// console.log('preserved deleted fields'); console.log('preserved deleted fields');
// console.log(submissions); // console.log(submissions);
async.forEachOfSeries(modifiedSubmissions, function (submission, key, callback) { async.forEachOfSeries(modifiedSubmissions, function (submission, key, callback) {
@ -403,5 +428,4 @@ FormSchema.methods.generateFDFTemplate = function() {
return jsonObj; return jsonObj;
}; };
mongoose.model('Form', FormSchema);
mongoose.model('Form', FormSchema);

View file

@ -53,7 +53,7 @@ var FormFieldSchema = new Schema({
type: String, type: String,
default: '', default: '',
trim: true, trim: true,
required: 'Title cannot be blank' required: 'Field title cannot be blank'
}, },
description: { description: {
type: String, type: String,

View file

@ -40,10 +40,6 @@ var UserSchema = new Schema({
default: '', default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name'] validate: [validateLocalStrategyProperty, 'Please fill in your last name']
}, },
displayName: {
type: String,
trim: true
},
email: { email: {
type: String, type: String,
trim: true, trim: true,
@ -103,6 +99,11 @@ var UserSchema = new Schema({
token: String token: String
}); });
UserSchema.virtual('displayName').get(function () {
return this.firstName + ' ' + this.lastName;
});
//Create folder for user's pdfs //Create folder for user's pdfs
UserSchema.pre('save', function (next) { UserSchema.pre('save', function (next) {
if(!this.username || this.username !== this.email){ if(!this.username || this.username !== this.email){

View file

@ -13,7 +13,7 @@ var should = require('should'),
/** /**
* Globals * Globals
*/ */
var user, myForm, mySubmission, FormFDF; var user, myForm, mySubmission;
/** /**
* Unit tests * Unit tests
@ -54,26 +54,44 @@ describe('Form Model Unit Tests:', function() {
}); });
it('should be able to show an error when try to save without title', function(done) { it('should be able to show an error when try to save without title', function(done) {
myForm.title = ''; var _form = myForm;
_form.title = '';
return myForm.save(function(err) { return _form.save(function(err) {
should.exist(err); should.exist(err);
should.equal(err.errors.title.message, 'Title cannot be blank'); should.equal(err.errors.title.message, 'Form Title cannot be blank');
done(); done();
}); });
}); });
}); });
describe('Test FormField and Submission Logic', function() { describe('Method Find', function(){
var new_form_fields_add1, new_form_fields_del, submission_fields, old_fields; beforeEach(function(done){
myForm.save(function(err) {
done();
});
});
it('should be able to findOne my form without problems', function(done) {
return Form.findOne({_id: myForm._id}, function(err,form) {
should.not.exist(err);
should.exist(form);
should.deepEqual(form.toObject(), myForm.toObject());
done();
});
});
});
before(function(done){
new_form_fields_add1 = _.clone(myForm.form_fields); describe('Test FormField and Submission Logic', function() {
var new_form_fields_add1, new_form_fields_del, submission_fields, old_fields, form;
before(function(){
new_form_fields_add1 = _.clone(myForm.toObject().form_fields);
new_form_fields_add1.push( new_form_fields_add1.push(
{'fieldType':'textfield', 'title':'Last Name', 'fieldValue': ''} {'fieldType':'textfield', 'title':'Last Name', 'fieldValue': ''}
); );
new_form_fields_del = _.clone(myForm.form_fields); new_form_fields_del = _.clone(myForm.toObject().form_fields);
new_form_fields_del.splice(0, 1); new_form_fields_del.splice(0, 1);
submission_fields = _.clone(myForm.toObject().form_fields); submission_fields = _.clone(myForm.toObject().form_fields);
@ -87,45 +105,50 @@ describe('Form Model Unit Tests:', function() {
form: myForm, form: myForm,
timeElapsed: 17.55 timeElapsed: 17.55
}); });
});
mySubmission.save(function(){ beforeEach(function(done){
done(); myForm.save(function(){
mySubmission.save(function(){
done();
});
}); });
}); });
after(function(done){ afterEach(function(done){
mySubmission.remove(function(){ mySubmission.remove(function(){
done(); done();
}); });
}); });
beforeEach(function(done){
old_fields = myForm.toObject().form_fields;
// console.log(old_fields);
done();
});
it('should preserve deleted form_fields that have submissions without any problems', function(done) { it('should preserve deleted form_fields that have submissions without any problems', function(done) {
var expected_fields = old_fields.slice(1,3).concat(old_fields.slice(0,1)); old_fields = myForm.toObject().form_fields;
// console.log(old_fields); // console.log(old_fields);
myForm.form_fields = new_form_fields_del; // var expected_fields = old_fields.slice(1,3).concat(old_fields.slice(0,1));
return myForm.save(function(err, form) {
should.not.exist(err);
var actual_fields = form.toObject().form_fields;
// console.log(actual_fields);
should.deepEqual(form.toObject().form_fields, expected_fields, 'old form_fields not equal to newly saved form_fields'); myForm.form_fields = new_form_fields_del;
myForm.save(function(err, _form) {
should.not.exist(err);
should.exist(_form);
// var actual_fields = _.map(_form.toObject().form_fields, function(o){ _.omit(o, '_id')});
// old_fields = _.map(old_fields, function(o){ _.omit(o, '_id')});
// console.log(old_fields);
should.deepEqual(JSON.stringify(_form.toObject().form_fields), JSON.stringify(old_fields), 'old form_fields not equal to newly saved form_fields');
done(); done();
}); });
}); });
// it('should delete \'preseved\' form_fields whose submissions have been removed without any problems', function(done) { // it('should delete \'preserved\' form_fields whose submissions have been removed without any problems', function(done) {
// myForm.form_fields = new_form_fields_del; // myForm.form_fields = new_form_fields_del;
// myForm.save(function(err, form) { // myForm.save(function(err, form
// should.not.exist(err); // should.not.exist(err);
// (form.form_fields).should.be.eql(old_fields, 'old form_fields not equal to newly saved form_fields'); // (form.form_fields).should.be.eql(old_fields, 'old form_fields not equal to newly saved form_fields');
@ -136,28 +159,30 @@ describe('Form Model Unit Tests:', function() {
// }); // });
// }); // });
// }); // });
}); });
describe('Method generateFDFTemplate', function() { describe('Method generateFDFTemplate', function() {
beforeEach(function(done){ var FormFDF;
FormFDF = { before(function(done){
'First Name': '', return myForm.save(function(err, form){
'nascar': '',
'hockey': '' FormFDF = {
}; 'First Name': '',
done(); 'nascar': '',
'hockey': ''
};
done();
});
}); });
it('should be able to generate a FDF template without any problems', function(done) { it('should be able to generate a FDF template without any problems', function() {
var fdfTemplate = myForm.generateFDFTemplate(); var fdfTemplate = myForm.generateFDFTemplate();
(fdfTemplate).should.be.eql(FormFDF); (fdfTemplate).should.be.eql(FormFDF);
done();
}); });
}); });
afterEach(function(done) { afterEach(function(done) {
Form.remove().exec(function() { Form.remove({}, function() {
User.remove().exec(done); User.remove().exec(done);
}); });
}); });

View file

@ -57,9 +57,8 @@
<body ng-cloak> <body ng-cloak>
<header data-ng-include="'/modules/core/views/header.client.view.html'"></header> <header data-ng-include="'/modules/core/views/header.client.view.html'"></header>
<section class="content"> <section class="content">
<!-- <section class="container"> --> <!-- <section class="container"> -->
{% block content %}{% endblock %}
{% block content %}{% endblock %}
<!-- </section> --> <!-- </section> -->
</section> </section>

View file

@ -11,7 +11,7 @@
"appPath": "public/modules", "appPath": "public/modules",
"dependencies": { "dependencies": {
"bootstrap": "~3", "bootstrap": "~3",
"angular": "~1.2", "angular": "1.3.17",
"angular-resource": "~1.2", "angular-resource": "~1.2",
"angular-animate": "~1.2", "angular-animate": "~1.2",
"angular-mocks": "~1.2", "angular-mocks": "~1.2",
@ -26,10 +26,11 @@
"angular-raven": "~0.5.11", "angular-raven": "~0.5.11",
"angular-ui-date": "~0.0.8", "angular-ui-date": "~0.0.8",
"lodash": "~3.10.0", "lodash": "~3.10.0",
"angular-ui-sortable": "~0.13.4" "angular-ui-sortable": "~0.13.4",
"angular-busy": "~4.1.3"
}, },
"resolutions": { "resolutions": {
"angular": "^1.2.21", "angular": "^1.3.17",
"angular-resource": "~1.2", "angular-resource": "~1.2",
"ng-file-upload": "~5.0.9" "ng-file-upload": "~5.0.9"
} }

View file

@ -1,6 +1,7 @@
'use strict'; 'use strict';
module.exports = { module.exports = {
baseUrl: 'http://localhost:3000',
db: { db: {
uri: 'mongodb://localhost/mean-dev', uri: 'mongodb://localhost/mean-dev',
options: { options: {

View file

@ -1,6 +1,7 @@
'use strict'; 'use strict';
module.exports = { module.exports = {
baseUrl: 'http://forms.polydaic.com',
db: { db: {
uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean', uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean',
options: { options: {

View file

@ -1,6 +1,7 @@
'use strict'; 'use strict';
module.exports = { module.exports = {
baseUrl: 'https://forms.polydaic.com',
port: 8443, port: 8443,
db: { db: {
uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/mean', uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/mean',

1
config/env/test.js vendored
View file

@ -1,6 +1,7 @@
'use strict'; 'use strict';
module.exports = { module.exports = {
baseUrl: 'http://localhost:3000',
db: { db: {
uri: 'mongodb://localhost/mean-test', uri: 'mongodb://localhost/mean-test',
options: { options: {

View file

@ -34,13 +34,19 @@ angular.module(ApplicationConfiguration.applicationModuleName).run(['$rootScope'
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) { $rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState) {
$state.previous = fromState; $state.previous = fromState;
//Redirect home to listForms if user is authenticated //Redirect to listForms if user is authenticated
if(toState.name === 'home'){ if(toState.name === 'home' || toState.name === 'signin' || toState.name === 'resendVerifyEmail' || toState.name === 'verify' || toState.name === 'signup' || toState.name === 'signup-success'){
if(Auth.isAuthenticated()){ if(Auth.isAuthenticated()){
event.preventDefault(); // stop current execution event.preventDefault(); // stop current execution
$state.go('listForms'); // go to login $state.go('listForms'); // go to listForms page
} }
} }
//Redirect to 'home' route if user is not authenticated
else if(toState.name !== 'access_denied' && !Auth.isAuthenticated() ){
event.preventDefault(); // stop current execution
$state.go('home'); // go to listForms page
}
}); });
} }
@ -56,17 +62,14 @@ angular.module(ApplicationConfiguration.applicationModuleName).run(['$rootScope'
Auth.ensureHasCurrentUser(User); Auth.ensureHasCurrentUser(User);
user = Auth.currentUser; user = Auth.currentUser;
if(user){ if(user){
authenticator = new Authorizer(user); authenticator = new Authorizer(user);
// console.log('Permissions'); if( (permissions !== null) && !authenticator.canAccess(permissions) ){
// console.log(permissions); event.preventDefault();
console.log('access denied')
if( (permissions !== null) && !authenticator.canAccess(permissions) ){ $state.go('access_denied');
event.preventDefault(); }
console.log('access denied')
$state.go('access_denied');
}
} }
}); });
}]); }]);

View file

@ -4,7 +4,7 @@
var ApplicationConfiguration = (function() { var ApplicationConfiguration = (function() {
// Init module configuration options // Init module configuration options
var applicationModuleName = 'medform'; var applicationModuleName = 'medform';
var applicationModuleVendorDependencies = ['ngResource', 'ngAnimate', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven']; var applicationModuleVendorDependencies = ['ngResource', 'ngAnimate', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven', 'cgBusy'];
// Add a new vertical module // Add a new vertical module
var registerModule = function(moduleName, dependencies) { var registerModule = function(moduleName, dependencies) {

View file

@ -4,7 +4,7 @@
var ApplicationConfiguration = (function() { var ApplicationConfiguration = (function() {
// Init module configuration options // Init module configuration options
var applicationModuleName = 'medform'; var applicationModuleName = 'medform';
var applicationModuleVendorDependencies = ['ngResource', 'ngAnimate', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven']; var applicationModuleVendorDependencies = ['ngResource', 'ngAnimate', 'ui.router', 'ui.bootstrap', 'ui.utils', 'ngRaven', 'cgBusy'];
// Add a new vertical module // Add a new vertical module
var registerModule = function(moduleName, dependencies) { var registerModule = function(moduleName, dependencies) {
@ -142,11 +142,16 @@ angular.module('core').config(['$stateProvider', '$urlRouterProvider',
angular.module('core').controller('HeaderController', ['$rootScope','$scope','Menus', '$state', 'Auth', 'User', angular.module('core').controller('HeaderController', ['$rootScope','$scope','Menus', '$state', 'Auth', 'User',
function ($rootScope, $scope, Menus, $state, Auth, User) { function ($rootScope, $scope, Menus, $state, Auth, User) {
$scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User); $scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User);
$scope.authentication = $rootScope.authentication = Auth; $scope.authentication = $rootScope.authentication = Auth;
if(!$scope.user.username){
$scope.user = $rootScope.user = User.getCurrent();
$scope.authentication.currentUser = $rootScope.authentication.currentUser = $scope.user;
}
$rootScope.languages = $scope.languages = ['english', 'french', 'spanish']; $rootScope.languages = $scope.languages = ['english', 'french', 'spanish'];
$scope.isCollapsed = false; $scope.isCollapsed = false;
$scope.hideNav = false; $rootScope.hideNav = false;
$scope.menu = Menus.getMenu('topbar'); $scope.menu = Menus.getMenu('topbar');
$scope.signout = function() { $scope.signout = function() {
@ -169,48 +174,15 @@ angular.module('core').controller('HeaderController', ['$rootScope','$scope','Me
// Collapsing the menu after navigation // Collapsing the menu after navigation
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
$scope.isCollapsed = false; $scope.isCollapsed = false;
$scope.hideNav = false; $rootScope.hideNav = false;
if ( angular.isDefined( toState.data ) ) { if ( angular.isDefined( toState.data ) ) {
if ( angular.isDefined( toState.data.hideNav ) ) { if ( angular.isDefined( toState.data.hideNav ) ) {
$scope.hideNav = toState.data.hideNav; $rootScope.hideNav = toState.data.hideNav;
} }
} }
}); });
// Principal.identity().then(function(user){
// $rootScope.user = user;
// console.log('topbar')
// console.log($scope.user);
// },
// function(error){
// console.log(error);
// }).then(function(){
// $scope.signout = function() {
// $http.get('/auth/signout').success(function(response) {
// $state.go('home');
// }).error(function(error) {
// $scope.error = (error.message || error);
// });
// Principal.signout().then(
// function(result){
// $state.go('home');
// },
// function(error){
// $scope.error = (error.message || error);
// }
// );
// if( angular.isDefined(response_obj.error) ){
// $scope.error = response_obj.error;
// } else{
// $state.go('home');
// }
// };
// });
} }
]); ]);
'use strict'; 'use strict';
@ -229,32 +201,6 @@ angular.module('core').controller('HomeController', ['$rootScope', '$scope', 'Us
} }
]); ]);
// 'use strict';
// /**
// * @ngdoc function
// * @name medform.controller:IndexCtrl
// * @description
// * # IndexCtrl
// * Controller of core
// */
// angular.module('medform').controller('IndexCtrl', function ($scope, $rootScope, $location, User, Auth, $state) {
// $rootScope.user = Auth.ensureHasCurrentUser(User);
// // $rootScope.user = Auth.getUserState(User).user;
// $rootScope.authentication = Auth;
// $scope.signout = function() {
// User.logout(function() {
// Auth.logout();
// $rootScope.user = null;
// $state.go('home');
// // $scope.$apply();
// });
// };
// });
'use strict'; 'use strict';
//Menu service used for managing menus //Menu service used for managing menus
@ -499,49 +445,33 @@ angular.module('forms').config(['$stateProvider',
'use strict'; 'use strict';
// Forms controller // Forms controller
angular.module('forms').controller('SubmitFormController', ['$scope', '$stateParams', '$state', 'Forms', 'CurrentForm', angular.module('forms').controller('SubmitFormController', ['$scope', '$rootScope', '$stateParams', '$state', 'Forms', 'CurrentForm',
function($scope, $stateParams, $state, Forms, CurrentForm) { function($scope, $rootScope, $stateParams, $state, Forms, CurrentForm) {
$scope.form = Forms.get({ Forms.get({
formId: $stateParams.formId formId: $stateParams.formId
}); }).$promise.then(
CurrentForm.setForm($scope.form); //success
} function(form){
]); $scope.form = form;
'use strict';
// submissions controller //Show navbar if form is not public AND user is loggedin
angular.module('forms').controller('ViewSubmissionController', ['$scope', '$stateParams', '$state', 'Submissions','$http', if(!$scope.form.isLive && $rootScope.authentication.isAuthenticated()){
function($scope, $stateParams, $state, Submissions, $http) { $rootScope.hideNav = false;
$scope.submissionId = undefined; }else if(!$scope.form.isLive){
$state.go('access_denied');
// Return all form's submissions }else {
$scope.findAll = function() { CurrentForm.setForm($scope.form);
$scope.submissions = Submissions.query({ }
formId: $stateParams.formId console.log('$rootScope.hideNav: '+$rootScope.hideNav);
}); console.log('$scope.form.isLive: '+$scope.form.isLive);
}; },
//error
// Find a specific submission function( error ){
$scope.findOne = function() { $scope.error = error.message;
$scope.submission = Submissions.get({ console.log('ERROR: '+error.message);
submissionId: $scope.submissionId, $state.go('access_denied');
formId: $stateParams.formId });
});
};
// Remove existing submission
$scope.remove = function(submission) {
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..');
});
};
} }
]); ]);
'use strict'; 'use strict';
@ -554,7 +484,7 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
$scope.myform = CurrentForm.getForm(); $scope.myform = CurrentForm.getForm();
$scope.saveInProgress = false; $scope.saveInProgress = false;
$scope.viewSubmissions = false; $scope.viewSubmissions = false;
$scope.showCreateModal = false; $rootScope.showCreateModal = false;
$scope.table = { $scope.table = {
masterChecker: true, masterChecker: true,
rows: [] rows: []
@ -577,21 +507,19 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
$state.go(route, {'formId': id}, {reload: true}); $state.go(route, {'formId': id}, {reload: true});
}; };
$scope.setForm = function (form) { $scope.setForm = function (form) {
$scope.myform = form; $scope.myform = form;
}; };
//Modal functions //Modal functions
$scope.openCreateModal = function(){ $scope.openCreateModal = function(){
if(!$scope.showCreateModal){ if(!$rootScope.showCreateModal){
$scope.showCreateModal = true; $rootScope.showCreateModal = true;
} }
}; };
$scope.closeCreateModal = function(){ $scope.closeCreateModal = function(){
if($scope.showCreateModal){ if($rootScope.showCreateModal){
$scope.showCreateModal = false; $rootScope.showCreateModal = false;
} }
}; };
@ -599,14 +527,14 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
* Table Functions * Table Functions
*/ */
$scope.isAtLeastOneChecked = function(){ $scope.isAtLeastOneChecked = function(){
console.log('isAtLeastOneChecked'); // console.log('isAtLeastOneChecked');
for(var i=0; i<$scope.table.rows.length; i++){ for(var i=0; i<$scope.table.rows.length; i++){
if($scope.table.rows[i].selected) return true; if($scope.table.rows[i].selected) return true;
} }
return false; return false;
}; };
$scope.toggleAllCheckers = function(){ $scope.toggleAllCheckers = function(){
console.log('toggleAllCheckers'); // console.log('toggleAllCheckers');
for(var i=0; i<$scope.table.rows.length; i++){ for(var i=0; i<$scope.table.rows.length; i++){
$scope.table.rows[i].selected = $scope.table.masterChecker; $scope.table.rows[i].selected = $scope.table.masterChecker;
} }
@ -740,7 +668,7 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
form.title = $scope.myform.name.$modelValue; form.title = $scope.myform.name.$modelValue;
form.language = $scope.myform.language.$modelValue; form.language = $scope.myform.language.$modelValue;
console.log(form); console.log(form);
$scope.showCreateModal = true; $rootScope.showCreateModal = true;
console.log($scope.myform); console.log($scope.myform);
if($scope.myform.$valid && $scope.myform.$dirty){ if($scope.myform.$valid && $scope.myform.$dirty){
@ -765,10 +693,10 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
if(!$rootScope.saveInProgress){ if(!$rootScope.saveInProgress){
$rootScope.saveInProgress = true; $rootScope.saveInProgress = true;
// console.log('begin updating form'); console.log('begin updating form');
var err = null; var err = null;
$http.put('/forms/'+$scope.myform._id, {form: $scope.myform}) $scope.updatePromise = $http.put('/forms/'+$scope.myform._id, {form: $scope.myform})
.then(function(response){ .then(function(response){
$rootScope.myform = $scope.myform = response.data; $rootScope.myform = $scope.myform = response.data;
console.log(response.data); console.log(response.data);
@ -780,7 +708,7 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
console.log(response.data); console.log(response.data);
err = response.data; err = response.data;
}).finally(function() { }).finally(function() {
// console.log('finished updating'); console.log('finished updating');
$rootScope.saveInProgress = false; $rootScope.saveInProgress = false;
cb(err); cb(err);
}); });
@ -1502,7 +1430,6 @@ angular.module('forms').factory('Forms', ['$resource',
form.visible_form_fields = _.filter(form.form_fields, function(field){ form.visible_form_fields = _.filter(form.form_fields, function(field){
return field.deletePreserved === false; return field.deletePreserved === false;
}); //<-- replace each item with an instance of the resource object }); //<-- replace each item with an instance of the resource object
console.log(form);
return form; return form;
} }
}, },
@ -1567,7 +1494,8 @@ angular.module('users').config(['$httpProvider',
$httpProvider.interceptors.push(function($q, $location) { $httpProvider.interceptors.push(function($q, $location) {
return { return {
responseError: function(response) { responseError: function(response) {
if( $location.path() !== '/verify' && $location.path() !== '/users/me' && $location.path() !== '/' && $location.path() !== '/signup' && response.config){ console.log($location.path());
if( response.config.url !== '/users/me' && $location.path() !== '/users/me' && response.config){
console.log('intercepted rejection of ', response.config.url, response.status); console.log('intercepted rejection of ', response.config.url, response.status);
if (response.status === 401) { if (response.status === 401) {
@ -1699,7 +1627,7 @@ angular.module('users').controller('AuthenticationController', ['$scope', '$loca
Auth.login(response); Auth.login(response);
$scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User); $scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User);
if($state.previous.name !== 'home' && $state.previous.name !== ''){ if($state.previous.name !== 'home' && $state.previous.name !== 'verify' && $state.previous.name !== ''){
$state.go($state.previous.name); $state.go($state.previous.name);
}else{ }else{
$state.go('home'); $state.go('home');
@ -1740,40 +1668,40 @@ angular.module('users').controller('PasswordController', ['$scope', '$stateParam
function($scope, $stateParams, $state, User) { function($scope, $stateParams, $state, User) {
//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');
// 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(
function(response){ function(response){
$scope.success = response.message; $scope.success = response.message;
$scope.credentials = null; $scope.credentials = null;
}, },
function(error){ function(error){
$scope.error = error; $scope.error = error;
$scope.credentials = null; $scope.credentials = null;
} }
); );
}; };
// Change user password // Change user password
$scope.resetUserPassword = function() { $scope.resetUserPassword = function() {
$scope.success = $scope.error = null; $scope.success = $scope.error = null;
User.resetPassword($scope.passwordDetails, $stateParams.token).then( User.resetPassword($scope.passwordDetails, $stateParams.token).then(
function(response){ function(response){
// If successful show success message and clear form // If successful show success message and clear form
$scope.success = response.message; $scope.success = response.message;
$scope.passwordDetails = null; $scope.passwordDetails = null;
// And redirect to the index page // And redirect to the index page
$state.go('reset-success'); $state.go('reset-success');
}, },
function(error){ function(error){
$scope.error = error.message || error; $scope.error = error.message || error;
$scope.passwordDetails = null; $scope.passwordDetails = null;
} }
); );
}; };
} }
]); ]);
'use strict'; 'use strict';
@ -1853,7 +1781,7 @@ angular.module('users').controller('SettingsController', ['$scope', '$rootScope'
angular.module('users').controller('VerifyController', ['$scope', '$state', '$rootScope', 'User', 'Auth', '$stateParams', angular.module('users').controller('VerifyController', ['$scope', '$state', '$rootScope', 'User', 'Auth', '$stateParams',
function($scope, $state, $rootScope, User, Auth, $stateParams) { function($scope, $state, $rootScope, User, Auth, $stateParams) {
if($rootScope.authetication.isAuthenticated){ if($rootScope.authentication.isAuthenticated()){
$state.go('home'); $state.go('home');
} }
@ -1865,10 +1793,12 @@ angular.module('users').controller('VerifyController', ['$scope', '$state', '$ro
function(response){ function(response){
$scope.success = response.message; $scope.success = response.message;
$scope.credentials = null; $scope.credentials = null;
$scope.isResetSent = true;
}, },
function(error){ function(error){
$scope.error = error; $scope.error = error;
$scope.credentials = null; $scope.credentials = null;
$scope.isReset = false;
} }
); );
}; };
@ -1911,12 +1841,12 @@ angular.module('users').factory('Auth', function($window) {
// Auth <- $http <- $resource <- LoopBackResource <- User <- Auth // Auth <- $http <- $resource <- LoopBackResource <- User <- Auth
ensureHasCurrentUser: function(User) { ensureHasCurrentUser: function(User) {
if (service.currentUser && service.currentUser.displayName) { if (service.currentUser && service.currentUser.displayName) {
// console.log('Using local current user.'); console.log('Using local current user.');
// console.log(service.currentUser); // console.log(service.currentUser);
return service.currentUser; return service.currentUser;
} }
else if ($window.user){ else if ($window.user){
// console.log('Using cached current user.'); console.log('Using cached current user.');
// console.log($window.user); // console.log($window.user);
service.currentUser = $window.user; service.currentUser = $window.user;
return service.currentUser; return service.currentUser;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -4,20 +4,25 @@ angular.module('core').controller('HeaderController', ['$rootScope','$scope','Me
function ($rootScope, $scope, Menus, $state, Auth, User) { function ($rootScope, $scope, Menus, $state, Auth, User) {
$scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User); $scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User);
$scope.authentication = $rootScope.authentication = Auth; $scope.authentication = $rootScope.authentication = Auth;
// if(!$scope.user || !$scope.user.username){
// $scope.user = $rootScope.user = User.getCurrent();
// $scope.authentication.currentUser = $rootScope.authentication.currentUser = $scope.user;
// }
$rootScope.languages = $scope.languages = ['english', 'french', 'spanish']; $rootScope.languages = $scope.languages = ['english', 'french', 'spanish'];
$scope.isCollapsed = false; $scope.isCollapsed = false;
$scope.hideNav = false; $rootScope.hideNav = false;
$scope.menu = Menus.getMenu('topbar'); $scope.menu = Menus.getMenu('topbar');
$scope.signout = function() { $scope.signout = function() {
var promise = User.logout(); var promise = User.logout();
promise.then(function() { promise.then(function() {
Auth.logout(); Auth.logout();
// Auth.ensureHasCurrentUser(null); Auth.ensureHasCurrentUser(User);
$rootScope.user = null; $scope.user = $rootScope.user = null;
$state.go('home'); $state.go('home');
}, },
function(reason) { function(reason) {
console.log('Logout Failed: ' + reason); console.log('Logout Failed: ' + reason);
}); });
@ -30,47 +35,14 @@ angular.module('core').controller('HeaderController', ['$rootScope','$scope','Me
// Collapsing the menu after navigation // Collapsing the menu after navigation
$scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) { $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
$scope.isCollapsed = false; $scope.isCollapsed = false;
$scope.hideNav = false; $rootScope.hideNav = false;
if ( angular.isDefined( toState.data ) ) { if ( angular.isDefined( toState.data ) ) {
if ( angular.isDefined( toState.data.hideNav ) ) { if ( angular.isDefined( toState.data.hideNav ) ) {
$scope.hideNav = toState.data.hideNav; $rootScope.hideNav = toState.data.hideNav;
} }
} }
}); });
// Principal.identity().then(function(user){
// $rootScope.user = user;
// console.log('topbar')
// console.log($scope.user);
// },
// function(error){
// console.log(error);
// }).then(function(){
// $scope.signout = function() {
// $http.get('/auth/signout').success(function(response) {
// $state.go('home');
// }).error(function(error) {
// $scope.error = (error.message || error);
// });
// Principal.signout().then(
// function(result){
// $state.go('home');
// },
// function(error){
// $scope.error = (error.message || error);
// }
// );
// if( angular.isDefined(response_obj.error) ){
// $scope.error = response_obj.error;
// } else{
// $state.go('home');
// }
// };
// });
} }
]); ]);

View file

@ -4,13 +4,5 @@
angular.module('core').controller('HomeController', ['$rootScope', '$scope', 'User', 'Auth', '$state', angular.module('core').controller('HomeController', ['$rootScope', '$scope', 'User', 'Auth', '$state',
function($rootScope, $scope, User, Auth, $state) { function($rootScope, $scope, User, Auth, $state) {
$scope = $rootScope; $scope = $rootScope;
$scope.user = Auth.ensureHasCurrentUser(User);
$scope.authentication = Auth;
// if($scope.authentication.isAuthenticated()){
// $state.go('listForms');
// }
} }
]); ]);

View file

@ -1,25 +0,0 @@
// 'use strict';
// /**
// * @ngdoc function
// * @name medform.controller:IndexCtrl
// * @description
// * # IndexCtrl
// * Controller of core
// */
// angular.module('medform').controller('IndexCtrl', function ($scope, $rootScope, $location, User, Auth, $state) {
// $rootScope.user = Auth.ensureHasCurrentUser(User);
// // $rootScope.user = Auth.getUserState(User).user;
// $rootScope.authentication = Auth;
// $scope.signout = function() {
// User.logout(function() {
// Auth.logout();
// $rootScope.user = null;
// $state.go('home');
// // $scope.$apply();
// });
// };
// });

View file

@ -1,63 +1,63 @@
<section class="navbar navbar-fixed-top navbar-inverse"data-ng-controller="HeaderController" ng-hide="hideNav" <section class="navbar navbar-fixed-top navbar-inverse" data-ng-controller="HeaderController" ng-hide="hideNav">
<div class="container" > <div class="container" >
<div class="navbar-header"> <div class="navbar-header">
<button class="navbar-toggle" type="button" data-ng-click="toggleCollapsibleMenu()"> <button class="navbar-toggle" type="button" data-ng-click="toggleCollapsibleMenu()">
<span class="sr-only">Toggle navigation</span> <span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span> <span class="icon-bar"></span>
<span class="icon-bar"></span> <span class="icon-bar"></span>
<span class="icon-bar"></span> <span class="icon-bar"></span>
</button> </button>
<a href="/#!/" class="navbar-brand"> <a href="/#!/" class="navbar-brand">
<!-- <i class="fa fa-5 fa-heartbeat"></i> --> <!-- <i class="fa fa-5 fa-heartbeat"></i> -->
Med<span>Forms</span> Med<span>Forms</span>
</a> </a>
</div>
<nav class="collapse navbar-collapse" collapse="!isCollapsed" role="navigation">
<ul class="nav navbar-nav" data-ng-if="authentication.isAuthenticated()">
<li data-ng-repeat="item in menu.items | orderBy: 'position'" data-ng-if="item.shouldRender(authentication.isAuthenticated());" ng-switch="item.menuItemType" ui-route="{{item.uiRoute}}" class="{{item.menuItemClass}}" ng-class="{active: ($uiRoute)}" dropdown="item.menuItemType === 'dropdown'">
<a ng-switch-when="dropdown" class="dropdown-toggle" dropdown-toggle>
<span data-ng-bind="item.title"></span>
<b class="caret"></b>
</a>
<ul ng-switch-when="dropdown" class="dropdown-menu">
<li data-ng-repeat="subitem in item.items | orderBy: 'position'" data-ng-if="subitem.shouldRender(authentication.isAuthenticated());" ui-route="{{subitem.uiRoute}}" ng-class="{active: $uiRoute}">
<a href="/#!/{{subitem.link}}" data-ng-bind="subitem.title"></a>
</li>
</ul>
<a ng-switch-default href="/#!/{{item.link}}" data-ng-bind="item.title"></a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right" data-ng-hide="authentication.isAuthenticated()">
<li ui-route="/signup" ng-class="{active: $uiRoute}">
<a href="/#!/signup">Sign Up</a>
</li>
<li class="divider-vertical"></li>
<li ui-route="/signin" ng-class="{active: $uiRoute}">
<a href="/#!/signin">Sign In</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right" data-ng-show="authentication.isAuthenticated()">
<li class="dropdown" dropdown>
<a href="#" class="dropdown-toggle" data-toggle="dropdown" dropdown-toggle>
<span data-ng-bind="authentication.currentUser.displayName"></span> <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="/#!/settings/profile">Edit Profile</a>
</li>
<li>
<a href="/#!/settings/password">Change Password</a>
</li>
<li data-ng-show="authentication.isAuthenticated().provider === 'local'">
<a href="/#!/settings/password">Change Password</a>
</li>
<li class="divider"></li>
<li>
<a ng-click="signout()">Signout</a>
</li>
</ul>
</li>
</ul>
</nav>
</div> </div>
<nav class="collapse navbar-collapse" collapse="!isCollapsed" role="navigation">
<ul class="nav navbar-nav" data-ng-if="authentication.isAuthenticated();">
<li data-ng-repeat="item in menu.items | orderBy: 'position'" data-ng-if="item.shouldRender(authentication.isAuthenticated());" ng-switch="item.menuItemType" ui-route="{{item.uiRoute}}" class="{{item.menuItemClass}}" ng-class="{active: ($uiRoute)}" dropdown="item.menuItemType === 'dropdown'">
<a ng-switch-when="dropdown" class="dropdown-toggle" dropdown-toggle>
<span data-ng-bind="item.title"></span>
<b class="caret"></b>
</a>
<ul ng-switch-when="dropdown" class="dropdown-menu">
<li data-ng-repeat="subitem in item.items | orderBy: 'position'" data-ng-if="subitem.shouldRender(authentication.isAuthenticated());" ui-route="{{subitem.uiRoute}}" ng-class="{active: $uiRoute}">
<a href="/#!/{{subitem.link}}" data-ng-bind="subitem.title"></a>
</li>
</ul>
<a ng-switch-default href="/#!/{{item.link}}" data-ng-bind="item.title"></a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right" data-ng-hide="authentication.isAuthenticated()">
<li ui-route="/signup" ng-class="{active: $uiRoute}">
<a href="/#!/signup">Sign Up</a>
</li>
<li class="divider-vertical"></li>
<li ui-route="/signin" ng-class="{active: $uiRoute}">
<a href="/#!/signin">Sign In</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right" data-ng-show="authentication.isAuthenticated()">
<li class="dropdown" dropdown>
<a href="#" class="dropdown-toggle" data-toggle="dropdown" dropdown-toggle>
<span data-ng-bind="user.displayName"></span> <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li>
<a href="/#!/settings/profile">Edit Profile</a>
</li>
<li>
<a href="/#!/settings/password">Change Password</a>
</li>
<li data-ng-show="authentication.isAuthenticated().provider === 'local'">
<a href="/#!/settings/password">Change Password</a>
</li>
<li class="divider"></li>
<li>
<a ng-click="signout()">Signout</a>
</li>
</ul>
</li>
</ul>
</nav>
</div>
</section> </section>

View file

@ -9,6 +9,9 @@ angular.module('forms').config(['$stateProvider',
state('listForms', { state('listForms', {
url: '/forms', url: '/forms',
templateUrl: 'modules/forms/views/list-forms.client.view.html', templateUrl: 'modules/forms/views/list-forms.client.view.html',
data: {
permissions: [ 'editForm' ]
}
}). }).
state('viewForm', { state('viewForm', {
url: '/forms/:formId/admin', url: '/forms/:formId/admin',

View file

@ -1,12 +1,32 @@
'use strict'; 'use strict';
// Forms controller // Forms controller
angular.module('forms').controller('SubmitFormController', ['$scope', '$stateParams', '$state', 'Forms', 'CurrentForm', angular.module('forms').controller('SubmitFormController', ['$scope', '$rootScope', '$stateParams', '$state', 'Forms', 'CurrentForm',
function($scope, $stateParams, $state, Forms, CurrentForm) { function($scope, $rootScope, $stateParams, $state, Forms, CurrentForm) {
$scope.form = Forms.get({ Forms.get({
formId: $stateParams.formId formId: $stateParams.formId
}); }).$promise.then(
CurrentForm.setForm($scope.form); //success
function(form){
$scope.form = form;
//Show navbar if form is not public AND user is loggedin
if(!$scope.form.isLive && $rootScope.authentication.isAuthenticated()){
$rootScope.hideNav = false;
}else if(!$scope.form.isLive){
$state.go('access_denied');
}else {
CurrentForm.setForm($scope.form);
}
console.log('$rootScope.hideNav: '+$rootScope.hideNav);
console.log('$scope.form.isLive: '+$scope.form.isLive);
},
//error
function( error ){
$scope.error = error.message;
console.log('ERROR: '+error.message);
$state.go('access_denied');
});
} }
]); ]);

View file

@ -1,36 +0,0 @@
'use strict';
// submissions controller
angular.module('forms').controller('ViewSubmissionController', ['$scope', '$stateParams', '$state', 'Submissions','$http',
function($scope, $stateParams, $state, Submissions, $http) {
$scope.submissionId = undefined;
// Return all form's submissions
$scope.findAll = function() {
$scope.submissions = Submissions.query({
formId: $stateParams.formId
});
};
// Find a specific submission
$scope.findOne = function() {
$scope.submission = Submissions.get({
submissionId: $scope.submissionId,
formId: $stateParams.formId
});
};
// Remove existing submission
$scope.remove = function(submission) {
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..');
});
};
}
]);

View file

@ -6,17 +6,21 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
$scope = $rootScope; $scope = $rootScope;
$scope.myform = CurrentForm.getForm(); $scope.myform = CurrentForm.getForm();
$scope.saveInProgress = false; $rootScope.saveInProgress = false;
$scope.viewSubmissions = false; $scope.viewSubmissions = false;
$scope.showCreateModal = false; $rootScope.showCreateModal = false;
$scope.table = { $scope.table = {
masterChecker: true, masterChecker: false,
rows: [] rows: []
}; };
// Return all user's Forms // Return all user's Forms
$scope.findAll = function() { $scope.findAll = function() {
$scope.myforms = Forms.query(); if(!$scope.myforms){
Forms.query(function(_forms){
$scope.myforms = _forms;
});
}
}; };
// Find a specific Form // Find a specific Form
@ -31,21 +35,19 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
$state.go(route, {'formId': id}, {reload: true}); $state.go(route, {'formId': id}, {reload: true});
}; };
$scope.setForm = function (form) { $scope.setForm = function (form) {
$scope.myform = form; $scope.myform = form;
}; };
//Modal functions //Modal functions
$scope.openCreateModal = function(){ $scope.openCreateModal = function(){
if(!$scope.showCreateModal){ if(!$rootScope.showCreateModal){
$scope.showCreateModal = true; $rootScope.showCreateModal = true;
} }
}; };
$scope.closeCreateModal = function(){ $scope.closeCreateModal = function(){
if($scope.showCreateModal){ if($rootScope.showCreateModal){
$scope.showCreateModal = false; $rootScope.showCreateModal = false;
} }
}; };
@ -53,14 +55,14 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
* Table Functions * Table Functions
*/ */
$scope.isAtLeastOneChecked = function(){ $scope.isAtLeastOneChecked = function(){
console.log('isAtLeastOneChecked'); // console.log('isAtLeastOneChecked');
for(var i=0; i<$scope.table.rows.length; i++){ for(var i=0; i<$scope.table.rows.length; i++){
if($scope.table.rows[i].selected) return true; if($scope.table.rows[i].selected) return true;
} }
return false; return false;
}; };
$scope.toggleAllCheckers = function(){ $scope.toggleAllCheckers = function(){
console.log('toggleAllCheckers'); // console.log('toggleAllCheckers');
for(var i=0; i<$scope.table.rows.length; i++){ for(var i=0; i<$scope.table.rows.length; i++){
$scope.table.rows[i].selected = $scope.table.masterChecker; $scope.table.rows[i].selected = $scope.table.masterChecker;
} }
@ -194,7 +196,7 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
form.title = $scope.myform.name.$modelValue; form.title = $scope.myform.name.$modelValue;
form.language = $scope.myform.language.$modelValue; form.language = $scope.myform.language.$modelValue;
console.log(form); console.log(form);
$scope.showCreateModal = true; $rootScope.showCreateModal = true;
console.log($scope.myform); console.log($scope.myform);
if($scope.myform.$valid && $scope.myform.$dirty){ if($scope.myform.$valid && $scope.myform.$dirty){
@ -216,13 +218,13 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
// Update existing Form // Update existing Form
$scope.update = $rootScope.update = function(cb) { $scope.update = $rootScope.update = function(cb) {
if(!$rootScope.saveInProgress){ if(!$rootScope.saveInProgress && $rootScope.finishedRender){
$rootScope.saveInProgress = true; $rootScope.saveInProgress = true;
// console.log('begin updating form'); console.log('begin updating form');
var err = null; var err = null;
$http.put('/forms/'+$scope.myform._id, {form: $scope.myform}) $scope.updatePromise = $http.put('/forms/'+$scope.myform._id, {form: $scope.myform})
.then(function(response){ .then(function(response){
$rootScope.myform = $scope.myform = response.data; $rootScope.myform = $scope.myform = response.data;
console.log(response.data); console.log(response.data);
@ -234,7 +236,7 @@ angular.module('forms').controller('ViewFormController', ['$rootScope', '$scope'
console.log(response.data); console.log(response.data);
err = response.data; err = response.data;
}).finally(function() { }).finally(function() {
// console.log('finished updating'); console.log('finished updating');
$rootScope.saveInProgress = false; $rootScope.saveInProgress = false;
cb(err); cb(err);
}); });

View file

@ -1,6 +1,10 @@
.btn { .btn {
border: 1px solid #c6c6c6!important; border: 1px solid #c6c6c6!important;
} }
.btn[type='submit'] {
font-size: 1.5em;
padding: 0.35em 1.2em 0.35em 1.2em;
}
/* Styles for form submission view (/forms/:formID) */ /* Styles for form submission view (/forms/:formID) */
form .row.field { form .row.field {
@ -201,16 +205,16 @@ section > section.public-form {
font-size: 0.95em; font-size: 0.95em;
} }
/*Modal overlay (for lightbox effect)*/ /*Modal overlay (for lightbox effect)*/
.overlay { .overlay {
position: absolute; position: absolute;
top: 0; top: 0;
left: 0; left: 0;
height: 193%; height: 193%;
width: inherit; width: 100%;
background-color: rgba(0,0,0,0.5); background-color: rgba(0,0,0,0.5);
z-index: 10; z-index: 10;
} }
.form-item.row:hover, .form-item.row.create-new:hover { .form-item.row:hover, .form-item.row.create-new:hover {

View file

@ -9,6 +9,8 @@ angular.module('forms').directive('autoSaveForm', ['$rootScope', '$timeout', fun
// }, // },
link: function($scope, $element, $attrs, $ctrls) { link: function($scope, $element, $attrs, $ctrls) {
$rootScope.finishedRender = false;
if($rootScope.watchCount === undefined){ if($rootScope.watchCount === undefined){
$rootScope.watchCount = 0; $rootScope.watchCount = 0;
} }
@ -28,15 +30,15 @@ angular.module('forms').directive('autoSaveForm', ['$rootScope', '$timeout', fun
var $formCtrl = $ctrls[0]; var $formCtrl = $ctrls[0];
var savePromise = null; var savePromise = null;
$scope.finishedRender = false; // $scope.finishedRender = false;
var expression = $attrs.autoSaveForm || 'true'; var expression = $attrs.autoSaveForm || 'true';
$scope.$on('ngRepeatStarted', function(ngRepeatFinishedEvent) { $scope.$on('ngRepeatStarted', function(ngRepeatFinishedEvent) {
// $scope.finishedRender = false; $rootScope.finishedRender = false;
$rootScope.watchCount = 0; $rootScope.watchCount = 0;
}); });
$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) { $scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
$scope.finishedRender = true; $rootScope.finishedRender = true;
}); });
$scope.$watch('myform.form_fields', function(newValue, oldValue) { $scope.$watch('myform.form_fields', function(newValue, oldValue) {
@ -48,13 +50,13 @@ angular.module('forms').directive('autoSaveForm', ['$rootScope', '$timeout', fun
// console.log('\n\n----------\n$dirty: '+( $formCtrl.$dirty ) ); // console.log('\n\n----------\n$dirty: '+( $formCtrl.$dirty ) );
// console.log('form_fields changed: '+difference(oldValue,newValue).length ); // console.log('form_fields changed: '+difference(oldValue,newValue).length );
// console.log('$valid: '+$formCtrl.$valid); // console.log('$valid: '+$formCtrl.$valid);
// console.log('finishedRender: '+$scope.finishedRender); // console.log('finishedRender: '+$rootScope.finishedRender);
console.log('saveInProgress: '+$rootScope.saveInProgress); // console.log('saveInProgress: '+$rootScope.saveInProgress);
if($scope.finishedRender && ($formCtrl.$dirty || difference(oldValue,newValue).length !== 0) && !$rootScope.saveInProgress) { if($rootScope.finishedRender && ($formCtrl.$dirty || difference(oldValue,newValue).length !== 0) && !$rootScope.saveInProgress) {
$rootScope.watchCount++; $rootScope.watchCount++;
if($rootScope.watchCount === 1) { // if($rootScope.watchCount === 1) {
if(savePromise) { if(savePromise) {
$timeout.cancel(savePromise); $timeout.cancel(savePromise);
@ -66,11 +68,12 @@ angular.module('forms').directive('autoSaveForm', ['$rootScope', '$timeout', fun
$rootScope[$attrs.autoSaveCallback]( $rootScope[$attrs.autoSaveCallback](
function(err){ function(err){
if(!err){ if(!err){
console.log('Form data persisted -- setting pristine flag'); console.log('\n\nForm data persisted -- setting pristine flag');
console.log('\n\n---------\nUpdate form CLIENT'); // console.log('\n\n---------\nUpdate form CLIENT');
console.log(Date.now()); // console.log(Date.now());
$rootScope.watchCount = 0; $rootScope.watchCount = 0;
$formCtrl.$setPristine(); $formCtrl.$setPristine();
// $rootScope.saveInProgress = false;
}else{ }else{
console.log('Error form data NOT persisted'); console.log('Error form data NOT persisted');
console.log(err); console.log(err);
@ -79,7 +82,7 @@ angular.module('forms').directive('autoSaveForm', ['$rootScope', '$timeout', fun
}); });
} // }
}else{ }else{
return; return;
} }

View file

@ -7,13 +7,14 @@ angular.module('forms').directive('onFinishRender', function ($rootScope, $timeo
if (scope.$first === true) { if (scope.$first === true) {
$timeout(function () { $timeout(function () {
$rootScope.$broadcast('ngRepeatStarted'); $rootScope.$broadcast('ngRepeatStarted');
}, 500); });
} }
if (scope.$last === true) { if (scope.$last === true) {
console.log(element);
$timeout(function () { $timeout(function () {
// console.log('ngRepeatFinished') console.log('ngRepeatFinished')
$rootScope.$broadcast('ngRepeatFinished'); $rootScope.$broadcast('ngRepeatFinished');
}, 500); });
} }
} }
}; };

View file

@ -27,7 +27,6 @@ angular.module('forms').factory('Forms', ['$resource',
form.visible_form_fields = _.filter(form.form_fields, function(field){ form.visible_form_fields = _.filter(form.form_fields, function(field){
return field.deletePreserved === false; return field.deletePreserved === false;
}); //<-- replace each item with an instance of the resource object }); //<-- replace each item with an instance of the resource object
console.log(form);
return form; return form;
} }
}, },

View file

@ -10,7 +10,7 @@
<span ng-if="form.$dirty && form.$valid" class="help-block">Updating ...</span> <span ng-if="form.$dirty && form.$valid" class="help-block">Updating ...</span>
</div> </div>
<div class="panel-group row" class="draggable" ng-model="addField.types"> <div class="panel-group row" class="draggable" ng-model="addField.types">
<div class="col-xs-6" ng-repeat="type in addField.types" on-finish-render> <div class="col-xs-6" ng-repeat="type in addField.types">
<div class="panel panel-default" style="background-color:#f5f5f5;"> <div class="panel panel-default" style="background-color:#f5f5f5;">
<div class="panel-heading" ng-click="addNewField(type.name)" style="cursor: pointer; font-size:14px;"> <div class="panel-heading" ng-click="addNewField(type.name)" style="cursor: pointer; font-size:14px;">
<span class="pull-left"> <span class="pull-left">
@ -30,7 +30,7 @@
<div class="col-xs-10"> <div class="col-xs-10">
<accordion close-others="accordion.oneAtATime" ui-sortable="dropzone" ng-model="myform.form_fields" class="dropzone"> <accordion close-others="accordion.oneAtATime" ui-sortable="dropzone" ng-model="myform.form_fields" class="dropzone">
<accordion-group ng-repeat="field in myform.form_fields" is-open="accordion[$index].isOpen" on-finish-render="setFormValid()" ng-show="!field.deletePreserved"> <accordion-group ng-repeat="field in myform.form_fields" is-open="accordion[$index].isOpen" on-finish-render ng-show="!field.deletePreserved">
<accordion-heading> <accordion-heading>

View file

@ -1,5 +1,5 @@
<section class="overlay" ng-if="showCreateModal" ng-click="closeCreateModal()"></section>
<section data-ng-controller="ViewFormController as ctrl" data-ng-init="findAll()" class="container"> <section data-ng-controller="ViewFormController as ctrl" data-ng-init="findAll()" class="container">
<section class="overlay" ng-if="showCreateModal" ng-click="closeCreateModal()"></section>
<div class="row"> <div class="row">
<div class="page-header col-xs-10 col-xs-offset-1"> <div class="page-header col-xs-10 col-xs-offset-1">
@ -25,7 +25,7 @@
<div class="title-row row"> <div class="title-row row">
<div class="col-xs-5 field-title">Name </div> <div class="col-xs-5 field-title">Name </div>
<div class="col-xs-8 field-input"> <div class="col-xs-8 field-input">
<input type="text" name="name" ng-model="name" required style="color:black;" ng-pattern="/^[a-zA-Z0-9 ]*$/"/> <input type="text" name="name" ng-model="name" required style="color:black; border:none;" ng-pattern="/^[a-zA-Z0-9 ]*$/"/>
</div> </div>
</div> </div>
<div class="details-row row"> <div class="details-row row">

View file

@ -20,7 +20,7 @@
</div> </div>
</div> </div>
<div class="row"> <div class="row" cg-busy="{promise:updatePromise,message:'Updating form...',backdrop:true}">
<!-- <div > --> <!-- <div > -->
<tabset class="col-xs-12"> <tabset class="col-xs-12">
<tab> <tab>
@ -33,13 +33,17 @@
<tab-heading > <tab-heading >
Edit Design Edit Design
</tab-heading> </tab-heading>
<edit-form-directive myform="myform" user="user"></edit-form-directive> <div cg-busy="promise:updatePromise"></div>
<edit-form-directive myform="myform" user="user">
</edit-form-directive>
</tab> </tab>
<tab> <tab>
<tab-heading> <tab-heading>
Configure Configure
</tab-heading> </tab-heading>
<configure-form-directive myform="myform" user="user"></configure-form-directive> <div cg-busy="promise:updatePromise"></div>
<configure-form-directive myform="myform" user="user">
</configure-form-directive>
</tab> </tab>
<tab data-ng-click="showSubmissions()"> <tab data-ng-click="showSubmissions()">
<tab-heading> <tab-heading>

View file

@ -6,7 +6,8 @@ angular.module('users').config(['$httpProvider',
$httpProvider.interceptors.push(function($q, $location) { $httpProvider.interceptors.push(function($q, $location) {
return { return {
responseError: function(response) { responseError: function(response) {
if( $location.path() !== '/verify' && $location.path() !== '/users/me' && $location.path() !== '/' && $location.path() !== '/signup' && response.config){ // console.log($location.path());
if( response.config.url !== '/users/me' && $location.path() !== '/users/me' && response.config){
console.log('intercepted rejection of ', response.config.url, response.status); console.log('intercepted rejection of ', response.config.url, response.status);
if (response.status === 401) { if (response.status === 401) {

View file

@ -7,21 +7,18 @@ angular.module('users').controller('AuthenticationController', ['$scope', '$loca
$scope.credentials = {}; $scope.credentials = {};
$scope.error = null; $scope.error = null;
// If user is signed in then redirect back home
if ($scope.authentication.isAuthenticated()) $state.go('home');
$scope.signin = function() { $scope.signin = function() {
Auth.currentUser = User.login($scope.credentials).then( User.login($scope.credentials).then(
function(response) { function(response) {
console.log(response)
Auth.login(response); Auth.login(response);
$scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User); $scope.user = $rootScope.user = Auth.ensureHasCurrentUser(User);
if($state.previous.name !== 'home' && $state.previous.name !== ''){ if($state.previous.name !== 'home' && $state.previous.name !== 'verify' && $state.previous.name !== ''){
$state.go($state.previous.name); $state.go($state.previous.name);
}else{ }else{
$state.go('home'); $state.go('listForms');
} }
}, },
function(error) { function(error) {
$rootScope.user = Auth.ensureHasCurrentUser(User); $rootScope.user = Auth.ensureHasCurrentUser(User);

View file

@ -4,39 +4,39 @@ angular.module('users').controller('PasswordController', ['$scope', '$stateParam
function($scope, $stateParams, $state, User) { function($scope, $stateParams, $state, User) {
//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');
// 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(
function(response){ function(response){
$scope.success = response.message; $scope.success = response.message;
$scope.credentials = null; $scope.credentials = null;
}, },
function(error){ function(error){
$scope.error = error; $scope.error = error;
$scope.credentials = null; $scope.credentials = null;
} }
); );
}; };
// Change user password // Change user password
$scope.resetUserPassword = function() { $scope.resetUserPassword = function() {
$scope.success = $scope.error = null; $scope.success = $scope.error = null;
User.resetPassword($scope.passwordDetails, $stateParams.token).then( User.resetPassword($scope.passwordDetails, $stateParams.token).then(
function(response){ function(response){
// If successful show success message and clear form // If successful show success message and clear form
$scope.success = response.message; $scope.success = response.message;
$scope.passwordDetails = null; $scope.passwordDetails = null;
// And redirect to the index page // And redirect to the index page
$state.go('reset-success'); $state.go('reset-success');
}, },
function(error){ function(error){
$scope.error = error.message || error; $scope.error = error.message || error;
$scope.passwordDetails = null; $scope.passwordDetails = null;
} }
); );
}; };
} }
]); ]);

View file

@ -2,7 +2,7 @@
angular.module('users').controller('VerifyController', ['$scope', '$state', '$rootScope', 'User', 'Auth', '$stateParams', angular.module('users').controller('VerifyController', ['$scope', '$state', '$rootScope', 'User', 'Auth', '$stateParams',
function($scope, $state, $rootScope, User, Auth, $stateParams) { function($scope, $state, $rootScope, User, Auth, $stateParams) {
if($rootScope.authetication.isAuthenticated){ if($rootScope.authentication.isAuthenticated()){
$state.go('home'); $state.go('home');
} }
@ -14,10 +14,12 @@ angular.module('users').controller('VerifyController', ['$scope', '$state', '$ro
function(response){ function(response){
$scope.success = response.message; $scope.success = response.message;
$scope.credentials = null; $scope.credentials = null;
$scope.isResetSent = true;
}, },
function(error){ function(error){
$scope.error = error; $scope.error = error;
$scope.credentials = null; $scope.credentials = null;
$scope.isReset = false;
} }
); );
}; };

View file

@ -14,12 +14,12 @@ angular.module('users').factory('Auth', function($window) {
// Auth <- $http <- $resource <- LoopBackResource <- User <- Auth // Auth <- $http <- $resource <- LoopBackResource <- User <- Auth
ensureHasCurrentUser: function(User) { ensureHasCurrentUser: function(User) {
if (service.currentUser && service.currentUser.displayName) { if (service.currentUser && service.currentUser.displayName) {
// console.log('Using local current user.'); console.log('Using local current user.');
// console.log(service.currentUser); console.log(service.currentUser);
return service.currentUser; return service.currentUser;
} }
else if ($window.user){ else if ($window.user){
// console.log('Using cached current user.'); console.log('Using cached current user.');
// console.log($window.user); // console.log($window.user);
service.currentUser = $window.user; service.currentUser = $window.user;
return service.currentUser; return service.currentUser;

View file

@ -25,7 +25,7 @@
Error: <strong data-ng-bind="error"></strong> Error: <strong data-ng-bind="error"></strong>
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="username">Username</label> <label for="username">Account Email</label>
<input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username"> <input type="text" id="username" name="username" class="form-control" data-ng-model="credentials.username" placeholder="Username">
</div> </div>
<div class="form-group"> <div class="form-group">

View file

@ -20,12 +20,16 @@
<h3 class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6 text-center">Signup Successful</h3> <h3 class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6 text-center">Signup Successful</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6"> <div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<h2> <h2>
Congrats! You've successfully registered an account at MedForms. <br>But your account is <b>not verified yet</b> You've successfully registered an account at MedForms.
<br><br>But your account is <b>not activated yet</b>
</h2> </h2>
<p>Before you continue, make sure to check your email for our verification email. If you don't receive it within 24h drop us a line at <a href="mail:hi@medforms.com">hi@medforms.com</a></p> <br><br>
<p>Before you continue, make sure to check your email for our verification. If you don't receive it within 24h drop us a line at <a href="mail:hi@medforms.com">hi@medforms.com</a></p>
<div class="text-center form-group"> <div class="text-center form-group">
<button type="submit" class="btn btn-large btn-primary"> <button type="submit" class="btn btn-large btn-primary">
<a href="/">Continue</a> <a href="/" style="color: white; text-decoration: none;">Continue</a>
</button> </button>
</div> </div>
</div> </div>

View file

@ -1,6 +1,6 @@
<section class="auth row" data-ng-controller="PasswordController"> <section class="auth row" data-ng-controller="PasswordController">
<h3 class="col-md-12 text-center">Restore your password</h3> <h3 class="col-md-12 text-center">Restore your password</h3>
<p class="small text-center">Enter your account username.</p> <p class="small text-center">Enter your account email.</p>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6"> <div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<form data-ng-submit="askForPasswordReset()" class="signin form-horizontal" autocomplete="off"> <form data-ng-submit="askForPasswordReset()" class="signin form-horizontal" autocomplete="off">
<fieldset> <fieldset>

View file

@ -1,22 +1,40 @@
<section class="auth row" data-ng-controller="VerifyController"> <section class="auth row" data-ng-controller="VerifyController">
<h3 class="col-md-12 text-center">Resend your account verification email</h3> <section ng-if="!isResetSent">
<p class="small text-center">Enter your account email.</p> <h3 class="col-md-12 text-center">Resend your account verification email</h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6"> <p class="small text-center">Enter your account email.</p>
<form data-ng-submit="resendVerifyEmail()" class="signin form-horizontal" autocomplete="off"> <div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<fieldset> <form data-ng-submit="resendVerifyEmail()" class="signin form-horizontal" autocomplete="off">
<div class="form-group"> <fieldset>
<input type="text" id="username" name="email" class="form-control" data-ng-model="email" placeholder="bob@example.com"> <div class="form-group">
</div> <input type="text" id="username" name="email" class="form-control" data-ng-model="email" placeholder="bob@example.com">
<div class="text-center form-group"> </div>
<button type="submit" class="btn btn-primary">Submit</button> <div class="text-center form-group">
</div> <button type="submit" class="btn btn-primary" ng-click="resendVerifyEmail()">Submit</button>
<div data-ng-show="error" class="text-center text-danger"> </div>
<strong>{{error}}</strong>
</div> <div data-ng-show="error" class="text-center text-danger">
<div data-ng-show="success" class="text-center text-success"> <strong>{{error}}</strong>
<strong>{{success}}</strong> </div>
</div> <!-- <div data-ng-show="success" class="text-center text-success">
</fieldset> <strong>{{success}}</strong>
</form> </div> -->
</div> </fieldset>
</form>
</div>
</section>
<section ng-if="isResetSent">
<h3 class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6 text-center">Verification Email has been Sent </h3>
<div class="col-xs-offset-2 col-xs-8 col-md-offset-3 col-md-6">
<h2>
A verification email has been sent to {{username}}.<br>But your account is still <b>not activated yet</b>
</h2>
<p>Check your email and click on the activation link to activate your account. If you have any questions drop us a line at <a href="mail:hi@medforms.com">hi@medforms.com</a></p>
<div class="text-center form-group">
<button type="submit" class="btn btn-large btn-primary">
<a href="/#!/">Continue</a>
</button>
</div>
</div>
</section>
</section> </section>

View file

@ -1,8 +1,8 @@
<section class="row text-center" data-ng-controller="VerifyController" ng-init="validateVerifyToken()"> <section class="row text-center" data-ng-controller="VerifyController" ng-init="validateVerifyToken()">
<section class="row text-center" ng-if="isReset"> <section class="row text-center" ng-if="isReset">
<h3 class="col-md-12">Password successfully reset</h3> <h3 class="col-md-12">Account successfuly activated</h3>
<a href="/#!/" class="col-md-12">Continue to home page</a> <a href="/#!/signin" class="col-md-12">Continue to login page</a>
</section> </section>
<section class="row text-center" ng-if="!isReset"> <section class="row text-center" ng-if="!isReset">