mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-20 14:50:32 +00:00
feat: redesign accounts types.
This commit is contained in:
@@ -136,7 +136,7 @@ function AccountsDataTable({
|
|||||||
Header: formatMessage({ id: 'account_name' }),
|
Header: formatMessage({ id: 'account_name' }),
|
||||||
accessor: 'name',
|
accessor: 'name',
|
||||||
className: 'account_name',
|
className: 'account_name',
|
||||||
width: 220,
|
width: 200,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'code',
|
id: 'code',
|
||||||
|
|||||||
@@ -22,11 +22,6 @@
|
|||||||
"app-root-path": "^3.0.0",
|
"app-root-path": "^3.0.0",
|
||||||
"axios": "^0.20.0",
|
"axios": "^0.20.0",
|
||||||
"bcryptjs": "^2.4.3",
|
"bcryptjs": "^2.4.3",
|
||||||
"bookshelf": "^0.15.1",
|
|
||||||
"bookshelf-cascade-delete": "^2.0.1",
|
|
||||||
"bookshelf-json-columns": "^2.1.1",
|
|
||||||
"bookshelf-modelbase": "^2.10.4",
|
|
||||||
"bookshelf-paranoia": "^0.13.1",
|
|
||||||
"compression": "^1.7.4",
|
"compression": "^1.7.4",
|
||||||
"country-codes-list": "^1.6.8",
|
"country-codes-list": "^1.6.8",
|
||||||
"crypto-random-string": "^3.2.0",
|
"crypto-random-string": "^3.2.0",
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import BaseController from 'api/controllers/BaseController';
|
|||||||
import AccountsTypesService from 'services/Accounts/AccountsTypesServices';
|
import AccountsTypesService from 'services/Accounts/AccountsTypesServices';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class AccountsTypesController extends BaseController{
|
export default class AccountsTypesController extends BaseController {
|
||||||
@Inject()
|
@Inject()
|
||||||
accountsTypesService: AccountsTypesService;
|
accountsTypesService: AccountsTypesService;
|
||||||
|
|
||||||
@@ -15,23 +15,26 @@ export default class AccountsTypesController extends BaseController{
|
|||||||
router() {
|
router() {
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
router.get('/',
|
router.get('/', asyncMiddleware(this.getAccountTypesList.bind(this)));
|
||||||
asyncMiddleware(this.getAccountTypesList.bind(this))
|
|
||||||
);
|
|
||||||
return router;
|
return router;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve accounts types list.
|
* Retrieve accounts types list.
|
||||||
|
* @param {Request} req - Request.
|
||||||
|
* @param {Response} res - Response.
|
||||||
|
* @return {Response}
|
||||||
*/
|
*/
|
||||||
async getAccountTypesList(req: Request, res: Response, next: NextFunction) {
|
getAccountTypesList(req: Request, res: Response, next: NextFunction) {
|
||||||
const { tenantId, user } = req;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const accountTypes = await this.accountsTypesService.getAccountsTypes(tenantId);
|
const accountTypes = this.accountsTypesService.getAccountsTypes();
|
||||||
return res.status(200).send({ account_types: accountTypes });
|
|
||||||
|
return res.status(200).send({
|
||||||
|
account_types: this.transfromToResponse(accountTypes, ['label'], req),
|
||||||
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
next(error);
|
next(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|||||||
@@ -109,10 +109,11 @@ export default class AccountsController extends BaseController {
|
|||||||
.isLength({ min: 3, max: 6 })
|
.isLength({ min: 3, max: 6 })
|
||||||
.trim()
|
.trim()
|
||||||
.escape(),
|
.escape(),
|
||||||
check('account_type_id')
|
check('account_type')
|
||||||
.exists()
|
.exists()
|
||||||
.isInt({ min: 0, max: DATATYPES_LENGTH.INT_10 })
|
.isLength({ min: 3, max: DATATYPES_LENGTH.STRING })
|
||||||
.toInt(),
|
.trim()
|
||||||
|
.escape(),
|
||||||
check('description')
|
check('description')
|
||||||
.optional({ nullable: true })
|
.optional({ nullable: true })
|
||||||
.isLength({ max: DATATYPES_LENGTH.TEXT })
|
.isLength({ max: DATATYPES_LENGTH.TEXT })
|
||||||
@@ -341,6 +342,7 @@ export default class AccountsController extends BaseController {
|
|||||||
* Retrieve accounts datatable list.
|
* Retrieve accounts datatable list.
|
||||||
* @param {Request} req
|
* @param {Request} req
|
||||||
* @param {Response} res
|
* @param {Response} res
|
||||||
|
* @param {Response}
|
||||||
*/
|
*/
|
||||||
async getAccountsList(req: Request, res: Response, next: NextFunction) {
|
async getAccountsList(req: Request, res: Response, next: NextFunction) {
|
||||||
const { tenantId } = req;
|
const { tenantId } = req;
|
||||||
@@ -360,7 +362,7 @@ export default class AccountsController extends BaseController {
|
|||||||
} = await this.accountsService.getAccountsList(tenantId, filter);
|
} = await this.accountsService.getAccountsList(tenantId, filter);
|
||||||
|
|
||||||
return res.status(200).send({
|
return res.status(200).send({
|
||||||
accounts,
|
accounts: this.transfromToResponse(accounts, 'accountTypeLabel', req),
|
||||||
filter_meta: this.transfromToResponse(filterMeta),
|
filter_meta: this.transfromToResponse(filterMeta),
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Response, Request, NextFunction } from 'express';
|
import { Response, Request, NextFunction } from 'express';
|
||||||
import { matchedData, validationResult } from "express-validator";
|
import { matchedData, validationResult } from "express-validator";
|
||||||
import { camelCase, snakeCase, omit } from "lodash";
|
import { camelCase, snakeCase, omit, set, get } from "lodash";
|
||||||
import { mapKeysDeep } from 'utils'
|
import { mapKeysDeep } from 'utils'
|
||||||
import asyncMiddleware from 'api/middleware/asyncMiddleware';
|
import asyncMiddleware from 'api/middleware/asyncMiddleware';
|
||||||
|
|
||||||
@@ -61,8 +61,18 @@ export default class BaseController {
|
|||||||
* Transform the given data to response.
|
* Transform the given data to response.
|
||||||
* @param {any} data
|
* @param {any} data
|
||||||
*/
|
*/
|
||||||
transfromToResponse(data: any) {
|
transfromToResponse(data: any, translatable?: string | string[], req?: Request) {
|
||||||
return mapKeysDeep(data, (v, k) => snakeCase(k));
|
const response = mapKeysDeep(data, (v, k) => snakeCase(k));
|
||||||
|
|
||||||
|
if (translatable) {
|
||||||
|
const translatables = Array.isArray(translatable) ? translatable : [translatable];
|
||||||
|
|
||||||
|
translatables.forEach((path) => {
|
||||||
|
const value = get(response, path);
|
||||||
|
set(response, path, req.__(value));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
asyncMiddleware(callback) {
|
asyncMiddleware(callback) {
|
||||||
|
|||||||
@@ -334,10 +334,10 @@ export default class PaymentReceivesController extends BaseController {
|
|||||||
errors: [{ type: 'PAYMENT_RECEIVE_NOT_EXISTS', code: 300 }],
|
errors: [{ type: 'PAYMENT_RECEIVE_NOT_EXISTS', code: 300 }],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (error.errorType === 'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE') {
|
if (error.errorType === 'DEPOSIT_ACCOUNT_INVALID_TYPE') {
|
||||||
return res.boom.badRequest(null, {
|
return res.boom.badRequest(null, {
|
||||||
errors: [
|
errors: [
|
||||||
{ type: 'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE', code: 300 },
|
{ type: 'DEPOSIT_ACCOUNT_INVALID_TYPE', code: 300 },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
226
server/src/data/AccountTypes.ts
Normal file
226
server/src/data/AccountTypes.ts
Normal file
@@ -0,0 +1,226 @@
|
|||||||
|
|
||||||
|
|
||||||
|
export const ACCOUNT_TYPE = {
|
||||||
|
CASH: 'cash',
|
||||||
|
BANK: 'bank',
|
||||||
|
ACCOUNTS_RECEIVABLE: 'accounts-receivable',
|
||||||
|
INVENTORY: 'inventory',
|
||||||
|
OTHER_CURRENT_ASSET: 'other-ACCOUNT_PARENT_TYPE.CURRENT_ASSET',
|
||||||
|
FIXED_ASSET: 'fixed-asset',
|
||||||
|
NON_CURRENT_ASSET: 'non-ACCOUNT_PARENT_TYPE.CURRENT_ASSET',
|
||||||
|
|
||||||
|
ACCOUNTS_PAYABLE: 'accounts-payable',
|
||||||
|
CREDIT_CARD: 'credit-card',
|
||||||
|
TAX_PAYABLE: 'tax-payable',
|
||||||
|
OTHER_CURRENT_LIABILITY: 'other-current-liability',
|
||||||
|
LOGN_TERM_LIABILITY: 'long-term-liability',
|
||||||
|
NON_CURRENT_LIABILITY: 'non-current-liability',
|
||||||
|
|
||||||
|
EQUITY: 'equity',
|
||||||
|
INCOME: 'income',
|
||||||
|
OTHER_INCOME: 'other-income',
|
||||||
|
COST_OF_GOODS_SOLD: 'cost-of-goods-sold',
|
||||||
|
EXPENSE: 'expense',
|
||||||
|
OTHER_EXPENSE: 'other-expense',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ACCOUNT_PARENT_TYPE = {
|
||||||
|
CURRENT_ASSET: 'current-asset',
|
||||||
|
FIXED_ASSET: 'fixed-asset',
|
||||||
|
NON_CURRENT_ASSET: 'non-ACCOUNT_PARENT_TYPE.CURRENT_ASSET',
|
||||||
|
|
||||||
|
CURRENT_LIABILITY: 'current-liability',
|
||||||
|
LOGN_TERM_LIABILITY: 'long-term-liability',
|
||||||
|
NON_CURRENT_LIABILITY: 'non-current-liability',
|
||||||
|
|
||||||
|
EQUITY: 'equity',
|
||||||
|
EXPENSE: 'expense',
|
||||||
|
INCOME: 'income',
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ACCOUNT_ROOT_TYPE = {
|
||||||
|
ASSET: 'asset',
|
||||||
|
LIABILITY: 'liability',
|
||||||
|
EQUITY: 'equity',
|
||||||
|
EXPENSE: 'expene',
|
||||||
|
INCOME: 'income',
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
export const ACCOUNT_NORMAL = {
|
||||||
|
CREDIT: 'credit',
|
||||||
|
DEBIT: 'debit',
|
||||||
|
};
|
||||||
|
export const ACCOUNT_TYPES = [
|
||||||
|
{
|
||||||
|
label: 'Cash',
|
||||||
|
key: ACCOUNT_TYPE.CASH,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.CURRENT_ASSET,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.ASSET,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Bank',
|
||||||
|
key: ACCOUNT_TYPE.BANK,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.CURRENT_ASSET,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.ASSET,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Accounts Receivable',
|
||||||
|
key: ACCOUNT_TYPE.ACCOUNTS_RECEIVABLE,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.ASSET,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.CURRENT_ASSET,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Inventory',
|
||||||
|
key: ACCOUNT_TYPE.INVENTORY,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.ASSET,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.CURRENT_ASSET,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Other Current Asset',
|
||||||
|
key: ACCOUNT_TYPE.OTHER_CURRENT_ASSET,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.ASSET,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.CURRENT_ASSET,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Fixed Asset',
|
||||||
|
key: ACCOUNT_TYPE.FIXED_ASSET,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.ASSET,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.FIXED_ASSET,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Non-Current Asset',
|
||||||
|
key: ACCOUNT_TYPE.NON_CURRENT_ASSET,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.ASSET,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.FIXED_ASSET,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Accounts Payable',
|
||||||
|
key: ACCOUNT_TYPE.ACCOUNTS_PAYABLE,
|
||||||
|
normal: ACCOUNT_NORMAL.CREDIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.LIABILITY,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.CURRENT_LIABILITY,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Credit Card',
|
||||||
|
key: ACCOUNT_TYPE.CREDIT_CARD,
|
||||||
|
normal: ACCOUNT_NORMAL.CREDIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.LIABILITY,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.CURRENT_LIABILITY,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Tax Payable',
|
||||||
|
key: ACCOUNT_TYPE.TAX_PAYABLE,
|
||||||
|
normal: ACCOUNT_NORMAL.CREDIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.LIABILITY,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.CURRENT_LIABILITY,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Other Current Liability',
|
||||||
|
key: ACCOUNT_TYPE.OTHER_CURRENT_LIABILITY,
|
||||||
|
normal: ACCOUNT_NORMAL.CREDIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.LIABILITY,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.CURRENT_LIABILITY,
|
||||||
|
balanceSheet: false,
|
||||||
|
incomeSheet: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Long Term Liability',
|
||||||
|
key: ACCOUNT_TYPE.LOGN_TERM_LIABILITY,
|
||||||
|
normal: ACCOUNT_NORMAL.CREDIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.LIABILITY,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.LOGN_TERM_LIABILITY,
|
||||||
|
balanceSheet: false,
|
||||||
|
incomeSheet: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Non-Current Liability',
|
||||||
|
key: ACCOUNT_TYPE.NON_CURRENT_LIABILITY,
|
||||||
|
normal: ACCOUNT_NORMAL.CREDIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.LIABILITY,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.NON_CURRENT_LIABILITY,
|
||||||
|
balanceSheet: false,
|
||||||
|
incomeSheet: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Equity',
|
||||||
|
key: ACCOUNT_TYPE.EQUITY,
|
||||||
|
normal: ACCOUNT_NORMAL.CREDIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.EQUITY,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.EQUITY,
|
||||||
|
balanceSheet: true,
|
||||||
|
incomeSheet: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Income',
|
||||||
|
key: ACCOUNT_TYPE.INCOME,
|
||||||
|
normal: ACCOUNT_NORMAL.CREDIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.INCOME,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.INCOME,
|
||||||
|
balanceSheet: false,
|
||||||
|
incomeSheet: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Other Income',
|
||||||
|
key: ACCOUNT_TYPE.OTHER_INCOME,
|
||||||
|
normal: ACCOUNT_NORMAL.CREDIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.INCOME,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.INCOME,
|
||||||
|
balanceSheet: false,
|
||||||
|
incomeSheet: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Cost of Goods Sold',
|
||||||
|
key: ACCOUNT_TYPE.COST_OF_GOODS_SOLD,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.EXPENSE,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.EXPENSE,
|
||||||
|
balanceSheet: false,
|
||||||
|
incomeSheet: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Expense',
|
||||||
|
key: ACCOUNT_TYPE.EXPENSE,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.EXPENSE,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.EXPENSE,
|
||||||
|
balanceSheet: false,
|
||||||
|
incomeSheet: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: 'Other Expense',
|
||||||
|
key: ACCOUNT_TYPE.OTHER_EXPENSE,
|
||||||
|
normal: ACCOUNT_NORMAL.DEBIT,
|
||||||
|
rootType: ACCOUNT_ROOT_TYPE.EXPENSE,
|
||||||
|
parentType: ACCOUNT_PARENT_TYPE.EXPENSE,
|
||||||
|
balanceSheet: false,
|
||||||
|
incomeSheet: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
|
|
||||||
exports.up = (knex) => {
|
|
||||||
return knex.schema.createTable('account_types', (table) => {
|
|
||||||
table.increments();
|
|
||||||
table.string('key').index();
|
|
||||||
table.string('normal').index();
|
|
||||||
table.string('root_type').index();
|
|
||||||
table.string('child_type');
|
|
||||||
table.boolean('balance_sheet');
|
|
||||||
table.boolean('income_sheet');
|
|
||||||
}).raw('ALTER TABLE `ACCOUNT_TYPES` AUTO_INCREMENT = 1000');
|
|
||||||
};
|
|
||||||
|
|
||||||
exports.down = (knex) => knex.schema.dropTableIfExists('account_types');
|
|
||||||
@@ -3,7 +3,7 @@ exports.up = function (knex) {
|
|||||||
table.increments('id').comment('Auto-generated id');
|
table.increments('id').comment('Auto-generated id');
|
||||||
table.string('name').index();
|
table.string('name').index();
|
||||||
table.string('slug');
|
table.string('slug');
|
||||||
table.integer('account_type_id').unsigned().references('id').inTable('account_types');
|
table.string('account_type').index();
|
||||||
table.integer('parent_account_id').unsigned().references('id').inTable('accounts');
|
table.integer('parent_account_id').unsigned().references('id').inTable('accounts');
|
||||||
table.string('code', 10).index();
|
table.string('code', 10).index();
|
||||||
table.text('description');
|
table.text('description');
|
||||||
|
|||||||
@@ -3,30 +3,10 @@ import { get } from 'lodash';
|
|||||||
import TenancyService from 'services/Tenancy/TenancyService'
|
import TenancyService from 'services/Tenancy/TenancyService'
|
||||||
import AccountsData from '../data/accounts';
|
import AccountsData from '../data/accounts';
|
||||||
|
|
||||||
|
|
||||||
exports.up = function (knex) {
|
exports.up = function (knex) {
|
||||||
const tenancyService = Container.get(TenancyService);
|
|
||||||
const i18n = tenancyService.i18n(knex.userParams.tenantId);
|
|
||||||
|
|
||||||
const accountMapper = (account) => {
|
|
||||||
return knex('account_types').where('key', account.account_type).first()
|
|
||||||
.then((accountType) => ({
|
|
||||||
name: i18n.__(account.name),
|
|
||||||
slug: account.slug,
|
|
||||||
account_type_id: get(accountType, 'id', null),
|
|
||||||
code: account.code,
|
|
||||||
description: i18n.__(account.description),
|
|
||||||
active: 1,
|
|
||||||
index: 1,
|
|
||||||
predefined: account.predefined,
|
|
||||||
}));
|
|
||||||
};
|
|
||||||
return knex('accounts').then(async () => {
|
return knex('accounts').then(async () => {
|
||||||
const accountsPromises = AccountsData.map(accountMapper);
|
|
||||||
const accounts = await Promise.all(accountsPromises);
|
|
||||||
|
|
||||||
// Inserts seed entries.
|
// Inserts seed entries.
|
||||||
return knex('accounts').insert([ ...accounts ]);
|
return knex('accounts').insert([ ...AccountsData ]);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ export default [
|
|||||||
name:'Computer Equipment',
|
name:'Computer Equipment',
|
||||||
slug: 'computer-equipment',
|
slug: 'computer-equipment',
|
||||||
code: '10005',
|
code: '10005',
|
||||||
account_type: 'fixed_asset',
|
account_type: 'fixed-asset',
|
||||||
predefined: 0,
|
predefined: 0,
|
||||||
parent_account_id: null,
|
parent_account_id: null,
|
||||||
index: 1,
|
index: 1,
|
||||||
@@ -55,7 +55,7 @@ export default [
|
|||||||
name:'Office Equipment',
|
name:'Office Equipment',
|
||||||
slug: 'office-equipment',
|
slug: 'office-equipment',
|
||||||
code: '10006',
|
code: '10006',
|
||||||
account_type: 'fixed_asset',
|
account_type: 'fixed-asset',
|
||||||
predefined: 0,
|
predefined: 0,
|
||||||
parent_account_id: null,
|
parent_account_id: null,
|
||||||
index: 1,
|
index: 1,
|
||||||
@@ -65,7 +65,7 @@ export default [
|
|||||||
{
|
{
|
||||||
name:'Accounts Receivable (A/R)',
|
name:'Accounts Receivable (A/R)',
|
||||||
slug: 'accounts-receivable',
|
slug: 'accounts-receivable',
|
||||||
account_type: 'accounts_receivable',
|
account_type: 'accounts-receivable',
|
||||||
code: '10007',
|
code: '10007',
|
||||||
description: '',
|
description: '',
|
||||||
active: 1,
|
active: 1,
|
||||||
@@ -88,7 +88,7 @@ export default [
|
|||||||
{
|
{
|
||||||
name:'Accounts Payable (A/P)',
|
name:'Accounts Payable (A/P)',
|
||||||
slug: 'accounts-payable',
|
slug: 'accounts-payable',
|
||||||
account_type: 'accounts_payable',
|
account_type: 'accounts-payable',
|
||||||
parent_account_id: null,
|
parent_account_id: null,
|
||||||
code: '20001',
|
code: '20001',
|
||||||
description: '',
|
description: '',
|
||||||
@@ -99,7 +99,7 @@ export default [
|
|||||||
{
|
{
|
||||||
name:'Owner A Drawings',
|
name:'Owner A Drawings',
|
||||||
slug: 'owner-drawings',
|
slug: 'owner-drawings',
|
||||||
account_type: 'other_current_liability',
|
account_type: 'other-current-liability',
|
||||||
parent_account_id: null,
|
parent_account_id: null,
|
||||||
code: '20002',
|
code: '20002',
|
||||||
description:'Withdrawals by the owners.',
|
description:'Withdrawals by the owners.',
|
||||||
@@ -110,7 +110,7 @@ export default [
|
|||||||
{
|
{
|
||||||
name:'Loan',
|
name:'Loan',
|
||||||
slug: 'owner-drawings',
|
slug: 'owner-drawings',
|
||||||
account_type: 'other_current_liability',
|
account_type: 'other-current-liability',
|
||||||
code: '20003',
|
code: '20003',
|
||||||
description:'Money that has been borrowed from a creditor.',
|
description:'Money that has been borrowed from a creditor.',
|
||||||
active: 1,
|
active: 1,
|
||||||
@@ -120,7 +120,7 @@ export default [
|
|||||||
{
|
{
|
||||||
name:'Opening Balance Adjustments',
|
name:'Opening Balance Adjustments',
|
||||||
slug: 'opening-balance-adjustments',
|
slug: 'opening-balance-adjustments',
|
||||||
account_type: 'other_current_liability',
|
account_type: 'other-current-liability',
|
||||||
code: '20004',
|
code: '20004',
|
||||||
description:'This account will hold the difference in the debits and credits entered during the opening balance..',
|
description:'This account will hold the difference in the debits and credits entered during the opening balance..',
|
||||||
active: 1,
|
active: 1,
|
||||||
@@ -129,8 +129,8 @@ export default [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
name:'Revenue Received in Advance',
|
name:'Revenue Received in Advance',
|
||||||
slug: 'Revenue-received-in-advance',
|
slug: 'revenue-received-in-advance',
|
||||||
account_type: 'other_current_liability',
|
account_type: 'other-current-liability',
|
||||||
parent_account_id: null,
|
parent_account_id: null,
|
||||||
code: '20005',
|
code: '20005',
|
||||||
description: 'When customers pay in advance for products/services.',
|
description: 'When customers pay in advance for products/services.',
|
||||||
@@ -141,7 +141,7 @@ export default [
|
|||||||
{
|
{
|
||||||
name:'Sales Tax Payable',
|
name:'Sales Tax Payable',
|
||||||
slug: 'owner-drawings',
|
slug: 'owner-drawings',
|
||||||
account_type: 'tax_payable',
|
account_type: 'other-current-liability',
|
||||||
code: '20006',
|
code: '20006',
|
||||||
description: '',
|
description: '',
|
||||||
active: 1,
|
active: 1,
|
||||||
@@ -206,7 +206,7 @@ export default [
|
|||||||
{
|
{
|
||||||
name:'Cost of Goods Sold',
|
name:'Cost of Goods Sold',
|
||||||
slug: 'cost-of-goods-sold',
|
slug: 'cost-of-goods-sold',
|
||||||
account_type: 'cost_of_goods_sold',
|
account_type: 'cost-of-goods-sold',
|
||||||
parent_account_id: null,
|
parent_account_id: null,
|
||||||
code: '40002',
|
code: '40002',
|
||||||
description:'Tracks the direct cost of the goods sold.',
|
description:'Tracks the direct cost of the goods sold.',
|
||||||
@@ -239,7 +239,7 @@ export default [
|
|||||||
{
|
{
|
||||||
name:'Exchange Gain or Loss',
|
name:'Exchange Gain or Loss',
|
||||||
slug: 'exchange-grain-loss',
|
slug: 'exchange-grain-loss',
|
||||||
account_type: 'other_expense',
|
account_type: 'other-expense',
|
||||||
parent_account_id: null,
|
parent_account_id: null,
|
||||||
code: '40005',
|
code: '40005',
|
||||||
description:'Tracks the gain and losses of the exchange differences.',
|
description:'Tracks the gain and losses of the exchange differences.',
|
||||||
@@ -307,7 +307,7 @@ export default [
|
|||||||
{
|
{
|
||||||
name:'Other Income',
|
name:'Other Income',
|
||||||
slug: 'other-income',
|
slug: 'other-income',
|
||||||
account_type: 'other_income',
|
account_type: 'other-income',
|
||||||
parent_account_id: null,
|
parent_account_id: null,
|
||||||
code: '50004',
|
code: '50004',
|
||||||
description:'The income activities are not associated to the core business.',
|
description:'The income activities are not associated to the core business.',
|
||||||
|
|||||||
@@ -105,51 +105,5 @@ export default [
|
|||||||
balance_sheet: false,
|
balance_sheet: false,
|
||||||
income_sheet: true,
|
income_sheet: true,
|
||||||
},
|
},
|
||||||
{
|
|
||||||
key: 'equity',
|
|
||||||
normal: 'credit',
|
|
||||||
root_type: 'equity',
|
|
||||||
child_type: 'equity',
|
|
||||||
balance_sheet: true,
|
|
||||||
income_sheet: false,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'income',
|
|
||||||
normal: 'credit',
|
|
||||||
root_type: 'income',
|
|
||||||
child_type: 'income',
|
|
||||||
balance_sheet: false,
|
|
||||||
income_sheet: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'other_income',
|
|
||||||
normal: 'credit',
|
|
||||||
root_type: 'income',
|
|
||||||
child_type: 'other_income',
|
|
||||||
balance_sheet: false,
|
|
||||||
income_sheet: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'cost_of_goods_sold',
|
|
||||||
normal: 'debit',
|
|
||||||
root_type: 'expenses',
|
|
||||||
child_type: 'expenses',
|
|
||||||
balance_sheet: false,
|
|
||||||
income_sheet: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'expense',
|
|
||||||
normal: 'debit',
|
|
||||||
root_type: 'expense',
|
|
||||||
child_type: 'expense',
|
|
||||||
balance_sheet: false,
|
|
||||||
income_sheet: true,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'other_expense',
|
|
||||||
normal: 'debit',
|
|
||||||
root_type: 'expense',
|
|
||||||
balance_sheet: false,
|
|
||||||
income_sheet: true,
|
|
||||||
},
|
|
||||||
];
|
];
|
||||||
@@ -4,7 +4,7 @@ export interface IAccountDTO {
|
|||||||
name: string,
|
name: string,
|
||||||
code: string,
|
code: string,
|
||||||
description: string,
|
description: string,
|
||||||
accountTypeId: number,
|
accountType: string,
|
||||||
parentAccountId: number,
|
parentAccountId: number,
|
||||||
active: boolean,
|
active: boolean,
|
||||||
};
|
};
|
||||||
@@ -16,7 +16,7 @@ export interface IAccount {
|
|||||||
code: string,
|
code: string,
|
||||||
index: number,
|
index: number,
|
||||||
description: string,
|
description: string,
|
||||||
accountTypeId: number,
|
accountType: string,
|
||||||
parentAccountId: number,
|
parentAccountId: number,
|
||||||
active: boolean,
|
active: boolean,
|
||||||
predefined: boolean,
|
predefined: boolean,
|
||||||
@@ -31,7 +31,7 @@ export interface IAccountsFilter extends IDynamicListFilterDTO {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export interface IAccountType {
|
export interface IAccountType {
|
||||||
id: number,
|
label: string,
|
||||||
key: string,
|
key: string,
|
||||||
label: string,
|
label: string,
|
||||||
normal: string,
|
normal: string,
|
||||||
|
|||||||
101
server/src/lib/AccountTypes/index.ts
Normal file
101
server/src/lib/AccountTypes/index.ts
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
import { get } from 'lodash';
|
||||||
|
import { ACCOUNT_TYPES } from 'data/AccountTypes';
|
||||||
|
|
||||||
|
export default class AccountTypesUtils {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve account types list.
|
||||||
|
*/
|
||||||
|
static getList() {
|
||||||
|
return ACCOUNT_TYPES;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {string} rootType
|
||||||
|
*/
|
||||||
|
static getTypesByRootType(rootType: string) {
|
||||||
|
return ACCOUNT_TYPES.filter((type) => type.rootType === rootType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {string} key
|
||||||
|
* @param {string} accessor
|
||||||
|
*/
|
||||||
|
static getType(key: string, accessor?: string) {
|
||||||
|
const type = ACCOUNT_TYPES.find((type) => type.key === key);
|
||||||
|
|
||||||
|
if (accessor) {
|
||||||
|
return get(type, accessor);
|
||||||
|
}
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {string} parentType
|
||||||
|
*/
|
||||||
|
static getTypesByParentType(parentType: string) {
|
||||||
|
return ACCOUNT_TYPES.filter((type) => type.parentType === parentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {string} normal
|
||||||
|
*/
|
||||||
|
static getTypesByNormal(normal: string) {
|
||||||
|
return ACCOUNT_TYPES.filter((type) => type.normal === normal);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {string} key
|
||||||
|
* @param {string} rootType
|
||||||
|
*/
|
||||||
|
static isRootTypeEqualsKey(key: string, rootType: string) {
|
||||||
|
return ACCOUNT_TYPES.some((type) => {
|
||||||
|
const isType = type.key === key;
|
||||||
|
const isRootType = type.rootType === rootType;
|
||||||
|
|
||||||
|
return isType && isRootType;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {string} key
|
||||||
|
* @param {string} parentType
|
||||||
|
*/
|
||||||
|
static isParentTypeEqualsKey(key: string, parentType: string) {
|
||||||
|
return ACCOUNT_TYPES.some((type) => {
|
||||||
|
const isType = type.key === key;
|
||||||
|
const isParentType = type.parentType === parentType;
|
||||||
|
|
||||||
|
return isType && isParentType;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {string} key
|
||||||
|
*/
|
||||||
|
static isTypeBalanceSheet(key: string) {
|
||||||
|
return ACCOUNT_TYPES.some((type) => {
|
||||||
|
const isType = type.key === key;
|
||||||
|
return isType && type.balanceSheet;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param {string} key
|
||||||
|
*/
|
||||||
|
static isTypePLSheet(key: string) {
|
||||||
|
return ACCOUNT_TYPES.some((type) => {
|
||||||
|
const isType = type.key === key;
|
||||||
|
return isType && type.incomeSheet;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,7 +2,6 @@ import { mapValues } from 'lodash';
|
|||||||
|
|
||||||
import Account from 'models/Account';
|
import Account from 'models/Account';
|
||||||
import AccountTransaction from 'models/AccountTransaction';
|
import AccountTransaction from 'models/AccountTransaction';
|
||||||
import AccountType from 'models/AccountType';
|
|
||||||
import Item from 'models/Item';
|
import Item from 'models/Item';
|
||||||
import ItemEntry from 'models/ItemEntry';
|
import ItemEntry from 'models/ItemEntry';
|
||||||
import ItemCategory from 'models/ItemCategory';
|
import ItemCategory from 'models/ItemCategory';
|
||||||
@@ -43,7 +42,6 @@ export default (knex) => {
|
|||||||
Option,
|
Option,
|
||||||
Account,
|
Account,
|
||||||
AccountTransaction,
|
AccountTransaction,
|
||||||
AccountType,
|
|
||||||
Item,
|
Item,
|
||||||
ItemCategory,
|
ItemCategory,
|
||||||
ItemEntry,
|
ItemEntry,
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
import AccountRepository from 'repositories/AccountRepository';
|
import AccountRepository from 'repositories/AccountRepository';
|
||||||
import AccountTypeRepository from 'repositories/AccountTypeRepository';
|
|
||||||
import VendorRepository from 'repositories/VendorRepository';
|
import VendorRepository from 'repositories/VendorRepository';
|
||||||
import CustomerRepository from 'repositories/CustomerRepository';
|
import CustomerRepository from 'repositories/CustomerRepository';
|
||||||
import ExpenseRepository from 'repositories/ExpenseRepository';
|
import ExpenseRepository from 'repositories/ExpenseRepository';
|
||||||
@@ -18,7 +17,6 @@ export default (knex, cache) => {
|
|||||||
return {
|
return {
|
||||||
accountRepository: new AccountRepository(knex, cache),
|
accountRepository: new AccountRepository(knex, cache),
|
||||||
transactionsRepository: new AccountTransactionsRepository(knex, cache),
|
transactionsRepository: new AccountTransactionsRepository(knex, cache),
|
||||||
accountTypeRepository: new AccountTypeRepository(knex, cache),
|
|
||||||
customerRepository: new CustomerRepository(knex, cache),
|
customerRepository: new CustomerRepository(knex, cache),
|
||||||
vendorRepository: new VendorRepository(knex, cache),
|
vendorRepository: new VendorRepository(knex, cache),
|
||||||
contactRepository: new ContactRepository(knex, cache),
|
contactRepository: new ContactRepository(knex, cache),
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
{
|
{
|
||||||
"Petty Cash": "Petty Cash",
|
"Petty Cash": "Petty Cash",
|
||||||
|
"Cash": "Cash",
|
||||||
"Bank": "Bank",
|
"Bank": "Bank",
|
||||||
"Other Income": "Other Income",
|
"Other Income": "Other Income",
|
||||||
"Interest Income": "Interest Income",
|
"Interest Income": "Interest Income",
|
||||||
@@ -9,10 +10,13 @@
|
|||||||
"Sales of Product Income": "Sales of Product Income",
|
"Sales of Product Income": "Sales of Product Income",
|
||||||
"Inventory Asset": "Inventory Asset",
|
"Inventory Asset": "Inventory Asset",
|
||||||
"Cost of Goods Sold (COGS)": "Cost of Goods Sold (COGS)",
|
"Cost of Goods Sold (COGS)": "Cost of Goods Sold (COGS)",
|
||||||
|
"Cost of Goods Sold": "Cost of Goods Sold",
|
||||||
"Accounts Payable": "Accounts Payable",
|
"Accounts Payable": "Accounts Payable",
|
||||||
"Other Expenses": "Other Expenses",
|
"Other Expense": "Other Expense",
|
||||||
"Payroll Expenses": "Payroll Expenses",
|
"Payroll Expenses": "Payroll Expenses",
|
||||||
"Fixed Asset": "Fixed Asset",
|
"Fixed Asset": "Fixed Asset",
|
||||||
|
"Credit Card": "Credit Card",
|
||||||
|
"Non-Current Asset": "Non-Current Asset",
|
||||||
"Current Asset": "Current Asset",
|
"Current Asset": "Current Asset",
|
||||||
"Other Asset": "Other Asset",
|
"Other Asset": "Other Asset",
|
||||||
"Long Term Liability": "Long Term Liability",
|
"Long Term Liability": "Long Term Liability",
|
||||||
@@ -20,14 +24,17 @@
|
|||||||
"Other Liability": "Other Liability",
|
"Other Liability": "Other Liability",
|
||||||
"Equity": "Equity",
|
"Equity": "Equity",
|
||||||
"Expense": "Expense",
|
"Expense": "Expense",
|
||||||
"Other Expense": "Other Expense",
|
|
||||||
"Income": "Income",
|
"Income": "Income",
|
||||||
"Accounts Receivable (A/R)": "Accounts Receivable (A/R)",
|
"Accounts Receivable (A/R)": "Accounts Receivable (A/R)",
|
||||||
|
"Accounts Receivable": "Accounts Receivable",
|
||||||
"Accounts Payable (A/P)": "Accounts Payable (A/P)",
|
"Accounts Payable (A/P)": "Accounts Payable (A/P)",
|
||||||
"Inactive": "Inactive",
|
"Inactive": "Inactive",
|
||||||
|
"Other Current Asset": "Other Current Asset",
|
||||||
|
"Tax Payable": "Tax Payable",
|
||||||
|
"Other Current Liability": "Other Current Liability",
|
||||||
|
"Non-Current Liability": "Non-Current Liability",
|
||||||
"Assets": "Assets",
|
"Assets": "Assets",
|
||||||
"Liabilities": "Liabilities",
|
"Liabilities": "Liabilities",
|
||||||
"Expenses": "Expenses",
|
|
||||||
"Account name": "Account name",
|
"Account name": "Account name",
|
||||||
"Account type": "Account type",
|
"Account type": "Account type",
|
||||||
"Account normal": "Account normal",
|
"Account normal": "Account normal",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
/* eslint-disable global-require */
|
/* eslint-disable global-require */
|
||||||
import { Model } from 'objection';
|
import { Model } from 'objection';
|
||||||
import { flatten } from 'lodash';
|
import { flatten, castArray } from 'lodash';
|
||||||
import TenantModel from 'models/TenantModel';
|
import TenantModel from 'models/TenantModel';
|
||||||
import {
|
import {
|
||||||
buildFilterQuery,
|
buildFilterQuery,
|
||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
} from 'lib/ViewRolesBuilder';
|
} from 'lib/ViewRolesBuilder';
|
||||||
import { flatToNestedArray } from 'utils';
|
import { flatToNestedArray } from 'utils';
|
||||||
import DependencyGraph from 'lib/DependencyGraph';
|
import DependencyGraph from 'lib/DependencyGraph';
|
||||||
|
import AccountTypesUtils from 'lib/AccountTypes'
|
||||||
|
|
||||||
export default class Account extends TenantModel {
|
export default class Account extends TenantModel {
|
||||||
/**
|
/**
|
||||||
@@ -24,6 +25,54 @@ export default class Account extends TenantModel {
|
|||||||
return ['createdAt', 'updatedAt'];
|
return ['createdAt', 'updatedAt'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Virtual attributes.
|
||||||
|
*/
|
||||||
|
static get virtualAttributes() {
|
||||||
|
return [
|
||||||
|
'accountTypeLabel',
|
||||||
|
'accountParentTypeLabel',
|
||||||
|
'accountNormal',
|
||||||
|
'isBalanceSheetAccount',
|
||||||
|
'isPLSheet'
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Account normal.
|
||||||
|
*/
|
||||||
|
get accountNormal() {
|
||||||
|
return AccountTypesUtils.getType(this.accountType, 'normal');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve account type label.
|
||||||
|
*/
|
||||||
|
get accountTypeLabel() {
|
||||||
|
return AccountTypesUtils.getType(this.accountType, 'label');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve account parent type.
|
||||||
|
*/
|
||||||
|
get accountParentType() {
|
||||||
|
return AccountTypesUtils.getType(this.accountType, 'parentType');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve whether the account is balance sheet account.
|
||||||
|
*/
|
||||||
|
get isBalanceSheetAccount() {
|
||||||
|
return this.isBalanceSheet();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve whether the account is profit/loss sheet account.
|
||||||
|
*/
|
||||||
|
get isPLSheet() {
|
||||||
|
return this.isProfitLossSheet();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Allows to mark model as resourceable to viewable and filterable.
|
* Allows to mark model as resourceable to viewable and filterable.
|
||||||
*/
|
*/
|
||||||
@@ -61,22 +110,9 @@ export default class Account extends TenantModel {
|
|||||||
* Relationship mapping.
|
* Relationship mapping.
|
||||||
*/
|
*/
|
||||||
static get relationMappings() {
|
static get relationMappings() {
|
||||||
const AccountType = require('models/AccountType');
|
|
||||||
const AccountTransaction = require('models/AccountTransaction');
|
const AccountTransaction = require('models/AccountTransaction');
|
||||||
|
|
||||||
return {
|
return {
|
||||||
/**
|
|
||||||
* Account model may belongs to account type.
|
|
||||||
*/
|
|
||||||
type: {
|
|
||||||
relation: Model.BelongsToOneRelation,
|
|
||||||
modelClass: AccountType.default,
|
|
||||||
join: {
|
|
||||||
from: 'accounts.accountTypeId',
|
|
||||||
to: 'account_types.id',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Account model may has many transactions.
|
* Account model may has many transactions.
|
||||||
*/
|
*/
|
||||||
@@ -90,6 +126,58 @@ export default class Account extends TenantModel {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detarmines whether the given type equals the account type.
|
||||||
|
* @param {string} accountType
|
||||||
|
* @return {boolean}
|
||||||
|
*/
|
||||||
|
isAccountType(accountType) {
|
||||||
|
const types = castArray(accountType);
|
||||||
|
return types.indexOf(this.accountType) !== -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detarmines whether the given root type equals the account type.
|
||||||
|
* @param {string} rootType
|
||||||
|
* @return {boolean}
|
||||||
|
*/
|
||||||
|
isRootType(rootType) {
|
||||||
|
return AccountTypesUtils.isRootTypeEqualsKey(this.accountType, rootType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detarmine whether the given parent type equals the account type.
|
||||||
|
* @param {string} parentType
|
||||||
|
* @return {boolean}
|
||||||
|
*/
|
||||||
|
isParentType(parentType) {
|
||||||
|
return AccountTypesUtils.isParentTypeEqualsKey(this.accountType, parentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detarmines whether the account is balance sheet account.
|
||||||
|
* @return {boolean}
|
||||||
|
*/
|
||||||
|
isBalanceSheet() {
|
||||||
|
return AccountTypesUtils.isTypeBalanceSheet(this.accountType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detarmines whether the account is profit/loss account.
|
||||||
|
* @return {boolean}
|
||||||
|
*/
|
||||||
|
isProfitLossSheet() {
|
||||||
|
return AccountTypesUtils.isTypePLSheet(this.accountType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Detarmines whether the account is income statement account
|
||||||
|
* @return {boolean}
|
||||||
|
*/
|
||||||
|
isIncomeSheet() {
|
||||||
|
return this.isProfitLossSheet();
|
||||||
|
}
|
||||||
|
|
||||||
static collectJournalEntries(accounts) {
|
static collectJournalEntries(accounts) {
|
||||||
return flatten(accounts.map((account) => account.transactions.map((transaction) => ({
|
return flatten(accounts.map((account) => account.transactions.map((transaction) => ({
|
||||||
|
|||||||
@@ -1,80 +0,0 @@
|
|||||||
// import path from 'path';
|
|
||||||
import { Model, mixin } from 'objection';
|
|
||||||
import TenantModel from 'models/TenantModel';
|
|
||||||
|
|
||||||
export default class AccountType extends TenantModel {
|
|
||||||
/**
|
|
||||||
* Table name.
|
|
||||||
*/
|
|
||||||
static get tableName() {
|
|
||||||
return 'account_types';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Virtaul attributes.
|
|
||||||
*/
|
|
||||||
static get virtualAttributes() {
|
|
||||||
return ['label'];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Allows to mark model as resourceable to viewable and filterable.
|
|
||||||
*/
|
|
||||||
static get resourceable() {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Translatable lable.
|
|
||||||
*/
|
|
||||||
label() {
|
|
||||||
return AccountType.labels[this.key] || '';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Relationship mapping.
|
|
||||||
*/
|
|
||||||
static get relationMappings() {
|
|
||||||
const Account = require('models/Account');
|
|
||||||
|
|
||||||
return {
|
|
||||||
/**
|
|
||||||
* Account type may has many associated accounts.
|
|
||||||
*/
|
|
||||||
accounts: {
|
|
||||||
relation: Model.HasManyRelation,
|
|
||||||
modelClass: Account.default,
|
|
||||||
join: {
|
|
||||||
from: 'account_types.id',
|
|
||||||
to: 'accounts.accountTypeId',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Accounts types labels.
|
|
||||||
*/
|
|
||||||
static get labels() {
|
|
||||||
return {
|
|
||||||
inventory: 'Inventory',
|
|
||||||
other_current_asset: 'Other Current Asset',
|
|
||||||
bank: 'Bank Account',
|
|
||||||
cash: 'Cash',
|
|
||||||
fixed_asset: 'Fixed Asset',
|
|
||||||
non_current_asset: 'Non-Current Asset',
|
|
||||||
accounts_payable: 'Accounts Payable (A/P)',
|
|
||||||
accounts_receivable: 'Accounts Receivable (A/R)',
|
|
||||||
credit_card: 'Credit Card',
|
|
||||||
long_term_liability: 'Long Term Liability',
|
|
||||||
other_current_liability: 'Other Current Liability',
|
|
||||||
other_liability: 'Other Liability',
|
|
||||||
equity: "Equity",
|
|
||||||
expense: "Expense",
|
|
||||||
income: "Income",
|
|
||||||
other_income: "Other Income",
|
|
||||||
other_expense: "Other Expense",
|
|
||||||
cost_of_goods_sold: "Cost of Goods Sold (COGS)",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -17,7 +17,6 @@ import BillPaymentEntry from './BillPaymentEntry';
|
|||||||
import View from './View';
|
import View from './View';
|
||||||
import ItemEntry from './ItemEntry';
|
import ItemEntry from './ItemEntry';
|
||||||
import InventoryTransaction from './InventoryTransaction';
|
import InventoryTransaction from './InventoryTransaction';
|
||||||
import AccountType from './AccountType';
|
|
||||||
import InventoryLotCostTracker from './InventoryCostLotTracker';
|
import InventoryLotCostTracker from './InventoryCostLotTracker';
|
||||||
import Customer from './Customer';
|
import Customer from './Customer';
|
||||||
import Contact from './Contact';
|
import Contact from './Contact';
|
||||||
@@ -45,7 +44,6 @@ export {
|
|||||||
ItemEntry,
|
ItemEntry,
|
||||||
InventoryTransaction,
|
InventoryTransaction,
|
||||||
InventoryLotCostTracker,
|
InventoryLotCostTracker,
|
||||||
AccountType,
|
|
||||||
Option,
|
Option,
|
||||||
Contact,
|
Contact,
|
||||||
ExpenseCategory,
|
ExpenseCategory,
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
import TenantRepository from 'repositories/TenantRepository';
|
|
||||||
import { IAccountType } from 'interfaces';
|
|
||||||
import { AccountType } from 'models';
|
|
||||||
|
|
||||||
export default class AccountTypeRepository extends TenantRepository {
|
|
||||||
/**
|
|
||||||
* Gets the repository's model.
|
|
||||||
*/
|
|
||||||
get model() {
|
|
||||||
return AccountType.bindKnex(this.knex);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieve accounts types of the given keys.
|
|
||||||
* @param {string[]} keys
|
|
||||||
* @return {Promise<IAccountType[]>}
|
|
||||||
*/
|
|
||||||
getByKeys(keys: string[]): Promise<IAccountType[]> {
|
|
||||||
return super.findWhereIn('key', keys);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieve account tpy eof the given key.
|
|
||||||
* @param {string} key
|
|
||||||
* @return {Promise<IAccountType>}
|
|
||||||
*/
|
|
||||||
getByKey(key: string): Promise<IAccountType> {
|
|
||||||
return super.findOne({ key });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieve accounts types of the given root type.
|
|
||||||
* @param {string} rootType
|
|
||||||
* @return {Promise<IAccountType[]>}
|
|
||||||
*/
|
|
||||||
getByRootType(rootType: string): Promise<IAccountType[]> {
|
|
||||||
return super.find({ root_type: rootType });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieve accounts types of the given child type.
|
|
||||||
* @param {string} childType
|
|
||||||
* @return {Promise<IAccountType[]>}
|
|
||||||
*/
|
|
||||||
getByChildType(childType: string): Promise<IAccountType[]> {
|
|
||||||
return super.find({ child_type: childType });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
} from 'decorators/eventDispatcher';
|
} from 'decorators/eventDispatcher';
|
||||||
import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
||||||
import events from 'subscribers/events';
|
import events from 'subscribers/events';
|
||||||
|
import AccountTypesUtils from 'lib/AccountTypes';
|
||||||
|
|
||||||
const ERRORS = {
|
const ERRORS = {
|
||||||
ACCOUNT_NOT_FOUND: 'account_not_found',
|
ACCOUNT_NOT_FOUND: 'account_not_found',
|
||||||
@@ -52,17 +53,13 @@ export default class AccountsService {
|
|||||||
* @param {number} accountTypeId -
|
* @param {number} accountTypeId -
|
||||||
* @return {IAccountType}
|
* @return {IAccountType}
|
||||||
*/
|
*/
|
||||||
private async getAccountTypeOrThrowError(
|
private getAccountTypeOrThrowError(
|
||||||
tenantId: number,
|
accountTypeKey: string
|
||||||
accountTypeId: number
|
|
||||||
) {
|
) {
|
||||||
const { accountTypeRepository } = this.tenancy.repositories(tenantId);
|
|
||||||
|
|
||||||
this.logger.info('[accounts] validating account type existance.', {
|
this.logger.info('[accounts] validating account type existance.', {
|
||||||
tenantId,
|
accountTypeKey
|
||||||
accountTypeId,
|
|
||||||
});
|
});
|
||||||
const accountType = await accountTypeRepository.findOneById(accountTypeId);
|
const accountType = AccountTypesUtils.getType(accountTypeKey);
|
||||||
|
|
||||||
if (!accountType) {
|
if (!accountType) {
|
||||||
this.logger.info('[accounts] account type not found.');
|
this.logger.info('[accounts] account type not found.');
|
||||||
@@ -153,7 +150,7 @@ export default class AccountsService {
|
|||||||
accountDTO: IAccountDTO,
|
accountDTO: IAccountDTO,
|
||||||
parentAccount: IAccount
|
parentAccount: IAccount
|
||||||
) {
|
) {
|
||||||
if (accountDTO.accountTypeId !== parentAccount.accountTypeId) {
|
if (accountDTO.accountType !== parentAccount.accountType) {
|
||||||
throw new ServiceError(ERRORS.PARENT_ACCOUNT_HAS_DIFFERENT_TYPE);
|
throw new ServiceError(ERRORS.PARENT_ACCOUNT_HAS_DIFFERENT_TYPE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -193,7 +190,7 @@ export default class AccountsService {
|
|||||||
oldAccount: IAccount | IAccountDTO,
|
oldAccount: IAccount | IAccountDTO,
|
||||||
newAccount: 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);
|
throw new ServiceError(ERRORS.ACCOUNT_TYPE_NOT_ALLOWED_TO_CHANGE);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -244,7 +241,7 @@ export default class AccountsService {
|
|||||||
if (accountDTO.code) {
|
if (accountDTO.code) {
|
||||||
await this.isAccountCodeUniqueOrThrowError(tenantId, accountDTO.code);
|
await this.isAccountCodeUniqueOrThrowError(tenantId, accountDTO.code);
|
||||||
}
|
}
|
||||||
await this.getAccountTypeOrThrowError(tenantId, accountDTO.accountTypeId);
|
this.getAccountTypeOrThrowError(accountDTO.accountType);
|
||||||
|
|
||||||
if (accountDTO.parentAccountId) {
|
if (accountDTO.parentAccountId) {
|
||||||
const parentAccount = await this.getParentAccountOrThrowError(
|
const parentAccount = await this.getParentAccountOrThrowError(
|
||||||
@@ -638,7 +635,6 @@ export default class AccountsService {
|
|||||||
filter,
|
filter,
|
||||||
});
|
});
|
||||||
const accounts = await Account.query().onBuild((builder) => {
|
const accounts = await Account.query().onBuild((builder) => {
|
||||||
builder.withGraphFetched('type');
|
|
||||||
dynamicList.buildQuery()(builder);
|
dynamicList.buildQuery()(builder);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -673,10 +669,8 @@ export default class AccountsService {
|
|||||||
toAccountId,
|
toAccountId,
|
||||||
deleteAfterClosing,
|
deleteAfterClosing,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { AccountTransaction } = this.tenancy.models(tenantId);
|
const { AccountTransaction } = this.tenancy.models(tenantId);
|
||||||
const {
|
const {
|
||||||
accountTypeRepository,
|
|
||||||
accountRepository,
|
accountRepository,
|
||||||
} = this.tenancy.repositories(tenantId);
|
} = this.tenancy.repositories(tenantId);
|
||||||
|
|
||||||
@@ -685,14 +679,7 @@ export default class AccountsService {
|
|||||||
|
|
||||||
this.throwErrorIfAccountPredefined(account);
|
this.throwErrorIfAccountPredefined(account);
|
||||||
|
|
||||||
const accountType = await accountTypeRepository.findOneById(
|
if (account.accountType !== toAccount.accountType) {
|
||||||
account.accountTypeId
|
|
||||||
);
|
|
||||||
const toAccountType = await accountTypeRepository.findOneById(
|
|
||||||
toAccount.accountTypeId
|
|
||||||
);
|
|
||||||
|
|
||||||
if (accountType.rootType !== toAccountType.rootType) {
|
|
||||||
throw new ServiceError(ERRORS.CLOSE_ACCOUNT_AND_TO_ACCOUNT_NOT_SAME_TYPE);
|
throw new ServiceError(ERRORS.CLOSE_ACCOUNT_AND_TO_ACCOUNT_NOT_SAME_TYPE);
|
||||||
}
|
}
|
||||||
const updateAccountBalanceOper = await accountRepository.balanceChange(
|
const updateAccountBalanceOper = await accountRepository.balanceChange(
|
||||||
|
|||||||
@@ -1,20 +1,14 @@
|
|||||||
import { Inject, Service } from 'typedi';
|
import { Service } from 'typedi';
|
||||||
import { omit } from 'lodash';
|
|
||||||
import TenancyService from 'services/Tenancy/TenancyService';
|
|
||||||
import { IAccountsTypesService, IAccountType } from 'interfaces';
|
import { IAccountsTypesService, IAccountType } from 'interfaces';
|
||||||
|
import AccountTypesUtils from 'lib/AccountTypes';
|
||||||
|
|
||||||
@Service()
|
@Service()
|
||||||
export default class AccountsTypesService implements IAccountsTypesService {
|
export default class AccountsTypesService implements IAccountsTypesService {
|
||||||
@Inject()
|
|
||||||
tenancy: TenancyService;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve all accounts types.
|
* Retrieve all accounts types.
|
||||||
* @param {number} tenantId -
|
* @return {IAccountType}
|
||||||
* @return {Promise<IAccountType>}
|
|
||||||
*/
|
*/
|
||||||
async getAccountsTypes(tenantId: number): Promise<IAccountType> {
|
getAccountsTypes(): IAccountType[] {
|
||||||
const { accountTypeRepository } = this.tenancy.repositories(tenantId);
|
return AccountTypesUtils.getList();
|
||||||
return accountTypeRepository.all();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
||||||
import events from 'subscribers/events';
|
import events from 'subscribers/events';
|
||||||
import ContactsService from 'services/Contacts/ContactsService';
|
import ContactsService from 'services/Contacts/ContactsService';
|
||||||
|
import { ACCOUNT_PARENT_TYPE, ACCOUNT_ROOT_TYPE } from 'data/AccountTypes'
|
||||||
|
|
||||||
const ERRORS = {
|
const ERRORS = {
|
||||||
EXPENSE_NOT_FOUND: 'expense_not_found',
|
EXPENSE_NOT_FOUND: 'expense_not_found',
|
||||||
@@ -153,17 +154,10 @@ export default class ExpensesService implements IExpensesService {
|
|||||||
tenantId,
|
tenantId,
|
||||||
expensesAccounts,
|
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[] = [];
|
const invalidExpenseAccounts: number[] = [];
|
||||||
|
|
||||||
expensesAccounts.forEach((expenseAccount) => {
|
expensesAccounts.forEach((expenseAccount) => {
|
||||||
if (expensesTypesIds.indexOf(expenseAccount.accountTypeId) === -1) {
|
if (expenseAccount.isRootType(ACCOUNT_ROOT_TYPE.EXPENSE)) {
|
||||||
invalidExpenseAccounts.push(expenseAccount.id);
|
invalidExpenseAccounts.push(expenseAccount.id);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -187,16 +181,7 @@ export default class ExpensesService implements IExpensesService {
|
|||||||
paymentAccount,
|
paymentAccount,
|
||||||
});
|
});
|
||||||
|
|
||||||
const { accountTypeRepository } = this.tenancy.repositories(tenantId);
|
if (paymentAccount.isParentType(ACCOUNT_PARENT_TYPE.CURRENT_ASSET)) {
|
||||||
|
|
||||||
// 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) {
|
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
'[expenses] the given payment account has invalid type',
|
'[expenses] the given payment account has invalid type',
|
||||||
{ tenantId, paymentAccount }
|
{ tenantId, paymentAccount }
|
||||||
@@ -270,7 +255,6 @@ export default class ExpensesService implements IExpensesService {
|
|||||||
tenantId,
|
tenantId,
|
||||||
expenseId,
|
expenseId,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Retrieve the given expense by id.
|
// Retrieve the given expense by id.
|
||||||
const expense = await expenseRepository.findOneById(expenseId);
|
const expense = await expenseRepository.findOneById(expenseId);
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
||||||
import TenancyService from 'services/Tenancy/TenancyService';
|
import TenancyService from 'services/Tenancy/TenancyService';
|
||||||
import events from 'subscribers/events';
|
import events from 'subscribers/events';
|
||||||
|
import { ACCOUNT_ROOT_TYPE, ACCOUNT_TYPE } from 'data/AccountTypes';
|
||||||
|
|
||||||
const ERRORS = {
|
const ERRORS = {
|
||||||
ITEM_CATEGORIES_NOT_FOUND: 'ITEM_CATEGORIES_NOT_FOUND',
|
ITEM_CATEGORIES_NOT_FOUND: 'ITEM_CATEGORIES_NOT_FOUND',
|
||||||
@@ -172,16 +173,12 @@ export default class ItemCategoriesService implements IItemCategoriesService {
|
|||||||
* @return {Promise<void>}
|
* @return {Promise<void>}
|
||||||
*/
|
*/
|
||||||
private async validateSellAccount(tenantId: number, sellAccountId: number) {
|
private async validateSellAccount(tenantId: number, sellAccountId: number) {
|
||||||
const {
|
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||||
accountRepository,
|
|
||||||
accountTypeRepository,
|
|
||||||
} = this.tenancy.repositories(tenantId);
|
|
||||||
|
|
||||||
this.logger.info('[items] validate sell account existance.', {
|
this.logger.info('[items] validate sell account existance.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
sellAccountId,
|
sellAccountId,
|
||||||
});
|
});
|
||||||
const incomeType = await accountTypeRepository.getByKey('income');
|
|
||||||
const foundAccount = await accountRepository.findOneById(sellAccountId);
|
const foundAccount = await accountRepository.findOneById(sellAccountId);
|
||||||
|
|
||||||
if (!foundAccount) {
|
if (!foundAccount) {
|
||||||
@@ -190,7 +187,7 @@ export default class ItemCategoriesService implements IItemCategoriesService {
|
|||||||
sellAccountId,
|
sellAccountId,
|
||||||
});
|
});
|
||||||
throw new ServiceError(ERRORS.SELL_ACCOUNT_NOT_FOUND);
|
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.', {
|
this.logger.info('[items] sell account not income type.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
sellAccountId,
|
sellAccountId,
|
||||||
@@ -206,16 +203,12 @@ export default class ItemCategoriesService implements IItemCategoriesService {
|
|||||||
* @return {Promise<void>}
|
* @return {Promise<void>}
|
||||||
*/
|
*/
|
||||||
private async validateCostAccount(tenantId: number, costAccountId: number) {
|
private async validateCostAccount(tenantId: number, costAccountId: number) {
|
||||||
const {
|
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||||
accountRepository,
|
|
||||||
accountTypeRepository,
|
|
||||||
} = this.tenancy.repositories(tenantId);
|
|
||||||
|
|
||||||
this.logger.info('[items] validate cost account existance.', {
|
this.logger.info('[items] validate cost account existance.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
costAccountId,
|
costAccountId,
|
||||||
});
|
});
|
||||||
const COGSType = await accountTypeRepository.getByKey('cost_of_goods_sold');
|
|
||||||
const foundAccount = await accountRepository.findOneById(costAccountId);
|
const foundAccount = await accountRepository.findOneById(costAccountId);
|
||||||
|
|
||||||
if (!foundAccount) {
|
if (!foundAccount) {
|
||||||
@@ -224,7 +217,7 @@ export default class ItemCategoriesService implements IItemCategoriesService {
|
|||||||
costAccountId,
|
costAccountId,
|
||||||
});
|
});
|
||||||
throw new ServiceError(ERRORS.COST_ACCOUNT_NOT_FOUMD);
|
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.', {
|
this.logger.info('[items] validate cost account not COGS type.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
costAccountId,
|
costAccountId,
|
||||||
@@ -243,16 +236,12 @@ export default class ItemCategoriesService implements IItemCategoriesService {
|
|||||||
tenantId: number,
|
tenantId: number,
|
||||||
inventoryAccountId: number
|
inventoryAccountId: number
|
||||||
) {
|
) {
|
||||||
const {
|
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||||
accountTypeRepository,
|
|
||||||
accountRepository,
|
|
||||||
} = this.tenancy.repositories(tenantId);
|
|
||||||
|
|
||||||
this.logger.info('[items] validate inventory account existance.', {
|
this.logger.info('[items] validate inventory account existance.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
inventoryAccountId,
|
inventoryAccountId,
|
||||||
});
|
});
|
||||||
const otherAsset = await accountTypeRepository.getByKey('other_asset');
|
|
||||||
const foundAccount = await accountRepository.findOneById(
|
const foundAccount = await accountRepository.findOneById(
|
||||||
inventoryAccountId
|
inventoryAccountId
|
||||||
);
|
);
|
||||||
@@ -263,7 +252,7 @@ export default class ItemCategoriesService implements IItemCategoriesService {
|
|||||||
inventoryAccountId,
|
inventoryAccountId,
|
||||||
});
|
});
|
||||||
throw new ServiceError(ERRORS.INVENTORY_ACCOUNT_NOT_FOUND);
|
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.', {
|
this.logger.info('[items] inventory account not inventory type.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
inventoryAccountId,
|
inventoryAccountId,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { defaultTo, difference, omit, pick } from 'lodash';
|
import { defaultTo, difference } from 'lodash';
|
||||||
import { Service, Inject } from 'typedi';
|
import { Service, Inject } from 'typedi';
|
||||||
import {
|
import {
|
||||||
EventDispatcher,
|
EventDispatcher,
|
||||||
@@ -10,7 +10,7 @@ import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
|||||||
import TenancyService from 'services/Tenancy/TenancyService';
|
import TenancyService from 'services/Tenancy/TenancyService';
|
||||||
import { ServiceError } from 'exceptions';
|
import { ServiceError } from 'exceptions';
|
||||||
import InventoryService from 'services/Inventory/Inventory';
|
import InventoryService from 'services/Inventory/Inventory';
|
||||||
import InventoryAdjustmentEntry from 'models/InventoryAdjustmentEntry';
|
import { ACCOUNT_ROOT_TYPE, ACCOUNT_TYPE } from 'data/AccountTypes'
|
||||||
|
|
||||||
const ERRORS = {
|
const ERRORS = {
|
||||||
NOT_FOUND: 'NOT_FOUND',
|
NOT_FOUND: 'NOT_FOUND',
|
||||||
@@ -29,7 +29,8 @@ const ERRORS = {
|
|||||||
ITEMS_HAVE_ASSOCIATED_TRANSACTIONS: 'ITEMS_HAVE_ASSOCIATED_TRANSACTIONS',
|
ITEMS_HAVE_ASSOCIATED_TRANSACTIONS: 'ITEMS_HAVE_ASSOCIATED_TRANSACTIONS',
|
||||||
ITEM_HAS_ASSOCIATED_TRANSACTINS: 'ITEM_HAS_ASSOCIATED_TRANSACTINS',
|
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()
|
@Service()
|
||||||
@@ -114,16 +115,12 @@ export default class ItemsService implements IItemsService {
|
|||||||
tenantId: number,
|
tenantId: number,
|
||||||
costAccountId: number
|
costAccountId: number
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const {
|
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||||
accountRepository,
|
|
||||||
accountTypeRepository,
|
|
||||||
} = this.tenancy.repositories(tenantId);
|
|
||||||
|
|
||||||
this.logger.info('[items] validate cost account existance.', {
|
this.logger.info('[items] validate cost account existance.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
costAccountId,
|
costAccountId,
|
||||||
});
|
});
|
||||||
const COGSType = await accountTypeRepository.getByKey('cost_of_goods_sold');
|
|
||||||
const foundAccount = await accountRepository.findOneById(costAccountId);
|
const foundAccount = await accountRepository.findOneById(costAccountId);
|
||||||
|
|
||||||
if (!foundAccount) {
|
if (!foundAccount) {
|
||||||
@@ -132,7 +129,9 @@ export default class ItemsService implements IItemsService {
|
|||||||
costAccountId,
|
costAccountId,
|
||||||
});
|
});
|
||||||
throw new ServiceError(ERRORS.COST_ACCOUNT_NOT_FOUMD);
|
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.', {
|
this.logger.info('[items] validate cost account not COGS type.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
costAccountId,
|
costAccountId,
|
||||||
@@ -152,14 +151,13 @@ export default class ItemsService implements IItemsService {
|
|||||||
) {
|
) {
|
||||||
const {
|
const {
|
||||||
accountRepository,
|
accountRepository,
|
||||||
accountTypeRepository,
|
|
||||||
} = this.tenancy.repositories(tenantId);
|
} = this.tenancy.repositories(tenantId);
|
||||||
|
|
||||||
this.logger.info('[items] validate sell account existance.', {
|
this.logger.info('[items] validate sell account existance.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
sellAccountId,
|
sellAccountId,
|
||||||
});
|
});
|
||||||
const incomeType = await accountTypeRepository.getByKey('income');
|
|
||||||
const foundAccount = await accountRepository.findOneById(sellAccountId);
|
const foundAccount = await accountRepository.findOneById(sellAccountId);
|
||||||
|
|
||||||
if (!foundAccount) {
|
if (!foundAccount) {
|
||||||
@@ -168,7 +166,8 @@ export default class ItemsService implements IItemsService {
|
|||||||
sellAccountId,
|
sellAccountId,
|
||||||
});
|
});
|
||||||
throw new ServiceError(ERRORS.SELL_ACCOUNT_NOT_FOUND);
|
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.', {
|
this.logger.info('[items] sell account not income type.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
sellAccountId,
|
sellAccountId,
|
||||||
@@ -187,7 +186,6 @@ export default class ItemsService implements IItemsService {
|
|||||||
inventoryAccountId: number
|
inventoryAccountId: number
|
||||||
) {
|
) {
|
||||||
const {
|
const {
|
||||||
accountTypeRepository,
|
|
||||||
accountRepository,
|
accountRepository,
|
||||||
} = this.tenancy.repositories(tenantId);
|
} = this.tenancy.repositories(tenantId);
|
||||||
|
|
||||||
@@ -195,7 +193,6 @@ export default class ItemsService implements IItemsService {
|
|||||||
tenantId,
|
tenantId,
|
||||||
inventoryAccountId,
|
inventoryAccountId,
|
||||||
});
|
});
|
||||||
const otherAsset = await accountTypeRepository.getByKey('other_asset');
|
|
||||||
const foundAccount = await accountRepository.findOneById(
|
const foundAccount = await accountRepository.findOneById(
|
||||||
inventoryAccountId
|
inventoryAccountId
|
||||||
);
|
);
|
||||||
@@ -206,7 +203,8 @@ export default class ItemsService implements IItemsService {
|
|||||||
inventoryAccountId,
|
inventoryAccountId,
|
||||||
});
|
});
|
||||||
throw new ServiceError(ERRORS.INVENTORY_ACCOUNT_NOT_FOUND);
|
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.', {
|
this.logger.info('[items] inventory account not inventory type.', {
|
||||||
tenantId,
|
tenantId,
|
||||||
inventoryAccountId,
|
inventoryAccountId,
|
||||||
@@ -361,11 +359,11 @@ export default class ItemsService implements IItemsService {
|
|||||||
await this.getItemOrThrowError(tenantId, itemId);
|
await this.getItemOrThrowError(tenantId, itemId);
|
||||||
|
|
||||||
// Validate the item has no associated inventory transactions.
|
// 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.
|
// Validate the item has no associated invoices or bills.
|
||||||
await this.validateHasNoInvoicesOrBills(tenantId, itemId);
|
await this.validateHasNoInvoicesOrBills(tenantId, itemId);
|
||||||
|
|
||||||
await Item.query().findById(itemId).delete();
|
await Item.query().findById(itemId).delete();
|
||||||
|
|
||||||
this.logger.info('[items] deleted successfully.', { tenantId, itemId });
|
this.logger.info('[items] deleted successfully.', { tenantId, itemId });
|
||||||
@@ -479,7 +477,7 @@ export default class ItemsService implements IItemsService {
|
|||||||
await this.validateItemsIdsExists(tenantId, itemsIds);
|
await this.validateItemsIdsExists(tenantId, itemsIds);
|
||||||
|
|
||||||
// Validate the item has no associated inventory transactions.
|
// 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.
|
// Validate the items have no associated invoices or bills.
|
||||||
await this.validateHasNoInvoicesOrBills(tenantId, itemsIds);
|
await this.validateHasNoInvoicesOrBills(tenantId, itemsIds);
|
||||||
@@ -554,14 +552,15 @@ export default class ItemsService implements IItemsService {
|
|||||||
*/
|
*/
|
||||||
private async validateHasNoInventoryAdjustments(
|
private async validateHasNoInventoryAdjustments(
|
||||||
tenantId: number,
|
tenantId: number,
|
||||||
itemId: number[] | number,
|
itemId: number[] | number
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const { InventoryAdjustmentEntry } = this.tenancy.models(tenantId);
|
const { InventoryAdjustmentEntry } = this.tenancy.models(tenantId);
|
||||||
const itemsIds = Array.isArray(itemId) ? itemId : [itemId];
|
const itemsIds = Array.isArray(itemId) ? itemId : [itemId];
|
||||||
|
|
||||||
const inventoryAdjEntries = await InventoryAdjustmentEntry.query()
|
const inventoryAdjEntries = await InventoryAdjustmentEntry.query().whereIn(
|
||||||
.whereIn('item_id', itemsIds);
|
'item_id',
|
||||||
|
itemsIds
|
||||||
|
);
|
||||||
if (inventoryAdjEntries.length > 0) {
|
if (inventoryAdjEntries.length > 0) {
|
||||||
throw new ServiceError(ERRORS.ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT);
|
throw new ServiceError(ERRORS.ITEM_HAS_ASSOCIATED_INVENTORY_ADJUSTMENT);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,13 +25,15 @@ import TenancyService from 'services/Tenancy/TenancyService';
|
|||||||
import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
||||||
import { entriesAmountDiff, formatDateFields } from 'utils';
|
import { entriesAmountDiff, formatDateFields } from 'utils';
|
||||||
import { ServiceError } from 'exceptions';
|
import { ServiceError } from 'exceptions';
|
||||||
|
import { ACCOUNT_PARENT_TYPE } from 'data/AccountTypes';
|
||||||
|
|
||||||
const ERRORS = {
|
const ERRORS = {
|
||||||
BILL_VENDOR_NOT_FOUND: 'VENDOR_NOT_FOUND',
|
BILL_VENDOR_NOT_FOUND: 'VENDOR_NOT_FOUND',
|
||||||
PAYMENT_MADE_NOT_FOUND: 'PAYMENT_MADE_NOT_FOUND',
|
PAYMENT_MADE_NOT_FOUND: 'PAYMENT_MADE_NOT_FOUND',
|
||||||
BILL_PAYMENT_NUMBER_NOT_UNQIUE: 'BILL_PAYMENT_NUMBER_NOT_UNQIUE',
|
BILL_PAYMENT_NUMBER_NOT_UNQIUE: 'BILL_PAYMENT_NUMBER_NOT_UNQIUE',
|
||||||
PAYMENT_ACCOUNT_NOT_FOUND: 'PAYMENT_ACCOUNT_NOT_FOUND',
|
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_ENTRIES_IDS_NOT_FOUND: 'BILL_ENTRIES_IDS_NOT_FOUND',
|
||||||
BILL_PAYMENT_ENTRIES_NOT_FOUND: 'BILL_PAYMENT_ENTRIES_NOT_FOUND',
|
BILL_PAYMENT_ENTRIES_NOT_FOUND: 'BILL_PAYMENT_ENTRIES_NOT_FOUND',
|
||||||
INVALID_BILL_PAYMENT_AMOUNT: 'INVALID_BILL_PAYMENT_AMOUNT',
|
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.
|
* Validate whether the bill payment vendor exists on the storage.
|
||||||
* @param {Request} req
|
* @param {Request} req
|
||||||
* @param {Response} res
|
* @param {Response} res
|
||||||
* @param {Function} next
|
* @param {Function} next
|
||||||
*/
|
*/
|
||||||
private async getVendorOrThrowError(tenantId: number, vendorId: number) {
|
private async getVendorOrThrowError(tenantId: number, vendorId: number) {
|
||||||
const { vendorRepository } = this.tenancy.repositories(tenantId);
|
const { vendorRepository } = this.tenancy.repositories(tenantId);
|
||||||
@@ -74,18 +76,21 @@ export default class BillPaymentsService {
|
|||||||
const vendor = await vendorRepository.findOneById(vendorId);
|
const vendor = await vendorRepository.findOneById(vendorId);
|
||||||
|
|
||||||
if (!vendor) {
|
if (!vendor) {
|
||||||
throw new ServiceError(ERRORS.BILL_VENDOR_NOT_FOUND)
|
throw new ServiceError(ERRORS.BILL_VENDOR_NOT_FOUND);
|
||||||
}
|
}
|
||||||
return vendor;
|
return vendor;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates the bill payment existance.
|
* Validates the bill payment existance.
|
||||||
* @param {Request} req
|
* @param {Request} req
|
||||||
* @param {Response} res
|
* @param {Response} res
|
||||||
* @param {Function} next
|
* @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 } = this.tenancy.models(tenantid);
|
||||||
const billPayment = await BillPayment.query()
|
const billPayment = await BillPayment.query()
|
||||||
.withGraphFetched('entries')
|
.withGraphFetched('entries')
|
||||||
@@ -98,23 +103,25 @@ export default class BillPaymentsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates the payment account.
|
* Validates the payment account.
|
||||||
* @param {number} tenantId -
|
* @param {number} tenantId -
|
||||||
* @param {number} paymentAccountId
|
* @param {number} paymentAccountId
|
||||||
* @return {Promise<IAccountType>}
|
* @return {Promise<IAccountType>}
|
||||||
*/
|
*/
|
||||||
private async getPaymentAccountOrThrowError(tenantId: number, paymentAccountId: number) {
|
private async getPaymentAccountOrThrowError(
|
||||||
const { accountTypeRepository, accountRepository } = this.tenancy.repositories(tenantId);
|
tenantId: number,
|
||||||
|
paymentAccountId: number
|
||||||
|
) {
|
||||||
|
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||||
|
|
||||||
const currentAssetTypes = await accountTypeRepository.getByChildType('current_asset');
|
const paymentAccount = await accountRepository.findOneById(
|
||||||
const paymentAccount = await accountRepository.findOneById(paymentAccountId);
|
paymentAccountId
|
||||||
|
);
|
||||||
const currentAssetTypesIds = currentAssetTypes.map(type => type.id);
|
|
||||||
|
|
||||||
if (!paymentAccount) {
|
if (!paymentAccount) {
|
||||||
throw new ServiceError(ERRORS.PAYMENT_ACCOUNT_NOT_FOUND);
|
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);
|
throw new ServiceError(ERRORS.PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE);
|
||||||
}
|
}
|
||||||
return paymentAccount;
|
return paymentAccount;
|
||||||
@@ -122,35 +129,44 @@ export default class BillPaymentsService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates the payment number uniqness.
|
* Validates the payment number uniqness.
|
||||||
* @param {number} tenantId -
|
* @param {number} tenantId -
|
||||||
* @param {string} paymentMadeNumber -
|
* @param {string} paymentMadeNumber -
|
||||||
* @return {Promise<IBillPayment>}
|
* @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 { BillPayment } = this.tenancy.models(tenantId);
|
||||||
|
|
||||||
const foundBillPayment = await BillPayment.query()
|
const foundBillPayment = await BillPayment.query().onBuild(
|
||||||
.onBuild((builder: any) => {
|
(builder: any) => {
|
||||||
builder.findOne('payment_number', paymentMadeNumber);
|
builder.findOne('payment_number', paymentMadeNumber);
|
||||||
|
|
||||||
if (notPaymentMadeId) {
|
if (notPaymentMadeId) {
|
||||||
builder.whereNot('id', notPaymentMadeId);
|
builder.whereNot('id', notPaymentMadeId);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
);
|
||||||
|
|
||||||
if (foundBillPayment) {
|
if (foundBillPayment) {
|
||||||
throw new ServiceError(ERRORS.BILL_PAYMENT_NUMBER_NOT_UNQIUE)
|
throw new ServiceError(ERRORS.BILL_PAYMENT_NUMBER_NOT_UNQIUE);
|
||||||
}
|
}
|
||||||
return foundBillPayment;
|
return foundBillPayment;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate whether the entries bills ids exist on the storage.
|
* Validate whether the entries bills ids exist on the storage.
|
||||||
* @param {Request} req
|
* @param {Request} req
|
||||||
* @param {Response} res
|
* @param {Response} res
|
||||||
* @param {NextFunction} next
|
* @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 { Bill } = this.tenancy.models(tenantId);
|
||||||
const entriesBillsIds = billPaymentEntries.map((e: any) => e.billId);
|
const entriesBillsIds = billPaymentEntries.map((e: any) => e.billId);
|
||||||
|
|
||||||
@@ -162,15 +178,15 @@ export default class BillPaymentsService {
|
|||||||
const notFoundBillsIds = difference(entriesBillsIds, storedBillsIds);
|
const notFoundBillsIds = difference(entriesBillsIds, storedBillsIds);
|
||||||
|
|
||||||
if (notFoundBillsIds.length > 0) {
|
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.
|
* Validate wether the payment amount bigger than the payable amount.
|
||||||
* @param {Request} req
|
* @param {Request} req
|
||||||
* @param {Response} res
|
* @param {Response} res
|
||||||
* @param {NextFunction} next
|
* @param {NextFunction} next
|
||||||
* @return {void}
|
* @return {void}
|
||||||
*/
|
*/
|
||||||
private async validateBillsDueAmount(
|
private async validateBillsDueAmount(
|
||||||
@@ -179,22 +195,28 @@ export default class BillPaymentsService {
|
|||||||
oldPaymentEntries: IBillPaymentEntry[] = []
|
oldPaymentEntries: IBillPaymentEntry[] = []
|
||||||
) {
|
) {
|
||||||
const { Bill } = this.tenancy.models(tenantId);
|
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 storedBills = await Bill.query().whereIn('id', billsIds);
|
||||||
const storedBillsMap = new Map(
|
const storedBillsMap = new Map(
|
||||||
storedBills
|
storedBills.map((bill) => {
|
||||||
.map((bill) => {
|
const oldEntries = oldPaymentEntries.filter(
|
||||||
const oldEntries = oldPaymentEntries.filter(entry => entry.billId === bill.id);
|
(entry) => entry.billId === bill.id
|
||||||
const oldPaymentAmount = sumBy(oldEntries, 'paymentAmount') || 0;
|
);
|
||||||
|
const oldPaymentAmount = sumBy(oldEntries, 'paymentAmount') || 0;
|
||||||
|
|
||||||
return [bill.id, { ...bill, dueAmount: bill.dueAmount + oldPaymentAmount }];
|
return [
|
||||||
}),
|
bill.id,
|
||||||
|
{ ...bill, dueAmount: bill.dueAmount + oldPaymentAmount },
|
||||||
|
];
|
||||||
|
})
|
||||||
);
|
);
|
||||||
interface invalidPaymentAmountError{
|
interface invalidPaymentAmountError {
|
||||||
index: number,
|
index: number;
|
||||||
due_amount: number
|
due_amount: number;
|
||||||
};
|
}
|
||||||
const hasWrongPaymentAmount: invalidPaymentAmountError[] = [];
|
const hasWrongPaymentAmount: invalidPaymentAmountError[] = [];
|
||||||
|
|
||||||
billPaymentEntries.forEach((entry: IBillPaymentEntryDTO, index: number) => {
|
billPaymentEntries.forEach((entry: IBillPaymentEntryDTO, index: number) => {
|
||||||
@@ -203,7 +225,7 @@ export default class BillPaymentsService {
|
|||||||
|
|
||||||
if (dueAmount < entry.paymentAmount) {
|
if (dueAmount < entry.paymentAmount) {
|
||||||
hasWrongPaymentAmount.push({ index, due_amount: dueAmount });
|
hasWrongPaymentAmount.push({ index, due_amount: dueAmount });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
if (hasWrongPaymentAmount.length > 0) {
|
if (hasWrongPaymentAmount.length > 0) {
|
||||||
throw new ServiceError(ERRORS.INVALID_BILL_PAYMENT_AMOUNT);
|
throw new ServiceError(ERRORS.INVALID_BILL_PAYMENT_AMOUNT);
|
||||||
@@ -211,9 +233,9 @@ export default class BillPaymentsService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate the payment receive entries IDs existance.
|
* Validate the payment receive entries IDs existance.
|
||||||
* @param {Request} req
|
* @param {Request} req
|
||||||
* @param {Response} res
|
* @param {Response} res
|
||||||
* @return {Response}
|
* @return {Response}
|
||||||
*/
|
*/
|
||||||
private async validateEntriesIdsExistance(
|
private async validateEntriesIdsExistance(
|
||||||
@@ -227,9 +249,12 @@ export default class BillPaymentsService {
|
|||||||
.filter((entry: any) => entry.id)
|
.filter((entry: any) => entry.id)
|
||||||
.map((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);
|
const notFoundEntriesIds = difference(entriesIds, storedEntriesIds);
|
||||||
|
|
||||||
if (notFoundEntriesIds.length > 0) {
|
if (notFoundEntriesIds.length > 0) {
|
||||||
@@ -256,7 +281,10 @@ export default class BillPaymentsService {
|
|||||||
tenantId: number,
|
tenantId: number,
|
||||||
billPaymentDTO: IBillPaymentDTO
|
billPaymentDTO: IBillPaymentDTO
|
||||||
): Promise<IBillPayment> {
|
): 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 { BillPayment } = this.tenancy.models(tenantId);
|
||||||
|
|
||||||
const billPaymentObj = {
|
const billPaymentObj = {
|
||||||
@@ -268,28 +296,39 @@ export default class BillPaymentsService {
|
|||||||
await this.getVendorOrThrowError(tenantId, billPaymentObj.vendorId);
|
await this.getVendorOrThrowError(tenantId, billPaymentObj.vendorId);
|
||||||
|
|
||||||
// Validate the payment account existance and type.
|
// Validate the payment account existance and type.
|
||||||
await this.getPaymentAccountOrThrowError(tenantId, billPaymentObj.paymentAccountId);
|
await this.getPaymentAccountOrThrowError(
|
||||||
|
tenantId,
|
||||||
|
billPaymentObj.paymentAccountId
|
||||||
|
);
|
||||||
|
|
||||||
// Validate the payment number uniquiness.
|
// Validate the payment number uniquiness.
|
||||||
if (billPaymentObj.paymentNumber) {
|
if (billPaymentObj.paymentNumber) {
|
||||||
await this.validatePaymentNumber(tenantId, billPaymentObj.paymentNumber);
|
await this.validatePaymentNumber(tenantId, billPaymentObj.paymentNumber);
|
||||||
}
|
}
|
||||||
// Validates the bills existance and associated to the given vendor.
|
// 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.
|
// Validates the bills due payment amount.
|
||||||
await this.validateBillsDueAmount(tenantId, billPaymentObj.entries);
|
await this.validateBillsDueAmount(tenantId, billPaymentObj.entries);
|
||||||
|
|
||||||
const billPayment = await BillPayment.query()
|
const billPayment = await BillPayment.query().insertGraphAndFetch({
|
||||||
.insertGraphAndFetch({
|
...omit(billPaymentObj, ['entries']),
|
||||||
...omit(billPaymentObj, ['entries']),
|
entries: billPaymentDTO.entries,
|
||||||
entries: billPaymentDTO.entries,
|
});
|
||||||
});
|
|
||||||
|
|
||||||
await this.eventDispatcher.dispatch(events.billPayment.onCreated, {
|
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;
|
return billPayment;
|
||||||
}
|
}
|
||||||
@@ -315,11 +354,14 @@ export default class BillPaymentsService {
|
|||||||
public async editBillPayment(
|
public async editBillPayment(
|
||||||
tenantId: number,
|
tenantId: number,
|
||||||
billPaymentId: number,
|
billPaymentId: number,
|
||||||
billPaymentDTO,
|
billPaymentDTO
|
||||||
): Promise<IBillPayment> {
|
): Promise<IBillPayment> {
|
||||||
const { BillPayment } = this.tenancy.models(tenantId);
|
const { BillPayment } = this.tenancy.models(tenantId);
|
||||||
|
|
||||||
const oldBillPayment = await this.getPaymentMadeOrThrowError(tenantId, billPaymentId);
|
const oldBillPayment = await this.getPaymentMadeOrThrowError(
|
||||||
|
tenantId,
|
||||||
|
billPaymentId
|
||||||
|
);
|
||||||
|
|
||||||
const billPaymentObj = {
|
const billPaymentObj = {
|
||||||
amount: sumBy(billPaymentDTO.entries, 'paymentAmount'),
|
amount: sumBy(billPaymentDTO.entries, 'paymentAmount'),
|
||||||
@@ -330,31 +372,57 @@ export default class BillPaymentsService {
|
|||||||
await this.getVendorOrThrowError(tenantId, billPaymentObj.vendorId);
|
await this.getVendorOrThrowError(tenantId, billPaymentObj.vendorId);
|
||||||
|
|
||||||
// Validate the payment account existance and type.
|
// 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.
|
// 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.
|
// 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.
|
// 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.
|
// Validate the payment number uniquiness.
|
||||||
if (billPaymentObj.paymentNumber) {
|
if (billPaymentObj.paymentNumber) {
|
||||||
await this.validatePaymentNumber(tenantId, billPaymentObj.paymentNumber, billPaymentId);
|
await this.validatePaymentNumber(
|
||||||
|
tenantId,
|
||||||
|
billPaymentObj.paymentNumber,
|
||||||
|
billPaymentId
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const billPayment = await BillPayment.query()
|
const billPayment = await BillPayment.query().upsertGraphAndFetch({
|
||||||
.upsertGraphAndFetch({
|
id: billPaymentId,
|
||||||
id: billPaymentId,
|
...omit(billPaymentObj, ['entries']),
|
||||||
...omit(billPaymentObj, ['entries']),
|
entries: billPaymentDTO.entries,
|
||||||
entries: billPaymentDTO.entries,
|
});
|
||||||
});
|
await this.eventDispatcher.dispatch(events.billPayment.onEdited, {
|
||||||
await this.eventDispatcher.dispatch(events.billPayment.onEdited, {
|
tenantId,
|
||||||
tenantId, billPaymentId, billPayment, oldBillPayment,
|
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;
|
return billPayment;
|
||||||
}
|
}
|
||||||
@@ -367,15 +435,30 @@ export default class BillPaymentsService {
|
|||||||
*/
|
*/
|
||||||
public async deleteBillPayment(tenantId: number, billPaymentId: number) {
|
public async deleteBillPayment(tenantId: number, billPaymentId: number) {
|
||||||
const { BillPayment, BillPaymentEntry } = this.tenancy.models(tenantId);
|
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 BillPayment.query().where('id', billPaymentId).delete();
|
||||||
|
|
||||||
await this.eventDispatcher.dispatch(events.billPayment.onDeleted, { tenantId, billPaymentId, oldBillPayment });
|
await this.eventDispatcher.dispatch(events.billPayment.onDeleted, {
|
||||||
this.logger.info('[bill_payment] deleted successfully.', { tenantId, billPaymentId });
|
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) {
|
public async getPaymentBills(tenantId: number, billPaymentId: number) {
|
||||||
const { Bill } = this.tenancy.models(tenantId);
|
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 paymentBillsIds = billPayment.entries.map((entry) => entry.id);
|
||||||
|
|
||||||
const bills = await Bill.query().whereIn('id', paymentBillsIds);
|
const bills = await Bill.query().whereIn('id', paymentBillsIds);
|
||||||
@@ -396,11 +482,14 @@ export default class BillPaymentsService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Records bill payment receive journal transactions.
|
* Records bill payment receive journal transactions.
|
||||||
* @param {number} tenantId -
|
* @param {number} tenantId -
|
||||||
* @param {BillPayment} billPayment
|
* @param {BillPayment} billPayment
|
||||||
* @param {Integer} billPaymentId
|
* @param {Integer} billPaymentId
|
||||||
*/
|
*/
|
||||||
public async recordJournalEntries(tenantId: number, billPayment: IBillPayment) {
|
public async recordJournalEntries(
|
||||||
|
tenantId: number,
|
||||||
|
billPayment: IBillPayment
|
||||||
|
) {
|
||||||
const { AccountTransaction } = this.tenancy.models(tenantId);
|
const { AccountTransaction } = this.tenancy.models(tenantId);
|
||||||
const { accountRepository } = this.tenancy.repositories(tenantId);
|
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||||
|
|
||||||
@@ -408,7 +497,9 @@ export default class BillPaymentsService {
|
|||||||
const formattedDate = moment(billPayment.paymentDate).format('YYYY-MM-DD');
|
const formattedDate = moment(billPayment.paymentDate).format('YYYY-MM-DD');
|
||||||
|
|
||||||
// Retrieve AP account from the storage.
|
// 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 journal = new JournalPoster(tenantId);
|
||||||
const commonJournal = {
|
const commonJournal = {
|
||||||
@@ -451,44 +542,50 @@ export default class BillPaymentsService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Reverts bill payment journal entries.
|
* Reverts bill payment journal entries.
|
||||||
* @param {number} tenantId
|
* @param {number} tenantId
|
||||||
* @param {number} billPaymentId
|
* @param {number} billPaymentId
|
||||||
* @return {Promise<void>}
|
* @return {Promise<void>}
|
||||||
*/
|
*/
|
||||||
public async revertJournalEntries(tenantId: number, billPaymentId: number) {
|
public async revertJournalEntries(tenantId: number, billPaymentId: number) {
|
||||||
const journal = new JournalPoster(tenantId);
|
const journal = new JournalPoster(tenantId);
|
||||||
const journalCommands = new JournalCommands(journal);
|
const journalCommands = new JournalCommands(journal);
|
||||||
|
|
||||||
await journalCommands.revertJournalEntries(billPaymentId, 'BillPayment');
|
await journalCommands.revertJournalEntries(billPaymentId, 'BillPayment');
|
||||||
|
|
||||||
return Promise.all([
|
return Promise.all([journal.saveBalance(), journal.deleteEntries()]);
|
||||||
journal.saveBalance(),
|
|
||||||
journal.deleteEntries(),
|
|
||||||
]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieve bill payment paginted and filterable list.
|
* Retrieve bill payment paginted and filterable list.
|
||||||
* @param {number} tenantId
|
* @param {number} tenantId
|
||||||
* @param {IBillPaymentsFilter} billPaymentsFilter
|
* @param {IBillPaymentsFilter} billPaymentsFilter
|
||||||
*/
|
*/
|
||||||
public async listBillPayments(
|
public async listBillPayments(
|
||||||
tenantId: number,
|
tenantId: number,
|
||||||
billPaymentsFilter: IBillPaymentsFilter,
|
billPaymentsFilter: IBillPaymentsFilter
|
||||||
): Promise<{ billPayments: IBillPayment, pagination: IPaginationMeta, filterMeta: IFilterMeta }> {
|
): Promise<{
|
||||||
|
billPayments: IBillPayment;
|
||||||
|
pagination: IPaginationMeta;
|
||||||
|
filterMeta: IFilterMeta;
|
||||||
|
}> {
|
||||||
const { BillPayment } = this.tenancy.models(tenantId);
|
const { BillPayment } = this.tenancy.models(tenantId);
|
||||||
const dynamicFilter = await this.dynamicListService.dynamicList(tenantId, BillPayment, billPaymentsFilter);
|
const dynamicFilter = await this.dynamicListService.dynamicList(
|
||||||
|
tenantId,
|
||||||
this.logger.info('[bill_payment] try to get bill payments list.', { tenantId });
|
BillPayment,
|
||||||
const { results, pagination } = await BillPayment.query().onBuild((builder) => {
|
billPaymentsFilter
|
||||||
builder.withGraphFetched('vendor');
|
|
||||||
builder.withGraphFetched('paymentAccount');
|
|
||||||
dynamicFilter.buildQuery()(builder);
|
|
||||||
}).pagination(
|
|
||||||
billPaymentsFilter.page - 1,
|
|
||||||
billPaymentsFilter.pageSize,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
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 {
|
return {
|
||||||
billPayments: results,
|
billPayments: results,
|
||||||
pagination,
|
pagination,
|
||||||
@@ -501,10 +598,13 @@ export default class BillPaymentsService {
|
|||||||
* @param {number} billPaymentId - The bill payment id.
|
* @param {number} billPaymentId - The bill payment id.
|
||||||
* @return {object}
|
* @return {object}
|
||||||
*/
|
*/
|
||||||
public async getBillPayment(tenantId: number, billPaymentId: number): Promise<{
|
public async getBillPayment(
|
||||||
billPayment: IBillPayment,
|
tenantId: number,
|
||||||
payableBills: IBill[],
|
billPaymentId: number
|
||||||
paymentMadeBills: IBill[],
|
): Promise<{
|
||||||
|
billPayment: IBillPayment;
|
||||||
|
payableBills: IBill[];
|
||||||
|
paymentMadeBills: IBill[];
|
||||||
}> {
|
}> {
|
||||||
const { BillPayment, Bill } = this.tenancy.models(tenantId);
|
const { BillPayment, Bill } = this.tenancy.models(tenantId);
|
||||||
const billPayment = await BillPayment.query()
|
const billPayment = await BillPayment.query()
|
||||||
@@ -527,8 +627,8 @@ export default class BillPaymentsService {
|
|||||||
|
|
||||||
// Retrieve all payment made assocaited bills.
|
// Retrieve all payment made assocaited bills.
|
||||||
const paymentMadeBills = billPayment.entries.map((entry) => ({
|
const paymentMadeBills = billPayment.entries.map((entry) => ({
|
||||||
...(entry.bill),
|
...entry.bill,
|
||||||
dueAmount: (entry.bill.dueAmount + entry.paymentAmount),
|
dueAmount: entry.bill.dueAmount + entry.paymentAmount,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -552,7 +652,7 @@ export default class BillPaymentsService {
|
|||||||
public async saveChangeBillsPaymentAmount(
|
public async saveChangeBillsPaymentAmount(
|
||||||
tenantId: number,
|
tenantId: number,
|
||||||
paymentMadeEntries: IBillPaymentEntryDTO[],
|
paymentMadeEntries: IBillPaymentEntryDTO[],
|
||||||
oldPaymentMadeEntries?: IBillPaymentEntryDTO[],
|
oldPaymentMadeEntries?: IBillPaymentEntryDTO[]
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const { Bill } = this.tenancy.models(tenantId);
|
const { Bill } = this.tenancy.models(tenantId);
|
||||||
const opers: Promise<void>[] = [];
|
const opers: Promise<void>[] = [];
|
||||||
@@ -561,17 +661,21 @@ export default class BillPaymentsService {
|
|||||||
paymentMadeEntries,
|
paymentMadeEntries,
|
||||||
oldPaymentMadeEntries,
|
oldPaymentMadeEntries,
|
||||||
'paymentAmount',
|
'paymentAmount',
|
||||||
'billId',
|
'billId'
|
||||||
);
|
);
|
||||||
diffEntries.forEach((diffEntry: { paymentAmount: number, billId: number }) => {
|
diffEntries.forEach(
|
||||||
if (diffEntry.paymentAmount === 0) { return; }
|
(diffEntry: { paymentAmount: number; billId: number }) => {
|
||||||
|
if (diffEntry.paymentAmount === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const oper = Bill.changePaymentAmount(
|
const oper = Bill.changePaymentAmount(
|
||||||
diffEntry.billId,
|
diffEntry.billId,
|
||||||
diffEntry.paymentAmount,
|
diffEntry.paymentAmount
|
||||||
);
|
);
|
||||||
opers.push(oper);
|
opers.push(oper);
|
||||||
});
|
}
|
||||||
|
);
|
||||||
await Promise.all(opers);
|
await Promise.all(opers);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,13 +31,13 @@ import { ServiceError } from 'exceptions';
|
|||||||
import CustomersService from 'services/Contacts/CustomersService';
|
import CustomersService from 'services/Contacts/CustomersService';
|
||||||
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
|
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
|
||||||
import JournalCommands from 'services/Accounting/JournalCommands';
|
import JournalCommands from 'services/Accounting/JournalCommands';
|
||||||
|
import { ACCOUNT_PARENT_TYPE } from 'data/AccountTypes';
|
||||||
|
|
||||||
const ERRORS = {
|
const ERRORS = {
|
||||||
PAYMENT_RECEIVE_NO_EXISTS: 'PAYMENT_RECEIVE_NO_EXISTS',
|
PAYMENT_RECEIVE_NO_EXISTS: 'PAYMENT_RECEIVE_NO_EXISTS',
|
||||||
PAYMENT_RECEIVE_NOT_EXISTS: 'PAYMENT_RECEIVE_NOT_EXISTS',
|
PAYMENT_RECEIVE_NOT_EXISTS: 'PAYMENT_RECEIVE_NOT_EXISTS',
|
||||||
DEPOSIT_ACCOUNT_NOT_FOUND: 'DEPOSIT_ACCOUNT_NOT_FOUND',
|
DEPOSIT_ACCOUNT_NOT_FOUND: 'DEPOSIT_ACCOUNT_NOT_FOUND',
|
||||||
DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE:
|
DEPOSIT_ACCOUNT_INVALID_TYPE: 'DEPOSIT_ACCOUNT_INVALID_TYPE',
|
||||||
'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE',
|
|
||||||
INVALID_PAYMENT_AMOUNT: 'INVALID_PAYMENT_AMOUNT',
|
INVALID_PAYMENT_AMOUNT: 'INVALID_PAYMENT_AMOUNT',
|
||||||
INVOICES_IDS_NOT_FOUND: 'INVOICES_IDS_NOT_FOUND',
|
INVOICES_IDS_NOT_FOUND: 'INVOICES_IDS_NOT_FOUND',
|
||||||
ENTRIES_IDS_NOT_EXISTS: 'ENTRIES_IDS_NOT_EXISTS',
|
ENTRIES_IDS_NOT_EXISTS: 'ENTRIES_IDS_NOT_EXISTS',
|
||||||
@@ -99,8 +99,8 @@ export default class PaymentReceiveService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates the payment receive existance.
|
* Validates the payment receive existance.
|
||||||
* @param {number} tenantId -
|
* @param {number} tenantId - Tenant id.
|
||||||
* @param {number} paymentReceiveId -
|
* @param {number} paymentReceiveId - Payment receive id.
|
||||||
*/
|
*/
|
||||||
async getPaymentReceiveOrThrowError(
|
async getPaymentReceiveOrThrowError(
|
||||||
tenantId: number,
|
tenantId: number,
|
||||||
@@ -119,32 +119,25 @@ export default class PaymentReceiveService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Validate the deposit account id existance.
|
* Validate the deposit account id existance.
|
||||||
* @param {number} tenantId -
|
* @param {number} tenantId - Tenant id.
|
||||||
* @param {number} depositAccountId -
|
* @param {number} depositAccountId - Deposit account id.
|
||||||
|
* @return {Promise<IAccount>}
|
||||||
*/
|
*/
|
||||||
async getDepositAccountOrThrowError(
|
async getDepositAccountOrThrowError(
|
||||||
tenantId: number,
|
tenantId: number,
|
||||||
depositAccountId: number
|
depositAccountId: number
|
||||||
): Promise<IAccount> {
|
): Promise<IAccount> {
|
||||||
const {
|
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||||
accountTypeRepository,
|
|
||||||
accountRepository,
|
|
||||||
} = this.tenancy.repositories(tenantId);
|
|
||||||
|
|
||||||
const currentAssetTypes = await accountTypeRepository.getByChildType(
|
|
||||||
'current_asset'
|
|
||||||
);
|
|
||||||
const depositAccount = await accountRepository.findOneById(
|
const depositAccount = await accountRepository.findOneById(
|
||||||
depositAccountId
|
depositAccountId
|
||||||
);
|
);
|
||||||
|
|
||||||
const currentAssetTypesIds = currentAssetTypes.map((type) => type.id);
|
|
||||||
|
|
||||||
if (!depositAccount) {
|
if (!depositAccount) {
|
||||||
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND);
|
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND);
|
||||||
}
|
}
|
||||||
if (currentAssetTypesIds.indexOf(depositAccount.accountTypeId) === -1) {
|
// Detarmines whether the account is cash equivalents.
|
||||||
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE);
|
if (!depositAccount.isParentType(ACCOUNT_PARENT_TYPE.CURRENT_ASSET)) {
|
||||||
|
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_INVALID_TYPE);
|
||||||
}
|
}
|
||||||
return depositAccount;
|
return depositAccount;
|
||||||
}
|
}
|
||||||
@@ -316,7 +309,6 @@ export default class PaymentReceiveService {
|
|||||||
...formatDateFields(omit(paymentReceiveDTO, ['entries']), [
|
...formatDateFields(omit(paymentReceiveDTO, ['entries']), [
|
||||||
'paymentDate',
|
'paymentDate',
|
||||||
]),
|
]),
|
||||||
|
|
||||||
entries: paymentReceiveDTO.entries.map((entry) => ({
|
entries: paymentReceiveDTO.entries.map((entry) => ({
|
||||||
...omit(entry, ['id']),
|
...omit(entry, ['id']),
|
||||||
})),
|
})),
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import { ServiceError } from 'exceptions';
|
|||||||
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
|
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
|
||||||
import { ItemEntry } from 'models';
|
import { ItemEntry } from 'models';
|
||||||
import InventoryService from 'services/Inventory/Inventory';
|
import InventoryService from 'services/Inventory/Inventory';
|
||||||
|
import { ACCOUNT_PARENT_TYPE } from 'data/AccountTypes';
|
||||||
|
|
||||||
const ERRORS = {
|
const ERRORS = {
|
||||||
SALE_RECEIPT_NOT_FOUND: 'SALE_RECEIPT_NOT_FOUND',
|
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.
|
* Validate whether sale receipt deposit account exists on the storage.
|
||||||
* @param {number} tenantId -
|
* @param {number} tenantId - Tenant id.
|
||||||
* @param {number} accountId -
|
* @param {number} accountId - Account id.
|
||||||
*/
|
*/
|
||||||
async validateReceiptDepositAccountExistance(
|
async validateReceiptDepositAccountExistance(
|
||||||
tenantId: number,
|
tenantId: number,
|
||||||
accountId: number
|
accountId: number
|
||||||
) {
|
) {
|
||||||
const {
|
const { accountRepository } = this.tenancy.repositories(tenantId);
|
||||||
accountRepository,
|
|
||||||
accountTypeRepository,
|
|
||||||
} = this.tenancy.repositories(tenantId);
|
|
||||||
const depositAccount = await accountRepository.findOneById(accountId);
|
const depositAccount = await accountRepository.findOneById(accountId);
|
||||||
|
|
||||||
if (!depositAccount) {
|
if (!depositAccount) {
|
||||||
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND);
|
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND);
|
||||||
}
|
}
|
||||||
const depositAccountType = await accountTypeRepository.findOneById(
|
if (!depositAccount.isParentType(ACCOUNT_PARENT_TYPE.CURRENT_ASSET)) {
|
||||||
depositAccount.accountTypeId
|
|
||||||
);
|
|
||||||
|
|
||||||
if (
|
|
||||||
!depositAccountType ||
|
|
||||||
depositAccountType.childRoot === 'current_asset'
|
|
||||||
) {
|
|
||||||
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET);
|
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user