feat: remove path alias.

feat: remove Webpack and depend on nodemon.
feat: refactoring expenses.
feat: optimize system users with caching.
feat: architecture tenant optimize.
This commit is contained in:
Ahmed Bouhuolia
2020-09-15 00:51:39 +02:00
parent ad00f140d1
commit a22c8395f3
293 changed files with 3391 additions and 1637 deletions

View File

@@ -0,0 +1,400 @@
import { Router, Request, Response } from 'express';
import { check, param, query, matchedData } from 'express-validator';
import { Service, Inject } from 'typedi';
import { difference } from 'lodash';
import { BillOTD } from 'interfaces';
import validateMiddleware from 'api/middleware/validateMiddleware';
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 DynamicListingBuilder from 'services/DynamicListing/DynamicListingBuilder';
import DynamicListing from 'services/DynamicListing/DynamicListing';
import { dynamicListingErrorsToResponse } from 'services/DynamicListing/HasDynamicListing';
@Service()
export default class BillsController extends BaseController {
@Inject()
itemsService: ItemsService;
@Inject()
billsService: BillsService;
@Inject()
tenancy: TenancyService;
/**
* Router constructor.
*/
router() {
const router = Router();
router.post(
'/',
[...this.billValidationSchema],
validateMiddleware,
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))
);
router.post(
'/:id',
[...this.billValidationSchema, ...this.specificBillValidationSchema],
validateMiddleware,
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],
validateMiddleware,
asyncMiddleware(this.validateBillExistance.bind(this)),
asyncMiddleware(this.getBill.bind(this))
);
router.get(
'/',
[...this.billsListingValidationSchema],
validateMiddleware,
asyncMiddleware(this.listingBills.bind(this))
);
router.delete(
'/:id',
[...this.specificBillValidationSchema],
validateMiddleware,
asyncMiddleware(this.validateBillExistance.bind(this)),
asyncMiddleware(this.deleteBill.bind(this))
);
return router;
}
/**
* Common validation schema.
*/
get billValidationSchema() {
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.
*/
get specificBillValidationSchema() {
return [param('id').exists().isNumeric().toInt()];
}
/**
* Bills list validation schema.
*/
get billsListingValidationSchema() {
return [
query('custom_view_id').optional().isNumeric().toInt(),
query('stringified_filter_roles').optional().isJSON(),
query('page').optional().isNumeric().toInt(),
query('page_size').optional().isNumeric().toInt(),
query('column_sort_by').optional(),
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;
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 });
}
/**
* Edit bill details with associated entries and rewrites journal transactions.
* @param {Request} req
* @param {Response} res
*/
async editBill(req: Request, res: Response) {
const { id: billId } = req.params;
const { ItemEntry } = req.models;
const { tenantId } = 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 });
}
/**
* Retrieve the given bill details with associated item entries.
* @param {Request} req
* @param {Response} res
* @return {Response}
*/
async getBill(req: Request, res: Response) {
const { tenantId } = req;
const { id: billId } = req.params;
const bill = await this.billsService.getBillWithMetadata(tenantId, billId);
return res.status(200).send({ bill });
}
/**
* Deletes the given bill with associated entries and journal transactions.
* @param {Request} req -
* @param {Response} res -
* @return {Response}
*/
async deleteBill(req: Request, res: Response) {
const billId = req.params.id;
const { tenantId } = req;
await this.billsService.deleteBill(tenantId, billId);
return res.status(200).send({ id: billId });
}
/**
* Listing bills with pagination meta.
* @param {Request} req -
* @param {Response} res -
* @return {Response}
*/
async listingBills(req: Request, res: Response) {
const filter = {
filter_roles: [],
sort_order: 'asc',
page: 1,
page_size: 10,
...req.query,
};
if (filter.stringified_filter_roles) {
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
}
const { Bill, View, Resource } = req.models;
const resource = await Resource.query()
.remember()
.where('name', 'bills')
.withGraphFetched('fields')
.first();
if (!resource) {
return res.status(400).send({
errors: [{ type: 'BILLS_RESOURCE_NOT_FOUND', code: 200 }],
});
}
const viewMeta = await View.query()
.modify('allMetadata')
.modify('specificOrFavourite', filter.custom_view_id)
.where('resource_id', resource.id)
.first();
const listingBuilder = new DynamicListingBuilder();
const errorReasons = [];
listingBuilder.addModelClass(Bill);
listingBuilder.addCustomViewId(filter.custom_view_id);
listingBuilder.addFilterRoles(filter.filter_roles);
listingBuilder.addSortBy(filter.sort_by, filter.sort_order);
listingBuilder.addView(viewMeta);
const dynamicListing = new DynamicListing(listingBuilder);
if (dynamicListing instanceof Error) {
const errors = dynamicListingErrorsToResponse(dynamicListing);
errorReasons.push(...errors);
}
if (errorReasons.length > 0) {
return res.status(400).send({ errors: errorReasons });
}
const bills = await Bill.query()
.onBuild((builder) => {
dynamicListing.buildQuery()(builder);
builder.withGraphFetched('vendor');
return builder;
})
.pagination(filter.page - 1, filter.page_size);
return res.status(200).send({
bills: {
...bills,
...(viewMeta
? {
view_meta: {
customViewId: viewMeta.id,
},
}
: {}),
},
});
}
}

View File

@@ -0,0 +1,453 @@
import { Router } from 'express';
import { Service, Inject } from 'typedi';
import { check, param, query, ValidationChain, matchedData } from 'express-validator';
import { difference } from 'lodash';
import asyncMiddleware from 'api/middleware/asyncMiddleware';
import validateMiddleware from 'api/middleware/validateMiddleware';
import BaseController from 'api/controllers/BaseController';
import BillPaymentsService from 'services/Purchases/BillPayments';
import AccountsService from 'services/Accounts/AccountsService';
import DynamicListingBuilder from 'services/DynamicListing/DynamicListingBuilder';
import DynamicListing from 'services/DynamicListing/DynamicListing';
import { dynamicListingErrorsToResponse } from 'services/DynamicListing/hasDynamicListing';
/**
* Bills payments controller.
* @service
*/
@Service()
export default class BillsPayments extends BaseController {
@Inject()
billPaymentService: BillPaymentsService;
@Inject()
accountsService: AccountsService;
/**
* Router constructor.
*/
router() {
const router = Router();
router.post('/', [
...this.billPaymentSchemaValidation,
],
validateMiddleware,
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)),
);
router.post('/:id', [
...this.billPaymentSchemaValidation,
...this.specificBillPaymentValidateSchema,
],
validateMiddleware,
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)),
)
router.delete('/:id',
this.specificBillPaymentValidateSchema,
validateMiddleware,
asyncMiddleware(this.validateBillPaymentExistance.bind(this)),
asyncMiddleware(this.deleteBillPayment.bind(this)),
);
router.get('/:id',
this.specificBillPaymentValidateSchema,
validateMiddleware,
asyncMiddleware(this.validateBillPaymentExistance.bind(this)),
asyncMiddleware(this.getBillPayment.bind(this)),
);
router.get('/',
this.listingValidationSchema,
validateMiddleware,
asyncMiddleware(this.getBillsPayments.bind(this))
);
return router;
}
/**
* Bill payments schema validation.
*/
get billPaymentSchemaValidation(): ValidationChain[] {
return [
check('vendor_id').exists().isNumeric().toInt(),
check('payment_account_id').exists().isNumeric().toInt(),
check('payment_number').exists().trim().escape(),
check('payment_date').exists(),
check('description').optional().trim().escape(),
check('reference').optional().trim().escape(),
check('entries').exists().isArray({ min: 1 }),
check('entries.*.bill_id').exists().isNumeric().toInt(),
check('entries.*.payment_amount').exists().isNumeric().toInt(),
];
}
/**
* Specific bill payment schema validation.
*/
get specificBillPaymentValidateSchema(): ValidationChain[] {
return [
param('id').exists().isNumeric().toInt(),
];
}
/**
* Bills payment list validation schema.
*/
get listingValidationSchema(): ValidationChain[] {
return [
query('custom_view_id').optional().isNumeric().toInt(),
query('stringified_filter_roles').optional().isJSON(),
query('column_sort_by').optional(),
query('sort_order').optional().isIn(['desc', 'asc']),
query('page').optional().isNumeric().toInt(),
query('page_size').optional().isNumeric().toInt(),
];
}
/**
* 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
* @param {Request} req
* @param {Response} res
* @param {Response} res
*/
async createBillPayment(req: Request, res: Response) {
const { tenantId } = req;
const billPayment = matchedData(req, {
locations: ['body'],
includeOptionals: true,
});
const storedPayment = await this.billPaymentService
.createBillPayment(tenantId, billPayment);
return res.status(200).send({ id: storedPayment.id });
}
/**
* Edits the given bill payment details.
* @param {Request} req
* @param {Response} res
*/
async editBillPayment(req: Request, res: Response) {
const { tenantId } = req;
const billPayment = matchedData(req, {
locations: ['body'],
includeOptionals: true,
});
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 });
}
/**
* Deletes the bill payment and revert the journal
* transactions with accounts balance.
* @param {Request} req -
* @param {Response} res -
* @return {Response} res -
*/
async deleteBillPayment(req: Request, res: Response) {
const { tenantId } = req;
const { id: billPaymentId } = req.params;
const billPayment = req.body;
await this.billPaymentService.deleteBillPayment(tenantId, billPaymentId);
return res.status(200).send({ id: billPaymentId });
}
/**
* Retrieve the bill payment.
* @param {Request} req
* @param {Response} res
*/
async getBillPayment(req: Request, res: Response) {
const { tenantId } = req;
const { id: billPaymentId } = req.params;
const billPayment = await this.billPaymentService
.getBillPaymentWithMetadata(tenantId, billPaymentId);
return res.status(200).send({ bill_payment: { ...billPayment } });
}
/**
* Retrieve bills payments listing with pagination metadata.
* @param {Request} req -
* @param {Response} res -
* @return {Response}
*/
async getBillsPayments(req: Request, res: Response) {
const filter = {
filter_roles: [],
sort_order: 'asc',
page: 1,
page_size: 10,
...req.query,
};
if (filter.stringified_filter_roles) {
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
}
const { BillPayment, View, Resource } = req.models;
const resource = await Resource.query()
.where('name', 'bill_payments')
.withGraphFetched('fields')
.first();
if (!resource) {
return res.status(400).send({
errors: [{ type: 'BILL.PAYMENTS.RESOURCE.NOT_FOUND', code: 200 }],
});
}
const viewMeta = await View.query()
.modify('allMetadata')
.modify('specificOrFavourite', filter.custom_view_id)
.where('resource_id', resource.id)
.first();
const listingBuilder = new DynamicListingBuilder();
const errorReasons = [];
listingBuilder.addModelClass(BillPayment);
listingBuilder.addCustomViewId(filter.custom_view_id);
listingBuilder.addFilterRoles(filter.filter_roles);
listingBuilder.addSortBy(filter.sort_by, filter.sort_order);
listingBuilder.addView(viewMeta);
const dynamicListing = new DynamicListing(listingBuilder);
if (dynamicListing instanceof Error) {
const errors = dynamicListingErrorsToResponse(dynamicListing);
errorReasons.push(...errors);
}
if (errorReasons.length > 0) {
return res.status(400).send({ errors: errorReasons });
}
const billPayments = await BillPayment.query().onBuild((builder) => {
dynamicListing.buildQuery()(builder);
builder.withGraphFetched('vendor');
builder.withGraphFetched('paymentAccount');
return builder;
}).pagination(filter.page - 1, filter.page_size);
return res.status(200).send({
bill_payments: {
...billPayments,
...(viewMeta
? {
view_meta: {
customViewId: viewMeta.id,
},
}
: {}),
},
});
}
}

View File

@@ -0,0 +1,16 @@
import express from 'express';
import { Container } from 'typedi';
import Bills from 'api/controllers/Purchases/Bills'
import BillPayments from 'api/controllers/Purchases/BillsPayments';
export default {
router() {
const router = express.Router();
router.use('/bills', Container.get(Bills).router());
router.use('/bill_payments', Container.get(BillPayments).router());
return router;
}
}