mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-18 13:50:31 +00:00
- feat: Optimize tenancy software architecture.
This commit is contained in:
@@ -28,13 +28,11 @@ export default {
|
||||
this.getManualJournal.validation,
|
||||
asyncMiddleware(this.getManualJournal.handler)
|
||||
);
|
||||
|
||||
router.get(
|
||||
'/manual-journals',
|
||||
this.manualJournals.validation,
|
||||
asyncMiddleware(this.manualJournals.handler)
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/make-journal-entries',
|
||||
this.validateMediaIds,
|
||||
@@ -42,13 +40,11 @@ export default {
|
||||
this.makeJournalEntries.validation,
|
||||
asyncMiddleware(this.makeJournalEntries.handler)
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/manual-journals/:id/publish',
|
||||
this.publishManualJournal.validation,
|
||||
asyncMiddleware(this.publishManualJournal.handler)
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/manual-journals/:id',
|
||||
this.validateMediaIds,
|
||||
@@ -56,31 +52,26 @@ export default {
|
||||
this.editManualJournal.validation,
|
||||
asyncMiddleware(this.editManualJournal.handler)
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/manual-journals/:id',
|
||||
this.deleteManualJournal.validation,
|
||||
asyncMiddleware(this.deleteManualJournal.handler)
|
||||
);
|
||||
|
||||
router.delete(
|
||||
'/manual-journals',
|
||||
this.deleteBulkManualJournals.validation,
|
||||
asyncMiddleware(this.deleteBulkManualJournals.handler)
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/recurring-journal-entries',
|
||||
this.recurringJournalEntries.validation,
|
||||
asyncMiddleware(this.recurringJournalEntries.handler)
|
||||
);
|
||||
|
||||
router.post(
|
||||
'quick-journal-entries',
|
||||
this.quickJournalEntries.validation,
|
||||
asyncMiddleware(this.quickJournalEntries.handler)
|
||||
);
|
||||
|
||||
return router;
|
||||
},
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
|
||||
|
||||
|
||||
export default class BaseController {
|
||||
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { check, param, query, ValidationChain } from 'express-validator';
|
||||
import { check, param, query, ValidationChain, matchedData } from 'express-validator';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
import ItemsService from '@/services/Items/ItemsService';
|
||||
@@ -7,23 +8,27 @@ import DynamicListing from '@/services/DynamicListing/DynamicListing';
|
||||
import DynamicListingBuilder from '@/services/DynamicListing/DynamicListingBuilder';
|
||||
import { dynamicListingErrorsToResponse } from '@/services/DynamicListing/hasDynamicListing';
|
||||
|
||||
@Service()
|
||||
export default class ItemsController {
|
||||
@Inject()
|
||||
itemsService: ItemsService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
router() {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
this.validateItemSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateCategoryExistance),
|
||||
asyncMiddleware(this.validateCostAccountExistance),
|
||||
asyncMiddleware(this.validateSellAccountExistance),
|
||||
asyncMiddleware(this.validateInventoryAccountExistance),
|
||||
asyncMiddleware(this.validateItemNameExistance),
|
||||
asyncMiddleware(this.newItem),
|
||||
asyncMiddleware(this.validateCategoryExistance.bind(this)),
|
||||
asyncMiddleware(this.validateCostAccountExistance.bind(this)),
|
||||
asyncMiddleware(this.validateSellAccountExistance.bind(this)),
|
||||
asyncMiddleware(this.validateInventoryAccountExistance.bind(this)),
|
||||
asyncMiddleware(this.validateItemNameExistance.bind(this)),
|
||||
asyncMiddleware(this.newItem.bind(this)),
|
||||
);
|
||||
router.post(
|
||||
'/:id', [
|
||||
@@ -31,49 +36,41 @@ export default class ItemsController {
|
||||
...this.validateSpecificItemSchema,
|
||||
],
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateItemExistance),
|
||||
asyncMiddleware(this.validateCategoryExistance),
|
||||
asyncMiddleware(this.validateCostAccountExistance),
|
||||
asyncMiddleware(this.validateSellAccountExistance),
|
||||
asyncMiddleware(this.validateInventoryAccountExistance),
|
||||
asyncMiddleware(this.validateItemNameExistance),
|
||||
asyncMiddleware(this.editItem),
|
||||
asyncMiddleware(this.validateItemExistance.bind(this)),
|
||||
asyncMiddleware(this.validateCategoryExistance.bind(this)),
|
||||
asyncMiddleware(this.validateCostAccountExistance.bind(this)),
|
||||
asyncMiddleware(this.validateSellAccountExistance.bind(this)),
|
||||
asyncMiddleware(this.validateInventoryAccountExistance.bind(this)),
|
||||
asyncMiddleware(this.validateItemNameExistance.bind(this)),
|
||||
asyncMiddleware(this.editItem.bind(this)),
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
this.validateSpecificItemSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateItemExistance),
|
||||
asyncMiddleware(this.deleteItem),
|
||||
asyncMiddleware(this.validateItemExistance.bind(this)),
|
||||
asyncMiddleware(this.deleteItem.bind(this)),
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
this.validateSpecificItemSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateItemExistance),
|
||||
asyncMiddleware(this.getItem),
|
||||
asyncMiddleware(this.validateItemExistance.bind(this)),
|
||||
asyncMiddleware(this.getItem.bind(this)),
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.validateListQuerySchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.listItems),
|
||||
asyncMiddleware(this.listItems.bind(this)),
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate item schema.
|
||||
*
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
* @return {ValidationChain[]} - validation chain.
|
||||
*/
|
||||
static get validateItemSchema(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: Function,
|
||||
): ValidationChain[] {
|
||||
get validateItemSchema(): ValidationChain[] {
|
||||
return [
|
||||
check('name').exists(),
|
||||
check('type').exists().trim().escape()
|
||||
@@ -122,7 +119,7 @@ export default class ItemsController {
|
||||
/**
|
||||
* Validate specific item params schema.
|
||||
*/
|
||||
static get validateSpecificItemSchema(): ValidationChain[] {
|
||||
get validateSpecificItemSchema(): ValidationChain[] {
|
||||
return [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
];
|
||||
@@ -132,7 +129,7 @@ export default class ItemsController {
|
||||
/**
|
||||
* Validate list query schema
|
||||
*/
|
||||
static get validateListQuerySchema() {
|
||||
get validateListQuerySchema() {
|
||||
return [
|
||||
query('column_sort_order').optional().isIn(['created_at', 'name', 'amount', 'sku']),
|
||||
query('sort_order').optional().isIn(['desc', 'asc']),
|
||||
@@ -149,7 +146,7 @@ export default class ItemsController {
|
||||
* @param {Response} res -
|
||||
* @param {NextFunction} next -
|
||||
*/
|
||||
static async validateItemExistance(req: Request, res: Response, next: Function) {
|
||||
async validateItemExistance(req: Request, res: Response, next: Function) {
|
||||
const { Item } = req.models;
|
||||
const itemId: number = req.params.id;
|
||||
|
||||
@@ -169,7 +166,7 @@ export default class ItemsController {
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
static async validateItemNameExistance(req: Request, res: Response, next: Function) {
|
||||
async validateItemNameExistance(req: Request, res: Response, next: Function) {
|
||||
const { Item } = req.models;
|
||||
const item = req.body;
|
||||
const itemId: number = req.params.id;
|
||||
@@ -195,7 +192,7 @@ export default class ItemsController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateCategoryExistance(req: Request, res: Response, next: Function) {
|
||||
async validateCategoryExistance(req: Request, res: Response, next: Function) {
|
||||
const { ItemCategory } = req.models;
|
||||
const item = req.body;
|
||||
|
||||
@@ -217,7 +214,7 @@ export default class ItemsController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateCostAccountExistance(req: Request, res: Response, next: Function) {
|
||||
async validateCostAccountExistance(req: Request, res: Response, next: Function) {
|
||||
const { Account, AccountType } = req.models;
|
||||
const item = req.body;
|
||||
|
||||
@@ -244,7 +241,7 @@ export default class ItemsController {
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
static async validateSellAccountExistance(req: Request, res: Response, next: Function) {
|
||||
async validateSellAccountExistance(req: Request, res: Response, next: Function) {
|
||||
const { Account, AccountType } = req.models;
|
||||
const item = req.body;
|
||||
|
||||
@@ -271,7 +268,7 @@ export default class ItemsController {
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
static async validateInventoryAccountExistance(req: Request, res: Response, next: Function) {
|
||||
async validateInventoryAccountExistance(req: Request, res: Response, next: Function) {
|
||||
const { Account, AccountType } = req.models;
|
||||
const item = req.body;
|
||||
|
||||
@@ -297,9 +294,14 @@ export default class ItemsController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async newItem(req: Request, res: Response,) {
|
||||
const item = req.body;
|
||||
const storedItem = await ItemsService.newItem(item);
|
||||
async newItem(req: Request, res: Response,) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const item = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true
|
||||
});
|
||||
const storedItem = await this.itemsService.newItem(tenantId, item);
|
||||
|
||||
return res.status(200).send({ id: storedItem.id });
|
||||
}
|
||||
@@ -309,10 +311,15 @@ export default class ItemsController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async editItem(req: Request, res: Response) {
|
||||
const item = req.body;
|
||||
async editItem(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const itemId: number = req.params.id;
|
||||
const updatedItem = await ItemsService.editItem(item, itemId);
|
||||
const item = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true
|
||||
});
|
||||
const updatedItem = await this.itemsService.editItem(tenantId, item, itemId);
|
||||
|
||||
return res.status(200).send({ id: itemId });
|
||||
}
|
||||
@@ -322,9 +329,11 @@ export default class ItemsController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async deleteItem(req: Request, res: Response) {
|
||||
async deleteItem(req: Request, res: Response) {
|
||||
const itemId: number = req.params.id;
|
||||
await ItemsService.deleteItem(itemId);
|
||||
const { tenantId } = req;
|
||||
|
||||
await this.itemsService.deleteItem(tenantId, itemId);
|
||||
|
||||
return res.status(200).send({ id: itemId });
|
||||
}
|
||||
@@ -335,9 +344,11 @@ export default class ItemsController {
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
static async getItem(req: Request, res: Response) {
|
||||
async getItem(req: Request, res: Response) {
|
||||
const itemId: number = req.params.id;
|
||||
const storedItem = await ItemsService.getItemWithMetadata(itemId);
|
||||
const { tenantId } = req;
|
||||
|
||||
const storedItem = await this.itemsService.getItemWithMetadata(tenantId, itemId);
|
||||
|
||||
return res.status(200).send({ item: storedItem });
|
||||
}
|
||||
@@ -347,7 +358,7 @@ export default class ItemsController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async listItems(req: Request, res: Response) {
|
||||
async listItems(req: Request, res: Response) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
|
||||
@@ -1,63 +1,75 @@
|
||||
import express from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
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 '@/http/middleware/validateMiddleware';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
import BillsService from '@/services/Purchases/Bills';
|
||||
import BaseController from '@/http/controllers/BaseController';
|
||||
import VendorsServices from '@/services/Vendors/VendorsService';
|
||||
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';
|
||||
import { difference } from 'lodash';
|
||||
|
||||
@Service()
|
||||
export default class BillsController extends BaseController {
|
||||
@Inject()
|
||||
itemsService: ItemsService;
|
||||
|
||||
@Inject()
|
||||
billsService: BillsService;
|
||||
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
const router = express.Router();
|
||||
router() {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
[...this.billValidationSchema],
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateVendorExistance),
|
||||
asyncMiddleware(this.validateItemsIds),
|
||||
asyncMiddleware(this.validateBillNumberExists),
|
||||
asyncMiddleware(this.validateNonPurchasableEntriesItems),
|
||||
asyncMiddleware(this.newBill)
|
||||
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),
|
||||
asyncMiddleware(this.validateVendorExistance),
|
||||
asyncMiddleware(this.validateItemsIds),
|
||||
asyncMiddleware(this.validateEntriesIdsExistance),
|
||||
asyncMiddleware(this.validateNonPurchasableEntriesItems),
|
||||
asyncMiddleware(this.editBill)
|
||||
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),
|
||||
asyncMiddleware(this.getBill)
|
||||
asyncMiddleware(this.validateBillExistance.bind(this)),
|
||||
asyncMiddleware(this.getBill.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
[...this.billsListingValidationSchema],
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.listingBills)
|
||||
asyncMiddleware(this.listingBills.bind(this))
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
[...this.specificBillValidationSchema],
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateBillExistance),
|
||||
asyncMiddleware(this.deleteBill)
|
||||
asyncMiddleware(this.validateBillExistance.bind(this)),
|
||||
asyncMiddleware(this.deleteBill.bind(this))
|
||||
);
|
||||
return router;
|
||||
}
|
||||
@@ -65,7 +77,7 @@ export default class BillsController extends BaseController {
|
||||
/**
|
||||
* Common validation schema.
|
||||
*/
|
||||
static get billValidationSchema() {
|
||||
get billValidationSchema() {
|
||||
return [
|
||||
check('bill_number').exists().trim().escape(),
|
||||
check('bill_date').exists().isISO8601(),
|
||||
@@ -87,14 +99,14 @@ export default class BillsController extends BaseController {
|
||||
/**
|
||||
* Bill validation schema.
|
||||
*/
|
||||
static get specificBillValidationSchema() {
|
||||
get specificBillValidationSchema() {
|
||||
return [param('id').exists().isNumeric().toInt()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Bills list validation schema.
|
||||
*/
|
||||
static get billsListingValidationSchema() {
|
||||
get billsListingValidationSchema() {
|
||||
return [
|
||||
query('custom_view_id').optional().isNumeric().toInt(),
|
||||
query('stringified_filter_roles').optional().isJSON(),
|
||||
@@ -107,14 +119,17 @@ export default class BillsController extends BaseController {
|
||||
|
||||
/**
|
||||
* Validates whether the vendor is exist.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateVendorExistance(req, res, next) {
|
||||
const isVendorExists = await VendorsServices.isVendorExists(
|
||||
req.body.vendor_id
|
||||
);
|
||||
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 }],
|
||||
@@ -125,12 +140,17 @@ export default class BillsController extends BaseController {
|
||||
|
||||
/**
|
||||
* Validates the given bill existance.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateBillExistance(req, res, next) {
|
||||
const isBillExists = await BillsService.isBillExists(req.params.id);
|
||||
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 }],
|
||||
@@ -141,13 +161,17 @@ export default class BillsController extends BaseController {
|
||||
|
||||
/**
|
||||
* Validates the entries items ids.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateItemsIds(req, res, 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 ItemsService.isItemsIdsExists(itemsIds);
|
||||
|
||||
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 }],
|
||||
@@ -158,15 +182,17 @@ export default class BillsController extends BaseController {
|
||||
|
||||
/**
|
||||
* Validates the bill number existance.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateBillNumberExists(req, res, next) {
|
||||
const isBillNoExists = await BillsService.isBillNoExists(
|
||||
req.body.bill_number
|
||||
);
|
||||
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 }],
|
||||
@@ -181,20 +207,20 @@ export default class BillsController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateEntriesIdsExistance(req, res, 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.tenant()
|
||||
.query()
|
||||
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 }],
|
||||
@@ -209,7 +235,7 @@ export default class BillsController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateNonPurchasableEntriesItems(req, res, 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);
|
||||
@@ -235,17 +261,15 @@ export default class BillsController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async newBill(req, res, next) {
|
||||
async newBill(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const { ItemEntry } = req.models;
|
||||
|
||||
const bill = {
|
||||
...req.body,
|
||||
entries: req.body.entries.map((entry) => ({
|
||||
...entry,
|
||||
amount: ItemEntry.calcAmount(entry),
|
||||
})),
|
||||
};
|
||||
const storedBill = await BillsService.createBill(bill);
|
||||
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 });
|
||||
}
|
||||
@@ -255,17 +279,16 @@ export default class BillsController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async editBill(req, res) {
|
||||
const { ItemEntry } = req.models;
|
||||
async editBill(req: Request, res: Response) {
|
||||
const { id: billId } = req.params;
|
||||
const bill = {
|
||||
...req.body,
|
||||
entries: req.body.entries.map((entry) => ({
|
||||
...entry,
|
||||
amount: ItemEntry.calcAmount(entry),
|
||||
})),
|
||||
};
|
||||
const editedBill = await BillsService.editBill(billId, bill);
|
||||
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 });
|
||||
}
|
||||
@@ -276,9 +299,11 @@ export default class BillsController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
static async getBill(req, res) {
|
||||
async getBill(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const { id: billId } = req.params;
|
||||
const bill = await BillsService.getBillWithMetadata(billId);
|
||||
|
||||
const bill = await this.billsService.getBillWithMetadata(tenantId, billId);
|
||||
|
||||
return res.status(200).send({ bill });
|
||||
}
|
||||
@@ -289,9 +314,11 @@ export default class BillsController extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @return {Response}
|
||||
*/
|
||||
static async deleteBill(req, res) {
|
||||
async deleteBill(req: Request, res: Response) {
|
||||
const billId = req.params.id;
|
||||
await BillsService.deleteBill(billId);
|
||||
const { tenantId } = req;
|
||||
|
||||
await this.billsService.deleteBill(tenantId, billId);
|
||||
|
||||
return res.status(200).send({ id: billId });
|
||||
}
|
||||
@@ -302,7 +329,7 @@ export default class BillsController extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @return {Response}
|
||||
*/
|
||||
static async listingBills(req, res) {
|
||||
async listingBills(req: Request, res: Response) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
@@ -1,6 +1,7 @@
|
||||
|
||||
import { Router } from 'express';
|
||||
import { check, param, query, ValidationChain } from 'express-validator';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { check, param, query, ValidationChain, matchedData } from 'express-validator';
|
||||
import { difference } from 'lodash';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
@@ -13,55 +14,62 @@ import { dynamicListingErrorsToResponse } from '@/services/DynamicListing/hasDyn
|
||||
|
||||
/**
|
||||
* Bills payments controller.
|
||||
* @controller
|
||||
* @service
|
||||
*/
|
||||
@Service()
|
||||
export default class BillsPayments extends BaseController {
|
||||
@Inject()
|
||||
billPaymentService: BillPaymentsService;
|
||||
|
||||
@Inject()
|
||||
accountsService: AccountsService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
router() {
|
||||
const router = Router();
|
||||
|
||||
router.post('/', [
|
||||
...this.billPaymentSchemaValidation,
|
||||
],
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateBillPaymentVendorExistance),
|
||||
asyncMiddleware(this.validatePaymentAccount),
|
||||
asyncMiddleware(this.validatePaymentNumber),
|
||||
asyncMiddleware(this.validateEntriesBillsExistance),
|
||||
asyncMiddleware(this.validateVendorsDueAmount),
|
||||
asyncMiddleware(this.createBillPayment),
|
||||
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),
|
||||
asyncMiddleware(this.validatePaymentAccount),
|
||||
asyncMiddleware(this.validatePaymentNumber),
|
||||
asyncMiddleware(this.validateEntriesIdsExistance),
|
||||
asyncMiddleware(this.validateEntriesBillsExistance),
|
||||
asyncMiddleware(this.validateVendorsDueAmount),
|
||||
asyncMiddleware(this.editBillPayment),
|
||||
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),
|
||||
asyncMiddleware(this.deleteBillPayment),
|
||||
asyncMiddleware(this.validateBillPaymentExistance.bind(this)),
|
||||
asyncMiddleware(this.deleteBillPayment.bind(this)),
|
||||
);
|
||||
router.get('/:id',
|
||||
this.specificBillPaymentValidateSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateBillPaymentExistance),
|
||||
asyncMiddleware(this.getBillPayment),
|
||||
asyncMiddleware(this.validateBillPaymentExistance.bind(this)),
|
||||
asyncMiddleware(this.getBillPayment.bind(this)),
|
||||
);
|
||||
router.get('/',
|
||||
this.listingValidationSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.getBillsPayments)
|
||||
asyncMiddleware(this.getBillsPayments.bind(this))
|
||||
);
|
||||
return router;
|
||||
}
|
||||
@@ -69,7 +77,7 @@ export default class BillsPayments extends BaseController {
|
||||
/**
|
||||
* Bill payments schema validation.
|
||||
*/
|
||||
static get billPaymentSchemaValidation(): ValidationChain[] {
|
||||
get billPaymentSchemaValidation(): ValidationChain[] {
|
||||
return [
|
||||
check('vendor_id').exists().isNumeric().toInt(),
|
||||
check('payment_account_id').exists().isNumeric().toInt(),
|
||||
@@ -87,19 +95,33 @@ export default class BillsPayments extends BaseController {
|
||||
/**
|
||||
* Specific bill payment schema validation.
|
||||
*/
|
||||
static get specificBillPaymentValidateSchema(): ValidationChain[] {
|
||||
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
|
||||
*/
|
||||
static async validateBillPaymentVendorExistance(req: Request, res: Response, next: any ) {
|
||||
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);
|
||||
@@ -118,7 +140,7 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateBillPaymentExistance(req: Request, res: Response, next: any ) {
|
||||
async validateBillPaymentExistance(req: Request, res: Response, next: any ) {
|
||||
const { id: billPaymentId } = req.params;
|
||||
const { BillPayment } = req.models;
|
||||
const foundBillPayment = await BillPayment.query().findById(billPaymentId);
|
||||
@@ -137,11 +159,15 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validatePaymentAccount(req: Request, res: Response, next: any) {
|
||||
async validatePaymentAccount(req: Request, res: Response, next: any) {
|
||||
const { tenantId } = req;
|
||||
const billPayment = { ...req.body };
|
||||
const isAccountExists = await AccountsService.isAccountExists(
|
||||
|
||||
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 }],
|
||||
@@ -156,7 +182,7 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} res
|
||||
*/
|
||||
static async validatePaymentNumber(req: Request, res: Response, next: any) {
|
||||
async validatePaymentNumber(req: Request, res: Response, next: any) {
|
||||
const billPayment = { ...req.body };
|
||||
const { id: billPaymentId } = req.params;
|
||||
const { BillPayment } = req.models;
|
||||
@@ -164,7 +190,6 @@ export default class BillsPayments extends BaseController {
|
||||
const foundBillPayment = await BillPayment.query()
|
||||
.onBuild((builder: any) => {
|
||||
builder.where('payment_number', billPayment.payment_number)
|
||||
|
||||
if (billPaymentId) {
|
||||
builder.whereNot('id', billPaymentId);
|
||||
}
|
||||
@@ -185,7 +210,7 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
static async validateEntriesBillsExistance(req: Request, res: Response, next: any) {
|
||||
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);
|
||||
@@ -210,7 +235,7 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {NextFunction} next
|
||||
* @return {void}
|
||||
*/
|
||||
static async validateVendorsDueAmount(req: Request, res: Response, next: Function) {
|
||||
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()
|
||||
@@ -248,7 +273,7 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
static async validateEntriesIdsExistance(req: Request, res: Response, next: Function) {
|
||||
async validateEntriesIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const { BillPaymentEntry } = req.models;
|
||||
|
||||
const billPayment = { id: req.params.id, ...req.body };
|
||||
@@ -256,7 +281,7 @@ export default class BillsPayments extends BaseController {
|
||||
.filter((entry: any) => entry.id)
|
||||
.map((entry: any) => entry.id);
|
||||
|
||||
const storedEntries = await BillPaymentEntry.tenant().query()
|
||||
const storedEntries = await BillPaymentEntry.query()
|
||||
.where('bill_payment_id', billPayment.id);
|
||||
|
||||
const storedEntriesIds = storedEntries.map((entry: any) => entry.id);
|
||||
@@ -277,9 +302,15 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async createBillPayment(req: Request, res: Response) {
|
||||
const billPayment = { ...req.body };
|
||||
const storedPayment = await BillPaymentsService.createBillPayment(billPayment);
|
||||
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 });
|
||||
}
|
||||
@@ -289,10 +320,14 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async editBillPayment(req: Request, res: Response) {
|
||||
const billPayment = { ...req.body };
|
||||
const { id: billPaymentId } = req.params;
|
||||
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()
|
||||
@@ -300,7 +335,8 @@ export default class BillsPayments extends BaseController {
|
||||
.withGraphFetched('entries')
|
||||
.first();
|
||||
|
||||
await BillPaymentsService.editBillPayment(
|
||||
await this.billPaymentService.editBillPayment(
|
||||
tenantId,
|
||||
billPaymentId,
|
||||
billPayment,
|
||||
oldBillPayment,
|
||||
@@ -315,11 +351,13 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @return {Response} res -
|
||||
*/
|
||||
static async deleteBillPayment(req: Request, res: Response) {
|
||||
async deleteBillPayment(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const { id: billPaymentId } = req.params;
|
||||
const billPayment = req.body;
|
||||
|
||||
await BillPaymentsService.deleteBillPayment(billPaymentId);
|
||||
await this.billPaymentService.deleteBillPayment(tenantId, billPaymentId);
|
||||
|
||||
return res.status(200).send({ id: billPaymentId });
|
||||
}
|
||||
@@ -329,34 +367,23 @@ export default class BillsPayments extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async getBillPayment(req: Request, res: Response) {
|
||||
async getBillPayment(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const { id: billPaymentId } = req.params;
|
||||
const billPayment = await BillPaymentsService.getBillPaymentWithMetadata(billPaymentId);
|
||||
|
||||
const billPayment = await this.billPaymentService
|
||||
.getBillPaymentWithMetadata(tenantId, billPaymentId);
|
||||
|
||||
return res.status(200).send({ bill_payment: { ...billPayment } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Bills payment list validation schema.
|
||||
*/
|
||||
static 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(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve bills payments listing with pagination metadata.
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
* @return {Response}
|
||||
*/
|
||||
static async getBillsPayments(req: Request, res: Response) {
|
||||
async getBillsPayments(req: Request, res: Response) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import express from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import Bills from '@/http/controllers/Purchases/Bills'
|
||||
import BillPayments from '@/http/controllers/Purchases/BillsPayments';
|
||||
|
||||
@@ -7,8 +8,8 @@ export default {
|
||||
router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use('/bills', Bills.router());
|
||||
router.use('/bill_payments', BillPayments.router());
|
||||
router.use('/bills', Container.get(Bills).router());
|
||||
router.use('/bill_payments', Container.get(BillPayments).router());
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import express from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { check, param, query, ValidationChain, matchedData } from 'express-validator';
|
||||
import { difference } from 'lodash';
|
||||
import { PaymentReceiveEntry } from '@/models';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { IPaymentReceive, IPaymentReceiveOTD } from '@/interfaces';
|
||||
import BaseController from '@/http/controllers/BaseController';
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
import PaymentReceiveService from '@/services/Sales/PaymentsReceives';
|
||||
import CustomersService from '@/services/Customers/CustomersService';
|
||||
import SaleInvoicesService from '@/services/Sales/SalesInvoices';
|
||||
import SaleInvoiceService from '@/services/Sales/SalesInvoices';
|
||||
import AccountsService from '@/services/Accounts/AccountsService';
|
||||
import DynamicListing from '@/services/DynamicListing/DynamicListing';
|
||||
import DynamicListingBuilder from '@/services/DynamicListing/DynamicListingBuilder';
|
||||
@@ -15,70 +16,134 @@ import { dynamicListingErrorsToResponse } from '@/services/DynamicListing/hasDyn
|
||||
|
||||
/**
|
||||
* Payments receives controller.
|
||||
* @controller
|
||||
* @service
|
||||
*/
|
||||
@Service()
|
||||
export default class PaymentReceivesController extends BaseController {
|
||||
@Inject()
|
||||
paymentReceiveService: PaymentReceiveService;
|
||||
|
||||
@Inject()
|
||||
customersService: CustomersService;
|
||||
|
||||
@Inject()
|
||||
accountsService: AccountsService;
|
||||
|
||||
@Inject()
|
||||
saleInvoiceService: SaleInvoiceService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
const router = express.Router();
|
||||
router() {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/:id',
|
||||
this.editPaymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validatePaymentReceiveExistance),
|
||||
asyncMiddleware(this.validatePaymentReceiveNoExistance),
|
||||
asyncMiddleware(this.validateCustomerExistance),
|
||||
asyncMiddleware(this.validateDepositAccount),
|
||||
asyncMiddleware(this.validateInvoicesIDs),
|
||||
asyncMiddleware(this.validateEntriesIdsExistance),
|
||||
asyncMiddleware(this.validateInvoicesPaymentsAmount),
|
||||
asyncMiddleware(this.editPaymentReceive),
|
||||
asyncMiddleware(this.validatePaymentReceiveExistance.bind(this)),
|
||||
asyncMiddleware(this.validatePaymentReceiveNoExistance.bind(this)),
|
||||
asyncMiddleware(this.validateCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateDepositAccount.bind(this)),
|
||||
asyncMiddleware(this.validateInvoicesIDs.bind(this)),
|
||||
asyncMiddleware(this.validateEntriesIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.validateInvoicesPaymentsAmount.bind(this)),
|
||||
asyncMiddleware(this.editPaymentReceive.bind(this)),
|
||||
);
|
||||
router.post(
|
||||
'/',
|
||||
this.newPaymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validatePaymentReceiveNoExistance),
|
||||
asyncMiddleware(this.validateCustomerExistance),
|
||||
asyncMiddleware(this.validateDepositAccount),
|
||||
asyncMiddleware(this.validateInvoicesIDs),
|
||||
asyncMiddleware(this.validateInvoicesPaymentsAmount),
|
||||
asyncMiddleware(this.newPaymentReceive),
|
||||
asyncMiddleware(this.validatePaymentReceiveNoExistance.bind(this)),
|
||||
asyncMiddleware(this.validateCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateDepositAccount.bind(this)),
|
||||
asyncMiddleware(this.validateInvoicesIDs.bind(this)),
|
||||
asyncMiddleware(this.validateInvoicesPaymentsAmount.bind(this)),
|
||||
asyncMiddleware(this.newPaymentReceive.bind(this)),
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
this.paymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validatePaymentReceiveExistance),
|
||||
asyncMiddleware(this.getPaymentReceive)
|
||||
asyncMiddleware(this.validatePaymentReceiveExistance.bind(this)),
|
||||
asyncMiddleware(this.getPaymentReceive.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.validatePaymentReceiveList,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.getPaymentReceiveList),
|
||||
asyncMiddleware(this.getPaymentReceiveList.bind(this)),
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
this.paymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validatePaymentReceiveExistance),
|
||||
asyncMiddleware(this.deletePaymentReceive),
|
||||
asyncMiddleware(this.validatePaymentReceiveExistance.bind(this)),
|
||||
asyncMiddleware(this.deletePaymentReceive.bind(this)),
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Payment receive schema.
|
||||
* @return {Array}
|
||||
*/
|
||||
get paymentReceiveSchema(): ValidationChain[] {
|
||||
return [
|
||||
check('customer_id').exists().isNumeric().toInt(),
|
||||
check('payment_date').exists(),
|
||||
check('reference_no').optional(),
|
||||
check('deposit_account_id').exists().isNumeric().toInt(),
|
||||
check('payment_receive_no').exists().trim().escape(),
|
||||
check('statement').optional().trim().escape(),
|
||||
|
||||
check('entries').isArray({ min: 1 }),
|
||||
|
||||
check('entries.*.invoice_id').exists().isNumeric().toInt(),
|
||||
check('entries.*.payment_amount').exists().isNumeric().toInt(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Payment receive list validation schema.
|
||||
*/
|
||||
get validatePaymentReceiveList(): 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 payment receive parameters.
|
||||
*/
|
||||
get paymentReceiveValidation() {
|
||||
return [param('id').exists().isNumeric().toInt()];
|
||||
}
|
||||
|
||||
/**
|
||||
* New payment receive validation schema.
|
||||
* @return {Array}
|
||||
*/
|
||||
get newPaymentReceiveValidation() {
|
||||
return [...this.paymentReceiveSchema];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the payment receive number existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validatePaymentReceiveNoExistance(req, res, next) {
|
||||
const isPaymentNoExists = await PaymentReceiveService.isPaymentReceiveNoExists(
|
||||
async validatePaymentReceiveNoExistance(req: Request, res: Response, next: Function) {
|
||||
const tenantId = req.tenantId;
|
||||
const isPaymentNoExists = await this.paymentReceiveService.isPaymentReceiveNoExists(
|
||||
tenantId,
|
||||
req.body.payment_receive_no,
|
||||
req.params.id,
|
||||
);
|
||||
@@ -96,13 +161,16 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validatePaymentReceiveExistance(req, res, next) {
|
||||
const isPaymentNoExists = await PaymentReceiveService.isPaymentReceiveExists(
|
||||
req.params.id
|
||||
);
|
||||
async validatePaymentReceiveExistance(req: Request, res: Response, next: Function) {
|
||||
const tenantId = req.tenantId;
|
||||
const isPaymentNoExists = await this.paymentReceiveService
|
||||
.isPaymentReceiveExists(
|
||||
tenantId,
|
||||
req.params.id
|
||||
);
|
||||
if (!isPaymentNoExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'PAYMENT.RECEIVE.NO.EXISTS', code: 600 }],
|
||||
errors: [{ type: 'PAYMENT.RECEIVE.NOT.EXISTS', code: 600 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
@@ -114,8 +182,10 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateDepositAccount(req, res, next) {
|
||||
const isDepositAccExists = await AccountsService.isAccountExists(
|
||||
async validateDepositAccount(req: Request, res: Response, next: Function) {
|
||||
const tenantId = req.tenantId;
|
||||
const isDepositAccExists = await this.accountsService.isAccountExists(
|
||||
tenantId,
|
||||
req.body.deposit_account_id
|
||||
);
|
||||
if (!isDepositAccExists) {
|
||||
@@ -132,10 +202,11 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateCustomerExistance(req, res, next) {
|
||||
const isCustomerExists = await CustomersService.isCustomerExists(
|
||||
req.body.customer_id
|
||||
);
|
||||
async validateCustomerExistance(req: Request, res: Response, next: Function) {
|
||||
const { Customer } = req.models;
|
||||
|
||||
const isCustomerExists = await Customer.query().findById(req.body.customer_id);
|
||||
|
||||
if (!isCustomerExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 }],
|
||||
@@ -150,10 +221,14 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @param {Function} next -
|
||||
*/
|
||||
static async validateInvoicesIDs(req, res, next) {
|
||||
async validateInvoicesIDs(req: Request, res: Response, next: Function) {
|
||||
const paymentReceive = { ...req.body };
|
||||
const invoicesIds = paymentReceive.entries.map((e) => e.invoice_id);
|
||||
const notFoundInvoicesIDs = await SaleInvoicesService.isInvoicesExist(
|
||||
const { tenantId } = req;
|
||||
const invoicesIds = paymentReceive.entries
|
||||
.map((e) => e.invoice_id);
|
||||
|
||||
const notFoundInvoicesIDs = await this.saleInvoiceService.isInvoicesExist(
|
||||
tenantId,
|
||||
invoicesIds,
|
||||
paymentReceive.customer_id,
|
||||
);
|
||||
@@ -171,19 +246,19 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @param {Function} next -
|
||||
*/
|
||||
static async validateInvoicesPaymentsAmount(req, res, next) {
|
||||
async validateInvoicesPaymentsAmount(req: Request, res: Response, next: Function) {
|
||||
const { SaleInvoice } = req.models;
|
||||
const invoicesIds = req.body.entries.map((e) => e.invoice_id);
|
||||
const storedInvoices = await SaleInvoice.tenant()
|
||||
.query()
|
||||
|
||||
const storedInvoices = await SaleInvoice.query()
|
||||
.whereIn('id', invoicesIds);
|
||||
|
||||
const storedInvoicesMap = new Map(
|
||||
storedInvoices.map((invoice) => [invoice.id, invoice])
|
||||
);
|
||||
const hasWrongPaymentAmount = [];
|
||||
const hasWrongPaymentAmount: any[] = [];
|
||||
|
||||
req.body.entries.forEach((entry, index) => {
|
||||
req.body.entries.forEach((entry, index: number) => {
|
||||
const entryInvoice = storedInvoicesMap.get(entry.invoice_id);
|
||||
const { dueAmount } = entryInvoice;
|
||||
|
||||
@@ -211,13 +286,15 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
static async validateEntriesIdsExistance(req, res, next) {
|
||||
async validateEntriesIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const paymentReceive = { id: req.params.id, ...req.body };
|
||||
const entriesIds = paymentReceive.entries
|
||||
.filter(entry => entry.id)
|
||||
.map(entry => entry.id);
|
||||
|
||||
const storedEntries = await PaymentReceiveEntry.tenant().query()
|
||||
const { PaymentReceiveEntry } = req.models;
|
||||
|
||||
const storedEntries = await PaymentReceiveEntry.query()
|
||||
.where('payment_receive_id', paymentReceive.id);
|
||||
|
||||
const storedEntriesIds = storedEntries.map((entry) => entry.id);
|
||||
@@ -231,49 +308,28 @@ export default class PaymentReceivesController extends BaseController {
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Payment receive schema.
|
||||
* @return {Array}
|
||||
*/
|
||||
static get paymentReceiveSchema() {
|
||||
return [
|
||||
check('customer_id').exists().isNumeric().toInt(),
|
||||
check('payment_date').exists(),
|
||||
check('reference_no').optional(),
|
||||
check('deposit_account_id').exists().isNumeric().toInt(),
|
||||
check('payment_receive_no').exists().trim().escape(),
|
||||
check('statement').optional().trim().escape(),
|
||||
|
||||
check('entries').isArray({ min: 1 }),
|
||||
|
||||
check('entries.*.invoice_id').exists().isNumeric().toInt(),
|
||||
check('entries.*.payment_amount').exists().isNumeric().toInt(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* New payment receive validation schema.
|
||||
* @return {Array}
|
||||
*/
|
||||
static get newPaymentReceiveValidation() {
|
||||
return [...this.paymentReceiveSchema];
|
||||
}
|
||||
|
||||
/**
|
||||
* Records payment receive to the given customer with associated invoices.
|
||||
*/
|
||||
static async newPaymentReceive(req, res) {
|
||||
const paymentReceive = { ...req.body };
|
||||
const storedPaymentReceive = await PaymentReceiveService.createPaymentReceive(
|
||||
paymentReceive
|
||||
);
|
||||
async newPaymentReceive(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const paymentReceive: IPaymentReceiveOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true,
|
||||
});
|
||||
|
||||
const storedPaymentReceive = await this.paymentReceiveService
|
||||
.createPaymentReceive(
|
||||
tenantId,
|
||||
paymentReceive,
|
||||
);
|
||||
return res.status(200).send({ id: storedPaymentReceive.id });
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit payment receive validation.
|
||||
*/
|
||||
static get editPaymentReceiveValidation() {
|
||||
get editPaymentReceiveValidation() {
|
||||
return [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
...this.paymentReceiveSchema,
|
||||
@@ -286,18 +342,23 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
static async editPaymentReceive(req, res) {
|
||||
const paymentReceive = { ...req.body };
|
||||
async editPaymentReceive(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
const { PaymentReceive } = req.models;
|
||||
|
||||
const paymentReceive: IPaymentReceiveOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
});
|
||||
|
||||
// Retrieve the payment receive before updating.
|
||||
const oldPaymentReceive = await PaymentReceive.query()
|
||||
const oldPaymentReceive: IPaymentReceive = await PaymentReceive.query()
|
||||
.where('id', paymentReceiveId)
|
||||
.withGraphFetched('entries')
|
||||
.first();
|
||||
|
||||
await PaymentReceiveService.editPaymentReceive(
|
||||
await this.paymentReceiveService.editPaymentReceive(
|
||||
tenantId,
|
||||
paymentReceiveId,
|
||||
paymentReceive,
|
||||
oldPaymentReceive,
|
||||
@@ -305,28 +366,23 @@ export default class PaymentReceivesController extends BaseController {
|
||||
return res.status(200).send({ id: paymentReceiveId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate payment receive parameters.
|
||||
*/
|
||||
static get paymentReceiveValidation() {
|
||||
return [param('id').exists().isNumeric().toInt()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Delets the given payment receive id.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async deletePaymentReceive(req, res) {
|
||||
async deletePaymentReceive(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
|
||||
const { PaymentReceive } = req.models;
|
||||
|
||||
const storedPaymentReceive = await PaymentReceive.query()
|
||||
.where('id', paymentReceiveId)
|
||||
.withGraphFetched('entries')
|
||||
.first();
|
||||
|
||||
await PaymentReceiveService.deletePaymentReceive(
|
||||
await this.paymentReceiveService.deletePaymentReceive(
|
||||
tenantId,
|
||||
paymentReceiveId,
|
||||
storedPaymentReceive
|
||||
);
|
||||
@@ -339,7 +395,7 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
*/
|
||||
static async getPaymentReceive(req, res) {
|
||||
async getPaymentReceive(req: Request, res: Response) {
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
const paymentReceive = await PaymentReceiveService.getPaymentReceive(
|
||||
paymentReceiveId
|
||||
@@ -347,27 +403,13 @@ export default class PaymentReceivesController extends BaseController {
|
||||
return res.status(200).send({ paymentReceive });
|
||||
}
|
||||
|
||||
/**
|
||||
* Payment receive list validation schema.
|
||||
*/
|
||||
static get validatePaymentReceiveList() {
|
||||
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(),
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve payment receive list with pagination metadata.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
static async getPaymentReceiveList(req, res) {
|
||||
async getPaymentReceiveList(req: Request, res: Response) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
@@ -1,6 +1,7 @@
|
||||
import express from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
import { ItemEntry } from '@/models';
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { check, param, query, matchedData } from 'express-validator';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ISaleEstimate, ISaleEstimateOTD } from '@/interfaces';
|
||||
import BaseController from '@/http/controllers/BaseController'
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
@@ -10,21 +11,31 @@ import ItemsService from '@/services/Items/ItemsService';
|
||||
import DynamicListingBuilder from '@/services/DynamicListing/DynamicListingBuilder';
|
||||
import DynamicListing from '@/services/DynamicListing/DynamicListing';
|
||||
|
||||
@Service()
|
||||
export default class SalesEstimatesController extends BaseController {
|
||||
@Inject()
|
||||
saleEstimateService: SaleEstimateService;
|
||||
|
||||
@Inject()
|
||||
itemsService: ItemsService;
|
||||
|
||||
@Inject()
|
||||
customersService: CustomersService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
const router = express.Router();
|
||||
router() {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
this.estimateValidationSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateEstimateCustomerExistance),
|
||||
asyncMiddleware(this.validateEstimateNumberExistance),
|
||||
asyncMiddleware(this.validateEstimateEntriesItemsExistance),
|
||||
asyncMiddleware(this.newEstimate)
|
||||
asyncMiddleware(this.validateEstimateCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEstimateNumberExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEstimateEntriesItemsExistance.bind(this)),
|
||||
asyncMiddleware(this.newEstimate.bind(this))
|
||||
);
|
||||
router.post(
|
||||
'/:id', [
|
||||
@@ -32,33 +43,33 @@ export default class SalesEstimatesController extends BaseController {
|
||||
...this.estimateValidationSchema,
|
||||
],
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateEstimateIdExistance),
|
||||
asyncMiddleware(this.validateEstimateCustomerExistance),
|
||||
asyncMiddleware(this.validateEstimateNumberExistance),
|
||||
asyncMiddleware(this.validateEstimateEntriesItemsExistance),
|
||||
asyncMiddleware(this.valdiateInvoiceEntriesIdsExistance),
|
||||
asyncMiddleware(this.editEstimate)
|
||||
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(
|
||||
'/:id', [
|
||||
this.validateSpecificEstimateSchema,
|
||||
],
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateEstimateIdExistance),
|
||||
asyncMiddleware(this.deleteEstimate)
|
||||
asyncMiddleware(this.validateEstimateIdExistance.bind(this)),
|
||||
asyncMiddleware(this.deleteEstimate.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
this.validateSpecificEstimateSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateEstimateIdExistance),
|
||||
asyncMiddleware(this.getEstimate)
|
||||
asyncMiddleware(this.validateEstimateIdExistance.bind(this)),
|
||||
asyncMiddleware(this.getEstimate.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.validateEstimateListSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.getEstimates)
|
||||
asyncMiddleware(this.getEstimates.bind(this))
|
||||
);
|
||||
return router;
|
||||
}
|
||||
@@ -66,7 +77,7 @@ export default class SalesEstimatesController extends BaseController {
|
||||
/**
|
||||
* Estimate validation schema.
|
||||
*/
|
||||
static get estimateValidationSchema() {
|
||||
get estimateValidationSchema() {
|
||||
return [
|
||||
check('customer_id').exists().isNumeric().toInt(),
|
||||
check('estimate_date').exists().isISO8601(),
|
||||
@@ -90,7 +101,7 @@ export default class SalesEstimatesController extends BaseController {
|
||||
/**
|
||||
* Specific sale estimate validation schema.
|
||||
*/
|
||||
static get validateSpecificEstimateSchema() {
|
||||
get validateSpecificEstimateSchema() {
|
||||
return [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
];
|
||||
@@ -99,7 +110,7 @@ export default class SalesEstimatesController extends BaseController {
|
||||
/**
|
||||
* Sales estimates list validation schema.
|
||||
*/
|
||||
static get validateEstimateListSchema() {
|
||||
get validateEstimateListSchema() {
|
||||
return [
|
||||
query('custom_view_id').optional().isNumeric().toInt(),
|
||||
query('stringified_filter_roles').optional().isJSON(),
|
||||
@@ -116,12 +127,13 @@ export default class SalesEstimatesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateEstimateCustomerExistance(req, res, next) {
|
||||
async validateEstimateCustomerExistance(req: Request, res: Response, next: Function) {
|
||||
const estimate = { ...req.body };
|
||||
const isCustomerExists = await CustomersService.isCustomerExists(
|
||||
estimate.customer_id
|
||||
);
|
||||
if (!isCustomerExists) {
|
||||
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 }],
|
||||
});
|
||||
@@ -135,10 +147,12 @@ export default class SalesEstimatesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateEstimateNumberExistance(req, res, next) {
|
||||
async validateEstimateNumberExistance(req: Request, res: Response, next: Function) {
|
||||
const estimate = { ...req.body };
|
||||
const { tenantId } = req;
|
||||
|
||||
const isEstNumberUnqiue = await SaleEstimateService.isEstimateNumberUnique(
|
||||
const isEstNumberUnqiue = await this.saleEstimateService.isEstimateNumberUnique(
|
||||
tenantId,
|
||||
estimate.estimate_number,
|
||||
req.params.id,
|
||||
);
|
||||
@@ -147,7 +161,7 @@ export default class SalesEstimatesController extends BaseController {
|
||||
errors: [{ type: 'ESTIMATE.NUMBER.IS.NOT.UNQIUE', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -156,12 +170,13 @@ export default class SalesEstimatesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateEstimateEntriesItemsExistance(req, res, 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 ItemsService.isItemsIdsExists(estimateItemsIds);
|
||||
const notFoundItemsIds = await this.itemsService.isItemsIdsExists(tenantId, estimateItemsIds);
|
||||
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
return res.boom.badRequest(null, {
|
||||
@@ -177,9 +192,12 @@ export default class SalesEstimatesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateEstimateIdExistance(req, res, next) {
|
||||
async validateEstimateIdExistance(req: Request, res: Response, next: Function) {
|
||||
const { id: estimateId } = req.params;
|
||||
const storedEstimate = await SaleEstimateService.getEstimate(estimateId);
|
||||
const { tenantId } = req;
|
||||
|
||||
const storedEstimate = await this.saleEstimateService
|
||||
.getEstimate(tenantId, estimateId);
|
||||
|
||||
if (!storedEstimate) {
|
||||
return res.status(404).send({
|
||||
@@ -195,14 +213,16 @@ export default class SalesEstimatesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async valdiateInvoiceEntriesIdsExistance(req, res, 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.tenant().query()
|
||||
const foundEntries = await ItemEntry.query()
|
||||
.whereIn('id', entriesIds)
|
||||
.where('reference_type', 'SaleInvoice')
|
||||
.where('reference_id', saleInvoiceId);
|
||||
@@ -221,15 +241,14 @@ export default class SalesEstimatesController extends BaseController {
|
||||
* @param {Response} res -
|
||||
* @return {Response} res -
|
||||
*/
|
||||
static async newEstimate(req, res) {
|
||||
const estimate = {
|
||||
...req.body,
|
||||
entries: req.body.entries.map((entry) => ({
|
||||
...entry,
|
||||
amount: ItemEntry.calcAmount(entry),
|
||||
})),
|
||||
};
|
||||
const storedEstimate = await SaleEstimateService.createEstimate(estimate);
|
||||
async newEstimate(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const estimateOTD: ISaleEstimateOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true,
|
||||
});
|
||||
const storedEstimate = await this.saleEstimateService
|
||||
.createEstimate(tenantId, estimateOTD);
|
||||
|
||||
return res.status(200).send({ id: storedEstimate.id });
|
||||
}
|
||||
@@ -239,12 +258,16 @@ export default class SalesEstimatesController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async editEstimate(req, res) {
|
||||
async editEstimate(req: Request, res: Response) {
|
||||
const { id: estimateId } = req.params;
|
||||
const estimate = { ...req.body };
|
||||
const { tenantId } = req;
|
||||
|
||||
const estimateOTD: ISaleEstimateOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true,
|
||||
});
|
||||
// Update estimate with associated estimate entries.
|
||||
await SaleEstimateService.editEstimate(estimateId, estimate);
|
||||
await this.saleEstimateService.editEstimate(tenantId, estimateId, estimateOTD);
|
||||
|
||||
return res.status(200).send({ id: estimateId });
|
||||
}
|
||||
@@ -254,9 +277,11 @@ export default class SalesEstimatesController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async deleteEstimate(req, res) {
|
||||
async deleteEstimate(req: Request, res: Response) {
|
||||
const { id: estimateId } = req.params;
|
||||
await SaleEstimateService.deleteEstimate(estimateId);
|
||||
const { tenantId } = req;
|
||||
|
||||
await this.saleEstimateService.deleteEstimate(tenantId, estimateId);
|
||||
|
||||
return res.status(200).send({ id: estimateId });
|
||||
}
|
||||
@@ -264,9 +289,12 @@ export default class SalesEstimatesController extends BaseController {
|
||||
/**
|
||||
* Retrieve the given estimate with associated entries.
|
||||
*/
|
||||
static async getEstimate(req, res) {
|
||||
async getEstimate(req: Request, res: Response) {
|
||||
const { id: estimateId } = req.params;
|
||||
const estimate = await SaleEstimateService.getEstimateWithEntries(estimateId);
|
||||
const { tenantId } = req;
|
||||
|
||||
const estimate = await this.saleEstimateService
|
||||
.getEstimateWithEntries(tenantId, estimateId);
|
||||
|
||||
return res.status(200).send({ estimate });
|
||||
}
|
||||
@@ -276,7 +304,7 @@ export default class SalesEstimatesController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async getEstimates(req, res) {
|
||||
async getEstimates(req: Request, res: Response) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
@@ -288,7 +316,7 @@ export default class SalesEstimatesController extends BaseController {
|
||||
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
|
||||
}
|
||||
const { SaleEstimate, Resource, View } = req.models;
|
||||
const resource = await Resource.tenant().query()
|
||||
const resource = await Resource.query()
|
||||
.remember()
|
||||
.where('name', 'sales_estimates')
|
||||
.withGraphFetched('fields')
|
||||
@@ -1,34 +1,40 @@
|
||||
import express from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
import { check, param, query, matchedData } from 'express-validator';
|
||||
import { difference } from 'lodash';
|
||||
import { raw } from 'objection';
|
||||
import { ItemEntry } from '@/models';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
import SaleInvoiceService from '@/services/Sales/SalesInvoices';
|
||||
import ItemsService from '@/services/Items/ItemsService';
|
||||
import CustomersService from '@/services/Customers/CustomersService';
|
||||
import DynamicListing from '@/services/DynamicListing/DynamicListing';
|
||||
import DynamicListingBuilder from '@/services/DynamicListing/DynamicListingBuilder';
|
||||
import { dynamicListingErrorsToResponse } from '@/services/DynamicListing/hasDynamicListing';
|
||||
import { Customer, Item } from '../../../models';
|
||||
import { ISaleInvoiceOTD } from '@/interfaces';
|
||||
|
||||
@Service()
|
||||
export default class SaleInvoicesController {
|
||||
@Inject()
|
||||
itemsService: ItemsService;
|
||||
|
||||
@Inject()
|
||||
saleInvoiceService: SaleInvoiceService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
this.saleInvoiceValidationSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateInvoiceCustomerExistance),
|
||||
asyncMiddleware(this.validateInvoiceNumberUnique),
|
||||
asyncMiddleware(this.validateInvoiceItemsIdsExistance),
|
||||
asyncMiddleware(this.validateNonSellableEntriesItems),
|
||||
asyncMiddleware(this.newSaleInvoice)
|
||||
asyncMiddleware(this.validateInvoiceCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceNumberUnique.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceItemsIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.validateNonSellableEntriesItems.bind(this)),
|
||||
asyncMiddleware(this.newSaleInvoice.bind(this))
|
||||
);
|
||||
router.post(
|
||||
'/:id',
|
||||
@@ -37,38 +43,38 @@ export default class SaleInvoicesController {
|
||||
...this.specificSaleInvoiceValidation,
|
||||
],
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateInvoiceExistance),
|
||||
asyncMiddleware(this.validateInvoiceCustomerExistance),
|
||||
asyncMiddleware(this.validateInvoiceNumberUnique),
|
||||
asyncMiddleware(this.validateInvoiceItemsIdsExistance),
|
||||
asyncMiddleware(this.valdiateInvoiceEntriesIdsExistance),
|
||||
asyncMiddleware(this.validateEntriesIdsExistance),
|
||||
asyncMiddleware(this.validateNonSellableEntriesItems),
|
||||
asyncMiddleware(this.editSaleInvoice)
|
||||
asyncMiddleware(this.validateInvoiceExistance.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceNumberUnique.bind(this)),
|
||||
asyncMiddleware(this.validateInvoiceItemsIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.valdiateInvoiceEntriesIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEntriesIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.validateNonSellableEntriesItems.bind(this)),
|
||||
asyncMiddleware(this.editSaleInvoice.bind(this))
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
this.specificSaleInvoiceValidation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateInvoiceExistance),
|
||||
asyncMiddleware(this.deleteSaleInvoice)
|
||||
asyncMiddleware(this.validateInvoiceExistance.bind(this)),
|
||||
asyncMiddleware(this.deleteSaleInvoice.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/due_invoices',
|
||||
this.dueSalesInvoicesListValidationSchema,
|
||||
asyncMiddleware(this.getDueSalesInvoice),
|
||||
asyncMiddleware(this.getDueSalesInvoice.bind(this)),
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
this.specificSaleInvoiceValidation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateInvoiceExistance),
|
||||
asyncMiddleware(this.getSaleInvoice)
|
||||
asyncMiddleware(this.validateInvoiceExistance.bind(this)),
|
||||
asyncMiddleware(this.getSaleInvoice.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.saleInvoiceListValidationSchema,
|
||||
asyncMiddleware(this.getSalesInvoices)
|
||||
asyncMiddleware(this.getSalesInvoices.bind(this))
|
||||
)
|
||||
return router;
|
||||
}
|
||||
@@ -76,7 +82,7 @@ export default class SaleInvoicesController {
|
||||
/**
|
||||
* Sale invoice validation schema.
|
||||
*/
|
||||
static get saleInvoiceValidationSchema() {
|
||||
get saleInvoiceValidationSchema() {
|
||||
return [
|
||||
check('customer_id').exists().isNumeric().toInt(),
|
||||
check('invoice_date').exists().isISO8601(),
|
||||
@@ -102,14 +108,14 @@ export default class SaleInvoicesController {
|
||||
/**
|
||||
* Specific sale invoice validation schema.
|
||||
*/
|
||||
static get specificSaleInvoiceValidation() {
|
||||
get specificSaleInvoiceValidation() {
|
||||
return [param('id').exists().isNumeric().toInt()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sales invoices list validation schema.
|
||||
*/
|
||||
static get saleInvoiceListValidationSchema() {
|
||||
get saleInvoiceListValidationSchema() {
|
||||
return [
|
||||
query('custom_view_id').optional().isNumeric().toInt(),
|
||||
query('stringified_filter_roles').optional().isJSON(),
|
||||
@@ -120,8 +126,10 @@ export default class SaleInvoicesController {
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
static get dueSalesInvoicesListValidationSchema() {
|
||||
/**
|
||||
* Due sale invoice list validation schema.
|
||||
*/
|
||||
get dueSalesInvoicesListValidationSchema() {
|
||||
return [
|
||||
query('customer_id').optional().isNumeric().toInt(),
|
||||
]
|
||||
@@ -133,11 +141,12 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateInvoiceCustomerExistance(req, res, next) {
|
||||
async validateInvoiceCustomerExistance(req: Request, res: Response, next: Function) {
|
||||
const saleInvoice = { ...req.body };
|
||||
const isCustomerIDExists = await CustomersService.isCustomerExists(
|
||||
saleInvoice.customer_id
|
||||
);
|
||||
const { Customer } = req.models;
|
||||
|
||||
const isCustomerIDExists = await Customer.query().findById(saleInvoice.customer_id);
|
||||
|
||||
if (!isCustomerIDExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 }],
|
||||
@@ -148,15 +157,17 @@ export default class SaleInvoicesController {
|
||||
|
||||
/**
|
||||
* Validate whether sale invoice items ids esits on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
* @param {Function} next -
|
||||
*/
|
||||
static async validateInvoiceItemsIdsExistance(req, res, next) {
|
||||
async validateInvoiceItemsIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const saleInvoice = { ...req.body };
|
||||
const entriesItemsIds = saleInvoice.entries.map((e) => e.item_id);
|
||||
const isItemsIdsExists = await ItemsService.isItemsIdsExists(
|
||||
entriesItemsIds
|
||||
|
||||
const isItemsIdsExists = await this.itemsService.isItemsIdsExists(
|
||||
tenantId, entriesItemsIds,
|
||||
);
|
||||
if (isItemsIdsExists.length > 0) {
|
||||
return res.status(400).send({
|
||||
@@ -173,9 +184,12 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateInvoiceNumberUnique(req, res, next) {
|
||||
async validateInvoiceNumberUnique(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const saleInvoice = { ...req.body };
|
||||
const isInvoiceNoExists = await SaleInvoiceService.isSaleInvoiceNumberExists(
|
||||
|
||||
const isInvoiceNoExists = await this.saleInvoiceService.isSaleInvoiceNumberExists(
|
||||
tenantId,
|
||||
saleInvoice.invoice_no,
|
||||
req.params.id
|
||||
);
|
||||
@@ -195,10 +209,12 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateInvoiceExistance(req, res, next) {
|
||||
async validateInvoiceExistance(req: Request, res: Response, next: Function) {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const isSaleInvoiceExists = await SaleInvoiceService.isSaleInvoiceExists(
|
||||
saleInvoiceId
|
||||
const { tenantId } = req;
|
||||
|
||||
const isSaleInvoiceExists = await this.saleInvoiceService.isSaleInvoiceExists(
|
||||
tenantId, saleInvoiceId,
|
||||
);
|
||||
if (!isSaleInvoiceExists) {
|
||||
return res
|
||||
@@ -214,12 +230,13 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async valdiateInvoiceEntriesIdsExistance(req, res, next) {
|
||||
async valdiateInvoiceEntriesIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const saleInvoice = { ...req.body };
|
||||
const entriesItemsIds = saleInvoice.entries.map((e) => e.item_id);
|
||||
|
||||
const isItemsIdsExists = await ItemsService.isItemsIdsExists(
|
||||
entriesItemsIds
|
||||
const isItemsIdsExists = await this.itemsService.isItemsIdsExists(
|
||||
tenantId, entriesItemsIds,
|
||||
);
|
||||
if (isItemsIdsExists.length > 0) {
|
||||
return res.status(400).send({
|
||||
@@ -235,14 +252,16 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateEntriesIdsExistance(req, res, next) {
|
||||
async validateEntriesIdsExistance(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 storedEntries = await ItemEntry.tenant().query()
|
||||
|
||||
const storedEntries = await ItemEntry.query()
|
||||
.whereIn('reference_id', [saleInvoiceId])
|
||||
.whereIn('reference_type', ['SaleInvoice']);
|
||||
|
||||
@@ -265,7 +284,7 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateNonSellableEntriesItems(req, res, next) {
|
||||
async validateNonSellableEntriesItems(req: Request, res: Response, next: Function) {
|
||||
const { Item } = req.models;
|
||||
const saleInvoice = { ...req.body };
|
||||
const itemsIds = saleInvoice.entries.map(e => e.item_id);
|
||||
@@ -291,22 +310,17 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async newSaleInvoice(req, res) {
|
||||
const errorReasons = [];
|
||||
const saleInvoice = {
|
||||
...req.body,
|
||||
entries: req.body.entries.map((entry) => ({
|
||||
...entry,
|
||||
amount: ItemEntry.calcAmount(entry),
|
||||
})),
|
||||
};
|
||||
async newSaleInvoice(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const saleInvoiceOTD: ISaleInvoiceOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true
|
||||
});
|
||||
|
||||
// Creates a new sale invoice with associated entries.
|
||||
const storedSaleInvoice = await SaleInvoiceService.createSaleInvoice(
|
||||
saleInvoice
|
||||
const storedSaleInvoice = await this.saleInvoiceService.createSaleInvoice(
|
||||
tenantId, saleInvoiceOTD,
|
||||
);
|
||||
|
||||
// InventoryService.trackingInventoryLotsCost();
|
||||
|
||||
return res.status(200).send({ id: storedSaleInvoice.id });
|
||||
}
|
||||
|
||||
@@ -316,19 +330,18 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async editSaleInvoice(req, res) {
|
||||
async editSaleInvoice(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const saleInvoice = {
|
||||
...req.body,
|
||||
entries: req.body.entries.map((entry) => ({
|
||||
...entry,
|
||||
amount: ItemEntry.calcAmount(entry),
|
||||
})),
|
||||
};
|
||||
// Update the given sale invoice details.
|
||||
await SaleInvoiceService.editSaleInvoice(saleInvoiceId, saleInvoice);
|
||||
|
||||
return res.status(200).send({ id: saleInvoice.id });
|
||||
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 });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -337,10 +350,12 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async deleteSaleInvoice(req, res) {
|
||||
async deleteSaleInvoice(req: Request, res: Response) {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
// Deletes the sale invoice with associated entries and journal transaction.
|
||||
await SaleInvoiceService.deleteSaleInvoice(saleInvoiceId);
|
||||
await this.saleInvoiceService.deleteSaleInvoice(tenantId, saleInvoiceId);
|
||||
|
||||
return res.status(200).send({ id: saleInvoiceId });
|
||||
}
|
||||
@@ -350,10 +365,12 @@ export default class SaleInvoicesController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async getSaleInvoice(req, res) {
|
||||
async getSaleInvoice(req: Request, res: Response) {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const saleInvoice = await SaleInvoiceService.getSaleInvoiceWithEntries(
|
||||
saleInvoiceId
|
||||
const { tenantId } = req;
|
||||
|
||||
const saleInvoice = await this.saleInvoiceService.getSaleInvoiceWithEntries(
|
||||
tenantId, saleInvoiceId,
|
||||
);
|
||||
return res.status(200).send({ sale_invoice: saleInvoice });
|
||||
}
|
||||
@@ -363,13 +380,14 @@ export default class SaleInvoicesController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async getDueSalesInvoice(req, res) {
|
||||
async getDueSalesInvoice(req: Request, res: Response) {
|
||||
const { Customer, SaleInvoice } = req.models;
|
||||
const { tenantId } = req;
|
||||
|
||||
const filter = {
|
||||
customer_id: null,
|
||||
...req.query,
|
||||
};
|
||||
const { Customer, SaleInvoice } = req.models;
|
||||
|
||||
if (filter.customer_id) {
|
||||
const foundCustomer = await Customer.query().findById(filter.customer_id);
|
||||
|
||||
@@ -381,7 +399,6 @@ export default class SaleInvoicesController {
|
||||
}
|
||||
const dueSalesInvoices = await SaleInvoice.query().onBuild((query) => {
|
||||
query.where(raw('BALANCE - PAYMENT_AMOUNT > 0'));
|
||||
|
||||
if (filter.customer_id) {
|
||||
query.where('customer_id', filter.customer_id);
|
||||
}
|
||||
@@ -397,7 +414,7 @@ export default class SaleInvoicesController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async getSalesInvoices(req, res) {
|
||||
async getSalesInvoices(req, res) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
@@ -1,9 +1,8 @@
|
||||
import express from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
import { ItemEntry } from '@/models';
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { check, param, query, matchedData } from 'express-validator';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
import CustomersService from '@/services/Customers/CustomersService';
|
||||
import AccountsService from '@/services/Accounts/AccountsService';
|
||||
import ItemsService from '@/services/Items/ItemsService';
|
||||
import SaleReceiptService from '@/services/Sales/SalesReceipts';
|
||||
@@ -13,12 +12,22 @@ import {
|
||||
dynamicListingErrorsToResponse
|
||||
} from '@/services/DynamicListing/HasDynamicListing';
|
||||
|
||||
@Service()
|
||||
export default class SalesReceiptsController {
|
||||
@Inject()
|
||||
saleReceiptService: SaleReceiptService;
|
||||
|
||||
@Inject()
|
||||
accountsService: AccountsService;
|
||||
|
||||
@Inject()
|
||||
itemsService: ItemsService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
const router = express.Router();
|
||||
router() {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/:id', [
|
||||
@@ -26,34 +35,34 @@ export default class SalesReceiptsController {
|
||||
...this.salesReceiptsValidationSchema,
|
||||
],
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateSaleReceiptExistance),
|
||||
asyncMiddleware(this.validateReceiptCustomerExistance),
|
||||
asyncMiddleware(this.validateReceiptDepositAccountExistance),
|
||||
asyncMiddleware(this.validateReceiptItemsIdsExistance),
|
||||
asyncMiddleware(this.validateReceiptEntriesIds),
|
||||
asyncMiddleware(this.editSaleReceipt)
|
||||
asyncMiddleware(this.validateSaleReceiptExistance.bind(this)),
|
||||
asyncMiddleware(this.validateReceiptCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateReceiptDepositAccountExistance.bind(this)),
|
||||
asyncMiddleware(this.validateReceiptItemsIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.validateReceiptEntriesIds.bind(this)),
|
||||
asyncMiddleware(this.editSaleReceipt.bind(this))
|
||||
);
|
||||
router.post(
|
||||
'/',
|
||||
this.salesReceiptsValidationSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateReceiptCustomerExistance),
|
||||
asyncMiddleware(this.validateReceiptDepositAccountExistance),
|
||||
asyncMiddleware(this.validateReceiptItemsIdsExistance),
|
||||
asyncMiddleware(this.newSaleReceipt)
|
||||
asyncMiddleware(this.validateReceiptCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateReceiptDepositAccountExistance.bind(this)),
|
||||
asyncMiddleware(this.validateReceiptItemsIdsExistance.bind(this)),
|
||||
asyncMiddleware(this.newSaleReceipt.bind(this))
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
this.specificReceiptValidationSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateSaleReceiptExistance),
|
||||
asyncMiddleware(this.deleteSaleReceipt)
|
||||
asyncMiddleware(this.validateSaleReceiptExistance.bind(this)),
|
||||
asyncMiddleware(this.deleteSaleReceipt.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.listSalesReceiptsValidationSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.listingSalesReceipts)
|
||||
asyncMiddleware(this.listingSalesReceipts.bind(this))
|
||||
);
|
||||
return router;
|
||||
}
|
||||
@@ -62,7 +71,7 @@ export default class SalesReceiptsController {
|
||||
* Sales receipt validation schema.
|
||||
* @return {Array}
|
||||
*/
|
||||
static get salesReceiptsValidationSchema() {
|
||||
get salesReceiptsValidationSchema() {
|
||||
return [
|
||||
check('customer_id').exists().isNumeric().toInt(),
|
||||
check('deposit_account_id').exists().isNumeric().toInt(),
|
||||
@@ -88,7 +97,7 @@ export default class SalesReceiptsController {
|
||||
/**
|
||||
* Specific sale receipt validation schema.
|
||||
*/
|
||||
static get specificReceiptValidationSchema() {
|
||||
get specificReceiptValidationSchema() {
|
||||
return [
|
||||
param('id').exists().isNumeric().toInt()
|
||||
];
|
||||
@@ -97,7 +106,7 @@ export default class SalesReceiptsController {
|
||||
/**
|
||||
* List sales receipts validation schema.
|
||||
*/
|
||||
static get listSalesReceiptsValidationSchema() {
|
||||
get listSalesReceiptsValidationSchema() {
|
||||
return [
|
||||
query('custom_view_id').optional().isNumeric().toInt(),
|
||||
query('stringified_filter_roles').optional().isJSON(),
|
||||
@@ -113,11 +122,15 @@ export default class SalesReceiptsController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async validateSaleReceiptExistance(req, res, next) {
|
||||
async validateSaleReceiptExistance(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const { id: saleReceiptId } = req.params;
|
||||
const isSaleReceiptExists = await SaleReceiptService.isSaleReceiptExists(
|
||||
saleReceiptId
|
||||
);
|
||||
|
||||
const isSaleReceiptExists = await this.saleReceiptService
|
||||
.isSaleReceiptExists(
|
||||
tenantId,
|
||||
saleReceiptId,
|
||||
);
|
||||
if (!isSaleReceiptExists) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'SALE.RECEIPT.NOT.FOUND', code: 200 }],
|
||||
@@ -132,12 +145,13 @@ export default class SalesReceiptsController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateReceiptCustomerExistance(req, res, next) {
|
||||
async validateReceiptCustomerExistance(req: Request, res: Response, next: Function) {
|
||||
const saleReceipt = { ...req.body };
|
||||
const isCustomerExists = await CustomersService.isCustomerExists(
|
||||
saleReceipt.customer_id
|
||||
);
|
||||
if (!isCustomerExists) {
|
||||
const { Customer } = req.models;
|
||||
|
||||
const foundCustomer = await Customer.query().findById(saleReceipt.customer_id);
|
||||
|
||||
if (!foundCustomer) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 }],
|
||||
});
|
||||
@@ -151,9 +165,12 @@ export default class SalesReceiptsController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateReceiptDepositAccountExistance(req, res, next) {
|
||||
async validateReceiptDepositAccountExistance(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const saleReceipt = { ...req.body };
|
||||
const isDepositAccountExists = await AccountsService.isAccountExists(
|
||||
const isDepositAccountExists = await this.accountsService.isAccountExists(
|
||||
tenantId,
|
||||
saleReceipt.deposit_account_id
|
||||
);
|
||||
if (!isDepositAccountExists) {
|
||||
@@ -170,10 +187,14 @@ export default class SalesReceiptsController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateReceiptItemsIdsExistance(req, res, next) {
|
||||
async validateReceiptItemsIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const saleReceipt = { ...req.body };
|
||||
const estimateItemsIds = saleReceipt.entries.map((e) => e.item_id);
|
||||
const notFoundItemsIds = await ItemsService.isItemsIdsExists(
|
||||
|
||||
const notFoundItemsIds = await this.itemsService.isItemsIdsExists(
|
||||
tenantId,
|
||||
estimateItemsIds
|
||||
);
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
@@ -188,15 +209,19 @@ export default class SalesReceiptsController {
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateReceiptEntriesIds(req, res, next) {
|
||||
async validateReceiptEntriesIds(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const saleReceipt = { ...req.body };
|
||||
const { id: saleReceiptId } = req.params;
|
||||
|
||||
// Validate the entries IDs that not stored or associated to the sale receipt.
|
||||
const notExistsEntriesIds = await SaleReceiptService.isSaleReceiptEntriesIDsExists(
|
||||
saleReceiptId,
|
||||
saleReceipt
|
||||
);
|
||||
const notExistsEntriesIds = await this.saleReceiptService
|
||||
.isSaleReceiptEntriesIDsExists(
|
||||
tenantId,
|
||||
saleReceiptId,
|
||||
saleReceipt,
|
||||
);
|
||||
if (notExistsEntriesIds.length > 0) {
|
||||
return res.status(400).send({ errors: [{
|
||||
type: 'ENTRIES.IDS.NOT.FOUND',
|
||||
@@ -212,19 +237,19 @@ export default class SalesReceiptsController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async newSaleReceipt(req, res) {
|
||||
const saleReceipt = {
|
||||
...req.body,
|
||||
entries: req.body.entries.map((entry) => ({
|
||||
...entry,
|
||||
amount: ItemEntry.calcAmount(entry),
|
||||
})),
|
||||
};
|
||||
async newSaleReceipt(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const saleReceipt = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true,
|
||||
});
|
||||
// Store the given sale receipt details with associated entries.
|
||||
const storedSaleReceipt = await SaleReceiptService.createSaleReceipt(
|
||||
saleReceipt
|
||||
);
|
||||
const storedSaleReceipt = await this.saleReceiptService
|
||||
.createSaleReceipt(
|
||||
tenantId,
|
||||
saleReceipt,
|
||||
);
|
||||
return res.status(200).send({ id: storedSaleReceipt.id });
|
||||
}
|
||||
|
||||
@@ -233,11 +258,12 @@ export default class SalesReceiptsController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async deleteSaleReceipt(req, res) {
|
||||
async deleteSaleReceipt(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const { id: saleReceiptId } = req.params;
|
||||
|
||||
// Deletes the sale receipt.
|
||||
await SaleReceiptService.deleteSaleReceipt(saleReceiptId);
|
||||
await this.saleReceiptService.deleteSaleReceipt(tenantId, saleReceiptId);
|
||||
|
||||
return res.status(200).send({ id: saleReceiptId });
|
||||
}
|
||||
@@ -248,9 +274,12 @@ export default class SalesReceiptsController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async editSaleReceipt(req, res) {
|
||||
async editSaleReceipt(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const { id: saleReceiptId } = req.params;
|
||||
const saleReceipt = { ...req.body };
|
||||
|
||||
const errorReasons = [];
|
||||
|
||||
// Handle all errors with reasons messages.
|
||||
@@ -258,7 +287,11 @@ export default class SalesReceiptsController {
|
||||
return res.boom.badRequest(null, { errors: errorReasons });
|
||||
}
|
||||
// Update the given sale receipt details.
|
||||
await SaleReceiptService.editSaleReceipt(saleReceiptId, saleReceipt);
|
||||
await this.saleReceiptService.editSaleReceipt(
|
||||
tenantId,
|
||||
saleReceiptId,
|
||||
saleReceipt,
|
||||
);
|
||||
|
||||
return res.status(200).send();
|
||||
}
|
||||
@@ -268,7 +301,7 @@ export default class SalesReceiptsController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async listingSalesReceipts(req, res) {
|
||||
async listingSalesReceipts(req: Request, res: Response) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
@@ -280,7 +313,7 @@ export default class SalesReceiptsController {
|
||||
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
|
||||
}
|
||||
const { SaleReceipt, Resource, View } = req.models;
|
||||
const resource = await Resource.tenant().query()
|
||||
const resource = await Resource.query()
|
||||
.remember()
|
||||
.where('name', 'sales_receipts')
|
||||
.withGraphFetched('fields')
|
||||
@@ -1,4 +1,5 @@
|
||||
import express from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import SalesEstimates from './SalesEstimates';
|
||||
import SalesReceipts from './SalesReceipts';
|
||||
import SalesInvoices from './SalesInvoices'
|
||||
@@ -11,10 +12,10 @@ export default {
|
||||
router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use('/invoices', SalesInvoices.router());
|
||||
router.use('/estimates', SalesEstimates.router());
|
||||
router.use('/receipts', SalesReceipts.router());
|
||||
router.use('/payment_receives', PaymentReceives.router());
|
||||
router.use('/invoices', Container.get(SalesInvoices).router());
|
||||
router.use('/estimates', Container.get(SalesEstimates).router());
|
||||
router.use('/receipts', Container.get(SalesReceipts).router());
|
||||
router.use('/payment_receives', Container.get(PaymentReceives).router());
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -25,14 +25,15 @@ export default class VouchersController {
|
||||
this.generateVoucherSchema,
|
||||
validateMiddleware,
|
||||
PrettierMiddleware,
|
||||
asyncMiddleware(this.validatePlanExistance),
|
||||
asyncMiddleware(this.validatePlanExistance.bind(this)),
|
||||
asyncMiddleware(this.generateVoucher.bind(this)),
|
||||
);
|
||||
router.post(
|
||||
'/disable/:voucherId',
|
||||
validateMiddleware,
|
||||
PrettierMiddleware,
|
||||
asyncMiddleware(this.validateVoucherExistance),
|
||||
asyncMiddleware(this.validateNotDisabledVoucher),
|
||||
asyncMiddleware(this.validateVoucherExistance.bind(this)),
|
||||
asyncMiddleware(this.validateNotDisabledVoucher.bind(this)),
|
||||
asyncMiddleware(this.disableVoucher.bind(this)),
|
||||
);
|
||||
router.post(
|
||||
@@ -45,7 +46,7 @@ export default class VouchersController {
|
||||
router.delete(
|
||||
'/:voucherId',
|
||||
PrettierMiddleware,
|
||||
asyncMiddleware(this.validateVoucherExistance),
|
||||
asyncMiddleware(this.validateVoucherExistance.bind(this)),
|
||||
asyncMiddleware(this.deleteVoucher.bind(this)),
|
||||
);
|
||||
router.get(
|
||||
@@ -158,23 +159,21 @@ export default class VouchersController {
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
async generateVoucher(req: Request, res: Response) {
|
||||
async generateVoucher(req: Request, res: Response, next: Function) {
|
||||
const { loop = 10, period, periodInterval, planId } = req.body;
|
||||
const generatedVouchers: string[] = [];
|
||||
const asyncOpers = [];
|
||||
|
||||
times(loop, () => {
|
||||
const generateOper = this.voucherService
|
||||
.generateVoucher(period, periodInterval, planId)
|
||||
.then((generatedVoucher: any) => {
|
||||
generatedVouchers.push(generatedVoucher)
|
||||
});
|
||||
asyncOpers.push(generateOper);
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
vouchers: generatedVouchers,
|
||||
});
|
||||
try {
|
||||
await this.voucherService.generateVouchers(
|
||||
loop, period, periodInterval, planId,
|
||||
);
|
||||
return res.status(200).send({
|
||||
code: 100,
|
||||
message: 'The vouchers have been generated successfully.'
|
||||
});
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -49,7 +49,7 @@ export default (app) => {
|
||||
dashboard.use('/api/account_types', AccountTypes.router());
|
||||
dashboard.use('/api/accounting', Accounting.router());
|
||||
dashboard.use('/api/views', Views.router());
|
||||
dashboard.use('/api/items', Items.router());
|
||||
dashboard.use('/api/items', Container.get(Items).router());
|
||||
dashboard.use('/api/item_categories', Container.get(ItemCategories));
|
||||
dashboard.use('/api/expenses', Expenses.router());
|
||||
dashboard.use('/api/financial_statements', FinancialStatements.router());
|
||||
@@ -61,7 +61,7 @@ export default (app) => {
|
||||
dashboard.use('/api/resources', Resources.router());
|
||||
dashboard.use('/api/exchange_rates', ExchangeRates.router());
|
||||
dashboard.use('/api/media', Media.router());
|
||||
|
||||
|
||||
app.use('/agendash', Agendash.router());
|
||||
app.use('/', dashboard);
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import fs from 'fs';
|
||||
import path from 'path';
|
||||
import TenantsManager from '@/system/TenantsManager';
|
||||
import TenantModel from '@/models/TenantModel';
|
||||
import { Container } from 'typedi';
|
||||
|
||||
function loadModelsFromDirectory() {
|
||||
const models = {};
|
||||
@@ -45,6 +46,7 @@ export default async (req, res, next) => {
|
||||
req.knex = knex;
|
||||
req.organizationId = organizationId;
|
||||
req.tenant = tenant;
|
||||
req.tenantId = tenant.id;
|
||||
req.models = {
|
||||
...Object.values(models).reduce((acc, model) => {
|
||||
if (typeof model.resource.default !== 'undefined' &&
|
||||
@@ -56,5 +58,8 @@ export default async (req, res, next) => {
|
||||
return acc;
|
||||
}, {}),
|
||||
};
|
||||
Container.of(`tenant-${tenant.id}`).set('models', {
|
||||
...req.models,
|
||||
});
|
||||
next();
|
||||
};
|
||||
Reference in New Issue
Block a user