++ Projects

This commit is contained in:
Paolo Arena
2019-03-28 12:58:58 +01:00
parent efceb9915b
commit f4ad69674e
5 changed files with 329 additions and 2 deletions

132
server/models/project.js Normal file
View File

@@ -0,0 +1,132 @@
var mongoose = require('mongoose');
const _ = require('lodash');
const tools = require('../tools/general');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', process.env.DEBUG);
var ProjectSchema = new mongoose.Schema({
userId: {
type: String,
},
pos: {
type: Number,
},
descr: {
type: String,
},
priority: {
type: Number,
},
completed: {
type: Boolean,
default: false
},
created_at: {
type: Date
},
modify_at: {
type: Date
},
completed_at: {
type: Date
},
expiring_at: {
type: Date,
},
enableExpiring: {
type: Boolean,
default: false
},
id_prev: {
type: String,
},
progressCalc: {
type: Number,
},
modified: {
type: Boolean,
},
});
ProjectSchema.methods.toJSON = function () {
var Project = this;
var projObject = Project.toObject();
// console.log(projObject);
return _.pick(projObject, tools.allfieldTodoWithId());
};
ProjectSchema.statics.findByUserIdAndCat = function (userId, category) {
var Project = this;
return Project.find({
'userId': userId,
'category': category,
});
};
ProjectSchema.statics.findAllByUserIdAndCat = function (userId, category = '') {
var Project = this;
if (category === '') {
return Project.find({
'userId': userId,
}).then(ris => {
return tools.mapSort(ris)
})
} else {
return Project.find({
'userId': userId,
'category': category,
});
}
};
ProjectSchema.statics.getArrCategoryInTable = function (userId) {
var Project = this;
return Project.find({ 'userId': userId }).distinct("category")
.then(arrcategory => {
return arrcategory
})
};
ProjectSchema.statics.getAllProjects = async function (userId) {
var Project = this;
let obj = [];
obj.arrproj = await Project.findAllByUserIdAndCat(userId);
return obj;
};
ProjectSchema.pre('save', function (next) {
// var Project = this;
// console.log('Project.expiring_at', Project.expiring_at);
next();
});
var Project = mongoose.model('Projects', ProjectSchema);
module.exports = { Project };

View File

@@ -0,0 +1,176 @@
const express = require('express');
const router = express.Router();
const tools = require('../tools/general');
var server_constants = require('../tools/server_constants');
var { authenticate } = require('../middleware/authenticate');
// var mongoose = require('mongoose');
var { Project } = require('../models/project');
const _ = require('lodash');
const { ObjectID } = require('mongodb');
router.post('/', authenticate, (req, res) => {
var body = _.pick(req.body, tools.allfieldProjectWithId());
tools.mylogshow('PROJ INPUT', body);
var project = new Project(body);
// project.expiring_at = new Date(project.expiring_at);
tools.mylog('ID :', project._id, project.descr, project.userId, req.user._id);
if (!('descr' in req.body)) {
return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
}
if (String(project.userId) !== String(req.user._id)) {
// I'm trying to write something not mine!
tools.mylog('project.userId = ', project.userId, 'req.user._id', req.user._id);
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
tools.mylog('PROJECT POST :', project.descr, project._id);
project.modified = false;
if (!project.descr) {
console.log('RECORD NON VALIDO !?', req.body)
}
project.save().then((writeresult) => {
let idobj = writeresult._id;
Project.findById(idobj)
.then(record => {
tools.mylog('REC SAVED :', record.descr);
tools.sendNotificationToUser(project.userId, 'Project: ' + record.descr, record.descr, '/project/' + project.category, 'project')
.then(ris => {
if (ris) {
res.send({ record });
} else {
// already sent the error on calling sendNotificationToUser
}
})
})
}).catch((e) => {
console.log('ERRORE in PROJECT POST', e.message);
res.status(400).send(e);
});
});
router.patch('/:id', authenticate, (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, tools.allfieldProject());
tools.mylogshow('PATCH PROJECT: ', id)
if (!ObjectID.isValid(id)) {
tools.mylog('ERROR: id not VALID', id);
return res.status(404).send();
}
Project.findByIdAndUpdate(id, { $set: body }, { new: true }).then((project) => {
tools.mylogshow(' PROJECT TO MODIFY: ', project.descr, project.expiring_at);
if (!project) {
return res.status(404).send();
}
if (project.userId !== String(req.user._id)) {
// I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
project.modified = false;
tools.mylog('PATCH ', project.descr, project._id);
res.send({ project });
}).catch((e) => {
tools.mylogserr('Error patch PROJECT: ', e);
res.status(400).send();
})
});
router.get('/:userId', authenticate, (req, res) => {
var userId = req.params.userId;
// var category = req.params.category;
tools.mylog('GET PROJECTS : ', req.params);
if (!ObjectID.isValid(userId)) {
return res.status(404).send();
}
if (userId !== String(req.user._id)) {
// I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
// Extract all the projects of the userId only
// Project.findAllByUserIdAndCat(userId, category).then((projects) => {
Project.getAllProjects(userId).then((objprojects) => {
tools.mylog('projects', objprojects.arrproj.length);
objout = calcProjects(objprojects);
res.send({ projects: objout });
tools.mylog('objout', objout);
// res.send({ projects: objprojects.arrproj, categories: objprojects.arrcategories });
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
function calcProjects(obj) {
let myarr = tools.jsonCopy(obj.arrproj);
for (const indrec in myarr) {
// Calculate the Progression of the Project
// Find the todos for this project
// sum the progression
myarr[indrec].progressCalc = 1;
}
return myarr
}
router.delete('/:id', authenticate, (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Project.findByIdAndRemove(id).then((project) => {
if (!project) {
return res.status(404).send();
}
tools.mylog('DELETED ', project.descr, project._id);
res.send({ project });
}).catch((e) => {
res.status(400).send();
});
});
module.exports = router;

View File

@@ -81,11 +81,13 @@ router.patch('/:id', authenticate, (req, res) => {
Todo.findByIdAndUpdate(id, { $set: body }, { new: true }).then((todo) => { Todo.findByIdAndUpdate(id, { $set: body }, { new: true }).then((todo) => {
tools.mylogshow(' TODO TO MODIFY: ', todo.descr, todo.expiring_at);
if (!todo) { if (!todo) {
tools.mylogshow(' TODO NOT FOUND !: id:', id, 'body: ', body);
return res.status(404).send(); return res.status(404).send();
} }
tools.mylogshow(' TODO TO MODIFY: ', todo.descr, todo.expiring_at);
if (todo.userId !== String(req.user._id)) { if (todo.userId !== String(req.user._id)) {
// I'm trying to write something not mine! // I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }); return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
@@ -107,7 +109,7 @@ router.get('/:userId', authenticate, (req, res) => {
var userId = req.params.userId; var userId = req.params.userId;
// var category = req.params.category; // var category = req.params.category;
tools.mylog('GET : ', req.params); tools.mylog('GET TODOS : ', req.params);
if (!ObjectID.isValid(userId)) { if (!ObjectID.isValid(userId)) {
return res.status(404).send(); return res.status(404).send();

View File

@@ -25,6 +25,7 @@ if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test')
} }
require('./models/todo'); require('./models/todo');
require('./models/project');
require('./models/user'); require('./models/user');
require('./models/subscribers'); require('./models/subscribers');
require('./models/cfgserver'); require('./models/cfgserver');
@@ -35,6 +36,7 @@ const push_router = require('./router/push_router');
const subscribe_router = require('./router/subscribe_router'); const subscribe_router = require('./router/subscribe_router');
const email_router = require('./router/email_router'); const email_router = require('./router/email_router');
const todos_router = require('./router/todos_router'); const todos_router = require('./router/todos_router');
const projects_router = require('./router/projects_router');
const users_router = require('./router/users_router'); const users_router = require('./router/users_router');
const admin_router = require('./router/admin_router'); const admin_router = require('./router/admin_router');
@@ -83,6 +85,7 @@ app.use('/subscribe', subscribe_router);
app.use('/push', push_router); app.use('/push', push_router);
app.use('/email', email_router); app.use('/email', email_router);
app.use('/todos', todos_router); app.use('/todos', todos_router);
app.use('/projects', projects_router);
app.use('/users', users_router); app.use('/users', users_router);
app.use('/admin', admin_router); app.use('/admin', admin_router);

View File

@@ -57,6 +57,20 @@ module.exports = {
return ['_id', ...this.allfieldTodo()] return ['_id', ...this.allfieldTodo()]
}, },
// #TODO Projects++ Add fields ...
allfieldProject: function () {
return ['userId', 'pos', 'descr', 'priority', 'completed', 'created_at', 'modify_at',
'completed_at', 'expiring_at', 'enableExpiring', 'id_prev', 'progressCalc', 'modified']
},
allfieldProjectWithId: function () {
return ['_id', ...this.allfieldProject()]
},
jsonCopy(src) {
return JSON.parse(JSON.stringify(src))
},
sendBackNotif: function (subscription, payload) { sendBackNotif: function (subscription, payload) {
console.log('sendBackNotif:', subscription, payload); console.log('sendBackNotif:', subscription, payload);