feat: reponse readable text and linting some pages.

This commit is contained in:
a.bouhuolia
2021-01-02 10:44:38 +02:00
parent d30e76c5cf
commit b6392e4208
9 changed files with 164 additions and 85 deletions

View File

@@ -213,7 +213,10 @@ export default class CustomersController extends ContactsController {
try { try {
await this.customersService.deleteCustomer(tenantId, contactId) await this.customersService.deleteCustomer(tenantId, contactId)
return res.status(200).send({ id: contactId }); return res.status(200).send({
id: contactId,
message: 'The customer has been deleted successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -252,7 +255,11 @@ export default class CustomersController extends ContactsController {
try { try {
await this.customersService.deleteBulkCustomers(tenantId, contactsIds) await this.customersService.deleteBulkCustomers(tenantId, contactsIds)
return res.status(200).send({ ids: contactsIds });
return res.status(200).send({
ids: contactsIds,
message: 'The customers have been deleted successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }

View File

@@ -194,7 +194,10 @@ export default class ExpensesController extends BaseController {
expenseDTO, expenseDTO,
user user
); );
return res.status(200).send({ id: expenseId }); return res.status(200).send({
id: expenseId,
message: 'The expense has been created successfully.'
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -215,7 +218,7 @@ export default class ExpensesController extends BaseController {
return res.status(200).send({ return res.status(200).send({
id: expenseId, id: expenseId,
message: 'The expense has been deleted.', message: 'The expense has been deleted successfully.',
}); });
} catch (error) { } catch (error) {
next(error); next(error);
@@ -237,7 +240,7 @@ export default class ExpensesController extends BaseController {
return res.status(200).send({ return res.status(200).send({
id: expenseId, id: expenseId,
message: 'The expense has been published', message: 'The expense has been published successfully',
}); });
} catch (error) { } catch (error) {
next(error); next(error);
@@ -260,7 +263,10 @@ export default class ExpensesController extends BaseController {
expensesIds, expensesIds,
user user
); );
return res.status(200).send({ ids: expensesIds }); return res.status(200).send({
ids: expensesIds,
message: 'The expenses have been deleted successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -282,7 +288,10 @@ export default class ExpensesController extends BaseController {
expensesIds, expensesIds,
user user
); );
return res.status(200).send({}); return res.status(200).send({
ids: expensesIds,
message: 'The expenses have been published successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }

View File

@@ -239,7 +239,7 @@ export default class ItemsController extends BaseController {
return res.status(200).send({ return res.status(200).send({
id: storedItem.id, id: storedItem.id,
message: 'Item has been created successfully.', message: 'The item has been created successfully.',
}); });
} catch (error) { } catch (error) {
next(error); next(error);
@@ -258,7 +258,11 @@ export default class ItemsController extends BaseController {
try { try {
await this.itemsService.editItem(tenantId, itemId, item); await this.itemsService.editItem(tenantId, itemId, item);
return res.status(200).send({ id: itemId });
return res.status(200).send({
id: itemId,
message: 'The item has been edited successfully.'
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -319,7 +323,11 @@ export default class ItemsController extends BaseController {
try { try {
await this.itemsService.deleteItem(tenantId, itemId); await this.itemsService.deleteItem(tenantId, itemId);
return res.status(200).send({ id: itemId });
return res.status(200).send({
id: itemId,
message: 'The item has been deleted successfully.'
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -340,8 +348,6 @@ export default class ItemsController extends BaseController {
return res.status(200).send({ item: storedItem }); return res.status(200).send({ item: storedItem });
} catch (error) { } catch (error) {
console.log(error);
next(error); next(error);
} }
} }

View File

@@ -205,7 +205,10 @@ export default class ManualJournalsController extends BaseController {
try { try {
await this.manualJournalsService.publishManualJournal(tenantId, manualJournalId); await this.manualJournalsService.publishManualJournal(tenantId, manualJournalId);
return res.status(200).send(); return res.status(200).send({
id: manualJournalId,
message: 'The manual journal has been published successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -224,7 +227,10 @@ export default class ManualJournalsController extends BaseController {
try { try {
await this.manualJournalsService.publishManualJournals(tenantId, manualJournalsIds); await this.manualJournalsService.publishManualJournals(tenantId, manualJournalsIds);
return res.status(200).send(); return res.status(200).send({
ids: manualJournalsIds,
message: 'The manual journals have been published successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -288,7 +294,10 @@ export default class ManualJournalsController extends BaseController {
const { manualJournal } = await this.manualJournalsService const { manualJournal } = await this.manualJournalsService
.makeJournalEntries(tenantId, manualJournalDTO, user); .makeJournalEntries(tenantId, manualJournalDTO, user);
return res.status(200).send({ id: manualJournal.id }); return res.status(200).send({
id: manualJournal.id,
message: 'The manual journal has been created successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -312,7 +321,10 @@ export default class ManualJournalsController extends BaseController {
manualJournalDTO, manualJournalDTO,
user, user,
); );
return res.status(200).send({ id: manualJournal.id }); return res.status(200).send({
id: manualJournal.id,
message: 'The manual journal has been edited successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }

View File

@@ -1,4 +1,3 @@
import { Router, Request, Response, NextFunction } from 'express'; import { Router, Request, Response, NextFunction } from 'express';
import { Service, Inject } from 'typedi'; import { Service, Inject } from 'typedi';
import { check, param, query, ValidationChain } from 'express-validator'; import { check, param, query, ValidationChain } from 'express-validator';
@@ -31,46 +30,51 @@ export default class BillsPayments extends BaseController {
router() { router() {
const router = Router(); const router = Router();
router.post('/', [ router.post(
...this.billPaymentSchemaValidation, '/',
], [...this.billPaymentSchemaValidation],
this.validationResult, this.validationResult,
asyncMiddleware(this.createBillPayment.bind(this)), asyncMiddleware(this.createBillPayment.bind(this)),
this.handleServiceError, this.handleServiceError
); );
router.post('/:id', [ router.post(
...this.billPaymentSchemaValidation, '/:id',
...this.specificBillPaymentValidateSchema, [
], ...this.billPaymentSchemaValidation,
this.validationResult,
asyncMiddleware(this.editBillPayment.bind(this)),
this.handleServiceError,
)
router.delete('/:id', [
...this.specificBillPaymentValidateSchema, ...this.specificBillPaymentValidateSchema,
], ],
this.validationResult, this.validationResult,
asyncMiddleware(this.deleteBillPayment.bind(this)), asyncMiddleware(this.editBillPayment.bind(this)),
this.handleServiceError, this.handleServiceError
); );
router.get('/:id/bills', router.delete(
'/:id',
[...this.specificBillPaymentValidateSchema],
this.validationResult,
asyncMiddleware(this.deleteBillPayment.bind(this)),
this.handleServiceError
);
router.get(
'/:id/bills',
this.specificBillPaymentValidateSchema, this.specificBillPaymentValidateSchema,
this.validationResult, this.validationResult,
asyncMiddleware(this.getPaymentBills.bind(this)), asyncMiddleware(this.getPaymentBills.bind(this)),
this.handleServiceError, this.handleServiceError
); );
router.get('/:id', router.get(
'/:id',
this.specificBillPaymentValidateSchema, this.specificBillPaymentValidateSchema,
this.validationResult, this.validationResult,
asyncMiddleware(this.getBillPayment.bind(this)), asyncMiddleware(this.getBillPayment.bind(this)),
this.handleServiceError, this.handleServiceError
); );
router.get('/', router.get(
'/',
this.listingValidationSchema, this.listingValidationSchema,
this.validationResult, this.validationResult,
asyncMiddleware(this.getBillsPayments.bind(this)), asyncMiddleware(this.getBillsPayments.bind(this)),
this.handleServiceError, this.handleServiceError,
this.dynamicListService.handlerErrorsToResponse, this.dynamicListService.handlerErrorsToResponse
); );
return router; return router;
} }
@@ -97,9 +101,7 @@ export default class BillsPayments extends BaseController {
* Specific bill payment schema validation. * Specific bill payment schema validation.
*/ */
get specificBillPaymentValidateSchema(): ValidationChain[] { get specificBillPaymentValidateSchema(): ValidationChain[] {
return [ return [param('id').exists().isNumeric().toInt()];
param('id').exists().isNumeric().toInt(),
];
} }
/** /**
@@ -119,16 +121,19 @@ export default class BillsPayments extends BaseController {
/** /**
* Creates a bill payment. * Creates a bill payment.
* @async * @async
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {Response} res * @param {Response} res
*/ */
async createBillPayment(req: Request, res: Response, next: NextFunction) { async createBillPayment(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId } = req;
const billPaymentDTO = this.matchedBodyData(req); const billPaymentDTO = this.matchedBodyData(req);
try { try {
const billPayment = await this.billPaymentService.createBillPayment(tenantId, billPaymentDTO); const billPayment = await this.billPaymentService.createBillPayment(
tenantId,
billPaymentDTO
);
return res.status(200).send({ return res.status(200).send({
id: billPayment.id, id: billPayment.id,
@@ -142,8 +147,8 @@ export default class BillsPayments extends BaseController {
/** /**
* Edits the given bill payment details. * Edits the given bill payment details.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
*/ */
async editBillPayment(req: Request, res: Response, next: NextFunction) { async editBillPayment(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId } = req;
@@ -190,8 +195,8 @@ export default class BillsPayments extends BaseController {
/** /**
* Retrieve the bill payment. * Retrieve the bill payment.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
*/ */
async getBillPayment(req: Request, res: Response, next: NextFunction) { async getBillPayment(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId } = req;
@@ -206,8 +211,8 @@ export default class BillsPayments extends BaseController {
return res.status(200).send({ return res.status(200).send({
bill_payment: this.transfromToResponse({ ...billPayment }), bill_payment: this.transfromToResponse({ ...billPayment }),
payable_bills: this.transfromToResponse([ ...payableBills ]), payable_bills: this.transfromToResponse([...payableBills]),
payment_bills: this.transfromToResponse([ ...paymentMadeBills ]), payment_bills: this.transfromToResponse([...paymentMadeBills]),
}); });
} catch (error) { } catch (error) {
next(error); next(error);
@@ -216,16 +221,19 @@ export default class BillsPayments extends BaseController {
/** /**
* Retrieve associated bills for the given payment made. * Retrieve associated bills for the given payment made.
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
async getPaymentBills(req: Request, res: Response, next: NextFunction) { async getPaymentBills(req: Request, res: Response, next: NextFunction) {
const { tenantId } = req; const { tenantId } = req;
const { id: billPaymentId } = req.params; const { id: billPaymentId } = req.params;
try { try {
const bills = await this.billPaymentService.getPaymentBills(tenantId, billPaymentId); const bills = await this.billPaymentService.getPaymentBills(
tenantId,
billPaymentId
);
return res.status(200).send({ bills }); return res.status(200).send({ bills });
} catch (error) { } catch (error) {
next(error); next(error);
@@ -233,7 +241,7 @@ export default class BillsPayments extends BaseController {
} }
/** /**
* Retrieve bills payments listing with pagination metadata. * Retrieve bills payments listing with pagination metadata.
* @param {Request} req - * @param {Request} req -
* @param {Response} res - * @param {Response} res -
* @return {Response} * @return {Response}
@@ -250,12 +258,19 @@ export default class BillsPayments extends BaseController {
}; };
try { try {
const { billPayments, pagination, filterMeta } = await this.billPaymentService.listBillPayments(tenantId, billPaymentsFilter); const {
billPayments,
pagination,
filterMeta,
} = await this.billPaymentService.listBillPayments(
tenantId,
billPaymentsFilter
);
return res.status(200).send({ return res.status(200).send({
bill_payments: billPayments, bill_payments: billPayments,
pagination: this.transfromToResponse(pagination), pagination: this.transfromToResponse(pagination),
filter_meta: this.transfromToResponse(filterMeta) filter_meta: this.transfromToResponse(filterMeta),
}); });
} catch (error) { } catch (error) {
next(error); next(error);
@@ -264,46 +279,54 @@ export default class BillsPayments extends BaseController {
/** /**
* Handle service errors. * Handle service errors.
* @param {Error} error * @param {Error} error
* @param {Request} req * @param {Request} req
* @param {Response} res * @param {Response} res
* @param {NextFunction} next * @param {NextFunction} next
*/ */
handleServiceError(error: Error, req: Request, res: Response, next: NextFunction) { handleServiceError(
error: Error,
req: Request,
res: Response,
next: NextFunction
) {
if (error instanceof ServiceError) { if (error instanceof ServiceError) {
if (error.errorType === 'PAYMENT_MADE_NOT_FOUND') { if (error.errorType === 'PAYMENT_MADE_NOT_FOUND') {
return res.status(404).send({ return res.status(404).send({
message: 'Payment made not found.', message: 'Payment made not found.',
errors: [{ type: 'BILL_NOT_FOUND', code: 100 }],
}); });
} }
if (error.errorType === 'VENDOR_NOT_FOUND') { if (error.errorType === 'VENDOR_NOT_FOUND') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'BILL.PAYMENT.VENDOR.NOT.FOUND', code: 500 }], errors: [{ type: 'BILL.PAYMENT.VENDOR.NOT.FOUND', code: 200 }],
}); });
} }
if (error.errorType === 'PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE') { if (error.errorType === 'PAYMENT_ACCOUNT_NOT_CURRENT_ASSET_TYPE') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'PAYMENT_ACCOUNT.NOT.CURRENT_ASSET.TYPE', code: 100 }], errors: [
{ type: 'PAYMENT_ACCOUNT.NOT.CURRENT_ASSET.TYPE', code: 300 },
],
}); });
} }
if (error.errorType === 'BILL_PAYMENT_NUMBER_NOT_UNQIUE') { if (error.errorType === 'BILL_PAYMENT_NUMBER_NOT_UNQIUE') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'PAYMENT.NUMBER.NOT.UNIQUE', code: 300 }], errors: [{ type: 'PAYMENT.NUMBER.NOT.UNIQUE', code: 400 }],
}); });
} }
if (error.errorType === 'PAYMENT_ACCOUNT_NOT_FOUND') { if (error.errorType === 'PAYMENT_ACCOUNT_NOT_FOUND') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 200 }], errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 500 }],
}); });
} }
if (error.errorType === 'PAYMENT_ACCOUNT_NOT_FOUND') { if (error.errorType === 'PAYMENT_ACCOUNT_NOT_FOUND') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 200 }], errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 600 }],
}); });
} }
if (error.errorType === '') { if (error.errorType === '') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'BILLS.IDS.NOT.EXISTS', code: 600 }], errors: [{ type: 'BILLS.IDS.NOT.EXISTS', code: 700 }],
}); });
} }
if (error.errorType === 'BILL_PAYMENT_ENTRIES_NOT_FOUND') { if (error.errorType === 'BILL_PAYMENT_ENTRIES_NOT_FOUND') {
@@ -313,15 +336,15 @@ export default class BillsPayments extends BaseController {
} }
if (error.errorType === 'INVALID_BILL_PAYMENT_AMOUNT') { if (error.errorType === 'INVALID_BILL_PAYMENT_AMOUNT') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'INVALID_BILL_PAYMENT_AMOUNT', code: 100 }], errors: [{ type: 'INVALID_BILL_PAYMENT_AMOUNT', code: 900 }],
}); });
} }
if (error.errorType === 'BILL_ENTRIES_IDS_NOT_FOUND') { if (error.errorType === 'BILL_ENTRIES_IDS_NOT_FOUND') {
return res.status(400).send({ return res.status(400).send({
errors: [{ type: 'BILLS_NOT_FOUND', code: 100 }], errors: [{ type: 'BILLS_NOT_FOUND', code: 1000 }],
}) });
} }
} }
next(error); next(error);
} }
} }

View File

@@ -155,7 +155,10 @@ export default class SalesEstimatesController extends BaseController {
try { try {
const storedEstimate = await this.saleEstimateService.createEstimate(tenantId, estimateDTO); const storedEstimate = await this.saleEstimateService.createEstimate(tenantId, estimateDTO);
return res.status(200).send({ id: storedEstimate.id }); return res.status(200).send({
id: storedEstimate.id,
message: 'The sale estimate has been created successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -175,7 +178,10 @@ export default class SalesEstimatesController extends BaseController {
// Update estimate with associated estimate entries. // Update estimate with associated estimate entries.
await this.saleEstimateService.editEstimate(tenantId, estimateId, estimateDTO); await this.saleEstimateService.editEstimate(tenantId, estimateId, estimateDTO);
return res.status(200).send({ id: estimateId }); return res.status(200).send({
id: estimateId,
message: 'The sale estimate has been created successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -193,7 +199,10 @@ export default class SalesEstimatesController extends BaseController {
try { try {
await this.saleEstimateService.deleteEstimate(tenantId, estimateId); await this.saleEstimateService.deleteEstimate(tenantId, estimateId);
return res.status(200).send({ id: estimateId }); return res.status(200).send({
id: estimateId,
message: 'The sale estimate has been deleted successfully.'
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -276,6 +285,7 @@ export default class SalesEstimatesController extends BaseController {
try { try {
const estimate = await this.saleEstimateService.getEstimate(tenantId, estimateId); const estimate = await this.saleEstimateService.getEstimate(tenantId, estimateId);
return res.status(200).send({ estimate }); return res.status(200).send({ estimate });
} catch (error) { } catch (error) {
next(error); next(error);

View File

@@ -104,7 +104,11 @@ export default class UsersController extends BaseController{
try { try {
await this.usersService.editUser(tenantId, userId, userDTO); await this.usersService.editUser(tenantId, userId, userDTO);
return res.status(200).send({ id: userId });
return res.status(200).send({
id: userId,
message: 'The user has been edited successfully.',
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -122,7 +126,10 @@ export default class UsersController extends BaseController{
try { try {
await this.usersService.deleteUser(tenantId, id); await this.usersService.deleteUser(tenantId, id);
return res.status(200).send({ id }); return res.status(200).send({
id,
message: 'The user has been deleted successfully.'
});
} catch (error) { } catch (error) {
next(error); next(error);
} }
@@ -175,7 +182,11 @@ export default class UsersController extends BaseController{
try { try {
await this.usersService.activateUser(tenantId, userId, user); await this.usersService.activateUser(tenantId, userId, user);
return res.status(200).send({ id: userId });
return res.status(200).send({
id: userId,
message: 'The user has been activated successfully.',
});
} catch(error) { } catch(error) {
next(error); next(error);
} }
@@ -193,7 +204,11 @@ export default class UsersController extends BaseController{
try { try {
await this.usersService.inactivateUser(tenantId, userId, user); await this.usersService.inactivateUser(tenantId, userId, user);
return res.status(200).send({ id: userId });
return res.status(200).send({
id: userId,
message: 'The user has been inactivated successfully.',
});
} catch(error) { } catch(error) {
next(error); next(error);
} }

View File

@@ -130,13 +130,12 @@ export default class CustomersService {
* @return {Promise<void>} * @return {Promise<void>}
*/ */
public async deleteCustomer(tenantId: number, customerId: number): Promise<void> { public async deleteCustomer(tenantId: number, customerId: number): Promise<void> {
const { Contact } = this.tenancy.models(tenantId);
this.logger.info('[customer] trying to delete customer.', { tenantId, customerId }); this.logger.info('[customer] trying to delete customer.', { tenantId, customerId });
await this.getCustomerByIdOrThrowError(tenantId, customerId); await this.getCustomerByIdOrThrowError(tenantId, customerId);
await this.customerHasNoInvoicesOrThrowError(tenantId, customerId); await this.customerHasNoInvoicesOrThrowError(tenantId, customerId);
await Contact.query().findById(customerId).delete(); await this.contactService.deleteContact(tenantId, customerId, 'customer');
await this.eventDispatcher.dispatch(events.customers.onDeleted, { tenantId, customerId }); await this.eventDispatcher.dispatch(events.customers.onDeleted, { tenantId, customerId });
this.logger.info('[customer] deleted successfully.', { tenantId, customerId }); this.logger.info('[customer] deleted successfully.', { tenantId, customerId });

View File

@@ -120,8 +120,6 @@ export default class VendorsService {
* @return {Promise<void>} * @return {Promise<void>}
*/ */
public async deleteVendor(tenantId: number, vendorId: number) { public async deleteVendor(tenantId: number, vendorId: number) {
const { Contact } = this.tenancy.models(tenantId);
await this.getVendorByIdOrThrowError(tenantId, vendorId); await this.getVendorByIdOrThrowError(tenantId, vendorId);
await this.vendorHasNoBillsOrThrowError(tenantId, vendorId); await this.vendorHasNoBillsOrThrowError(tenantId, vendorId);
@@ -129,7 +127,7 @@ export default class VendorsService {
tenantId, tenantId,
vendorId, vendorId,
}); });
await Contact.query().findById(vendorId).delete(); await this.contactService.deleteContact(tenantId, vendorId, 'vendor');
await this.eventDispatcher.dispatch(events.vendors.onDeleted, { await this.eventDispatcher.dispatch(events.vendors.onDeleted, {
tenantId, tenantId,