mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-15 20:30:33 +00:00
feat(nestjs): migrate to NestJS
This commit is contained in:
13
packages/server/src/modules/Ledger/JournalEntry.ts
Normal file
13
packages/server/src/modules/Ledger/JournalEntry.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { ILedgerEntry } from "./types/Ledger.types";
|
||||
|
||||
export class JournalEntry {
|
||||
entry: ILedgerEntry;
|
||||
|
||||
constructor(entry: ILedgerEntry) {
|
||||
const defaults = {
|
||||
credit: 0,
|
||||
debit: 0,
|
||||
};
|
||||
this.entry = { ...defaults, ...entry };
|
||||
}
|
||||
}
|
||||
27
packages/server/src/modules/Ledger/Ledger.module.ts
Normal file
27
packages/server/src/modules/Ledger/Ledger.module.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { LedgerStorageService } from './LedgerStorage.service';
|
||||
import { LedgerEntriesStorageService } from './LedgerEntriesStorage.service';
|
||||
import { LedgerRevertService } from './LedgerStorageRevert.service';
|
||||
import { LedgerContactsBalanceStorage } from './LedgerContactStorage.service';
|
||||
import { TenancyContext } from '../Tenancy/TenancyContext.service';
|
||||
import { LedegrAccountsStorage } from './LedgetAccountStorage.service';
|
||||
import { AccountsModule } from '../Accounts/Accounts.module';
|
||||
|
||||
@Module({
|
||||
imports: [AccountsModule],
|
||||
providers: [
|
||||
LedgerStorageService,
|
||||
LedgerEntriesStorageService,
|
||||
LedgerRevertService,
|
||||
LedgerContactsBalanceStorage,
|
||||
LedegrAccountsStorage,
|
||||
TenancyContext
|
||||
],
|
||||
exports: [
|
||||
LedgerStorageService,
|
||||
LedgerEntriesStorageService,
|
||||
LedgerRevertService,
|
||||
LedegrAccountsStorage
|
||||
],
|
||||
})
|
||||
export class LedgerModule {}
|
||||
297
packages/server/src/modules/Ledger/Ledger.ts
Normal file
297
packages/server/src/modules/Ledger/Ledger.ts
Normal file
@@ -0,0 +1,297 @@
|
||||
import * as moment from 'moment';
|
||||
import { defaultTo, sumBy, uniqBy } from 'lodash';
|
||||
import { ILedger } from './types/Ledger.types';
|
||||
import { ILedgerEntry } from './types/Ledger.types';
|
||||
import { AccountTransaction } from '../Accounts/models/AccountTransaction.model';
|
||||
import { IAccountTransaction } from '@/interfaces/Account';
|
||||
import { ModelObject } from 'objection';
|
||||
|
||||
export class Ledger implements ILedger {
|
||||
readonly entries: ILedgerEntry[];
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
* @param {ILedgerEntry[]} entries
|
||||
*/
|
||||
constructor(entries: ILedgerEntry[]) {
|
||||
this.entries = entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the ledegr entries.
|
||||
* @param callback
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public filter(callback): ILedger {
|
||||
const entries = this.entries.filter(callback);
|
||||
return new Ledger(entries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the all entries of the ledger.
|
||||
* @return {ILedgerEntry[]}
|
||||
*/
|
||||
public getEntries(): ILedgerEntry[] {
|
||||
return this.entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters entries by th given contact id and returns a new ledger.
|
||||
* @param {number} contactId
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public whereContactId(contactId: number): ILedger {
|
||||
return this.filter((entry) => entry.contactId === contactId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters entries by the given account id and returns a new ledger.
|
||||
* @param {number} accountId
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public whereAccountId(accountId: number): ILedger {
|
||||
return this.filter((entry) => entry.accountId === accountId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters entries by the given accounts ids then returns a new ledger.
|
||||
* @param {number[]} accountIds
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public whereAccountsIds(accountIds: number[]): ILedger {
|
||||
return this.filter((entry) => accountIds.indexOf(entry.accountId) !== -1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters entries that before or same the given date and returns a new ledger.
|
||||
* @param {Date|string} fromDate
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public whereFromDate(fromDate: Date | string): ILedger {
|
||||
const fromDateParsed = moment(fromDate);
|
||||
|
||||
return this.filter(
|
||||
(entry) =>
|
||||
fromDateParsed.isBefore(entry.date) ||
|
||||
fromDateParsed.isSame(entry.date),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters ledger entries that after the given date and retruns a new ledger.
|
||||
* @param {Date|string} toDate
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public whereToDate(toDate: Date | string): ILedger {
|
||||
const toDateParsed = moment(toDate);
|
||||
|
||||
return this.filter(
|
||||
(entry) =>
|
||||
toDateParsed.isAfter(entry.date) || toDateParsed.isSame(entry.date),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the ledget entries by the given currency code.
|
||||
* @param {string} currencyCode -
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public whereCurrencyCode(currencyCode: string): ILedger {
|
||||
return this.filter((entry) => entry.currencyCode === currencyCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the ledger entries by the given branch id.
|
||||
* @param {number} branchId
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public whereBranch(branchId: number): ILedger {
|
||||
return this.filter((entry) => entry.branchId === branchId);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {number} projectId
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public whereProject(projectId: number): ILedger {
|
||||
return this.filter((entry) => entry.projectId === projectId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters the ledger entries by the given item id.
|
||||
* @param {number} itemId
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
public whereItem(itemId: number): ILedger {
|
||||
return this.filter((entry) => entry.itemId === itemId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the closing balance of the entries.
|
||||
* @returns {number}
|
||||
*/
|
||||
public getClosingBalance(): number {
|
||||
let closingBalance = 0;
|
||||
|
||||
this.entries.forEach((entry) => {
|
||||
if (entry.accountNormal === 'credit') {
|
||||
closingBalance += entry.credit - entry.debit;
|
||||
} else if (entry.accountNormal === 'debit') {
|
||||
closingBalance += entry.debit - entry.credit;
|
||||
}
|
||||
});
|
||||
return closingBalance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the closing credit of the entries.
|
||||
* @returns {number}
|
||||
*/
|
||||
public getClosingCredit(): number {
|
||||
return sumBy(this.entries, 'credit');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the closing debit of the entries.
|
||||
* @returns {number}
|
||||
*/
|
||||
public getClosingDebit(): number {
|
||||
return sumBy(this.entries, 'debit');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the closing balance of the entries.
|
||||
* @returns {number}
|
||||
*/
|
||||
public getForeignClosingBalance(): number {
|
||||
let closingBalance = 0;
|
||||
|
||||
this.entries.forEach((entry) => {
|
||||
const exchangeRate = entry.exchangeRate || 1;
|
||||
|
||||
if (entry.accountNormal === 'credit') {
|
||||
closingBalance += (entry.credit - entry.debit) / exchangeRate;
|
||||
} else if (entry.accountNormal === 'debit') {
|
||||
closingBalance += (entry.debit - entry.credit) / exchangeRate;
|
||||
}
|
||||
});
|
||||
return closingBalance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detarmines whether the ledger has no entries.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
public isEmpty(): boolean {
|
||||
return this.entries.length === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the accounts ids of the entries uniquely.
|
||||
* @returns {number[]}
|
||||
*/
|
||||
public getAccountsIds = (): number[] => {
|
||||
return uniqBy(this.entries, 'accountId').map(
|
||||
(e: ILedgerEntry) => e.accountId,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the contacts ids of the entries uniquely.
|
||||
* @returns {number[]}
|
||||
*/
|
||||
public getContactsIds = (): number[] => {
|
||||
return uniqBy(this.entries, 'contactId')
|
||||
.filter((e: ILedgerEntry) => e.contactId)
|
||||
.map((e: ILedgerEntry) => e.contactId);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverses the ledger entries.
|
||||
* @returns {Ledger}
|
||||
*/
|
||||
public reverse = (): Ledger => {
|
||||
const newEntries = this.entries.map((e) => {
|
||||
const credit = e.debit;
|
||||
const debit = e.credit;
|
||||
|
||||
return { ...e, credit, debit };
|
||||
});
|
||||
return new Ledger(newEntries);
|
||||
};
|
||||
|
||||
// ---------------------------------
|
||||
// # STATIC METHODS.
|
||||
// ----------------------------------
|
||||
/**
|
||||
* Mappes the account transactions to ledger entries.
|
||||
* @param {IAccountTransaction[]} entries
|
||||
* @returns {ILedgerEntry[]}
|
||||
*/
|
||||
static mappingTransactions(entries: ModelObject<AccountTransaction>[]): ILedgerEntry[] {
|
||||
return entries.map(this.mapTransaction);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mappes the account transaction to ledger entry.
|
||||
* @param {IAccountTransaction} entry - Account transaction.
|
||||
* @returns {ILedgerEntry}
|
||||
*/
|
||||
static mapTransaction(entry: ModelObject<AccountTransaction>): ILedgerEntry {
|
||||
return {
|
||||
credit: defaultTo(entry.credit, 0),
|
||||
debit: defaultTo(entry.debit, 0),
|
||||
|
||||
exchangeRate: entry.exchangeRate,
|
||||
currencyCode: entry.currencyCode,
|
||||
|
||||
accountNormal: entry.account.accountNormal,
|
||||
accountId: entry.accountId,
|
||||
contactId: entry.contactId,
|
||||
|
||||
date: entry.date,
|
||||
|
||||
transactionId: entry.referenceId,
|
||||
transactionType: entry.referenceType,
|
||||
transactionSubType: entry.transactionType,
|
||||
|
||||
transactionNumber: entry.transactionNumber,
|
||||
referenceNumber: entry.referenceNumber,
|
||||
|
||||
index: entry.index,
|
||||
indexGroup: entry.indexGroup,
|
||||
|
||||
entryId: entry.id,
|
||||
branchId: entry.branchId,
|
||||
projectId: entry.projectId,
|
||||
|
||||
taxRateId: entry.taxRateId,
|
||||
taxRate: entry.taxRate,
|
||||
|
||||
note: entry.note,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mappes the account transactions to ledger entries.
|
||||
* @param {IAccountTransaction[]} transactions
|
||||
* @returns {ILedger}
|
||||
*/
|
||||
static fromTransactions(
|
||||
transactions: Array<ModelObject<AccountTransaction>>,
|
||||
): Ledger {
|
||||
const entries = Ledger.mappingTransactions(transactions);
|
||||
return new Ledger(entries);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the transaction amount.
|
||||
* @param {number} credit - Credit amount.
|
||||
* @param {number} debit - Debit amount.
|
||||
* @param {string} normal - Credit or debit.
|
||||
*/
|
||||
static getAmount(credit: number, debit: number, normal: string) {
|
||||
return normal === 'credit' ? credit - debit : debit - credit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import async from 'async';
|
||||
import { Knex } from 'knex';
|
||||
import {
|
||||
ILedger,
|
||||
ILedgerEntry,
|
||||
ISaleContactsBalanceQueuePayload,
|
||||
} from './types/Ledger.types';
|
||||
import { ACCOUNT_TYPE } from '@/constants/accounts';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Contact } from '../Contacts/models/Contact';
|
||||
import { Account } from '../Accounts/models/Account.model';
|
||||
import { TenancyContext } from '../Tenancy/TenancyContext.service';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class LedgerContactsBalanceStorage {
|
||||
constructor(
|
||||
private tenancyContext: TenancyContext,
|
||||
|
||||
@Inject(Contact.name)
|
||||
private contactModel: TenantModelProxy<typeof Contact>,
|
||||
|
||||
@Inject(Account.name)
|
||||
private accountModel: TenantModelProxy<typeof Account>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Saves the contacts balance.
|
||||
* @param {ILedger} ledger
|
||||
* @param {Knex.Transaction} trx
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public saveContactsBalance = async (
|
||||
ledger: ILedger,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> => {
|
||||
// Save contact balance queue.
|
||||
const saveContactsBalanceQueue = async.queue(
|
||||
this.saveContactBalanceTask,
|
||||
10,
|
||||
);
|
||||
// Retrieves the effected contacts ids.
|
||||
const effectedContactsIds = ledger.getContactsIds();
|
||||
|
||||
effectedContactsIds.forEach((contactId: number) => {
|
||||
saveContactsBalanceQueue.push({ contactId, ledger, trx });
|
||||
});
|
||||
if (effectedContactsIds.length > 0) await saveContactsBalanceQueue.drain();
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves the contact balance.
|
||||
* @param {ISaleContactsBalanceQueuePayload} task
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private saveContactBalanceTask = async (
|
||||
task: ISaleContactsBalanceQueuePayload,
|
||||
) => {
|
||||
const { contactId, ledger, trx } = task;
|
||||
|
||||
await this.saveContactBalance(ledger, contactId, trx);
|
||||
};
|
||||
|
||||
/**
|
||||
* Filters AP/AR ledger entries.
|
||||
* @param {number} tenantId
|
||||
* @param {Knex.Transaction} trx
|
||||
* @returns {Promise<(entry: ILedgerEntry) => boolean>}
|
||||
*/
|
||||
private filterARAPLedgerEntris = async (
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<(entry: ILedgerEntry) => boolean> => {
|
||||
const ARAPAccounts = await this.accountModel()
|
||||
.query(trx)
|
||||
.whereIn('accountType', [
|
||||
ACCOUNT_TYPE.ACCOUNTS_RECEIVABLE,
|
||||
ACCOUNT_TYPE.ACCOUNTS_PAYABLE,
|
||||
]);
|
||||
const ARAPAccountsIds = ARAPAccounts.map((a) => a.id);
|
||||
|
||||
return (entry: ILedgerEntry) => {
|
||||
return ARAPAccountsIds.indexOf(entry.accountId) !== -1;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {number} tenantId
|
||||
* @param {ILedger} ledger
|
||||
* @param {number} contactId
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private saveContactBalance = async (
|
||||
ledger: ILedger,
|
||||
contactId: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> => {
|
||||
const contact = await this.contactModel().query(trx).findById(contactId);
|
||||
const tenant = await this.tenancyContext.getTenant(true);
|
||||
|
||||
// Detarmines whether the contact has foreign currency.
|
||||
const isForeignContact =
|
||||
contact.currencyCode !== tenant?.metadata.baseCurrency;
|
||||
|
||||
// Filters the ledger base on the given contact id.
|
||||
const filterARAPLedgerEntris = await this.filterARAPLedgerEntris(trx);
|
||||
const contactLedger = ledger
|
||||
// Filter entries only that have contact id.
|
||||
.whereContactId(contactId)
|
||||
// Filter entries on AR/AP accounts.
|
||||
.filter(filterARAPLedgerEntris);
|
||||
|
||||
const closingBalance = isForeignContact
|
||||
? contactLedger
|
||||
.whereCurrencyCode(contact.currencyCode)
|
||||
.getForeignClosingBalance()
|
||||
: contactLedger.getClosingBalance();
|
||||
|
||||
await this.changeContactBalance(contactId, closingBalance, trx);
|
||||
};
|
||||
|
||||
/**
|
||||
* Changes the contact receiable/payable balance.
|
||||
* @param {number} contactId - The contact ID.
|
||||
* @param {number} change - The change amount.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private changeContactBalance = (
|
||||
contactId: number,
|
||||
change: number,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
// return this.contactModel.changeAmount(
|
||||
// { id: contactId },
|
||||
// 'balance',
|
||||
// change,
|
||||
// trx,
|
||||
// );
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Knex } from 'knex';
|
||||
import async from 'async';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { transformLedgerEntryToTransaction } from './utils';
|
||||
import {
|
||||
ILedgerEntry,
|
||||
ISaveLedgerEntryQueuePayload,
|
||||
} from './types/Ledger.types';
|
||||
import { ILedger } from './types/Ledger.types';
|
||||
import { AccountTransaction } from '../Accounts/models/AccountTransaction.model';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
// Filter the blank entries.
|
||||
const filterBlankEntry = (entry: ILedgerEntry) =>
|
||||
Boolean(entry.credit || entry.debit);
|
||||
|
||||
@Injectable()
|
||||
export class LedgerEntriesStorageService {
|
||||
/**
|
||||
* @param {TenantModelProxy<typeof AccountTransaction>} accountTransactionModel - Account transaction model.
|
||||
*/
|
||||
constructor(
|
||||
@Inject(AccountTransaction.name)
|
||||
private readonly accountTransactionModel: TenantModelProxy<
|
||||
typeof AccountTransaction
|
||||
>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Saves entries of the given ledger.
|
||||
* @param {ILedger} ledger - Ledger.
|
||||
* @param {Knex.Transaction} trx - Knex transaction.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public saveEntries = async (ledger: ILedger, trx?: Knex.Transaction) => {
|
||||
const saveEntryQueue = async.queue(this.saveEntryTask, 10);
|
||||
const entries = ledger.filter(filterBlankEntry).getEntries();
|
||||
|
||||
entries.forEach((entry) => {
|
||||
saveEntryQueue.push({ entry, trx });
|
||||
});
|
||||
if (entries.length > 0) await saveEntryQueue.drain();
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes the ledger entries.
|
||||
* @param {ILedger} ledger - Ledger.
|
||||
* @param {Knex.Transaction} trx - Knex transaction.
|
||||
*/
|
||||
public deleteEntries = async (ledger: ILedger, trx?: Knex.Transaction) => {
|
||||
const entriesIds = ledger
|
||||
.getEntries()
|
||||
.filter((e) => e.entryId)
|
||||
.map((e) => e.entryId);
|
||||
|
||||
await this.accountTransactionModel()
|
||||
.query(trx)
|
||||
.whereIn('id', entriesIds)
|
||||
.delete();
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves the ledger entry to the account transactions repository.
|
||||
* @param {ILedgerEntry} entry - Ledger entry.
|
||||
* @param {Knex.Transaction} trx
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private saveEntry = async (
|
||||
entry: ILedgerEntry,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> => {
|
||||
const transaction = transformLedgerEntryToTransaction(entry);
|
||||
|
||||
await this.accountTransactionModel().query(trx).insert(transaction);
|
||||
};
|
||||
|
||||
/**
|
||||
* Save the ledger entry to the transactions repository async task.
|
||||
* @param {ISaveLedgerEntryQueuePayload} task - Task payload.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private saveEntryTask = async (
|
||||
task: ISaveLedgerEntryQueuePayload,
|
||||
): Promise<void> => {
|
||||
const { entry, trx } = task;
|
||||
|
||||
await this.saveEntry(entry, trx);
|
||||
};
|
||||
}
|
||||
95
packages/server/src/modules/Ledger/LedgerStorage.service.ts
Normal file
95
packages/server/src/modules/Ledger/LedgerStorage.service.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { Knex } from 'knex';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { ILedger } from './types/Ledger.types';
|
||||
import { LedgerContactsBalanceStorage } from './LedgerContactStorage.service';
|
||||
import { LedegrAccountsStorage } from './LedgetAccountStorage.service';
|
||||
import { LedgerEntriesStorageService } from './LedgerEntriesStorage.service';
|
||||
import { AccountTransaction } from '../Accounts/models/AccountTransaction.model';
|
||||
import { Ledger } from './Ledger';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class LedgerStorageService {
|
||||
/**
|
||||
* @param {LedgerContactsBalanceStorage} ledgerContactsBalance - Ledger contacts balance storage.
|
||||
* @param {LedegrAccountsStorage} ledgerAccountsBalance - Ledger accounts balance storage.
|
||||
* @param {LedgerEntriesStorageService} ledgerEntriesService - Ledger entries storage service.
|
||||
*/
|
||||
constructor(
|
||||
private ledgerContactsBalance: LedgerContactsBalanceStorage,
|
||||
private ledgerAccountsBalance: LedegrAccountsStorage,
|
||||
private ledgerEntriesService: LedgerEntriesStorageService,
|
||||
|
||||
@Inject(AccountTransaction.name)
|
||||
private accountTransactionModel: TenantModelProxy<
|
||||
typeof AccountTransaction
|
||||
>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Commit the ledger to the storage layer as one unit-of-work.
|
||||
* @param {ILedger} ledger
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public commit = async (
|
||||
ledger: ILedger,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> => {
|
||||
const tasks = [
|
||||
// Saves the ledger entries.
|
||||
this.ledgerEntriesService.saveEntries(ledger, trx),
|
||||
|
||||
// Mutates the associated accounts balances.
|
||||
this.ledgerAccountsBalance.saveAccountsBalance(ledger, trx),
|
||||
|
||||
// Mutates the associated contacts balances.
|
||||
this.ledgerContactsBalance.saveContactsBalance(ledger, trx),
|
||||
];
|
||||
await Promise.all(tasks);
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes the given ledger and revert balances.
|
||||
* @param {number} tenantId
|
||||
* @param {ILedger} ledger
|
||||
* @param {Knex.Transaction} trx
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public delete = async (ledger: ILedger, trx?: Knex.Transaction) => {
|
||||
const tasks = [
|
||||
// Deletes the ledger entries.
|
||||
this.ledgerEntriesService.deleteEntries(ledger, trx),
|
||||
|
||||
// Mutates the associated accounts balances.
|
||||
this.ledgerAccountsBalance.saveAccountsBalance(ledger, trx),
|
||||
|
||||
// Mutates the associated contacts balances.
|
||||
this.ledgerContactsBalance.saveContactsBalance(ledger, trx),
|
||||
];
|
||||
await Promise.all(tasks);
|
||||
};
|
||||
|
||||
/**
|
||||
* Deletes the ledger entries by the given reference.
|
||||
* @param {number | number[]} referenceId - The reference ID.
|
||||
* @param {string | string[]} referenceType - The reference type.
|
||||
* @param {Knex.Transaction} trx - The knex transaction.
|
||||
*/
|
||||
public deleteByReference = async (
|
||||
referenceId: number | number[],
|
||||
referenceType: string | string[],
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
// Retrieves the transactions of the given reference.
|
||||
const transactions = await this.accountTransactionModel()
|
||||
.query(trx)
|
||||
.modify('filterByReference', referenceId, referenceType)
|
||||
.withGraphFetched('account');
|
||||
|
||||
// Creates a new ledger from transaction and reverse the entries.
|
||||
const reversedLedger = Ledger.fromTransactions(transactions).reverse();
|
||||
|
||||
// Deletes and reverts the balances.
|
||||
await this.delete(reversedLedger, trx);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { castArray } from 'lodash';
|
||||
import { Injectable, Inject } from '@nestjs/common';
|
||||
import { Knex } from 'knex';
|
||||
import { Ledger } from './Ledger';
|
||||
import { LedgerStorageService } from './LedgerStorage.service';
|
||||
import { AccountTransaction } from '../Accounts/models/AccountTransaction.model';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class LedgerRevertService {
|
||||
/**
|
||||
* @param {LedgerStorageService} ledgerStorage - Ledger storage service.
|
||||
* @param {TenantModelProxy<typeof AccountTransaction>} accountTransactionModel - Account transaction model.
|
||||
*/
|
||||
constructor(
|
||||
private readonly ledgerStorage: LedgerStorageService,
|
||||
|
||||
@Inject(AccountTransaction.name)
|
||||
private readonly accountTransactionModel: TenantModelProxy<
|
||||
typeof AccountTransaction
|
||||
>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Reverts the jouranl entries.
|
||||
* @param {number|number[]} referenceId - Reference id.
|
||||
* @param {string} referenceType - Reference type.
|
||||
*/
|
||||
public getTransactionsByReference = async (
|
||||
referenceId: number | number[],
|
||||
referenceType: string | string[],
|
||||
) => {
|
||||
const transactions = await this.accountTransactionModel()
|
||||
.query()
|
||||
.whereIn('reference_type', castArray(referenceType))
|
||||
.whereIn('reference_id', castArray(referenceId))
|
||||
.withGraphFetched('account');
|
||||
|
||||
return transactions;
|
||||
};
|
||||
|
||||
/**
|
||||
* Reverts the journal entries.
|
||||
* @param {number|number[]} referenceId - Reference id.
|
||||
* @param {string|string[]} referenceType - Reference type.
|
||||
* @param {Knex.Transaction} trx
|
||||
*/
|
||||
public revertGLEntries = async (
|
||||
referenceId: number | number[],
|
||||
referenceType: string | string[],
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
// Gets the transactions by reference.
|
||||
const transactions = await this.getTransactionsByReference(
|
||||
referenceId,
|
||||
referenceType,
|
||||
);
|
||||
// Creates a new ledger from transaction and reverse the entries.
|
||||
const ledger = Ledger.fromTransactions(transactions);
|
||||
const reversedLedger = ledger.reverse();
|
||||
|
||||
// Commits the reversed ledger.
|
||||
await this.ledgerStorage.commit(reversedLedger, trx);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import async from 'async';
|
||||
import { Knex } from 'knex';
|
||||
import { uniq } from 'lodash';
|
||||
import {
|
||||
ILedger,
|
||||
ISaveAccountsBalanceQueuePayload,
|
||||
} from './types/Ledger.types';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { Account } from '../Accounts/models/Account.model';
|
||||
import { AccountRepository } from '../Accounts/repositories/Account.repository';
|
||||
import { TenancyContext } from '../Tenancy/TenancyContext.service';
|
||||
import { TenantModelProxy } from '../System/models/TenantBaseModel';
|
||||
|
||||
@Injectable()
|
||||
export class LedegrAccountsStorage {
|
||||
/**
|
||||
* @param {typeof Account} accountModel
|
||||
* @param {AccountRepository} accountRepository -
|
||||
*/
|
||||
constructor(
|
||||
private tenancyContext: TenancyContext,
|
||||
private accountRepository: AccountRepository,
|
||||
|
||||
@Inject(Account.name)
|
||||
private accountModel: TenantModelProxy<typeof Account>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Retrieve depepants ids of the give accounts ids.
|
||||
* @param {number[]} accountsIds
|
||||
* @param depGraph
|
||||
* @returns {number[]}
|
||||
*/
|
||||
private getDependantsAccountsIds = (
|
||||
accountsIds: number[],
|
||||
depGraph,
|
||||
): number[] => {
|
||||
const depAccountsIds = [];
|
||||
|
||||
accountsIds.forEach((accountId: number) => {
|
||||
const depAccountIds = depGraph.dependantsOf(accountId);
|
||||
depAccountsIds.push(accountId, ...depAccountIds);
|
||||
});
|
||||
return uniq(depAccountsIds);
|
||||
};
|
||||
|
||||
/**
|
||||
* Finds the dependant accounts ids.
|
||||
* @param {number[]} accountsIds
|
||||
* @returns {number[]}
|
||||
*/
|
||||
private findDependantsAccountsIds = async (
|
||||
accountsIds: number[],
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<number[]> => {
|
||||
const accountsGraph = await this.accountRepository.getDependencyGraph(
|
||||
null,
|
||||
trx,
|
||||
);
|
||||
return this.getDependantsAccountsIds(accountsIds, accountsGraph);
|
||||
};
|
||||
|
||||
/**
|
||||
* Atomic mutation for accounts balances.
|
||||
* @param {number} tenantId
|
||||
* @param {ILedger} ledger
|
||||
* @param {Knex.Transaction} trx -
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
public saveAccountsBalance = async (
|
||||
ledger: ILedger,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> => {
|
||||
// Initiate a new queue for accounts balance mutation.
|
||||
const saveAccountsBalanceQueue = async.queue(
|
||||
this.saveAccountBalanceTask,
|
||||
10,
|
||||
);
|
||||
const effectedAccountsIds = ledger.getAccountsIds();
|
||||
const dependAccountsIds = await this.findDependantsAccountsIds(
|
||||
effectedAccountsIds,
|
||||
trx,
|
||||
);
|
||||
dependAccountsIds.forEach((accountId: number) => {
|
||||
saveAccountsBalanceQueue.push({ ledger, accountId, trx });
|
||||
});
|
||||
if (dependAccountsIds.length > 0) {
|
||||
await saveAccountsBalanceQueue.drain();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Async task mutates the given account balance.
|
||||
* @param {ISaveAccountsBalanceQueuePayload} task
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private saveAccountBalanceTask = async (
|
||||
task: ISaveAccountsBalanceQueuePayload,
|
||||
): Promise<void> => {
|
||||
const { ledger, accountId, trx } = task;
|
||||
|
||||
await this.saveAccountBalanceFromLedger(ledger, accountId, trx);
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves specific account balance from the given ledger.
|
||||
* @param {number} tenantId
|
||||
* @param {ILedger} ledger
|
||||
* @param {number} accountId
|
||||
* @param {Knex.Transaction} trx -
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private saveAccountBalanceFromLedger = async (
|
||||
ledger: ILedger,
|
||||
accountId: number,
|
||||
trx?: Knex.Transaction,
|
||||
): Promise<void> => {
|
||||
const account = await this.accountModel().query(trx).findById(accountId);
|
||||
|
||||
// Filters the ledger entries by the current account.
|
||||
const accountLedger = ledger.whereAccountId(accountId);
|
||||
|
||||
// Retrieves the given tenant metadata.
|
||||
const tenant = await this.tenancyContext.getTenant(true);
|
||||
|
||||
// Detarmines whether the account has foreign currency.
|
||||
const isAccountForeign =
|
||||
account.currencyCode !== tenant.metadata?.baseCurrency;
|
||||
|
||||
// Calculates the closing foreign balance by the given currency if account was has
|
||||
// foreign currency otherwise get closing balance.
|
||||
const closingBalance = isAccountForeign
|
||||
? accountLedger
|
||||
.whereCurrencyCode(account.currencyCode)
|
||||
.getForeignClosingBalance()
|
||||
: accountLedger.getClosingBalance();
|
||||
|
||||
await this.saveAccountBalance(accountId, closingBalance, trx);
|
||||
};
|
||||
|
||||
/**
|
||||
* Saves the account balance.
|
||||
* @param {number} accountId
|
||||
* @param {number} change
|
||||
* @param {Knex.Transaction} trx -
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private saveAccountBalance = async (
|
||||
accountId: number,
|
||||
change: number,
|
||||
trx?: Knex.Transaction,
|
||||
) => {
|
||||
// Ensure the account has atleast zero in amount.
|
||||
await this.accountModel()
|
||||
.query(trx)
|
||||
.findById(accountId)
|
||||
.whereNull('amount')
|
||||
.patch({ amount: 0 });
|
||||
|
||||
// await this.accountModel.changeAmount(
|
||||
// { id: accountId },
|
||||
// 'amount',
|
||||
// change,
|
||||
// trx,
|
||||
// );
|
||||
};
|
||||
}
|
||||
92
packages/server/src/modules/Ledger/types/Ledger.types.ts
Normal file
92
packages/server/src/modules/Ledger/types/Ledger.types.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import { Knex } from 'knex';
|
||||
import * as moment from 'moment';
|
||||
|
||||
export interface ILedger {
|
||||
entries: ILedgerEntry[];
|
||||
|
||||
getEntries(): ILedgerEntry[];
|
||||
|
||||
filter(cb: (entry: ILedgerEntry) => boolean): ILedger;
|
||||
|
||||
whereAccountId(accountId: number): ILedger;
|
||||
whereAccountsIds(accountsIds: number[]): ILedger;
|
||||
whereContactId(contactId: number): ILedger;
|
||||
whereFromDate(fromDate: Date | string): ILedger;
|
||||
whereToDate(toDate: Date | string): ILedger;
|
||||
whereCurrencyCode(currencyCode: string): ILedger;
|
||||
whereBranch(branchId: number): ILedger;
|
||||
whereItem(itemId: number): ILedger;
|
||||
whereProject(projectId: number): ILedger;
|
||||
|
||||
getClosingBalance(): number;
|
||||
getForeignClosingBalance(): number;
|
||||
getClosingDebit(): number;
|
||||
getClosingCredit(): number;
|
||||
|
||||
getContactsIds(): number[];
|
||||
getAccountsIds(): number[];
|
||||
|
||||
reverse(): ILedger;
|
||||
isEmpty(): boolean;
|
||||
}
|
||||
|
||||
export interface ILedgerEntry {
|
||||
id?: number;
|
||||
|
||||
credit: number;
|
||||
debit: number;
|
||||
|
||||
currencyCode: string;
|
||||
exchangeRate: number;
|
||||
|
||||
accountId?: number;
|
||||
accountNormal: string;
|
||||
contactId?: number;
|
||||
date: moment.MomentInput;
|
||||
|
||||
transactionType: string;
|
||||
transactionSubType?: string;
|
||||
|
||||
transactionId: number;
|
||||
|
||||
transactionNumber?: string;
|
||||
|
||||
referenceNumber?: string;
|
||||
index: number;
|
||||
indexGroup?: number;
|
||||
|
||||
note?: string;
|
||||
|
||||
userId?: number;
|
||||
itemId?: number;
|
||||
branchId?: number;
|
||||
projectId?: number;
|
||||
|
||||
taxRateId?: number;
|
||||
taxRate?: number;
|
||||
|
||||
entryId?: number;
|
||||
createdAt?: Date | string;
|
||||
|
||||
costable?: boolean;
|
||||
}
|
||||
|
||||
export interface ISaveLedgerEntryQueuePayload {
|
||||
tenantId: number;
|
||||
entry: ILedgerEntry;
|
||||
trx?: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface ISaveAccountsBalanceQueuePayload {
|
||||
ledger: ILedger;
|
||||
tenantId: number;
|
||||
accountId: number;
|
||||
trx?: Knex.Transaction;
|
||||
}
|
||||
|
||||
export interface ISaleContactsBalanceQueuePayload {
|
||||
ledger: ILedger;
|
||||
tenantId: number;
|
||||
contactId: number;
|
||||
trx?: Knex.Transaction;
|
||||
}
|
||||
42
packages/server/src/modules/Ledger/utils.ts
Normal file
42
packages/server/src/modules/Ledger/utils.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { AccountTransaction } from "../Accounts/models/AccountTransaction.model";
|
||||
import { ILedgerEntry } from "./types/Ledger.types";
|
||||
|
||||
export const transformLedgerEntryToTransaction = (
|
||||
entry: ILedgerEntry
|
||||
): Partial<AccountTransaction> => {
|
||||
return {
|
||||
date: moment(entry.date).toDate(),
|
||||
|
||||
credit: entry.credit,
|
||||
debit: entry.debit,
|
||||
|
||||
currencyCode: entry.currencyCode,
|
||||
exchangeRate: entry.exchangeRate,
|
||||
|
||||
accountId: entry.accountId,
|
||||
contactId: entry.contactId,
|
||||
|
||||
referenceType: entry.transactionType,
|
||||
referenceId: entry.transactionId,
|
||||
|
||||
transactionNumber: entry.transactionNumber,
|
||||
transactionType: entry.transactionSubType,
|
||||
|
||||
referenceNumber: entry.referenceNumber,
|
||||
|
||||
note: entry.note,
|
||||
|
||||
index: entry.index,
|
||||
indexGroup: entry.indexGroup,
|
||||
|
||||
branchId: entry.branchId,
|
||||
userId: entry.userId,
|
||||
itemId: entry.itemId,
|
||||
projectId: entry.projectId,
|
||||
|
||||
// costable: entry.costable,
|
||||
|
||||
taxRateId: entry.taxRateId,
|
||||
taxRate: entry.taxRate,
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user