Repository navigation
Expand file tree
/
Copy pathDistanceRequestUtils.ts
More file actions
1120 lines (996 loc) · 48.5 KB
/
Copy pathDistanceRequestUtils.ts
File metadata and controls
1120 lines (996 loc) · 48.5 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type {CurrencyListActionsContextType} from '@components/CurrencyListContextProvider';
import type {LocaleContextProps} from '@components/LocaleContextProvider';
import CONST from '@src/CONST';
import type {IOURequestType} from '@src/CONST';
import type {LastSelectedDistanceRates, OnyxInputOrEntry, Transaction} from '@src/types/onyx';
import type DefaultP2PMileageRate from '@src/types/onyx/DefaultP2PMileageRate';
import type {RateAttributes, Unit} from '@src/types/onyx/Policy';
import type Policy from '@src/types/onyx/Policy';
import type {TransactionCustomUnit} from '@src/types/onyx/Transaction';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type {Locale as DateFnsLocale} from 'date-fns';
import type {OnyxCollection, OnyxEntry} from 'react-native-onyx';
import {format, parseISO} from 'date-fns';
import DateUtils from './DateUtils';
import {getDistanceUnitLabel, getFormattedDistanceInUnits} from './DistanceDisplayUtils';
import {convertDistanceUnit, convertToDistanceInMeters} from './DistanceUnitConversionUtils';
import getStoredDefaultP2PMileageRate from './getStoredDefaultP2PMileageRate';
import {getDistanceRateCustomUnit, getDistanceRateCustomUnitRate, getUnitRateValue} from './PolicyUtils/customUnits';
import replaceAllDigits from './replaceAllDigits';
import {getCurrency, getFormattedCreated, getRateID, isCustomUnitRateIDForP2P, isExpenseUnreported} from './TransactionUtils/fields';
type MileageRate = {
customUnitRateID?: string;
rate?: number;
currency?: string;
unit: Unit;
name?: string;
enabled?: boolean;
index?: number;
startDate?: string | null;
endDate?: string | null;
attributes?: RateAttributes;
};
type CommuterExclusionData = Required<Pick<TransactionCustomUnit, 'commuterExclusion' | 'reimbursableDistance' | 'distanceUnit'>>;
const DEFAULT_P2P_RATE_CENTS_PER_MILE = 67;
function getMileageRates(policy: OnyxInputOrEntry<Policy>, includeDisabledRates = false, selectedRateID?: string): Record<string, MileageRate> {
const mileageRates: Record<string, MileageRate> = {};
if (!policy?.customUnits) {
return mileageRates;
}
const distanceUnit = getDistanceRateCustomUnit(policy);
if (!distanceUnit?.rates) {
return mileageRates;
}
for (const [rateID, rate] of Object.entries(distanceUnit.rates)) {
if (!includeDisabledRates && rate.enabled === false && (!selectedRateID || rateID !== selectedRateID)) {
continue;
}
if (!distanceUnit.attributes) {
continue;
}
mileageRates[rateID] = {
rate: rate.rate,
currency: rate.currency,
unit: distanceUnit.attributes.unit,
name: rate.name,
customUnitRateID: rate.customUnitRateID,
enabled: rate.enabled,
index: rate.index,
startDate: rate.startDate,
endDate: rate.endDate,
attributes: rate.attributes,
};
}
return mileageRates;
}
/**
* Retrieves the default mileage rate based on a given policy.
* Default rate is the first created rate when you create the policy.
* It's NOT always the rate whose name is "Default rate" because rate name is now changeable.
*
* @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: OnyxInputOrEntry<Policy>): MileageRate | undefined {
if (isEmptyObject(policy) || !policy?.customUnits) {
return undefined;
}
const distanceUnit = getDistanceRateCustomUnit(policy);
if (!distanceUnit?.rates || !distanceUnit.attributes) {
return;
}
const mileageRates = Object.values(getMileageRates(policy)).sort((a, b) => {
const aIndex = a.index ?? CONST.DEFAULT_NUMBER_ID;
const bIndex = b.index ?? CONST.DEFAULT_NUMBER_ID;
return aIndex - bIndex;
});
const distanceRate = mileageRates.at(0) ?? ({} as MileageRate);
return {
customUnitRateID: distanceRate.customUnitRateID,
rate: distanceRate.rate,
currency: distanceRate.currency,
unit: distanceUnit.attributes.unit,
name: distanceRate.name,
index: distanceRate.index,
};
}
/**
* Converts a distance into the given unit at the two decimal places the backend stores distances with. The
* commuter exclusion arithmetic has to use this: the backend rounds both the trip and the commute before
* subtracting, so an amount derived from unrounded values lands a cent away from the one the backend calculates
* and is then mistaken for an amount the member typed themselves.
*/
function convertRoundedDistanceUnit(distanceInMeters: number, unit: Unit): number {
return Number(convertDistanceUnit(distanceInMeters, unit).toFixed(CONST.DISTANCE_DECIMAL_PLACES));
}
/**
* @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(CONST.DISTANCE_DECIMAL_PLACES);
}
/**
* @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
* @param useShortFormUnit If true, the unit will be returned in short form (e.g., "mi", "km").
* @returns A string that displays the rate used for expense calculation
*/
function getFormattedRateValue(
unit: Unit | undefined,
rate: number | undefined,
currency: string | undefined,
translate: LocaleContextProps['translate'],
toLocaleDigit: LocaleContextProps['toLocaleDigit'],
getCurrencySymbol: CurrencyListActionsContextType['getCurrencySymbol'],
isOffline?: boolean,
useShortFormUnit?: 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 = getUnitRateValue(toLocaleDigit, {rate}, useShortFormUnit);
const currencySymbol = getCurrencySymbol(currency) || `${currency} `;
return `${currencySymbol}${formattedRate} / ${useShortFormUnit ? unit : singularDistanceUnit}`;
}
/**
* Get the rate title to display on the expense page.
* If the rate is out of policy, displays "Rate out of policy".
* For workspace expenses, shows the rate name (e.g., "Default Rate") so that updating a rate's
* value on the workspace does not retroactively change the displayed rate on historical expenses.
* For P2P expenses (no rate name), shows the formatted rate value (e.g., "$0.67 / mi").
*/
function getRateForExpenseDisplay(
rateName: string | undefined,
isCustomUnitOutOfPolicy: boolean,
unit: Unit | undefined,
rate: number | undefined,
currency: string | undefined,
translate: LocaleContextProps['translate'],
toLocaleDigit: LocaleContextProps['toLocaleDigit'],
getCurrencySymbol: CurrencyListActionsContextType['getCurrencySymbol'],
isOffline?: boolean,
): string {
if (isCustomUnitOutOfPolicy) {
return translate('common.rateOutOfPolicy');
}
if (rateName) {
return rateName;
}
return getFormattedRateValue(unit, rate, currency, translate, toLocaleDigit, getCurrencySymbol, isOffline);
}
/**
* @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
* @param useShortFormUnit If true, the unit will be returned in short form (e.g., "mi", "km").
* @param isZeroDistanceAllowed If true, a zero distance is formatted instead of returning an empty string.
* @param commuterExclusionData When provided, the reimbursable distance (after the commuter exclusion) is displayed instead of the full route distance.
* @returns A string that describes the distance traveled
*/
function getDistanceForDisplay(
hasRoute: boolean,
distanceInMeters: number,
unit: Unit | undefined,
translate: LocaleContextProps['translate'],
useShortFormUnit?: boolean,
isZeroDistanceAllowed?: boolean,
commuterExclusionData?: CommuterExclusionData | null,
): string {
const displayUnit = unit ?? commuterExclusionData?.distanceUnit;
if (!hasRoute || !displayUnit) {
return translate('iou.fieldPending');
}
const distanceToDisplayInMeters = commuterExclusionData ? convertToDistanceInMeters(commuterExclusionData.reimbursableDistance, displayUnit) : distanceInMeters;
if (!distanceToDisplayInMeters && !isZeroDistanceAllowed && !commuterExclusionData) {
return '';
}
return getFormattedDistanceInUnits(convertDistanceUnit(distanceToDisplayInMeters, displayUnit), displayUnit, translate, useShortFormUnit);
}
function getDistanceForDisplayLabel(distanceInMeters: number, unit: Unit): string {
const distanceInUnits = getRoundedDistanceInUnits(distanceInMeters, unit);
return `${distanceInUnits} ${unit}`;
}
/**
* @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
* @param commuterExclusionData When provided, the reimbursable distance (after the commuter exclusion) is shown instead of the full route distance.
* @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'],
getCurrencySymbol: CurrencyListActionsContextType['getCurrencySymbol'],
isZeroDistanceAllowed?: boolean,
commuterExclusionData?: CommuterExclusionData | null,
): string {
if (!hasRoute || !rate) {
return translate('iou.fieldPending');
}
if (!distanceInMeters && !isZeroDistanceAllowed && !commuterExclusionData) {
return '';
}
const distanceInUnits = getDistanceForDisplay(hasRoute, distanceInMeters, unit, translate, true, isZeroDistanceAllowed, commuterExclusionData);
const ratePerUnit = getFormattedRateValue(unit, rate, currency, translate, toLocaleDigit, getCurrencySymbol, undefined, true);
return `${distanceInUnits} ${CONST.DISTANCE_MERCHANT_SEPARATOR} ${ratePerUnit}`;
}
/**
* Retrieves the rate and unit for a P2P distance expense for a given currency.
*
* Let's ensure this logic is consistent with the logic in the backend (Auth), since we're using the same method to calculate the rate value in distance requests created via Concierge.
*
* @param currency
* @returns The rate and unit in MileageRate object.
*/
function getRateForP2P(currency: string, transaction: OnyxEntry<Transaction>): MileageRate {
const defaultRate = getStoredDefaultP2PMileageRate();
const p2pRate: DefaultP2PMileageRate = defaultRate ?? {rate: DEFAULT_P2P_RATE_CENTS_PER_MILE, unit: CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES};
const rate = transaction && getCurrency(transaction) === currency ? (transaction.comment?.customUnit?.defaultP2PRate ?? p2pRate.rate) : p2pRate.rate;
// If a distance expense is being edited, the defaultP2PRate may not have been loaded yet, so use data from the existing transaction.
const fallbackUnit = transaction?.comment?.customUnit?.distanceUnit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES;
return {
rate,
unit: defaultRate ? p2pRate.unit : fallbackUnit,
currency: defaultRate ? currency : getCurrency(transaction),
};
}
/**
* Rounds a distance (already in the target unit) to 2 decimal places,
* multiplies by the rate, and rounds to the nearest integer (cents).
*/
function roundDistanceAmount(distanceInUnits: number, rate: number): number {
const roundedDistance = parseFloat(distanceInUnits.toFixed(2));
return Math.round(roundedDistance * rate);
}
/**
* 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 {
return roundDistanceAmount(convertDistanceUnit(distance, unit), rate);
}
function getCommuterExclusionDisplayData(customUnit: TransactionCustomUnit | undefined, distanceUnit: Unit): CommuterExclusionData | null {
const commuterExclusion = customUnit?.commuterExclusion;
if (typeof commuterExclusion !== 'number' || commuterExclusion <= 0) {
return null;
}
return {
commuterExclusion,
reimbursableDistance: typeof customUnit?.reimbursableDistance === 'number' ? customUnit.reimbursableDistance : Math.max(0, (customUnit?.quantity ?? 0) - commuterExclusion),
distanceUnit: customUnit?.distanceUnit ?? distanceUnit,
};
}
/**
* Whether the commuter exclusion preview on the transaction is the one for this workspace. The preview rides
* along on the route response, so one left behind by a workspace the member has since switched away from
* describes a different trip and does not answer for this one.
*/
function hasCommuterExclusionPreviewForPolicy(transaction: OnyxEntry<Transaction>, policy: OnyxEntry<Policy>): boolean {
return !!policy?.id && transaction?.commuterExclusionPreview?.policyID === policy.id;
}
/**
* Whether a workspace's commuter exclusion applies to a distance expense of this request type.
*
* Only a distance the app itself measured describes a route the workspace can recognize a commute in, so a manually
* entered or odometer distance is reimbursed in full.
*/
function isCommuterExclusionApplicableToRequestType(iouRequestType: IOURequestType | undefined): boolean {
return iouRequestType !== CONST.IOU.REQUEST_TYPE.DISTANCE_MANUAL && iouRequestType !== CONST.IOU.REQUEST_TYPE.DISTANCE_ODOMETER;
}
/**
* Returns the distance a workspace excludes from a distance of `distance` units, expressed in that same unit.
*
* Returns 0 when the workspace excludes nothing, so callers can treat it as "no exclusion applies". The exclusion never
* exceeds the distance itself, which is what keeps a reimbursable distance from going negative.
*/
function getPolicyCommuterExclusionForDistance(policy: OnyxEntry<Policy>, distance: number, distanceUnit: Unit): number {
const commuterExclusions = policy?.commuterExclusions;
if (commuterExclusions?.method !== CONST.POLICY.COMMUTER_EXCLUSION_METHOD.FIXED_DISTANCE) {
return 0;
}
const fixedDistanceUnit: Unit =
commuterExclusions.fixedDistanceUnit === CONST.CUSTOM_UNITS.DISTANCE_UNIT_KILOMETERS ? CONST.CUSTOM_UNITS.DISTANCE_UNIT_KILOMETERS : CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES;
const fixedDistanceInRequestUnit = convertRoundedDistanceUnit(convertToDistanceInMeters(commuterExclusions.fixedDistance ?? 0, fixedDistanceUnit), distanceUnit);
return Math.max(0, Math.min(fixedDistanceInRequestUnit, distance));
}
function getTransactionCommuterExclusionData({
transaction,
policy,
customUnit,
storedCustomUnit,
translate,
toLocaleDigit,
getCurrencySymbol,
personalPolicyOutputCurrency,
hasTripChanged = false,
}: {
transaction: OnyxEntry<Transaction>;
policy: OnyxEntry<Policy>;
customUnit?: TransactionCustomUnit;
storedCustomUnit?: TransactionCustomUnit;
translate?: LocaleContextProps['translate'];
toLocaleDigit?: LocaleContextProps['toLocaleDigit'];
getCurrencySymbol?: CurrencyListActionsContextType['getCurrencySymbol'];
personalPolicyOutputCurrency?: string;
/** Whether the trip's waypoints just changed, which retires an exclusion derived from the old ones */
hasTripChanged?: boolean;
}): (Pick<Transaction, 'modifiedMerchant'> & {modifiedAmount: number; customUnit: TransactionCustomUnit}) | undefined {
if (!isCommuterExclusionApplicableToRequestType(transaction?.iouRequestType)) {
return;
}
const existingCustomUnit = customUnit ?? transaction?.comment?.customUnit;
const selectedRate = existingCustomUnit?.customUnitRateID
? (getRateByCustomUnitRateID({customUnitRateID: existingCustomUnit.customUnitRateID, policy}) ?? getRate({transaction, policy, personalPolicyOutputCurrency}))
: getRate({transaction, policy, personalPolicyOutputCurrency});
const requestDistanceUnit = existingCustomUnit?.distanceUnit ?? selectedRate.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES;
let routeDistanceInMeters: number | undefined;
if (typeof existingCustomUnit?.routeDistanceMeters === 'number') {
routeDistanceInMeters = existingCustomUnit.routeDistanceMeters;
} else if (typeof transaction?.routes?.route0?.distance === 'number') {
routeDistanceInMeters = transaction.routes.route0.distance;
}
let routeDistance: number | undefined;
if (typeof existingCustomUnit?.quantity === 'number') {
routeDistance = existingCustomUnit.quantity;
} else if (routeDistanceInMeters !== undefined) {
routeDistance = convertRoundedDistanceUnit(routeDistanceInMeters, requestDistanceUnit);
}
if (routeDistance === undefined) {
return;
}
// A stored exclusion is the one the expense was created with. A fixed distance is a per-claim constant, so it
// stays frozen even if the workspace later changes it. A home and office exclusion was derived from where the
// trip started and ended, so a changed trip or a fresh decision for the current one retires it.
const storedCommuterExclusion = storedCustomUnit?.commuterExclusion;
const commuterExclusionPreview = transaction?.commuterExclusionPreview;
const hasPreviewForThisPolicy = hasCommuterExclusionPreviewForPolicy(transaction, policy);
const isStoredExclusionDerivedFromTheTrip = storedCustomUnit?.commuterExclusionMethod === CONST.POLICY.COMMUTER_EXCLUSION_METHOD.HOME_AND_OFFICE;
const shouldReuseStoredExclusion =
typeof storedCommuterExclusion === 'number' && storedCommuterExclusion > 0 && !(isStoredExclusionDerivedFromTheTrip && (hasPreviewForThisPolicy || hasTripChanged));
let commuterExclusion: number;
let commuterExclusionMethod: NonNullable<TransactionCustomUnit['commuterExclusionMethod']>;
if (shouldReuseStoredExclusion) {
const storedExclusionInRequestUnit = convertRoundedDistanceUnit(
convertToDistanceInMeters(storedCommuterExclusion, storedCustomUnit?.distanceUnit ?? requestDistanceUnit),
requestDistanceUnit,
);
commuterExclusion = Math.max(0, Math.min(storedExclusionInRequestUnit, routeDistance));
commuterExclusionMethod = storedCustomUnit?.commuterExclusionMethod ?? CONST.POLICY.COMMUTER_EXCLUSION_METHOD.FIXED_DISTANCE;
} else if (policy?.commuterExclusions?.method === CONST.POLICY.COMMUTER_EXCLUSION_METHOD.HOME_AND_OFFICE) {
// How much of a trip is the member's commute is decided against their home address and the workspace
// address, which takes geocoding the backend does and the app can't, so the preview rides along on the
// route response.
if (!hasPreviewForThisPolicy || !commuterExclusionPreview?.hasExclusion) {
commuterExclusion = 0;
} else if (commuterExclusionPreview.isWholeTripExcluded) {
// The route distance here is the one to exclude, rather than the backend's copy of it, so the trip
// still comes out at nothing reimbursable when the member picked a different alternate route.
commuterExclusion = routeDistance;
} else {
commuterExclusion = Math.min(routeDistance, convertRoundedDistanceUnit(commuterExclusionPreview.commuteDistanceMeters, requestDistanceUnit));
}
commuterExclusionMethod = CONST.POLICY.COMMUTER_EXCLUSION_METHOD.HOME_AND_OFFICE;
} else {
commuterExclusion = getPolicyCommuterExclusionForDistance(policy, routeDistance, requestDistanceUnit);
commuterExclusionMethod = CONST.POLICY.COMMUTER_EXCLUSION_METHOD.FIXED_DISTANCE;
}
if (commuterExclusion <= 0) {
return;
}
const reimbursableDistance = Math.max(0, routeDistance - commuterExclusion);
const reimbursableDistanceInMeters = convertToDistanceInMeters(reimbursableDistance, requestDistanceUnit);
const distanceRate = selectedRate.rate ?? 0;
const modifiedMerchant =
translate && toLocaleDigit && getCurrencySymbol
? getDistanceMerchant(
true,
reimbursableDistanceInMeters,
requestDistanceUnit,
distanceRate,
selectedRate.currency ?? transaction?.currency ?? CONST.CURRENCY.USD,
translate,
toLocaleDigit,
getCurrencySymbol,
true,
)
: undefined;
return {
modifiedAmount: getDistanceRequestAmount(reimbursableDistanceInMeters, requestDistanceUnit, distanceRate),
modifiedMerchant,
customUnit: {
...existingCustomUnit,
customUnitRateID: existingCustomUnit?.customUnitRateID ?? selectedRate.customUnitRateID,
distanceUnit: requestDistanceUnit,
quantity: routeDistance,
name: existingCustomUnit?.name ?? CONST.CUSTOM_UNITS.NAME_DISTANCE,
...(routeDistanceInMeters !== undefined && {routeDistanceMeters: routeDistanceInMeters}),
commuterExclusion,
reimbursableDistance,
commuterExclusionMethod,
},
};
}
/**
* Returns the description label and hint text for a distance field, incorporating commuter exclusion details when present.
*
* @param commuterExclusionData - The commuter exclusion breakdown, or null/undefined when not applicable
* @param distanceUnit - The unit to use for display formatting (falls back to data's unit or miles)
* @param translate - Translate function
*/
function getDistanceDisplayDetailsWithCommuter(
commuterExclusionData: CommuterExclusionData | null | undefined,
distanceUnit: Unit | undefined,
translate: LocaleContextProps['translate'],
): {distanceToDisplayDescription: string; distanceToDisplayHintText: string | undefined} {
const baseLabel = translate('common.distance');
if (!commuterExclusionData) {
return {
distanceToDisplayDescription: baseLabel,
distanceToDisplayHintText: undefined,
};
}
const unitToUse = distanceUnit ?? commuterExclusionData.distanceUnit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES;
const {commuterExclusion, reimbursableDistance} = commuterExclusionData;
const originalDistance = reimbursableDistance + commuterExclusion;
const originalDistanceFormatted = getFormattedDistanceInUnits(originalDistance, unitToUse, translate, true);
const commuterDistance = commuterExclusion.toFixed(CONST.DISTANCE_DECIMAL_PLACES);
return {
distanceToDisplayDescription: `${baseLabel} ${CONST.DOT_SEPARATOR} ${translate('distance.commuterExclusion.original', {formattedDistance: originalDistanceFormatted})}`,
distanceToDisplayHintText: translate(
unitToUse === CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES ? 'distance.commuterExclusion.removedCommuterDistance.mi' : 'distance.commuterExclusion.removedCommuterDistance.km',
{
distance: commuterDistance,
count: commuterExclusion,
},
),
};
}
/**
* Returns whether the distance custom unit rate ID is unset or represents a non-workspace rate (P2P or placeholder).
*/
function isUnsetDistanceCustomUnitRateID(customUnitRateID: string | undefined): boolean {
if (!customUnitRateID) {
return true;
}
return customUnitRateID === CONST.CUSTOM_UNITS.FAKE_P2P_ID || customUnitRateID === CONST.CUSTOM_UNITS.UNSET_DISTANCE_RATE_ID;
}
/**
* Checks if a mileage rate is eligible for a given expense date.
* A rate is eligible if the date falls within its startDate/endDate bounds (inclusive).
* Missing bounds mean unbounded in that direction.
*/
function isRateEligibleForDate(rate: MileageRate, expenseDate: string): boolean {
const normalizedExpenseDate = DateUtils.formatMachineDateWithUTCTimeZone(expenseDate, CONST.DATE.FNS_FORMAT_STRING);
if (!normalizedExpenseDate) {
return true;
}
if (rate.startDate && normalizedExpenseDate < rate.startDate) {
return false;
}
if (rate.endDate && normalizedExpenseDate > rate.endDate) {
return false;
}
return true;
}
/**
* Returns a boundedness score: 2 = fully bounded (both dates), 1 = partially bounded (one date), 0 = unbounded.
*/
function getBoundednessScore(rate: MileageRate): number {
if (rate.startDate && rate.endDate) {
return 2;
}
if (rate.startDate || rate.endDate) {
return 1;
}
return 0;
}
function getFullyBoundedDateRangeMs(rate: MileageRate): number | undefined {
if (!rate.startDate || !rate.endDate) {
return undefined;
}
return new Date(rate.endDate).getTime() - new Date(rate.startDate).getTime();
}
/**
* Ranks two rates that are both eligible for the same expense date.
* Selection order per design doc:
* 1. Most specific date range (fully bounded > partially bounded > unbounded)
* 2. Narrower date range for two fully bounded ranges
* 3. Latest start date
* 4. Lowest index (creation order)
*/
function compareRatesByDateSpecificity(a: MileageRate, b: MileageRate): number {
const aScore = getBoundednessScore(a);
const bScore = getBoundednessScore(b);
if (aScore !== bScore) {
return bScore - aScore;
}
// Both scores are equal here, so aScore === 2 means both rates are fully bounded.
if (aScore === 2) {
const aRange = getFullyBoundedDateRangeMs(a);
const bRange = getFullyBoundedDateRangeMs(b);
if (aRange !== undefined && bRange !== undefined && aRange !== bRange) {
return aRange - bRange;
}
}
const aStart = a.startDate ?? '';
const bStart = b.startDate ?? '';
if (aStart !== bStart) {
return aStart < bStart ? 1 : -1;
}
const aIndex = a.index ?? CONST.DEFAULT_NUMBER_ID;
const bIndex = b.index ?? CONST.DEFAULT_NUMBER_ID;
return aIndex - bIndex;
}
/**
* Finds the best eligible rate for a given expense date from a set of mileage rates.
*/
function getBestEligibleRate(mileageRates: Record<string, MileageRate>, expenseDate: string): MileageRate | undefined {
const eligibleRates = Object.values(mileageRates).filter((rate) => rate.enabled !== false && isRateEligibleForDate(rate, expenseDate));
if (eligibleRates.length === 0) {
return undefined;
}
eligibleRates.sort(compareRatesByDateSpecificity);
return eligibleRates.at(0);
}
function getBestEligibleRateOrPolicyDefault(mileageRates: Record<string, MileageRate>, expenseDate: string, policy: OnyxEntry<Policy>): MileageRate | undefined {
const bestRate = getBestEligibleRate(mileageRates, expenseDate);
if (bestRate) {
return bestRate;
}
return getDefaultMileageRate(policy);
}
/**
* Finds the rate that is equivalent to the expense's current rate: same value, same currency and same distance unit, and valid for the expense date.
* The unit is taken from the policy's distance custom unit, so a unit mismatch disqualifies every rate on that policy.
*/
function getRateMatchingCurrentRate(mileageRates: Record<string, MileageRate>, currentRate: MileageRate | undefined, expenseDate: string): MileageRate | undefined {
if (currentRate?.rate === undefined || !currentRate.currency) {
return undefined;
}
const equivalentRates = Object.fromEntries(
Object.entries(mileageRates).filter(([, rate]) => rate.rate === currentRate.rate && rate.currency === currentRate.currency && rate.unit === currentRate.unit),
);
return getBestEligibleRate(equivalentRates, expenseDate);
}
/**
* Selects the distance rate for an expense moving to a different workspace: an equivalent rate on the destination policy, else its
* best rate for the expense date, else its default rate, else nothing so the caller keeps the `customUnitOutOfPolicy` violation.
*
* `currentRate` resolves against the source policy, which this module cannot look up, so callers pass it in. It is optional because
* a P2P expense carries its rate on the transaction.
*
* Let's ensure this logic is consistent with the logic in the backend (Auth), which is authoritative here.
*/
function getRateForPolicyChange({transaction, policy, currentRate}: {transaction: OnyxEntry<Transaction>; policy: OnyxEntry<Policy>; currentRate?: MileageRate}): MileageRate | undefined {
const expenseDate = getFormattedCreated(transaction);
const mileageRates = getMileageRates(policy);
const p2pRate = isCustomUnitRateIDForP2P(transaction) ? getRateForP2P(getCurrency(transaction), transaction) : undefined;
// getRateForP2P reports the loaded global default's unit, not the expense's, so read the unit off the transaction the way getRate does.
// Otherwise an expense saved in kilometers is matched as miles and the fallback rate reprices it.
const rateToMatch = currentRate ?? (p2pRate ? {...p2pRate, unit: getDistanceUnit(transaction, p2pRate)} : undefined);
const selectedRate = getRateMatchingCurrentRate(mileageRates, rateToMatch, expenseDate) ?? getBestEligibleRateOrPolicyDefault(mileageRates, expenseDate, policy);
// getDefaultMileageRate returns a fully shaped rate with an undefined customUnitRateID when the policy has no enabled rates, so normalize that case to undefined.
return selectedRate?.customUnitRateID ? selectedRate : undefined;
}
/**
* Returns custom unit rate ID for the distance transaction.
* When an expenseDate is provided, uses date-aware rate selection:
* 1. Last selected rate, if enabled and valid for the expense date
* 2. Best eligible rate for the expense date
* 3. Default rate fallback
*/
function getCustomUnitRateID({
reportID,
isPolicyExpenseChat,
policy,
isTrackDistanceExpense = false,
lastSelectedDistanceRates,
expenseDate,
}: {
reportID: string | undefined;
isPolicyExpenseChat: boolean;
policy: OnyxEntry<Policy> | undefined;
lastSelectedDistanceRates?: OnyxEntry<LastSelectedDistanceRates>;
isTrackDistanceExpense?: boolean;
expenseDate?: string;
}): string {
const customUnitRateID: string = CONST.CUSTOM_UNITS.FAKE_P2P_ID;
if (!reportID) {
return customUnitRateID;
}
if (isEmptyObject(policy)) {
return customUnitRateID;
}
// For TrackDistanceExpense we will return the default or last selected rate of the policyForMovingExpenses.
if (isPolicyExpenseChat || isTrackDistanceExpense) {
const distanceUnit = Object.values(policy.customUnits ?? {}).find((unit) => unit.name === CONST.CUSTOM_UNITS.NAME_DISTANCE);
const lastSelectedDistanceRateID = lastSelectedDistanceRates?.[policy.id];
const lastSelectedDistanceRate = lastSelectedDistanceRateID ? distanceUnit?.rates[lastSelectedDistanceRateID] : undefined;
if (!expenseDate) {
if (lastSelectedDistanceRate?.enabled && lastSelectedDistanceRateID) {
return lastSelectedDistanceRateID;
}
const defaultMileageRate = getDefaultMileageRate(policy);
if (defaultMileageRate?.customUnitRateID) {
return defaultMileageRate.customUnitRateID;
}
return customUnitRateID;
}
const mileageRates = getMileageRates(policy);
if (lastSelectedDistanceRate?.enabled && lastSelectedDistanceRateID) {
const lastSelectedMileageRate = mileageRates[lastSelectedDistanceRateID];
// mileageRates may be empty when the distance unit has no attributes. Guard against undefined before calling isRateEligibleForDate, and preserve the user's last selected ID when rate metadata is unavailable.
if (!lastSelectedMileageRate || isRateEligibleForDate(lastSelectedMileageRate, expenseDate)) {
return lastSelectedDistanceRateID;
}
}
const bestRate = getBestEligibleRateOrPolicyDefault(mileageRates, expenseDate, policy);
if (bestRate?.customUnitRateID) {
return bestRate.customUnitRateID;
}
}
return customUnitRateID;
}
/**
* Returns the workspace rate to auto-select for a tracked expense moved onto that workspace:
* 1. A workspace rate with the same value and unit as the one the expense already uses
* 2. Best eligible rate for the expense date
* 3. Default rate fallback
* Returns undefined when the workspace has no rate to offer, so the caller can keep the current one.
*/
function getRateIDForMovedTrackExpense({
transaction,
policy,
policyForMovingExpenses,
policies,
expenseDate,
personalPolicyOutputCurrency,
}: {
transaction: OnyxEntry<Transaction>;
policy: OnyxEntry<Policy>;
policyForMovingExpenses: OnyxEntry<Policy>;
policies: OnyxCollection<Policy>;
expenseDate: string | undefined;
personalPolicyOutputCurrency: string | undefined;
}): string | undefined {
const mileageRates = getMileageRates(policy);
if (isEmptyObject(mileageRates)) {
return undefined;
}
// Read the expense's current rate through getRate, the same call the confirmation page uses, so the value is compared against the rate the user sees.
const currentRate = getRate({
transaction,
policy,
...(policyForMovingExpenses && {policyForMovingExpenses}),
isMovingTransactionFromTrackExpense: true,
useTransactionDistanceUnit: false,
personalPolicyOutputCurrency,
});
// getRate only resolves a rate owned by the destination or the moving policy, so a rate left over from any other workspace is looked up by ID.
const resolvedRate = currentRate.rate !== undefined ? currentRate : getRateByCustomUnitRateIDAcrossPolicies({customUnitRateID: getRateID(transaction), policies});
if (resolvedRate?.rate !== undefined) {
const currentUnit = getDistanceUnit(transaction, resolvedRate);
const matchingRateID = Object.values(mileageRates).find((rate) => rate.rate === resolvedRate.rate && rate.unit === currentUnit)?.customUnitRateID;
if (matchingRateID) {
return matchingRateID;
}
}
if (!expenseDate) {
return getDefaultMileageRate(policy)?.customUnitRateID;
}
return getBestEligibleRateOrPolicyDefault(mileageRates, expenseDate, policy)?.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 = getDistanceRateCustomUnit(policy);
const customUnitRate = getDistanceRateCustomUnitRate(policy, customUnitRateID);
if (!distanceUnit?.customUnitID || !customUnitRate) {
return 0;
}
const unit = distanceUnit?.attributes?.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES;
const rate = customUnitRate?.rate ?? CONST.DEFAULT_NUMBER_ID;
const amount = getDistanceRequestAmount(distance, unit, rate);
const taxClaimablePercentage = customUnitRate.attributes?.taxClaimablePercentage ?? CONST.DEFAULT_NUMBER_ID;
return amount * taxClaimablePercentage;
}
function getDistanceUnit(transaction: OnyxEntry<Transaction>, mileageRate: OnyxEntry<MileageRate>): Unit {
return transaction?.comment?.customUnit?.distanceUnit ?? mileageRate?.unit ?? CONST.CUSTOM_UNITS.DISTANCE_UNIT_MILES;
}
/**
* Get the selected rate for a transaction, from the policy or P2P default rate.
* Use the distanceUnit stored on the transaction by default to prevent policy changes modifying existing transactions. Otherwise, get the unit from the rate.
*
* Let's ensure this logic is consistent with the logic in the backend (Auth), since we're using the same method to calculate the rate value in distance requests created via Concierge.
*/
function getRate({
transaction,
policy,
policyDraft,
useTransactionDistanceUnit = true,
policyForMovingExpenses,
isFakeP2PRate,
isMovingTransactionFromTrackExpense,
personalPolicyOutputCurrency,
}: {
transaction: OnyxEntry<Transaction>;
policy: OnyxEntry<Policy>;
policyDraft?: OnyxEntry<Policy>;
policyForMovingExpenses?: OnyxEntry<Policy>;
useTransactionDistanceUnit?: boolean;
isFakeP2PRate?: boolean;
isMovingTransactionFromTrackExpense?: boolean;
personalPolicyOutputCurrency: string | undefined;
}): MileageRate {
let mileageRates = getMileageRates(policy, true, transaction?.comment?.customUnit?.customUnitRateID);
if (isEmptyObject(mileageRates) && policyDraft) {
mileageRates = getMileageRates(policyDraft, true, transaction?.comment?.customUnit?.customUnitRateID);
}
const mileageRatesForMovingExpenses = getMileageRates(policyForMovingExpenses, true, transaction?.comment?.customUnit?.customUnitRateID);
const policyCurrency = policy?.outputCurrency ?? personalPolicyOutputCurrency ?? CONST.CURRENCY.USD;
const isUnreportedExpense = isExpenseUnreported(transaction);
const defaultMileageRate = getDefaultMileageRate(policy);
const customUnitRateID = getRateID(transaction);
const customMileageRate =
(customUnitRateID && (mileageRates?.[customUnitRateID] ?? mileageRatesForMovingExpenses?.[customUnitRateID])) ||
(isUnreportedExpense || isMovingTransactionFromTrackExpense ? undefined : defaultMileageRate);
const mileageRate = isCustomUnitRateIDForP2P(transaction) || isFakeP2PRate ? getRateForP2P(policyCurrency, transaction) : customMileageRate;
const unit = getDistanceUnit(useTransactionDistanceUnit ? transaction : undefined, mileageRate);
return {
...mileageRate,
unit,
currency: mileageRate?.currency ?? policyCurrency,
};
}
/**
* Get the updated distance unit from the selected rate instead of the distanceUnit stored on the transaction.
* Useful for updating the transaction distance unit when the distance or rate changes.
*
* For example, if an expense is '10 mi @ $1.00 / mi' and the rate is updated to '$1.00 / km',
* then the updated distance unit should be 'km' from the updated rate, not 'mi' from the currently stored transaction distance unit.
*/
function getUpdatedDistanceUnit({transaction, policy, policyDraft}: {transaction: OnyxEntry<Transaction>; policy: OnyxEntry<Policy>; policyDraft?: OnyxEntry<Policy>}) {
// The distance unit doesn't depend on the currency (the rate is selected by ID/P2P, not currency), so
// personalPolicyOutputCurrency isn't accepted here and is passed as undefined to getRate.
return getRate({transaction, policy, policyDraft, useTransactionDistanceUnit: false, personalPolicyOutputCurrency: undefined}).unit;
}
/**
* Get the mileage rate by its ID in the form it's configured for the policy.
* If not found, return undefined.
*/
function getRateByCustomUnitRateID({customUnitRateID, policy}: {customUnitRateID: string; policy: OnyxEntry<Policy>}): MileageRate | undefined {
return getMileageRates(policy, true, customUnitRateID)[customUnitRateID];
}
/**
* Resolve an enabled mileage rate by its ID across every policy the user belongs to.
* Useful when the caller doesn't know which policy owns the rate (e.g. a self-DM split on the personal rate).
* Returns `undefined` for the P2P rate, a missing ID, or a disabled/deleted rate.
*/
function getEnabledRateByCustomUnitRateIDFromAnyPolicy(customUnitRateID: string | undefined, policies: OnyxCollection<Policy>): MileageRate | undefined {
if (!customUnitRateID || customUnitRateID === CONST.CUSTOM_UNITS.FAKE_P2P_ID) {
return undefined;
}
for (const policy of Object.values(policies ?? {})) {
const rate = getMileageRates(policy)[customUnitRateID];
if (rate) {
return rate;
}
}
return undefined;
}
/**
* Resolve a mileage rate from the supplied policy, falling back to any policy that owns an enabled rate with the same ID.
*/
function getRateByCustomUnitRateIDAcrossPolicies({
customUnitRateID,
policy,
policies,
}: {
customUnitRateID: string | undefined;
policy?: OnyxEntry<Policy>;
policies?: OnyxCollection<Policy>;
}): MileageRate | undefined {
if (!customUnitRateID) {
return undefined;
}
return getRateByCustomUnitRateID({customUnitRateID, policy}) ?? getEnabledRateByCustomUnitRateIDFromAnyPolicy(customUnitRateID, policies);
}
/**
* Returns whether the selected custom unit rate is out of its valid date range for the given expense date.
*/
function isCustomUnitRateOutOfDateRange({
customUnitRateID,
policy,
expenseDate,
}: {
customUnitRateID: string | undefined;
policy: OnyxEntry<Policy>;
expenseDate: string | undefined;
}): boolean {
if (!expenseDate || isUnsetDistanceCustomUnitRateID(customUnitRateID) || !policy?.customUnits || !customUnitRateID) {
return false;
}
const mileageRate = getRateByCustomUnitRateID({customUnitRateID, policy});
if (!mileageRate || mileageRate.enabled === false) {
return false;
}
return !isRateEligibleForDate(mileageRate, expenseDate);
}
/**
* Returns whether the calculated distance expense amount (distance * rate) is within the backend's safe limit.
* The backend WAF rejects amounts exceeding 12 digits (999,999,999,999 cents).
*
* @param distance - The distance in the unit specified (km or mi), NOT meters
* @param rate - The rate in cents per unit
* @returns true if the amount is within limits, false if it would exceed the backend limit
*/
function isDistanceAmountWithinLimit(distance: number, rate: number): boolean {
return Math.abs(roundDistanceAmount(distance, rate)) <= CONST.IOU.MAX_SAFE_AMOUNT;
}
/**
* Normalize odometer text by standardizing locale digits and stripping all
* non-numeric characters except the decimal point. fromLocaleDigit converts
* each locale character to its standard equivalent (e.g. German ',' → '.'
* for decimal, German '.' → ',' for group separator), so after conversion
* dots are always decimals and commas are always group separators.
* We then strip everything except digits and the standard decimal point.
*/
function normalizeOdometerText(text: string, fromLocaleDigit: (char: string) => string): string {
const standardized = replaceAllDigits(text, fromLocaleDigit);
const stripped = standardized.replaceAll(/[^0-9.]/g, '');
// Remove redundant leading zeroes (e.g. "007" → "7", "000" → "0") but
// keep a single zero before a decimal point (e.g. "0.5" stays "0.5").
return stripped.replace(/^0+(?=\d)/, '');
}
/**
* Prepare odometer input text for display by removing non-numeric characters
* (except the decimal point, comma, and space — which serve as group or
* decimal separators depending on locale) and stripping redundant leading zeroes.
*/
function prepareTextForDisplay(text: string): string {
return text.replaceAll(/[^0-9., ]/g, '').replace(/^0+(?=\d)/, '');
}
function getRateDateLabel(rate: MileageRate, translate: LocaleContextProps['translate'], dateFnsLocale: DateFnsLocale | undefined): string {
const dateFormat = CONST.DATE.MONTH_DAY_YEAR_ABBR_FORMAT;
try {
if (rate.startDate && rate.endDate) {
return translate('iou.rateValidDateRange', {
startDate: format(parseISO(rate.startDate), dateFormat, {locale: dateFnsLocale}),
endDate: format(parseISO(rate.endDate), dateFormat, {locale: dateFnsLocale}),
});