refactoring: payment receive and sale invoice actions.

This commit is contained in:
Ahmed Bouhuolia
2020-10-25 18:30:44 +02:00
parent 39d1875cbb
commit 426f9fcf55
20 changed files with 820 additions and 1069 deletions

View File

@@ -152,7 +152,11 @@ export default class BillsController extends BaseController {
try {
const storedBill = await this.billsService.createBill(tenantId, billDTO, user);
return res.status(200).send({ id: storedBill.id });
return res.status(200).send({
id: storedBill.id,
message: 'The bill has been created successfully.',
});
} catch (error) {
next(error);
}
@@ -170,7 +174,10 @@ export default class BillsController extends BaseController {
try {
const editedBill = await this.billsService.editBill(tenantId, billId, billDTO);
return res.status(200).send({ id: billId });
return res.status(200).send({
id: billId,
message: 'The bill has been edited successfully.',
});
} catch (error) {
next(error);
}

View File

@@ -1,13 +1,12 @@
import { Router, Request, Response } from 'express';
import { check, param, query, ValidationChain, matchedData } from 'express-validator';
import { difference } from 'lodash';
import { Router, Request, Response, NextFunction } from 'express';
import { check, param, query, ValidationChain } from 'express-validator';
import { Inject, Service } from 'typedi';
import { IPaymentReceive, IPaymentReceiveOTD } from 'interfaces';
import { IPaymentReceiveDTO } from 'interfaces';
import BaseController from 'api/controllers/BaseController';
import asyncMiddleware from 'api/middleware/asyncMiddleware';
import PaymentReceiveService from 'services/Sales/PaymentsReceives';
import SaleInvoiceService from 'services/Sales/SalesInvoices';
import AccountsService from 'services/Accounts/AccountsService';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { ServiceError } from 'exceptions';
/**
* Payments receives controller.
@@ -19,11 +18,8 @@ export default class PaymentReceivesController extends BaseController {
paymentReceiveService: PaymentReceiveService;
@Inject()
accountsService: AccountsService;
@Inject()
saleInvoiceService: SaleInvoiceService;
dynamicListService: DynamicListingService;
/**
* Router constructor.
*/
@@ -34,45 +30,37 @@ export default class PaymentReceivesController extends BaseController {
'/:id',
this.editPaymentReceiveValidation,
this.validationResult,
asyncMiddleware(this.validatePaymentReceiveExistance.bind(this)),
asyncMiddleware(this.validatePaymentReceiveNoExistance.bind(this)),
asyncMiddleware(this.validateCustomerExistance.bind(this)),
asyncMiddleware(this.validateDepositAccount.bind(this)),
asyncMiddleware(this.validateInvoicesIDs.bind(this)),
asyncMiddleware(this.validateEntriesIdsExistance.bind(this)),
asyncMiddleware(this.validateInvoicesPaymentsAmount.bind(this)),
asyncMiddleware(this.editPaymentReceive.bind(this)),
this.handleServiceErrors,
);
router.post(
'/',
this.newPaymentReceiveValidation,
this.validationResult,
asyncMiddleware(this.validatePaymentReceiveNoExistance.bind(this)),
asyncMiddleware(this.validateCustomerExistance.bind(this)),
asyncMiddleware(this.validateDepositAccount.bind(this)),
asyncMiddleware(this.validateInvoicesIDs.bind(this)),
asyncMiddleware(this.validateInvoicesPaymentsAmount.bind(this)),
asyncMiddleware(this.newPaymentReceive.bind(this)),
this.handleServiceErrors,
);
router.get(
'/:id',
this.paymentReceiveValidation,
this.validationResult,
asyncMiddleware(this.validatePaymentReceiveExistance.bind(this)),
asyncMiddleware(this.getPaymentReceive.bind(this))
asyncMiddleware(this.getPaymentReceive.bind(this)),
this.handleServiceErrors,
);
router.get(
'/',
this.validatePaymentReceiveList,
this.validationResult,
asyncMiddleware(this.getPaymentReceiveList.bind(this)),
this.handleServiceErrors,
this.dynamicListService.handlerErrorsToResponse,
);
router.delete(
'/:id',
this.paymentReceiveValidation,
this.validationResult,
asyncMiddleware(this.validatePaymentReceiveExistance.bind(this)),
asyncMiddleware(this.deletePaymentReceive.bind(this)),
this.handleServiceErrors,
);
return router;
}
@@ -126,198 +114,6 @@ export default class PaymentReceivesController extends BaseController {
return [...this.paymentReceiveSchema];
}
/**
* Validates the payment receive number existance.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validatePaymentReceiveNoExistance(req: Request, res: Response, next: Function) {
const tenantId = req.tenantId;
const isPaymentNoExists = await this.paymentReceiveService.isPaymentReceiveNoExists(
tenantId,
req.body.payment_receive_no,
req.params.id,
);
if (isPaymentNoExists) {
return res.status(400).send({
errors: [{ type: 'PAYMENT.RECEIVE.NUMBER.EXISTS', code: 400 }],
});
}
next();
}
/**
* Validates the payment receive existance.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validatePaymentReceiveExistance(req: Request, res: Response, next: Function) {
const tenantId = req.tenantId;
const isPaymentNoExists = await this.paymentReceiveService
.isPaymentReceiveExists(
tenantId,
req.params.id
);
if (!isPaymentNoExists) {
return res.status(400).send({
errors: [{ type: 'PAYMENT.RECEIVE.NOT.EXISTS', code: 600 }],
});
}
next();
}
/**
* Validate the deposit account id existance.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateDepositAccount(req: Request, res: Response, next: Function) {
const tenantId = req.tenantId;
const isDepositAccExists = await this.accountsService.isAccountExists(
tenantId,
req.body.deposit_account_id
);
if (!isDepositAccExists) {
return res.status(400).send({
errors: [{ type: 'DEPOSIT.ACCOUNT.NOT.EXISTS', code: 300 }],
});
}
next();
}
/**
* Validates the `customer_id` existance.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateCustomerExistance(req: Request, res: Response, next: Function) {
const { Customer } = req.models;
const isCustomerExists = await Customer.query().findById(req.body.customer_id);
if (!isCustomerExists) {
return res.status(400).send({
errors: [{ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 }],
});
}
next();
}
/**
* Validates the invoices IDs existance.
* @param {Request} req -
* @param {Response} res -
* @param {Function} next -
*/
async validateInvoicesIDs(req: Request, res: Response, next: Function) {
const paymentReceive = { ...req.body };
const { tenantId } = req;
const invoicesIds = paymentReceive.entries
.map((e) => e.invoice_id);
const notFoundInvoicesIDs = await this.saleInvoiceService.isInvoicesExist(
tenantId,
invoicesIds,
paymentReceive.customer_id,
);
if (notFoundInvoicesIDs.length > 0) {
return res.status(400).send({
errors: [{ type: 'INVOICES.IDS.NOT.FOUND', code: 500 }],
});
}
next();
}
/**
* Validates entries invoice payment amount.
* @param {Request} req -
* @param {Response} res -
* @param {Function} next -
*/
async validateInvoicesPaymentsAmount(req: Request, res: Response, next: Function) {
const { SaleInvoice } = req.models;
const invoicesIds = req.body.entries.map((e) => e.invoice_id);
const storedInvoices = await SaleInvoice.query()
.whereIn('id', invoicesIds);
const storedInvoicesMap = new Map(
storedInvoices.map((invoice) => [invoice.id, invoice])
);
const hasWrongPaymentAmount: any[] = [];
req.body.entries.forEach((entry, index: number) => {
const entryInvoice = storedInvoicesMap.get(entry.invoice_id);
const { dueAmount } = entryInvoice;
if (dueAmount < entry.payment_amount) {
hasWrongPaymentAmount.push({ index, due_amount: dueAmount });
}
});
if (hasWrongPaymentAmount.length > 0) {
return res.status(400).send({
errors: [
{
type: 'INVOICE.PAYMENT.AMOUNT',
code: 200,
indexes: hasWrongPaymentAmount,
},
],
});
}
next();
}
/**
* Validate the payment receive entries IDs existance.
* @param {Request} req
* @param {Response} res
* @return {Response}
*/
async validateEntriesIdsExistance(req: Request, res: Response, next: Function) {
const paymentReceive = { id: req.params.id, ...req.body };
const entriesIds = paymentReceive.entries
.filter(entry => entry.id)
.map(entry => entry.id);
const { PaymentReceiveEntry } = req.models;
const storedEntries = await PaymentReceiveEntry.query()
.where('payment_receive_id', paymentReceive.id);
const storedEntriesIds = storedEntries.map((entry) => entry.id);
const notFoundEntriesIds = difference(entriesIds, storedEntriesIds);
if (notFoundEntriesIds.length > 0) {
return res.status(400).send({
errors: [{ type: 'ENTEIES.IDS.NOT.FOUND', code: 800 }],
});
}
next();
}
/**
* Records payment receive to the given customer with associated invoices.
*/
async newPaymentReceive(req: Request, res: Response) {
const { tenantId } = req;
const paymentReceive: IPaymentReceiveOTD = matchedData(req, {
locations: ['body'],
includeOptionals: true,
});
const storedPaymentReceive = await this.paymentReceiveService
.createPaymentReceive(
tenantId,
paymentReceive,
);
return res.status(200).send({ id: storedPaymentReceive.id });
}
/**
* Edit payment receive validation.
*/
@@ -328,34 +124,48 @@ export default class PaymentReceivesController extends BaseController {
];
}
/**
* Records payment receive to the given customer with associated invoices.
*/
async newPaymentReceive(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const paymentReceive: IPaymentReceiveDTO = this.matchedBodyData(req);
try {
const storedPaymentReceive = await this.paymentReceiveService
.createPaymentReceive(
tenantId,
paymentReceive,
);
return res.status(200).send({
id: storedPaymentReceive.id,
message: 'The payment receive has been created successfully.',
});
} catch (error) {
next(error);
}
}
/**
* Edit the given payment receive.
* @param {Request} req
* @param {Response} res
* @return {Response}
*/
async editPaymentReceive(req: Request, res: Response) {
async editPaymentReceive(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const { id: paymentReceiveId } = req.params;
const { PaymentReceive } = req.models;
const paymentReceive: IPaymentReceiveOTD = matchedData(req, {
locations: ['body'],
});
const paymentReceive: IPaymentReceiveDTO = this.matchedBodyData(req);
// Retrieve the payment receive before updating.
const oldPaymentReceive: IPaymentReceive = await PaymentReceive.query()
.where('id', paymentReceiveId)
.withGraphFetched('entries')
.first();
await this.paymentReceiveService.editPaymentReceive(
tenantId,
paymentReceiveId,
paymentReceive,
oldPaymentReceive,
);
return res.status(200).send({ id: paymentReceiveId });
try {
await this.paymentReceiveService.editPaymentReceive(
tenantId, paymentReceiveId, paymentReceive,
);
return res.status(200).send({ id: paymentReceiveId });
} catch (error) {
next(error);
}
}
/**
@@ -363,22 +173,22 @@ export default class PaymentReceivesController extends BaseController {
* @param {Request} req
* @param {Response} res
*/
async deletePaymentReceive(req: Request, res: Response) {
async deletePaymentReceive(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const { id: paymentReceiveId } = req.params;
const { PaymentReceive } = req.models;
const storedPaymentReceive = await PaymentReceive.query()
.where('id', paymentReceiveId)
.withGraphFetched('entries')
.first();
await this.paymentReceiveService.deletePaymentReceive(
tenantId,
paymentReceiveId,
storedPaymentReceive
);
return res.status(200).send({ id: paymentReceiveId });
try {
await this.paymentReceiveService.deletePaymentReceive(
tenantId,
paymentReceiveId,
);
return res.status(200).send({
id: paymentReceiveId,
message: 'The payment receive has been edited successfully',
});
} catch (error) {
next(error);
}
}
/**
@@ -387,12 +197,18 @@ export default class PaymentReceivesController extends BaseController {
* @param {Request} req -
* @param {Response} res -
*/
async getPaymentReceive(req: Request, res: Response) {
async getPaymentReceive(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const { id: paymentReceiveId } = req.params;
const paymentReceive = await PaymentReceiveService.getPaymentReceive(
paymentReceiveId
);
return res.status(200).send({ paymentReceive });
try {
const paymentReceive = await this.paymentReceiveService.getPaymentReceive(
tenantId, paymentReceiveId
);
return res.status(200).send({ paymentReceive });
} catch (error) {
next(error);
}
}
/**
@@ -401,7 +217,88 @@ export default class PaymentReceivesController extends BaseController {
* @param {Response} res
* @return {Response}
*/
async getPaymentReceiveList(req: Request, res: Response) {
async getPaymentReceiveList(req: Request, res: Response, next: NextFunction) {
const { tenantId } = 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 {
const {
paymentReceives,
pagination,
filterMeta,
} = await this.paymentReceiveService.listPaymentReceives(tenantId, filter);
return res.status(200).send({
payment_receives: paymentReceives,
pagination: this.transfromToResponse(pagination),
filter_meta: this.transfromToResponse(filterMeta),
});
} catch (error) {
next(error);
}
}
/**
* Handles service errors.
* @param error
* @param req
* @param res
* @param next
*/
handleServiceErrors(error: Error, req: Request, res: Response, next: NextFunction) {
if (error instanceof ServiceError) {
if (error.errorType === 'DEPOSIT_ACCOUNT_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'DEPOSIT.ACCOUNT.NOT.EXISTS', code: 300 }],
});
}
if (error.errorType === 'PAYMENT_RECEIVE_NO_EXISTS') {
return res.boom.badRequest(null, {
errors: [{ type: 'PAYMENT_RECEIVE_NO_EXISTS', code: 300 }],
});
}
if (error.errorType === 'PAYMENT_RECEIVE_NOT_EXISTS') {
return res.boom.badRequest(null, {
errors: [{ type: 'PAYMENT_RECEIVE_NOT_EXISTS', code: 300 }],
});
}
if (error.errorType === 'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE') {
return res.boom.badRequest(null, {
errors: [{ type: 'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE', code: 300 }],
});
}
if (error.errorType === 'INVALID_PAYMENT_AMOUNT_INVALID') {
return res.boom.badRequest(null, {
errors: [{ type: 'INVALID_PAYMENT_AMOUNT', code: 300 }],
});
}
if (error.errorType === 'INVOICES_IDS_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'INVOICES_IDS_NOT_FOUND', code: 300 }],
});
}
if (error.errorType === 'ENTRIES_IDS_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ENTRIES_IDS_NOT_FOUND', code: 300 }],
});
}
if (error.errorType === 'contact_not_found') {
return res.boom.badRequest(null, {
errors: [{ type: 'CUSTOMER_NOT_FOUND', code: 300 }],
});
}
console.log(error.errorType);
}
next(error);
}
}

View File

@@ -1,6 +1,5 @@
import { Router, Request, Response, NextFunction } from 'express';
import { check, param, query, matchedData } from 'express-validator';
import { difference } from 'lodash';
import { check, param, query } from 'express-validator';
import { raw } from 'objection';
import { Service, Inject } from 'typedi';
import BaseController from '../BaseController';
@@ -8,6 +7,7 @@ import asyncMiddleware from 'api/middleware/asyncMiddleware';
import SaleInvoiceService from 'services/Sales/SalesInvoices';
import ItemsService from 'services/Items/ItemsService';
import DynamicListingService from 'services/DynamicListing/DynamicListService';
import { ServiceError } from 'exceptions';
import { ISaleInvoiceOTD, ISalesInvoicesFilter } from 'interfaces';
@Service()
@@ -31,11 +31,8 @@ export default class SaleInvoicesController extends BaseController{
'/',
this.saleInvoiceValidationSchema,
this.validationResult,
asyncMiddleware(this.validateInvoiceCustomerExistance.bind(this)),
// asyncMiddleware(this.validateInvoiceNumberUnique.bind(this)),
asyncMiddleware(this.validateInvoiceItemsIdsExistance.bind(this)),
asyncMiddleware(this.validateNonSellableEntriesItems.bind(this)),
asyncMiddleware(this.newSaleInvoice.bind(this))
asyncMiddleware(this.newSaleInvoice.bind(this)),
this.handleServiceErrors,
);
router.post(
'/:id',
@@ -44,39 +41,36 @@ export default class SaleInvoicesController extends BaseController{
...this.specificSaleInvoiceValidation,
],
this.validationResult,
asyncMiddleware(this.validateInvoiceExistance.bind(this)),
asyncMiddleware(this.validateInvoiceCustomerExistance.bind(this)),
// asyncMiddleware(this.validateInvoiceNumberUnique.bind(this)),
asyncMiddleware(this.validateInvoiceItemsIdsExistance.bind(this)),
asyncMiddleware(this.valdiateInvoiceEntriesIdsExistance.bind(this)),
asyncMiddleware(this.validateEntriesIdsExistance.bind(this)),
asyncMiddleware(this.validateNonSellableEntriesItems.bind(this)),
asyncMiddleware(this.editSaleInvoice.bind(this))
asyncMiddleware(this.editSaleInvoice.bind(this)),
this.handleServiceErrors,
);
router.delete(
'/:id',
this.specificSaleInvoiceValidation,
this.validationResult,
asyncMiddleware(this.validateInvoiceExistance.bind(this)),
asyncMiddleware(this.deleteSaleInvoice.bind(this))
asyncMiddleware(this.deleteSaleInvoice.bind(this)),
this.handleServiceErrors,
);
router.get(
'/due_invoices',
this.dueSalesInvoicesListValidationSchema,
asyncMiddleware(this.getDueSalesInvoice.bind(this)),
this.handleServiceErrors,
);
router.get(
'/:id',
this.specificSaleInvoiceValidation,
this.validationResult,
asyncMiddleware(this.validateInvoiceExistance.bind(this)),
asyncMiddleware(this.getSaleInvoice.bind(this))
asyncMiddleware(this.getSaleInvoice.bind(this)),
this.handleServiceErrors,
);
router.get(
'/',
this.saleInvoiceListValidationSchema,
this.validationResult,
asyncMiddleware(this.getSalesInvoices.bind(this))
asyncMiddleware(this.getSalesInvoices.bind(this)),
this.handleServiceErrors,
this.dynamicListService.handlerErrorsToResponse,
)
return router;
}
@@ -133,177 +127,8 @@ export default class SaleInvoicesController extends BaseController{
*/
get dueSalesInvoicesListValidationSchema() {
return [
query('customer_id').optional().isNumeric().toInt(),
]
}
/**
* Validate whether sale invoice customer exists on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateInvoiceCustomerExistance(req: Request, res: Response, next: Function) {
const saleInvoice = { ...req.body };
const { Customer } = req.models;
const isCustomerIDExists = await Customer.query().findById(saleInvoice.customer_id);
if (!isCustomerIDExists) {
return res.status(400).send({
errors: [{ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 }],
});
}
next();
}
/**
* Validate whether sale invoice items ids esits on the storage.
* @param {Request} req -
* @param {Response} res -
* @param {Function} next -
*/
async validateInvoiceItemsIdsExistance(req: Request, res: Response, next: Function) {
const { tenantId } = req;
const saleInvoice = { ...req.body };
const entriesItemsIds = saleInvoice.entries.map((e) => e.item_id);
const isItemsIdsExists = await this.itemsService.isItemsIdsExists(
tenantId, entriesItemsIds,
);
if (isItemsIdsExists.length > 0) {
return res.status(400).send({
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 300 }],
});
}
next();
}
/**
*
* Validate whether sale invoice number unqiue on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateInvoiceNumberUnique(req: Request, res: Response, next: Function) {
const { tenantId } = req;
const saleInvoice = { ...req.body };
const isInvoiceNoExists = await this.saleInvoiceService.isSaleInvoiceNumberExists(
tenantId,
saleInvoice.invoice_no,
req.params.id
);
if (isInvoiceNoExists) {
return res
.status(400)
.send({
errors: [{ type: 'SALE.INVOICE.NUMBER.IS.EXISTS', code: 200 }],
});
}
next();
}
/**
* Validate whether sale invoice exists on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateInvoiceExistance(req: Request, res: Response, next: Function) {
const { id: saleInvoiceId } = req.params;
const { tenantId } = req;
const isSaleInvoiceExists = await this.saleInvoiceService.isSaleInvoiceExists(
tenantId, saleInvoiceId,
);
if (!isSaleInvoiceExists) {
return res
.status(404)
.send({ errors: [{ type: 'SALE.INVOICE.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 { tenantId } = req;
const saleInvoice = { ...req.body };
const entriesItemsIds = saleInvoice.entries.map((e) => e.item_id);
const isItemsIdsExists = await this.itemsService.isItemsIdsExists(
tenantId, entriesItemsIds,
);
if (isItemsIdsExists.length > 0) {
return res.status(400).send({
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 300 }],
});
}
next();
}
/**
* Validate whether the sale estimate entries IDs exist on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateEntriesIdsExistance(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 storedEntries = await ItemEntry.query()
.whereIn('reference_id', [saleInvoiceId])
.whereIn('reference_type', ['SaleInvoice']);
const storedEntriesIds = storedEntries.map((entry) => entry.id);
const notFoundEntriesIds = difference(
entriesIds,
storedEntriesIds,
);
if (notFoundEntriesIds.length > 0) {
return res.boom.badRequest(null, {
errors: [{ type: 'SALE.INVOICE.ENTRIES.IDS.NOT.FOUND', code: 500 }],
});
}
next();
}
/**
* Validate the entries items that not sellable.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateNonSellableEntriesItems(req: Request, res: Response, next: Function) {
const { Item } = req.models;
const saleInvoice = { ...req.body };
const itemsIds = saleInvoice.entries.map(e => e.item_id);
const sellableItems = await Item.query()
.where('sellable', true)
.whereIn('id', itemsIds);
const sellableItemsIds = sellableItems.map((item) => item.id);
const notSellableItems = difference(itemsIds, sellableItemsIds);
if (notSellableItems.length > 0) {
return res.status(400).send({
errors: [{ type: 'NOT.SELLABLE.ITEMS', code: 600 }],
});
}
next();
query('customer_id').optional().isNumeric().toInt(),
];
}
/**
@@ -372,14 +197,18 @@ export default class SaleInvoicesController extends BaseController{
* @param {Request} req
* @param {Response} res
*/
async getSaleInvoice(req: Request, res: Response) {
async getSaleInvoice(req: Request, res: Response, next: NextFunction) {
const { id: saleInvoiceId } = req.params;
const { tenantId } = req;
const saleInvoice = await this.saleInvoiceService.getSaleInvoiceWithEntries(
tenantId, saleInvoiceId,
);
return res.status(200).send({ sale_invoice: saleInvoice });
try {
const saleInvoice = await this.saleInvoiceService.getSaleInvoiceWithEntries(
tenantId, saleInvoiceId,
);
return res.status(200).send({ sale_invoice: saleInvoice });
} catch (error) {
next(error);
}
}
/**
@@ -422,12 +251,20 @@ export default class SaleInvoicesController extends BaseController{
* @param {Function} next
*/
public async getSalesInvoices(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req.params;
const salesInvoicesFilter: ISalesInvoicesFilter = req.query;
const { tenantId } = req;
const filter: ISalesInvoicesFilter = {
filterRoles: [],
sortOrder: 'asc',
columnSortBy: 'name',
...this.matchedQueryData(req),
};
if (filter.stringifiedFilterRoles) {
filter.filterRoles = JSON.parse(filter.stringifiedFilterRoles);
}
try {
const { salesInvoices, filterMeta, pagination } = await this.saleInvoiceService.salesInvoicesList(
tenantId, salesInvoicesFilter,
tenantId, filter,
);
return res.status(200).send({
sales_invoices: salesInvoices,
@@ -438,4 +275,63 @@ export default class SaleInvoicesController extends BaseController{
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 === 'INVOICE_NUMBER_NOT_UNIQUE') {
return res.boom.badRequest(null, {
errors: [{ type: 'SALE.INVOICE.NUMBER.IS.EXISTS', code: 200 }],
});
}
if (error.errorType === 'SALE_INVOICE_NOT_FOUND') {
return res.status(404).send({
errors: [{ type: 'SALE.INVOICE.NOT.FOUND', code: 200 }]
});
}
if (error.errorType === 'ENTRIES_ITEMS_IDS_NOT_EXISTS') {
return res.boom.badRequest(null, {
errors: [{ type: 'ENTRIES_ITEMS_IDS_NOT_EXISTS', code: 200 }],
});
}
if (error.errorType === 'NOT_SELLABLE_ITEMS') {
return res.boom.badRequest(null, {
errors: [{ type: 'NOT_SELLABLE_ITEMS', code: 200 }],
});
}
if (error.errorType === 'SALE_INVOICE_NO_NOT_UNIQUE') {
return res.boom.badRequest(null, {
errors: [{ type: 'SALE_INVOICE_NO_NOT_UNIQUE', code: 200 }],
});
}
if (error.errorType === 'ITEMS_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ITEMS_NOT_FOUND', code: 200 }],
});
}
if (error.errorType === 'ENTRIES_IDS_NOT_FOUND') {
return res.boom.badRequest(null, {
errors: [{ type: 'ENTRIES_IDS_NOT_FOUND', code: 200 }],
});
}
if (error.errorType === 'NOT_SELL_ABLE_ITEMS') {
return res.boom.badRequest(null, {
errors: [{ type: 'NOT_SELL_ABLE_ITEMS', code: 200 }],
});
}
if (error.errorType === 'contact_not_found') {
return res.boom.badRequest(null, {
errors: [{ type: 'CUSTOMER_NOT_FOUND', code: 200 }],
});
}
}
console.log(error.errorType);
next(error);
}
}

View File

@@ -13,10 +13,10 @@ export default class SalesController {
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('/receipts', Container.get(SalesReceipts).router());
// router.use('/payment_receives', Container.get(PaymentReceives).router());
router.use('/payment_receives', Container.get(PaymentReceives).router());
return router;
}