refactor(nestjs): pdf templates

This commit is contained in:
Ahmed Bouhuolia
2025-05-22 13:36:10 +02:00
parent 0823bfc4e9
commit 4e64a9eadb
16 changed files with 170 additions and 69 deletions

View File

@@ -70,7 +70,10 @@ export class SerializeInterceptor implements NestInterceptor<any, any> {
next: CallHandler<any>,
): Observable<any> {
const request = context.switchToHttp().getRequest();
// Transform both body and query parameters
request.body = this.strategy.in(request.body);
request.query = this.strategy.in(request.query);
// handle returns stream..
return next.handle().pipe(map(this.strategy.out));

View File

@@ -19,7 +19,7 @@ export class ValidationPipe implements PipeTransform<any> {
if (errors.length > 0) {
throw new BadRequestException(errors);
}
return value;
return object;
}
private toValidate(metatype: Function): boolean {

View File

@@ -1,8 +1,13 @@
import { Inject, Injectable } from '@nestjs/common';
import { Account } from '@/modules/Accounts/models/Account.model';
import { UncategorizedBankTransaction } from '@/modules/BankingTransactions/models/UncategorizedBankTransaction';
import { BaseModel } from '@/models/Model';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { Knex } from 'knex';
import { TENANCY_DB_CONNECTION } from '@/modules/Tenancy/TenancyDB/TenancyDB.constants';
import { initialize } from 'objection';
import { MatchedBankTransaction } from '@/modules/BankingMatching/models/MatchedBankTransaction';
import { TenantModel } from '@/modules/System/models/TenantModel';
import { RecognizedBankTransaction } from '@/modules/BankingTranasctionsRegonize/models/RecognizedBankTransaction';
@Injectable()
export class GetBankAccountSummary {
@@ -14,6 +19,19 @@ export class GetBankAccountSummary {
private readonly uncategorizedBankTransactionModel: TenantModelProxy<
typeof UncategorizedBankTransaction
>,
@Inject(MatchedBankTransaction.name)
private readonly matchedBankTransactionModel: TenantModelProxy<
typeof MatchedBankTransaction
>,
@Inject(RecognizedBankTransaction.name)
private readonly recognizedBankTransaction: TenantModelProxy<
typeof RecognizedBankTransaction
>,
@Inject(TENANCY_DB_CONNECTION)
private readonly tenantDb: () => Knex,
) {}
/**
@@ -27,6 +45,11 @@ export class GetBankAccountSummary {
.findById(bankAccountId)
.throwIfNotFound();
await initialize(this.tenantDb(), [
this.uncategorizedBankTransactionModel(),
this.matchedBankTransactionModel(),
this.recognizedBankTransaction(),
]);
const commonQuery = (q) => {
// Include just the given account.
q.where('accountId', bankAccountId);
@@ -37,11 +60,6 @@ export class GetBankAccountSummary {
// Only the not categorized.
q.modify('notCategorized');
};
interface UncategorizedTransactionsCount {
total: number;
}
// Retrieves the uncategorized transactions count of the given bank account.
const uncategorizedTranasctionsCount =
await this.uncategorizedBankTransactionModel()

View File

@@ -9,11 +9,8 @@ import {
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { BankingTransactionsApplication } from './BankingTransactionsApplication.service';
import {
IBankAccountsFilter,
ICashflowAccountTransactionsQuery,
} from './types/BankingTransactions.types';
import { CreateBankTransactionDto } from './dtos/CreateBankTransaction.dto';
import { GetBankTransactionsQueryDto } from './dtos/GetBankTranasctionsQuery.dto';
@Controller('banking/transactions')
@ApiTags('banking-transactions')
@@ -24,7 +21,7 @@ export class BankingTransactionsController {
@Get()
async getBankAccountTransactions(
@Query() query: ICashflowAccountTransactionsQuery,
@Query() query: GetBankTransactionsQueryDto,
) {
return this.bankingTransactionsApplication.getBankAccountTransactions(
query,

View File

@@ -0,0 +1,28 @@
import {
IsNotEmpty,
IsNumber,
IsNumberString,
IsOptional,
} from 'class-validator';
import { NumberFormatQueryDto } from './NumberFormatQuery.dto';
import { Type } from 'class-transformer';
export class GetBankTransactionsQueryDto {
@IsOptional()
@Type(() => Number)
@IsNumber()
page: number;
@IsOptional()
@Type(() => Number)
@IsNumber()
pageSize: number;
@IsNotEmpty()
@Type(() => Number)
@IsNumber()
accountId: number;
@IsOptional()
numberFormat: NumberFormatQueryDto;
}

View File

@@ -0,0 +1,26 @@
import { Type } from "class-transformer";
import { IsBoolean, IsEnum, IsNumber, IsOptional, IsPositive } from "class-validator";
export class NumberFormatQueryDto {
@Type(() => Number)
@IsNumber()
@IsPositive()
@IsOptional()
readonly precision: number;
@IsBoolean()
@IsOptional()
readonly divideOn1000: boolean;
@IsBoolean()
@IsOptional()
readonly showZero: boolean;
@IsEnum(['total', 'always', 'none'])
@IsOptional()
readonly formatMoney: 'total' | 'always' | 'none';
@IsEnum(['parentheses', 'mines'])
@IsOptional()
readonly negativeFormat: 'parentheses' | 'mines';
}

View File

@@ -1,9 +1,9 @@
/* eslint-disable global-require */
import * as moment from 'moment';
import { Model } from 'objection';
import { BaseModel } from '@/models/Model';
import { TenantBaseModel } from '@/modules/System/models/TenantBaseModel';
export class UncategorizedBankTransaction extends BaseModel {
export class UncategorizedBankTransaction extends TenantBaseModel {
readonly amount!: number;
readonly date!: Date | string;
readonly categorized!: boolean;

View File

@@ -1,6 +1,6 @@
// @ts-nocheck
import R from 'ramda';
import moment from 'moment';
import * as R from 'ramda';
import * as moment from 'moment';
import { first, isEmpty } from 'lodash';
import {
ICashflowAccountTransaction,

View File

@@ -1,13 +1,16 @@
import { Injectable, Scope } from '@nestjs/common';
import { Inject, Injectable, Scope } from '@nestjs/common';
import { ICashflowAccountTransactionsQuery } from '../../types/BankingTransactions.types';
import {
groupMatchedBankTransactions,
groupUncategorizedTransactions,
} from './_utils';
import { TenantModelProxy } from '@/modules/System/models/TenantBaseModel';
import { AccountTransaction } from '@/modules/Accounts/models/AccountTransaction.model';
import { UncategorizedBankTransaction } from '../../models/UncategorizedBankTransaction';
import { MatchedBankTransaction } from '@/modules/BankingMatching/models/MatchedBankTransaction';
@Injectable({ scope: Scope.REQUEST })
export class GetBankAccountTransactionsRepository {
private models: any;
public query: ICashflowAccountTransactionsQuery;
public transactions: any;
public uncategorizedTransactions: any;
@@ -17,6 +20,28 @@ export class GetBankAccountTransactionsRepository {
public pagination: any;
public openingBalance: any;
/**
* @param {TenantModelProxy<typeof AccountTransaction>} accountTransactionModel - Account transaction model.
* @param {TenantModelProxy<typeof UncategorizedBankTransaction>} uncategorizedBankTransactionModel - Uncategorized transaction model
* @param {TenantModelProxy<typeof MatchedBankTransaction>} matchedBankTransactionModel - Matched bank transaction model.
*/
constructor(
@Inject(AccountTransaction.name)
private readonly accountTransactionModel: TenantModelProxy<
typeof AccountTransaction
>,
@Inject(UncategorizedBankTransaction.name)
private readonly uncategorizedBankTransactionModel: TenantModelProxy<
typeof UncategorizedBankTransaction
>,
@Inject(MatchedBankTransaction.name)
private readonly matchedBankTransactionModel: TenantModelProxy<
typeof MatchedBankTransaction
>,
) {}
setQuery(query: ICashflowAccountTransactionsQuery) {
this.query = query;
}
@@ -37,9 +62,8 @@ export class GetBankAccountTransactionsRepository {
* @param {ICashflowAccountTransactionsQuery} query -
*/
async initCashflowAccountTransactions() {
const { AccountTransaction } = this.models;
const { results, pagination } = await AccountTransaction.query()
const { results, pagination } = await this.accountTransactionModel()
.query()
.where('account_id', this.query.accountId)
.orderBy([
{ column: 'date', order: 'desc' },
@@ -59,10 +83,9 @@ export class GetBankAccountTransactionsRepository {
* @return {Promise<number>}
*/
async initCashflowAccountOpeningBalance(): Promise<void> {
const { AccountTransaction } = this.models;
// Retrieve the opening balance of credit and debit balances.
const openingBalancesSubquery = AccountTransaction.query()
const openingBalancesSubquery = this.accountTransactionModel()
.query()
.where('account_id', this.query.accountId)
.orderBy([
{ column: 'date', order: 'desc' },
@@ -72,7 +95,8 @@ export class GetBankAccountTransactionsRepository {
.offset(this.pagination.pageSize * (this.pagination.page - 1));
// Sumation of credit and debit balance.
const openingBalances = await AccountTransaction.query()
const openingBalances = await this.accountTransactionModel()
.query()
.sum('credit as credit')
.sum('debit as debit')
.from(openingBalancesSubquery.as('T'))
@@ -87,14 +111,11 @@ export class GetBankAccountTransactionsRepository {
* Initialize the uncategorized transactions of the bank account.
*/
async initCategorizedTransactions() {
const { UncategorizedCashflowTransaction } = this.models;
const refs = this.transactions.map((t) => [t.referenceType, t.referenceId]);
const uncategorizedTransactions =
await UncategorizedCashflowTransaction.query().whereIn(
['categorizeRefType', 'categorizeRefId'],
refs,
);
await this.uncategorizedBankTransactionModel()
.query()
.whereIn(['categorizeRefType', 'categorizeRefId'], refs);
this.uncategorizedTransactions = uncategorizedTransactions;
this.uncategorizedTransactionsMapByRef = groupUncategorizedTransactions(
@@ -106,14 +127,11 @@ export class GetBankAccountTransactionsRepository {
* Initialize the matched bank transactions of the bank account.
*/
async initMatchedTransactions(): Promise<void> {
const { MatchedBankTransaction } = this.models;
const refs = this.transactions.map((t) => [t.referenceType, t.referenceId]);
const matchedBankTransactions =
await MatchedBankTransaction.query().whereIn(
['referenceType', 'referenceId'],
refs,
);
const matchedBankTransactions = await this.matchedBankTransactionModel()
.query()
.whereIn(['referenceType', 'referenceId'], refs);
this.matchedBankTransactions = matchedBankTransactions;
this.matchedBankTransactionsMapByRef = groupMatchedBankTransactions(
matchedBankTransactions,

View File

@@ -29,7 +29,7 @@ export class PdfTemplateApplication {
* @param {ICreateInvoicePdfTemplateDTO} invoiceTemplateDTO - The data transfer object containing the details for the new PDF template.
* @returns {Promise<any>}
*/
public async createPdfTemplate(
public createPdfTemplate(
templateName: string,
resource: string,
invoiceTemplateDTO: ICreateInvoicePdfTemplateDTO,
@@ -45,7 +45,7 @@ export class PdfTemplateApplication {
* Deletes a PDF template.
* @param {number} templateId - The ID of the template to delete.
*/
public async deletePdfTemplate(templateId: number) {
public deletePdfTemplate(templateId: number) {
return this.deletePdfTemplateService.deletePdfTemplate(templateId);
}
@@ -53,7 +53,7 @@ export class PdfTemplateApplication {
* Retrieves a specific PDF template.
* @param {number} templateId - The ID of the template to retrieve.
*/
public async getPdfTemplate(templateId: number) {
public getPdfTemplate(templateId: number) {
return this.getPdfTemplateService.getPdfTemplate(templateId);
}
@@ -61,7 +61,7 @@ export class PdfTemplateApplication {
* Retrieves all PDF templates.
* @param {string} resource - The resource type to filter templates.
*/
public async getPdfTemplates(query?: { resource?: string }) {
public getPdfTemplates(query?: { resource?: string }) {
return this.getPdfTemplatesService.getPdfTemplates(query);
}
@@ -70,7 +70,7 @@ export class PdfTemplateApplication {
* @param {number} templateId - The ID of the template to edit.
* @param {IEditPdfTemplateDTO} editDTO - The data transfer object containing the updates.
*/
public async editPdfTemplate(
public editPdfTemplate(
templateId: number,
editDTO: IEditPdfTemplateDTO,
) {
@@ -80,7 +80,7 @@ export class PdfTemplateApplication {
/**
* Gets the PDF template branding state.
*/
public async getPdfTemplateBrandingState() {
public getPdfTemplateBrandingState() {
return this.getPdfTemplateBrandingStateService.execute();
}
@@ -89,7 +89,7 @@ export class PdfTemplateApplication {
* @param {number} templateId - The ID of the PDF template to assign as default.
* @returns {Promise<any>}
*/
public async assignPdfTemplateAsDefault(templateId: number) {
public assignPdfTemplateAsDefault(templateId: number) {
return this.assignPdfTemplateDefaultService.assignDefaultTemplate(
templateId,
);
@@ -99,7 +99,7 @@ export class PdfTemplateApplication {
* Retrieves the organization branding attributes.
* @returns {Promise<CommonOrganizationBrandingAttributes>} The organization branding attributes.
*/
getOrganizationBrandingAttributes() {
public getOrganizationBrandingAttributes() {
return this.getOrganizationBrandingAttributesService.execute();
}
}

View File

@@ -47,6 +47,17 @@ export class PdfTemplatesController {
return this.pdfTemplateApplication.deletePdfTemplate(templateId);
}
@Get('/state')
@ApiOperation({ summary: 'Retrieves the PDF template branding state.' })
@ApiResponse({
status: 200,
description:
'The PDF template branding state has been successfully retrieved.',
})
async getPdfTemplateBrandingState() {
return this.pdfTemplateApplication.getPdfTemplateBrandingState();
}
@Get(':id')
@ApiOperation({ summary: 'Retrieves the PDF template details.' })
@ApiResponse({