refactoring: bills service.

refactoring: bills payments made service.
This commit is contained in:
Ahmed Bouhuolia
2020-10-15 15:10:41 +02:00
parent 8713c77289
commit 899ea7a52d
39 changed files with 2192 additions and 1193 deletions

View File

@@ -1,10 +1,9 @@
import { Router, Request, Response } from 'express';
import { Router, Request, Response, NextFunction } from 'express';
import { Service, Inject } from 'typedi';
import { check, param, query, ValidationChain, matchedData } from 'express-validator';
import { difference } from 'lodash';
import { check, param, query, ValidationChain } from 'express-validator';
import asyncMiddleware from 'api/middleware/asyncMiddleware';
import validateMiddleware from 'api/middleware/validateMiddleware';
import { ServiceError } from 'exceptions';
import BaseController from 'api/controllers/BaseController';
import BillPaymentsService from 'services/Purchases/BillPayments';
import AccountsService from 'services/Accounts/AccountsService';
@@ -31,43 +30,34 @@ export default class BillsPayments extends BaseController {
...this.billPaymentSchemaValidation,
],
this.validationResult,
asyncMiddleware(this.validateBillPaymentVendorExistance.bind(this)),
asyncMiddleware(this.validatePaymentAccount.bind(this)),
asyncMiddleware(this.validatePaymentNumber.bind(this)),
asyncMiddleware(this.validateEntriesBillsExistance.bind(this)),
asyncMiddleware(this.validateVendorsDueAmount.bind(this)),
asyncMiddleware(this.createBillPayment.bind(this)),
this.handleServiceError,
);
router.post('/:id', [
...this.billPaymentSchemaValidation,
...this.specificBillPaymentValidateSchema,
],
this.validationResult,
asyncMiddleware(this.validateBillPaymentVendorExistance.bind(this)),
asyncMiddleware(this.validatePaymentAccount.bind(this)),
asyncMiddleware(this.validatePaymentNumber.bind(this)),
asyncMiddleware(this.validateEntriesIdsExistance.bind(this)),
asyncMiddleware(this.validateEntriesBillsExistance.bind(this)),
asyncMiddleware(this.validateVendorsDueAmount.bind(this)),
asyncMiddleware(this.editBillPayment.bind(this)),
this.handleServiceError,
)
router.delete('/:id',
this.specificBillPaymentValidateSchema,
router.delete('/:id', [
...this.specificBillPaymentValidateSchema,
],
this.validationResult,
asyncMiddleware(this.validateBillPaymentExistance.bind(this)),
asyncMiddleware(this.deleteBillPayment.bind(this)),
this.handleServiceError,
);
router.get('/:id',
this.specificBillPaymentValidateSchema,
this.validationResult,
asyncMiddleware(this.validateBillPaymentExistance.bind(this)),
asyncMiddleware(this.getBillPayment.bind(this)),
);
router.get('/',
this.listingValidationSchema,
this.validationResult,
asyncMiddleware(this.getBillsPayments.bind(this))
);
// router.get('/:id',
// this.specificBillPaymentValidateSchema,
// this.validationResult,
// asyncMiddleware(this.getBillPayment.bind(this)),
// );
// router.get('/',
// this.listingValidationSchema,
// this.validationResult,
// asyncMiddleware(this.getBillsPayments.bind(this))
// );
return router;
}
@@ -112,186 +102,6 @@ export default class BillsPayments extends BaseController {
];
}
/**
* Validate whether the bill payment vendor exists on the storage.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateBillPaymentVendorExistance(req: Request, res: Response, next: any ) {
const billPayment = req.body;
const { Vendor } = req.models;
const isVendorExists = await Vendor.query().findById(billPayment.vendor_id);
if (!isVendorExists) {
return res.status(400).send({
errors: [{ type: 'BILL.PAYMENT.VENDOR.NOT.FOUND', code: 500 }],
});
}
next();
}
/**
* Validates the bill payment existance.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validateBillPaymentExistance(req: Request, res: Response, next: any ) {
const { id: billPaymentId } = req.params;
const { BillPayment } = req.models;
const foundBillPayment = await BillPayment.query().findById(billPaymentId);
if (!foundBillPayment) {
return res.status(404).send({
errors: [{ type: 'BILL.PAYMENT.NOT.FOUND', code: 100 }],
});
}
next();
}
/**
* Validates the payment account.
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
async validatePaymentAccount(req: Request, res: Response, next: any) {
const { tenantId } = req;
const billPayment = { ...req.body };
const isAccountExists = await this.accountsService.isAccountExists(
tenantId,
billPayment.payment_account_id
);
if (!isAccountExists) {
return res.status(400).send({
errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 200 }],
});
}
next();
}
/**
* Validates the payment number uniqness.
* @param {Request} req
* @param {Response} res
* @param {Function} res
*/
async validatePaymentNumber(req: Request, res: Response, next: any) {
const billPayment = { ...req.body };
const { id: billPaymentId } = req.params;
const { BillPayment } = req.models;
const foundBillPayment = await BillPayment.query()
.onBuild((builder: any) => {
builder.where('payment_number', billPayment.payment_number)
if (billPaymentId) {
builder.whereNot('id', billPaymentId);
}
})
.first();
if (foundBillPayment) {
return res.status(400).send({
errors: [{ type: 'PAYMENT.NUMBER.NOT.UNIQUE', code: 300 }],
});
}
next();
}
/**
* Validate whether the entries bills ids exist on the storage.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
async validateEntriesBillsExistance(req: Request, res: Response, next: any) {
const { Bill } = req.models;
const billPayment = { ...req.body };
const entriesBillsIds = billPayment.entries.map((e: any) => e.bill_id);
// Retrieve not found bills that associated to the given vendor id.
const notFoundBillsIds = await Bill.getNotFoundBills(
entriesBillsIds,
billPayment.vendor_id,
);
if (notFoundBillsIds.length > 0) {
return res.status(400).send({
errors: [{ type: 'BILLS.IDS.NOT.EXISTS', code: 600 }],
});
}
next();
}
/**
* Validate wether the payment amount bigger than the payable amount.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {void}
*/
async validateVendorsDueAmount(req: Request, res: Response, next: Function) {
const { Bill } = req.models;
const billsIds = req.body.entries.map((entry: any) => entry.bill_id);
const storedBills = await Bill.query()
.whereIn('id', billsIds);
const storedBillsMap = new Map(
storedBills.map((bill: any) => [bill.id, bill]),
);
interface invalidPaymentAmountError{
index: number,
due_amount: number
};
const hasWrongPaymentAmount: invalidPaymentAmountError[] = [];
const { entries } = req.body;
entries.forEach((entry: any, index: number) => {
const entryBill = storedBillsMap.get(entry.bill_id);
const { dueAmount } = entryBill;
if (dueAmount < entry.payment_amount) {
hasWrongPaymentAmount.push({ index, due_amount: dueAmount });
}
});
if (hasWrongPaymentAmount.length > 0) {
return res.status(400).send({
errors: [{ type: 'INVALID.BILL.PAYMENT.AMOUNT', code: 400, 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 { BillPaymentEntry } = req.models;
const billPayment = { id: req.params.id, ...req.body };
const entriesIds = billPayment.entries
.filter((entry: any) => entry.id)
.map((entry: any) => entry.id);
const storedEntries = await BillPaymentEntry.query()
.where('bill_payment_id', billPayment.id);
const storedEntriesIds = storedEntries.map((entry: any) => 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();
}
/**
* Creates a bill payment.
* @async
@@ -299,17 +109,21 @@ export default class BillsPayments extends BaseController {
* @param {Response} res
* @param {Response} res
*/
async createBillPayment(req: Request, res: Response) {
async createBillPayment(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const billPaymentDTO = this.matchedBodyData(req);
const billPayment = matchedData(req, {
locations: ['body'],
includeOptionals: true,
});
const storedPayment = await this.billPaymentService
.createBillPayment(tenantId, billPayment);
try {
const billPayment = await this.billPaymentService.createBillPayment(tenantId, billPaymentDTO);
return res.status(200).send({ id: storedPayment.id });
return res.status(200).send({
id: billPayment.id,
message: 'Payment made has been created successfully.',
});
} catch (error) {
console.log(error);
next(error);
}
}
/**
@@ -317,28 +131,24 @@ export default class BillsPayments extends BaseController {
* @param {Request} req
* @param {Response} res
*/
async editBillPayment(req: Request, res: Response) {
async editBillPayment(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const billPayment = matchedData(req, {
locations: ['body'],
includeOptionals: true,
});
const billPaymentDTO = this.matchedBodyData(req);
const { id: billPaymentId } = req.params;
const { BillPayment } = req.models;
const oldBillPayment = await BillPayment.query()
.where('id', billPaymentId)
.withGraphFetched('entries')
.first();
await this.billPaymentService.editBillPayment(
tenantId,
billPaymentId,
billPayment,
oldBillPayment,
);
return res.status(200).send({ id: 1 });
try {
const paymentMade = await this.billPaymentService.editBillPayment(
tenantId,
billPaymentId,
billPaymentDTO
);
return res.status(200).send({
id: paymentMade.id,
message: 'Payment made has been edited successfully.',
});
} catch (error) {
next(error);
}
}
/**
@@ -348,15 +158,20 @@ export default class BillsPayments extends BaseController {
* @param {Response} res -
* @return {Response} res -
*/
async deleteBillPayment(req: Request, res: Response) {
async deleteBillPayment(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const { id: billPaymentId } = req.params;
const billPayment = req.body;
await this.billPaymentService.deleteBillPayment(tenantId, billPaymentId);
try {
await this.billPaymentService.deleteBillPayment(tenantId, billPaymentId);
return res.status(200).send({ id: billPaymentId });
return res.status(200).send({
id: billPaymentId,
message: 'Payment made has been deleted successfully.',
});
} catch (error) {
next(error);
}
}
/**
@@ -364,7 +179,7 @@ export default class BillsPayments extends BaseController {
* @param {Request} req
* @param {Response} res
*/
async getBillPayment(req: Request, res: Response) {
async getBillPayment(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req;
const { id: billPaymentId } = req.params;
@@ -380,7 +195,7 @@ export default class BillsPayments extends BaseController {
* @param {Response} res -
* @return {Response}
*/
async getBillsPayments(req: Request, res: Response) {
async getBillsPayments(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req.params;
const billPaymentsFilter = this.matchedQueryData(req);
@@ -397,4 +212,68 @@ export default class BillsPayments extends BaseController {
next(error);
}
}
/**
* Handle service errors.
* @param {Error} error
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
*/
handleServiceError(error: Error, req: Request, res: Response, next: NextFunction) {
if (error instanceof ServiceError) {
if (error.errorType === 'PAYMENT_MADE_NOT_FOUND') {
return res.status(404).send({
message: 'Payment made not found.',
});
}
if (error.errorType === 'VENDOR_NOT_FOUND') {
return res.status(400).send({
errors: [{ type: 'BILL.PAYMENT.VENDOR.NOT.FOUND', code: 500 }],
});
}
if (error.errorType === 'PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE') {
return res.status(400).send({
errors: [{ type: 'PAYMENT_ACCOUNT.NOT.CURRENT_ASSET.TYPE', code: 100 }],
});
}
if (error.errorType === 'BILL_PAYMENT_NUMBER_NOT_UNQIUE') {
return res.status(400).send({
errors: [{ type: 'PAYMENT.NUMBER.NOT.UNIQUE', code: 300 }],
});
}
if (error.errorType === 'PAYMENT_ACCOUNT_NOT_FOUND') {
return res.status(400).send({
errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 200 }],
});
}
if (error.errorType === 'PAYMENT_ACCOUNT_NOT_FOUND') {
return res.status(400).send({
errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 200 }],
});
}
if (error.errorType === '') {
return res.status(400).send({
errors: [{ type: 'BILLS.IDS.NOT.EXISTS', code: 600 }],
});
}
if (error.errorType === 'BILL_PAYMENT_ENTRIES_NOT_FOUND') {
return res.status(400).send({
errors: [{ type: 'ENTEIES.IDS.NOT.FOUND', code: 800 }],
});
}
if (error.errorType === 'INVALID_BILL_PAYMENT_AMOUNT') {
return res.status(400).send({
errors: [{ type: 'INVALID_BILL_PAYMENT_AMOUNT', code: 100 }],
});
}
if (error.errorType === 'BILL_ENTRIES_IDS_NOT_FOUND') {
return res.status(400).send({
errors: [{ type: 'BILLS_NOT_FOUND', code: 100 }],
})
}
}
console.log(error);
next(error);
}
}