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({

View File

@@ -18,14 +18,14 @@ const PaymentsReceivedListContext = createContext();
function PaymentsReceivedListProvider({ query, tableStateChanged, ...props }) {
// Fetch payment receives resource views and fields.
const { data: paymentReceivesViews, isLoading: isViewsLoading } =
useResourceViews('payment_receives');
useResourceViews('payment-received');
// Fetch the payment receives resource fields.
const {
data: resourceMeta,
isLoading: isResourceLoading,
isFetching: isResourceFetching,
} = useResourceMeta('payment_receives');
} = useResourceMeta('payment-received');
// Fetch payment receives list according to the given custom view id.
const {

View File

@@ -83,7 +83,7 @@ export function useDisconnectBankAccount(
DisconnectBankAccountValues
>(
({ bankAccountId }) =>
apiRequest.post(`/banking/bank_accounts/${bankAccountId}/disconnect`),
apiRequest.post(`/banking/accounts/${bankAccountId}/disconnect`),
{
...options,
onSuccess: (res, values) => {
@@ -115,7 +115,7 @@ export function useUpdateBankAccount(
return useMutation<DisconnectBankAccountRes, Error, UpdateBankAccountValues>(
({ bankAccountId }) =>
apiRequest.post(`/banking/bank_accounts/${bankAccountId}/update`),
apiRequest.post(`/banking/accounts/${bankAccountId}/update`),
{
...options,
onSuccess: () => {},
@@ -254,7 +254,7 @@ export function useGetBankTransactionsMatches(
[BANK_QUERY_KEY.BANK_TRANSACTION_MATCHES, uncategorizeTransactionsIds],
() =>
apiRequest
.get(`/cashflow/transactions/matches`, {
.get(`/banking/matching/matched`, {
params: { uncategorizeTransactionsIds },
})
.then((res) => transformToCamelCase(res.data)),
@@ -312,7 +312,7 @@ export function useExcludeUncategorizedTransaction(
>(
(uncategorizedTransactionId: number) =>
apiRequest.put(
`/cashflow/transactions/${uncategorizedTransactionId}/exclude`,
`/banking/transactions/${uncategorizedTransactionId}/exclude`,
),
{
onSuccess: (res, id) => {
@@ -353,7 +353,7 @@ export function useUnexcludeUncategorizedTransaction(
>(
(uncategorizedTransactionId: number) =>
apiRequest.put(
`/cashflow/transactions/${uncategorizedTransactionId}/unexclude`,
`/banking/transactions/${uncategorizedTransactionId}/unexclude`,
),
{
onSuccess: (res, id) => {
@@ -392,7 +392,7 @@ export function useExcludeUncategorizedTransactions(
ExcludeBankTransactionsValue
>(
(value: { ids: Array<number | string> }) =>
apiRequest.put(`/cashflow/transactions/exclude`, { ids: value.ids }),
apiRequest.put(`/banking/transactions/exclude`, { ids: value.ids }),
{
onSuccess: (res, id) => {
onValidateExcludeUncategorizedTransaction(queryClient);
@@ -430,7 +430,7 @@ export function useUnexcludeUncategorizedTransactions(
UnexcludeBankTransactionsValue
>(
(value: { ids: Array<number | string> }) =>
apiRequest.put(`/cashflow/transactions/unexclude`, { ids: value.ids }),
apiRequest.put(`/banking/transactions/unexclude`, { ids: value.ids }),
{
onSuccess: (res, id) => {
onValidateExcludeUncategorizedTransaction(queryClient);
@@ -515,7 +515,7 @@ export function useUnmatchMatchedUncategorizedTransaction(
UnmatchUncategorizedTransactionRes,
Error,
UnmatchUncategorizedTransactionValues
>(({ id }) => apiRequest.post(`/banking/matches/unmatch/${id}`), {
>(({ id }) => apiRequest.post(`/banking/matching/unmatch/${id}`), {
onSuccess: (res, id) => {
queryClient.invalidateQueries(
t.CASHFLOW_ACCOUNT_UNCATEGORIZED_TRANSACTIONS_INFINITY,
@@ -579,7 +579,7 @@ export function useGetBankAccountSummaryMeta(
[BANK_QUERY_KEY.BANK_ACCOUNT_SUMMARY_META, bankAccountId],
() =>
apiRequest
.get(`/banking/bank_accounts/${bankAccountId}/meta`)
.get(`/banking/accounts/${bankAccountId}/summary`)
.then((res) => transformToCamelCase(res.data?.data)),
{ ...options },
);
@@ -668,7 +668,7 @@ export function useExcludedBankTransactionsInfinity(
const response = await apiRequest.http({
...axios,
method: 'get',
url: `/api/cashflow/excluded`,
url: `/api/banking/excluded`,
params: { page: pageParam, ...query },
});
return response.data;
@@ -700,7 +700,7 @@ export function usePendingBankTransactionsInfinity(
const response = await apiRequest.http({
...axios,
method: 'get',
url: `/api/banking/bank_accounts/pending_transactions`,
url: `/api/banking/accounts/pending_transactions`,
params: { page: pageParam, ...query },
});
return response.data;

View File

@@ -54,7 +54,7 @@ export function useCreateCashflowTransaction(props) {
const apiRequest = useApiRequest();
return useMutation(
(values) => apiRequest.post('cashflow/transactions', values),
(values) => apiRequest.post('banking/transactions', values),
{
onSuccess: () => {
// Invalidate queries.
@@ -73,7 +73,7 @@ export function useCreateCashflowTransaction(props) {
export function useCashflowTransaction(id, props) {
return useRequestQuery(
[t.CASH_FLOW_TRANSACTIONS, id],
{ method: 'get', url: `cashflow/transactions/${id}` },
{ method: 'get', url: `banking/transactions/${id}` },
{
select: (res) => res.data.cashflow_transaction,
defaultData: [],
@@ -89,7 +89,7 @@ export function useDeleteCashflowTransaction(props) {
const queryClient = useQueryClient();
const apiRequest = useApiRequest();
return useMutation((id) => apiRequest.delete(`cashflow/transactions/${id}`), {
return useMutation((id) => apiRequest.delete(`banking/transactions/${id}`), {
onSuccess: (res, id) => {
// Invalidate queries.
commonInvalidateQueries(queryClient);
@@ -118,7 +118,7 @@ export function useAccountTransactionsInfinity(
const response = await apiRequest.http({
...axios,
method: 'get',
url: `/api/financial_statements/cashflow-account-transactions`,
url: `/api/banking/transactions`,
params: { page: pageParam, ...query },
});
return response.data;
@@ -157,7 +157,7 @@ export function useAccountUncategorizedTransactionsInfinity(
const response = await apiRequest.http({
...axios,
method: 'get',
url: `/api/cashflow/transactions/${accountId}/uncategorized`,
url: `/api/banking/transactions/${accountId}/uncategorized`,
params: { page: pageParam, ...query },
});
return response.data;
@@ -231,7 +231,7 @@ export function useUncategorizedTransaction(
[t.CASHFLOW_UNCAATEGORIZED_TRANSACTION, uncategorizedTranasctionId],
{
method: 'get',
url: `cashflow/transactions/uncategorized/${uncategorizedTranasctionId}`,
url: `banking/transactions/uncategorized/${uncategorizedTranasctionId}`,
},
{
select: (res) => res.data?.data,
@@ -248,7 +248,7 @@ export function useCategorizeTransaction(props) {
const apiRequest = useApiRequest();
return useMutation(
(values) => apiRequest.post(`cashflow/transactions/categorize`, values),
(values) => apiRequest.post(`banking/transactions/categorize`, values),
{
onSuccess: (res, id) => {
// Invalidate queries.
@@ -274,7 +274,7 @@ export function useUncategorizeTransaction(props) {
const apiRequest = useApiRequest();
return useMutation(
(id: number) => apiRequest.post(`cashflow/transactions/${id}/uncategorize`),
(id: number) => apiRequest.post(`banking/transactions/${id}/uncategorize`),
{
onSuccess: (res, id) => {
// Invalidate queries.

View File

@@ -185,7 +185,7 @@ export function useInvoice(invoiceId, props, requestProps) {
[t.SALE_INVOICE, invoiceId],
{ method: 'get', url: `sale-invoices/${invoiceId}`, ...requestProps },
{
select: (res) => res.data.sale_invoice,
select: (res) => res.data,
defaultData: {},
...props,
},
@@ -338,7 +338,7 @@ export function useInvoicePaymentTransactions(invoiceId, props) {
[t.SALE_INVOICE_PAYMENT_TRANSACTIONS, invoiceId],
{
method: 'get',
url: `sale-invoices/${invoiceId}/payment-transactions`,
url: `sale-invoices/${invoiceId}/payments`,
},
{
select: (res) => res.data.data,

View File

@@ -230,7 +230,7 @@ export const useGetPdfTemplateBrandingState = (
() =>
apiRequest
.get('/pdf-templates/state')
.then((res) => transformToCamelCase(res.data?.data)),
.then((res) => transformToCamelCase(res.data)),
options,
);
};