Skip to content

Commit

Permalink
remake exporting to csv filters fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
CarlosQ96 committed Jul 26, 2023
1 parent 3c781c5 commit 8756212
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 49 deletions.
3 changes: 2 additions & 1 deletion src/server/adminJs/adminJs-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,11 @@ export interface AdminJsProjectsQuery {
verified?: string;
// listed?: string;
isImported?: string;
reviewStatus: ReviewStatus;
reviewStatus?: ReviewStatus;
}

export interface AdminJsDonationsQuery {
id?: string;
projectId?: string;
contactEmail?: string;
referrerWallet?: string;
Expand Down
50 changes: 19 additions & 31 deletions src/server/adminJs/adminJs.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import adminJs, { AdminJSOptions } from 'adminjs';
import adminJs, { ActionContext, AdminJSOptions } from 'adminjs';
import { User } from '../../entities/user';
import adminJsExpress from '@adminjs/express';
import config from '../../config';
Expand Down Expand Up @@ -72,37 +72,25 @@ export const getAdminJsRouter = async () => {
);
};

// Express Middleware to save query of a search
export const adminJsQueryCache = async (req, res, next) => {
if (
req.url.startsWith('/admin/api/resources/') &&
req.headers.cookie.includes('adminbro')
) {
const admin = await getCurrentAdminJsSession(req);
if (!admin) return next(); // skip saving queries

const matches = req.url.match(/\/admin\/api\/resources\/(.+?)(\/|$)/);
if (!matches) return next(); // invalid URL

const resourceName = matches[1];
const queryStrings = {};

// Extract filter names and values from URL query string parameters
for (const key of Object.keys(req.query)) {
const [_, filter] = key.split('.');
if (!filter) continue;

queryStrings[filter] = req.query[key];
}
// Save query strings to Redis hash with an expiration
await redis.hset(
`adminbro:${admin.id}:${resourceName}`,
queryStrings,
'ex',
1800,
);
// Extract Referrer Header Parameter Filter Params
export const extractAdminJsReferrerUrlParams = (req: ActionContext) => {
const queryStrings = {};

const refererUrlHeaderIndex = req.rawHeaders.indexOf('Referer');
if (refererUrlHeaderIndex < 0) return {};

const refererUrl = new URL(req.rawHeaders[refererUrlHeaderIndex + 1]);
const searchParams = refererUrl.searchParams;

// Extract filter names and values from URL query string parameters
for (const [key, value] of searchParams.entries()) {
const [_, filter] = key.split('.');
if (!filter) continue;

queryStrings[filter] = value;
}
next();

return queryStrings;
};

// Get CurrentSession for external express middlewares
Expand Down
14 changes: 9 additions & 5 deletions src/server/adminJs/tabs/donationTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ import {
addDonationsSheetToSpreadsheet,
} from '../../../services/googleSheets';
import { SelectQueryBuilder } from 'typeorm';
import { ActionContext } from 'adminjs';
import { extractAdminJsReferrerUrlParams } from '../adminJs';

export const createDonation = async (
request: AdminJsRequestInterface,
Expand Down Expand Up @@ -186,6 +188,11 @@ export const buildDonationsQuery = (
.where('donation.amount > 0')
.addOrderBy('donation.createdAt', 'DESC');

if (queryStrings.id)
query.andWhere('donation.id = :id', {
id: queryStrings.id,
});

if (queryStrings.projectId)
query.andWhere('donation.projectId = :projectId', {
projectId: queryStrings.projectId,
Expand Down Expand Up @@ -250,16 +257,13 @@ export const buildDonationsQuery = (
};

export const exportDonationsWithFiltersToCsv = async (
_request: AdminJsRequestInterface,
_request: ActionContext,
_response,
context: AdminJsContextInterface,
) => {
try {
const { records } = context;
const rawQueryStrings = await redis.get(
`adminbro:${context.currentAdmin.id}:Donation`,
);
const queryStrings = rawQueryStrings ? JSON.parse(rawQueryStrings) : {};
const queryStrings = extractAdminJsReferrerUrlParams(_request);
const projectsQuery = buildDonationsQuery(queryStrings);
const projects = await projectsQuery.getMany();

Expand Down
10 changes: 4 additions & 6 deletions src/server/adminJs/tabs/projectsTab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
ReviewStatus,
RevokeSteps,
} from '../../../entities/project';
import adminJs from 'adminjs';
import adminJs, { ActionContext } from 'adminjs';
import {
canAccessProjectAction,
canAccessQfRoundAction,
Expand Down Expand Up @@ -62,6 +62,7 @@ import {
refreshProjectDonationSummaryView,
refreshProjectEstimatedMatchingView,
} from '../../../services/projectViewsService';
import { extractAdminJsReferrerUrlParams } from '../adminJs';

// add queries depending on which filters were selected
export const buildProjectsQuery = (
Expand Down Expand Up @@ -605,16 +606,13 @@ export const listDelist = async (
};

export const exportProjectsWithFiltersToCsv = async (
_request: AdminJsRequestInterface,
_request: ActionContext,
_response,
context: AdminJsContextInterface,
) => {
try {
const { records } = context;
const rawQueryStrings = await redis.get(
`adminbro:${context.currentAdmin.id}:Project`,
);
const queryStrings = rawQueryStrings ? JSON.parse(rawQueryStrings) : {};
const queryStrings = extractAdminJsReferrerUrlParams(_request);
const projectsQuery = buildProjectsQuery(queryStrings);
const projects = await projectsQuery.getMany();

Expand Down
7 changes: 1 addition & 6 deletions src/server/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,7 @@ import { runCheckPendingProjectListingCronJob } from '../services/cronJobs/syncP
import { runCheckProjectVerificationStatus } from '../services/cronJobs/checkProjectVerificationStatus';
import { webhookHandler } from '../services/transak/webhookHandler';

import {
adminJsQueryCache,
adminJsRootPath,
getAdminJsRouter,
} from './adminJs/adminJs';
import { adminJsRootPath, getAdminJsRouter } from './adminJs/adminJs';
import { redis } from '../redis';
import { logger } from '../utils/logger';
import { runNotifyMissingDonationsCronJob } from '../services/cronJobs/notifyDonationsWithSegment';
Expand Down Expand Up @@ -337,7 +333,6 @@ export async function bootstrap() {
);

// AdminJs!
app.use(adminJsQueryCache);
app.use(adminJsRootPath, await getAdminJsRouter());

if (!isTestEnv) {
Expand Down

0 comments on commit 8756212

Please sign in to comment.