mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-17 21:30:31 +00:00
- feat: Sales estimates APIs.
- feat: Sales invoices APIs. - feat: Sales receipts APIs. - WIP: Sales payment receipts. - WIP: Purchases bills. - WIP: Purchases payments made.
This commit is contained in:
@@ -123,7 +123,6 @@ export default {
|
||||
const foundAccountTypePromise = AccountType.query().findById(
|
||||
form.account_type_id
|
||||
);
|
||||
|
||||
const [foundAccountCode, foundAccountType] = await Promise.all([
|
||||
foundAccountCodePromise,
|
||||
foundAccountTypePromise,
|
||||
@@ -379,7 +378,6 @@ export default {
|
||||
);
|
||||
dynamicFilter.setFilter(sortByFilter);
|
||||
}
|
||||
|
||||
// View roles.
|
||||
if (view && view.roles.length > 0) {
|
||||
const viewFilter = new DynamicFilterViews(
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
import express from 'express';
|
||||
|
||||
export default {
|
||||
|
||||
router() {
|
||||
const router = express.Router();
|
||||
|
||||
return router;
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
|
||||
|
||||
export default class InventoryValuationSummary {
|
||||
|
||||
static router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/inventory_valuation_summary',
|
||||
asyncMiddleware(this.inventoryValuationSummary),
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
static inventoryValuationSummary(req, res) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,6 @@ export default class PayableAgingSummary extends AgingReport {
|
||||
filter,
|
||||
vendors_ids
|
||||
);
|
||||
|
||||
if (notStoredCustomersIds.length) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'VENDORS.IDS.NOT.FOUND', code: 300 }],
|
||||
|
||||
@@ -27,24 +27,28 @@ export default {
|
||||
|
||||
router.post('/:id',
|
||||
this.editItem.validation,
|
||||
asyncMiddleware(this.editItem.handler));
|
||||
asyncMiddleware(this.editItem.handler)
|
||||
);
|
||||
|
||||
router.post('/',
|
||||
this.newItem.validation,
|
||||
asyncMiddleware(this.newItem.handler));
|
||||
asyncMiddleware(this.newItem.handler)
|
||||
);
|
||||
|
||||
router.delete('/:id',
|
||||
this.deleteItem.validation,
|
||||
asyncMiddleware(this.deleteItem.handler));
|
||||
asyncMiddleware(this.deleteItem.handler)
|
||||
);
|
||||
|
||||
router.delete('/',
|
||||
this.bulkDeleteItems.validation,
|
||||
asyncMiddleware(this.bulkDeleteItems.handler));
|
||||
asyncMiddleware(this.bulkDeleteItems.handler)
|
||||
);
|
||||
|
||||
router.get('/',
|
||||
this.listItems.validation,
|
||||
asyncMiddleware(this.listItems.handler));
|
||||
|
||||
asyncMiddleware(this.listItems.handler)
|
||||
);
|
||||
return router;
|
||||
},
|
||||
|
||||
@@ -57,6 +61,10 @@ export default {
|
||||
check('type').exists().trim().escape()
|
||||
.isIn(['service', 'non-inventory', 'inventory']),
|
||||
check('sku').optional({ nullable: true }).trim().escape(),
|
||||
|
||||
check('purchasable').exists().isBoolean().toBoolean(),
|
||||
check('sellable').exists().isBoolean().toBoolean(),
|
||||
|
||||
check('cost_price').exists().isNumeric().toFloat(),
|
||||
check('sell_price').exists().isNumeric().toFloat(),
|
||||
check('cost_account_id').exists().isInt().toInt(),
|
||||
@@ -66,6 +74,10 @@ export default {
|
||||
.exists()
|
||||
.isInt()
|
||||
.toInt(),
|
||||
|
||||
check('sell_description').optional().trim().escape(),
|
||||
check('cost_description').optional().trim().escape(),
|
||||
|
||||
check('category_id').optional({ nullable: true }).isInt().toInt(),
|
||||
|
||||
check('custom_fields').optional().isArray({ min: 1 }),
|
||||
@@ -204,9 +216,12 @@ export default {
|
||||
check('cost_account_id').exists().isInt(),
|
||||
check('sell_account_id').exists().isInt(),
|
||||
check('category_id').optional({ nullable: true }).isInt().toInt(),
|
||||
check('note').optional(),
|
||||
check('note').optional().trim().escape(),
|
||||
check('attachment').optional(),
|
||||
check('')
|
||||
check('sell_description').optional().trim().escape(),
|
||||
check('cost_description').optional().trim().escape(),
|
||||
check('purchasable').exists().isBoolean().toBoolean(),
|
||||
check('sellable').exists().isBoolean().toBoolean(),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const validationErrors = validationResult(req);
|
||||
|
||||
157
server/src/http/controllers/Purchases/Bills.js
Normal file
157
server/src/http/controllers/Purchases/Bills.js
Normal file
@@ -0,0 +1,157 @@
|
||||
import express from "express";
|
||||
import { check, param } from 'express-validator';
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
import BillsService from "@/services/Purchases/Bills";
|
||||
import BaseController from '@/http/controllers/BaseController';
|
||||
import VendorsServices from '@/services/Vendors/VendorsService';
|
||||
import ItemsService from '@/services/Items/ItemsService';
|
||||
|
||||
export default class BillsController extends BaseController {
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.post('/', [
|
||||
...this.validationSchema,
|
||||
],
|
||||
validateMiddleware,
|
||||
this.validateVendorExistance,
|
||||
this.validateItemsIds,
|
||||
this.validateBillNumberExists,
|
||||
this.newBill,
|
||||
);
|
||||
// router.post('/:id', [
|
||||
// ...this.billValidationSchema,
|
||||
// ...this.validationSchema,
|
||||
// ],
|
||||
// validateMiddleware,
|
||||
// this.validateBillExistance,
|
||||
// this.validateVendorExistance,
|
||||
// this.validateItemsIds,
|
||||
// this.editBill,
|
||||
// );
|
||||
router.delete('/:id', [
|
||||
...this.billValidationSchema,
|
||||
],
|
||||
validateMiddleware,
|
||||
this.validateBillExistance,
|
||||
this.deleteBill
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Common validation schema.
|
||||
*/
|
||||
static get validationSchema() {
|
||||
return [
|
||||
check('bill_number').exists().trim().escape(),
|
||||
check('bill_date').exists().isISO8601(),
|
||||
check('due_date').optional().isISO8601(),
|
||||
check('vendor_id').exists().isNumeric().toInt(),
|
||||
check('note').optional().trim().escape(),
|
||||
check('entries').isArray({ min: 1 }),
|
||||
check('entries.*.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(),
|
||||
]
|
||||
}
|
||||
|
||||
static get billValidationSchema() {
|
||||
return [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
];
|
||||
}
|
||||
|
||||
static async validateVendorExistance(req, res, next) {
|
||||
const isVendorExists = await VendorsServices.isVendorExists(req.body.vendor_id);
|
||||
if (!isVendorExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'VENDOR.ID.NOT.FOUND', code: 300 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the given bill existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateBillExistance(req, res, next) {
|
||||
const isBillExists = await BillsService.isBillExists(req.params.id);
|
||||
if (!isBillExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'BILL.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the entries items ids.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateItemsIds(req, res, next) {
|
||||
const itemsIds = req.body.entries.map((e) => e.item_id);
|
||||
const notFoundItemsIds = await ItemsService.isItemsIdsExists(
|
||||
itemsIds
|
||||
);
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.FOUND', code: 400 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the bill number existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateBillNumberExists(req, res, next) {
|
||||
const isBillNoExists = await BillsService.isBillNoExists(req.body.bill_number);
|
||||
|
||||
if (isBillNoExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'BILL.NUMBER.EXISTS', code: 500 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new bill and records journal transactions.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async newBill(req, res, next) {
|
||||
const bill = { ...req.body };
|
||||
const storedBill = await BillsService.createBill(bill);
|
||||
|
||||
return res.status(200).send({ id: storedBill });
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the given bill with associated entries and journal transactions.
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
* @return {Response}
|
||||
*/
|
||||
static async deleteBill(req, res) {
|
||||
const billId = req.params.id;
|
||||
await BillsService.deleteBill(billId);
|
||||
|
||||
return res.status(200).send({ id: billId });
|
||||
}
|
||||
}
|
||||
140
server/src/http/controllers/Purchases/BillsPayments.js
Normal file
140
server/src/http/controllers/Purchases/BillsPayments.js
Normal file
@@ -0,0 +1,140 @@
|
||||
|
||||
import express from 'express';
|
||||
import { check, param } from 'express-validator';
|
||||
import BaseController from '@/http/controllers/BaseController';
|
||||
import BillPaymentsService from '@/services/Purchases/BillPayments';
|
||||
|
||||
export default class BillsPayments extends BaseController {
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.post('/', [
|
||||
...this.billPaymentSchemaValidation,
|
||||
],
|
||||
this.validatePaymentAccount,
|
||||
this.validatePaymentNumber,
|
||||
this.validateItemsIds,
|
||||
this.createBillPayment,
|
||||
);
|
||||
router.delete('/:id',
|
||||
this.validateBillPaymentExistance,
|
||||
this.deleteBillPayment,
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bill payments schema validation.
|
||||
*/
|
||||
static get billPaymentSchemaValidation() {
|
||||
return [
|
||||
check('payment_account_id').exists().isNumeric().toInt(),
|
||||
check('payment_number').exists().trim().escape(),
|
||||
check('payment_date').exists(),
|
||||
check('description').optional().trim().escape(),
|
||||
check('entries').exists().isArray({ min: 1 }),
|
||||
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(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the bill payment existance.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateBillPaymentExistance(req, res, next) {
|
||||
const foundBillPayment = await BillPaymentsService.isBillPaymentExists(req.params.id);
|
||||
|
||||
if (!foundBillPayment) {
|
||||
return res.status(404).sned({
|
||||
errors: [{ type: 'BILL.PAYMENT.NOT.FOUND', code: 100 }],
|
||||
});
|
||||
}
|
||||
next(req, res, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the payment account.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validatePaymentAccount(req, res, next) {
|
||||
const isAccountExists = AccountsService.isAccountExists(req.body.payment_account_id);
|
||||
|
||||
if (!isAccountExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'PAYMENT.ACCOUNT.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
next(req, res, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the payment number uniqness.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} res
|
||||
*/
|
||||
static async validatePaymentNumber(req, res, next) {
|
||||
const isNumberExists = await BillPaymentsService.isBillNoExists(req.body.payment_number);
|
||||
|
||||
if (!isNumberExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'PAYMENT.NUMBER.NOT.UNIQUE', code: 300 }],
|
||||
});
|
||||
}
|
||||
next(req, res, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* validate entries items ids existance on the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Function} next
|
||||
*/
|
||||
static async validateItemsIds(req, res, next) {
|
||||
const itemsIds = req.body.entries.map((e) => e.item_id);
|
||||
const notFoundItemsIds = await ItemsService.isItemsIdsExists(
|
||||
itemsIds
|
||||
);
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.FOUND', code: 400 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a bill payment.
|
||||
* @async
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async createBillPayment(req, res) {
|
||||
const billPayment = { ...req.body };
|
||||
const storedPayment = await BillPaymentsService.createBillPayment(billPayment);
|
||||
|
||||
return res.status(200).send({ id: storedPayment.id });
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @return {Response} res
|
||||
*/
|
||||
static async deleteBillPayment(req, res) {
|
||||
|
||||
}
|
||||
}
|
||||
15
server/src/http/controllers/Purchases/index.js
Normal file
15
server/src/http/controllers/Purchases/index.js
Normal file
@@ -0,0 +1,15 @@
|
||||
import express from 'express';
|
||||
import Bills from '@/http/controllers/Purchases/Bills'
|
||||
import BillPayments from '@/http/controllers/Purchases/BillsPayments';
|
||||
|
||||
export default {
|
||||
|
||||
router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use('/bills', Bills.router());
|
||||
router.use('/bill_payments', BillPayments.router());
|
||||
|
||||
return router;
|
||||
}
|
||||
}
|
||||
215
server/src/http/controllers/Sales/PaymentReceives.js
Normal file
215
server/src/http/controllers/Sales/PaymentReceives.js
Normal file
@@ -0,0 +1,215 @@
|
||||
import express from 'express';
|
||||
import { check, param } from 'express-validator';
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
import PaymentReceiveService from '@/services/Sales/PaymentReceive';
|
||||
import CustomersService from '@/services/Customers/CustomersService';
|
||||
import SaleInvoicesService from '@/services/Sales/SaleInvoice';
|
||||
import AccountsService from '@/services/Accounts/AccountsService';
|
||||
|
||||
export default class PaymentReceivesController {
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
static router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.post('/',
|
||||
this.newPaymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
this.validatePaymentReceiveNoExistance,
|
||||
this.validateCustomerExistance,
|
||||
this.validateDepositAccount,
|
||||
this.validateInvoicesIDs,
|
||||
asyncMiddleware(this.newPaymentReceive),
|
||||
);
|
||||
router.post('/:id',
|
||||
this.editPaymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
this.validatePaymentReceiveNoExistance,
|
||||
this.validateCustomerExistance,
|
||||
this.validateDepositAccount,
|
||||
this.validateInvoicesIDs,
|
||||
asyncMiddleware(this.editPaymentReceive),
|
||||
);
|
||||
router.get('/:id',
|
||||
this.paymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
this.validatePaymentReceiveExistance,
|
||||
asyncMiddleware(this.getPaymentReceive),
|
||||
);
|
||||
router.delete('/:id',
|
||||
this.paymentReceiveValidation,
|
||||
validateMiddleware,
|
||||
this.validatePaymentReceiveExistance,
|
||||
asyncMiddleware(this.deletePaymentReceive),
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the payment receive number existance.
|
||||
*/
|
||||
static async validatePaymentReceiveNoExistance(req, res, next) {
|
||||
const isPaymentNoExists = await PaymentReceiveService.isPaymentReceiveNoExists(
|
||||
req.body.payment_receive_no,
|
||||
);
|
||||
if (isPaymentNoExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'PAYMENT.RECEIVE.NUMBER.EXISTS', code: 400 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the payment receive existance.
|
||||
*/
|
||||
static async validatePaymentReceiveExistance(req, res, next) {
|
||||
const isPaymentNoExists = await PaymentReceiveService.isPaymentReceiveExists(
|
||||
req.params.id,
|
||||
);
|
||||
if (!isPaymentNoExists) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'PAYMENT.RECEIVE.NO.EXISTS', code: 600 }],
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the deposit account id existance.
|
||||
*/
|
||||
static async validateDepositAccount(req, res, next) {
|
||||
const isDepositAccExists = await AccountsService.isAccountExists(
|
||||
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
|
||||
*/
|
||||
static async validateCustomerExistance(req, res, next) {
|
||||
const isCustomerExists = await CustomersService.isCustomerExists(
|
||||
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.
|
||||
*/
|
||||
static async validateInvoicesIDs(req, res, next) {
|
||||
const invoicesIds = req.body.entries.map((e) => e.invoice_id);
|
||||
const notFoundInvoicesIDs = await SaleInvoicesService.isInvoicesExist(invoicesIds);
|
||||
|
||||
if (notFoundInvoicesIDs.length > 0) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'INVOICES.IDS.NOT.FOUND', code: 500 }],
|
||||
});
|
||||
}
|
||||
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('entries').isArray({ min: 1 }),
|
||||
check('entries.*.invoice_id').exists().isNumeric().toInt(),
|
||||
check('entries.*.payment_amount').exists().isNumeric().toInt(),
|
||||
];
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
return res.status(200).send({ id: storedPaymentReceive.id });
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit payment receive validation.
|
||||
*/
|
||||
static get editPaymentReceiveValidation() {
|
||||
return [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
...this.paymentReceiveSchema,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit the given payment receive.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
*/
|
||||
static async editPaymentReceive(req, res) {
|
||||
const paymentReceive = { ...req.body };
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
await PaymentReceiveService.editPaymentReceive(paymentReceiveId, paymentReceive);
|
||||
|
||||
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) {
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
await PaymentReceiveService.deletePaymentReceive(paymentReceiveId);
|
||||
|
||||
return res.status(200).send({ id: paymentReceiveId });
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the given payment receive details.
|
||||
* @asycn
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
*/
|
||||
static async getPaymentReceive(req, res) {
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
const paymentReceive = await PaymentReceiveService.getPaymentReceive(paymentReceiveId);
|
||||
|
||||
return res.status(200).send({ paymentReceive });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import express from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
import CustomersService from '@/services/Customers/CustomersService';
|
||||
import SaleEstimateService from '@/services/Sales/SalesEstimate';
|
||||
import ItemsService from '@/services/Items/ItemsService';
|
||||
import DynamicListingBuilder from '@/services/DynamicListing/DynamicListingBuilder';
|
||||
import DynamicListing from '@/services/DynamicListing/DynamicListing';
|
||||
|
||||
export default {
|
||||
router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
this.newEstimate.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.newEstimate.handler)
|
||||
);
|
||||
router.post(
|
||||
'/:id',
|
||||
this.editEstimate.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.editEstimate.handler)
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
this.deleteEstimate.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.deleteEstimate.handler)
|
||||
);
|
||||
router.get(
|
||||
'/:id',
|
||||
this.getEstimate.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.getEstimate.handler)
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.getEstimates.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.getEstimates.handler)
|
||||
);
|
||||
|
||||
return router;
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle create a new estimate with associated entries.
|
||||
*/
|
||||
newEstimate: {
|
||||
validation: [
|
||||
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.*.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(),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const estimate = { ...req.body };
|
||||
const isCustomerExists = await CustomersService.isCustomerExists(
|
||||
estimate.customer_id
|
||||
);
|
||||
|
||||
if (!isCustomerExists) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'CUSTOMER.ID.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
const isEstNumberUnqiue = await SaleEstimateService.isEstimateNumberUnique(
|
||||
estimate.estimate_number
|
||||
);
|
||||
if (isEstNumberUnqiue) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ESTIMATE.NUMBER.IS.NOT.UNQIUE', code: 300 }],
|
||||
});
|
||||
}
|
||||
// Validate items ids in estimate entries exists.
|
||||
const estimateItemsIds = estimate.entries.map(e => e.item_id);
|
||||
const notFoundItemsIds = await ItemsService.isItemsIdsExists(estimateItemsIds);
|
||||
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 }],
|
||||
});
|
||||
}
|
||||
const storedEstimate = await SaleEstimateService.createEstimate(estimate);
|
||||
|
||||
return res.status(200).send({ id: storedEstimate.id });
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle update estimate details with associated entries.
|
||||
*/
|
||||
editEstimate: {
|
||||
validation: [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
|
||||
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.*.id').optional().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(),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const { id: estimateId } = req.params;
|
||||
const estimate = { ...req.body };
|
||||
const storedEstimate = await SaleEstimateService.getEstimate(estimateId);
|
||||
|
||||
if (!storedEstimate) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'SALE.ESTIMATE.ID.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
const isCustomerExists = await CustomersService.isCustomerExists(
|
||||
estimate.customer_id
|
||||
);
|
||||
if (!isCustomerExists) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'CUSTOMER.ID.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
// Validate the estimate number is unique except on the current estimate id.
|
||||
const foundEstimateNumbers = await SaleEstimateService.isEstimateNumberUnique(
|
||||
estimate.estimate_number,
|
||||
storedEstimate.id, // Exclude the given estimate id.
|
||||
);
|
||||
if (foundEstimateNumbers) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ESTIMATE.NUMBER.IS.NOT.UNQIUE', code: 300 }],
|
||||
});
|
||||
}
|
||||
// Validate items ids in estimate entries exists.
|
||||
const estimateItemsIds = estimate.entries.map(e => e.item_id);
|
||||
const notFoundItemsIds = await ItemsService.isItemsIdsExists(estimateItemsIds);
|
||||
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 }],
|
||||
});
|
||||
}
|
||||
// Validate the sale estimate entries IDs that not found.
|
||||
const notFoundEntriesIds = await SaleEstimateService.isEstimateEntriesIDsExists(
|
||||
storedEstimate.id,
|
||||
estimate
|
||||
);
|
||||
if (notFoundEntriesIds.length > 0) {
|
||||
return res.boom.badRequest(null, {
|
||||
errors: [{ type: 'ESTIMATE.NOT.FOUND.ENTRIES.IDS', code: 500 }],
|
||||
});
|
||||
}
|
||||
// Update estimate with associated estimate entries.
|
||||
await SaleEstimateService.editEstimate(estimateId, estimate);
|
||||
|
||||
return res.status(200).send({ id: estimateId });
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Deletes the given estimate with associated entries.
|
||||
*/
|
||||
deleteEstimate: {
|
||||
validation: [param('id').exists().isNumeric().toInt()],
|
||||
async handler(req, res) {
|
||||
const { id: estimateId } = req.params;
|
||||
const isEstimateExists = await SaleEstimateService.isEstimateExists(estimateId);
|
||||
|
||||
if (!isEstimateExists) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'SALE.ESTIMATE.ID.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
await SaleEstimateService.deleteEstimate(estimateId);
|
||||
|
||||
return res.status(200).send({ id: estimateId });
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Retrieve the given estimate with associated entries.
|
||||
*/
|
||||
getEstimate: {
|
||||
validation: [param('id').exists().isNumeric().toInt()],
|
||||
async handler(req, res) {
|
||||
const { id: estimateId } = req.params;
|
||||
const estimate = await SaleEstimateService.getEstimateWithEntries(estimateId);
|
||||
|
||||
if (!estimate) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'SALE.ESTIMATE.ID.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
return res.status(200).send({ estimate });
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Retrieve estimates with pagination metadata.
|
||||
*/
|
||||
getEstimates: {
|
||||
validation: [
|
||||
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']),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
...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.tenant().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);
|
||||
return builder;
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
sales_estimates: salesEstimates,
|
||||
...(viewMeta ? {
|
||||
custom_view_id: viewMeta.id,
|
||||
} : {}),
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
261
server/src/http/controllers/Sales/SalesInvoices.js
Normal file
261
server/src/http/controllers/Sales/SalesInvoices.js
Normal file
@@ -0,0 +1,261 @@
|
||||
import express from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
import validateMiddleware from '@/http/middleware/validateMiddleware';
|
||||
import asyncMiddleware from '@/http/middleware/asyncMiddleware';
|
||||
import SaleInvoiceService from '@/services/Sales/SaleInvoice';
|
||||
import ItemsService from '@/services/Items/ItemsService';
|
||||
import CustomersService from '@/services/Customers/CustomersService';
|
||||
import { SaleInvoice } from '@/models';
|
||||
import DynamicListing, { DYNAMIC_LISTING_ERRORS } from '@/services/DynamicListing/DynamicListing';
|
||||
import DynamicListingBuilder from '../../../services/DynamicListing/DynamicListingBuilder';
|
||||
import {
|
||||
dynamicListingErrorsToResponse
|
||||
} from '@/services/DynamicListing/hasDynamicListing';
|
||||
|
||||
export default {
|
||||
router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.post(
|
||||
'/',
|
||||
this.newSaleInvoice.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.newSaleInvoice.handler)
|
||||
);
|
||||
router.post(
|
||||
'/:id',
|
||||
this.editSaleInvoice.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.editSaleInvoice.handler)
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
this.deleteSaleInvoice.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.deleteSaleInvoice.handler)
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.getSalesInvoices.validation,
|
||||
asyncMiddleware(this.getSalesInvoices.handler)
|
||||
);
|
||||
return router;
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new sale invoice.
|
||||
*/
|
||||
newSaleInvoice: {
|
||||
validation: [
|
||||
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.*.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(),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const errorReasons = [];
|
||||
const saleInvoice = { ...req.body };
|
||||
const isInvoiceNoExists = await SaleInvoiceService.isSaleInvoiceNumberExists(
|
||||
saleInvoice.invoice_no
|
||||
);
|
||||
if (isInvoiceNoExists) {
|
||||
errorReasons.push({ type: 'SALE.INVOICE.NUMBER.IS.EXISTS', code: 200 });
|
||||
}
|
||||
const entriesItemsIds = saleInvoice.entries.map((e) => e.item_id);
|
||||
const isItemsIdsExists = await ItemsService.isItemsIdsExists(
|
||||
entriesItemsIds
|
||||
);
|
||||
if (isItemsIdsExists.length > 0) {
|
||||
errorReasons.push({ type: 'ITEMS.IDS.NOT.EXISTS', code: 300 });
|
||||
}
|
||||
// Validate the customer id exists.
|
||||
const isCustomerIDExists = await CustomersService.isCustomerExists(
|
||||
saleInvoice.customer_id
|
||||
);
|
||||
if (!isCustomerIDExists) {
|
||||
errorReasons.push({ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 });
|
||||
}
|
||||
if (errorReasons.length > 0) {
|
||||
return res.status(400).send({ errors: errorReasons });
|
||||
}
|
||||
// Creates a new sale invoice with associated entries.
|
||||
const storedSaleInvoice = await SaleInvoiceService.createSaleInvoice(
|
||||
saleInvoice
|
||||
);
|
||||
return res.status(200).send({ id: storedSaleInvoice.id });
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Edit sale invoice details.
|
||||
*/
|
||||
editSaleInvoice: {
|
||||
validation: [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
|
||||
check('customer_id').exists().isNumeric().toInt(),
|
||||
check('invoice_date').exists(),
|
||||
check('due_date').exists(),
|
||||
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.*.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(),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const saleInvoice = { ...req.body };
|
||||
const isSaleInvoiceExists = await SaleInvoiceService.isSaleInvoiceExists(
|
||||
saleInvoiceId
|
||||
);
|
||||
if (!isSaleInvoiceExists) {
|
||||
return res
|
||||
.status(404)
|
||||
.send({ type: 'SALE.INVOICE.NOT.FOUND', code: 200 });
|
||||
}
|
||||
const errorReasons = [];
|
||||
|
||||
// Validate the invoice number uniqness.
|
||||
const isInvoiceNoExists = await SaleInvoiceService.isSaleInvoiceNumberExists(
|
||||
saleInvoice.invoice_no,
|
||||
saleInvoiceId
|
||||
);
|
||||
if (isInvoiceNoExists) {
|
||||
errorReasons.push({ type: 'SALE.INVOICE.NUMBER.IS.EXISTS', code: 200 });
|
||||
}
|
||||
// Validate sale invoice entries items IDs.
|
||||
const entriesItemsIds = saleInvoice.entries.map((e) => e.item_id);
|
||||
const isItemsIdsExists = await ItemsService.isItemsIdsExists(
|
||||
entriesItemsIds
|
||||
);
|
||||
if (isItemsIdsExists.length > 0) {
|
||||
errorReasons.push({ type: 'ITEMS.IDS.NOT.EXISTS', code: 300 });
|
||||
}
|
||||
// Validate the customer id exists.
|
||||
const isCustomerIDExists = await CustomersService.isCustomerExists(
|
||||
saleInvoice.customer_id
|
||||
);
|
||||
if (!isCustomerIDExists) {
|
||||
errorReasons.push({ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 });
|
||||
}
|
||||
if (errorReasons.length > 0) {
|
||||
return res.status(400).send({ errors: errorReasons });
|
||||
}
|
||||
// Update the given sale invoice details.
|
||||
await SaleInvoiceService.editSaleInvoice(saleInvoiceId, saleInvoice);
|
||||
|
||||
return res.status(200).send({ id: saleInvoice.id });
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Deletes the sale invoice with associated entries and journal transactions.
|
||||
*/
|
||||
deleteSaleInvoice: {
|
||||
validation: [param('id').exists().isNumeric().toInt()],
|
||||
async handler(req, res) {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const isSaleInvoiceExists = await SaleInvoiceService.isSaleInvoiceExists(
|
||||
saleInvoiceId
|
||||
);
|
||||
if (!isSaleInvoiceExists) {
|
||||
return res
|
||||
.status(404)
|
||||
.send({ errors: [{ type: 'SALE.INVOICE.NOT.FOUND', code: 200 }] });
|
||||
}
|
||||
// Deletes the sale invoice with associated entries and journal transaction.
|
||||
await SaleInvoiceService.deleteSaleInvoice(saleInvoiceId);
|
||||
|
||||
return res.status(200).send();
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Retrieve paginated sales invoices with custom view metadata.
|
||||
*/
|
||||
getSalesInvoices: {
|
||||
validation: [
|
||||
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']),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
...req.query,
|
||||
};
|
||||
if (filter.stringified_filter_roles) {
|
||||
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
|
||||
}
|
||||
const { SaleInvoice, 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 = View.query()
|
||||
.modify('allMetadata')
|
||||
.modify('specificOrFavourite', filter.custom_view_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(dynamicListingBuilder);
|
||||
|
||||
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) => {
|
||||
dynamicListing.buildQuery()(builder);
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
sales_invoices: salesInvoices,
|
||||
...(viewMeta
|
||||
? {
|
||||
customViewId: viewMeta.id,
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,276 @@
|
||||
import express from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
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/SalesReceipt';
|
||||
import DynamicListingBuilder from '@/services/DynamicListing/DynamicListingBuilder';
|
||||
import DynamicListing from '@/services/DynamicListing/DynamicListing';
|
||||
import {
|
||||
dynamicListingErrorsToResponse
|
||||
} from '@/services/DynamicListing/HasDynamicListing';
|
||||
|
||||
export default {
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
router() {
|
||||
const router = express.Router();
|
||||
|
||||
router.post(
|
||||
'/:id',
|
||||
this.editSaleReceipt.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.editSaleReceipt.handler)
|
||||
);
|
||||
router.post(
|
||||
'/',
|
||||
this.newSaleReceipt.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.newSaleReceipt.handler)
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
this.deleteSaleReceipt.handler,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.deleteSaleReceipt.handler)
|
||||
);
|
||||
router.get(
|
||||
'/',
|
||||
this.listingSalesReceipts.validation,
|
||||
validateMiddleware,
|
||||
asyncMiddleware(this.listingSalesReceipts.handler)
|
||||
);
|
||||
return router;
|
||||
},
|
||||
|
||||
/**
|
||||
* Creates a new receipt.
|
||||
*/
|
||||
newSaleReceipt: {
|
||||
validation: [
|
||||
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.*.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(),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const saleReceipt = { ...req.body };
|
||||
|
||||
const isCustomerExists = await CustomersService.isCustomerExists(
|
||||
saleReceipt.customer_id
|
||||
);
|
||||
const isDepositAccountExists = await AccountsService.isAccountExists(
|
||||
saleReceipt.deposit_account_id
|
||||
);
|
||||
const errorReasons = [];
|
||||
|
||||
if (!isCustomerExists) {
|
||||
errorReasons.push({ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 });
|
||||
}
|
||||
if (!isDepositAccountExists) {
|
||||
errorReasons.push({ type: 'DEPOSIT.ACCOUNT.NOT.EXISTS', code: 300 });
|
||||
}
|
||||
// Validate items ids in estimate entries exists.
|
||||
const estimateItemsIds = saleReceipt.entries.map((e) => e.item_id);
|
||||
const notFoundItemsIds = await ItemsService.isItemsIdsExists(
|
||||
estimateItemsIds
|
||||
);
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
errorReasons.push({ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 });
|
||||
}
|
||||
if (errorReasons.length > 0) {
|
||||
return res.status(400).send({ errors: errorReasons });
|
||||
}
|
||||
// Store the given sale receipt details with associated entries.
|
||||
const storedSaleReceipt = await SaleReceiptService.createSaleReceipt(
|
||||
saleReceipt
|
||||
);
|
||||
|
||||
return res.status(200).send({ id: storedSaleReceipt.id });
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Deletes the sale receipt with associated entries and journal transactions.
|
||||
*/
|
||||
deleteSaleReceipt: {
|
||||
validation: [param('id').exists().isNumeric().toInt()],
|
||||
async handler(req, res) {
|
||||
const { id: saleReceiptId } = req.params;
|
||||
const isSaleReceiptExists = await SaleReceiptService.isSaleReceiptExists(
|
||||
saleReceiptId
|
||||
);
|
||||
|
||||
if (!isSaleReceiptExists) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'SALE.RECEIPT.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
// Deletes the sale receipt.
|
||||
await SaleReceiptService.deleteSaleReceipt(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.
|
||||
*/
|
||||
editSaleReceipt: {
|
||||
validation: [
|
||||
param('id').exists().isNumeric().toInt(),
|
||||
|
||||
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.*.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(),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const { id: saleReceiptId } = req.params;
|
||||
const saleReceipt = { ...req.body };
|
||||
|
||||
const isSaleReceiptExists = await SaleReceiptService.isSaleReceiptExists(
|
||||
saleReceiptId
|
||||
);
|
||||
if (!isSaleReceiptExists) {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'SALE.RECEIPT.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
const isCustomerExists = await CustomersService.isCustomerExists(
|
||||
saleReceipt.customer_id
|
||||
);
|
||||
const isDepositAccountExists = await AccountsService.isAccountsExists(
|
||||
saleReceipt.deposit_account_id
|
||||
);
|
||||
const errorReasons = [];
|
||||
|
||||
if (!isCustomerExists) {
|
||||
errorReasons.push({ type: 'CUSTOMER.ID.NOT.EXISTS', code: 200 });
|
||||
}
|
||||
if (!isDepositAccountExists) {
|
||||
errorReasons.push({ type: 'DEPOSIT.ACCOUNT.NOT.EXISTS', code: 300 });
|
||||
}
|
||||
// Validate items ids in estimate entries exists.
|
||||
const entriesItemsIDs = saleReceipt.entries.map((e) => e.item_id);
|
||||
const notFoundItemsIds = await ItemsService.isItemsIdsExists(
|
||||
entriesItemsIDs
|
||||
);
|
||||
if (notFoundItemsIds.length > 0) {
|
||||
errorReasons.push({ type: 'ITEMS.IDS.NOT.EXISTS', code: 400 });
|
||||
}
|
||||
// Validate the entries IDs that not stored or associated to the sale receipt.
|
||||
const notExistsEntriesIds = await SaleReceiptService.isSaleReceiptEntriesIDsExists(
|
||||
saleReceiptId,
|
||||
saleReceipt
|
||||
);
|
||||
if (notExistsEntriesIds.length > 0) {
|
||||
errorReasons.push({
|
||||
type: 'ENTRIES.IDS.NOT.FOUND',
|
||||
code: 500,
|
||||
});
|
||||
}
|
||||
// Handle all errors with reasons messages.
|
||||
if (errorReasons.length > 0) {
|
||||
return res.boom.badRequest(null, { errors: errorReasons });
|
||||
}
|
||||
// Update the given sale receipt details.
|
||||
await SaleReceiptService.editSaleReceipt(saleReceiptId, saleReceipt);
|
||||
|
||||
return res.status(200).send();
|
||||
},
|
||||
},
|
||||
|
||||
/**
|
||||
* Listing sales receipts.
|
||||
*/
|
||||
listingSalesReceipts: {
|
||||
validation: [
|
||||
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']),
|
||||
],
|
||||
async handler(req, res) {
|
||||
const filter = {
|
||||
filter_roles: [],
|
||||
sort_order: 'asc',
|
||||
};
|
||||
if (filter.stringified_filter_roles) {
|
||||
filter.filter_roles = JSON.parse(filter.stringified_filter_roles);
|
||||
}
|
||||
const { SaleReceipt, Resource, View } = req.models;
|
||||
const resource = await Resource.tenant().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) => {
|
||||
dynamicListing.buildQuery()(builder);
|
||||
return builder;
|
||||
});
|
||||
|
||||
return res.status(200).send({
|
||||
sales_receipts: salesReceipts,
|
||||
...(viewMeta ? {
|
||||
customViewId: viewMeta.id,
|
||||
} : {}),
|
||||
});
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
21
server/src/http/controllers/Sales/index.js
Normal file
21
server/src/http/controllers/Sales/index.js
Normal file
@@ -0,0 +1,21 @@
|
||||
import express from 'express';
|
||||
import SalesEstimates from './SalesEstimates';
|
||||
import SalesReceipts from './SalesReceipt';
|
||||
import SalesInvoices from './SalesInvoices'
|
||||
import PaymentReceives from './PaymentReceives';
|
||||
|
||||
export default {
|
||||
/**
|
||||
* Router constructor.
|
||||
*/
|
||||
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());
|
||||
|
||||
return router;
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,9 @@ import Options from '@/http/controllers/Options';
|
||||
import Currencies from '@/http/controllers/Currencies';
|
||||
import Customers from '@/http/controllers/Customers';
|
||||
import Vendors from '@/http/controllers/Vendors';
|
||||
import Sales from '@/http/controllers/Sales'
|
||||
// import Suppliers from '@/http/controllers/Suppliers';
|
||||
// import Bills from '@/http/controllers/Bills';
|
||||
import Purchases from '@/http/controllers/Purchases';
|
||||
// import CurrencyAdjustment from './controllers/CurrencyAdjustment';
|
||||
import Resources from './controllers/Resources';
|
||||
import ExchangeRates from '@/http/controllers/ExchangeRates';
|
||||
@@ -56,11 +57,12 @@ export default (app) => {
|
||||
dashboard.use('/api/expenses', Expenses.router());
|
||||
dashboard.use('/api/financial_statements', FinancialStatements.router());
|
||||
dashboard.use('/api/options', Options.router());
|
||||
dashboard.use('/api/sales', Sales.router());
|
||||
// app.use('/api/budget_reports', BudgetReports.router());
|
||||
dashboard.use('/api/customers', Customers.router());
|
||||
dashboard.use('/api/vendors', Vendors.router());
|
||||
dashboard.use('/api/purchases', Purchases.router());
|
||||
// app.use('/api/suppliers', Suppliers.router());
|
||||
// app.use('/api/bills', Bills.router());
|
||||
// app.use('/api/budget', Budget.router());
|
||||
dashboard.use('/api/resources', Resources.router());
|
||||
dashboard.use('/api/exchange_rates', ExchangeRates.router());
|
||||
|
||||
@@ -46,7 +46,8 @@ export default async (req, res, next) => {
|
||||
req.organizationId = organizationId;
|
||||
req.models = {
|
||||
...Object.values(models).reduce((acc, model) => {
|
||||
if (typeof model.resource.default.requestModel === 'function' &&
|
||||
if (typeof model.resource.default !== 'undefined' &&
|
||||
typeof model.resource.default.requestModel === 'function' &&
|
||||
model.resource.default.requestModel() &&
|
||||
model.name !== 'TenantModel') {
|
||||
acc[model.name] = model.resource.default.bindKnex(knex);
|
||||
|
||||
13
server/src/http/middleware/validateMiddleware.js
Normal file
13
server/src/http/middleware/validateMiddleware.js
Normal file
@@ -0,0 +1,13 @@
|
||||
import { validationResult } from 'express-validator';
|
||||
|
||||
export default (req, res, next) => {
|
||||
const validationErrors = validationResult(req);
|
||||
|
||||
if (!validationErrors.isEmpty()) {
|
||||
return res.boom.badData(null, {
|
||||
code: 'validation_error',
|
||||
...validationErrors,
|
||||
});
|
||||
}
|
||||
next();
|
||||
}
|
||||
Reference in New Issue
Block a user