From 51ffef14e72d2ec4988f3e063790935d05af67d3 Mon Sep 17 00:00:00 2001 From: asihud Date: Sat, 8 Apr 2017 19:11:52 +0300 Subject: [PATCH] Asi 08 04 changes (#256) * last commit * latest check * new db migrations and updated passport * login with drupal support * add the rest, and lint * GUI changes * not sure how does res reach here * that cache again * cleanup * remove code duplication * fix lint * adding error handling * pass the error handling on * fixed constants.js * tmp disable travis cache for node_modules * Update passport.js * update to latest * adding test special case * no yoda notation for me T_T * Update main_routes.test.js * dddd * update test-user and raise timeout * update test-user and omit some test logic to adjust to new bizlogic of login * changed the test user no need for mock anymore * remove underscore * updated imported csv to new members_camp * commit changes * d * fixed the validated sign * some fixes, adding the EVENT_ID * removed the campDetails from all places. fixed one insert and update. update on new camp the event_id * fix for eslint * fixes * fixed for eslint * local commit * added enabled status * refine * Merge branch 'master' of https://github.com/Midburn/Spark * camps route fix * Revert "camps route fix" This reverts commit d926484a77b981f08ec68501acf61992c1621d05. * basic members implementation * bug fix * add member form * removed unnecessary function call * fixed several small issues, with getUserCamps functions, moving the functionality from API to the User model. * fixed several small issues, with getUserCamps functions, moving the functionality from API to the User model. * manually loaded api_camps_route * test * fix * sdfsadf * change activity time to multi select * lilach location fixes * improve contact person dropdown display * facebook link size fix * data validation * lint * Changed the API commands for join & join_deliver to work with the model commands. * fix lint issues * added option to remove approve new members * lint * fixed some bugs with getUserCamps and fix security issues. * ui fixes * commit passport + approve * ddd * changes * join camp is according to lang * FB link doesn't get too long * translation fixes * added approve join request btn * added email templates * comit local changes * changes of field names for members * typo fix * updated the join camp flow, and tested * lint shit * lint shit * fixes the join system, and several bug fix * lint shit * finalized the join flow several bug was removed. still having angular issue, need to be found. * removed junk * lint * fixes issues before production, also import bugs. * show contact information good * d * changes for lint * small issues * fixed the cancel user request fixed some small security issues with users removed automatic fetch from camps_v2 added language string for all status code. * lint shit * Introduced the camp __prototype to use for other camp types. fixed the camp_location_area * fixing all hebrew titles fixed who am i introduced the camp_type schema * lint shit * changes * fixes split issue * template api_gate * fixed the members add, for admin show all camps * lint * fixed mail delivery to join request * lint * refactoring edit + new, to fix foreign key, and adding fields to edit only for admin * fixed add new camp, and adding default member. todo: after success update, forward to edit camp check if camp_name hebrew + english are not empty change selection of camp manager to be select2 input * lint * lint * lint * lint fixes * lint * latest fixes --- libs/common.js | 18 ++ models/camp.js | 19 +- models/camp_member.js | 20 --- models/user.js | 11 +- public/scripts/camps.js | 98 +++++----- public/scripts/controllers/camp_edit.js | 40 +++-- routes/api_camps_routes.js | 226 ++++++++++++++---------- routes/camps_routes.js | 2 +- 8 files changed, 227 insertions(+), 207 deletions(-) create mode 100644 libs/common.js delete mode 100644 models/camp_member.js diff --git a/libs/common.js b/libs/common.js new file mode 100644 index 000000000..d702d365f --- /dev/null +++ b/libs/common.js @@ -0,0 +1,18 @@ +var functions = { + __hasRole: function (role, roles) { + return (roles && roles.split(',').indexOf(role) > -1); + }, + __updateUserRec: function (user) { + if (!user.name && (user.first_name || user.last_name)) { + user.name = user.first_name + ' ' + user.last_name; + } + if (!user.name) { + user.name = user.email; + } + }, +} + +// Create the model and expose it +module.exports = { + common: functions, +}; diff --git a/models/camp.js b/models/camp.js index f170b482a..e2dc1a43d 100644 --- a/models/camp.js +++ b/models/camp.js @@ -1,15 +1,9 @@ -// var i18next = require('i18next'); -// var config = require('config'); -// var i18nConfig = config.get('i18n'); +const common = require('../libs/common').common; var bookshelf = require('../libs/db').bookshelf; var constants = require('./constants.js'); var User = require('../models/user').User; const knex = require('../libs/db').knex; -function __hasRole(role, roles) { - return (roles && roles.split(',').indexOf(role) > -1); -} - var Camp = bookshelf.Model.extend({ tableName: constants.CAMPS_TABLE_NAME, idAttribute: 'id', @@ -39,17 +33,12 @@ var Camp = bookshelf.Model.extend({ if (t !== undefined) { // translate function users[i].member_status_i18n = t('camps:members.status_' + _status); } + common.__updateUserRec(users[i]); users[i].can_remove = ['rejected', 'pending_mgr',].indexOf(_status) > -1; users[i].can_approve = ['pending', 'rejected'].indexOf(_status) > -1 && users[i].validated; users[i].can_reject = ['pending', 'approved'].indexOf(_status) > -1 && _this.attributes.main_contact !== users[i].user_id; - - if (!users[i].name && (users[i].first_name || users[i].last_name)) { - users[i].name = users[i].first_name + ' ' + users[i].last_name; - } - if (!users[i].name) { - users[i].name = users[i].email; - } - if (((_this.attributes.main_contact === users[i].user_id || __hasRole('camp_manager', users[i].roles)) + + if (((_this.attributes.main_contact === users[i].user_id || common.__hasRole('camp_manager', users[i].roles)) && users[i].member_status === 'approved') || (users[i].member_status === 'approved_mgr')) { users[i].isManager = true; diff --git a/models/camp_member.js b/models/camp_member.js deleted file mode 100644 index 163a98768..000000000 --- a/models/camp_member.js +++ /dev/null @@ -1,20 +0,0 @@ -var bookshelf = require('../libs/db').bookshelf; -var constants = require('./constants.js'); -var User = require('../models/user').User; -var Camp = require('../models/camp').Camp; - -var CampMember = bookshelf.Model.extend({ - tableName: constants.CAMP_MEMBERS_TABLE_NAME, - idAttribute: 'user_id', - user: function() { - return this.hasOne(User, 'user_id') - }, - camp: function() { - return this.hasOne(Camp, 'id') - } -}); - -// Create the model and expose it -module.exports = { - CampMember: CampMember -}; diff --git a/models/user.js b/models/user.js index ff57604b8..d2abde0c4 100644 --- a/models/user.js +++ b/models/user.js @@ -1,3 +1,4 @@ +const common = require('../libs/common').common; var bookshelf = require('../libs/db').bookshelf; var bcrypt = require('bcrypt-nodejs'); var randtoken = require('rand-token'); @@ -55,7 +56,6 @@ var User = bookshelf.Model.extend({ var first_camp; var is_manager = false; var member_type_array = ['approved', 'pending', 'pending_mgr', 'approved_mgr', 'supplier']; - // i18next.init({lng:'he'}); for (var i in camps) { let _status = camps[i].member_status; if (t !== undefined) { // translate function @@ -64,11 +64,9 @@ var User = bookshelf.Model.extend({ if (!first_camp && member_type_array.indexOf(_status) > -1) { first_camp = camps[i]; } - if (((camps[i].main_contact === this.attributes.user_id || this.__hasRole('camp_manager', this.attributes.roles)) + if (((camps[i].main_contact === this.attributes.user_id || common.__hasRole('camp_manager', this.attributes.roles)) && camps[i].member_status === 'approved') || (camps[i].member_status === 'approved_mgr')) { - // if ((camps[i].main_contact === this.attributes.user_id && camps[i].member_status === 'approved') || - // camps[i].member_status === 'approved_mgr') { first_camp = camps[i]; is_manager = true; break; @@ -85,11 +83,8 @@ var User = bookshelf.Model.extend({ validPassword: function (password) { return bcrypt.compareSync(password, this.attributes.password); }, - __hasRole: function (role, roles) { - return (roles && roles.split(',').indexOf(role) > -1); - }, hasRole: function (role) { - return this.__hasRole(role, this.attributes.roles); + return common.__hasRole(role, this.attributes.roles); }, isManagerOfCamp: function (camp_id) { let isCampManager = false; diff --git a/public/scripts/camps.js b/public/scripts/camps.js index cfdf7e60a..4a35bba33 100644 --- a/public/scripts/camps.js +++ b/public/scripts/camps.js @@ -1,13 +1,13 @@ /** * GLOBALS */ -$(document).ajaxStart(function() { +$(document).ajaxStart(function () { $('#ajax_indicator').removeClass('done').removeClass('hide').fadeIn('fast'); }); -$(document).ajaxComplete(function() { +$(document).ajaxComplete(function () { $('#ajax_indicator').addClass('done').fadeOut('slow'); }); -$(function() { +$(function () { // tooltips $('[data-toggle="tooltip"]').tooltip() }); @@ -15,7 +15,7 @@ $(function() { /** * Scroll to top - footer button */ -$('#scroll_top').click(function() { +$('#scroll_top').click(function () { $("html, body").stop().animate({ scrollTop: 0 }, '250', 'swing'); @@ -28,12 +28,12 @@ var interval = 800, typingTimer, $input = $(".camps input[name='camp_name_en']"); -$input.keyup(function() { +$input.keyup(function () { clearTimeout(typingTimer); typingTimer = setTimeout(doneTyping, interval); }); -$input.keydown(function() { +$input.keydown(function () { clearTimeout(typingTimer); }); @@ -45,7 +45,7 @@ function doneTyping() { btn = $('#check_camp_name'); if (val.length > 3) { var data = $.get('../camps/' + val); - data.done(function() { + data.done(function () { if (data.status === 204) { input.removeClass('error'); status.removeClass('glyphicon-remove').addClass('glyphicon-ok'); @@ -64,7 +64,7 @@ function doneTyping() { function getUserTemplate(data) { if (data !== undefined) { - return "" + return "" } } /** @@ -76,28 +76,28 @@ function fetchUsersOnce(elm) { elm = $(elm) if (!elm.attr('fetched')) { - $.getJSON('/camps/' + camp_id + '/members', function(data) {}) - .success((data) => { - users = [data.users]; - for (var i = 0; i < users.length; i++) { - elm.append(getUserTemplate(users[i])); - } - }) - .error((data) => { - if (lang === 'he') { - sweetAlert("אופס...", "אין משתמשים פעילים!", "error"); - } else { - sweetAlert("Oops...", "No user available!", "error"); - } - }) + $.getJSON('/camps/' + camp_id + '/members', function (data) { }) + .success((data) => { + users = [data.users]; + for (var i = 0; i < users.length; i++) { + elm.append(getUserTemplate(users[i])); + } + }) + .error((data) => { + if (lang === 'he') { + sweetAlert("אופס...", "אין משתמשים פעילים!", "error"); + } else { + sweetAlert("Oops...", "No user available!", "error"); + } + }) elm.attr('fetched', true); } } -$(function() { +$(function () { var user_inputs = '#create_camp_contact_person_id'; if ($('.camps').is('.camp_create')) { - fetchUsersOnce(user_inputs); + fetchUsersOnce(user_inputs); } }); @@ -105,7 +105,7 @@ $(function() { * Component: Editing camp * (PUT) /camps/:camp_id/edit */ -$('#camp_edit_save').click(function() { +$('#camp_edit_save').click(function () { var lang = document.getElementById('meta__lang').value; var type = fetchAllCheckboxValues('camp_type'); var activity_time = fetchAllCheckboxValues('camp_activity_time'); @@ -141,8 +141,8 @@ $('#camp_edit_save').click(function() { url: '/camps/' + camp_id + '/edit', type: 'PUT', data: camp_data, - success: function(result) { - if (lang ==='he') { + success: function (result) { + if (lang === 'he') { sweetAlert("כל הכבוד", "המחנה עודכן, על מנת לראות את השינויים יש לרענן את העמוד", "success"); } else { sweetAlert("You good...", "Camp details updated! reload the page.", "success"); @@ -150,17 +150,17 @@ $('#camp_edit_save').click(function() { } }); }); -$('#camp_edit_publish').click(function() { +$('#camp_edit_publish').click(function () { var camp_id = $('#camp_edit_camp_id').val(); $.ajax({ url: '/camps/' + camp_id + '/publish', type: 'PUT', - success: function(result) { + success: function (result) { console.log(result); } }); }); -$('#camp_edit_unpublish').click(function() { +$('#camp_edit_unpublish').click(function () { var camp_name = $('#meta__camp_name_en').attr('value'), agree_unpublish = confirm('Un-publish camp\n\n\nThis action will remove ' + camp_name + ' from the public camps list.\n\n\n---\n Are you sure?'); if (agree_unpublish) { @@ -168,7 +168,7 @@ $('#camp_edit_unpublish').click(function() { $.ajax({ url: '/camps/' + camp_id + '/unpublish', type: 'PUT', - success: function(result) { + success: function (result) { console.log(result); } }); @@ -176,7 +176,7 @@ $('#camp_edit_unpublish').click(function() { }); // display other text field if other selected -$('#edit_type_other').click(function() { +$('#edit_type_other').click(function () { if ($('#edit_type_other').is(':checked')) { $('#edit_type_other_text').removeClass('hidden'); } else { @@ -187,7 +187,7 @@ $('#edit_type_other').click(function() { /** * Component: Create new camp with approval modal */ -$('#camp_create_save').click(function() { +$('#camp_create_save').click(function () { var type = fetchAllCheckboxValues('camp_type'); var activity_time = fetchAllCheckboxValues('camp_activity_time'); var camp_data = { @@ -221,12 +221,12 @@ $('#camp_create_save').click(function() { $('#create_camp_request_modal').modal('show'); _campAppendData(); // approve create camp - $('#camp_create_save_modal_request').click(function() { + $('#camp_create_save_modal_request').click(function () { _sendRequest(); }); function _campAppendData() { - $.each(camp_data, function(label, data) { + $.each(camp_data, function (label, data) { if (data) { $('.' + label).show(); $('.' + label + ' span').text(': ' + data).css('font-weight', 'bold'); @@ -242,17 +242,17 @@ $('#camp_create_save').click(function() { url: '/camps/new', type: 'POST', data: camp_data, - success: function(result) { + success: function (result) { var camp_id = result.data.camp_id; $('#create_camp_request_modal').find('.modal-body').html('

Camp created succesfully.
you can edit it: here

'); $('#create_camp_request_modal').find('#camp_create_save_modal_request').hide(); // 10 sec countdown to close modal var sec = 10; - setInterval(function() { + setInterval(function () { $('#create_camp_request_modal').find('#create_camp_close_btn').text('Close ' + sec); sec -= 1; }, 1000); - setTimeout(function() { + setTimeout(function () { $('#create_camp_request_modal').modal('hide'); }, sec * 1000); } @@ -261,7 +261,7 @@ $('#camp_create_save').click(function() { }); // display other text field if other selected -$('#camp_type_other_checkbox').click(function() { +$('#camp_type_other_checkbox').click(function () { if ($('#camp_type_other_checkbox').is(':checked')) { $('#camp_type_other_text').removeClass('hidden'); } else { @@ -271,14 +271,14 @@ $('#camp_type_other_checkbox').click(function() { // Collect all checkbox values function fetchAllCheckboxValues(className) { - var val = []; - $('.' + className + ':checked').each(function(i) { - val[i] = $(this).val(); - if (val[i] === 'other') { - val[i] += '=' + $('#'+ className + '_other_text').val() - } - }); - return val.toString(); + var val = []; + $('.' + className + ':checked').each(function (i) { + val[i] = $(this).val(); + if (val[i] === 'other') { + val[i] += '=' + $('#' + className + '_other_text').val() + } + }); + return val.toString(); } /* * Component: view camp details @@ -286,7 +286,7 @@ function fetchAllCheckboxValues(className) { // Fetch & inject user data var user_type; function _fetchUserData(user_id) { - $.getJSON('/users/' + user_id, function(response) { + $.getJSON('/users/' + user_id, function (response) { _injectUserData(response) }) } @@ -301,7 +301,7 @@ function _injectUserData(user_data) { $(type).removeClass('hidden').fadeIn('fast'); } if ($('.camp_details')) { - $('.fetch_user_info').click(function() { + $('.fetch_user_info').click(function () { var user_id = $(this).attr('data-user-id') user_type = $(this).attr('data-user-type'); _fetchUserData(user_id); diff --git a/public/scripts/controllers/camp_edit.js b/public/scripts/controllers/camp_edit.js index 7ac9fe880..3c6a39890 100644 --- a/public/scripts/controllers/camp_edit.js +++ b/public/scripts/controllers/camp_edit.js @@ -1,19 +1,26 @@ var angular_getMembers = function ($http, $scope, camp_id) { - $http.get(`/camps/${camp_id}/members`).then((res) => { - var members = res.data.members; - var _members = []; - var approved_members = []; - for (var i in members) { - if (['approved', 'pending', 'pending_mgr', 'approved_mgr', 'rejected'].indexOf(members[i].member_status) > -1) { - _members.push(members[i]); - } - if (['approved', 'approved_mgr'].indexOf(members[i].member_status) > -1) { - approved_members.push(members[i]); + if (camp_id === 'new') { + $http.get('/users').then((res) => { + $scope.members = []; + $scope.approved_members = res.data.users; + }); + } else { + $http.get(`/camps/${camp_id}/members`).then((res) => { + var members = res.data.members; + var _members = []; + var approved_members = []; + for (var i in members) { + if (['approved', 'pending', 'pending_mgr', 'approved_mgr', 'rejected'].indexOf(members[i].member_status) > -1) { + _members.push(members[i]); + } + if (['approved', 'approved_mgr'].indexOf(members[i].member_status) > -1) { + approved_members.push(members[i]); + } } - } - $scope.members = _members; - $scope.approved_members = approved_members; - }); + $scope.members = _members; + $scope.approved_members = approved_members; + }); + } } var angular_updateUser = function ($http, $scope, action_type, user_rec) { var camp_id = user_rec.camp_id; @@ -76,7 +83,7 @@ app.controller("campEditController", ($scope, $http, $filter) => { $scope.orderMembers = orderByValue; } if (typeof camp_id !== 'undefined') { - $scope.current_camp_id=camp_id; + $scope.current_camp_id = camp_id; $scope.getMembers(); } $scope.lang = document.getElementById('meta__lang').value; @@ -93,8 +100,9 @@ app.controller("campEditController", ($scope, $http, $filter) => { $http.post(`/camps/${camp_id}/members/add`, data).then(function (res) { // update table with new data $scope.getMembers(); + $scope.camps_members_add_member=''; }).catch((err) => { - sweetAlert("Error!", "Something went wrong, please try again later " + err, "error"); + sweetAlert("Error!", "Add new member error: " + err.data.data.message, "error"); }); } $scope.updateUser = (user_name, user_id, action_type) => { diff --git a/routes/api_camps_routes.js b/routes/api_camps_routes.js index 310cb8e22..739f3b19e 100644 --- a/routes/api_camps_routes.js +++ b/routes/api_camps_routes.js @@ -1,3 +1,4 @@ +const common = require('../libs/common').common; var User = require('../models/user').User; var Camp = require('../models/camp').Camp; const constants = require('../models/constants.js'); @@ -53,6 +54,60 @@ module.exports = (app, passport) => { }); }); }); + + var __camps_create_camp_obj = function (req, isNew) { + var data = { + __prototype: constants.prototype_camps.THEME_CAMP.id, + event_id: constants.CURRENT_EVENT_ID, + // for update or insert, need to merge with create to be the same call + updated_at: Date(), + camp_desc_he: req.body.camp_desc_he, + camp_desc_en: req.body.camp_desc_en, + status: req.body.status, + type: req.body.type, + facebook_page_url: req.body.facebook_page_url, + contact_person_name: req.body.contact_person_name, + contact_person_email: req.body.contact_person_email, + contact_person_phone: req.body.contact_person_phone, + accept_families: req.body.accept_families, + camp_activity_time: req.body.camp_activity_time, + child_friendly: req.body.child_friendly, + noise_level: req.body.noise_level, + support_art: req.body.support_art, + } + var __update_prop_foreign = function (propName) { + if (parseInt(req.body[propName]) > 0) { + data[propName] = req.body[propName]; + } + } + var __update_prop = function (propName) { + if (req.body[propName] !== undefined) { + data[propName] = req.body[propName]; + } + } + if (isNew) { + data.created_at = Date(); + } + if (isNew || req.user.isAdmin) { + __update_prop('camp_name_en'); + __update_prop('camp_name_he'); + } + __update_prop_foreign('main_contact_person_id'); + __update_prop_foreign('main_contact'); + __update_prop_foreign('moop_contact'); + __update_prop_foreign('safety_contact'); + + if (req.user.isAdmin) { + __update_prop('public_activity_area_sqm'); + __update_prop('public_activity_area_desc'); + __update_prop('location_comments'); + __update_prop('camp_location_street'); + __update_prop('camp_location_street_time'); + __update_prop('camp_location_area'); + } + // console.log(data); + return data; + } /** * API: (POST) create camp * request => /camps/new @@ -60,46 +115,8 @@ module.exports = (app, passport) => { app.post('/camps/new', [userRole.isLoggedIn(), userRole.isAllowNewCamp()], (req, res) => { - Camp.forge({ - // for new fields! - created_at: Date(), - __prototype: constants.prototype_camps.THEME_CAMP.id, - event_id: constants.CURRENT_EVENT_ID, - // for update or insert, need to merge with create to be the same call - updated_at: Date(), - camp_name_en: req.body.camp_name_en, - camp_name_he: req.body.camp_name_he, - camp_desc_he: req.body.camp_desc_he, - camp_desc_en: req.body.camp_desc_en, - status: req.body.status, - type: req.body.type, - contact_person_id: req.body.contact_person_id, - facebook_page_url: req.body.facebook_page_url, - contact_person_name: req.body.contact_person_name, - contact_person_email: req.body.contact_person_email, - contact_person_phone: req.body.contact_person_phone, - accept_families: req.body.accept_families, - main_contact: req.body.main_contact, - moop_contact: req.body.moop_contact, - safety_contact: req.body.safety_contact, - camp_activity_time: req.body.camp_activity_time, - child_friendly: req.body.child_friendly, - noise_level: req.body.noise_level, - public_activity_area_sqm: req.body.public_activity_area_sqm, - public_activity_area_desc: req.body.public_activity_area_desc, - support_art: req.body.support_art, - location_comments: req.body.location_comments, - camp_location_street: req.body.camp_location_street, - camp_location_street_time: req.body.camp_location_street_time, - camp_location_area: req.body.camp_location_area - }).save().then((camp) => { - res.json({ - error: false, - data: { - message: 'camp created', - camp_id: camp.attributes.id - } - }); + Camp.forge(__camps_create_camp_obj(req, true)).save().then((camp) => { + __camps_update_status(camp.attributes.id, camp.attributes.main_contact, 'approve_new_mgr', req.user, res); }).catch((e) => { res.status(500).json({ error: true, @@ -118,37 +135,7 @@ module.exports = (app, passport) => { [userRole.isLoggedIn(), userRole.isAllowEditCamp()], (req, res) => { Camp.forge({ id: req.params.id }).fetch().then((camp) => { - camp.save({ - // for update or insert - updated_at: Date(), - event_id: constants.CURRENT_EVENT_ID, - __prototype: constants.prototype_camps.THEME_CAMP.id, - camp_name_en: req.body.camp_name_en, - camp_name_he: req.body.camp_name_he, - camp_desc_he: req.body.camp_desc_he, - camp_desc_en: req.body.camp_desc_en, - status: req.body.status, - type: req.body.type, - contact_person_id: req.body.contact_person_id, - facebook_page_url: req.body.facebook_page_url, - accept_families: req.body.accept_families, - contact_person_name: req.body.contact_person_name, - contact_person_email: req.body.contact_person_email, - contact_person_phone: req.body.contact_person_phone, - main_contact: req.body.main_contact, - moop_contact: req.body.moop_contact, - safety_contact: req.body.safety_contact, - camp_activity_time: req.body.camp_activity_time, - child_friendly: req.body.child_friendly, - noise_level: req.body.noise_level, - public_activity_area_sqm: req.body.public_activity_area_sqm, - public_activity_area_desc: req.body.public_activity_area_desc, - support_art: req.body.support_art, - location_comments: req.body.location_comments, - camp_location_street: req.body.camp_location_street, - camp_location_street_time: req.body.camp_location_street_time, - camp_location_area: req.body.camp_location_area - }).then(() => { + camp.save(__camps_create_camp_obj(req, false)).then(() => { res.json({ error: false, status: 'Camp updated' }); // }); }).catch((err) => { @@ -219,7 +206,15 @@ module.exports = (app, passport) => { }); }); - __camps_update_status = (camp_id, user_id, action, camp_mgr_id, res) => { + __camps_update_status = (camp_id, user_id, action, camp_mgr, res) => { + var isAdmin = false; + var camp_mgr_id; + if (camp_mgr instanceof User) { + camp_mgr_id = camp_mgr.id; + isAdmin = camp_mgr.isAdmin; + } else { + camp_mgr_id = parseInt(camp_mgr); + } console.log(action + " from camp " + camp_id + " of user " + user_id + " / mgr id: " + camp_mgr_id); Camp.forge({ id: camp_id }).fetch().then((camp) => { camp.getCampUsers((users) => { @@ -233,7 +228,13 @@ module.exports = (app, passport) => { var user = camp.isUserInCamp(user_id); // camp manager commands - if (camp.isCampManager(camp_mgr_id)) { + if (action === 'approve_new_mgr' && (camp_mgr_id === camp.attributes.main_contact || isAdmin)) { + new_status = 'approved'; + if (!user) { + save_method.require = false; + save_method.method = 'insert'; + } + } else if (camp.isCampManager(camp_mgr_id) || isAdmin) { if (user && action === "approve" && user.can_approve) { mail_delivery.to_mail = user.email; mail_delivery.subject = 'Spark: you have been approved!'; @@ -250,7 +251,7 @@ module.exports = (app, passport) => { new_status = 'pending'; } else if (action === "request_mgr") { new_status = 'pending_mgr'; - mail_delivery.to_mail = user.email; + mail_delivery.to_mail = ''; mail_delivery.subject = 'Spark: you have been requested to join camp'; mail_delivery.template = 'emails/camps/member_request'; if (!user) { @@ -307,14 +308,20 @@ module.exports = (app, passport) => { console.log(action + " from camp " + data.camp_id + " of user " + data.user_id + " / status: " + data.status); if (mail_delivery.template !== '') { if (mail_delivery.to_mail !== '') { - emailDeliver(mail_delivery.to_mail, mail_delivery.subject, mail_delivery.template); // notify the user + emailDeliver(mail_delivery.to_mail, mail_delivery.subject, mail_delivery.template, { user: user }); // notify the user } else { User.forge({ user_id: user_id }).fetch().then((user) => { - emailDeliver(user.email, mail_delivery.subject, mail_delivery.template); // notify the user + emailDeliver(user.attributes.email, mail_delivery.subject, mail_delivery.template, { user: user }); // notify the user }); } } - res.status(200).json({ data: { member: data } }); + var res_data = { data: { member: data } }; + if (action === 'approve_new_mgr') { + res_data.data.message = 'camp created'; + res_data.data.camp_id = camp_id; + } + res.status(200).json(res_data); + } knex.raw(query).then(_after_update); } else { @@ -339,7 +346,7 @@ module.exports = (app, passport) => { var action = req.params.action; var actions = ['approve', 'remove', 'revive', 'reject']; if (actions.indexOf(action) > -1) { - __camps_update_status(camp_id, user_id, action, req.user.id, res); + __camps_update_status(camp_id, user_id, action, req.user, res); } else { res.status(404).json({ error: true, data: { message: "illegal command (" + action + ")" } }); } @@ -390,20 +397,34 @@ module.exports = (app, passport) => { }); /** - * API: (GET) return active user list + * API: (GET) return active user list. + * if req.user.isAdmin - return all users + * if req.user.isCampManager - return all users from all camps + * else return req.user * request => /users */ - app.get('/users', userRole.isAdmin(), (req, res) => { - User.fetchAll().then((users) => { - res.status(200).json({ users: users.toJSON() }) - }).catch((err) => { - res.status(500).json({ - error: true, - data: { - message: err.message + app.get('/users', (req, res) => { + if (req.user.isAdmin) { + User.where('validated', '=', '1').fetchAll().then((users) => { + // User.forge({ validated: true }).fetchAll().then((users) => { + // console.log(users); + var _users = users.toJSON(); + for (var i in _users) { + common.__updateUserRec(_users[i]); + // console.log(_users[i]); } + res.status(200).json({ users: _users }) + }).catch((err) => { + res.status(500).json({ + error: true, + data: { + message: err.message + } + }); }); - }); + } else { + res.status(200).json({ users: [req.user.toJSON()] }) + } }); /** @@ -571,7 +592,7 @@ module.exports = (app, passport) => { } }); } - },req.t); + }, req.t); }); } else { res.status(404).json({ @@ -583,18 +604,18 @@ module.exports = (app, passport) => { } }); - var emailDeliver = (recipient, subject, template) => { + var emailDeliver = (recipient, subject, template, props) => { /** * Deliver email request to camp manager * notifiying a user wants to join his camp * @return {boolean} should return true if mail delivered. FIXME: in mail.js */ - console.log('Trying to send mail to '+recipient+' from '+mailConfig.from+': '+subject+', template '+template); + console.log('Trying to send mail to ' + recipient + ' from ' + mailConfig.from + ': ' + subject + ', template ' + template); mail.send( recipient, mailConfig.from, subject, - template, {} + template, props ) } @@ -624,12 +645,12 @@ module.exports = (app, passport) => { app.get('/camps/:id/members', userRole.isLoggedIn(), (req, res) => { Camp.forge({ id: req.params.id }).fetch().then((camp) => { camp.getCampUsers((members) => { - if (camp.isCampManager(req.user.id,req.t) || req.user.isAdmin) { + if (camp.isCampManager(req.user.id, req.t) || req.user.isAdmin) { res.status(200).json({ members: members }); } else { res.status(500).json({ error: true, data: { message: 'Permission denied' } }); } - },req.t); + }, req.t); }).catch((e) => { res.status(500).json({ error: true, @@ -649,19 +670,28 @@ module.exports = (app, passport) => { var camp_id = req.params.id var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(user_email)) { - res.status(404).end(); + res.status(500).json({ error: true, data: { message: 'Bad email entered!' } }); return; } req.user.getUserCamps((camps) => { - if (req.user.isManagerOfCamp(req.params.id) || req.user.isAdmin) { + if (req.user.isManagerOfCamp(camp_id) || req.user.isAdmin) { User.forge({ email: user_email }).fetch().then((user) => { if (user !== null) { - __camps_update_status(camp_id, user.attributes.user_id, 'request_mgr', req.user.id, res); + // check that user is only at one camp! + user.getUserCamps((camps) => { + if (camps.length === 0 || user.isUserInCamp(camp_id)) { + __camps_update_status(camp_id, user.attributes.user_id, 'request_mgr', req.user, res); + } else { + res.status(500).json({ error: true, data: { message: 'Already applied to different camp!' } }); + } + }); } else { User.forge().save({ + updated_at: Date(), + created_at: Date(), email: user_email }).then((user) => { - __camps_update_status(camp_id, user.attributes.user_id, 'request_mgr', req.user.id, res); + __camps_update_status(camp_id, user.attributes.user_id, 'request_mgr', req.user, res); }); } diff --git a/routes/camps_routes.js b/routes/camps_routes.js index b392864e4..741a42940 100644 --- a/routes/camps_routes.js +++ b/routes/camps_routes.js @@ -58,7 +58,7 @@ module.exports = function (app, passport) { camp_name_en: req.query.c, breadcrumbs: req.breadcrumbs(), isNew: true, - camp: { type: '' }, + camp: { type: '', id: 'new' }, details: {} }); });