mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-16 12:50:38 +00:00
refactoring: bills service.
refactoring: bills payments made service.
This commit is contained in:
@@ -24,7 +24,8 @@ export default class CustomersController extends ContactsController {
|
||||
...this.customerDTOSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.newCustomer.bind(this))
|
||||
asyncMiddleware(this.newCustomer.bind(this)),
|
||||
this.handlerServiceErrors
|
||||
);
|
||||
router.post('/:id', [
|
||||
...this.contactDTOSchema,
|
||||
@@ -32,19 +33,22 @@ export default class CustomersController extends ContactsController {
|
||||
...this.customerDTOSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.editCustomer.bind(this))
|
||||
asyncMiddleware(this.editCustomer.bind(this)),
|
||||
this.handlerServiceErrors,
|
||||
);
|
||||
router.delete('/:id', [
|
||||
...this.specificContactSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.deleteCustomer.bind(this))
|
||||
asyncMiddleware(this.deleteCustomer.bind(this)),
|
||||
this.handlerServiceErrors,
|
||||
);
|
||||
router.delete('/', [
|
||||
...this.bulkContactsSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.deleteBulkCustomers.bind(this))
|
||||
asyncMiddleware(this.deleteBulkCustomers.bind(this)),
|
||||
this.handlerServiceErrors,
|
||||
);
|
||||
router.get('/', [
|
||||
|
||||
@@ -56,7 +60,8 @@ export default class CustomersController extends ContactsController {
|
||||
...this.specificContactSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.getCustomer.bind(this))
|
||||
asyncMiddleware(this.getCustomer.bind(this)),
|
||||
this.handlerServiceErrors
|
||||
);
|
||||
return router;
|
||||
}
|
||||
@@ -104,13 +109,6 @@ export default class CustomersController extends ContactsController {
|
||||
await this.customersService.editCustomer(tenantId, contactId, contactDTO);
|
||||
return res.status(200).send({ id: contactId });
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contact_not_found') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'CUSTOMER.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
@@ -129,18 +127,6 @@ export default class CustomersController extends ContactsController {
|
||||
await this.customersService.deleteCustomer(tenantId, contactId)
|
||||
return res.status(200).send({ id: contactId });
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contact_not_found') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'CUSTOMER.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'customer_has_invoices') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'CUSTOMER.HAS.SALES_INVOICES', code: 200 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
@@ -159,13 +145,6 @@ export default class CustomersController extends ContactsController {
|
||||
const contact = await this.customersService.getCustomer(tenantId, contactId)
|
||||
return res.status(200).send({ contact });
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contact_not_found') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'CONTACT.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
@@ -184,18 +163,6 @@ export default class CustomersController extends ContactsController {
|
||||
await this.customersService.deleteBulkCustomers(tenantId, contactsIds)
|
||||
return res.status(200).send({ ids: contactsIds });
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contacts_not_found') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'CUSTOMERS.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'some_customers_have_invoices') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'SOME.CUSTOMERS.HAVE.SALES_INVOICES', code: 200 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
@@ -210,4 +177,31 @@ export default class CustomersController extends ContactsController {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles service errors.
|
||||
* @param {Error} error
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
handlerServiceErrors(error: Error, req: Request, res: Response, next: NextFunction) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contacts_not_found') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'CUSTOMERS.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'some_customers_have_invoices') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'SOME.CUSTOMERS.HAVE.SALES_INVOICES', code: 200 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'customer_has_invoices') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'CUSTOMER.HAS.SALES_INVOICES', code: 200 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,8 @@ export default class VendorsController extends ContactsController {
|
||||
...this.vendorDTOSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.newVendor.bind(this))
|
||||
asyncMiddleware(this.newVendor.bind(this)),
|
||||
this.handlerServiceErrors,
|
||||
);
|
||||
router.post('/:id', [
|
||||
...this.contactDTOSchema,
|
||||
@@ -32,25 +33,29 @@ export default class VendorsController extends ContactsController {
|
||||
...this.vendorDTOSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.editVendor.bind(this))
|
||||
asyncMiddleware(this.editVendor.bind(this)),
|
||||
this.handlerServiceErrors,
|
||||
);
|
||||
router.delete('/:id', [
|
||||
...this.specificContactSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.deleteVendor.bind(this))
|
||||
asyncMiddleware(this.deleteVendor.bind(this)),
|
||||
this.handlerServiceErrors,
|
||||
);
|
||||
router.delete('/', [
|
||||
...this.bulkContactsSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.deleteBulkVendors.bind(this))
|
||||
asyncMiddleware(this.deleteBulkVendors.bind(this)),
|
||||
this.handlerServiceErrors,
|
||||
);
|
||||
router.get('/:id', [
|
||||
...this.specificContactSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.getVendor.bind(this))
|
||||
asyncMiddleware(this.getVendor.bind(this)),
|
||||
this.handlerServiceErrors,
|
||||
);
|
||||
router.get('/', [
|
||||
...this.vendorsListSchema,
|
||||
@@ -99,8 +104,8 @@ export default class VendorsController extends ContactsController {
|
||||
const { tenantId } = req;
|
||||
|
||||
try {
|
||||
const contact = await this.vendorsService.newVendor(tenantId, contactDTO);
|
||||
return res.status(200).send({ id: contact.id });
|
||||
const vendor = await this.vendorsService.newVendor(tenantId, contactDTO);
|
||||
return res.status(200).send({ id: vendor.id });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -121,13 +126,6 @@ export default class VendorsController extends ContactsController {
|
||||
await this.vendorsService.editVendor(tenantId, contactId, contactDTO);
|
||||
return res.status(200).send({ id: contactId });
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contact_not_found') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'VENDOR.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
@@ -146,18 +144,6 @@ export default class VendorsController extends ContactsController {
|
||||
await this.vendorsService.deleteVendor(tenantId, contactId)
|
||||
return res.status(200).send({ id: contactId });
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contact_not_found') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'VENDOR.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'vendor_has_bills') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'VENDOR.HAS.BILLS', code: 200 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
@@ -176,13 +162,6 @@ export default class VendorsController extends ContactsController {
|
||||
const vendor = await this.vendorsService.getVendor(tenantId, vendorId)
|
||||
return res.status(200).send({ vendor });
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contact_not_found') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'VENDOR.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
@@ -201,18 +180,6 @@ export default class VendorsController extends ContactsController {
|
||||
await this.vendorsService.deleteBulkVendors(tenantId, contactsIds)
|
||||
return res.status(200).send({ ids: contactsIds });
|
||||
} catch (error) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contacts_not_found') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'VENDORS.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'some_vendors_have_bills') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'SOME.VENDORS.HAVE.BILLS', code: 200 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
@@ -236,4 +203,31 @@ export default class VendorsController extends ContactsController {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle service errors.
|
||||
* @param {Error} error -
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
* @param {NextFunction} next -
|
||||
*/
|
||||
handlerServiceErrors(error, req: Request, res: Response, next: NextFunction) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'contacts_not_found') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'VENDORS.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'some_vendors_have_bills') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'SOME.VENDORS.HAVE.BILLS', code: 200 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'vendor_has_bills') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'VENDOR.HAS.BILLS', code: 200 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { check, param, query, matchedData } from 'express-validator';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { difference } from 'lodash';
|
||||
import { BillOTD } from 'interfaces';
|
||||
import { IBillDTO, IBillEditDTO } from 'interfaces';
|
||||
import asyncMiddleware from 'api/middleware/asyncMiddleware';
|
||||
import BillsService from 'services/Purchases/Bills';
|
||||
import BaseController from 'api/controllers/BaseController';
|
||||
import ItemsService from 'services/Items/ItemsService';
|
||||
import TenancyService from 'services/Tenancy/TenancyService';
|
||||
import { ServiceError } from 'exceptions';
|
||||
|
||||
@Service()
|
||||
export default class BillsController extends BaseController {
|
||||
@@ -27,45 +27,49 @@ export default class BillsController extends BaseController {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
[...this.billValidationSchema],
|
||||
'/', [
|
||||
...this.billValidationSchema
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateVendorExistance.bind(this)),
|
||||
asyncMiddleware(this.validateItemsIds.bind(this)),
|
||||
asyncMiddleware(this.validateBillNumberExists.bind(this)),
|
||||
asyncMiddleware(this.validateNonPurchasableEntriesItems.bind(this)),
|
||||
asyncMiddleware(this.newBill.bind(this))
|
||||
asyncMiddleware(this.newBill.bind(this)),
|
||||
this.handleServiceError,
|
||||
);
|
||||
router.post(
|
||||
'/:id',
|
||||
[...this.billValidationSchema, ...this.specificBillValidationSchema],
|
||||
'/:id', [
|
||||
...this.billValidationSchema,
|
||||
...this.specificBillValidationSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateBillExistance.bind(this)),
|
||||
asyncMiddleware(this.validateVendorExistance.bind(this)),
|
||||
asyncMiddleware(this.validateItemsIds.bind(this)),
|
||||
asyncMiddleware(this.validateEntriesIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.validateNonPurchasableEntriesItems.bind(this)),
|
||||
asyncMiddleware(this.editBill.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
[...this.specificBillValidationSchema],
|
||||
'/:id', [
|
||||
...this.specificBillValidationSchema
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateBillExistance.bind(this)),
|
||||
asyncMiddleware(this.getBill.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
[...this.billsListingValidationSchema],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.listingBills.bind(this))
|
||||
asyncMiddleware(this.getBill.bind(this)),
|
||||
);
|
||||
|
||||
// router.get(
|
||||
// '/:id',
|
||||
// [...this.specificBillValidationSchema],
|
||||
// this.validationResult,
|
||||
// asyncMiddleware(this.getBill.bind(this)),
|
||||
// this.handleServiceError,
|
||||
// );
|
||||
// router.get(
|
||||
// '/',
|
||||
// [...this.billsListingValidationSchema],
|
||||
// this.validationResult,
|
||||
// asyncMiddleware(this.listingBills.bind(this)),
|
||||
// this.handleServiceError,
|
||||
// );
|
||||
router.delete(
|
||||
'/:id',
|
||||
[...this.specificBillValidationSchema],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateBillExistance.bind(this)),
|
||||
asyncMiddleware(this.deleteBill.bind(this))
|
||||
asyncMiddleware(this.deleteBill.bind(this)),
|
||||
this.handleServiceError,
|
||||
);
|
||||
return router;
|
||||
}
|
||||
@@ -92,6 +96,28 @@ export default class BillsController extends BaseController {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Common validation schema.
|
||||
*/
|
||||
get billEditValidationSchema() {
|
||||
return [
|
||||
// check('bill_number').exists().trim().escape(),
|
||||
check('bill_date').exists().isISO8601(),
|
||||
check('due_date').optional().isISO8601(),
|
||||
// check('vendor_id').exists().isNumeric().toInt(),
|
||||
check('note').optional().trim().escape(),
|
||||
check('entries').isArray({ min: 1 }),
|
||||
|
||||
check('entries.*.id').optional().isNumeric().toInt(),
|
||||
check('entries.*.index').exists().isNumeric().toInt(),
|
||||
check('entries.*.item_id').exists().isNumeric().toInt(),
|
||||
check('entries.*.rate').exists().isNumeric().toFloat(),
|
||||
check('entries.*.quantity').exists().isNumeric().toFloat(),
|
||||
check('entries.*.discount').optional().isNumeric().toFloat(),
|
||||
check('entries.*.description').optional().trim().escape(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Bill validation schema.
|
||||
*/
|
||||
@@ -112,162 +138,23 @@ export default class BillsController extends BaseController {
|
||||
query('sort_order').optional().isIn(['desc', 'asc']),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates whether the vendor is exist.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateVendorExistance(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const { Vendor } = req.models;
|
||||
|
||||
const isVendorExists = await Vendor.query().findById(req.body.vendor_id);
|
||||
|
||||
if (!isVendorExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'VENDOR.ID.NOT.FOUND', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the given bill existance.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateBillExistance(req: Request, res: Response, next: Function) {
|
||||
const billId: number = req.params.id;
|
||||
const { tenantId } = req;
|
||||
|
||||
const isBillExists = await this.billsService.isBillExists(tenantId, billId);
|
||||
|
||||
if (!isBillExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'BILL.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the entries items ids.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateItemsIds(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const itemsIds = req.body.entries.map((e) => e.item_id);
|
||||
|
||||
const notFoundItemsIds = await this.itemsService.isItemsIdsExists(tenantId, itemsIds);
|
||||
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.FOUND', code: 400 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the bill number existance.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateBillNumberExists(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const isBillNoExists = await this.billsService.isBillNoExists(
|
||||
tenantId, req.body.bill_number,
|
||||
);
|
||||
if (isBillNoExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'BILL.NUMBER.EXISTS', code: 500 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the entries ids existance on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateEntriesIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const { id: billId } = req.params;
|
||||
const bill = { ...req.body };
|
||||
const { ItemEntry } = req.models;
|
||||
|
||||
const entriesIds = bill.entries.filter((e) => e.id).map((e) => e.id);
|
||||
|
||||
const storedEntries = await ItemEntry.query()
|
||||
.whereIn('reference_id', [billId])
|
||||
.whereIn('reference_type', ['Bill']);
|
||||
|
||||
const storedEntriesIds = storedEntries.map((entry) => entry.id);
|
||||
const notFoundEntriesIds = difference(entriesIds, storedEntriesIds);
|
||||
|
||||
if (notFoundEntriesIds.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'BILL.ENTRIES.IDS.NOT.FOUND', code: 600 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the entries items that not purchase-able.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateNonPurchasableEntriesItems(req: Request, res: Response, next: Function) {
|
||||
const { Item } = req.models;
|
||||
const bill = { ...req.body };
|
||||
const itemsIds = bill.entries.map(e => e.item_id);
|
||||
|
||||
const purchasbleItems = await Item.query()
|
||||
.where('purchasable', true)
|
||||
.whereIn('id', itemsIds);
|
||||
|
||||
const purchasbleItemsIds = purchasbleItems.map((item) => item.id);
|
||||
const notPurchasableItems = difference(itemsIds, purchasbleItemsIds);
|
||||
|
||||
if (notPurchasableItems.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'NOT.PURCHASE.ABLE.ITEMS', code: 600 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates a new bill and records journal transactions.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async newBill(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const { ItemEntry } = req.models;
|
||||
async newBill(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId, user } = req;
|
||||
const billDTO: IBillDTO = this.matchedBodyData(req);
|
||||
|
||||
const billOTD: BillOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true
|
||||
});
|
||||
const storedBill = await this.billsService.createBill(tenantId, billOTD);
|
||||
|
||||
return res.status(200).send({ id: storedBill.id });
|
||||
try {
|
||||
const storedBill = await this.billsService.createBill(tenantId, billDTO, user);
|
||||
return res.status(200).send({ id: storedBill.id });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -275,18 +162,17 @@ export default class BillsController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async editBill(req: Request, res: Response) {
|
||||
async editBill(req: Request, res: Response, next: NextFunction) {
|
||||
const { id: billId } = req.params;
|
||||
const { ItemEntry } = req.models;
|
||||
const { tenantId } = req;
|
||||
const billDTO: IBillEditDTO = this.matchedBodyData(req);
|
||||
|
||||
const billOTD: BillOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true
|
||||
});
|
||||
const editedBill = await this.billsService.editBill(tenantId, billId, billOTD);
|
||||
|
||||
return res.status(200).send({ id: billId });
|
||||
try {
|
||||
const editedBill = await this.billsService.editBill(tenantId, billId, billDTO);
|
||||
return res.status(200).send({ id: billId });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -295,13 +181,17 @@ export default class BillsController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
async getBill(req: Request, res: Response) {
|
||||
async getBill(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const { id: billId } = req.params;
|
||||
|
||||
const bill = await this.billsService.getBillWithMetadata(tenantId, billId);
|
||||
try {
|
||||
const bill = await this.billsService.getBillWithMetadata(tenantId, billId);
|
||||
|
||||
return res.status(200).send({ bill });
|
||||
return res.status(200).send({ bill });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -310,13 +200,19 @@ export default class BillsController extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @return {Response}
|
||||
*/
|
||||
async deleteBill(req: Request, res: Response) {
|
||||
async deleteBill(req: Request, res: Response, next: NextFunction) {
|
||||
const billId = req.params.id;
|
||||
const { tenantId } = req;
|
||||
|
||||
await this.billsService.deleteBill(tenantId, billId);
|
||||
|
||||
return res.status(200).send({ id: billId });
|
||||
try {
|
||||
await this.billsService.deleteBill(tenantId, billId);
|
||||
return res.status(200).send({
|
||||
id: billId,
|
||||
message: 'The given bill deleted successfully.',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -325,7 +221,50 @@ export default class BillsController extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @return {Response}
|
||||
*/
|
||||
async listingBills(req: Request, res: Response) {
|
||||
async billsList(req: Request, res: Response) {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles 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 === 'BILL_NOT_FOUND') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'BILL_NOT_FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'BILL_NUMBER_EXISTS') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'BILL.NUMBER.EXISTS', code: 500 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'BILL_VENDOR_NOT_FOUND') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'BILL_VENDOR_NOT_FOUND', code: 600 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'BILL_ITEMS_NOT_PURCHASABLE') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'BILL_ITEMS_NOT_PURCHASABLE', code: 700 }]
|
||||
})
|
||||
}
|
||||
if (error.errorType === 'NOT_PURCHASE_ABLE_ITEMS') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'NOT_PURCHASE_ABLE_ITEMS', code: 800 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'BILL_ITEMS_NOT_FOUND') {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.FOUND', code: 400 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import express from 'express';
|
||||
import { Router } from 'express';
|
||||
import { Container, Service } from 'typedi';
|
||||
import Bills from 'api/controllers/Purchases/Bills'
|
||||
import BillPayments from 'api/controllers/Purchases/BillsPayments';
|
||||
@@ -7,7 +7,7 @@ import BillPayments from 'api/controllers/Purchases/BillsPayments';
|
||||
export default class PurchasesController {
|
||||
|
||||
router() {
|
||||
const router = express.Router();
|
||||
const router = Router();
|
||||
|
||||
router.use('/bills', Container.get(Bills).router());
|
||||
router.use('/bill_payments', Container.get(BillPayments).router());
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { check, param, query, matchedData } from 'express-validator';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ISaleEstimate, ISaleEstimateOTD } from 'interfaces';
|
||||
@@ -25,9 +25,9 @@ export default class SalesEstimatesController extends BaseController {
|
||||
'/',
|
||||
this.estimateValidationSchema,
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateEstimateCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEstimateNumberExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEstimateEntriesItemsExistance.bind(this)),
|
||||
// asyncMiddleware(this.validateEstimateCustomerExistance.bind(this)),
|
||||
// asyncMiddleware(this.validateEstimateNumberExistance.bind(this)),
|
||||
// asyncMiddleware(this.validateEstimateEntriesItemsExistance.bind(this)),
|
||||
asyncMiddleware(this.newEstimate.bind(this))
|
||||
);
|
||||
router.post(
|
||||
@@ -36,11 +36,11 @@ export default class SalesEstimatesController extends BaseController {
|
||||
...this.estimateValidationSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateEstimateIdExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEstimateCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEstimateNumberExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEstimateEntriesItemsExistance.bind(this)),
|
||||
asyncMiddleware(this.valdiateInvoiceEntriesIdsExistance.bind(this)),
|
||||
// asyncMiddleware(this.validateEstimateIdExistance.bind(this)),
|
||||
// asyncMiddleware(this.validateEstimateCustomerExistance.bind(this)),
|
||||
// asyncMiddleware(this.validateEstimateNumberExistance.bind(this)),
|
||||
// asyncMiddleware(this.validateEstimateEntriesItemsExistance.bind(this)),
|
||||
// asyncMiddleware(this.valdiateInvoiceEntriesIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.editEstimate.bind(this))
|
||||
);
|
||||
router.delete(
|
||||
@@ -48,14 +48,14 @@ export default class SalesEstimatesController extends BaseController {
|
||||
this.validateSpecificEstimateSchema,
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateEstimateIdExistance.bind(this)),
|
||||
// asyncMiddleware(this.validateEstimateIdExistance.bind(this)),
|
||||
asyncMiddleware(this.deleteEstimate.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
this.validateSpecificEstimateSchema,
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateEstimateIdExistance.bind(this)),
|
||||
// asyncMiddleware(this.validateEstimateIdExistance.bind(this)),
|
||||
asyncMiddleware(this.getEstimate.bind(this))
|
||||
);
|
||||
router.get(
|
||||
@@ -114,120 +114,6 @@ export default class SalesEstimatesController extends BaseController {
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether the estimate customer exists on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateEstimateCustomerExistance(req: Request, res: Response, next: Function) {
|
||||
const estimate = { ...req.body };
|
||||
const { Customer } = req.models
|
||||
|
||||
const foundCustomer = await Customer.query().findById(estimate.customer_id);
|
||||
|
||||
if (!foundCustomer) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'CUSTOMER.ID.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the estimate number unique on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateEstimateNumberExistance(req: Request, res: Response, next: Function) {
|
||||
const estimate = { ...req.body };
|
||||
const { tenantId } = req;
|
||||
|
||||
const isEstNumberUnqiue = await this.saleEstimateService.isEstimateNumberUnique(
|
||||
tenantId,
|
||||
estimate.estimate_number,
|
||||
req.params.id,
|
||||
);
|
||||
if (isEstNumberUnqiue) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ESTIMATE.NUMBER.IS.NOT.UNQIUE', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the estimate entries items ids existance on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateEstimateEntriesItemsExistance(req: Request, res: Response, next: Function) {
|
||||
const tenantId = req.tenantId;
|
||||
const estimate = { ...req.body };
|
||||
const estimateItemsIds = estimate.entries.map(e => e.item_id);
|
||||
|
||||
// Validate items ids in estimate entries exists.
|
||||
const notFoundItemsIds = await this.itemsService.isItemsIdsExists(tenantId, estimateItemsIds);
|
||||
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether the sale estimate id exists on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateEstimateIdExistance(req: Request, res: Response, next: Function) {
|
||||
const { id: estimateId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
const storedEstimate = await this.saleEstimateService
|
||||
.getEstimate(tenantId, estimateId);
|
||||
|
||||
if (!storedEstimate) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'SALE.ESTIMATE.ID.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate sale invoice entries ids existance on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async valdiateInvoiceEntriesIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const { ItemEntry } = req.models;
|
||||
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const saleInvoice = { ...req.body };
|
||||
const entriesIds = saleInvoice.entries
|
||||
.filter(e => e.id)
|
||||
.map((e) => e.id);
|
||||
|
||||
const foundEntries = await ItemEntry.query()
|
||||
.whereIn('id', entriesIds)
|
||||
.where('reference_type', 'SaleInvoice')
|
||||
.where('reference_id', saleInvoiceId);
|
||||
|
||||
if (foundEntries.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'ENTRIES.IDS.NOT.EXISTS', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle create a new estimate with associated entries.
|
||||
* @param {Request} req -
|
||||
|
||||
@@ -32,7 +32,7 @@ export default class SaleInvoicesController extends BaseController{
|
||||
this.saleInvoiceValidationSchema,
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateInvoiceCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceNumberUnique.bind(this)),
|
||||
// asyncMiddleware(this.validateInvoiceNumberUnique.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceItemsIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.validateNonSellableEntriesItems.bind(this)),
|
||||
asyncMiddleware(this.newSaleInvoice.bind(this))
|
||||
@@ -46,7 +46,7 @@ export default class SaleInvoicesController extends BaseController{
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validateInvoiceExistance.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceNumberUnique.bind(this)),
|
||||
// asyncMiddleware(this.validateInvoiceNumberUnique.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceItemsIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.valdiateInvoiceEntriesIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEntriesIdsExistance.bind(this)),
|
||||
@@ -312,18 +312,19 @@ export default class SaleInvoicesController extends BaseController{
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async newSaleInvoice(req: Request, res: Response) {
|
||||
async newSaleInvoice(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const saleInvoiceOTD: ISaleInvoiceOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true
|
||||
});
|
||||
const saleInvoiceOTD: ISaleInvoiceOTD = this.matchedBodyData(req);
|
||||
|
||||
// Creates a new sale invoice with associated entries.
|
||||
const storedSaleInvoice = await this.saleInvoiceService.createSaleInvoice(
|
||||
tenantId, saleInvoiceOTD,
|
||||
);
|
||||
return res.status(200).send({ id: storedSaleInvoice.id });
|
||||
try {
|
||||
// Creates a new sale invoice with associated entries.
|
||||
const storedSaleInvoice = await this.saleInvoiceService.createSaleInvoice(
|
||||
tenantId, saleInvoiceOTD,
|
||||
);
|
||||
return res.status(200).send({ id: storedSaleInvoice.id });
|
||||
} catch (error) {
|
||||
next(error)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -332,18 +333,18 @@ export default class SaleInvoicesController extends BaseController{
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async editSaleInvoice(req: Request, res: Response) {
|
||||
async editSaleInvoice(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const saleInvoiceOTD: ISaleInvoiceOTD = this.matchedBodyData(req);
|
||||
|
||||
const saleInvoiceOTD: ISaleInvoiceOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true
|
||||
});
|
||||
// Update the given sale invoice details.
|
||||
await this.saleInvoiceService.editSaleInvoice(tenantId, saleInvoiceId, saleInvoiceOTD);
|
||||
|
||||
return res.status(200).send({ id: saleInvoiceId });
|
||||
try {
|
||||
// Update the given sale invoice details.
|
||||
await this.saleInvoiceService.editSaleInvoice(tenantId, saleInvoiceId, saleInvoiceOTD);
|
||||
return res.status(200).send({ id: saleInvoiceId });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -352,14 +353,18 @@ export default class SaleInvoicesController extends BaseController{
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async deleteSaleInvoice(req: Request, res: Response) {
|
||||
async deleteSaleInvoice(req: Request, res: Response, next: NextFunction) {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
// Deletes the sale invoice with associated entries and journal transaction.
|
||||
await this.saleInvoiceService.deleteSaleInvoice(tenantId, saleInvoiceId);
|
||||
|
||||
return res.status(200).send({ id: saleInvoiceId });
|
||||
try {
|
||||
// Deletes the sale invoice with associated entries and journal transaction.
|
||||
await this.saleInvoiceService.deleteSaleInvoice(tenantId, saleInvoiceId);
|
||||
|
||||
return res.status(200).send({ id: saleInvoiceId });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { check, param, query, matchedData } from 'express-validator';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import asyncMiddleware from 'api/middleware/asyncMiddleware';
|
||||
import AccountsService from 'services/Accounts/AccountsService';
|
||||
import ItemsService from 'services/Items/ItemsService';
|
||||
import SaleReceiptService from 'services/Sales/SalesReceipts';
|
||||
import BaseController from '../BaseController';
|
||||
import { ISaleReceiptDTO } from 'interfaces/SaleReceipt';
|
||||
|
||||
@Service()
|
||||
export default class SalesReceiptsController extends BaseController{
|
||||
@@ -232,20 +233,21 @@ export default class SalesReceiptsController extends BaseController{
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async newSaleReceipt(req: Request, res: Response) {
|
||||
async newSaleReceipt(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const saleReceiptDTO: ISaleReceiptDTO = this.matchedBodyData(req);
|
||||
|
||||
const saleReceipt = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true,
|
||||
});
|
||||
// Store the given sale receipt details with associated entries.
|
||||
const storedSaleReceipt = await this.saleReceiptService
|
||||
.createSaleReceipt(
|
||||
tenantId,
|
||||
saleReceipt,
|
||||
);
|
||||
return res.status(200).send({ id: storedSaleReceipt.id });
|
||||
try {
|
||||
// Store the given sale receipt details with associated entries.
|
||||
const storedSaleReceipt = await this.saleReceiptService
|
||||
.createSaleReceipt(
|
||||
tenantId,
|
||||
saleReceiptDTO,
|
||||
);
|
||||
return res.status(200).send({ id: storedSaleReceipt.id });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -253,14 +255,18 @@ export default class SalesReceiptsController extends BaseController{
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async deleteSaleReceipt(req: Request, res: Response) {
|
||||
async deleteSaleReceipt(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const { id: saleReceiptId } = req.params;
|
||||
|
||||
// Deletes the sale receipt.
|
||||
await this.saleReceiptService.deleteSaleReceipt(tenantId, saleReceiptId);
|
||||
|
||||
return res.status(200).send({ id: saleReceiptId });
|
||||
try {
|
||||
// Deletes the sale receipt.
|
||||
await this.saleReceiptService.deleteSaleReceipt(tenantId, saleReceiptId);
|
||||
|
||||
return res.status(200).send({ id: saleReceiptId });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -269,25 +275,22 @@ export default class SalesReceiptsController extends BaseController{
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async editSaleReceipt(req: Request, res: Response) {
|
||||
async editSaleReceipt(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const { id: saleReceiptId } = req.params;
|
||||
const saleReceipt = { ...req.body };
|
||||
const errorReasons = [];
|
||||
|
||||
// Handle all errors with reasons messages.
|
||||
if (errorReasons.length > 0) {
|
||||
return res.boom.badRequest(null, { errors: errorReasons });
|
||||
}
|
||||
// Update the given sale receipt details.
|
||||
await this.saleReceiptService.editSaleReceipt(
|
||||
tenantId,
|
||||
saleReceiptId,
|
||||
saleReceipt,
|
||||
);
|
||||
|
||||
return res.status(200).send();
|
||||
try {
|
||||
// Update the given sale receipt details.
|
||||
await this.saleReceiptService.editSaleReceipt(
|
||||
tenantId,
|
||||
saleReceiptId,
|
||||
saleReceipt,
|
||||
);
|
||||
return res.status(200).send();
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,7 +29,7 @@ import Settings from 'api/controllers/Settings';
|
||||
import Currencies from 'api/controllers/Currencies';
|
||||
import Customers from 'api/controllers/Contacts/Customers';
|
||||
import Vendors from 'api/controllers/Contacts/Vendors';
|
||||
import Sales from 'api/controllers/Sales'
|
||||
// import Sales from 'api/controllers/Sales'
|
||||
import Purchases from 'api/controllers/Purchases';
|
||||
import Resources from './controllers/Resources';
|
||||
import ExchangeRates from 'api/controllers/ExchangeRates';
|
||||
@@ -95,7 +95,7 @@ export default () => {
|
||||
dashboard.use('/customers', Container.get(Customers).router());
|
||||
dashboard.use('/vendors', Container.get(Vendors).router());
|
||||
// dashboard.use('/sales', Container.get(Sales).router());
|
||||
// dashboard.use('/purchases', Container.get(Purchases).router());
|
||||
dashboard.use('/purchases', Container.get(Purchases).router());
|
||||
dashboard.use('/resources', Container.get(Resources).router());
|
||||
dashboard.use('/exchange_rates', Container.get(ExchangeRates).router());
|
||||
dashboard.use('/media', Container.get(Media).router());
|
||||
|
||||
Reference in New Issue
Block a user