Skip to content

Commit

Permalink
Merge branch 'main' into authorization
Browse files Browse the repository at this point in the history
  • Loading branch information
mgtennant committed Apr 16, 2024
2 parents 83b8b03 + 5ba03c6 commit 5044524
Show file tree
Hide file tree
Showing 24 changed files with 337 additions and 332 deletions.
31 changes: 7 additions & 24 deletions backend/src/admin/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,21 +61,17 @@ export class AdminController {
});
}



@Get('preview-template/:id')
async previewTemplate(@Param('id') id: number, @Res() res) {
try {
const dtObject = await this.adminService.downloadTemplate(id);
const base64Data = dtObject.the_file;
const pdfBuffer = await this.adminService.convertDocxToPdfBuffer(base64Data);
const pdfBuffer = await this.adminService.getPreviewPdf(id);
const streamableFile = new stream.PassThrough();
streamableFile.end(pdfBuffer);
res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=file.pdf',
});
streamableFile.pipe(res);
streamableFile.end(pdfBuffer);
res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename=file.pdf',
});
streamableFile.pipe(res);
} catch (error) {
console.error('Error:', error);
res.status(500).send('Internal Server Error');
Expand Down Expand Up @@ -144,14 +140,6 @@ export class AdminController {
return { message: 'Template uploaded successfully' };
}

// @Post('upload-template')
// @UseInterceptors(FileInterceptor('file'))
// async uploadTemplate(@UploadedFile() file: Express.Multer.File, @Body() body: any) {
// console.log(file); // Check if the file is received correctly
// console.log(body); // Log the body to see if other data is as expected
// return { message: 'Debugging' };
// }

/**
* Used for an AJAX route to render all admins in a datatable
* @returns altered admin object array
Expand Down Expand Up @@ -200,11 +188,6 @@ export class AdminController {
return this.adminService.removeAdmin(input.idirUsername);
}

// @Get('templates/:reportId')
// getTemplates(@Param('reportId') reportId: number): Promise<any> {
// return this.adminService.getTemplates(reportId);
// }

@Get('open-document/:document_id')
setSessionDocument(@Session() session: { data?: SessionData }, @Param('document_id') documentId: number): void {
session.data.selected_document = { document_id: documentId };
Expand Down
77 changes: 41 additions & 36 deletions backend/src/admin/admin.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,9 @@ import { DocumentTemplateService } from 'src/document_template/document_template
import { ProvisionService } from 'src/provision/provision.service';
import { DocumentTypeService } from 'src/document_type/document_type.service';
import { DocumentType } from 'src/document_type/entities/document_type.entity';
import * as fs from 'fs';
import * as mammoth from 'mammoth';
import * as PDFDocument from 'pdfkit';
import * as pdf from 'html-pdf';

import { TTLSService } from 'src/ttls/ttls.service';

const axios = require('axios');
const FormData = require('form-data');

dotenv.config();
let hostname: string;
Expand All @@ -23,6 +18,7 @@ let port: number;
export class AdminService {
constructor(
private readonly httpService: HttpService,
private readonly ttlsService: TTLSService,
private readonly documentTemplateService: DocumentTemplateService,
private readonly provisionService: ProvisionService,
private readonly documentTypeService: DocumentTypeService
Expand Down Expand Up @@ -364,35 +360,44 @@ export class AdminService {
return header + csvRows.join('\n');
}

async convertDocxToPdfBuffer(base64Data: string): Promise<Buffer> {
// Decode base64 string
const buffer = Buffer.from(base64Data, 'base64');

// Write buffer to temporary file
const tempFilePath = './temp.docx';
fs.writeFileSync(tempFilePath, buffer);

// Convert DOCX to HTML
const { value } = await mammoth.convertToHtml({ path: tempFilePath });
const htmlContent = value;

// Set options for html-pdf
const options: pdf.CreateOptions = {
format: 'Letter', // Set the PDF format (e.g., 'A4', 'Letter', etc.)
base: `file://${__dirname}/`, // Set the base path for local file references
};
async getPreviewPdf(id: number): Promise<Buffer> {
const cdogsToken = await this.ttlsService.callGetToken();
const documentTemplateObject = await this.documentTemplateService.findOne(id);

const bufferBase64 = documentTemplateObject.the_file;
const data = {};
const md = JSON.stringify({
data,
formatters:
'{"myFormatter":"_function_myFormatter|function(data) { return data.slice(1); }","myOtherFormatter":"_function_myOtherFormatter|function(data) {return data.slice(2);}"}',
options: {
cacheReport: false,
convertTo: 'pdf',
overwrite: true,
reportName: 'ticdi-report',
},
template: {
content: `${bufferBase64}`,
encodingType: 'base64',
fileType: 'docx',
},
});

return new Promise<Buffer>((resolve, reject) => {
// Convert HTML to PDF
pdf.create(htmlContent, options).toBuffer((err, buffer) => {
if (err) {
reject(err);
} else {
// Remove temporary file
fs.unlinkSync(tempFilePath);
resolve(buffer);
}
});
});
}
const conf = {
method: 'post',
url: process.env.cdogs_url,
headers: {
Authorization: `Bearer ${cdogsToken}`,
'Content-Type': 'application/json',
},
responseType: 'arraybuffer',
data: md,
};
const ax = require('axios');
const response = await ax(conf).catch((error) => {
console.log(error.response);
});
console.log('time - ' + Date.now());
return response.data;
}
}
18 changes: 1 addition & 17 deletions backend/src/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,8 @@
import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import { DataSource } from 'typeorm';

@Injectable()
export class AppService {
constructor(private dataSource: DataSource) {}

async initializeDb() {
const queryRunner = this.dataSource.createQueryRunner();
// Check if there are already provisions/groups/variants in the db
const [provisionCount] = await queryRunner.query('SELECT COUNT(*) FROM provision');
const [groupCount] = await queryRunner.query('SELECT COUNT(*) FROM provision_group');
const [documentType] = await queryRunner.query('SELECT COUNT(*) FROM document_type');
// If there is no data in any of the tables, run the SQL script
if (provisionCount.count == 0 && groupCount.count == 0 && documentType.count == 0) {
const sql = fs.readFileSync('./utils/db/init-db.sql', 'utf8');
await queryRunner.query(sql);
await queryRunner.release();
}
}
constructor() {}

getHello(): string {
return 'Hello Backend!';
Expand Down
2 changes: 1 addition & 1 deletion backend/src/document_data/document_data.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ export class DocumentDataService {
}

// helper function for getProvisionsByDocTypeIdAndDtid
async getDocumentDataVariables(document_type_id, dtid: number): Promise<DocumentDataVariable[]> {
async getDocumentDataVariables(document_type_id: number, dtid: number): Promise<DocumentDataVariable[]> {
const documentData: DocumentData = await this.documentDataRepository.findOne({
where: { dtid: dtid, document_type: { id: document_type_id } },
relations: ['document_data_provisions'],
Expand Down
3 changes: 0 additions & 3 deletions backend/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { AppService } from './app.service';

async function bootstrap() {
const app = await NestFactory.create(AppModule);
Expand All @@ -15,8 +14,6 @@ async function bootstrap() {

const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
const appService = app.get(AppService);
// await appService.initializeDb();

await app.listen(process.env.ticdi_environment == 'DEVELOPMENT' ? 3001 : 3000);
}
Expand Down
4 changes: 2 additions & 2 deletions backend/src/ormconfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { ProvisionVariable } from './provision/entities/provision_variable.entit
import { DocumentTypeProvision } from './provision/entities/document_type_provision';

const config: TypeOrmModuleOptions = {
logging: true,
logging: ['error'],
type: 'postgres',
host: process.env.POSTGRESQL_HOST || 'localhost',
port: 5432,
Expand All @@ -30,7 +30,7 @@ const config: TypeOrmModuleOptions = {
DocumentType,
DocumentTypeProvision,
],
synchronize: true,
synchronize: false,
};

export default config;
9 changes: 5 additions & 4 deletions backend/src/provision/provision.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ export class ProvisionController {
return this.provisionService.findAllVariables();
}

@Get('variables-by-doc-type/:document_type_id')
findVariablesByDocType(@Param('document_type_id') document_type_id: number) {
return this.provisionService.findVariablesByDocType(+document_type_id);
}

@Post('add')
addProvision(
@Body()
Expand Down Expand Up @@ -149,10 +154,6 @@ export class ProvisionController {

@Post('update-manage-doc-type-provisions')
updateManageDocTypeProvisions(@Body() data: { document_type_id: number; provisions: ManageDocTypeProvision[] }) {
console.log('~~~~~~');
console.log(data.document_type_id);
console.log(data.provisions);
console.log('~~~~~~');
return this.provisionService.updateManageDocTypeProvisions(data.document_type_id, data.provisions);
}
}
24 changes: 23 additions & 1 deletion backend/src/provision/provision.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,28 @@ export class ProvisionService {
});
}

async findVariablesByDocType(document_type_id: number): Promise<any[]> {
console.log('document_type_id: ' + document_type_id);
const variables = await this.provisionVariableRepository.find({
relations: ['provision'],
});
const documentTypeProvisions = await this.documentTypeProvisionRepository.find({
where: { associated: true },
relations: ['provision', 'document_type'],
});
const filteredDtps = documentTypeProvisions.filter((dtp) => dtp.document_type.id === document_type_id);
const docTypeProvisionIds = filteredDtps.map((dtp) => dtp.provision.id);
const associatedVariables = variables
.filter((variable) => docTypeProvisionIds.includes(variable.provision.id))
.map((variable) => {
return {
...variable,
provision_id: variable.provision.id,
};
});
return associatedVariables;
}

// old route to be deleted
async getProvisionsByDocumentTypeId(document_type_id: number): Promise<Provision[]> {
const provisions: Provision[] = await this.provisionRepository
Expand Down Expand Up @@ -279,7 +301,7 @@ export class ProvisionService {
update_timestamp: string;
};
const docTypeProvisions = await this.documentTypeProvisionRepository.find({
where: { document_type: { id: document_type_id } },
where: { document_type: { id: document_type_id }, associated: true },
relations: ['document_type', 'provision', 'provision_group', 'document_data_provisions'],
});
const provisions = await this.provisionRepository.find({ relations: ['provision_variables'] });
Expand Down
6 changes: 5 additions & 1 deletion backend/src/report/report.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
Param,
UseGuards,
UseFilters,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { ProvisionJSON, SessionData, VariableJSON } from 'src/types';
import { TTLSService } from '../ttls/ttls.service';
Expand Down Expand Up @@ -50,6 +52,8 @@ export class ReportController {
console.log('callHttp failed');
console.log(err);
console.log(err.response.data);
const errorMessage = `Disposition Transaction not found with id ${dtid}`;
throw new HttpException(errorMessage, HttpStatus.INTERNAL_SERVER_ERROR);
});
return response;
}
Expand Down Expand Up @@ -189,6 +193,6 @@ export class ReportController {

@Get()
getHealthCheck() {
return "";
return '';
}
}
4 changes: 1 addition & 3 deletions backend/src/report/report.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1272,14 +1272,12 @@ export class ReportService {
dtid: document.dtid,
version: templatesLookup[document.template_id].template_version,
file_name: templatesLookup[document.template_id].file_name,
updated_date: document.update_timestamp.toISOString().slice(0, 10),
updated_date: document && document.update_timestamp ? document.update_timestamp.toISOString().slice(0, 10) : '',
status: document.status,
active: templatesLookup[document.template_id].active_flag,
document_data_id: document.id,
document_type: document.document_type,
}));
console.log(combinedArray[0].updated_date);
// returns this: 2024-03-29T22:06:09.151Z

return combinedArray;
}
Expand Down
Loading

0 comments on commit 5044524

Please sign in to comment.