fix: handle expense already published error.

fix: expense validation schema.
This commit is contained in:
Ahmed Bouhuolia
2020-11-30 12:44:34 +02:00
parent ad5a6b3eb9
commit 5c5a9438ee
2 changed files with 158 additions and 114 deletions

View File

@@ -1,12 +1,13 @@
import { Inject, Service } from "typedi"; import { Inject, Service } from 'typedi';
import { check, param, query } from 'express-validator'; import { check, param, query } from 'express-validator';
import { Router, Request, Response, NextFunction } from 'express'; import { Router, Request, Response, NextFunction } from 'express';
import asyncMiddleware from 'api/middleware/asyncMiddleware'; import asyncMiddleware from 'api/middleware/asyncMiddleware';
import BaseController from "api/controllers/BaseController"; import BaseController from 'api/controllers/BaseController';
import ExpensesService from "services/Expenses/ExpensesService"; 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 { DATATYPES_LENGTH } from 'data/DataTypes';
@Service() @Service()
export default class ExpensesController extends BaseController { export default class ExpensesController extends BaseController {
@@ -23,68 +24,60 @@ export default class ExpensesController extends BaseController {
const router = Router(); const router = Router();
router.post( router.post(
'/', [ '/',
...this.expenseDTOSchema, [...this.expenseDTOSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.newExpense.bind(this)), asyncMiddleware(this.newExpense.bind(this)),
this.catchServiceErrors, this.catchServiceErrors
); );
router.post( router.post(
'/publish', [ '/publish',
...this.bulkSelectSchema, [...this.bulkSelectSchema],
],
this.bulkPublishExpenses.bind(this), this.bulkPublishExpenses.bind(this),
this.catchServiceErrors, this.catchServiceErrors
); );
router.post( router.post(
'/:id/publish', [ '/:id/publish',
...this.expenseParamSchema, [...this.expenseParamSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.publishExpense.bind(this)), asyncMiddleware(this.publishExpense.bind(this)),
this.catchServiceErrors, this.catchServiceErrors
); );
router.post( router.post(
'/:id', [ '/:id',
...this.expenseDTOSchema, [...this.expenseDTOSchema, ...this.expenseParamSchema],
...this.expenseParamSchema,
],
this.validationResult, this.validationResult,
asyncMiddleware(this.editExpense.bind(this)), asyncMiddleware(this.editExpense.bind(this)),
this.catchServiceErrors, this.catchServiceErrors
); );
router.delete( router.delete(
'/:id', [ '/:id',
...this.expenseParamSchema, [...this.expenseParamSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.deleteExpense.bind(this)), asyncMiddleware(this.deleteExpense.bind(this)),
this.catchServiceErrors, this.catchServiceErrors
); );
router.delete('/', [ router.delete(
...this.bulkSelectSchema, '/',
], [...this.bulkSelectSchema],
this.validationResult, this.validationResult,
asyncMiddleware(this.bulkDeleteExpenses.bind(this)), asyncMiddleware(this.bulkDeleteExpenses.bind(this)),
this.catchServiceErrors, this.catchServiceErrors
); );
router.get( router.get(
'/', [ '/',
...this.expensesListSchema, [...this.expensesListSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.getExpensesList.bind(this)), asyncMiddleware(this.getExpensesList.bind(this)),
this.dynamicListService.handlerErrorsToResponse, this.dynamicListService.handlerErrorsToResponse,
this.catchServiceErrors, this.catchServiceErrors
); );
router.get( router.get(
'/:id', [ '/:id',
this.expenseParamSchema, [this.expenseParamSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.getExpense.bind(this)), asyncMiddleware(this.getExpense.bind(this)),
this.catchServiceErrors, this.catchServiceErrors
); );
return router; return router;
} }
@@ -94,26 +87,42 @@ export default class ExpensesController extends BaseController {
*/ */
get expenseDTOSchema() { get expenseDTOSchema() {
return [ return [
check('reference_no').optional().trim().escape().isLength({ max: 255 }), check('reference_no')
.optional({ nullable: true })
.trim()
.escape()
.isLength({ max: DATATYPES_LENGTH.STRING }),
check('payment_date').exists().isISO8601(), check('payment_date').exists().isISO8601(),
check('payment_account_id').exists().isNumeric().toInt(), check('payment_account_id')
check('description').optional(), .exists()
check('currency_code').optional(), .isInt({ max: DATATYPES_LENGTH.INT_10 })
check('exchange_rate').optional().isNumeric().toFloat(), .toInt(),
check('description')
.optional({ nullable: true })
.isString()
.isLength({ max: DATATYPES_LENGTH.TEXT }),
check('currency_code').optional().isString().isLength({ max: 3 }),
check('exchange_rate').optional({ nullable: true }).isNumeric().toFloat(),
check('publish').optional().isBoolean().toBoolean(), check('publish').optional().isBoolean().toBoolean(),
check('categories').exists().isArray({ min: 1 }), check('categories').exists().isArray({ min: 1 }),
check('categories.*.index').exists().isNumeric().toInt(), check('categories.*.index')
check('categories.*.expense_account_id').exists().isNumeric().toInt(), .exists()
.isInt({ max: DATATYPES_LENGTH.INT_10 })
.toInt(),
check('categories.*.expense_account_id')
.exists()
.isInt({ max: DATATYPES_LENGTH.INT_10 })
.toInt(),
check('categories.*.amount') check('categories.*.amount')
.optional({ nullable: true }) .optional({ nullable: true })
.isNumeric() .isFloat({ max: DATATYPES_LENGTH.DECIMAL_13_3 }) // 13, 3
.isDecimal()
.isFloat({ max: 9999999999.999 }) // 13, 3
.toFloat(), .toFloat(),
check('categories.*.description').optional().trim().escape().isLength({ check('categories.*.description')
max: 255, .optional()
}), .trim()
.escape()
.isLength({ max: DATATYPES_LENGTH.STRING }),
]; ];
} }
@@ -121,9 +130,7 @@ export default class ExpensesController extends BaseController {
* Expense param schema. * Expense param schema.
*/ */
get expenseParamSchema() { get expenseParamSchema() {
return [ return [param('id').exists().isNumeric().toInt()];
param('id').exists().isNumeric().toInt(),
];
} }
get bulkSelectSchema() { get bulkSelectSchema() {
@@ -148,16 +155,20 @@ export default class ExpensesController extends BaseController {
/** /**
* Creates a new expense on * Creates a new expense on
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async newExpense(req: Request, res: Response, next: NextFunction) { async newExpense(req: Request, res: Response, next: NextFunction) {
const expenseDTO: IExpenseDTO = this.matchedBodyData(req); const expenseDTO: IExpenseDTO = this.matchedBodyData(req);
const { tenantId, user } = req; const { tenantId, user } = req;
try { try {
const expense = await this.expensesService.newExpense(tenantId, expenseDTO, user); const expense = await this.expensesService.newExpense(
tenantId,
expenseDTO,
user
);
return res.status(200).send({ id: expense.id }); return res.status(200).send({ id: expense.id });
} catch (error) { } catch (error) {
next(error); next(error);
@@ -166,9 +177,9 @@ export default class ExpensesController extends BaseController {
/** /**
* Edits details of the given expense. * Edits details of the given expense.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async editExpense(req: Request, res: Response, next: NextFunction) { async editExpense(req: Request, res: Response, next: NextFunction) {
const { id: expenseId } = req.params; const { id: expenseId } = req.params;
@@ -176,18 +187,23 @@ export default class ExpensesController extends BaseController {
const { tenantId, user } = req; const { tenantId, user } = req;
try { try {
await this.expensesService.editExpense(tenantId, expenseId, expenseDTO, user); await this.expensesService.editExpense(
tenantId,
expenseId,
expenseDTO,
user
);
return res.status(200).send({ id: expenseId }); return res.status(200).send({ id: expenseId });
} catch (error) { } catch (error) {
next(error) next(error);
} }
} }
/** /**
* Deletes the given expense. * Deletes the given expense.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async deleteExpense(req: Request, res: Response, next: NextFunction) { async deleteExpense(req: Request, res: Response, next: NextFunction) {
const { tenantId, user } = req; const { tenantId, user } = req;
@@ -195,25 +211,33 @@ export default class ExpensesController extends BaseController {
try { try {
await this.expensesService.deleteExpense(tenantId, expenseId, user); await this.expensesService.deleteExpense(tenantId, expenseId, user);
return res.status(200).send({ id: expenseId });
return res.status(200).send({
id: expenseId,
message: 'The expense has been deleted.',
});
} catch (error) { } catch (error) {
next(error) next(error);
} }
} }
/** /**
* Publishs the given expense. * Publishs the given expense.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async publishExpense(req: Request, res: Response, next: NextFunction) { async publishExpense(req: Request, res: Response, next: NextFunction) {
const { tenantId, user } = req; const { tenantId, user } = req;
const { id: expenseId } = req.params; const { id: expenseId } = req.params;
try { try {
await this.expensesService.publishExpense(tenantId, expenseId, user) await this.expensesService.publishExpense(tenantId, expenseId, user);
return res.status(200).send({ });
return res.status(200).send({
id: expenseId,
message: 'The expense has been published',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -221,16 +245,20 @@ export default class ExpensesController extends BaseController {
/** /**
* Deletes the expenses in bulk. * Deletes the expenses in bulk.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async bulkDeleteExpenses(req: Request, res: Response, next: NextFunction) { async bulkDeleteExpenses(req: Request, res: Response, next: NextFunction) {
const { tenantId, user } = req; const { tenantId, user } = req;
const { ids: expensesIds } = req.params; const { ids: expensesIds } = req.params;
try { try {
await this.expensesService.deleteBulkExpenses(tenantId, expensesIds, user); await this.expensesService.deleteBulkExpenses(
tenantId,
expensesIds,
user
);
return res.status(200).send({ ids: expensesIds }); return res.status(200).send({ ids: expensesIds });
} catch (error) { } catch (error) {
next(error); next(error);
@@ -239,16 +267,20 @@ export default class ExpensesController extends BaseController {
/** /**
* Publishes the given expenses in bulk. * Publishes the given expenses in bulk.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async bulkPublishExpenses(req: Request, res: Response, next: NextFunction) { async bulkPublishExpenses(req: Request, res: Response, next: NextFunction) {
const { tenantId, user } = req; const { tenantId, user } = req;
const { ids: expensesIds } = req.query; const { ids: expensesIds } = req.query;
try { try {
await this.expensesService.publishBulkExpenses(tenantId, expensesIds, user); await this.expensesService.publishBulkExpenses(
tenantId,
expensesIds,
user
);
return res.status(200).send({}); return res.status(200).send({});
} catch (error) { } catch (error) {
next(error); next(error);
@@ -257,8 +289,8 @@ export default class ExpensesController extends BaseController {
/** /**
* Retrieve expneses list. * Retrieve expneses list.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async getExpensesList(req: Request, res: Response, next: NextFunction) { async getExpensesList(req: Request, res: Response, next: NextFunction) {
@@ -276,7 +308,11 @@ export default class ExpensesController extends BaseController {
} }
try { try {
const { expenses, pagination, filterMeta } = await this.expensesService.getExpensesList(tenantId, filter); const {
expenses,
pagination,
filterMeta,
} = await this.expensesService.getExpensesList(tenantId, filter);
return res.status(200).send({ return res.status(200).send({
expenses, expenses,
@@ -290,16 +326,19 @@ export default class ExpensesController extends BaseController {
/** /**
* Retrieve expense details. * Retrieve expense details.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async getExpense(req: Request, res: Response, next: NextFunction) { async getExpense(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId } = req;
const { id: expenseId } = req.params; const { id: expenseId } = req.params;
try { try {
const expense = await this.expensesService.getExpense(tenantId, expenseId); const expense = await this.expensesService.getExpense(
tenantId,
expenseId
);
return res.status(200).send({ expense }); return res.status(200).send({ expense });
} catch (error) { } catch (error) {
next(error); next(error);
@@ -308,47 +347,52 @@ export default class ExpensesController extends BaseController {
/** /**
* Transform service errors to api response errors. * Transform service errors to api response errors.
* @param {Response} res * @param {Response} res
* @param {ServiceError} error * @param {ServiceError} error
*/ */
catchServiceErrors(error: Error, req: Request, res: Response, next: NextFunction) { catchServiceErrors(
error: Error,
req: Request,
res: Response,
next: NextFunction
) {
if (error instanceof ServiceError) { if (error instanceof ServiceError) {
if (error.errorType === 'expense_not_found') { if (error.errorType === 'expense_not_found') {
return res.boom.badRequest( return res.boom.badRequest('Expense not found.', {
'Expense not found.', errors: [{ type: 'EXPENSE_NOT_FOUND', code: 100 }],
{ errors: [{ type: 'EXPENSE_NOT_FOUND', code: 100 }] } });
);
} }
if (error.errorType === 'total_amount_equals_zero') { if (error.errorType === 'total_amount_equals_zero') {
return res.boom.badRequest( return res.boom.badRequest('Expense total should not equal zero.', {
'Expense total should not equal zero.', errors: [{ type: 'TOTAL.AMOUNT.EQUALS.ZERO', code: 200 }],
{ errors: [{ type: 'TOTAL.AMOUNT.EQUALS.ZERO', code: 200 }] }, });
);
} }
if (error.errorType === 'payment_account_not_found') { if (error.errorType === 'payment_account_not_found') {
return res.boom.badRequest( return res.boom.badRequest('Payment account not found.', {
'Payment account not found.', errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 300 }],
{ errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 300 }] }, });
);
} }
if (error.errorType === 'some_expenses_not_found') { if (error.errorType === 'some_expenses_not_found') {
return res.boom.badRequest( return res.boom.badRequest('Some expense accounts not found.', {
'Some expense accounts not found.', errors: [{ type: 'SOME.EXPENSE.ACCOUNTS.NOT.FOUND', code: 400 }],
{ errors: [{ type: 'SOME.EXPENSE.ACCOUNTS.NOT.FOUND', code: 400 }] }, });
);
} }
if (error.errorType === 'payment_account_has_invalid_type') { if (error.errorType === 'payment_account_has_invalid_type') {
return res.boom.badRequest( return res.boom.badRequest('Payment account has invalid type.', {
'Payment account has invalid type.', errors: [{ type: 'PAYMENT.ACCOUNT.HAS.INVALID.TYPE', code: 500 }],
{ errors: [{ type: 'PAYMENT.ACCOUNT.HAS.INVALID.TYPE', code: 500 }], }, });
);
} }
if (error.errorType === 'expenses_account_has_invalid_type') { if (error.errorType === 'expenses_account_has_invalid_type') {
return res.boom.badRequest(null, { return res.boom.badRequest(null, {
errors: [{ type: 'EXPENSES.ACCOUNT.HAS.INVALID.TYPE', code: 600 }] errors: [{ type: 'EXPENSES.ACCOUNT.HAS.INVALID.TYPE', code: 600 }],
});
}
if (error.errorType === 'expense_already_published') {
return res.boom.badRequest(null, {
errors: [{ type: 'EXPENSE_ALREADY_PUBLISHED', code: 700 }],
}); });
} }
} }
next(error); next(error);
} }
} }

View File

@@ -20,7 +20,7 @@ const ERRORS = {
TOTAL_AMOUNT_EQUALS_ZERO: 'total_amount_equals_zero', TOTAL_AMOUNT_EQUALS_ZERO: 'total_amount_equals_zero',
PAYMENT_ACCOUNT_HAS_INVALID_TYPE: 'payment_account_has_invalid_type', PAYMENT_ACCOUNT_HAS_INVALID_TYPE: 'payment_account_has_invalid_type',
EXPENSES_ACCOUNT_HAS_INVALID_TYPE: 'expenses_account_has_invalid_type', EXPENSES_ACCOUNT_HAS_INVALID_TYPE: 'expenses_account_has_invalid_type',
EXPENSE_ACCOUNT_ALREADY_PUBLISED: 'expense_already_published', EXPENSE_ALREADY_PUBLISHED: 'expense_already_published',
}; };
@Service() @Service()
@@ -219,7 +219,7 @@ export default class ExpensesService implements IExpensesService {
*/ */
private validateExpenseIsNotPublished(expense: IExpense) { private validateExpenseIsNotPublished(expense: IExpense) {
if (expense.publishedAt) { if (expense.publishedAt) {
throw new ServiceError(ERRORS.EXPENSE_ACCOUNT_ALREADY_PUBLISED); throw new ServiceError(ERRORS.EXPENSE_ALREADY_PUBLISHED);
} }
} }