|
| 1 | +'use strict'; |
| 2 | +const { |
| 3 | + getAccessToken, |
| 4 | + getData, |
| 5 | + handleExceptionResponse |
| 6 | +} = require('../utils'); |
| 7 | +const HttpStatus = require('http-status-codes'); |
| 8 | +const config = require('../../config'); |
| 9 | +const log = require('../logger'); |
| 10 | +const {doesSchoolBelongToDistrict} = require('../institute-cache'); |
| 11 | + |
| 12 | + |
| 13 | +async function downloadPsiSelectionReport(req, res) { |
| 14 | + try { |
| 15 | + console.log(req.params.schoolID); |
| 16 | + if(req.session.activeInstituteType === 'DISTRICT'){ |
| 17 | + if(!doesSchoolBelongToDistrict(req.params.schoolID, req.session.activeInstituteIdentifier)){ |
| 18 | + return res.status(HttpStatus.CONFLICT).json({ |
| 19 | + status: HttpStatus.CONFLICT, |
| 20 | + message: 'The school is not within your district. The report cannot be accessed.' |
| 21 | + }); |
| 22 | + } else { |
| 23 | + return res.status(HttpStatus.CONFLICT).json({ |
| 24 | + status: HttpStatus.CONFLICT, |
| 25 | + message: 'This report is only available to schools.' |
| 26 | + }); |
| 27 | + } |
| 28 | + }else if(req.session.activeInstituteType === 'SCHOOL'){ |
| 29 | + if(req.params.schoolID !== req.session.activeInstituteIdentifier){ |
| 30 | + return res.status(HttpStatus.CONFLICT).json({ |
| 31 | + status: HttpStatus.CONFLICT, |
| 32 | + message: 'Your school is not your school. The report cannot be accessed.' |
| 33 | + }); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + |
| 38 | + const token = getAccessToken(req); |
| 39 | + |
| 40 | + let url = `${config.get('psiSelection:rootURL')}/report/school/${req.params.schoolID}`; |
| 41 | + |
| 42 | + const resData = await getData(token, url); |
| 43 | + const fileDetails = getFileDetails('psi', null, null); |
| 44 | + |
| 45 | + setResponseHeaders(res, fileDetails); |
| 46 | + const buffer = Buffer.from(resData.documentData, 'base64'); |
| 47 | + return res.status(HttpStatus.OK).send(buffer); |
| 48 | + } catch (e) { |
| 49 | + log.error('downloadPsiReport Error', e.stack); |
| 50 | + return handleExceptionResponse(e, res); |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +function setResponseHeaders(res, { filename, contentType }) { |
| 55 | + res.setHeader('Content-Disposition', `attachment; filename=${filename}`); |
| 56 | + res.setHeader('Content-Type', contentType); |
| 57 | +} |
| 58 | + |
| 59 | + |
| 60 | +function getFileDetails(reportType) { |
| 61 | + const mappings = { |
| 62 | + |
| 63 | + 'DEFAULT': { filename: 'download.csv', contentType: 'text/csv' } |
| 64 | + }; |
| 65 | + return mappings[reportType] || mappings['DEFAULT']; |
| 66 | +} |
| 67 | + |
| 68 | +module.exports = { |
| 69 | + downloadPsiSelectionReport |
| 70 | +}; |
| 71 | + |
0 commit comments