mirror of
https://github.com/bigcapitalhq/bigcapital.git
synced 2026-02-14 03:40:31 +00:00
Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b77bda77f | ||
|
|
ba387e81f7 | ||
|
|
0414c090ea | ||
|
|
a52f3a933f | ||
|
|
d01eacf8d9 | ||
|
|
0da151faaa | ||
|
|
f93c8b46dc | ||
|
|
59c5c8979d | ||
|
|
74a07847a4 | ||
|
|
1740226294 | ||
|
|
1b20d1b073 | ||
|
|
ac7175d83b | ||
|
|
d72d8e60d6 | ||
|
|
de5920f910 | ||
|
|
475c4e9967 | ||
|
|
21eb88ef53 | ||
|
|
429159acf9 | ||
|
|
7eb84474a5 | ||
|
|
e42adcae63 | ||
|
|
abffdd1029 | ||
|
|
d052c23560 | ||
|
|
f02afd3c9f | ||
|
|
3df17390e2 | ||
|
|
df38f8893d | ||
|
|
8882bc677e | ||
|
|
f03d01113c | ||
|
|
8f431597d9 | ||
|
|
03bc78a068 | ||
|
|
ecf5d60db0 | ||
|
|
3a5fd2782a | ||
|
|
1d8416ebfe | ||
|
|
3672abe7a5 | ||
|
|
2753908b83 | ||
|
|
8495990ec2 | ||
|
|
471ce1b7af | ||
|
|
4a920176f4 | ||
|
|
74fd76ce77 | ||
|
|
c9f57d9a75 |
@@ -87,6 +87,24 @@
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "xprnio",
|
||||
"name": "Ragnar Laud",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/3042904?v=4",
|
||||
"profile": "https://ragnarlaud.dev",
|
||||
"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,
|
||||
|
||||
10
.env.example
10
.env.example
@@ -56,5 +56,11 @@ GOTENBERG_URL=http://gotenberg:3000
|
||||
GOTENBERG_DOCS_URL=http://server:3000/public/
|
||||
|
||||
# Gotenberg API - (development)
|
||||
# GOTENBERG_URL=http://gotenberg:3000
|
||||
# GOTENBERG_DOCS_URL=http://server:3000/public/
|
||||
# GOTENBERG_URL=http://localhost:9000
|
||||
# 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=
|
||||
20
CHANGELOG.md
20
CHANGELOG.md
@@ -2,6 +2,26 @@
|
||||
|
||||
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
|
||||
* docs: add ANasouf as a contributor for code by @allcontributors in https://github.com/bigcapitalhq/bigcapital/pull/305
|
||||
* feat: Export general ledger & Journal to CSV and XLSX by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/303
|
||||
* feat: Auto re-calculate the items rate once changing the invoice exchange rate. by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/270
|
||||
|
||||
## [0.13.0] - 31-12-2023
|
||||
|
||||
* feat: Send an invoice mail the customer email by @abouolia in https://github.com/bigcapitalhq/bigcapital/pull/292
|
||||
|
||||
@@ -116,6 +116,8 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
|
||||
<tr>
|
||||
<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',
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,14 +3,15 @@ import { query, ValidationChain } from 'express-validator';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
|
||||
import BaseFinancialReportController from './BaseFinancialReportController';
|
||||
import InventoryValuationService from '@/services/FinancialStatements/InventoryValuationSheet/InventoryValuationSheetService';
|
||||
import { AbilitySubject, ReportsAction } from '@/interfaces';
|
||||
import CheckPolicies from '@/api/middleware/CheckPolicies';
|
||||
import { InventoryValuationSheetApplication } from '@/services/FinancialStatements/InventoryValuationSheet/InventoryValuationSheetApplication';
|
||||
import { ACCEPT_TYPE } from '@/interfaces/Http';
|
||||
|
||||
@Service()
|
||||
export default class InventoryValuationReportController extends BaseFinancialReportController {
|
||||
@Inject()
|
||||
inventoryValuationService: InventoryValuationService;
|
||||
private inventoryValuationApp: InventoryValuationSheetApplication;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
@@ -71,19 +72,45 @@ export default class InventoryValuationReportController extends BaseFinancialRep
|
||||
const { tenantId } = req;
|
||||
const filter = this.matchedQueryData(req);
|
||||
|
||||
try {
|
||||
const { data, query, meta } =
|
||||
await this.inventoryValuationService.inventoryValuationSheet(
|
||||
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,
|
||||
]);
|
||||
|
||||
// Retrieves the json table format.
|
||||
if (ACCEPT_TYPE.APPLICATION_JSON_TABLE === acceptType) {
|
||||
const table = await this.inventoryValuationApp.table(tenantId, filter);
|
||||
|
||||
return res.status(200).send(table);
|
||||
// Retrieves the csv format.
|
||||
} else if (ACCEPT_TYPE.APPLICATION_CSV == acceptType) {
|
||||
const buffer = await this.inventoryValuationApp.csv(tenantId, filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
|
||||
return res.send(buffer);
|
||||
// Retrieves the xslx buffer format.
|
||||
} else if (ACCEPT_TYPE.APPLICATION_XLSX === acceptType) {
|
||||
const buffer = await this.inventoryValuationApp.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);
|
||||
// Retrieves the json format.
|
||||
} else {
|
||||
const { data, query, meta } = await this.inventoryValuationApp.sheet(
|
||||
tenantId,
|
||||
filter
|
||||
);
|
||||
return res.status(200).send({ meta, data, query });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
import { Router, Request, Response, NextFunction } from 'express';
|
||||
import { query, ValidationChain } from 'express-validator';
|
||||
import moment from 'moment';
|
||||
import { query, ValidationChain, ValidationSchema } from 'express-validator';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import asyncMiddleware from '@/api/middleware/asyncMiddleware';
|
||||
import BaseFinancialReportController from './BaseFinancialReportController';
|
||||
import SalesByItemsReportService from '@/services/FinancialStatements/SalesByItems/SalesByItemsService';
|
||||
import { AbilitySubject, ReportsAction } from '@/interfaces';
|
||||
import CheckPolicies from '@/api/middleware/CheckPolicies';
|
||||
import { ACCEPT_TYPE } from '@/interfaces/Http';
|
||||
import { SalesByItemsApplication } from '@/services/FinancialStatements/SalesByItems/SalesByItemsApplication';
|
||||
|
||||
@Service()
|
||||
export default class SalesByItemsReportController extends BaseFinancialReportController {
|
||||
@Inject()
|
||||
salesByItemsService: SalesByItemsReportService;
|
||||
salesByItemsApp: SalesByItemsApplication;
|
||||
|
||||
/**
|
||||
* Router constructor.
|
||||
@@ -24,13 +24,14 @@ export default class SalesByItemsReportController extends BaseFinancialReportCon
|
||||
CheckPolicies(ReportsAction.READ_SALES_BY_ITEMS, AbilitySubject.Report),
|
||||
this.validationSchema,
|
||||
this.validationResult,
|
||||
asyncMiddleware(this.purchasesByItems.bind(this))
|
||||
asyncMiddleware(this.salesByItems.bind(this))
|
||||
);
|
||||
return router;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validation schema.
|
||||
* @returns {ValidationChain[]}
|
||||
*/
|
||||
private get validationSchema(): ValidationChain[] {
|
||||
return [
|
||||
@@ -60,26 +61,44 @@ export default class SalesByItemsReportController extends BaseFinancialReportCon
|
||||
* @param {Request} req -
|
||||
* @param {Response} res -
|
||||
*/
|
||||
private async purchasesByItems(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
private async salesByItems(req: Request, res: Response, next: NextFunction) {
|
||||
const { tenantId } = req;
|
||||
const filter = this.matchedQueryData(req);
|
||||
const accept = this.accepts(req);
|
||||
|
||||
try {
|
||||
const { data, query, meta } = await this.salesByItemsService.salesByItems(
|
||||
tenantId,
|
||||
filter
|
||||
const acceptType = accept.types([
|
||||
ACCEPT_TYPE.APPLICATION_JSON,
|
||||
ACCEPT_TYPE.APPLICATION_JSON_TABLE,
|
||||
ACCEPT_TYPE.APPLICATION_CSV,
|
||||
ACCEPT_TYPE.APPLICATION_XLSX,
|
||||
]);
|
||||
// Retrieves the csv format.
|
||||
if (ACCEPT_TYPE.APPLICATION_CSV === acceptType) {
|
||||
const buffer = await this.salesByItemsApp.csv(tenantId, filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.csv');
|
||||
res.setHeader('Content-Type', 'text/csv');
|
||||
|
||||
return res.send(buffer);
|
||||
// Retrieves the json table format.
|
||||
} else if (ACCEPT_TYPE.APPLICATION_JSON_TABLE === acceptType) {
|
||||
const table = await this.salesByItemsApp.table(tenantId, filter);
|
||||
|
||||
return res.status(200).send(table);
|
||||
// Retrieves the xlsx format.
|
||||
} else if (ACCEPT_TYPE.APPLICATION_XLSX === acceptType) {
|
||||
const buffer = this.salesByItemsApp.xlsx(tenantId, filter);
|
||||
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=output.xlsx');
|
||||
res.setHeader(
|
||||
'Content-Type',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
);
|
||||
return res.status(200).send({
|
||||
meta: this.transfromToResponse(meta),
|
||||
data: this.transfromToResponse(data),
|
||||
query: this.transfromToResponse(query),
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
return res.send(buffer);
|
||||
// Retrieves the json format.
|
||||
} else {
|
||||
const sheet = await this.salesByItemsApp.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.',
|
||||
@@ -418,43 +414,35 @@ export default class SaleInvoicesController extends BaseController {
|
||||
* @param {Request} req - Request object.
|
||||
* @param {Response} res - Response object.
|
||||
*/
|
||||
private async getSaleInvoice(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
) {
|
||||
private async getSaleInvoice(req: Request, res: Response) {
|
||||
const { id: saleInvoiceId } = req.params;
|
||||
const { tenantId, user } = req;
|
||||
|
||||
try {
|
||||
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
|
||||
);
|
||||
// Response formatter.
|
||||
res.format({
|
||||
// JSON content type.
|
||||
[ACCEPT_TYPE.APPLICATION_JSON]: () => {
|
||||
return res
|
||||
.status(200)
|
||||
.send(this.transfromToResponse({ saleInvoice }));
|
||||
},
|
||||
// PDF content type.
|
||||
[ACCEPT_TYPE.APPLICATION_PDF]: async () => {
|
||||
const pdfContent = await this.saleInvoiceApplication.saleInvoicePdf(
|
||||
tenantId,
|
||||
saleInvoice
|
||||
);
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Length': pdfContent.length,
|
||||
});
|
||||
res.send(pdfContent);
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
return res.status(200).send({ saleInvoice });
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -477,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);
|
||||
}
|
||||
@@ -511,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);
|
||||
}
|
||||
@@ -541,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;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { INumberFormatQuery } from './FinancialStatements';
|
||||
import { IFinancialTable } from './Table';
|
||||
|
||||
export interface IInventoryValuationReportQuery {
|
||||
asDate: Date | string;
|
||||
@@ -39,9 +40,19 @@ export interface IInventoryValuationTotal {
|
||||
quantityFormatted: string;
|
||||
}
|
||||
|
||||
export type IInventoryValuationStatement =
|
||||
| {
|
||||
items: IInventoryValuationItem[];
|
||||
total: IInventoryValuationTotal;
|
||||
}
|
||||
| {};
|
||||
export type IInventoryValuationStatement = {
|
||||
items: IInventoryValuationItem[];
|
||||
total: IInventoryValuationTotal;
|
||||
};
|
||||
export type IInventoryValuationSheetData = IInventoryValuationStatement;
|
||||
|
||||
export interface IInventoryValuationSheet {
|
||||
data: IInventoryValuationStatement;
|
||||
meta: IInventoryValuationSheetMeta;
|
||||
query: IInventoryValuationReportQuery;
|
||||
}
|
||||
|
||||
export interface IInventoryValuationTable extends IFinancialTable {
|
||||
meta: IInventoryValuationSheetMeta;
|
||||
query: IInventoryValuationReportQuery;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,45 +1,54 @@
|
||||
import {
|
||||
INumberFormatQuery,
|
||||
} from './FinancialStatements';
|
||||
import { INumberFormatQuery } from './FinancialStatements';
|
||||
import { IFinancialTable } from './Table';
|
||||
|
||||
export interface ISalesByItemsReportQuery {
|
||||
fromDate: Date | string;
|
||||
toDate: Date | string;
|
||||
itemsIds: number[],
|
||||
itemsIds: number[];
|
||||
numberFormat: INumberFormatQuery;
|
||||
noneTransactions: boolean;
|
||||
onlyActive: boolean;
|
||||
};
|
||||
onlyActive: boolean;
|
||||
}
|
||||
|
||||
export interface ISalesByItemsSheetMeta {
|
||||
organizationName: string,
|
||||
baseCurrency: string,
|
||||
};
|
||||
organizationName: string;
|
||||
baseCurrency: string;
|
||||
}
|
||||
|
||||
export interface ISalesByItemsItem {
|
||||
id: number,
|
||||
name: string,
|
||||
code: string,
|
||||
quantitySold: number,
|
||||
soldCost: number,
|
||||
averageSellPrice: number,
|
||||
id: number;
|
||||
name: string;
|
||||
code: string;
|
||||
quantitySold: number;
|
||||
soldCost: number;
|
||||
averageSellPrice: number;
|
||||
|
||||
quantitySoldFormatted: string,
|
||||
soldCostFormatted: string,
|
||||
averageSellPriceFormatted: string,
|
||||
currencyCode: string,
|
||||
};
|
||||
quantitySoldFormatted: string;
|
||||
soldCostFormatted: string;
|
||||
averageSellPriceFormatted: string;
|
||||
currencyCode: string;
|
||||
}
|
||||
|
||||
export interface ISalesByItemsTotal {
|
||||
quantitySold: number,
|
||||
soldCost: number,
|
||||
quantitySoldFormatted: string,
|
||||
soldCostFormatted: string,
|
||||
currencyCode: string,
|
||||
quantitySold: number;
|
||||
soldCost: number;
|
||||
quantitySoldFormatted: string;
|
||||
soldCostFormatted: string;
|
||||
currencyCode: string;
|
||||
}
|
||||
|
||||
export type ISalesByItemsSheetData = {
|
||||
items: ISalesByItemsItem[];
|
||||
total: ISalesByItemsTotal;
|
||||
};
|
||||
|
||||
export type ISalesByItemsSheetStatement = {
|
||||
items: ISalesByItemsItem[],
|
||||
total: ISalesByItemsTotal
|
||||
} | {};
|
||||
export interface ISalesByItemsSheet {
|
||||
data: ISalesByItemsSheetData;
|
||||
query: ISalesByItemsReportQuery;
|
||||
meta: ISalesByItemsSheetMeta;
|
||||
}
|
||||
|
||||
export interface ISalesByItemsTable extends IFinancialTable {
|
||||
query: ISalesByItemsReportQuery;
|
||||
meta: ISalesByItemsSheetMeta;
|
||||
}
|
||||
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';
|
||||
@@ -7,8 +7,12 @@ import {
|
||||
} from '@/services/Cashflow/utils';
|
||||
import AccountTransaction from './AccountTransaction';
|
||||
import { CASHFLOW_DIRECTION } from '@/services/Cashflow/constants';
|
||||
|
||||
import { getTransactionTypeLabel } from '@/utils/transactions-types';
|
||||
export default class CashflowTransaction extends TenantModel {
|
||||
transactionType: string;
|
||||
amount: number;
|
||||
exchangeRate: number;
|
||||
|
||||
/**
|
||||
* Table name.
|
||||
*/
|
||||
@@ -55,9 +59,10 @@ export default class CashflowTransaction extends TenantModel {
|
||||
|
||||
/**
|
||||
* Transaction type formatted.
|
||||
* @returns {string}
|
||||
*/
|
||||
get transactionTypeFormatted() {
|
||||
return AccountTransaction.getReferenceTypeFormatted(this.transactionType);
|
||||
return getTransactionTypeLabel(this.transactionType);
|
||||
}
|
||||
|
||||
get typeMeta() {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
} from '@/interfaces';
|
||||
import { allPassedConditionsPass, transformToMap } from 'utils';
|
||||
|
||||
export default class InventoryValuationSheet extends FinancialSheet {
|
||||
export class InventoryValuationSheet extends FinancialSheet {
|
||||
readonly query: IInventoryValuationReportQuery;
|
||||
readonly items: IItem[];
|
||||
readonly INInventoryCostLots: Map<number, InventoryCostLotTracker>;
|
||||
@@ -259,6 +259,6 @@ export default class InventoryValuationSheet extends FinancialSheet {
|
||||
const items = this.itemsSection();
|
||||
const total = this.totalSection(items);
|
||||
|
||||
return items.length > 0 ? { items, total } : {};
|
||||
return { items, total };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
IInventoryValuationReportQuery,
|
||||
IInventoryValuationSheet,
|
||||
IInventoryValuationTable,
|
||||
} from '@/interfaces';
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { InventoryValuationSheetService } from './InventoryValuationSheetService';
|
||||
import { InventoryValuationSheetTableInjectable } from './InventoryValuationSheetTableInjectable';
|
||||
import { InventoryValuationSheetExportable } from './InventoryValuationSheetExportable';
|
||||
|
||||
@Service()
|
||||
export class InventoryValuationSheetApplication {
|
||||
@Inject()
|
||||
private inventoryValuationSheet: InventoryValuationSheetService;
|
||||
|
||||
@Inject()
|
||||
private inventoryValuationTable: InventoryValuationSheetTableInjectable;
|
||||
|
||||
@Inject()
|
||||
private inventoryValuationExport: InventoryValuationSheetExportable;
|
||||
|
||||
/**
|
||||
* Retrieves the inventory valuation json format.
|
||||
* @param {number} tenantId
|
||||
* @param {IInventoryValuationReportQuery} query
|
||||
* @returns
|
||||
*/
|
||||
public sheet(
|
||||
tenantId: number,
|
||||
query: IInventoryValuationReportQuery
|
||||
): Promise<IInventoryValuationSheet> {
|
||||
return this.inventoryValuationSheet.inventoryValuationSheet(
|
||||
tenantId,
|
||||
query
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the inventory valuation json table format.
|
||||
* @param {number} tenantId
|
||||
* @param {IInventoryValuationReportQuery} query
|
||||
* @returns {Promise<IInventoryValuationTable>}
|
||||
*/
|
||||
public table(
|
||||
tenantId: number,
|
||||
query: IInventoryValuationReportQuery
|
||||
): Promise<IInventoryValuationTable> {
|
||||
return this.inventoryValuationTable.table(tenantId, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the inventory valuation xlsx format.
|
||||
* @param {number} tenantId
|
||||
* @param {IInventoryValuationReportQuery} query
|
||||
* @returns
|
||||
*/
|
||||
public xlsx(
|
||||
tenantId: number,
|
||||
query: IInventoryValuationReportQuery
|
||||
): Promise<Buffer> {
|
||||
return this.inventoryValuationExport.xlsx(tenantId, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the inventory valuation csv format.
|
||||
* @param {number} tenantId
|
||||
* @param {IInventoryValuationReportQuery} query
|
||||
* @returns
|
||||
*/
|
||||
public csv(
|
||||
tenantId: number,
|
||||
query: IInventoryValuationReportQuery
|
||||
): Promise<string> {
|
||||
return this.inventoryValuationExport.csv(tenantId, query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { IInventoryValuationReportQuery } from '@/interfaces';
|
||||
import { InventoryValuationSheetTableInjectable } from './InventoryValuationSheetTableInjectable';
|
||||
import { TableSheet } from '@/lib/Xlsx/TableSheet';
|
||||
|
||||
@Service()
|
||||
export class InventoryValuationSheetExportable {
|
||||
@Inject()
|
||||
private inventoryValuationTable: InventoryValuationSheetTableInjectable;
|
||||
|
||||
/**
|
||||
* Retrieves the trial balance sheet in XLSX format.
|
||||
* @param {number} tenantId
|
||||
* @param {IInventoryValuationReportQuery} query
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
public async xlsx(
|
||||
tenantId: number,
|
||||
query: IInventoryValuationReportQuery
|
||||
): Promise<Buffer> {
|
||||
const table = await this.inventoryValuationTable.table(tenantId, query);
|
||||
|
||||
const tableSheet = new TableSheet(table.table);
|
||||
const tableCsv = tableSheet.convertToXLSX();
|
||||
|
||||
return tableSheet.convertToBuffer(tableCsv, 'xlsx');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the trial balance sheet in CSV format.
|
||||
* @param {number} tenantId
|
||||
* @param {IInventoryValuationReportQuery} query
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
public async csv(
|
||||
tenantId: number,
|
||||
query: IInventoryValuationReportQuery
|
||||
): Promise<string> {
|
||||
const table = await this.inventoryValuationTable.table(tenantId, query);
|
||||
|
||||
const tableSheet = new TableSheet(table.table);
|
||||
const tableCsv = tableSheet.convertToCSV();
|
||||
|
||||
return tableCsv;
|
||||
}
|
||||
}
|
||||
@@ -3,15 +3,16 @@ import moment from 'moment';
|
||||
import { isEmpty } from 'lodash';
|
||||
import {
|
||||
IInventoryValuationReportQuery,
|
||||
IInventoryValuationSheet,
|
||||
IInventoryValuationSheetMeta,
|
||||
} from '@/interfaces';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import InventoryValuationSheet from './InventoryValuationSheet';
|
||||
import { InventoryValuationSheet } from './InventoryValuationSheet';
|
||||
import InventoryService from '@/services/Inventory/Inventory';
|
||||
import { Tenant } from '@/system/models';
|
||||
|
||||
@Service()
|
||||
export default class InventoryValuationSheetService {
|
||||
export class InventoryValuationSheetService {
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
@@ -80,7 +81,7 @@ export default class InventoryValuationSheetService {
|
||||
public async inventoryValuationSheet(
|
||||
tenantId: number,
|
||||
query: IInventoryValuationReportQuery
|
||||
) {
|
||||
): Promise<IInventoryValuationSheet> {
|
||||
const { Item, InventoryCostLotTracker } = this.tenancy.models(tenantId);
|
||||
|
||||
const tenant = await Tenant.query()
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import * as R from 'ramda';
|
||||
import {
|
||||
IInventoryValuationItem,
|
||||
IInventoryValuationSheetData,
|
||||
IInventoryValuationTotal,
|
||||
ITableColumn,
|
||||
ITableColumnAccessor,
|
||||
ITableRow,
|
||||
} from '@/interfaces';
|
||||
import { tableRowMapper } from '@/utils';
|
||||
import FinancialSheet from '../FinancialSheet';
|
||||
import { FinancialSheetStructure } from '../FinancialSheetStructure';
|
||||
import { FinancialTable } from '../FinancialTable';
|
||||
import { ROW_TYPE } from './_constants';
|
||||
|
||||
export class InventoryValuationSheetTable extends R.compose(
|
||||
FinancialTable,
|
||||
FinancialSheetStructure
|
||||
)(FinancialSheet) {
|
||||
private readonly data: IInventoryValuationSheetData;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
* @param {IInventoryValuationSheetData} data
|
||||
*/
|
||||
constructor(data: IInventoryValuationSheetData) {
|
||||
super();
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the common columns accessors.
|
||||
* @returns {ITableColumnAccessor}
|
||||
*/
|
||||
private commonColumnsAccessors(): ITableColumnAccessor[] {
|
||||
return [
|
||||
{ key: 'item_name', accessor: 'name' },
|
||||
{ key: 'quantity', accessor: 'quantityFormatted' },
|
||||
{ key: 'valuation', accessor: 'valuationFormatted' },
|
||||
{ key: 'average', accessor: 'averageFormatted' },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps the given total node to table row.
|
||||
* @param {IInventoryValuationTotal} total
|
||||
* @returns {ITableRow}
|
||||
*/
|
||||
private totalRowMapper = (total: IInventoryValuationTotal): ITableRow => {
|
||||
const accessors = this.commonColumnsAccessors();
|
||||
const meta = {
|
||||
rowTypes: [ROW_TYPE.TOTAL],
|
||||
};
|
||||
return tableRowMapper(total, accessors, meta);
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps the given item node to table row.
|
||||
* @param {IInventoryValuationItem} item
|
||||
* @returns {ITableRow}
|
||||
*/
|
||||
private itemRowMapper = (item: IInventoryValuationItem): ITableRow => {
|
||||
const accessors = this.commonColumnsAccessors();
|
||||
const meta = {
|
||||
rowTypes: [ROW_TYPE.ITEM],
|
||||
};
|
||||
return tableRowMapper(item, accessors, meta);
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps the given items nodes to table rowes.
|
||||
* @param {IInventoryValuationItem[]} items
|
||||
* @returns {ITableRow[]}
|
||||
*/
|
||||
private itemsRowsMapper = (items: IInventoryValuationItem[]): ITableRow[] => {
|
||||
return R.map(this.itemRowMapper)(items);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the table rows.
|
||||
* @returns {ITableRow[]}
|
||||
*/
|
||||
public tableRows(): ITableRow[] {
|
||||
const itemsRows = this.itemsRowsMapper(this.data.items);
|
||||
const totalRow = this.totalRowMapper(this.data.total);
|
||||
|
||||
return R.compose(
|
||||
R.when(R.always(R.not(R.isEmpty(itemsRows))), R.append(totalRow))
|
||||
)([...itemsRows]) as ITableRow[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the table columns.
|
||||
* @returns {ITableColumn[]}
|
||||
*/
|
||||
public tableColumns(): ITableColumn[] {
|
||||
const columns = [
|
||||
{ key: 'item_name', label: 'Item Name' },
|
||||
{ key: 'quantity', label: 'Quantity' },
|
||||
{ key: 'valuation', label: 'Valuation' },
|
||||
{ key: 'average', label: 'Average' },
|
||||
];
|
||||
return R.compose(this.tableColumnsCellIndexing)(columns);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { InventoryValuationSheetService } from './InventoryValuationSheetService';
|
||||
import {
|
||||
IInventoryValuationReportQuery,
|
||||
IInventoryValuationTable,
|
||||
} from '@/interfaces';
|
||||
import { InventoryValuationSheetTable } from './InventoryValuationSheetTable';
|
||||
|
||||
@Service()
|
||||
export class InventoryValuationSheetTableInjectable {
|
||||
@Inject()
|
||||
private sheet: InventoryValuationSheetService;
|
||||
|
||||
/**
|
||||
* Retrieves the inventory valuation json table format.
|
||||
* @param {number} tenantId -
|
||||
* @param {IInventoryValuationReportQuery} filter -
|
||||
* @returns {Promise<IInventoryValuationTable>}
|
||||
*/
|
||||
public async table(
|
||||
tenantId: number,
|
||||
filter: IInventoryValuationReportQuery
|
||||
): Promise<IInventoryValuationTable> {
|
||||
const { data, query, meta } = await this.sheet.inventoryValuationSheet(
|
||||
tenantId,
|
||||
filter
|
||||
);
|
||||
const table = new InventoryValuationSheetTable(data);
|
||||
|
||||
return {
|
||||
table: {
|
||||
columns: table.tableColumns(),
|
||||
rows: table.tableRows(),
|
||||
},
|
||||
query,
|
||||
meta,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export enum ROW_TYPE {
|
||||
ITEM = 'ITEM',
|
||||
TOTAL = 'TOTAL',
|
||||
}
|
||||
@@ -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'
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
IAccountTransaction,
|
||||
ISalesByItemsItem,
|
||||
ISalesByItemsTotal,
|
||||
ISalesByItemsSheetStatement,
|
||||
ISalesByItemsSheetData,
|
||||
IItem,
|
||||
} from '@/interfaces';
|
||||
|
||||
@@ -146,7 +146,7 @@ export default class SalesByItemsReport extends FinancialSheet {
|
||||
* @param {IInventoryValuationItem[]} items
|
||||
* @returns {IInventoryValuationTotal}
|
||||
*/
|
||||
totalSection(items: ISalesByItemsItem[]): ISalesByItemsTotal {
|
||||
private totalSection(items: ISalesByItemsItem[]): ISalesByItemsTotal {
|
||||
const quantitySold = sumBy(items, (item) => item.quantitySold);
|
||||
const soldCost = sumBy(items, (item) => item.soldCost);
|
||||
|
||||
@@ -163,12 +163,12 @@ export default class SalesByItemsReport extends FinancialSheet {
|
||||
|
||||
/**
|
||||
* Retrieve the sheet data.
|
||||
* @returns {ISalesByItemsSheetStatement}
|
||||
* @returns {ISalesByItemsSheetData}
|
||||
*/
|
||||
reportData(): ISalesByItemsSheetStatement {
|
||||
public reportData(): ISalesByItemsSheetData {
|
||||
const items = this.itemsSection();
|
||||
const total = this.totalSection(items);
|
||||
|
||||
return items.length > 0 ? { items, total } : {};
|
||||
return { items, total };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import {
|
||||
ISalesByItemsReportQuery,
|
||||
ISalesByItemsSheet,
|
||||
ISalesByItemsSheetData,
|
||||
ISalesByItemsTable,
|
||||
} from '@/interfaces';
|
||||
import { SalesByItemsReportService } from './SalesByItemsService';
|
||||
import { SalesByItemsTableInjectable } from './SalesByItemsTableInjectable';
|
||||
import { SalesByItemsExport } from './SalesByItemsExport';
|
||||
|
||||
@Service()
|
||||
export class SalesByItemsApplication {
|
||||
@Inject()
|
||||
private salesByItemsSheet: SalesByItemsReportService;
|
||||
|
||||
@Inject()
|
||||
private salesByItemsTable: SalesByItemsTableInjectable;
|
||||
|
||||
@Inject()
|
||||
private salesByItemsExport: SalesByItemsExport;
|
||||
|
||||
/**
|
||||
* Retrieves the sales by items report in json format.
|
||||
* @param {number} tenantId
|
||||
* @param {ISalesByItemsReportQuery} filter
|
||||
* @returns {Promise<ISalesByItemsSheetData>}
|
||||
*/
|
||||
public sheet(
|
||||
tenantId: number,
|
||||
filter: ISalesByItemsReportQuery
|
||||
): Promise<ISalesByItemsSheet> {
|
||||
return this.salesByItemsSheet.salesByItems(tenantId, filter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the sales by items report in table format.
|
||||
* @param {number} tenantId
|
||||
* @param {ISalesByItemsReportQuery} filter
|
||||
* @returns {Promise<ISalesByItemsTable>}
|
||||
*/
|
||||
public table(
|
||||
tenantId: number,
|
||||
filter: ISalesByItemsReportQuery
|
||||
): Promise<ISalesByItemsTable> {
|
||||
return this.salesByItemsTable.table(tenantId, filter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the sales by items report in csv format.
|
||||
* @param {number} tenantId
|
||||
* @param {ISalesByItemsReportQuery} filter
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
public csv(
|
||||
tenantId: number,
|
||||
filter: ISalesByItemsReportQuery
|
||||
): Promise<string> {
|
||||
return this.salesByItemsExport.csv(tenantId, filter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the sales by items report in xlsx format.
|
||||
* @param {number} tenantId
|
||||
* @param {ISalesByItemsReportQuery} filter
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
public xlsx(
|
||||
tenantId: number,
|
||||
filter: ISalesByItemsReportQuery
|
||||
): Promise<Buffer> {
|
||||
return this.salesByItemsExport.xlsx(tenantId, filter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { TableSheet } from '@/lib/Xlsx/TableSheet';
|
||||
import { ISalesByItemsReportQuery } from '@/interfaces';
|
||||
import { SalesByItemsTableInjectable } from './SalesByItemsTableInjectable';
|
||||
|
||||
@Service()
|
||||
export class SalesByItemsExport {
|
||||
@Inject()
|
||||
private salesByItemsTable: SalesByItemsTableInjectable;
|
||||
|
||||
/**
|
||||
* Retrieves the trial balance sheet in XLSX format.
|
||||
* @param {number} tenantId
|
||||
* @param {ISalesByItemsReportQuery} query
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
public async xlsx(tenantId: number, query: ISalesByItemsReportQuery) {
|
||||
const table = await this.salesByItemsTable.table(tenantId, query);
|
||||
|
||||
const tableSheet = new TableSheet(table.table);
|
||||
const tableCsv = tableSheet.convertToXLSX();
|
||||
|
||||
return tableSheet.convertToBuffer(tableCsv, 'xlsx');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the trial balance sheet in CSV format.
|
||||
* @param {number} tenantId
|
||||
* @param {ISalesByItemsReportQuery} query
|
||||
* @returns {Promise<Buffer>}
|
||||
*/
|
||||
public async csv(
|
||||
tenantId: number,
|
||||
query: ISalesByItemsReportQuery
|
||||
): Promise<string> {
|
||||
const table = await this.salesByItemsTable.table(tenantId, query);
|
||||
|
||||
const tableSheet = new TableSheet(table.table);
|
||||
const tableCsv = tableSheet.convertToCSV();
|
||||
|
||||
return tableCsv;
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,15 @@ import { Service, Inject } from 'typedi';
|
||||
import moment from 'moment';
|
||||
import {
|
||||
ISalesByItemsReportQuery,
|
||||
ISalesByItemsSheetStatement,
|
||||
ISalesByItemsSheetMeta
|
||||
ISalesByItemsSheetMeta,
|
||||
ISalesByItemsSheet,
|
||||
} from '@/interfaces';
|
||||
import TenancyService from '@/services/Tenancy/TenancyService';
|
||||
import SalesByItems from './SalesByItems';
|
||||
import { Tenant } from '@/system/models';
|
||||
|
||||
@Service()
|
||||
export default class SalesByItemsReportService {
|
||||
export class SalesByItemsReportService {
|
||||
@Inject()
|
||||
tenancy: TenancyService;
|
||||
|
||||
@@ -63,20 +63,14 @@ export default class SalesByItemsReportService {
|
||||
|
||||
/**
|
||||
* Retrieve balance sheet statement.
|
||||
* -------------
|
||||
* @param {number} tenantId
|
||||
* @param {IBalanceSheetQuery} query
|
||||
*
|
||||
* @return {IBalanceSheetStatement}
|
||||
* @return {Promise<ISalesByItemsSheet>}
|
||||
*/
|
||||
public async salesByItems(
|
||||
tenantId: number,
|
||||
query: ISalesByItemsReportQuery
|
||||
): Promise<{
|
||||
data: ISalesByItemsSheetStatement,
|
||||
query: ISalesByItemsReportQuery,
|
||||
meta: ISalesByItemsSheetMeta,
|
||||
}> {
|
||||
): Promise<ISalesByItemsSheet> {
|
||||
const { Item, InventoryTransaction } = this.tenancy.models(tenantId);
|
||||
|
||||
const tenant = await Tenant.query()
|
||||
@@ -107,20 +101,19 @@ export default class SalesByItemsReportService {
|
||||
builder.whereIn('itemId', inventoryItemsIds);
|
||||
|
||||
// Filter the date range of the sheet.
|
||||
builder.modify('filterDateRange', filter.fromDate, filter.toDate)
|
||||
builder.modify('filterDateRange', filter.fromDate, filter.toDate);
|
||||
}
|
||||
);
|
||||
|
||||
const purchasesByItemsInstance = new SalesByItems(
|
||||
const sheet = new SalesByItems(
|
||||
filter,
|
||||
inventoryItems,
|
||||
inventoryTransactions,
|
||||
tenant.metadata.baseCurrency,
|
||||
tenant.metadata.baseCurrency
|
||||
);
|
||||
const purchasesByItemsData = purchasesByItemsInstance.reportData();
|
||||
const salesByItemsData = sheet.reportData();
|
||||
|
||||
return {
|
||||
data: purchasesByItemsData,
|
||||
data: salesByItemsData,
|
||||
query: filter,
|
||||
meta: this.reportMetadata(tenantId),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import * as R from 'ramda';
|
||||
import {
|
||||
ISalesByItemsItem,
|
||||
ISalesByItemsSheetStatement,
|
||||
ISalesByItemsTotal,
|
||||
ITableColumn,
|
||||
ITableRow,
|
||||
} from '@/interfaces';
|
||||
import { tableRowMapper } from '@/utils';
|
||||
import FinancialSheet from '../FinancialSheet';
|
||||
import { FinancialSheetStructure } from '../FinancialSheetStructure';
|
||||
import { FinancialTable } from '../FinancialTable';
|
||||
import { ROW_TYPE } from './constants';
|
||||
|
||||
export class SalesByItemsTable extends R.compose(
|
||||
FinancialTable,
|
||||
FinancialSheetStructure
|
||||
)(FinancialSheet) {
|
||||
private readonly data: ISalesByItemsSheetStatement;
|
||||
|
||||
/**
|
||||
* Constructor method.
|
||||
* @param {ISalesByItemsSheetStatement} data
|
||||
*/
|
||||
constructor(data: ISalesByItemsSheetStatement) {
|
||||
super();
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the common table accessors.
|
||||
* @returns {ITableColumn[]}
|
||||
*/
|
||||
private commonTableAccessors() {
|
||||
return [
|
||||
{ key: 'item_name', accessor: 'name' },
|
||||
{ key: 'sold_quantity', accessor: 'quantitySoldFormatted' },
|
||||
{ key: 'sold_amount', accessor: 'soldCostFormatted' },
|
||||
{ key: 'average_price', accessor: 'averageSellPriceFormatted' },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps the given item node to table row.
|
||||
* @param {ISalesByItemsItem} item
|
||||
* @returns {ITableRow}
|
||||
*/
|
||||
private itemMap = (item: ISalesByItemsItem): 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 {ISalesByItemsItem[]} items
|
||||
* @returns {ITableRow[]}
|
||||
*/
|
||||
private itemsMap = (items: ISalesByItemsItem[]): ITableRow[] => {
|
||||
return R.map(this.itemMap, items);
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps the given total node to table row.
|
||||
* @param {ISalesByItemsTotal} total
|
||||
* @returns {ITableRow[]}
|
||||
*/
|
||||
private totalMap = (total: ISalesByItemsTotal) => {
|
||||
const columns = this.commonTableAccessors();
|
||||
const meta = {
|
||||
rowTypes: [ROW_TYPE.TOTAL],
|
||||
};
|
||||
return tableRowMapper(total, columns, meta);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the table rows.
|
||||
* @returns {ITableRow[]}
|
||||
*/
|
||||
public tableData(): ITableRow[] {
|
||||
const itemsRows = this.itemsMap(this.data.items);
|
||||
const totalRow = this.totalMap(this.data.total);
|
||||
|
||||
return R.compose(
|
||||
R.when(R.always(R.not(R.isEmpty(itemsRows))), R.append(totalRow))
|
||||
)([...itemsRows]) as ITableRow[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the table columns.
|
||||
* @returns {ITableColumn[]}
|
||||
*/
|
||||
public tableColumns(): ITableColumn[] {
|
||||
const columns = [
|
||||
{ key: 'item_name', label: 'Item name' },
|
||||
{ key: 'sold_quantity', label: 'Sold quantity' },
|
||||
{ key: 'sold_amount', label: 'Sold amount' },
|
||||
{ key: 'average_price', label: 'Average price' },
|
||||
];
|
||||
return R.compose(this.tableColumnsCellIndexing)(columns);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ISalesByItemsReportQuery } from '@/interfaces';
|
||||
import { SalesByItemsReportService } from './SalesByItemsService';
|
||||
import { SalesByItemsTable } from './SalesByItemsTable';
|
||||
|
||||
@Service()
|
||||
export class SalesByItemsTableInjectable {
|
||||
@Inject()
|
||||
private salesByItemSheet: SalesByItemsReportService;
|
||||
|
||||
/**
|
||||
* Retrieves the sales by items report in table format.
|
||||
* @param {number} tenantId
|
||||
* @param {ISalesByItemsReportQuery} filter
|
||||
* @returns {Promise<ISalesByItemsTable>}
|
||||
*/
|
||||
public async table(tenantId: number, filter: ISalesByItemsReportQuery) {
|
||||
const { data, query, meta } = await this.salesByItemSheet.salesByItems(
|
||||
tenantId,
|
||||
filter
|
||||
);
|
||||
const table = new SalesByItemsTable(data);
|
||||
|
||||
return {
|
||||
table: {
|
||||
columns: table.tableColumns(),
|
||||
rows: table.tableData(),
|
||||
},
|
||||
meta,
|
||||
query,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
|
||||
|
||||
export enum ROW_TYPE {
|
||||
ITEM = 'ITEM',
|
||||
TOTAL = 'TOTAL',
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { Inject, Service } from 'typedi';
|
||||
import { ChromiumlyTenancy } from '@/services/ChromiumlyTenancy/ChromiumlyTenancy';
|
||||
import { TemplateInjectable } from '@/services/TemplateInjectable/TemplateInjectable';
|
||||
import HasTenancyService from '@/services/Tenancy/TenancyService';
|
||||
import { CommandSaleInvoiceValidators } from './CommandSaleInvoiceValidators';
|
||||
import { GetSaleInvoice } from './GetSaleInvoice';
|
||||
|
||||
@Service()
|
||||
export class SaleInvoicePdf {
|
||||
@@ -13,10 +12,7 @@ export class SaleInvoicePdf {
|
||||
private templateInjectable: TemplateInjectable;
|
||||
|
||||
@Inject()
|
||||
private validators: CommandSaleInvoiceValidators;
|
||||
|
||||
@Inject()
|
||||
private tenancy: HasTenancyService;
|
||||
private getInvoiceService: GetSaleInvoice;
|
||||
|
||||
/**
|
||||
* Retrieve sale invoice pdf content.
|
||||
@@ -28,18 +24,10 @@ export class SaleInvoicePdf {
|
||||
tenantId: number,
|
||||
invoiceId: number
|
||||
): Promise<Buffer> {
|
||||
const { SaleInvoice } = this.tenancy.models(tenantId);
|
||||
|
||||
const saleInvoice = await SaleInvoice.query()
|
||||
.findById(invoiceId)
|
||||
.withGraphFetched('entries.item')
|
||||
.withGraphFetched('entries.tax')
|
||||
.withGraphFetched('customer')
|
||||
.withGraphFetched('taxes.taxRate');
|
||||
|
||||
// Validates the given sale invoice existance.
|
||||
this.validators.validateInvoiceExistance(saleInvoice);
|
||||
|
||||
const saleInvoice = await this.getInvoiceService.getSaleInvoice(
|
||||
tenantId,
|
||||
invoiceId
|
||||
);
|
||||
const htmlContent = await this.templateInjectable.render(
|
||||
tenantId,
|
||||
'modules/invoice-regular',
|
||||
|
||||
@@ -8,7 +8,7 @@ export class PaymentReceiveEntryTransfromer extends Transformer {
|
||||
* @returns {Array}
|
||||
*/
|
||||
public includeAttributes = (): string[] => {
|
||||
return ['paymentAmountFormatted', 'entry'];
|
||||
return ['paymentAmountFormatted', 'invoice'];
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { IPaymentReceive, IPaymentReceiveEntry } from '@/interfaces';
|
||||
import { Transformer } from '@/lib/Transformer/Transformer';
|
||||
import { formatNumber } from 'utils';
|
||||
import { SaleInvoiceTransformer } from '../Invoices/SaleInvoiceTransformer';
|
||||
import { PaymentReceiveEntryTransfromer } from './PaymentReceiveEntryTransformer';
|
||||
|
||||
export class PaymentReceiveTransfromer extends Transformer {
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
@@ -34,7 +34,7 @@ function CustomerSelectRoot({
|
||||
<FSelect
|
||||
items={items}
|
||||
textAccessor={'display_name'}
|
||||
labelAccessor={'currency_code'}
|
||||
labelAccessor={'formatted_balance'}
|
||||
valueAccessor={'id'}
|
||||
popoverProps={{ minimal: true, usePortal: true, inline: false }}
|
||||
createNewItemRenderer={maybeCreateNewItemRenderer}
|
||||
|
||||
@@ -35,7 +35,7 @@ function VendorsSelectRoot({
|
||||
<FSelect
|
||||
items={items}
|
||||
textAccessor={'display_name'}
|
||||
labelAccessor={'code'}
|
||||
labelAccessor={'formatted_balance'}
|
||||
valueAccessor={'id'}
|
||||
popoverProps={{ minimal: true, usePortal: true, inline: false }}
|
||||
createNewItemRenderer={maybeCreateNewItemRenderer}
|
||||
|
||||
@@ -8,7 +8,7 @@ const AccountInactivateAlert = React.lazy(
|
||||
() => import('@/containers/Alerts/Accounts/AccountInactivateAlert'),
|
||||
);
|
||||
const AccountActivateAlert = React.lazy(
|
||||
() => import('@/containers/Alerts/Accounts/AccountDeleteAlert'),
|
||||
() => import('@/containers/Alerts/Accounts/AccountActivateAlert'),
|
||||
);
|
||||
|
||||
export default [
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import { MoneyInDialogProvider } from './MoneyInDialogProvider';
|
||||
import MoneyInForm from './MoneyInForm';
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ function MoneyInForm({
|
||||
};
|
||||
|
||||
// Handles the form submit.
|
||||
const handleFormSubmit = (values, { setSubmitting, setErrors }) => {
|
||||
const handleFormSubmit = (values, { setSubmitting }) => {
|
||||
const form = {
|
||||
...omit(values, ['currency_code']),
|
||||
publish: true,
|
||||
|
||||
@@ -51,7 +51,6 @@ function MoneyOutForm({
|
||||
accountId,
|
||||
accountType,
|
||||
createCashflowTransactionMutate,
|
||||
submitPayload,
|
||||
} = useMoneyOutDialogContext();
|
||||
|
||||
// transaction number.
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useUpdateEffect } from '@/hooks';
|
||||
|
||||
import withSettings from '@/containers/Settings/withSettings';
|
||||
import withDialogActions from '@/containers/Dialog/withDialogActions';
|
||||
import { transactionNumber } from '@/utils';
|
||||
|
||||
/**
|
||||
* Syncs cashflow auto-increment settings to the form once update.
|
||||
|
||||
@@ -9,11 +9,11 @@ import ReferenceNumberForm from '@/containers/JournalNumber/ReferenceNumberForm'
|
||||
import withDialogActions from '@/containers/Dialog/withDialogActions';
|
||||
import withSettings from '@/containers/Settings/withSettings';
|
||||
import withSettingsActions from '@/containers/Settings/withSettingsActions';
|
||||
import { compose } from '@/utils';
|
||||
import {
|
||||
transformFormToSettings,
|
||||
transformSettingsToForm,
|
||||
} from '@/containers/JournalNumber/utils';
|
||||
import { compose } from '@/utils';
|
||||
|
||||
/**
|
||||
* Transaction number dialog content.
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
|
||||
@@ -19,6 +19,7 @@ import withInventoryValuationActions from './withInventoryValuationActions';
|
||||
import { useInventoryValuationContext } from './InventoryValuationProvider';
|
||||
|
||||
import { compose, saveInvoke } from '@/utils';
|
||||
import { InventoryValuationExportMenu } from './components';
|
||||
|
||||
function InventoryValuationActionsBar({
|
||||
// #withInventoryValuation
|
||||
@@ -109,11 +110,18 @@ function InventoryValuationActionsBar({
|
||||
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={<InventoryValuationExportMenu />}
|
||||
interactionKind={PopoverInteractionKind.CLICK}
|
||||
position={Position.BOTTOM_LEFT}
|
||||
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 from 'react';
|
||||
import FinancialReportPage from '../FinancialReportPage';
|
||||
import { useInventoryValuation } from '@/hooks/query';
|
||||
import { useInventoryValuationTable } from '@/hooks/query';
|
||||
import { transformFilterFormToQuery } from '../common';
|
||||
|
||||
const InventoryValuationContext = React.createContext();
|
||||
@@ -21,7 +21,7 @@ function InventoryValuationProvider({ query, ...props }) {
|
||||
isFetching,
|
||||
isLoading,
|
||||
refetch,
|
||||
} = useInventoryValuation(requestQuery, {
|
||||
} = useInventoryValuationTable(requestQuery, {
|
||||
keepPreviousData: true,
|
||||
});
|
||||
|
||||
|
||||
@@ -8,23 +8,23 @@ import { ReportDataTable, FinancialSheet } from '@/components';
|
||||
import { tableRowTypesToClassnames } from '@/utils';
|
||||
|
||||
import { useInventoryValuationContext } from './InventoryValuationProvider';
|
||||
import { useInventoryValuationTableColumns } from './components';
|
||||
import { useInventoryValuationColumns } from './dynamicColumns';
|
||||
|
||||
/**
|
||||
* inventory valuation data table.
|
||||
* Inventory valuation data table.
|
||||
*/
|
||||
export default function InventoryValuationTable({
|
||||
//#ownProps
|
||||
// #ownProps
|
||||
companyName,
|
||||
}) {
|
||||
// inventory valuation context.
|
||||
// Inventory valuation context.
|
||||
const {
|
||||
inventoryValuation: { tableRows, query },
|
||||
inventoryValuation: { table, query },
|
||||
isLoading,
|
||||
} = useInventoryValuationContext();
|
||||
|
||||
// inventory valuation table columns.
|
||||
const columns = useInventoryValuationTableColumns();
|
||||
// Inventory valuation table columns.
|
||||
const columns = useInventoryValuationColumns();
|
||||
|
||||
return (
|
||||
<InventoryValuationSheet
|
||||
@@ -35,7 +35,7 @@ export default function InventoryValuationTable({
|
||||
>
|
||||
<InventoryValuationDataTable
|
||||
columns={columns}
|
||||
data={tableRows}
|
||||
data={table.rows}
|
||||
expandable={true}
|
||||
expandToggleColumn={1}
|
||||
expandColumnSpace={1}
|
||||
@@ -62,7 +62,7 @@ const InventoryValuationDataTable = styled(ReportDataTable)`
|
||||
padding-top: 0.4rem;
|
||||
padding-bottom: 0.4rem;
|
||||
}
|
||||
.tr.row_type--total .td {
|
||||
.tr.row_type--TOTAL .td {
|
||||
border-top: 1px solid #bbb;
|
||||
font-weight: 500;
|
||||
border-bottom: 3px double #000;
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
// @ts-nocheck
|
||||
import React, { useMemo } from 'react';
|
||||
import { useMemo, useRef } from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
|
||||
import { If } from '@/components';
|
||||
import classNames from 'classnames';
|
||||
import { AppToaster, If, Stack } from '@/components';
|
||||
import { Align } from '@/constants';
|
||||
import { getColumnWidth } from '@/utils';
|
||||
import { CellTextSpan } from '@/components/Datatable/Cells';
|
||||
import { useInventoryValuationContext } from './InventoryValuationProvider';
|
||||
import FinancialLoadingBar from '../FinancialLoadingBar';
|
||||
import {
|
||||
Classes,
|
||||
Intent,
|
||||
Menu,
|
||||
MenuItem,
|
||||
ProgressBar,
|
||||
Text,
|
||||
} from '@blueprintjs/core';
|
||||
import {
|
||||
useInventoryValuationCsvExport,
|
||||
useInventoryValuationXlsxExport,
|
||||
} from '@/hooks/query';
|
||||
|
||||
/**
|
||||
* Retrieve inventory valuation table columns.
|
||||
@@ -77,3 +89,87 @@ export function InventoryValuationLoadingBar() {
|
||||
</If>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the inventory valuation sheet export menu.
|
||||
* @returns {JSX.Element}
|
||||
*/
|
||||
export const InventoryValuationExportMenu = () => {
|
||||
const toastKey = useRef(null);
|
||||
const commonToastConfig = {
|
||||
isCloseButtonShown: true,
|
||||
timeout: 2000,
|
||||
};
|
||||
const { query } = useInventoryValuationContext();
|
||||
|
||||
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 } = useInventoryValuationXlsxExport(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 } = useInventoryValuationCsvExport(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,97 @@
|
||||
// @ts-nocheck
|
||||
import { Align } from '@/constants';
|
||||
import { getColumnWidth } from '@/utils';
|
||||
import * as R from 'ramda';
|
||||
import { useInventoryValuationContext } from './InventoryValuationProvider';
|
||||
|
||||
const getTableCellValueAccessor = (index) => `cells[${index}].value`;
|
||||
|
||||
const getReportColWidth = (data, accessor, headerText) => {
|
||||
return getColumnWidth(
|
||||
data,
|
||||
accessor,
|
||||
{ magicSpacing: 10, minWidth: 100 },
|
||||
headerText,
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Common column mapper.
|
||||
*/
|
||||
const commonAccessor = R.curry((data, column) => {
|
||||
const accessor = getTableCellValueAccessor(column.cell_index);
|
||||
|
||||
return {
|
||||
key: column.key,
|
||||
Header: column.label,
|
||||
accessor,
|
||||
className: column.key,
|
||||
textOverview: true,
|
||||
align: Align.Left,
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
* 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: 240,
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Dynamic column mapper.
|
||||
* @param {} data -
|
||||
* @param {} column -
|
||||
*/
|
||||
const dynamicColumnMapper = R.curry((data, column) => {
|
||||
const _commonAccessor = commonAccessor(data);
|
||||
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'), _numericColumnAccessor),
|
||||
R.when(R.pathEq(['key'], 'valuation'), _numericColumnAccessor),
|
||||
R.when(R.pathEq(['key'], 'average'), _numericColumnAccessor),
|
||||
_commonAccessor,
|
||||
)(column);
|
||||
});
|
||||
|
||||
/**
|
||||
* Composes the fetched dynamic columns from the server to the columns to pass it
|
||||
* to the table component.
|
||||
*/
|
||||
export const dynamicColumns = (columns, data) => {
|
||||
return R.map(dynamicColumnMapper(data), columns);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves the table columns of inventory valuation sheet.
|
||||
*/
|
||||
export const useInventoryValuationColumns = () => {
|
||||
const { inventoryValuation } = useInventoryValuationContext();
|
||||
|
||||
if (!inventoryValuation) {
|
||||
throw new Error('The inventory valuation is not loaded');
|
||||
}
|
||||
const { table } = inventoryValuation;
|
||||
|
||||
return dynamicColumns(table.columns, table.rows);
|
||||
};
|
||||
@@ -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);
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
// @ts-nocheck
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import { createContext, useContext } from 'react';
|
||||
import FinancialReportPage from '../FinancialReportPage';
|
||||
import { useSalesByItems } from '@/hooks/query';
|
||||
import { useSalesByItemsTable } from '@/hooks/query';
|
||||
import { transformFilterFormToQuery } from '../common';
|
||||
|
||||
const SalesByItemsContext = createContext();
|
||||
@@ -12,7 +12,7 @@ function SalesByItemProvider({ query, ...props }) {
|
||||
isFetching,
|
||||
isLoading,
|
||||
refetch,
|
||||
} = useSalesByItems(
|
||||
} = useSalesByItemsTable(
|
||||
{
|
||||
...transformFilterFormToQuery(query),
|
||||
},
|
||||
|
||||
@@ -19,6 +19,7 @@ import withSalesByItemsActions from './withSalesByItemsActions';
|
||||
|
||||
import { compose, saveInvoke } from '@/utils';
|
||||
import { useSalesByItemsContext } from './SalesByItemProvider';
|
||||
import { SalesByItemsSheetExportMenu } from './components';
|
||||
|
||||
function SalesByItemsActionsBar({
|
||||
// #withSalesByItems
|
||||
@@ -108,11 +109,18 @@ function SalesByItemsActionsBar({
|
||||
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={<SalesByItemsSheetExportMenu />}
|
||||
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>
|
||||
);
|
||||
|
||||
@@ -5,7 +5,7 @@ import styled from 'styled-components';
|
||||
|
||||
import { ReportDataTable, FinancialSheet } from '@/components';
|
||||
import { useSalesByItemsContext } from './SalesByItemProvider';
|
||||
import { useSalesByItemsTableColumns } from './components';
|
||||
import { useSalesByItemsTableColumns } from './dynamicColumns';
|
||||
import { tableRowTypesToClassnames } from '@/utils';
|
||||
import { TableStyle } from '@/constants';
|
||||
|
||||
@@ -15,7 +15,7 @@ import { TableStyle } from '@/constants';
|
||||
export default function SalesByItemsTable({ companyName }) {
|
||||
// Sales by items context.
|
||||
const {
|
||||
salesByItems: { tableRows, query },
|
||||
salesByItems: { table, query },
|
||||
isLoading,
|
||||
} = useSalesByItemsContext();
|
||||
|
||||
@@ -32,7 +32,7 @@ export default function SalesByItemsTable({ companyName }) {
|
||||
>
|
||||
<SalesByItemsDataTable
|
||||
columns={columns}
|
||||
data={tableRows}
|
||||
data={table.rows}
|
||||
expandable={true}
|
||||
expandToggleColumn={1}
|
||||
expandColumnSpace={1}
|
||||
@@ -59,7 +59,7 @@ const SalesByItemsDataTable = styled(ReportDataTable)`
|
||||
padding-top: 0.4rem;
|
||||
padding-bottom: 0.4rem;
|
||||
}
|
||||
.tr.row_type--total .td {
|
||||
.tr.row_type--TOTAL .td {
|
||||
border-top: 1px solid #bbb;
|
||||
font-weight: 500;
|
||||
border-bottom: 3px double #000;
|
||||
|
||||
@@ -1,70 +1,20 @@
|
||||
// @ts-nocheck
|
||||
import React, { useMemo } from 'react';
|
||||
import { useMemo, useRef } from 'react';
|
||||
import intl from 'react-intl-universal';
|
||||
import classNames from 'classnames';
|
||||
import { Classes } from '@blueprintjs/core';
|
||||
|
||||
import { getColumnWidth } from '@/utils';
|
||||
import { If } from '@/components';
|
||||
import { AppToaster, If, Stack } from '@/components';
|
||||
import { Align } from '@/constants';
|
||||
import { CellTextSpan } from '@/components/Datatable/Cells';
|
||||
import { useSalesByItemsContext } from './SalesByItemProvider';
|
||||
import FinancialLoadingBar from '../FinancialLoadingBar';
|
||||
|
||||
|
||||
/**
|
||||
* Retrieve sales by items table columns.
|
||||
*/
|
||||
export const useSalesByItemsTableColumns = () => {
|
||||
//sales by items context.
|
||||
const {
|
||||
salesByItems: { tableRows },
|
||||
} = useSalesByItemsContext();
|
||||
|
||||
return 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('sold_quantity'),
|
||||
accessor: 'quantity_sold_formatted',
|
||||
Cell: CellTextSpan,
|
||||
className: 'quantity_sold',
|
||||
width: getColumnWidth(tableRows, `quantity_sold_formatted`, {
|
||||
minWidth: 150,
|
||||
}),
|
||||
textOverview: true,
|
||||
align: Align.Right,
|
||||
},
|
||||
{
|
||||
Header: intl.get('sold_amount'),
|
||||
accessor: 'sold_cost_formatted',
|
||||
Cell: CellTextSpan,
|
||||
className: 'sold_cost',
|
||||
width: getColumnWidth(tableRows, `sold_cost_formatted`, {
|
||||
minWidth: 150,
|
||||
}),
|
||||
textOverview: true,
|
||||
align: Align.Right,
|
||||
},
|
||||
{
|
||||
Header: intl.get('average_price'),
|
||||
accessor: 'average_sell_price_formatted',
|
||||
Cell: CellTextSpan,
|
||||
className: 'average_sell_price',
|
||||
width: getColumnWidth(tableRows, `average_sell_price_formatted`, {
|
||||
minWidth: 150,
|
||||
}),
|
||||
textOverview: true,
|
||||
align: Align.Right,
|
||||
},
|
||||
],
|
||||
[tableRows],
|
||||
);
|
||||
};
|
||||
import { Intent, Menu, MenuItem, ProgressBar, Text } from '@blueprintjs/core';
|
||||
import {
|
||||
useSalesByItemsCsvExport,
|
||||
useSalesByItemsXlsxExport,
|
||||
} from '@/hooks/query';
|
||||
|
||||
/**
|
||||
* sales by items progress loading bar.
|
||||
@@ -77,3 +27,88 @@ export function SalesByItemsLoadingBar() {
|
||||
</If>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the sales by items export menu.
|
||||
* @returns {JSX.Element}
|
||||
*/
|
||||
export const SalesByItemsSheetExportMenu = () => {
|
||||
const toastKey = useRef(null);
|
||||
const commonToastConfig = {
|
||||
isCloseButtonShown: true,
|
||||
timeout: 2000,
|
||||
};
|
||||
const { query } = useSalesByItemsContext();
|
||||
|
||||
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 } = useSalesByItemsXlsxExport(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 } = useSalesByItemsCsvExport(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 { useSalesByItemsContext } from './SalesByItemProvider';
|
||||
|
||||
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'], 'sold_quantity'), _numericColumnAccessor),
|
||||
R.when(R.pathEq(['key'], 'sold_amount'), _numericColumnAccessor),
|
||||
R.when(R.pathEq(['key'], 'average_price'), _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 G/L sheet table columns for table component.
|
||||
*/
|
||||
export const useSalesByItemsTableColumns = () => {
|
||||
const { salesByItems } = useSalesByItemsContext();
|
||||
|
||||
if (!salesByItems) {
|
||||
throw new Error('Sales by items context not found');
|
||||
}
|
||||
const { table } = salesByItems;
|
||||
|
||||
return dynamicColumns(table.rows, table.columns);
|
||||
};
|
||||
@@ -1,194 +1,4 @@
|
||||
// @ts-nocheck
|
||||
import React from 'react';
|
||||
import moment from 'moment';
|
||||
import { chain } from 'lodash';
|
||||
import { FormattedMessage as T } from '@/components';
|
||||
|
||||
export const trialBalanceSheetReducer = (sheet) => {
|
||||
const results = [];
|
||||
|
||||
if (sheet.accounts) {
|
||||
sheet.accounts.forEach((account) => {
|
||||
results.push(account);
|
||||
});
|
||||
}
|
||||
if (sheet.total) {
|
||||
results.push({
|
||||
row_types: 'total',
|
||||
...sheet.total,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
};
|
||||
|
||||
|
||||
|
||||
export const journalTableRowsReducer = (journal) => {
|
||||
const TYPES = {
|
||||
ENTRY: 'ENTRY',
|
||||
TOTAL_ENTRIES: 'TOTAL_ENTRIES',
|
||||
EMPTY_ROW: 'EMPTY_ROW',
|
||||
};
|
||||
|
||||
const entriesMapper = (transaction) => {
|
||||
return transaction.entries.map((entry, index) => ({
|
||||
...(index === 0
|
||||
? {
|
||||
date: transaction.date,
|
||||
reference_type: transaction.reference_type,
|
||||
reference_id: transaction.reference_id,
|
||||
reference_type_formatted: transaction.reference_type_formatted,
|
||||
}
|
||||
: {}),
|
||||
row_types: TYPES.ENTRY,
|
||||
...entry,
|
||||
}));
|
||||
};
|
||||
|
||||
return chain(journal)
|
||||
.map((transaction) => {
|
||||
const entries = entriesMapper(transaction);
|
||||
|
||||
return [
|
||||
...entries,
|
||||
{
|
||||
row_types: TYPES.TOTAL_ENTRIES,
|
||||
currency_code: transaction.currency_code,
|
||||
credit: transaction.credit,
|
||||
debit: transaction.debit,
|
||||
formatted_credit: transaction.formatted_credit,
|
||||
formatted_debit: transaction.formatted_debit,
|
||||
},
|
||||
{
|
||||
row_types: TYPES.EMPTY_ROW,
|
||||
},
|
||||
];
|
||||
})
|
||||
.flatten()
|
||||
.value();
|
||||
};
|
||||
|
||||
export const generalLedgerTableRowsReducer = (accounts) => {
|
||||
return chain(accounts)
|
||||
.map((account) => {
|
||||
return {
|
||||
name: '',
|
||||
code: account.code,
|
||||
row_types: 'ACCOUNT_ROW',
|
||||
date: account.name,
|
||||
children: [
|
||||
{
|
||||
...account.opening_balance,
|
||||
name: <T id={'opening_balance'} />,
|
||||
row_types: 'OPENING_BALANCE',
|
||||
date: moment(account.opening_balance.date).format('DD MMM YYYY'),
|
||||
},
|
||||
...account.transactions.map((transaction) => ({
|
||||
...transaction,
|
||||
name: account.name,
|
||||
code: account.code,
|
||||
date: moment(transaction.date).format('DD MMM YYYY'),
|
||||
})),
|
||||
{
|
||||
...account.closing_balance,
|
||||
name: <T id={'closing_balance'} />,
|
||||
row_types: 'CLOSING_BALANCE',
|
||||
date: moment(account.closing_balance.date).format('DD MMM YYYY'),
|
||||
},
|
||||
],
|
||||
amount: account.closing_balance.amount,
|
||||
formatted_amount: account.closing_balance.formatted_amount,
|
||||
};
|
||||
})
|
||||
.value();
|
||||
};
|
||||
|
||||
export const ARAgingSummaryTableRowsMapper = (sheet, total) => {
|
||||
const rows = [];
|
||||
|
||||
const mapAging = (agingPeriods) => {
|
||||
return agingPeriods.reduce((acc, aging, index) => {
|
||||
acc[`aging-${index}`] = aging.total.formatted_amount;
|
||||
return acc;
|
||||
}, {});
|
||||
};
|
||||
sheet.customers.forEach((customer) => {
|
||||
const agingRow = mapAging(customer.aging);
|
||||
|
||||
rows.push({
|
||||
row_types: 'customer',
|
||||
name: customer.customer_name,
|
||||
...agingRow,
|
||||
current: customer.current.formatted_amount,
|
||||
total: customer.total.formatted_amount,
|
||||
});
|
||||
});
|
||||
if (rows.length <= 0) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
...rows,
|
||||
{
|
||||
name: '',
|
||||
row_types: 'total',
|
||||
current: sheet.total.current.formatted_amount,
|
||||
...mapAging(sheet.total.aging),
|
||||
total: sheet.total.total.formatted_amount,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
export const APAgingSummaryTableRowsMapper = (sheet, total) => {
|
||||
const rows = [];
|
||||
|
||||
const mapAging = (agingPeriods) => {
|
||||
return agingPeriods.reduce((acc, aging, index) => {
|
||||
acc[`aging-${index}`] = aging.total.formatted_amount;
|
||||
return acc;
|
||||
}, {});
|
||||
};
|
||||
sheet.vendors.forEach((vendor) => {
|
||||
const agingRow = mapAging(vendor.aging);
|
||||
|
||||
rows.push({
|
||||
row_types: 'vendor',
|
||||
name: vendor.vendor_name,
|
||||
...agingRow,
|
||||
current: vendor.current.formatted_amount,
|
||||
total: vendor.total.formatted_amount,
|
||||
});
|
||||
});
|
||||
if (rows.length <= 0) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
...rows,
|
||||
{
|
||||
name: '',
|
||||
row_types: 'total',
|
||||
current: sheet.total.current.formatted_amount,
|
||||
...mapAging(sheet.total.aging),
|
||||
total: sheet.total.total.formatted_amount,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
export const inventoryValuationReducer = (sheet) => {
|
||||
const results = [];
|
||||
|
||||
if (sheet.items) {
|
||||
sheet.items.forEach((item) => {
|
||||
results.push(item);
|
||||
});
|
||||
}
|
||||
if (sheet.total) {
|
||||
results.push({
|
||||
row_types: 'total',
|
||||
...sheet.total,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
};
|
||||
|
||||
export const purchasesByItemsReducer = (sheet) => {
|
||||
const results = [];
|
||||
@@ -206,19 +16,3 @@ export const purchasesByItemsReducer = (sheet) => {
|
||||
}
|
||||
return results;
|
||||
};
|
||||
export const salesByItemsReducer = (sheet) => {
|
||||
const results = [];
|
||||
|
||||
if (sheet.items) {
|
||||
sheet.items.forEach((item) => {
|
||||
results.push(item);
|
||||
});
|
||||
}
|
||||
if (sheet.total) {
|
||||
results.push({
|
||||
row_types: 'total',
|
||||
...sheet.total,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user