feat: redesign accounts types.

This commit is contained in:
a.bouhuolia
2021-01-23 11:39:29 +02:00
parent 1a89730855
commit d919b56e78
29 changed files with 786 additions and 528 deletions

View File

@@ -15,6 +15,7 @@ import {
} from 'decorators/eventDispatcher';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import events from 'subscribers/events';
import AccountTypesUtils from 'lib/AccountTypes';
const ERRORS = {
ACCOUNT_NOT_FOUND: 'account_not_found',
@@ -52,17 +53,13 @@ export default class AccountsService {
* @param {number} accountTypeId -
* @return {IAccountType}
*/
private async getAccountTypeOrThrowError(
tenantId: number,
accountTypeId: number
private getAccountTypeOrThrowError(
accountTypeKey: string
) {
const { accountTypeRepository } = this.tenancy.repositories(tenantId);
this.logger.info('[accounts] validating account type existance.', {
tenantId,
accountTypeId,
accountTypeKey
});
const accountType = await accountTypeRepository.findOneById(accountTypeId);
const accountType = AccountTypesUtils.getType(accountTypeKey);
if (!accountType) {
this.logger.info('[accounts] account type not found.');
@@ -153,7 +150,7 @@ export default class AccountsService {
accountDTO: IAccountDTO,
parentAccount: IAccount
) {
if (accountDTO.accountTypeId !== parentAccount.accountTypeId) {
if (accountDTO.accountType !== parentAccount.accountType) {
throw new ServiceError(ERRORS.PARENT_ACCOUNT_HAS_DIFFERENT_TYPE);
}
}
@@ -193,7 +190,7 @@ export default class AccountsService {
oldAccount: IAccount | IAccountDTO,
newAccount: IAccount | IAccountDTO
) {
if (oldAccount.accountTypeId !== newAccount.accountTypeId) {
if (oldAccount.accountType !== newAccount.accountType) {
throw new ServiceError(ERRORS.ACCOUNT_TYPE_NOT_ALLOWED_TO_CHANGE);
}
}
@@ -244,7 +241,7 @@ export default class AccountsService {
if (accountDTO.code) {
await this.isAccountCodeUniqueOrThrowError(tenantId, accountDTO.code);
}
await this.getAccountTypeOrThrowError(tenantId, accountDTO.accountTypeId);
this.getAccountTypeOrThrowError(accountDTO.accountType);
if (accountDTO.parentAccountId) {
const parentAccount = await this.getParentAccountOrThrowError(
@@ -638,7 +635,6 @@ export default class AccountsService {
filter,
});
const accounts = await Account.query().onBuild((builder) => {
builder.withGraphFetched('type');
dynamicList.buildQuery()(builder);
});
@@ -673,10 +669,8 @@ export default class AccountsService {
toAccountId,
deleteAfterClosing,
});
const { AccountTransaction } = this.tenancy.models(tenantId);
const {
accountTypeRepository,
accountRepository,
} = this.tenancy.repositories(tenantId);
@@ -685,14 +679,7 @@ export default class AccountsService {
this.throwErrorIfAccountPredefined(account);
const accountType = await accountTypeRepository.findOneById(
account.accountTypeId
);
const toAccountType = await accountTypeRepository.findOneById(
toAccount.accountTypeId
);
if (accountType.rootType !== toAccountType.rootType) {
if (account.accountType !== toAccount.accountType) {
throw new ServiceError(ERRORS.CLOSE_ACCOUNT_AND_TO_ACCOUNT_NOT_SAME_TYPE);
}
const updateAccountBalanceOper = await accountRepository.balanceChange(

View File

@@ -1,20 +1,14 @@
import { Inject, Service } from 'typedi';
import { omit } from 'lodash';
import TenancyService from 'services/Tenancy/TenancyService';
import { Service } from 'typedi';
import { IAccountsTypesService, IAccountType } from 'interfaces';
import AccountTypesUtils from 'lib/AccountTypes';
@Service()
export default class AccountsTypesService implements IAccountsTypesService {
@Inject()
tenancy: TenancyService;
/**
* Retrieve all accounts types.
* @param {number} tenantId -
* @return {Promise<IAccountType>}
* @return {IAccountType}
*/
async getAccountsTypes(tenantId: number): Promise<IAccountType> {
const { accountTypeRepository } = this.tenancy.repositories(tenantId);
return accountTypeRepository.all();
getAccountsTypes(): IAccountType[] {
return AccountTypesUtils.getList();
}
}

View File

@@ -21,6 +21,7 @@ import {
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import events from 'subscribers/events';
import ContactsService from 'services/Contacts/ContactsService';
import { ACCOUNT_PARENT_TYPE, ACCOUNT_ROOT_TYPE } from 'data/AccountTypes'
const ERRORS = {
EXPENSE_NOT_FOUND: 'expense_not_found',
@@ -153,17 +154,10 @@ export default class ExpensesService implements IExpensesService {
tenantId,
expensesAccounts,
});
const { accountTypeRepository } = this.tenancy.repositories(tenantId);
// Retrieve accounts types of the given root type.
const expensesTypes = await accountTypeRepository.getByRootType('expense');
const expensesTypesIds = expensesTypes.map((t) => t.id);
const invalidExpenseAccounts: number[] = [];
expensesAccounts.forEach((expenseAccount) => {
if (expensesTypesIds.indexOf(expenseAccount.accountTypeId) === -1) {
if (expenseAccount.isRootType(ACCOUNT_ROOT_TYPE.EXPENSE)) {
invalidExpenseAccounts.push(expenseAccount.id);
}
});
@@ -187,16 +181,7 @@ export default class ExpensesService implements IExpensesService {
paymentAccount,
});
const { accountTypeRepository } = this.tenancy.repositories(tenantId);
// Retrieve account tpy eof the given key.
const validAccountsType = await accountTypeRepository.getByKeys([
'current_asset',
'fixed_asset',
]);
const validAccountsTypeIds = validAccountsType.map((t) => t.id);
if (validAccountsTypeIds.indexOf(paymentAccount.accountTypeId) === -1) {
if (paymentAccount.isParentType(ACCOUNT_PARENT_TYPE.CURRENT_ASSET)) {
this.logger.info(
'[expenses] the given payment account has invalid type',
{ tenantId, paymentAccount }
@@ -270,7 +255,6 @@ export default class ExpensesService implements IExpensesService {
tenantId,
expenseId,
});
// Retrieve the given expense by id.
const expense = await expenseRepository.findOneById(expenseId);

View File

@@ -16,6 +16,7 @@ import {
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import TenancyService from 'services/Tenancy/TenancyService';
import events from 'subscribers/events';
import { ACCOUNT_ROOT_TYPE, ACCOUNT_TYPE } from 'data/AccountTypes';
const ERRORS = {
ITEM_CATEGORIES_NOT_FOUND: 'ITEM_CATEGORIES_NOT_FOUND',
@@ -172,16 +173,12 @@ export default class ItemCategoriesService implements IItemCategoriesService {
* @return {Promise<void>}
*/
private async validateSellAccount(tenantId: number, sellAccountId: number) {
const {
accountRepository,
accountTypeRepository,
} = this.tenancy.repositories(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate sell account existance.', {
tenantId,
sellAccountId,
});
const incomeType = await accountTypeRepository.getByKey('income');
const foundAccount = await accountRepository.findOneById(sellAccountId);
if (!foundAccount) {
@@ -190,7 +187,7 @@ export default class ItemCategoriesService implements IItemCategoriesService {
sellAccountId,
});
throw new ServiceError(ERRORS.SELL_ACCOUNT_NOT_FOUND);
} else if (foundAccount.accountTypeId !== incomeType.id) {
} else if (!foundAccount.isRootType(ACCOUNT_ROOT_TYPE.INCOME)) {
this.logger.info('[items] sell account not income type.', {
tenantId,
sellAccountId,
@@ -206,16 +203,12 @@ export default class ItemCategoriesService implements IItemCategoriesService {
* @return {Promise<void>}
*/
private async validateCostAccount(tenantId: number, costAccountId: number) {
const {
accountRepository,
accountTypeRepository,
} = this.tenancy.repositories(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate cost account existance.', {
tenantId,
costAccountId,
});
const COGSType = await accountTypeRepository.getByKey('cost_of_goods_sold');
const foundAccount = await accountRepository.findOneById(costAccountId);
if (!foundAccount) {
@@ -224,7 +217,7 @@ export default class ItemCategoriesService implements IItemCategoriesService {
costAccountId,
});
throw new ServiceError(ERRORS.COST_ACCOUNT_NOT_FOUMD);
} else if (foundAccount.accountTypeId !== COGSType.id) {
} else if (!foundAccount.isRootType(ACCOUNT_ROOT_TYPE.EXPENSE)) {
this.logger.info('[items] validate cost account not COGS type.', {
tenantId,
costAccountId,
@@ -243,16 +236,12 @@ export default class ItemCategoriesService implements IItemCategoriesService {
tenantId: number,
inventoryAccountId: number
) {
const {
accountTypeRepository,
accountRepository,
} = this.tenancy.repositories(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate inventory account existance.', {
tenantId,
inventoryAccountId,
});
const otherAsset = await accountTypeRepository.getByKey('other_asset');
const foundAccount = await accountRepository.findOneById(
inventoryAccountId
);
@@ -263,7 +252,7 @@ export default class ItemCategoriesService implements IItemCategoriesService {
inventoryAccountId,
});
throw new ServiceError(ERRORS.INVENTORY_ACCOUNT_NOT_FOUND);
} else if (otherAsset.id !== foundAccount.accountTypeId) {
} else if (!foundAccount.isAccountType(ACCOUNT_TYPE.INVENTORY)) {
this.logger.info('[items] inventory account not inventory type.', {
tenantId,
inventoryAccountId,

View File

@@ -1,4 +1,4 @@
import { defaultTo, difference, omit, pick } from 'lodash';
import { defaultTo, difference } from 'lodash';
import { Service, Inject } from 'typedi';
import {
EventDispatcher,
@@ -10,7 +10,7 @@ import DynamicListingService from 'services/DynamicListing/DynamicListService';
import TenancyService from 'services/Tenancy/TenancyService';
import { ServiceError } from 'exceptions';
import InventoryService from 'services/Inventory/Inventory';
import InventoryAdjustmentEntry from 'models/InventoryAdjustmentEntry';
import { ACCOUNT_ROOT_TYPE, ACCOUNT_TYPE } from 'data/AccountTypes'
const ERRORS = {
NOT_FOUND: 'NOT_FOUND',
@@ -29,7 +29,8 @@ const ERRORS = {
ITEMS_HAVE_ASSOCIATED_TRANSACTIONS: 'ITEMS_HAVE_ASSOCIATED_TRANSACTIONS',
ITEM_HAS_ASSOCIATED_TRANSACTINS: 'ITEM_HAS_ASSOCIATED_TRANSACTINS',
ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT: 'ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT',
ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT:
'ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT',
};
@Service()
@@ -114,16 +115,12 @@ export default class ItemsService implements IItemsService {
tenantId: number,
costAccountId: number
): Promise<void> {
const {
accountRepository,
accountTypeRepository,
} = this.tenancy.repositories(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate cost account existance.', {
tenantId,
costAccountId,
});
const COGSType = await accountTypeRepository.getByKey('cost_of_goods_sold');
const foundAccount = await accountRepository.findOneById(costAccountId);
if (!foundAccount) {
@@ -132,7 +129,9 @@ export default class ItemsService implements IItemsService {
costAccountId,
});
throw new ServiceError(ERRORS.COST_ACCOUNT_NOT_FOUMD);
} else if (foundAccount.accountTypeId !== COGSType.id) {
// Detarmines the cost of goods sold account.
} else if (foundAccount.isRootType(ACCOUNT_ROOT_TYPE.EXPENSE)) {
this.logger.info('[items] validate cost account not COGS type.', {
tenantId,
costAccountId,
@@ -152,14 +151,13 @@ export default class ItemsService implements IItemsService {
) {
const {
accountRepository,
accountTypeRepository,
} = this.tenancy.repositories(tenantId);
this.logger.info('[items] validate sell account existance.', {
tenantId,
sellAccountId,
});
const incomeType = await accountTypeRepository.getByKey('income');
const foundAccount = await accountRepository.findOneById(sellAccountId);
if (!foundAccount) {
@@ -168,7 +166,8 @@ export default class ItemsService implements IItemsService {
sellAccountId,
});
throw new ServiceError(ERRORS.SELL_ACCOUNT_NOT_FOUND);
} else if (foundAccount.accountTypeId !== incomeType.id) {
} else if (!foundAccount.isRootType(ACCOUNT_ROOT_TYPE.INCOME)) {
this.logger.info('[items] sell account not income type.', {
tenantId,
sellAccountId,
@@ -187,7 +186,6 @@ export default class ItemsService implements IItemsService {
inventoryAccountId: number
) {
const {
accountTypeRepository,
accountRepository,
} = this.tenancy.repositories(tenantId);
@@ -195,7 +193,6 @@ export default class ItemsService implements IItemsService {
tenantId,
inventoryAccountId,
});
const otherAsset = await accountTypeRepository.getByKey('other_asset');
const foundAccount = await accountRepository.findOneById(
inventoryAccountId
);
@@ -206,7 +203,8 @@ export default class ItemsService implements IItemsService {
inventoryAccountId,
});
throw new ServiceError(ERRORS.INVENTORY_ACCOUNT_NOT_FOUND);
} else if (otherAsset.id !== foundAccount.accountTypeId) {
} else if (foundAccount.isAccountType(ACCOUNT_TYPE.INVENTORY)) {
this.logger.info('[items] inventory account not inventory type.', {
tenantId,
inventoryAccountId,
@@ -361,11 +359,11 @@ export default class ItemsService implements IItemsService {
await this.getItemOrThrowError(tenantId, itemId);
// Validate the item has no associated inventory transactions.
await this.validateHasNoInventoryAdjustments(tenantId, itemId);
await this.validateHasNoInventoryAdjustments(tenantId, itemId);
// Validate the item has no associated invoices or bills.
await this.validateHasNoInvoicesOrBills(tenantId, itemId);
await Item.query().findById(itemId).delete();
this.logger.info('[items] deleted successfully.', { tenantId, itemId });
@@ -479,7 +477,7 @@ export default class ItemsService implements IItemsService {
await this.validateItemsIdsExists(tenantId, itemsIds);
// Validate the item has no associated inventory transactions.
await this.validateHasNoInventoryAdjustments(tenantId, itemsIds);
await this.validateHasNoInventoryAdjustments(tenantId, itemsIds);
// Validate the items have no associated invoices or bills.
await this.validateHasNoInvoicesOrBills(tenantId, itemsIds);
@@ -554,14 +552,15 @@ export default class ItemsService implements IItemsService {
*/
private async validateHasNoInventoryAdjustments(
tenantId: number,
itemId: number[] | number,
itemId: number[] | number
): Promise<void> {
const { InventoryAdjustmentEntry } = this.tenancy.models(tenantId);
const itemsIds = Array.isArray(itemId) ? itemId : [itemId];
const inventoryAdjEntries = await InventoryAdjustmentEntry.query()
.whereIn('item_id', itemsIds);
const inventoryAdjEntries = await InventoryAdjustmentEntry.query().whereIn(
'item_id',
itemsIds
);
if (inventoryAdjEntries.length > 0) {
throw new ServiceError(ERRORS.ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT);
}

View File

@@ -25,13 +25,15 @@ import TenancyService from 'services/Tenancy/TenancyService';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { entriesAmountDiff, formatDateFields } from 'utils';
import { ServiceError } from 'exceptions';
import { ACCOUNT_PARENT_TYPE } from 'data/AccountTypes';
const ERRORS = {
BILL_VENDOR_NOT_FOUND: 'VENDOR_NOT_FOUND',
PAYMENT_MADE_NOT_FOUND: 'PAYMENT_MADE_NOT_FOUND',
BILL_PAYMENT_NUMBER_NOT_UNQIUE: 'BILL_PAYMENT_NUMBER_NOT_UNQIUE',
PAYMENT_ACCOUNT_NOT_FOUND: 'PAYMENT_ACCOUNT_NOT_FOUND',
PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE: 'PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE',
PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE:
'PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE',
BILL_ENTRIES_IDS_NOT_FOUND: 'BILL_ENTRIES_IDS_NOT_FOUND',
BILL_PAYMENT_ENTRIES_NOT_FOUND: 'BILL_PAYMENT_ENTRIES_NOT_FOUND',
INVALID_BILL_PAYMENT_AMOUNT: 'INVALID_BILL_PAYMENT_AMOUNT',
@@ -63,9 +65,9 @@ export default class BillPaymentsService {
/**
* Validate whether the bill payment vendor exists on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
private async getVendorOrThrowError(tenantId: number, vendorId: number) {
const { vendorRepository } = this.tenancy.repositories(tenantId);
@@ -74,18 +76,21 @@ export default class BillPaymentsService {
const vendor = await vendorRepository.findOneById(vendorId);
if (!vendor) {
throw new ServiceError(ERRORS.BILL_VENDOR_NOT_FOUND)
throw new ServiceError(ERRORS.BILL_VENDOR_NOT_FOUND);
}
return vendor;
}
/**
* Validates the bill payment existance.
* @param {Request} req
* @param {Response} res
* @param {Function} next
* Validates the bill payment existance.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
private async getPaymentMadeOrThrowError(tenantid: number, paymentMadeId: number) {
private async getPaymentMadeOrThrowError(
tenantid: number,
paymentMadeId: number
) {
const { BillPayment } = this.tenancy.models(tenantid);
const billPayment = await BillPayment.query()
.withGraphFetched('entries')
@@ -98,23 +103,25 @@ export default class BillPaymentsService {
}
/**
* Validates the payment account.
* @param {number} tenantId -
* Validates the payment account.
* @param {number} tenantId -
* @param {number} paymentAccountId
* @return {Promise<IAccountType>}
*/
private async getPaymentAccountOrThrowError(tenantId: number, paymentAccountId: number) {
const { accountTypeRepository, accountRepository } = this.tenancy.repositories(tenantId);
private async getPaymentAccountOrThrowError(
tenantId: number,
paymentAccountId: number
) {
const { accountRepository } = this.tenancy.repositories(tenantId);
const currentAssetTypes = await accountTypeRepository.getByChildType('current_asset');
const paymentAccount = await accountRepository.findOneById(paymentAccountId);
const currentAssetTypesIds = currentAssetTypes.map(type => type.id);
const paymentAccount = await accountRepository.findOneById(
paymentAccountId
);
if (!paymentAccount) {
throw new ServiceError(ERRORS.PAYMENT_ACCOUNT_NOT_FOUND);
}
if (currentAssetTypesIds.indexOf(paymentAccount.accountTypeId) === -1) {
if (!paymentAccount.isParentType(ACCOUNT_PARENT_TYPE.CURRENT_ASSET)) {
throw new ServiceError(ERRORS.PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE);
}
return paymentAccount;
@@ -122,35 +129,44 @@ export default class BillPaymentsService {
/**
* Validates the payment number uniqness.
* @param {number} tenantId -
* @param {string} paymentMadeNumber -
* @param {number} tenantId -
* @param {string} paymentMadeNumber -
* @return {Promise<IBillPayment>}
*/
private async validatePaymentNumber(tenantId: number, paymentMadeNumber: string, notPaymentMadeId?: number) {
private async validatePaymentNumber(
tenantId: number,
paymentMadeNumber: string,
notPaymentMadeId?: number
) {
const { BillPayment } = this.tenancy.models(tenantId);
const foundBillPayment = await BillPayment.query()
.onBuild((builder: any) => {
const foundBillPayment = await BillPayment.query().onBuild(
(builder: any) => {
builder.findOne('payment_number', paymentMadeNumber);
if (notPaymentMadeId) {
builder.whereNot('id', notPaymentMadeId);
}
});
}
);
if (foundBillPayment) {
throw new ServiceError(ERRORS.BILL_PAYMENT_NUMBER_NOT_UNQIUE)
throw new ServiceError(ERRORS.BILL_PAYMENT_NUMBER_NOT_UNQIUE);
}
return foundBillPayment;
}
/**
* Validate whether the entries bills ids exist on the storage.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
private async validateBillsExistance(tenantId: number, billPaymentEntries: IBillPaymentEntry[], vendorId: number) {
private async validateBillsExistance(
tenantId: number,
billPaymentEntries: IBillPaymentEntry[],
vendorId: number
) {
const { Bill } = this.tenancy.models(tenantId);
const entriesBillsIds = billPaymentEntries.map((e: any) => e.billId);
@@ -162,15 +178,15 @@ export default class BillPaymentsService {
const notFoundBillsIds = difference(entriesBillsIds, storedBillsIds);
if (notFoundBillsIds.length > 0) {
throw new ServiceError(ERRORS.BILL_ENTRIES_IDS_NOT_FOUND)
throw new ServiceError(ERRORS.BILL_ENTRIES_IDS_NOT_FOUND);
}
}
/**
* Validate wether the payment amount bigger than the payable amount.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {void}
*/
private async validateBillsDueAmount(
@@ -179,22 +195,28 @@ export default class BillPaymentsService {
oldPaymentEntries: IBillPaymentEntry[] = []
) {
const { Bill } = this.tenancy.models(tenantId);
const billsIds = billPaymentEntries.map((entry: IBillPaymentEntryDTO) => entry.billId);
const billsIds = billPaymentEntries.map(
(entry: IBillPaymentEntryDTO) => entry.billId
);
const storedBills = await Bill.query().whereIn('id', billsIds);
const storedBillsMap = new Map(
storedBills
.map((bill) => {
const oldEntries = oldPaymentEntries.filter(entry => entry.billId === bill.id);
const oldPaymentAmount = sumBy(oldEntries, 'paymentAmount') || 0;
storedBills.map((bill) => {
const oldEntries = oldPaymentEntries.filter(
(entry) => entry.billId === bill.id
);
const oldPaymentAmount = sumBy(oldEntries, 'paymentAmount') || 0;
return [bill.id, { ...bill, dueAmount: bill.dueAmount + oldPaymentAmount }];
}),
return [
bill.id,
{ ...bill, dueAmount: bill.dueAmount + oldPaymentAmount },
];
})
);
interface invalidPaymentAmountError{
index: number,
due_amount: number
};
interface invalidPaymentAmountError {
index: number;
due_amount: number;
}
const hasWrongPaymentAmount: invalidPaymentAmountError[] = [];
billPaymentEntries.forEach((entry: IBillPaymentEntryDTO, index: number) => {
@@ -203,7 +225,7 @@ export default class BillPaymentsService {
if (dueAmount < entry.paymentAmount) {
hasWrongPaymentAmount.push({ index, due_amount: dueAmount });
}
}
});
if (hasWrongPaymentAmount.length > 0) {
throw new ServiceError(ERRORS.INVALID_BILL_PAYMENT_AMOUNT);
@@ -211,9 +233,9 @@ export default class BillPaymentsService {
}
/**
* Validate the payment receive entries IDs existance.
* @param {Request} req
* @param {Response} res
* Validate the payment receive entries IDs existance.
* @param {Request} req
* @param {Response} res
* @return {Response}
*/
private async validateEntriesIdsExistance(
@@ -227,9 +249,12 @@ export default class BillPaymentsService {
.filter((entry: any) => entry.id)
.map((entry: any) => entry.id);
const storedEntries = await BillPaymentEntry.query().where('bill_payment_id', billPaymentId);
const storedEntries = await BillPaymentEntry.query().where(
'bill_payment_id',
billPaymentId
);
const storedEntriesIds = storedEntries.map((entry: any) => entry.id);
const storedEntriesIds = storedEntries.map((entry: any) => entry.id);
const notFoundEntriesIds = difference(entriesIds, storedEntriesIds);
if (notFoundEntriesIds.length > 0) {
@@ -256,7 +281,10 @@ export default class BillPaymentsService {
tenantId: number,
billPaymentDTO: IBillPaymentDTO
): Promise<IBillPayment> {
this.logger.info('[paymentDate] trying to save payment made.', { tenantId, billPaymentDTO });
this.logger.info('[paymentDate] trying to save payment made.', {
tenantId,
billPaymentDTO,
});
const { BillPayment } = this.tenancy.models(tenantId);
const billPaymentObj = {
@@ -268,28 +296,39 @@ export default class BillPaymentsService {
await this.getVendorOrThrowError(tenantId, billPaymentObj.vendorId);
// Validate the payment account existance and type.
await this.getPaymentAccountOrThrowError(tenantId, billPaymentObj.paymentAccountId);
await this.getPaymentAccountOrThrowError(
tenantId,
billPaymentObj.paymentAccountId
);
// Validate the payment number uniquiness.
if (billPaymentObj.paymentNumber) {
await this.validatePaymentNumber(tenantId, billPaymentObj.paymentNumber);
}
// Validates the bills existance and associated to the given vendor.
await this.validateBillsExistance(tenantId, billPaymentObj.entries, billPaymentDTO.vendorId);
await this.validateBillsExistance(
tenantId,
billPaymentObj.entries,
billPaymentDTO.vendorId
);
// Validates the bills due payment amount.
await this.validateBillsDueAmount(tenantId, billPaymentObj.entries);
const billPayment = await BillPayment.query()
.insertGraphAndFetch({
...omit(billPaymentObj, ['entries']),
entries: billPaymentDTO.entries,
});
const billPayment = await BillPayment.query().insertGraphAndFetch({
...omit(billPaymentObj, ['entries']),
entries: billPaymentDTO.entries,
});
await this.eventDispatcher.dispatch(events.billPayment.onCreated, {
tenantId, billPayment, billPaymentId: billPayment.id,
tenantId,
billPayment,
billPaymentId: billPayment.id,
});
this.logger.info('[payment_made] inserted successfully.', {
tenantId,
billPaymentId: billPayment.id,
});
this.logger.info('[payment_made] inserted successfully.', { tenantId, billPaymentId: billPayment.id, });
return billPayment;
}
@@ -315,11 +354,14 @@ export default class BillPaymentsService {
public async editBillPayment(
tenantId: number,
billPaymentId: number,
billPaymentDTO,
billPaymentDTO
): Promise<IBillPayment> {
const { BillPayment } = this.tenancy.models(tenantId);
const oldBillPayment = await this.getPaymentMadeOrThrowError(tenantId, billPaymentId);
const oldBillPayment = await this.getPaymentMadeOrThrowError(
tenantId,
billPaymentId
);
const billPaymentObj = {
amount: sumBy(billPaymentDTO.entries, 'paymentAmount'),
@@ -330,31 +372,57 @@ export default class BillPaymentsService {
await this.getVendorOrThrowError(tenantId, billPaymentObj.vendorId);
// Validate the payment account existance and type.
await this.getPaymentAccountOrThrowError(tenantId, billPaymentObj.paymentAccountId);
await this.getPaymentAccountOrThrowError(
tenantId,
billPaymentObj.paymentAccountId
);
// Validate the items entries IDs existance on the storage.
await this.validateEntriesIdsExistance(tenantId, billPaymentId, billPaymentObj.entries);
await this.validateEntriesIdsExistance(
tenantId,
billPaymentId,
billPaymentObj.entries
);
// Validate the bills existance and associated to the given vendor.
await this.validateBillsExistance(tenantId, billPaymentObj.entries, billPaymentDTO.vendorId);
await this.validateBillsExistance(
tenantId,
billPaymentObj.entries,
billPaymentDTO.vendorId
);
// Validates the bills due payment amount.
await this.validateBillsDueAmount(tenantId, billPaymentObj.entries, oldBillPayment.entries);
await this.validateBillsDueAmount(
tenantId,
billPaymentObj.entries,
oldBillPayment.entries
);
// Validate the payment number uniquiness.
if (billPaymentObj.paymentNumber) {
await this.validatePaymentNumber(tenantId, billPaymentObj.paymentNumber, billPaymentId);
await this.validatePaymentNumber(
tenantId,
billPaymentObj.paymentNumber,
billPaymentId
);
}
const billPayment = await BillPayment.query()
.upsertGraphAndFetch({
id: billPaymentId,
...omit(billPaymentObj, ['entries']),
entries: billPaymentDTO.entries,
});
await this.eventDispatcher.dispatch(events.billPayment.onEdited, {
tenantId, billPaymentId, billPayment, oldBillPayment,
const billPayment = await BillPayment.query().upsertGraphAndFetch({
id: billPaymentId,
...omit(billPaymentObj, ['entries']),
entries: billPaymentDTO.entries,
});
await this.eventDispatcher.dispatch(events.billPayment.onEdited, {
tenantId,
billPaymentId,
billPayment,
oldBillPayment,
});
this.logger.info('[bill_payment] edited successfully.', {
tenantId,
billPaymentId,
billPayment,
oldBillPayment,
});
this.logger.info('[bill_payment] edited successfully.', { tenantId, billPaymentId, billPayment, oldBillPayment });
return billPayment;
}
@@ -367,15 +435,30 @@ export default class BillPaymentsService {
*/
public async deleteBillPayment(tenantId: number, billPaymentId: number) {
const { BillPayment, BillPaymentEntry } = this.tenancy.models(tenantId);
this.logger.info('[bill_payment] trying to delete.', { tenantId, billPaymentId });
const oldBillPayment = await this.getPaymentMadeOrThrowError(tenantId, billPaymentId);
await BillPaymentEntry.query().where('bill_payment_id', billPaymentId).delete();
this.logger.info('[bill_payment] trying to delete.', {
tenantId,
billPaymentId,
});
const oldBillPayment = await this.getPaymentMadeOrThrowError(
tenantId,
billPaymentId
);
await BillPaymentEntry.query()
.where('bill_payment_id', billPaymentId)
.delete();
await BillPayment.query().where('id', billPaymentId).delete();
await this.eventDispatcher.dispatch(events.billPayment.onDeleted, { tenantId, billPaymentId, oldBillPayment });
this.logger.info('[bill_payment] deleted successfully.', { tenantId, billPaymentId });
await this.eventDispatcher.dispatch(events.billPayment.onDeleted, {
tenantId,
billPaymentId,
oldBillPayment,
});
this.logger.info('[bill_payment] deleted successfully.', {
tenantId,
billPaymentId,
});
}
/**
@@ -386,7 +469,10 @@ export default class BillPaymentsService {
public async getPaymentBills(tenantId: number, billPaymentId: number) {
const { Bill } = this.tenancy.models(tenantId);
const billPayment = await this.getPaymentMadeOrThrowError(tenantId, billPaymentId);
const billPayment = await this.getPaymentMadeOrThrowError(
tenantId,
billPaymentId
);
const paymentBillsIds = billPayment.entries.map((entry) => entry.id);
const bills = await Bill.query().whereIn('id', paymentBillsIds);
@@ -396,11 +482,14 @@ export default class BillPaymentsService {
/**
* Records bill payment receive journal transactions.
* @param {number} tenantId -
* @param {number} tenantId -
* @param {BillPayment} billPayment
* @param {Integer} billPaymentId
*/
public async recordJournalEntries(tenantId: number, billPayment: IBillPayment) {
public async recordJournalEntries(
tenantId: number,
billPayment: IBillPayment
) {
const { AccountTransaction } = this.tenancy.models(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
@@ -408,7 +497,9 @@ export default class BillPaymentsService {
const formattedDate = moment(billPayment.paymentDate).format('YYYY-MM-DD');
// Retrieve AP account from the storage.
const payableAccount = await accountRepository.findOne({ slug: 'accounts-payable' });
const payableAccount = await accountRepository.findOne({
slug: 'accounts-payable',
});
const journal = new JournalPoster(tenantId);
const commonJournal = {
@@ -451,44 +542,50 @@ export default class BillPaymentsService {
/**
* Reverts bill payment journal entries.
* @param {number} tenantId
* @param {number} billPaymentId
* @param {number} tenantId
* @param {number} billPaymentId
* @return {Promise<void>}
*/
public async revertJournalEntries(tenantId: number, billPaymentId: number) {
const journal = new JournalPoster(tenantId);
const journalCommands = new JournalCommands(journal);
await journalCommands.revertJournalEntries(billPaymentId, 'BillPayment');
return Promise.all([
journal.saveBalance(),
journal.deleteEntries(),
]);
return Promise.all([journal.saveBalance(), journal.deleteEntries()]);
}
/**
* Retrieve bill payment paginted and filterable list.
* @param {number} tenantId
* @param {IBillPaymentsFilter} billPaymentsFilter
* @param {number} tenantId
* @param {IBillPaymentsFilter} billPaymentsFilter
*/
public async listBillPayments(
tenantId: number,
billPaymentsFilter: IBillPaymentsFilter,
): Promise<{ billPayments: IBillPayment, pagination: IPaginationMeta, filterMeta: IFilterMeta }> {
billPaymentsFilter: IBillPaymentsFilter
): Promise<{
billPayments: IBillPayment;
pagination: IPaginationMeta;
filterMeta: IFilterMeta;
}> {
const { BillPayment } = this.tenancy.models(tenantId);
const dynamicFilter = await this.dynamicListService.dynamicList(tenantId, BillPayment, billPaymentsFilter);
this.logger.info('[bill_payment] try to get bill payments list.', { tenantId });
const { results, pagination } = await BillPayment.query().onBuild((builder) => {
builder.withGraphFetched('vendor');
builder.withGraphFetched('paymentAccount');
dynamicFilter.buildQuery()(builder);
}).pagination(
billPaymentsFilter.page - 1,
billPaymentsFilter.pageSize,
const dynamicFilter = await this.dynamicListService.dynamicList(
tenantId,
BillPayment,
billPaymentsFilter
);
this.logger.info('[bill_payment] try to get bill payments list.', {
tenantId,
});
const { results, pagination } = await BillPayment.query()
.onBuild((builder) => {
builder.withGraphFetched('vendor');
builder.withGraphFetched('paymentAccount');
dynamicFilter.buildQuery()(builder);
})
.pagination(billPaymentsFilter.page - 1, billPaymentsFilter.pageSize);
return {
billPayments: results,
pagination,
@@ -501,10 +598,13 @@ export default class BillPaymentsService {
* @param {number} billPaymentId - The bill payment id.
* @return {object}
*/
public async getBillPayment(tenantId: number, billPaymentId: number): Promise<{
billPayment: IBillPayment,
payableBills: IBill[],
paymentMadeBills: IBill[],
public async getBillPayment(
tenantId: number,
billPaymentId: number
): Promise<{
billPayment: IBillPayment;
payableBills: IBill[];
paymentMadeBills: IBill[];
}> {
const { BillPayment, Bill } = this.tenancy.models(tenantId);
const billPayment = await BillPayment.query()
@@ -527,8 +627,8 @@ export default class BillPaymentsService {
// Retrieve all payment made assocaited bills.
const paymentMadeBills = billPayment.entries.map((entry) => ({
...(entry.bill),
dueAmount: (entry.bill.dueAmount + entry.paymentAmount),
...entry.bill,
dueAmount: entry.bill.dueAmount + entry.paymentAmount,
}));
return {
@@ -552,7 +652,7 @@ export default class BillPaymentsService {
public async saveChangeBillsPaymentAmount(
tenantId: number,
paymentMadeEntries: IBillPaymentEntryDTO[],
oldPaymentMadeEntries?: IBillPaymentEntryDTO[],
oldPaymentMadeEntries?: IBillPaymentEntryDTO[]
): Promise<void> {
const { Bill } = this.tenancy.models(tenantId);
const opers: Promise<void>[] = [];
@@ -561,17 +661,21 @@ export default class BillPaymentsService {
paymentMadeEntries,
oldPaymentMadeEntries,
'paymentAmount',
'billId',
'billId'
);
diffEntries.forEach((diffEntry: { paymentAmount: number, billId: number }) => {
if (diffEntry.paymentAmount === 0) { return; }
diffEntries.forEach(
(diffEntry: { paymentAmount: number; billId: number }) => {
if (diffEntry.paymentAmount === 0) {
return;
}
const oper = Bill.changePaymentAmount(
diffEntry.billId,
diffEntry.paymentAmount,
);
opers.push(oper);
});
const oper = Bill.changePaymentAmount(
diffEntry.billId,
diffEntry.paymentAmount
);
opers.push(oper);
}
);
await Promise.all(opers);
}
}

View File

@@ -31,13 +31,13 @@ import { ServiceError } from 'exceptions';
import CustomersService from 'services/Contacts/CustomersService';
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
import JournalCommands from 'services/Accounting/JournalCommands';
import { ACCOUNT_PARENT_TYPE } from 'data/AccountTypes';
const ERRORS = {
PAYMENT_RECEIVE_NO_EXISTS: 'PAYMENT_RECEIVE_NO_EXISTS',
PAYMENT_RECEIVE_NOT_EXISTS: 'PAYMENT_RECEIVE_NOT_EXISTS',
DEPOSIT_ACCOUNT_NOT_FOUND: 'DEPOSIT_ACCOUNT_NOT_FOUND',
DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE:
'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE',
DEPOSIT_ACCOUNT_INVALID_TYPE: 'DEPOSIT_ACCOUNT_INVALID_TYPE',
INVALID_PAYMENT_AMOUNT: 'INVALID_PAYMENT_AMOUNT',
INVOICES_IDS_NOT_FOUND: 'INVOICES_IDS_NOT_FOUND',
ENTRIES_IDS_NOT_EXISTS: 'ENTRIES_IDS_NOT_EXISTS',
@@ -99,8 +99,8 @@ export default class PaymentReceiveService {
/**
* Validates the payment receive existance.
* @param {number} tenantId -
* @param {number} paymentReceiveId -
* @param {number} tenantId - Tenant id.
* @param {number} paymentReceiveId - Payment receive id.
*/
async getPaymentReceiveOrThrowError(
tenantId: number,
@@ -119,32 +119,25 @@ export default class PaymentReceiveService {
/**
* Validate the deposit account id existance.
* @param {number} tenantId -
* @param {number} depositAccountId -
* @param {number} tenantId - Tenant id.
* @param {number} depositAccountId - Deposit account id.
* @return {Promise<IAccount>}
*/
async getDepositAccountOrThrowError(
tenantId: number,
depositAccountId: number
): Promise<IAccount> {
const {
accountTypeRepository,
accountRepository,
} = this.tenancy.repositories(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
const currentAssetTypes = await accountTypeRepository.getByChildType(
'current_asset'
);
const depositAccount = await accountRepository.findOneById(
depositAccountId
);
const currentAssetTypesIds = currentAssetTypes.map((type) => type.id);
if (!depositAccount) {
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND);
}
if (currentAssetTypesIds.indexOf(depositAccount.accountTypeId) === -1) {
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE);
// Detarmines whether the account is cash equivalents.
if (!depositAccount.isParentType(ACCOUNT_PARENT_TYPE.CURRENT_ASSET)) {
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_INVALID_TYPE);
}
return depositAccount;
}
@@ -316,7 +309,6 @@ export default class PaymentReceiveService {
...formatDateFields(omit(paymentReceiveDTO, ['entries']), [
'paymentDate',
]),
entries: paymentReceiveDTO.entries.map((entry) => ({
...omit(entry, ['id']),
})),

View File

@@ -18,6 +18,7 @@ import { ServiceError } from 'exceptions';
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
import { ItemEntry } from 'models';
import InventoryService from 'services/Inventory/Inventory';
import { ACCOUNT_PARENT_TYPE } from 'data/AccountTypes';
const ERRORS = {
SALE_RECEIPT_NOT_FOUND: 'SALE_RECEIPT_NOT_FOUND',
@@ -78,30 +79,20 @@ export default class SalesReceiptService {
/**
* Validate whether sale receipt deposit account exists on the storage.
* @param {number} tenantId -
* @param {number} accountId -
* @param {number} tenantId - Tenant id.
* @param {number} accountId - Account id.
*/
async validateReceiptDepositAccountExistance(
tenantId: number,
accountId: number
) {
const {
accountRepository,
accountTypeRepository,
} = this.tenancy.repositories(tenantId);
const { accountRepository } = this.tenancy.repositories(tenantId);
const depositAccount = await accountRepository.findOneById(accountId);
if (!depositAccount) {
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND);
}
const depositAccountType = await accountTypeRepository.findOneById(
depositAccount.accountTypeId
);
if (
!depositAccountType ||
depositAccountType.childRoot === 'current_asset'
) {
if (!depositAccount.isParentType(ACCOUNT_PARENT_TYPE.CURRENT_ASSET)) {
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET);
}
}