fix: item opening quantity and cost validation schema.

This commit is contained in:
a.bouhuolia
2020-12-24 12:47:17 +02:00
parent af96d4bde4
commit de9f6d9521

View File

@@ -1,6 +1,6 @@
import { Inject, Service } from 'typedi'; import { Inject, Service } from 'typedi';
import { Router, Request, Response, NextFunction } from 'express'; import { Router, Request, Response, NextFunction } from 'express';
import { check, param, query, ValidationChain } from 'express-validator'; import { check, param, body, query, ValidationChain } from 'express-validator';
import asyncMiddleware from 'api/middleware/asyncMiddleware'; import asyncMiddleware from 'api/middleware/asyncMiddleware';
import ItemsService from 'services/Items/ItemsService'; import ItemsService from 'services/Items/ItemsService';
import BaseController from 'api/controllers/BaseController'; import BaseController from 'api/controllers/BaseController';
@@ -23,70 +23,62 @@ export default class ItemsController extends BaseController {
router() { router() {
const router = Router(); const router = Router();
router.post('/', [ router.post(
...this.validateItemSchema, '/',
...this.validateNewItemSchema, [...this.validateItemSchema, ...this.validateNewItemSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.newItem.bind(this)), asyncMiddleware(this.newItem.bind(this)),
this.handlerServiceErrors, this.handlerServiceErrors
); );
router.post( router.post(
'/:id/activate', [ '/:id/activate',
...this.validateSpecificItemSchema, [...this.validateSpecificItemSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.activateItem.bind(this)), asyncMiddleware(this.activateItem.bind(this)),
this.handlerServiceErrors this.handlerServiceErrors
); );
router.post( router.post(
'/:id/inactivate', [ '/:id/inactivate',
...this.validateSpecificItemSchema, [...this.validateSpecificItemSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.inactivateItem.bind(this)), asyncMiddleware(this.inactivateItem.bind(this)),
this.handlerServiceErrors, this.handlerServiceErrors
) );
router.post( router.post(
'/:id', [ '/:id',
...this.validateItemSchema, [...this.validateItemSchema, ...this.validateSpecificItemSchema],
...this.validateSpecificItemSchema,
],
this.validationResult, this.validationResult,
asyncMiddleware(this.editItem.bind(this)), asyncMiddleware(this.editItem.bind(this)),
this.handlerServiceErrors, this.handlerServiceErrors
); );
router.delete('/', [ router.delete(
...this.validateBulkSelectSchema, '/',
], [...this.validateBulkSelectSchema],
this.validationResult, this.validationResult,
asyncMiddleware(this.bulkDeleteItems.bind(this)), asyncMiddleware(this.bulkDeleteItems.bind(this)),
this.handlerServiceErrors this.handlerServiceErrors
); );
router.delete( router.delete(
'/:id', [ '/:id',
...this.validateSpecificItemSchema, [...this.validateSpecificItemSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.deleteItem.bind(this)), asyncMiddleware(this.deleteItem.bind(this)),
this.handlerServiceErrors, this.handlerServiceErrors
); );
router.get( router.get(
'/:id', [ '/:id',
...this.validateSpecificItemSchema, [...this.validateSpecificItemSchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.getItem.bind(this)), asyncMiddleware(this.getItem.bind(this)),
this.handlerServiceErrors, this.handlerServiceErrors
); );
router.get( router.get(
'/', [ '/',
...this.validateListQuerySchema, [...this.validateListQuerySchema],
],
this.validationResult, this.validationResult,
asyncMiddleware(this.getItemsList.bind(this)), asyncMiddleware(this.getItemsList.bind(this)),
this.dynamicListService.handlerErrorsToResponse, this.dynamicListService.handlerErrorsToResponse,
this.handlerServiceErrors, this.handlerServiceErrors
); );
return router; return router;
} }
@@ -97,8 +89,21 @@ export default class ItemsController extends BaseController {
get validateNewItemSchema(): ValidationChain[] { get validateNewItemSchema(): ValidationChain[] {
return [ return [
check('opening_quantity').default(0).isInt({ min: 0 }).toInt(), check('opening_quantity').default(0).isInt({ min: 0 }).toInt(),
check('opening_cost').optional({ nullable: true }).isFloat({ min: 0 }).toFloat(), check('opening_cost')
check('opening_date').optional({ nullable: true }).isISO8601(), .if(body('opening_quantity').exists().isInt({ min: 1 }))
.exists()
.isFloat(),
check('opening_cost')
.optional({ nullable: true })
.isFloat({ min: 0 })
.toFloat(),
check('opening_date')
.if(
body('opening_quantity').exists().isFloat({ min: 1 }) ||
body('opening_cost').exists().isFloat({ min: 1 })
)
.exists(),
check('opening_date').optional({ nullable: true }).isISO8601().toDate(),
]; ];
} }
@@ -107,8 +112,12 @@ export default class ItemsController extends BaseController {
*/ */
get validateItemSchema(): ValidationChain[] { get validateItemSchema(): ValidationChain[] {
return [ return [
check('name').exists().isString().isLength({ max: DATATYPES_LENGTH.STRING }), check('name')
check('type').exists() .exists()
.isString()
.isLength({ max: DATATYPES_LENGTH.STRING }),
check('type')
.exists()
.isString() .isString()
.trim() .trim()
.escape() .escape()
@@ -127,12 +136,11 @@ export default class ItemsController extends BaseController {
.toFloat() .toFloat()
.if(check('purchasable').equals('true')) .if(check('purchasable').equals('true'))
.exists(), .exists(),
check('cost_account_id').if(check('purchasable').equals('true')).exists(),
check('cost_account_id') check('cost_account_id')
.optional({ nullable: true }) .optional({ nullable: true })
.isInt({ min: 0, max: DATATYPES_LENGTH.INT_10 }) .isInt({ min: 0, max: DATATYPES_LENGTH.INT_10 })
.toInt() .toInt(),
.if(check('purchasable').equals('true'))
.exists(),
// Sell attributes. // Sell attributes.
check('sellable').optional().isBoolean().toBoolean(), check('sellable').optional().isBoolean().toBoolean(),
check('sell_price') check('sell_price')
@@ -141,18 +149,18 @@ export default class ItemsController extends BaseController {
.toFloat() .toFloat()
.if(check('sellable').equals('true')) .if(check('sellable').equals('true'))
.exists(), .exists(),
check('sell_account_id').if(check('sellable').equals('true')).exists(),
check('sell_account_id') check('sell_account_id')
.optional({ nullable: true }) .optional({ nullable: true })
.isInt({ min: 0, max: DATATYPES_LENGTH.INT_10 }) .isInt({ min: 0, max: DATATYPES_LENGTH.INT_10 })
.toInt() .toInt(),
.if(check('sellable').equals('true')) check('inventory_account_id')
.if(check('type').equals('inventory'))
.exists(), .exists(),
check('inventory_account_id') check('inventory_account_id')
.optional({ nullable: true }) .optional({ nullable: true })
.isInt({ min: 0, max: DATATYPES_LENGTH.INT_10 }) .isInt({ min: 0, max: DATATYPES_LENGTH.INT_10 })
.toInt() .toInt(),
.if(check('type').equals('inventory'))
.exists(),
check('sell_description') check('sell_description')
.optional({ nullable: true }) .optional({ nullable: true })
.isString() .isString()
@@ -187,9 +195,7 @@ export default class ItemsController extends BaseController {
* @return {ValidationChain[]} * @return {ValidationChain[]}
*/ */
get validateSpecificItemSchema(): ValidationChain[] { get validateSpecificItemSchema(): ValidationChain[] {
return [ return [param('id').exists().isNumeric().toInt()];
param('id').exists().isNumeric().toInt(),
];
} }
/** /**
@@ -216,7 +222,7 @@ export default class ItemsController extends BaseController {
query('custom_view_id').optional().isNumeric().toInt(), query('custom_view_id').optional().isNumeric().toInt(),
query('stringified_filter_roles').optional().isJSON(), query('stringified_filter_roles').optional().isJSON(),
] ];
} }
/** /**
@@ -336,7 +342,7 @@ export default class ItemsController extends BaseController {
} catch (error) { } catch (error) {
console.log(error); console.log(error);
next(error) next(error);
} }
} }
@@ -362,7 +368,7 @@ export default class ItemsController extends BaseController {
const { const {
items, items,
pagination, pagination,
filterMeta filterMeta,
} = await this.itemsService.itemsList(tenantId, filter); } = await this.itemsService.itemsList(tenantId, filter);
return res.status(200).send({ return res.status(200).send({
@@ -404,7 +410,12 @@ export default class ItemsController extends BaseController {
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
handlerServiceErrors(error: Error, req: Request, res: Response, next: NextFunction) { handlerServiceErrors(
error: Error,
req: Request,
res: Response,
next: NextFunction
) {
if (error instanceof ServiceError) { if (error instanceof ServiceError) {
if (error.errorType === 'NOT_FOUND') { if (error.errorType === 'NOT_FOUND') {
return res.status(400).send({ return res.status(400).send({
@@ -479,7 +490,7 @@ export default class ItemsController extends BaseController {
if (error.errorType === 'ITEM_HAS_ASSOCIATED_TRANSACTINS') { if (error.errorType === 'ITEM_HAS_ASSOCIATED_TRANSACTINS') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'ITEM_HAS_ASSOCIATED_TRANSACTINS', code: 320 }], errors: [{ type: 'ITEM_HAS_ASSOCIATED_TRANSACTINS', code: 320 }],
}) });
} }
} }
next(error); next(error);