%PDF- %PDF-
| Direktori : /home/opti/workflow/src/routes/ |
| Current File : /home/opti/workflow/src/routes/workflow.js |
var express = require('express');
var router = express.Router();
var bcrypt = require('bcrypt')
var formidable = require('formidable');
var fs = require('fs');
var path = require('path');
var con = require('../../config');
var secured = require('../middleware/login');
var db = require('../models');
//get all structures, it could be a get request but, post works fine
router.post('/get', function(req, res, next) {
db.Structure.all()
.then( structures=>{
res.json(structures);
})
});
//get method/route for sll structure list/view,
router.get('/', secured, function(req, res, next) {
// var orgId = 0;
var user = req.user;
let orgId = user.orgId ;
Work.findAll({ where: {orgId: orgId}, include: [{ all: true, nested: true }], order: [['parentId','ASC']] } ).then(structures => {
isOrganized = false;
if(structures.length > 0) { //structure not already organized
isOrganized =true;
}
console.log(structures[3])
res.render('structure/index', { user, structures: structures, isOrganized});
})
.catch(error => {
// Ooops, do some error-handling
console.log(error);
})
});
router.get('/:id', secured, async(req, res, next) => {
var user = req.user;
console.log(req.params.id)
const [ workflow ] = await Promise.all([
db.Workflow.findOne({where:{id:req.params.id, orgId:user.orgId}}),
]);
const [ requests ] = await Promise.all([
db.Request.findAll({where:{owner:user.id, workflowId:workflow.id,}, include:[{ all: true }]}),
]);
switch(req.params.id){
case "1":
return res.render('workflow/itRequest', {user, workflow, requests});
case "25":
return res.render('workflow/capitalExpenditureRequest', {user, workflow, requests});
}
});
router.post('/:id', secured, async(req, res, next) => {
var user = req.user;
// var [nextOfficer =
const [ workflow ] = await Promise.all([
db.Workflow.findOne({where:{id:req.params.id, orgId:user.orgId}}),
]);
const [targetedStructure] = await Promise.all([
db.CompanyStructure.findOne({where:{id:workflow.companyStructureId/* IT department*/, orgId:user.orgId}})
])
const [companyStructure] = await Promise.all([
db.CompanyStructure.findOne({where:{id:user.companyStructureId}})
])
// switch(req.params.id){
// case "1":
db.Request.create({serviceType:req.body.serviceType, title:req.body.title, description:req.body.description, amount:req.body.amount, justification:req.body.justification, owner:user.id, targetedStructure:targetedStructure.id, nextOfficer:companyStructure.headId, status:"New", workflowId:workflow.id})
.then(request=>{
// console.log(request);
if(request.workflowId == 1 )
var type = "IT Service Request";
else if(request.workflowId == 25)
var type = "Capital Expenditure Request";
//lets keep it in history
db.RequestHistory.create({requestId:request.id,updatedBy:user.id,status:request.status,message:user.firstName+" "+user.lastName+" made a new "+workflow.name});
//lets send notification
db.Notification.create({senderId:user.id,receiverId:companyStructure.headId,type,message:user.firstName+" "+user.lastName+" has made an "+workflow.name +" and needs your review",url:"/workflow/request/"+request.uuid,seen:0})
.then(()=>{})
// oh lets notify the assistant head also
db.Notification.create({senderId:user.id,receiverId:companyStructure.assistantId,type,message:user.firstName+" "+user.lastName+" has made an "+workflow.name+ " and needs your review",url:"/workflow/request/"+request.uuid,seen:0})
.then(notification =>{
return res.redirect(`/workflow/request/${request.uuid}`);
})
})
.catch(error=>console.log(error))
// }
});
router.get('/request/:uuid', secured, async(req, res, next) => {
var user = req.user;
// var [nextOfficer =
const [request] = await Promise.all([
db.Request.findOne({where:{uuid: req.params.uuid}, include:[{ all: true }]})
])
// console.log(request.id + " hegehehe")
switch(request.workflowId){
case 1:
return res.render('workflow/itRequestView', {user, request})
case 25:
return res.render('workflow/capitalExpenditureRequestView', {user, request})
}
// return res.render('workflow/itRequestView', {user, request})
// switch(req.params.id){
// case "1":
// db.Request.create({serviceType:req.body.serviceType, description:req.body.description, owner:user.id, targetedStructure:targetedStructure.id, nextOfficer:targetedStructure.headId, status:"New", workflowId:workflow.id})
// .then(request=>{
// // console.log(request);
// //lets keep it in history
// db.RequestHistory.create({requestId:request.id,updatedBy:user.id,status:request.status,message:user.firstName+" "+user.lastName+" made a new IT Service Request"});
// //lets send notification
// db.Notification.create({senderId:user.id,receiverId:targetedStructure.headId,type:"IT Service Request",message:user.firstName+" "+user.lastName+" has made an IT Service Request and needs your review",url:"/workflow/"+workflow.id,seen:0})
// .then(notification =>console.log(notification))
// // oh lets notify the assistant head also
// db.Notification.create({senderId:user.id,receiverId:targetedStructure.assistantId,type:"IT Service Request",message:user.firstName+" "+user.lastName+" has made an IT Service Request and needs your review",url:"/workflow/"+workflow.id+"/"+request.uuid,seen:0})
// .then(notification =>console.log(notification))
// })
// .catch(error=>console.log(error))
// return res.render('workflow', {user, workflow});
// }
});
router.get('/request/:uuid/:action', secured, async(req, res, next) => {
var user = req.user;
// var [nextOfficer =
const [request] = await Promise.all([
db.Request.findOne({where:{uuid: req.params.uuid}, include:[{ all: true }]})
])
const [workflow] = await Promise.all([
db.Workflow.findOne({where:{id: request.workflowId}, include:[{ all: true }]})
])
request.supervisorComment = req.body.supervisorComment;
if(request.workflowId == 1 )
var type = "IT Service Request";
else if(request.workflowId == 25)
var type = "Capital Expenditure Request";
switch(req.params.action){
case "1": //reject
request.status = "Rejected";
request.nextOfficer = request.owner;
request.save({fields:['supervisorComment','status','nextOfficer']})
.then(()=>{
db.RequestHistory.create({requestId:request.id,updatedBy:user.id,status:request.status,message:user.firstName+" "+user.lastName+" rejected "+workflow.name});
//lets send notification
db.Notification.create({senderId:user.id,receiverId:request.owner,type,message:user.firstName+" "+user.lastName+" has rejected your "+workflow.name,url:"/workflow/request/"+request.uuid,seen:0})
.then(notification =>console.log(notification));
req.flash('success', 'Request has been rejected!' );
res.redirect('/workflow/request/'+request.uuid)
});
break;
// case 2: //rework
// request.status = "To be reworked";
// request.save({fields:['supervisorComment','status']})
// .then(()=>{
// db.RequestHistory.create({requestId:request.id,updatedBy:user.id,status:request.status,message:user.firstName+" "+user.lastName+" returned IT Service Request for rework"});
// //lets send notification
// db.Notification.create({senderId:user.id,receiverId:request.owner,type:"IT Service Request",message:user.firstName+" "+user.lastName+" has returned your IT Service Request for rework",url:"/workflow/"+workflow.id+"/"+request.uuid,seen:0})
// .then(notification =>console.log(notification));
// req.flash('success', 'Request has been returned for rework!' );
// });
// break;
case "3": //approve
request.status = "Approved";
request.nextOfficer = request.structure.headId;
request.save({fields:['supervisorComment','status','nextOfficer']})
.then(()=>{
db.RequestHistory.create({requestId:request.id,updatedBy:user.id,status:request.status,message:user.firstName+" "+user.lastName+" Approved the Request!"});
//lets send notification
db.Notification.create({senderId:user.id,receiverId:request.owner,type,message:user.firstName+" "+user.lastName+" has Approved your "+type +" and it's now forwarded to "+request.structure.name+"!",url:"/workflow/request/"+request.uuid,seen:0})
.then(notification =>console.log(notification));
db.Notification.create({senderId:user.id,receiverId:request.structure.headId,type,message:user.firstName+" "+user.lastName+" has forwarded "+type+" approval to your office for review",url:"/workflow/request/"+request.uuid,seen:0})
.then(notification =>console.log(notification));
req.flash('success', `Request has been Approved and now forwarded to ${request.structure.name} !` );
res.redirect('/workflow/request/'+request.uuid)
});
break;
case "4": //approve
request.status = "Resolved";
request.nextOfficer = request.owner;
request.save({fields:['status','nextOfficer']})
.then(()=>{
db.RequestHistory.create({requestId:request.id,updatedBy:user.id,status:request.status,message:user.firstName+" "+user.lastName+" marked the Request resolved!"});
//lets send notification
db.Notification.create({senderId:user.id,receiverId:request.owner,type,message:user.firstName+" "+user.lastName+" has marked your "+type+" Resolved!",url:"/workflow/request/"+request.uuid,seen:0})
.then(notification =>{
console.log(notification);
});
// db.Notification.create({senderId:user.id,receiverId:request.owner,type,message:user.firstName+" "+user.lastName+" has marked your "+type+" Resolved!",url:"/workflow/request/"+request.uuid,seen:0})
// .then(notification =>{
// // console.log(notification);
// });
// db.Notification.create({senderId:user.id,receiverId:request.structure.headId,type:"IT Service Request",message:user.firstName+" "+user.lastName+" has forwarded an IT Service Request approval to your office for review",url:"/workflow/request/"+request.uuid,seen:0})
// .then(notification =>console.log(notification));
req.flash('success', `Request has been marked resolved!` );
res.redirect('/workflow/request/'+request.uuid)
});
break;
}
// switch(req.params.id){
// case "1":
// db.Request.create({serviceType:req.body.serviceType, description:req.body.description, owner:user.id, targetedStructure:targetedStructure.id, nextOfficer:targetedStructure.headId, status:"New", workflowId:workflow.id})
// .then(request=>{
// // console.log(request);
// //lets keep it in history
// db.RequestHistory.create({requestId:request.id,updatedBy:user.id,status:request.status,message:user.firstName+" "+user.lastName+" made a new IT Service Request"});
// //lets send notification
// db.Notification.create({senderId:user.id,receiverId:targetedStructure.headId,type:"IT Service Request",message:user.firstName+" "+user.lastName+" has made an IT Service Request and needs your review",url:"/workflow/"+workflow.id,seen:0})
// .then(notification =>console.log(notification))
// // oh lets notify the assistant head also
// db.Notification.create({senderId:user.id,receiverId:targetedStructure.assistantId,type:"IT Service Request",message:user.firstName+" "+user.lastName+" has made an IT Service Request and needs your review",url:"/workflow/"+workflow.id+"/"+request.uuid,seen:0})
// .then(notification =>console.log(notification))
// })
// .catch(error=>console.log(error))
// return res.render('workflow', {user, workflow});
// }
});
// save organization structure
router.post('/save_organization_structure', async(req, res, next) =>{
structure_ids = req.body.structure_ids;
structure_names = req.body.structure_names;
let orgId = req.user.orgId || 0;
await structure_names.forEach((element, index) => {
db.Structure.findOrCreate({where: {name: element} })
.spread((structure, created) => {
if(created)
structure_ids[index] = structure.id;
let parentId;
if(index == 0)
parentId = 0;
else
parentId = structure_ids[index-1]; //get previous element/structure id
OrganisationStructure.create({structureId:structure_ids[index], orgId, parentId})
.then(organisationStructure=>{
req.flash('success', 'Organization successfully Structured!' );
res.redirect('/structure');
})
.catch(error=>{
console.log(error)
});
// console.log(structure);
})
})
});
//get all parents, it could be a get request but, post works fine
router.post('/getParents', function(req, res, next) {
var parentStructureId = req.body.parentStructureId;
OrganisationStructure.findOne({where:{orgId:req.user.orgId,structureId:parentStructureId}})
.then(parent => {
db.CompanyStructure.findAll({where:{orgStructureId:parent.parentId}})
.then( companyStructures=>{
res.json(companyStructures);
})
})
});
//get for creating new company structure
router.get('/add', secured, function(req, res, next) {
// let orgId = 0;
let user = req.user;
OrganisationStructure.findAll({ where: {orgId: user.orgId}, include: [ db.Structure ], order: [['parentId','ASC']] } )
.then(structures => {
isOrganized = false;
if(structures.length > 0) { //structure not already organized
isOrganized =true;
}
Grade.findAll({where:{orgId:user.orgId}}).then(grades => {
res.render('structure/addStructure', { user, structures: structures, script: 'index',grades});
})
})
.catch(error => {
// Ooops, do some error-handling
console.log(error);
})
});
//get for creating new company structure
router.post('/add', secured, function(req, res, next) {
var form = new formidable.IncomingForm();
form.parse(req, async(err, fields, files) =>{
//TODO::form Validation
var user = req.user;
var orgId = user.orgId;
//create structure, head and assisattant
var salt = bcrypt.genSaltSync(10);
var password = bcrypt.hashSync("changeMe", salt);
avatar = saveFile(files.headImage);
//TODO::find a way to determine user branch
//create structure head
const [ head, assistant ] = await Promise.all([
User.create({firstName:fields.headFirstName,lastName:fields.headLastName,lastName:fields.headMiddleName,email:fields.headEmail,password,avatar,gradeId:fields.headGradeId}),
User.create({firstName:fields.assistantFirstName,lastName:fields.assistantLastName,lastName:fields.assistantMiddleName,email:fields.assistantEmail,password,avatar,gradeId:fields.assistantGradeId})
]);
// User.create({firstName:fields.headFirstName,lastName:fields.headLastName,email:fields.headEmail,password,avatar})
// .then(head=>{
// console.log("head "+head);
// })
db.CompanyStructure.create({orgId, orgStructureId:fields.organisationStructureId, parentStructureId:fields.structureParentId, name:fields.name, email: fields.email, createdBy: user.id, headId:head.id, assistantId:assistant.id} )
.then(structures => {
isOrganized = false;
// if(structures.length > 0) { //structure not already organized
// isOrganized =true;
// }
res.render('structure', { user, structures: structures});
})
.catch(error => {
// Ooops, do some error-handling
console.log(error);
})
})
});
function saveFile(file){
const name = `${Math.floor(Date.now() / 1000)}_${Math.round(Math.random() * 10000)}.${file.name.split('.').pop()}`;
const dest = path.join(__dirname, '..', 'public', 'assets', 'images', 'users', name);
const data = fs.readFileSync(file.path);
fs.writeFileSync(dest, data);
fs.unlinkSync(file.path);
// uploadInfo.fileSize = fileUpload.size;
// uploadInfo.fileType = fileUpload.type;
return name;
}
module.exports = router;