WIP Metadata class.

This commit is contained in:
Ahmed Bouhuolia
2019-09-08 02:41:46 +02:00
parent 70809cb05c
commit 9a8de9ca7d
29 changed files with 1707 additions and 98 deletions

View File

@@ -0,0 +1,63 @@
import express from 'express';
import { check, validationResult, oneOf } from 'express-validator';
import { difference } from 'lodash';
import asyncMiddleware from '../middleware/asyncMiddleware';
import Account from '@/models/Account';
// import AccountBalance from '@/models/AccountBalance';
export default {
router() {
const router = express.Router();
router.post('/',
this.openingBalnace.validation,
asyncMiddleware(this.openingBalnace.handler));
return router;
},
openingBalnace: {
validation: [
check('accounts').isArray({ min: 1 }),
check('accounts.*.id').exists().isInt(),
oneOf([
check('accounts.*.debit').isNumeric().toFloat(),
check('accounts.*.credit').isNumeric().toFloat(),
]),
],
async handler(req, res) {
const validationErrors = validationResult(req);
if (!validationErrors.isEmpty()) {
return res.boom.badData(null, {
code: 'validation_error', ...validationErrors,
});
}
const { accounts } = req.body;
const accountsIds = accounts.map((account) => account.id);
const accountsCollection = await Account.query((query) => {
query.select(['id']);
query.whereIn('id', accountsIds);
}).fetchAll();
const accountsStoredIds = accountsCollection.map((account) => account.attributes.id);
const notFoundAccountsIds = difference(accountsIds, accountsStoredIds);
const errorReasons = [];
if (notFoundAccountsIds.length > 0) {
const ids = notFoundAccountsIds.map((a) => parseInt(a, 10));
errorReasons.push({ type: 'NOT_FOUND_ACCOUNT', code: 100, ids });
}
if (errorReasons.length > 0) {
return res.boom.badData(null, { errors: errorReasons });
}
return res.status(200).send();
},
},
};

View File

@@ -4,7 +4,7 @@ import asyncMiddleware from '../middleware/asyncMiddleware';
import Account from '@/models/Account';
import AccountBalance from '@/models/AccountBalance';
import AccountType from '@/models/AccountType';
import JWTAuth from '@/http/middleware/jwtAuth';
// import JWTAuth from '@/http/middleware/jwtAuth';
export default {
/**
@@ -13,18 +13,22 @@ export default {
router() {
const router = express.Router();
router.use(JWTAuth);
// router.use(JWTAuth);
router.post('/',
this.newAccount.validation,
asyncMiddleware(this.newAccount.handler));
router.get('/:id',
this.getAccount.validation,
asyncMiddleware(this.getAccount.handler));
router.post('/:id',
this.editAccount.validation,
asyncMiddleware(this.editAccount.handler));
router.delete('/:id',
this.deleteAccount.validation,
asyncMiddleware(this.deleteAccount.handler));
// router.get('/:id',
// this.getAccount.validation,
// asyncMiddleware(this.getAccount.handler));
// router.delete('/:id',
// this.deleteAccount.validation,
// asyncMiddleware(this.deleteAccount.handler));
return router;
},
@@ -36,20 +40,22 @@ export default {
validation: [
check('name').isLength({ min: 3 }).trim().escape(),
check('code').isLength({ max: 10 }).trim().escape(),
check('type_id').isNumeric().toInt(),
check('account_type_id').isNumeric().toInt(),
check('description').trim().escape(),
],
async handler(req, res) {
const errors = validationResult(req);
const validationErrors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
if (!validationErrors.isEmpty()) {
return res.boom.badData(null, {
code: 'validation_error', ...validationErrors,
});
}
const { name, code, description } = req.body;
const { type_id: typeId } = req.body;
const { account_type_id: typeId } = req.body;
const foundAccountCodePromise = Account.where('code', code).fetch();
const foundAccountCodePromise = code ? Account.where('code', code).fetch() : null;
const foundAccountTypePromise = AccountType.where('id', typeId).fetch();
const [foundAccountCode, foundAccountType] = await Promise.all([
@@ -57,7 +63,7 @@ export default {
foundAccountTypePromise,
]);
if (!foundAccountCode) {
if (!foundAccountCode && foundAccountCodePromise) {
return res.boom.badRequest(null, {
errors: [{ type: 'NOT_UNIQUE_CODE', code: 100 }],
});
@@ -68,11 +74,67 @@ export default {
});
}
const account = Account.forge({
name, code, type_id: typeId, description,
name, code, account_type_id: typeId, description,
});
await account.save();
return res.boom.success({ item: { ...account.attributes } });
return res.status(200).send({ item: { ...account.attributes } });
},
},
/**
* Edit the given account details.
*/
editAccount: {
validation: [
check('name').isLength({ min: 3 }).trim().escape(),
check('code').isLength({ max: 10 }).trim().escape(),
check('account_type_id').isNumeric().toInt(),
check('description').trim().escape(),
],
async handler(req, res) {
const { id } = req.params;
const validationErrors = validationResult(req);
if (!validationErrors.isEmpty()) {
return res.boom.badData(null, {
code: 'validation_error', ...validationErrors,
});
}
const account = await Account.where('id', id).fetch();
if (!account) {
return res.boom.notFound();
}
const { name, code, description } = req.body;
const { account_type_id: typeId } = req.body;
const foundAccountCodePromise = (code && code !== account.attributes.code)
? Account.query({ where: { code }, whereNot: { id } }).fetch() : null;
const foundAccountTypePromise = (typeId !== account.attributes.account_type_id)
? AccountType.where('id', typeId).fetch() : null;
const [foundAccountCode, foundAccountType] = await Promise.all([
foundAccountCodePromise, foundAccountTypePromise,
]);
if (!foundAccountCode && foundAccountCodePromise) {
return res.boom.badRequest(null, {
errors: [{ type: 'NOT_UNIQUE_CODE', code: 100 }],
});
}
if (!foundAccountType && foundAccountTypePromise) {
return res.boom.badRequest(null, {
errors: [{ type: 'NOT_EXIST_ACCOUNT_TYPE', code: 110 }],
});
}
await account.save({
name, code, account_type_id: typeId, description,
});
return res.status(200).send();
},
},
@@ -105,7 +167,6 @@ export default {
if (!account) {
return res.boom.notFound();
}
await account.destroy();
await AccountBalance.where('account_id', id).destroy({ require: false });

View File

@@ -37,16 +37,15 @@ export default {
*/
login: {
validation: [
check('crediential').isEmail(),
check('password').isLength({ min: 5 }),
check('crediential').exists().isEmail(),
check('password').exists().isLength({ min: 5 }),
],
async handler(req, res) {
const validationErrors = validationResult(req);
if (!validationErrors.isEmpty()) {
return res.boom.badData(null, {
code: 'validation_error',
...validationErrors,
code: 'validation_error', ...validationErrors,
});
}
const { crediential, password } = req.body;
@@ -81,17 +80,19 @@ export default {
*/
sendResetPassword: {
validation: [
check('email').isEmail(),
check('email').exists().isEmail(),
],
// eslint-disable-next-line consistent-return
async handler(req, res) {
const errors = validationResult(req);
const validationErrors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
if (!validationErrors.isEmpty()) {
return res.boom.badData(null, {
code: 'validation_error', ...validationErrors,
});
}
const { email } = req.body;
const user = User.where('email').fetch();
const user = User.where('email', email).fetch();
if (!user) {
return res.status(422).send();
@@ -137,14 +138,21 @@ export default {
*/
resetPassword: {
validation: [
check('password').isLength({ min: 5 }),
check('reset_password'),
check('password').exists().isLength({ min: 5 }).custom((value, { req }) => {
if (value !== req.body.confirm_password) {
throw new Error("Passwords don't match");
} else {
return value;
}
}),
],
async handler(req, res) {
const errors = validationResult(req);
const validationErrors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
if (!validationErrors.isEmpty()) {
return res.boom.badData(null, {
code: 'VALIDATION_ERROR', ...validationErrors,
});
}
const { token } = req.params;
const { password } = req.body;
@@ -155,11 +163,8 @@ export default {
}).fetch();
if (!tokenModel) {
return res.status(400).send({
error: {
type: 'token.invalid',
message: 'Password reset token is invalid or has expired',
},
return res.boom.badRequest(null, {
errors: [{ type: 'TOKEN_INVALID', code: 100 }],
});
}
@@ -167,8 +172,8 @@ export default {
email: tokenModel.attributes.email,
});
if (!user) {
return res.status(400).send({
error: { message: 'An unexpected error occurred.' },
return res.boom.badRequest(null, {
errors: [{ type: 'USER_NOT_FOUND', code: 120 }],
});
}
const hashedPassword = await hashPassword(password);

View File

@@ -184,7 +184,10 @@ export default {
page: filter.page,
});
return res.status(200).send({ ...items.toJSON() });
return res.status(200).send({
items: items.toJSON(),
pagination: items.pagination,
});
},
},
};

View File

@@ -0,0 +1,241 @@
import express from 'express';
import { check, validationResult } from 'express-validator';
import User from '@/models/User';
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
export default {
/**
* Router constructor.
*/
router() {
const router = express.Router();
router.post('/',
this.newUser.validation,
asyncMiddleware(this.newUser.handler));
router.post('/:id',
this.editUser.validation,
asyncMiddleware(this.editUser.handler));
// router.get('/',
// this.listUsers.validation,
// asyncMiddleware(this.listUsers.handler));
// router.get('/:id',
// this.getUser.validation,
// asyncMiddleware(this.getUser.handler));
router.delete('/:id',
this.deleteUser.validation,
asyncMiddleware(this.deleteUser.handler));
return router;
},
/**
* Creates a new user.
*/
newUser: {
validation: [
check('first_name').exists(),
check('last_name').exists(),
check('email').exists().isEmail(),
check('phone_number').optional().isMobilePhone(),
check('password').isLength({ min: 4 }).exists().custom((value, { req }) => {
if (value !== req.body.confirm_password) {
throw new Error("Passwords don't match");
} else {
return value;
}
}),
check('status').exists().isBoolean().toBoolean(),
],
async handler(req, res) {
const validationErrors = validationResult(req);
if (!validationErrors.isEmpty()) {
return res.boom.badData(null, {
code: 'validation_error', ...validationErrors,
});
}
const { email, phone_number: phoneNumber } = req.body;
const foundUsers = await User.query((query) => {
query.where('email', email);
query.orWhere('phone_number', phoneNumber);
}).fetchAll();
const foundUserEmail = foundUsers.find((u) => u.attributes.email === email);
const foundUserPhone = foundUsers.find((u) => u.attributes.phone_number === phoneNumber);
const errorReasons = [];
if (foundUserEmail) {
errorReasons.push({ type: 'EMAIL_ALREADY_EXIST', code: 100 });
}
if (foundUserPhone) {
errorReasons.push({ type: 'PHONE_NUMBER_ALREADY_EXIST', code: 120 });
}
if (errorReasons.length > 0) {
return res.boom.badRequest(null, { errors: errorReasons });
}
const user = User.forge({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
phone_number: req.body.phone_number,
active: req.body.status,
});
await user.save();
return res.status(200).send({ id: user.get('id') });
},
},
/**
* Edit details of the given user.
*/
editUser: {
validation: [
check('first_name').exists(),
check('last_name').exists(),
check('email').exists().isEmail(),
check('phone_number').optional().isMobilePhone(),
check('password').isLength({ min: 4 }).exists().custom((value, { req }) => {
if (value !== req.body.confirm_password) {
throw new Error("Passwords don't match");
} else {
return value;
}
}),
check('status').exists().isBoolean().toBoolean(),
],
async handler(req, res) {
const { id } = req.params;
const validationErrors = validationResult(req);
if (!validationErrors.isEmpty()) {
return res.boom.badData(null, {
code: 'validation_error', ...validationErrors,
});
}
const user = await User.where('id', id).fetch();
if (!user) {
return res.boom.notFound();
}
const { email, phone_number: phoneNumber } = req.body;
const foundUsers = await User.query((query) => {
query.whereNot('id', id);
query.where('email', email);
query.orWhere('phone_number', phoneNumber);
}).fetchAll();
const foundUserEmail = foundUsers.find((u) => u.attribues.email === email);
const foundUserPhone = foundUsers.find((u) => u.attribues.phone_number === phoneNumber);
const errorReasons = [];
if (foundUserEmail) {
errorReasons.push({ type: 'EMAIL_ALREADY_EXIST', code: 100 });
}
if (foundUserPhone) {
errorReasons.push({ type: 'PHONE_NUMBER_ALREADY_EXIST', code: 120 });
}
if (errorReasons.length > 0) {
return res.badRequest(null, { errors: errorReasons });
}
await user.save({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
phone_number: req.body.phone_number,
status: req.body.status,
});
return res.status(200).send();
},
},
/**
* Soft deleting the given user.
*/
deleteUser: {
validation: [],
async handler(req, res) {
const { id } = req.params;
const user = await User.where('id', id).fetch();
if (!user) {
return res.boom.notFound(null, {
errors: [{ type: 'USER_NOT_FOUND', code: 100 }],
});
}
await user.destroy();
return res.status(200).send();
},
},
getUser: {
validation: [],
async handler(req, res) {
const { id } = req.params;
const user = await User.where('id', id).fetch();
if (!user) {
return res.boom.notFound();
}
return res.status(200).send({ item: user.toJSON() });
},
},
/**
* Retrieve the list of users.
*/
listUsers: {
validation: [],
handler(req, res) {
const filter = {
first_name: '',
last_name: '',
email: '',
phone_number: '',
page_size: 10,
page: 1,
...req.query,
};
const users = User.query((query) => {
if (filter.first_name) {
query.where('first_name', filter.first_name);
}
if (filter.last_name) {
query.where('last_name', filter.last_name);
}
if (filter.email) {
query.where('email', filter.email);
}
if (filter.phone_number) {
query.where('phone_number', filter.phone_number);
}
}).fetchPage({
page_size: filter.page_size,
page: filter.page,
});
return res.status(200).send({
items: users.toJSON(),
pagination: users.pagination,
});
},
},
};