mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-17 05:10:31 +00:00
refactoring: payment receive and sale invoice actions.
This commit is contained in:
@@ -1,13 +1,12 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { check, param, query, ValidationChain, matchedData } from 'express-validator';
|
||||
import { difference } from 'lodash';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { check, param, query, ValidationChain } from 'express-validator';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { IPaymentReceive, IPaymentReceiveOTD } from 'interfaces';
|
||||
import { IPaymentReceiveDTO } from 'interfaces';
|
||||
import BaseController from 'api/controllers/BaseController';
|
||||
import asyncMiddleware from 'api/middleware/asyncMiddleware';
|
||||
import PaymentReceiveService from 'services/Sales/PaymentsReceives';
|
||||
import SaleInvoiceService from 'services/Sales/SalesInvoices';
|
||||
import AccountsService from 'services/Accounts/AccountsService';
|
||||
import DynamicListingService from 'services/DynamicListing/DynamicListService';
|
||||
import { ServiceError } from 'exceptions';
|
||||
|
||||
/**
|
||||
* Payments receives controller.
|
||||
@@ -19,11 +18,8 @@ export default class PaymentReceivesController extends BaseController {
|
||||
paymentReceiveService: PaymentReceiveService;
|
||||
|
||||
@Inject()
|
||||
accountsService: AccountsService;
|
||||
|
||||
@Inject()
|
||||
saleInvoiceService: SaleInvoiceService;
|
||||
|
||||
dynamicListService: DynamicListingService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
@@ -34,45 +30,37 @@ export default class PaymentReceivesController extends BaseController {
|
||||
'/:id',
|
||||
this.editPaymentReceiveValidation,
|
||||
this.validationResult,
|
||||
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)),
|
||||
this.handleServiceErrors,
|
||||
);
|
||||
router.post(
|
||||
'/',
|
||||
this.newPaymentReceiveValidation,
|
||||
this.validationResult,
|
||||
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)),
|
||||
this.handleServiceErrors,
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
this.paymentReceiveValidation,
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validatePaymentReceiveExistance.bind(this)),
|
||||
asyncMiddleware(this.getPaymentReceive.bind(this))
|
||||
asyncMiddleware(this.getPaymentReceive.bind(this)),
|
||||
this.handleServiceErrors,
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.validatePaymentReceiveList,
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.getPaymentReceiveList.bind(this)),
|
||||
this.handleServiceErrors,
|
||||
this.dynamicListService.handlerErrorsToResponse,
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
this.paymentReceiveValidation,
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.validatePaymentReceiveExistance.bind(this)),
|
||||
asyncMiddleware(this.deletePaymentReceive.bind(this)),
|
||||
this.handleServiceErrors,
|
||||
);
|
||||
return router;
|
||||
}
|
||||
@@ -126,198 +114,6 @@ export default class PaymentReceivesController extends BaseController {
|
||||
return [...this.paymentReceiveSchema];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the payment receive number existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
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,
|
||||
);
|
||||
if (isPaymentNoExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'PAYMENT.RECEIVE.NUMBER.EXISTS', code: 400 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the payment receive existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
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.NOT.EXISTS', code: 600 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the deposit account id existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
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) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'DEPOSIT.ACCOUNT.NOT.EXISTS', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the `customer_id` existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
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 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the invoices IDs existance.
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
* @param {Function} next -
|
||||
*/
|
||||
async validateInvoicesIDs(req: Request, res: Response, next: Function) {
|
||||
const paymentReceive = { ...req.body };
|
||||
const { tenantId } = req;
|
||||
const invoicesIds = paymentReceive.entries
|
||||
.map((e) => e.invoice_id);
|
||||
|
||||
const notFoundInvoicesIDs = await this.saleInvoiceService.isInvoicesExist(
|
||||
tenantId,
|
||||
invoicesIds,
|
||||
paymentReceive.customer_id,
|
||||
);
|
||||
if (notFoundInvoicesIDs.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'INVOICES.IDS.NOT.FOUND', code: 500 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates entries invoice payment amount.
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
* @param {Function} 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.query()
|
||||
.whereIn('id', invoicesIds);
|
||||
|
||||
const storedInvoicesMap = new Map(
|
||||
storedInvoices.map((invoice) => [invoice.id, invoice])
|
||||
);
|
||||
const hasWrongPaymentAmount: any[] = [];
|
||||
|
||||
req.body.entries.forEach((entry, index: number) => {
|
||||
const entryInvoice = storedInvoicesMap.get(entry.invoice_id);
|
||||
const { dueAmount } = entryInvoice;
|
||||
|
||||
if (dueAmount < entry.payment_amount) {
|
||||
hasWrongPaymentAmount.push({ index, due_amount: dueAmount });
|
||||
}
|
||||
});
|
||||
if (hasWrongPaymentAmount.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [
|
||||
{
|
||||
type: 'INVOICE.PAYMENT.AMOUNT',
|
||||
code: 200,
|
||||
indexes: hasWrongPaymentAmount,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the payment receive entries IDs existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
async validateEntriesIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const paymentReceive = { id: req.params.id, ...req.body };
|
||||
const entriesIds = paymentReceive.entries
|
||||
.filter(entry => entry.id)
|
||||
.map(entry => entry.id);
|
||||
|
||||
const { PaymentReceiveEntry } = req.models;
|
||||
|
||||
const storedEntries = await PaymentReceiveEntry.query()
|
||||
.where('payment_receive_id', paymentReceive.id);
|
||||
|
||||
const storedEntriesIds = storedEntries.map((entry) => entry.id);
|
||||
const notFoundEntriesIds = difference(entriesIds, storedEntriesIds);
|
||||
|
||||
if (notFoundEntriesIds.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'ENTEIES.IDS.NOT.FOUND', code: 800 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Records payment receive to the given customer with associated invoices.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
@@ -328,34 +124,48 @@ export default class PaymentReceivesController extends BaseController {
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Records payment receive to the given customer with associated invoices.
|
||||
*/
|
||||
async newPaymentReceive(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const paymentReceive: IPaymentReceiveDTO = this.matchedBodyData(req);
|
||||
|
||||
try {
|
||||
const storedPaymentReceive = await this.paymentReceiveService
|
||||
.createPaymentReceive(
|
||||
tenantId,
|
||||
paymentReceive,
|
||||
);
|
||||
return res.status(200).send({
|
||||
id: storedPaymentReceive.id,
|
||||
message: 'The payment receive has been created successfully.',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit the given payment receive.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
async editPaymentReceive(req: Request, res: Response) {
|
||||
async editPaymentReceive(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
const { PaymentReceive } = req.models;
|
||||
|
||||
const paymentReceive: IPaymentReceiveOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
});
|
||||
const paymentReceive: IPaymentReceiveDTO = this.matchedBodyData(req);
|
||||
|
||||
// Retrieve the payment receive before updating.
|
||||
const oldPaymentReceive: IPaymentReceive = await PaymentReceive.query()
|
||||
.where('id', paymentReceiveId)
|
||||
.withGraphFetched('entries')
|
||||
.first();
|
||||
|
||||
await this.paymentReceiveService.editPaymentReceive(
|
||||
tenantId,
|
||||
paymentReceiveId,
|
||||
paymentReceive,
|
||||
oldPaymentReceive,
|
||||
);
|
||||
return res.status(200).send({ id: paymentReceiveId });
|
||||
try {
|
||||
await this.paymentReceiveService.editPaymentReceive(
|
||||
tenantId, paymentReceiveId, paymentReceive,
|
||||
);
|
||||
return res.status(200).send({ id: paymentReceiveId });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -363,22 +173,22 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async deletePaymentReceive(req: Request, res: Response) {
|
||||
async deletePaymentReceive(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
const { PaymentReceive } = req.models;
|
||||
|
||||
const storedPaymentReceive = await PaymentReceive.query()
|
||||
.where('id', paymentReceiveId)
|
||||
.withGraphFetched('entries')
|
||||
.first();
|
||||
|
||||
await this.paymentReceiveService.deletePaymentReceive(
|
||||
tenantId,
|
||||
paymentReceiveId,
|
||||
storedPaymentReceive
|
||||
);
|
||||
return res.status(200).send({ id: paymentReceiveId });
|
||||
try {
|
||||
await this.paymentReceiveService.deletePaymentReceive(
|
||||
tenantId,
|
||||
paymentReceiveId,
|
||||
);
|
||||
return res.status(200).send({
|
||||
id: paymentReceiveId,
|
||||
message: 'The payment receive has been edited successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -387,12 +197,18 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
*/
|
||||
async getPaymentReceive(req: Request, res: Response) {
|
||||
async getPaymentReceive(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
const paymentReceive = await PaymentReceiveService.getPaymentReceive(
|
||||
paymentReceiveId
|
||||
);
|
||||
return res.status(200).send({ paymentReceive });
|
||||
|
||||
try {
|
||||
const paymentReceive = await this.paymentReceiveService.getPaymentReceive(
|
||||
tenantId, paymentReceiveId
|
||||
);
|
||||
return res.status(200).send({ paymentReceive });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -401,7 +217,88 @@ export default class PaymentReceivesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
async getPaymentReceiveList(req: Request, res: Response) {
|
||||
|
||||
async getPaymentReceiveList(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const filter = {
|
||||
filterRoles: [],
|
||||
sortOrder: 'asc',
|
||||
columnSortBy: 'created_at',
|
||||
page: 1,
|
||||
pageSize: 12,
|
||||
...this.matchedQueryData(req),
|
||||
};
|
||||
if (filter.stringifiedFilterRoles) {
|
||||
filter.filterRoles = JSON.parse(filter.stringifiedFilterRoles);
|
||||
}
|
||||
|
||||
try {
|
||||
const {
|
||||
paymentReceives,
|
||||
pagination,
|
||||
filterMeta,
|
||||
} = await this.paymentReceiveService.listPaymentReceives(tenantId, filter);
|
||||
|
||||
return res.status(200).send({
|
||||
payment_receives: paymentReceives,
|
||||
pagination: this.transfromToResponse(pagination),
|
||||
filter_meta: this.transfromToResponse(filterMeta),
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles service errors.
|
||||
* @param error
|
||||
* @param req
|
||||
* @param res
|
||||
* @param next
|
||||
*/
|
||||
handleServiceErrors(error: Error, req: Request, res: Response, next: NextFunction) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'DEPOSIT_ACCOUNT_NOT_FOUND') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'DEPOSIT.ACCOUNT.NOT.EXISTS', code: 300 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'PAYMENT_RECEIVE_NO_EXISTS') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'PAYMENT_RECEIVE_NO_EXISTS', code: 300 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'PAYMENT_RECEIVE_NOT_EXISTS') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'PAYMENT_RECEIVE_NOT_EXISTS', code: 300 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'DEPOSIT_ACCOUNT_NOT_CURRENT_ASSET_TYPE', code: 300 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'INVALID_PAYMENT_AMOUNT_INVALID') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'INVALID_PAYMENT_AMOUNT', code: 300 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'INVOICES_IDS_NOT_FOUND') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'INVOICES_IDS_NOT_FOUND', code: 300 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'ENTRIES_IDS_NOT_FOUND') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ENTRIES_IDS_NOT_FOUND', code: 300 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'contact_not_found') {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'CUSTOMER_NOT_FOUND', code: 300 }],
|
||||
});
|
||||
}
|
||||
console.log(error.errorType);
|
||||
}
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user