-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
DistanceRequestUtils.ts
303 lines (269 loc) · 11.4 KB
/
DistanceRequestUtils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import type {LocaleContextProps} from '@components/LocaleContextProvider';
import type {RateAndUnit} from '@src/CONST';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {LastSelectedDistanceRates, Report} from '@src/types/onyx';
import type {Unit} from '@src/types/onyx/Policy';
import type Policy from '@src/types/onyx/Policy';
import type {EmptyObject} from '@src/types/utils/EmptyObject';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import * as CurrencyUtils from './CurrencyUtils';
import * as PolicyUtils from './PolicyUtils';
import * as ReportUtils from './ReportUtils';
type MileageRate = {
customUnitRateID?: string;
rate?: number;
currency?: string;
unit: Unit;
name?: string;
};
let lastSelectedDistanceRates: OnyxEntry<LastSelectedDistanceRates> = {};
Onyx.connect({
key: ONYXKEYS.NVP_LAST_SELECTED_DISTANCE_RATES,
callback: (value) => {
lastSelectedDistanceRates = value;
},
});
let allReports: OnyxCollection<Report>;
Onyx.connect({
key: ONYXKEYS.COLLECTION.REPORT,
waitForCollectionCallback: true,
callback: (value) => (allReports = value),
});
const METERS_TO_KM = 0.001; // 1 kilometer is 1000 meters
const METERS_TO_MILES = 0.000621371; // There are approximately 0.000621371 miles in a meter
function getMileageRates(policy: OnyxEntry<Policy>, includeDisabledRates = false): Record<string, MileageRate> {
const mileageRates: Record<string, MileageRate> = {};
if (!policy || !policy?.customUnits) {
return mileageRates;
}
const distanceUnit = PolicyUtils.getCustomUnit(policy);
if (!distanceUnit?.rates) {
return mileageRates;
}
Object.entries(distanceUnit.rates).forEach(([rateID, rate]) => {
if (!includeDisabledRates && !rate.enabled) {
return;
}
mileageRates[rateID] = {
rate: rate.rate,
currency: rate.currency,
unit: distanceUnit.attributes.unit,
name: rate.name,
customUnitRateID: rate.customUnitRateID,
};
});
return mileageRates;
}
/**
* Retrieves the default mileage rate based on a given policy.
*
* @param policy - The policy from which to extract the default mileage rate.
*
* @returns An object containing the rate and unit for the default mileage or null if not found.
* @returns [rate] - The default rate for the mileage.
* @returns [currency] - The currency associated with the rate.
* @returns [unit] - The unit of measurement for the distance.
*/
function getDefaultMileageRate(policy: OnyxEntry<Policy> | EmptyObject): MileageRate | null {
if (isEmptyObject(policy) || !policy?.customUnits) {
return null;
}
const distanceUnit = PolicyUtils.getCustomUnit(policy);
if (!distanceUnit?.rates) {
return null;
}
const mileageRates = getMileageRates(policy);
const distanceRate = Object.values(mileageRates).find((rate) => rate.name === CONST.CUSTOM_UNITS.DEFAULT_RATE) ?? Object.values(mileageRates)[0];
return {
customUnitRateID: distanceRate.customUnitRateID,
rate: distanceRate.rate,
currency: distanceRate.currency,
unit: distanceUnit.attributes.unit,
name: distanceRate.name,
};
}
/**
* Converts a given distance in meters to the specified unit (kilometers or miles).
*
* @param distanceInMeters - The distance in meters to be converted.
* @param unit - The desired unit of conversion, either 'km' for kilometers or 'mi' for miles.
*
* @returns The converted distance in the specified unit.
*/
function convertDistanceUnit(distanceInMeters: number, unit: Unit): number {
switch (unit) {
case CONST.CUSTOM_UNITS.DISTANCE_UNIT_KILOMETERS:
return distanceInMeters * METERS_TO_KM;
case CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES:
return distanceInMeters * METERS_TO_MILES;
default:
throw new Error('Unsupported unit. Supported units are "mi" or "km".');
}
}
/**
* @param distanceInMeters Distance traveled
* @param unit Unit that should be used to display the distance
* @returns The distance in requested units, rounded to 2 decimals
*/
function getRoundedDistanceInUnits(distanceInMeters: number, unit: Unit): string {
const convertedDistance = convertDistanceUnit(distanceInMeters, unit);
return convertedDistance.toFixed(2);
}
/**
* @param unit Unit that should be used to display the distance
* @param rate Expensable amount allowed per unit
* @param currency The currency associated with the rate
* @param translate Translate function
* @param toLocaleDigit Function to convert to localized digit
* @returns A string that displays the rate used for expense calculation
*/
function getRateForDisplay(
unit: Unit | undefined,
rate: number | undefined,
currency: string | undefined,
translate: LocaleContextProps['translate'],
toLocaleDigit: LocaleContextProps['toLocaleDigit'],
isOffline?: boolean,
): string {
if (isOffline && !rate) {
return translate('iou.defaultRate');
}
if (!rate || !currency || !unit) {
return translate('iou.fieldPending');
}
const singularDistanceUnit = unit === CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES ? translate('common.mile') : translate('common.kilometer');
const formattedRate = PolicyUtils.getUnitRateValue(toLocaleDigit, {rate});
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const currencySymbol = CurrencyUtils.getCurrencySymbol(currency) || `${currency} `;
return `${currencySymbol}${formattedRate} / ${singularDistanceUnit}`;
}
/**
* @param hasRoute Whether the route exists for the distance expense
* @param distanceInMeters Distance traveled
* @param unit Unit that should be used to display the distance
* @param rate Expensable amount allowed per unit
* @param translate Translate function
* @returns A string that describes the distance traveled
*/
function getDistanceForDisplay(hasRoute: boolean, distanceInMeters: number, unit: Unit | undefined, rate: number | undefined, translate: LocaleContextProps['translate']): string {
if (!hasRoute || !rate || !unit || !distanceInMeters) {
return translate('iou.fieldPending');
}
const distanceInUnits = getRoundedDistanceInUnits(distanceInMeters, unit);
const distanceUnit = unit === CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES ? translate('common.miles') : translate('common.kilometers');
const singularDistanceUnit = unit === CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES ? translate('common.mile') : translate('common.kilometer');
const unitString = distanceInUnits === '1' ? singularDistanceUnit : distanceUnit;
return `${distanceInUnits} ${unitString}`;
}
/**
* @param hasRoute Whether the route exists for the distance expense
* @param distanceInMeters Distance traveled
* @param unit Unit that should be used to display the distance
* @param rate Expensable amount allowed per unit
* @param currency The currency associated with the rate
* @param translate Translate function
* @param toLocaleDigit Function to convert to localized digit
* @returns A string that describes the distance traveled and the rate used for expense calculation
*/
function getDistanceMerchant(
hasRoute: boolean,
distanceInMeters: number,
unit: Unit | undefined,
rate: number | undefined,
currency: string,
translate: LocaleContextProps['translate'],
toLocaleDigit: LocaleContextProps['toLocaleDigit'],
): string {
if (!hasRoute || !rate) {
return translate('iou.fieldPending');
}
const distanceInUnits = getDistanceForDisplay(hasRoute, distanceInMeters, unit, rate, translate);
const ratePerUnit = getRateForDisplay(unit, rate, currency, translate, toLocaleDigit);
return `${distanceInUnits} @ ${ratePerUnit}`;
}
/**
* Retrieves the rate and unit for a P2P distance expense for a given currency.
*
* @param currency
* @returns The rate and unit in RateAndUnit object.
*/
function getRateForP2P(currency: string): RateAndUnit {
return CONST.CURRENCY_TO_DEFAULT_MILEAGE_RATE[currency] ?? CONST.CURRENCY_TO_DEFAULT_MILEAGE_RATE.USD;
}
/**
* Calculates the expense amount based on distance, unit, and rate.
*
* @param distance - The distance traveled in meters
* @param unit - The unit of measurement for the distance
* @param rate - Rate used for calculating the expense amount
* @returns The computed expense amount (rounded) in "cents".
*/
function getDistanceRequestAmount(distance: number, unit: Unit, rate: number): number {
const convertedDistance = convertDistanceUnit(distance, unit);
const roundedDistance = parseFloat(convertedDistance.toFixed(2));
return Math.round(roundedDistance * rate);
}
/**
* Converts the distance from kilometers or miles to meters.
*
* @param distance - The distance to be converted.
* @param unit - The unit of measurement for the distance.
* @returns The distance in meters.
*/
function convertToDistanceInMeters(distance: number, unit: Unit): number {
if (unit === CONST.CUSTOM_UNITS.DISTANCE_UNIT_KILOMETERS) {
return distance / METERS_TO_KM;
}
return distance / METERS_TO_MILES;
}
/**
* Returns custom unit rate ID for the distance transaction
*/
function getCustomUnitRateID(reportID: string) {
const report = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`] ?? null;
const parentReport = allReports?.[`${ONYXKEYS.COLLECTION.REPORT}${report?.parentReportID}`] ?? null;
const policy = PolicyUtils.getPolicy(report?.policyID ?? parentReport?.policyID ?? '');
let customUnitRateID: string = CONST.CUSTOM_UNITS.FAKE_P2P_ID;
if (ReportUtils.isPolicyExpenseChat(report) || ReportUtils.isPolicyExpenseChat(parentReport)) {
const distanceUnit = Object.values(policy?.customUnits ?? {}).find((unit) => unit.name === CONST.CUSTOM_UNITS.NAME_DISTANCE);
const lastSelectedDistanceRateID = lastSelectedDistanceRates?.[policy?.id ?? ''] ?? '';
const lastSelectedDistanceRate = distanceUnit?.rates[lastSelectedDistanceRateID] ?? {};
if (lastSelectedDistanceRate.enabled && lastSelectedDistanceRateID) {
customUnitRateID = lastSelectedDistanceRateID;
} else {
customUnitRateID = getDefaultMileageRate(policy)?.customUnitRateID ?? '';
}
}
return customUnitRateID;
}
/**
* Get taxable amount from a specific distance rate, taking into consideration the tax claimable amount configured for the distance rate
*/
function getTaxableAmount(policy: OnyxEntry<Policy>, customUnitRateID: string, distance: number) {
const distanceUnit = PolicyUtils.getCustomUnit(policy);
const customUnitRate = PolicyUtils.getCustomUnitRate(policy, customUnitRateID);
if (!distanceUnit || !distanceUnit?.customUnitID || !customUnitRate) {
return 0;
}
const unit = distanceUnit?.attributes?.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES;
const rate = customUnitRate?.rate ?? 0;
const amount = getDistanceRequestAmount(distance, unit, rate);
const taxClaimablePercentage = customUnitRate.attributes?.taxClaimablePercentage ?? 0;
return amount * taxClaimablePercentage;
}
export default {
getDefaultMileageRate,
getDistanceMerchant,
getDistanceRequestAmount,
getRateForDisplay,
getMileageRates,
getDistanceForDisplay,
getRateForP2P,
getCustomUnitRateID,
convertToDistanceInMeters,
getTaxableAmount,
};
export type {MileageRate};