Skip to content

Commit

Permalink
Rough out downloadReports for downloadable report csvs
Browse files Browse the repository at this point in the history
  • Loading branch information
dcloud committed Mar 23, 2021
1 parent 8161178 commit da6681a
Show file tree
Hide file tree
Showing 5 changed files with 112 additions and 1 deletion.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
"statements": 90,
"functions": 90,
"branches": 81,
"lines": 90
"lines": 90
}
}
},
Expand Down Expand Up @@ -162,6 +162,7 @@
"cookie-session": "^1.4.0",
"cron": "^1.8.2",
"csv-parse": "^4.14.1",
"csv-stringify": "^5.6.2",
"cucumber-html-reporter": "^5.2.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
Expand Down
38 changes: 38 additions & 0 deletions src/routes/activityReports/handlers.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import stringify from 'csv-stringify/lib/sync';
import handleErrors from '../../lib/apiErrorHandler';
import SCOPES from '../../middleware/scopeConstants';
import ActivityReport from '../../policies/activityReport';
Expand All @@ -11,11 +12,13 @@ import {
setStatus,
activityReportAlerts,
activityReportByLegacyId,
getDownloadableActivityReports,
} from '../../services/activityReports';
import { goalsForGrants } from '../../services/goals';
import { userById, usersWithPermissions } from '../../services/users';
import { REPORT_STATUSES, DECIMAL_BASE } from '../../constants';
import { getUserReadRegions } from '../../services/accessValidation';
import activityReportToCsvRecord from '../../lib/transform';

const { APPROVE_REPORTS } = SCOPES;

Expand Down Expand Up @@ -294,3 +297,38 @@ export async function createReport(req, res) {
await handleErrors(req, res, error, logContext);
}
}

/**
* Download activity reports
*
* @param {*} req - request
* @param {*} res - response
*/
export async function downloadReports(req, res) {
try {
const readRegions = await getUserReadRegions(req.session.userId);
const reportsWithCount = await getDownloadableActivityReports(readRegions, req.query);
const { format = 'json' } = req.query;

if (!reportsWithCount) {
res.sendStatus(404);
} else if (format === 'csv') {
const { rows } = reportsWithCount;
const csvRows = await Promise.all(rows.map((r) => activityReportToCsvRecord(r)));
const csvData = stringify(
csvRows,
{
header: true,
quoted: true,
quoted_empty: true,
},
);
res.attachment('activity-reports.csv');
res.send(csvData);
} else {
res.json(reportsWithCount);
}
} catch (error) {
await handleErrors(req, res, error, logContext);
}
}
2 changes: 2 additions & 0 deletions src/routes/activityReports/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
reviewReport,
resetToDraft,
getLegacyReport,
downloadReports,
} from './handlers';

const router = express.Router();
Expand All @@ -26,6 +27,7 @@ router.get('/activity-recipients', getActivityRecipients);
router.get('/goals', getGoals);
router.get('/alerts', getReportAlerts);
router.get('/legacy/:legacyReportId', getLegacyReport);
router.get('/download', downloadReports);
router.get('/:activityReportId', getReport);
router.get('/', getReports);
router.put('/:activityReportId', saveReport);
Expand Down
65 changes: 65 additions & 0 deletions src/services/activityReports.js
Original file line number Diff line number Diff line change
Expand Up @@ -585,3 +585,68 @@ export async function possibleRecipients(regionId) {
});
return { grants, nonGrantees };
}

/**
* Fetches ActivityReports for downloading
* using sequelize.literal for several associated fields based on the following
* https://github.com/sequelize/sequelize/issues/11288
*
* @param {*} sortBy - field to sort by; default updatedAt
* @param {*} sortDir - order: either ascending or descending; default desc
* @returns {Promise<any>} - returns a promise with total reports count and the reports slice
*/
export async function getDownloadableActivityReports(readRegions, {
sortBy = 'updatedAt', sortDir = 'desc',
}) {
const regions = readRegions || [];

// TODO: What limits? multiple `id`s. Filters?
const result = await ActivityReport.findAndCountAll(
{
where: { regionId: regions, imported: null },
attributes: { exclude: ['imported', 'legacyId'] },
include: [
{
model: ActivityRecipient,
attributes: ['id', 'name', 'activityRecipientId', 'grantId', 'nonGranteeId'],
as: 'activityRecipients',
required: false,
include: [
{
model: Grant,
attributes: ['id', 'number'],
as: 'grant',
required: false,
include: [
{
model: Grantee,
as: 'grantee',
attributes: ['name'],
},
],
},
{
model: NonGrantee,
as: 'nonGrantee',
required: false,
},
],
},
{
model: User,
attributes: ['name', 'role', 'fullName', 'homeRegionId'],
as: 'author',
},
{
model: User,
attributes: ['id', 'name', 'role', 'fullName'],
as: 'collaborators',
through: { attributes: [] },
},
],
order: orderReportsBy(sortBy, sortDir),
distinct: true,
},
);
return result;
}
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3358,6 +3358,11 @@ csv-parse@^4.14.1:
resolved "https://registry.yarnpkg.com/csv-parse/-/csv-parse-4.15.3.tgz#8a62759617a920c328cb31c351b05053b8f92b10"
integrity sha512-jlTqDvLdHnYMSr08ynNfk4IAUSJgJjTKy2U5CQBSu4cN9vQOJonLVZP4Qo4gKKrIgIQ5dr07UwOJdi+lRqT12w==

csv-stringify@^5.6.2:
version "5.6.2"
resolved "https://registry.yarnpkg.com/csv-stringify/-/csv-stringify-5.6.2.tgz#e653783e2189c4c797fbb12abf7f4943c787caa9"
integrity sha512-n3rIVbX6ylm1YsX2NEug9IaPV8xRnT+9/NNZbrA/bcHgOSSeqtWla6XnI/xmyu57wIw+ASCAoX1oM6EZtqJV0A==

cucumber-html-reporter@^5.2.0:
version "5.3.0"
resolved "https://registry.yarnpkg.com/cucumber-html-reporter/-/cucumber-html-reporter-5.3.0.tgz#831d21e2ad64c10949bf2bab920343f1d01ef3ee"
Expand Down

0 comments on commit da6681a

Please sign in to comment.