This commit is contained in:
elforjani3
2020-10-24 22:20:59 +02:00
14 changed files with 517 additions and 556 deletions

View File

@@ -7,7 +7,6 @@ import ExpensesService from "services/Expenses/ExpensesService";
import { IExpenseDTO } from 'interfaces'; import { IExpenseDTO } from 'interfaces';
import { ServiceError } from "exceptions"; import { ServiceError } from "exceptions";
import DynamicListingService from 'services/DynamicListing/DynamicListService'; import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { takeWhile } from "lodash";
@Service() @Service()
export default class ExpensesController extends BaseController { export default class ExpensesController extends BaseController {
@@ -134,7 +133,6 @@ export default class ExpensesController extends BaseController {
]; ];
} }
get expensesListSchema() { get expensesListSchema() {
return [ return [
query('custom_view_id').optional().isNumeric().toInt(), query('custom_view_id').optional().isNumeric().toInt(),

View File

@@ -1,11 +1,12 @@
import { Router, Request, Response, NextFunction } from 'express'; import { Router, Request, Response, NextFunction } from 'express';
import { check, param, query, matchedData } from 'express-validator'; import { check, param, query, matchedData } from 'express-validator';
import { Inject, Service } from 'typedi'; import { Inject, Service } from 'typedi';
import { ISaleEstimate, ISaleEstimateOTD } from 'interfaces'; import { ISaleEstimateDTO } from 'interfaces';
import BaseController from 'api/controllers/BaseController' import BaseController from 'api/controllers/BaseController'
import asyncMiddleware from 'api/middleware/asyncMiddleware'; import asyncMiddleware from 'api/middleware/asyncMiddleware';
import SaleEstimateService from 'services/Sales/SalesEstimate'; import SaleEstimateService from 'services/Sales/SalesEstimate';
import ItemsService from 'services/Items/ItemsService'; import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { ServiceError } from "exceptions";
@Service() @Service()
export default class SalesEstimatesController extends BaseController { export default class SalesEstimatesController extends BaseController {
@@ -13,7 +14,7 @@ export default class SalesEstimatesController extends BaseController {
saleEstimateService: SaleEstimateService; saleEstimateService: SaleEstimateService;
@Inject() @Inject()
itemsService: ItemsService; dynamicListService: DynamicListingService;
/** /**
* Router constructor. * Router constructor.
@@ -25,10 +26,8 @@ export default class SalesEstimatesController extends BaseController {
'/', '/',
this.estimateValidationSchema, this.estimateValidationSchema,
this.validationResult, this.validationResult,
// asyncMiddleware(this.validateEstimateCustomerExistance.bind(this)), asyncMiddleware(this.newEstimate.bind(this)),
// asyncMiddleware(this.validateEstimateNumberExistance.bind(this)), this.handleServiceErrors,
// asyncMiddleware(this.validateEstimateEntriesItemsExistance.bind(this)),
asyncMiddleware(this.newEstimate.bind(this))
); );
router.post( router.post(
'/:id', [ '/:id', [
@@ -36,33 +35,31 @@ export default class SalesEstimatesController extends BaseController {
...this.estimateValidationSchema, ...this.estimateValidationSchema,
], ],
this.validationResult, this.validationResult,
// asyncMiddleware(this.validateEstimateIdExistance.bind(this)), asyncMiddleware(this.editEstimate.bind(this)),
// asyncMiddleware(this.validateEstimateCustomerExistance.bind(this)), this.handleServiceErrors,
// asyncMiddleware(this.validateEstimateNumberExistance.bind(this)),
// asyncMiddleware(this.validateEstimateEntriesItemsExistance.bind(this)),
// asyncMiddleware(this.valdiateInvoiceEntriesIdsExistance.bind(this)),
asyncMiddleware(this.editEstimate.bind(this))
); );
router.delete( router.delete(
'/:id', [ '/:id', [
this.validateSpecificEstimateSchema, this.validateSpecificEstimateSchema,
], ],
this.validationResult, this.validationResult,
// asyncMiddleware(this.validateEstimateIdExistance.bind(this)), asyncMiddleware(this.deleteEstimate.bind(this)),
asyncMiddleware(this.deleteEstimate.bind(this)) this.handleServiceErrors,
); );
router.get( router.get(
'/:id', '/:id',
this.validateSpecificEstimateSchema, this.validateSpecificEstimateSchema,
this.validationResult, this.validationResult,
// asyncMiddleware(this.validateEstimateIdExistance.bind(this)), asyncMiddleware(this.getEstimate.bind(this)),
asyncMiddleware(this.getEstimate.bind(this)) this.handleServiceErrors,
); );
router.get( router.get(
'/', '/',
this.validateEstimateListSchema, this.validateEstimateListSchema,
this.validationResult, this.validationResult,
asyncMiddleware(this.getEstimates.bind(this)) asyncMiddleware(this.getEstimates.bind(this)),
this.handleServiceErrors,
this.dynamicListService.handlerErrorsToResponse,
); );
return router; return router;
} }
@@ -120,16 +117,17 @@ export default class SalesEstimatesController extends BaseController {
* @param {Response} res - * @param {Response} res -
* @return {Response} res - * @return {Response} res -
*/ */
async newEstimate(req: Request, res: Response) { async newEstimate(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId } = req;
const estimateOTD: ISaleEstimateOTD = matchedData(req, { const estimateDTO: ISaleEstimateDTO = this.matchedBodyData(req);
locations: ['body'],
includeOptionals: true,
});
const storedEstimate = await this.saleEstimateService
.createEstimate(tenantId, estimateOTD);
return res.status(200).send({ id: storedEstimate.id }); try {
const storedEstimate = await this.saleEstimateService.createEstimate(tenantId, estimateDTO);
return res.status(200).send({ id: storedEstimate.id });
} catch (error) {
next(error);
}
} }
/** /**
@@ -137,18 +135,19 @@ export default class SalesEstimatesController extends BaseController {
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
*/ */
async editEstimate(req: Request, res: Response) { async editEstimate(req: Request, res: Response, next: NextFunction) {
const { id: estimateId } = req.params; const { id: estimateId } = req.params;
const { tenantId } = req; const { tenantId } = req;
const estimateDTO: ISaleEstimateDTO = this.matchedBodyData(req);
const estimateOTD: ISaleEstimateOTD = matchedData(req, { try {
locations: ['body'], // Update estimate with associated estimate entries.
includeOptionals: true, await this.saleEstimateService.editEstimate(tenantId, estimateId, estimateDTO);
});
// Update estimate with associated estimate entries.
await this.saleEstimateService.editEstimate(tenantId, estimateId, estimateOTD);
return res.status(200).send({ id: estimateId }); return res.status(200).send({ id: estimateId });
} catch (error) {
next(error);
}
} }
/** /**
@@ -156,26 +155,32 @@ export default class SalesEstimatesController extends BaseController {
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
*/ */
async deleteEstimate(req: Request, res: Response) { async deleteEstimate(req: Request, res: Response, next: NextFunction) {
const { id: estimateId } = req.params; const { id: estimateId } = req.params;
const { tenantId } = req; const { tenantId } = req;
await this.saleEstimateService.deleteEstimate(tenantId, estimateId); try {
await this.saleEstimateService.deleteEstimate(tenantId, estimateId);
return res.status(200).send({ id: estimateId }); return res.status(200).send({ id: estimateId });
} catch (error) {
next(error);
}
} }
/** /**
* Retrieve the given estimate with associated entries. * Retrieve the given estimate with associated entries.
*/ */
async getEstimate(req: Request, res: Response) { async getEstimate(req: Request, res: Response, next: NextFunction) {
const { id: estimateId } = req.params; const { id: estimateId } = req.params;
const { tenantId } = req; const { tenantId } = req;
const estimate = await this.saleEstimateService try {
.getEstimateWithEntries(tenantId, estimateId); const estimate = await this.saleEstimateService.getEstimate(tenantId, estimateId);
return res.status(200).send({ estimate });
return res.status(200).send({ estimate }); } catch (error) {
next(error);
}
} }
/** /**
@@ -185,11 +190,24 @@ export default class SalesEstimatesController extends BaseController {
*/ */
async getEstimates(req: Request, res: Response, next: NextFunction) { async getEstimates(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId } = req;
const estimatesFilter: ISalesEstimatesFilter = this.matchedQueryData(req); const filter = {
filterRoles: [],
sortOrder: 'asc',
columnSortBy: 'created_at',
page: 1,
pageSize: 12,
...this.matchedQueryData(req),
};
if (filter.stringifiedFilterRoles) {
filter.filterRoles = JSON.parse(filter.stringifiedFilterRoles);
}
try { try {
const { salesEstimates, pagination, filterMeta } = await this.saleEstimateService const {
.estimatesList(tenantId, estimatesFilter); salesEstimates,
pagination,
filterMeta
} = await this.saleEstimateService.estimatesList(tenantId, filter);
return res.status(200).send({ return res.status(200).send({
sales_estimates: this.transfromToResponse(salesEstimates), sales_estimates: this.transfromToResponse(salesEstimates),
@@ -200,4 +218,52 @@ export default class SalesEstimatesController extends BaseController {
next(error); next(error);
} }
} }
/**
* Handles service errors.
* @param {Error} error
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
handleServiceErrors(error: Error, req: Request, res: Response, next: NextFunction) {
if (error instanceof ServiceError) {
if (error.errorType === 'ITEMS_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 }],
});
}
if (error.errorType === 'ENTRIES_IDS_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ENTRIES.IDS.NOT.EXISTS', code: 300 }],
});
}
if (error.errorType === 'ITEMS_IDS_NOT_EXISTS') {
return res.boom.badRequest(null, {
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 200 }],
});
}
if (error.errorType === 'NOT_PURCHASE_ABLE_ITEMS') {
return res.boom.badRequest(null, {
errors: [{ type: 'NOT_PURCHASABLE_ITEMS', code: 200 }],
});
}
if (error.errorType === 'SALE_ESTIMATE_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'SALE_ESTIMATE_NOT_FOUND', code: 200 }],
});
}
if (error.errorType === 'CUSTOMER_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'CUSTOMER_NOT_FOUND', code: 200 }],
});
}
if (error.errorType === 'SALE_ESTIMATE_NUMBER_EXISTANCE') {
return res.boom.badRequest(null, {
errors: [{ type: 'ESTIMATE.NUMBER.IS.NOT.UNQIUE', code: 300 }],
});
}
}
next(error);
}
}; };

View File

@@ -2,11 +2,11 @@ import { Router, Request, Response, NextFunction } from 'express';
import { check, param, query } from 'express-validator'; import { check, param, query } from 'express-validator';
import { Inject, Service } from 'typedi'; import { Inject, Service } from 'typedi';
import asyncMiddleware from 'api/middleware/asyncMiddleware'; import asyncMiddleware from 'api/middleware/asyncMiddleware';
import AccountsService from 'services/Accounts/AccountsService';
import ItemsService from 'services/Items/ItemsService';
import SaleReceiptService from 'services/Sales/SalesReceipts'; import SaleReceiptService from 'services/Sales/SalesReceipts';
import BaseController from '../BaseController'; import BaseController from '../BaseController';
import { ISaleReceiptDTO } from 'interfaces/SaleReceipt'; import { ISaleReceiptDTO } from 'interfaces/SaleReceipt';
import { ServiceError } from 'exceptions';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
@Service() @Service()
export default class SalesReceiptsController extends BaseController{ export default class SalesReceiptsController extends BaseController{
@@ -14,10 +14,7 @@ export default class SalesReceiptsController extends BaseController{
saleReceiptService: SaleReceiptService; saleReceiptService: SaleReceiptService;
@Inject() @Inject()
accountsService: AccountsService; dynamicListService: DynamicListingService;
@Inject()
itemsService: ItemsService;
/** /**
* Router constructor. * Router constructor.
@@ -31,34 +28,30 @@ export default class SalesReceiptsController extends BaseController{
...this.salesReceiptsValidationSchema, ...this.salesReceiptsValidationSchema,
], ],
this.validationResult, this.validationResult,
asyncMiddleware(this.validateSaleReceiptExistance.bind(this)), asyncMiddleware(this.editSaleReceipt.bind(this)),
asyncMiddleware(this.validateReceiptCustomerExistance.bind(this)), this.handleServiceErrors,
asyncMiddleware(this.validateReceiptDepositAccountExistance.bind(this)),
asyncMiddleware(this.validateReceiptItemsIdsExistance.bind(this)),
asyncMiddleware(this.validateReceiptEntriesIds.bind(this)),
asyncMiddleware(this.editSaleReceipt.bind(this))
); );
router.post( router.post(
'/', '/',
this.salesReceiptsValidationSchema, this.salesReceiptsValidationSchema,
this.validationResult, this.validationResult,
asyncMiddleware(this.validateReceiptCustomerExistance.bind(this)), asyncMiddleware(this.newSaleReceipt.bind(this)),
asyncMiddleware(this.validateReceiptDepositAccountExistance.bind(this)), this.handleServiceErrors,
asyncMiddleware(this.validateReceiptItemsIdsExistance.bind(this)),
asyncMiddleware(this.newSaleReceipt.bind(this))
); );
router.delete( router.delete(
'/:id', '/:id',
this.specificReceiptValidationSchema, this.specificReceiptValidationSchema,
this.validationResult, this.validationResult,
asyncMiddleware(this.validateSaleReceiptExistance.bind(this)), asyncMiddleware(this.deleteSaleReceipt.bind(this)),
asyncMiddleware(this.deleteSaleReceipt.bind(this)) this.handleServiceErrors,
); );
router.get( router.get(
'/', '/',
this.listSalesReceiptsValidationSchema, this.listSalesReceiptsValidationSchema,
this.validationResult, this.validationResult,
asyncMiddleware(this.listingSalesReceipts.bind(this)) asyncMiddleware(this.getSalesReceipts.bind(this)),
this.handleServiceErrors,
this.dynamicListService.handlerErrorsToResponse,
); );
return router; return router;
} }
@@ -163,13 +156,13 @@ export default class SalesReceiptsController extends BaseController{
/** /**
* Edit the sale receipt details with associated entries and re-write * Edit the sale receipt details with associated entries and re-write
* journal transaction on the same date. * journal transaction on the same date.
* @param {Request} req * @param {Request} req -
* @param {Response} res * @param {Response} res -
*/ */
async editSaleReceipt(req: Request, res: Response, next: NextFunction) { async editSaleReceipt(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId } = req;
const { id: saleReceiptId } = req.params; const { id: saleReceiptId } = req.params;
const saleReceipt = { ...req.body }; const saleReceipt = this.matchedBodyData(req);
try { try {
// Update the given sale receipt details. // Update the given sale receipt details.
@@ -179,6 +172,7 @@ export default class SalesReceiptsController extends BaseController{
saleReceipt, saleReceipt,
); );
return res.status(200).send({ return res.status(200).send({
id: saleReceiptId,
message: 'Sale receipt has been edited successfully.', message: 'Sale receipt has been edited successfully.',
}); });
} catch (error) { } catch (error) {
@@ -191,19 +185,85 @@ export default class SalesReceiptsController extends BaseController{
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
*/ */
async getSalesReceipts(req: Request, res: Response) { async getSalesReceipts(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId } = req;
const filter = { const filter = {
filterRoles: [],
sortOrder: 'asc', sortOrder: 'asc',
columnSortBy: 'created_at',
page: 1, page: 1,
pageSize: 12, pageSize: 12,
...this.matchedBodyData(req), ...this.matchedQueryData(req),
}; };
if (filter.stringifiedFilterRoles) {
filter.filterRoles = JSON.parse(filter.stringifiedFilterRoles);
}
try { try {
const { salesReceipts, pagination, filterMeta } = await this.saleReceiptService
.salesReceiptsList(tenantId, filter);
return res.status(200).send({
sale_receipts: salesReceipts,
pagination: this.transfromToResponse(pagination),
filter_meta: this.transfromToResponse(filterMeta),
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
} }
/**
* Handles service errors.
* @param {Error} error
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
handleServiceErrors(error: Error, req: Request, res: Response, next: NextFunction) {
if (error instanceof ServiceError) {
if (error.errorType === 'SALE_RECEIPT_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'SALE_RECEIPT_NOT_FOUND', code: 100 }],
})
}
if (error.errorType === 'DEPOSIT_ACCOUNT_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'DEPOSIT_ACCOUNT_NOT_FOUND', code: 200 }],
})
}
if (error.errorType === 'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET') {
return res.boom.badRequest(null, {
errors: [{ type: 'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET', code: 300 }],
})
}
if (error.errorType === 'ITEMS_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ITEMS_NOT_FOUND', code: 400, }],
});
}
if (error.errorType === 'ENTRIES_IDS_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ENTRIES_IDS_NOT_FOUND', code: 500, }],
});
}
if (error.errorType === 'NOT_SELL_ABLE_ITEMS') {
return res.boom.badRequest(null, {
errors: [{ type: 'NOT_SELL_ABLE_ITEMS', code: 600, }],
});
}
if (error.errorType === 'SALE.RECEIPT.NOT.FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'SALE.RECEIPT.NOT.FOUND', code: 700 }],
});
}
if (error.errorType === 'DEPOSIT.ACCOUNT.NOT.EXISTS') {
return res.boom.badRequest(null, {
errors: [{ type: 'DEPOSIT.ACCOUNT.NOT.EXISTS', code: 800 }],
});
}
}
console.log(error);
next(error);
}
}; };

View File

@@ -1,4 +1,4 @@
import express from 'express'; import { Router } from 'express';
import { Container, Service } from 'typedi'; import { Container, Service } from 'typedi';
import SalesEstimates from './SalesEstimates'; import SalesEstimates from './SalesEstimates';
import SalesReceipts from './SalesReceipts'; import SalesReceipts from './SalesReceipts';
@@ -11,12 +11,12 @@ export default class SalesController {
* Router constructor. * Router constructor.
*/ */
router() { router() {
const router = express.Router(); const router = Router();
router.use('/invoices', Container.get(SalesInvoices).router()); // router.use('/invoices', Container.get(SalesInvoices).router());
router.use('/estimates', Container.get(SalesEstimates).router()); router.use('/estimates', Container.get(SalesEstimates).router());
router.use('/receipts', Container.get(SalesReceipts).router()); router.use('/receipts', Container.get(SalesReceipts).router());
router.use('/payment_receives', Container.get(PaymentReceives).router()); // router.use('/payment_receives', Container.get(PaymentReceives).router());
return router; return router;
} }

View File

@@ -29,7 +29,7 @@ import Settings from 'api/controllers/Settings';
import Currencies from 'api/controllers/Currencies'; import Currencies from 'api/controllers/Currencies';
import Customers from 'api/controllers/Contacts/Customers'; import Customers from 'api/controllers/Contacts/Customers';
import Vendors from 'api/controllers/Contacts/Vendors'; import Vendors from 'api/controllers/Contacts/Vendors';
// import Sales from 'api/controllers/Sales' import Sales from 'api/controllers/Sales'
import Purchases from 'api/controllers/Purchases'; import Purchases from 'api/controllers/Purchases';
import Resources from './controllers/Resources'; import Resources from './controllers/Resources';
import ExchangeRates from 'api/controllers/ExchangeRates'; import ExchangeRates from 'api/controllers/ExchangeRates';
@@ -94,7 +94,7 @@ export default () => {
dashboard.use('/financial_statements', FinancialStatements.router()); dashboard.use('/financial_statements', FinancialStatements.router());
dashboard.use('/customers', Container.get(Customers).router()); dashboard.use('/customers', Container.get(Customers).router());
dashboard.use('/vendors', Container.get(Vendors).router()); dashboard.use('/vendors', Container.get(Vendors).router());
// dashboard.use('/sales', Container.get(Sales).router()); dashboard.use('/sales', Container.get(Sales).router());
dashboard.use('/purchases', Container.get(Purchases).router()); dashboard.use('/purchases', Container.get(Purchases).router());
dashboard.use('/resources', Container.get(Resources).router()); dashboard.use('/resources', Container.get(Resources).router());
dashboard.use('/exchange_rates', Container.get(ExchangeRates).router()); dashboard.use('/exchange_rates', Container.get(ExchangeRates).router());

View File

@@ -1,5 +1,5 @@
import { IItemEntry } from "./ItemEntry"; import { IItemEntry } from "./ItemEntry";
import { IDynamicListFilterDTO } from 'interfaces/DynamicFilter';
export interface ISaleEstimate { export interface ISaleEstimate {
id?: number, id?: number,
@@ -23,3 +23,7 @@ export interface ISaleEstimateDTO {
note: string, note: string,
termsConditions: string, termsConditions: string,
}; };
export interface ISalesEstimatesFilter extends IDynamicListFilterDTO {
stringifiedFilterRoles?: string,
}

View File

@@ -10,6 +10,7 @@ export * from './License';
export * from './ItemCategory'; export * from './ItemCategory';
export * from './Payment'; export * from './Payment';
export * from './SaleInvoice'; export * from './SaleInvoice';
export * from './SaleReceipt';
export * from './PaymentReceive'; export * from './PaymentReceive';
export * from './SaleEstimate'; export * from './SaleEstimate';
export * from './Authentication'; export * from './Authentication';

View File

@@ -32,7 +32,7 @@ export default class SaleEstimate extends TenantModel {
to: 'contacts.id', to: 'contacts.id',
}, },
filter(query) { filter(query) {
query.where('contact_type', 'Customer'); query.where('contact_service', 'customer');
} }
}, },
@@ -49,4 +49,17 @@ export default class SaleEstimate extends TenantModel {
}, },
}; };
} }
/**
* Model defined fields.
*/
static get fields() {
return {
created_at: {
label: 'Created at',
column: 'created_at',
columnType: 'date',
},
};
}
} }

View File

@@ -72,4 +72,17 @@ export default class SaleReceipt extends TenantModel {
} }
}; };
} }
/**
* Model defined fields.
*/
static get fields() {
return {
created_at: {
label: 'Created at',
column: 'created_at',
columnType: 'date',
},
};
}
} }

View File

@@ -192,7 +192,7 @@ export default class CustomersService {
* @param {number} tenantId * @param {number} tenantId
* @param {number} customerId * @param {number} customerId
*/ */
private getCustomerByIdOrThrowError(tenantId: number, customerId: number) { public getCustomerByIdOrThrowError(tenantId: number, customerId: number) {
return this.contactService.getContactByIdOrThrowError(tenantId, customerId, 'customer'); return this.contactService.getContactByIdOrThrowError(tenantId, customerId, 'customer');
} }

View File

@@ -0,0 +1,105 @@
import { difference } from 'lodash';
import { Inject, Service } from 'typedi';
import {
IItemEntry,
IItemEntryDTO,
IItem,
} from 'interfaces';
import { ServiceError } from 'exceptions';
import TenancyService from 'services/Tenancy/TenancyService';
const ERRORS = {
ITEMS_NOT_FOUND: 'ITEMS_NOT_FOUND',
ENTRIES_IDS_NOT_FOUND: 'ENTRIES_IDS_NOT_FOUND',
NOT_PURCHASE_ABLE_ITEMS: 'NOT_PURCHASE_ABLE_ITEMS',
NOT_SELL_ABLE_ITEMS: 'NOT_SELL_ABLE_ITEMS'
};
@Service()
export default class ItemsEntriesService {
@Inject()
tenancy: TenancyService;
/**
* Validates the entries items ids.
* @async
* @param {number} tenantId -
* @param {IItemEntryDTO} itemEntries -
*/
public async validateItemsIdsExistance(tenantId: number, itemEntries: IItemEntryDTO[]) {
const { Item } = this.tenancy.models(tenantId);
const itemsIds = itemEntries.map((e) => e.itemId);
const foundItems = await Item.query().whereIn('id', itemsIds);
const foundItemsIds = foundItems.map((item: IItem) => item.id);
const notFoundItemsIds = difference(itemsIds, foundItemsIds);
if (notFoundItemsIds.length > 0) {
throw new ServiceError(ERRORS.ITEMS_NOT_FOUND);
}
}
/**
* Validates the entries ids existance on the storage.
* @param {number} tenantId -
* @param {number} billId -
* @param {IItemEntry[]} billEntries -
*/
public async validateEntriesIdsExistance(tenantId: number, billId: number, modelName: string, billEntries: IItemEntryDTO[]) {
const { ItemEntry } = this.tenancy.models(tenantId);
const entriesIds = billEntries
.filter((e: IItemEntry) => e.id)
.map((e: IItemEntry) => e.id);
const storedEntries = await ItemEntry.query()
.whereIn('reference_id', [billId])
.whereIn('reference_type', [modelName]);
const storedEntriesIds = storedEntries.map((entry) => entry.id);
const notFoundEntriesIds = difference(entriesIds, storedEntriesIds);
if (notFoundEntriesIds.length > 0) {
throw new ServiceError(ERRORS.ENTRIES_IDS_NOT_FOUND)
}
}
/**
* Validate the entries items that not purchase-able.
*/
public async validateNonPurchasableEntriesItems(tenantId: number, itemEntries: IItemEntryDTO[]) {
const { Item } = this.tenancy.models(tenantId);
const itemsIds = itemEntries.map((e: IItemEntryDTO) => e.itemId);
const purchasbleItems = await Item.query()
.where('purchasable', true)
.whereIn('id', itemsIds);
const purchasbleItemsIds = purchasbleItems.map((item: IItem) => item.id);
const notPurchasableItems = difference(itemsIds, purchasbleItemsIds);
if (notPurchasableItems.length > 0) {
throw new ServiceError(ERRORS.NOT_PURCHASE_ABLE_ITEMS);
}
}
/**
* Validate the entries items that not sell-able.
*/
public async validateNonSellableEntriesItems(tenantId: number, itemEntries: IItemEntryDTO[]) {
const { Item } = this.tenancy.models(tenantId);
const itemsIds = itemEntries.map((e: IItemEntryDTO) => e.itemId);
const sellableItems = await Item.query()
.where('sellable', true)
.whereIn('id', itemsIds);
const sellableItemsIds = sellableItems.map((item: IItem) => item.id);
const nonSellableItems = difference(itemsIds, sellableItemsIds);
if (nonSellableItems.length > 0) {
throw new ServiceError(ERRORS.NOT_SELL_ABLE_ITEMS);
}
}
}

View File

@@ -19,8 +19,6 @@ import {
IBill, IBill,
IItem, IItem,
ISystemUser, ISystemUser,
IItemEntry,
IItemEntryDTO,
IBillEditDTO, IBillEditDTO,
IPaginationMeta, IPaginationMeta,
IFilterMeta, IFilterMeta,
@@ -28,6 +26,7 @@ import {
} from 'interfaces'; } from 'interfaces';
import { ServiceError } from 'exceptions'; import { ServiceError } from 'exceptions';
import ItemsService from 'services/Items/ItemsService'; import ItemsService from 'services/Items/ItemsService';
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
const ERRORS = { const ERRORS = {
BILL_NOT_FOUND: 'BILL_NOT_FOUND', BILL_NOT_FOUND: 'BILL_NOT_FOUND',
@@ -66,6 +65,9 @@ export default class BillsService extends SalesInvoicesCost {
@Inject() @Inject()
dynamicListService: DynamicListingService; dynamicListService: DynamicListingService;
@Inject()
itemsEntriesService: ItemsEntriesService;
/** /**
* Validates whether the vendor is exist. * Validates whether the vendor is exist.
* @async * @async
@@ -105,27 +107,6 @@ export default class BillsService extends SalesInvoicesCost {
return foundBill; return foundBill;
} }
/**
* Validates the entries items ids.
* @async
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
private async validateItemsIdsExistance(tenantId: number, billEntries: IItemEntryDTO[]) {
const { Item } = this.tenancy.models(tenantId);
const itemsIds = billEntries.map((e) => e.itemId);
const foundItems = await Item.query().whereIn('id', itemsIds);
const foundItemsIds = foundItems.map((item: IItem) => item.id);
const notFoundItemsIds = difference(itemsIds, foundItemsIds);
if (notFoundItemsIds.length > 0) {
throw new ServiceError(ERRORS.BILL_ITEMS_NOT_FOUND);
}
}
/** /**
* Validates the bill number existance. * Validates the bill number existance.
* @async * @async
@@ -146,52 +127,6 @@ export default class BillsService extends SalesInvoicesCost {
} }
} }
/**
* Validates the entries ids existance on the storage.
* @param {number} tenantId -
* @param {number} billId -
* @param {IItemEntry[]} billEntries -
*/
private async validateEntriesIdsExistance(tenantId: number, billId: number, billEntries: IItemEntryDTO[]) {
const { ItemEntry } = this.tenancy.models(tenantId);
const entriesIds = billEntries
.filter((e: IItemEntry) => e.id)
.map((e: IItemEntry) => e.id);
const storedEntries = await ItemEntry.query()
.whereIn('reference_id', [billId])
.whereIn('reference_type', ['Bill']);
const storedEntriesIds = storedEntries.map((entry) => entry.id);
const notFoundEntriesIds = difference(entriesIds, storedEntriesIds);
if (notFoundEntriesIds.length > 0) {
throw new ServiceError(ERRORS.BILL_ENTRIES_IDS_NOT_FOUND)
}
}
/**
* Validate the entries items that not purchase-able.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
private async validateNonPurchasableEntriesItems(tenantId: number, billEntries: IItemEntryDTO[]) {
const { Item } = this.tenancy.models(tenantId);
const itemsIds = billEntries.map((e: IItemEntryDTO) => e.itemId);
const purchasbleItems = await Item.query()
.where('purchasable', true)
.whereIn('id', itemsIds);
const purchasbleItemsIds = purchasbleItems.map((item: IItem) => item.id);
const notPurchasableItems = difference(itemsIds, purchasbleItemsIds);
if (notPurchasableItems.length > 0) {
throw new ServiceError(ERRORS.NOT_PURCHASE_ABLE_ITEMS);
}
}
/** /**
* Converts bill DTO to model. * Converts bill DTO to model.
* @param {number} tenantId * @param {number} tenantId
@@ -249,8 +184,8 @@ export default class BillsService extends SalesInvoicesCost {
await this.getVendorOrThrowError(tenantId, billDTO.vendorId); await this.getVendorOrThrowError(tenantId, billDTO.vendorId);
await this.validateBillNumberExists(tenantId, billDTO.billNumber); await this.validateBillNumberExists(tenantId, billDTO.billNumber);
await this.validateItemsIdsExistance(tenantId, billDTO.entries); await this.itemsEntriesService.validateItemsIdsExistance(tenantId, billDTO.entries);
await this.validateNonPurchasableEntriesItems(tenantId, billDTO.entries); await this.itemsEntriesService.validateNonPurchasableEntriesItems(tenantId, billDTO.entries);
const bill = await Bill.query() const bill = await Bill.query()
.insertGraph({ .insertGraph({
@@ -302,9 +237,9 @@ export default class BillsService extends SalesInvoicesCost {
await this.getVendorOrThrowError(tenantId, billDTO.vendorId); await this.getVendorOrThrowError(tenantId, billDTO.vendorId);
await this.validateBillNumberExists(tenantId, billDTO.billNumber, billId); await this.validateBillNumberExists(tenantId, billDTO.billNumber, billId);
await this.validateEntriesIdsExistance(tenantId, billId, billDTO.entries); await this.itemsEntriesService.validateEntriesIdsExistance(tenantId, billId, 'Bill', billDTO.entries);
await this.validateItemsIdsExistance(tenantId, billDTO.entries); await this.itemsEntriesService.validateItemsIdsExistance(tenantId, billDTO.entries);
await this.validateNonPurchasableEntriesItems(tenantId, billDTO.entries); await this.itemsEntriesService.validateNonPurchasableEntriesItems(tenantId, billDTO.entries);
// Update the bill transaction. // Update the bill transaction.
const bill = await Bill.query().upsertGraph({ const bill = await Bill.query().upsertGraph({

View File

@@ -1,16 +1,25 @@
import { omit, difference, sumBy, mixin } from 'lodash'; import { omit, sumBy } from 'lodash';
import { Service, Inject } from 'typedi'; import { Service, Inject } from 'typedi';
import { IEstimatesFilter, IFilterMeta, IPaginationMeta, ISaleEstimate, ISaleEstimateDTO } from 'interfaces'; import { IEstimatesFilter, IFilterMeta, IPaginationMeta, ISaleEstimate, ISaleEstimateDTO } from 'interfaces';
import { import {
EventDispatcher, EventDispatcher,
EventDispatcherInterface, EventDispatcherInterface,
} from 'decorators/eventDispatcher'; } from 'decorators/eventDispatcher';
import HasItemsEntries from 'services/Sales/HasItemsEntries';
import { formatDateFields } from 'utils'; import { formatDateFields } from 'utils';
import TenancyService from 'services/Tenancy/TenancyService'; import TenancyService from 'services/Tenancy/TenancyService';
import DynamicListingService from 'services/DynamicListing/DynamicListService'; import DynamicListingService from 'services/DynamicListing/DynamicListService';
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
import events from 'subscribers/events'; import events from 'subscribers/events';
import { ServiceError } from 'exceptions';
import CustomersService from 'services/Contacts/CustomersService';
const ERRORS = {
SALE_ESTIMATE_NOT_FOUND: 'SALE_ESTIMATE_NOT_FOUND',
CUSTOMER_NOT_FOUND: 'CUSTOMER_NOT_FOUND',
SALE_ESTIMATE_NUMBER_EXISTANCE: 'SALE_ESTIMATE_NUMBER_EXISTANCE',
ITEMS_IDS_NOT_EXISTS: 'ITEMS_IDS_NOT_EXISTS',
}
/** /**
* Sale estimate service. * Sale estimate service.
* @Service * @Service
@@ -21,7 +30,10 @@ export default class SaleEstimateService {
tenancy: TenancyService; tenancy: TenancyService;
@Inject() @Inject()
itemsEntriesService: HasItemsEntries; itemsEntriesService: ItemsEntriesService;
@Inject()
customersService: CustomersService;
@Inject('logger') @Inject('logger')
logger: any; logger: any;
@@ -32,25 +44,19 @@ export default class SaleEstimateService {
@EventDispatcher() @EventDispatcher()
eventDispatcher: EventDispatcherInterface; eventDispatcher: EventDispatcherInterface;
/** /**
* Validate whether the estimate customer exists on the storage. * Retrieve sale estimate or throw service error.
* @param {Request} req * @param {number} tenantId
* @param {Response} res * @return {ISaleEstimate}
* @param {Function} next
*/ */
async validateEstimateCustomerExistance(req: Request, res: Response, next: Function) { async getSaleEstimateOrThrowError(tenantId: number, saleEstimateId: number) {
const estimate = { ...req.body }; const { SaleEstimate } = this.tenancy.models(tenantId);
const { Customer } = req.models const foundSaleEstimate = await SaleEstimate.query().findById(saleEstimateId);
const foundCustomer = await Customer.query().findById(estimate.customer_id); if (!foundSaleEstimate) {
throw new ServiceError(ERRORS.SALE_ESTIMATE_NOT_FOUND);
if (!foundCustomer) {
return res.status(404).send({
errors: [{ type: 'CUSTOMER.ID.NOT.FOUND', code: 200 }],
});
} }
next(); return foundSaleEstimate;
} }
/** /**
@@ -59,92 +65,19 @@ export default class SaleEstimateService {
* @param {Response} res * @param {Response} res
* @param {Function} next * @param {Function} next
*/ */
async validateEstimateNumberExistance(req: Request, res: Response, next: Function) { async validateEstimateNumberExistance(tenantId: number, estimateNumber: string, notEstimateId?: number) {
const estimate = { ...req.body }; const { SaleEstimate } = this.tenancy.models(tenantId);
const { tenantId } = req;
const isEstNumberUnqiue = await this.saleEstimateService.isEstimateNumberUnique( const foundSaleEstimate = await SaleEstimate.query()
tenantId, .findOne('estimate_number', estimateNumber)
estimate.estimate_number, .onBuild((builder) => {
req.params.id, if (notEstimateId) {
); builder.whereNot('id', notEstimateId);
if (isEstNumberUnqiue) { }
return res.boom.badRequest(null, {
errors: [{ type: 'ESTIMATE.NUMBER.IS.NOT.UNQIUE', code: 300 }],
}); });
if (foundSaleEstimate) {
throw new ServiceError(ERRORS.SALE_ESTIMATE_NUMBER_EXISTANCE);
} }
next();
}
/**
* Validate the estimate entries items ids existance on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateEstimateEntriesItemsExistance(req: Request, res: Response, next: Function) {
const tenantId = req.tenantId;
const estimate = { ...req.body };
const estimateItemsIds = estimate.entries.map(e => e.item_id);
// Validate items ids in estimate entries exists.
const notFoundItemsIds = await this.itemsService.isItemsIdsExists(tenantId, estimateItemsIds);
if (notFoundItemsIds.length > 0) {
return res.boom.badRequest(null, {
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 }],
});
}
next();
}
/**
* Validate whether the sale estimate id exists on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateEstimateIdExistance(req: Request, res: Response, next: Function) {
const { id: estimateId } = req.params;
const { tenantId } = req;
const storedEstimate = await this.saleEstimateService
.getEstimate(tenantId, estimateId);
if (!storedEstimate) {
return res.status(404).send({
errors: [{ type: 'SALE.ESTIMATE.ID.NOT.FOUND', code: 200 }],
});
}
next();
}
/**
* Validate sale invoice entries ids existance on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async valdiateInvoiceEntriesIdsExistance(req: Request, res: Response, next: Function) {
const { ItemEntry } = req.models;
const { id: saleInvoiceId } = req.params;
const saleInvoice = { ...req.body };
const entriesIds = saleInvoice.entries
.filter(e => e.id)
.map((e) => e.id);
const foundEntries = await ItemEntry.query()
.whereIn('id', entriesIds)
.where('reference_type', 'SaleInvoice')
.where('reference_id', saleInvoiceId);
if (foundEntries.length > 0) {
return res.status(400).send({
errors: [{ type: 'ENTRIES.IDS.NOT.EXISTS', code: 300 }],
});
}
next();
} }
/** /**
@@ -154,22 +87,27 @@ export default class SaleEstimateService {
* @param {EstimateDTO} estimate * @param {EstimateDTO} estimate
* @return {Promise<ISaleEstimate>} * @return {Promise<ISaleEstimate>}
*/ */
async createEstimate(tenantId: number, estimateDTO: ISaleEstimateDTO): Promise<ISaleEstimate> { public async createEstimate(tenantId: number, estimateDTO: ISaleEstimateDTO): Promise<ISaleEstimate> {
const { SaleEstimate, ItemEntry } = this.tenancy.models(tenantId); const { SaleEstimate, ItemEntry } = this.tenancy.models(tenantId);
this.logger.info('[sale_estimate] inserting sale estimate to the storage.');
const amount = sumBy(estimateDTO.entries, e => ItemEntry.calcAmount(e)); const amount = sumBy(estimateDTO.entries, e => ItemEntry.calcAmount(e));
const estimate = { const estimateObj = {
amount, amount,
...formatDateFields(estimateDTO, ['estimate_date', 'expiration_date']), ...formatDateFields(estimateDTO, ['estimate_date', 'expiration_date']),
}; };
await this.validateEstimateNumberExistance(tenantId, estimateDTO.estimateNumber);
await this.customersService.getCustomer(tenantId, estimateDTO.customerId);
this.logger.info('[sale_estimate] inserting sale estimate to the storage.'); await this.itemsEntriesService.validateItemsIdsExistance(tenantId, estimateDTO.entries);
const storedEstimate = await SaleEstimate.query() await this.itemsEntriesService.validateNonSellableEntriesItems(tenantId, estimateDTO.entries);
.insert({
...omit(estimate, ['entries']), const saleEstimate = await SaleEstimate.query()
entries: estimate.entries.map((entry) => ({ .upsertGraph({
...omit(estimateObj, ['entries']),
entries: estimateObj.entries.map((entry) => ({
reference_type: 'SaleEstimate', reference_type: 'SaleEstimate',
reference_id: storedEstimate.id,
...omit(entry, ['total', 'amount', 'id']), ...omit(entry, ['total', 'amount', 'id']),
})) }))
}); });
@@ -177,7 +115,7 @@ export default class SaleEstimateService {
this.logger.info('[sale_estimate] insert sale estimated success.'); this.logger.info('[sale_estimate] insert sale estimated success.');
await this.eventDispatcher.dispatch(events.saleEstimates.onCreated); await this.eventDispatcher.dispatch(events.saleEstimates.onCreated);
return storedEstimate; return saleEstimate;
} }
/** /**
@@ -188,31 +126,36 @@ export default class SaleEstimateService {
* @param {EstimateDTO} estimate * @param {EstimateDTO} estimate
* @return {void} * @return {void}
*/ */
async editEstimate(tenantId: number, estimateId: number, estimateDTO: ISaleEstimateDTO): Promise<void> { public async editEstimate(tenantId: number, estimateId: number, estimateDTO: ISaleEstimateDTO): Promise<ISaleEstimate> {
const { SaleEstimate, ItemEntry } = this.tenancy.models(tenantId); const { SaleEstimate, ItemEntry } = this.tenancy.models(tenantId);
const amount = sumBy(estimateDTO.entries, e => ItemEntry.calcAmount(e)); const oldSaleEstimate = await this.getSaleEstimateOrThrowError(tenantId, estimateId);
const estimate = { const amount = sumBy(estimateDTO.entries, (e) => ItemEntry.calcAmount(e));
const estimateObj = {
amount, amount,
...formatDateFields(estimateDTO, ['estimate_date', 'expiration_date']), ...formatDateFields(estimateDTO, ['estimate_date', 'expiration_date']),
}; };
this.logger.info('[sale_estimate] editing sale estimate on the storage.'); await this.validateEstimateNumberExistance(tenantId, estimateDTO.estimateNumber, estimateId);
const updatedEstimate = await SaleEstimate.query() await this.customersService.getCustomer(tenantId, estimateDTO.customerId);
.update({
...omit(estimate, ['entries']),
});
const storedEstimateEntries = await ItemEntry.query()
.where('reference_id', estimateId)
.where('reference_type', 'SaleEstimate');
await this.itemsEntriesService.patchItemsEntries( await this.itemsEntriesService.validateEntriesIdsExistance(tenantId, estimateId, 'SaleEstiamte', estimateDTO.entries);
tenantId, await this.itemsEntriesService.validateItemsIdsExistance(tenantId, estimateDTO.entries);
estimate.entries, await this.itemsEntriesService.validateNonSellableEntriesItems(tenantId, estimateDTO.entries);
storedEstimateEntries,
'SaleEstimate', this.logger.info('[sale_estimate] editing sale estimate on the storage.');
estimateId, const saleEstimate = await SaleEstimate.query()
); .upsertGraph({
await this.eventDispatcher.dispatch(events.saleEstimates.onEdited); id: estimateId,
...omit(estimateObj, ['entries']),
entries: estimateObj.entries.map((entry) => ({
...omit(entry, ['total', 'amount']),
})),
});
await this.eventDispatcher.dispatch(events.saleEstimates.onEdited, {
tenantId, estimateId, saleEstimate, oldSaleEstimate,
});
return saleEstimate;
} }
/** /**
@@ -222,9 +165,11 @@ export default class SaleEstimateService {
* @param {IEstimate} estimateId * @param {IEstimate} estimateId
* @return {void} * @return {void}
*/ */
async deleteEstimate(tenantId: number, estimateId: number) { public async deleteEstimate(tenantId: number, estimateId: number): Promise<void> {
const { SaleEstimate, ItemEntry } = this.tenancy.models(tenantId); const { SaleEstimate, ItemEntry } = this.tenancy.models(tenantId);
const oldSaleEstimate = await this.getSaleEstimateOrThrowError(tenantId, estimateId);
this.logger.info('[sale_estimate] delete sale estimate and associated entries from the storage.'); this.logger.info('[sale_estimate] delete sale estimate and associated entries from the storage.');
await ItemEntry.query() await ItemEntry.query()
.where('reference_id', estimateId) .where('reference_id', estimateId)
@@ -234,63 +179,9 @@ export default class SaleEstimateService {
await SaleEstimate.query().where('id', estimateId).delete(); await SaleEstimate.query().where('id', estimateId).delete();
this.logger.info('[sale_estimate] deleted successfully.', { tenantId, estimateId }); this.logger.info('[sale_estimate] deleted successfully.', { tenantId, estimateId });
await this.eventDispatcher.dispatch(events.saleEstimates.onDeleted); await this.eventDispatcher.dispatch(events.saleEstimates.onDeleted, {
} tenantId, saleEstimateId: estimateId, oldSaleEstimate,
});
/**
* Validates the given estimate ID exists.
* @async
* @param {number} tenantId - The tenant id.
* @param {Numeric} estimateId
* @return {Boolean}
*/
async isEstimateExists(tenantId: number, estimateId: number) {
const { SaleEstimate } = this.tenancy.models(tenantId);
const foundEstimate = await SaleEstimate.query().where('id', estimateId);
return foundEstimate.length !== 0;
}
/**
* Validates the given estimate entries IDs.
* @async
* @param {number} tenantId - The tenant id.
* @param {Numeric} estimateId - the sale estimate id.
* @param {IEstimate} estimate
*/
async isEstimateEntriesIDsExists(tenantId: number, estimateId: number, estimate: any) {
const { ItemEntry } = this.tenancy.models(tenantId);
const estimateEntriesIds = estimate.entries
.filter((e: any) => e.id)
.map((e: any) => e.id);
const estimateEntries = await ItemEntry.query()
.whereIn('id', estimateEntriesIds)
.where('reference_id', estimateId)
.where('reference_type', 'SaleEstimate');
const storedEstimateEntriesIds = estimateEntries.map((e: any) => e.id);
const notFoundEntriesIDs = difference(
estimateEntriesIds,
storedEstimateEntriesIds
);
return notFoundEntriesIDs;
}
/**
* Retrieve the estimate details of the given estimate id.
* @async
* @param {number} tenantId - The tenant id.
* @param {Integer} estimateId
* @return {IEstimate}
*/
async getEstimate(tenantId: number, estimateId: number) {
const { SaleEstimate } = this.tenancy.models(tenantId);
const estimate = await SaleEstimate.query()
.where('id', estimateId)
.first();
return estimate;
} }
/** /**
@@ -299,42 +190,23 @@ export default class SaleEstimateService {
* @param {number} tenantId - The tenant id. * @param {number} tenantId - The tenant id.
* @param {Integer} estimateId * @param {Integer} estimateId
*/ */
async getEstimateWithEntries(tenantId: number, estimateId: number) { public async getEstimate(tenantId: number, estimateId: number) {
const { SaleEstimate } = this.tenancy.models(tenantId); const { SaleEstimate } = this.tenancy.models(tenantId);
const estimate = await SaleEstimate.query() const estimate = await SaleEstimate.query()
.where('id', estimateId) .findById(estimateId)
.withGraphFetched('entries') .withGraphFetched('entries')
.withGraphFetched('customer') .withGraphFetched('customer');
.first();
if (!estimate) {
throw new ServiceError(ERRORS.SALE_ESTIMATE_NOT_FOUND);
}
return estimate; return estimate;
} }
/**
* Detarmines the estimate number uniqness.
* @async
* @param {number} tenantId - The tenant id.
* @param {String} estimateNumber
* @param {Integer} excludeEstimateId
* @return {Boolean}
*/
async isEstimateNumberUnique(tenantId: number, estimateNumber: string, excludeEstimateId: number) {
const { SaleEstimate } = this.tenancy.models(tenantId);
const foundEstimates = await SaleEstimate.query()
.onBuild((query: any) => {
query.where('estimate_number', estimateNumber);
if (excludeEstimateId) {
query.whereNot('id', excludeEstimateId);
}
return query;
});
return foundEstimates.length > 0;
}
/** /**
* Retrieves estimates filterable and paginated list. * Retrieves estimates filterable and paginated list.
* @param {number} tenantId * @param {number} tenantId -
* @param {IEstimatesFilter} estimatesFilter * @param {IEstimatesFilter} estimatesFilter -
*/ */
public async estimatesList( public async estimatesList(
tenantId: number, tenantId: number,

View File

@@ -1,17 +1,25 @@
import { omit, difference, sumBy } from 'lodash'; import { omit, sumBy } from 'lodash';
import { Service, Inject } from 'typedi'; import { Service, Inject } from 'typedi';
import { import {
EventDispatcher, EventDispatcher,
EventDispatcherInterface, EventDispatcherInterface,
} from 'decorators/eventDispatcher'; } from 'decorators/eventDispatcher';
import events from 'subscribers/events'; import events from 'subscribers/events';
import { ISaleReceipt } from 'interfaces';
import JournalPosterService from 'services/Sales/JournalPosterService'; import JournalPosterService from 'services/Sales/JournalPosterService';
import HasItemEntries from 'services/Sales/HasItemsEntries';
import TenancyService from 'services/Tenancy/TenancyService'; import TenancyService from 'services/Tenancy/TenancyService';
import { formatDateFields } from 'utils'; import { formatDateFields } from 'utils';
import { IFilterMeta, IPaginationMeta } from 'interfaces'; import { IFilterMeta, IPaginationMeta } from 'interfaces';
import DynamicListingService from 'services/DynamicListing/DynamicListService'; import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { ServiceError } from 'exceptions';
import ItemsEntriesService from 'services/Items/ItemsEntriesService';
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',
};
@Service() @Service()
export default class SalesReceiptService { export default class SalesReceiptService {
@Inject() @Inject()
@@ -24,152 +32,84 @@ export default class SalesReceiptService {
journalService: JournalPosterService; journalService: JournalPosterService;
@Inject() @Inject()
itemsEntriesService: HasItemEntries; itemsEntriesService: ItemsEntriesService;
@EventDispatcher() @EventDispatcher()
eventDispatcher: EventDispatcherInterface; eventDispatcher: EventDispatcherInterface;
@Inject('logger')
logger: any;
/** /**
* Validate whether sale receipt exists on the storage. * Validate whether sale receipt exists on the storage.
* @param {Request} req * @param {number} tenantId -
* @param {Response} res * @param {number} saleReceiptId -
*/ */
async getSaleReceiptOrThrowError(tenantId: number, saleReceiptId: number) { async getSaleReceiptOrThrowError(tenantId: number, saleReceiptId: number) {
const { tenantId } = req; const { SaleReceipt } = this.tenancy.models(tenantId);
const { id: saleReceiptId } = req.params;
const isSaleReceiptExists = await this.saleReceiptService this.logger.info('[sale_receipt] trying to validate existance.', { tenantId, saleReceiptId });
.isSaleReceiptExists( const foundSaleReceipt = await SaleReceipt.query().findById(saleReceiptId);
tenantId,
saleReceiptId, if (!foundSaleReceipt) {
); this.logger.info('[sale_receipt] not found on the storage.', { tenantId, saleReceiptId });
if (!isSaleReceiptExists) { throw new ServiceError(ERRORS.SALE_RECEIPT_NOT_FOUND);
return res.status(404).send({
errors: [{ type: 'SALE.RECEIPT.NOT.FOUND', code: 200 }],
});
} }
next(); return foundSaleReceipt;
}
/**
* Validate whether sale receipt customer exists on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateReceiptCustomerExistance(req: Request, res: Response, next: Function) {
const saleReceipt = { ...req.body };
const { Customer } = req.models;
const foundCustomer = await Customer.query().findById(saleReceipt.customer_id);
if (!foundCustomer) {
return res.status(400).send({
errors: [{ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 }],
});
}
next();
} }
/** /**
* Validate whether sale receipt deposit account exists on the storage. * Validate whether sale receipt deposit account exists on the storage.
* @param {Request} req * @param {number} tenantId -
* @param {Response} res * @param {number} accountId -
* @param {Function} next
*/ */
async validateReceiptDepositAccountExistance(req: Request, res: Response, next: Function) { async validateReceiptDepositAccountExistance(tenantId: number, accountId: number) {
const { tenantId } = req; const { accountRepository, accountTypeRepository } = this.tenancy.repositories(tenantId);
const depositAccount = await accountRepository.findById(accountId);
const saleReceipt = { ...req.body }; if (!depositAccount) {
const isDepositAccountExists = await this.accountsService.isAccountExists( throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_FOUND);
tenantId,
saleReceipt.deposit_account_id
);
if (!isDepositAccountExists) {
return res.status(400).send({
errors: [{ type: 'DEPOSIT.ACCOUNT.NOT.EXISTS', code: 300 }],
});
} }
next(); const depositAccountType = await accountTypeRepository.getTypeMeta(depositAccount.accountTypeId);
}
/** if (!depositAccountType || depositAccountType.childRoot === 'current_asset') {
* Validate whether receipt items ids exist on the storage. throw new ServiceError(ERRORS.DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET);
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateReceiptItemsIdsExistance(req: Request, res: Response, next: Function) {
const { tenantId } = req;
const saleReceipt = { ...req.body };
const estimateItemsIds = saleReceipt.entries.map((e) => e.item_id);
const notFoundItemsIds = await this.itemsService.isItemsIdsExists(
tenantId,
estimateItemsIds
);
if (notFoundItemsIds.length > 0) {
return res.status(400).send({ errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 }] });
} }
next();
} }
/**
* Validate receipt entries ids existance on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateReceiptEntriesIds(req: Request, res: Response, next: Function) {
const { tenantId } = req;
const saleReceipt = { ...req.body };
const { id: saleReceiptId } = req.params;
// Validate the entries IDs that not stored or associated to the sale receipt.
const notExistsEntriesIds = await this.saleReceiptService
.isSaleReceiptEntriesIDsExists(
tenantId,
saleReceiptId,
saleReceipt,
);
if (notExistsEntriesIds.length > 0) {
return res.status(400).send({ errors: [{
type: 'ENTRIES.IDS.NOT.FOUND',
code: 500,
}]
});
}
next();
}
/** /**
* Creates a new sale receipt with associated entries. * Creates a new sale receipt with associated entries.
* @async * @async
* @param {ISaleReceipt} saleReceipt * @param {ISaleReceipt} saleReceipt
* @return {Object} * @return {Object}
*/ */
public async createSaleReceipt(tenantId: number, saleReceiptDTO: any) { public async createSaleReceipt(tenantId: number, saleReceiptDTO: any): Promise<ISaleReceipt> {
const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId); const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId);
const amount = sumBy(saleReceiptDTO.entries, e => ItemEntry.calcAmount(e)); const amount = sumBy(saleReceiptDTO.entries, e => ItemEntry.calcAmount(e));
const saleReceipt = { const saleReceiptObj = {
amount, amount,
...formatDateFields(saleReceiptDTO, ['receipt_date']) ...formatDateFields(saleReceiptDTO, ['receipt_date'])
}; };
const storedSaleReceipt = await SaleReceipt.query() await this.validateReceiptDepositAccountExistance(tenantId, saleReceiptDTO.depositAccountId);
.insert({ await this.itemsEntriesService.validateItemsIdsExistance(tenantId, saleReceiptDTO.entries);
...omit(saleReceipt, ['entries']), await this.itemsEntriesService.validateNonSellableEntriesItems(tenantId, saleReceiptDTO.entries);
entries: saleReceipt.entries.map((entry) => ({
this.logger.info('[sale_receipt] trying to insert sale receipt graph.', { tenantId, saleReceiptDTO });
const saleReceipt = await SaleReceipt.query()
.insertGraph({
...omit(saleReceiptObj, ['entries']),
entries: saleReceiptObj.entries.map((entry) => ({
reference_type: 'SaleReceipt', reference_type: 'SaleReceipt',
reference_id: storedSaleReceipt.id,
...omit(entry, ['id', 'amount']), ...omit(entry, ['id', 'amount']),
})) }))
}); });
await this.eventDispatcher.dispatch(events.saleReceipts.onCreated, { tenantId, saleReceipt });
await this.eventDispatcher.dispatch(events.saleReceipts.onCreated); this.logger.info('[sale_receipt] sale receipt inserted successfully.', { tenantId });
return saleReceipt;
} }
/** /**
@@ -182,30 +122,32 @@ export default class SalesReceiptService {
const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId); const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId);
const amount = sumBy(saleReceiptDTO.entries, e => ItemEntry.calcAmount(e)); const amount = sumBy(saleReceiptDTO.entries, e => ItemEntry.calcAmount(e));
const saleReceipt = { const saleReceiptObj = {
amount, amount,
...formatDateFields(saleReceiptDTO, ['receipt_date']) ...formatDateFields(saleReceiptDTO, ['receipt_date'])
}; };
const updatedSaleReceipt = await SaleReceipt.query() const oldSaleReceipt = await this.getSaleReceiptOrThrowError(tenantId, saleReceiptId);
.where('id', saleReceiptId)
.update({ await this.validateReceiptDepositAccountExistance(tenantId, saleReceiptDTO.depositAccountId);
...omit(saleReceipt, ['entries']), await this.itemsEntriesService.validateItemsIdsExistance(tenantId, saleReceiptDTO.entries);
await this.itemsEntriesService.validateNonSellableEntriesItems(tenantId, saleReceiptDTO.entries);
const saleReceipt = await SaleReceipt.query()
.upsertGraph({
id: saleReceiptId,
...omit(saleReceiptObj, ['entries']),
entries: saleReceiptObj.entries.map((entry) => ({
reference_type: 'SaleReceipt',
...omit(entry, ['amount']),
}))
}); });
const storedSaleReceiptEntries = await ItemEntry.query()
.where('reference_id', saleReceiptId)
.where('reference_type', 'SaleReceipt');
// Patch sale receipt items entries. this.logger.info('[sale_receipt] edited successfully.', { tenantId, saleReceiptId });
const patchItemsEntries = this.itemsEntriesService.patchItemsEntries( await this.eventDispatcher.dispatch(events.saleReceipts.onEdited, {
tenantId, oldSaleReceipt, tenantId, saleReceiptId, saleReceipt,
saleReceipt.entries, });
storedSaleReceiptEntries, return saleReceipt;
'SaleReceipt',
saleReceiptId,
);
await Promise.all([patchItemsEntries]);
await this.eventDispatcher.dispatch(events.saleReceipts.onCreated);
} }
/** /**
@@ -215,66 +157,18 @@ export default class SalesReceiptService {
*/ */
public async deleteSaleReceipt(tenantId: number, saleReceiptId: number) { public async deleteSaleReceipt(tenantId: number, saleReceiptId: number) {
const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId); const { SaleReceipt, ItemEntry } = this.tenancy.models(tenantId);
const deleteSaleReceiptOper = SaleReceipt.query()
.where('id', saleReceiptId)
.delete();
const deleteItemsEntriesOper = ItemEntry.query() await ItemEntry.query()
.where('reference_id', saleReceiptId) .where('reference_id', saleReceiptId)
.where('reference_type', 'SaleReceipt') .where('reference_type', 'SaleReceipt')
.delete(); .delete();
// Delete all associated journal transactions to payment receive transaction. await SaleReceipt.query().where('id', saleReceiptId).delete();
const deleteTransactionsOper = this.journalService.deleteJournalTransactions(
tenantId,
saleReceiptId,
'SaleReceipt'
);
await Promise.all([
deleteItemsEntriesOper,
deleteSaleReceiptOper,
deleteTransactionsOper,
]);
this.logger.info('[sale_receipt] deleted successfully.', { tenantId, saleReceiptId });
await this.eventDispatcher.dispatch(events.saleReceipts.onDeleted); await this.eventDispatcher.dispatch(events.saleReceipts.onDeleted);
} }
/**
* Validates the given sale receipt ID exists.
* @param {Integer} saleReceiptId
* @returns {Boolean}
*/
async isSaleReceiptExists(tenantId: number, saleReceiptId: number) {
const { SaleReceipt } = this.tenancy.models(tenantId);
const foundSaleReceipt = await SaleReceipt.query()
.where('id', saleReceiptId);
return foundSaleReceipt.length !== 0;
}
/**
* Detarmines the sale receipt entries IDs exists.
* @param {Integer} saleReceiptId
* @param {ISaleReceipt} saleReceipt
*/
async isSaleReceiptEntriesIDsExists(tenantId: number, saleReceiptId: number, saleReceipt: any) {
const { ItemEntry } = this.tenancy.models(tenantId);
const entriesIDs = saleReceipt.entries
.filter((e) => e.id)
.map((e) => e.id);
const storedEntries = await ItemEntry.query()
.whereIn('id', entriesIDs)
.where('reference_id', saleReceiptId)
.where('reference_type', 'SaleReceipt');
const storedEntriesIDs = storedEntries.map((e: any) => e.id);
const notFoundEntriesIDs = difference(
entriesIDs,
storedEntriesIDs
);
return notFoundEntriesIDs;
}
/** /**
* Retrieve sale receipt with associated entries. * Retrieve sale receipt with associated entries.
* @param {Integer} saleReceiptId * @param {Integer} saleReceiptId