feat: closed sale receipt status.

feat: approve and reject sale estimate.
feat: initial receipts, invoices, estimates and bills views.
This commit is contained in:
a.bouhuolia
2020-12-14 20:25:38 +02:00
parent 461e18f2a4
commit 27483495cb
23 changed files with 801 additions and 86 deletions

View File

@@ -39,7 +39,7 @@ export default class DynamicListService implements IDynamicListService {
*/
private async getCustomViewOrThrowError(tenantId: number, viewId: number, model: IModel) {
const { viewRepository } = this.tenancy.repositories(tenantId);
const view = await viewRepository.findOneById(viewId);
const view = await viewRepository.findOneById(viewId, 'roles');
if (!view || view.resourceModel !== model.name) {
throw new ServiceError(ERRORS.VIEW_NOT_FOUND);

View File

@@ -25,7 +25,6 @@ import TenancyService from 'services/Tenancy/TenancyService';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { entriesAmountDiff, formatDateFields } from 'utils';
import { ServiceError } from 'exceptions';
import { Bill } from 'models';
const ERRORS = {
BILL_VENDOR_NOT_FOUND: 'VENDOR_NOT_FOUND',

View File

@@ -21,7 +21,10 @@ const ERRORS = {
SALE_ESTIMATE_NUMBER_EXISTANCE: 'SALE_ESTIMATE_NUMBER_EXISTANCE',
ITEMS_IDS_NOT_EXISTS: 'ITEMS_IDS_NOT_EXISTS',
SALE_ESTIMATE_ALREADY_DELIVERED: 'SALE_ESTIMATE_ALREADY_DELIVERED',
SALE_ESTIMATE_CONVERTED_TO_INVOICE: 'SALE_ESTIMATE_CONVERTED_TO_INVOICE'
SALE_ESTIMATE_CONVERTED_TO_INVOICE: 'SALE_ESTIMATE_CONVERTED_TO_INVOICE',
SALE_ESTIMATE_ALREADY_REJECTED: 'SALE_ESTIMATE_ALREADY_REJECTED',
SALE_ESTIMATE_ALREADY_APPROVED: 'SALE_ESTIMATE_ALREADY_APPROVED',
SALE_ESTIMATE_NOT_DELIVERED: 'SALE_ESTIMATE_NOT_DELIVERED'
};
/**
* Sale estimate service.
@@ -352,4 +355,61 @@ export default class SaleEstimateService {
deliveredAt: moment().toMySqlDateTime()
});
}
/**
* Mark the sale estimate as approved from the customer.
* @param {number} tenantId
* @param {number} saleEstimateId
*/
public async approveSaleEstimate(
tenantId: number,
saleEstimateId: number,
): Promise<void> {
const { SaleEstimate } = this.tenancy.models(tenantId);
// Retrieve details of the given sale estimate id.
const saleEstimate = await this.getSaleEstimateOrThrowError(tenantId, saleEstimateId);
// Throws error in case the sale estimate still not delivered to customer.
if (!saleEstimate.isDelivered) {
throw new ServiceError(ERRORS.SALE_ESTIMATE_NOT_DELIVERED);
}
// Throws error in case the sale estimate already approved.
if (saleEstimate.isApproved) {
throw new ServiceError(ERRORS.SALE_ESTIMATE_ALREADY_APPROVED);
}
await SaleEstimate.query().where('id', saleEstimateId).patch({
approvedAt: moment().toMySqlDateTime(),
rejectedAt: null,
});
}
/**
* Mark the sale estimate as rejected from the customer.
* @param {number} tenantId
* @param {number} saleEstimateId
*/
public async rejectSaleEstimate(
tenantId: number,
saleEstimateId: number,
): Promise<void> {
const { SaleEstimate } = this.tenancy.models(tenantId);
// Retrieve details of the given sale estimate id.
const saleEstimate = await this.getSaleEstimateOrThrowError(tenantId, saleEstimateId);
// Throws error in case the sale estimate still not delivered to customer.
if (!saleEstimate.isDelivered) {
throw new ServiceError(ERRORS.SALE_ESTIMATE_NOT_DELIVERED);
}
// Throws error in case the sale estimate already rejected.
if (saleEstimate.isRejected) {
throw new ServiceError(ERRORS.SALE_ESTIMATE_ALREADY_REJECTED);
}
// Mark the sale estimate as reject on the storage.
await SaleEstimate.query().where('id', saleEstimateId).patch({
rejectedAt: moment().toMySqlDateTime(),
approvedAt: null,
});
}
}

View File

@@ -449,12 +449,19 @@ export default class SaleInvoicesService extends SalesInvoicesCost {
public async salesInvoicesList(
tenantId: number,
salesInvoicesFilter: ISalesInvoicesFilter
): Promise<{ salesInvoices: ISaleInvoice[], pagination: IPaginationMeta, filterMeta: IFilterMeta }> {
): Promise<{
salesInvoices: ISaleInvoice[],
pagination: IPaginationMeta,
filterMeta: IFilterMeta
}> {
const { SaleInvoice } = this.tenancy.models(tenantId);
const dynamicFilter = await this.dynamicListService.dynamicList(tenantId, SaleInvoice, salesInvoicesFilter);
this.logger.info('[sale_invoice] try to get sales invoices list.', { tenantId, salesInvoicesFilter });
const { results, pagination } = await SaleInvoice.query().onBuild((builder) => {
const {
results,
pagination,
} = await SaleInvoice.query().onBuild((builder) => {
builder.withGraphFetched('entries');
builder.withGraphFetched('customer');
dynamicFilter.buildQuery()(builder);

View File

@@ -1,11 +1,12 @@
import { omit, sumBy } from 'lodash';
import { Service, Inject } from 'typedi';
import moment from 'moment';
import {
EventDispatcher,
EventDispatcherInterface,
} from 'decorators/eventDispatcher';
import events from 'subscribers/events';
import { ISaleReceipt } from 'interfaces';
import { ISaleReceipt, ISaleReceiptDTO } from 'interfaces';
import JournalPosterService from 'services/Sales/JournalPosterService';
import TenancyService from 'services/Tenancy/TenancyService';
import { formatDateFields } from 'utils';
@@ -13,13 +14,15 @@ import { IFilterMeta, IPaginationMeta } from 'interfaces';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { ServiceError } from 'exceptions';
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
import { ItemEntry } from 'models';
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_NUMBER_NOT_UNIQUE: 'SALE_RECEIPT_NUMBER_NOT_UNIQUE',
SALE_RECEIPT_IS_ALREADY_CLOSED: 'SALE_RECEIPT_IS_ALREADY_CLOSED'
};
@Service()
export default class SalesReceiptService {
@@ -102,6 +105,35 @@ export default class SalesReceiptService {
}
}
/**
* Transform DTO object to model object.
* @param {ISaleReceiptDTO} saleReceiptDTO -
* @param {ISaleReceipt} oldSaleReceipt -
* @returns {ISaleReceipt}
*/
transformObjectDTOToModel(
saleReceiptDTO: ISaleReceiptDTO,
oldSaleReceipt?: ISaleReceipt
): ISaleReceipt {
const amount = sumBy(saleReceiptDTO.entries, e => ItemEntry.calcAmount(e));
return {
amount,
...formatDateFields(
omit(saleReceiptDTO, ['closed', 'entries']),
['receiptDate']
),
// Avoid rewrite the deliver date in edit mode when already published.
...(saleReceiptDTO.closed && (!oldSaleReceipt?.closedAt)) && ({
closedAt: moment().toMySqlDateTime(),
}),
entries: saleReceiptDTO.entries.map((entry) => ({
reference_type: 'SaleReceipt',
...omit(entry, ['id', 'amount']),
})),
};
}
/**
* Creates a new sale receipt with associated entries.
* @async
@@ -109,13 +141,10 @@ export default class SalesReceiptService {
* @return {Object}
*/
public async createSaleReceipt(tenantId: number, saleReceiptDTO: any): Promise<ISaleReceipt> {
const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId);
const { SaleReceipt } = this.tenancy.models(tenantId);
const amount = sumBy(saleReceiptDTO.entries, e => ItemEntry.calcAmount(e));
const saleReceiptObj = {
amount,
...formatDateFields(saleReceiptDTO, ['receiptDate'])
};
// Transform sale receipt DTO to model.
const saleReceiptObj = this.transformObjectDTOToModel(saleReceiptDTO);
// Validate receipt deposit account existance and type.
await this.validateReceiptDepositAccountExistance(tenantId, saleReceiptDTO.depositAccountId);
@@ -131,15 +160,8 @@ export default class SalesReceiptService {
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({
...omit(saleReceiptObj, ['entries']),
const saleReceipt = await SaleReceipt.query().insertGraphAndFetch({ ...saleReceiptObj });
entries: saleReceiptObj.entries.map((entry) => ({
reference_type: 'SaleReceipt',
...omit(entry, ['id', 'amount']),
}))
});
await this.eventDispatcher.dispatch(events.saleReceipt.onCreated, { tenantId, saleReceipt });
this.logger.info('[sale_receipt] sale receipt inserted successfully.', { tenantId });
@@ -156,13 +178,11 @@ export default class SalesReceiptService {
public async editSaleReceipt(tenantId: number, saleReceiptId: number, saleReceiptDTO: any) {
const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId);
const amount = sumBy(saleReceiptDTO.entries, e => ItemEntry.calcAmount(e));
const saleReceiptObj = {
amount,
...formatDateFields(saleReceiptDTO, ['receiptDate'])
};
// Retrieve sale receipt or throw not found service error.
const oldSaleReceipt = await this.getSaleReceiptOrThrowError(tenantId, saleReceiptId);
// Transform sale receipt DTO to model.
const saleReceiptObj = this.transformObjectDTOToModel(saleReceiptDTO, oldSaleReceipt);
// Validate receipt deposit account existance and type.
await this.validateReceiptDepositAccountExistance(tenantId, saleReceiptDTO.depositAccountId);
@@ -178,16 +198,10 @@ export default class SalesReceiptService {
await this.validateReceiptNumberUnique(tenantId, saleReceiptDTO.receiptNumber, saleReceiptId);
}
const saleReceipt = await SaleReceipt.query()
.upsertGraphAndFetch({
id: saleReceiptId,
...omit(saleReceiptObj, ['entries']),
entries: saleReceiptObj.entries.map((entry) => ({
reference_type: 'SaleReceipt',
...omit(entry, ['amount']),
}))
});
const saleReceipt = await SaleReceipt.query().upsertGraphAndFetch({
id: saleReceiptId,
...saleReceiptObj
});
this.logger.info('[sale_receipt] edited successfully.', { tenantId, saleReceiptId });
await this.eventDispatcher.dispatch(events.saleReceipt.onEdited, {
@@ -265,4 +279,29 @@ export default class SalesReceiptService {
filterMeta: dynamicFilter.getResponseMeta(),
};
}
/**
* Mark the given sale receipt as closed.
* @param {number} tenantId
* @param {number} saleReceiptId
* @return {Promise<void>}
*/
async closeSaleReceipt(
tenantId: number,
saleReceiptId: number
): Promise<void> {
const { SaleReceipt } = this.tenancy.models(tenantId);
// Retrieve sale receipt or throw not found service error.
const oldSaleReceipt = await this.getSaleReceiptOrThrowError(tenantId, saleReceiptId);
// Throw service error if the sale receipt already closed.
if (oldSaleReceipt.isClosed) {
throw new ServiceError(ERRORS.SALE_RECEIPT_IS_ALREADY_CLOSED);
}
// Mark the sale receipt as closed on the storage.
await SaleReceipt.query().findById(saleReceiptId).patch({
closedAt: moment().toMySqlDateTime(),
});
}
}

View File

@@ -41,14 +41,17 @@ export default class ViewsService implements IViewsService {
* @param {number} tenantId -
* @param {string} resourceModel -
*/
public async listResourceViews(tenantId: number, resourceModelName: string): Promise<IView[]> {
public async listResourceViews(
tenantId: number,
resourceModelName: string,
): Promise<IView[]> {
this.logger.info('[views] trying to retrieve resource views.', { tenantId, resourceModelName });
// Validate the resource model name is valid.
const resourceModel = this.getResourceModelOrThrowError(tenantId, resourceModelName);
const { viewRepository } = this.tenancy.repositories(tenantId);
return viewRepository.allByResource(resourceModel.name, ['columns', 'roles']);
return viewRepository.allByResource(resourceModel.name, 'roles');
}
/**
@@ -56,7 +59,10 @@ export default class ViewsService implements IViewsService {
* @param {string} resourceName
* @param {IViewRoleDTO[]} viewRoles
*/
private validateResourceRolesFieldsExistance(ResourceModel: IModel, viewRoles: IViewRoleDTO[]) {
private validateResourceRolesFieldsExistance(
ResourceModel: IModel,
viewRoles: IViewRoleDTO[],
) {
const resourceFieldsKeys = getModelFieldsKeys(ResourceModel);
const fieldsKeys = viewRoles.map(viewRole => viewRole.fieldKey);
@@ -73,7 +79,10 @@ export default class ViewsService implements IViewsService {
* @param {string} resourceName
* @param {IViewColumnDTO[]} viewColumns
*/
private validateResourceColumnsExistance(ResourceModel: IModel, viewColumns: IViewColumnDTO[]) {
private validateResourceColumnsExistance(
ResourceModel: IModel,
viewColumns: IViewColumnDTO[],
) {
const resourceFieldsKeys = getModelFieldsKeys(ResourceModel);
const fieldsKeys = viewColumns.map((viewColumn: IViewColumnDTO) => viewColumn.fieldKey);
@@ -118,7 +127,10 @@ export default class ViewsService implements IViewsService {
* @param {number} tenantId
* @param {number} resourceModel
*/
private getResourceModelOrThrowError(tenantId: number, resourceModel: string): IModel {
private getResourceModelOrThrowError(
tenantId: number,
resourceModel: string,
): IModel {
return this.resourceService.getResourceModel(tenantId, resourceModel);
}
@@ -137,7 +149,9 @@ export default class ViewsService implements IViewsService {
): void {
const { View } = this.tenancy.models(tenantId);
this.logger.info('[views] trying to validate view name uniqiness.', { tenantId, resourceModel, viewName });
this.logger.info('[views] trying to validate view name uniqiness.', {
tenantId, resourceModel, viewName,
});
const foundViews = await View.query()
.where('resource_model', resourceModel)
.where('name', viewName)