-
Notifications
You must be signed in to change notification settings - Fork 5
/
uploads.ts
486 lines (448 loc) · 13.3 KB
/
uploads.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import { Prisma } from '@prisma/client'
import type { Organization, ReportingPeriod } from '@prisma/client'
import cloneDeep from 'lodash/cloneDeep'
import type {
QueryResolvers,
MutationResolvers,
ResolversTypes,
UploadRelationResolvers,
} from 'types/graphql'
import { v4 as uuidv4 } from 'uuid'
import { RedwoodError } from '@redwoodjs/api'
import { CurrentUser } from 'src/lib/auth'
import { hasRole } from 'src/lib/auth'
import {
s3UploadFilePutSignedUrl,
getSignedUrl,
getS3UploadFileKey,
startStepFunctionExecution,
} from 'src/lib/aws'
import { ROLES } from 'src/lib/constants'
import { db } from 'src/lib/db'
import { logger } from 'src/lib/logger'
import { ValidationError } from 'src/lib/validation-error'
interface WhereInputs {
agency: { id?: number; organizationId: number }
}
export const uploads: QueryResolvers['uploads'] = () => {
const currentUser = context.currentUser
const whereInputs: WhereInputs = {
agency: {
organizationId: currentUser.agency.organizationId,
},
}
if (hasRole(ROLES.ORGANIZATION_STAFF)) {
whereInputs.agency = { ...whereInputs.agency, id: currentUser.agency.id }
}
return db.upload.findMany({
where: whereInputs,
orderBy: { createdAt: 'desc' },
})
}
export const upload: QueryResolvers['upload'] = ({ id }) => {
return db.upload.findUnique({
where: { id },
})
}
export const createUpload: MutationResolvers['createUpload'] = async ({
input,
}) => {
const inputWithContext: Prisma.UploadUncheckedCreateInput = {
...input,
uploadedById: context.currentUser.id,
}
const upload = await db.upload.create({
data: inputWithContext,
})
// We don't need to store the result of the validation creation, it will be provided via
// the relation resolver below
await db.uploadValidation.create({
data: {
uploadId: upload.id,
initiatedById: upload.uploadedById,
passed: false,
isManual: false,
results: null,
},
})
const signedUrl = await s3UploadFilePutSignedUrl(
upload,
upload.id,
context.currentUser.agency.organizationId
)
return { ...upload, signedUrl }
}
export const updateUpload: MutationResolvers['updateUpload'] = ({
id,
input,
}) => {
return db.upload.update({
data: input,
where: { id },
})
}
export const deleteUpload: MutationResolvers['deleteUpload'] = ({ id }) => {
// 1. delete any upload validations
db.uploadValidation.deleteMany({
where: { uploadId: id },
})
// remove object from s3
const upload = db.upload.findUnique({
where: { id },
include: { agency: true },
})
if (!upload) {
throw new ValidationError(`Upload with id ${id} not found`)
}
// TODO: fix aws permissions issue on ECS instance. For now, we'll just log the delete
// deleteUploadFile(upload)
logger.info({ upload_id: id }, 'deleted database record for upload')
// 2. delete the upload
return db.upload.delete({
where: { id },
})
}
export const downloadUploadFile: MutationResolvers['downloadUploadFile'] =
async ({ id }) => {
const upload = await db.upload.findUnique({
where: { id },
include: { agency: true },
})
if (!upload) {
throw new ValidationError(`Upload with id ${id} not found`)
}
logger.info(`Downloading file for upload ${id}`)
const signedUrl = await getSignedUrl(upload)
return signedUrl
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export const Upload: UploadRelationResolvers = {
uploadedBy: (_obj, { root }) => {
return db.upload.findUnique({ where: { id: root?.id } }).uploadedBy()
},
agency: (_obj, { root }) => {
return db.upload.findUnique({ where: { id: root?.id } }).agency()
},
reportingPeriod: (_obj, { root }) => {
return db.upload.findUnique({ where: { id: root?.id } }).reportingPeriod()
},
expenditureCategory: (_obj, { root }) => {
return db.upload
.findUnique({ where: { id: root?.id } })
.expenditureCategory()
},
validations: (_obj, { root }) => {
return db.upload.findUnique({ where: { id: root?.id } }).validations()
},
latestValidation: async (_obj, { root }) => {
const latestValidation = await db.uploadValidation.findFirst({
where: { uploadId: root?.id },
orderBy: {
createdAt: 'desc',
},
})
return latestValidation
},
seriesUploads: async (
_obj,
{ root }
): Promise<ResolversTypes['Upload'][]> => {
return db.upload.findMany({
where: {
AND: {
agencyId: root?.agencyId,
expenditureCategoryId: root?.expenditureCategoryId,
reportingPeriodId: root?.reportingPeriodId,
},
},
orderBy: {
createdAt: 'desc',
},
})
},
}
type UploadsWithValidationsAndExpenditureCategory = Prisma.UploadGetPayload<{
include: { validations: true; expenditureCategory: true }
}>
type ExpenditureCategoryCode = string
type AgencyId = number
type OrganizationObj = {
id: number
preferences: {
current_reporting_period_id: number
}
}
type UserObj = {
email: string
id: number
}
type UploadPayload = {
objectKey: string
filename: string
createdAt: Date
}
type UploadInfoForProject = {
organization: OrganizationObj
user: UserObj
outputTemplateId: number
ProjectType: string
uploadsToAdd: Partial<Record<AgencyId, UploadPayload>>
uploadsToRemove: Partial<Record<AgencyId, UploadPayload>>
forceRegenerate: boolean
}
type InfoForSubrecipient = {
organization: OrganizationObj
user: UserObj
outputTemplateId: number
}
type InfoForArchive = {
organization: OrganizationObj
}
type InfoForEmail = {
organization: OrganizationObj
user: UserObj
}
/*
This type should be similar to the following python class:
class ProjectLambdaPayload(BaseModel):
*/
export type ProjectLambdaPayload = Record<
ExpenditureCategoryCode,
UploadInfoForProject
>
export type SubrecipientLambdaPayload = Record<
'Subrecipient',
InfoForSubrecipient
>
export type CreateArchiveLambdaPayload = Record<'zip', InfoForArchive>
export type EmailLambdaPayload = Record<'email', InfoForEmail>
export const getUploadsByExpenditureCategory = async (
organization: Organization,
reportingPeriod: ReportingPeriod,
regenerate = false
): Promise<ProjectLambdaPayload> => {
const validUploadsInPeriod: UploadsWithValidationsAndExpenditureCategory[] =
await getValidUploadsInCurrentPeriod(organization, reportingPeriod)
const commonData = {
organization: {
id: organization.id,
preferences: {
current_reporting_period_id:
organization.preferences['current_reporting_period_id'],
},
},
user: {
email: context.currentUser.email,
id: context.currentUser.id,
},
outputTemplateId: reportingPeriod.outputTemplateId,
uploadsToAdd: {},
uploadsToRemove: {},
forceRegenerate: regenerate,
}
const uploadsByEC: ProjectLambdaPayload = {
'1A': { ...cloneDeep(commonData), ProjectType: '1A' },
'1B': { ...cloneDeep(commonData), ProjectType: '1B' },
'1C': { ...cloneDeep(commonData), ProjectType: '1C' },
}
// Get the most recent upload for each expenditure category and agency and set the S3 Object key
for (const upload of validUploadsInPeriod) {
const uploadPayload: UploadPayload = {
objectKey: await getS3UploadFileKey(organization.id, upload),
createdAt: upload.createdAt,
filename: upload.filename,
}
if (
!uploadsByEC[upload.expenditureCategory.code].uploadsToAdd[
upload.agencyId
]
) {
// The agency was never added. This is the time to initialize it.
uploadsByEC[upload.expenditureCategory.code].uploadsToAdd[
upload.agencyId
] = uploadPayload
continue
}
// If the current upload is newer than the one stored, replace it
if (
upload.createdAt >
uploadsByEC[upload.expenditureCategory.code].uploadsToAdd[upload.agencyId]
.createdAt
) {
uploadsByEC[upload.expenditureCategory.code].uploadsToAdd[
upload.agencyId
] = uploadPayload
}
}
return uploadsByEC
}
export const getValidUploadsInCurrentPeriod = async (
organization: Organization,
reportingPeriod: ReportingPeriod
): Promise<UploadsWithValidationsAndExpenditureCategory[]> => {
/* Step 1: Identify uploads in the given reporting period */
const uploadsInPeriod = await db.upload.findMany({
where: {
reportingPeriodId: reportingPeriod.id,
agency: { organizationId: organization.id },
},
include: { validations: true, expenditureCategory: true },
})
/* Step 2: Filter out uploads whose latest validation is not passed */
const validUploadsInPeriod = uploadsInPeriod.filter((upload) => {
const latestValidation = upload.validations.reduce((latest, current) =>
current.createdAt > latest.createdAt ? current : latest
)
return latestValidation.passed
})
return validUploadsInPeriod
}
export const getSubrecipientLambdaPayload = async (
organization: Organization,
user: CurrentUser,
reportingPeriod: ReportingPeriod
): Promise<SubrecipientLambdaPayload> => {
return {
Subrecipient: {
organization: {
id: organization.id,
preferences: {
current_reporting_period_id:
organization.preferences['current_reporting_period_id'],
},
},
user: {
email: user.email,
id: user.id,
},
outputTemplateId: reportingPeriod.outputTemplateId,
},
}
}
export const getCreateArchiveLambdaPayload = async (
organization: Organization
): Promise<CreateArchiveLambdaPayload> => {
return {
zip: {
organization: {
id: organization.id,
preferences: {
current_reporting_period_id:
organization.preferences['current_reporting_period_id'],
},
},
},
}
}
export const getEmailLambdaPayload = async (
organization: Organization,
user: CurrentUser
): Promise<EmailLambdaPayload> => {
return {
email: {
organization: {
id: organization.id,
preferences: {
current_reporting_period_id:
organization.preferences['current_reporting_period_id'],
},
},
user: {
email: user.email,
id: user.id,
},
},
}
}
export const generateTreasuryReport: MutationResolvers['generateTreasuryReport'] =
async ({ regenerate }) => {
try {
const organization = await db.organization.findFirst({
where: { id: context.currentUser.agency.organizationId },
})
const reportingPeriod = await db.reportingPeriod.findFirst({
where: { id: organization.preferences['current_reporting_period_id'] },
})
const projectLambdaPayload: ProjectLambdaPayload =
await getUploadsByExpenditureCategory(
organization,
reportingPeriod,
regenerate
)
const subrecipientLambdaPayload: SubrecipientLambdaPayload =
await getSubrecipientLambdaPayload(
organization,
context.currentUser,
reportingPeriod
)
const createArchiveLambdaPayload: CreateArchiveLambdaPayload =
await getCreateArchiveLambdaPayload(organization)
const emailLambdaPayload: EmailLambdaPayload =
await getEmailLambdaPayload(organization, context.currentUser)
const input = {
'1A': {},
'1B': {},
'1C': {},
Subrecipient: {},
zip: {},
email: {},
...projectLambdaPayload,
...subrecipientLambdaPayload,
...createArchiveLambdaPayload,
...emailLambdaPayload,
}
await startStepFunctionExecution(
process.env.TREASURY_STEP_FUNCTION_ARN,
`Force-kick-off-${uuidv4()}`,
JSON.stringify(input)
)
return true
} catch (error) {
logger.error(error, 'Error sending Treasury Report')
throw new RedwoodError(error.message)
}
}
export const sendTreasuryReport: MutationResolvers['sendTreasuryReport'] =
async () => {
try {
const organization = await db.organization.findFirst({
where: { id: context.currentUser.agency.organizationId },
})
const reportingPeriod = await db.reportingPeriod.findFirst({
where: { id: organization.preferences['current_reporting_period_id'] },
})
const projectLambdaPayload: ProjectLambdaPayload =
await getUploadsByExpenditureCategory(organization, reportingPeriod)
const subrecipientLambdaPayload: SubrecipientLambdaPayload =
await getSubrecipientLambdaPayload(
organization,
context.currentUser,
reportingPeriod
)
const createArchiveLambdaPayload: CreateArchiveLambdaPayload =
await getCreateArchiveLambdaPayload(organization)
const emailLambdaPayload: EmailLambdaPayload =
await getEmailLambdaPayload(organization, context.currentUser)
const input = {
'1A': {},
'1B': {},
'1C': {},
Subrecipient: {},
zip: {},
email: {},
...projectLambdaPayload,
...subrecipientLambdaPayload,
...createArchiveLambdaPayload,
...emailLambdaPayload,
}
await startStepFunctionExecution(
process.env.TREASURY_STEP_FUNCTION_ARN,
`Force-kick-off-${uuidv4()}`,
JSON.stringify(input)
)
return true
} catch (error) {
logger.error(error, 'Error sending Treasury Report')
throw new RedwoodError(error.message)
}
}