| 1 |
import { formatCurrency as webFormatCurrency } from "@web/core/currency"; |
| 2 |
import { formatFloat } from "@web/core/utils/numbers"; |
| 3 |
import { escapeRegExp } from "@web/core/utils/strings"; |
| 4 |
import { registry } from "@web/core/registry"; |
| 5 |
import { parseFloat } from "@web/views/fields/parsers"; |
| 6 |
|
| 7 |
/** |
| 8 |
* This service introduces `utils` namespace in the `env` which can contain |
| 9 |
* functions that are parameterized by the data in `pos` service. |
| 10 |
*/ |
| 11 |
export const contextualUtilsService = { |
| 12 |
dependencies: ["pos", "localization"], |
| 13 |
start(env, { pos, localization }) { |
| 14 |
const res_currency = pos.currency; |
| 15 |
const ProductUnit = pos.data.models["decimal.precision"].find( |
| 16 |
(dp) => dp.name === "Product Unit" |
| 17 |
); |
| 18 |
const decimalPoint = localization.decimalPoint; |
| 19 |
const thousandsSep = localization.thousandsSep; |
| 20 |
// Replace the thousands separator and decimal point with regex-escaped versions |
| 21 |
const escapedDecimalPoint = escapeRegExp(decimalPoint); |
| 22 |
let floatRegex; |
| 23 |
if (thousandsSep) { |
| 24 |
const escapedThousandsSep = escapeRegExp(thousandsSep); |
| 25 |
floatRegex = new RegExp( |
| 26 |
`^-?(?:\\d+(${escapedThousandsSep}\\d+)*)?(?:${escapedDecimalPoint}\\d*)?$` |
| 27 |
); |
| 28 |
} else { |
| 29 |
floatRegex = new RegExp(`^-?(?:\\d+)?(?:${escapedDecimalPoint}\\d*)?$`); |
| 30 |
} |
| 31 |
|
| 32 |
const formatProductQty = (qty, trailingZeros = true) => |
| 33 |
formatFloat(qty, { digits: [true, ProductUnit.digits], trailingZeros: trailingZeros }); |
| 34 |
|
| 35 |
const formatCurrency = (value, hasSymbol = true) => |
| 36 |
webFormatCurrency(value, res_currency.id, { |
| 37 |
noSymbol: !hasSymbol, |
| 38 |
}); |
| 39 |
|
| 40 |
const roundCurrency = (value) => res_currency.round(value); |
| 41 |
|
| 42 |
const isValidFloat = (inputValue) => |
| 43 |
![decimalPoint, "-"].includes(inputValue) && floatRegex.test(inputValue); |
| 44 |
|
| 45 |
const parseValidFloat = (inputValue) => |
| 46 |
isValidFloat(inputValue) ? parseFloat(inputValue) : 0; |
| 47 |
|
| 48 |
env.utils = { |
| 49 |
formatCurrency, |
| 50 |
roundCurrency, |
| 51 |
formatProductQty, |
| 52 |
isValidFloat, |
| 53 |
parseValidFloat, |
| 54 |
}; |
| 55 |
}, |
| 56 |
}; |
| 57 |
registry.category("services").add("contextual_utils_service", contextualUtilsService); |