feat: licenses administration basic authentication.

feat: accounts slug.
feat: duplicate accounts_balance table and merge balance with accounts table.
feat: refactoring customers and vendors.
feat: system user soft deleting.
feat: preventing build tenant database without any subscription.
feat: remove 'password' property from 'req.user' object.
feat: refactoring JournalPoster class.
feat: delete duplicated directories and files.
This commit is contained in:
Ahmed Bouhuolia
2020-09-09 21:30:19 +02:00
parent 98bba3d3a0
commit ad00f140d1
77 changed files with 2431 additions and 1848 deletions

View File

@@ -40,13 +40,84 @@ interface NonInventoryJEntries {
export default class JournalCommands{
journal: JournalPoster;
models: any;
repositories: any;
/**
* Constructor method.
* @param {JournalPoster} journal -
*/
constructor(journal: JournalPoster) {
this.journal = journal;
Object.assign(this, arguments[1]);
this.repositories = this.journal.repositories;
this.models = this.journal.models;
}
/**
* Customer opening balance journals.
* @param {number} customerId
* @param {number} openingBalance
*/
async customerOpeningBalance(customerId: number, openingBalance: number) {
const { accountRepository } = this.repositories;
const openingBalanceAccount = await accountRepository.getBySlug('opening-balance');
const receivableAccount = await accountRepository.getBySlug('accounts-receivable');
const commonEntry = {
referenceType: 'CustomerOpeningBalance',
referenceId: customerId,
contactType: 'Customer',
contactId: customerId,
};
const creditEntry = new JournalEntry({
...commonEntry,
credit: openingBalance,
debit: 0,
account: openingBalanceAccount.id,
});
const debitEntry = new JournalEntry({
...commonEntry,
credit: 0,
debit: openingBalance,
account: receivableAccount.id,
});
this.journal.debit(debitEntry);
this.journal.credit(creditEntry);
}
/**
* Vendor opening balance journals
* @param {number} vendorId
* @param {number} openingBalance
*/
async vendorOpeningBalance(vendorId: number, openingBalance: number) {
const { accountRepository } = this.repositories;
const payableAccount = await accountRepository.getBySlug('accounts-payable');
const otherCost = await accountRepository.getBySlug('other-expenses');
const commonEntry = {
referenceType: 'VendorOpeningBalance',
referenceId: vendorId,
contactType: 'Vendor',
contactId: vendorId,
};
const creditEntry = new JournalEntry({
...commonEntry,
account: payableAccount.id,
credit: openingBalance,
debit: 0,
});
const debitEntry = new JournalEntry({
...commonEntry,
account: otherCost.id,
debit: openingBalance,
credit: 0,
});
this.journal.debit(debitEntry);
this.journal.credit(creditEntry);
}
/**

View File

@@ -0,0 +1,207 @@
import moment from 'moment';
export default class JournalFinancial {
accountsBalanceTable: { [key: number]: number; } = {};
/**
* Retrieve the closing balance for the given account and closing date.
* @param {Number} accountId -
* @param {Date} closingDate -
* @param {string} dataType? -
* @return {number}
*/
getClosingBalance(
accountId: number,
closingDate: Date|string,
dateType: string = 'day'
): number {
let closingBalance = 0;
const momentClosingDate = moment(closingDate);
this.entries.forEach((entry) => {
// Can not continue if not before or event same closing date.
if (
(!momentClosingDate.isAfter(entry.date, dateType) &&
!momentClosingDate.isSame(entry.date, dateType)) ||
(entry.account !== accountId && accountId)
) {
return;
}
if (entry.accountNormal === 'credit') {
closingBalance += entry.credit ? entry.credit : -1 * entry.debit;
} else if (entry.accountNormal === 'debit') {
closingBalance += entry.debit ? entry.debit : -1 * entry.credit;
}
});
return closingBalance;
}
/**
* Retrieve the given account balance with dependencies accounts.
* @param {Number} accountId
* @param {Date} closingDate
* @param {String} dateType
* @return {Number}
*/
getAccountBalance(accountId: number, closingDate: Date|string, dateType: string) {
const accountNode = this.accountsDepGraph.getNodeData(accountId);
const depAccountsIds = this.accountsDepGraph.dependenciesOf(accountId);
const depAccounts = depAccountsIds
.map((id) => this.accountsDepGraph.getNodeData(id));
let balance: number = 0;
[...depAccounts, accountNode].forEach((account) => {
const closingBalance = this.getClosingBalance(
account.id,
closingDate,
dateType
);
this.accountsBalanceTable[account.id] = closingBalance;
balance += this.accountsBalanceTable[account.id];
});
return balance;
}
/**
* Retrieve the credit/debit sumation for the given account and date.
* @param {Number} account -
* @param {Date|String} closingDate -
*/
getTrialBalance(accountId, closingDate, dateType) {
const momentClosingDate = moment(closingDate);
const result = {
credit: 0,
debit: 0,
balance: 0,
};
this.entries.forEach((entry) => {
if (
(!momentClosingDate.isAfter(entry.date, dateType) &&
!momentClosingDate.isSame(entry.date, dateType)) ||
(entry.account !== accountId && accountId)
) {
return;
}
result.credit += entry.credit;
result.debit += entry.debit;
if (entry.accountNormal === 'credit') {
result.balance += entry.credit - entry.debit;
} else if (entry.accountNormal === 'debit') {
result.balance += entry.debit - entry.credit;
}
});
return result;
}
/**
* Retrieve trial balance of the given account with depends.
* @param {Number} accountId
* @param {Date} closingDate
* @param {String} dateType
* @return {Number}
*/
getTrialBalanceWithDepands(accountId: number, closingDate: Date, dateType: string) {
const accountNode = this.accountsDepGraph.getNodeData(accountId);
const depAccountsIds = this.accountsDepGraph.dependenciesOf(accountId);
const depAccounts = depAccountsIds.map((id) =>
this.accountsDepGraph.getNodeData(id)
);
const trialBalance = { credit: 0, debit: 0, balance: 0 };
[...depAccounts, accountNode].forEach((account) => {
const _trialBalance = this.getTrialBalance(
account.id,
closingDate,
dateType
);
trialBalance.credit += _trialBalance.credit;
trialBalance.debit += _trialBalance.debit;
trialBalance.balance += _trialBalance.balance;
});
return trialBalance;
}
getContactTrialBalance(
accountId: number,
contactId: number,
contactType: string,
closingDate: Date|string,
openingDate: Date|string,
) {
const momentClosingDate = moment(closingDate);
const momentOpeningDate = moment(openingDate);
const trial = {
credit: 0,
debit: 0,
balance: 0,
};
this.entries.forEach((entry) => {
if (
(closingDate &&
!momentClosingDate.isAfter(entry.date, 'day') &&
!momentClosingDate.isSame(entry.date, 'day')) ||
(openingDate &&
!momentOpeningDate.isBefore(entry.date, 'day') &&
!momentOpeningDate.isSame(entry.date)) ||
(accountId && entry.account !== accountId) ||
(contactId && entry.contactId !== contactId) ||
entry.contactType !== contactType
) {
return;
}
if (entry.credit) {
trial.balance -= entry.credit;
trial.credit += entry.credit;
}
if (entry.debit) {
trial.balance += entry.debit;
trial.debit += entry.debit;
}
});
return trial;
}
/**
* Retrieve total balnace of the given customer/vendor contact.
* @param {Number} accountId
* @param {Number} contactId
* @param {String} contactType
* @param {Date} closingDate
*/
getContactBalance(
accountId: number,
contactId: number,
contactType: string,
closingDate: Date,
openingDate: Date,
) {
const momentClosingDate = moment(closingDate);
let balance = 0;
this.entries.forEach((entry) => {
if (
(closingDate &&
!momentClosingDate.isAfter(entry.date, 'day') &&
!momentClosingDate.isSame(entry.date, 'day')) ||
(entry.account !== accountId && accountId) ||
(contactId && entry.contactId !== contactId) ||
entry.contactType !== contactType
) {
return;
}
if (entry.credit) {
balance -= entry.credit;
}
if (entry.debit) {
balance += entry.debit;
}
});
return balance;
}
}

View File

@@ -1,502 +0,0 @@
import { pick } from 'lodash';
import moment from 'moment';
import JournalEntry from '@/services/Accounting/JournalEntry';
import AccountTransaction from '@/models/AccountTransaction';
import AccountBalance from '@/models/AccountBalance';
import { promiseSerial } from '@/utils';
import Account from '@/models/Account';
import NestedSet from '../../collection/NestedSet';
export default class JournalPoster {
/**
* Journal poster constructor.
*/
constructor(accountsGraph) {
this.entries = [];
this.balancesChange = {};
this.deletedEntriesIds = [];
this.accountsBalanceTable = {};
this.accountsGraph = accountsGraph;
}
/**
* Writes the credit entry for the given account.
* @param {JournalEntry} entry -
*/
credit(entryModel) {
if (entryModel instanceof JournalEntry === false) {
throw new Error('The entry is not instance of JournalEntry.');
}
this.entries.push(entryModel.entry);
this.setAccountBalanceChange(entryModel.entry, 'credit');
}
/**
* Writes the debit entry for the given account.
* @param {JournalEntry} entry -
*/
debit(entryModel) {
if (entryModel instanceof JournalEntry === false) {
throw new Error('The entry is not instance of JournalEntry.');
}
this.entries.push(entryModel.entry);
this.setAccountBalanceChange(entryModel.entry, 'debit');
}
/**
* Sets account balance change.
* @param {JournalEntry} entry
* @param {String} type
*/
setAccountBalanceChange(entry, entryType) {
const depAccountsIds = this.accountsGraph.dependantsOf(entry.account);
const balanceChangeEntry = {
debit: entry.debit,
credit: entry.credit,
entryType,
accountNormal: entry.accountNormal,
};
this._setAccountBalanceChange({
...balanceChangeEntry,
accountId: entry.account,
});
if (entry.contactType && entry.contactId) {
}
// Effect parent accounts of the given account id.
depAccountsIds.forEach((accountId) => {
this._setAccountBalanceChange({
...balanceChangeEntry,
accountId,
});
});
}
/**
* Sets account balance change.
* @private
*/
_setAccountBalanceChange({
accountId,
accountNormal,
debit,
credit,
entryType,
}) {
if (!this.balancesChange[accountId]) {
this.balancesChange[accountId] = 0;
}
let change = 0;
if (accountNormal === 'credit') {
change = entryType === 'credit' ? credit : -1 * debit;
} else if (accountNormal === 'debit') {
change = entryType === 'debit' ? debit : -1 * credit;
}
this.balancesChange[accountId] += change;
}
/**
* Set contact balance change.
* @param {Object} param -
*/
_setContactBalanceChange({
contactType,
contactId,
accountNormal,
debit,
credit,
entryType,
}) {
}
/**
* Mapping the balance change to list.
*/
mapBalanceChangesToList() {
const mappedList = [];
Object.keys(this.balancesChange).forEach((accountId) => {
const balance = this.balancesChange[accountId];
mappedList.push({
account_id: accountId,
amount: balance,
});
});
return mappedList;
}
/**
* Saves the balance change of journal entries.
*/
async saveBalance() {
const balancesList = this.mapBalanceChangesToList();
const balanceUpdateOpers = [];
const balanceInsertOpers = [];
const balanceFindOneOpers = [];
let balanceAccounts = [];
balancesList.forEach((balance) => {
const oper = AccountBalance.tenant()
.query()
.findOne('account_id', balance.account_id);
balanceFindOneOpers.push(oper);
});
balanceAccounts = await Promise.all(balanceFindOneOpers);
balancesList.forEach((balance) => {
const method = balance.amount < 0 ? 'decrement' : 'increment';
// Detarmine if the account balance is already exists or not.
const foundAccBalance = balanceAccounts.some(
(account) => account && account.account_id === balance.account_id
);
if (foundAccBalance) {
const query = AccountBalance.tenant()
.query()
[method]('amount', Math.abs(balance.amount))
.where('account_id', balance.account_id);
balanceUpdateOpers.push(query);
} else {
const query = AccountBalance.tenant().query().insert({
account_id: balance.account_id,
amount: balance.amount,
currency_code: 'USD',
});
balanceInsertOpers.push(query);
}
});
await Promise.all([...balanceUpdateOpers, ...balanceInsertOpers]);
}
/**
* Saves the stacked journal entries to the storage.
*/
async saveEntries() {
const saveOperations = [];
this.entries.forEach((entry) => {
const oper = AccountTransaction.tenant()
.query()
.insert({
accountId: entry.account,
...pick(entry, [
'credit',
'debit',
'transactionType',
'date',
'userId',
'referenceType',
'referenceId',
'note',
'contactId',
'contactType',
]),
});
saveOperations.push(() => oper);
});
await promiseSerial(saveOperations);
}
/**
* Reverses the stacked journal entries.
*/
reverseEntries() {
const reverseEntries = [];
this.entries.forEach((entry) => {
const reverseEntry = { ...entry };
if (entry.credit) {
reverseEntry.debit = entry.credit;
}
if (entry.debit) {
reverseEntry.credit = entry.debit;
}
reverseEntries.push(reverseEntry);
});
this.entries = reverseEntries;
}
/**
*
* @param {Array} ids -
*/
removeEntries(ids = []) {
const targetIds = ids.length <= 0 ? this.entries.map((e) => e.id) : ids;
const removeEntries = this.entries.filter(
(e) => targetIds.indexOf(e.id) !== -1
);
this.entries = this.entries.filter((e) => targetIds.indexOf(e.id) === -1);
removeEntries.forEach((entry) => {
entry.credit = -1 * entry.credit;
entry.debit = -1 * entry.debit;
this.setAccountBalanceChange(entry, entry.accountNormal);
});
this.deletedEntriesIds.push(...removeEntries.map((entry) => entry.id));
}
/**
* Revert the given transactions.
* @param {*} entries
*/
removeTransactions(entries) {
this.loadEntries(entries);
this.deletedEntriesIds.push(...entriesIDsShouldDel);
}
/**
* Delete all the stacked entries.
*/
async deleteEntries() {
if (this.deletedEntriesIds.length > 0) {
await AccountTransaction.tenant()
.query()
.whereIn('id', this.deletedEntriesIds)
.delete();
}
}
/**
* Retrieve the closing balance for the given account and closing date.
* @param {Number} accountId -
* @param {Date} closingDate -
*/
getClosingBalance(accountId, closingDate, dateType = 'day') {
let closingBalance = 0;
const momentClosingDate = moment(closingDate);
this.entries.forEach((entry) => {
// Can not continue if not before or event same closing date.
if (
(!momentClosingDate.isAfter(entry.date, dateType) &&
!momentClosingDate.isSame(entry.date, dateType)) ||
(entry.account !== accountId && accountId)
) {
return;
}
if (entry.accountNormal === 'credit') {
closingBalance += entry.credit ? entry.credit : -1 * entry.debit;
} else if (entry.accountNormal === 'debit') {
closingBalance += entry.debit ? entry.debit : -1 * entry.credit;
}
});
return closingBalance;
}
/**
* Retrieve the given account balance with dependencies accounts.
* @param {Number} accountId
* @param {Date} closingDate
* @param {String} dateType
* @return {Number}
*/
getAccountBalance(accountId, closingDate, dateType) {
const accountNode = this.accountsGraph.getNodeData(accountId);
const depAccountsIds = this.accountsGraph.dependenciesOf(accountId);
const depAccounts = depAccountsIds.map((id) =>
this.accountsGraph.getNodeData(id)
);
let balance = 0;
[...depAccounts, accountNode].forEach((account) => {
// if (!this.accountsBalanceTable[account.id]) {
const closingBalance = this.getClosingBalance(
account.id,
closingDate,
dateType
);
this.accountsBalanceTable[account.id] = closingBalance;
// }
balance += this.accountsBalanceTable[account.id];
});
return balance;
}
/**
* Retrieve the credit/debit sumation for the given account and date.
* @param {Number} account -
* @param {Date|String} closingDate -
*/
getTrialBalance(accountId, closingDate, dateType) {
const momentClosingDate = moment(closingDate);
const result = {
credit: 0,
debit: 0,
balance: 0,
};
this.entries.forEach((entry) => {
if (
(!momentClosingDate.isAfter(entry.date, dateType) &&
!momentClosingDate.isSame(entry.date, dateType)) ||
(entry.account !== accountId && accountId)
) {
return;
}
result.credit += entry.credit;
result.debit += entry.debit;
if (entry.accountNormal === 'credit') {
result.balance += entry.credit - entry.debit;
} else if (entry.accountNormal === 'debit') {
result.balance += entry.debit - entry.credit;
}
});
return result;
}
/**
* Retrieve trial balance of the given account with depends.
* @param {Number} accountId
* @param {Date} closingDate
* @param {String} dateType
* @return {Number}
*/
getTrialBalanceWithDepands(accountId, closingDate, dateType) {
const accountNode = this.accountsGraph.getNodeData(accountId);
const depAccountsIds = this.accountsGraph.dependenciesOf(accountId);
const depAccounts = depAccountsIds.map((id) =>
this.accountsGraph.getNodeData(id)
);
const trialBalance = { credit: 0, debit: 0, balance: 0 };
[...depAccounts, accountNode].forEach((account) => {
const _trialBalance = this.getTrialBalance(
account.id,
closingDate,
dateType
);
trialBalance.credit += _trialBalance.credit;
trialBalance.debit += _trialBalance.debit;
trialBalance.balance += _trialBalance.balance;
});
return trialBalance;
}
getContactTrialBalance(
accountId,
contactId,
contactType,
closingDate,
openingDate
) {
const momentClosingDate = moment(closingDate);
const momentOpeningDate = moment(openingDate);
const trial = {
credit: 0,
debit: 0,
balance: 0,
};
this.entries.forEach((entry) => {
if (
(closingDate &&
!momentClosingDate.isAfter(entry.date, 'day') &&
!momentClosingDate.isSame(entry.date, 'day')) ||
(openingDate &&
!momentOpeningDate.isBefore(entry.date, 'day') &&
!momentOpeningDate.isSame(entry.date)) ||
(accountId && entry.account !== accountId) ||
(contactId && entry.contactId !== contactId) ||
entry.contactType !== contactType
) {
return;
}
if (entry.credit) {
trial.balance -= entry.credit;
trial.credit += entry.credit;
}
if (entry.debit) {
trial.balance += entry.debit;
trial.debit += entry.debit;
}
});
return trial;
}
/**
* Retrieve total balnace of the given customer/vendor contact.
* @param {Number} accountId
* @param {Number} contactId
* @param {String} contactType
* @param {Date} closingDate
*/
getContactBalance(
accountId,
contactId,
contactType,
closingDate,
openingDate
) {
const momentClosingDate = moment(closingDate);
let balance = 0;
this.entries.forEach((entry) => {
if (
(closingDate &&
!momentClosingDate.isAfter(entry.date, 'day') &&
!momentClosingDate.isSame(entry.date, 'day')) ||
(entry.account !== accountId && accountId) ||
(contactId && entry.contactId !== contactId) ||
entry.contactType !== contactType
) {
return;
}
if (entry.credit) {
balance -= entry.credit;
}
if (entry.debit) {
balance += entry.debit;
}
});
return balance;
}
/**
* Load fetched accounts journal entries.
* @param {Array} entries -
*/
loadEntries(entries) {
entries.forEach((entry) => {
this.entries.push({
...entry,
account: entry.account ? entry.account.id : entry.accountId,
accountNormal:
entry.account && entry.account.type
? entry.account.type.normal
: entry.accountNormal,
});
});
}
/**
* Calculates the entries balance change.
*/
calculateEntriesBalanceChange() {
this.entries.forEach((entry) => {
if (entry.credit) {
this.setAccountBalanceChange(entry, 'credit');
}
if (entry.debit) {
this.setAccountBalanceChange(entry, 'debit');
}
});
}
}

View File

@@ -0,0 +1,337 @@
import { omit } from 'lodash';
import { Container } from 'typedi';
import JournalEntry from '@/services/Accounting/JournalEntry';
import TenancyService from '@/services/Tenancy/TenancyService';
import {
IJournalEntry,
IJournalPoster,
IAccountChange,
IAccountsChange,
TEntryType,
} from '@/interfaces';
export default class JournalPoster implements IJournalPoster {
tenantId: number;
tenancy: TenancyService;
logger: any;
models: any;
repositories: any;
deletedEntriesIds: number[] = [];
entries: IJournalEntry[] = [];
balancesChange: IAccountsChange = {};
accountsDepGraph: IAccountsChange = {};
/**
* Journal poster constructor.
* @param {number} tenantId -
*/
constructor(
tenantId: number,
) {
this.initTenancy();
this.tenantId = tenantId;
this.models = this.tenancy.models(tenantId);
this.repositories = this.tenancy.repositories(tenantId);
}
/**
* Initial tenancy.
* @private
*/
private initTenancy() {
try {
this.tenancy = Container.get(TenancyService);
this.logger = Container.get('logger');
} catch (exception) {
throw new Error('Should execute this class inside tenancy area.');
}
}
/**
* Async initialize acccounts dependency graph.
* @private
* @returns {Promise<void>}
*/
private async initializeAccountsDepGraph(): Promise<void> {
const { accountRepository } = this.repositories;
const accountsDepGraph = await accountRepository.getDependencyGraph();
this.accountsDepGraph = accountsDepGraph;
}
/**
* Writes the credit entry for the given account.
* @param {IJournalEntry} entry -
*/
public credit(entryModel: IJournalEntry): void {
if (entryModel instanceof JournalEntry === false) {
throw new Error('The entry is not instance of JournalEntry.');
}
this.entries.push(entryModel.entry);
this.setAccountBalanceChange(entryModel.entry);
}
/**
* Writes the debit entry for the given account.
* @param {JournalEntry} entry -
*/
public debit(entryModel: IJournalEntry): void {
if (entryModel instanceof JournalEntry === false) {
throw new Error('The entry is not instance of JournalEntry.');
}
this.entries.push(entryModel.entry);
this.setAccountBalanceChange(entryModel.entry);
}
/**
* Sets account balance change.
* @param {JournalEntry} entry
* @param {String} type
*/
private setAccountBalanceChange(entry: IJournalEntry): void {
const accountChange: IAccountChange = {
debit: entry.debit,
credit: entry.credit,
};
this._setAccountBalanceChange(entry.account, accountChange);
}
/**
* Sets account balance change.
* @private
* @param {number} accountId -
* @param {IAccountChange} accountChange
*/
private _setAccountBalanceChange(
accountId: number,
accountChange: IAccountChange
) {
this.balancesChange = this.accountBalanceChangeReducer(
this.balancesChange, accountId, accountChange,
);
}
/**
* Accounts balance change reducer.
* @param {IAccountsChange} balancesChange
* @param {number} accountId
* @param {IAccountChange} accountChange
* @return {IAccountChange}
*/
private accountBalanceChangeReducer(
balancesChange: IAccountsChange,
accountId: number,
accountChange: IAccountChange,
) {
const change = { ...balancesChange };
if (!change[accountId]) {
change[accountId] = { credit: 0, debit: 0 };
}
if (accountChange.credit) {
change[accountId].credit += accountChange.credit;
}
if (accountChange.debit) {
change[accountId].debit += accountChange.debit;
}
return change;
}
/**
* Converts balance changes to array.
* @private
* @param {IAccountsChange} accountsChange -
* @return {Promise<{ account: number, change: number }>}
*/
private async convertBalanceChangesToArr(
accountsChange: IAccountsChange
) : Promise<{ account: number, change: number }[]>{
const { accountTypeRepository } = this.repositories;
const mappedList: { account: number, change: number }[] = [];
const accountsIds: number[] = Object.keys(accountsChange).map(id => parseInt(id, 10));
await Promise.all(
accountsIds.map(async (account: number) => {
const accountChange = accountsChange[account];
const accountNode = this.accountsDepGraph.getNodeData(account);
const accountTypeMeta = await accountTypeRepository.getTypeMeta(accountNode.accountTypeId);
const { normal }: { normal: TEntryType } = accountTypeMeta;
let change = 0;
if (accountChange.credit) {
change = (normal === 'credit') ? accountChange.credit : -1 * accountChange.credit;
}
if (accountChange.debit) {
change = (normal === 'debit') ? accountChange.debit : -1 * accountChange.debit;
}
mappedList.push({ account, change });
}),
);
return mappedList;
}
/**
* Saves the balance change of journal entries.
* @returns {Promise<void>}
*/
public async saveBalance() {
await this.initializeAccountsDepGraph();
const { Account } = this.models;
const accountsChange = this.balanceChangeWithDepends(this.balancesChange);
const balancesList = await this.convertBalanceChangesToArr(accountsChange);
const balancesAccounts = balancesList.map(b => b.account);
// Ensure the accounts has atleast zero in amount.
await Account.query().where('amount', null).whereIn('id', balancesAccounts)
.patch({ amount: 0 });
const balanceUpdateOpers: Promise<void>[] = [];
balancesList.forEach((balance: { account: number, change: number }) => {
const method: string = (balance.change < 0) ? 'decrement' : 'increment';
this.logger.info('[journal_poster] increment/decrement account balance.', {
balance, tenantId: this.tenantId,
})
const query = Account.query()
[method]('amount', Math.abs(balance.change))
.where('id', balance.account);
balanceUpdateOpers.push(query);
});
await Promise.all(balanceUpdateOpers);
this.resetAccountsBalanceChange();
}
/**
* Changes all accounts that dependencies of changed accounts.
* @param {IAccountsChange} accountsChange
* @returns {IAccountsChange}
*/
private balanceChangeWithDepends(accountsChange: IAccountsChange): IAccountsChange {
const accountsIds = Object.keys(accountsChange);
let changes: IAccountsChange = {};
accountsIds.forEach((accountId) => {
const accountChange = accountsChange[accountId];
const depAccountsIds = this.accountsDepGraph.dependenciesOf(accountId);
[accountId, ...depAccountsIds].forEach((account) => {
changes = this.accountBalanceChangeReducer(changes, account, accountChange);
});
});
return changes;
}
/**
* Resets accounts balance change.
* @private
*/
private resetAccountsBalanceChange() {
this.balancesChange = {};
}
/**
* Saves the stacked journal entries to the storage.
* @returns {Promise<void>}
*/
public async saveEntries() {
const { AccountTransaction } = this.models;
const saveOperations: Promise<void>[] = [];
this.entries.forEach((entry) => {
const oper = AccountTransaction.query()
.insert({
accountId: entry.account,
...omit(entry, ['account']),
});
saveOperations.push(oper);
});
await Promise.all(saveOperations);
}
/**
* Reverses the stacked journal entries.
*/
public reverseEntries() {
const reverseEntries: IJournalEntry[] = [];
this.entries.forEach((entry) => {
const reverseEntry = { ...entry };
if (entry.credit) {
reverseEntry.debit = entry.credit;
}
if (entry.debit) {
reverseEntry.credit = entry.debit;
}
reverseEntries.push(reverseEntry);
});
this.entries = reverseEntries;
}
/**
* Removes all stored entries or by the given in ids.
* @param {Array} ids -
*/
removeEntries(ids: number[] = []) {
const targetIds = ids.length <= 0 ? this.entries.map((e) => e.id) : ids;
const removeEntries = this.entries.filter(
(e) => targetIds.indexOf(e.id) !== -1
);
this.entries = this.entries.filter((e) => targetIds.indexOf(e.id) === -1);
removeEntries.forEach((entry) => {
entry.credit = -1 * entry.credit;
entry.debit = -1 * entry.debit;
this.setAccountBalanceChange(entry, entry.accountNormal);
});
this.deletedEntriesIds.push(...removeEntries.map((entry) => entry.id));
}
/**
* Delete all the stacked entries.
* @return {Promise<void>}
*/
public async deleteEntries() {
const { AccountTransaction } = this.models;
if (this.deletedEntriesIds.length > 0) {
await AccountTransaction.query()
.whereIn('id', this.deletedEntriesIds)
.delete();
}
}
/**
* Load fetched accounts journal entries.
* @param {IJournalEntry[]} entries -
*/
loadEntries(entries: IJournalEntry[]): void {
entries.forEach((entry: IJournalEntry) => {
this.entries.push({
...entry,
account: entry.account ? entry.account.id : entry.accountId,
});
});
}
/**
* Calculates the entries balance change.
* @public
*/
public calculateEntriesBalanceChange() {
this.entries.forEach((entry) => {
if (entry.credit) {
this.setAccountBalanceChange(entry, 'credit');
}
if (entry.debit) {
this.setAccountBalanceChange(entry, 'debit');
}
});
}
}

View File

@@ -1,4 +1,5 @@
import { Inject, Service } from 'typedi';
import { kebabCase } from 'lodash'
import TenancyService from '@/services/Tenancy/TenancyService';
import { ServiceError } from '@/exceptions';
import { IAccountDTO, IAccount } from '@/interfaces';
@@ -174,6 +175,7 @@ export default class AccountsService {
}
const account = await Account.query().insertAndFetch({
...accountDTO,
slug: kebabCase(accountDTO.name),
});
this.logger.info('[account] account created successfully.', { account, accountDTO });
return account;

View File

@@ -88,6 +88,10 @@ export default class AuthenticationService {
this.eventDispatcher.dispatch(events.auth.login, {
emailOrPhone, password,
});
// Remove password property from user object.
Reflect.deleteProperty(user, 'password');
return { user, token };
}

View File

@@ -1,18 +1,18 @@
import NodeCache from 'node-cache';
class Cache {
export default class Cache {
cache: NodeCache;
constructor() {
constructor(config?: object) {
this.cache = new NodeCache({
// stdTTL: 9999999,
// checkperiod: 9999999 * 0.2,
useClones: false,
...config,
});
}
get(key, storeFunction) {
get(key: string, storeFunction: () => Promise<any>) {
const value = this.cache.get(key);
if (value) {
return Promise.resolve(value);
}
@@ -22,11 +22,11 @@ class Cache {
});
}
set(key, results) {
set(key: string, results: any) {
this.cache.set(key, results);
}
del(keys) {
del(keys: string) {
this.cache.del(keys);
}
@@ -46,7 +46,4 @@ class Cache {
flush() {
this.cache.flushAll();
}
}
export default new Cache();
}

View File

@@ -0,0 +1,131 @@
import { Inject, Service } from 'typedi';
import { difference } from 'lodash';
import { ServiceError } from "@/exceptions";
import TenancyService from '@/services/Tenancy/TenancyService';
import {
IContact,
IContactNewDTO,
IContactEditDTO,
} from "@/interfaces";
type TContactService = 'customer' | 'vendor';
@Service()
export default class ContactsService {
@Inject()
tenancy: TenancyService;
@Inject('logger')
logger: any;
/**
* Get the given contact or throw not found contact.
* @param {number} tenantId
* @param {number} contactId
* @param {TContactService} contactService
* @return {Promise<IContact>}
*/
private async getContactByIdOrThrowError(tenantId: number, contactId: number, contactService: TContactService) {
const { Contact } = this.tenancy.models(tenantId);
this.logger.info('[contact] trying to validate contact existance.', { tenantId, contactId });
const contact = await Contact.query().findById(contactId).where('contact_service', contactService);
if (!contact) {
throw new ServiceError('contact_not_found');
}
return contact;
}
/**
* Creates a new contact on the storage.
* @param {number} tenantId
* @param {TContactService} contactService
* @param {IContactDTO} contactDTO
*/
async newContact(tenantId: number, contactDTO: IContactNewDTO, contactService: TContactService) {
const { Contact } = this.tenancy.models(tenantId);
this.logger.info('[contacts] trying to insert contact to the storage.', { tenantId, contactDTO });
const contact = await Contact.query().insert({ contactService, ...contactDTO });
this.logger.info('[contacts] contact inserted successfully.', { tenantId, contact });
return contact;
}
/**
* Edit details of the given on the storage.
* @param {number} tenantId
* @param {number} contactId
* @param {TContactService} contactService
* @param {IContactDTO} contactDTO
*/
async editContact(tenantId: number, contactId: number, contactDTO: IContactEditDTO, contactService: TContactService) {
const { Contact } = this.tenancy.models(tenantId);
const contact = await this.getContactByIdOrThrowError(tenantId, contactId, contactService);
this.logger.info('[contacts] trying to edit the given contact details.', { tenantId, contactId, contactDTO });
await Contact.query().findById(contactId).patch({ ...contactDTO })
}
/**
* Deletes the given contact from the storage.
* @param {number} tenantId
* @param {number} contactId
* @param {TContactService} contactService
* @return {Promise<void>}
*/
async deleteContact(tenantId: number, contactId: number, contactService: TContactService) {
const { Contact } = this.tenancy.models(tenantId);
const contact = await this.getContactByIdOrThrowError(tenantId, contactId, contactService);
this.logger.info('[contacts] trying to delete the given contact.', { tenantId, contactId });
await Contact.query().findById(contactId).delete();
}
/**
* Get contact details of the given contact id.
* @param {number} tenantId
* @param {number} contactId
* @param {TContactService} contactService
* @returns {Promise<IContact>}
*/
async getContact(tenantId: number, contactId: number, contactService: TContactService) {
return this.getContactByIdOrThrowError(tenantId, contactId, contactService);
}
/**
* Retrieve contacts or throw not found error if one of ids were not found
* on the storage.
* @param {number} tenantId
* @param {number[]} contactsIds
* @param {TContactService} contactService
* @return {Promise<IContact>}
*/
async getContactsOrThrowErrorNotFound(tenantId: number, contactsIds: number[], contactService: TContactService) {
const { Contact } = this.tenancy.models(tenantId);
const contacts = await Contact.query().whereIn('id', contactsIds).where('contact_service', contactService);
const storedContactsIds = contacts.map((contact: IContact) => contact.id);
const notFoundCustomers = difference(contactsIds, storedContactsIds);
if (notFoundCustomers.length > 0) {
throw new ServiceError('contacts_not_found');
}
return contacts;
}
/**
* Deletes the given contacts in bulk.
* @param {number} tenantId
* @param {number[]} contactsIds
* @param {TContactService} contactService
* @return {Promise<void>}
*/
async deleteBulkContacts(tenantId: number, contactsIds: number[], contactService: TContactService) {
const { Contact } = this.tenancy.models(tenantId);
this.getContactsOrThrowErrorNotFound(tenantId, contactsIds, contactService);
await Contact.query().whereIn('id', contactsIds).delete();
}
}

View File

@@ -0,0 +1,171 @@
import { Inject, Service } from 'typedi';
import { omit, difference } from 'lodash';
import JournalPoster from "@/services/Accounting/JournalPoster";
import JournalCommands from "@/services/Accounting/JournalCommands";
import ContactsService from '@/services/Contacts/ContactsService';
import {
ICustomerNewDTO,
ICustomerEditDTO,
} from '@/interfaces';
import { ServiceError } from '@/exceptions';
import TenancyService from '@/services/Tenancy/TenancyService';
import { ICustomer } from 'src/interfaces';
@Service()
export default class CustomersService {
@Inject()
contactService: ContactsService;
@Inject()
tenancy: TenancyService;
/**
* Converts customer to contact DTO.
* @param {ICustomerNewDTO|ICustomerEditDTO} customerDTO
* @returns {IContactDTO}
*/
customerToContactDTO(customerDTO: ICustomerNewDTO|ICustomerEditDTO) {
return {
...omit(customerDTO, ['customerType']),
contactType: customerDTO.customerType,
active: (typeof customerDTO.active === 'undefined') ?
true : customerDTO.active,
};
}
/**
* Creates a new customer.
* @param {number} tenantId
* @param {ICustomerNewDTO} customerDTO
* @return {Promise<void>}
*/
async newCustomer(tenantId: number, customerDTO: ICustomerNewDTO) {
const contactDTO = this.customerToContactDTO(customerDTO)
const customer = await this.contactService.newContact(tenantId, contactDTO, 'customer');
// Writes the customer opening balance journal entries.
if (customer.openingBalance) {
await this.writeCustomerOpeningBalanceJournal(
tenantId,
customer.id,
customer.openingBalance,
);
}
return customer;
}
/**
* Edits details of the given customer.
* @param {number} tenantId
* @param {ICustomerEditDTO} customerDTO
*/
async editCustomer(tenantId: number, customerId: number, customerDTO: ICustomerEditDTO) {
const contactDTO = this.customerToContactDTO(customerDTO);
return this.contactService.editContact(tenantId, customerId, contactDTO, 'customer');
}
/**
* Deletes the given customer from the storage.
* @param {number} tenantId
* @param {number} customerId
* @return {Promise<void>}
*/
async deleteCustomer(tenantId: number, customerId: number) {
await this.customerHasNoInvoicesOrThrowError(tenantId, customerId);
return this.contactService.deleteContact(tenantId, customerId, 'customer');
}
/**
* Retrieve the given customer details.
* @param {number} tenantId
* @param {number} customerId
*/
async getCustomer(tenantId: number, customerId: number) {
return this.contactService.getContact(tenantId, customerId, 'customer');
}
/**
* Writes customer opening balance journal entries.
* @param {number} tenantId
* @param {number} customerId
* @param {number} openingBalance
* @return {Promise<void>}
*/
async writeCustomerOpeningBalanceJournal(
tenantId: number,
customerId: number,
openingBalance: number,
) {
const journal = new JournalPoster(tenantId);
const journalCommands = new JournalCommands(journal);
await journalCommands.customerOpeningBalance(customerId, openingBalance)
await Promise.all([
journal.saveBalance(),
journal.saveEntries(),
]);
}
/**
* Retrieve the given customers or throw error if one of them not found.
* @param {numebr} tenantId
* @param {number[]} customersIds
*/
getCustomersOrThrowErrorNotFound(tenantId: number, customersIds: number[]) {
return this.contactService.getContactsOrThrowErrorNotFound(tenantId, customersIds, 'customer');
}
/**
* Deletes the given customers from the storage.
* @param {number} tenantId
* @param {number[]} customersIds
* @return {Promise<void>}
*/
async deleteBulkCustomers(tenantId: number, customersIds: number[]) {
const { Contact } = this.tenancy.models(tenantId);
await this.getCustomersOrThrowErrorNotFound(tenantId, customersIds);
await this.customersHaveNoInvoicesOrThrowError(tenantId, customersIds);
await Contact.query().whereIn('id', customersIds).delete();
}
/**
* Validates the customer has no associated sales invoice
* or throw service error.
* @param {number} tenantId
* @param {number} customerId
*/
async customerHasNoInvoicesOrThrowError(tenantId: number, customerId: number) {
const { customerRepository } = this.tenancy.repositories(tenantId);
const salesInvoice = await customerRepository.getSalesInvoices(customerId);
if (salesInvoice.length > 0) {
throw new ServiceError('customer_has_invoices');
}
}
/**
* Throws error in case one of customers have associated sales invoices.
* @param {number} tenantId
* @param {number[]} customersIds
* @throws {ServiceError}
*/
async customersHaveNoInvoicesOrThrowError(tenantId: number, customersIds: number[]) {
const { customerRepository } = this.tenancy.repositories(tenantId);
const customersWithInvoices = await customerRepository.customersWithSalesInvoices(
customersIds,
);
const customersIdsWithInvoice = customersWithInvoices
.filter((customer: ICustomer) => customer.salesInvoices.length > 0)
.map((customer: ICustomer) => customer.id);
const customersHaveInvoices = difference(customersIds, customersIdsWithInvoice);
if (customersHaveInvoices.length > 0) {
throw new ServiceError('some_customers_have_invoices');
}
}
}

View File

@@ -0,0 +1,167 @@
import { Inject, Service } from 'typedi';
import { difference } from 'lodash';
import JournalPoster from "@/services/Accounting/JournalPoster";
import JournalCommands from "@/services/Accounting/JournalCommands";
import ContactsService from '@/services/Contacts/ContactsService';
import {
IVendorNewDTO,
IVendorEditDTO,
IVendor
} from '@/interfaces';
import { ServiceError } from '@/exceptions';
import TenancyService from '@/services/Tenancy/TenancyService';
@Service()
export default class VendorsService {
@Inject()
contactService: ContactsService;
@Inject()
tenancy: TenancyService;
/**
* Converts vendor to contact DTO.
* @param {IVendorNewDTO|IVendorEditDTO} vendorDTO
* @returns {IContactDTO}
*/
vendorToContactDTO(vendorDTO: IVendorNewDTO|IVendorEditDTO) {
return {
...vendorDTO,
active: (typeof vendorDTO.active === 'undefined') ?
true : vendorDTO.active,
};
}
/**
* Creates a new vendor.
* @param {number} tenantId
* @param {IVendorNewDTO} vendorDTO
* @return {Promise<void>}
*/
async newVendor(tenantId: number, vendorDTO: IVendorNewDTO) {
const contactDTO = this.vendorToContactDTO(vendorDTO)
const vendor = await this.contactService.newContact(tenantId, contactDTO, 'vendor');
// Writes the vendor opening balance journal entries.
if (vendor.openingBalance) {
await this.writeVendorOpeningBalanceJournal(
tenantId,
vendor.id,
vendor.openingBalance,
);
}
return vendor;
}
/**
* Edits details of the given vendor.
* @param {number} tenantId
* @param {IVendorEditDTO} vendorDTO
*/
async editVendor(tenantId: number, vendorId: number, vendorDTO: IVendorEditDTO) {
const contactDTO = this.vendorToContactDTO(vendorDTO);
return this.contactService.editContact(tenantId, vendorId, contactDTO, 'vendor');
}
/**
* Deletes the given vendor from the storage.
* @param {number} tenantId
* @param {number} vendorId
* @return {Promise<void>}
*/
async deleteVendor(tenantId: number, vendorId: number) {
await this.vendorHasNoBillsOrThrowError(tenantId, vendorId);
return this.contactService.deleteContact(tenantId, vendorId, 'vendor');
}
/**
* Retrieve the given vendor details.
* @param {number} tenantId
* @param {number} vendorId
*/
async getVendor(tenantId: number, vendorId: number) {
return this.contactService.getContact(tenantId, vendorId, 'vendor');
}
/**
* Writes vendor opening balance journal entries.
* @param {number} tenantId
* @param {number} vendorId
* @param {number} openingBalance
* @return {Promise<void>}
*/
async writeVendorOpeningBalanceJournal(
tenantId: number,
vendorId: number,
openingBalance: number,
) {
const journal = new JournalPoster(tenantId);
const journalCommands = new JournalCommands(journal);
await journalCommands.vendorOpeningBalance(vendorId, openingBalance)
await Promise.all([
journal.saveBalance(),
journal.saveEntries(),
]);
}
/**
* Retrieve the given vendors or throw error if one of them not found.
* @param {numebr} tenantId
* @param {number[]} vendorsIds
*/
getVendorsOrThrowErrorNotFound(tenantId: number, vendorsIds: number[]) {
return this.contactService.getContactsOrThrowErrorNotFound(tenantId, vendorsIds, 'vendor');
}
/**
* Deletes the given vendors from the storage.
* @param {number} tenantId
* @param {number[]} vendorsIds
* @return {Promise<void>}
*/
async deleteBulkVendors(tenantId: number, vendorsIds: number[]) {
const { Contact } = this.tenancy.models(tenantId);
await this.getVendorsOrThrowErrorNotFound(tenantId, vendorsIds);
await this.vendorsHaveNoBillsOrThrowError(tenantId, vendorsIds);
await Contact.query().whereIn('id', vendorsIds).delete();
}
/**
* Validates the vendor has no associated bills or throw service error.
* @param {number} tenantId
* @param {number} vendorId
*/
async vendorHasNoBillsOrThrowError(tenantId: number, vendorId: number) {
const { vendorRepository } = this.tenancy.repositories(tenantId);
const bills = await vendorRepository.getBills(vendorId);
if (bills) {
throw new ServiceError('vendor_has_bills')
}
}
/**
* Throws error in case one of vendors have associated bills.
* @param {number} tenantId
* @param {number[]} customersIds
* @throws {ServiceError}
*/
async vendorsHaveNoBillsOrThrowError(tenantId: number, vendorsIds: number[]) {
const { vendorRepository } = this.tenancy.repositories(tenantId);
const vendorsWithBills = await vendorRepository.vendorsWithBills(vendorsIds);
const vendorsIdsWithBills = vendorsWithBills
.filter((vendor: IVendor) => vendor.bills.length > 0)
.map((vendor: IVendor) => vendor.id);
const vendorsHaveInvoices = difference(vendorsIds, vendorsIdsWithBills);
if (vendorsHaveInvoices.length > 0) {
throw new ServiceError('some_vendors_have_bills');
}
}
}

View File

@@ -1,10 +0,0 @@
import Customer from "../../models/Customer";
export default class CustomersService {
static async isCustomerExists(customerId) {
const foundCustomeres = await Customer.query().where('id', customerId);
return foundCustomeres.length > 0;
}
}

View File

@@ -67,4 +67,8 @@ export default class ItemsService {
);
return notFoundItemsIds;
}
writeItemInventoryOpeningQuantity(tenantId: number, itemId: number, openingQuantity: number, averageCost: number) {
}
}

View File

@@ -213,9 +213,7 @@ export default class BillPaymentsService {
'accounts_payable'
);
const accountsDepGraph = await Account.depGraph().query();
const journal = new JournalPoster(accountsDepGraph);
const journal = new JournalPoster(tenantId);
const commonJournal = {
debit: 0,
credit: 0,

View File

@@ -10,7 +10,7 @@ import HasItemsEntries from '@/services/Sales/HasItemsEntries';
import SalesInvoicesCost from '@/services/Sales/SalesInvoicesCost';
import TenancyService from '@/services/Tenancy/TenancyService';
import { formatDateFields } from '@/utils';
import{ IBillOTD } from '@/interfaces';
import{ IBillOTD, IBill, IItem } from '@/interfaces';
/**
* Vendor bills services.
@@ -27,6 +27,35 @@ export default class BillsService extends SalesInvoicesCost {
@Inject()
tenancy: TenancyService;
/**
* Converts bill DTO to model.
* @param {number} tenantId
* @param {IBillDTO} billDTO
* @param {IBill} oldBill
*
* @returns {IBill}
*/
async billDTOToModel(tenantId: number, billDTO: IBillOTD, oldBill?: IBill) {
const { ItemEntry } = this.tenancy.models(tenantId);
let invLotNumber = oldBill?.invLotNumber;
if (!invLotNumber) {
invLotNumber = await this.inventoryService.nextLotNumber(tenantId);
}
const entries = billDTO.entries.map((entry) => ({
...entry,
amount: ItemEntry.calcAmount(entry),
}));
const amount = sumBy(entries, 'amount');
return {
...formatDateFields(billDTO, ['bill_date', 'due_date']),
amount,
invLotNumber,
entries,
};
}
/**
* Creates a new bill and stored it to the storage.
*
@@ -45,14 +74,7 @@ export default class BillsService extends SalesInvoicesCost {
async createBill(tenantId: number, billDTO: IBillOTD) {
const { Vendor, Bill, ItemEntry } = this.tenancy.models(tenantId);
const invLotNumber = await this.inventoryService.nextLotNumber(tenantId);
const amount = sumBy(billDTO.entries, e => ItemEntry.calcAmount(e));
const bill = {
...formatDateFields(billDTO, ['bill_date', 'due_date']),
amount,
invLotNumber: billDTO.invLotNumber || invLotNumber
};
const bill = await this.billDTOToModel(tenantId, billDTO);
const saveEntriesOpers = [];
const storedBill = await Bill.query()
@@ -116,13 +138,8 @@ export default class BillsService extends SalesInvoicesCost {
const { Bill, ItemEntry, Vendor } = this.tenancy.models(tenantId);
const oldBill = await Bill.query().findById(billId);
const amount = sumBy(billDTO.entries, e => ItemEntry.calcAmount(e));
const bill = this.billDTOToModel(tenantId, billDTO, oldBill);
const bill = {
...formatDateFields(billDTO, ['bill_date', 'due_date']),
amount,
invLotNumber: oldBill.invLotNumber,
};
// Update the bill transaction.
const updatedBill = await Bill.query()
.where('id', billId)
@@ -246,7 +263,7 @@ export default class BillsService extends SalesInvoicesCost {
* @param {Integer} billId
*/
async recordJournalTransactions(tenantId: number, bill: any, billId?: number) {
const { AccountTransaction, Item, Account } = this.tenancy.models(tenantId);
const { AccountTransaction, Item } = this.tenancy.models(tenantId);
const entriesItemsIds = bill.entries.map((entry) => entry.item_id);
const payableTotal = sumBy(bill.entries, 'amount');
@@ -259,8 +276,7 @@ export default class BillsService extends SalesInvoicesCost {
const payableAccount = await this.accountsService.getAccountByType(
tenantId, 'accounts_payable'
);
const accountsDepGraph = await Account.depGraph().query();
const journal = new JournalPoster(accountsDepGraph);
const journal = new JournalPoster(tenantId);
const commonJournalMeta = {
debit: 0,
@@ -289,7 +305,7 @@ export default class BillsService extends SalesInvoicesCost {
journal.credit(payableEntry);
bill.entries.forEach((entry) => {
const item = storedItemsMap.get(entry.item_id);
const item: IItem = storedItemsMap.get(entry.item_id);
const debitEntry = new JournalEntry({
...commonJournalMeta,

View File

@@ -183,8 +183,7 @@ export default class SaleInvoicesService extends SalesInvoicesCost {
.where('reference_id', saleInvoiceId)
.withGraphFetched('account.type');
const accountsDepGraph = await Account.depGraph().query();
const journal = new JournalPoster(accountsDepGraph);
const journal = new JournalPoster(tenantId);
journal.loadEntries(invoiceTransactions);
journal.removeEntries();
@@ -385,10 +384,9 @@ export default class SaleInvoicesService extends SalesInvoicesCost {
saleInvoice: ISaleInvoice,
override: boolean
) {
const { Account, AccountTransaction } = this.tenancy.models(tenantId);
const { AccountTransaction } = this.tenancy.models(tenantId);
const accountsDepGraph = await Account.depGraph().query();
const journal = new JournalPoster(accountsDepGraph);
const journal = new JournalPoster(tenantId);
if (override) {
const oldTransactions = await AccountTransaction.query()

View File

@@ -1,5 +1,6 @@
import { Container } from 'typedi';
import { Container, Service } from 'typedi';
@Service()
export default class HasTenancyService {
/**
* Retrieve the given tenant container.
@@ -10,6 +11,14 @@ export default class HasTenancyService {
return Container.of(`tenant-${tenantId}`);
}
/**
* Retrieve knex instance of the given tenant id.
* @param {number} tenantId
*/
knex(tenantId: number) {
return this.tenantContainer(tenantId).get('knex');
}
/**
* Retrieve models of the givne tenant id.
* @param {number} tenantId - The tenant id.
@@ -18,11 +27,27 @@ export default class HasTenancyService {
return this.tenantContainer(tenantId).get('models');
}
/**
* Retrieve repositories of the given tenant id.
* @param {number} tenantId
*/
repositories(tenantId: number) {
return this.tenantContainer(tenantId).get('repositories');
}
/**
* Retrieve i18n locales methods.
* @param {number} tenantId
*/
i18n(tenantId: number) {
this.tenantContainer(tenantId).get('i18n');
return this.tenantContainer(tenantId).get('i18n');
}
/**
* Retrieve tenant cache instance.
* @param {number} tenantId -
*/
cache(tenantId: number) {
return this.tenantContainer(tenantId).get('cache');
}
}

View File

@@ -9,6 +9,9 @@ export default class UsersService {
@Inject()
tenancy: TenancyService;
@Inject('logger')
logger: any;
/**
* Creates a new user.
* @param {number} tenantId
@@ -61,6 +64,7 @@ export default class UsersService {
id: userId, tenant_id: tenantId,
});
if (!user) {
this.logger.info('[users] the given user not found.', { tenantId, userId });
throw new ServiceError('user_not_found');
}
return user;
@@ -73,7 +77,12 @@ export default class UsersService {
*/
async deleteUser(tenantId: number, userId: number): Promise<void> {
await this.getUserOrThrowError(tenantId, userId);
await SystemUser.query().where('id', userId).delete();
this.logger.info('[users] trying to delete the given user.', { tenantId, userId });
await SystemUser.query().where('tenant_id', tenantId)
.where('id', userId).delete();
this.logger.info('[users] the given user deleted successfully.', { tenantId, userId });
}
/**

View File

@@ -1,15 +0,0 @@
import { Vendor } from '@/models';
export default class VendorsService {
static async isVendorExists(vendorId) {
const foundVendors = await Vendor.tenant().query().where('id', vendorId);
return foundVendors.length > 0;
}
static async isVendorsExist(vendorsIds) {
}
}