Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 5x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | import { BadRequestException, Logger, NotFoundException } from '@nestjs/common';
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
import { InjectRepository } from '@nestjs/typeorm';
import { In, type Repository } from 'typeorm';
import { globalConfiguration, LtiGrant, LtiGrantDocument, LtiPlan, LtiPlanDocument } from '@amalia/core/models';
import { assert } from '@amalia/ext/typescript';
import {
EnrollmentWidgetType,
getLtiTemplateFileExtensionFromMimeType,
isLtiPlanDocumentPreviewable,
LtiDocumentMimeType,
type EnrollmentConfiguration,
type EnrollmentDocumentWidget,
type LtiPlanDocument as LtiPlanDocumentType,
} from '@amalia/lti/types';
import { CarboneService } from '@amalia/vendors/carbone';
import { CloudStorageDownloadService, CloudStorageUploadService } from '@amalia/vendors/google-cloud/cloud-storage';
import { GetLtiTemplateKeywordsUseCase } from '../use-cases/lti-document/shared/get-lti-template-keywords.use-case';
import { RebuildGrantDocumentsForUnsentGrantsCommand } from './rebuild-grant-documents-for-unsent-grants.command';
@CommandHandler(RebuildGrantDocumentsForUnsentGrantsCommand)
export class RebuildGrantDocumentsForUnsentGrantsCommandHandler implements ICommandHandler<RebuildGrantDocumentsForUnsentGrantsCommand> {
private readonly logger = new Logger(RebuildGrantDocumentsForUnsentGrantsCommandHandler.name);
public constructor(
@InjectRepository(LtiGrant)
private readonly ltiGrantRepository: Repository<LtiGrant>,
@InjectRepository(LtiGrantDocument)
private readonly ltiGrantDocumentRepository: Repository<LtiGrantDocument>,
@InjectRepository(LtiPlan)
private readonly ltiPlanRepository: Repository<LtiPlan>,
@InjectRepository(LtiPlanDocument)
private readonly ltiPlanDocumentRepository: Repository<LtiPlanDocument>,
private readonly getLtiTemplateKeywordsUseCase: GetLtiTemplateKeywordsUseCase,
private readonly carboneService: CarboneService,
private readonly cloudStorageDownloadService: CloudStorageDownloadService,
private readonly cloudStorageUploadService: CloudStorageUploadService,
) {}
public async execute(command: RebuildGrantDocumentsForUnsentGrantsCommand): Promise<void> {
const { companyId, planId, grantIds } = command.params;
const plan = await this.ltiPlanRepository.findOne({
where: { companyId, id: planId },
});
assert(plan, new NotFoundException(`LTI plan ${planId} not found.`));
const grants = await this.ltiGrantRepository.find({
where: { companyId, planId, id: In(grantIds) },
});
if (!grants.length) {
this.logger.debug({
message: 'No grants found to rebuild documents for.',
planId,
requestedGrantCount: grantIds.length,
});
return;
}
const missingGrantIds = grantIds.filter((id) => !grants.some((grant) => grant.id === id));
assert(!missingGrantIds.length, new NotFoundException(`LTI grants not found: ${missingGrantIds.join(', ')}`));
const sentGrantIds = grants.filter((grant) => grant.invitationSentAt !== null).map((grant) => grant.id);
assert(
!sentGrantIds.length,
new BadRequestException(
`Grant documents can only be rebuilt for unsent grants. Grants with sent invitations: ${sentGrantIds.join(
', ',
)}`,
),
);
const documentIds = this.extractDocumentIds(plan.enrollmentConfiguration);
await this.ltiGrantDocumentRepository.delete({
companyId,
grantId: In(grantIds),
});
if (!documentIds.length) {
this.logger.debug({ message: 'No documents to rebuild for unsent grants.', planId, grantCount: grantIds.length });
return;
}
const planDocuments = await this.ltiPlanDocumentRepository.find({
where: { companyId, planId, id: In(documentIds) },
});
const planDocumentMap = new Map<LtiPlanDocumentType['id'], LtiPlanDocument>(
planDocuments.map((document: LtiPlanDocument) => [document.id, document]),
);
const grantDocuments: Partial<LtiGrantDocument>[] = [];
for (const grant of grants) {
for (const documentId of documentIds) {
const grantDocument = await this.buildGrantDocument({
companyId,
documentId,
grant,
planDocument: planDocumentMap.get(documentId),
planId,
});
if (grantDocument) {
grantDocuments.push(grantDocument);
}
}
}
if (!grantDocuments.length) {
return;
}
await this.ltiGrantDocumentRepository.save(grantDocuments);
this.logger.log({
message: 'Rebuilt grant documents for unsent grants.',
planId,
grantCount: grantIds.length,
documentCount: documentIds.length,
totalRows: grantDocuments.length,
});
}
private extractDocumentIds(enrollmentConfiguration: EnrollmentConfiguration): LtiPlanDocumentType['id'][] {
const documentWidgets = enrollmentConfiguration.sections
.flatMap((section) => section.widgets)
.filter(
(widget): widget is EnrollmentDocumentWidget =>
widget.type === EnrollmentWidgetType.DOCUMENT && !!widget.documentId,
);
return [...new Set(documentWidgets.map((widget) => widget.documentId!))];
}
private async renderAndUploadGrantDocument({
companyId,
grant,
planDocument,
planId,
}: {
companyId: RebuildGrantDocumentsForUnsentGrantsCommand['params']['companyId'];
grant: LtiGrant;
planDocument: LtiPlanDocument;
planId: RebuildGrantDocumentsForUnsentGrantsCommand['params']['planId'];
}): Promise<LtiGrantDocument['fileUrl']> {
const fileName = planDocument.fileUrl.split('/').pop();
if (!fileName) {
throw new Error(`Plan document file name could not be determined for ${planDocument.id}`);
}
const templateBase64 = await this.cloudStorageDownloadService.getFileAsBase64(
{ id: companyId },
planId,
fileName,
globalConfiguration().gcp.storage.ltiDocuments,
);
const renderedPdf = await this.carboneService.renderTemplateToPdf({
templateExtension: getLtiTemplateFileExtensionFromMimeType(
planDocument.mimeType as Exclude<LtiDocumentMimeType, 'application/pdf'>,
),
data: await this.getLtiTemplateKeywordsUseCase.execute({
companyId,
planId,
participantUserId: grant.userId,
}),
reportName: `${planDocument.name}.pdf`,
template: Buffer.from(templateBase64, 'base64'),
});
return this.cloudStorageUploadService.uploadUInt8ArrayToBucket({ id: companyId }, renderedPdf, {
bucketName: globalConfiguration().gcp.storage.ltiDocuments,
folder: planId,
fileName: `${grant.id}-${planDocument.id}.pdf`,
contentType: 'application/pdf',
});
}
private async buildGrantDocument({
companyId,
documentId,
grant,
planDocument,
planId,
}: {
companyId: RebuildGrantDocumentsForUnsentGrantsCommand['params']['companyId'];
documentId: LtiPlanDocumentType['id'];
grant: LtiGrant;
planDocument?: LtiPlanDocument;
planId: RebuildGrantDocumentsForUnsentGrantsCommand['params']['planId'];
}): Promise<Partial<LtiGrantDocument> | null> {
if (!planDocument) {
this.logger.warn({ message: 'Plan document not found, skipping', documentId, planId });
return null;
}
// Static PDFs can still reuse the uploaded source file, they can't be personalized.
// DOCX/ODT templates must be rendered and personalized for each grant, so they always require a new file upload.
const fileUrl = isLtiPlanDocumentPreviewable(planDocument.mimeType)
? planDocument.fileUrl
: await this.renderAndUploadGrantDocument({ companyId, planId, grant, planDocument });
return {
companyId,
grantId: grant.id,
documentId,
fileUrl,
signedAt: null,
seenAt: null,
};
}
}
|