fix: refactoring invoice calc cost service.

This commit is contained in:
a.bouhuolia
2021-01-05 17:06:42 +02:00
parent d25360d279
commit df85c9b295
41 changed files with 1684 additions and 1085 deletions

View File

@@ -6,7 +6,9 @@ import {
EventDispatcherInterface,
} from 'decorators/eventDispatcher';
import events from 'subscribers/events';
import { ISaleReceipt, ISaleReceiptDTO } from 'interfaces';
import JournalPoster from 'services/Accounting/JournalPoster';
import JournalCommands from 'services/Accounting/JournalCommands';
import { ISaleReceipt, ISaleReceiptDTO, IItemEntry, IItem } from 'interfaces';
import JournalPosterService from 'services/Sales/JournalPosterService';
import TenancyService from 'services/Tenancy/TenancyService';
import { formatDateFields } from 'utils';
@@ -15,15 +17,16 @@ import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { ServiceError } from 'exceptions';
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
import { ItemEntry } from 'models';
import InventoryService from 'services/Inventory/Inventory';
const ERRORS = {
SALE_RECEIPT_NOT_FOUND: 'SALE_RECEIPT_NOT_FOUND',
DEPOSIT_ACCOUNT_NOT_FOUND: 'DEPOSIT_ACCOUNT_NOT_FOUND',
DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET: 'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET',
SALE_RECEIPT_NUMBER_NOT_UNIQUE: 'SALE_RECEIPT_NUMBER_NOT_UNIQUE',
SALE_RECEIPT_IS_ALREADY_CLOSED: 'SALE_RECEIPT_IS_ALREADY_CLOSED'
SALE_RECEIPT_IS_ALREADY_CLOSED: 'SALE_RECEIPT_IS_ALREADY_CLOSED',
};
@Service()
export default class SalesReceiptService {
@Inject()
@@ -38,6 +41,9 @@ export default class SalesReceiptService {
@Inject()
itemsEntriesService: ItemsEntriesService;
@Inject()
inventoryService: InventoryService;
@EventDispatcher()
eventDispatcher: EventDispatcherInterface;
@@ -46,37 +52,56 @@ export default class SalesReceiptService {
/**
* Validate whether sale receipt exists on the storage.
* @param {number} tenantId -
* @param {number} saleReceiptId -
* @param {number} tenantId -
* @param {number} saleReceiptId -
*/
async getSaleReceiptOrThrowError(tenantId: number, saleReceiptId: number) {
const { SaleReceipt } = this.tenancy.models(tenantId);
this.logger.info('[sale_receipt] trying to validate existance.', { tenantId, saleReceiptId });
const foundSaleReceipt = await SaleReceipt.query().findById(saleReceiptId);
this.logger.info('[sale_receipt] trying to validate existance.', {
tenantId,
saleReceiptId,
});
const foundSaleReceipt = await SaleReceipt.query()
.findById(saleReceiptId)
.withGraphFetched('entries');
if (!foundSaleReceipt) {
this.logger.info('[sale_receipt] not found on the storage.', { tenantId, saleReceiptId });
this.logger.info('[sale_receipt] not found on the storage.', {
tenantId,
saleReceiptId,
});
throw new ServiceError(ERRORS.SALE_RECEIPT_NOT_FOUND);
}
return foundSaleReceipt;
}
/**
* Validate whether sale receipt deposit account exists on the storage.
* @param {number} tenantId -
* @param {number} tenantId -
* @param {number} accountId -
*/
async validateReceiptDepositAccountExistance(tenantId: number, accountId: number) {
const { accountRepository, accountTypeRepository } = this.tenancy.repositories(tenantId);
async validateReceiptDepositAccountExistance(
tenantId: number,
accountId: number
) {
const {
accountRepository,
accountTypeRepository,
} = this.tenancy.repositories(tenantId);
const depositAccount = await accountRepository.findOneById(accountId);
if (!depositAccount) {
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND);
}
const depositAccountType = await accountTypeRepository.findOneById(depositAccount.accountTypeId);
const depositAccountType = await accountTypeRepository.findOneById(
depositAccount.accountTypeId
);
if (!depositAccountType || depositAccountType.childRoot === 'current_asset') {
if (
!depositAccountType ||
depositAccountType.childRoot === 'current_asset'
) {
throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET);
}
}
@@ -87,10 +112,17 @@ export default class SalesReceiptService {
* @param {string} receiptNumber -
* @param {number} notReceiptId -
*/
async validateReceiptNumberUnique(tenantId: number, receiptNumber: string, notReceiptId?: number) {
async validateReceiptNumberUnique(
tenantId: number,
receiptNumber: string,
notReceiptId?: number
) {
const { SaleReceipt } = this.tenancy.models(tenantId);
this.logger.info('[sale_receipt] validate receipt number uniquiness.', { tenantId, receiptNumber });
this.logger.info('[sale_receipt] validate receipt number uniquiness.', {
tenantId,
receiptNumber,
});
const saleReceipt = await SaleReceipt.query()
.findOne('receipt_number', receiptNumber)
.onBuild((builder) => {
@@ -98,9 +130,11 @@ export default class SalesReceiptService {
builder.whereNot('id', notReceiptId);
}
});
if (saleReceipt) {
this.logger.info('[sale_receipt] sale receipt number not unique.', { tenantId });
this.logger.info('[sale_receipt] sale receipt number not unique.', {
tenantId,
});
throw new ServiceError(ERRORS.SALE_RECEIPT_NUMBER_NOT_UNIQUE);
}
}
@@ -115,18 +149,20 @@ export default class SalesReceiptService {
saleReceiptDTO: ISaleReceiptDTO,
oldSaleReceipt?: ISaleReceipt
): ISaleReceipt {
const amount = sumBy(saleReceiptDTO.entries, e => ItemEntry.calcAmount(e));
const amount = sumBy(saleReceiptDTO.entries, (e) =>
ItemEntry.calcAmount(e)
);
return {
amount,
...formatDateFields(
omit(saleReceiptDTO, ['closed', 'entries']),
['receiptDate']
),
...formatDateFields(omit(saleReceiptDTO, ['closed', 'entries']), [
'receiptDate',
]),
// Avoid rewrite the deliver date in edit mode when already published.
...(saleReceiptDTO.closed && (!oldSaleReceipt?.closedAt)) && ({
closedAt: moment().toMySqlDateTime(),
}),
...(saleReceiptDTO.closed &&
!oldSaleReceipt?.closedAt && {
closedAt: moment().toMySqlDateTime(),
}),
entries: saleReceiptDTO.entries.map((entry) => ({
reference_type: 'SaleReceipt',
...omit(entry, ['id', 'amount']),
@@ -140,31 +176,56 @@ export default class SalesReceiptService {
* @param {ISaleReceipt} saleReceipt
* @return {Object}
*/
public async createSaleReceipt(tenantId: number, saleReceiptDTO: any): Promise<ISaleReceipt> {
public async createSaleReceipt(
tenantId: number,
saleReceiptDTO: any
): Promise<ISaleReceipt> {
const { SaleReceipt } = this.tenancy.models(tenantId);
// Transform sale receipt DTO to model.
const saleReceiptObj = this.transformObjectDTOToModel(saleReceiptDTO);
// Validate receipt deposit account existance and type.
await this.validateReceiptDepositAccountExistance(tenantId, saleReceiptDTO.depositAccountId);
await this.validateReceiptDepositAccountExistance(
tenantId,
saleReceiptDTO.depositAccountId
);
// Validate items IDs existance on the storage.
await this.itemsEntriesService.validateItemsIdsExistance(tenantId, saleReceiptDTO.entries);
await this.itemsEntriesService.validateItemsIdsExistance(
tenantId,
saleReceiptDTO.entries
);
// Validate the sellable items.
await this.itemsEntriesService.validateNonSellableEntriesItems(tenantId, saleReceiptDTO.entries);
await this.itemsEntriesService.validateNonSellableEntriesItems(
tenantId,
saleReceiptDTO.entries
);
// Validate sale receipt number uniuqiness.
if (saleReceiptDTO.receiptNumber) {
await this.validateReceiptNumberUnique(tenantId, saleReceiptDTO.receiptNumber);
await this.validateReceiptNumberUnique(
tenantId,
saleReceiptDTO.receiptNumber
);
}
this.logger.info('[sale_receipt] trying to insert sale receipt graph.', { tenantId, saleReceiptDTO });
const saleReceipt = await SaleReceipt.query().insertGraphAndFetch({ ...saleReceiptObj });
await this.eventDispatcher.dispatch(events.saleReceipt.onCreated, { tenantId, saleReceipt });
this.logger.info('[sale_receipt] sale receipt inserted successfully.', { tenantId });
this.logger.info('[sale_receipt] trying to insert sale receipt graph.', {
tenantId,
saleReceiptDTO,
});
const saleReceipt = await SaleReceipt.query().upsertGraph({
...saleReceiptObj,
});
// Triggers `onSaleReceiptCreated` event.
await this.eventDispatcher.dispatch(events.saleReceipt.onCreated, {
tenantId,
saleReceipt,
saleReceiptId: saleReceipt.id,
});
this.logger.info('[sale_receipt] sale receipt inserted successfully.', {
tenantId,
});
return saleReceipt;
}
@@ -175,37 +236,61 @@ export default class SalesReceiptService {
* @param {ISaleReceipt} saleReceipt
* @return {void}
*/
public async editSaleReceipt(tenantId: number, saleReceiptId: number, saleReceiptDTO: any) {
const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId);
public async editSaleReceipt(
tenantId: number,
saleReceiptId: number,
saleReceiptDTO: any
) {
const { SaleReceipt } = this.tenancy.models(tenantId);
// Retrieve sale receipt or throw not found service error.
const oldSaleReceipt = await this.getSaleReceiptOrThrowError(tenantId, saleReceiptId);
const oldSaleReceipt = await this.getSaleReceiptOrThrowError(
tenantId,
saleReceiptId
);
// Transform sale receipt DTO to model.
const saleReceiptObj = this.transformObjectDTOToModel(saleReceiptDTO, oldSaleReceipt);
const saleReceiptObj = this.transformObjectDTOToModel(
saleReceiptDTO,
oldSaleReceipt
);
// Validate receipt deposit account existance and type.
await this.validateReceiptDepositAccountExistance(tenantId, saleReceiptDTO.depositAccountId);
await this.validateReceiptDepositAccountExistance(
tenantId,
saleReceiptDTO.depositAccountId
);
// Validate items IDs existance on the storage.
await this.itemsEntriesService.validateItemsIdsExistance(tenantId, saleReceiptDTO.entries);
await this.itemsEntriesService.validateItemsIdsExistance(
tenantId,
saleReceiptDTO.entries
);
// Validate the sellable items.
await this.itemsEntriesService.validateNonSellableEntriesItems(tenantId, saleReceiptDTO.entries);
await this.itemsEntriesService.validateNonSellableEntriesItems(
tenantId,
saleReceiptDTO.entries
);
// Validate sale receipt number uniuqiness.
if (saleReceiptDTO.receiptNumber) {
await this.validateReceiptNumberUnique(tenantId, saleReceiptDTO.receiptNumber, saleReceiptId);
await this.validateReceiptNumberUnique(
tenantId,
saleReceiptDTO.receiptNumber,
saleReceiptId
);
}
const saleReceipt = await SaleReceipt.query().upsertGraphAndFetch({
id: saleReceiptId,
...saleReceiptObj
...saleReceiptObj,
});
this.logger.info('[sale_receipt] edited successfully.', { tenantId, saleReceiptId });
this.logger.info('[sale_receipt] edited successfully.', {
tenantId,
saleReceiptId,
});
// Triggers `onSaleReceiptEdited` event.
await this.eventDispatcher.dispatch(events.saleReceipt.onEdited, {
oldSaleReceipt, tenantId, saleReceiptId, saleReceipt,
tenantId,
oldSaleReceipt,
saleReceipt,
saleReceiptId,
});
return saleReceipt;
}
@@ -218,20 +303,31 @@ export default class SalesReceiptService {
public async deleteSaleReceipt(tenantId: number, saleReceiptId: number) {
const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId);
const oldSaleReceipt = await this.getSaleReceiptOrThrowError(
tenantId,
saleReceiptId
);
await ItemEntry.query()
.where('reference_id', saleReceiptId)
.where('reference_type', 'SaleReceipt')
.delete();
await SaleReceipt.query().where('id', saleReceiptId).delete();
this.logger.info('[sale_receipt] deleted successfully.', { tenantId, saleReceiptId });
await this.eventDispatcher.dispatch(events.saleReceipt.onDeleted);
this.logger.info('[sale_receipt] deleted successfully.', {
tenantId,
saleReceiptId,
});
await this.eventDispatcher.dispatch(events.saleReceipt.onDeleted, {
tenantId,
saleReceiptId,
oldSaleReceipt
});
}
/**
* Retrieve sale receipt with associated entries.
* @param {Integer} saleReceiptId
* @param {Integer} saleReceiptId
* @return {ISaleReceipt}
*/
async getSaleReceipt(tenantId: number, saleReceiptId: number) {
@@ -242,7 +338,7 @@ export default class SalesReceiptService {
.withGraphFetched('entries')
.withGraphFetched('customer')
.withGraphFetched('depositAccount');
if (!saleReceipt) {
throw new ServiceError(ERRORS.SALE_RECEIPT_NOT_FOUND);
}
@@ -251,28 +347,37 @@ export default class SalesReceiptService {
/**
* Retrieve sales receipts paginated and filterable list.
* @param {number} tenantId
* @param {ISaleReceiptFilter} salesReceiptsFilter
* @param {number} tenantId
* @param {ISaleReceiptFilter} salesReceiptsFilter
*/
public async salesReceiptsList(
tenantId: number,
salesReceiptsFilter: ISaleReceiptFilter,
): Promise<{ salesReceipts: ISaleReceipt[], pagination: IPaginationMeta, filterMeta: IFilterMeta }> {
salesReceiptsFilter: ISaleReceiptFilter
): Promise<{
salesReceipts: ISaleReceipt[];
pagination: IPaginationMeta;
filterMeta: IFilterMeta;
}> {
const { SaleReceipt } = this.tenancy.models(tenantId);
const dynamicFilter = await this.dynamicListService.dynamicList(tenantId, SaleReceipt, salesReceiptsFilter);
this.logger.info('[sale_receipt] try to get sales receipts list.', { tenantId });
const { results, pagination } = await SaleReceipt.query().onBuild((builder) => {
builder.withGraphFetched('depositAccount');
builder.withGraphFetched('customer');
builder.withGraphFetched('entries');
dynamicFilter.buildQuery()(builder);
}).pagination(
salesReceiptsFilter.page - 1,
salesReceiptsFilter.pageSize,
const dynamicFilter = await this.dynamicListService.dynamicList(
tenantId,
SaleReceipt,
salesReceiptsFilter
);
this.logger.info('[sale_receipt] try to get sales receipts list.', {
tenantId,
});
const { results, pagination } = await SaleReceipt.query()
.onBuild((builder) => {
builder.withGraphFetched('depositAccount');
builder.withGraphFetched('customer');
builder.withGraphFetched('entries');
dynamicFilter.buildQuery()(builder);
})
.pagination(salesReceiptsFilter.page - 1, salesReceiptsFilter.pageSize);
return {
salesReceipts: results,
pagination,
@@ -282,8 +387,8 @@ export default class SalesReceiptService {
/**
* Mark the given sale receipt as closed.
* @param {number} tenantId
* @param {number} saleReceiptId
* @param {number} tenantId
* @param {number} saleReceiptId
* @return {Promise<void>}
*/
async closeSaleReceipt(
@@ -293,7 +398,10 @@ export default class SalesReceiptService {
const { SaleReceipt } = this.tenancy.models(tenantId);
// Retrieve sale receipt or throw not found service error.
const oldSaleReceipt = await this.getSaleReceiptOrThrowError(tenantId, saleReceiptId);
const oldSaleReceipt = await this.getSaleReceiptOrThrowError(
tenantId,
saleReceiptId
);
// Throw service error if the sale receipt already closed.
if (oldSaleReceipt.isClosed) {
@@ -304,4 +412,96 @@ export default class SalesReceiptService {
closedAt: moment().toMySqlDateTime(),
});
}
/**
* Writes the sale invoice income journal entries.
* @param {number} tenantId - Tenant id.
* @param {ISaleInvoice} saleInvoice - Sale invoice id.
*/
public async writesIncomeJournalEntries(
tenantId: number,
saleInvoice: ISaleReceipt & {
entries: IItemEntry & { item: IItem };
},
override: boolean = false
): Promise<void> {
const journal = new JournalPoster(tenantId);
const journalCommands = new JournalCommands(journal);
if (override) {
await journalCommands.revertJournalEntries(saleInvoice.id, 'SaleReceipt');
}
// Records the sale invoice journal entries.
await journalCommands.saleReceiptIncomeEntries(saleInvoice);
await Promise.all([
journal.deleteEntries(),
journal.saveBalance(),
journal.saveEntries(),
]);
}
/**
* Reverting the sale receipt journal entries.
* @param {number} tenantId
* @param {number} saleReceiptId
* @return {Promise<void>}
*/
public async revertReceiptJournalEntries(
tenantId: number,
saleReceiptId: number | number[]
): Promise<void> {
return this.journalService.revertJournalTransactions(
tenantId,
saleReceiptId,
'SaleReceipt'
);
}
/**
* Records the inventory transactions from the given bill input.
* @param {Bill} bill - Bill model object.
* @param {number} billId - Bill id.
* @return {Promise<void>}
*/
public async recordInventoryTransactions(
tenantId: number,
saleReceipt: ISaleReceipt,
override?: boolean
): Promise<void> {
await this.inventoryService.recordInventoryTransactionsFromItemsEntries(
tenantId,
saleReceipt.id,
'SaleReceipt',
saleReceipt.receiptDate,
'OUT',
override,
);
// Triggers `onInventoryTransactionsCreated` event.
this.eventDispatcher.dispatch(
events.saleReceipt.onInventoryTransactionsCreated,
{
tenantId,
saleReceipt,
saleReceiptId: saleReceipt.id,
}
);
}
/**
* Reverts the inventory transactions of the given bill id.
* @param {number} tenantId - Tenant id.
* @param {number} billId - Bill id.
* @return {Promise<void>}
*/
public async revertInventoryTransactions(
tenantId: number,
receiptId: number
) {
return this.inventoryService.deleteInventoryTransactions(
tenantId,
receiptId,
'SaleReceipt'
);
}
}