Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b77bda77f | ||
|
|
ba387e81f7 | ||
|
|
0414c090ea | ||
|
|
a52f3a933f | ||
|
|
d01eacf8d9 | ||
|
|
0da151faaa | ||
|
|
f93c8b46dc | ||
|
|
59c5c8979d | ||
|
|
74a07847a4 | ||
|
|
1740226294 | ||
|
|
1b20d1b073 | ||
|
|
ac7175d83b | ||
|
|
d72d8e60d6 | ||
|
|
de5920f910 | ||
|
|
475c4e9967 | ||
|
|
21eb88ef53 | ||
|
|
429159acf9 | ||
|
|
7eb84474a5 | ||
|
|
e42adcae63 |
@@ -96,6 +96,15 @@
|
||||
"contributions": [
|
||||
"bug"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "asenawritescode",
|
||||
"name": "Asena",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/67445192?v=4",
|
||||
"profile": "https://github.com/asenawritescode",
|
||||
"contributions": [
|
||||
"bug"
|
||||
]
|
||||
}
|
||||
],
|
||||
"contributorsPerLine": 7,
|
||||
|
||||
@@ -57,4 +57,10 @@ GOTENBERG_DOCS_URL=http://server:3000/public/
|
||||
|
||||
# Gotenberg API - (development)
|
||||
# GOTENBERG_URL=http://localhost:9000
|
||||
# GOTENBERG_DOCS_URL=http://host.docker.internal:3000/public/
|
||||
# GOTENBERG_DOCS_URL=http://host.docker.internal:3000/public/
|
||||
|
||||
# Exchange Rate Service
|
||||
EXCHANGE_RATE_SERVICE=open-exchange-rate
|
||||
|
||||
# Open Exchange Rate
|
||||
OPEN_EXCHANGE_RATE_APP_ID=
|
||||
13
CHANGELOG.md
13
CHANGELOG.md
@@ -2,6 +2,19 @@
|
||||
|
||||
All notable changes to Bigcapital server-side will be in this file.
|
||||
|
||||
## [0.13.3] - 22-01-2024
|
||||
|
||||
* hotfix(server): Unhandled thrown errors of services by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/329
|
||||
|
||||
## [0.13.2] - 21-01-2024
|
||||
|
||||
* feat: show customer / vendor balance. by @asenawritescode in https://github.com/bigcapitalhq/bigcapital/pull/311
|
||||
* feat: inventory valuation csv and xlsx export by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/308
|
||||
* feat: sales by items export csv & xlsx by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/310
|
||||
* fix(server): the invoice and payment receipt printing by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/315
|
||||
* fix: get cashflow transaction broken cause transaction type by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/318
|
||||
* fix: `AccountActivateAlert` import by @xprnio in https://github.com/bigcapitalhq/bigcapital/pull/322
|
||||
|
||||
## [0.13.1] - 15-01-2024
|
||||
|
||||
* feat(webapp): add approve/reject to action bar of estimate details dr… by @ANasouf in https://github.com/bigcapitalhq/bigcapital/pull/304
|
||||
|
||||
@@ -117,6 +117,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
|
||||
<td align="center" valign="top" width="14.28%"><a href="http://cschuijt.nl"><img src="https://avatars.githubusercontent.com/u/5460015?v=4?s=100" width="100px;" alt="Casper Schuijt"/><br /><sub><b>Casper Schuijt</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Acschuijt" title="Bug reports">🐛</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/ANasouf"><img src="https://avatars.githubusercontent.com/u/19536487?v=4?s=100" width="100px;" alt="ANasouf"/><br /><sub><b>ANasouf</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/commits?author=ANasouf" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://ragnarlaud.dev"><img src="https://avatars.githubusercontent.com/u/3042904?v=4?s=100" width="100px;" alt="Ragnar Laud"/><br /><sub><b>Ragnar Laud</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Axprnio" title="Bug reports">🐛</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/asenawritescode"><img src="https://avatars.githubusercontent.com/u/67445192?v=4?s=100" width="100px;" alt="Asena"/><br /><sub><b>Asena</b></sub></a><br /><a href="https://github.com/bigcapitalhq/bigcapital/issues?q=author%3Aasenawritescode" title="Bug reports">🐛</a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -1,19 +1,16 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { check, param, query } from 'express-validator';
|
||||
import { query, oneOf } from 'express-validator';
|
||||
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
|
||||
import BaseController from './BaseController';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import ExchangeRatesService from '@/services/ExchangeRates/ExchangeRatesService';
|
||||
import DynamicListingService from '@/services/DynamicListing/DynamicListService';
|
||||
import { EchangeRateErrors } from '@/lib/ExchangeRate/types';
|
||||
import { ExchangeRateApplication } from '@/services/ExchangeRates/ExchangeRateApplication';
|
||||
|
||||
@Service()
|
||||
export default class ExchangeRatesController extends BaseController {
|
||||
@Inject()
|
||||
exchangeRatesService: ExchangeRatesService;
|
||||
|
||||
@Inject()
|
||||
dynamicListService: DynamicListingService;
|
||||
private exchangeRatesApp: ExchangeRateApplication;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
@@ -22,164 +19,40 @@ export default class ExchangeRatesController extends BaseController {
|
||||
const router = Router();
|
||||
|
||||
router.get(
|
||||
'/',
|
||||
[...this.exchangeRatesListSchema],
|
||||
'/latest',
|
||||
[
|
||||
oneOf([
|
||||
query('to_currency').exists().isString().isISO4217(),
|
||||
query('from_currency').exists().isString().isISO4217(),
|
||||
]),
|
||||
],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.exchangeRates.bind(this)),
|
||||
this.dynamicListService.handlerErrorsToResponse,
|
||||
this.handleServiceError,
|
||||
);
|
||||
router.post(
|
||||
'/',
|
||||
[...this.exchangeRateDTOSchema],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.addExchangeRate.bind(this)),
|
||||
this.handleServiceError
|
||||
);
|
||||
router.post(
|
||||
'/:id',
|
||||
[...this.exchangeRateEditDTOSchema, ...this.exchangeRateIdSchema],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.editExchangeRate.bind(this)),
|
||||
this.handleServiceError
|
||||
);
|
||||
router.delete(
|
||||
'/:id',
|
||||
[...this.exchangeRateIdSchema],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.deleteExchangeRate.bind(this)),
|
||||
asyncMiddleware(this.latestExchangeRate.bind(this)),
|
||||
this.handleServiceError
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
get exchangeRatesListSchema() {
|
||||
return [
|
||||
query('page').optional().isNumeric().toInt(),
|
||||
query('page_size').optional().isNumeric().toInt(),
|
||||
|
||||
query('column_sort_by').optional(),
|
||||
query('sort_order').optional().isIn(['desc', 'asc']),
|
||||
];
|
||||
}
|
||||
|
||||
get exchangeRateDTOSchema() {
|
||||
return [
|
||||
check('exchange_rate').exists().isNumeric().toFloat(),
|
||||
check('currency_code').exists().trim().escape(),
|
||||
check('date').exists().isISO8601(),
|
||||
];
|
||||
}
|
||||
|
||||
get exchangeRateEditDTOSchema() {
|
||||
return [check('exchange_rate').exists().isNumeric().toFloat()];
|
||||
}
|
||||
|
||||
get exchangeRateIdSchema() {
|
||||
return [param('id').isNumeric().toInt()];
|
||||
}
|
||||
|
||||
get exchangeRatesIdsSchema() {
|
||||
return [
|
||||
query('ids').isArray({ min: 2 }),
|
||||
query('ids.*').isNumeric().toInt(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve exchange rates.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
async exchangeRates(req: Request, res: Response, next: NextFunction) {
|
||||
private async latestExchangeRate(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
const { tenantId } = req;
|
||||
const filter = {
|
||||
page: 1,
|
||||
pageSize: 12,
|
||||
filterRoles: [],
|
||||
columnSortBy: 'created_at',
|
||||
sortOrder: 'asc',
|
||||
...this.matchedQueryData(req),
|
||||
};
|
||||
if (filter.stringifiedFilterRoles) {
|
||||
filter.filterRoles = JSON.parse(filter.stringifiedFilterRoles);
|
||||
}
|
||||
try {
|
||||
const exchangeRates = await this.exchangeRatesService.listExchangeRates(
|
||||
tenantId,
|
||||
filter
|
||||
);
|
||||
return res.status(200).send({ exchange_rates: exchangeRates });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new exchange rate on the given date.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
async addExchangeRate(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const exchangeRateDTO = this.matchedBodyData(req);
|
||||
const exchangeRateQuery = this.matchedQueryData(req);
|
||||
|
||||
try {
|
||||
const exchangeRate = await this.exchangeRatesService.newExchangeRate(
|
||||
const exchangeRate = await this.exchangeRatesApp.latest(
|
||||
tenantId,
|
||||
exchangeRateDTO
|
||||
exchangeRateQuery
|
||||
);
|
||||
return res.status(200).send({ id: exchangeRate.id });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit the given exchange rate.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
async editExchangeRate(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const { id: exchangeRateId } = req.params;
|
||||
const exchangeRateDTO = this.matchedBodyData(req);
|
||||
|
||||
try {
|
||||
const exchangeRate = await this.exchangeRatesService.editExchangeRate(
|
||||
tenantId,
|
||||
exchangeRateId,
|
||||
exchangeRateDTO
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
id: exchangeRateId,
|
||||
message: 'The exchange rate has been edited successfully.',
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the given exchange rate from the storage.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
async deleteExchangeRate(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const { id: exchangeRateId } = req.params;
|
||||
|
||||
try {
|
||||
await this.exchangeRatesService.deleteExchangeRate(
|
||||
tenantId,
|
||||
exchangeRateId
|
||||
);
|
||||
return res.status(200).send({ id: exchangeRateId });
|
||||
return res.status(200).send(exchangeRate);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -192,26 +65,56 @@ export default class ExchangeRatesController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
handleServiceError(
|
||||
private handleServiceError(
|
||||
error: Error,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
if (error instanceof ServiceError) {
|
||||
if (error.errorType === 'EXCHANGE_RATE_NOT_FOUND') {
|
||||
return res.status(404).send({
|
||||
errors: [{ type: 'EXCHANGE.RATE.NOT.FOUND', code: 200 }],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'NOT_FOUND_EXCHANGE_RATES') {
|
||||
if (EchangeRateErrors.EX_RATE_INVALID_BASE_CURRENCY === error.errorType) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'EXCHANGE.RATES.IS.NOT.FOUND', code: 100 }],
|
||||
errors: [
|
||||
{
|
||||
type: EchangeRateErrors.EX_RATE_INVALID_BASE_CURRENCY,
|
||||
code: 100,
|
||||
message: 'The given base currency is invalid.',
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
if (error.errorType === 'EXCHANGE_RATE_PERIOD_EXISTS') {
|
||||
} else if (
|
||||
EchangeRateErrors.EX_RATE_SERVICE_NOT_ALLOWED === error.errorType
|
||||
) {
|
||||
return res.status(400).send({
|
||||
errors: [{ type: 'EXCHANGE.RATE.PERIOD.EXISTS', code: 300 }],
|
||||
errors: [
|
||||
{
|
||||
type: EchangeRateErrors.EX_RATE_SERVICE_NOT_ALLOWED,
|
||||
code: 200,
|
||||
message: 'The service is not allowed',
|
||||
},
|
||||
],
|
||||
});
|
||||
} else if (
|
||||
EchangeRateErrors.EX_RATE_SERVICE_API_KEY_REQUIRED === error.errorType
|
||||
) {
|
||||
return res.status(400).send({
|
||||
errors: [
|
||||
{
|
||||
type: EchangeRateErrors.EX_RATE_SERVICE_API_KEY_REQUIRED,
|
||||
code: 300,
|
||||
message: 'The API key is required',
|
||||
},
|
||||
],
|
||||
});
|
||||
} else if (EchangeRateErrors.EX_RATE_LIMIT_EXCEEDED === error.errorType) {
|
||||
return res.status(400).send({
|
||||
errors: [
|
||||
{
|
||||
type: EchangeRateErrors.EX_RATE_LIMIT_EXCEEDED,
|
||||
code: 400,
|
||||
message: 'The API rate limit has been exceeded',
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { query, ValidationChain } from 'express-validator';
|
||||
import moment from 'moment';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
|
||||
import BaseFinancialReportController from './BaseFinancialReportController';
|
||||
import PurchasesByItemsService from '@/services/FinancialStatements/PurchasesByItems/PurchasesByItemsService';
|
||||
import { PurchasesByItemsService } from '@/services/FinancialStatements/PurchasesByItems/PurchasesByItemsService';
|
||||
import { AbilitySubject, ReportsAction } from '@/interfaces';
|
||||
import CheckPolicies from '@/api/middleware/CheckPolicies';
|
||||
import { ACCEPT_TYPE } from '@/interfaces/Http';
|
||||
import { PurcahsesByItemsApplication } from '@/services/FinancialStatements/PurchasesByItems/PurchasesByItemsApplication';
|
||||
|
||||
@Service()
|
||||
export default class PurchasesByItemReportController extends BaseFinancialReportController {
|
||||
@Inject()
|
||||
purchasesByItemsService: PurchasesByItemsService;
|
||||
private purchasesByItemsApp: PurcahsesByItemsApplication;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
@@ -63,20 +64,47 @@ export default class PurchasesByItemReportController extends BaseFinancialReport
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
*/
|
||||
async purchasesByItems(req: Request, res: Response, next: NextFunction) {
|
||||
public async purchasesByItems(req: Request, res: Response) {
|
||||
const { tenantId } = req;
|
||||
const filter = this.matchedQueryData(req);
|
||||
|
||||
try {
|
||||
const { data, query, meta } =
|
||||
await this.purchasesByItemsService.purchasesByItems(tenantId, filter);
|
||||
return res.status(200).send({
|
||||
meta: this.transfromToResponse(meta),
|
||||
data: this.transfromToResponse(data),
|
||||
query: this.transfromToResponse(query),
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
const accept = this.accepts(req);
|
||||
|
||||
const acceptType = accept.types([
|
||||
ACCEPT_TYPE.APPLICATION_JSON,
|
||||
ACCEPT_TYPE.APPLICATION_JSON_TABLE,
|
||||
ACCEPT_TYPE.APPLICATION_XLSX,
|
||||
ACCEPT_TYPE.APPLICATION_CSV,
|
||||
]);
|
||||
|
||||
// JSON table response format.
|
||||
if (ACCEPT_TYPE.APPLICATION_JSON_TABLE === acceptType) {
|
||||
const table = await this.purchasesByItemsApp.table(tenantId, filter);
|
||||
|
||||
return res.status(200).send(table);
|
||||
// CSV response format.
|
||||
} else if (ACCEPT_TYPE.APPLICATION_CSV === acceptType) {
|
||||
const buffer = await this.purchasesByItemsApp.csv(tenantId, filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
|
||||
return res.send(buffer);
|
||||
// Xlsx response format.
|
||||
} else if (ACCEPT_TYPE.APPLICATION_XLSX === acceptType) {
|
||||
const buffer = await this.purchasesByItemsApp.xlsx(tenantId, filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
res.setHeader(
|
||||
'Content-Type',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
);
|
||||
return res.send(buffer);
|
||||
// Json response format.
|
||||
} else {
|
||||
const sheet = await this.purchasesByItemsApp.sheet(tenantId, filter);
|
||||
|
||||
return res.status(200).send(sheet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -303,7 +303,7 @@ export default class BillsController extends BaseController {
|
||||
try {
|
||||
const bill = await this.billsApplication.getBill(tenantId, billId);
|
||||
|
||||
return res.status(200).send(this.transfromToResponse({ bill }));
|
||||
return res.status(200).send({ bill });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -348,14 +348,11 @@ export default class BillsController extends BaseController {
|
||||
};
|
||||
|
||||
try {
|
||||
const { bills, pagination, filterMeta } =
|
||||
await this.billsApplication.getBills(tenantId, filter);
|
||||
|
||||
return res.status(200).send({
|
||||
bills: this.transfromToResponse(bills),
|
||||
pagination: this.transfromToResponse(pagination),
|
||||
filter_meta: this.transfromToResponse(filterMeta),
|
||||
});
|
||||
const billsWithPagination = await this.billsApplication.getBills(
|
||||
tenantId,
|
||||
filter
|
||||
);
|
||||
return res.status(200).send(billsWithPagination);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
|
||||
@@ -158,15 +158,11 @@ export default class BillsPayments extends BaseController {
|
||||
const { tenantId } = req;
|
||||
const { vendorId } = this.matchedQueryData(req);
|
||||
|
||||
try {
|
||||
const entries = await this.billPaymentsPages.getNewPageEntries(
|
||||
tenantId,
|
||||
vendorId
|
||||
);
|
||||
return res.status(200).send({
|
||||
entries: this.transfromToResponse(entries),
|
||||
});
|
||||
} catch (error) {}
|
||||
const entries = await this.billPaymentsPages.getNewPageEntries(
|
||||
tenantId,
|
||||
vendorId
|
||||
);
|
||||
return res.status(200).send({ entries });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -183,16 +179,12 @@ export default class BillsPayments extends BaseController {
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
|
||||
try {
|
||||
const { billPayment, entries } =
|
||||
const billPaymentsWithEditEntries =
|
||||
await this.billPaymentsPages.getBillPaymentEditPage(
|
||||
tenantId,
|
||||
paymentReceiveId
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
bill_payment: this.transfromToResponse(billPayment),
|
||||
entries: this.transfromToResponse(entries),
|
||||
});
|
||||
return res.status(200).send(billPaymentsWithEditEntries);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -304,9 +296,7 @@ export default class BillsPayments extends BaseController {
|
||||
tenantId,
|
||||
billPaymentId
|
||||
);
|
||||
return res.status(200).send({
|
||||
bill_payment: this.transfromToResponse(billPayment),
|
||||
});
|
||||
return res.status(200).send({ billPayment });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -359,17 +349,12 @@ export default class BillsPayments extends BaseController {
|
||||
};
|
||||
|
||||
try {
|
||||
const { billPayments, pagination, filterMeta } =
|
||||
const billPaymentsWithPagination =
|
||||
await this.billPaymentsApplication.getBillPayments(
|
||||
tenantId,
|
||||
billPaymentsFilter
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
bill_payments: this.transfromToResponse(billPayments),
|
||||
pagination: this.transfromToResponse(pagination),
|
||||
filter_meta: this.transfromToResponse(filterMeta),
|
||||
});
|
||||
return res.status(200).send(billPaymentsWithPagination);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
|
||||
@@ -320,20 +320,19 @@ export default class VendorCreditController extends BaseController {
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) => {
|
||||
const { id: billId } = req.params;
|
||||
const { id: vendorCreditId } = req.params;
|
||||
const { tenantId, user } = req;
|
||||
const vendorCreditEditDTO: IVendorCreditEditDTO = this.matchedBodyData(req);
|
||||
|
||||
try {
|
||||
await this.editVendorCreditService.editVendorCredit(
|
||||
tenantId,
|
||||
billId,
|
||||
vendorCreditEditDTO,
|
||||
user
|
||||
vendorCreditId,
|
||||
vendorCreditEditDTO
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
id: billId,
|
||||
id: vendorCreditId,
|
||||
message: 'The vendor credit has been edited successfully.',
|
||||
});
|
||||
} catch (error) {
|
||||
|
||||
@@ -26,6 +26,7 @@ import GetCreditNoteAssociatedInvoicesToApply from '@/services/CreditNotes/GetCr
|
||||
import GetCreditNoteAssociatedAppliedInvoices from '@/services/CreditNotes/GetCreditNoteAssociatedAppliedInvoices';
|
||||
import GetRefundCreditTransaction from '@/services/CreditNotes/GetRefundCreditNoteTransaction';
|
||||
import GetCreditNotePdf from '../../../services/CreditNotes/GetCreditNotePdf';
|
||||
import { ACCEPT_TYPE } from '@/interfaces/Http';
|
||||
/**
|
||||
* Credit notes controller.
|
||||
* @service
|
||||
@@ -293,7 +294,7 @@ export default class PaymentReceivesController extends BaseController {
|
||||
return [
|
||||
check('from_account_id').exists().isNumeric().toInt(),
|
||||
check('description').optional(),
|
||||
|
||||
|
||||
check('amount').exists().isNumeric().toFloat(),
|
||||
check('exchange_rate').optional().isFloat({ gt: 0 }).toFloat(),
|
||||
|
||||
@@ -438,7 +439,7 @@ export default class PaymentReceivesController extends BaseController {
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve the payment receive details.
|
||||
* Retrieve the credit note details.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
@@ -451,38 +452,28 @@ export default class PaymentReceivesController extends BaseController {
|
||||
const { tenantId } = req;
|
||||
const { id: creditNoteId } = req.params;
|
||||
|
||||
try {
|
||||
const accept = this.accepts(req);
|
||||
|
||||
const acceptType = accept.types([
|
||||
ACCEPT_TYPE.APPLICATION_JSON,
|
||||
ACCEPT_TYPE.APPLICATION_PDF,
|
||||
]);
|
||||
if (ACCEPT_TYPE.APPLICATION_PDF === acceptType) {
|
||||
const pdfContent = await this.creditNotePdf.getCreditNotePdf(
|
||||
tenantId,
|
||||
creditNoteId
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
} else {
|
||||
const creditNote = await this.getCreditNoteService.getCreditNote(
|
||||
tenantId,
|
||||
creditNoteId
|
||||
);
|
||||
const ACCEPT_TYPE = {
|
||||
APPLICATION_PDF: 'application/pdf',
|
||||
APPLICATION_JSON: 'application/json',
|
||||
};
|
||||
// Response formatter.
|
||||
res.format({
|
||||
// Json content type.
|
||||
[ACCEPT_TYPE.APPLICATION_JSON]: () => {
|
||||
return res
|
||||
.status(200)
|
||||
.send({ credit_note: this.transfromToResponse(creditNote) });
|
||||
},
|
||||
// Pdf content type.
|
||||
[ACCEPT_TYPE.APPLICATION_PDF]: async () => {
|
||||
const pdfContent = await this.creditNotePdf.getCreditNotePdf(
|
||||
tenantId,
|
||||
creditNote
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
return res.status(200).send({ creditNote });
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import DynamicListingService from '@/services/DynamicListing/DynamicListService'
|
||||
import { PaymentReceivesApplication } from '@/services/Sales/PaymentReceives/PaymentReceivesApplication';
|
||||
import CheckPolicies from '@/api/middleware/CheckPolicies';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import { ACCEPT_TYPE } from '@/interfaces/Http';
|
||||
|
||||
@Service()
|
||||
export default class PaymentReceivesController extends BaseController {
|
||||
@@ -348,17 +349,12 @@ export default class PaymentReceivesController extends BaseController {
|
||||
};
|
||||
|
||||
try {
|
||||
const { paymentReceives, pagination, filterMeta } =
|
||||
const paymentsReceivedWithPagination =
|
||||
await this.paymentReceiveApplication.getPaymentReceives(
|
||||
tenantId,
|
||||
filter
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
payment_receives: this.transfromToResponse(paymentReceives),
|
||||
pagination: this.transfromToResponse(pagination),
|
||||
filter_meta: this.transfromToResponse(filterMeta),
|
||||
});
|
||||
return res.status(200).send(paymentsReceivedWithPagination);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -435,37 +431,34 @@ export default class PaymentReceivesController extends BaseController {
|
||||
const { tenantId } = req;
|
||||
const { id: paymentReceiveId } = req.params;
|
||||
|
||||
try {
|
||||
const ACCEPT_TYPE = {
|
||||
APPLICATION_PDF: 'application/pdf',
|
||||
APPLICATION_JSON: 'application/json',
|
||||
};
|
||||
res.format({
|
||||
[ACCEPT_TYPE.APPLICATION_JSON]: async () => {
|
||||
const paymentReceive =
|
||||
await this.paymentReceiveApplication.getPaymentReceive(
|
||||
tenantId,
|
||||
paymentReceiveId
|
||||
);
|
||||
return res.status(200).send({
|
||||
payment_receive: paymentReceive,
|
||||
});
|
||||
},
|
||||
[ACCEPT_TYPE.APPLICATION_PDF]: async () => {
|
||||
const pdfContent =
|
||||
await this.paymentReceiveApplication.getPaymentReceivePdf(
|
||||
tenantId,
|
||||
paymentReceiveId
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
},
|
||||
const accept = this.accepts(req);
|
||||
|
||||
const acceptType = accept.types([
|
||||
ACCEPT_TYPE.APPLICATION_JSON,
|
||||
ACCEPT_TYPE.APPLICATION_PDF,
|
||||
]);
|
||||
// Response in pdf format.
|
||||
if (ACCEPT_TYPE.APPLICATION_PDF === acceptType) {
|
||||
const pdfContent =
|
||||
await this.paymentReceiveApplication.getPaymentReceivePdf(
|
||||
tenantId,
|
||||
paymentReceiveId
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
// Response in json format.
|
||||
} else {
|
||||
const paymentReceive =
|
||||
await this.paymentReceiveApplication.getPaymentReceive(
|
||||
tenantId,
|
||||
paymentReceiveId
|
||||
);
|
||||
return res.status(200).send({
|
||||
payment_receive: paymentReceive,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,7 +492,7 @@ export default class PaymentReceivesController extends BaseController {
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* Retrieves the sms details of the given payment receive.
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
@@ -588,10 +581,10 @@ export default class PaymentReceivesController extends BaseController {
|
||||
|
||||
/**
|
||||
* Handles service errors.
|
||||
* @param error
|
||||
* @param req
|
||||
* @param res
|
||||
* @param next
|
||||
* @param {Error} error
|
||||
* @param {Request} req
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
private handleServiceErrors(
|
||||
error: Error,
|
||||
|
||||
@@ -334,7 +334,6 @@ export default class SalesEstimatesController extends BaseController {
|
||||
tenantId,
|
||||
estimateId
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
id: estimateId,
|
||||
message: 'The sale estimate has been approved successfully.',
|
||||
@@ -363,7 +362,6 @@ export default class SalesEstimatesController extends BaseController {
|
||||
tenantId,
|
||||
estimateId
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
id: estimateId,
|
||||
message: 'The sale estimate has been rejected successfully.',
|
||||
@@ -383,33 +381,30 @@ export default class SalesEstimatesController extends BaseController {
|
||||
const { id: estimateId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
try {
|
||||
// Response formatter.
|
||||
res.format({
|
||||
// JSON content type.
|
||||
[ACCEPT_TYPE.APPLICATION_JSON]: async () => {
|
||||
const estimate = await this.saleEstimatesApplication.getSaleEstimate(
|
||||
tenantId,
|
||||
estimateId
|
||||
);
|
||||
return res.status(200).send({ estimate });
|
||||
},
|
||||
// PDF content type.
|
||||
[ACCEPT_TYPE.APPLICATION_PDF]: async () => {
|
||||
const pdfContent =
|
||||
await this.saleEstimatesApplication.getSaleEstimatePdf(
|
||||
tenantId,
|
||||
estimateId
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
},
|
||||
const accept = this.accepts(req);
|
||||
|
||||
const acceptType = accept.types([
|
||||
ACCEPT_TYPE.APPLICATION_JSON,
|
||||
ACCEPT_TYPE.APPLICATION_PDF,
|
||||
]);
|
||||
// Retrieves estimate in pdf format.
|
||||
if (ACCEPT_TYPE.APPLICATION_PDF == acceptType) {
|
||||
const pdfContent = await this.saleEstimatesApplication.getSaleEstimatePdf(
|
||||
tenantId,
|
||||
estimateId
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
res.send(pdfContent);
|
||||
// Retrieves estimates in json format.
|
||||
} else {
|
||||
const estimate = await this.saleEstimatesApplication.getSaleEstimate(
|
||||
tenantId,
|
||||
estimateId
|
||||
);
|
||||
return res.status(200).send({ estimate });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -427,22 +422,11 @@ export default class SalesEstimatesController extends BaseController {
|
||||
pageSize: 12,
|
||||
...this.matchedQueryData(req),
|
||||
};
|
||||
|
||||
try {
|
||||
const { salesEstimates, pagination, filterMeta } =
|
||||
const salesEstimatesWithPagination =
|
||||
await this.saleEstimatesApplication.getSaleEstimates(tenantId, filter);
|
||||
|
||||
res.format({
|
||||
[ACCEPT_TYPE.APPLICATION_JSON]: () => {
|
||||
return res.status(200).send(
|
||||
this.transfromToResponse({
|
||||
salesEstimates,
|
||||
pagination,
|
||||
filterMeta,
|
||||
})
|
||||
);
|
||||
},
|
||||
});
|
||||
return res.status(200).send(salesEstimatesWithPagination);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
|
||||
@@ -14,11 +14,8 @@ import {
|
||||
} from '@/interfaces';
|
||||
import CheckPolicies from '@/api/middleware/CheckPolicies';
|
||||
import { SaleInvoiceApplication } from '@/services/Sales/Invoices/SaleInvoicesApplication';
|
||||
import { ACCEPT_TYPE } from '@/interfaces/Http';
|
||||
|
||||
const ACCEPT_TYPE = {
|
||||
APPLICATION_PDF: 'application/pdf',
|
||||
APPLICATION_JSON: 'application/json',
|
||||
};
|
||||
@Service()
|
||||
export default class SaleInvoicesController extends BaseController {
|
||||
@Inject()
|
||||
@@ -403,7 +400,6 @@ export default class SaleInvoicesController extends BaseController {
|
||||
saleInvoiceId,
|
||||
user
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
id: saleInvoiceId,
|
||||
message: 'The sale invoice has been deleted successfully.',
|
||||
@@ -422,30 +418,32 @@ export default class SaleInvoicesController extends BaseController {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const { tenantId, user } = req;
|
||||
|
||||
// Response formatter.
|
||||
return res.format({
|
||||
// JSON content type.
|
||||
[ACCEPT_TYPE.APPLICATION_JSON]: async () => {
|
||||
const saleInvoice = await this.saleInvoiceApplication.getSaleInvoice(
|
||||
tenantId,
|
||||
saleInvoiceId,
|
||||
user
|
||||
);
|
||||
return res.status(200).send(this.transfromToResponse({ saleInvoice }));
|
||||
},
|
||||
// PDF content type.
|
||||
[ACCEPT_TYPE.APPLICATION_PDF]: async () => {
|
||||
const pdfContent = await this.saleInvoiceApplication.saleInvoicePdf(
|
||||
tenantId,
|
||||
saleInvoiceId
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
},
|
||||
});
|
||||
const accept = this.accepts(req);
|
||||
|
||||
const acceptType = accept.types([
|
||||
ACCEPT_TYPE.APPLICATION_JSON,
|
||||
ACCEPT_TYPE.APPLICATION_PDF,
|
||||
]);
|
||||
// Retrieves invoice in pdf format.
|
||||
if (ACCEPT_TYPE.APPLICATION_PDF == acceptType) {
|
||||
const pdfContent = await this.saleInvoiceApplication.saleInvoicePdf(
|
||||
tenantId,
|
||||
saleInvoiceId
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
// Retrieves invoice in json format.
|
||||
} else {
|
||||
const saleInvoice = await this.saleInvoiceApplication.getSaleInvoice(
|
||||
tenantId,
|
||||
saleInvoiceId,
|
||||
user
|
||||
);
|
||||
return res.status(200).send({ saleInvoice });
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Retrieve paginated sales invoices with custom view metadata.
|
||||
@@ -467,14 +465,10 @@ export default class SaleInvoicesController extends BaseController {
|
||||
...this.matchedQueryData(req),
|
||||
};
|
||||
try {
|
||||
const { salesInvoices, filterMeta, pagination } =
|
||||
const salesInvoicesWithPagination =
|
||||
await this.saleInvoiceApplication.getSaleInvoices(tenantId, filter);
|
||||
|
||||
return res.status(200).send({
|
||||
sales_invoices: this.transfromToResponse(salesInvoices),
|
||||
pagination: this.transfromToResponse(pagination),
|
||||
filter_meta: this.transfromToResponse(filterMeta),
|
||||
});
|
||||
return res.status(200).send(salesInvoicesWithPagination);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -501,9 +495,7 @@ export default class SaleInvoicesController extends BaseController {
|
||||
tenantId,
|
||||
customerId
|
||||
);
|
||||
return res.status(200).send({
|
||||
sales_invoices: this.transfromToResponse(salesInvoices),
|
||||
});
|
||||
return res.status(200).send({ salesInvoices });
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -531,7 +523,6 @@ export default class SaleInvoicesController extends BaseController {
|
||||
invoiceId,
|
||||
writeoffDTO
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
id: saleInvoice.id,
|
||||
message: 'The given sale invoice has been written-off successfully.',
|
||||
|
||||
@@ -3,12 +3,17 @@ import { body, check, param, query } from 'express-validator';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
|
||||
import BaseController from '../BaseController';
|
||||
import { ISaleReceiptDTO, SaleReceiptMailOpts, SaleReceiptMailOptsDTO } from '@/interfaces/SaleReceipt';
|
||||
import {
|
||||
ISaleReceiptDTO,
|
||||
SaleReceiptMailOpts,
|
||||
SaleReceiptMailOptsDTO,
|
||||
} from '@/interfaces/SaleReceipt';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import DynamicListingService from '@/services/DynamicListing/DynamicListService';
|
||||
import CheckPolicies from '@/api/middleware/CheckPolicies';
|
||||
import { AbilitySubject, SaleReceiptAction } from '@/interfaces';
|
||||
import { SaleReceiptApplication } from '@/services/Sales/Receipts/SaleReceiptApplication';
|
||||
import { ACCEPT_TYPE } from '@/interfaces/Http';
|
||||
|
||||
@Service()
|
||||
export default class SalesReceiptsController extends BaseController {
|
||||
@@ -62,9 +67,7 @@ export default class SalesReceiptsController extends BaseController {
|
||||
);
|
||||
router.get(
|
||||
'/:id/mail',
|
||||
[
|
||||
...this.specificReceiptValidationSchema,
|
||||
],
|
||||
[...this.specificReceiptValidationSchema],
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.getSaleReceiptMail.bind(this)),
|
||||
this.handleServiceErrors
|
||||
@@ -228,7 +231,6 @@ export default class SalesReceiptsController extends BaseController {
|
||||
tenantId,
|
||||
saleReceiptId
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
id: saleReceiptId,
|
||||
message: 'Sale receipt has been deleted successfully.',
|
||||
@@ -317,15 +319,10 @@ export default class SalesReceiptsController extends BaseController {
|
||||
...this.matchedQueryData(req),
|
||||
};
|
||||
try {
|
||||
const { data, pagination, filterMeta } =
|
||||
const salesReceiptsWithPagination =
|
||||
await this.saleReceiptsApplication.getSaleReceipts(tenantId, filter);
|
||||
|
||||
const response = this.transfromToResponse({
|
||||
data,
|
||||
pagination,
|
||||
filterMeta,
|
||||
});
|
||||
return res.status(200).send(response);
|
||||
return res.status(200).send(salesReceiptsWithPagination);
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
@@ -337,34 +334,34 @@ export default class SalesReceiptsController extends BaseController {
|
||||
* @param {Response} res
|
||||
* @param {NextFunction} next
|
||||
*/
|
||||
public async getSaleReceipt(req: Request, res: Response, next: NextFunction) {
|
||||
public async getSaleReceipt(req: Request, res: Response) {
|
||||
const { id: saleReceiptId } = req.params;
|
||||
const { tenantId } = req;
|
||||
|
||||
try {
|
||||
res.format({
|
||||
'application/json': async () => {
|
||||
const saleReceipt = await this.saleReceiptsApplication.getSaleReceipt(
|
||||
tenantId,
|
||||
saleReceiptId
|
||||
);
|
||||
return res.status(200).send({ saleReceipt });
|
||||
},
|
||||
'application/pdf': async () => {
|
||||
const pdfContent =
|
||||
await this.saleReceiptsApplication.getSaleReceiptPdf(
|
||||
tenantId,
|
||||
saleReceiptId
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
},
|
||||
const accept = this.accepts(req);
|
||||
|
||||
const acceptType = accept.types([
|
||||
ACCEPT_TYPE.APPLICATION_JSON,
|
||||
ACCEPT_TYPE.APPLICATION_PDF,
|
||||
]);
|
||||
// Retrieves receipt in pdf format.
|
||||
if (ACCEPT_TYPE.APPLICATION_PDF == acceptType) {
|
||||
const pdfContent = await this.saleReceiptsApplication.getSaleReceiptPdf(
|
||||
tenantId,
|
||||
saleReceiptId
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
res.send(pdfContent);
|
||||
// Retrieves receipt in json format.
|
||||
} else {
|
||||
const saleReceipt = await this.saleReceiptsApplication.getSaleReceipt(
|
||||
tenantId,
|
||||
saleReceiptId
|
||||
);
|
||||
return res.status(200).send({ saleReceipt });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -169,4 +169,14 @@ module.exports = {
|
||||
* to application detarmines to upgrade.
|
||||
*/
|
||||
databaseBatch: 4,
|
||||
|
||||
/**
|
||||
* Exchange rate.
|
||||
*/
|
||||
exchangeRate: {
|
||||
service: 'open-exchange-rate',
|
||||
openExchangeRate: {
|
||||
appId: process.env.OPEN_EXCHANGE_RATE_APP_ID,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import {
|
||||
IAgingPeriod,
|
||||
IAgingPeriodTotal,
|
||||
IAgingAmount,
|
||||
IAgingSummaryQuery,
|
||||
IAgingSummaryTotal,
|
||||
IAgingSummaryContact,
|
||||
IAgingSummaryData,
|
||||
} from './AgingReport';
|
||||
import { INumberFormatQuery } from './FinancialStatements';
|
||||
import { IFinancialTable } from './Table';
|
||||
|
||||
export interface IAPAgingSummaryQuery extends IAgingSummaryQuery {
|
||||
|
||||
@@ -1,36 +1,10 @@
|
||||
import { IFilterRole } from './DynamicFilter';
|
||||
export interface ExchangeRateLatestDTO {
|
||||
toCurrency: string;
|
||||
fromCurrency: string;
|
||||
}
|
||||
|
||||
export interface IExchangeRate {
|
||||
id: number,
|
||||
currencyCode: string,
|
||||
exchangeRate: number,
|
||||
date: Date,
|
||||
createdAt: Date,
|
||||
updatedAt: Date,
|
||||
};
|
||||
|
||||
export interface IExchangeRateDTO {
|
||||
currencyCode: string,
|
||||
exchangeRate: number,
|
||||
date: Date,
|
||||
};
|
||||
|
||||
export interface IExchangeRateEditDTO {
|
||||
exchangeRate: number,
|
||||
};
|
||||
|
||||
export interface IExchangeRateFilter {
|
||||
page: number,
|
||||
pageSize: number,
|
||||
filterRoles?: IFilterRole[];
|
||||
columnSortBy: string;
|
||||
sortOrder: string;
|
||||
};
|
||||
|
||||
export interface IExchangeRatesService {
|
||||
newExchangeRate(tenantId: number, exchangeRateDTO: IExchangeRateDTO): Promise<IExchangeRate>;
|
||||
editExchangeRate(tenantId: number, exchangeRateId: number, editExRateDTO: IExchangeRateEditDTO): Promise<void>;
|
||||
|
||||
deleteExchangeRate(tenantId: number, exchangeRateId: number): Promise<void>;
|
||||
listExchangeRates(tenantId: number, exchangeRateFilter: IExchangeRateFilter): Promise<void>;
|
||||
};
|
||||
export interface EchangeRateLatestPOJO {
|
||||
baseCurrency: string;
|
||||
toCurrency: string;
|
||||
exchangeRate: number;
|
||||
}
|
||||
|
||||
54
packages/server/src/interfaces/PurchasesByItemsSheet.ts
Normal file
54
packages/server/src/interfaces/PurchasesByItemsSheet.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { INumberFormatQuery } from './FinancialStatements';
|
||||
import { IFinancialTable } from './Table';
|
||||
|
||||
export interface IPurchasesByItemsReportQuery {
|
||||
fromDate: Date | string;
|
||||
toDate: Date | string;
|
||||
itemsIds: number[];
|
||||
numberFormat: INumberFormatQuery;
|
||||
noneTransactions: boolean;
|
||||
onlyActive: boolean;
|
||||
}
|
||||
|
||||
export interface IPurchasesByItemsSheetMeta {
|
||||
organizationName: string;
|
||||
baseCurrency: string;
|
||||
}
|
||||
|
||||
export interface IPurchasesByItemsItem {
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
quantitySold: number;
|
||||
soldCost: number;
|
||||
averageSellPrice: number;
|
||||
|
||||
quantitySoldFormatted: string;
|
||||
soldCostFormatted: string;
|
||||
averageSellPriceFormatted: string;
|
||||
currencyCode: string;
|
||||
}
|
||||
|
||||
export interface IPurchasesByItemsTotal {
|
||||
quantitySold: number;
|
||||
soldCost: number;
|
||||
quantitySoldFormatted: string;
|
||||
soldCostFormatted: string;
|
||||
currencyCode: string;
|
||||
}
|
||||
|
||||
export type IPurchasesByItemsSheetData = {
|
||||
items: IPurchasesByItemsItem[];
|
||||
total: IPurchasesByItemsTotal;
|
||||
};
|
||||
|
||||
export interface IPurchasesByItemsSheet {
|
||||
data: IPurchasesByItemsSheetData;
|
||||
query: IPurchasesByItemsReportQuery;
|
||||
meta: IPurchasesByItemsSheetMeta;
|
||||
}
|
||||
|
||||
export interface IPurchasesByItemsTable extends IFinancialTable {
|
||||
query: IPurchasesByItemsReportQuery;
|
||||
meta: IPurchasesByItemsSheetMeta;
|
||||
}
|
||||
45
packages/server/src/lib/ExchangeRate/ExchangeRate.ts
Normal file
45
packages/server/src/lib/ExchangeRate/ExchangeRate.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { OpenExchangeRate } from './OpenExchangeRate';
|
||||
import { ExchangeRateServiceType, IExchangeRateService } from './types';
|
||||
|
||||
export class ExchangeRate {
|
||||
private exchangeRateService: IExchangeRateService;
|
||||
private exchangeRateServiceType: ExchangeRateServiceType;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
* @param {ExchangeRateServiceType} service
|
||||
*/
|
||||
constructor(service: ExchangeRateServiceType) {
|
||||
this.exchangeRateServiceType = service;
|
||||
this.initService();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the exchange rate service based on the service type.
|
||||
*/
|
||||
private initService() {
|
||||
if (
|
||||
this.exchangeRateServiceType === ExchangeRateServiceType.OpenExchangeRate
|
||||
) {
|
||||
this.setExchangeRateService(new OpenExchangeRate());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the exchange rate service.
|
||||
* @param {IExchangeRateService} service
|
||||
*/
|
||||
private setExchangeRateService(service: IExchangeRateService) {
|
||||
this.exchangeRateService = service;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the latest exchange rate.
|
||||
* @param {string} baseCurrency
|
||||
* @param {string} toCurrency
|
||||
* @returns {number}
|
||||
*/
|
||||
public latest(baseCurrency: string, toCurrency: string): Promise<number> {
|
||||
return this.exchangeRateService.latest(baseCurrency, toCurrency);
|
||||
}
|
||||
}
|
||||
81
packages/server/src/lib/ExchangeRate/OpenExchangeRate.ts
Normal file
81
packages/server/src/lib/ExchangeRate/OpenExchangeRate.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import Axios, { AxiosError } from 'axios';
|
||||
import {
|
||||
EchangeRateErrors,
|
||||
IExchangeRateService,
|
||||
OPEN_EXCHANGE_RATE_LATEST_URL,
|
||||
} from './types';
|
||||
import config from '@/config';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
|
||||
export class OpenExchangeRate implements IExchangeRateService {
|
||||
/**
|
||||
* Gets the latest exchange rate.
|
||||
* @param {string} baseCurrency
|
||||
* @param {string} toCurrency
|
||||
* @returns {Promise<number}
|
||||
*/
|
||||
public async latest(
|
||||
baseCurrency: string,
|
||||
toCurrency: string
|
||||
): Promise<number> {
|
||||
// Vaclidates the Open Exchange Rate api id early.
|
||||
this.validateApiIdExistance();
|
||||
|
||||
try {
|
||||
const result = await Axios.get(OPEN_EXCHANGE_RATE_LATEST_URL, {
|
||||
params: {
|
||||
app_id: config.exchangeRate.openExchangeRate.appId,
|
||||
base: baseCurrency,
|
||||
symbols: toCurrency,
|
||||
},
|
||||
});
|
||||
return result.data.rates[toCurrency] || (1 as number);
|
||||
} catch (error) {
|
||||
this.handleLatestErrors(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the Open Exchange Rate api id.
|
||||
* @throws {ServiceError}
|
||||
*/
|
||||
private validateApiIdExistance() {
|
||||
const apiId = config.exchangeRate.openExchangeRate.appId;
|
||||
|
||||
if (!apiId) {
|
||||
throw new ServiceError(
|
||||
EchangeRateErrors.EX_RATE_SERVICE_API_KEY_REQUIRED,
|
||||
'Invalid App ID provided. Please sign up at https://openexchangerates.org/signup, or contact support@openexchangerates.org.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the latest errors.
|
||||
* @param {any} error
|
||||
* @throws {ServiceError}
|
||||
*/
|
||||
private handleLatestErrors(error: any) {
|
||||
if (error.response.data?.message === 'missing_app_id') {
|
||||
throw new ServiceError(
|
||||
EchangeRateErrors.EX_RATE_SERVICE_API_KEY_REQUIRED,
|
||||
'Invalid App ID provided. Please sign up at https://openexchangerates.org/signup, or contact support@openexchangerates.org.'
|
||||
);
|
||||
} else if (error.response.data?.message === 'invalid_app_id') {
|
||||
throw new ServiceError(
|
||||
EchangeRateErrors.EX_RATE_SERVICE_API_KEY_REQUIRED,
|
||||
'Invalid App ID provided. Please sign up at https://openexchangerates.org/signup, or contact support@openexchangerates.org.'
|
||||
);
|
||||
} else if (error.response.data?.message === 'not_allowed') {
|
||||
throw new ServiceError(
|
||||
EchangeRateErrors.EX_RATE_SERVICE_NOT_ALLOWED,
|
||||
'Getting the exchange rate from the given base currency to the given currency is not allowed.'
|
||||
);
|
||||
} else if (error.response.data?.message === 'invalid_base') {
|
||||
throw new ServiceError(
|
||||
EchangeRateErrors.EX_RATE_INVALID_BASE_CURRENCY,
|
||||
'The given base currency is invalid.'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
17
packages/server/src/lib/ExchangeRate/types.ts
Normal file
17
packages/server/src/lib/ExchangeRate/types.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
export interface IExchangeRateService {
|
||||
latest(baseCurrency: string, toCurrency: string): Promise<number>;
|
||||
}
|
||||
|
||||
export enum ExchangeRateServiceType {
|
||||
OpenExchangeRate = 'OpenExchangeRate',
|
||||
}
|
||||
|
||||
export enum EchangeRateErrors {
|
||||
EX_RATE_SERVICE_NOT_ALLOWED = 'EX_RATE_SERVICE_NOT_ALLOWED',
|
||||
EX_RATE_LIMIT_EXCEEDED = 'EX_RATE_LIMIT_EXCEEDED',
|
||||
EX_RATE_SERVICE_API_KEY_REQUIRED = 'EX_RATE_SERVICE_API_KEY_REQUIRED',
|
||||
EX_RATE_INVALID_BASE_CURRENCY = 'EX_RATE_INVALID_BASE_CURRENCY',
|
||||
}
|
||||
|
||||
export const OPEN_EXCHANGE_RATE_LATEST_URL =
|
||||
'https://openexchangerates.org/api/latest.json';
|
||||
@@ -2,6 +2,8 @@ import { Model } from 'objection';
|
||||
import TenantModel from 'models/TenantModel';
|
||||
|
||||
export default class ExpenseCategory extends TenantModel {
|
||||
amount: number;
|
||||
|
||||
/**
|
||||
* Table name
|
||||
*/
|
||||
|
||||
@@ -3,8 +3,10 @@ import {
|
||||
IAccount,
|
||||
IAccountCreateDTO,
|
||||
IAccountEditDTO,
|
||||
IAccountResponse,
|
||||
IAccountsFilter,
|
||||
IAccountsTransactionsFilter,
|
||||
IFilterMeta,
|
||||
IGetAccountTransactionPOJO,
|
||||
} from '@/interfaces';
|
||||
import { CreateAccount } from './CreateAccount';
|
||||
@@ -14,6 +16,7 @@ import { ActivateAccount } from './ActivateAccount';
|
||||
import { GetAccounts } from './GetAccounts';
|
||||
import { GetAccount } from './GetAccount';
|
||||
import { GetAccountTransactions } from './GetAccountTransactions';
|
||||
|
||||
@Service()
|
||||
export class AccountsApplication {
|
||||
@Inject()
|
||||
@@ -113,19 +116,22 @@ export class AccountsApplication {
|
||||
|
||||
/**
|
||||
* Retrieves the accounts list.
|
||||
* @param {number} tenantId
|
||||
* @param {IAccountsFilter} filterDTO
|
||||
* @returns
|
||||
* @param {number} tenantId
|
||||
* @param {IAccountsFilter} filterDTO
|
||||
* @returns {Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }>}
|
||||
*/
|
||||
public getAccounts = (tenantId: number, filterDTO: IAccountsFilter) => {
|
||||
public getAccounts = (
|
||||
tenantId: number,
|
||||
filterDTO: IAccountsFilter
|
||||
): Promise<{ accounts: IAccountResponse[]; filterMeta: IFilterMeta }> => {
|
||||
return this.getAccountsService.getAccountsList(tenantId, filterDTO);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the given account transactions.
|
||||
* @param {number} tenantId
|
||||
* @param {IAccountsTransactionsFilter} filter
|
||||
* @returns {Promise<IGetAccountTransactionPOJO[]>}
|
||||
* @param {number} tenantId
|
||||
* @param {IAccountsTransactionsFilter} filter
|
||||
* @returns {Promise<IGetAccountTransactionPOJO[]>}
|
||||
*/
|
||||
public getAccountsTransactions = (
|
||||
tenantId: number,
|
||||
|
||||
@@ -80,7 +80,7 @@ export default class EditCreditNote extends BaseCreditNotes {
|
||||
} as ICreditNoteEditingPayload);
|
||||
|
||||
// Saves the credit note graph to the storage.
|
||||
const creditNote = await CreditNote.query(trx).upsertGraph({
|
||||
const creditNote = await CreditNote.query(trx).upsertGraphAndFetch({
|
||||
id: creditNoteId,
|
||||
...creditNoteModel,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ChromiumlyTenancy } from '../ChromiumlyTenancy/ChromiumlyTenancy';
|
||||
import { TemplateInjectable } from '../TemplateInjectable/TemplateInjectable';
|
||||
import GetCreditNote from './GetCreditNote';
|
||||
|
||||
@Service()
|
||||
export default class GetCreditNotePdf {
|
||||
@@ -10,11 +11,19 @@ export default class GetCreditNotePdf {
|
||||
@Inject()
|
||||
private templateInjectable: TemplateInjectable;
|
||||
|
||||
@Inject()
|
||||
private getCreditNoteService: GetCreditNote;
|
||||
|
||||
/**
|
||||
* Retrieve sale invoice pdf content.
|
||||
* @param {} saleInvoice -
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {number} creditNoteId - Credit note id.
|
||||
*/
|
||||
public async getCreditNotePdf(tenantId: number, creditNote) {
|
||||
public async getCreditNotePdf(tenantId: number, creditNoteId: number) {
|
||||
const creditNote = await this.getCreditNoteService.getCreditNote(
|
||||
tenantId,
|
||||
creditNoteId
|
||||
);
|
||||
const htmlContent = await this.templateInjectable.render(
|
||||
tenantId,
|
||||
'modules/credit-note-standard',
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Inject } from 'typedi';
|
||||
import { ExchangeRatesService } from './ExchangeRatesService';
|
||||
import { EchangeRateLatestPOJO, ExchangeRateLatestDTO } from '@/interfaces';
|
||||
|
||||
export class ExchangeRateApplication {
|
||||
@Inject()
|
||||
private exchangeRateService: ExchangeRatesService;
|
||||
|
||||
/**
|
||||
* Gets the latest exchange rate.
|
||||
* @param {number} tenantId
|
||||
* @param {ExchangeRateLatestDTO} exchangeRateLatestDTO
|
||||
* @returns {Promise<EchangeRateLatestPOJO>}
|
||||
*/
|
||||
public latest(
|
||||
tenantId: number,
|
||||
exchangeRateLatestDTO: ExchangeRateLatestDTO
|
||||
): Promise<EchangeRateLatestPOJO> {
|
||||
return this.exchangeRateService.latest(tenantId, exchangeRateLatestDTO);
|
||||
}
|
||||
}
|
||||
@@ -1,193 +1,37 @@
|
||||
import moment from 'moment';
|
||||
import { difference } from 'lodash';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { ServiceError } from '@/exceptions';
|
||||
import DynamicListingService from '@/services/DynamicListing/DynamicListService';
|
||||
import {
|
||||
EventDispatcher,
|
||||
EventDispatcherInterface,
|
||||
} from 'decorators/eventDispatcher';
|
||||
import {
|
||||
IExchangeRateDTO,
|
||||
IExchangeRate,
|
||||
IExchangeRatesService,
|
||||
IExchangeRateEditDTO,
|
||||
IExchangeRateFilter,
|
||||
} from '@/interfaces';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
|
||||
const ERRORS = {
|
||||
NOT_FOUND_EXCHANGE_RATES: 'NOT_FOUND_EXCHANGE_RATES',
|
||||
EXCHANGE_RATE_PERIOD_EXISTS: 'EXCHANGE_RATE_PERIOD_EXISTS',
|
||||
EXCHANGE_RATE_NOT_FOUND: 'EXCHANGE_RATE_NOT_FOUND',
|
||||
};
|
||||
import { Service } from 'typedi';
|
||||
import { ExchangeRate } from '@/lib/ExchangeRate/ExchangeRate';
|
||||
import { ExchangeRateServiceType } from '@/lib/ExchangeRate/types';
|
||||
import { EchangeRateLatestPOJO, ExchangeRateLatestDTO } from '@/interfaces';
|
||||
import { TenantMetadata } from '@/system/models';
|
||||
|
||||
@Service()
|
||||
export default class ExchangeRatesService implements IExchangeRatesService {
|
||||
@Inject('logger')
|
||||
logger: any;
|
||||
|
||||
@EventDispatcher()
|
||||
eventDispatcher: EventDispatcherInterface;
|
||||
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
@Inject()
|
||||
dynamicListService: DynamicListingService;
|
||||
|
||||
export class ExchangeRatesService {
|
||||
/**
|
||||
* Creates a new exchange rate.
|
||||
* Gets the latest exchange rate.
|
||||
* @param {number} tenantId
|
||||
* @param {IExchangeRateDTO} exchangeRateDTO
|
||||
* @returns {Promise<IExchangeRate>}
|
||||
* @param {number} exchangeRateLatestDTO
|
||||
* @returns {EchangeRateLatestPOJO}
|
||||
*/
|
||||
public async newExchangeRate(
|
||||
public async latest(
|
||||
tenantId: number,
|
||||
exchangeRateDTO: IExchangeRateDTO
|
||||
): Promise<IExchangeRate> {
|
||||
const { ExchangeRate } = this.tenancy.models(tenantId);
|
||||
exchangeRateLatestDTO: ExchangeRateLatestDTO
|
||||
): Promise<EchangeRateLatestPOJO> {
|
||||
const organization = await TenantMetadata.query().findOne({ tenantId });
|
||||
|
||||
this.logger.info('[exchange_rates] trying to insert new exchange rate.', {
|
||||
tenantId,
|
||||
exchangeRateDTO,
|
||||
});
|
||||
await this.validateExchangeRatePeriodExistance(tenantId, exchangeRateDTO);
|
||||
// Assign the organization base currency as a default currency
|
||||
// if no currency is provided
|
||||
const fromCurrency =
|
||||
exchangeRateLatestDTO.fromCurrency || organization.baseCurrency;
|
||||
const toCurrency =
|
||||
exchangeRateLatestDTO.toCurrency || organization.baseCurrency;
|
||||
|
||||
const exchangeRate = await ExchangeRate.query().insertAndFetch({
|
||||
...exchangeRateDTO,
|
||||
date: moment(exchangeRateDTO.date).format('YYYY-MM-DD'),
|
||||
});
|
||||
this.logger.info('[exchange_rates] inserted successfully.', {
|
||||
tenantId,
|
||||
exchangeRateDTO,
|
||||
});
|
||||
return exchangeRate;
|
||||
}
|
||||
const exchange = new ExchangeRate(ExchangeRateServiceType.OpenExchangeRate);
|
||||
const exchangeRate = await exchange.latest(fromCurrency, toCurrency);
|
||||
|
||||
/**
|
||||
* Edits the exchange rate details.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {number} exchangeRateId - Exchange rate id.
|
||||
* @param {IExchangeRateEditDTO} editExRateDTO - Edit exchange rate DTO.
|
||||
*/
|
||||
public async editExchangeRate(
|
||||
tenantId: number,
|
||||
exchangeRateId: number,
|
||||
editExRateDTO: IExchangeRateEditDTO
|
||||
): Promise<void> {
|
||||
const { ExchangeRate } = this.tenancy.models(tenantId);
|
||||
|
||||
this.logger.info('[exchange_rates] trying to edit exchange rate.', {
|
||||
tenantId,
|
||||
exchangeRateId,
|
||||
editExRateDTO,
|
||||
});
|
||||
await this.validateExchangeRateExistance(tenantId, exchangeRateId);
|
||||
|
||||
await ExchangeRate.query()
|
||||
.where('id', exchangeRateId)
|
||||
.update({ ...editExRateDTO });
|
||||
this.logger.info('[exchange_rates] exchange rate edited successfully.', {
|
||||
tenantId,
|
||||
exchangeRateId,
|
||||
editExRateDTO,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the given exchange rate.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {number} exchangeRateId - Exchange rate id.
|
||||
*/
|
||||
public async deleteExchangeRate(
|
||||
tenantId: number,
|
||||
exchangeRateId: number
|
||||
): Promise<void> {
|
||||
const { ExchangeRate } = this.tenancy.models(tenantId);
|
||||
await this.validateExchangeRateExistance(tenantId, exchangeRateId);
|
||||
|
||||
await ExchangeRate.query().findById(exchangeRateId).delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Listing exchange rates details.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {IExchangeRateFilter} exchangeRateFilter - Exchange rates list filter.
|
||||
*/
|
||||
public async listExchangeRates(
|
||||
tenantId: number,
|
||||
exchangeRateFilter: IExchangeRateFilter
|
||||
): Promise<void> {
|
||||
const { ExchangeRate } = this.tenancy.models(tenantId);
|
||||
const dynamicFilter = await this.dynamicListService.dynamicList(
|
||||
tenantId,
|
||||
ExchangeRate,
|
||||
exchangeRateFilter
|
||||
);
|
||||
// Retrieve exchange rates by the given query.
|
||||
const exchangeRates = await ExchangeRate.query()
|
||||
.onBuild((query) => {
|
||||
dynamicFilter.buildQuery()(query);
|
||||
})
|
||||
.pagination(exchangeRateFilter.page - 1, exchangeRateFilter.pageSize);
|
||||
|
||||
return exchangeRates;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates period of the exchange rate existance.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {IExchangeRateDTO} exchangeRateDTO - Exchange rate DTO.
|
||||
* @return {Promise<void>}
|
||||
*/
|
||||
private async validateExchangeRatePeriodExistance(
|
||||
tenantId: number,
|
||||
exchangeRateDTO: IExchangeRateDTO
|
||||
): Promise<void> {
|
||||
const { ExchangeRate } = this.tenancy.models(tenantId);
|
||||
|
||||
this.logger.info('[exchange_rates] trying to validate period existance.', {
|
||||
tenantId,
|
||||
});
|
||||
const foundExchangeRate = await ExchangeRate.query()
|
||||
.where('currency_code', exchangeRateDTO.currencyCode)
|
||||
.where('date', exchangeRateDTO.date);
|
||||
|
||||
if (foundExchangeRate.length > 0) {
|
||||
this.logger.info('[exchange_rates] given exchange rate period exists.', {
|
||||
tenantId,
|
||||
});
|
||||
throw new ServiceError(ERRORS.EXCHANGE_RATE_PERIOD_EXISTS);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the given echange rate id existance.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
* @param {number} exchangeRateId - Exchange rate id.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
private async validateExchangeRateExistance(
|
||||
tenantId: number,
|
||||
exchangeRateId: number
|
||||
) {
|
||||
const { ExchangeRate } = this.tenancy.models(tenantId);
|
||||
|
||||
this.logger.info(
|
||||
'[exchange_rates] trying to validate exchange rate id existance.',
|
||||
{ tenantId, exchangeRateId }
|
||||
);
|
||||
const foundExchangeRate = await ExchangeRate.query().findById(
|
||||
exchangeRateId
|
||||
);
|
||||
|
||||
if (!foundExchangeRate) {
|
||||
this.logger.info('[exchange_rates] exchange rate not found.', {
|
||||
tenantId,
|
||||
exchangeRateId,
|
||||
});
|
||||
throw new ServiceError(ERRORS.EXCHANGE_RATE_NOT_FOUND);
|
||||
}
|
||||
return {
|
||||
baseCurrency: fromCurrency,
|
||||
toCurrency: exchangeRateLatestDTO.toCurrency,
|
||||
exchangeRate,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ export class EditExpense {
|
||||
} as IExpenseEventEditingPayload);
|
||||
|
||||
// Upsert the expense object with expense entries.
|
||||
const expense: IExpense = await Expense.query(trx).upsertGraph({
|
||||
const expense: IExpense = await Expense.query(trx).upsertGraphAndFetch({
|
||||
id: expenseId,
|
||||
...expenseObj,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Transformer } from '@/lib/Transformer/Transformer';
|
||||
import { ExpenseCategory } from '@/models';
|
||||
import { formatNumber } from '@/utils';
|
||||
|
||||
export class ExpenseCategoryTransformer extends Transformer {
|
||||
/**
|
||||
* Include these attributes to expense object.
|
||||
* @returns {Array}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['amountFormatted'];
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the formatted amount.
|
||||
* @param {ExpenseCategory} category
|
||||
* @returns {string}
|
||||
*/
|
||||
protected amountFormatted(category: ExpenseCategory) {
|
||||
return formatNumber(category.amount, {
|
||||
currencyCode: this.context.currencyCode,
|
||||
money: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Transformer } from '@/lib/Transformer/Transformer';
|
||||
import { formatNumber } from 'utils';
|
||||
import { IExpense } from '@/interfaces';
|
||||
import { ExpenseCategoryTransformer } from './ExpenseCategoryTransformer';
|
||||
|
||||
export class ExpenseTransfromer extends Transformer {
|
||||
/**
|
||||
@@ -12,7 +13,8 @@ export class ExpenseTransfromer extends Transformer {
|
||||
'formattedAmount',
|
||||
'formattedLandedCostAmount',
|
||||
'formattedAllocatedCostAmount',
|
||||
'formattedDate'
|
||||
'formattedDate',
|
||||
'categories',
|
||||
];
|
||||
};
|
||||
|
||||
@@ -56,5 +58,16 @@ export class ExpenseTransfromer extends Transformer {
|
||||
*/
|
||||
protected formattedDate = (expense: IExpense): string => {
|
||||
return this.formatDate(expense.paymentDate);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the transformed expense categories.
|
||||
* @param {IExpense} expense
|
||||
* @returns {}
|
||||
*/
|
||||
protected categories = (expense: IExpense) => {
|
||||
return this.item(expense.categories, new ExpenseCategoryTransformer(), {
|
||||
currencyCode: expense.currencyCode,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Knex } from 'knex';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import LedgerStorageService from '@/services/Accounting/LedgerStorageService';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { ExpenseGLEntries } from './ExpenseGLEntries';
|
||||
|
||||
@Service()
|
||||
|
||||
@@ -70,10 +70,10 @@ export class ExpensesWriteGLSubscriber {
|
||||
authorizedUser,
|
||||
trx,
|
||||
}: IExpenseEventEditPayload) => {
|
||||
// In case expense published, write journal entries.
|
||||
if (expense.publishedAt) return;
|
||||
// Cannot continue if the expense is not published.
|
||||
if (!expense.publishedAt) return;
|
||||
|
||||
await this.expenseGLEntries.writeExpenseGLEntries(
|
||||
await this.expenseGLEntries.rewriteExpenseGLEntries(
|
||||
tenantId,
|
||||
expense.id,
|
||||
trx
|
||||
|
||||
@@ -2,36 +2,34 @@ import { get, isEmpty, sumBy } from 'lodash';
|
||||
import * as R from 'ramda';
|
||||
import FinancialSheet from '../FinancialSheet';
|
||||
import { allPassedConditionsPass, transformToMap } from 'utils';
|
||||
import { IAccountTransaction, IItem } from '@/interfaces';
|
||||
import {
|
||||
IAccountTransaction,
|
||||
IInventoryValuationTotal,
|
||||
IInventoryValuationItem,
|
||||
IInventoryValuationReportQuery,
|
||||
IInventoryValuationStatement,
|
||||
IItem,
|
||||
} from '@/interfaces';
|
||||
IPurchasesByItemsItem,
|
||||
IPurchasesByItemsReportQuery,
|
||||
IPurchasesByItemsSheetData,
|
||||
IPurchasesByItemsTotal,
|
||||
} from '@/interfaces/PurchasesByItemsSheet';
|
||||
|
||||
export default class InventoryValuationReport extends FinancialSheet {
|
||||
export class PurchasesByItems extends FinancialSheet {
|
||||
readonly baseCurrency: string;
|
||||
readonly items: IItem[];
|
||||
readonly itemsTransactions: Map<number, IAccountTransaction>;
|
||||
readonly query: IInventoryValuationReportQuery;
|
||||
readonly query: IPurchasesByItemsReportQuery;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
* @param {IInventoryValuationReportQuery} query
|
||||
* @param {IPurchasesByItemsReportQuery} query
|
||||
* @param {IItem[]} items
|
||||
* @param {IAccountTransaction[]} itemsTransactions
|
||||
* @param {string} baseCurrency
|
||||
*/
|
||||
constructor(
|
||||
query: IInventoryValuationReportQuery,
|
||||
query: IPurchasesByItemsReportQuery,
|
||||
items: IItem[],
|
||||
itemsTransactions: IAccountTransaction[],
|
||||
baseCurrency: string
|
||||
) {
|
||||
super();
|
||||
|
||||
this.baseCurrency = baseCurrency;
|
||||
this.items = items;
|
||||
this.itemsTransactions = transformToMap(itemsTransactions, 'itemId');
|
||||
@@ -98,7 +96,7 @@ export default class InventoryValuationReport extends FinancialSheet {
|
||||
* @param {IInventoryValuationItem} item
|
||||
* @returns
|
||||
*/
|
||||
private itemSectionMapper = (item: IItem): IInventoryValuationItem => {
|
||||
private itemSectionMapper = (item: IItem): IPurchasesByItemsItem => {
|
||||
const meta = this.getItemTransaction(item.id);
|
||||
|
||||
return {
|
||||
@@ -145,9 +143,9 @@ export default class InventoryValuationReport extends FinancialSheet {
|
||||
|
||||
/**
|
||||
* Retrieve the items sections.
|
||||
* @returns {IInventoryValuationItem[]}
|
||||
* @returns {IPurchasesByItemsItem[]}
|
||||
*/
|
||||
private itemsSection = (): IInventoryValuationItem[] => {
|
||||
private itemsSection = (): IPurchasesByItemsItem[] => {
|
||||
return R.compose(
|
||||
R.when(this.isItemsPostFilter, this.itemsFilter),
|
||||
this.itemsMapper
|
||||
@@ -156,10 +154,10 @@ export default class InventoryValuationReport extends FinancialSheet {
|
||||
|
||||
/**
|
||||
* Retrieve the total section of the sheet.
|
||||
* @param {IInventoryValuationItem[]} items
|
||||
* @returns {IInventoryValuationTotal}
|
||||
* @param {IPurchasesByItemsItem[]} items
|
||||
* @returns {IPurchasesByItemsTotal}
|
||||
*/
|
||||
totalSection(items: IInventoryValuationItem[]): IInventoryValuationTotal {
|
||||
private totalSection(items: IPurchasesByItemsItem[]): IPurchasesByItemsTotal {
|
||||
const quantityPurchased = sumBy(items, (item) => item.quantityPurchased);
|
||||
const purchaseCost = sumBy(items, (item) => item.purchaseCost);
|
||||
|
||||
@@ -176,12 +174,12 @@ export default class InventoryValuationReport extends FinancialSheet {
|
||||
|
||||
/**
|
||||
* Retrieve the sheet data.
|
||||
* @returns
|
||||
* @returns {IInventoryValuationStatement}
|
||||
*/
|
||||
reportData(): IInventoryValuationStatement {
|
||||
public reportData(): IPurchasesByItemsSheetData {
|
||||
const items = this.itemsSection();
|
||||
const total = this.totalSection(items);
|
||||
|
||||
return items.length > 0 ? { items, total } : {};
|
||||
return { items, total };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import { PurchasesByItemsExport } from './PurchasesByItemsExport';
|
||||
import {
|
||||
IPurchasesByItemsReportQuery,
|
||||
IPurchasesByItemsSheet,
|
||||
IPurchasesByItemsTable,
|
||||
} from '@/interfaces/PurchasesByItemsSheet';
|
||||
import { PurchasesByItemsTableInjectable } from './PurchasesByItemsTableInjectable';
|
||||
import { PurchasesByItemsService } from './PurchasesByItemsService';
|
||||
|
||||
@Service()
|
||||
export class PurcahsesByItemsApplication {
|
||||
@Inject()
|
||||
private purchasesByItemsSheet: PurchasesByItemsService;
|
||||
|
||||
@Inject()
|
||||
private purchasesByItemsTable: PurchasesByItemsTableInjectable;
|
||||
|
||||
@Inject()
|
||||
private purchasesByItemsExport: PurchasesByItemsExport;
|
||||
|
||||
/**
|
||||
* Retrieves the purchases by items in json format.
|
||||
* @param {number} tenantId
|
||||
* @param {IPurchasesByItemsReportQuery} query
|
||||
* @returns
|
||||
*/
|
||||
public sheet(
|
||||
tenantId: number,
|
||||
query: IPurchasesByItemsReportQuery
|
||||
): Promise<IPurchasesByItemsSheet> {
|
||||
return this.purchasesByItemsSheet.purchasesByItems(tenantId, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the purchases by items in table format.
|
||||
* @param {number} tenantId
|
||||
* @param {IPurchasesByItemsReportQuery} query
|
||||
* @returns {Promise<IPurchasesByItemsTable>}
|
||||
*/
|
||||
public table(
|
||||
tenantId: number,
|
||||
query: IPurchasesByItemsReportQuery
|
||||
): Promise<IPurchasesByItemsTable> {
|
||||
return this.purchasesByItemsTable.table(tenantId, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the purchases by items in csv format.
|
||||
* @param {number} tenantId
|
||||
* @param {IPurchasesByItemsReportQuery} query
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
public csv(
|
||||
tenantId: number,
|
||||
query: IPurchasesByItemsReportQuery
|
||||
): Promise<string> {
|
||||
return this.purchasesByItemsExport.csv(tenantId, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the purchases by items in xlsx format.
|
||||
* @param {number} tenantId
|
||||
* @param {IPurchasesByItemsReportQuery} query
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
public xlsx(
|
||||
tenantId: number,
|
||||
query: IPurchasesByItemsReportQuery
|
||||
): Promise<Buffer> {
|
||||
return this.purchasesByItemsExport.xlsx(tenantId, query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { TableSheet } from '@/lib/Xlsx/TableSheet';
|
||||
import { PurchasesByItemsTableInjectable } from './PurchasesByItemsTableInjectable';
|
||||
import { IPurchasesByItemsReportQuery } from '@/interfaces/PurchasesByItemsSheet';
|
||||
|
||||
@Service()
|
||||
export class PurchasesByItemsExport {
|
||||
@Inject()
|
||||
private purchasesByItemsTable: PurchasesByItemsTableInjectable;
|
||||
|
||||
/**
|
||||
* Retrieves the purchases by items sheet in XLSX format.
|
||||
* @param {number} tenantId
|
||||
* @param {IPurchasesByItemsReportQuery} query
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
public async xlsx(
|
||||
tenantId: number,
|
||||
query: IPurchasesByItemsReportQuery
|
||||
): Promise<Buffer> {
|
||||
const table = await this.purchasesByItemsTable.table(tenantId, query);
|
||||
|
||||
const tableSheet = new TableSheet(table.table);
|
||||
const tableCsv = tableSheet.convertToXLSX();
|
||||
|
||||
return tableSheet.convertToBuffer(tableCsv, 'xlsx');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the purchases by items sheet in CSV format.
|
||||
* @param {number} tenantId
|
||||
* @param {IPurchasesByItemsReportQuery} query
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
public async csv(
|
||||
tenantId: number,
|
||||
query: IPurchasesByItemsReportQuery
|
||||
): Promise<string> {
|
||||
const table = await this.purchasesByItemsTable.table(tenantId, query);
|
||||
|
||||
const tableSheet = new TableSheet(table.table);
|
||||
const tableCsv = tableSheet.convertToCSV();
|
||||
|
||||
return tableCsv;
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,24 @@
|
||||
import { Service, Inject } from 'typedi';
|
||||
import moment from 'moment';
|
||||
import {
|
||||
IInventoryValuationReportQuery,
|
||||
IInventoryValuationStatement,
|
||||
IInventoryValuationSheetMeta,
|
||||
} from '@/interfaces';
|
||||
import { Service, Inject } from 'typedi';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import PurchasesByItems from './PurchasesByItems';
|
||||
import { PurchasesByItems } from './PurchasesByItems';
|
||||
import { Tenant } from '@/system/models';
|
||||
import {
|
||||
IPurchasesByItemsReportQuery,
|
||||
IPurchasesByItemsSheet,
|
||||
IPurchasesByItemsSheetMeta,
|
||||
} from '@/interfaces/PurchasesByItemsSheet';
|
||||
|
||||
@Service()
|
||||
export default class InventoryValuationReportService {
|
||||
export class PurchasesByItemsService {
|
||||
@Inject()
|
||||
private tenancy: TenancyService;
|
||||
|
||||
/**
|
||||
* Defaults balance sheet filter query.
|
||||
* @return {IBalanceSheetQuery}
|
||||
* Defaults purchases by items filter query.
|
||||
* @return {IPurchasesByItemsReportQuery}
|
||||
*/
|
||||
get defaultQuery(): IInventoryValuationReportQuery {
|
||||
get defaultQuery(): IPurchasesByItemsReportQuery {
|
||||
return {
|
||||
fromDate: moment().startOf('month').format('YYYY-MM-DD'),
|
||||
toDate: moment().format('YYYY-MM-DD'),
|
||||
@@ -40,7 +40,7 @@ export default class InventoryValuationReportService {
|
||||
* @param {number} tenantId -
|
||||
* @returns {IBalanceSheetMeta}
|
||||
*/
|
||||
reportMetadata(tenantId: number): IInventoryValuationSheetMeta {
|
||||
reportMetadata(tenantId: number): IPurchasesByItemsSheetMeta {
|
||||
const settings = this.tenancy.settings(tenantId);
|
||||
|
||||
const organizationName = settings.get({
|
||||
@@ -62,18 +62,13 @@ export default class InventoryValuationReportService {
|
||||
* Retrieve balance sheet statement.
|
||||
* -------------
|
||||
* @param {number} tenantId
|
||||
* @param {IBalanceSheetQuery} query
|
||||
*
|
||||
* @return {IBalanceSheetStatement}
|
||||
* @param {IPurchasesByItemsReportQuery} query
|
||||
* @return {Promise<IPurchasesByItemsSheet>}
|
||||
*/
|
||||
public async purchasesByItems(
|
||||
tenantId: number,
|
||||
query: IInventoryValuationReportQuery
|
||||
): Promise<{
|
||||
data: IInventoryValuationStatement;
|
||||
query: IInventoryValuationReportQuery;
|
||||
meta: IInventoryValuationSheetMeta;
|
||||
}> {
|
||||
query: IPurchasesByItemsReportQuery
|
||||
): Promise<IPurchasesByItemsSheet> {
|
||||
const { Item, InventoryTransaction } = this.tenancy.models(tenantId);
|
||||
|
||||
const tenant = await Tenant.query()
|
||||
@@ -106,7 +101,6 @@ export default class InventoryValuationReportService {
|
||||
builder.modify('filterDateRange', filter.fromDate, filter.toDate);
|
||||
}
|
||||
);
|
||||
|
||||
const purchasesByItemsInstance = new PurchasesByItems(
|
||||
filter,
|
||||
inventoryItems,
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import * as R from 'ramda';
|
||||
import { ITableColumn, ITableColumnAccessor, ITableRow } from '@/interfaces';
|
||||
import { ROW_TYPE } from './_types';
|
||||
import { tableRowMapper } from '@/utils';
|
||||
import { FinancialTable } from '../FinancialTable';
|
||||
import { FinancialSheetStructure } from '../FinancialSheetStructure';
|
||||
import FinancialSheet from '../FinancialSheet';
|
||||
import {
|
||||
IPurchasesByItemsItem,
|
||||
IPurchasesByItemsSheetData,
|
||||
IPurchasesByItemsTotal,
|
||||
} from '@/interfaces/PurchasesByItemsSheet';
|
||||
|
||||
export class PurchasesByItemsTable extends R.compose(
|
||||
FinancialTable,
|
||||
FinancialSheetStructure
|
||||
)(FinancialSheet) {
|
||||
private data: IPurchasesByItemsSheetData;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
* @param data
|
||||
*/
|
||||
constructor(data) {
|
||||
super();
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves thge common table accessors.
|
||||
* @returns {ITableColumnAccessor[]}
|
||||
*/
|
||||
private commonTableAccessors(): ITableColumnAccessor[] {
|
||||
return [
|
||||
{ key: 'item_name', accessor: 'name' },
|
||||
{ key: 'quantity_purchases', accessor: 'quantityPurchasedFormatted' },
|
||||
{ key: 'purchase_amount', accessor: 'purchaseCostFormatted' },
|
||||
{ key: 'average_cost', accessor: 'averageCostPriceFormatted' },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the common table columns.
|
||||
* @returns {ITableColumn[]}
|
||||
*/
|
||||
private commonTableColumns(): ITableColumn[] {
|
||||
return [
|
||||
{ label: 'Item name', key: 'item_name' },
|
||||
{ label: 'Quantity Purchased', key: 'quantity_purchases' },
|
||||
{ label: 'Purchase Amount', key: 'purchase_amount' },
|
||||
{ label: 'Average Price', key: 'average_cost' },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps the given item node to table row.
|
||||
* @param {IPurchasesByItemsItem} item
|
||||
* @returns {ITableRow}
|
||||
*/
|
||||
private itemMap = (item: IPurchasesByItemsItem): ITableRow => {
|
||||
const columns = this.commonTableAccessors();
|
||||
const meta = {
|
||||
rowTypes: [ROW_TYPE.ITEM],
|
||||
};
|
||||
return tableRowMapper(item, columns, meta);
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps the given items nodes to table rows.
|
||||
* @param {IPurchasesByItemsItem[]} items - Items nodes.
|
||||
* @returns {ITableRow[]}
|
||||
*/
|
||||
private itemsMap = (items: IPurchasesByItemsItem[]): ITableRow[] => {
|
||||
return R.map(this.itemMap)(items);
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps the given total node to table rows.
|
||||
* @param {IPurchasesByItemsTotal} total
|
||||
* @returns {ITableRow}
|
||||
*/
|
||||
private totalNodeMap = (total: IPurchasesByItemsTotal): ITableRow => {
|
||||
const columns = this.commonTableAccessors();
|
||||
const meta = {
|
||||
rowTypes: [ROW_TYPE.TOTAL],
|
||||
};
|
||||
return tableRowMapper(total, columns, meta);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the table columns.
|
||||
* @returns {ITableColumn[]}
|
||||
*/
|
||||
public tableColumns(): ITableColumn[] {
|
||||
const columns = this.commonTableColumns();
|
||||
return R.compose(this.tableColumnsCellIndexing)(columns);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the table rows.
|
||||
* @returns {ITableRow[]}
|
||||
*/
|
||||
public tableData(): ITableRow[] {
|
||||
const itemsRows = this.itemsMap(this.data.items);
|
||||
const totalRow = this.totalNodeMap(this.data.total);
|
||||
|
||||
return R.compose(
|
||||
R.when(R.always(R.not(R.isEmpty(itemsRows))), R.append(totalRow))
|
||||
)(itemsRows) as ITableRow[];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
IPurchasesByItemsReportQuery,
|
||||
IPurchasesByItemsTable,
|
||||
} from '@/interfaces/PurchasesByItemsSheet';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { PurchasesByItemsService } from './PurchasesByItemsService';
|
||||
import { PurchasesByItemsTable } from './PurchasesByItemsTable';
|
||||
|
||||
@Service()
|
||||
export class PurchasesByItemsTableInjectable {
|
||||
@Inject()
|
||||
private purchasesByItemsSheet: PurchasesByItemsService;
|
||||
|
||||
/**
|
||||
* Retrieves the purchases by items table format.
|
||||
* @param {number} tenantId
|
||||
* @param {IPurchasesByItemsReportQuery} filter
|
||||
* @returns {Promise<IPurchasesByItemsTable>}
|
||||
*/
|
||||
public async table(
|
||||
tenantId: number,
|
||||
filter: IPurchasesByItemsReportQuery
|
||||
): Promise<IPurchasesByItemsTable> {
|
||||
const { data, query, meta } =
|
||||
await this.purchasesByItemsSheet.purchasesByItems(tenantId, filter);
|
||||
|
||||
const table = new PurchasesByItemsTable(data);
|
||||
|
||||
return {
|
||||
table: {
|
||||
columns: table.tableColumns(),
|
||||
rows: table.tableData(),
|
||||
},
|
||||
meta,
|
||||
query,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
|
||||
export enum ROW_TYPE {
|
||||
TOTAL = 'TOTAL',
|
||||
ITEM = 'ITEM'
|
||||
}
|
||||
@@ -13,6 +13,7 @@ export class PurchaseInvoiceTransformer extends Transformer {
|
||||
return [
|
||||
'formattedBillDate',
|
||||
'formattedDueDate',
|
||||
'formattedAmount',
|
||||
'formattedPaymentAmount',
|
||||
'formattedBalance',
|
||||
'formattedDueAmount',
|
||||
|
||||
@@ -9,6 +9,7 @@ import UnitOfWork from '@/services/UnitOfWork';
|
||||
import { EventPublisher } from '@/lib/EventPublisher/EventPublisher';
|
||||
import ItemsEntriesService from '@/services/Items/ItemsEntriesService';
|
||||
import events from '@/subscribers/events';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
|
||||
@Service()
|
||||
export default class EditVendorCredit extends BaseVendorCredit {
|
||||
@@ -21,6 +22,9 @@ export default class EditVendorCredit extends BaseVendorCredit {
|
||||
@Inject()
|
||||
private itemsEntriesService: ItemsEntriesService;
|
||||
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
|
||||
/**
|
||||
* Deletes the given vendor credit.
|
||||
* @param {number} tenantId - Tenant id.
|
||||
@@ -31,7 +35,7 @@ export default class EditVendorCredit extends BaseVendorCredit {
|
||||
vendorCreditId: number,
|
||||
vendorCreditDTO: IVendorCreditEditDTO
|
||||
) => {
|
||||
const { VendorCredit } = this.tenancy.models(tenantId);
|
||||
const { VendorCredit, Contact } = this.tenancy.models(tenantId);
|
||||
|
||||
// Retrieve the vendor credit or throw not found service error.
|
||||
const oldVendorCredit = await this.getVendorCreditOrThrowError(
|
||||
|
||||
@@ -32,7 +32,7 @@ export class SaleReceiptGLEntries {
|
||||
): Promise<void> => {
|
||||
const { SaleReceipt } = this.tenancy.models(tenantId);
|
||||
|
||||
const saleReceipt = await SaleReceipt.query()
|
||||
const saleReceipt = await SaleReceipt.query(trx)
|
||||
.findById(saleReceiptId)
|
||||
.withGraphFetched('entries.item');
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import BaseModel from 'models/Model';
|
||||
|
||||
export default class TenantMetadata extends BaseModel {
|
||||
baseCurrency: string;
|
||||
|
||||
/**
|
||||
* Table name.
|
||||
*/
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
TotalLineTextStyle,
|
||||
} from '@/components';
|
||||
import { useExpenseDrawerContext } from './ExpenseDrawerProvider';
|
||||
import { FormatNumber, TotalLine } from '@/components';
|
||||
import { TotalLine } from '@/components';
|
||||
|
||||
/**
|
||||
* Footer details of expense readonly details.
|
||||
@@ -22,12 +22,12 @@ export default function ExpenseDrawerFooter() {
|
||||
<ExpenseTotalLines labelColWidth={'180px'} amountColWidth={'180px'}>
|
||||
<TotalLine
|
||||
title={<T id={'expense.details.subtotal'} />}
|
||||
value={<FormatNumber value={expense.total_amount} />}
|
||||
value={expense.formatted_amount}
|
||||
borderStyle={TotalLineBorderStyle.SingleDark}
|
||||
/>
|
||||
<TotalLine
|
||||
title={<T id={'expense.details.total'} />}
|
||||
value={<FormatNumber value={expense.formatted_amount} />}
|
||||
value={expense.formatted_amount}
|
||||
borderStyle={TotalLineBorderStyle.DoubleDark}
|
||||
textStyle={TotalLineTextStyle.Bold}
|
||||
/>
|
||||
|
||||
@@ -36,8 +36,7 @@ export const useExpenseReadEntriesColumns = () => {
|
||||
},
|
||||
{
|
||||
Header: intl.get('amount'),
|
||||
accessor: 'amount',
|
||||
Cell: FormatNumberCell,
|
||||
accessor: 'amount_formatted',
|
||||
width: getColumnWidth(categories, 'amount', {
|
||||
minWidth: 60,
|
||||
magicSpacing: 5,
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { useExchangeRate } from '@/hooks/query';
|
||||
import { useCurrentOrganization } from '@/hooks/state';
|
||||
import React from 'react';
|
||||
import { useLatestExchangeRate } from '@/hooks/query';
|
||||
|
||||
interface AutoExchangeRateProviderProps {
|
||||
children: React.ReactNode;
|
||||
@@ -18,16 +17,19 @@ const AutoExchangeRateContext = React.createContext(
|
||||
function AutoExchangeRateProvider({ children }: AutoExchangeRateProviderProps) {
|
||||
const [autoExRateCurrency, setAutoExRateCurrency] =
|
||||
React.useState<string>('');
|
||||
const currentOrganization = useCurrentOrganization();
|
||||
|
||||
// Retrieves the exchange rate.
|
||||
const { data: autoExchangeRate, isLoading: isAutoExchangeRateLoading } =
|
||||
useExchangeRate(autoExRateCurrency, currentOrganization.base_currency, {
|
||||
enabled: Boolean(currentOrganization.base_currency && autoExRateCurrency),
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 0,
|
||||
cacheTime: 0,
|
||||
});
|
||||
useLatestExchangeRate(
|
||||
{ fromCurrency: autoExRateCurrency },
|
||||
{
|
||||
enabled: Boolean(autoExRateCurrency),
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 0,
|
||||
cacheTime: 0,
|
||||
retry: 0,
|
||||
},
|
||||
);
|
||||
|
||||
const value = {
|
||||
autoExRateCurrency,
|
||||
|
||||
@@ -98,24 +98,30 @@ interface UseSyncExRateToFormProps {
|
||||
*/
|
||||
export const useSyncExRateToForm = ({ onSynced }: UseSyncExRateToFormProps) => {
|
||||
const { setFieldValue, values } = useFormikContext();
|
||||
const { autoExRateCurrency, autoExchangeRate } = useAutoExRateContext();
|
||||
const { autoExRateCurrency, autoExchangeRate, isAutoExchangeRateLoading } =
|
||||
useAutoExRateContext();
|
||||
const updateEntriesOnExChange = useUpdateEntriesOnExchangeRateChange();
|
||||
|
||||
// Sync the fetched real-time exchanage rate to the form.
|
||||
useEffect(() => {
|
||||
if (autoExchangeRate?.exchange_rate && autoExRateCurrency) {
|
||||
setFieldValue('exchange_rate', autoExchangeRate?.exchange_rate + '');
|
||||
if (!isAutoExchangeRateLoading && autoExRateCurrency) {
|
||||
// Sets a default ex. rate to 1 in case the exchange rate service wasn't configured.
|
||||
// or returned an error from the server-side.
|
||||
const exchangeRate = autoExchangeRate?.exchange_rate || 1;
|
||||
|
||||
setFieldValue('exchange_rate', exchangeRate + '');
|
||||
setFieldValue(
|
||||
'entries',
|
||||
updateEntriesOnExChange(
|
||||
values.exchange_rate,
|
||||
autoExchangeRate?.exchange_rate,
|
||||
),
|
||||
updateEntriesOnExChange(values.exchange_rate, exchangeRate),
|
||||
);
|
||||
onSynced?.();
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [autoExchangeRate?.exchange_rate, autoExRateCurrency]);
|
||||
}, [
|
||||
autoExchangeRate?.exchange_rate,
|
||||
autoExRateCurrency,
|
||||
isAutoExchangeRateLoading,
|
||||
]);
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
@@ -18,6 +18,7 @@ import withPurchasesByItems from './withPurchasesByItems';
|
||||
import withPurchasesByItemsActions from './withPurchasesByItemsActions';
|
||||
import { compose, saveInvoke } from '@/utils';
|
||||
import { usePurchaseByItemsContext } from './PurchasesByItemsProvider';
|
||||
import { PurchasesByItemsExportMenu } from './components';
|
||||
|
||||
function PurchasesByItemsActionsBar({
|
||||
// #withPurchasesByItems
|
||||
@@ -106,11 +107,18 @@ function PurchasesByItemsActionsBar({
|
||||
icon={<Icon icon="print-16" iconSize={16} />}
|
||||
text={<T id={'print'} />}
|
||||
/>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon="file-export-16" iconSize={16} />}
|
||||
text={<T id={'export'} />}
|
||||
/>
|
||||
<Popover
|
||||
content={<PurchasesByItemsExportMenu />}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
placement="bottom-start"
|
||||
minimal
|
||||
>
|
||||
<Button
|
||||
className={Classes.MINIMAL}
|
||||
icon={<Icon icon="file-export-16" iconSize={16} />}
|
||||
text={<T id={'export'} />}
|
||||
/>
|
||||
</Popover>
|
||||
</NavbarGroup>
|
||||
</DashboardActionsBar>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @ts-nocheck
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import FinancialReportPage from '../FinancialReportPage';
|
||||
import { usePurchasesByItems } from '@/hooks/query';
|
||||
import { usePurchasesByItemsTable } from '@/hooks/query';
|
||||
import { transformFilterFormToQuery } from '../common';
|
||||
|
||||
const PurchasesByItemsContext = createContext();
|
||||
@@ -13,7 +13,7 @@ function PurchasesByItemsProvider({ query, ...props }) {
|
||||
isFetching,
|
||||
isLoading,
|
||||
refetch,
|
||||
} = usePurchasesByItems(
|
||||
} = usePurchasesByItemsTable(
|
||||
{
|
||||
...transformFilterFormToQuery(query),
|
||||
},
|
||||
@@ -26,7 +26,6 @@ function PurchasesByItemsProvider({ query, ...props }) {
|
||||
purchaseByItems,
|
||||
isFetching,
|
||||
isLoading,
|
||||
|
||||
refetchSheet: refetch,
|
||||
};
|
||||
return (
|
||||
|
||||
@@ -6,10 +6,10 @@ import styled from 'styled-components';
|
||||
import { ReportDataTable, FinancialSheet } from '@/components';
|
||||
|
||||
import { usePurchaseByItemsContext } from './PurchasesByItemsProvider';
|
||||
import { usePurchasesByItemsTableColumns } from './components';
|
||||
|
||||
import { tableRowTypesToClassnames } from '@/utils';
|
||||
import { TableStyle } from '@/constants';
|
||||
import { usePurchasesByItemsTableColumns } from './dynamicColumns';
|
||||
|
||||
/**
|
||||
* Purchases by items data table.
|
||||
@@ -17,7 +17,7 @@ import { TableStyle } from '@/constants';
|
||||
export default function PurchasesByItemsTable({ companyName }) {
|
||||
// Purchases by items context.
|
||||
const {
|
||||
purchaseByItems: { tableRows, query },
|
||||
purchaseByItems: { table, query },
|
||||
} = usePurchaseByItemsContext();
|
||||
|
||||
// Purchases by items table columns.
|
||||
@@ -32,7 +32,7 @@ export default function PurchasesByItemsTable({ companyName }) {
|
||||
>
|
||||
<PurchasesByItemsDataTable
|
||||
columns={columns}
|
||||
data={tableRows}
|
||||
data={table.rows}
|
||||
expandable={true}
|
||||
expandToggleColumn={1}
|
||||
expandColumnSpace={1}
|
||||
@@ -58,7 +58,7 @@ const PurchasesByItemsDataTable = styled(ReportDataTable)`
|
||||
padding-top: 0.36rem;
|
||||
padding-bottom: 0.36rem;
|
||||
}
|
||||
.tr.row_type--total .td {
|
||||
.tr.row_type--TOTAL .td {
|
||||
border-top: 1px solid #bbb;
|
||||
font-weight: 500;
|
||||
border-bottom: 3px double #000;
|
||||
|
||||
@@ -1,69 +1,22 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import { useRef } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
Classes,
|
||||
Intent,
|
||||
Menu,
|
||||
MenuItem,
|
||||
ProgressBar,
|
||||
Text,
|
||||
} from '@blueprintjs/core';
|
||||
|
||||
import { If } from '@/components';
|
||||
import { Align } from '@/constants';
|
||||
import { CellTextSpan } from '@/components/Datatable/Cells';
|
||||
import { AppToaster, If, Stack } from '@/components';
|
||||
import { usePurchaseByItemsContext } from './PurchasesByItemsProvider';
|
||||
import { getColumnWidth } from '@/utils';
|
||||
import FinancialLoadingBar from '../FinancialLoadingBar';
|
||||
|
||||
/**
|
||||
* Retrieve purchases by items table columns.
|
||||
*/
|
||||
export const usePurchasesByItemsTableColumns = () => {
|
||||
// purchases by items context.
|
||||
const {
|
||||
purchaseByItems: { tableRows },
|
||||
} = usePurchaseByItemsContext();
|
||||
|
||||
return React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: intl.get('item_name'),
|
||||
accessor: (row) => (row.code ? `${row.name} - ${row.code}` : row.name),
|
||||
className: 'name',
|
||||
width: 180,
|
||||
textOverview: true,
|
||||
},
|
||||
{
|
||||
Header: intl.get('quantity_purchased'),
|
||||
accessor: 'quantity_purchased_formatted',
|
||||
Cell: CellTextSpan,
|
||||
className: 'quantity_purchased_formatted',
|
||||
width: getColumnWidth(tableRows, `quantity_purchased_formatted`, {
|
||||
minWidth: 150,
|
||||
}),
|
||||
textOverview: true,
|
||||
align: Align.Right,
|
||||
},
|
||||
{
|
||||
Header: intl.get('purchase_amount'),
|
||||
accessor: 'purchase_cost_formatted',
|
||||
Cell: CellTextSpan,
|
||||
className: 'purchase_cost_formatted',
|
||||
width: getColumnWidth(tableRows, `purchase_cost_formatted`, {
|
||||
minWidth: 150,
|
||||
}),
|
||||
textOverview: true,
|
||||
align: Align.Right,
|
||||
},
|
||||
{
|
||||
Header: intl.get('average_price'),
|
||||
accessor: 'average_cost_price_formatted',
|
||||
Cell: CellTextSpan,
|
||||
className: 'average_cost_price_formatted',
|
||||
width: getColumnWidth(tableRows, `average_cost_price_formatted`, {
|
||||
minWidth: 180,
|
||||
}),
|
||||
textOverview: true,
|
||||
align: Align.Right,
|
||||
},
|
||||
],
|
||||
[tableRows],
|
||||
);
|
||||
};
|
||||
import {
|
||||
usePurchasesByItemsCsvExport,
|
||||
usePurchasesByItemsXlsxExport,
|
||||
} from '@/hooks/query';
|
||||
|
||||
/**
|
||||
* Purchases by items progress loading bar.
|
||||
@@ -77,3 +30,88 @@ export function PurchasesByItemsLoadingBar() {
|
||||
</If>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the purchases by items export menu.
|
||||
* @returns {JSX.Element}
|
||||
*/
|
||||
export const PurchasesByItemsExportMenu = () => {
|
||||
const toastKey = useRef(null);
|
||||
const commonToastConfig = {
|
||||
isCloseButtonShown: true,
|
||||
timeout: 2000,
|
||||
};
|
||||
const { query } = usePurchaseByItemsContext();
|
||||
|
||||
const openProgressToast = (amount: number) => {
|
||||
return (
|
||||
<Stack spacing={8}>
|
||||
<Text>The report has been exported successfully.</Text>
|
||||
<ProgressBar
|
||||
className={classNames('toast-progress', {
|
||||
[Classes.PROGRESS_NO_STRIPES]: amount >= 100,
|
||||
})}
|
||||
intent={amount < 100 ? Intent.PRIMARY : Intent.SUCCESS}
|
||||
value={amount / 100}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
// Export the report to xlsx.
|
||||
const { mutateAsync: xlsxExport } = usePurchasesByItemsXlsxExport(query, {
|
||||
onDownloadProgress: (xlsxExportProgress: number) => {
|
||||
if (!toastKey.current) {
|
||||
toastKey.current = AppToaster.show({
|
||||
message: openProgressToast(xlsxExportProgress),
|
||||
...commonToastConfig,
|
||||
});
|
||||
} else {
|
||||
AppToaster.show(
|
||||
{
|
||||
message: openProgressToast(xlsxExportProgress),
|
||||
...commonToastConfig,
|
||||
},
|
||||
toastKey.current,
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
// Export the report to csv.
|
||||
const { mutateAsync: csvExport } = usePurchasesByItemsCsvExport(query, {
|
||||
onDownloadProgress: (xlsxExportProgress: number) => {
|
||||
if (!toastKey.current) {
|
||||
toastKey.current = AppToaster.show({
|
||||
message: openProgressToast(xlsxExportProgress),
|
||||
...commonToastConfig,
|
||||
});
|
||||
} else {
|
||||
AppToaster.show(
|
||||
{
|
||||
message: openProgressToast(xlsxExportProgress),
|
||||
...commonToastConfig,
|
||||
},
|
||||
toastKey.current,
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
// Handle csv export button click.
|
||||
const handleCsvExportBtnClick = () => {
|
||||
csvExport();
|
||||
};
|
||||
// Handle xlsx export button click.
|
||||
const handleXlsxExportBtnClick = () => {
|
||||
xlsxExport();
|
||||
};
|
||||
|
||||
return (
|
||||
<Menu>
|
||||
<MenuItem
|
||||
text={'XLSX (Microsoft Excel)'}
|
||||
onClick={handleXlsxExportBtnClick}
|
||||
/>
|
||||
<MenuItem text={'CSV'} onClick={handleCsvExportBtnClick} />
|
||||
</Menu>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// @ts-nocheck
|
||||
import { getColumnWidth } from '@/utils';
|
||||
import * as R from 'ramda';
|
||||
import { Align } from '@/constants';
|
||||
import { usePurchaseByItemsContext } from './PurchasesByItemsProvider';
|
||||
|
||||
const getTableCellValueAccessor = (index) => `cells[${index}].value`;
|
||||
|
||||
const getReportColWidth = (data, accessor, headerText) => {
|
||||
return getColumnWidth(
|
||||
data,
|
||||
accessor,
|
||||
{ magicSpacing: 10, minWidth: 100 },
|
||||
headerText,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Account name column mapper.
|
||||
*/
|
||||
const commonColumnMapper = R.curry((data, column) => {
|
||||
const accessor = getTableCellValueAccessor(column.cell_index);
|
||||
|
||||
return {
|
||||
key: column.key,
|
||||
Header: column.label,
|
||||
accessor,
|
||||
className: column.key,
|
||||
textOverview: true,
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Numeric columns accessor.
|
||||
*/
|
||||
const numericColumnAccessor = R.curry((data, column) => {
|
||||
const accessor = getTableCellValueAccessor(column.cell_index);
|
||||
const width = getReportColWidth(data, accessor, column.label);
|
||||
|
||||
return {
|
||||
...column,
|
||||
align: Align.Right,
|
||||
width,
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* Item name column accessor.
|
||||
*/
|
||||
const itemNameColumnAccessor = R.curry((data, column) => {
|
||||
return {
|
||||
...column,
|
||||
width: 180,
|
||||
};
|
||||
});
|
||||
|
||||
const dynamiColumnMapper = R.curry((data, column) => {
|
||||
const _numericColumnAccessor = numericColumnAccessor(data);
|
||||
const _itemNameColumnAccessor = itemNameColumnAccessor(data);
|
||||
|
||||
return R.compose(
|
||||
R.when(R.pathEq(['key'], 'item_name'), _itemNameColumnAccessor),
|
||||
R.when(R.pathEq(['key'], 'quantity_purchases'), _numericColumnAccessor),
|
||||
R.when(R.pathEq(['key'], 'purchase_amount'), _numericColumnAccessor),
|
||||
R.when(R.pathEq(['key'], 'average_cost'), _numericColumnAccessor),
|
||||
commonColumnMapper(data),
|
||||
)(column);
|
||||
});
|
||||
|
||||
/**
|
||||
* Composes the dynamic columns that fetched from request to columns to table component.
|
||||
*/
|
||||
export const dynamicColumns = R.curry((data, columns) => {
|
||||
return R.map(dynamiColumnMapper(data), columns);
|
||||
});
|
||||
|
||||
/**
|
||||
* Retrieves the purchases by items sheet table columns for table component.
|
||||
*/
|
||||
export const usePurchasesByItemsTableColumns = () => {
|
||||
const { purchaseByItems } = usePurchaseByItemsContext();
|
||||
|
||||
if (!purchaseByItems) {
|
||||
throw new Error('Purchases by items context not found');
|
||||
}
|
||||
const { table } = purchaseByItems;
|
||||
|
||||
return dynamicColumns(table.rows, table.columns);
|
||||
};
|
||||
@@ -22,7 +22,7 @@ function VendorCreditUniversalSearchSelectComponent({
|
||||
openDrawer,
|
||||
}) {
|
||||
if (resourceType === RESOURCES_TYPES.VENDOR_CREDIT) {
|
||||
openDrawer(DRAWERS.VENDOR_CREDIT_DETAIL_DRAWER, {
|
||||
openDrawer(DRAWERS.VENDOR_CREDIT_DETAILS, {
|
||||
vendorCreditId: resourceId,
|
||||
});
|
||||
onAction && onAction();
|
||||
@@ -83,7 +83,7 @@ export function VendorCreditUniversalSearchItem(
|
||||
}
|
||||
label={
|
||||
<>
|
||||
<div class="amount">${item.reference.amount}</div>
|
||||
<div class="amount">{item.reference.formatted_amount}</div>
|
||||
<VendorCreditUniversalSearchStatus receipt={item.reference} />
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { Icon } from '@/components';
|
||||
import { RESOURCES_TYPES } from '@/constants/resourcesTypes';
|
||||
import { highlightText } from '@/utils';
|
||||
import { AbilitySubject, PaymentMadeAction } from '@/constants/abilityOption';
|
||||
import { DRAWERS } from '@/constants/drawers';
|
||||
import withDrawerActions from '@/containers/Drawer/withDrawerActions';
|
||||
|
||||
/**
|
||||
|
||||
@@ -82,7 +82,7 @@ export function CreditNoteUniversalSearchItem(
|
||||
}
|
||||
label={
|
||||
<>
|
||||
<div class="amount">${item.reference.amount}</div>
|
||||
<div class="amount">{item.reference.formatted_amount}</div>
|
||||
<CreditNoteUniversalSearchStatus receipt={item.reference} />
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -83,13 +83,13 @@ export function InvoiceUniversalSearchItem(
|
||||
<span class="bp4-text-muted">
|
||||
{highlightText(item.reference.invoice_no, query)}{' '}
|
||||
<Icon icon={'caret-right-16'} iconSize={16} />
|
||||
{item.reference.formatted_invoice_date}
|
||||
{item.reference.invoice_date_formatted}
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
label={
|
||||
<>
|
||||
<div class="amount">${item.reference.balance}</div>
|
||||
<div class="amount">{item.reference.total_formatted}</div>
|
||||
<InvoiceStatus customer={item.reference} />
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ export function ReceiptUniversalSearchItem(
|
||||
}
|
||||
label={
|
||||
<>
|
||||
<div class="amount">${item.reference.amount}</div>
|
||||
<div class="amount">{item.reference.formatted_amount}</div>
|
||||
<ReceiptStatus receipt={item.reference} />
|
||||
</>
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ const VendorUniversalSearchSelectAction = withDrawerActions(
|
||||
const vendorToSearch = (contact) => ({
|
||||
id: contact.id,
|
||||
text: contact.display_name,
|
||||
label: contact.balance > 0 ? contact.formatted_balance + '' : '',
|
||||
label: contact.formatted_balance,
|
||||
reference: contact,
|
||||
});
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ const commonInvalidateQueries = (queryClient) => {
|
||||
// Invalidate financial reports.
|
||||
queryClient.invalidateQueries(t.FINANCIAL_REPORT);
|
||||
|
||||
// Invalidate the transactions by reference.
|
||||
queryClient.invalidateQueries(t.TRANSACTIONS_BY_REFERENCE);
|
||||
|
||||
// Invalidate items associated bills transactions.
|
||||
queryClient.invalidateQueries(t.ITEMS_ASSOCIATED_WITH_BILLS);
|
||||
|
||||
|
||||
@@ -44,6 +44,9 @@ const commonInvalidateQueries = (queryClient) => {
|
||||
// Invalidate financial reports.
|
||||
queryClient.invalidateQueries(t.FINANCIAL_REPORT);
|
||||
|
||||
// Invalidate transactions by reference.
|
||||
queryClient.invalidateQueries(t.TRANSACTIONS_BY_REFERENCE);
|
||||
|
||||
// Invalidate mutate base currency abilities.
|
||||
queryClient.invalidateQueries(t.ORGANIZATION_MUTATE_BASE_CURRENCY_ABILITIES);
|
||||
};
|
||||
|
||||
@@ -1,34 +1,36 @@
|
||||
// @ts-nocheck
|
||||
import { useQuery } from 'react-query';
|
||||
import QUERY_TYPES from './types';
|
||||
import useApiRequest from '../useRequest';
|
||||
|
||||
function getRandomItemFromArray(arr) {
|
||||
const randomIndex = Math.floor(Math.random() * arr.length);
|
||||
return arr[randomIndex];
|
||||
}
|
||||
function delay(t, val) {
|
||||
return new Promise((resolve) => setTimeout(resolve, t, val));
|
||||
interface LatestExchangeRateQuery {
|
||||
fromCurrency?: string;
|
||||
toCurrency?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves tax rates.
|
||||
* Retrieves latest exchange rate.
|
||||
* @param {number} customerId - Customer id.
|
||||
*/
|
||||
export function useExchangeRate(
|
||||
fromCurrency: string,
|
||||
toCurrency: string,
|
||||
export function useLatestExchangeRate(
|
||||
{ toCurrency, fromCurrency }: LatestExchangeRateQuery,
|
||||
props,
|
||||
) {
|
||||
return useQuery(
|
||||
[QUERY_TYPES.EXCHANGE_RATE, fromCurrency, toCurrency],
|
||||
async () => {
|
||||
await delay(100);
|
||||
const apiRequest = useApiRequest();
|
||||
|
||||
return {
|
||||
from_currency: fromCurrency,
|
||||
to_currency: toCurrency,
|
||||
exchange_rate: 1.00,
|
||||
};
|
||||
},
|
||||
return useQuery(
|
||||
[QUERY_TYPES.EXCHANGE_RATE, toCurrency, fromCurrency],
|
||||
() =>
|
||||
apiRequest
|
||||
.http({
|
||||
url: `/api/exchange_rates/latest`,
|
||||
method: 'get',
|
||||
params: {
|
||||
to_currency: toCurrency,
|
||||
from_currency: fromCurrency,
|
||||
},
|
||||
})
|
||||
.then((res) => res.data),
|
||||
props,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -426,20 +426,58 @@ export function usePurchasesByItems(query, props) {
|
||||
params: query,
|
||||
},
|
||||
{
|
||||
select: (res) => ({
|
||||
tableRows: purchasesByItemsReducer(res.data.data),
|
||||
...res.data,
|
||||
}),
|
||||
defaultData: {
|
||||
tableRows: [],
|
||||
data: [],
|
||||
query: {},
|
||||
},
|
||||
select: (res) => res.data,
|
||||
...props,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function usePurchasesByItemsTable(query, props) {
|
||||
return useRequestQuery(
|
||||
[t.FINANCIAL_REPORT, t.PURCHASES_BY_ITEMS, query],
|
||||
{
|
||||
method: 'get',
|
||||
url: '/financial_statements/purchases-by-items',
|
||||
params: query,
|
||||
headers: {
|
||||
accept: 'application/json+table',
|
||||
},
|
||||
},
|
||||
{
|
||||
select: (res) => res.data,
|
||||
...props,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export const usePurchasesByItemsCsvExport = (query, args) => {
|
||||
return useDownloadFile({
|
||||
url: '/financial_statements/purchases-by-items',
|
||||
config: {
|
||||
headers: {
|
||||
accept: 'application/csv',
|
||||
},
|
||||
params: query,
|
||||
},
|
||||
filename: 'purchases_by_items.csv',
|
||||
...args,
|
||||
});
|
||||
};
|
||||
|
||||
export const usePurchasesByItemsXlsxExport = (query, args) => {
|
||||
return useDownloadFile({
|
||||
url: '/financial_statements/purchases-by-items',
|
||||
config: {
|
||||
headers: {
|
||||
accept: 'application/xlsx',
|
||||
},
|
||||
params: query,
|
||||
},
|
||||
filename: 'purchases_by_items.xlsx',
|
||||
...args,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieve sales by items.
|
||||
*/
|
||||
|
||||
@@ -24,6 +24,9 @@ const commonInvalidateQueries = (queryClient) => {
|
||||
|
||||
// Invalidate financial reports.
|
||||
queryClient.invalidateQueries(t.FINANCIAL_REPORT);
|
||||
|
||||
// Invalidate transactions by reference.
|
||||
queryClient.invalidateQueries(t.TRANSACTIONS_BY_REFERENCE);
|
||||
|
||||
// Invalidate accounts.
|
||||
queryClient.invalidateQueries(t.ACCOUNTS);
|
||||
|
||||
@@ -24,6 +24,9 @@ const commonInvalidateQueries = (client) => {
|
||||
// Invalidate financial reports.
|
||||
client.invalidateQueries(t.FINANCIAL_REPORT);
|
||||
|
||||
// Invalidate transactions by reference.
|
||||
client.invalidateQueries(t.TRANSACTIONS_BY_REFERENCE);
|
||||
|
||||
// Invalidate customers.
|
||||
client.invalidateQueries(t.CUSTOMERS);
|
||||
client.invalidateQueries(t.CUSTOMER);
|
||||
|
||||
@@ -21,6 +21,9 @@ const commonInvalidateQueries = (queryClient) => {
|
||||
// Invalidate financial reports.
|
||||
queryClient.invalidateQueries(t.FINANCIAL_REPORT);
|
||||
|
||||
// Invalidate the transactions by reference.
|
||||
queryClient.invalidateQueries(t.TRANSACTIONS_BY_REFERENCE);
|
||||
|
||||
// Invalidate the cashflow transactions.
|
||||
queryClient.invalidateQueries(t.CASH_FLOW_TRANSACTIONS);
|
||||
queryClient.invalidateQueries(t.CASHFLOW_ACCOUNT_TRANSACTIONS_INFINITY);
|
||||
|
||||
@@ -43,6 +43,9 @@ const commonInvalidateQueries = (queryClient) => {
|
||||
// Invalidate financial reports.
|
||||
queryClient.invalidateQueries(t.FINANCIAL_REPORT);
|
||||
|
||||
// Invalidate the transactions by reference.
|
||||
queryClient.invalidateQueries(t.TRANSACTIONS_BY_REFERENCE);
|
||||
|
||||
// Invalidate mutate base currency abilities.
|
||||
queryClient.invalidateQueries(t.ORGANIZATION_MUTATE_BASE_CURRENCY_ABILITIES);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user