Skip to content

Commit

Permalink
Merge pull request #97 from abhinovpankaj/main
Browse files Browse the repository at this point in the history
Add project report end point for uplaoding report to stroage and return url
  • Loading branch information
abhinovpankaj authored Oct 15, 2023
2 parents 74bb457 + 2ab3124 commit 68477d5
Show file tree
Hide file tree
Showing 12 changed files with 225 additions and 42 deletions.
Binary file modified Deck2AllData.docx
Binary file not shown.
Binary file modified DeckAllData.docx
Binary file not shown.
Binary file modified DeckProjectHeader.docx
Binary file not shown.
Binary file modified Wicr2AllData.docx
Binary file not shown.
Binary file modified WicrAllData.docx
Binary file not shown.
6 changes: 6 additions & 0 deletions database/mongo.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,14 @@ var Connect = async function () {
module.exports.Sections = client.db(dbName).collection('VisualSection');
module.exports.Users = client.db(dbName).collection('Users');
module.exports.ProjectDocuments = client.db(dbName).collection('ProjectDocuments');

module.exports.ProjectReports = client.db(dbName).collection('ProjectReports');
module.exports.InvasiveSections = client.db(dbName).collection('LocalInvasiveSection');
module.exports.ConclusiveSections = client.db(dbName).collection('LocalConclusiveSection');

module.exports.InvasiveSections = client.db(dbName).collection('InvasiveSection');
module.exports.ConclusiveSections = client.db(dbName).collection('ConclusiveSection');

// //module.exports.ClientInfo = db.collection('clientInfo');
console.log('Connected to MongoDB');
} catch (e) {
Expand Down
56 changes: 56 additions & 0 deletions model/projectReports.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"use strict";
const { ObjectId } = require('mongodb');
// var ObjectId = require('mongodb').ObjectId;
var mongo = require('../database/mongo');
const Role = require('./role');

var addProjectReport = function (projectReport, callback) {
mongo.ProjectReports.insertOne({project_id:projectReport.project_id,url: projectReport.url,name:projectReport.name,timestamp:projectReport.timestamp, uploader: projectReport.uploader}, {w: 1}, function (err, result) {
if (err) {
var error = new Error("addProjectReport()." + err.message);
error.status = err.status;
callback (error);
return;
}
callback(null, result);
});
};

var getProjectReportsbyProjectId = async function (project_id, callback) {

var result = mongo.ProjectReports.find({project_id: project_id});

const res = [];
for await (const doc of result){
res.push(doc);
}

if(res.length===0){
var error1 = new Error("getProjectReportsbyProjectId(). \nMessage: No Document Found.");
error1.status = 404;
callback (error1);
return;
}
callback(null, res);

};

var removeReport = async function (id, callback) {
var result = await mongo.ProjectReports.deleteOne({_id: ObjectId(id)});
if(result.deletedCount==1){
callback(null,{status:201,message:"Document deleted successfully."});
}
else{
var error2 = new Error("Error occurred. Didn't remove document. " + err.message);
error2.status = err.status;
callback (error2);
return;
}

};

module.exports = {
addProjectReport: addProjectReport,
getProjectReportsbyProjectId: getProjectReportsbyProjectId,
removeReport: removeReport
};
2 changes: 2 additions & 0 deletions routes.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const express = require("express");
var userRouter = require("./routes/user-endpoint");
var projectDocumentsRouter = require("./routes/projectdocuments-endpoint");
var projectReportsRouter = require("./routes/projectreports-endpoint");
var imageRouter = require("./routes/images-endpoint");
var projectRouter = require("./routes/project-endpoint");
var subprojectRouter = require("./routes/subproject-endpoint");
Expand All @@ -13,6 +14,7 @@ module.exports = function(app) {
app.use(express.json());
app.use("/api/user", userRouter);
app.use("/api/projectdocuments", projectDocumentsRouter);
app.use("/api/projectreports", projectReportsRouter);
app.use("/api/image", imageRouter);
app.use("/api/project", projectRouter);
app.use("/api/subproject", subprojectRouter);
Expand Down
97 changes: 57 additions & 40 deletions routes/project-endpoint.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ require("dotenv").config();
const multer = require('multer');
const upload = multer({ dest: path.join(__dirname, '..') });
const {v4 : uuidv4} = require('uuid');
var uploadBlob = require('../database/uploadimage');
const projectReports = require("../model/projectReports");

router.route('/add')
.post(async function (req, res) {
Expand Down Expand Up @@ -387,61 +389,76 @@ router.route('/generatereport')
const companyName = req.body.companyName;
const reportType = req.body.reportType;
const reportFormat = req.body.reportFormat;
const requestType = req.body.requestType;
// const requestType = req.body.requestType;
// const reportId = uuidv4();
// console.log(`reportID: ${reportId}`);
const projectName = req.body.projectName;
const uploader = req.body.user;
// const docpath = `${projectName}_${reportType}_${reportId}`;

if(requestType === 'init'){
const reportId = uuidv4();
const docpath = `${projectName}_${reportType}_${reportId}`;
generateProjectReport(projectId,sectionImageProperties,companyName,reportType, reportFormat, docpath);
res.status(200).send({reportId: reportId ,message: 'report generation started'});
} else{
const reportId = req.body.reportId;
const docpath = `${projectName}_${reportType}_${reportId}`;
console.log(docpath);
const now = new Date();
const timestamp = `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}-${now.getHours().toString().padStart(2, '0')}-${now.getMinutes().toString().padStart(2, '0')}-${now.getSeconds().toString().padStart(2, '0')}`;
const docpath = `${projectName}_${reportType}_${timestamp}`;
res.status(200).json({message: 'Generating report'});
await generateProjectReport(projectId,sectionImageProperties,companyName,reportType, reportFormat, docpath);
const absolutePath = path.resolve(`${docpath}.${reportFormat}`);
console.log(absolutePath);
reportFormat =='pdf'?res.setHeader('Content-Type', 'application/pdf'):
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');

res.setHeader('Content-Disposition', `attachment; filename="${docpath}"`);
res.sendFile(absolutePath, {}, (err) => {
if (err) {
console.error('Error sending file:', err);
return res.status(500).send('Error sending file');
} else {
console.log('Report sent successfully');
fs.unlinkSync(absolutePath);
const containerName = projectName;
const uploadOptions = {
metadata: {
'uploader': uploader,
},
tags: {
'project': containerName,
'owner': projectName
}
});
}
};
const newContainerName = containerName.replace(/\s+/g, '').toLowerCase();
const fileName = `${docpath}.${reportFormat}`
var result = await uploadBlob.uploadFile(newContainerName, fileName, absolutePath, uploadOptions);
var response = JSON.parse(result);
if (response.error) {
responseError = new ErrorResponse(500, 'Internal server error', result.error);
console.log(response);
// res.status(500).json(responseError);
return;
}
if (response.message) {
fs.unlinkSync(absolutePath);
//Update images Url
let url = response.url;
let project_id = projectId;
let name = projectName;
console.log(response);
let timestamp = (new Date(Date.now())).toISOString();
projectReports.addProjectReport({
project_id,
name,
url,
uploader,
timestamp
},function(err,result){
if (err) {
console.log(err)
}
if (result){
console.log(result)
}
});
console.log(projectId);
console.log('report uploaded');
}
// else
// res.status(409).json(response);



} catch (err) {
console.error('Error generating Report:', err);
return res.status(500).send('Error generating Report');
}
});

router.route('/getReportStatus')
.post(async function (req, res){
const reportId = req.body.reportId;
const reportType = req.body.reportType;
const projectName = req.body.projectName;
const reportFormat = req.body.reportFormat;
const filename = `${projectName}_${reportType}_${reportId}.${reportFormat}`;
const absolutePath = path.join(__dirname, '..',filename);
console.log(`Report file: ${absolutePath}`);
if (fs.existsSync(absolutePath)){
res.status(200).send({reportStatus: true});
}
else{
res.status(200).send({reportStatus: false});
}
})

router.route('/generatereporthtml').post(async function (req, res) {
try {
const projectId = req.body.id;
Expand Down
87 changes: 87 additions & 0 deletions routes/projectreports-endpoint.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"use strict";
var express = require('express');
var router = express.Router();

var path = require('path');
const projectReports = require("../model/projectReports");
var jwt = require('jsonwebtoken');
const Role=require('../model/role');

require("dotenv").config();

router.route('/add')
.post( function(req, res) {
try {
// Get document input
const { project_id, name, url, uploader } = req.body;
var timestamp = (new Date(Date.now())).toISOString();
// Validate document input
if (!(project_id && name && url)) {
res.status(400).send("All input is required");
}

// Create document in our database
projectReports.addProjectReport({
project_id,
name,
url,
uploader,
timestamp
},function(err,result){
if (err) {
res.status(err.status).send(err.message);
}
if (result){
res.status(201).json(result);
}
});

}catch (err) {
console.log(err);
}

});

router.route('/:project_id')
.get(async function(req,res){
try{
const project_id = req.params.project_id;
projectReports.getProjectReportsbyProjectId(project_id ,async function(err,records){
if (err) { res.status(err.status).send(err.message);
}
else {
if (records){
res.status(200).json(records);
}
else
res.status(401).send("reports not found.");
}
});
}
catch{
res.status(500).send("Internal server error.");
}
});

router.route('/delete')
.post(async function(req,res){
try {
// Get user input
const document = req.body;
projectReports.removeReport(document._id,function(err,result){
if(err){
res.status(err.status).send(err.message);
}
else{
res.status(result.status).send(result.message);
}
})

}
catch (err) {
console.log(err);
res.status(500).send(`Internal server error ${err}`)
}
});

module.exports = router ;
7 changes: 5 additions & 2 deletions service/reportstrategy/reportGeneration.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@ class ReportGeneration{
const promises = [];
const reportDocList = [];
project.data.item.projectHeader = this.getProjectHeader(reportType);
let projectHtml = ['projectheader.docx'];//ejs.render(template, project.data.item);
let projectHtml = ['projectheader.docx'];
//create project header docx
var template;
var createdBy='WICR Waterproofing & Construction';

if (companyName=='Wicr') {
template = fs.readFileSync('WicrProjectHeader.docx');
}else{
createdBy ='Deck Inspectors Inc.';
template = fs.readFileSync('DeckProjectHeader.docx');
}

Expand All @@ -38,7 +41,7 @@ class ReportGeneration{
name: project.data.item.name,
address: project.data.item.address,
description:project.data.item.description,
createdBy:companyName,
createdBy:createdBy,
createdAt : date.toLocaleString(),

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const conclusiveSections = require("../../../../model/conclusiveSections");
const blobManager = require("../../../../database/uploadimage");
const jo = require('jpeg-autorotate');


const generateDocReportForLocation = async function (locationId,companyName, sectionImageProperties, reportType,subprojectName='') {
try {
const sectionDataDoc =
Expand Down Expand Up @@ -210,6 +211,7 @@ const generateDocReportForLocation = async function (locationId,companyName, sec
furtherinvasive:sectionData.data.item.furtherinvasivereviewrequired=='True'?'Yes':'No',
conditionalassesment:sectionData.data.item.conditionalassessment=='Futureinspection'?'Future Inspection':sectionData.data.item.conditionalassessment,
additionalconsiderations:sectionData.data.item.additionalconsiderations,
//additionalconsiderationshtml:sectionData.data.item.additionalconsiderationshtml,
eee:sectionData.data.item.eee,
lbc:sectionData.data.item.lbc,
awe:sectionData.data.item.awe,
Expand Down Expand Up @@ -261,6 +263,16 @@ const getLocationDoc = async function(sectionId,template,sectionDocValues){

return tempArray;
},
// getadditionalconsiderations: ()=>{
// console.log('inside html fetch');
// // if (sectionDocValues.additionalconsiderationshtml===null ||sectionDocValues.additionalconsiderationshtml===undefined) {
// // return sectionDocValues.additionalconsiderations;
// // }else{
// return '<font face="Nunito"><b>This</b> is a Test <u>text in html</u> <font color="#e31c1c">format</font> with different <span>colors</span> and <i>combinations</i>.</font>';
// return sectionDocValues.additionalconsiderationshtml;

// //}
// },
tile: async (imageurl) => {

if (imageurl===undefined) {
Expand Down

0 comments on commit 68477d5

Please sign in to comment.