mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-17 05:10:31 +00:00
feat: remove path alias.
feat: remove Webpack and depend on nodemon. feat: refactoring expenses. feat: optimize system users with caching. feat: architecture tenant optimize.
This commit is contained in:
476
server/src/api/controllers/Sales/PaymentReceives.ts
Normal file
476
server/src/api/controllers/Sales/PaymentReceives.ts
Normal file
@@ -0,0 +1,476 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { check, param, query, ValidationChain, matchedData } from 'express-validator';
|
||||
import { difference } from 'lodash';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { IPaymentReceive, IPaymentReceiveOTD } from 'interfaces';
|
||||
import BaseController from 'api/controllers/BaseController';
|
||||
import validateMiddleware from 'api/middleware/validateMiddleware';
|
||||
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 DynamicListing from 'services/DynamicListing/DynamicListing';
|
||||
import DynamicListingBuilder from 'services/DynamicListing/DynamicListingBuilder';
|
||||
import { dynamicListingErrorsToResponse } from 'services/DynamicListing/hasDynamicListing';
|
||||
|
||||
/**
|
||||
* Payments receives controller.
|
||||
* @service
|
||||
*/
|
||||
@Service()
|
||||
export default class PaymentReceivesController extends BaseController {
|
||||
@Inject()
|
||||
paymentReceiveService: PaymentReceiveService;
|
||||
|
||||
@Inject()
|
||||
accountsService: AccountsService;
|
||||
|
||||
@Inject()
|
||||
saleInvoiceService: SaleInvoiceService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
router() {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/:id',
|
||||
this.editPaymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
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.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.bind(this)),
|
||||
asyncMiddleware(this.getPaymentReceive.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.validatePaymentReceiveList,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.getPaymentReceiveList.bind(this)),
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
this.paymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
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
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
get editPaymentReceiveValidation() {
|
||||
return [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
...this.paymentReceiveSchema,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit the given payment receive.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
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: 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 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Delets the given payment receive id.
|
||||
* @param {Request} req
|
||||
* @param {Response} 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 this.paymentReceiveService.deletePaymentReceive(
|
||||
tenantId,
|
||||
paymentReceiveId,
|
||||
storedPaymentReceive
|
||||
);
|
||||
return res.status(200).send({ id: paymentReceiveId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the given payment receive details.
|
||||
* @asycn
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
*/
|
||||
async getPaymentReceive(req: Request, res: Response) {
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
const paymentReceive = await PaymentReceiveService.getPaymentReceive(
|
||||
paymentReceiveId
|
||||
);
|
||||
return res.status(200).send({ paymentReceive });
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve payment receive list with pagination metadata.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @return {Response}
|
||||
*/
|
||||
async getPaymentReceiveList(req: Request, res: Response) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
page: 1,
|
||||
page_size: 10,
|
||||
...req.query,
|
||||
};
|
||||
if (filter.stringified_filter_roles) {
|
||||
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
|
||||
}
|
||||
const { Resource, PaymentReceive, View, Bill } = req.models;
|
||||
const resource = await Resource.query()
|
||||
.remember()
|
||||
.where('name', 'payment_receives')
|
||||
.withGraphFetched('fields')
|
||||
.first();
|
||||
|
||||
if (!resource) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'PAYMENT_RECEIVES_RESOURCE_NOT_FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
const viewMeta = await View.query()
|
||||
.modify('allMetadata')
|
||||
.modify('specificOrFavourite', filter.custom_view_id)
|
||||
.where('resource_id', resource.id)
|
||||
.first();
|
||||
|
||||
const listingBuilder = new DynamicListingBuilder();
|
||||
const errorReasons = [];
|
||||
|
||||
listingBuilder.addModelClass(Bill);
|
||||
listingBuilder.addCustomViewId(filter.custom_view_id);
|
||||
listingBuilder.addFilterRoles(filter.filter_roles);
|
||||
listingBuilder.addSortBy(filter.sort_by, filter.sort_order);
|
||||
listingBuilder.addView(viewMeta);
|
||||
|
||||
const dynamicListing = new DynamicListing(listingBuilder);
|
||||
|
||||
if (dynamicListing instanceof Error) {
|
||||
const errors = dynamicListingErrorsToResponse(dynamicListing);
|
||||
errorReasons.push(...errors);
|
||||
}
|
||||
if (errorReasons.length > 0) {
|
||||
return res.status(400).send({ errors: errorReasons });
|
||||
}
|
||||
const paymentReceives = await PaymentReceive.query().onBuild((builder) => {
|
||||
builder.withGraphFetched('customer');
|
||||
builder.withGraphFetched('depositAccount');
|
||||
|
||||
dynamicListing.buildQuery()(builder);
|
||||
return builder;
|
||||
}).pagination(filter.page - 1, filter.page_size);
|
||||
|
||||
return res.status(200).send({
|
||||
payment_receives: {
|
||||
...paymentReceives,
|
||||
...(viewMeta
|
||||
? {
|
||||
viewMeta: {
|
||||
customViewId: viewMeta.id,
|
||||
}
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
369
server/src/api/controllers/Sales/SalesEstimates.ts
Normal file
369
server/src/api/controllers/Sales/SalesEstimates.ts
Normal file
@@ -0,0 +1,369 @@
|
||||
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 'api/controllers/BaseController'
|
||||
import validateMiddleware from 'api/middleware/validateMiddleware';
|
||||
import asyncMiddleware from 'api/middleware/asyncMiddleware';
|
||||
import SaleEstimateService from 'services/Sales/SalesEstimate';
|
||||
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;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
router() {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
this.estimateValidationSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateEstimateCustomerExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEstimateNumberExistance.bind(this)),
|
||||
asyncMiddleware(this.validateEstimateEntriesItemsExistance.bind(this)),
|
||||
asyncMiddleware(this.newEstimate.bind(this))
|
||||
);
|
||||
router.post(
|
||||
'/:id', [
|
||||
...this.validateSpecificEstimateSchema,
|
||||
...this.estimateValidationSchema,
|
||||
],
|
||||
validateMiddleware,
|
||||
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.bind(this)),
|
||||
asyncMiddleware(this.deleteEstimate.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
this.validateSpecificEstimateSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateEstimateIdExistance.bind(this)),
|
||||
asyncMiddleware(this.getEstimate.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.validateEstimateListSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.getEstimates.bind(this))
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Estimate validation schema.
|
||||
*/
|
||||
get estimateValidationSchema() {
|
||||
return [
|
||||
check('customer_id').exists().isNumeric().toInt(),
|
||||
check('estimate_date').exists().isISO8601(),
|
||||
check('expiration_date').optional().isISO8601(),
|
||||
check('reference').optional(),
|
||||
check('estimate_number').exists().trim().escape(),
|
||||
|
||||
check('entries').exists().isArray({ min: 1 }),
|
||||
check('entries.*.index').exists().isNumeric().toInt(),
|
||||
check('entries.*.item_id').exists().isNumeric().toInt(),
|
||||
check('entries.*.description').optional().trim().escape(),
|
||||
check('entries.*.quantity').exists().isNumeric().toInt(),
|
||||
check('entries.*.rate').exists().isNumeric().toFloat(),
|
||||
check('entries.*.discount').optional().isNumeric().toFloat(),
|
||||
|
||||
check('note').optional().trim().escape(),
|
||||
check('terms_conditions').optional().trim().escape(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Specific sale estimate validation schema.
|
||||
*/
|
||||
get validateSpecificEstimateSchema() {
|
||||
return [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sales estimates list validation schema.
|
||||
*/
|
||||
get validateEstimateListSchema() {
|
||||
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 estimate customer exists on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateEstimateCustomerExistance(req: Request, res: Response, next: Function) {
|
||||
const estimate = { ...req.body };
|
||||
const { Customer } = req.models
|
||||
|
||||
const foundCustomer = await Customer.query().findById(estimate.customer_id);
|
||||
|
||||
if (!foundCustomer) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'CUSTOMER.ID.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the estimate number unique on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateEstimateNumberExistance(req: Request, res: Response, next: Function) {
|
||||
const estimate = { ...req.body };
|
||||
const { tenantId } = req;
|
||||
|
||||
const isEstNumberUnqiue = await this.saleEstimateService.isEstimateNumberUnique(
|
||||
tenantId,
|
||||
estimate.estimate_number,
|
||||
req.params.id,
|
||||
);
|
||||
if (isEstNumberUnqiue) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ESTIMATE.NUMBER.IS.NOT.UNQIUE', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the estimate entries items ids existance on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateEstimateEntriesItemsExistance(req: Request, res: Response, next: Function) {
|
||||
const tenantId = req.tenantId;
|
||||
const estimate = { ...req.body };
|
||||
const estimateItemsIds = estimate.entries.map(e => e.item_id);
|
||||
|
||||
// Validate items ids in estimate entries exists.
|
||||
const notFoundItemsIds = await this.itemsService.isItemsIdsExists(tenantId, estimateItemsIds);
|
||||
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether the sale estimate id exists on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateEstimateIdExistance(req: Request, res: Response, next: Function) {
|
||||
const { id: estimateId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
const storedEstimate = await this.saleEstimateService
|
||||
.getEstimate(tenantId, estimateId);
|
||||
|
||||
if (!storedEstimate) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'SALE.ESTIMATE.ID.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate sale invoice entries ids existance on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async valdiateInvoiceEntriesIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const { ItemEntry } = req.models;
|
||||
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const saleInvoice = { ...req.body };
|
||||
const entriesIds = saleInvoice.entries
|
||||
.filter(e => e.id)
|
||||
.map((e) => e.id);
|
||||
|
||||
const foundEntries = await ItemEntry.query()
|
||||
.whereIn('id', entriesIds)
|
||||
.where('reference_type', 'SaleInvoice')
|
||||
.where('reference_id', saleInvoiceId);
|
||||
|
||||
if (foundEntries.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'ENTRIES.IDS.NOT.EXISTS', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle create a new estimate with associated entries.
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
* @return {Response} res -
|
||||
*/
|
||||
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 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle update estimate details with associated entries.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async editEstimate(req: Request, res: Response) {
|
||||
const { id: estimateId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
const estimateOTD: ISaleEstimateOTD = matchedData(req, {
|
||||
locations: ['body'],
|
||||
includeOptionals: true,
|
||||
});
|
||||
// Update estimate with associated estimate entries.
|
||||
await this.saleEstimateService.editEstimate(tenantId, estimateId, estimateOTD);
|
||||
|
||||
return res.status(200).send({ id: estimateId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the given estimate with associated entries.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async deleteEstimate(req: Request, res: Response) {
|
||||
const { id: estimateId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
await this.saleEstimateService.deleteEstimate(tenantId, estimateId);
|
||||
|
||||
return res.status(200).send({ id: estimateId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the given estimate with associated entries.
|
||||
*/
|
||||
async getEstimate(req: Request, res: Response) {
|
||||
const { id: estimateId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
const estimate = await this.saleEstimateService
|
||||
.getEstimateWithEntries(tenantId, estimateId);
|
||||
|
||||
return res.status(200).send({ estimate });
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve estimates with pagination metadata.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getEstimates(req: Request, res: Response) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
page: 1,
|
||||
page_size: 10,
|
||||
...req.query,
|
||||
};
|
||||
if (filter.stringified_filter_roles) {
|
||||
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
|
||||
}
|
||||
const { SaleEstimate, Resource, View } = req.models;
|
||||
const resource = await Resource.query()
|
||||
.remember()
|
||||
.where('name', 'sales_estimates')
|
||||
.withGraphFetched('fields')
|
||||
.first();
|
||||
|
||||
if (!resource) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'RESOURCE.NOT.FOUND', code: 200, }],
|
||||
});
|
||||
}
|
||||
const viewMeta = await View.query()
|
||||
.modify('allMetadata')
|
||||
.modify('specificOrFavourite', filter.custom_view_id)
|
||||
.where('resource_id', resource.id)
|
||||
.first();
|
||||
|
||||
const listingBuilder = new DynamicListingBuilder();
|
||||
const errorReasons = [];
|
||||
|
||||
listingBuilder.addView(viewMeta);
|
||||
listingBuilder.addModelClass(SaleEstimate);
|
||||
listingBuilder.addCustomViewId(filter.custom_view_id);
|
||||
listingBuilder.addFilterRoles(filter.filter_roles);
|
||||
listingBuilder.addSortBy(filter.sort_by, filter.sort_order);
|
||||
|
||||
const dynamicListing = new DynamicListing(listingBuilder);
|
||||
|
||||
if (dynamicListing instanceof Error) {
|
||||
const errors = dynamicListingErrorsToResponse(dynamicListing);
|
||||
errorReasons.push(...errors);
|
||||
}
|
||||
if (errorReasons.length > 0) {
|
||||
return res.status(400).send({ errors: errorReasons });
|
||||
}
|
||||
|
||||
const salesEstimates = await SaleEstimate.query().onBuild((builder) => {
|
||||
dynamicListing.buildQuery()(builder);
|
||||
builder.withGraphFetched('customer');
|
||||
return builder;
|
||||
}).pagination(filter.page - 1, filter.page_size);
|
||||
|
||||
return res.status(200).send({
|
||||
sales_estimates: {
|
||||
...salesEstimates,
|
||||
...(viewMeta ? {
|
||||
viewMeta: {
|
||||
custom_view_id: viewMeta.id,
|
||||
},
|
||||
} : {}),
|
||||
},
|
||||
|
||||
});
|
||||
}
|
||||
};
|
||||
483
server/src/api/controllers/Sales/SalesInvoices.ts
Normal file
483
server/src/api/controllers/Sales/SalesInvoices.ts
Normal file
@@ -0,0 +1,483 @@
|
||||
import express from 'express';
|
||||
import { check, param, query, matchedData } from 'express-validator';
|
||||
import { difference } from 'lodash';
|
||||
import { raw } from 'objection';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import validateMiddleware from 'api/middleware/validateMiddleware';
|
||||
import asyncMiddleware from 'api/middleware/asyncMiddleware';
|
||||
import SaleInvoiceService from 'services/Sales/SalesInvoices';
|
||||
import ItemsService from 'services/Items/ItemsService';
|
||||
import DynamicListing from 'services/DynamicListing/DynamicListing';
|
||||
import DynamicListingBuilder from 'services/DynamicListing/DynamicListingBuilder';
|
||||
import { dynamicListingErrorsToResponse } from 'services/DynamicListing/hasDynamicListing';
|
||||
import { ISaleInvoiceOTD } from 'interfaces';
|
||||
|
||||
@Service()
|
||||
export default class SaleInvoicesController {
|
||||
@Inject()
|
||||
itemsService: ItemsService;
|
||||
|
||||
@Inject()
|
||||
saleInvoiceService: SaleInvoiceService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
this.saleInvoiceValidationSchema,
|
||||
validateMiddleware,
|
||||
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',
|
||||
[
|
||||
...this.saleInvoiceValidationSchema,
|
||||
...this.specificSaleInvoiceValidation,
|
||||
],
|
||||
validateMiddleware,
|
||||
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.bind(this)),
|
||||
asyncMiddleware(this.deleteSaleInvoice.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/due_invoices',
|
||||
this.dueSalesInvoicesListValidationSchema,
|
||||
asyncMiddleware(this.getDueSalesInvoice.bind(this)),
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
this.specificSaleInvoiceValidation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.validateInvoiceExistance.bind(this)),
|
||||
asyncMiddleware(this.getSaleInvoice.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.saleInvoiceListValidationSchema,
|
||||
asyncMiddleware(this.getSalesInvoices.bind(this))
|
||||
)
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sale invoice validation schema.
|
||||
*/
|
||||
get saleInvoiceValidationSchema() {
|
||||
return [
|
||||
check('customer_id').exists().isNumeric().toInt(),
|
||||
check('invoice_date').exists().isISO8601(),
|
||||
check('due_date').exists().isISO8601(),
|
||||
check('invoice_no').exists().trim().escape(),
|
||||
check('reference_no').optional().trim().escape(),
|
||||
check('status').exists().trim().escape(),
|
||||
|
||||
check('invoice_message').optional().trim().escape(),
|
||||
check('terms_conditions').optional().trim().escape(),
|
||||
|
||||
check('entries').exists().isArray({ min: 1 }),
|
||||
|
||||
check('entries.*.index').exists().isNumeric().toInt(),
|
||||
check('entries.*.item_id').exists().isNumeric().toInt(),
|
||||
check('entries.*.rate').exists().isNumeric().toFloat(),
|
||||
check('entries.*.quantity').exists().isNumeric().toFloat(),
|
||||
check('entries.*.discount').optional().isNumeric().toFloat(),
|
||||
check('entries.*.description').optional().trim().escape(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Specific sale invoice validation schema.
|
||||
*/
|
||||
get specificSaleInvoiceValidation() {
|
||||
return [param('id').exists().isNumeric().toInt()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sales invoices list validation schema.
|
||||
*/
|
||||
get saleInvoiceListValidationSchema() {
|
||||
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(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Due sale invoice list validation schema.
|
||||
*/
|
||||
get dueSalesInvoicesListValidationSchema() {
|
||||
return [
|
||||
query('customer_id').optional().isNumeric().toInt(),
|
||||
]
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether sale invoice customer exists on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateInvoiceCustomerExistance(req: Request, res: Response, next: Function) {
|
||||
const saleInvoice = { ...req.body };
|
||||
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 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether sale invoice items ids esits on the storage.
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
* @param {Function} 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 this.itemsService.isItemsIdsExists(
|
||||
tenantId, entriesItemsIds,
|
||||
);
|
||||
if (isItemsIdsExists.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Validate whether sale invoice number unqiue on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateInvoiceNumberUnique(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const saleInvoice = { ...req.body };
|
||||
|
||||
const isInvoiceNoExists = await this.saleInvoiceService.isSaleInvoiceNumberExists(
|
||||
tenantId,
|
||||
saleInvoice.invoice_no,
|
||||
req.params.id
|
||||
);
|
||||
if (isInvoiceNoExists) {
|
||||
return res
|
||||
.status(400)
|
||||
.send({
|
||||
errors: [{ type: 'SALE.INVOICE.NUMBER.IS.EXISTS', code: 200 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether sale invoice exists on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateInvoiceExistance(req: Request, res: Response, next: Function) {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
const isSaleInvoiceExists = await this.saleInvoiceService.isSaleInvoiceExists(
|
||||
tenantId, saleInvoiceId,
|
||||
);
|
||||
if (!isSaleInvoiceExists) {
|
||||
return res
|
||||
.status(404)
|
||||
.send({ errors: [{ type: 'SALE.INVOICE.NOT.FOUND', code: 200 }] });
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate sale invoice entries ids existance on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async valdiateInvoiceEntriesIdsExistance(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const saleInvoice = { ...req.body };
|
||||
const entriesItemsIds = saleInvoice.entries.map((e) => e.item_id);
|
||||
|
||||
const isItemsIdsExists = await this.itemsService.isItemsIdsExists(
|
||||
tenantId, entriesItemsIds,
|
||||
);
|
||||
if (isItemsIdsExists.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether the sale estimate entries IDs exist on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} 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.query()
|
||||
.whereIn('reference_id', [saleInvoiceId])
|
||||
.whereIn('reference_type', ['SaleInvoice']);
|
||||
|
||||
const storedEntriesIds = storedEntries.map((entry) => entry.id);
|
||||
const notFoundEntriesIds = difference(
|
||||
entriesIds,
|
||||
storedEntriesIds,
|
||||
);
|
||||
if (notFoundEntriesIds.length > 0) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'SALE.INVOICE.ENTRIES.IDS.NOT.FOUND', code: 500 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the entries items that not sellable.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} 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);
|
||||
|
||||
const sellableItems = await Item.query()
|
||||
.where('sellable', true)
|
||||
.whereIn('id', itemsIds);
|
||||
|
||||
const sellableItemsIds = sellableItems.map((item) => item.id);
|
||||
const notSellableItems = difference(itemsIds, sellableItemsIds);
|
||||
|
||||
if (notSellableItems.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'NOT.SELLABLE.ITEMS', code: 600 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new sale invoice.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
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 this.saleInvoiceService.createSaleInvoice(
|
||||
tenantId, saleInvoiceOTD,
|
||||
);
|
||||
return res.status(200).send({ id: storedSaleInvoice.id });
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit sale invoice details.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async editSaleInvoice(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
|
||||
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 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the sale invoice with associated entries and journal transactions.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
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 this.saleInvoiceService.deleteSaleInvoice(tenantId, saleInvoiceId);
|
||||
|
||||
return res.status(200).send({ id: saleInvoiceId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the sale invoice with associated entries.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getSaleInvoice(req: Request, res: Response) {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
const saleInvoice = await this.saleInvoiceService.getSaleInvoiceWithEntries(
|
||||
tenantId, saleInvoiceId,
|
||||
);
|
||||
return res.status(200).send({ sale_invoice: saleInvoice });
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the due sales invoices for the given customer.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async getDueSalesInvoice(req: Request, res: Response) {
|
||||
const { Customer, SaleInvoice } = req.models;
|
||||
const { tenantId } = req;
|
||||
|
||||
const filter = {
|
||||
customer_id: null,
|
||||
...req.query,
|
||||
};
|
||||
if (filter.customer_id) {
|
||||
const foundCustomer = await Customer.query().findById(filter.customer_id);
|
||||
|
||||
if (!foundCustomer) {
|
||||
return res.status(200).send({
|
||||
errors: [{ type: 'CUSTOMER.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
}
|
||||
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);
|
||||
}
|
||||
});
|
||||
return res.status(200).send({
|
||||
due_sales_invoices: dueSalesInvoices,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve paginated sales invoices with custom view metadata.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async getSalesInvoices(req, res) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
page: 1,
|
||||
page_size: 10,
|
||||
...req.query,
|
||||
};
|
||||
if (filter.stringified_filter_roles) {
|
||||
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
|
||||
}
|
||||
const { SaleInvoice, View, Resource } = req.models;
|
||||
const resource = await Resource.query()
|
||||
.remember()
|
||||
.where('name', 'sales_invoices')
|
||||
.withGraphFetched('fields')
|
||||
.first();
|
||||
|
||||
if (!resource) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'SALES_INVOICES_RESOURCE_NOT_FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
const viewMeta = await View.query()
|
||||
.modify('allMetadata')
|
||||
.modify('specificOrFavourite', filter.custom_view_id)
|
||||
.where('resource_id', resource.id)
|
||||
.first();
|
||||
|
||||
const listingBuilder = new DynamicListingBuilder();
|
||||
const errorReasons = [];
|
||||
|
||||
listingBuilder.addModelClass(SaleInvoice);
|
||||
listingBuilder.addCustomViewId(filter.custom_view_id);
|
||||
listingBuilder.addFilterRoles(filter.filter_roles);
|
||||
listingBuilder.addSortBy(filter.sort_by, filter.sort_order);
|
||||
listingBuilder.addView(viewMeta);
|
||||
|
||||
const dynamicListing = new DynamicListing(listingBuilder);
|
||||
|
||||
if (dynamicListing instanceof Error) {
|
||||
const errors = dynamicListingErrorsToResponse(dynamicListing);
|
||||
errorReasons.push(...errors);
|
||||
}
|
||||
if (errorReasons.length > 0) {
|
||||
return res.status(400).send({ errors: errorReasons });
|
||||
}
|
||||
const salesInvoices = await SaleInvoice.query().onBuild((builder) => {
|
||||
builder.withGraphFetched('entries');
|
||||
builder.withGraphFetched('customer');
|
||||
dynamicListing.buildQuery()(builder);
|
||||
}).pagination(filter.page - 1, filter.page_size);
|
||||
|
||||
return res.status(200).send({
|
||||
sales_invoices: {
|
||||
...salesInvoices,
|
||||
...(viewMeta
|
||||
? {
|
||||
view_meta: {
|
||||
customViewId: viewMeta.id,
|
||||
}
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
366
server/src/api/controllers/Sales/SalesReceipts.ts
Normal file
366
server/src/api/controllers/Sales/SalesReceipts.ts
Normal file
@@ -0,0 +1,366 @@
|
||||
import { Router, Request, Response } from 'express';
|
||||
import { check, param, query, matchedData } from 'express-validator';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import validateMiddleware from 'api/middleware/validateMiddleware';
|
||||
import asyncMiddleware from 'api/middleware/asyncMiddleware';
|
||||
import AccountsService from 'services/Accounts/AccountsService';
|
||||
import ItemsService from 'services/Items/ItemsService';
|
||||
import SaleReceiptService from 'services/Sales/SalesReceipts';
|
||||
import DynamicListingBuilder from 'services/DynamicListing/DynamicListingBuilder';
|
||||
import DynamicListing from 'services/DynamicListing/DynamicListing';
|
||||
import {
|
||||
dynamicListingErrorsToResponse
|
||||
} from 'services/DynamicListing/HasDynamicListing';
|
||||
|
||||
@Service()
|
||||
export default class SalesReceiptsController {
|
||||
@Inject()
|
||||
saleReceiptService: SaleReceiptService;
|
||||
|
||||
@Inject()
|
||||
accountsService: AccountsService;
|
||||
|
||||
@Inject()
|
||||
itemsService: ItemsService;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
router() {
|
||||
const router = Router();
|
||||
|
||||
router.post(
|
||||
'/:id', [
|
||||
...this.specificReceiptValidationSchema,
|
||||
...this.salesReceiptsValidationSchema,
|
||||
],
|
||||
validateMiddleware,
|
||||
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.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.bind(this)),
|
||||
asyncMiddleware(this.deleteSaleReceipt.bind(this))
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.listSalesReceiptsValidationSchema,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.listingSalesReceipts.bind(this))
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sales receipt validation schema.
|
||||
* @return {Array}
|
||||
*/
|
||||
get salesReceiptsValidationSchema() {
|
||||
return [
|
||||
check('customer_id').exists().isNumeric().toInt(),
|
||||
check('deposit_account_id').exists().isNumeric().toInt(),
|
||||
check('receipt_date').exists().isISO8601(),
|
||||
check('send_to_email').optional().isEmail(),
|
||||
check('reference_no').optional().trim().escape(),
|
||||
|
||||
check('entries').exists().isArray({ min: 1 }),
|
||||
|
||||
check('entries.*.id').optional({ nullable: true }).isNumeric().toInt(),
|
||||
check('entries.*.index').exists().isNumeric().toInt(),
|
||||
check('entries.*.item_id').exists().isNumeric().toInt(),
|
||||
check('entries.*.description').optional().trim().escape(),
|
||||
check('entries.*.quantity').exists().isNumeric().toInt(),
|
||||
check('entries.*.rate').exists().isNumeric().toInt(),
|
||||
check('entries.*.discount').optional().isNumeric().toInt(),
|
||||
|
||||
check('receipt_message').optional().trim().escape(),
|
||||
check('statement').optional().trim().escape(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Specific sale receipt validation schema.
|
||||
*/
|
||||
get specificReceiptValidationSchema() {
|
||||
return [
|
||||
param('id').exists().isNumeric().toInt()
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* List sales receipts validation schema.
|
||||
*/
|
||||
get listSalesReceiptsValidationSchema() {
|
||||
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 sale receipt exists on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async validateSaleReceiptExistance(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
const { id: saleReceiptId } = req.params;
|
||||
|
||||
const isSaleReceiptExists = await this.saleReceiptService
|
||||
.isSaleReceiptExists(
|
||||
tenantId,
|
||||
saleReceiptId,
|
||||
);
|
||||
if (!isSaleReceiptExists) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'SALE.RECEIPT.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether sale receipt customer exists on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateReceiptCustomerExistance(req: Request, res: Response, next: Function) {
|
||||
const saleReceipt = { ...req.body };
|
||||
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 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether sale receipt deposit account exists on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
async validateReceiptDepositAccountExistance(req: Request, res: Response, next: Function) {
|
||||
const { tenantId } = req;
|
||||
|
||||
const saleReceipt = { ...req.body };
|
||||
const isDepositAccountExists = await this.accountsService.isAccountExists(
|
||||
tenantId,
|
||||
saleReceipt.deposit_account_id
|
||||
);
|
||||
if (!isDepositAccountExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'DEPOSIT.ACCOUNT.NOT.EXISTS', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate whether receipt items ids exist on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} 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 this.itemsService.isItemsIdsExists(
|
||||
tenantId,
|
||||
estimateItemsIds
|
||||
);
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
return res.status(400).send({ errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 }] });
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate receipt entries ids existance on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} 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 this.saleReceiptService
|
||||
.isSaleReceiptEntriesIDsExists(
|
||||
tenantId,
|
||||
saleReceiptId,
|
||||
saleReceipt,
|
||||
);
|
||||
if (notExistsEntriesIds.length > 0) {
|
||||
return res.status(400).send({ errors: [{
|
||||
type: 'ENTRIES.IDS.NOT.FOUND',
|
||||
code: 500,
|
||||
}]
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new receipt.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
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 this.saleReceiptService
|
||||
.createSaleReceipt(
|
||||
tenantId,
|
||||
saleReceipt,
|
||||
);
|
||||
return res.status(200).send({ id: storedSaleReceipt.id });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the sale receipt with associated entries and journal transactions.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async deleteSaleReceipt(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const { id: saleReceiptId } = req.params;
|
||||
|
||||
// Deletes the sale receipt.
|
||||
await this.saleReceiptService.deleteSaleReceipt(tenantId, saleReceiptId);
|
||||
|
||||
return res.status(200).send({ id: saleReceiptId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit the sale receipt details with associated entries and re-write
|
||||
* journal transaction on the same date.
|
||||
* @param {Request} req
|
||||
* @param {Response} 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.
|
||||
if (errorReasons.length > 0) {
|
||||
return res.boom.badRequest(null, { errors: errorReasons });
|
||||
}
|
||||
// Update the given sale receipt details.
|
||||
await this.saleReceiptService.editSaleReceipt(
|
||||
tenantId,
|
||||
saleReceiptId,
|
||||
saleReceipt,
|
||||
);
|
||||
|
||||
return res.status(200).send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Listing sales receipts.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
async listingSalesReceipts(req: Request, res: Response) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
page: 1,
|
||||
page_size: 10,
|
||||
...req.query,
|
||||
};
|
||||
if (filter.stringified_filter_roles) {
|
||||
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
|
||||
}
|
||||
const { SaleReceipt, Resource, View } = req.models;
|
||||
const resource = await Resource.query()
|
||||
.remember()
|
||||
.where('name', 'sales_receipts')
|
||||
.withGraphFetched('fields')
|
||||
.first();
|
||||
|
||||
if (!resource) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'RESOURCE.NOT.FOUND', code: 200, }],
|
||||
});
|
||||
}
|
||||
const viewMeta = await View.query()
|
||||
.modify('allMetadata')
|
||||
.modify('specificOrFavourite', filter.custom_view_id)
|
||||
.where('resource_id', resource.id)
|
||||
.first();
|
||||
|
||||
const listingBuilder = new DynamicListingBuilder();
|
||||
const errorReasons = [];
|
||||
|
||||
listingBuilder.addView(viewMeta);
|
||||
listingBuilder.addModelClass(SaleReceipt);
|
||||
listingBuilder.addCustomViewId(filter.custom_view_id);
|
||||
listingBuilder.addFilterRoles(filter.filter_roles);
|
||||
listingBuilder.addSortBy(filter.sort_by, filter.sort_order);
|
||||
|
||||
const dynamicListing = new DynamicListing(listingBuilder);
|
||||
|
||||
if (dynamicListing instanceof Error) {
|
||||
const errors = dynamicListingErrorsToResponse(dynamicListing);
|
||||
errorReasons.push(...errors);
|
||||
}
|
||||
const salesReceipts = await SaleReceipt.query().onBuild((builder) => {
|
||||
builder.withGraphFetched('customer');
|
||||
builder.withGraphFetched('depositAccount');
|
||||
builder.withGraphFetched('entries');
|
||||
dynamicListing.buildQuery()(builder);
|
||||
}).pagination(filter.page - 1, filter.page_size);
|
||||
|
||||
return res.status(200).send({
|
||||
sales_receipts: {
|
||||
...salesReceipts,
|
||||
...(viewMeta ? {
|
||||
view_meta: {
|
||||
customViewId: viewMeta.id,
|
||||
}
|
||||
} : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
22
server/src/api/controllers/Sales/index.ts
Normal file
22
server/src/api/controllers/Sales/index.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import express from 'express';
|
||||
import { Container } from 'typedi';
|
||||
import SalesEstimates from './SalesEstimates';
|
||||
import SalesReceipts from './SalesReceipts';
|
||||
import SalesInvoices from './SalesInvoices'
|
||||
import PaymentReceives from './PaymentReceives';
|
||||
|
||||
export default {
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
router() {
|
||||
const router = express.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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user